@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.
Files changed (130) hide show
  1. package/CHANGELOG.md +480 -3
  2. package/README.md +70 -21
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/canonical.d.ts +16 -0
  6. package/lib/src/canonical.js +46 -0
  7. package/lib/src/car.d.ts +34 -0
  8. package/lib/src/car.js +203 -0
  9. package/lib/src/checklinks.js +8 -2
  10. package/lib/src/cli/bake.js +4 -3
  11. package/lib/src/cli/build-image.d.ts +1 -0
  12. package/lib/src/cli/build-image.js +1 -0
  13. package/lib/src/cli/common.js +4 -1
  14. package/lib/src/cli/hosts.d.ts +5 -0
  15. package/lib/src/cli/hosts.js +78 -0
  16. package/lib/src/cli/images.js +23 -5
  17. package/lib/src/cli/import-config.d.ts +2 -0
  18. package/lib/src/cli/import-config.js +56 -0
  19. package/lib/src/cli/index.d.ts +3 -1
  20. package/lib/src/cli/index.js +31 -2
  21. package/lib/src/cli/integrity.d.ts +2 -0
  22. package/lib/src/cli/integrity.js +77 -0
  23. package/lib/src/cli/network.d.ts +7 -0
  24. package/lib/src/cli/network.js +14 -3
  25. package/lib/src/cli/serve-keys.d.ts +39 -0
  26. package/lib/src/cli/serve-keys.js +106 -0
  27. package/lib/src/cli/serve-worker.js +46 -8
  28. package/lib/src/cli/servers.d.ts +124 -1
  29. package/lib/src/cli/servers.js +705 -62
  30. package/lib/src/cli/up.d.ts +2 -0
  31. package/lib/src/cli/up.js +193 -0
  32. package/lib/src/cli/watch.d.ts +14 -1
  33. package/lib/src/cli/watch.js +20 -3
  34. package/lib/src/cli.js +138 -18
  35. package/lib/src/csp.d.ts +17 -0
  36. package/lib/src/csp.js +52 -0
  37. package/lib/src/dictionary.d.ts +16 -0
  38. package/lib/src/dictionary.js +89 -0
  39. package/lib/src/epub.d.ts +5 -0
  40. package/lib/src/epub.js +113 -0
  41. package/lib/src/errors.d.ts +22 -9
  42. package/lib/src/errors.js +20 -1
  43. package/lib/src/executor.d.ts +31 -1
  44. package/lib/src/executor.js +192 -22
  45. package/lib/src/explain.js +33 -3
  46. package/lib/src/export-for.d.ts +42 -0
  47. package/lib/src/export-for.js +466 -0
  48. package/lib/src/export-formats.d.ts +2 -2
  49. package/lib/src/export-formats.js +52 -2
  50. package/lib/src/fingerprint.d.ts +3 -1
  51. package/lib/src/fingerprint.js +32 -5
  52. package/lib/src/host-config.d.ts +34 -0
  53. package/lib/src/host-config.js +645 -0
  54. package/lib/src/hosts.d.ts +47 -0
  55. package/lib/src/hosts.js +106 -0
  56. package/lib/src/index.d.ts +1 -1
  57. package/lib/src/index.js +1 -1
  58. package/lib/src/integrity.d.ts +115 -0
  59. package/lib/src/integrity.js +273 -0
  60. package/lib/src/language/ast.d.ts +116 -3
  61. package/lib/src/language/ast.js +7 -1
  62. package/lib/src/language/parser.js +176 -7
  63. package/lib/src/language/validate.js +21 -0
  64. package/lib/src/links.d.ts +33 -0
  65. package/lib/src/links.js +271 -3
  66. package/lib/src/lint.d.ts +1 -1
  67. package/lib/src/lint.js +26 -1
  68. package/lib/src/mime-data.d.ts +2 -0
  69. package/lib/src/mime-data.js +92 -0
  70. package/lib/src/oci.d.ts +20 -2
  71. package/lib/src/oci.js +70 -28
  72. package/lib/src/outdated.d.ts +3 -0
  73. package/lib/src/outdated.js +4 -4
  74. package/lib/src/planner.d.ts +69 -2
  75. package/lib/src/planner.js +150 -8
  76. package/lib/src/plugins/cache.d.ts +11 -0
  77. package/lib/src/plugins/cache.js +29 -0
  78. package/lib/src/plugins/host.d.ts +51 -2
  79. package/lib/src/plugins/host.js +144 -18
  80. package/lib/src/plugins/wasm.js +1 -3
  81. package/lib/src/portable.d.ts +8 -0
  82. package/lib/src/portable.js +47 -0
  83. package/lib/src/precache.d.ts +33 -0
  84. package/lib/src/precache.js +75 -0
  85. package/lib/src/precompress.d.ts +19 -0
  86. package/lib/src/precompress.js +35 -0
  87. package/lib/src/qr.d.ts +18 -0
  88. package/lib/src/qr.js +372 -0
  89. package/lib/src/registry-ops.js +4 -2
  90. package/lib/src/reload-client.d.ts +2 -0
  91. package/lib/src/reload-client.js +304 -0
  92. package/lib/src/resources/archive.d.ts +36 -0
  93. package/lib/src/resources/archive.js +338 -67
  94. package/lib/src/resources/convert.js +3 -1
  95. package/lib/src/resources/https.d.ts +9 -1
  96. package/lib/src/resources/https.js +36 -0
  97. package/lib/src/resources/network.d.ts +25 -3
  98. package/lib/src/resources/network.js +77 -6
  99. package/lib/src/secrets.d.ts +12 -3
  100. package/lib/src/secrets.js +18 -5
  101. package/lib/src/serve-auth.d.ts +32 -0
  102. package/lib/src/serve-auth.js +112 -0
  103. package/lib/src/serve-rules.d.ts +83 -7
  104. package/lib/src/serve-rules.js +264 -53
  105. package/lib/src/server.d.ts +437 -10
  106. package/lib/src/server.js +1236 -52
  107. package/lib/src/servers-file.d.ts +36 -0
  108. package/lib/src/servers-file.js +101 -0
  109. package/lib/src/servers.d.ts +109 -7
  110. package/lib/src/servers.js +151 -29
  111. package/lib/src/single-file.d.ts +12 -0
  112. package/lib/src/single-file.js +147 -0
  113. package/lib/src/site.d.ts +54 -0
  114. package/lib/src/site.js +204 -6
  115. package/lib/src/store.js +9 -5
  116. package/lib/src/swbn.d.ts +10 -0
  117. package/lib/src/swbn.js +86 -0
  118. package/lib/src/toml.d.ts +17 -0
  119. package/lib/src/toml.js +323 -0
  120. package/lib/src/wacz.d.ts +6 -0
  121. package/lib/src/wacz.js +96 -0
  122. package/lib/src/warc.d.ts +28 -0
  123. package/lib/src/warc.js +252 -0
  124. package/lib/src/watch.d.ts +12 -1
  125. package/lib/src/watch.js +67 -1
  126. package/lib/src/wbn.d.ts +9 -1
  127. package/lib/src/wbn.js +23 -33
  128. package/lib/src/zstd.d.ts +4 -0
  129. package/lib/src/zstd.js +328 -0
  130. package/package.json +1 -1
