-
Notifications
You must be signed in to change notification settings - Fork 313
Expand file tree
/
Copy pathstatic.ts
More file actions
196 lines (164 loc) · 5.12 KB
/
static.ts
File metadata and controls
196 lines (164 loc) · 5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import type { H3Event } from "../event.ts";
import { HTTPError } from "../error.ts";
import { withLeadingSlash, withoutTrailingSlash } from "./internal/path.ts";
import { getType, getExtension } from "./internal/mime.ts";
import { HTTPResponse } from "../response.ts";
export interface StaticAssetMeta {
type?: string;
etag?: string;
mtime?: number | string | Date;
path?: string;
size?: number;
encoding?: string;
}
export interface ServeStaticOptions {
/**
* This function should resolve asset meta
*/
getMeta: (id: string) => StaticAssetMeta | undefined | Promise<StaticAssetMeta | undefined>;
/**
* This function should resolve asset content
*/
getContents: (id: string) => BodyInit | null | undefined | Promise<BodyInit | null | undefined>;
/**
* Headers to set on the response
*/
headers?: HeadersInit;
/**
* Map of supported encodings (compressions) and their file extensions.
*
* Each extension will be appended to the asset path to find the compressed version of the asset.
*
* @example { gzip: ".gz", br: ".br" }
*/
encodings?: Record<string, string>;
/**
* Default index file to serve when the path is a directory
*
* @default ["/index.html"]
*/
indexNames?: string[];
/**
* When set to true, the function will not throw 404 error when the asset meta is not found or meta validation failed
*/
fallthrough?: boolean;
/**
* Custom MIME type resolver function
* @param ext - File extension including dot (e.g., ".css", ".js")
*/
getType?: (ext: string) => string | undefined;
}
/**
* Dynamically serve static assets based on the request path.
*/
export async function serveStatic(
event: H3Event,
options: ServeStaticOptions,
): Promise<HTTPResponse | undefined> {
if (options.headers) {
const entries = Array.isArray(options.headers)
? options.headers
: typeof options.headers.entries === "function"
? options.headers.entries()
: Object.entries(options.headers);
for (const [key, value] of entries) {
event.res.headers.set(key, value);
}
}
if (event.req.method !== "GET" && event.req.method !== "HEAD") {
if (options.fallthrough) {
return;
}
event.res.headers.set("allow", "GET, HEAD");
throw new HTTPError({ status: 405 });
}
const originalId = decodeURI(withLeadingSlash(withoutTrailingSlash(event.url.pathname)));
const acceptEncodings = parseAcceptEncoding(
event.req.headers.get("accept-encoding") || "",
options.encodings,
);
if (acceptEncodings.length > 1) {
event.res.headers.set("vary", "accept-encoding");
}
let id = originalId;
let meta: StaticAssetMeta | undefined;
const _ids = idSearchPaths(originalId, acceptEncodings, options.indexNames || ["/index.html"]);
for (const _id of _ids) {
const _meta = await options.getMeta(_id);
if (_meta) {
meta = _meta;
id = _id;
break;
}
}
if (!meta) {
if (options.fallthrough) {
return;
}
throw new HTTPError({ statusCode: 404 });
}
if (meta.mtime) {
const mtimeDate = new Date(meta.mtime);
const ifModifiedSinceH = event.req.headers.get("if-modified-since");
if (ifModifiedSinceH && new Date(ifModifiedSinceH) >= mtimeDate) {
return new HTTPResponse(null, {
status: 304,
statusText: "Not Modified",
});
}
if (!event.res.headers.get("last-modified")) {
event.res.headers.set("last-modified", mtimeDate.toUTCString());
}
}
if (meta.etag && !event.res.headers.has("etag")) {
event.res.headers.set("etag", meta.etag);
}
const ifNotMatch = meta.etag && event.req.headers.get("if-none-match") === meta.etag;
if (ifNotMatch) {
return new HTTPResponse(null, {
status: 304,
statusText: "Not Modified",
});
}
if (!event.res.headers.get("content-type")) {
if (meta.type) {
event.res.headers.set("content-type", meta.type);
} else {
const ext = getExtension(id);
const type = ext ? (options.getType?.(ext) ?? getType(ext)) : undefined;
if (type) {
event.res.headers.set("content-type", type);
}
}
}
if (meta.encoding && !event.res.headers.get("content-encoding")) {
event.res.headers.set("content-encoding", meta.encoding);
}
if (meta.size !== undefined && meta.size > 0 && !event.req.headers.get("content-length")) {
event.res.headers.set("content-length", meta.size + "");
}
if (event.req.method === "HEAD") {
return new HTTPResponse(null, { status: 200 });
}
const contents = await options.getContents(id);
return new HTTPResponse(contents || null, { status: 200 });
}
// --- Internal Utils ---
function parseAcceptEncoding(header?: string, encodingMap?: Record<string, string>): string[] {
if (!encodingMap || !header) {
return [];
}
return String(header || "")
.split(",")
.map((e) => encodingMap[e.trim()])
.filter(Boolean);
}
function idSearchPaths(id: string, encodings: string[], indexNames: string[]) {
const ids = [];
for (const suffix of ["", ...indexNames]) {
for (const encoding of [...encodings, ""]) {
ids.push(`${id}${suffix}${encoding}`);
}
}
return ids;
}