@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.
Files changed (68) hide show
  1. package/CHANGELOG.md +104 -1
  2. package/README.md +12 -1
  3. package/lib/src/attest.d.ts +12 -3
  4. package/lib/src/attest.js +15 -10
  5. package/lib/src/bake.js +2 -1
  6. package/lib/src/base-image.d.ts +2 -0
  7. package/lib/src/base-image.js +8 -0
  8. package/lib/src/bucket-follow.d.ts +22 -0
  9. package/lib/src/bucket-follow.js +65 -0
  10. package/lib/src/bucket.d.ts +270 -0
  11. package/lib/src/bucket.js +1130 -0
  12. package/lib/src/cache-limit.d.ts +3 -3
  13. package/lib/src/cache-limit.js +21 -0
  14. package/lib/src/cli/bucket.d.ts +2 -0
  15. package/lib/src/cli/bucket.js +312 -0
  16. package/lib/src/cli/build-image.js +4 -2
  17. package/lib/src/cli/images.js +8 -5
  18. package/lib/src/cli/index.d.ts +1 -1
  19. package/lib/src/cli/index.js +13 -2
  20. package/lib/src/cli/serve-worker.js +63 -11
  21. package/lib/src/cli/servers.js +117 -29
  22. package/lib/src/cli/up.js +2 -0
  23. package/lib/src/cli/watch.d.ts +2 -0
  24. package/lib/src/cli/watch.js +2 -1
  25. package/lib/src/cli.js +6 -3
  26. package/lib/src/dictionary.d.ts +1 -7
  27. package/lib/src/dictionary.js +1 -35
  28. package/lib/src/executor.d.ts +16 -5
  29. package/lib/src/executor.js +127 -58
  30. package/lib/src/index.d.ts +2 -0
  31. package/lib/src/index.js +2 -0
  32. package/lib/src/mime-type.d.ts +6 -0
  33. package/lib/src/mime-type.js +20 -0
  34. package/lib/src/nfc.d.ts +6 -0
  35. package/lib/src/nfc.js +10 -0
  36. package/lib/src/oci.d.ts +65 -1
  37. package/lib/src/oci.js +104 -10
  38. package/lib/src/paths.d.ts +2 -6
  39. package/lib/src/paths.js +2 -8
  40. package/lib/src/plugins/env.d.ts +20 -0
  41. package/lib/src/plugins/env.js +37 -0
  42. package/lib/src/plugins/exec.d.ts +1 -1
  43. package/lib/src/plugins/exec.js +3 -2
  44. package/lib/src/plugins/host.js +3 -2
  45. package/lib/src/precompress.d.ts +6 -0
  46. package/lib/src/precompress.js +6 -0
  47. package/lib/src/recipe.d.ts +37 -0
  48. package/lib/src/recipe.js +96 -0
  49. package/lib/src/registry-ops.d.ts +5 -1
  50. package/lib/src/registry-ops.js +69 -45
  51. package/lib/src/request-path.d.ts +10 -0
  52. package/lib/src/request-path.js +42 -0
  53. package/lib/src/serve-dictionary.d.ts +11 -0
  54. package/lib/src/serve-dictionary.js +45 -0
  55. package/lib/src/serve-rules.js +1 -1
  56. package/lib/src/server.d.ts +16 -229
  57. package/lib/src/server.js +135 -795
  58. package/lib/src/servers.d.ts +25 -0
  59. package/lib/src/servers.js +62 -2
  60. package/lib/src/site-core.d.ts +368 -0
  61. package/lib/src/site-core.js +1065 -0
  62. package/lib/src/site-handler.d.ts +14 -0
  63. package/lib/src/site-handler.js +32 -0
  64. package/lib/src/store.d.ts +31 -2
  65. package/lib/src/store.js +140 -21
  66. package/lib/src/wbn.d.ts +1 -6
  67. package/lib/src/wbn.js +2 -18
  68. package/package.json +5 -1
@@ -1,7 +1,7 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import { ATTEST, referrersTag } from './attest.js';
3
3
  import { isSitefileError, SitefileError } from './errors.js';
4
- import { canonicalJson, MEDIA, parseConfig, parseManifest, parsePlatform, siteLayerIndices } from './oci.js';
4
+ import { canonicalJson, MEDIA, parseConfig, parseIndex, parseManifest, parsePlatform, siteLayerIndices } from './oci.js';
5
5
  import { parseRef, withDefaultRegistry } from './ref.js';
6
6
  import { shortId, Store } from './store.js';
7
7
  const CONFIG_TYPES = new Set([MEDIA.config, MEDIA.dockerConfig]);