@@ -0,0 +1,466 @@
1
+ import { SitefileError } from './errors.js';
2
+ import { globMatch } from './serve-rules.js';
3
+ import { makeFile, Tree } from './tree.js';
4
+ const PLACEHOLDER_SEG = /^:[A-Za-z_][A-Za-z0-9_]*$/;
5
+ /** What a REDIRECT source is: an exact path, `<prefix>/*`, `:placeholder` segments (and a trailing `/*`), or other. */
6
+ function shapeOf(from) {
7
+ const splat = from === '/*' || from.endsWith('/*');
8
+ const head = splat ? from.slice(0, -2) : from;
9
+ if (head.includes('*'))
10
+ return { kind: 'other' };
11
+ const segments = head.split('/').slice(1);
12
+ const named = segments.some((s) => s.startsWith(':'));
13
+ if (named) {
14
+ if (!segments.every((s) => !s.startsWith(':') || PLACEHOLDER_SEG.test(s)))
15
+ return { kind: 'other' };
16
+ return { kind: 'placeholders', segments, splat };
17
+ }
18
+ if (splat)
19
+ return { kind: 'splat', prefix: head };
20
+ return { kind: 'exact', path: from };
21
+ }
22
+ /** The path a file in `tree` answers for `from` (Netlify serves a file before a rule), if any. */
23
+ function shadowingFile(tree, from) {
24
+ const s = shapeOf(from);
25
+ const files = tree.entries().map(([p]) => p);
26
+ if (s.kind === 'exact') {
27
+ const p = s.path.length > 1 && s.path.endsWith('/') ? s.path.slice(0, -1) : s.path;
28
+ for (const c of p === '/' ? ['/index.html'] : [p, `${p}/index.html`, `${p}.html`])
29
+ if (tree.isFile(c))
30
+ return c;
31
+ return undefined;
32
+ }
33
+ const prefix = s.kind === 'splat' ? s.prefix : s.kind === 'placeholders' ? '/' + s.segments.slice(0, s.segments.findIndex((x) => x.startsWith(':'))).join('/') : '';
34
+ const dir = prefix === '/' || prefix === '' ? '/' : `${prefix}/`;
35
+ return files.find((f) => f.startsWith(dir));
36
+ }
37
+ class Ctx {
38
+ host;
39
+ o;
40
+ constructor(host, o) {
41
+ this.host = host;
42
+ this.o = o;
43
+ }
44
+ redirectText(r) {
45
+ return `REDIRECT ${r.from} ${r.to} ${r.status}`;
46
+ }
47
+ /** Refuse `r` (E_EXPORT), or with --lossy warn and leave it out. */
48
+ refuse(r, reason) {
49
+ const what = this.redirectText(r);
50
+ if (this.o.lossy) {
51
+ this.o.warn(`${this.o.label}:${r.span.line} ${what}: ${reason}; left out (--lossy)`);
52
+ return;
53
+ }
54
+ throw new SitefileError('E_EXPORT', `EXPORT … FOR ${this.host}: ${what}: ${reason} (build with --lossy to leave it out)`, r.span);
55
+ }
56
+ refuseHeader(h, reason) {
57
+ if (h.auto) {
58
+ this.o.warn(`${this.o.label}:${h.span.line} FINGERPRINT: the ${h.name} header for ${h.pattern} is left out: ${reason}`);
59
+ return;
60
+ }
61
+ const what = `HEADER ${h.pattern} ${h.name}`;
62
+ if (this.o.lossy) {
63
+ this.o.warn(`${this.o.label}:${h.span.line} ${what}: ${reason}; left out (--lossy)`);
64
+ return;
65
+ }
66
+ throw new SitefileError('E_EXPORT', `EXPORT … FOR ${this.host}: ${what}: ${reason} (build with --lossy to leave it out)`, h.span);
67
+ }
68
+ /** False (and refused) when a file in the export answers the rule's path first on Netlify. */
69
+ unshadowed(tree, r, hostName) {
70
+ const f = shadowingFile(tree, r.from);
71
+ if (f === undefined)
72
+ return true;
73
+ this.refuse(r, `${f} is a file in the export: Netlify and sitefile serve answer with the file, ${hostName} applies the redirect first`);
74
+ return false;
75
+ }
76
+ }
77
+ /** Header rules grouped by pattern, in order of first use. */
78
+ function blocks(headers) {
79
+ const m = new Map();
80
+ for (const h of headers)
81
+ m.set(h.pattern, [...(m.get(h.pattern) ?? []), h]);
82
+ return [...m];
83
+ }
84
+ const json = (v) => new TextEncoder().encode(JSON.stringify(v, null, 2) + '\n');
85
+ /** `output` with every file moved below `dir`. */
86
+ function moved(output, dir) {
87
+ return Tree.fromFiles(output.entries().map(([p, n]) => [dir + p, n]));
88
+ }
89
+ function add(output, files, o, origin) {
90
+ return output.withFiles(files.map(([p, b]) => [p, makeFile(b, `${o.label}:${o.span.line} ${origin}`)]), 'error', o.span);
91
+ }
92
+ // ------------------------------------------------------------------ Cloudflare Pages
93
+ const CF_STATIC_MAX = 2000;
94
+ const CF_DYNAMIC_MAX = 100;
95
+ const CF_HEADER_RULES_MAX = 100;
96
+ function cloudflare(output, rs, hs, c) {
97
+ const redirects = [];
98
+ let statics = 0;
99
+ let dynamics = 0;
100
+ for (const r of rs) {
101
+ if (!c.unshadowed(output, r, 'Cloudflare Pages'))
102
+ continue;
103
+ const dynamic = shapeOf(r.from).kind !== 'exact';
104
+ if (dynamic ? dynamics >= CF_DYNAMIC_MAX : statics >= CF_STATIC_MAX) {
105
+ c.refuse(r, dynamic ? `Cloudflare Pages takes at most ${CF_DYNAMIC_MAX} dynamic redirects` : `Cloudflare Pages takes at most ${CF_STATIC_MAX} static redirects`);
106
+ continue;
107
+ }
108
+ if (dynamic)
109
+ dynamics++;
110
+ else
111
+ statics++;
112
+ redirects.push(r);
113
+ }
114
+ const headers = [];
115
+ const patterns = [];
116
+ for (const h of hs) {
117
+ if (!patterns.includes(h.pattern)) {
118
+ if (patterns.length >= CF_HEADER_RULES_MAX) {
119
+ c.refuseHeader(h, `Cloudflare Pages takes at most ${CF_HEADER_RULES_MAX} header rules`);
120
+ continue;
121
+ }
122
+ patterns.push(h.pattern);
123
+ }
124
+ headers.push(h);
125
+ }
126
+ return { redirects, headers, output };
127
+ }
128
+ // ------------------------------------------------------------------ GitHub Pages
129
+ function githubPages(output, rs, hs, c, o) {
130
+ for (const r of rs)
131
+ c.refuse(r, 'GitHub Pages has no redirects');
132
+ for (const h of hs)
133
+ c.refuseHeader(h, 'GitHub Pages cannot set response headers');
134
+ const files = [['/.nojekyll', new Uint8Array()]];
135
+ if (o.base !== undefined) {
136
+ if (!/^https?:\/\//i.test(o.base))
137
+ throw new SitefileError('E_VALIDATION', `EXPORT … FOR github-pages: BASE must be an http(s) URL, got '${o.base}'`, o.span);
138
+ let u;
139
+ try {
140
+ u = new URL(o.base);
141
+ }
142
+ catch {
143
+ throw new SitefileError('E_VALIDATION', `EXPORT … FOR github-pages: BASE '${o.base}' is not a URL`, o.span);
144
+ }
145
+ const host = u.hostname.toLowerCase();
146
+ if (!host.endsWith('.github.io')) {
147
+ if (u.pathname !== '/' || u.search !== '' || u.hash !== '') {
148
+ throw new SitefileError('E_VALIDATION', `EXPORT … FOR github-pages: a custom domain serves the site at its root, so BASE '${o.base}' cannot have a path`, o.span);
149
+ }
150
+ files.push(['/CNAME', new TextEncoder().encode(`${host}\n`)]);
151
+ }
152
+ }
153
+ return { redirects: [], headers: [], output: add(output, files, o, 'EXPORT FOR github-pages') };
154
+ }
155
+ // ------------------------------------------------------------------ Vercel (Build Output API v3)
156
+ const reEscape = (s) => s.replace(/[.+?^$()[\]{}|\\]/g, '\\$&');
157
+ /** A `_headers` pattern as a Vercel `src`: `*` is any run of characters, `:name` one segment. */
158
+ function headerRegex(pattern) {
159
+ return `^${pattern
160
+ .split('/')
161
+ .map((seg) => (PLACEHOLDER_SEG.test(seg) ? '[^/]+' : seg.split('*').map(reEscape).join('.*')))
162
+ .join('/')}$`;
163
+ }
164
+ /** The names a target uses (`:splat`, `:name` at the start of a path segment), with `$name` in their place. */
165
+ function targetWith(to, sigil) {
166
+ const m = /^(https?:\/\/[^/]*)(.*)$/i.exec(to);
167
+ const [origin, path] = m ? [m[1], m[2]] : ['', to];
168
+ const names = [];
169
+ const out = path.replace(/(^|\/):([A-Za-z_][A-Za-z0-9_]*)/g, (_all, pre, name) => {
170
+ names.push(name);
171
+ return pre + sigil(name);
172
+ });
173
+ return { to: origin + out, names };
174
+ }
175
+ function vercel(output, rs, hs, c, o) {
176
+ const routes = [];
177
+ for (const [pattern, list] of blocks(hs)) {
178
+ const headers = {};
179
+ for (const h of list)
180
+ headers[h.name] = headers[h.name] === undefined ? h.value : `${headers[h.name]}, ${h.value}`;
181
+ routes.push({ src: headerRegex(pattern), headers, continue: true });
182
+ }
183
+ routes.push({ handle: 'filesystem' });
184
+ for (const r of rs) {
185
+ const s = shapeOf(r.from);
186
+ let src;
187
+ const captures = [];
188
+ if (s.kind === 'exact') {
189
+ const p = s.path.length > 1 && s.path.endsWith('/') ? s.path.slice(0, -1) : s.path;
190
+ src = p === '/' ? '^/$' : `^${reEscape(p)}/?$`;
191
+ }
192
+ else if (s.kind === 'splat') {
193
+ src = `^${reEscape(s.prefix)}/(?<splat>.*)$`;
194
+ captures.push('splat');
195
+ }
196
+ else if (s.kind === 'placeholders') {
197
+ const segs = s.segments.map((seg) => {
198
+ if (!PLACEHOLDER_SEG.test(seg))
199
+ return reEscape(seg);
200
+ captures.push(seg.slice(1));
201
+ return `(?<${seg.slice(1)}>[^/]+)`;
202
+ });
203
+ src = `^/${segs.join('/')}${s.splat ? '/(?<splat>.*)' : ''}$`;
204
+ if (s.splat)
205
+ captures.push('splat');
206
+ }
207
+ else {
208
+ c.refuse(r, '* is supported only as a trailing /*');
209
+ continue;
210
+ }
211
+ const t = targetWith(r.to, (n) => `$${n}`);
212
+ const unknown = t.names.find((n) => !captures.includes(n));
213
+ if (unknown !== undefined) {
214
+ c.refuse(r, `:${unknown} in the target is not in the source`);
215
+ continue;
216
+ }
217
+ routes.push({ src, headers: { Location: t.to }, status: r.status });
218
+ }
219
+ if (output.isFile('/404.html'))
220
+ routes.push({ handle: 'error' }, { status: 404, src: '^/.*$', dest: '/404.html' });
221
+ const out = add(moved(output, '/.vercel/output/static'), [['/.vercel/output/config.json', json({ version: 3, routes })]], o, 'EXPORT FOR vercel');
222
+ return { redirects: [], headers: [], output: out };
223
+ }
224
+ // ------------------------------------------------------------------ Firebase Hosting
225
+ function firebase(output, rs, hs, c, o) {
226
+ const redirects = [];
227
+ for (const r of rs) {
228
+ if (r.status !== 301 && r.status !== 302) {
229
+ c.refuse(r, 'Firebase Hosting redirects are 301 or 302');
230
+ continue;
231
+ }
232
+ const s = shapeOf(r.from);
233
+ let source;
234
+ if (s.kind === 'exact')
235
+ source = s.path;
236
+ else if (s.kind === 'splat')
237
+ source = `${s.prefix}/:splat*`;
238
+ else if (s.kind === 'placeholders')
239
+ source = `/${s.segments.join('/')}${s.splat ? '/:splat*' : ''}`;
240
+ else {
241
+ c.refuse(r, '* is supported only as a trailing /*');
242
+ continue;
243
+ }
244
+ if (!c.unshadowed(output, r, 'Firebase Hosting'))
245
+ continue;
246
+ redirects.push({ source, destination: r.to, type: r.status });
247
+ }
248
+ const headers = [];
249
+ for (const [pattern, list] of blocks(hs)) {
250
+ if (pattern.split('/').some((seg) => seg.startsWith(':'))) {
251
+ for (const h of list)
252
+ c.refuseHeader(h, 'Firebase Hosting header sources are globs, without :placeholders');
253
+ continue;
254
+ }
255
+ headers.push({ source: pattern.replace(/\*+/g, '**'), headers: list.map((h) => ({ key: h.name, value: h.value })) });
256
+ }
257
+ const hosting = { public: 'public' };
258
+ if (redirects.length)
259
+ hosting['redirects'] = redirects;
260
+ if (headers.length)
261
+ hosting['headers'] = headers;
262
+ const out = add(moved(output, '/public'), [['/firebase.json', json({ hosting })]], o, 'EXPORT FOR firebase');
263
+ return { redirects: [], headers: [], output: out };
264
+ }
265
+ // ------------------------------------------------------------------ Azure Static Web Apps
266
+ /** A route as (prefix, below): an exact path, or everything below `prefix/` for `prefix/*`. */
267
+ function routeOf(p) {
268
+ const s = shapeOf(p);
269
+ if (s.kind === 'exact')
270
+ return { prefix: s.path, below: false };
271
+ if (s.kind === 'splat')
272
+ return { prefix: s.prefix, below: true };
273
+ return undefined;
274
+ }
275
+ function overlap(a, b) {
276
+ const under = (x, dir) => (dir === '' ? true : x.startsWith(`${dir}/`));
277
+ if (!a.below && !b.below)
278
+ return a.prefix === b.prefix;
279
+ if (a.below && b.below)
280
+ return a.prefix === b.prefix || under(a.prefix, b.prefix) || under(b.prefix, a.prefix);
281
+ const [dir, path] = a.below ? [a.prefix, b.prefix] : [b.prefix, a.prefix];
282
+ return under(path, dir);
283
+ }
284
+ function azure(output, rs, hs, c, o) {
285
+ const routes = [];
286
+ const taken = [];
287
+ for (const r of rs) {
288
+ if (r.status !== 301 && r.status !== 302) {
289
+ c.refuse(r, 'Azure Static Web Apps redirects are 301 or 302');
290
+ continue;
291
+ }
292
+ const route = routeOf(r.from);
293
+ if (!route) {
294
+ c.refuse(r, shapeOf(r.from).kind === 'placeholders' ? 'Azure Static Web Apps routes have no :placeholders' : '* is supported only as a trailing /*');
295
+ continue;
296
+ }
297
+ if (targetWith(r.to, (n) => n).names.length > 0) {
298
+ c.refuse(r, 'Azure Static Web Apps redirects cannot use :splat or :placeholders in the target');
299
+ continue;
300
+ }
301
+ if (!c.unshadowed(output, r, 'Azure Static Web Apps'))
302
+ continue;
303
+ routes.push({ route: r.from, redirect: r.to, statusCode: r.status });
304
+ taken.push({ ...route, what: `REDIRECT ${r.from}` });
305
+ }
306
+ const globalHeaders = {};
307
+ const routeHeaders = [];
308
+ const globalBlock = blocks(hs).find(([p]) => p === '/*');
309
+ for (const h of globalBlock?.[1] ?? [])
310
+ globalHeaders[h.name] = globalHeaders[h.name] === undefined ? h.value : `${globalHeaders[h.name]}, ${h.value}`;
311
+ for (const [pattern, list] of blocks(hs)) {
312
+ if (pattern === '/*')
313
+ continue;
314
+ const route = routeOf(pattern);
315
+ if (!route) {
316
+ for (const h of list)
317
+ c.refuseHeader(h, 'Azure Static Web Apps routes are exact paths or end in /*');
318
+ continue;
319
+ }
320
+ const clash = taken.find((t) => overlap(t, route));
321
+ if (clash) {
322
+ for (const h of list)
323
+ c.refuseHeader(h, `on Azure Static Web Apps only the first matching route applies, and ${clash.what} matches the same paths`);
324
+ continue;
325
+ }
326
+ const headers = {};
327
+ for (const h of list) {
328
+ if (Object.keys(globalHeaders).some((g) => g.toLowerCase() === h.name.toLowerCase())) {
329
+ c.refuseHeader(h, `on Azure Static Web Apps a route's ${h.name} replaces the one for /* instead of adding to it`);
330
+ continue;
331
+ }
332
+ headers[h.name] = headers[h.name] === undefined ? h.value : `${headers[h.name]}, ${h.value}`;
333
+ }
334
+ if (Object.keys(headers).length === 0)
335
+ continue;
336
+ routeHeaders.push({ pattern, route, headers });
337
+ taken.push({ ...route, what: `HEADER ${pattern}` });
338
+ }
339
+ for (const rh of routeHeaders)
340
+ routes.push({ route: rh.pattern, headers: rh.headers });
341
+ const config = {};
342
+ if (routes.length)
343
+ config['routes'] = routes;
344
+ if (Object.keys(globalHeaders).length)
345
+ config['globalHeaders'] = globalHeaders;
346
+ if (output.isFile('/404.html'))
347
+ config['responseOverrides'] = { '404': { rewrite: '/404.html' } };
348
+ const out = add(output, [['/staticwebapp.config.json', json(config)]], o, 'EXPORT FOR azure');
349
+ return { redirects: [], headers: [], output: out };
350
+ }
351
+ // ------------------------------------------------------------------ S3 website hosting
352
+ /** `_headers` names S3 stores as object metadata, and the PutObject field each becomes. */
353
+ const S3_FIELDS = {
354
+ 'cache-control': 'CacheControl',
355
+ 'content-type': 'ContentType',
356
+ 'content-disposition': 'ContentDisposition',
357
+ 'content-encoding': 'ContentEncoding',
358
+ 'content-language': 'ContentLanguage',
359
+ expires: 'Expires',
360
+ };
361
+ const utf16Compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
362
+ function s3(output, rs, hs, c, o) {
363
+ const objects = new Map();
364
+ const object = (key) => {
365
+ let v = objects.get(key);
366
+ if (!v)
367
+ objects.set(key, (v = { Key: key }));
368
+ return v;
369
+ };
370
+ const rules = [];
371
+ for (const r of rs) {
372
+ const s = shapeOf(r.from);
373
+ if (s.kind === 'exact') {
374
+ if (r.status !== 301) {
375
+ c.refuse(r, 'S3 object redirects are always 301');
376
+ continue;
377
+ }
378
+ if (s.path === '/') {
379
+ c.refuse(r, 'S3 cannot redirect the root object');
380
+ continue;
381
+ }
382
+ const key = s.path.endsWith('/') ? `${s.path.slice(1)}index.html` : s.path.slice(1);
383
+ if (output.isFile(`/${key}`)) {
384
+ c.refuse(r, `/${key} is a file in the export, and an S3 object is either a file or a redirect`);
385
+ continue;
386
+ }
387
+ object(key)['WebsiteRedirectLocation'] = r.to;
388
+ continue;
389
+ }
390
+ if (s.kind !== 'splat' || s.prefix === '') {
391
+ c.refuse(r, s.kind === 'placeholders' ? 'S3 routing rules have no :placeholders' : s.kind === 'splat' ? 'S3 cannot redirect every key' : '* is supported only as a trailing /*');
392
+ continue;
393
+ }
394
+ const t = targetWith(r.to, (n) => `:${n}`);
395
+ const splatAtEnd = t.names.length === 1 && t.names[0] === 'splat' && t.to.endsWith(':splat');
396
+ if (t.names.length > 0 && !splatAtEnd) {
397
+ c.refuse(r, 'S3 routing rules can only keep the rest of the path at the end of the target (…/:splat)');
398
+ continue;
399
+ }
400
+ if (!c.unshadowed(output, r, 'S3'))
401
+ continue;
402
+ const m = /^(https?):\/\/([^/]+)(.*)$/i.exec(r.to);
403
+ const path = (m ? m[3] : r.to).replace(/:splat$/, '').replace(/^\//, '');
404
+ const redirect = {};
405
+ if (m) {
406
+ redirect['Protocol'] = m[1].toLowerCase();
407
+ redirect['HostName'] = m[2];
408
+ }
409
+ if (splatAtEnd)
410
+ redirect['ReplaceKeyPrefixWith'] = path;
411
+ else if (path !== '')
412
+ redirect['ReplaceKeyWith'] = path;
413
+ redirect['HttpRedirectCode'] = String(r.status);
414
+ rules.push({ Condition: { KeyPrefixEquals: `${s.prefix.slice(1)}/` }, Redirect: redirect });
415
+ }
416
+ const valid = [];
417
+ for (const h of hs) {
418
+ if (S3_FIELDS[h.name.toLowerCase()] === undefined)
419
+ c.refuseHeader(h, 'S3 serves only Cache-Control, Content-Type, Content-Disposition, Content-Encoding, Content-Language and Expires from object metadata');
420
+ else if (h.pattern.split('/').some((seg) => seg.startsWith(':')))
421
+ c.refuseHeader(h, 'S3 object metadata is set per file, so the pattern cannot have :placeholders');
422
+ else
423
+ valid.push(h);
424
+ }
425
+ for (const [f] of output.entries()) {
426
+ const urls = f.endsWith('/index.html') ? [f, f.slice(0, -'index.html'.length)] : [f];
427
+ for (const h of valid) {
428
+ if (!urls.some((u) => globMatch(h.pattern, u)))
429
+ continue;
430
+ const rec = object(f.slice(1));
431
+ const field = S3_FIELDS[h.name.toLowerCase()];
432
+ rec[field] = rec[field] === undefined ? h.value : `${rec[field]}, ${h.value}`;
433
+ }
434
+ }
435
+ const website = { IndexDocument: { Suffix: 'index.html' } };
436
+ if (output.isFile('/404.html'))
437
+ website['ErrorDocument'] = { Key: '404.html' };
438
+ if (rules.length)
439
+ website['RoutingRules'] = rules;
440
+ const list = [...objects.values()].sort((a, b) => utf16Compare(a['Key'], b['Key']));
441
+ const out = add(output, [
442
+ ['/_s3/website.json', json(website)],
443
+ ['/_s3/objects.json', json(list)],
444
+ ], o, 'EXPORT FOR s3');
445
+ return { redirects: [], headers: [], output: out };
446
+ }
447
+ // ------------------------------------------------------------------ entry point
448
+ /** Apply `EXPORT … FOR <host>` (not `netlify`, which is `_redirects` and `_headers` as they are). */
449
+ export function exportForHost(host, output, redirects, headers, o) {
450
+ const c = new Ctx(host, o);
451
+ switch (host) {
452
+ case 'cloudflare':
453
+ return cloudflare(output, redirects, headers, c);
454
+ case 'github-pages':
455
+ return githubPages(output, redirects, headers, c, o);
456
+ case 'vercel':
457
+ return vercel(output, redirects, headers, c, o);
458
+ case 'firebase':
459
+ return firebase(output, redirects, headers, c, o);
460
+ case 'azure':
461
+ return azure(output, redirects, headers, c, o);
462
+ case 's3':
463
+ return s3(output, redirects, headers, c, o);
464
+ }
465
+ }
466
+ //# sourceMappingURL=export-for.js.map
@@ -6,11 +6,11 @@ export type ArchiveFormat = Exclude<ExportFormat, 'directory' | 'oci'>;
6
6
  export declare function isArchiveFormat(f: ExportFormat): f is ArchiveFormat;
7
7
  /**
8
8
  * Default output path relative to the context: `dist`, `dist.zip`, `dist.tar`, `dist.tar.gz`, `dist.wbn`
9
- * (`dist.wbn.gz` for a gzipped bundle), `dist.oci.tar`.
9
+ * (`dist.wbn.gz` for a gzipped bundle), `dist.oci.tar`, `dist.car`, `dist.html`, `dist.mhtml`, `dist.warc` (`dist.warc.gz` gzipped), `dist.swbn`, `dist.wacz`, `dist.epub`.
10
10
  */
11
11
  export declare function defaultOutName(format: ExportFormat, compression?: OciCompression): string;
12
12
  export interface EncodeOptions extends WriterOptions {
13
- /** Required for `wbn`: absolute https URL ending in `/`. */
13
+ /** Required for `wbn`: absolute https URL ending in `/`; for `mhtml`, the parts' URLs (default https://site.invalid/). */
14
14
  readonly baseUrl?: string | undefined;
15
15
  /** `wbn`: `gzip` wraps the finished bundle in gzip (the shared deterministic encoder); default none. */
16
16
  readonly compression?: OciCompression | undefined;
@@ -1,13 +1,19 @@
1
+ import { writeEpub } from './epub.js';
2
+ import { SitefileError } from './errors.js';
1
3
  import { writeTar, writeTgz, writeZip } from './archive-writers.js';
2
4
  import { gzip } from './deflate.js';
3
5
  import { writeWebBundle } from './wbn.js';
6
+ import { writeCar } from './car.js';
7
+ import { writeMhtml, writeSingleFile } from './single-file.js';
8
+ import { writeWacz } from './wacz.js';
9
+ import { writeWarc } from './warc.js';
4
10
  /** Single-file formats encoded by {@link encodeTree}. `oci` is handled separately (layout directory or OCI archive). */
5
11
  export function isArchiveFormat(f) {
6
12
  return f !== 'directory' && f !== 'oci';
7
13
  }
8
14
  /**
9
15
  * Default output path relative to the context: `dist`, `dist.zip`, `dist.tar`, `dist.tar.gz`, `dist.wbn`
10
- * (`dist.wbn.gz` for a gzipped bundle), `dist.oci.tar`.
16
+ * (`dist.wbn.gz` for a gzipped bundle), `dist.oci.tar`, `dist.car`, `dist.html`, `dist.mhtml`, `dist.warc` (`dist.warc.gz` gzipped), `dist.swbn`, `dist.wacz`, `dist.epub`.
11
17
  */
12
18
  export function defaultOutName(format, compression) {
13
19
  switch (format) {
@@ -23,6 +29,20 @@ export function defaultOutName(format, compression) {
23
29
  return compression === 'gzip' ? 'dist.wbn.gz' : 'dist.wbn';
24
30
  case 'oci':
25
31
  return 'dist.oci.tar';
32
+ case 'car':
33
+ return 'dist.car';
34
+ case 'html':
35
+ return 'dist.html';
36
+ case 'mhtml':
37
+ return 'dist.mhtml';
38
+ case 'warc':
39
+ return compression === 'gzip' ? 'dist.warc.gz' : 'dist.warc';
40
+ case 'swbn':
41
+ return 'dist.swbn';
42
+ case 'wacz':
43
+ return 'dist.wacz';
44
+ case 'epub':
45
+ return 'dist.epub';
26
46
  }
27
47
  }
28
48
  /** Serialize a tree in an archive format. Deterministic: see archive-writers.ts and wbn.ts. */
@@ -39,6 +59,21 @@ export function encodeTree(tree, format, options = {}) {
39
59
  const bundle = writeWebBundle(tree, options.baseUrl);
40
60
  return options.compression === 'gzip' ? gzip(bundle) : bundle;
41
61
  }
62
+ case 'car':
63
+ return writeCar(tree);
64
+ case 'html':
65
+ return writeSingleFile(tree);
66
+ case 'mhtml':
67
+ return writeMhtml(tree, undefined, options.baseUrl);
68
+ case 'warc':
69
+ return writeWarc(tree, { baseUrl: options.baseUrl, epoch: options.epoch, compression: options.compression });
70
+ case 'swbn':
71
+ // Signing needs the build's secrets: see exportBuild in executor.ts.
72
+ throw new SitefileError('E_VALIDATION', "swbn export needs a signing key: build with 'EXPORT ... AS swbn KEY <secret-id>' and --secret");
73
+ case 'wacz':
74
+ return writeWacz(tree, { baseUrl: options.baseUrl, epoch: options.epoch });
75
+ case 'epub':
76
+ return writeEpub(tree, options.epoch);
42
77
  }
43
78
  }
44
79
  /** The export format implied by an output file name, if it has an archive extension. */
@@ -54,10 +89,25 @@ export function formatFromExtension(out) {
54
89
  return 'zip';
55
90
  if (name.endsWith('.wbn') || name.endsWith('.wbn.gz'))
56
91
  return 'wbn';
92
+ if (name.endsWith('.car'))
93
+ return 'car';
94
+ if (name.endsWith('.swbn'))
95
+ return 'swbn';
96
+ if (name.endsWith('.warc') || name.endsWith('.warc.gz'))
97
+ return 'warc';
98
+ if (name.endsWith('.wacz'))
99
+ return 'wacz';
100
+ if (name.endsWith('.mhtml') || name.endsWith('.mht'))
101
+ return 'mhtml';
102
+ if (name.endsWith('.epub'))
103
+ return 'epub';
57
104
  return undefined;
58
105
  }
59
106
  /** The compression implied by an output file name for `format`: `gzip` for a wbn written to `*.wbn.gz`. */
60
107
  export function compressionFromExtension(out, format) {
61
- return format === 'wbn' && out.toLowerCase().endsWith('.wbn.gz') ? 'gzip' : undefined;
108
+ const name = out.toLowerCase();
109
+ if (format === 'wbn')
110
+ return name.endsWith('.wbn.gz') ? 'gzip' : undefined;
111
+ return format === 'warc' && name.endsWith('.warc.gz') ? 'gzip' : undefined;
62
112
  }
63
113
  //# sourceMappingURL=export-formats.js.map
@@ -6,7 +6,7 @@ export declare const HASH_LENGTH = 10;
6
6
  * Check a FINGERPRINT pattern: an absolute path (NFC) with no control characters. A trailing `/`
7
7
  * means everything below that directory (`/assets/` is `/assets/**`).
8
8
  */
9
- export declare function checkPattern(raw: string, span: SourceSpan): string;
9
+ export declare function checkPattern(raw: string, span: SourceSpan, what?: string): string;
10
10
  /**
11
11
  * Whether a tree path matches a pattern. Segments are compared one by one; a `**` segment matches any
12
12
  * number of segments (also none). Matching is by code point and case-sensitive.
@@ -17,6 +17,8 @@ export declare function hashedName(path: string, hash: string): string;
17
17
  export interface FingerprintOp {
18
18
  readonly patterns: readonly string[];
19
19
  readonly manifest?: string;
20
+ /** `INTEGRITY`: add Subresource Integrity attributes for the renamed files to the HTML that loads them. */
21
+ readonly integrity?: boolean;
20
22
  /** The directory the site is served from (the EXPORT path): absolute references resolve below it. */
21
23
  readonly root: string;
22
24
  readonly overwrite: boolean;
@@ -3,7 +3,8 @@
3
3
  // tree, manifest and messages.
4
4
  import { createHash } from 'node:crypto';
5
5
  import { SitefileError } from './errors.js';
6
- import { referenceKind, resolveReference, rewriteReferences, scanFile } from './links.js';
6
+ import { integrityTags, referenceKind, resolveReference, rewriteReferences, scanFile } from './links.js';
7
+ import { integrityOf } from './media.js';
7
8
  import { nfc } from './paths.js';
8
9
  import { makeFile, Tree } from './tree.js';
9
10
  /** Hex digits of the SHA-256 of the content in a fingerprinted name. */
@@ -15,11 +16,11 @@ const FIXED_NAMES = new Set(['_redirects', '_headers']);
15
16
  * Check a FINGERPRINT pattern: an absolute path (NFC) with no control characters. A trailing `/`
16
17
  * means everything below that directory (`/assets/` is `/assets/**`).
17
18
  */
18
- export function checkPattern(raw, span) {
19
+ export function checkPattern(raw, span, what = 'FINGERPRINT') {
19
20
  if (/[\u0000-\u001f\u007f]/.test(raw))
20
- throw new SitefileError('E_VALIDATION', 'FINGERPRINT pattern must not contain control characters', span);
21
+ throw new SitefileError('E_VALIDATION', `${what} pattern must not contain control characters`, span);
21
22
  if (!raw.startsWith('/'))
22
- throw new SitefileError('E_VALIDATION', `FINGERPRINT pattern '${raw}' must be an absolute path starting with '/' (e.g. /assets/ or /**/*.css)`, span);
23
+ throw new SitefileError('E_VALIDATION', `${what} pattern '${raw}' must be an absolute path starting with '/' (e.g. /assets/ or /**/*.css)`, span);
23
24
  const p = nfc(raw);
24
25
  return p.endsWith('/') ? p + '**' : p;
25
26
  }
@@ -138,12 +139,19 @@ export function fingerprint(tree, op, origin, warn) {
138
139
  };
139
140
  for (const [p] of selected)
140
141
  visit(p, []);
142
+ // INTEGRITY: the SRI value of each renamed file, by its new path.
143
+ const sri = new Map();
144
+ if (op.integrity)
145
+ for (const [p] of selected)
146
+ sri.set(renamed.get(p), integrityOf(content.get(p)));
141
147
  const files = [];
142
148
  for (const [p, node] of entries) {
143
149
  if (isSelected.has(p))
144
150
  continue;
145
151
  const s = referenceKind(p) !== undefined ? scan(p, node) : undefined;
146
- const text = s ? rewriteReferences(s.text, s.refs, p, op.root, (q) => renamed.get(q)) : undefined;
152
+ let text = s ? rewriteReferences(s.text, s.refs, p, op.root, (q) => renamed.get(q)) : undefined;
153
+ if (s && sri.size > 0 && referenceKind(p) === 'html')
154
+ text = withIntegrity(text ?? s.text, p, op.root, sri) ?? text;
147
155
  files.push([p, text === undefined ? node : makeFile(new TextEncoder().encode(text), origin, node.mode)]);
148
156
  }
149
157
  const renames = selected.map(([p]) => [p, renamed.get(p)]);
@@ -153,6 +161,25 @@ export function fingerprint(tree, op, origin, warn) {
153
161
  out = out.withFiles([[op.manifest, makeFile(new TextEncoder().encode(manifestJson(renames)), origin)]], policy, op.span);
154
162
  return { tree: out, renames };
155
163
  }
164
+ /**
165
+ * `text` (an HTML file at `from`) with ` integrity="…"` added after the tag name of each script and
166
+ * stylesheet tag that loads a file of `sri` (new path -> value); undefined when no tag does.
167
+ */
168
+ function withIntegrity(text, from, root, sri) {
169
+ let out = '';
170
+ let at = 0;
171
+ for (const tag of integrityTags(text)) {
172
+ const t = resolveReference(tag.url, from, root);
173
+ if (t.kind !== 'internal' || t.dir)
174
+ continue;
175
+ const value = sri.get(t.path);
176
+ if (value === undefined)
177
+ continue;
178
+ out += text.slice(at, tag.at) + ` integrity="${value}"`;
179
+ at = tag.at;
180
+ }
181
+ return at === 0 ? undefined : out + text.slice(at);
182
+ }
156
183
  /** Compose rename maps: `earlier` then `later` (a renamed file renamed again maps to its last name). */
157
184
  export function composeRenames(earlier, later) {
158
185
  const next = new Map(later);