@johnhenry/sitefile 0.0.2 → 0.0.3
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 +467 -0
- package/README.md +55 -6
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/canonical.d.ts +16 -0
- package/lib/src/canonical.js +46 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +3 -1
- package/lib/src/cli/index.js +31 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +46 -8
- package/lib/src/cli/servers.d.ts +124 -1
- package/lib/src/cli/servers.js +705 -62
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +192 -22
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +116 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +176 -7
- package/lib/src/language/validate.js +21 -0
- package/lib/src/links.d.ts +33 -0
- package/lib/src/links.js +271 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +69 -2
- package/lib/src/planner.js +150 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +141 -16
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +304 -0
- package/lib/src/resources/archive.d.ts +36 -0
- package/lib/src/resources/archive.js +338 -67
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +32 -0
- package/lib/src/serve-auth.js +112 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +437 -10
- package/lib/src/server.js +1236 -52
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +109 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +54 -0
- package/lib/src/site.js +204 -6
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The servers file (issue #223), for `sitefile up`, `down` and `ps`: several detached site servers
|
|
3
|
+
* described in one place, like a Compose file.
|
|
4
|
+
*
|
|
5
|
+
* ```yaml
|
|
6
|
+
* servers:
|
|
7
|
+
* docs:
|
|
8
|
+
* source: ./docs/dist # a directory or archive file (relative to this file), or an image
|
|
9
|
+
* publish: 8081 # [host:]port, as serve -p (default 127.0.0.1, a free port)
|
|
10
|
+
* spa: true # as serve --spa (default false)
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Each key under `servers` is the server's name (as `serve -d --name`).
|
|
14
|
+
*/
|
|
15
|
+
export declare const SERVERS_FILES: readonly string[];
|
|
16
|
+
export interface ServerSpec {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/** As written: `./dir`, `../site.zip`, `/abs`, an image reference or ID, or an archive file name. */
|
|
19
|
+
readonly source: string;
|
|
20
|
+
/** `[host:]port` as written (a number is its decimal form); undefined: 127.0.0.1 and a free port. */
|
|
21
|
+
readonly publish: string | undefined;
|
|
22
|
+
readonly spa: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface ServersFile {
|
|
25
|
+
/** The file as given (for messages). */
|
|
26
|
+
readonly label: string;
|
|
27
|
+
/** The directory relative sources are resolved against. */
|
|
28
|
+
readonly dir: string;
|
|
29
|
+
readonly servers: readonly ServerSpec[];
|
|
30
|
+
}
|
|
31
|
+
/** `file` when given, else the first of {@link SERVERS_FILES} in the current directory. */
|
|
32
|
+
export declare function findServersFile(file: string | undefined): Promise<string>;
|
|
33
|
+
/** Check the shape of a parsed servers file. */
|
|
34
|
+
export declare function parseServersDefinition(value: unknown, label: string, dir: string): ServersFile;
|
|
35
|
+
/** Read and check a servers file (.yaml, .yml or .json). */
|
|
36
|
+
export declare function loadServersFile(file: string): Promise<ServersFile>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { SitefileError } from './errors.js';
|
|
4
|
+
import { parseYaml } from './yaml.js';
|
|
5
|
+
/**
|
|
6
|
+
* The servers file (issue #223), for `sitefile up`, `down` and `ps`: several detached site servers
|
|
7
|
+
* described in one place, like a Compose file.
|
|
8
|
+
*
|
|
9
|
+
* ```yaml
|
|
10
|
+
* servers:
|
|
11
|
+
* docs:
|
|
12
|
+
* source: ./docs/dist # a directory or archive file (relative to this file), or an image
|
|
13
|
+
* publish: 8081 # [host:]port, as serve -p (default 127.0.0.1, a free port)
|
|
14
|
+
* spa: true # as serve --spa (default false)
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Each key under `servers` is the server's name (as `serve -d --name`).
|
|
18
|
+
*/
|
|
19
|
+
export const SERVERS_FILES = ['sitefile.servers.yaml', 'sitefile.servers.yml', 'sitefile.servers.json'];
|
|
20
|
+
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
|
|
21
|
+
const SERVER_KEYS = ['source', 'publish', 'spa'];
|
|
22
|
+
const isMapping = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
23
|
+
function fail(label, detail) {
|
|
24
|
+
throw new SitefileError('E_DATA', `${label}: ${detail}`);
|
|
25
|
+
}
|
|
26
|
+
/** `file` when given, else the first of {@link SERVERS_FILES} in the current directory. */
|
|
27
|
+
export async function findServersFile(file) {
|
|
28
|
+
if (file !== undefined)
|
|
29
|
+
return file;
|
|
30
|
+
for (const name of SERVERS_FILES) {
|
|
31
|
+
if (await readFile(name).then(() => true, () => false))
|
|
32
|
+
return name;
|
|
33
|
+
}
|
|
34
|
+
throw new SitefileError('E_NOT_FOUND', `no servers file: ${SERVERS_FILES.join(', ')} not found in the current directory (or pass -f)`);
|
|
35
|
+
}
|
|
36
|
+
/** Check the shape of a parsed servers file. */
|
|
37
|
+
export function parseServersDefinition(value, label, dir) {
|
|
38
|
+
if (!isMapping(value))
|
|
39
|
+
fail(label, 'a servers file must be a mapping with a servers key');
|
|
40
|
+
for (const key of Object.keys(value))
|
|
41
|
+
if (key !== 'servers')
|
|
42
|
+
fail(label, `unknown key '${key}' (expected servers)`);
|
|
43
|
+
const raw = value['servers'];
|
|
44
|
+
if (!isMapping(raw) || Object.keys(raw).length === 0)
|
|
45
|
+
fail(label, 'servers must be a non-empty mapping of name: server');
|
|
46
|
+
const servers = [];
|
|
47
|
+
for (const [name, s] of Object.entries(raw)) {
|
|
48
|
+
if (!NAME_RE.test(name))
|
|
49
|
+
fail(label, `'${name}' is not a valid server name (letters, digits, '_', '.', '-'; at most 63)`);
|
|
50
|
+
// A key of digits only would be reordered by JavaScript objects; file order is the start order.
|
|
51
|
+
if (/^[0-9]+$/.test(name))
|
|
52
|
+
fail(label, `'${name}' is not a valid server name here: use at least one letter`);
|
|
53
|
+
const where = `server '${name}'`;
|
|
54
|
+
if (!isMapping(s))
|
|
55
|
+
fail(label, `${where} must be a mapping with a source`);
|
|
56
|
+
for (const key of Object.keys(s)) {
|
|
57
|
+
if (!SERVER_KEYS.includes(key))
|
|
58
|
+
fail(label, `${where}: unknown key '${key}' (expected ${SERVER_KEYS.join(', ')})`);
|
|
59
|
+
}
|
|
60
|
+
const source = s['source'];
|
|
61
|
+
if (typeof source !== 'string' || source === '')
|
|
62
|
+
fail(label, `${where}: source must be a non-empty string`);
|
|
63
|
+
const publish = s['publish'];
|
|
64
|
+
if (publish !== undefined && publish !== null && typeof publish !== 'string' && !(typeof publish === 'number' && Number.isSafeInteger(publish) && publish >= 0)) {
|
|
65
|
+
fail(label, `${where}: publish must be [host:]port (a string or a port number)`);
|
|
66
|
+
}
|
|
67
|
+
const spa = s['spa'];
|
|
68
|
+
if (spa !== undefined && spa !== null && typeof spa !== 'boolean')
|
|
69
|
+
fail(label, `${where}: spa must be true or false`);
|
|
70
|
+
servers.push({ name, source, publish: publish === undefined || publish === null ? undefined : String(publish), spa: spa === true });
|
|
71
|
+
}
|
|
72
|
+
return { label, dir, servers };
|
|
73
|
+
}
|
|
74
|
+
/** Read and check a servers file (.yaml, .yml or .json). */
|
|
75
|
+
export async function loadServersFile(file) {
|
|
76
|
+
const base = path.basename(file).toLowerCase();
|
|
77
|
+
const json = base.endsWith('.json');
|
|
78
|
+
if (!json && !base.endsWith('.yaml') && !base.endsWith('.yml')) {
|
|
79
|
+
throw new SitefileError('E_USAGE', `servers file '${file}': unknown format (use a .yaml, .yml or .json file)`);
|
|
80
|
+
}
|
|
81
|
+
let text;
|
|
82
|
+
try {
|
|
83
|
+
text = await readFile(file, 'utf8');
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
throw new SitefileError('E_NOT_FOUND', `cannot read servers file '${file}'`, undefined, { cause: e });
|
|
87
|
+
}
|
|
88
|
+
let value;
|
|
89
|
+
if (!json)
|
|
90
|
+
value = parseYaml(text, file);
|
|
91
|
+
else {
|
|
92
|
+
try {
|
|
93
|
+
value = JSON.parse(text.replace(/^/, ''));
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
throw new SitefileError('E_DATA', `${file} is not valid JSON: ${e.message}`, undefined, { cause: e });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return parseServersDefinition(value, file, path.dirname(path.resolve(file)));
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=servers-file.js.map
|
package/lib/src/servers.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import type { SiteContent } from './server.js';
|
|
1
2
|
import { type ArchiveLimits } from './resources/types.js';
|
|
2
3
|
import { Store } from './store.js';
|
|
3
4
|
import { Tree } from './tree.js';
|
|
5
|
+
import type { CachePreview } from './server.js';
|
|
6
|
+
import type { AuthEntry } from './serve-auth.js';
|
|
4
7
|
/**
|
|
5
8
|
* Detached site servers ("containers"). One state file per server:
|
|
6
9
|
*
|
|
@@ -30,6 +33,60 @@ export interface ServerState {
|
|
|
30
33
|
readonly path: string;
|
|
31
34
|
};
|
|
32
35
|
readonly spa: boolean;
|
|
36
|
+
/** `--spa-exclude`: request paths that never fall back (absent: none). */
|
|
37
|
+
readonly spaExclude?: readonly string[];
|
|
38
|
+
/** `--spa-fallback`: the file every fallback serves (absent: the nearest 200.html or index.html). */
|
|
39
|
+
readonly spaFallback?: string;
|
|
40
|
+
/** `--base`: the path prefix the site is served under, `/repo/` (absent: `/`). */
|
|
41
|
+
readonly base?: string;
|
|
42
|
+
/** `--rewrite-base`: the production URL replaced by the local one in HTML, CSS and XML (absent: none). */
|
|
43
|
+
readonly rewriteBase?: string;
|
|
44
|
+
/** `--host-profile`: netlify, cloudflare, vercel, github-pages or firebase (absent: sitefile's own rules). */
|
|
45
|
+
readonly hostProfile?: 'netlify' | 'cloudflare' | 'vercel' | 'github-pages' | 'firebase';
|
|
46
|
+
/** `--html-handling`: auto, force-slash, drop-slash or none (absent: the profile's). */
|
|
47
|
+
readonly htmlHandling?: 'auto' | 'force-slash' | 'drop-slash' | 'none';
|
|
48
|
+
/** `--keep-os-metadata`: serve a directory's or archive's OS metadata files too (absent: false). */
|
|
49
|
+
readonly keepOsMetadata?: boolean;
|
|
50
|
+
/** `--allowed-host` names (absent: none; localhost names and IP addresses are always allowed). */
|
|
51
|
+
readonly allowedHosts?: readonly string[];
|
|
52
|
+
/** `--cors` (absent: false). */
|
|
53
|
+
readonly cors?: boolean;
|
|
54
|
+
/** `--isolate`: the Cross-Origin-Embedder-Policy sent with COOP and CORP (absent: not isolated). */
|
|
55
|
+
readonly isolate?: 'require-corp' | 'credentialless';
|
|
56
|
+
/** `--max-age`, `--immutable`, `--max-age-html` (absent: every response keeps `no-cache`). */
|
|
57
|
+
readonly cache?: CachePreview;
|
|
58
|
+
/** `--log-format json` (absent: text). */
|
|
59
|
+
readonly logFormat?: 'json';
|
|
60
|
+
/** `--log-ip` (absent: false). */
|
|
61
|
+
readonly logIp?: boolean;
|
|
62
|
+
/** `--quiet` (absent: false). */
|
|
63
|
+
readonly quiet?: boolean;
|
|
64
|
+
/** `--auth`, `SITEFILE_SERVE_AUTH`: users and password verifiers (never passwords; absent: none). */
|
|
65
|
+
readonly auth?: readonly AuthEntry[];
|
|
66
|
+
/** `--auth-file`: an htpasswd file, read at every start (absent: none). */
|
|
67
|
+
readonly authFile?: string;
|
|
68
|
+
/** `--max-connections-per-ip` (absent: no limit). */
|
|
69
|
+
readonly maxConnectionsPerIp?: number;
|
|
70
|
+
/** `--random-route`: `base` is a secret, so `/` is a plain 404 (absent: false). */
|
|
71
|
+
readonly hideBase?: boolean;
|
|
72
|
+
/** `--allow-ip` / `--deny-ip` blocks as given (absent: none). */
|
|
73
|
+
readonly allowIp?: readonly string[];
|
|
74
|
+
readonly denyIp?: readonly string[];
|
|
75
|
+
/** `--stop-after`: when the server stops itself (ISO time; absent: never). */
|
|
76
|
+
readonly expires?: string;
|
|
77
|
+
/** `--tls-cert`, `--tls-key`: HTTPS with these PEM files, read at every start (absent: HTTP). */
|
|
78
|
+
readonly tlsCert?: string;
|
|
79
|
+
readonly tlsKey?: string;
|
|
80
|
+
/** `--compress` (absent: false). */
|
|
81
|
+
readonly compress?: boolean;
|
|
82
|
+
/** `--throttle` as given (absent: none). */
|
|
83
|
+
readonly throttle?: string;
|
|
84
|
+
/** `--mime`, `--mime-file`: extension → content type (absent: the built-in table only). */
|
|
85
|
+
readonly mime?: Readonly<Record<string, string>>;
|
|
86
|
+
/** `--country`: what `_redirects` `Country=` conditions match (absent: none matches). */
|
|
87
|
+
readonly country?: string;
|
|
88
|
+
/** `--strict-site-files`: an ignored `_redirects`/`_headers` line stops the server from starting (absent: false). */
|
|
89
|
+
readonly strictSiteFiles?: boolean;
|
|
33
90
|
/** The requested bind address (port 0 = pick a free port). */
|
|
34
91
|
readonly bind: {
|
|
35
92
|
readonly host: string;
|
|
@@ -42,6 +99,8 @@ export interface ServerState {
|
|
|
42
99
|
readonly logFile: string;
|
|
43
100
|
readonly ready: boolean;
|
|
44
101
|
readonly error?: string;
|
|
102
|
+
/** The servers file (`sitefile up`) that started it, by real path; absent for `serve -d`. */
|
|
103
|
+
readonly project?: string;
|
|
45
104
|
}
|
|
46
105
|
export interface ServerView extends ServerState {
|
|
47
106
|
readonly status: 'running' | 'exited';
|
|
@@ -71,15 +130,58 @@ export declare class ServerRegistry {
|
|
|
71
130
|
export declare function pidAlive(pid: number): boolean;
|
|
72
131
|
/** Alive AND answering on its port with its own id header (guards against pid and port reuse). */
|
|
73
132
|
export declare function isRunning(s: ServerState): Promise<boolean>;
|
|
74
|
-
/**
|
|
75
|
-
export
|
|
133
|
+
/** How a directory or archive is read for serving. */
|
|
134
|
+
export interface ServedTreeOptions {
|
|
135
|
+
/** Serve OS metadata files (`__MACOSX/`, `._*`, `Thumbs.db`, `desktop.ini`, ...) too; default false. */
|
|
136
|
+
readonly keepOsMetadata?: boolean;
|
|
137
|
+
/** Told how many OS metadata files were skipped. */
|
|
138
|
+
readonly warn?: (message: string) => void;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
|
|
142
|
+
* and OS metadata files are not served.
|
|
143
|
+
*/
|
|
144
|
+
export declare function loadDirectoryTree(dir: string, options?: ServedTreeOptions): Promise<Tree>;
|
|
76
145
|
/**
|
|
77
146
|
* Load an archive file into a Tree. The format comes from the bytes, never the name: zip, tar, tar.gz,
|
|
78
147
|
* a Web Bundle, or an OCI image archive (a tar holding an OCI layout, as `build -o x.oci.tar` and `save`
|
|
79
148
|
* write it). A zip, tar or Web Bundle is extracted with `limits` (unsafe entries are refused) and served
|
|
80
|
-
* like a directory, without hidden files except `.well-known
|
|
81
|
-
*
|
|
149
|
+
* like a directory, without hidden files except `.well-known` and without OS metadata files (unless
|
|
150
|
+
* `options.keepOsMetadata`); an OCI archive serves its first image's files, like that image from the
|
|
151
|
+
* store, after checking every blob's digest and its site layer against `limits`.
|
|
152
|
+
* `hidden` keeps hidden files and OS metadata (verify and diff compare every file).
|
|
153
|
+
*/
|
|
154
|
+
export declare function loadArchiveTree(file: string, limits?: ArchiveLimits, options?: ServedTreeOptions & {
|
|
155
|
+
readonly hidden?: boolean;
|
|
156
|
+
}): Promise<Tree>;
|
|
157
|
+
/** What a server serves: the tree and, for a zip served in place, where its contents come from. */
|
|
158
|
+
export interface ServedSite {
|
|
159
|
+
readonly tree: Tree;
|
|
160
|
+
readonly content?: SiteContent;
|
|
161
|
+
/** Release the open zip file, if any. */
|
|
162
|
+
close(): void;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* A zip archive file opened for serving in place (#213): its entries are checked and indexed at
|
|
166
|
+
* start (each inflated once, one at a time, for its CRC-32 and digest) and read from the file on
|
|
167
|
+
* each request, so memory does not grow with the archive. The tree is the one {@link loadArchiveTree}
|
|
168
|
+
* serves, with the same errors. Undefined for anything that is not a zip (or a zip holding an OCI layout).
|
|
169
|
+
*/
|
|
170
|
+
export declare function openZipArchive(file: string, limits?: ArchiveLimits, options?: ServedTreeOptions): Promise<ServedSite | undefined>;
|
|
171
|
+
/** {@link loadServedTree}, serving a zip archive in place ({@link openZipArchive}). */
|
|
172
|
+
export declare function loadServedSite(store: Store, source: ServerState['source'], options?: ServedTreeOptions): Promise<ServedSite>;
|
|
173
|
+
/** The tree a server state serves (`options` apply to a directory or archive). */
|
|
174
|
+
export declare function loadServedTree(store: Store, source: ServerState['source'], options?: ServedTreeOptions): Promise<Tree>;
|
|
175
|
+
/**
|
|
176
|
+
* Warn about every `_redirects`/`_headers` line `serve` ignores; with `strict` (`--strict-site-files`)
|
|
177
|
+
* any such line is then an error.
|
|
178
|
+
*/
|
|
179
|
+
export declare function checkSiteFiles(tree: Tree, strict: boolean, warn: (m: string) => void, content?: SiteContent): void;
|
|
180
|
+
/**
|
|
181
|
+
* When a server's files last changed, in Unix seconds (`Last-Modified`): for an image, when it was
|
|
182
|
+
* first stored (never older than its files, unlike the config's `created`, which is the Unix epoch
|
|
183
|
+
* unless SOURCE_DATE_EPOCH is set); for a directory, the newest modification time of the files it
|
|
184
|
+
* serves (hidden entries but `.well-known` are skipped, symbolic links to files followed); for an
|
|
185
|
+
* archive, the file's modification time. Undefined when there is none.
|
|
82
186
|
*/
|
|
83
|
-
export declare function
|
|
84
|
-
/** The tree a server state serves. */
|
|
85
|
-
export declare function loadServedTree(store: Store, source: ServerState['source']): Promise<Tree>;
|
|
187
|
+
export declare function servedLastModified(store: Store, source: ServerState['source']): Promise<number | undefined>;
|
package/lib/src/servers.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { looksLikeWarc, readWarc } from './warc.js';
|
|
1
2
|
import { randomBytes } from 'node:crypto';
|
|
2
3
|
import { promises as fs } from 'node:fs';
|
|
3
4
|
import http from 'node:http';
|
|
5
|
+
import https from 'node:https';
|
|
4
6
|
import path from 'node:path';
|
|
5
7
|
import { sha256 } from './digest.js';
|
|
6
8
|
import { SitefileError } from './errors.js';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
+
import { siteFileWarnings } from './serve-rules.js';
|
|
10
|
+
import { blobPathOf, decodeIndex, extractImageFiles, MEDIA, parseConfig, parseManifest, siteLayerIndices } from './oci.js';
|
|
11
|
+
import { extractArchive, openZipFile, osMetadataWarning, withoutOsMetadata } from './resources/archive.js';
|
|
9
12
|
import { LocalContext } from './resources/local.js';
|
|
10
13
|
import { DEFAULT_ARCHIVE_LIMITS } from './resources/types.js';
|
|
11
14
|
import { Store } from './store.js';
|
|
@@ -96,12 +99,12 @@ export class ServerRegistry {
|
|
|
96
99
|
}
|
|
97
100
|
async view(s) {
|
|
98
101
|
const running = await isRunning(s);
|
|
99
|
-
return { ...s, status: running ? 'running' : 'exited', url: s.ready ? urlOf(s) : '' };
|
|
102
|
+
return { ...s, status: running ? 'running' : 'exited', url: s.ready ? urlOf(s) + (s.base ?? '/').slice(1) : '' };
|
|
100
103
|
}
|
|
101
104
|
}
|
|
102
105
|
function urlOf(s) {
|
|
103
106
|
const shown = s.host === '0.0.0.0' ? '127.0.0.1' : s.host === '::' ? '::1' : s.host;
|
|
104
|
-
return
|
|
107
|
+
return `${s.tlsCert !== undefined ? 'https' : 'http'}://${shown.includes(':') ? `[${shown}]` : shown}:${s.port}/`;
|
|
105
108
|
}
|
|
106
109
|
export function pidAlive(pid) {
|
|
107
110
|
if (!Number.isInteger(pid) || pid <= 0)
|
|
@@ -120,7 +123,9 @@ export async function isRunning(s) {
|
|
|
120
123
|
return false;
|
|
121
124
|
const host = s.host === '0.0.0.0' ? '127.0.0.1' : s.host === '::' ? '::1' : s.host;
|
|
122
125
|
return new Promise((resolve) => {
|
|
123
|
-
|
|
126
|
+
// Over HTTPS the probe skips certificate checks: it only reads this server's own id header.
|
|
127
|
+
const request = s.tlsCert !== undefined ? (o, cb) => https.request({ ...o, rejectUnauthorized: false }, cb) : http.request;
|
|
128
|
+
const req = request({ host, port: s.port, method: 'HEAD', path: '/', headers: { 'x-sitefile-probe': s.id }, timeout: 1500, agent: false }, (res) => {
|
|
124
129
|
res.resume();
|
|
125
130
|
resolve(res.headers['x-sitefile-server'] === s.id);
|
|
126
131
|
});
|
|
@@ -133,34 +138,97 @@ export async function isRunning(s) {
|
|
|
133
138
|
function visible(tree) {
|
|
134
139
|
return Tree.fromFiles(tree.entries().filter(([p]) => p.split('/').every((seg) => !seg.startsWith('.') || seg === '' || seg === '.well-known')));
|
|
135
140
|
}
|
|
136
|
-
/**
|
|
137
|
-
|
|
141
|
+
/** `tree` as served: without OS metadata (unless kept; with a warning naming `origin`) and hidden files except `.well-known`. */
|
|
142
|
+
function served(tree, origin, options) {
|
|
143
|
+
if (!options.keepOsMetadata) {
|
|
144
|
+
const r = withoutOsMetadata(tree);
|
|
145
|
+
if (r.skipped > 0)
|
|
146
|
+
options.warn?.(osMetadataWarning(origin, r.skipped));
|
|
147
|
+
tree = r.tree;
|
|
148
|
+
}
|
|
149
|
+
return visible(tree);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
|
|
153
|
+
* and OS metadata files are not served.
|
|
154
|
+
*/
|
|
155
|
+
export async function loadDirectoryTree(dir, options = {}) {
|
|
138
156
|
const ctx = await LocalContext.open(dir, { sitefileignore: false });
|
|
139
157
|
const { tree } = await ctx.readTree('', 'serve');
|
|
140
|
-
return
|
|
158
|
+
return served(tree, dir, options);
|
|
141
159
|
}
|
|
142
160
|
/**
|
|
143
161
|
* Load an archive file into a Tree. The format comes from the bytes, never the name: zip, tar, tar.gz,
|
|
144
162
|
* a Web Bundle, or an OCI image archive (a tar holding an OCI layout, as `build -o x.oci.tar` and `save`
|
|
145
163
|
* write it). A zip, tar or Web Bundle is extracted with `limits` (unsafe entries are refused) and served
|
|
146
|
-
* like a directory, without hidden files except `.well-known
|
|
147
|
-
*
|
|
164
|
+
* like a directory, without hidden files except `.well-known` and without OS metadata files (unless
|
|
165
|
+
* `options.keepOsMetadata`); an OCI archive serves its first image's files, like that image from the
|
|
166
|
+
* store, after checking every blob's digest and its site layer against `limits`.
|
|
167
|
+
* `hidden` keeps hidden files and OS metadata (verify and diff compare every file).
|
|
148
168
|
*/
|
|
149
|
-
export async function loadArchiveTree(file, limits = DEFAULT_ARCHIVE_LIMITS) {
|
|
169
|
+
export async function loadArchiveTree(file, limits = DEFAULT_ARCHIVE_LIMITS, options = {}) {
|
|
150
170
|
const origin = file;
|
|
151
|
-
const unreadable =
|
|
171
|
+
const unreadable = await checkArchiveFile(file, limits);
|
|
172
|
+
const bytes = new Uint8Array(await fs.readFile(file).catch(() => { throw unreadable(); }));
|
|
173
|
+
const warc = looksLikeWarc(bytes);
|
|
174
|
+
const tree = warc ? readWarc(bytes, origin, limits) : await extractArchive(bytes, origin, limits);
|
|
175
|
+
if (!warc && tree.get('/oci-layout'))
|
|
176
|
+
return ociArchiveTree(tree, origin, limits);
|
|
177
|
+
return options.hidden ? tree : served(tree, origin, options);
|
|
178
|
+
}
|
|
179
|
+
/** The checks every archive file gets before it is read; returns the error for an unreadable file. */
|
|
180
|
+
async function checkArchiveFile(file, limits) {
|
|
181
|
+
const unreadable = () => new SitefileError('E_ARCHIVE', `cannot read '${file}'`);
|
|
152
182
|
const st = await fs.stat(file).catch((e) => {
|
|
153
|
-
throw e.code === 'ENOENT' ? new SitefileError('E_NOT_FOUND', `'${
|
|
183
|
+
throw e.code === 'ENOENT' ? new SitefileError('E_NOT_FOUND', `'${file}' does not exist`) : unreadable();
|
|
154
184
|
});
|
|
155
185
|
if (!st.isFile())
|
|
156
|
-
throw new SitefileError('E_TYPE', `'${
|
|
186
|
+
throw new SitefileError('E_TYPE', `'${file}' is not a file`);
|
|
157
187
|
// The archive is at most its expanded size plus tar framing for every entry.
|
|
158
188
|
if (st.size > limits.maxTotalBytes + (limits.maxEntries + 2) * 4 * 512) {
|
|
159
|
-
throw new SitefileError('E_ARCHIVE_LIMIT', `${
|
|
189
|
+
throw new SitefileError('E_ARCHIVE_LIMIT', `${file}: archive expands beyond ${limits.maxTotalBytes} bytes`);
|
|
160
190
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
191
|
+
return unreadable;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* A zip archive file opened for serving in place (#213): its entries are checked and indexed at
|
|
195
|
+
* start (each inflated once, one at a time, for its CRC-32 and digest) and read from the file on
|
|
196
|
+
* each request, so memory does not grow with the archive. The tree is the one {@link loadArchiveTree}
|
|
197
|
+
* serves, with the same errors. Undefined for anything that is not a zip (or a zip holding an OCI layout).
|
|
198
|
+
*/
|
|
199
|
+
export async function openZipArchive(file, limits = DEFAULT_ARCHIVE_LIMITS, options = {}) {
|
|
200
|
+
const unreadable = await checkArchiveFile(file, limits);
|
|
201
|
+
const head = Buffer.alloc(4);
|
|
202
|
+
try {
|
|
203
|
+
const fh = await fs.open(file, 'r');
|
|
204
|
+
try {
|
|
205
|
+
await fh.read(head, 0, 4, 0);
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
await fh.close();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
throw unreadable();
|
|
213
|
+
}
|
|
214
|
+
const zip = head[0] === 0x50 && head[1] === 0x4b && ((head[2] === 3 && head[3] === 4) || (head[2] === 5 && head[3] === 6));
|
|
215
|
+
if (!zip)
|
|
216
|
+
return undefined;
|
|
217
|
+
const z = await openZipFile(file, file, limits);
|
|
218
|
+
if (z.tree.get('/oci-layout')) {
|
|
219
|
+
z.close();
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return { tree: served(z.tree, file, options), content: z, close: () => z.close() };
|
|
223
|
+
}
|
|
224
|
+
/** {@link loadServedTree}, serving a zip archive in place ({@link openZipArchive}). */
|
|
225
|
+
export async function loadServedSite(store, source, options = {}) {
|
|
226
|
+
if (source.kind === 'archive') {
|
|
227
|
+
const site = await openZipArchive(source.path, DEFAULT_ARCHIVE_LIMITS, options);
|
|
228
|
+
if (site)
|
|
229
|
+
return site;
|
|
230
|
+
}
|
|
231
|
+
return { tree: await loadServedTree(store, source, options), close: () => undefined };
|
|
164
232
|
}
|
|
165
233
|
/** The files of the first image in an extracted OCI layout. */
|
|
166
234
|
async function ociArchiveTree(layout, origin, limits) {
|
|
@@ -202,24 +270,78 @@ async function ociArchiveTree(layout, origin, limits) {
|
|
|
202
270
|
catch {
|
|
203
271
|
throw bad("OCI archive's image config is corrupt");
|
|
204
272
|
}
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
273
|
+
const layers = siteLayerIndices(m, cfg).map((i) => m.layers[i]);
|
|
274
|
+
// An empty list makes extractImageFiles report "not a Sitefile image".
|
|
275
|
+
const blobs = [];
|
|
276
|
+
if (layers.every((l) => l.mediaType === MEDIA.layer || l.mediaType === MEDIA.layerTar)) {
|
|
277
|
+
for (const l of layers) {
|
|
278
|
+
const b = blob(l.digest, l.size);
|
|
279
|
+
// Hold each site layer to the archive limits before it is fully decoded.
|
|
280
|
+
await extractArchive(b, origin, limits);
|
|
281
|
+
blobs.push(b);
|
|
282
|
+
}
|
|
211
283
|
}
|
|
212
|
-
return extractImageFiles(m, cfg,
|
|
284
|
+
return extractImageFiles(m, cfg, layers.length ? blobs : [new Uint8Array(0)], origin);
|
|
213
285
|
}
|
|
214
|
-
/** The tree a server state serves. */
|
|
215
|
-
export async function loadServedTree(store, source) {
|
|
286
|
+
/** The tree a server state serves (`options` apply to a directory or archive). */
|
|
287
|
+
export async function loadServedTree(store, source, options = {}) {
|
|
216
288
|
switch (source.kind) {
|
|
217
289
|
case 'image':
|
|
218
290
|
return store.loadTree(source.imageId);
|
|
219
291
|
case 'dir':
|
|
220
|
-
return loadDirectoryTree(source.path);
|
|
292
|
+
return loadDirectoryTree(source.path, options);
|
|
221
293
|
case 'archive':
|
|
222
|
-
return loadArchiveTree(source.path);
|
|
294
|
+
return loadArchiveTree(source.path, DEFAULT_ARCHIVE_LIMITS, options);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Warn about every `_redirects`/`_headers` line `serve` ignores; with `strict` (`--strict-site-files`)
|
|
299
|
+
* any such line is then an error.
|
|
300
|
+
*/
|
|
301
|
+
export function checkSiteFiles(tree, strict, warn, content) {
|
|
302
|
+
const ignored = siteFileWarnings(tree, content);
|
|
303
|
+
for (const m of ignored)
|
|
304
|
+
warn(m);
|
|
305
|
+
if (strict && ignored.length > 0) {
|
|
306
|
+
const n = ignored.length;
|
|
307
|
+
throw new SitefileError('E_VALIDATION', `${n} line${n === 1 ? '' : 's'} of _redirects/_headers ${n === 1 ? 'is' : 'are'} ignored (--strict-site-files)`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* When a server's files last changed, in Unix seconds (`Last-Modified`): for an image, when it was
|
|
312
|
+
* first stored (never older than its files, unlike the config's `created`, which is the Unix epoch
|
|
313
|
+
* unless SOURCE_DATE_EPOCH is set); for a directory, the newest modification time of the files it
|
|
314
|
+
* serves (hidden entries but `.well-known` are skipped, symbolic links to files followed); for an
|
|
315
|
+
* archive, the file's modification time. Undefined when there is none.
|
|
316
|
+
*/
|
|
317
|
+
export async function servedLastModified(store, source) {
|
|
318
|
+
const secs = (ms) => Math.floor(ms / 1000);
|
|
319
|
+
switch (source.kind) {
|
|
320
|
+
case 'image': {
|
|
321
|
+
const ms = Date.parse((await store.details(source.imageId)).created);
|
|
322
|
+
return Number.isNaN(ms) ? undefined : secs(ms);
|
|
323
|
+
}
|
|
324
|
+
case 'archive':
|
|
325
|
+
return secs((await fs.stat(source.path)).mtimeMs);
|
|
326
|
+
case 'dir': {
|
|
327
|
+
let newest;
|
|
328
|
+
const walk = async (dir) => {
|
|
329
|
+
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
330
|
+
if (e.name.startsWith('.') && e.name !== '.well-known')
|
|
331
|
+
continue;
|
|
332
|
+
const p = path.join(dir, e.name);
|
|
333
|
+
if (e.isDirectory())
|
|
334
|
+
await walk(p);
|
|
335
|
+
else if (e.isFile() || e.isSymbolicLink()) {
|
|
336
|
+
const st = await fs.stat(p).catch(() => undefined);
|
|
337
|
+
if (st?.isFile())
|
|
338
|
+
newest = Math.max(newest ?? 0, secs(st.mtimeMs));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
await walk(source.path);
|
|
343
|
+
return newest;
|
|
344
|
+
}
|
|
223
345
|
}
|
|
224
346
|
}
|
|
225
347
|
//# sourceMappingURL=servers.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Tree } from './tree.js';
|
|
2
|
+
/** `EXPORT … AS html`: the page with every asset inlined as a data: URI. */
|
|
3
|
+
export declare function writeSingleFile(tree: Tree, page?: string): Uint8Array;
|
|
4
|
+
/** The default MHTML base URL (no EXPORT BASE or --base-url). */
|
|
5
|
+
export declare const MHTML_DEFAULT_BASE = "https://site.invalid/";
|
|
6
|
+
/**
|
|
7
|
+
* `EXPORT … AS mhtml [BASE <url>]`: the page and its assets as MHTML (RFC 2557 multipart/related, as
|
|
8
|
+
* Chrome saves "Webpage, Single File"): each part base64 with its Content-Type and an absolute
|
|
9
|
+
* Content-Location under the base URL (default `https://site.invalid/`), the page first. References
|
|
10
|
+
* are kept as written; the browser resolves them against the page's Content-Location.
|
|
11
|
+
*/
|
|
12
|
+
export declare function writeMhtml(tree: Tree, page?: string, baseUrl?: string): Uint8Array;
|