@johnhenry/sitefile 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -1
- package/README.md +12 -1
- package/lib/src/attest.d.ts +12 -3
- package/lib/src/attest.js +15 -10
- package/lib/src/bake.js +2 -1
- package/lib/src/base-image.d.ts +2 -0
- package/lib/src/base-image.js +8 -0
- package/lib/src/bucket-follow.d.ts +22 -0
- package/lib/src/bucket-follow.js +65 -0
- package/lib/src/bucket.d.ts +270 -0
- package/lib/src/bucket.js +1130 -0
- package/lib/src/cache-limit.d.ts +3 -3
- package/lib/src/cache-limit.js +21 -0
- package/lib/src/cli/bucket.d.ts +2 -0
- package/lib/src/cli/bucket.js +312 -0
- package/lib/src/cli/build-image.js +4 -2
- package/lib/src/cli/images.js +8 -5
- package/lib/src/cli/index.d.ts +1 -1
- package/lib/src/cli/index.js +13 -2
- package/lib/src/cli/serve-worker.js +63 -11
- package/lib/src/cli/servers.js +117 -29
- package/lib/src/cli/up.js +2 -0
- package/lib/src/cli/watch.d.ts +2 -0
- package/lib/src/cli/watch.js +2 -1
- package/lib/src/cli.js +6 -3
- package/lib/src/dictionary.d.ts +1 -7
- package/lib/src/dictionary.js +1 -35
- package/lib/src/executor.d.ts +16 -5
- package/lib/src/executor.js +127 -58
- package/lib/src/index.d.ts +2 -0
- package/lib/src/index.js +2 -0
- package/lib/src/mime-type.d.ts +6 -0
- package/lib/src/mime-type.js +20 -0
- package/lib/src/nfc.d.ts +6 -0
- package/lib/src/nfc.js +10 -0
- package/lib/src/oci.d.ts +65 -1
- package/lib/src/oci.js +104 -10
- package/lib/src/paths.d.ts +2 -6
- package/lib/src/paths.js +2 -8
- package/lib/src/plugins/env.d.ts +20 -0
- package/lib/src/plugins/env.js +37 -0
- package/lib/src/plugins/exec.d.ts +1 -1
- package/lib/src/plugins/exec.js +3 -2
- package/lib/src/plugins/host.js +3 -2
- package/lib/src/precompress.d.ts +6 -0
- package/lib/src/precompress.js +6 -0
- package/lib/src/recipe.d.ts +37 -0
- package/lib/src/recipe.js +96 -0
- package/lib/src/registry-ops.d.ts +5 -1
- package/lib/src/registry-ops.js +69 -45
- package/lib/src/request-path.d.ts +10 -0
- package/lib/src/request-path.js +42 -0
- package/lib/src/serve-dictionary.d.ts +11 -0
- package/lib/src/serve-dictionary.js +45 -0
- package/lib/src/serve-rules.js +1 -1
- package/lib/src/server.d.ts +16 -229
- package/lib/src/server.js +135 -795
- package/lib/src/servers.d.ts +25 -0
- package/lib/src/servers.js +62 -2
- package/lib/src/site-core.d.ts +368 -0
- package/lib/src/site-core.js +1065 -0
- package/lib/src/site-handler.d.ts +14 -0
- package/lib/src/site-handler.js +32 -0
- package/lib/src/store.d.ts +31 -2
- package/lib/src/store.js +140 -21
- package/lib/src/wbn.d.ts +1 -6
- package/lib/src/wbn.js +2 -18
- package/package.json +5 -1
|
@@ -0,0 +1,1065 @@
|
|
|
1
|
+
// The site handler's implementation: what `serve` answers for a request, with no listener and no `node:` import.
|
|
2
|
+
//
|
|
3
|
+
// NOT a public module: `src/site-handler.ts` is the package's `./site-handler` subpath and exports only
|
|
4
|
+
// `createSiteHandler`, `createSiteResponder` and their option and reply types. This file also carries what the
|
|
5
|
+
// adapter (`src/server.ts`) and the tests need (the helpers, the reload script, `SiteCoreOptions`).
|
|
6
|
+
//
|
|
7
|
+
// `createSiteHandler(tree, options)` returns a `(Request) => Promise<Response>`. It applies the serve
|
|
8
|
+
// rules to an immutable tree: clean URLs, `/404.html`, `_redirects` and `_headers` (never served
|
|
9
|
+
// themselves), ETags and `304`, single byte ranges, precompressed `.br` / `.gz` sidecars, `.dcz`
|
|
10
|
+
// deltas, `--compress`, `--spa`, `--base`, `--rewrite-base`, host profiles, CORS and the
|
|
11
|
+
// cross-origin isolation headers, and `--proxy` routes. `src/server.ts` is the Node adapter around
|
|
12
|
+
// it: listener, Host allow-list, IP rules, basic auth, connection limits, throttling, the access
|
|
13
|
+
// log and the live-reload stream. The Rust port has the same split (`rust/src/server.rs`,
|
|
14
|
+
// `respond`). Documented in docs/CLI.md, "serve", under "The site handler".
|
|
15
|
+
//
|
|
16
|
+
// Nothing here may import a `node:` module, directly or through another module: the module graph
|
|
17
|
+
// is checked by test/site-handler.test.ts, which also drives the handler with plain `Request`s.
|
|
18
|
+
import { isSitefileError, SitefileError } from './errors.js';
|
|
19
|
+
import { gzip } from './deflate.js';
|
|
20
|
+
import { mimeTypeFor } from './mime-type.js';
|
|
21
|
+
import { encodePath, originForm, safeSegments } from './request-path.js';
|
|
22
|
+
import { deltaFor } from './serve-dictionary.js';
|
|
23
|
+
import { globMatch, headersFor, isRewriteStatus, matchRedirect, matchRule, parseHeaderRules, parseRedirectRules, substituteTarget } from './serve-rules.js';
|
|
24
|
+
export { originForm, safeSegments };
|
|
25
|
+
/** Response headers a proxy does not pass on (RFC 9110 section 7.6.1), and the length it recomputes. */
|
|
26
|
+
const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
|
|
27
|
+
/** Request headers passed to the upstream (no cookies or credentials: they belong to this server's origin). */
|
|
28
|
+
const PROXY_REQUEST_HEADERS = ['accept', 'accept-language', 'if-none-match', 'if-modified-since', 'range'];
|
|
29
|
+
/** Bodies of this many bytes or more are a stream of views of this size, not one buffer. */
|
|
30
|
+
const STREAM_FROM = 256 * 1024;
|
|
31
|
+
const CHUNK = 64 * 1024;
|
|
32
|
+
function bodyOf(bytes) {
|
|
33
|
+
if (bytes.byteLength < STREAM_FROM)
|
|
34
|
+
return bytes;
|
|
35
|
+
let at = 0;
|
|
36
|
+
return new ReadableStream({
|
|
37
|
+
pull(controller) {
|
|
38
|
+
const end = Math.min(bytes.byteLength, at + CHUNK);
|
|
39
|
+
controller.enqueue(bytes.subarray(at, end));
|
|
40
|
+
at = end;
|
|
41
|
+
if (at >= bytes.byteLength)
|
|
42
|
+
controller.close();
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const utf8 = new TextEncoder();
|
|
47
|
+
/** A byte string as a JavaScript string of code points 0-255 (every byte kept). */
|
|
48
|
+
function latin1(bytes) {
|
|
49
|
+
let s = '';
|
|
50
|
+
for (let i = 0; i < bytes.byteLength; i += 8192)
|
|
51
|
+
s += String.fromCharCode(...bytes.subarray(i, i + 8192));
|
|
52
|
+
return s;
|
|
53
|
+
}
|
|
54
|
+
function fromLatin1(s) {
|
|
55
|
+
const out = new Uint8Array(s.length);
|
|
56
|
+
for (let i = 0; i < s.length; i++)
|
|
57
|
+
out[i] = s.charCodeAt(i);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
function concat(...parts) {
|
|
61
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0));
|
|
62
|
+
let at = 0;
|
|
63
|
+
for (const p of parts) {
|
|
64
|
+
out.set(p, at);
|
|
65
|
+
at += p.byteLength;
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
|
|
70
|
+
export function gzipMember(deflate, crc, size) {
|
|
71
|
+
const out = new Uint8Array(10 + deflate.byteLength + 8);
|
|
72
|
+
out.set([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]);
|
|
73
|
+
out.set(deflate, 10);
|
|
74
|
+
const view = new DataView(out.buffer);
|
|
75
|
+
view.setUint32(10 + deflate.byteLength, crc >>> 0, true);
|
|
76
|
+
view.setUint32(10 + deflate.byteLength + 4, size % 2 ** 32, true);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** `html` with {@link RELOAD_SCRIPT} inserted before the last `</body` (ASCII case-insensitive), else appended. */
|
|
80
|
+
export function injectReloadScript(html) {
|
|
81
|
+
const at = latin1(html).toLowerCase().lastIndexOf('</body');
|
|
82
|
+
const script = utf8.encode(RELOAD_SCRIPT);
|
|
83
|
+
return at === -1 ? concat(html, script) : concat(html.subarray(0, at), script, html.subarray(at));
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
|
|
87
|
+
* the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
|
|
88
|
+
* so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
|
|
89
|
+
*/
|
|
90
|
+
export function rewriteBaseUrls(body, from, to) {
|
|
91
|
+
const text = latin1(body);
|
|
92
|
+
let out = '';
|
|
93
|
+
let i = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
const at = text.indexOf(from, i);
|
|
96
|
+
if (at === -1)
|
|
97
|
+
break;
|
|
98
|
+
const next = text[at + from.length];
|
|
99
|
+
out += text.slice(i, at) + (next !== undefined && /[A-Za-z0-9._~:%-]/.test(next) ? from : to);
|
|
100
|
+
i = at + from.length;
|
|
101
|
+
}
|
|
102
|
+
if (i === 0)
|
|
103
|
+
return body;
|
|
104
|
+
return fromLatin1(out + text.slice(i));
|
|
105
|
+
}
|
|
106
|
+
/** Order two strings by their UTF-8 bytes (what `sort` over files does in the Rust port). */
|
|
107
|
+
const utf8Order = (a, b) => {
|
|
108
|
+
const x = utf8.encode(a);
|
|
109
|
+
const y = utf8.encode(b);
|
|
110
|
+
const n = Math.min(x.length, y.length);
|
|
111
|
+
for (let i = 0; i < n; i++)
|
|
112
|
+
if (x[i] !== y[i])
|
|
113
|
+
return x[i] - y[i];
|
|
114
|
+
return x.length - y.length;
|
|
115
|
+
};
|
|
116
|
+
/** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
|
|
117
|
+
export function acceptsGzip(header) {
|
|
118
|
+
if (header === undefined)
|
|
119
|
+
return false;
|
|
120
|
+
return header.split(',').some((part) => {
|
|
121
|
+
const [name, ...params] = part.trim().split(';');
|
|
122
|
+
if (name?.trim().toLowerCase() !== 'gzip' && name?.trim().toLowerCase() !== 'x-gzip')
|
|
123
|
+
return false;
|
|
124
|
+
const q = params.map((x) => x.trim()).find((x) => x.toLowerCase().startsWith('q='));
|
|
125
|
+
return q === undefined || Number(q.slice(2)) > 0;
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/** Reserved for the live-reload event stream while `serve --watch` runs. */
|
|
129
|
+
export const RELOAD_PATH = '/__sitefile/reload';
|
|
130
|
+
/** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
|
|
131
|
+
export const RELOAD_SCRIPT_PATH = '/__sitefile/reload.js';
|
|
132
|
+
/** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
|
|
133
|
+
export const RELOAD_SCRIPT = `<script src="${RELOAD_SCRIPT_PATH}"></script>`;
|
|
134
|
+
/**
|
|
135
|
+
* Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
|
|
136
|
+
* when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
|
|
137
|
+
* `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
|
|
138
|
+
*/
|
|
139
|
+
export function isNavigation(headers) {
|
|
140
|
+
const one = (k) => {
|
|
141
|
+
const v = headers[k];
|
|
142
|
+
return Array.isArray(v) ? v.join(', ') : v;
|
|
143
|
+
};
|
|
144
|
+
const mode = one('sec-fetch-mode');
|
|
145
|
+
if (mode !== undefined)
|
|
146
|
+
return mode.trim().toLowerCase() === 'navigate';
|
|
147
|
+
const dest = one('sec-fetch-dest');
|
|
148
|
+
if (dest !== undefined)
|
|
149
|
+
return ['document', 'iframe', 'frame'].includes(dest.trim().toLowerCase());
|
|
150
|
+
return (one('accept') ?? '').toLowerCase().includes('text/html');
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
|
|
154
|
+
* a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
|
|
155
|
+
* undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
|
|
156
|
+
* `https:` count as allowing the server's own origin (host sources are not matched), and
|
|
157
|
+
* `'strict-dynamic'` makes `'self'` ignored for scripts.
|
|
158
|
+
*/
|
|
159
|
+
export function cspBlocksReload(value) {
|
|
160
|
+
for (const policy of value.split(',')) {
|
|
161
|
+
const directives = new Map();
|
|
162
|
+
for (const d of policy.split(';')) {
|
|
163
|
+
const [name, ...sources] = d.trim().split(/[\t\n\f\r ]+/).filter((t) => t !== '');
|
|
164
|
+
if (name !== undefined && !directives.has(name.toLowerCase()))
|
|
165
|
+
directives.set(name.toLowerCase(), sources.map((t) => t.toLowerCase()));
|
|
166
|
+
}
|
|
167
|
+
const effective = (names) => names.map((n) => directives.get(n)).find((v) => v !== undefined);
|
|
168
|
+
const allows = (sources, script) => sources === undefined ||
|
|
169
|
+
(!(script && sources.includes("'strict-dynamic'")) && sources.some((t) => t === "'self'" || t === '*' || t === 'http:' || t === 'https:'));
|
|
170
|
+
if (!allows(effective(['script-src-elem', 'script-src', 'default-src']), true))
|
|
171
|
+
return 'script-src';
|
|
172
|
+
if (!allows(effective(['connect-src', 'default-src']), false))
|
|
173
|
+
return 'connect-src';
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
export const NOT_FOUND_PAGE = '<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n';
|
|
178
|
+
export const BAD_REQUEST_PAGE = '<!doctype html><meta charset="utf-8"><title>400 Bad Request</title><h1>400 Bad Request</h1>\n';
|
|
179
|
+
export const FORBIDDEN_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1>\n';
|
|
180
|
+
export const UNAUTHORIZED_PAGE = '<!doctype html><meta charset="utf-8"><title>401 Unauthorized</title><h1>401 Unauthorized</h1>\n';
|
|
181
|
+
export const FORBIDDEN_HOST_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1><p>This server answers requests for localhost and IP addresses only. To allow another host name, restart it with <code>--allowed-host <name></code>.</p>\n';
|
|
182
|
+
export const ERROR_PAGE = '<!doctype html><meta charset="utf-8"><title>500 Internal Server Error</title><h1>500 Internal Server Error</h1>\n';
|
|
183
|
+
export const METHOD_PAGE = '<!doctype html><meta charset="utf-8"><title>405 Method Not Allowed</title><h1>405 Method Not Allowed</h1>\n';
|
|
184
|
+
/**
|
|
185
|
+
* Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
|
|
186
|
+
* case-insensitive; an explicit entry wins over `*`.
|
|
187
|
+
*/
|
|
188
|
+
export function acceptsEncoding(header, coding) {
|
|
189
|
+
if (header === undefined)
|
|
190
|
+
return false;
|
|
191
|
+
let star;
|
|
192
|
+
for (const part of header.split(',')) {
|
|
193
|
+
const [name, ...params] = part.split(';').map((x) => x.trim());
|
|
194
|
+
const n = (name ?? '').replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
195
|
+
let q = 1;
|
|
196
|
+
for (const p of params) {
|
|
197
|
+
const m = /^[qQ][ \t]*=[ \t]*([0-9.]+)$/.exec(p);
|
|
198
|
+
if (m)
|
|
199
|
+
q = Number(m[1]);
|
|
200
|
+
}
|
|
201
|
+
const ok = Number.isFinite(q) && q > 0;
|
|
202
|
+
if (n === coding)
|
|
203
|
+
return ok;
|
|
204
|
+
if (n === '*')
|
|
205
|
+
star = ok;
|
|
206
|
+
}
|
|
207
|
+
return star ?? false;
|
|
208
|
+
}
|
|
209
|
+
/** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
|
|
210
|
+
export function isCompressible(type) {
|
|
211
|
+
const t = (type.split(';')[0] ?? '').trim();
|
|
212
|
+
return t.startsWith('text/') || t.endsWith('+json') || t.endsWith('+xml') || ['application/json', 'application/xml', 'application/javascript', 'application/wasm', 'image/svg+xml'].includes(t);
|
|
213
|
+
}
|
|
214
|
+
/** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
|
|
215
|
+
export function cacheControlFor(type, cache) {
|
|
216
|
+
if (cache === undefined)
|
|
217
|
+
return undefined;
|
|
218
|
+
if (type.startsWith('text/html'))
|
|
219
|
+
return cache.maxAgeHtml === undefined ? undefined : `public, max-age=${cache.maxAgeHtml}`;
|
|
220
|
+
if (cache.maxAge === undefined)
|
|
221
|
+
return undefined;
|
|
222
|
+
return `public, max-age=${cache.maxAge}${cache.immutable ? ', immutable' : ''}`;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
|
|
226
|
+
* section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
|
|
227
|
+
* `/` for an empty path); any other target is returned as it is. The authority is not checked.
|
|
228
|
+
*/
|
|
229
|
+
/** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
|
|
230
|
+
export function preflightHeaders(value) {
|
|
231
|
+
const v = value?.trim();
|
|
232
|
+
return v !== undefined && v !== '' && /^[A-Za-z0-9 \t,!#$%&'*+\-.^_`|~]+$/.test(v) ? v : undefined;
|
|
233
|
+
}
|
|
234
|
+
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
235
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
236
|
+
/** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
|
|
237
|
+
export function httpDate(secs) {
|
|
238
|
+
return new Date(secs * 1000).toUTCString();
|
|
239
|
+
}
|
|
240
|
+
/** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
|
|
241
|
+
export function parseHttpDate(value) {
|
|
242
|
+
const m = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT$/.exec(value.trim());
|
|
243
|
+
if (!m)
|
|
244
|
+
return undefined;
|
|
245
|
+
const [day, month, year, h, min, sec] = [Number(m[2]), MONTHS.indexOf(m[3]), Number(m[4]), Number(m[5]), Number(m[6]), Number(m[7])];
|
|
246
|
+
if (day < 1 || h > 23 || min > 59 || sec > 59)
|
|
247
|
+
return undefined;
|
|
248
|
+
const ms = Date.UTC(year, month, day, h, min, sec);
|
|
249
|
+
const d = new Date(ms);
|
|
250
|
+
if (d.getUTCDate() !== day || DAYS[d.getUTCDay()] !== m[1])
|
|
251
|
+
return undefined;
|
|
252
|
+
return ms / 1000;
|
|
253
|
+
}
|
|
254
|
+
/** A `bytes=` value's number: digits only; more than 15 digits counts as larger than any file. */
|
|
255
|
+
function rangeNumber(s) {
|
|
256
|
+
if (!/^[0-9]+$/.test(s))
|
|
257
|
+
return undefined;
|
|
258
|
+
return s.length > 15 ? Number.POSITIVE_INFINITY : Number(s);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
|
|
262
|
+
* `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
|
|
263
|
+
* asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
|
|
264
|
+
*/
|
|
265
|
+
export function byteRange(header, size) {
|
|
266
|
+
if (header === undefined)
|
|
267
|
+
return undefined;
|
|
268
|
+
const v = header.trim();
|
|
269
|
+
if (v.slice(0, 6).toLowerCase() !== 'bytes=')
|
|
270
|
+
return undefined;
|
|
271
|
+
const spec = v.slice(6).trim();
|
|
272
|
+
if (spec.includes(','))
|
|
273
|
+
return undefined;
|
|
274
|
+
const dash = spec.indexOf('-');
|
|
275
|
+
if (dash === -1)
|
|
276
|
+
return undefined;
|
|
277
|
+
const first = spec.slice(0, dash).trim();
|
|
278
|
+
const last = spec.slice(dash + 1).trim();
|
|
279
|
+
if (first === '') {
|
|
280
|
+
const n = rangeNumber(last);
|
|
281
|
+
if (n === undefined)
|
|
282
|
+
return undefined;
|
|
283
|
+
if (n === 0 || size === 0)
|
|
284
|
+
return 'unsatisfiable';
|
|
285
|
+
return [Math.max(0, size - n), size - 1];
|
|
286
|
+
}
|
|
287
|
+
const start = rangeNumber(first);
|
|
288
|
+
if (start === undefined)
|
|
289
|
+
return undefined;
|
|
290
|
+
const end = last === '' ? Number.POSITIVE_INFINITY : rangeNumber(last);
|
|
291
|
+
if (end === undefined || end < start)
|
|
292
|
+
return undefined;
|
|
293
|
+
if (start >= size)
|
|
294
|
+
return 'unsatisfiable';
|
|
295
|
+
return [start, Math.min(end, size - 1)];
|
|
296
|
+
}
|
|
297
|
+
function etagMatches(header, etag) {
|
|
298
|
+
if (header === undefined)
|
|
299
|
+
return false;
|
|
300
|
+
if (header.trim() === '*')
|
|
301
|
+
return true;
|
|
302
|
+
return header.split(',').some((t) => t.trim().replace(/^W\//, '') === etag);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
|
|
306
|
+
* else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
|
|
307
|
+
* has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
|
|
308
|
+
*/
|
|
309
|
+
export function spaFallback(segs, trailingSlash, isFile, fallback) {
|
|
310
|
+
if (fallback !== undefined)
|
|
311
|
+
return isFile(fallback) ? fallback : undefined;
|
|
312
|
+
const dirs = trailingSlash ? segs : segs.slice(0, -1);
|
|
313
|
+
for (let n = dirs.length; n >= 0; n--) {
|
|
314
|
+
const dir = `/${dirs.slice(0, n).map((d) => d + '/').join('')}`;
|
|
315
|
+
for (const name of ['200.html', 'index.html'])
|
|
316
|
+
if (isFile(dir + name))
|
|
317
|
+
return dir + name;
|
|
318
|
+
}
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
export const HTML_HANDLINGS = ['auto', 'force-slash', 'drop-slash', 'none'];
|
|
322
|
+
export const HOST_PROFILES = ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
|
|
323
|
+
/**
|
|
324
|
+
* The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
|
|
325
|
+
* undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
|
|
326
|
+
*
|
|
327
|
+
* | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
|
|
328
|
+
* | netlify | auto | 301 | yes | nearest 404.html |
|
|
329
|
+
* | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
|
|
330
|
+
* | vercel | none | 308 | no | /404.html |
|
|
331
|
+
* | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
|
|
332
|
+
* | firebase | none | 301 | no | /404.html |
|
|
333
|
+
*/
|
|
334
|
+
export function hostProfile(name, htmlHandling) {
|
|
335
|
+
const base = name === 'netlify'
|
|
336
|
+
? { htmlHandling: 'auto', redirectStatus: 301, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' }
|
|
337
|
+
: name === 'cloudflare'
|
|
338
|
+
? { htmlHandling: 'auto', redirectStatus: 307, siteFiles: true, notFound: 'index', slashHtml: 'redirect' }
|
|
339
|
+
: name === 'vercel'
|
|
340
|
+
? { htmlHandling: 'none', redirectStatus: 308, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
|
|
341
|
+
: name === 'github-pages'
|
|
342
|
+
? { redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'not-found' }
|
|
343
|
+
: name === 'firebase'
|
|
344
|
+
? { htmlHandling: 'none', redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
|
|
345
|
+
: { redirectStatus: 307, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' };
|
|
346
|
+
return htmlHandling === undefined ? base : { ...base, htmlHandling };
|
|
347
|
+
}
|
|
348
|
+
/** The server's routing profile for the flags (undefined: sitefile's own rules). */
|
|
349
|
+
export function routingFor(o) {
|
|
350
|
+
return o.hostProfile === undefined && o.htmlHandling === undefined ? undefined : hostProfile(o.hostProfile, o.htmlHandling);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
|
|
354
|
+
* from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
|
|
355
|
+
* host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
|
|
356
|
+
* conditions do not, in file order.
|
|
357
|
+
*/
|
|
358
|
+
export function nearMisses(tree, isFile, vpath, redirects, req) {
|
|
359
|
+
const lower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
360
|
+
const wanted = new Set([vpath, `${vpath === '/' ? '' : vpath}.html`, `${vpath === '/' ? '' : vpath}/index.html`].map(lower));
|
|
361
|
+
const out = [];
|
|
362
|
+
const files = [...tree.entries()]
|
|
363
|
+
.map(([p]) => p)
|
|
364
|
+
.filter((p) => isFile(p) && wanted.has(lower(p)))
|
|
365
|
+
.sort(utf8Order);
|
|
366
|
+
for (const p of files)
|
|
367
|
+
out.push({ path: p, why: 'the letter case differs (a case-insensitive disk finds it, a host does not)' });
|
|
368
|
+
for (const r of redirects) {
|
|
369
|
+
if (matchRedirect(r, vpath) !== undefined && matchRule(r, vpath, req) === undefined) {
|
|
370
|
+
out.push({ line: r.line, why: `matches the path but not its ${r.query.length > 0 ? 'query parameters' : 'conditions'}${r.query.length > 0 && r.conditions.length > 0 ? ' or conditions' : ''}` });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return out.slice(0, 20);
|
|
374
|
+
}
|
|
375
|
+
const escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => (c === '&' ? '&' : c === '<' ? '<' : c === '>' ? '>' : '"'));
|
|
376
|
+
/** The development 404 page listing near misses. */
|
|
377
|
+
export function nearMissPage(vpath, misses, mount = '') {
|
|
378
|
+
let out = `<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n<p>Nothing is served at <code>${escapeHtml(vpath)}</code>. Near misses:</p>\n<ul>\n`;
|
|
379
|
+
for (const m of misses) {
|
|
380
|
+
const what = m.path !== undefined ? `<a href="${escapeHtml(mount + encodePath(m.path))}">${escapeHtml(m.path)}</a>` : `<code>_redirects:${m.line}</code>`;
|
|
381
|
+
out += `<li>${what}: ${escapeHtml(m.why)}</li>\n`;
|
|
382
|
+
}
|
|
383
|
+
return out + '</ul>\n';
|
|
384
|
+
}
|
|
385
|
+
/** A `Host` header safe to write into a page: a name, IPv4 or bracketed IPv6 address, and a port. */
|
|
386
|
+
const SAFE_HOST = /^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?$/;
|
|
387
|
+
function isIpv4(s) {
|
|
388
|
+
const parts = s.split('.');
|
|
389
|
+
return parts.length === 4 && parts.every((p) => /^[0-9]{1,3}$/.test(p) && Number(p) <= 255);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* The DNS-rebinding guard of {@link SiteHandlerOptions.allowedHosts}: whether a `Host` header value
|
|
393
|
+
* may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
|
|
394
|
+
* attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
|
|
395
|
+
* port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
|
|
396
|
+
* it without the dot).
|
|
397
|
+
*/
|
|
398
|
+
export function hostAllowed(allowed, host) {
|
|
399
|
+
if (allowed === undefined || allowed.includes('*') || host === undefined)
|
|
400
|
+
return true;
|
|
401
|
+
const h = host.trim();
|
|
402
|
+
if (h === '')
|
|
403
|
+
return true;
|
|
404
|
+
if (h.startsWith('[')) {
|
|
405
|
+
const close = h.indexOf(']');
|
|
406
|
+
return close > 1 && /^[0-9A-Fa-f:.]+$/.test(h.slice(1, close)) && /^(:[0-9]*)?$/.test(h.slice(close + 1));
|
|
407
|
+
}
|
|
408
|
+
const m = /^(.*?)(:[0-9]*)?$/.exec(h);
|
|
409
|
+
let name = m[1].replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
410
|
+
if (name.endsWith('.'))
|
|
411
|
+
name = name.slice(0, -1);
|
|
412
|
+
if (isIpv4(name) || name === 'localhost' || name.endsWith('.localhost'))
|
|
413
|
+
return true;
|
|
414
|
+
return allowed.some((e) => (e.startsWith('.') ? name === e.slice(1) || name.endsWith(e) : name === e));
|
|
415
|
+
}
|
|
416
|
+
/** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
|
|
417
|
+
export function parseAllowedHost(value) {
|
|
418
|
+
const v = value.trim().replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
419
|
+
if (v === '*')
|
|
420
|
+
return v;
|
|
421
|
+
return /^\.?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/.test(v) ? v.replace(/\.$/, '') : undefined;
|
|
422
|
+
}
|
|
423
|
+
/** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
|
|
424
|
+
export function isRebasedType(type) {
|
|
425
|
+
return type.startsWith('text/html') || type.startsWith('text/css') || type.split(';', 1)[0].includes('xml');
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
|
|
429
|
+
* fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
|
|
430
|
+
* http(s) URL with a host.
|
|
431
|
+
*/
|
|
432
|
+
export function normalizeProductionUrl(raw) {
|
|
433
|
+
const m = /^(https?:\/\/[^/?#\s]+)(\/[^?#\s]*)?$/i.exec(raw.replace(/[?#].*$/, ''));
|
|
434
|
+
if (!m)
|
|
435
|
+
return undefined;
|
|
436
|
+
return m[1] + (m[2] ?? '').replace(/\/+$/, '');
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
|
|
440
|
+
* safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
|
|
441
|
+
*/
|
|
442
|
+
export function normalizeBase(raw) {
|
|
443
|
+
const m = /^https?:\/\/[^/?#]*(\/[^?#]*)?/i.exec(raw);
|
|
444
|
+
const p = m ? (m[1] ?? '/') : raw;
|
|
445
|
+
const segs = safeSegments(p.startsWith('/') ? p : '/' + p);
|
|
446
|
+
if (!segs)
|
|
447
|
+
return undefined;
|
|
448
|
+
return segs.length === 0 ? '/' : `/${segs.map(encodeURIComponent).join('/')}/`;
|
|
449
|
+
}
|
|
450
|
+
/** The headers every response of a handler with these options carries (before the response's own). */
|
|
451
|
+
export function siteBaseHeaders(options = {}) {
|
|
452
|
+
const base = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' };
|
|
453
|
+
if (options.serverId)
|
|
454
|
+
base['x-sitefile-server'] = options.serverId;
|
|
455
|
+
if (options.cors)
|
|
456
|
+
base['access-control-allow-origin'] = '*';
|
|
457
|
+
if (options.noindex)
|
|
458
|
+
base['x-robots-tag'] = 'noindex';
|
|
459
|
+
if (options.isolate !== undefined) {
|
|
460
|
+
base['cross-origin-opener-policy'] = 'same-origin';
|
|
461
|
+
base['cross-origin-embedder-policy'] = options.isolate;
|
|
462
|
+
base['cross-origin-resource-policy'] = 'same-origin';
|
|
463
|
+
}
|
|
464
|
+
return base;
|
|
465
|
+
}
|
|
466
|
+
/** `--base` as segments, normalized like the CLI does (`normalizeBase`): none is `[]`; a value it cannot normalize throws. */
|
|
467
|
+
function baseSegmentsOf(raw) {
|
|
468
|
+
const v = typeof raw === 'function' ? raw() : raw;
|
|
469
|
+
if (v === undefined)
|
|
470
|
+
return [];
|
|
471
|
+
const n = normalizeBase(v);
|
|
472
|
+
if (n === undefined)
|
|
473
|
+
throw new SitefileError('E_USAGE', `base expects a path such as /repo/, got '${v}'`);
|
|
474
|
+
return safeSegments(n) ?? [];
|
|
475
|
+
}
|
|
476
|
+
/** `--rewrite-base` as the normalized production URL, undefined for none; a value that is not an http(s) URL throws. */
|
|
477
|
+
function rewriteBaseOf(raw) {
|
|
478
|
+
const v = typeof raw === 'function' ? raw() : raw;
|
|
479
|
+
if (v === undefined)
|
|
480
|
+
return undefined;
|
|
481
|
+
const n = normalizeProductionUrl(v);
|
|
482
|
+
if (n === undefined)
|
|
483
|
+
throw new SitefileError('E_USAGE', `rewriteBase expects the production URL such as https://example.com/, got '${v}'`);
|
|
484
|
+
return n;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* The origin that `rewriteBase` writes into a page: `scheme://host`. With `allowedHosts` the `Host` header is the host (the
|
|
488
|
+
* caller has checked it); otherwise only an absolute-form target (a `Request` URL) names one. The scheme is the target's,
|
|
489
|
+
* `http` when it has none. The command-line server (`operator`) always uses the `Host` header and `http`.
|
|
490
|
+
*/
|
|
491
|
+
function originOf(target, host, options) {
|
|
492
|
+
const abs = options.operator ? null : /^(https?):\/\/([^/?#]*)/i.exec(target);
|
|
493
|
+
const authority = options.allowedHosts !== undefined && host !== undefined ? host : abs?.[2];
|
|
494
|
+
return authority !== undefined && SAFE_HOST.test(authority) ? `${abs ? abs[1].toLowerCase() : 'http'}://${authority}` : undefined;
|
|
495
|
+
}
|
|
496
|
+
/** What a proxy target's host must match to be let through whatever its scheme or address: `allow`, and each route's host. */
|
|
497
|
+
function proxyAllowList(proxy) {
|
|
498
|
+
const out = (proxy?.allow ?? []).map((h) => h.trim().replace(/[A-Z]/g, (c) => c.toLowerCase()));
|
|
499
|
+
for (const r of proxy?.routes ?? []) {
|
|
500
|
+
try {
|
|
501
|
+
out.push(new URL(r.target).hostname.replace(/^\[|\]$/g, ''));
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
throw new SitefileError('E_USAGE', `proxy route ${r.prefix}: '${r.target}' is not a URL`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return out;
|
|
508
|
+
}
|
|
509
|
+
/** Whether an IPv4 address (four numbers) is not a public unicast one: this-network, private, shared, loopback, link-local, protocol, documentation, benchmarking, multicast or reserved. */
|
|
510
|
+
function nonPublicV4(a, b, c) {
|
|
511
|
+
return (a === 0 || a === 10 || a === 127 || a >= 224 ||
|
|
512
|
+
(a === 100 && b >= 64 && b <= 127) ||
|
|
513
|
+
(a === 169 && b === 254) ||
|
|
514
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
515
|
+
(a === 192 && b === 0 && (c === 0 || c === 2)) ||
|
|
516
|
+
(a === 192 && b === 88 && c === 99) ||
|
|
517
|
+
(a === 192 && b === 168) ||
|
|
518
|
+
(a === 198 && (b === 18 || b === 19)) ||
|
|
519
|
+
(a === 198 && b === 51 && c === 100) ||
|
|
520
|
+
(a === 203 && b === 0 && c === 113));
|
|
521
|
+
}
|
|
522
|
+
/** Why a proxy target's literal host is not public (undefined: it may be). `host` is a URL's `hostname` (WHATWG: numbers canonical, IPv6 bracketed). */
|
|
523
|
+
function nonPublicHost(host) {
|
|
524
|
+
const h = host.replace(/\.$/, '');
|
|
525
|
+
const v4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/.exec(h);
|
|
526
|
+
if (v4)
|
|
527
|
+
return nonPublicV4(Number(v4[1]), Number(v4[2]), Number(v4[3])) ? 'a non-public address' : undefined;
|
|
528
|
+
if (h.startsWith('[')) {
|
|
529
|
+
const groups = parseV6(h.slice(1, -1));
|
|
530
|
+
if (groups === undefined)
|
|
531
|
+
return 'an IPv6 address it cannot read';
|
|
532
|
+
const [g0, g1] = [groups[0], groups[1]];
|
|
533
|
+
const embedded = (hi, lo) => nonPublicV4(hi >> 8, hi & 255, lo >> 8);
|
|
534
|
+
// Only global unicast (2000::/3) is public, minus documentation (2001:db8::/32) and Teredo (2001::/32); 6to4 (2002::/16) carries an IPv4 address.
|
|
535
|
+
if (g0 < 0x2000 || g0 > 0x3fff)
|
|
536
|
+
return 'a non-public address';
|
|
537
|
+
if (g0 === 0x2001 && (g1 === 0x0db8 || g1 === 0))
|
|
538
|
+
return 'a non-public address';
|
|
539
|
+
if (g0 === 0x2002 && embedded(g1, groups[2]))
|
|
540
|
+
return 'a non-public address';
|
|
541
|
+
return undefined;
|
|
542
|
+
}
|
|
543
|
+
if (h === '' || !h.includes('.') || h === 'localhost' || /\.(localhost|local|localdomain|internal|home\.arpa|lan|intranet|corp)$/.test(h))
|
|
544
|
+
return 'a local host name';
|
|
545
|
+
return undefined;
|
|
546
|
+
}
|
|
547
|
+
/** The eight 16-bit groups of an IPv6 address as a URL prints it (lowercase hex, `::` once, no embedded dotted quad), or undefined. */
|
|
548
|
+
function parseV6(text) {
|
|
549
|
+
const halves = text.split('::');
|
|
550
|
+
if (halves.length > 2)
|
|
551
|
+
return undefined;
|
|
552
|
+
const group = (t) => {
|
|
553
|
+
if (t === '')
|
|
554
|
+
return [];
|
|
555
|
+
const out = [];
|
|
556
|
+
for (const g of t.split(':')) {
|
|
557
|
+
if (!/^[0-9a-f]{1,4}$/i.test(g))
|
|
558
|
+
return undefined;
|
|
559
|
+
out.push(parseInt(g, 16));
|
|
560
|
+
}
|
|
561
|
+
return out;
|
|
562
|
+
};
|
|
563
|
+
const head = group(halves[0]);
|
|
564
|
+
const tail = halves.length === 2 ? group(halves[1]) : [];
|
|
565
|
+
if (head === undefined || tail === undefined)
|
|
566
|
+
return undefined;
|
|
567
|
+
if (halves.length === 1)
|
|
568
|
+
return head.length === 8 ? head : undefined;
|
|
569
|
+
const fill = 8 - head.length - tail.length;
|
|
570
|
+
return fill < 1 ? undefined : [...head, ...new Array(fill).fill(0), ...tail];
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* The handler's own proxy policy ({@link SiteProxy}), by the target's literal host: undefined when `target` may be
|
|
574
|
+
* fetched, else why not (for the operator's log only, never sent to a client).
|
|
575
|
+
*/
|
|
576
|
+
function proxyRefusal(target, allow) {
|
|
577
|
+
let u;
|
|
578
|
+
try {
|
|
579
|
+
u = new URL(target);
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
return 'the target is not a URL';
|
|
583
|
+
}
|
|
584
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:')
|
|
585
|
+
return `the scheme ${u.protocol} is not proxied`;
|
|
586
|
+
if (u.username !== '' || u.password !== '')
|
|
587
|
+
return 'the target carries credentials';
|
|
588
|
+
const host = u.hostname.toLowerCase();
|
|
589
|
+
const bare = host.replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
590
|
+
if (allow.some((e) => (e.startsWith('.') ? bare === e.slice(1) || bare.endsWith(e) : bare === e)))
|
|
591
|
+
return undefined;
|
|
592
|
+
if (u.protocol !== 'https:')
|
|
593
|
+
return 'the target is not https';
|
|
594
|
+
const why = nonPublicHost(host);
|
|
595
|
+
return why === undefined ? undefined : `the host is ${why}`;
|
|
596
|
+
}
|
|
597
|
+
/** `text` with URL credentials, queries and fragments removed and control characters and length bounded: safe for a log. */
|
|
598
|
+
function redactText(text) {
|
|
599
|
+
return text
|
|
600
|
+
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#@]*@/gi, '$1')
|
|
601
|
+
.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#]*)[?#]\S*/gi, '$1')
|
|
602
|
+
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
603
|
+
.slice(0, 300);
|
|
604
|
+
}
|
|
605
|
+
/** The body of every refused or failed proxy request: it never says why (that is for the operator's log). */
|
|
606
|
+
const PROXY_FAILED = '502 Bad Gateway: the request could not be proxied\n';
|
|
607
|
+
/**
|
|
608
|
+
* The site handler for an immutable tree: a function from a request (method, target, headers) to a
|
|
609
|
+
* {@link SiteReply}. GET and HEAD only (and `OPTIONS` with `cors`); nothing outside the tree is ever
|
|
610
|
+
* reachable because lookups are exact map keys built from validated segments. Honours `/404.html`,
|
|
611
|
+
* `/_redirects` and `/_headers` (which it never serves), answers `/about` with `/about.html` when
|
|
612
|
+
* there is no such file or directory, and redirects `/about/` to `/about` when only `/about.html`
|
|
613
|
+
* answers it. `site` may be a function: it is read per request (`serve --watch` swaps in each good rebuild).
|
|
614
|
+
*
|
|
615
|
+
* This is the low-level form the Node adapter uses, because it takes the request target exactly as
|
|
616
|
+
* received (a `Request` URL is already normalized by the platform, so `/a/../b` never reaches a handler).
|
|
617
|
+
* Use {@link createSiteHandler} anywhere a `Request` is what you have.
|
|
618
|
+
*/
|
|
619
|
+
export function createSiteResponder(site, options = {}) {
|
|
620
|
+
const current = typeof site === 'function' ? site : () => site;
|
|
621
|
+
const base = siteBaseHeaders(options);
|
|
622
|
+
// `base` and `rewriteBase` are normalized here, and a value that cannot be is refused now: a prefix the handler
|
|
623
|
+
// did not understand must never turn into "serve everything at /".
|
|
624
|
+
const baseOf = () => baseSegmentsOf(options.base);
|
|
625
|
+
const rewriteOf = () => rewriteBaseOf(options.rewriteBase);
|
|
626
|
+
baseOf();
|
|
627
|
+
rewriteOf();
|
|
628
|
+
const proxyAllow = proxyAllowList(options.proxy);
|
|
629
|
+
// `_redirects` / `_headers` are parsed once per tree (a watched server gets a new tree per rebuild).
|
|
630
|
+
let rulesTree;
|
|
631
|
+
let rules = { redirects: [], headers: [] };
|
|
632
|
+
const rulesFor = (t) => {
|
|
633
|
+
if (t !== rulesTree) {
|
|
634
|
+
const text = (p) => {
|
|
635
|
+
const f = t.get(p);
|
|
636
|
+
return f ? new TextDecoder().decode(options.content?.read(p) ?? f.bytes) : '';
|
|
637
|
+
};
|
|
638
|
+
rules = { redirects: parseRedirectRules(text('/_redirects')), headers: parseHeaderRules(text('/_headers')) };
|
|
639
|
+
rulesTree = t;
|
|
640
|
+
}
|
|
641
|
+
return rules;
|
|
642
|
+
};
|
|
643
|
+
// One warning per policy text: a site usually sends the same CSP on every page.
|
|
644
|
+
const warnedCsp = new Set();
|
|
645
|
+
const warnCsp = (served, policy) => {
|
|
646
|
+
if (policy === undefined || options.warn === undefined || warnedCsp.has(policy))
|
|
647
|
+
return;
|
|
648
|
+
const blocked = cspBlocksReload(policy);
|
|
649
|
+
if (blocked === undefined)
|
|
650
|
+
return;
|
|
651
|
+
warnedCsp.add(policy);
|
|
652
|
+
const what = blocked === 'script-src' ? `scripts from 'self' (${RELOAD_SCRIPT_PATH})` : `connections to 'self' (${RELOAD_PATH})`;
|
|
653
|
+
options.warn(`live reload: the Content-Security-Policy that _headers sets for ${served} does not allow ${what}, so open pages will not reload: ${policy}`);
|
|
654
|
+
};
|
|
655
|
+
/** --compress: gzip output by file digest (at most 256 files), so a file is compressed once. */
|
|
656
|
+
const gzipCache = new Map();
|
|
657
|
+
const gzipped = (digest, bytes) => {
|
|
658
|
+
let out = gzipCache.get(digest);
|
|
659
|
+
if (out === undefined) {
|
|
660
|
+
if (gzipCache.size >= 256)
|
|
661
|
+
gzipCache.clear();
|
|
662
|
+
out = gzip(bytes);
|
|
663
|
+
gzipCache.set(digest, out);
|
|
664
|
+
}
|
|
665
|
+
return out;
|
|
666
|
+
};
|
|
667
|
+
const respond = async (req) => {
|
|
668
|
+
const method = req.method;
|
|
669
|
+
const target = req.target;
|
|
670
|
+
const url = originForm(target);
|
|
671
|
+
const h = (name) => req.headers.get(name) ?? undefined;
|
|
672
|
+
/** What answered, for the access log (` → /new (_redirects:3)`), when a rule did. */
|
|
673
|
+
let note = '';
|
|
674
|
+
const finish = (status, headers, body) => {
|
|
675
|
+
const buf = body === undefined ? undefined : typeof body === 'string' ? utf8.encode(body) : body;
|
|
676
|
+
const send = buf !== undefined && method !== 'HEAD' && status !== 304 && buf.byteLength > 0 ? buf : undefined;
|
|
677
|
+
const out = new Headers();
|
|
678
|
+
for (const [k, v] of Object.entries({ ...base, ...headers })) {
|
|
679
|
+
if (typeof v === 'string' || typeof v === 'number')
|
|
680
|
+
out.set(k, String(v));
|
|
681
|
+
else
|
|
682
|
+
for (const x of v)
|
|
683
|
+
out.append(k, x);
|
|
684
|
+
}
|
|
685
|
+
return { response: new Response(send === undefined ? null : bodyOf(send), { status, headers: out }), note, bytes: send?.byteLength ?? 0 };
|
|
686
|
+
};
|
|
687
|
+
const page = (status, html, extra = {}) => {
|
|
688
|
+
const bytes = utf8.encode(html);
|
|
689
|
+
return finish(status, { 'content-type': 'text/html; charset=utf-8', 'content-length': bytes.byteLength, ...extra }, bytes);
|
|
690
|
+
};
|
|
691
|
+
// DNS rebinding: a page on another name must not read this server (before anything else). Only a handler that
|
|
692
|
+
// reads the `Host` header (`allowedHosts`) has anything to check.
|
|
693
|
+
const hostHeader = h('host');
|
|
694
|
+
if (options.allowedHosts !== undefined && !hostAllowed(options.allowedHosts, hostHeader))
|
|
695
|
+
return page(403, FORBIDDEN_HOST_PAGE);
|
|
696
|
+
/** The origin `rewriteBase` writes: the `Host` header's (with `allowedHosts`; the scheme the URL's), else the absolute-form target's. */
|
|
697
|
+
const origin = originOf(target, hostHeader, options);
|
|
698
|
+
if (options.cors && method === 'OPTIONS') {
|
|
699
|
+
// A CORS preflight: any path, nothing is looked up.
|
|
700
|
+
const allowHeaders = preflightHeaders(h('access-control-request-headers'));
|
|
701
|
+
return finish(204, { 'access-control-allow-methods': 'GET, HEAD', ...(allowHeaders !== undefined ? { 'access-control-allow-headers': allowHeaders } : {}), 'access-control-max-age': '600' }, undefined);
|
|
702
|
+
}
|
|
703
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
704
|
+
return page(405, METHOD_PAGE, { allow: options.cors ? 'GET, HEAD, OPTIONS' : 'GET, HEAD' });
|
|
705
|
+
const tree = current();
|
|
706
|
+
const profile = options.profile;
|
|
707
|
+
const siteFiles = profile?.siteFiles !== false;
|
|
708
|
+
const { redirects, headers: headerRules } = siteFiles ? rulesFor(tree) : { redirects: [], headers: [] };
|
|
709
|
+
const isFile = (p) => tree.isFile(p) && !(siteFiles && (p === '/_redirects' || p === '/_headers'));
|
|
710
|
+
const q = url.indexOf('?');
|
|
711
|
+
const hash = url.indexOf('#');
|
|
712
|
+
const end = Math.min(q === -1 ? url.length : q, hash === -1 ? url.length : hash);
|
|
713
|
+
const rawPath = url.slice(0, end);
|
|
714
|
+
const search = q === -1 ? '' : url.slice(q, hash === -1 || hash < q ? undefined : hash);
|
|
715
|
+
const allSegs = safeSegments(rawPath);
|
|
716
|
+
if (!allSegs)
|
|
717
|
+
return page(400, BAD_REQUEST_PAGE);
|
|
718
|
+
const trailingSlash = rawPath.endsWith('/');
|
|
719
|
+
// `--base`: the site lives under `mount`; requests outside it are 404 (or redirected into it).
|
|
720
|
+
const baseSegs = baseOf();
|
|
721
|
+
/** The `--base` prefix of generated `Location`s (`''` without one), percent-encoded. */
|
|
722
|
+
const mount = baseSegs.length === 0 ? '' : '/' + baseSegs.map(encodeURIComponent).join('/');
|
|
723
|
+
let segs = allSegs;
|
|
724
|
+
if (baseSegs.length > 0) {
|
|
725
|
+
const inside = baseSegs.every((b, i) => allSegs[i] === b);
|
|
726
|
+
if (inside && allSegs.length === baseSegs.length && !trailingSlash)
|
|
727
|
+
return finish(301, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
|
|
728
|
+
if (!inside && allSegs.length === 0 && !options.hideBase)
|
|
729
|
+
return finish(302, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
|
|
730
|
+
if (!inside)
|
|
731
|
+
return page(404, NOT_FOUND_PAGE);
|
|
732
|
+
segs = allSegs.slice(baseSegs.length);
|
|
733
|
+
}
|
|
734
|
+
const vpath = '/' + segs.join('/');
|
|
735
|
+
// `_headers` patterns match the request path (with its trailing slash).
|
|
736
|
+
const custom = headersFor(headerRules, vpath + (trailingSlash && segs.length > 0 ? '/' : ''));
|
|
737
|
+
const navigation = () => isNavigation({ 'sec-fetch-mode': h('sec-fetch-mode'), 'sec-fetch-dest': h('sec-fetch-dest'), accept: h('accept') });
|
|
738
|
+
const sendFile = (status, served) => {
|
|
739
|
+
const file = tree.get(served);
|
|
740
|
+
const ext = served.slice(served.lastIndexOf('/') + 1).split('.').slice(1).pop()?.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
741
|
+
const type = (ext !== undefined ? options.mime?.get(ext) : undefined) ?? mimeTypeFor(served);
|
|
742
|
+
const live = !!options.injectReload && type.startsWith('text/html') && navigation();
|
|
743
|
+
if (live)
|
|
744
|
+
warnCsp(served, custom['content-security-policy']);
|
|
745
|
+
const prodNow = rewriteOf();
|
|
746
|
+
const rebase = prodNow !== undefined && isRebasedType(type) && origin !== undefined ? { from: prodNow, to: `${origin}${mount}` } : undefined;
|
|
747
|
+
const ae = h('accept-encoding');
|
|
748
|
+
const rangeHeader = h('range');
|
|
749
|
+
// A `.dcz` sidecar (build --experimental-dictionary): sent when the request offers its dictionary.
|
|
750
|
+
const delta = live || rebase ? undefined : deltaFor(tree, served, h('available-dictionary'), ae);
|
|
751
|
+
const dictionaryVary = tree.isFile(`${served}.dcz`);
|
|
752
|
+
// A deflated zip entry goes to a gzip client as is, wrapped in a gzip header and trailer (not for a
|
|
753
|
+
// range request: ranges are served from the identity body).
|
|
754
|
+
const deflated = !live && !delta && !rebase && rangeHeader === undefined && acceptsGzip(ae) ? options.content?.deflated?.(served) : undefined;
|
|
755
|
+
let body;
|
|
756
|
+
try {
|
|
757
|
+
body = deflated ? gzipMember(deflated.deflate, deflated.crc, deflated.size) : (options.content?.read(served) ?? file.bytes);
|
|
758
|
+
}
|
|
759
|
+
catch (e) {
|
|
760
|
+
options.log?.(`error: ${e instanceof SitefileError ? e.message : String(e)}`);
|
|
761
|
+
return page(500, ERROR_PAGE);
|
|
762
|
+
}
|
|
763
|
+
if (rebase)
|
|
764
|
+
body = rewriteBaseUrls(body, rebase.from, rebase.to);
|
|
765
|
+
if (live)
|
|
766
|
+
body = injectReloadScript(body);
|
|
767
|
+
// Otherwise: a precompressed `<path>.br` / `<path>.gz` the client accepts (br first), else gzip on the fly
|
|
768
|
+
// under --compress. Range requests, live pages, rebased pages and deltas are never compressed here.
|
|
769
|
+
const plain = !deflated && !delta && !rebase && status === 200;
|
|
770
|
+
const hasBr = plain && isFile(`${served}.br`);
|
|
771
|
+
const hasGz = plain && isFile(`${served}.gz`);
|
|
772
|
+
const onTheFly = plain && !!options.compress && isCompressible(type) && body.byteLength >= 1024;
|
|
773
|
+
const negotiated = !live && (hasBr || hasGz || onTheFly);
|
|
774
|
+
let coding;
|
|
775
|
+
if (negotiated && rangeHeader === undefined) {
|
|
776
|
+
if (hasBr && acceptsEncoding(ae, 'br'))
|
|
777
|
+
[coding, body] = ['br', tree.get(`${served}.br`).bytes];
|
|
778
|
+
else if (hasGz && acceptsEncoding(ae, 'gzip'))
|
|
779
|
+
[coding, body] = ['gzip', tree.get(`${served}.gz`).bytes];
|
|
780
|
+
else if (onTheFly && acceptsEncoding(ae, 'gzip'))
|
|
781
|
+
[coding, body] = ['gzip', gzipped(file.digest, body)];
|
|
782
|
+
}
|
|
783
|
+
const varyOn = dictionaryVary ? 'accept-encoding, available-dictionary' : 'accept-encoding';
|
|
784
|
+
const vary = deflated || negotiated || dictionaryVary ? { vary: varyOn } : {};
|
|
785
|
+
const encoding = deflated ? { 'content-encoding': 'gzip', ...vary } : coding ? { 'content-encoding': coding, ...vary } : vary;
|
|
786
|
+
if (status !== 200)
|
|
787
|
+
return finish(status, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...custom }, body);
|
|
788
|
+
const preview = cacheControlFor(type, options.cache);
|
|
789
|
+
const cc = preview === undefined ? {} : { 'cache-control': preview };
|
|
790
|
+
// An injected page, a rebased page, a compressed response and a delta are other representations of the
|
|
791
|
+
// file: they get their own ETags.
|
|
792
|
+
const etag = `"${file.digest.replace(/^sha256:/, '')}${rebase ? '-rebased' : ''}${live ? '-live' : ''}${deflated ? '-gzip' : coding ? `-${coding}` : ''}${delta ? '-dcz' : ''}"`;
|
|
793
|
+
const modified = options.lastModified?.();
|
|
794
|
+
const lm = modified === undefined ? {} : { 'last-modified': httpDate(modified) };
|
|
795
|
+
const ifNoneMatch = h('if-none-match');
|
|
796
|
+
if (etagMatches(ifNoneMatch, etag))
|
|
797
|
+
return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
|
|
798
|
+
// If-Modified-Since only counts without If-None-Match (RFC 9110 section 13.2.2).
|
|
799
|
+
const ims = ifNoneMatch === undefined ? h('if-modified-since') : undefined;
|
|
800
|
+
const since = ims === undefined ? undefined : parseHttpDate(ims);
|
|
801
|
+
if (modified !== undefined && since !== undefined && modified <= since)
|
|
802
|
+
return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
|
|
803
|
+
// The delta is sent whole (no byte ranges of an encoded body).
|
|
804
|
+
if (delta)
|
|
805
|
+
return finish(200, { 'content-type': type, 'content-length': delta.byteLength, ...cc, ...custom, ...vary, 'content-encoding': 'dcz', etag, ...lm }, delta);
|
|
806
|
+
// A single byte range of a GET (`If-Range` must name this ETag); anything else gets the whole file.
|
|
807
|
+
const ifRange = h('if-range');
|
|
808
|
+
const range = method === 'GET' && (ifRange === undefined || ifRange.trim() === etag) ? byteRange(rangeHeader, body.byteLength) : undefined;
|
|
809
|
+
if (range === 'unsatisfiable') {
|
|
810
|
+
return finish(416, { ...custom, ...vary, 'accept-ranges': 'bytes', 'content-range': `bytes */${body.byteLength}`, 'content-length': 0 }, undefined);
|
|
811
|
+
}
|
|
812
|
+
if (range !== undefined) {
|
|
813
|
+
const [start, end] = range;
|
|
814
|
+
const part = body.subarray(start, end + 1);
|
|
815
|
+
return finish(206, { 'content-type': type, 'content-length': part.byteLength, ...cc, ...encoding, ...custom, etag, ...lm, 'accept-ranges': 'bytes', 'content-range': `bytes ${start}-${end}/${body.byteLength}` }, part);
|
|
816
|
+
}
|
|
817
|
+
return finish(200, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...cc, ...custom, etag, ...lm, 'accept-ranges': 'bytes' }, body);
|
|
818
|
+
};
|
|
819
|
+
/** The file for a path: exact, `<path>.html` (clean URLs), or `<dir>/index.html` with a trailing slash. */
|
|
820
|
+
const resolve = (p, slash) => {
|
|
821
|
+
if (isFile(p) && !(slash && p !== '/'))
|
|
822
|
+
return p;
|
|
823
|
+
if (!slash && p !== '/' && isFile(`${p}.html`))
|
|
824
|
+
return `${p}.html`;
|
|
825
|
+
if (slash && tree.isDirectory(p)) {
|
|
826
|
+
const index = p === '/' ? '/index.html' : `${p}/index.html`;
|
|
827
|
+
if (isFile(index))
|
|
828
|
+
return index;
|
|
829
|
+
}
|
|
830
|
+
return undefined;
|
|
831
|
+
};
|
|
832
|
+
const ruleRequest = { search, acceptLanguage: h('accept-language'), cookie: h('cookie'), country: options.country };
|
|
833
|
+
/** Answer from `target` (an http(s) URL) under the proxy policy; a refusal or a failed fetch is a 502 that does not say why. */
|
|
834
|
+
const proxyTo = async (target, from) => {
|
|
835
|
+
note = ` → ${redactUrl(target)} (proxy, ${from})`;
|
|
836
|
+
const headers = {};
|
|
837
|
+
for (const k of PROXY_REQUEST_HEADERS) {
|
|
838
|
+
const v = h(k);
|
|
839
|
+
if (v !== undefined)
|
|
840
|
+
headers[k] = v;
|
|
841
|
+
}
|
|
842
|
+
const operator = !!options.operator;
|
|
843
|
+
const fail = (why) => {
|
|
844
|
+
const text = utf8.encode(operator ? `502 Bad Gateway: ${why}\n` : PROXY_FAILED);
|
|
845
|
+
return finish(502, { 'content-type': 'text/plain; charset=utf-8', 'content-length': text.byteLength }, text);
|
|
846
|
+
};
|
|
847
|
+
try {
|
|
848
|
+
if (options.proxy === undefined)
|
|
849
|
+
throw new Error('this handler has no proxy');
|
|
850
|
+
if (!operator) {
|
|
851
|
+
const refused = proxyRefusal(target, proxyAllow);
|
|
852
|
+
if (refused !== undefined)
|
|
853
|
+
throw new Error(refused);
|
|
854
|
+
}
|
|
855
|
+
const r = await options.proxy.fetch(target, { method: method === 'HEAD' ? 'HEAD' : 'GET', headers, redirect: 'manual' });
|
|
856
|
+
const status = r.status ?? 502;
|
|
857
|
+
// A status a Response cannot carry (1xx, outside 200-599), a body on 204/205/304, and (unless the operator's
|
|
858
|
+
// server passes them on) a redirect are the upstream's fault, not ours: a 502, not a crash.
|
|
859
|
+
if (!Number.isInteger(status) || status < 200 || status > 599)
|
|
860
|
+
throw new Error(`the upstream answered ${status}`);
|
|
861
|
+
if ([204, 205, 304].includes(status) && r.bytes.byteLength > 0)
|
|
862
|
+
throw new Error(`the upstream answered ${status} with a body`);
|
|
863
|
+
if (!operator && status >= 300 && status < 400 && status !== 304)
|
|
864
|
+
throw new Error(`the upstream redirected (${status})`);
|
|
865
|
+
const out = {};
|
|
866
|
+
for (const [n, vs] of r.headers ?? []) {
|
|
867
|
+
if (HOP_BY_HOP.has(n) || (!operator && (n === 'set-cookie' || n === 'set-cookie2')))
|
|
868
|
+
continue;
|
|
869
|
+
out[n] = vs.length === 1 ? vs[0] : [...vs];
|
|
870
|
+
}
|
|
871
|
+
const upstreamLength = r.headers?.find(([n]) => n === 'content-length')?.[1][0];
|
|
872
|
+
out['content-length'] = method === 'HEAD' && upstreamLength !== undefined ? upstreamLength : String(r.bytes.byteLength);
|
|
873
|
+
return finish(status, out, r.bytes);
|
|
874
|
+
}
|
|
875
|
+
catch (e) {
|
|
876
|
+
const why = isSitefileError(e) ? `error[${e.code}]: ${e.detail}` : `error: ${String(e)}`;
|
|
877
|
+
if (operator) {
|
|
878
|
+
note += ` ${why}`;
|
|
879
|
+
return fail(why);
|
|
880
|
+
}
|
|
881
|
+
const safe = redactText(why);
|
|
882
|
+
note += ` ${safe}`;
|
|
883
|
+
options.log?.(`error: proxy ${redactUrl(target)} (${from}): ${safe}`);
|
|
884
|
+
return fail(safe);
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
// `--proxy` routes come first: they are what this server is asked to front.
|
|
888
|
+
for (const route of options.proxy?.routes ?? []) {
|
|
889
|
+
const inside = route.prefix === '/' || vpath === route.prefix || vpath.startsWith(`${route.prefix}/`);
|
|
890
|
+
if (!inside)
|
|
891
|
+
continue;
|
|
892
|
+
const rest = (route.prefix === '/' ? vpath : vpath.slice(route.prefix.length)) + (trailingSlash && segs.length > 0 ? '/' : '');
|
|
893
|
+
const encoded = rest.split('/').map((p) => encodeURIComponent(p)).join('/');
|
|
894
|
+
return proxyTo(route.target.replace(/\/$/, '') + encoded + search, `--proxy ${route.prefix}`);
|
|
895
|
+
}
|
|
896
|
+
/** Apply the first matching `_redirects` rule (forced ones, or the others); undefined when none applies. */
|
|
897
|
+
const redirect = async (forced) => {
|
|
898
|
+
for (const r of redirects) {
|
|
899
|
+
if (r.force !== forced)
|
|
900
|
+
continue;
|
|
901
|
+
const caps = matchRule(r, vpath, ruleRequest);
|
|
902
|
+
if (caps === undefined)
|
|
903
|
+
continue;
|
|
904
|
+
const target = substituteTarget(r.to, caps);
|
|
905
|
+
if (!isRewriteStatus(r.status)) {
|
|
906
|
+
// A rule that matches query parameters passes on only what its target names.
|
|
907
|
+
const mounted = target.startsWith('/') ? mount + target : target;
|
|
908
|
+
const location = mounted.includes('?') || r.query.length > 0 ? mounted : mounted + search;
|
|
909
|
+
note = ` → ${location} (_redirects:${r.line})`;
|
|
910
|
+
return finish(r.status, { location, 'content-length': 0 }, undefined);
|
|
911
|
+
}
|
|
912
|
+
if (r.status === 200 && /^https?:\/\//i.test(target)) {
|
|
913
|
+
// A proxy rule (#172): the request's query string goes along unless the target has one.
|
|
914
|
+
return proxyTo(target.includes('?') || r.query.length > 0 ? target : target + search, `_redirects:${r.line}`);
|
|
915
|
+
}
|
|
916
|
+
// 200 (rewrite), 404, 410 and 451: serve the target path's file with that status.
|
|
917
|
+
const tq = target.indexOf('?');
|
|
918
|
+
const tpath = tq === -1 ? target : target.slice(0, tq);
|
|
919
|
+
const tsegs = safeSegments(tpath);
|
|
920
|
+
const served = tsegs ? resolve('/' + tsegs.join('/'), tpath.endsWith('/')) : undefined;
|
|
921
|
+
if (served === undefined)
|
|
922
|
+
continue;
|
|
923
|
+
note = ` → ${encodePath(served)} (_redirects:${r.line})`;
|
|
924
|
+
return sendFile(r.status, served);
|
|
925
|
+
}
|
|
926
|
+
return undefined;
|
|
927
|
+
};
|
|
928
|
+
const forcedReply = await redirect(true);
|
|
929
|
+
if (forcedReply)
|
|
930
|
+
return forcedReply;
|
|
931
|
+
const handling = profile?.htmlHandling;
|
|
932
|
+
let served;
|
|
933
|
+
if (handling !== undefined) {
|
|
934
|
+
// `--html-handling` (Cloudflare's modes): one canonical spelling per page, the others redirect to it.
|
|
935
|
+
const go = (to, slash) => {
|
|
936
|
+
const path = to.length === 0 ? '/' : '/' + to.map(encodeURIComponent).join('/') + (slash ? '/' : '');
|
|
937
|
+
return finish(profile.redirectStatus, { location: mount + path + search, 'content-length': 0 }, undefined);
|
|
938
|
+
};
|
|
939
|
+
const last = segs[segs.length - 1];
|
|
940
|
+
const index = vpath === '/' ? '/index.html' : `${vpath}/index.html`;
|
|
941
|
+
const hasIndex = isFile(index);
|
|
942
|
+
const hasHtml = segs.length > 0 && isFile(`${vpath}.html`);
|
|
943
|
+
if (!trailingSlash && last !== undefined && last.endsWith('.html') && isFile(vpath) && handling !== 'none') {
|
|
944
|
+
// `/x.html` and `/x/index.html` are spelled out: send them to the clean form.
|
|
945
|
+
const dir = segs.slice(0, -1);
|
|
946
|
+
if (last === 'index.html')
|
|
947
|
+
return go(dir, dir.length > 0 && handling !== 'drop-slash');
|
|
948
|
+
return go([...dir, last.slice(0, -'.html'.length)], handling === 'force-slash');
|
|
949
|
+
}
|
|
950
|
+
if (!trailingSlash && isFile(vpath))
|
|
951
|
+
served = vpath;
|
|
952
|
+
else if (handling === 'none')
|
|
953
|
+
served = trailingSlash && hasIndex ? index : undefined;
|
|
954
|
+
else if (segs.length === 0)
|
|
955
|
+
served = hasIndex ? index : undefined;
|
|
956
|
+
else if (handling === 'auto') {
|
|
957
|
+
if (hasIndex) {
|
|
958
|
+
if (!trailingSlash)
|
|
959
|
+
return go(segs, true);
|
|
960
|
+
served = index;
|
|
961
|
+
}
|
|
962
|
+
else if (hasHtml) {
|
|
963
|
+
if (trailingSlash)
|
|
964
|
+
return go(segs, false);
|
|
965
|
+
served = `${vpath}.html`;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
else if (hasIndex || hasHtml) {
|
|
969
|
+
const slash = handling === 'force-slash';
|
|
970
|
+
if (trailingSlash !== slash)
|
|
971
|
+
return go(segs, slash);
|
|
972
|
+
served = slash ? (hasIndex ? index : `${vpath}.html`) : hasHtml ? `${vpath}.html` : index;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
else
|
|
976
|
+
served = resolve(vpath, trailingSlash);
|
|
977
|
+
if (handling === undefined && served === undefined && !trailingSlash && tree.isDirectory(vpath)) {
|
|
978
|
+
const location = mount + '/' + segs.map(encodeURIComponent).join('/') + '/' + search;
|
|
979
|
+
return finish(301, { location, 'content-length': 0 }, undefined);
|
|
980
|
+
}
|
|
981
|
+
if (served === undefined) {
|
|
982
|
+
const reply = await redirect(false);
|
|
983
|
+
if (reply)
|
|
984
|
+
return reply;
|
|
985
|
+
}
|
|
986
|
+
// `/about/` when only `/about.html` answers: redirect to the clean URL `/about` (relative links in the
|
|
987
|
+
// page then resolve as they do at `/about`). `_redirects` rules for the path come first.
|
|
988
|
+
if (handling === undefined && profile?.slashHtml !== 'not-found' && served === undefined && trailingSlash && segs.length > 0 && isFile(`${vpath}.html`)) {
|
|
989
|
+
const location = mount + '/' + segs.map(encodeURIComponent).join('/') + search;
|
|
990
|
+
return finish(301, { location, 'content-length': 0 }, undefined);
|
|
991
|
+
}
|
|
992
|
+
if (served === undefined && options.spa && navigation() && !(options.spaExclude ?? []).some((g) => globMatch(g, vpath + (trailingSlash && segs.length > 0 ? '/' : '')))) {
|
|
993
|
+
served = spaFallback(segs, trailingSlash, isFile, options.spaFallback);
|
|
994
|
+
if (served !== undefined)
|
|
995
|
+
note = ` → ${encodePath(served)} (spa fallback)`;
|
|
996
|
+
}
|
|
997
|
+
if (served !== undefined && note === '' && served === `${vpath}.html`)
|
|
998
|
+
note = ` → ${encodePath(served)} (clean URL)`;
|
|
999
|
+
if (served !== undefined)
|
|
1000
|
+
return sendFile(200, served);
|
|
1001
|
+
// The nearest 404.html: in the request's directory, then each parent up to the root (only the
|
|
1002
|
+
// root one for a profile whose host does not look further).
|
|
1003
|
+
const dirs = trailingSlash ? segs : segs.slice(0, -1);
|
|
1004
|
+
for (let n = profile?.notFound === 'root' ? 0 : dirs.length; n >= 0; n--) {
|
|
1005
|
+
const notFound = `/${dirs.slice(0, n).map((d) => d + '/').join('')}404.html`;
|
|
1006
|
+
if (isFile(notFound)) {
|
|
1007
|
+
note = ` → ${encodePath(notFound)}`;
|
|
1008
|
+
return sendFile(404, notFound);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
// Cloudflare Pages: a site without a 404.html is taken for a single-page app.
|
|
1012
|
+
if (profile?.notFound === 'index' && isFile('/index.html')) {
|
|
1013
|
+
note = ' → /index.html (no 404.html)';
|
|
1014
|
+
return sendFile(200, '/index.html');
|
|
1015
|
+
}
|
|
1016
|
+
const misses = options.devNotFound ? nearMisses(tree, isFile, vpath, redirects, ruleRequest) : [];
|
|
1017
|
+
return page(404, misses.length === 0 ? NOT_FOUND_PAGE : nearMissPage(vpath, misses, mount), custom);
|
|
1018
|
+
};
|
|
1019
|
+
return async (req) => {
|
|
1020
|
+
try {
|
|
1021
|
+
return await respond(req);
|
|
1022
|
+
}
|
|
1023
|
+
catch (e) {
|
|
1024
|
+
// A header value the platform refuses, or a bug: one 500, never a crash.
|
|
1025
|
+
options.log?.(`error: ${e instanceof SitefileError ? e.message : String(e)}`);
|
|
1026
|
+
const bytes = utf8.encode(ERROR_PAGE);
|
|
1027
|
+
const headers = new Headers({ ...base, 'content-type': 'text/html; charset=utf-8', 'content-length': String(bytes.byteLength) });
|
|
1028
|
+
return { response: new Response(req.method === 'HEAD' ? null : bytes, { status: 500, headers }), note: '', bytes: req.method === 'HEAD' ? 0 : bytes.byteLength };
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* The site handler as a `(Request) => Promise<Response>`, for Deno, Bun, edge runtimes, service workers
|
|
1034
|
+
* and tests: `createSiteHandler(tree, { spa: true })(new Request('https://site.test/about'))`. The tree is
|
|
1035
|
+
* a {@link SiteTree} (or a function returning one, read per request). The response body of a large file
|
|
1036
|
+
* or a range is a stream of views of the tree's bytes, never a copy of the whole.
|
|
1037
|
+
*
|
|
1038
|
+
* The request URL's path is the target. The platform has already normalized it (`..` segments are
|
|
1039
|
+
* resolved, `\` becomes `/`), so path traversal cannot get past a `Request`; a raw target that would be
|
|
1040
|
+
* refused (`400`) can only reach {@link createSiteResponder}. The origin that `rewriteBase` writes is the URL's
|
|
1041
|
+
* (scheme included). The `Host` header is only read with `allowedHosts`: then it is checked (any other host gets
|
|
1042
|
+
* `403`) and is the host that is written.
|
|
1043
|
+
*/
|
|
1044
|
+
export function createSiteHandler(site, options = {}) {
|
|
1045
|
+
const respond = createSiteResponder(site, options);
|
|
1046
|
+
return async (request) => {
|
|
1047
|
+
const u = new URL(request.url);
|
|
1048
|
+
// An http(s) URL carries its origin along as an absolute-form target; anything else has only a path.
|
|
1049
|
+
const target = u.protocol === 'http:' || u.protocol === 'https:' ? `${u.protocol}//${u.host}${u.pathname}${u.search}` : u.pathname + u.search;
|
|
1050
|
+
return (await respond({ method: request.method, target, headers: request.headers })).response;
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
/** A URL rendered without any userinfo, safe for logs and error messages. */
|
|
1054
|
+
function redactUrl(url) {
|
|
1055
|
+
try {
|
|
1056
|
+
const u = new URL(url);
|
|
1057
|
+
u.username = '';
|
|
1058
|
+
u.password = '';
|
|
1059
|
+
return u.href;
|
|
1060
|
+
}
|
|
1061
|
+
catch {
|
|
1062
|
+
return '<invalid url>';
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
//# sourceMappingURL=site-core.js.map
|