@johnhenry/sitefile 0.0.2 → 0.0.4
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 +516 -0
- package/README.md +59 -9
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +19 -0
- package/lib/src/canonical.js +60 -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 +6 -1
- package/lib/src/cli/index.js +34 -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 +119 -8
- package/lib/src/cli/servers.d.ts +130 -1
- package/lib/src/cli/servers.js +754 -72
- 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 +231 -24
- 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/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -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 +126 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +189 -7
- package/lib/src/language/validate.js +24 -0
- package/lib/src/links.d.ts +47 -0
- package/lib/src/links.js +289 -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 +87 -2
- package/lib/src/planner.js +189 -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 +419 -0
- package/lib/src/resources/archive.d.ts +37 -1
- package/lib/src/resources/archive.js +353 -71
- 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 +33 -0
- package/lib/src/serve-auth.js +120 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +529 -11
- package/lib/src/server.js +1439 -57
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +115 -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 +58 -0
- package/lib/src/site.js +216 -5
- 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
package/lib/src/cli/index.js
CHANGED
|
@@ -5,12 +5,16 @@ import { serverCommands, serverSubcommands } from './servers.js';
|
|
|
5
5
|
import { cacheSubcommands } from './cache.js';
|
|
6
6
|
import { vendorCommands } from './vendor.js';
|
|
7
7
|
import { outdatedCommands } from './outdated.js';
|
|
8
|
+
import { hostsCommands } from './hosts.js';
|
|
8
9
|
import { bakeCommands } from './bake.js';
|
|
10
|
+
import { upCommands } from './up.js';
|
|
11
|
+
import { importConfigCommands } from './import-config.js';
|
|
12
|
+
import { integrityCommands } from './integrity.js';
|
|
9
13
|
/**
|
|
10
14
|
* Image-store and site-server commands. They live outside cli.ts' build/validate/inspect
|
|
11
15
|
* parser: each has its own options and `--help`.
|
|
12
16
|
*/
|
|
13
|
-
const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...bakeCommands].filter(([k]) => !k.includes(' ')));
|
|
17
|
+
const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...hostsCommands, ...bakeCommands, ...integrityCommands, ...upCommands, ...importConfigCommands].filter(([k]) => !k.includes(' ')));
|
|
14
18
|
export const EXTRA_COMMANDS = [...TOP.keys(), 'image', 'server', 'cache', 'lsp'];
|
|
15
19
|
/**
|
|
16
20
|
* The language server exists only in the Rust implementation (a tooling
|
|
@@ -31,10 +35,23 @@ Images (local store: $SITEFILE_HOME or ~/.sitefile):
|
|
|
31
35
|
sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry
|
|
32
36
|
sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)
|
|
33
37
|
|
|
38
|
+
Integrity:
|
|
39
|
+
sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,
|
|
40
|
+
and their Merkle root (save --manifest too)
|
|
41
|
+
sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,
|
|
42
|
+
changed and extra files (exit 1 on any)
|
|
43
|
+
sitefile diff <a> <b> [--json] files added, removed and changed between two images,
|
|
44
|
+
directories or archives, and _redirects/_headers rules
|
|
45
|
+
|
|
34
46
|
Variants:
|
|
35
47
|
sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from
|
|
36
48
|
sitefile.bake.yaml; --print shows the plan
|
|
37
49
|
|
|
50
|
+
Host config files:
|
|
51
|
+
sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,
|
|
52
|
+
staticwebapp.config.json, wrangler.toml or .htaccess
|
|
53
|
+
into _redirects and _headers
|
|
54
|
+
|
|
38
55
|
Offline builds:
|
|
39
56
|
sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into
|
|
40
57
|
vendor/sitefile; builds then read them from there
|
|
@@ -43,6 +60,10 @@ Pins:
|
|
|
43
60
|
sitefile outdated [context] [--json] compare remote imports and the BASE image with
|
|
44
61
|
their pins (never changes anything)
|
|
45
62
|
|
|
63
|
+
Network:
|
|
64
|
+
sitefile hosts [context] [--json] list the hosts a build would contact and whether
|
|
65
|
+
--allow-hosts/--network strict allow them (no fetch)
|
|
66
|
+
|
|
46
67
|
Build cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):
|
|
47
68
|
sitefile cache info [--json] location, entries, size
|
|
48
69
|
sitefile cache prune [--older-than <days>] delete cached results
|
|
@@ -55,6 +76,9 @@ Serving sites (detached servers are tracked by name):
|
|
|
55
76
|
sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload
|
|
56
77
|
sitefile servers [-a] [--json] list servers (alias: server ls)
|
|
57
78
|
sitefile server stop|rm [-f]|restart|logs [-f] <name|id>
|
|
79
|
+
sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)
|
|
80
|
+
sitefile down [-f file] stop and remove the servers it started
|
|
81
|
+
sitefile ps [-f file] [--json] list them: running, exited or not created
|
|
58
82
|
|
|
59
83
|
Editor support:
|
|
60
84
|
sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)
|
|
@@ -90,6 +114,14 @@ export async function runExtraCommand(argv) {
|
|
|
90
114
|
const cmd = name === undefined ? undefined : TOP.get(name);
|
|
91
115
|
if (!cmd)
|
|
92
116
|
return usageError(`unknown command '${name ?? ''}'`);
|
|
93
|
-
return runCommand(cmd, rest);
|
|
117
|
+
return runCommand(cmd, name === 'serve' ? optionalOpen(rest) : rest);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
|
|
121
|
+
* or `--sync` (before `--`) is `--open=`, `--sync=`.
|
|
122
|
+
*/
|
|
123
|
+
export function optionalOpen(args) {
|
|
124
|
+
const end = args.indexOf('--');
|
|
125
|
+
return args.map((a, i) => ((a === '--open' || a === '--sync') && (end === -1 || i < end) ? `${a}=` : a));
|
|
94
126
|
}
|
|
95
127
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { SitefileError } from '../errors.js';
|
|
3
|
+
import { diffText, diffTrees, loadTarget, manifestOf, parseManifest, pathInside, resolveTarget, verifyText, verifyTree } from '../integrity.js';
|
|
4
|
+
import { Store } from '../store.js';
|
|
5
|
+
import { requireArgs, str, usage } from './common.js';
|
|
6
|
+
const openStore = () => {
|
|
7
|
+
let s;
|
|
8
|
+
return () => (s ??= Store.open());
|
|
9
|
+
};
|
|
10
|
+
const verify = {
|
|
11
|
+
name: 'verify',
|
|
12
|
+
summary: 'check a directory, archive or image against a file manifest',
|
|
13
|
+
usage: 'verify <dir|archive|ref|id> [--manifest <file>] [--json]',
|
|
14
|
+
description: 'Compare a deployed or extracted copy with the manifest written by "build --manifest" or "save --manifest":\nevery file the manifest lists must be there with the same size and SHA-256, and no other file may be.\nPrints one line per difference (missing, changed, extra) and fails with E_INTEGRITY when there is any.\nA directory is read like a build context (hidden files count; .git is skipped); an archive is read from\nits bytes (zip, tar, tar.gz, wbn, OCI archive). A manifest file inside the verified directory is not\ncounted as extra. Without --manifest the target must be an image: its stored blobs are checked.',
|
|
15
|
+
flags: ['--manifest <file> the manifest to check against (JSON, see docs/CLI.md)', '--json machine-readable report'],
|
|
16
|
+
options: { manifest: { type: 'string' }, json: { type: 'boolean' } },
|
|
17
|
+
async run(v, pos) {
|
|
18
|
+
requireArgs(pos, 1, 1, 'a directory, archive file or image reference');
|
|
19
|
+
const arg = pos[0];
|
|
20
|
+
const store = openStore();
|
|
21
|
+
const target = await resolveTarget(arg, store);
|
|
22
|
+
const manifestFile = str(v.manifest);
|
|
23
|
+
if (manifestFile === '')
|
|
24
|
+
usage('--manifest expects a file path');
|
|
25
|
+
if (manifestFile === undefined && target.kind !== 'image')
|
|
26
|
+
usage('verify needs --manifest <file> for a directory or an archive');
|
|
27
|
+
const tree = await loadTarget(target, store);
|
|
28
|
+
let manifest;
|
|
29
|
+
let ignore;
|
|
30
|
+
if (manifestFile !== undefined) {
|
|
31
|
+
const bytes = await fs.readFile(manifestFile).catch((e) => {
|
|
32
|
+
throw new SitefileError(e.code === 'ENOENT' ? 'E_NOT_FOUND' : 'E_INTEGRITY', `cannot read the manifest '${manifestFile}'`);
|
|
33
|
+
});
|
|
34
|
+
manifest = parseManifest(new Uint8Array(bytes), manifestFile);
|
|
35
|
+
if (target.kind === 'dir')
|
|
36
|
+
ignore = await pathInside(target.path, manifestFile);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
manifest = manifestOf(tree); // loadTree checked every blob against its digest
|
|
40
|
+
}
|
|
41
|
+
const r = verifyTree(tree, manifest, ignore);
|
|
42
|
+
process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : r.ok ? `OK: ${r.files} file${r.files === 1 ? '' : 's'} match ${r.root}\n` : verifyText(r));
|
|
43
|
+
if (!r.ok) {
|
|
44
|
+
const message = `'${arg}' does not match the manifest: ${r.missing.length} missing, ${r.changed.length} changed, ${r.extra.length} extra`;
|
|
45
|
+
// With --json the report above is the one document on stdout (it already says ok: false),
|
|
46
|
+
// so the error goes to stderr only instead of through the generic --json error output.
|
|
47
|
+
if (v.json) {
|
|
48
|
+
process.stderr.write(`error[E_INTEGRITY]: ${message}\n`);
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
throw new SitefileError('E_INTEGRITY', message);
|
|
52
|
+
}
|
|
53
|
+
return 0;
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
const diff = {
|
|
57
|
+
name: 'diff',
|
|
58
|
+
summary: 'files changed between two images, directories or archives',
|
|
59
|
+
usage: 'diff <a> <b> [--json] [--exit-code]',
|
|
60
|
+
description: 'List the files added (A), removed (D) and changed (C: content or mode) going from <a> to <b>, with their\nsizes, then the rules added (+) and removed (-) in _redirects and _headers. Each side is a directory, an\narchive file (zip, tar, tar.gz, wbn, OCI archive) or an image reference or ID, read as "sitefile verify"\nreads it (hidden files count). Digests, not timestamps, decide what changed.',
|
|
61
|
+
flags: ['--json machine-readable report (sizes in bytes, digests, modes)', '--exit-code exit 1 when the two differ (default 0 either way)'],
|
|
62
|
+
options: { json: { type: 'boolean' }, 'exit-code': { type: 'boolean' } },
|
|
63
|
+
async run(v, pos) {
|
|
64
|
+
requireArgs(pos, 2, 2, 'two images, directories or archive files');
|
|
65
|
+
const store = openStore();
|
|
66
|
+
const [a, b] = [await resolveTarget(pos[0], store), await resolveTarget(pos[1], store)];
|
|
67
|
+
const r = diffTrees(await loadTarget(a, store), await loadTarget(b, store));
|
|
68
|
+
process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : diffText(r));
|
|
69
|
+
const same = !r.added.length && !r.removed.length && !r.changed.length && !Object.keys(r.rules).length;
|
|
70
|
+
return v['exit-code'] && !same ? 1 : 0;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
export const integrityCommands = new Map([
|
|
74
|
+
['verify', verify],
|
|
75
|
+
['diff', diff],
|
|
76
|
+
]);
|
|
77
|
+
//# sourceMappingURL=integrity.js.map
|
package/lib/src/cli/network.d.ts
CHANGED
|
@@ -16,6 +16,13 @@ export declare const NETWORK_OPTIONS: {
|
|
|
16
16
|
readonly type: 'string';
|
|
17
17
|
readonly multiple: true;
|
|
18
18
|
};
|
|
19
|
+
readonly network: {
|
|
20
|
+
readonly type: 'string';
|
|
21
|
+
};
|
|
22
|
+
readonly 'allow-secret-host': {
|
|
23
|
+
readonly type: 'string';
|
|
24
|
+
readonly multiple: true;
|
|
25
|
+
};
|
|
19
26
|
readonly 'connect-timeout': {
|
|
20
27
|
readonly type: 'string';
|
|
21
28
|
};
|
package/lib/src/cli/network.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { SitefileError } from '../errors.js';
|
|
2
|
-
import { mergeNetwork, networkFromEnv, networkProblem, splitList } from '../resources/network.js';
|
|
2
|
+
import { mergeNetwork, networkFromEnv, networkProblem, parseNetworkMode, splitList } from '../resources/network.js';
|
|
3
3
|
/** parseArgs options for the network flags (build, validate, inspect, graph, why, pull, push, vendor, outdated). */
|
|
4
4
|
export const NETWORK_OPTIONS = {
|
|
5
5
|
proxy: { type: 'string' },
|
|
6
6
|
'no-proxy': { type: 'string', multiple: true },
|
|
7
7
|
'allow-hosts': { type: 'string', multiple: true },
|
|
8
8
|
'deny-hosts': { type: 'string', multiple: true },
|
|
9
|
+
network: { type: 'string' },
|
|
10
|
+
'allow-secret-host': { type: 'string', multiple: true },
|
|
9
11
|
'connect-timeout': { type: 'string' },
|
|
10
12
|
'read-timeout': { type: 'string' },
|
|
11
13
|
};
|
|
@@ -16,12 +18,17 @@ export function networkHelp(width) {
|
|
|
16
18
|
['--no-proxy <hosts>', ['hosts reached directly, not through the proxy (NO_PROXY syntax; repeatable,', 'comma-separated; also $SITEFILE_NO_PROXY)']],
|
|
17
19
|
['--allow-hosts <hosts>', ['contact only hosts matching these patterns (repeatable, comma-separated;', 'also $SITEFILE_ALLOW_HOSTS)']],
|
|
18
20
|
['--deny-hosts <hosts>', ['never contact hosts matching these patterns; beats --allow-hosts', '(repeatable, comma-separated; also $SITEFILE_DENY_HOSTS)']],
|
|
21
|
+
['--network <mode>', ['open (default) or strict: every host must match --allow-hosts, even with none', 'given (also $SITEFILE_NETWORK)']],
|
|
22
|
+
['--allow-secret-host <id=host>', ['in strict mode, let IMPORT ... SECRET <id> send its secret to this host', '(a host pattern; repeatable)']],
|
|
19
23
|
['--connect-timeout <ms>', ['time limit for opening each connection (also $SITEFILE_FETCH_TIMEOUT)']],
|
|
20
24
|
['--read-timeout <ms>', ['longest wait for data on a connection (also $SITEFILE_FETCH_TIMEOUT)']],
|
|
21
25
|
];
|
|
22
26
|
const out = [];
|
|
23
27
|
for (const [flag, lines] of rows) {
|
|
24
|
-
|
|
28
|
+
// A flag wider than the column gets a line of its own.
|
|
29
|
+
if (flag.length >= width)
|
|
30
|
+
out.push(flag);
|
|
31
|
+
lines.forEach((l, i) => out.push(`${(i === 0 && flag.length < width ? flag : '').padEnd(width)}${l}`));
|
|
25
32
|
}
|
|
26
33
|
return out;
|
|
27
34
|
}
|
|
@@ -44,10 +51,14 @@ export function networkOption(v, env = process.env) {
|
|
|
44
51
|
noProxy: strings(v['no-proxy']).flatMap(splitList),
|
|
45
52
|
allowHosts: strings(v['allow-hosts']).flatMap(splitList),
|
|
46
53
|
denyHosts: strings(v['deny-hosts']).flatMap(splitList),
|
|
54
|
+
secretHosts: strings(v['allow-secret-host']).flatMap(splitList),
|
|
47
55
|
connectTimeoutMs: ms(typeof v['connect-timeout'] === 'string' ? v['connect-timeout'] : undefined, '--connect-timeout'),
|
|
48
56
|
readTimeoutMs: ms(typeof v['read-timeout'] === 'string' ? v['read-timeout'] : undefined, '--read-timeout'),
|
|
49
57
|
};
|
|
50
|
-
const
|
|
58
|
+
const fromEnv = networkFromEnv(env);
|
|
59
|
+
// --network replaces SITEFILE_NETWORK (--network open turns an inherited strict mode off).
|
|
60
|
+
const mode = typeof v.network === 'string' ? (parseNetworkMode(v.network === '' ? '?' : v.network, '--network') ?? false) : undefined;
|
|
61
|
+
const merged = mergeNetwork(mode === undefined ? fromEnv : { ...fromEnv, strict: undefined }, mode ? { ...flags, strict: true } : flags);
|
|
51
62
|
const problem = networkProblem(merged);
|
|
52
63
|
if (problem)
|
|
53
64
|
throw new SitefileError('E_USAGE', problem);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `serve` in a terminal (issue #224): single keys while serving in the foreground, `--open[=path]` and
|
|
3
|
+
* `--qr`. Ported as rust/src/cli/serve_keys.rs (the same keys, messages and QR codes).
|
|
4
|
+
*/
|
|
5
|
+
export type KeyAction = 'open' | 'urls' | 'restart' | 'clear' | 'quit' | 'help';
|
|
6
|
+
/** What a key does (letters in either case; Ctrl-C and Ctrl-D quit), or undefined. */
|
|
7
|
+
export declare function keyAction(byte: number): KeyAction | undefined;
|
|
8
|
+
export declare const KEYS_HINT = "Press h for keys\n";
|
|
9
|
+
export declare const KEYS_HELP = "Keys: o open in the browser, u show the URLs, r rebuild (--watch) or re-read the directory, c clear the screen, q quit, h this help\n";
|
|
10
|
+
export declare const CLEAR = "\u001B[2J\u001B[3J\u001B[H";
|
|
11
|
+
/**
|
|
12
|
+
* The URLs to show (below `serve --base`, `https://` for a TLS server): the local one, and when bound to every
|
|
13
|
+
* interface the same network URLs as the start line (one per interface address, IPv4 first).
|
|
14
|
+
*/
|
|
15
|
+
export declare function serveUrls(host: string, port: number, base?: string, scheme?: 'http' | 'https'): {
|
|
16
|
+
local: string;
|
|
17
|
+
network: string[];
|
|
18
|
+
};
|
|
19
|
+
/** `u`: the URLs, and a QR code of the first network URL when there is one. */
|
|
20
|
+
export declare function urlsText(urls: {
|
|
21
|
+
local: string;
|
|
22
|
+
network: readonly string[];
|
|
23
|
+
}): string;
|
|
24
|
+
/** `--qr`: the URL and its QR code. */
|
|
25
|
+
export declare function qrText(url: string): string;
|
|
26
|
+
/** `--open=<path>` (or `--open`, `/`) joined to the server's URL. */
|
|
27
|
+
export declare function openUrl(base: string, path: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* Open `url` in the browser: `$BROWSER` when set (a program, run with the URL as its only argument, no
|
|
30
|
+
* shell), else `open` (macOS), `rundll32 url.dll,FileProtocolHandler` (Windows) or `xdg-open`. A failure is
|
|
31
|
+
* a warning: the server keeps running.
|
|
32
|
+
*/
|
|
33
|
+
export declare function openBrowser(url: string, warn: (m: string) => void): void;
|
|
34
|
+
/**
|
|
35
|
+
* Read single keys from stdin while serving: when stdin is a terminal (raw mode), or when
|
|
36
|
+
* `SITEFILE_SERVE_KEYS=1` (tests drive it through a pipe). Returns a function that stops reading and
|
|
37
|
+
* restores the terminal, or undefined when keys are off.
|
|
38
|
+
*/
|
|
39
|
+
export declare function readKeys(onAction: (a: KeyAction) => void): (() => void) | undefined;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { encodeQr, qrTerminal } from '../qr.js';
|
|
3
|
+
import { formatUrl, networkUrls } from '../server.js';
|
|
4
|
+
/** What a key does (letters in either case; Ctrl-C and Ctrl-D quit), or undefined. */
|
|
5
|
+
export function keyAction(byte) {
|
|
6
|
+
if (byte === 3 || byte === 4)
|
|
7
|
+
return 'quit';
|
|
8
|
+
switch (String.fromCharCode(byte).toLowerCase()) {
|
|
9
|
+
case 'o':
|
|
10
|
+
return 'open';
|
|
11
|
+
case 'u':
|
|
12
|
+
return 'urls';
|
|
13
|
+
case 'r':
|
|
14
|
+
return 'restart';
|
|
15
|
+
case 'c':
|
|
16
|
+
return 'clear';
|
|
17
|
+
case 'q':
|
|
18
|
+
return 'quit';
|
|
19
|
+
case 'h':
|
|
20
|
+
return 'help';
|
|
21
|
+
default:
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export const KEYS_HINT = 'Press h for keys\n';
|
|
26
|
+
export const KEYS_HELP = 'Keys: o open in the browser, u show the URLs, r rebuild (--watch) or re-read the directory, c clear the screen, q quit, h this help\n';
|
|
27
|
+
export const CLEAR = '\x1b[2J\x1b[3J\x1b[H';
|
|
28
|
+
const isWildcard = (h) => h === '0.0.0.0' || h === '::';
|
|
29
|
+
/**
|
|
30
|
+
* The URLs to show (below `serve --base`, `https://` for a TLS server): the local one, and when bound to every
|
|
31
|
+
* interface the same network URLs as the start line (one per interface address, IPv4 first).
|
|
32
|
+
*/
|
|
33
|
+
export function serveUrls(host, port, base = '/', scheme = 'http') {
|
|
34
|
+
const path = base.slice(1);
|
|
35
|
+
const local = formatUrl(host, port, scheme) + path;
|
|
36
|
+
return { local, network: isWildcard(host) ? networkUrls(host, port, scheme).map((u) => u + path) : [] };
|
|
37
|
+
}
|
|
38
|
+
/** `u`: the URLs, and a QR code of the first network URL when there is one. */
|
|
39
|
+
export function urlsText(urls) {
|
|
40
|
+
let out = ` Local: ${urls.local}\n`;
|
|
41
|
+
for (const n of urls.network)
|
|
42
|
+
out += ` Network: ${n}\n`;
|
|
43
|
+
if (urls.network[0] !== undefined)
|
|
44
|
+
out += qrText(urls.network[0]);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/** `--qr`: the URL and its QR code. */
|
|
48
|
+
export function qrText(url) {
|
|
49
|
+
const code = encodeQr(url);
|
|
50
|
+
return code ? qrTerminal(code) : '';
|
|
51
|
+
}
|
|
52
|
+
/** `--open=<path>` (or `--open`, `/`) joined to the server's URL. */
|
|
53
|
+
export function openUrl(base, path) {
|
|
54
|
+
return base + path.replace(/^\/+/, '');
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Open `url` in the browser: `$BROWSER` when set (a program, run with the URL as its only argument, no
|
|
58
|
+
* shell), else `open` (macOS), `rundll32 url.dll,FileProtocolHandler` (Windows) or `xdg-open`. A failure is
|
|
59
|
+
* a warning: the server keeps running.
|
|
60
|
+
*/
|
|
61
|
+
export function openBrowser(url, warn) {
|
|
62
|
+
const browser = process.env['BROWSER'];
|
|
63
|
+
const [cmd, args] = browser !== undefined && browser !== ''
|
|
64
|
+
? [browser, [url]]
|
|
65
|
+
: process.platform === 'darwin'
|
|
66
|
+
? ['open', [url]]
|
|
67
|
+
: process.platform === 'win32'
|
|
68
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
69
|
+
: ['xdg-open', [url]];
|
|
70
|
+
try {
|
|
71
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
72
|
+
child.on('error', (e) => warn(`cannot open the browser (${cmd}): ${e.message}`));
|
|
73
|
+
child.unref();
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
warn(`cannot open the browser (${cmd}): ${e.message}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Read single keys from stdin while serving: when stdin is a terminal (raw mode), or when
|
|
81
|
+
* `SITEFILE_SERVE_KEYS=1` (tests drive it through a pipe). Returns a function that stops reading and
|
|
82
|
+
* restores the terminal, or undefined when keys are off.
|
|
83
|
+
*/
|
|
84
|
+
export function readKeys(onAction) {
|
|
85
|
+
const tty = !!process.stdin.isTTY;
|
|
86
|
+
if (!tty && process.env['SITEFILE_SERVE_KEYS'] !== '1')
|
|
87
|
+
return undefined;
|
|
88
|
+
if (tty)
|
|
89
|
+
process.stdin.setRawMode(true);
|
|
90
|
+
const onData = (chunk) => {
|
|
91
|
+
for (const b of chunk) {
|
|
92
|
+
const a = keyAction(b);
|
|
93
|
+
if (a)
|
|
94
|
+
onAction(a);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
process.stdin.on('data', onData);
|
|
98
|
+
process.stdin.resume();
|
|
99
|
+
return () => {
|
|
100
|
+
process.stdin.off('data', onData);
|
|
101
|
+
if (tty)
|
|
102
|
+
process.stdin.setRawMode(false);
|
|
103
|
+
process.stdin.pause();
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=serve-keys.js.map
|
|
@@ -1,40 +1,151 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Detached server process spawned by `sitefile serve -d` / `restart`.
|
|
3
3
|
// Usage: node serve-worker.js <server id>. State and logs live in $SITEFILE_HOME/servers.
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
4
5
|
import { SitefileError } from '../errors.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
6
|
+
import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
|
|
7
|
+
import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
|
|
8
|
+
import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
|
|
9
|
+
import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
|
|
10
|
+
let json = false; // `--log-format json`: every line is a JSON object
|
|
11
|
+
const stamp = (m) => {
|
|
12
|
+
const ts = new Date().toISOString();
|
|
13
|
+
process.stdout.write(json ? `${m.startsWith('{') ? m : jsonLogLine(ts, m)}\n` : `${ts} ${m}\n`);
|
|
14
|
+
};
|
|
8
15
|
async function main() {
|
|
9
16
|
const id = process.argv[2] ?? '';
|
|
10
17
|
const reg = await ServerRegistry.open();
|
|
11
18
|
const state = await reg.read(id);
|
|
12
19
|
if (!state)
|
|
13
20
|
throw new SitefileError('E_SERVER', `no state for server '${id}'`);
|
|
21
|
+
json = state.logFormat === 'json';
|
|
14
22
|
try {
|
|
15
|
-
const
|
|
16
|
-
|
|
23
|
+
const left = state.expires === undefined ? undefined : Date.parse(state.expires) - Date.now();
|
|
24
|
+
if (left !== undefined && left <= 0)
|
|
25
|
+
throw new SitefileError('E_SERVER', `server expired at ${state.expires} (--stop-after)`);
|
|
26
|
+
const ipRules = state.allowIp !== undefined || state.denyIp !== undefined ? { allow: (state.allowIp ?? []).flatMap((t) => parseCidr(t) ?? []), deny: (state.denyIp ?? []).flatMap((t) => parseCidr(t) ?? []) } : undefined;
|
|
27
|
+
const loopback = state.bind.host === 'localhost' || state.bind.host === '::1' || /^127\./.test(state.bind.host);
|
|
28
|
+
const { tree, content } = await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
|
|
29
|
+
if (routingFor(state)?.siteFiles !== false)
|
|
30
|
+
checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
|
|
31
|
+
let modified = await servedLastModified(reg.store, state.source);
|
|
32
|
+
let current = tree;
|
|
33
|
+
// `-d --watch`: the directory is re-read on change and open pages reload (or swap stylesheets).
|
|
34
|
+
const live = state.watch && state.source.kind === 'dir' ? new LiveReload(state.sync === 'nav' || state.sync === 'scroll' ? { sync: state.sync } : {}) : undefined;
|
|
35
|
+
const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
|
|
36
|
+
const server = createSiteServer(() => current, { ...(live ? { liveReload: live } : {}), spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
|
|
17
37
|
const addr = await listen(server, state.bind.host, state.bind.port);
|
|
18
38
|
await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
|
|
19
|
-
|
|
39
|
+
const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
|
|
40
|
+
const url = `${root}${(state.base ?? '/').slice(1)}`;
|
|
41
|
+
if (json)
|
|
42
|
+
stamp(startedLogLine(new Date().toISOString(), state.image, tree.size, url));
|
|
43
|
+
else
|
|
44
|
+
stamp(`serving ${state.image} (${tree.size} files) at ${url}`);
|
|
45
|
+
const unwatch = live
|
|
46
|
+
? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
|
|
47
|
+
current = next;
|
|
48
|
+
modified = lastModified;
|
|
49
|
+
}, () => current)
|
|
50
|
+
: () => undefined;
|
|
20
51
|
const stop = (signal) => () => {
|
|
21
|
-
|
|
52
|
+
unwatch();
|
|
53
|
+
if (json)
|
|
54
|
+
stamp(stoppedLogLine(new Date().toISOString(), signal));
|
|
55
|
+
else
|
|
56
|
+
stamp(`received ${signal}, shutting down`);
|
|
22
57
|
void closeServer(server).then(async () => {
|
|
23
58
|
await reg.update(id, { ready: false }).catch(() => undefined);
|
|
24
59
|
process.exit(0);
|
|
25
60
|
});
|
|
26
61
|
setTimeout(() => process.exit(0), 3000).unref();
|
|
27
62
|
};
|
|
63
|
+
if (left !== undefined) {
|
|
64
|
+
setTimeout(() => {
|
|
65
|
+
unwatch();
|
|
66
|
+
if (json)
|
|
67
|
+
stamp(stoppedLogLine(new Date().toISOString(), 'expired'));
|
|
68
|
+
else
|
|
69
|
+
stamp('--stop-after reached, shutting down');
|
|
70
|
+
void closeServer(server).then(async () => {
|
|
71
|
+
await reg.update(id, { ready: false }).catch(() => undefined);
|
|
72
|
+
process.exit(0);
|
|
73
|
+
});
|
|
74
|
+
setTimeout(() => process.exit(0), 3000).unref();
|
|
75
|
+
}, Math.min(left, 2 ** 31 - 1));
|
|
76
|
+
}
|
|
28
77
|
process.on('SIGTERM', stop('SIGTERM'));
|
|
29
78
|
process.on('SIGINT', stop('SIGINT'));
|
|
30
79
|
}
|
|
31
80
|
catch (e) {
|
|
32
81
|
const message = e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`;
|
|
33
|
-
|
|
82
|
+
const ts = new Date().toISOString();
|
|
83
|
+
process.stderr.write(json ? `${jsonLogLine(ts, message)}\n` : `${ts} ${message}\n`);
|
|
34
84
|
await reg.update(id, { pid: 0, ready: false, error: message }).catch(() => undefined);
|
|
35
85
|
process.exit(1);
|
|
36
86
|
}
|
|
37
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* `-d --watch`: watch the served directory (file system events, or polling every `state.pollMs`) and,
|
|
90
|
+
* once changes settle, read it again: a good read is served and open pages are told what changed; a
|
|
91
|
+
* failed one is logged, shown in open pages, and the last good copy stays. Returns a function that stops watching.
|
|
92
|
+
*/
|
|
93
|
+
async function watchDirectory(reg, state, live, stamp, swap, current) {
|
|
94
|
+
if (state.source.kind !== 'dir')
|
|
95
|
+
return () => undefined;
|
|
96
|
+
const source = state.source;
|
|
97
|
+
const root = source.path;
|
|
98
|
+
const ignored = [await resolveReal(reg.store.home)];
|
|
99
|
+
const relevant = (p) => !isIgnoredChange(p, [root], ignored);
|
|
100
|
+
const warn = (m) => stamp(`warning: ${m}`);
|
|
101
|
+
const siteFiles = routingFor(state)?.siteFiles !== false;
|
|
102
|
+
/** The site-file warnings last logged: a re-read repeats them only when they change. */
|
|
103
|
+
const warningsOf = (t) => {
|
|
104
|
+
const shown = [];
|
|
105
|
+
if (siteFiles)
|
|
106
|
+
checkSiteFiles(t, false, (m) => shown.push(m));
|
|
107
|
+
return shown.join('\n');
|
|
108
|
+
};
|
|
109
|
+
let lastWarnings = warningsOf(current());
|
|
110
|
+
const scheduler = new RebuildScheduler(async () => {
|
|
111
|
+
stamp('Change detected, re-reading');
|
|
112
|
+
live.send(BUILDING_EVENT);
|
|
113
|
+
try {
|
|
114
|
+
const next = await loadServedTree(reg.store, source, { keepOsMetadata: !!state.keepOsMetadata, warn });
|
|
115
|
+
stamp(`Read ${next.size} file${next.size === 1 ? '' : 's'} (${next.digest()})`);
|
|
116
|
+
const warnings = warningsOf(next);
|
|
117
|
+
if (warnings !== lastWarnings && warnings !== '')
|
|
118
|
+
for (const m of warnings.split('\n'))
|
|
119
|
+
warn(m);
|
|
120
|
+
lastWarnings = warnings;
|
|
121
|
+
if (siteFiles)
|
|
122
|
+
checkSiteFiles(next, !!state.strictSiteFiles, () => undefined);
|
|
123
|
+
const event = reloadEventFor(current(), next, true, false) ?? OK_EVENT;
|
|
124
|
+
swap(next, await servedLastModified(reg.store, source));
|
|
125
|
+
live.send(event);
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
if (!(e instanceof SitefileError))
|
|
129
|
+
throw e;
|
|
130
|
+
stamp(`error[${e.code}]: ${e.message}`);
|
|
131
|
+
live.send(errorEvent(e));
|
|
132
|
+
stamp('Read failed; serving the last good copy');
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
const close = watchPaths({
|
|
136
|
+
dirs: [root],
|
|
137
|
+
files: [],
|
|
138
|
+
onChange: (p) => {
|
|
139
|
+
if (relevant(p))
|
|
140
|
+
scheduler.notify(p);
|
|
141
|
+
},
|
|
142
|
+
...(state.pollMs !== undefined ? { pollMs: state.pollMs, ignore: (p) => !relevant(p) } : {}),
|
|
143
|
+
});
|
|
144
|
+
return () => {
|
|
145
|
+
close();
|
|
146
|
+
scheduler.close();
|
|
147
|
+
};
|
|
148
|
+
}
|
|
38
149
|
main().catch((e) => {
|
|
39
150
|
process.stderr.write(`${e?.stack ?? String(e)}\n`);
|
|
40
151
|
process.exit(1);
|