@johnhenry/sitefile 0.0.1 → 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 +480 -3
- package/README.md +70 -21
- 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 +144 -18
- 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
package/lib/src/warc.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants, gunzipSync } from 'node:zlib';
|
|
3
|
+
import { gzip } from './deflate.js';
|
|
4
|
+
import { SitefileError } from './errors.js';
|
|
5
|
+
import { encodePath, percentDecode } from './links.js';
|
|
6
|
+
import { headersFor, parseHeaderRules } from './serve-rules.js';
|
|
7
|
+
import { DEFAULT_ARCHIVE_LIMITS } from './resources/types.js';
|
|
8
|
+
import { makeFile, Tree } from './tree.js';
|
|
9
|
+
import { mimeTypeFor, validateBaseUrl } from './wbn.js';
|
|
10
|
+
/**
|
|
11
|
+
* WARC (ISO 28500, WARC/1.1) export and import (issue #206).
|
|
12
|
+
*
|
|
13
|
+
* `EXPORT / AS warc BASE <url>` writes a `warcinfo` record, then one `response` record per file (path
|
|
14
|
+
* order) at `<base><path>`: `HTTP/1.1 200 OK`, the Content-Type from the Web Bundle MIME table (or the
|
|
15
|
+
* site's `_headers`), Content-Length, and every `_headers` rule that matches the path. `_headers` and
|
|
16
|
+
* `_redirects` are site configuration, not records. A directory's `index.html` is recorded a second
|
|
17
|
+
* time at the directory URL (`<base>sub/`), as a replay tool requests it. Record IDs are UUIDs derived
|
|
18
|
+
* from the record's content and every record is dated `SOURCE_DATE_EPOCH` (default the Unix epoch), so
|
|
19
|
+
* the file is deterministic. `COMPRESSION gzip` (or `-o x.warc.gz`) writes each record as its own gzip
|
|
20
|
+
* member, the usual `.warc.gz` layout.
|
|
21
|
+
*
|
|
22
|
+
* Reading (`IMPORT … AS tree`, `serve`): the `200` responses of the first response's host; a URL path
|
|
23
|
+
* ending in `/` is that directory's `index.html`; the first record for a path wins. Paths are checked
|
|
24
|
+
* like archive entries and the archive limits apply.
|
|
25
|
+
*/
|
|
26
|
+
const enc = new TextEncoder();
|
|
27
|
+
const CRLF = '\r\n';
|
|
28
|
+
const DATE_ZERO = '1970-01-01T00:00:00Z';
|
|
29
|
+
const SKIP = new Set(['/_headers', '/_redirects']);
|
|
30
|
+
function sha256Hex(data) {
|
|
31
|
+
return createHash('sha256').update(data).digest('hex');
|
|
32
|
+
}
|
|
33
|
+
/** A deterministic `urn:uuid:` (UUID version 8) from the hash of `seed`. */
|
|
34
|
+
function recordId(seed) {
|
|
35
|
+
const h = sha256Hex(seed);
|
|
36
|
+
const v = '8' + h.slice(13, 16);
|
|
37
|
+
const variant = ((parseInt(h.slice(16, 17), 16) & 3) | 8).toString(16) + h.slice(17, 20);
|
|
38
|
+
return `<urn:uuid:${h.slice(0, 8)}-${h.slice(8, 12)}-${v}-${variant}-${h.slice(20, 32)}>`;
|
|
39
|
+
}
|
|
40
|
+
export function isoDate(epoch) {
|
|
41
|
+
if (epoch === undefined)
|
|
42
|
+
return DATE_ZERO;
|
|
43
|
+
return new Date(epoch * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
44
|
+
}
|
|
45
|
+
function concat(parts) {
|
|
46
|
+
let n = 0;
|
|
47
|
+
for (const p of parts)
|
|
48
|
+
n += p.byteLength;
|
|
49
|
+
const out = new Uint8Array(n);
|
|
50
|
+
let o = 0;
|
|
51
|
+
for (const p of parts) {
|
|
52
|
+
out.set(p, o);
|
|
53
|
+
o += p.byteLength;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
function record(fields, block) {
|
|
58
|
+
const head = ['WARC/1.1', ...fields.map(([k, v]) => `${k}: ${v}`), `Content-Length: ${block.byteLength}`, '', ''].join(CRLF);
|
|
59
|
+
return concat([enc.encode(head), block, enc.encode(CRLF + CRLF)]);
|
|
60
|
+
}
|
|
61
|
+
/** `EXPORT … AS warc`: the tree as WARC/1.1 records (see the top of this file). */
|
|
62
|
+
export function writeWarc(tree, options) {
|
|
63
|
+
const records = warcRecords(tree, options).map((r) => r.bytes);
|
|
64
|
+
return options.compression === 'gzip' ? concat(records.map((r) => gzip(r))) : concat(records);
|
|
65
|
+
}
|
|
66
|
+
/** The records {@link writeWarc} writes, in order. */
|
|
67
|
+
export function warcRecords(tree, options) {
|
|
68
|
+
if (options.baseUrl === undefined || options.baseUrl === '') {
|
|
69
|
+
throw new SitefileError('E_VALIDATION', "warc export needs a base URL: use 'EXPORT <path> AS warc BASE https://example.com/' or --base-url");
|
|
70
|
+
}
|
|
71
|
+
const base = validateBaseUrl(options.baseUrl);
|
|
72
|
+
const date = isoDate(options.epoch);
|
|
73
|
+
const rules = parseHeaderRules(new TextDecoder().decode(tree.get('/_headers')?.bytes ?? new Uint8Array(0)));
|
|
74
|
+
const records = [];
|
|
75
|
+
const info = enc.encode(`software: sitefile${CRLF}format: WARC File Format 1.1${CRLF}`);
|
|
76
|
+
const infoId = recordId(`warcinfo\0${base}`);
|
|
77
|
+
records.push({
|
|
78
|
+
bytes: record([
|
|
79
|
+
['WARC-Type', 'warcinfo'],
|
|
80
|
+
['WARC-Record-ID', infoId],
|
|
81
|
+
['WARC-Date', date],
|
|
82
|
+
['Content-Type', 'application/warc-fields'],
|
|
83
|
+
], info),
|
|
84
|
+
});
|
|
85
|
+
const response = (uri, path, node) => {
|
|
86
|
+
const headers = headersFor(rules, path);
|
|
87
|
+
const type = headers['content-type'] ?? mimeTypeFor(path);
|
|
88
|
+
const lines = ['HTTP/1.1 200 OK', `Content-Type: ${type}`, `Content-Length: ${node.bytes.byteLength}`];
|
|
89
|
+
for (const [k, v] of Object.entries(headers))
|
|
90
|
+
if (k !== 'content-type')
|
|
91
|
+
lines.push(`${k}: ${v}`);
|
|
92
|
+
const block = concat([enc.encode(lines.join(CRLF) + CRLF + CRLF), node.bytes]);
|
|
93
|
+
const blockDigest = `sha256:${sha256Hex(block)}`;
|
|
94
|
+
const bytes = record([
|
|
95
|
+
['WARC-Type', 'response'],
|
|
96
|
+
['WARC-Record-ID', recordId(`response\0${uri}\0${blockDigest}`)],
|
|
97
|
+
['WARC-Warcinfo-ID', infoId],
|
|
98
|
+
['WARC-Date', date],
|
|
99
|
+
['WARC-Target-URI', uri],
|
|
100
|
+
['WARC-Payload-Digest', `sha256:${sha256Hex(node.bytes)}`],
|
|
101
|
+
['WARC-Block-Digest', blockDigest],
|
|
102
|
+
['Content-Type', 'application/http;msgtype=response'],
|
|
103
|
+
], block);
|
|
104
|
+
return { bytes, response: { uri, path, type, digest: `sha256:${sha256Hex(node.bytes)}` } };
|
|
105
|
+
};
|
|
106
|
+
for (const [p, n] of tree.entries()) {
|
|
107
|
+
if (SKIP.has(p))
|
|
108
|
+
continue;
|
|
109
|
+
records.push(response(base + encodePath(p.slice(1)), p, n));
|
|
110
|
+
if (p === '/index.html' || p.endsWith('/index.html')) {
|
|
111
|
+
const dir = p.slice(0, -'index.html'.length);
|
|
112
|
+
records.push(response(base + encodePath(dir.slice(1)), p, n));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return records;
|
|
116
|
+
}
|
|
117
|
+
/** True when `bytes` start a WARC file, plain or gzipped (the gzip is inflated to check). */
|
|
118
|
+
export function looksLikeWarc(bytes) {
|
|
119
|
+
const magic = (b) => b.byteLength >= 5 && new TextDecoder().decode(b.subarray(0, 5)) === 'WARC/';
|
|
120
|
+
if (magic(bytes))
|
|
121
|
+
return true;
|
|
122
|
+
if (bytes[0] !== 0x1f || bytes[1] !== 0x8b)
|
|
123
|
+
return false;
|
|
124
|
+
try {
|
|
125
|
+
// Inflate only the start of the stream (a truncated prefix, flushed): enough to see the magic.
|
|
126
|
+
return magic(new Uint8Array(gunzipSync(bytes.subarray(0, 4096), { finishFlush: constants.Z_SYNC_FLUSH })));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function inflate(bytes, origin, limits, span) {
|
|
133
|
+
const cap = limits.maxTotalBytes + limits.maxEntries * 4096 + 65536;
|
|
134
|
+
let out;
|
|
135
|
+
try {
|
|
136
|
+
out = new Uint8Array(gunzipSync(bytes, { maxOutputLength: cap }));
|
|
137
|
+
}
|
|
138
|
+
catch (e) {
|
|
139
|
+
if (e.code === 'ERR_BUFFER_TOO_LARGE')
|
|
140
|
+
throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: WARC expands beyond ${cap} bytes`, span);
|
|
141
|
+
throw new SitefileError('E_ARCHIVE', `${origin}: corrupt gzip in WARC`, span);
|
|
142
|
+
}
|
|
143
|
+
if (out.byteLength > 1024 * 1024 && out.byteLength > bytes.byteLength * limits.maxRatio) {
|
|
144
|
+
throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: WARC compression ratio exceeds ${limits.maxRatio}`, span);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
function indexOf(b, pat, from) {
|
|
149
|
+
outer: for (let i = from; i + pat.length <= b.length; i++) {
|
|
150
|
+
for (let k = 0; k < pat.length; k++)
|
|
151
|
+
if (b[i + k] !== pat[k])
|
|
152
|
+
continue outer;
|
|
153
|
+
return i;
|
|
154
|
+
}
|
|
155
|
+
return -1;
|
|
156
|
+
}
|
|
157
|
+
const BLANK = enc.encode('\r\n\r\n');
|
|
158
|
+
const latin1 = new TextDecoder('latin1');
|
|
159
|
+
/** Header lines (`Name: value`, names lower-cased) of a CRLF-separated head. */
|
|
160
|
+
function parseFields(lines) {
|
|
161
|
+
const m = new Map();
|
|
162
|
+
for (const l of lines) {
|
|
163
|
+
const i = l.indexOf(':');
|
|
164
|
+
if (i <= 0)
|
|
165
|
+
continue;
|
|
166
|
+
const k = l.slice(0, i).trim().toLowerCase();
|
|
167
|
+
if (!m.has(k))
|
|
168
|
+
m.set(k, l.slice(i + 1).trim());
|
|
169
|
+
}
|
|
170
|
+
return m;
|
|
171
|
+
}
|
|
172
|
+
/** `scheme://host/path` → [host, path] (lower-case host, path without query or fragment). */
|
|
173
|
+
function splitUrl(uri) {
|
|
174
|
+
const m = /^https?:\/\/([^/?#]*)([^?#]*)/i.exec(uri);
|
|
175
|
+
if (!m)
|
|
176
|
+
return undefined;
|
|
177
|
+
return [m[1].toLowerCase(), m[2] === '' ? '/' : m[2]];
|
|
178
|
+
}
|
|
179
|
+
/** The files of a WARC (plain or gzipped): see the top of this file. */
|
|
180
|
+
export function readWarc(input, origin, limits = DEFAULT_ARCHIVE_LIMITS, span) {
|
|
181
|
+
const bytes = input[0] === 0x1f && input[1] === 0x8b ? inflate(input, origin, limits, span) : input;
|
|
182
|
+
const bad = (why) => new SitefileError('E_ARCHIVE', `${origin}: ${why}`, span);
|
|
183
|
+
const files = new Map();
|
|
184
|
+
let host;
|
|
185
|
+
let total = 0;
|
|
186
|
+
let at = 0;
|
|
187
|
+
while (at < bytes.length) {
|
|
188
|
+
// Records are separated by CRLF CRLF; tolerate extra blank lines between them.
|
|
189
|
+
while (at < bytes.length && (bytes[at] === 0x0d || bytes[at] === 0x0a))
|
|
190
|
+
at++;
|
|
191
|
+
if (at >= bytes.length)
|
|
192
|
+
break;
|
|
193
|
+
const headEnd = indexOf(bytes, BLANK, at);
|
|
194
|
+
if (headEnd === -1)
|
|
195
|
+
throw bad('truncated WARC record header');
|
|
196
|
+
const lines = latin1.decode(bytes.subarray(at, headEnd)).split('\r\n');
|
|
197
|
+
if (!/^WARC\/1\.[01]$/.test(lines[0] ?? ''))
|
|
198
|
+
throw bad(`not a WARC record at byte ${at}`);
|
|
199
|
+
const fields = parseFields(lines.slice(1));
|
|
200
|
+
const lenText = fields.get('content-length') ?? '';
|
|
201
|
+
if (!/^[0-9]{1,15}$/.test(lenText))
|
|
202
|
+
throw bad('WARC record without a valid Content-Length');
|
|
203
|
+
const start = headEnd + 4;
|
|
204
|
+
const end = start + Number(lenText);
|
|
205
|
+
if (end > bytes.length)
|
|
206
|
+
throw bad('truncated WARC record');
|
|
207
|
+
at = end;
|
|
208
|
+
if (fields.get('warc-type') !== 'response' || !(fields.get('content-type') ?? '').toLowerCase().startsWith('application/http'))
|
|
209
|
+
continue;
|
|
210
|
+
const target = splitUrl(fields.get('warc-target-uri') ?? '');
|
|
211
|
+
if (!target)
|
|
212
|
+
continue;
|
|
213
|
+
const block = bytes.subarray(start, end);
|
|
214
|
+
const httpEnd = indexOf(block, BLANK, 0);
|
|
215
|
+
if (httpEnd === -1)
|
|
216
|
+
continue;
|
|
217
|
+
const status = latin1.decode(block.subarray(0, Math.min(httpEnd, 64))).split('\r\n')[0] ?? '';
|
|
218
|
+
if (!/^HTTP\/\d(\.\d)? 200( |$)/.test(status))
|
|
219
|
+
continue;
|
|
220
|
+
const [h, rawPath] = target;
|
|
221
|
+
host ??= h;
|
|
222
|
+
if (h !== host)
|
|
223
|
+
continue;
|
|
224
|
+
const segs = rawPath.split('/').slice(1).map(percentDecode);
|
|
225
|
+
if (segs[segs.length - 1] === '')
|
|
226
|
+
segs[segs.length - 1] = 'index.html';
|
|
227
|
+
for (const s of segs) {
|
|
228
|
+
if (s === '' || s === '.' || s === '..' || s.includes('\0') || s.includes('\\') || s.includes('/')) {
|
|
229
|
+
throw new SitefileError('E_ARCHIVE_UNSAFE', `${origin}: unsafe path in WARC record for ${fields.get('warc-target-uri')}`, span);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const p = '/' + segs.join('/');
|
|
233
|
+
if (files.has(p))
|
|
234
|
+
continue;
|
|
235
|
+
const body = block.subarray(httpEnd + 4);
|
|
236
|
+
total += body.byteLength;
|
|
237
|
+
if (files.size + 1 > limits.maxEntries)
|
|
238
|
+
throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: more than ${limits.maxEntries} entries`, span);
|
|
239
|
+
if (total > limits.maxTotalBytes)
|
|
240
|
+
throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: WARC expands beyond ${limits.maxTotalBytes} bytes`, span);
|
|
241
|
+
files.set(p, makeFile(new Uint8Array(body), `${origin}`));
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
return Tree.fromFiles(files);
|
|
245
|
+
}
|
|
246
|
+
catch (e) {
|
|
247
|
+
if (e instanceof SitefileError)
|
|
248
|
+
throw new SitefileError('E_ARCHIVE_UNSAFE', `${origin}: ${e.message}`, span, { cause: e });
|
|
249
|
+
throw e;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
//# sourceMappingURL=warc.js.map
|
package/lib/src/watch.d.ts
CHANGED
|
@@ -39,6 +39,17 @@ export interface WatchSpec {
|
|
|
39
39
|
readonly files: readonly string[];
|
|
40
40
|
/** Called with the absolute path of each change (the directory itself when the OS gives no name). */
|
|
41
41
|
readonly onChange: (abs: string) => void;
|
|
42
|
+
/**
|
|
43
|
+
* `--poll`: compare stat snapshots every this many milliseconds instead of using file system
|
|
44
|
+
* events (for network shares, Docker bind mounts and WSL paths, where events do not arrive).
|
|
45
|
+
*/
|
|
46
|
+
readonly pollMs?: number;
|
|
47
|
+
/** Paths the poller does not descend into or report (it re-checks at every scan). */
|
|
48
|
+
readonly ignore?: (abs: string) => boolean;
|
|
42
49
|
}
|
|
43
|
-
/**
|
|
50
|
+
/** Default interval of `--poll`. */
|
|
51
|
+
export declare const DEFAULT_POLL_MS = 1000;
|
|
52
|
+
/** A stat snapshot of `spec`'s directories (recursive) and files; a missing file is `missing`. */
|
|
53
|
+
export declare function pollSnapshot(spec: Pick<WatchSpec, 'dirs' | 'files' | 'ignore'>): Promise<Map<string, string>>;
|
|
54
|
+
/** Start fs.watch watchers (or, with `pollMs`, a poller) for `spec`; returns a function that closes them. */
|
|
44
55
|
export declare function watchPaths(spec: WatchSpec): () => void;
|
package/lib/src/watch.js
CHANGED
|
@@ -96,8 +96,74 @@ export async function resolveReal(p) {
|
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
-
/**
|
|
99
|
+
/** Default interval of `--poll`. */
|
|
100
|
+
export const DEFAULT_POLL_MS = 1000;
|
|
101
|
+
/** What a poll compares per path: type, size, mtime, ctime and inode (symlinks are not followed). */
|
|
102
|
+
function stampOf(st) {
|
|
103
|
+
return `${st.mode & 61440n}:${st.size}:${st.mtimeNs}:${st.ctimeNs}:${st.ino}`;
|
|
104
|
+
}
|
|
105
|
+
/** A stat snapshot of `spec`'s directories (recursive) and files; a missing file is `missing`. */
|
|
106
|
+
export async function pollSnapshot(spec) {
|
|
107
|
+
const out = new Map();
|
|
108
|
+
const walk = async (dir) => {
|
|
109
|
+
let entries;
|
|
110
|
+
try {
|
|
111
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
for (const e of entries) {
|
|
117
|
+
const p = path.join(dir, e.name);
|
|
118
|
+
if (spec.ignore?.(p))
|
|
119
|
+
continue;
|
|
120
|
+
const st = await fs.lstat(p, { bigint: true }).catch(() => undefined);
|
|
121
|
+
if (st === undefined)
|
|
122
|
+
continue;
|
|
123
|
+
out.set(p, stampOf(st));
|
|
124
|
+
if (st.isDirectory())
|
|
125
|
+
await walk(p);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
for (const d of spec.dirs)
|
|
129
|
+
await walk(d);
|
|
130
|
+
for (const f of spec.files) {
|
|
131
|
+
if (out.has(f) || spec.ignore?.(f))
|
|
132
|
+
continue;
|
|
133
|
+
out.set(f, await fs.stat(f, { bigint: true }).then(stampOf, () => 'missing'));
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
/** Poll `spec` every `spec.pollMs`; reports each added, removed or changed path. Returns a function that stops it. */
|
|
138
|
+
function pollPaths(spec) {
|
|
139
|
+
let stopped = false;
|
|
140
|
+
let timer;
|
|
141
|
+
let last;
|
|
142
|
+
const tick = async () => {
|
|
143
|
+
const snap = await pollSnapshot(spec);
|
|
144
|
+
if (stopped)
|
|
145
|
+
return;
|
|
146
|
+
if (last !== undefined) {
|
|
147
|
+
for (const [p, st] of snap)
|
|
148
|
+
if (last.get(p) !== st)
|
|
149
|
+
spec.onChange(p);
|
|
150
|
+
for (const p of last.keys())
|
|
151
|
+
if (!snap.has(p))
|
|
152
|
+
spec.onChange(p);
|
|
153
|
+
}
|
|
154
|
+
last = snap;
|
|
155
|
+
timer = setTimeout(() => void tick(), spec.pollMs);
|
|
156
|
+
};
|
|
157
|
+
void tick();
|
|
158
|
+
return () => {
|
|
159
|
+
stopped = true;
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/** Start fs.watch watchers (or, with `pollMs`, a poller) for `spec`; returns a function that closes them. */
|
|
100
164
|
export function watchPaths(spec) {
|
|
165
|
+
if (spec.pollMs !== undefined)
|
|
166
|
+
return pollPaths({ ...spec, pollMs: spec.pollMs });
|
|
101
167
|
const watchers = [];
|
|
102
168
|
const add = (dir, recursive, names) => {
|
|
103
169
|
const w = fsWatch(dir, { recursive, persistent: true }, (_event, filename) => {
|
package/lib/src/wbn.d.ts
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import type { Tree } from './tree.js';
|
|
2
|
+
/**
|
|
3
|
+
* The content type `serve` and Web Bundle export give a tree path: a well-known extensionless path
|
|
4
|
+
* (`/.well-known/apple-app-site-association`, ...) by its exact name, else by the extension, ASCII
|
|
5
|
+
* case-insensitively (`application/octet-stream` when unknown).
|
|
6
|
+
*/
|
|
2
7
|
export declare function mimeTypeFor(path: string): string;
|
|
3
8
|
/** An absolute https URL ending in `/`, without credentials, query or fragment. Returns its normalized form. */
|
|
4
9
|
export declare function validateBaseUrl(raw: string | undefined): string;
|
|
5
10
|
export declare function writeWebBundle(tree: Tree, baseUrl: string | undefined): Uint8Array;
|
|
11
|
+
/** {@link writeWebBundle} at a base URL the caller has already validated (`isolated-app://<id>/` for swbn). */
|
|
12
|
+
export declare function writeWebBundleAt(tree: Tree, base: string): Uint8Array;
|
|
6
13
|
/**
|
|
7
14
|
* The responses section and its URLs (tree paths, percent-encoded by the caller), as `sitefile
|
|
8
15
|
* serve` would answer them:
|
|
@@ -15,7 +22,8 @@ export declare function writeWebBundle(tree: Tree, baseUrl: string | undefined):
|
|
|
15
22
|
* `location` of the rule's target as written, and an empty body: at its path when no file
|
|
16
23
|
* would be served there, and over the file when forced (`301!`). Like `serve`, the first rule
|
|
17
24
|
* matching the path decides; when that is a splat or a 200/404 rewrite, the bundle leaves the
|
|
18
|
-
* path to `/_redirects`. Splat rules and
|
|
25
|
+
* path to `/_redirects`. Splat rules, rewrites and rules with placeholders, query parameters or
|
|
26
|
+
* conditions (which are left out entirely) are not baked in.
|
|
19
27
|
*
|
|
20
28
|
* `/_headers` and `/_redirects` stay in the bundle as files. Responses are deduplicated (both URLs
|
|
21
29
|
* of an index page share one when their headers agree; identical redirects share one).
|
package/lib/src/wbn.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SitefileError } from './errors.js';
|
|
2
2
|
import { cborArray, cborBytes, cborMap, cborText, cborUint } from './cbor.js';
|
|
3
|
-
import { headersFor, matchRedirect, parseHeaderRules, parseRedirectRules } from './serve-rules.js';
|
|
3
|
+
import { headersFor, isPlainRule, matchRedirect, parseHeaderRules, parseRedirectRules } from './serve-rules.js';
|
|
4
|
+
import { MIME_TYPES, WELL_KNOWN_TYPES } from './mime-data.js';
|
|
4
5
|
/**
|
|
5
6
|
* Unsigned Web Bundle, format version "b2"
|
|
6
7
|
* (draft-ietf-wpack-bundled-responses). Layout, as one CBOR array:
|
|
@@ -27,38 +28,22 @@ import { headersFor, matchRedirect, parseHeaderRules, parseRedirectRules } from
|
|
|
27
28
|
*/
|
|
28
29
|
const MAGIC = Buffer.from('f09f8c90f09f93a6', 'hex');
|
|
29
30
|
const VERSION = Buffer.from([0x62, 0x32, 0x00, 0x00]);
|
|
30
|
-
|
|
31
|
-
const MIME =
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
svg: 'image/svg+xml' + TEXT_CHARSET,
|
|
39
|
-
txt: 'text/plain' + TEXT_CHARSET,
|
|
40
|
-
xml: 'application/xml' + TEXT_CHARSET,
|
|
41
|
-
webmanifest: 'application/manifest+json' + TEXT_CHARSET,
|
|
42
|
-
png: 'image/png',
|
|
43
|
-
jpg: 'image/jpeg',
|
|
44
|
-
jpeg: 'image/jpeg',
|
|
45
|
-
gif: 'image/gif',
|
|
46
|
-
webp: 'image/webp',
|
|
47
|
-
avif: 'image/avif',
|
|
48
|
-
ico: 'image/x-icon',
|
|
49
|
-
wasm: 'application/wasm',
|
|
50
|
-
woff: 'font/woff',
|
|
51
|
-
woff2: 'font/woff2',
|
|
52
|
-
pdf: 'application/pdf',
|
|
53
|
-
mp4: 'video/mp4',
|
|
54
|
-
webm: 'video/webm',
|
|
55
|
-
mp3: 'audio/mpeg',
|
|
56
|
-
};
|
|
31
|
+
/** Content types by extension and well-known path (tools/gen-mime.mjs; the same tables as rust/src/mime_data.rs). */
|
|
32
|
+
const MIME = new Map(MIME_TYPES);
|
|
33
|
+
const WELL_KNOWN = new Map(WELL_KNOWN_TYPES);
|
|
34
|
+
/**
|
|
35
|
+
* The content type `serve` and Web Bundle export give a tree path: a well-known extensionless path
|
|
36
|
+
* (`/.well-known/apple-app-site-association`, ...) by its exact name, else by the extension, ASCII
|
|
37
|
+
* case-insensitively (`application/octet-stream` when unknown).
|
|
38
|
+
*/
|
|
57
39
|
export function mimeTypeFor(path) {
|
|
40
|
+
const known = WELL_KNOWN.get(path);
|
|
41
|
+
if (known !== undefined)
|
|
42
|
+
return known;
|
|
58
43
|
const base = path.slice(path.lastIndexOf('/') + 1);
|
|
59
44
|
const dot = base.lastIndexOf('.');
|
|
60
|
-
const ext = dot < 0 ? '' : base.slice(dot + 1).toLowerCase();
|
|
61
|
-
return MIME
|
|
45
|
+
const ext = dot < 0 ? '' : base.slice(dot + 1).replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
46
|
+
return MIME.get(ext) ?? 'application/octet-stream';
|
|
62
47
|
}
|
|
63
48
|
/** An absolute https URL ending in `/`, without credentials, query or fragment. Returns its normalized form. */
|
|
64
49
|
export function validateBaseUrl(raw) {
|
|
@@ -93,7 +78,10 @@ function encodePath(p) {
|
|
|
93
78
|
const enc = new TextEncoder();
|
|
94
79
|
const bstr = (s) => cborBytes(enc.encode(s));
|
|
95
80
|
export function writeWebBundle(tree, baseUrl) {
|
|
96
|
-
|
|
81
|
+
return writeWebBundleAt(tree, validateBaseUrl(baseUrl));
|
|
82
|
+
}
|
|
83
|
+
/** {@link writeWebBundle} at a base URL the caller has already validated (`isolated-app://<id>/` for swbn). */
|
|
84
|
+
export function writeWebBundleAt(tree, base) {
|
|
97
85
|
const { responses, urls } = bundleResponses(tree);
|
|
98
86
|
const index = [];
|
|
99
87
|
// Offset of the first response = size of the responses array head.
|
|
@@ -153,7 +141,8 @@ function exactRedirect(rules, forced, path) {
|
|
|
153
141
|
* `location` of the rule's target as written, and an empty body: at its path when no file
|
|
154
142
|
* would be served there, and over the file when forced (`301!`). Like `serve`, the first rule
|
|
155
143
|
* matching the path decides; when that is a splat or a 200/404 rewrite, the bundle leaves the
|
|
156
|
-
* path to `/_redirects`. Splat rules and
|
|
144
|
+
* path to `/_redirects`. Splat rules, rewrites and rules with placeholders, query parameters or
|
|
145
|
+
* conditions (which are left out entirely) are not baked in.
|
|
157
146
|
*
|
|
158
147
|
* `/_headers` and `/_redirects` stay in the bundle as files. Responses are deduplicated (both URLs
|
|
159
148
|
* of an index page share one when their headers agree; identical redirects share one).
|
|
@@ -163,7 +152,8 @@ export function bundleResponses(tree) {
|
|
|
163
152
|
const f = tree.get(p);
|
|
164
153
|
return f ? new TextDecoder().decode(f.bytes) : '';
|
|
165
154
|
};
|
|
166
|
-
|
|
155
|
+
// Rules with placeholders, query parameters or conditions depend on the request: left to `/_redirects`.
|
|
156
|
+
const redirects = parseRedirectRules(text('/_redirects')).filter(isPlainRule);
|
|
167
157
|
const headerRules = parseHeaderRules(text('/_headers'));
|
|
168
158
|
const responses = [];
|
|
169
159
|
const urls = [];
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** One frame of `content` compressed against the raw-content `dictionary`. */
|
|
2
|
+
export declare function zstdCompress(content: Uint8Array, dictionary?: Uint8Array): Uint8Array;
|
|
3
|
+
/** The `dcz` header: a skippable-frame magic, then the SHA-256 of the dictionary. */
|
|
4
|
+
export declare function dczEncode(content: Uint8Array, dictionary: Uint8Array): Uint8Array;
|