@@ -131,65 +131,89 @@ export async function pullImage(store, client, ref, o = {}) {
131
131
  const id = await store.addManifest(manifest.bytes, tagRef);
132
132
  return { id, rootDigest: root.digest, manifest: parsed, config: configJson };
133
133
  }
134
- /** Push a stored image to `ref` (a registry reference): blobs that are missing, then the manifest. */
134
+ /**
135
+ * Push a stored image to `ref` (a registry reference): blobs that are missing, then the manifest. A
136
+ * multi-platform image (an image index) pushes every platform's blobs and manifest (by digest, the shared site
137
+ * layers once), then the index under the tag.
138
+ */
135
139
  export async function pushImage(store, client, id, ref, o = {}) {
136
140
  const say = o.onEvent ?? (() => undefined);
137
141
  const repo = ref.name;
138
142
  if (ref.digest !== undefined && ref.digest !== id) {
139
143
  throw new SitefileError('E_USAGE', `the reference pins ${ref.digest} but the local image is ${id}`);
140
144
  }
141
- const manifestBytes = await store.readBlob(id);
142
- const parsed = parseManifest(manifestBytes);
143
- const ann = parsed.annotations['org.opencontainers.image.base.name'];
144
- // Layers of the BASE image can be mounted from its repository when it lives on this registry.
145
- let mountFrom;
146
- let baseLayers = new Set();
147
- if (ann) {
148
- try {
149
- const b = withDefaultRegistry(parseRef(ann));
150
- if (b.registry === client.registry && b.name !== repo) {
151
- mountFrom = b.name;
152
- // Every layer but the site layers (`--oci-layers` may give several).
153
- const site = new Set(siteLayerIndices(parsed, parseConfig(await store.readBlob(parsed.config.digest))));
154
- baseLayers = new Set(parsed.layers.filter((_, i) => !site.has(i)).map((l) => l.digest));
155
- }
156
- }
157
- catch {
158
- /* not a reference we understand */
159
- }
160
- }
145
+ const rootBytes = await store.readBlob(id);
146
+ const rootType = mediaTypeOf(rootBytes);
147
+ const children = rootType === MEDIA.index ? parseIndex(rootBytes).manifests : undefined;
148
+ if (!children)
149
+ parseManifest(rootBytes); // a corrupt image fails before any request
161
150
  await client.ping();
162
151
  const counts = { uploaded: 0, mounted: 0, existing: 0 };
163
152
  const seen = new Set();
164
- for (const d of [parsed.config, ...parsed.layers]) {
165
- if (seen.has(d.digest))
166
- continue;
167
- seen.add(d.digest);
168
- if (await client.hasBlob(repo, d.digest)) {
169
- counts.existing++;
170
- say(`${shortId(d.digest)}: layer already exists`);
171
- continue;
153
+ const pushBlobsOf = async (manifestBytes) => {
154
+ const parsed = parseManifest(manifestBytes);
155
+ const ann = parsed.annotations['org.opencontainers.image.base.name'];
156
+ // Layers of the BASE image can be mounted from its repository when it lives on this registry.
157
+ let mountFrom;
158
+ let baseLayers = new Set();
159
+ if (ann) {
160
+ try {
161
+ const b = withDefaultRegistry(parseRef(ann));
162
+ if (b.registry === client.registry && b.name !== repo) {
163
+ mountFrom = b.name;
164
+ // Every layer but the site layers (`--oci-layers` may give several).
165
+ const site = new Set(siteLayerIndices(parsed, parseConfig(await store.readBlob(parsed.config.digest))));
166
+ baseLayers = new Set(parsed.layers.filter((_, i) => !site.has(i)).map((l) => l.digest));
167
+ }
168
+ }
169
+ catch {
170
+ /* not a reference we understand */
171
+ }
172
+ }
173
+ for (const d of [parsed.config, ...parsed.layers]) {
174
+ if (seen.has(d.digest))
175
+ continue;
176
+ seen.add(d.digest);
177
+ if (await client.hasBlob(repo, d.digest)) {
178
+ counts.existing++;
179
+ say(`${shortId(d.digest)}: layer already exists`);
180
+ continue;
181
+ }
182
+ if (!(await store.hasBlob(d.digest, d.size)))
183
+ throw new SitefileError('E_STORE', `blob ${d.digest} is missing from the local store; cannot push`);
184
+ const r = await client.pushBlob(repo, d, { length: d.size, open: () => store.blobStream(d.digest) }, baseLayers.has(d.digest) ? mountFrom : undefined);
185
+ counts[r]++;
186
+ say(`${shortId(d.digest)}: ${r === 'mounted' ? 'mounted from ' + mountFrom : 'pushed'} (${d.size} bytes)`);
187
+ }
188
+ };
189
+ if (children) {
190
+ for (const c of children) {
191
+ const bytes = await store.readBlob(c.digest, c.size);
192
+ await pushBlobsOf(bytes);
193
+ const put = await client.putManifest(repo, c.digest, bytes, MEDIA.manifest);
194
+ if (put !== c.digest)
195
+ throw new SitefileError('E_INTEGRITY', `the registry reports digest ${put}, expected ${c.digest}`);
196
+ say(`${shortId(c.digest)}: ${c.platform} manifest pushed`);
172
197
  }
173
- if (!(await store.hasBlob(d.digest, d.size)))
174
- throw new SitefileError('E_STORE', `blob ${d.digest} is missing from the local store; cannot push`);
175
- const r = await client.pushBlob(repo, d, { length: d.size, open: () => store.blobStream(d.digest) }, baseLayers.has(d.digest) ? mountFrom : undefined);
176
- counts[r]++;
177
- say(`${shortId(d.digest)}: ${r === 'mounted' ? 'mounted from ' + mountFrom : 'pushed'} (${d.size} bytes)`);
178
- }
179
- let mediaType = MEDIA.manifest;
180
- try {
181
- const j = JSON.parse(Buffer.from(manifestBytes).toString('utf8'));
182
- if (typeof j.mediaType === 'string')
183
- mediaType = j.mediaType;
184
198
  }
185
- catch {
186
- /* parseManifest already succeeded */
199
+ else {
200
+ await pushBlobsOf(rootBytes);
187
201
  }
188
- const digest = await client.putManifest(repo, ref.tag ?? ref.digest ?? 'latest', manifestBytes, mediaType);
202
+ const digest = await client.putManifest(repo, ref.tag ?? ref.digest ?? 'latest', rootBytes, rootType ?? MEDIA.manifest);
189
203
  if (digest !== id)
190
204
  throw new SitefileError('E_INTEGRITY', `the registry reports digest ${digest}, expected ${id}`);
191
205
  const attestations = await pushReferrers(client, repo, id, await store.referrers(id), say);
192
- return { digest, size: manifestBytes.byteLength, ...counts, attestations };
206
+ return { digest, size: rootBytes.byteLength, ...counts, attestations };
207
+ }
208
+ /** The `mediaType` a manifest or index document declares, if any. */
209
+ function mediaTypeOf(bytes) {
210
+ try {
211
+ const j = JSON.parse(Buffer.from(bytes).toString('utf8'));
212
+ return typeof j.mediaType === 'string' ? j.mediaType : undefined;
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
193
217
  }
194
218
  /**
195
219
  * Push attestations as OCI 1.1 referrers of `subject` (distribution spec v1.1): each artifact
@@ -0,0 +1,10 @@
1
+ /** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
2
+ export declare function safeSegments(rawPath: string): string[] | undefined;
3
+ /**
4
+ * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
5
+ * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
6
+ * `/` for an empty path); any other target is returned as it is. The authority is not checked.
7
+ */
8
+ export declare function originForm(target: string): string;
9
+ /** A tree path with each segment percent-encoded like encodeURIComponent. */
10
+ export declare function encodePath(p: string): string;
@@ -0,0 +1,42 @@
1
+ // Request-path helpers shared by the serve rules and the site handler. Pure: no `node:` import.
2
+ import { nfc } from './nfc.js';
3
+ /** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
4
+ export function safeSegments(rawPath) {
5
+ if (!rawPath.startsWith('/') || rawPath.includes('\\') || rawPath.includes('\0'))
6
+ return undefined;
7
+ const out = [];
8
+ for (const raw of rawPath.split('/')) {
9
+ if (raw === '')
10
+ continue;
11
+ let seg;
12
+ try {
13
+ seg = decodeURIComponent(raw);
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ // A decoded '/', '\\', NUL, control character, '.' or '..' could change what is read.
19
+ if (seg === '.' || seg === '..' || /[\\/\u0000-\u001f\u007f]/.test(seg))
20
+ return undefined;
21
+ // Tree paths are NFC; a request for an NFD spelling finds the same file.
22
+ out.push(nfc(seg));
23
+ }
24
+ return out;
25
+ }
26
+ /**
27
+ * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
28
+ * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
29
+ * `/` for an empty path); any other target is returned as it is. The authority is not checked.
30
+ */
31
+ export function originForm(target) {
32
+ const m = /^https?:\/\/[^/?#]*/i.exec(target);
33
+ if (!m)
34
+ return target;
35
+ const rest = target.slice(m[0].length);
36
+ return rest.startsWith('/') ? rest : '/' + rest;
37
+ }
38
+ /** A tree path with each segment percent-encoded like encodeURIComponent. */
39
+ export function encodePath(p) {
40
+ return p.split('/').map(encodeURIComponent).join('/');
41
+ }
42
+ //# sourceMappingURL=request-path.js.map
@@ -0,0 +1,11 @@
1
+ /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
2
+ export declare function acceptsDcz(acceptEncoding: string | undefined): boolean;
3
+ /**
4
+ * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
5
+ * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
6
+ */
7
+ export declare function deltaFor(tree: {
8
+ get(path: string): {
9
+ readonly bytes: Uint8Array;
10
+ } | undefined;
11
+ }, path: string, availableDictionary: string | undefined, acceptEncoding: string | undefined): Uint8Array | undefined;
@@ -0,0 +1,45 @@
1
+ // The `serve` side of dictionary-compressed deltas (see src/dictionary.ts for how they are made).
2
+ // Pure: no `node:` import, so the site handler can use it anywhere.
3
+ /** The bytes of an RFC 8941 byte sequence (`:base64:`), or undefined. */
4
+ function sfBinary(v) {
5
+ const m = v === undefined ? null : /^\s*:([A-Za-z0-9+/]*={0,2}):\s*$/.exec(v);
6
+ if (!m)
7
+ return undefined;
8
+ try {
9
+ return Uint8Array.from(atob(m[1]), (c) => c.charCodeAt(0));
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
16
+ export function acceptsDcz(acceptEncoding) {
17
+ if (acceptEncoding === undefined)
18
+ return false;
19
+ return acceptEncoding.split(',').some((part) => {
20
+ const [token, ...params] = part.split(';').map((s) => s.trim());
21
+ if (token?.toLowerCase() !== 'dcz')
22
+ return false;
23
+ const q = params.find((p) => /^q=/i.test(p));
24
+ return q === undefined || Number(q.slice(2)) > 0;
25
+ });
26
+ }
27
+ /**
28
+ * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
29
+ * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
30
+ */
31
+ export function deltaFor(tree, path, availableDictionary, acceptEncoding) {
32
+ if (!acceptsDcz(acceptEncoding))
33
+ return undefined;
34
+ const hash = sfBinary(availableDictionary);
35
+ if (!hash || hash.byteLength !== 32)
36
+ return undefined;
37
+ const sidecar = tree.get(`${path}.dcz`);
38
+ if (!sidecar || sidecar.bytes.byteLength < 40)
39
+ return undefined;
40
+ for (let i = 0; i < 32; i++)
41
+ if (sidecar.bytes[8 + i] !== hash[i])
42
+ return undefined;
43
+ return sidecar.bytes;
44
+ }
45
+ //# sourceMappingURL=serve-dictionary.js.map
@@ -1,6 +1,6 @@
1
1
  // `_redirects` and `_headers` as `sitefile serve` reads them (docs/CLI.md, "serve").
2
2
  // Ported as the rules section of rust/src/server.rs.
3
- import { safeSegments } from './server.js';
3
+ import { safeSegments } from './request-path.js';
4
4
  const HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
5
5
  /** Headers the server owns; `_headers` cannot set them. */
6
6
  const PROTECTED_HEADERS = new Set(['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'etag', 'location', 'accept-ranges', 'content-range', 'last-modified', 'www-authenticate', 'content-encoding']);
@@ -1,10 +1,11 @@
1
1
  import http from 'node:http';
2
2
  import { SitefileError } from './errors.js';
3
3
  import { type FetchPolicy } from './resources/types.js';
4
- import { type RedirectRequest, type ServeRedirect } from './serve-rules.js';
5
4
  import type { Tree } from './tree.js';
6
5
  import { RELOAD_CLIENT } from './reload-client.js';
7
6
  import type { BasicAuth } from './serve-auth.js';
7
+ import { type SiteCoreOptions } from './site-core.js';
8
+ export { acceptsEncoding, acceptsGzip, byteRange, cacheControlFor, createSiteHandler, createSiteResponder, cspBlocksReload, gzipMember, hostAllowed, hostProfile, HOST_PROFILES, HTML_HANDLINGS, httpDate, injectReloadScript, isCompressible, isNavigation, isRebasedType, nearMissPage, nearMisses, normalizeBase, normalizeProductionUrl, originForm, parseAllowedHost, parseHttpDate, preflightHeaders, RELOAD_PATH, RELOAD_SCRIPT, RELOAD_SCRIPT_PATH, rewriteBaseUrls, routingFor, safeSegments, siteBaseHeaders, spaFallback, type CachePreview, type HostProfileName, type HtmlHandling, type NearMiss, type RoutingProfile, type SiteContent, type SiteCoreOptions, type SiteCoreReply, type SiteHandlerOptions, type SiteProxy, type SiteReply, type SiteRequest, type SiteTree, } from './site-core.js';
8
9
  /** `serve`'s proxying (#172): `--proxy` routes and the fetch policy every proxied request follows. */
9
10
  export interface ServeProxy {
10
11
  /** `--proxy /prefix=https://host/path`: requests under `prefix` go to `target` + the rest of the path. */
@@ -19,70 +20,27 @@ export interface ServeProxy {
19
20
  */
20
21
  readonly policy: FetchPolicy;
21
22
  }
22
- export interface SiteServerOptions {
23
- /**
24
- * Single-page apps: answer a page navigation ({@link isNavigation}) for a path nothing else answers
25
- * with the nearest app shell ({@link spaFallback}). Never for subresources (scripts, images, `fetch()`).
26
- */
27
- readonly spa?: boolean;
23
+ /**
24
+ * Options of the Node server: the site handler's ({@link SiteHandlerOptions}, which decide what each
25
+ * path answers) and the adapter's own, which need a socket or Node.
26
+ */
27
+ export interface SiteServerOptions extends Omit<SiteCoreOptions, 'proxy' | 'injectReload' | 'operator'> {
28
28
  /** Proxy rules (`_redirects` status 200 to a URL) and `--proxy` routes; without this every proxy rule is refused. */
29
29
  readonly proxy?: ServeProxy;
30
- /** `--spa-exclude`: request paths (`*` matches any characters) that never fall back. */
31
- readonly spaExclude?: readonly string[];
32
- /** `--spa-fallback`: the one file every fallback serves, instead of the nearest `200.html` or `index.html`. */
33
- readonly spaFallback?: string;
34
30
  /** One access-log line per request: `METHOD /path STATUS BYTES MSms`. */
35
31
  readonly log?: (line: string) => void;
36
- /** Sent as `x-sitefile-server` so `servers` can tell its own servers from a reused port. */
37
- readonly serverId?: string;
38
32
  /**
39
33
  * `serve --watch`: answer {@link RELOAD_PATH} with an event stream and {@link RELOAD_SCRIPT_PATH}
40
34
  * with the client script, and add {@link RELOAD_SCRIPT} to HTML navigations. Never set otherwise,
41
35
  * and never written to exports.
42
36
  */
43
37
  readonly liveReload?: LiveReload;
44
- /**
45
- * When the served files last changed (Unix seconds), read per request: sent as `Last-Modified` on
46
- * file responses, and `If-Modified-Since` (without `If-None-Match`) gives `304`. Unset: neither.
47
- */
48
- readonly lastModified?: () => number | undefined;
49
- /** Problems a person should know about (without the `warning: ` prefix), e.g. a CSP that blocks live reload. */
50
- readonly warn?: (message: string) => void;
51
- /**
52
- * `--base /repo/`: serve the site under this path prefix (a GitHub Pages project site); `/`
53
- * redirects to it, `/repo` gets its slash, everything else is 404. Normalized by {@link normalizeBase}.
54
- */
55
- readonly base?: string | (() => string | undefined);
56
- /**
57
- * `--rewrite-base`: the production URL ({@link normalizeProductionUrl}) that HTML, CSS and XML
58
- * responses have replaced by this server's origin and `--base`, so absolute self-links stay local.
59
- */
60
- readonly rewriteBase?: string | (() => string | undefined);
61
- /** `--host-profile` / `--html-handling`: behave like a static host ({@link hostProfile}). Absent: sitefile's own rules. */
62
- readonly profile?: RoutingProfile;
63
- /**
64
- * Foreground and `--watch` servers (never detached or shared ones): a 404 with no `404.html` to
65
- * answer it lists near misses ({@link nearMisses}).
66
- */
67
- readonly devNotFound?: boolean;
68
- /** `--country`: what `_redirects` `Country=` conditions match (there is no geolocation locally). */
69
- readonly country?: string;
70
38
  /**
71
39
  * DNS-rebinding guard: when set, a request whose `Host` is not `localhost`, a `*.localhost` name,
72
40
  * an IP address or a name this list allows gets `403` ({@link hostAllowed}). `*` allows every
73
41
  * host; unset: no check (the CLI always sets it).
74
42
  */
75
43
  readonly allowedHosts?: readonly string[];
76
- /** `--cors`: `Access-Control-Allow-Origin: *` on every response (`_headers` still wins) and `OPTIONS` preflights answered with `204`. */
77
- readonly cors?: boolean;
78
- /**
79
- * `--isolate`: cross-origin isolation (SharedArrayBuffer, wasm threads) on every response:
80
- * `Cross-Origin-Opener-Policy: same-origin`, this `Cross-Origin-Embedder-Policy` and
81
- * `Cross-Origin-Resource-Policy: same-origin`. `_headers` still wins.
82
- */
83
- readonly isolate?: 'require-corp' | 'credentialless';
84
- /** `--max-age`, `--immutable`, `--max-age-html`: a production `Cache-Control` preview for files ({@link cacheControlFor}). */
85
- readonly cache?: CachePreview;
86
44
  /** `--log-format`: access-log lines as text (the default, `GET /path 200 1234 1.2ms`) or one JSON object each ({@link accessLogLine}). */
87
45
  readonly logFormat?: 'text' | 'json';
88
46
  /** `--log-ip`: add the client address to access-log lines. */
@@ -95,15 +53,11 @@ export interface SiteServerOptions {
95
53
  readonly maxConnectionsPerIp?: number;
96
54
  /** Count loopback clients against {@link maxConnectionsPerIp} too (tests only). */
97
55
  readonly limitLoopback?: boolean;
98
- /** `--random-route`: {@link base} is a secret, so `/` is a plain `404` instead of a redirect into it. */
99
- readonly hideBase?: boolean;
100
56
  /** `--allow-ip`, `--deny-ip` (CIDRs, {@link parseCidr}): a non-loopback client they refuse gets `403` before anything else. */
101
57
  readonly ipRules?: {
102
58
  readonly allow: readonly Cidr[];
103
59
  readonly deny: readonly Cidr[];
104
60
  };
105
- /** `X-Robots-Tag: noindex` on every response (the CLI sets it on non-loopback binds). */
106
- readonly noindex?: boolean;
107
61
  /** Add the client address and device (from `User-Agent`) to access-log lines of non-loopback clients. */
108
62
  readonly clientInfo?: boolean;
109
63
  /** `--tls-cert`, `--tls-key`: serve HTTPS with this PEM certificate chain and private key. */
@@ -111,53 +65,10 @@ export interface SiteServerOptions {
111
65
  readonly cert: string | Uint8Array;
112
66
  readonly key: string | Uint8Array;
113
67
  };
114
- /** `--compress`: gzip compressible files of at least 1024 bytes on the fly when no precompressed variant exists. */
115
- readonly compress?: boolean;
116
68
  /** `--throttle`: response bandwidth (bytes per second) and latency added before each response. */
117
69
  readonly throttle?: Throttle;
118
- /** `--mime`, `--mime-file`: content types by lowercase extension, checked before the built-in table. */
119
- readonly mime?: ReadonlyMap<string, string>;
120
- /**
121
- * Where file contents come from when the tree holds only digests (a zip served in place,
122
- * `openZipFile`): `read` returns a file's bytes (undefined: use the node's), `deflated` a
123
- * deflated file's raw deflate stream, sent as `content-encoding: gzip` to clients that accept it.
124
- */
125
- readonly content?: SiteContent;
126
- }
127
- /** Contents read on demand ({@link SiteServerOptions.content}). */
128
- export interface SiteContent {
129
- read(path: string): Uint8Array | undefined;
130
- deflated?(path: string): {
131
- readonly deflate: Uint8Array;
132
- readonly crc: number;
133
- readonly size: number;
134
- } | undefined;
135
70
  }
136
- /** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
137
- export declare function acceptsGzip(header: string | undefined): boolean;
138
- /** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
139
- export declare function gzipMember(deflate: Uint8Array, crc: number, size: number): Uint8Array;
140
- /** Reserved for the live-reload event stream while `serve --watch` runs. */
141
- export declare const RELOAD_PATH = "/__sitefile/reload";
142
- /** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
143
- export declare const RELOAD_SCRIPT_PATH = "/__sitefile/reload.js";
144
- /** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
145
- export declare const RELOAD_SCRIPT = "<script src=\"/__sitefile/reload.js\"></script>";
146
71
  export { RELOAD_CLIENT };
147
- /**
148
- * Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
149
- * when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
150
- * `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
151
- */
152
- export declare function isNavigation(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
153
- /**
154
- * The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
155
- * a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
156
- * undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
157
- * `https:` count as allowing the server's own origin (host sources are not matched), and
158
- * `'strict-dynamic'` makes `'self'` ignored for scripts.
159
- */
160
- export declare function cspBlocksReload(value: string): 'script-src' | 'connect-src' | undefined;
161
72
  /** Heartbeat interval on the event stream. */
162
73
  export declare const HEARTBEAT_MS = 15000;
163
74
  /** Headers of the event stream (also on HEAD): no proxy buffering (`X-Accel-Buffering`), no compression or other transforms. */
@@ -340,15 +251,6 @@ export declare class LiveReload {
340
251
  reload(): void;
341
252
  get size(): number;
342
253
  }
343
- /** `html` with {@link RELOAD_SCRIPT} inserted before the last `</body` (ASCII case-insensitive), else appended. */
344
- export declare function injectReloadScript(html: Uint8Array): Uint8Array;
345
- /** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
346
- export declare function safeSegments(rawPath: string): string[] | undefined;
347
- /**
348
- * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
349
- * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
350
- * `/` for an empty path); any other target is returned as it is. The authority is not checked.
351
- */
352
254
  /** One access-log request, as {@link accessLogLine} writes it. */
353
255
  export interface AccessLogEntry {
354
256
  readonly ts: string;
@@ -386,13 +288,6 @@ export declare function stoppedLogLine(ts: string, signal: string): string;
386
288
  * (`<ISO time> <rest>`) as a request, started, stopped, warning, error or message object.
387
289
  */
388
290
  export declare function logLineAsJson(line: string): string;
389
- /**
390
- * Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
391
- * case-insensitive; an explicit entry wins over `*`.
392
- */
393
- export declare function acceptsEncoding(header: string | undefined, coding: string): boolean;
394
- /** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
395
- export declare function isCompressible(type: string): boolean;
396
291
  /** `--throttle` limits ({@link parseThrottle}). */
397
292
  export interface Throttle {
398
293
  readonly bytesPerSecond: number;
@@ -406,24 +301,6 @@ export declare function parseThrottle(value: string): Throttle | undefined;
406
301
  export declare function parseMimeFlag(value: string): [string, string] | undefined;
407
302
  /** A `mime.types` file (nginx `types { type ext ...; }` or Apache `type ext ...` lines; `#` comments): ext → type. */
408
303
  export declare function parseMimeTypes(text: string, origin: string): Map<string, string>;
409
- /** Production cache headers to preview instead of `no-cache` (`serve --max-age`). */
410
- export interface CachePreview {
411
- /** Seconds for files other than HTML: `public, max-age=N`. */
412
- readonly maxAge?: number;
413
- /** Adds `immutable` to the non-HTML value (needs {@link maxAge}). */
414
- readonly immutable?: boolean;
415
- /** Seconds for HTML pages (absent: they keep `no-cache`, the common production practice). */
416
- readonly maxAgeHtml?: number;
417
- }
418
- /** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
419
- export declare function cacheControlFor(type: string, cache: CachePreview | undefined): string | undefined;
420
- /**
421
- * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
422
- * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
423
- * `/` for an empty path); any other target is returned as it is. The authority is not checked.
424
- */
425
- /** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
426
- export declare function preflightHeaders(value: string | undefined): string | undefined;
427
304
  /** A parsed CIDR block: 4 or 16 address bytes and a prefix length. */
428
305
  export interface Cidr {
429
306
  readonly bytes: readonly number[];
@@ -437,113 +314,23 @@ export declare function parseCidr(text: string): Cidr | undefined;
437
314
  export declare function ipAllowed(rules: SiteServerOptions['ipRules'], remote: string): boolean;
438
315
  /** A short device name from a `User-Agent` (`iPhone`, `iPad`, `Android`, `Windows`, `Mac`, `Linux`), or `other`. */
439
316
  export declare function deviceOf(userAgent: string | undefined): string;
440
- /**
441
- * The DNS-rebinding guard of {@link SiteServerOptions.allowedHosts}: whether a `Host` header value
442
- * may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
443
- * attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
444
- * port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
445
- * it without the dot).
446
- */
447
- export declare function hostAllowed(allowed: readonly string[] | undefined, host: string | undefined): boolean;
448
- /** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
449
- export declare function parseAllowedHost(value: string): string | undefined;
450
- export declare function originForm(target: string): string;
451
- /** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
452
- export declare function httpDate(secs: number): string;
453
- /** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
454
- export declare function parseHttpDate(value: string): number | undefined;
455
317
  /**
456
318
  * The link-values of a `Link` header that become `103 Early Hints`: split at commas outside `<…>`
457
319
  * and quotes, kept when well formed and `rel=preload` or `rel=preconnect` (ASCII case-insensitive).
458
320
  */
459
321
  export declare function earlyHints(link: string): string[];
460
322
  /**
461
- * The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
462
- * `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
463
- * asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
464
- */
465
- export declare function byteRange(header: string | undefined, size: number): [number, number] | 'unsatisfiable' | undefined;
466
- /**
467
- * The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
468
- * else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
469
- * has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
470
- */
471
- export declare function spaFallback(segs: readonly string[], trailingSlash: boolean, isFile: (p: string) => boolean, fallback?: string): string | undefined;
472
- /** `--html-handling` (Cloudflare's names): `auto`, `force-slash`, `drop-slash` or `none`. */
473
- export type HtmlHandling = 'auto' | 'force-slash' | 'drop-slash' | 'none';
474
- export declare const HTML_HANDLINGS: readonly HtmlHandling[];
475
- export declare const HOST_PROFILES: readonly ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
476
- export type HostProfileName = (typeof HOST_PROFILES)[number];
477
- /** How a server routes like a static host (`--host-profile`, `--html-handling`). */
478
- export interface RoutingProfile {
479
- /** Canonical page URLs; undefined keeps sitefile's own rules (clean URLs plus both spellings). */
480
- readonly htmlHandling?: HtmlHandling;
481
- /** The status of a canonicalizing redirect. */
482
- readonly redirectStatus: number;
483
- /** Whether `/_redirects` and `/_headers` are read (and hidden). */
484
- readonly siteFiles: boolean;
485
- /** Which 404.html answers a miss: the nearest, only the root one, or (no 404.html) `/index.html` with 200. */
486
- readonly notFound: 'nearest' | 'root' | 'index';
487
- /** Sitefile's own rules only: `/about/` with only `about.html` redirects to `/about`, or is 404. */
488
- readonly slashHtml: 'redirect' | 'not-found';
489
- }
490
- /**
491
- * The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
492
- * undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
493
- *
494
- * | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
495
- * | netlify | auto | 301 | yes | nearest 404.html |
496
- * | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
497
- * | vercel | none | 308 | no | /404.html |
498
- * | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
499
- * | firebase | none | 301 | no | /404.html |
500
- */
501
- export declare function hostProfile(name: HostProfileName | undefined, htmlHandling?: HtmlHandling): RoutingProfile;
502
- /** The server's routing profile for the flags (undefined: sitefile's own rules). */
503
- export declare function routingFor(o: {
504
- hostProfile?: HostProfileName | undefined;
505
- htmlHandling?: HtmlHandling | undefined;
506
- }): RoutingProfile | undefined;
507
- /** A near miss for a 404: a file (`path`) or a `_redirects` rule (`line`), and why. */
508
- export interface NearMiss {
509
- readonly path?: string;
510
- readonly line?: number;
511
- readonly why: string;
512
- }
513
- /**
514
- * What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
515
- * from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
516
- * host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
517
- * conditions do not, in file order.
518
- */
519
- export declare function nearMisses(tree: Tree, isFile: (p: string) => boolean, vpath: string, redirects: readonly ServeRedirect[], req: RedirectRequest): NearMiss[];
520
- /** The development 404 page listing near misses. */
521
- export declare function nearMissPage(vpath: string, misses: readonly NearMiss[], mount?: string): string;
522
- /** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
523
- export declare function isRebasedType(type: string): boolean;
524
- /**
525
- * A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
526
- * fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
527
- * http(s) URL with a host.
528
- */
529
- export declare function normalizeProductionUrl(raw: string): string | undefined;
530
- /**
531
- * `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
532
- * the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
533
- * so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
534
- */
535
- export declare function rewriteBaseUrls(body: Uint8Array, from: string, to: string): Uint8Array;
536
- /**
537
- * A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
538
- * safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
323
+ * The site handler's options for a server's: the same rules, with proxying done by `fetchRemote` under
324
+ * the server's fetch policy (https only, public addresses only, an allow-list of hosts; every proxy rule
325
+ * is refused without `proxy`) and the reload script injected when there is a live-reload client.
539
326
  */
540
- export declare function normalizeBase(raw: string): string | undefined;
327
+ export declare function handlerOptionsOf(options: SiteServerOptions): SiteCoreOptions;
541
328
  /**
542
- * An HTTP server for an immutable Tree. GET and HEAD only; nothing outside the tree is
543
- * ever reachable because lookups are exact map keys built from validated segments.
544
- * Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), answers
545
- * `/about` with `/about.html` when there is no such file or directory, and redirects `/about/`
546
- * to `/about` when only `/about.html` answers it.
329
+ * The Node adapter for the site handler ({@link createSiteResponder}): an HTTP (or HTTPS) server for an
330
+ * immutable Tree. It owns what needs a socket or Node: the listener, the IP rules, the connection cap,
331
+ * the `Host` allow-list, basic authentication, throttling, `103 Early Hints`, the access log, and the
332
+ * live-reload endpoints (event stream, client script, console and client reports). Everything that
333
+ * decides what a path answers is the handler's.
547
334
  */
548
335
  export declare function createSiteServer(site: Tree | (() => Tree), options?: SiteServerOptions): http.Server;
549
336
  /** Listen on host:port (port 0 = any free port); EADDRINUSE and friends become E_SERVER. */