@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
package/lib/src/servers.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { SiteContent } from './server.js';
|
|
|
2
2
|
import { type ArchiveLimits } from './resources/types.js';
|
|
3
3
|
import { Store } from './store.js';
|
|
4
4
|
import { Tree } from './tree.js';
|
|
5
|
+
import { type BucketReadCache } from './bucket.js';
|
|
5
6
|
import type { CachePreview } from './server.js';
|
|
6
7
|
import type { AuthEntry } from './serve-auth.js';
|
|
7
8
|
/**
|
|
@@ -46,6 +47,13 @@ export interface ServerState {
|
|
|
46
47
|
| {
|
|
47
48
|
readonly kind: 'archive';
|
|
48
49
|
readonly path: string;
|
|
50
|
+
}
|
|
51
|
+
/** A bucket of the store (and a directory of it), read by name; the server follows its changes. */
|
|
52
|
+
| {
|
|
53
|
+
readonly kind: 'bucket';
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly prefix?: string; /** `--max-bytes`: most bytes held in memory (absent: the default). */
|
|
56
|
+
readonly maxBytes?: number;
|
|
49
57
|
};
|
|
50
58
|
readonly spa: boolean;
|
|
51
59
|
/** `--spa-exclude`: request paths that never fall back (absent: none). */
|
|
@@ -167,6 +175,8 @@ export interface ServedTreeOptions {
|
|
|
167
175
|
readonly keepOsMetadata?: boolean;
|
|
168
176
|
/** Told how many OS metadata files were skipped. */
|
|
169
177
|
readonly warn?: (message: string) => void;
|
|
178
|
+
/** A bucket server's files read so far: a reload reads only the files that changed and shares the rest. */
|
|
179
|
+
readonly bucketCache?: BucketReadCache;
|
|
170
180
|
}
|
|
171
181
|
/**
|
|
172
182
|
* Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
|
|
@@ -216,3 +226,18 @@ export declare function checkSiteFiles(tree: Tree, strict: boolean, warn: (m: st
|
|
|
216
226
|
* archive, the file's modification time. Undefined when there is none.
|
|
217
227
|
*/
|
|
218
228
|
export declare function servedLastModified(store: Store, source: ServerState['source']): Promise<number | undefined>;
|
|
229
|
+
/**
|
|
230
|
+
* Wait for a started worker to record that it listens (`ready`) or that it failed (`error`), until `hasExited`
|
|
231
|
+
* says its process is gone or the time is up. `read` reads the server's record, `kill` stops a worker that is
|
|
232
|
+
* still running when we give up. Resolves with the ready record; rejects with the worker's own error.
|
|
233
|
+
*
|
|
234
|
+
* The worker writes its `error` to the record and then exits, so the order of the two looks matters
|
|
235
|
+
* (johnhenry/sitefile#331): whether it has exited is sampled first, and a record read after that is final.
|
|
236
|
+
* Reading first and sampling afterwards could see the record before the error was written and the exit after
|
|
237
|
+
* it, and then report "exited before it was ready" instead of the worker's reason. Twin: `await_ready` in
|
|
238
|
+
* rust/src/servers.rs.
|
|
239
|
+
*/
|
|
240
|
+
export declare function awaitReady(read: () => Promise<ServerState | undefined>, hasExited: () => boolean, kill: () => void, options?: {
|
|
241
|
+
readonly timeoutMs?: number;
|
|
242
|
+
readonly pollMs?: number;
|
|
243
|
+
}): Promise<ServerState>;
|
package/lib/src/servers.js
CHANGED
|
@@ -7,12 +7,13 @@ import path from 'node:path';
|
|
|
7
7
|
import { sha256 } from './digest.js';
|
|
8
8
|
import { SitefileError } from './errors.js';
|
|
9
9
|
import { siteFileWarnings } from './serve-rules.js';
|
|
10
|
-
import { blobPathOf, decodeIndex, extractImageFiles, MEDIA, parseConfig, parseManifest, siteLayerIndices } from './oci.js';
|
|
10
|
+
import { blobPathOf, decodeIndex, extractImageFiles, MEDIA, parseConfig, parseIndex, parseManifest, siteLayerIndices } from './oci.js';
|
|
11
11
|
import { extractArchive, openZipFile, osMetadataWarning, withoutOsMetadata } from './resources/archive.js';
|
|
12
12
|
import { LocalContext } from './resources/local.js';
|
|
13
13
|
import { DEFAULT_ARCHIVE_LIMITS } from './resources/types.js';
|
|
14
14
|
import { Store } from './store.js';
|
|
15
15
|
import { Tree } from './tree.js';
|
|
16
|
+
import { bucketLabel, Buckets, scanDirectory } from './bucket.js';
|
|
16
17
|
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
|
|
17
18
|
export class ServerRegistry {
|
|
18
19
|
store;
|
|
@@ -254,7 +255,20 @@ async function ociArchiveTree(layout, origin, limits) {
|
|
|
254
255
|
const first = entries[0];
|
|
255
256
|
if (!first)
|
|
256
257
|
throw bad('OCI archive holds no image');
|
|
257
|
-
|
|
258
|
+
let manifestBytes = blob(first.digest, first.size);
|
|
259
|
+
// A multi-platform image: the files are the same in every platform's manifest, so the first one is read.
|
|
260
|
+
if (first.mediaType === MEDIA.index) {
|
|
261
|
+
let child;
|
|
262
|
+
try {
|
|
263
|
+
child = parseIndex(manifestBytes).manifests[0];
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
throw bad("OCI archive's image index is corrupt");
|
|
267
|
+
}
|
|
268
|
+
if (!child)
|
|
269
|
+
throw bad("OCI archive's image index lists no platform");
|
|
270
|
+
manifestBytes = blob(child.digest, child.size);
|
|
271
|
+
}
|
|
258
272
|
let m;
|
|
259
273
|
try {
|
|
260
274
|
m = parseManifest(manifestBytes);
|
|
@@ -292,6 +306,11 @@ export async function loadServedTree(store, source, options = {}) {
|
|
|
292
306
|
return loadDirectoryTree(source.path, options);
|
|
293
307
|
case 'archive':
|
|
294
308
|
return loadArchiveTree(source.path, DEFAULT_ARCHIVE_LIMITS, options);
|
|
309
|
+
case 'bucket':
|
|
310
|
+
return served(await Buckets.open(store).loadTree(source.name, source.prefix === undefined ? [] : source.prefix.split('/'), {
|
|
311
|
+
...(options.bucketCache ? { cache: options.bucketCache } : {}),
|
|
312
|
+
...(source.maxBytes !== undefined ? { maxBytes: source.maxBytes } : {}),
|
|
313
|
+
}), bucketLabel(source.name, source.prefix), options);
|
|
295
314
|
}
|
|
296
315
|
}
|
|
297
316
|
/**
|
|
@@ -342,6 +361,47 @@ export async function servedLastModified(store, source) {
|
|
|
342
361
|
await walk(source.path);
|
|
343
362
|
return newest;
|
|
344
363
|
}
|
|
364
|
+
case 'bucket': {
|
|
365
|
+
const b = Buckets.open(store);
|
|
366
|
+
const prefix = source.prefix === undefined ? [] : source.prefix.split('/');
|
|
367
|
+
const dir = await b.resolveDirectory(source.name, prefix).catch(() => undefined);
|
|
368
|
+
if (dir === undefined)
|
|
369
|
+
return undefined;
|
|
370
|
+
let newest;
|
|
371
|
+
for (const f of await scanDirectory(dir, source.name, prefix).catch(() => [])) {
|
|
372
|
+
if (f.path.split('/').some((seg) => seg.startsWith('.') && seg !== '.well-known'))
|
|
373
|
+
continue;
|
|
374
|
+
newest = Math.max(newest ?? 0, secs(f.st.mtimeMs));
|
|
375
|
+
}
|
|
376
|
+
return newest;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Wait for a started worker to record that it listens (`ready`) or that it failed (`error`), until `hasExited`
|
|
382
|
+
* says its process is gone or the time is up. `read` reads the server's record, `kill` stops a worker that is
|
|
383
|
+
* still running when we give up. Resolves with the ready record; rejects with the worker's own error.
|
|
384
|
+
*
|
|
385
|
+
* The worker writes its `error` to the record and then exits, so the order of the two looks matters
|
|
386
|
+
* (johnhenry/sitefile#331): whether it has exited is sampled first, and a record read after that is final.
|
|
387
|
+
* Reading first and sampling afterwards could see the record before the error was written and the exit after
|
|
388
|
+
* it, and then report "exited before it was ready" instead of the worker's reason. Twin: `await_ready` in
|
|
389
|
+
* rust/src/servers.rs.
|
|
390
|
+
*/
|
|
391
|
+
export async function awaitReady(read, hasExited, kill, options = {}) {
|
|
392
|
+
const deadline = Date.now() + (options.timeoutMs ?? 15_000);
|
|
393
|
+
for (;;) {
|
|
394
|
+
const gone = hasExited();
|
|
395
|
+
const cur = await read();
|
|
396
|
+
if (cur?.ready)
|
|
397
|
+
return cur;
|
|
398
|
+
if (gone || cur?.error || Date.now() > deadline) {
|
|
399
|
+
if (!gone)
|
|
400
|
+
kill();
|
|
401
|
+
const why = cur?.error ?? (gone ? 'the server process exited before it was ready' : 'timed out waiting for the server to start');
|
|
402
|
+
throw new SitefileError('E_SERVER', why.replace(/^error\[E_SERVER\]: /, ''));
|
|
403
|
+
}
|
|
404
|
+
await new Promise((r) => setTimeout(r, options.pollMs ?? 40));
|
|
345
405
|
}
|
|
346
406
|
}
|
|
347
407
|
//# sourceMappingURL=servers.js.map
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { originForm, safeSegments } from './request-path.js';
|
|
2
|
+
import { type RedirectRequest, type ServeRedirect } from './serve-rules.js';
|
|
3
|
+
export { originForm, safeSegments };
|
|
4
|
+
/** A file of a served tree: its bytes and `sha256:<hex>` digest (what an ETag is made of). */
|
|
5
|
+
export interface SiteFile {
|
|
6
|
+
readonly bytes: Uint8Array;
|
|
7
|
+
readonly digest: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* What the handler needs of a tree: exact-path lookups on normalized virtual paths (`/a/b.html`).
|
|
11
|
+
* `Tree` (src/tree.ts) satisfies it; so can a map over browser storage. Paths are NFC, case-sensitive
|
|
12
|
+
* and absolute; `isDirectory('/')` is true.
|
|
13
|
+
*/
|
|
14
|
+
export interface SiteTree {
|
|
15
|
+
get(path: string): SiteFile | undefined;
|
|
16
|
+
isFile(path: string): boolean;
|
|
17
|
+
isDirectory(path: string): boolean;
|
|
18
|
+
/** Every file, only read to list near misses on a development 404 (`devNotFound`). */
|
|
19
|
+
entries(): Iterable<readonly [string, SiteFile]>;
|
|
20
|
+
}
|
|
21
|
+
/** Contents read on demand ({@link SiteHandlerOptions.content}). */
|
|
22
|
+
export interface SiteContent {
|
|
23
|
+
read(path: string): Uint8Array | undefined;
|
|
24
|
+
deflated?(path: string): {
|
|
25
|
+
readonly deflate: Uint8Array;
|
|
26
|
+
readonly crc: number;
|
|
27
|
+
readonly size: number;
|
|
28
|
+
} | undefined;
|
|
29
|
+
}
|
|
30
|
+
/** What a proxied request got: the status, response headers (lowercase names, values in order) and body. */
|
|
31
|
+
export interface SiteProxyResponse {
|
|
32
|
+
readonly status?: number;
|
|
33
|
+
readonly headers?: ReadonlyArray<readonly [string, readonly string[]]>;
|
|
34
|
+
readonly bytes: Uint8Array;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Proxying (#172). The handler decides which requests are proxied (`routes`, and `_redirects` rules with
|
|
38
|
+
* status 200 to an http(s) URL) and applies a policy to every target BEFORE `fetch` is called; `fetch` does
|
|
39
|
+
* the request and may throw (a failed fetch becomes a `502` with a fixed message, never its error text).
|
|
40
|
+
* Without `proxy` every proxy rule is a `502`.
|
|
41
|
+
*
|
|
42
|
+
* The policy, by the target's literal host only (the handler cannot resolve names): `https:` only, no
|
|
43
|
+
* credentials in the URL, and no loopback, link-local, private, multicast, reserved or documentation address
|
|
44
|
+
* and no host name that is local by its form (`localhost`, `*.localhost`, `*.local`, `*.internal`, a name with
|
|
45
|
+
* no dot). {@link allow} widens it for the hosts it names, and the host of each `routes` target is allowed by
|
|
46
|
+
* being written. A name can still resolve to a non-public address, and an upstream can redirect: the `fetch` you
|
|
47
|
+
* supply must refuse non-public resolved addresses and must not follow redirects (it is called with
|
|
48
|
+
* `redirect: 'manual'`, and a `3xx` answer is treated as an upstream error). The request it gets carries only
|
|
49
|
+
* `accept`, `accept-language`, `if-none-match`, `if-modified-since` and `range`: never `cookie`,
|
|
50
|
+
* `authorization` or `host`.
|
|
51
|
+
*/
|
|
52
|
+
export interface SiteProxy {
|
|
53
|
+
/** `--proxy /prefix=https://host/path`: requests under `prefix` go to `target` + the rest of the path. */
|
|
54
|
+
readonly routes?: ReadonlyArray<{
|
|
55
|
+
readonly prefix: string;
|
|
56
|
+
readonly target: string;
|
|
57
|
+
}>;
|
|
58
|
+
/**
|
|
59
|
+
* Hosts the policy lets through whatever their scheme or address (`api.internal.example`, `localhost`, or
|
|
60
|
+
* `.example.com` for the name and every subdomain; host names only, no port). Absent: none.
|
|
61
|
+
*/
|
|
62
|
+
readonly allow?: readonly string[];
|
|
63
|
+
fetch(target: string, request: {
|
|
64
|
+
readonly method: 'GET' | 'HEAD';
|
|
65
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
66
|
+
readonly redirect: 'manual';
|
|
67
|
+
}): Promise<SiteProxyResponse>;
|
|
68
|
+
}
|
|
69
|
+
/** Options of the site handler: everything that changes what a request is answered with. */
|
|
70
|
+
export interface SiteHandlerOptions {
|
|
71
|
+
/**
|
|
72
|
+
* Single-page apps: answer a page navigation ({@link isNavigation}) for a path nothing else answers
|
|
73
|
+
* with the nearest app shell ({@link spaFallback}). Never for subresources (scripts, images, `fetch()`).
|
|
74
|
+
*/
|
|
75
|
+
readonly spa?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Proxy rules (`_redirects` status 200 to a URL) and `--proxy` routes, under the policy of {@link SiteProxy};
|
|
78
|
+
* without this every proxy rule is a `502`.
|
|
79
|
+
*/
|
|
80
|
+
readonly proxy?: SiteProxy;
|
|
81
|
+
/** `--spa-exclude`: request paths (`*` matches any characters) that never fall back. */
|
|
82
|
+
readonly spaExclude?: readonly string[];
|
|
83
|
+
/** `--spa-fallback`: the one file every fallback serves, instead of the nearest `200.html` or `index.html`. */
|
|
84
|
+
readonly spaFallback?: string;
|
|
85
|
+
/** Sent as `x-sitefile-server` so `servers` can tell its own servers from a reused port. */
|
|
86
|
+
readonly serverId?: string;
|
|
87
|
+
/**
|
|
88
|
+
* When the served files last changed (Unix seconds), read per request: sent as `Last-Modified` on
|
|
89
|
+
* file responses, and `If-Modified-Since` (without `If-None-Match`) gives `304`. Unset: neither.
|
|
90
|
+
*/
|
|
91
|
+
readonly lastModified?: () => number | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* `--base /repo/`: serve the site under this path prefix (a GitHub Pages project site); `/`
|
|
94
|
+
* redirects to it, `/repo` gets its slash, everything else is 404. The handler normalizes it itself
|
|
95
|
+
* (`repo`, `/repo` and `/repo/` are the same; a URL's path is taken) and THROWS when it cannot: it never
|
|
96
|
+
* serves the whole site at `/` for a prefix it did not understand. A function is read per request and
|
|
97
|
+
* checked once when the handler is created; a value it returns later that cannot be normalized answers `500`.
|
|
98
|
+
*/
|
|
99
|
+
readonly base?: string | (() => string | undefined);
|
|
100
|
+
/**
|
|
101
|
+
* `--rewrite-base`: the production URL (`https://example.com/blog`, normalized like `--rewrite-base`; THROWS
|
|
102
|
+
* when it is not an http(s) URL with a host) that HTML, CSS and XML responses have replaced by the request's
|
|
103
|
+
* origin and `--base`, so absolute self-links stay local. The origin is the request URL's, or (only with
|
|
104
|
+
* {@link allowedHosts}) the `Host` header's.
|
|
105
|
+
*/
|
|
106
|
+
readonly rewriteBase?: string | (() => string | undefined);
|
|
107
|
+
/**
|
|
108
|
+
* Host names a request may name in its `Host` header: `localhost`, `*.localhost` and IP addresses always; any other
|
|
109
|
+
* name must equal an entry, or end with an entry that starts with `.`. `*` allows every name. Any other host
|
|
110
|
+
* gets the `403` page. When set, the `Host` header is also the origin written by {@link rewriteBase}
|
|
111
|
+
* (its scheme is the request URL's). When unset the `Host` header is neither checked nor used: the origin is the
|
|
112
|
+
* request URL's.
|
|
113
|
+
*/
|
|
114
|
+
readonly allowedHosts?: readonly string[];
|
|
115
|
+
/** `--host-profile` / `--html-handling`: behave like a static host ({@link hostProfile}). Absent: sitefile's own rules. */
|
|
116
|
+
readonly profile?: RoutingProfile;
|
|
117
|
+
/** `--random-route`: {@link base} is a secret, so `/` is a plain `404` instead of a redirect into it. */
|
|
118
|
+
readonly hideBase?: boolean;
|
|
119
|
+
/** A 404 with no `404.html` to answer it lists near misses ({@link nearMisses}). Development servers only. */
|
|
120
|
+
readonly devNotFound?: boolean;
|
|
121
|
+
/** `--country`: what `_redirects` `Country=` conditions match (there is no geolocation locally). */
|
|
122
|
+
readonly country?: string;
|
|
123
|
+
/** `--cors`: `Access-Control-Allow-Origin: *` on every response (`_headers` still wins) and `OPTIONS` preflights answered with `204`. */
|
|
124
|
+
readonly cors?: boolean;
|
|
125
|
+
/**
|
|
126
|
+
* `--isolate`: cross-origin isolation (SharedArrayBuffer, wasm threads) on every response:
|
|
127
|
+
* `Cross-Origin-Opener-Policy: same-origin`, this `Cross-Origin-Embedder-Policy` and
|
|
128
|
+
* `Cross-Origin-Resource-Policy: same-origin`. `_headers` still wins.
|
|
129
|
+
*/
|
|
130
|
+
readonly isolate?: 'require-corp' | 'credentialless';
|
|
131
|
+
/** `--max-age`, `--immutable`, `--max-age-html`: a production `Cache-Control` preview for files ({@link cacheControlFor}). */
|
|
132
|
+
readonly cache?: CachePreview;
|
|
133
|
+
/** `X-Robots-Tag: noindex` on every response. */
|
|
134
|
+
readonly noindex?: boolean;
|
|
135
|
+
/** `--compress`: gzip compressible files of at least 1024 bytes on the fly when no precompressed variant exists. */
|
|
136
|
+
readonly compress?: boolean;
|
|
137
|
+
/** `--mime`, `--mime-file`: content types by lowercase extension, checked before the built-in table. */
|
|
138
|
+
readonly mime?: ReadonlyMap<string, string>;
|
|
139
|
+
/**
|
|
140
|
+
* Where file contents come from when the tree holds only digests (a zip served in place):
|
|
141
|
+
* `read` returns a file's bytes (undefined: use the node's), `deflated` a deflated file's raw
|
|
142
|
+
* deflate stream, sent as `content-encoding: gzip` to clients that accept it.
|
|
143
|
+
*/
|
|
144
|
+
readonly content?: SiteContent;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* What only the adapters set (`src/server.ts`, the tests): hooks and switches that are not part of the public
|
|
148
|
+
* options ({@link SiteHandlerOptions}), which `src/site-handler.ts` strips from what an embedder passes.
|
|
149
|
+
*/
|
|
150
|
+
export interface SiteCoreOptions extends SiteHandlerOptions {
|
|
151
|
+
/**
|
|
152
|
+
* Add {@link RELOAD_SCRIPT} to HTML navigations (`serve --watch`). The event stream and the client script
|
|
153
|
+
* themselves are endpoints of the Node adapter, not of the handler. Never set otherwise, never in exports.
|
|
154
|
+
*/
|
|
155
|
+
readonly injectReload?: boolean;
|
|
156
|
+
/** Problems a person should know about (without the `warning: ` prefix), e.g. a CSP that blocks live reload. */
|
|
157
|
+
readonly warn?: (message: string) => void;
|
|
158
|
+
/** Lines for the operator (`error: ...`), e.g. a file whose contents could not be read, or why a proxy request failed. */
|
|
159
|
+
readonly log?: (line: string) => void;
|
|
160
|
+
/**
|
|
161
|
+
* The command-line server: its `proxy.fetch` enforces the whole fetch policy itself (so the handler's is not
|
|
162
|
+
* applied, and its refusals name the flag to add in the `502` body), an upstream redirect is passed on, and the
|
|
163
|
+
* origin written by `rewriteBase` is `http://` + the `Host` header whatever the scheme.
|
|
164
|
+
*/
|
|
165
|
+
readonly operator?: boolean;
|
|
166
|
+
}
|
|
167
|
+
/** A request as the handler takes it: what the serve rules read, with the target as received. */
|
|
168
|
+
export interface SiteRequest {
|
|
169
|
+
/** `GET`, `HEAD` or `OPTIONS` (CORS) are answered; any other method gets `405`. */
|
|
170
|
+
readonly method: string;
|
|
171
|
+
/**
|
|
172
|
+
* The request target as received: `/path?query`, or an absolute-form `https://host/path?query`, whose scheme and
|
|
173
|
+
* host are then the origin that {@link SiteHandlerOptions.rewriteBase} writes.
|
|
174
|
+
*/
|
|
175
|
+
readonly target: string;
|
|
176
|
+
readonly headers: Headers;
|
|
177
|
+
}
|
|
178
|
+
/** The answer to one request, with what an access log wants to know about it. */
|
|
179
|
+
export interface SiteReply {
|
|
180
|
+
readonly response: Response;
|
|
181
|
+
/** Body bytes the response carries (0 for HEAD, `304` and redirects). */
|
|
182
|
+
readonly bytes: number;
|
|
183
|
+
}
|
|
184
|
+
/** What the adapters get: the reply, and what answered for the access log (` → /new (_redirects:3)`), else `''`. */
|
|
185
|
+
export interface SiteCoreReply extends SiteReply {
|
|
186
|
+
readonly note: string;
|
|
187
|
+
}
|
|
188
|
+
/** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
|
|
189
|
+
export declare function gzipMember(deflate: Uint8Array, crc: number, size: number): Uint8Array;
|
|
190
|
+
/** `html` with {@link RELOAD_SCRIPT} inserted before the last `</body` (ASCII case-insensitive), else appended. */
|
|
191
|
+
export declare function injectReloadScript(html: Uint8Array): Uint8Array;
|
|
192
|
+
/**
|
|
193
|
+
* `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
|
|
194
|
+
* the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
|
|
195
|
+
* so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
|
|
196
|
+
*/
|
|
197
|
+
export declare function rewriteBaseUrls(body: Uint8Array, from: string, to: string): Uint8Array;
|
|
198
|
+
/** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
|
|
199
|
+
export declare function acceptsGzip(header: string | undefined): boolean;
|
|
200
|
+
/** Reserved for the live-reload event stream while `serve --watch` runs. */
|
|
201
|
+
export declare const RELOAD_PATH = "/__sitefile/reload";
|
|
202
|
+
/** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
|
|
203
|
+
export declare const RELOAD_SCRIPT_PATH = "/__sitefile/reload.js";
|
|
204
|
+
/** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
|
|
205
|
+
export declare const RELOAD_SCRIPT = "<script src=\"/__sitefile/reload.js\"></script>";
|
|
206
|
+
/**
|
|
207
|
+
* Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
|
|
208
|
+
* when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
|
|
209
|
+
* `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
|
|
210
|
+
*/
|
|
211
|
+
export declare function isNavigation(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
|
|
212
|
+
/**
|
|
213
|
+
* The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
|
|
214
|
+
* a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
|
|
215
|
+
* undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
|
|
216
|
+
* `https:` count as allowing the server's own origin (host sources are not matched), and
|
|
217
|
+
* `'strict-dynamic'` makes `'self'` ignored for scripts.
|
|
218
|
+
*/
|
|
219
|
+
export declare function cspBlocksReload(value: string): 'script-src' | 'connect-src' | undefined;
|
|
220
|
+
export declare const NOT_FOUND_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>404 Not Found</title><h1>404 Not Found</h1>\n";
|
|
221
|
+
export declare const BAD_REQUEST_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>400 Bad Request</title><h1>400 Bad Request</h1>\n";
|
|
222
|
+
export declare const FORBIDDEN_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>403 Forbidden</title><h1>403 Forbidden</h1>\n";
|
|
223
|
+
export declare const UNAUTHORIZED_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>401 Unauthorized</title><h1>401 Unauthorized</h1>\n";
|
|
224
|
+
export declare 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";
|
|
225
|
+
export declare const ERROR_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>500 Internal Server Error</title><h1>500 Internal Server Error</h1>\n";
|
|
226
|
+
export declare const METHOD_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>405 Method Not Allowed</title><h1>405 Method Not Allowed</h1>\n";
|
|
227
|
+
/**
|
|
228
|
+
* Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
|
|
229
|
+
* case-insensitive; an explicit entry wins over `*`.
|
|
230
|
+
*/
|
|
231
|
+
export declare function acceptsEncoding(header: string | undefined, coding: string): boolean;
|
|
232
|
+
/** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
|
|
233
|
+
export declare function isCompressible(type: string): boolean;
|
|
234
|
+
/** Production cache headers to preview instead of `no-cache` (`serve --max-age`). */
|
|
235
|
+
export interface CachePreview {
|
|
236
|
+
/** Seconds for files other than HTML: `public, max-age=N`. */
|
|
237
|
+
readonly maxAge?: number;
|
|
238
|
+
/** Adds `immutable` to the non-HTML value (needs {@link maxAge}). */
|
|
239
|
+
readonly immutable?: boolean;
|
|
240
|
+
/** Seconds for HTML pages (absent: they keep `no-cache`, the common production practice). */
|
|
241
|
+
readonly maxAgeHtml?: number;
|
|
242
|
+
}
|
|
243
|
+
/** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
|
|
244
|
+
export declare function cacheControlFor(type: string, cache: CachePreview | undefined): string | undefined;
|
|
245
|
+
/**
|
|
246
|
+
* The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
|
|
247
|
+
* section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
|
|
248
|
+
* `/` for an empty path); any other target is returned as it is. The authority is not checked.
|
|
249
|
+
*/
|
|
250
|
+
/** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
|
|
251
|
+
export declare function preflightHeaders(value: string | undefined): string | undefined;
|
|
252
|
+
/** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
|
|
253
|
+
export declare function httpDate(secs: number): string;
|
|
254
|
+
/** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
|
|
255
|
+
export declare function parseHttpDate(value: string): number | undefined;
|
|
256
|
+
/**
|
|
257
|
+
* The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
|
|
258
|
+
* `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
|
|
259
|
+
* asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
|
|
260
|
+
*/
|
|
261
|
+
export declare function byteRange(header: string | undefined, size: number): [number, number] | 'unsatisfiable' | undefined;
|
|
262
|
+
/**
|
|
263
|
+
* The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
|
|
264
|
+
* else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
|
|
265
|
+
* has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
|
|
266
|
+
*/
|
|
267
|
+
export declare function spaFallback(segs: readonly string[], trailingSlash: boolean, isFile: (p: string) => boolean, fallback?: string): string | undefined;
|
|
268
|
+
/** `--html-handling` (Cloudflare's names): `auto`, `force-slash`, `drop-slash` or `none`. */
|
|
269
|
+
export type HtmlHandling = 'auto' | 'force-slash' | 'drop-slash' | 'none';
|
|
270
|
+
export declare const HTML_HANDLINGS: readonly HtmlHandling[];
|
|
271
|
+
export declare const HOST_PROFILES: readonly ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
|
|
272
|
+
export type HostProfileName = (typeof HOST_PROFILES)[number];
|
|
273
|
+
/** How a server routes like a static host (`--host-profile`, `--html-handling`). */
|
|
274
|
+
export interface RoutingProfile {
|
|
275
|
+
/** Canonical page URLs; undefined keeps sitefile's own rules (clean URLs plus both spellings). */
|
|
276
|
+
readonly htmlHandling?: HtmlHandling;
|
|
277
|
+
/** The status of a canonicalizing redirect. */
|
|
278
|
+
readonly redirectStatus: number;
|
|
279
|
+
/** Whether `/_redirects` and `/_headers` are read (and hidden). */
|
|
280
|
+
readonly siteFiles: boolean;
|
|
281
|
+
/** Which 404.html answers a miss: the nearest, only the root one, or (no 404.html) `/index.html` with 200. */
|
|
282
|
+
readonly notFound: 'nearest' | 'root' | 'index';
|
|
283
|
+
/** Sitefile's own rules only: `/about/` with only `about.html` redirects to `/about`, or is 404. */
|
|
284
|
+
readonly slashHtml: 'redirect' | 'not-found';
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
|
|
288
|
+
* undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
|
|
289
|
+
*
|
|
290
|
+
* | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
|
|
291
|
+
* | netlify | auto | 301 | yes | nearest 404.html |
|
|
292
|
+
* | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
|
|
293
|
+
* | vercel | none | 308 | no | /404.html |
|
|
294
|
+
* | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
|
|
295
|
+
* | firebase | none | 301 | no | /404.html |
|
|
296
|
+
*/
|
|
297
|
+
export declare function hostProfile(name: HostProfileName | undefined, htmlHandling?: HtmlHandling): RoutingProfile;
|
|
298
|
+
/** The server's routing profile for the flags (undefined: sitefile's own rules). */
|
|
299
|
+
export declare function routingFor(o: {
|
|
300
|
+
hostProfile?: HostProfileName | undefined;
|
|
301
|
+
htmlHandling?: HtmlHandling | undefined;
|
|
302
|
+
}): RoutingProfile | undefined;
|
|
303
|
+
/** A near miss for a 404: a file (`path`) or a `_redirects` rule (`line`), and why. */
|
|
304
|
+
export interface NearMiss {
|
|
305
|
+
readonly path?: string;
|
|
306
|
+
readonly line?: number;
|
|
307
|
+
readonly why: string;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
|
|
311
|
+
* from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
|
|
312
|
+
* host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
|
|
313
|
+
* conditions do not, in file order.
|
|
314
|
+
*/
|
|
315
|
+
export declare function nearMisses(tree: SiteTree, isFile: (p: string) => boolean, vpath: string, redirects: readonly ServeRedirect[], req: RedirectRequest): NearMiss[];
|
|
316
|
+
/** The development 404 page listing near misses. */
|
|
317
|
+
export declare function nearMissPage(vpath: string, misses: readonly NearMiss[], mount?: string): string;
|
|
318
|
+
/**
|
|
319
|
+
* The DNS-rebinding guard of {@link SiteHandlerOptions.allowedHosts}: whether a `Host` header value
|
|
320
|
+
* may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
|
|
321
|
+
* attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
|
|
322
|
+
* port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
|
|
323
|
+
* it without the dot).
|
|
324
|
+
*/
|
|
325
|
+
export declare function hostAllowed(allowed: readonly string[] | undefined, host: string | undefined): boolean;
|
|
326
|
+
/** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
|
|
327
|
+
export declare function parseAllowedHost(value: string): string | undefined;
|
|
328
|
+
/** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
|
|
329
|
+
export declare function isRebasedType(type: string): boolean;
|
|
330
|
+
/**
|
|
331
|
+
* A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
|
|
332
|
+
* fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
|
|
333
|
+
* http(s) URL with a host.
|
|
334
|
+
*/
|
|
335
|
+
export declare function normalizeProductionUrl(raw: string): string | undefined;
|
|
336
|
+
/**
|
|
337
|
+
* A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
|
|
338
|
+
* safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
|
|
339
|
+
*/
|
|
340
|
+
export declare function normalizeBase(raw: string): string | undefined;
|
|
341
|
+
/** The headers every response of a handler with these options carries (before the response's own). */
|
|
342
|
+
export declare function siteBaseHeaders(options?: Pick<SiteHandlerOptions, 'serverId' | 'cors' | 'noindex' | 'isolate'>): Record<string, string>;
|
|
343
|
+
/**
|
|
344
|
+
* The site handler for an immutable tree: a function from a request (method, target, headers) to a
|
|
345
|
+
* {@link SiteReply}. GET and HEAD only (and `OPTIONS` with `cors`); nothing outside the tree is ever
|
|
346
|
+
* reachable because lookups are exact map keys built from validated segments. Honours `/404.html`,
|
|
347
|
+
* `/_redirects` and `/_headers` (which it never serves), answers `/about` with `/about.html` when
|
|
348
|
+
* there is no such file or directory, and redirects `/about/` to `/about` when only `/about.html`
|
|
349
|
+
* answers it. `site` may be a function: it is read per request (`serve --watch` swaps in each good rebuild).
|
|
350
|
+
*
|
|
351
|
+
* This is the low-level form the Node adapter uses, because it takes the request target exactly as
|
|
352
|
+
* received (a `Request` URL is already normalized by the platform, so `/a/../b` never reaches a handler).
|
|
353
|
+
* Use {@link createSiteHandler} anywhere a `Request` is what you have.
|
|
354
|
+
*/
|
|
355
|
+
export declare function createSiteResponder(site: SiteTree | (() => SiteTree), options?: SiteCoreOptions): (request: SiteRequest) => Promise<SiteCoreReply>;
|
|
356
|
+
/**
|
|
357
|
+
* The site handler as a `(Request) => Promise<Response>`, for Deno, Bun, edge runtimes, service workers
|
|
358
|
+
* and tests: `createSiteHandler(tree, { spa: true })(new Request('https://site.test/about'))`. The tree is
|
|
359
|
+
* a {@link SiteTree} (or a function returning one, read per request). The response body of a large file
|
|
360
|
+
* or a range is a stream of views of the tree's bytes, never a copy of the whole.
|
|
361
|
+
*
|
|
362
|
+
* The request URL's path is the target. The platform has already normalized it (`..` segments are
|
|
363
|
+
* resolved, `\` becomes `/`), so path traversal cannot get past a `Request`; a raw target that would be
|
|
364
|
+
* refused (`400`) can only reach {@link createSiteResponder}. The origin that `rewriteBase` writes is the URL's
|
|
365
|
+
* (scheme included). The `Host` header is only read with `allowedHosts`: then it is checked (any other host gets
|
|
366
|
+
* `403`) and is the host that is written.
|
|
367
|
+
*/
|
|
368
|
+
export declare function createSiteHandler(site: SiteTree | (() => SiteTree), options?: SiteCoreOptions): (request: Request) => Promise<Response>;
|