@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
|
@@ -89,6 +89,17 @@ export declare class TransformCache {
|
|
|
89
89
|
/** Entries, blobs and bytes per plugin, sorted by name (entries that record none first). Reads no blob. */
|
|
90
90
|
usageByPlugin(): Promise<PluginCacheUsage[]>;
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* What INTEGRITY on a JavaScript plugin pins: `sha256:` + digestFolder of the plugin's folder.
|
|
94
|
+
* Refused (a message, not a digest) when the folder holds anything but regular files and
|
|
95
|
+
* directories (a symlink could change what an import resolves to without changing any file) or
|
|
96
|
+
* is over digestFolder's limits.
|
|
97
|
+
*/
|
|
98
|
+
export declare function pluginFolderIntegrity(dir: string): Promise<{
|
|
99
|
+
digest: string;
|
|
100
|
+
} | {
|
|
101
|
+
problem: string;
|
|
102
|
+
}>;
|
|
92
103
|
/** Digest of every regular file under `dir` (a plugin can read all of them, so any may change its output). */
|
|
93
104
|
export declare function digestFolder(dir: string, limits?: {
|
|
94
105
|
files: number;
|
package/lib/src/plugins/cache.js
CHANGED
|
@@ -298,6 +298,35 @@ export class TransformCache {
|
|
|
298
298
|
return out;
|
|
299
299
|
}
|
|
300
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* What INTEGRITY on a JavaScript plugin pins: `sha256:` + digestFolder of the plugin's folder.
|
|
303
|
+
* Refused (a message, not a digest) when the folder holds anything but regular files and
|
|
304
|
+
* directories (a symlink could change what an import resolves to without changing any file) or
|
|
305
|
+
* is over digestFolder's limits.
|
|
306
|
+
*/
|
|
307
|
+
export async function pluginFolderIntegrity(dir) {
|
|
308
|
+
const other = async (rel) => {
|
|
309
|
+
const entries = (await readdir(path.join(dir, rel), { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
310
|
+
for (const e of entries) {
|
|
311
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
312
|
+
if (e.isDirectory()) {
|
|
313
|
+
const found = await other(r);
|
|
314
|
+
if (found !== undefined)
|
|
315
|
+
return found;
|
|
316
|
+
}
|
|
317
|
+
else if (!e.isFile())
|
|
318
|
+
return r;
|
|
319
|
+
}
|
|
320
|
+
return undefined;
|
|
321
|
+
};
|
|
322
|
+
const odd = await other('');
|
|
323
|
+
if (odd !== undefined)
|
|
324
|
+
return { problem: `contains ${odd}, which is not a regular file or directory (a pinned folder can hold only those)` };
|
|
325
|
+
const hex = await digestFolder(dir);
|
|
326
|
+
if (hex === undefined)
|
|
327
|
+
return { problem: 'is too large to pin (more than 2000 files or 128 MiB)' };
|
|
328
|
+
return { digest: `sha256:${hex}` };
|
|
329
|
+
}
|
|
301
330
|
/** Digest of every regular file under `dir` (a plugin can read all of them, so any may change its output). */
|
|
302
331
|
export async function digestFolder(dir, limits = { files: 2000, bytes: 128 * 1024 * 1024 }) {
|
|
303
332
|
const h = createHash('sha256');
|
|
@@ -2,7 +2,7 @@ import { type SourceSpan } from '../errors.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Plugins run one Node process each, under Node's permission model:
|
|
4
4
|
*
|
|
5
|
-
* node --permission --allow-fs-read=<plugin folder> --input-type=module -e <runner>
|
|
5
|
+
* node --permission --allow-fs-read=<plugin folder> --max-old-space-size=<MiB> --input-type=module -e <runner>
|
|
6
6
|
*
|
|
7
7
|
* so a plugin can read files in its own folder and nothing else: no writes,
|
|
8
8
|
* child processes, workers, native addons, WASI or network, and an empty
|
|
@@ -11,12 +11,42 @@ import { type SourceSpan } from '../errors.js';
|
|
|
11
11
|
* Node documents the permission model as a "seat belt" for trusted code, not a
|
|
12
12
|
* defence against deliberately malicious code: plugins are code you choose to
|
|
13
13
|
* run. Pin them with INTEGRITY.
|
|
14
|
+
*
|
|
15
|
+
* The sandbox is only as strong as the Node that runs it: by default the Node
|
|
16
|
+
* running sitefile (`process.execPath`), or the one named by `--node` /
|
|
17
|
+
* `SITEFILE_NODE` / `BuildOptions.node`. Its version is checked (at least
|
|
18
|
+
* MIN_NODE) before the first plugin starts, and reported with `onNotice`.
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* The oldest Node that JavaScript plugins run on. Node 25 added network permissions
|
|
22
|
+
* (before it, `--permission` did not block sockets); 26 is the release sitefile
|
|
23
|
+
* requires and tests with (package.json `engines`).
|
|
24
|
+
*/
|
|
25
|
+
export declare const MIN_NODE: readonly [26, 0, 0];
|
|
26
|
+
/** The Node binary JavaScript plugins run on, as checked when the first one starts. */
|
|
27
|
+
export interface NodeRuntime {
|
|
28
|
+
/** Absolute real path. */
|
|
29
|
+
readonly path: string;
|
|
30
|
+
/** `process.version` of that binary, e.g. `v26.11.1`. */
|
|
31
|
+
readonly version: string;
|
|
32
|
+
}
|
|
33
|
+
/** `vX.Y.Z` → [X, Y, Z], or undefined. */
|
|
34
|
+
export declare function parseNodeVersion(v: string): [number, number, number] | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Resolve and check the Node binary for JavaScript plugins (`node`: an absolute path; default
|
|
37
|
+
* `process.execPath`). The error text is the part after `PLUGIN name: `.
|
|
14
38
|
*/
|
|
39
|
+
export declare function checkNode(node: string | undefined, timeoutMs: number): Promise<NodeRuntime>;
|
|
15
40
|
export interface PluginPolicy {
|
|
16
41
|
/** Per-call time limit (default 60 s); the process is killed when it passes. */
|
|
17
42
|
readonly timeoutMs: number;
|
|
18
43
|
/** Largest result accepted from one call (default 64 MiB). */
|
|
19
44
|
readonly maxOutputBytes: number;
|
|
45
|
+
/**
|
|
46
|
+
* Memory limit in MiB (default 1024, `--plugin-memory`): a JavaScript plugin's heap
|
|
47
|
+
* (`node --max-old-space-size`) and a wasm plugin's linear memory.
|
|
48
|
+
*/
|
|
49
|
+
readonly maxMemoryMiB: number;
|
|
20
50
|
}
|
|
21
51
|
export declare const DEFAULT_PLUGIN_POLICY: PluginPolicy;
|
|
22
52
|
/** A directory TRANSFORM runs at most this many wasm or tool calls at a time (a JS plugin, one). */
|
|
@@ -50,13 +80,32 @@ export interface HostStats {
|
|
|
50
80
|
/** transform() calls sent to a plugin process. */
|
|
51
81
|
calls: number;
|
|
52
82
|
}
|
|
83
|
+
/** What PluginHost warns when a JavaScript plugin whose results may be reused doesn't export `cache`. */
|
|
84
|
+
export declare function undeclaredCacheWarning(name: string): string;
|
|
85
|
+
/** Where JavaScript plugins' Node comes from, and where to report it. */
|
|
86
|
+
export interface PluginHostOptions {
|
|
87
|
+
/** Absolute path of the Node binary (default: `process.execPath`, the Node running sitefile). */
|
|
88
|
+
readonly node?: string;
|
|
89
|
+
/** Receives `plugins run on node <version> (<path>)` when the first JavaScript plugin starts. */
|
|
90
|
+
readonly onNotice?: (message: string) => void;
|
|
91
|
+
/**
|
|
92
|
+
* The build caches or memoizes results (a cache directory or an incremental rebuild), so a
|
|
93
|
+
* JavaScript plugin that doesn't export `cache` gets one warning.
|
|
94
|
+
*/
|
|
95
|
+
readonly reusesResults?: boolean;
|
|
96
|
+
}
|
|
53
97
|
export declare class PluginHost {
|
|
54
98
|
private readonly policy;
|
|
55
99
|
private readonly log;
|
|
100
|
+
private readonly options;
|
|
101
|
+
private readonly warnedCache;
|
|
56
102
|
private readonly registered;
|
|
57
103
|
private readonly procs;
|
|
58
104
|
readonly stats: HostStats;
|
|
59
|
-
|
|
105
|
+
private runtime;
|
|
106
|
+
constructor(policy?: PluginPolicy, log?: (line: string) => void, options?: PluginHostOptions);
|
|
107
|
+
/** The checked Node binary (resolved once, on the first JavaScript plugin). */
|
|
108
|
+
node(): Promise<NodeRuntime>;
|
|
60
109
|
/**
|
|
61
110
|
* `file` is the plugin's absolute real path (already sandbox- and integrity-checked).
|
|
62
111
|
* For a `.wasm` plugin, pass the checked module bytes. Runners start lazily.
|
package/lib/src/plugins/host.js
CHANGED
|
@@ -1,9 +1,77 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
2
3
|
import os from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { SitefileError } from '../errors.js';
|
|
5
6
|
import { WasmPlugin } from './wasm.js';
|
|
6
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Plugins run one Node process each, under Node's permission model:
|
|
9
|
+
*
|
|
10
|
+
* node --permission --allow-fs-read=<plugin folder> --max-old-space-size=<MiB> --input-type=module -e <runner>
|
|
11
|
+
*
|
|
12
|
+
* so a plugin can read files in its own folder and nothing else: no writes,
|
|
13
|
+
* child processes, workers, native addons, WASI or network, and an empty
|
|
14
|
+
* environment (no secrets). Requests and results travel over stdin/stdout.
|
|
15
|
+
*
|
|
16
|
+
* Node documents the permission model as a "seat belt" for trusted code, not a
|
|
17
|
+
* defence against deliberately malicious code: plugins are code you choose to
|
|
18
|
+
* run. Pin them with INTEGRITY.
|
|
19
|
+
*
|
|
20
|
+
* The sandbox is only as strong as the Node that runs it: by default the Node
|
|
21
|
+
* running sitefile (`process.execPath`), or the one named by `--node` /
|
|
22
|
+
* `SITEFILE_NODE` / `BuildOptions.node`. Its version is checked (at least
|
|
23
|
+
* MIN_NODE) before the first plugin starts, and reported with `onNotice`.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* The oldest Node that JavaScript plugins run on. Node 25 added network permissions
|
|
27
|
+
* (before it, `--permission` did not block sockets); 26 is the release sitefile
|
|
28
|
+
* requires and tests with (package.json `engines`).
|
|
29
|
+
*/
|
|
30
|
+
export const MIN_NODE = [26, 0, 0];
|
|
31
|
+
/** `vX.Y.Z` → [X, Y, Z], or undefined. */
|
|
32
|
+
export function parseNodeVersion(v) {
|
|
33
|
+
const m = /^v(\d+)\.(\d+)\.(\d+)$/.exec(v.trim());
|
|
34
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : undefined;
|
|
35
|
+
}
|
|
36
|
+
const atLeast = (v, min) => {
|
|
37
|
+
for (let i = 0; i < 3; i++)
|
|
38
|
+
if (v[i] !== min[i])
|
|
39
|
+
return v[i] > min[i];
|
|
40
|
+
return true;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Resolve and check the Node binary for JavaScript plugins (`node`: an absolute path; default
|
|
44
|
+
* `process.execPath`). The error text is the part after `PLUGIN name: `.
|
|
45
|
+
*/
|
|
46
|
+
export async function checkNode(node, timeoutMs) {
|
|
47
|
+
const given = node ?? process.execPath;
|
|
48
|
+
const choose = 'choose another with --node or SITEFILE_NODE';
|
|
49
|
+
if (!path.isAbsolute(given))
|
|
50
|
+
throw new Error(`the Node binary must be an absolute path, got '${given}'`);
|
|
51
|
+
let real;
|
|
52
|
+
try {
|
|
53
|
+
real = await realpath(given);
|
|
54
|
+
if (!(await stat(real)).isFile())
|
|
55
|
+
throw new Error('not a file');
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new Error(`could not start: no Node binary at ${given}`);
|
|
59
|
+
}
|
|
60
|
+
const out = await new Promise((resolve, reject) => execFile(real, ['--version'], { env: {}, timeout: timeoutMs, maxBuffer: 4096 }, (e, stdout) => (e ? reject(e) : resolve(String(stdout))))).catch(() => undefined);
|
|
61
|
+
const parsed = out === undefined ? undefined : parseNodeVersion(out);
|
|
62
|
+
if (!parsed)
|
|
63
|
+
throw new Error(`could not start: ${real} --version did not print a Node version; ${choose}`);
|
|
64
|
+
const version = out.trim();
|
|
65
|
+
if (!atLeast(parsed, MIN_NODE)) {
|
|
66
|
+
throw new Error(`node ${version} (${real}) is too old for the plugin sandbox: JavaScript plugins need Node ${MIN_NODE.join('.')} or later; ${choose}`);
|
|
67
|
+
}
|
|
68
|
+
return { path: real, version };
|
|
69
|
+
}
|
|
70
|
+
export const DEFAULT_PLUGIN_POLICY = { timeoutMs: 60_000, maxOutputBytes: 64 * 1024 * 1024, maxMemoryMiB: 1024 };
|
|
71
|
+
/** What V8 prints when a heap passes --max-old-space-size (followed by a native stack trace). */
|
|
72
|
+
const OUT_OF_MEMORY = 'JavaScript heap out of memory';
|
|
73
|
+
/** V8's out-of-memory report starts with one of these; it and everything after it is not logged. */
|
|
74
|
+
const isFatalReport = (line) => line.startsWith('<--- Last few GCs --->') || line.startsWith('FATAL ERROR:');
|
|
7
75
|
/** A directory TRANSFORM runs at most this many wasm or tool calls at a time (a JS plugin, one). */
|
|
8
76
|
export const TRANSFORM_JOBS = Math.max(1, Math.min(4, os.availableParallelism()));
|
|
9
77
|
/** Prefix that marks protocol lines on the child's stdout; anything else is plugin output. */
|
|
@@ -38,9 +106,11 @@ async function handle(msg) {
|
|
|
38
106
|
if (typeof api.transform !== 'function') throw new Error('the module must export transform(request), or a default object with transform');
|
|
39
107
|
if (version !== 1) throw new Error('unsupported plugin apiVersion ' + JSON.stringify(version) + ' (this Sitefile supports 1)');
|
|
40
108
|
transform = api.transform;
|
|
41
|
-
// 'export const cache = false' opts a (non-deterministic) plugin out of the result cache
|
|
109
|
+
// 'export const cache = false' opts a (non-deterministic) plugin out of the result cache;
|
|
110
|
+
// 'cache = true' says it is deterministic. Without either it is cached, with a warning.
|
|
42
111
|
const cache = api.cache ?? mod.cache;
|
|
43
|
-
|
|
112
|
+
if (cache !== undefined && typeof cache !== 'boolean') throw new Error('cache must be true or false, got ' + JSON.stringify(cache));
|
|
113
|
+
send({ type: 'ready', cache: cache !== false, declared: cache !== undefined });
|
|
44
114
|
} catch (e) {
|
|
45
115
|
send({ type: 'load-error', message: e && e.message ? e.message : String(e) });
|
|
46
116
|
}
|
|
@@ -77,26 +147,37 @@ class PluginProcess {
|
|
|
77
147
|
child;
|
|
78
148
|
buf = '';
|
|
79
149
|
stderr = '';
|
|
150
|
+
/** V8 reported that the heap passed the memory limit. */
|
|
151
|
+
outOfMemory = false;
|
|
152
|
+
/** Set once V8's fatal error report starts on stderr: the rest is a native stack trace, not logged. */
|
|
153
|
+
quiet = false;
|
|
80
154
|
nextId = 1;
|
|
81
155
|
pending = new Map();
|
|
82
156
|
/** False when the module exports `cache = false`; known once it has loaded. */
|
|
83
157
|
cacheable = true;
|
|
158
|
+
/** Whether the module exports `cache` at all; known once it has loaded. */
|
|
159
|
+
declaredCache = true;
|
|
84
160
|
ready;
|
|
85
161
|
exited;
|
|
86
|
-
constructor(name, file, policy, log, span) {
|
|
162
|
+
constructor(name, file, node, policy, log, span) {
|
|
87
163
|
this.name = name;
|
|
88
164
|
this.policy = policy;
|
|
89
165
|
this.log = log;
|
|
90
166
|
const dir = path.dirname(file);
|
|
91
|
-
this.child = spawn(
|
|
167
|
+
this.child = spawn(node, ['--permission', `--allow-fs-read=${dir}`, `--max-old-space-size=${policy.maxMemoryMiB}`, '--disable-warning=ExperimentalWarning', '--input-type=module', '-e', RUNNER], { cwd: dir, env: {}, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
92
168
|
this.child.stdout.setEncoding('utf8');
|
|
93
169
|
this.child.stderr.setEncoding('utf8');
|
|
94
170
|
this.child.stdout.on('data', (chunk) => this.onStdout(chunk));
|
|
95
171
|
this.child.stderr.on('data', (chunk) => {
|
|
96
172
|
this.stderr = (this.stderr + chunk).slice(-8192);
|
|
97
|
-
|
|
98
|
-
|
|
173
|
+
if (this.stderr.includes(OUT_OF_MEMORY))
|
|
174
|
+
this.outOfMemory = true;
|
|
175
|
+
for (const line of chunk.split('\n')) {
|
|
176
|
+
if (isFatalReport(line))
|
|
177
|
+
this.quiet = true;
|
|
178
|
+
if (line.trim() && !this.quiet)
|
|
99
179
|
this.log(line);
|
|
180
|
+
}
|
|
100
181
|
});
|
|
101
182
|
let onReady = () => { };
|
|
102
183
|
let onLoadError = () => { };
|
|
@@ -109,7 +190,8 @@ class PluginProcess {
|
|
|
109
190
|
this.onReadyMsg = onReady;
|
|
110
191
|
this.onLoadError = (m) => onLoadError(new SitefileError('E_PLUGIN', `PLUGIN ${name}: ${m}`, span));
|
|
111
192
|
this.child.on('error', (e) => this.fail(`could not start: ${e.message}`));
|
|
112
|
-
|
|
193
|
+
// 'close' (not 'exit'): stderr has been read by then, so the reason can say why it died.
|
|
194
|
+
this.child.on('close', (code, signal) => this.fail(signal ? `stopped by ${signal}` : `exited with code ${code}`));
|
|
113
195
|
this.write({ type: 'load', url: new URL(`file://${file}`).href });
|
|
114
196
|
}
|
|
115
197
|
onReadyMsg;
|
|
@@ -141,6 +223,7 @@ class PluginProcess {
|
|
|
141
223
|
switch (msg['type']) {
|
|
142
224
|
case 'ready':
|
|
143
225
|
this.cacheable = msg['cache'] !== false;
|
|
226
|
+
this.declaredCache = msg['declared'] === true;
|
|
144
227
|
this.onReadyMsg();
|
|
145
228
|
return;
|
|
146
229
|
case 'load-error':
|
|
@@ -175,6 +258,11 @@ class PluginProcess {
|
|
|
175
258
|
fail(reason) {
|
|
176
259
|
if (this.exited)
|
|
177
260
|
return;
|
|
261
|
+
if (this.outOfMemory) {
|
|
262
|
+
// The stderr tail would be V8's native stack trace: machine-specific, and no help.
|
|
263
|
+
reason = `ran out of memory (more than the ${this.policy.maxMemoryMiB} MiB limit)`;
|
|
264
|
+
this.stderr = '';
|
|
265
|
+
}
|
|
178
266
|
this.exited = reason;
|
|
179
267
|
const tail = this.stderr.trim() ? `\n${this.stderr.trim().split('\n').slice(-5).join('\n')}` : '';
|
|
180
268
|
const err = new Error(`${reason}${tail}`);
|
|
@@ -218,15 +306,34 @@ class PluginProcess {
|
|
|
218
306
|
this.child.kill();
|
|
219
307
|
}
|
|
220
308
|
}
|
|
309
|
+
/** What PluginHost warns when a JavaScript plugin whose results may be reused doesn't export `cache`. */
|
|
310
|
+
export function undeclaredCacheWarning(name) {
|
|
311
|
+
return `PLUGIN ${name} does not export cache, so its results are reused as if it were deterministic: export const cache = true to confirm, or cache = false if a result can depend on the clock, randomness or an earlier call`;
|
|
312
|
+
}
|
|
221
313
|
export class PluginHost {
|
|
222
314
|
policy;
|
|
223
315
|
log;
|
|
316
|
+
options;
|
|
317
|
+
warnedCache = new Set();
|
|
224
318
|
registered = new Map();
|
|
225
319
|
procs = new Map();
|
|
226
320
|
stats = { spawned: 0, calls: 0 };
|
|
227
|
-
|
|
321
|
+
runtime;
|
|
322
|
+
constructor(policy = DEFAULT_PLUGIN_POLICY, log = () => { }, options = {}) {
|
|
228
323
|
this.policy = policy;
|
|
229
324
|
this.log = log;
|
|
325
|
+
this.options = options;
|
|
326
|
+
}
|
|
327
|
+
/** The checked Node binary (resolved once, on the first JavaScript plugin). */
|
|
328
|
+
node() {
|
|
329
|
+
if (!this.runtime) {
|
|
330
|
+
this.runtime = checkNode(this.options.node, this.policy.timeoutMs).then((rt) => {
|
|
331
|
+
this.options.onNotice?.(`plugins run on node ${rt.version} (${rt.path})`);
|
|
332
|
+
return rt;
|
|
333
|
+
});
|
|
334
|
+
this.runtime.catch(() => { });
|
|
335
|
+
}
|
|
336
|
+
return this.runtime;
|
|
230
337
|
}
|
|
231
338
|
/**
|
|
232
339
|
* `file` is the plugin's absolute real path (already sandbox- and integrity-checked).
|
|
@@ -250,14 +357,32 @@ export class PluginHost {
|
|
|
250
357
|
const reg = this.registered.get(name);
|
|
251
358
|
if (!reg)
|
|
252
359
|
throw new SitefileError('E_UNDEFINED', `unknown plugin '${name}'`, span);
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
360
|
+
let node;
|
|
361
|
+
if (!reg.wasm) {
|
|
362
|
+
try {
|
|
363
|
+
node = await this.node();
|
|
364
|
+
}
|
|
365
|
+
catch (e) {
|
|
366
|
+
throw new SitefileError('E_PLUGIN', `PLUGIN ${name}: ${e.message}`, reg.span);
|
|
367
|
+
}
|
|
368
|
+
// Another call may have started it while this one waited for the check.
|
|
369
|
+
p = this.procs.get(name);
|
|
370
|
+
}
|
|
371
|
+
if (!p) {
|
|
372
|
+
p = reg.wasm
|
|
373
|
+
? new WasmPlugin(name, reg.wasm, this.policy, TRANSFORM_JOBS)
|
|
374
|
+
: new PluginProcess(name, reg.file, node.path, this.policy, (l) => this.log(`[plugin ${name}] ${l}`), reg.span);
|
|
375
|
+
this.procs.set(name, p);
|
|
376
|
+
this.stats.spawned++;
|
|
377
|
+
}
|
|
258
378
|
}
|
|
259
379
|
this.stats.calls++;
|
|
260
|
-
|
|
380
|
+
const result = await p.call(request, span);
|
|
381
|
+
if (this.options.reusesResults && p instanceof PluginProcess && !p.declaredCache && !this.warnedCache.has(name)) {
|
|
382
|
+
this.warnedCache.add(name);
|
|
383
|
+
this.log(undeclaredCacheWarning(name));
|
|
384
|
+
}
|
|
385
|
+
return result;
|
|
261
386
|
}
|
|
262
387
|
/** The folder a registered plugin lives in. */
|
|
263
388
|
folderOf(name) {
|
package/lib/src/plugins/wasm.js
CHANGED
|
@@ -74,8 +74,6 @@ parentPort.on('message', ({ id, request }) => {
|
|
|
74
74
|
}
|
|
75
75
|
});
|
|
76
76
|
`;
|
|
77
|
-
/** Largest linear memory a wasm plugin may use (default 1 GiB). */
|
|
78
|
-
const DEFAULT_MAX_MEMORY = 1024 * 1024 * 1024;
|
|
79
77
|
/**
|
|
80
78
|
* A wasm plugin: up to `lanes` workers, so a directory TRANSFORM can run several calls at once.
|
|
81
79
|
* A call waits for a free worker, and its time limit starts when that worker takes it.
|
|
@@ -146,7 +144,7 @@ class WasmLane {
|
|
|
146
144
|
return this.worker;
|
|
147
145
|
const w = new Worker(WORKER, {
|
|
148
146
|
eval: true,
|
|
149
|
-
workerData: { bytes: this.bytes, maxMemory:
|
|
147
|
+
workerData: { bytes: this.bytes, maxMemory: this.policy.maxMemoryMiB * 1024 * 1024 },
|
|
150
148
|
// The worker's own JS heap; wasm memory is checked after each call.
|
|
151
149
|
resourceLimits: { maxOldGenerationSizeMb: 256 },
|
|
152
150
|
env: {},
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Why a path cannot be written on Windows, or undefined. */
|
|
2
|
+
export declare function windowsProblem(path: string): string | undefined;
|
|
3
|
+
/**
|
|
4
|
+
* Portability problems of the exported files (`paths` are below the export root, in UTF-8 order): one message
|
|
5
|
+
* per path Windows cannot hold, then one about GitHub Pages when a file or folder starts with `_` (other than
|
|
6
|
+
* `/_headers` and `/_redirects`) and there is no `/.nojekyll`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function portabilityProblems(paths: readonly string[]): string[];
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Path portability (docs/LANGUAGE.md, "Portable paths"): names that work locally but break on other
|
|
2
|
+
// systems or hosts. Ported as rust/src/portable.rs: both must find the same problems, in the same words.
|
|
3
|
+
/** Windows device names: a file named so (with any extension) cannot be created there. */
|
|
4
|
+
const RESERVED = new Set(['CON', 'PRN', 'AUX', 'NUL', ...[1, 2, 3, 4, 5, 6, 7, 8, 9, '¹', '²', '³'].flatMap((n) => [`COM${n}`, `LPT${n}`])]);
|
|
5
|
+
/** Characters Windows does not allow in a file name. */
|
|
6
|
+
const WINDOWS_CHARS = /[<>:"|?*\\\u0000-\u001f]/;
|
|
7
|
+
/** Why a path cannot be written on Windows, or undefined. */
|
|
8
|
+
export function windowsProblem(path) {
|
|
9
|
+
for (const seg of path.split('/').slice(1)) {
|
|
10
|
+
const bad = WINDOWS_CHARS.exec(seg);
|
|
11
|
+
if (bad) {
|
|
12
|
+
const c = bad[0];
|
|
13
|
+
const shown = c.charCodeAt(0) < 0x20 ? `U+${c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}` : `'${c}'`;
|
|
14
|
+
return `${shown} is not allowed in a Windows file name`;
|
|
15
|
+
}
|
|
16
|
+
if (seg.endsWith('.') || seg.endsWith(' '))
|
|
17
|
+
return `'${seg}' ends with ${seg.endsWith('.') ? 'a dot' : 'a space'}, which Windows drops`;
|
|
18
|
+
const stem = seg.split('.')[0].replace(/ +$/, '').toUpperCase();
|
|
19
|
+
if (RESERVED.has(stem))
|
|
20
|
+
return `'${seg}' is a reserved device name on Windows`;
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
/** Root files Netlify and Cloudflare Pages read; GitHub Pages' Jekyll skipping them does no harm. */
|
|
25
|
+
const HOST_FILES = new Set(['/_headers', '/_redirects']);
|
|
26
|
+
/**
|
|
27
|
+
* Portability problems of the exported files (`paths` are below the export root, in UTF-8 order): one message
|
|
28
|
+
* per path Windows cannot hold, then one about GitHub Pages when a file or folder starts with `_` (other than
|
|
29
|
+
* `/_headers` and `/_redirects`) and there is no `/.nojekyll`.
|
|
30
|
+
*/
|
|
31
|
+
export function portabilityProblems(paths) {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const p of paths) {
|
|
34
|
+
const why = windowsProblem(p);
|
|
35
|
+
if (why)
|
|
36
|
+
out.push(`'${p}' cannot be extracted on Windows: ${why}`);
|
|
37
|
+
}
|
|
38
|
+
if (!paths.includes('/.nojekyll')) {
|
|
39
|
+
const hidden = paths.filter((p) => !HOST_FILES.has(p) && p.split('/').some((s) => s.startsWith('_')));
|
|
40
|
+
if (hidden.length > 0) {
|
|
41
|
+
const shown = hidden.slice(0, 3).join(', ') + (hidden.length > 3 ? `, … (${hidden.length} in all)` : '');
|
|
42
|
+
out.push(`GitHub Pages (with Jekyll) does not publish files or folders whose name starts with '_' (${shown}); if the site is hosted there, add an empty /.nojekyll`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=portable.js.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type SourceSpan } from './errors.js';
|
|
2
|
+
import { type Tree } from './tree.js';
|
|
3
|
+
/** Where `injectManifest` puts the manifest in a service worker (Workbox's default `injectionPoint`). */
|
|
4
|
+
export declare const INJECTION_POINT = "self.__WB_MANIFEST";
|
|
5
|
+
export interface PrecacheOp {
|
|
6
|
+
readonly patterns: readonly string[];
|
|
7
|
+
readonly dest?: string;
|
|
8
|
+
readonly into?: string;
|
|
9
|
+
readonly root: string;
|
|
10
|
+
readonly overwrite: boolean;
|
|
11
|
+
readonly span: SourceSpan;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The manifest entries: every file matching a pattern below `root` (other than the manifest and the
|
|
15
|
+
* service worker), as `{url, revision}` sorted by URL. The URL is the path below `root`, percent-encoded;
|
|
16
|
+
* the revision is the first 10 hex digits of the file's SHA-256, or null for a file a FINGERPRINT renamed
|
|
17
|
+
* (`fingerprinted`: its name already changes with its content).
|
|
18
|
+
*/
|
|
19
|
+
export declare function precacheEntries(tree: Tree, op: PrecacheOp, fingerprinted: ReadonlySet<string>): Array<{
|
|
20
|
+
url: string;
|
|
21
|
+
revision: string | null;
|
|
22
|
+
}>;
|
|
23
|
+
/** The manifest as JSON: one entry per line, two-space indented, with a final newline (`[]` when empty). */
|
|
24
|
+
export declare function precacheJson(entries: ReadonlyArray<{
|
|
25
|
+
url: string;
|
|
26
|
+
revision: string | null;
|
|
27
|
+
}>): string;
|
|
28
|
+
/**
|
|
29
|
+
* Write the manifest to `dest` and/or replace the first `self.__WB_MANIFEST` in the service worker `into`
|
|
30
|
+
* (a file of the tree, valid UTF-8, holding the placeholder: E_VALIDATION otherwise) with the JSON array.
|
|
31
|
+
* Warns when no file matches.
|
|
32
|
+
*/
|
|
33
|
+
export declare function precache(tree: Tree, op: PrecacheOp, fingerprinted: ReadonlySet<string>, origin: string, warn: (m: string) => void): Tree;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// PRECACHE (docs/LANGUAGE.md, "Precache manifest"): a Workbox-style list of the files a service worker
|
|
2
|
+
// precaches, `[{url, revision}]`. Ported as rust/src/precache.rs: both must write the same bytes.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { SitefileError } from './errors.js';
|
|
5
|
+
import { globMatches, HASH_LENGTH } from './fingerprint.js';
|
|
6
|
+
import { encodePath } from './links.js';
|
|
7
|
+
import { makeFile } from './tree.js';
|
|
8
|
+
/** Where `injectManifest` puts the manifest in a service worker (Workbox's default `injectionPoint`). */
|
|
9
|
+
export const INJECTION_POINT = 'self.__WB_MANIFEST';
|
|
10
|
+
function utf8Compare(a, b) {
|
|
11
|
+
return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The manifest entries: every file matching a pattern below `root` (other than the manifest and the
|
|
15
|
+
* service worker), as `{url, revision}` sorted by URL. The URL is the path below `root`, percent-encoded;
|
|
16
|
+
* the revision is the first 10 hex digits of the file's SHA-256, or null for a file a FINGERPRINT renamed
|
|
17
|
+
* (`fingerprinted`: its name already changes with its content).
|
|
18
|
+
*/
|
|
19
|
+
export function precacheEntries(tree, op, fingerprinted) {
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const [p, node] of tree.entries()) {
|
|
22
|
+
if (p === op.dest || p === op.into || !op.patterns.some((pat) => globMatches(pat, p)))
|
|
23
|
+
continue;
|
|
24
|
+
const below = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
|
|
25
|
+
if (below === undefined)
|
|
26
|
+
continue;
|
|
27
|
+
const revision = fingerprinted.has(p) ? null : createHash('sha256').update(node.bytes).digest('hex').slice(0, HASH_LENGTH);
|
|
28
|
+
out.push({ url: encodePath(below), revision });
|
|
29
|
+
}
|
|
30
|
+
return out.sort((a, b) => utf8Compare(a.url, b.url));
|
|
31
|
+
}
|
|
32
|
+
/** The manifest as JSON: one entry per line, two-space indented, with a final newline (`[]` when empty). */
|
|
33
|
+
export function precacheJson(entries) {
|
|
34
|
+
if (entries.length === 0)
|
|
35
|
+
return '[]\n';
|
|
36
|
+
return '[\n' + entries.map((e) => ` {"url": ${JSON.stringify(e.url)}, "revision": ${JSON.stringify(e.revision)}}`).join(',\n') + '\n]\n';
|
|
37
|
+
}
|
|
38
|
+
const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
39
|
+
/**
|
|
40
|
+
* Write the manifest to `dest` and/or replace the first `self.__WB_MANIFEST` in the service worker `into`
|
|
41
|
+
* (a file of the tree, valid UTF-8, holding the placeholder: E_VALIDATION otherwise) with the JSON array.
|
|
42
|
+
* Warns when no file matches.
|
|
43
|
+
*/
|
|
44
|
+
export function precache(tree, op, fingerprinted, origin, warn) {
|
|
45
|
+
const entries = precacheEntries(tree, op, fingerprinted);
|
|
46
|
+
if (entries.length === 0)
|
|
47
|
+
warn(`${origin}: no files match ${op.patterns.join(' ')}`);
|
|
48
|
+
const json = precacheJson(entries);
|
|
49
|
+
const files = [];
|
|
50
|
+
if (op.dest !== undefined)
|
|
51
|
+
files.push([op.dest, makeFile(new TextEncoder().encode(json), origin)]);
|
|
52
|
+
if (op.into !== undefined) {
|
|
53
|
+
const sw = tree.get(op.into);
|
|
54
|
+
if (!sw)
|
|
55
|
+
throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: there is no such file in the stage (COPY the service worker in first)`, op.span);
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
text = UTF8.decode(sw.bytes);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: the service worker is not UTF-8 text`, op.span);
|
|
62
|
+
}
|
|
63
|
+
const at = text.indexOf(INJECTION_POINT);
|
|
64
|
+
if (at === -1)
|
|
65
|
+
throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: the service worker has no ${INJECTION_POINT} to replace with the manifest`, op.span);
|
|
66
|
+
const injected = text.slice(0, at) + json.trimEnd() + text.slice(at + INJECTION_POINT.length);
|
|
67
|
+
files.push([op.into, makeFile(new TextEncoder().encode(injected), origin, sw.mode)]);
|
|
68
|
+
}
|
|
69
|
+
// The service worker is replaced by its injected version; the manifest follows the conflict rules.
|
|
70
|
+
let out = tree;
|
|
71
|
+
for (const [p, node] of files)
|
|
72
|
+
out = out.withFiles([[p, node]], p === op.into || op.overwrite ? 'overwrite' : 'error', op.span);
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=precache.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SourceSpan } from './errors.js';
|
|
2
|
+
import { type Tree } from './tree.js';
|
|
3
|
+
/** Extensions (lowercase, after the last dot) of the file types PRECOMPRESS compresses: text, scripts, data, fonts without their own compression. */
|
|
4
|
+
export declare const COMPRESSIBLE: Set<string>;
|
|
5
|
+
/** Whether a path names a compressible file type (by its extension, ASCII case-insensitive). */
|
|
6
|
+
export declare function compressible(path: string): boolean;
|
|
7
|
+
export interface PrecompressOp {
|
|
8
|
+
readonly patterns: readonly string[];
|
|
9
|
+
readonly min: number;
|
|
10
|
+
readonly overwrite: boolean;
|
|
11
|
+
readonly span: SourceSpan;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The tree with a `<path>.gz` sidecar (gzip, fixed header) for every file that matches a pattern, is
|
|
15
|
+
* compressible, has at least `min` bytes, and compresses to fewer bytes than it has. Sidecars keep the
|
|
16
|
+
* file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
|
|
17
|
+
* `overwrite`. Warns when no file matches the patterns.
|
|
18
|
+
*/
|
|
19
|
+
export declare function precompress(tree: Tree, op: PrecompressOp, origin: string, warn: (m: string) => void): Tree;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { gzip } from './deflate.js';
|
|
2
|
+
import { globMatches } from './fingerprint.js';
|
|
3
|
+
import { makeFile } from './tree.js';
|
|
4
|
+
/** Extensions (lowercase, after the last dot) of the file types PRECOMPRESS compresses: text, scripts, data, fonts without their own compression. */
|
|
5
|
+
export const COMPRESSIBLE = new Set([
|
|
6
|
+
'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'json', 'map', 'xml', 'svg', 'txt', 'md', 'csv', 'tsv',
|
|
7
|
+
'webmanifest', 'rss', 'atom', 'ics', 'vtt', 'yaml', 'yml', 'toml', 'wasm', 'ttf', 'otf', 'eot', 'ico',
|
|
8
|
+
]);
|
|
9
|
+
/** Whether a path names a compressible file type (by its extension, ASCII case-insensitive). */
|
|
10
|
+
export function compressible(path) {
|
|
11
|
+
const base = path.slice(path.lastIndexOf('/') + 1);
|
|
12
|
+
const dot = base.lastIndexOf('.');
|
|
13
|
+
return dot > 0 && COMPRESSIBLE.has(base.slice(dot + 1).toLowerCase());
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The tree with a `<path>.gz` sidecar (gzip, fixed header) for every file that matches a pattern, is
|
|
17
|
+
* compressible, has at least `min` bytes, and compresses to fewer bytes than it has. Sidecars keep the
|
|
18
|
+
* file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
|
|
19
|
+
* `overwrite`. Warns when no file matches the patterns.
|
|
20
|
+
*/
|
|
21
|
+
export function precompress(tree, op, origin, warn) {
|
|
22
|
+
const matched = tree.entries().filter(([p]) => op.patterns.some((pat) => globMatches(pat, p)));
|
|
23
|
+
if (matched.length === 0)
|
|
24
|
+
warn(`${origin}: no files match ${op.patterns.join(' ')}`);
|
|
25
|
+
const files = [];
|
|
26
|
+
for (const [p, node] of matched) {
|
|
27
|
+
if (!compressible(p) || node.bytes.byteLength < op.min)
|
|
28
|
+
continue;
|
|
29
|
+
const gz = gzip(node.bytes);
|
|
30
|
+
if (gz.byteLength < node.bytes.byteLength)
|
|
31
|
+
files.push([p + '.gz', makeFile(gz, origin, node.mode)]);
|
|
32
|
+
}
|
|
33
|
+
return files.length ? tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span) : tree;
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=precompress.js.map
|
package/lib/src/qr.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A QR Code encoder (ISO/IEC 18004), enough for `serve --qr` (issue #224): byte mode, error correction
|
|
3
|
+
* level M, the smallest version (1–40) that fits, and the mask with the lowest penalty. Ported as
|
|
4
|
+
* rust/src/qr.rs; both produce the same modules (test/fixtures/qr/*.txt are checked by both).
|
|
5
|
+
*/
|
|
6
|
+
/** A QR Code: `size` × `size` modules, `true` = dark. */
|
|
7
|
+
export interface QrCode {
|
|
8
|
+
readonly version: number;
|
|
9
|
+
readonly size: number;
|
|
10
|
+
readonly modules: readonly (readonly boolean[])[];
|
|
11
|
+
}
|
|
12
|
+
/** Encode `text` (UTF-8) as a QR Code, or undefined when it is too long for version 40. */
|
|
13
|
+
export declare function encodeQr(text: string): QrCode | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* The code for a terminal: two rows of modules per line with `▀`, `▄`, `█` and spaces, and a quiet zone
|
|
16
|
+
* of two modules, dark on a light background (the half blocks are the light parts' complement).
|
|
17
|
+
*/
|
|
18
|
+
export declare function qrTerminal(code: QrCode): string;
|