@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.
Files changed (136) hide show
  1. package/CHANGELOG.md +516 -0
  2. package/README.md +59 -9
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/bake.d.ts +2 -0
  6. package/lib/src/bake.js +30 -1
  7. package/lib/src/bcrypt.d.ts +25 -0
  8. package/lib/src/bcrypt.js +201 -0
  9. package/lib/src/canonical.d.ts +19 -0
  10. package/lib/src/canonical.js +60 -0
  11. package/lib/src/car.d.ts +34 -0
  12. package/lib/src/car.js +203 -0
  13. package/lib/src/checklinks.js +8 -2
  14. package/lib/src/cli/bake.js +4 -3
  15. package/lib/src/cli/build-image.d.ts +1 -0
  16. package/lib/src/cli/build-image.js +1 -0
  17. package/lib/src/cli/common.js +4 -1
  18. package/lib/src/cli/hosts.d.ts +5 -0
  19. package/lib/src/cli/hosts.js +78 -0
  20. package/lib/src/cli/images.js +23 -5
  21. package/lib/src/cli/import-config.d.ts +2 -0
  22. package/lib/src/cli/import-config.js +56 -0
  23. package/lib/src/cli/index.d.ts +6 -1
  24. package/lib/src/cli/index.js +34 -2
  25. package/lib/src/cli/integrity.d.ts +2 -0
  26. package/lib/src/cli/integrity.js +77 -0
  27. package/lib/src/cli/network.d.ts +7 -0
  28. package/lib/src/cli/network.js +14 -3
  29. package/lib/src/cli/serve-keys.d.ts +39 -0
  30. package/lib/src/cli/serve-keys.js +106 -0
  31. package/lib/src/cli/serve-worker.js +119 -8
  32. package/lib/src/cli/servers.d.ts +130 -1
  33. package/lib/src/cli/servers.js +754 -72
  34. package/lib/src/cli/up.d.ts +2 -0
  35. package/lib/src/cli/up.js +193 -0
  36. package/lib/src/cli/watch.d.ts +14 -1
  37. package/lib/src/cli/watch.js +20 -3
  38. package/lib/src/cli.js +138 -18
  39. package/lib/src/csp.d.ts +17 -0
  40. package/lib/src/csp.js +52 -0
  41. package/lib/src/dictionary.d.ts +16 -0
  42. package/lib/src/dictionary.js +89 -0
  43. package/lib/src/epub.d.ts +5 -0
  44. package/lib/src/epub.js +113 -0
  45. package/lib/src/errors.d.ts +22 -9
  46. package/lib/src/errors.js +20 -1
  47. package/lib/src/executor.d.ts +31 -1
  48. package/lib/src/executor.js +231 -24
  49. package/lib/src/explain.js +33 -3
  50. package/lib/src/export-for.d.ts +42 -0
  51. package/lib/src/export-for.js +466 -0
  52. package/lib/src/export-formats.d.ts +2 -2
  53. package/lib/src/export-formats.js +52 -2
  54. package/lib/src/fingerprint.d.ts +3 -1
  55. package/lib/src/fingerprint.js +32 -5
  56. package/lib/src/host-config.d.ts +34 -0
  57. package/lib/src/host-config.js +645 -0
  58. package/lib/src/hosts.d.ts +47 -0
  59. package/lib/src/hosts.js +106 -0
  60. package/lib/src/hreflang.d.ts +25 -0
  61. package/lib/src/hreflang.js +72 -0
  62. package/lib/src/index.d.ts +1 -1
  63. package/lib/src/index.js +1 -1
  64. package/lib/src/integrity.d.ts +115 -0
  65. package/lib/src/integrity.js +273 -0
  66. package/lib/src/language/ast.d.ts +126 -3
  67. package/lib/src/language/ast.js +7 -1
  68. package/lib/src/language/parser.js +189 -7
  69. package/lib/src/language/validate.js +24 -0
  70. package/lib/src/links.d.ts +47 -0
  71. package/lib/src/links.js +289 -3
  72. package/lib/src/lint.d.ts +1 -1
  73. package/lib/src/lint.js +26 -1
  74. package/lib/src/mime-data.d.ts +2 -0
  75. package/lib/src/mime-data.js +92 -0
  76. package/lib/src/oci.d.ts +20 -2
  77. package/lib/src/oci.js +70 -28
  78. package/lib/src/outdated.d.ts +3 -0
  79. package/lib/src/outdated.js +4 -4
  80. package/lib/src/planner.d.ts +87 -2
  81. package/lib/src/planner.js +189 -8
  82. package/lib/src/plugins/cache.d.ts +11 -0
  83. package/lib/src/plugins/cache.js +29 -0
  84. package/lib/src/plugins/host.d.ts +51 -2
  85. package/lib/src/plugins/host.js +141 -16
  86. package/lib/src/plugins/wasm.js +1 -3
  87. package/lib/src/portable.d.ts +8 -0
  88. package/lib/src/portable.js +47 -0
  89. package/lib/src/precache.d.ts +33 -0
  90. package/lib/src/precache.js +75 -0
  91. package/lib/src/precompress.d.ts +19 -0
  92. package/lib/src/precompress.js +35 -0
  93. package/lib/src/qr.d.ts +18 -0
  94. package/lib/src/qr.js +372 -0
  95. package/lib/src/registry-ops.js +4 -2
  96. package/lib/src/reload-client.d.ts +2 -0
  97. package/lib/src/reload-client.js +419 -0
  98. package/lib/src/resources/archive.d.ts +37 -1
  99. package/lib/src/resources/archive.js +353 -71
  100. package/lib/src/resources/convert.js +3 -1
  101. package/lib/src/resources/https.d.ts +9 -1
  102. package/lib/src/resources/https.js +36 -0
  103. package/lib/src/resources/network.d.ts +25 -3
  104. package/lib/src/resources/network.js +77 -6
  105. package/lib/src/secrets.d.ts +12 -3
  106. package/lib/src/secrets.js +18 -5
  107. package/lib/src/serve-auth.d.ts +33 -0
  108. package/lib/src/serve-auth.js +120 -0
  109. package/lib/src/serve-rules.d.ts +83 -7
  110. package/lib/src/serve-rules.js +264 -53
  111. package/lib/src/server.d.ts +529 -11
  112. package/lib/src/server.js +1439 -57
  113. package/lib/src/servers-file.d.ts +36 -0
  114. package/lib/src/servers-file.js +101 -0
  115. package/lib/src/servers.d.ts +115 -7
  116. package/lib/src/servers.js +151 -29
  117. package/lib/src/single-file.d.ts +12 -0
  118. package/lib/src/single-file.js +147 -0
  119. package/lib/src/site.d.ts +58 -0
  120. package/lib/src/site.js +216 -5
  121. package/lib/src/store.js +9 -5
  122. package/lib/src/swbn.d.ts +10 -0
  123. package/lib/src/swbn.js +86 -0
  124. package/lib/src/toml.d.ts +17 -0
  125. package/lib/src/toml.js +323 -0
  126. package/lib/src/wacz.d.ts +6 -0
  127. package/lib/src/wacz.js +96 -0
  128. package/lib/src/warc.d.ts +28 -0
  129. package/lib/src/warc.js +252 -0
  130. package/lib/src/watch.d.ts +12 -1
  131. package/lib/src/watch.js +67 -1
  132. package/lib/src/wbn.d.ts +9 -1
  133. package/lib/src/wbn.js +23 -33
  134. package/lib/src/zstd.d.ts +4 -0
  135. package/lib/src/zstd.js +328 -0
  136. package/package.json +1 -1
@@ -1,3 +1,6 @@
1
+ import { addDictionaryDeltas } from './dictionary.js';
2
+ import { writeSignedWebBundle } from './swbn.js';
3
+ import { encodeCar } from './car.js';
1
4
  import { chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
2
5
  import { statSync } from 'node:fs';
3
6
  import os from 'node:os';
@@ -10,7 +13,7 @@ import { joinVirtual, basenameVirtual, normalizeVirtual } from './paths.js';
10
13
  import { importedStageRefs, plan, targetPlan } from './planner.js';
11
14
  import { checkWasmPlugin } from './plugins/wasm.js';
12
15
  import { DEFAULT_PLUGIN_POLICY, PluginHost, TRANSFORM_JOBS } from './plugins/host.js';
13
- import { cacheKey, digestFolder, TransformCache } from './plugins/cache.js';
16
+ import { cacheKey, digestFolder, pluginFolderIntegrity, TransformCache } from './plugins/cache.js';
14
17
  import { DEFAULT_TOOL_POLICY, resolveTool, runTool } from './plugins/exec.js';
15
18
  import { decodeUtf8, fileRefs, fragmentNotValue, parseRenderTemplate, renderTemplate, resolveJsonPath, walk } from './render.js';
16
19
  import { dataCollection, markdownCollection, sortDocuments } from './resources/documents.js';
@@ -18,7 +21,7 @@ import { bytesToResource, verifyIntegrity } from './resources/convert.js';
18
21
  import { fetchRemote } from './resources/https.js';
19
22
  import { redactError, redactSecrets, secretHeaders } from './secrets.js';
20
23
  import { fetchGitCommit, pinnedGitUrl, selectGitPath } from './resources/git.js';
21
- import { extractArchive } from './resources/archive.js';
24
+ import { extractArchive, osMetadataWarning, withoutOsMetadata } from './resources/archive.js';
22
25
  import { writeTar } from './archive-writers.js';
23
26
  import { LocalContext } from './resources/local.js';
24
27
  import { Lockfile } from './resources/lockfile.js';
@@ -40,8 +43,15 @@ import { checkSchema, compileSchema } from './schema.js';
40
43
  import { groupBy, paginate } from './pages.js';
41
44
  import { parseYaml } from './yaml.js';
42
45
  import { brokenLinks, reportBrokenLinks } from './checklinks.js';
46
+ import { canonical } from './canonical.js';
47
+ import { alternates, isLanguageTag } from './hreflang.js';
43
48
  import { composeRenames, fingerprint } from './fingerprint.js';
44
- import { atomXml, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapXml } from './site.js';
49
+ import { exportForHost } from './export-for.js';
50
+ import { portabilityProblems } from './portable.js';
51
+ import { precache } from './precache.js';
52
+ import { precompress } from './precompress.js';
53
+ import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles, sitemapPages, SITEMAP_LIMITS } from './site.js';
54
+ import { cspPages } from './csp.js';
45
55
  /** Read, parse and validate a Sitefile. */
46
56
  export async function loadProgram(options) {
47
57
  const sitefilePath = path.resolve(options.sitefile ?? path.join(options.contextDir, 'Sitefile'));
@@ -194,6 +204,7 @@ async function buildWith(options, tempDirs) {
194
204
  local,
195
205
  policy,
196
206
  archiveLimits,
207
+ keepOsMetadata: !!options.keepOsMetadata,
197
208
  lock,
198
209
  label,
199
210
  warn,
@@ -246,7 +257,11 @@ async function buildWith(options, tempDirs) {
246
257
  images.push({ name: r.name, digest: r.digest, line: b.span.line, local: b.local, ...(unit !== undefined ? { import: unit } : {}) });
247
258
  return r;
248
259
  };
249
- const plugins = new PluginHost({ ...DEFAULT_PLUGIN_POLICY, ...options.pluginPolicy }, warn);
260
+ const plugins = new PluginHost({ ...DEFAULT_PLUGIN_POLICY, ...options.pluginPolicy }, warn, {
261
+ ...(options.node !== undefined ? { node: options.node } : {}),
262
+ ...(options.onNotice ? { onNotice: options.onNotice } : {}),
263
+ reusesResults: options.cacheDir !== undefined || memo !== undefined,
264
+ });
250
265
  const cache = options.cacheDir !== undefined ? new TransformCache(options.cacheDir, options.remoteCache) : undefined;
251
266
  const stats = { hits: 0, misses: 0, writes: 0, corrupt: 0, pluginsSpawned: 0, pluginCalls: 0, toolRuns: 0 };
252
267
  const toolPolicy = { ...DEFAULT_TOOL_POLICY, ...options.toolPolicy };
@@ -371,8 +386,15 @@ async function buildWith(options, tempDirs) {
371
386
  if (tree.isFile(p.exportPath)) {
372
387
  throw new SitefileError('E_EXPORT', `EXPORT path '${p.exportPath}' is a file; export a directory`);
373
388
  }
374
- tree = withSiteRules(tree, p, label, currentRenames);
375
- const output = tree.subtree(p.exportPath);
389
+ const site = withSiteRules(tree, p, label, currentRenames, warn, !!options.lossy);
390
+ tree = site.tree;
391
+ const output = site.output ?? tree.subtree(p.exportPath);
392
+ const portability = portabilityProblems(output.entries().map(([f]) => f).sort((a, b) => Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'))));
393
+ if (portability.length > 0 && options.strictPaths) {
394
+ throw new SitefileError('E_PATH_PORTABLE', `EXPORT ${p.exportPath}: ${portability.length === 1 ? 'a path is' : `${portability.length} paths are`} not portable (--strict-paths):${portability.map((m) => `\n ${m}`).join('')}`);
395
+ }
396
+ for (const m of portability)
397
+ warn(`EXPORT ${p.exportPath}: ${m}`);
376
398
  if (output.size === 0)
377
399
  warn(p.target === undefined ? `EXPORT ${p.exportPath} contains no files` : `--target ${p.target}: stage '${p.target}' contains no files`);
378
400
  // BASE: the image to build on. Resolved after the files so a failing build never pulls anything; its
@@ -483,7 +505,9 @@ export async function buildToDirectory(options) {
483
505
  span.end();
484
506
  }
485
507
  }
486
- async function exportBuild(result, format, options) {
508
+ async function exportBuild(built, format, options) {
509
+ const dictionary = options.dictionaryFrom ? addDictionaryDeltas(built.output, options.dictionaryFrom) : undefined;
510
+ const result = dictionary ? { ...built, output: dictionary.tree, dictionaryDeltas: dictionary.deltas } : built;
487
511
  const exportOptions = { contextDir: options.contextDir, ...(options.force ? { force: true } : {}) };
488
512
  // Watch mode: a directory export writes only what changed since the session's last one.
489
513
  const exportState = options.memo?.exportState;
@@ -493,6 +517,7 @@ async function exportBuild(result, format, options) {
493
517
  const img = buildOciImage(result.output, {
494
518
  root: options.ociRoot ?? result.plan.exportRoot,
495
519
  compression: options.ociCompression ?? sitefileCompression(result.plan, 'oci'),
520
+ ...(options.ociLayers !== undefined ? { layers: options.ociLayers } : {}),
496
521
  platform: options.platform,
497
522
  epoch: sourceDateEpoch(),
498
523
  base: result.base,
@@ -514,10 +539,26 @@ async function exportBuild(result, format, options) {
514
539
  const written = await exportDirectory(result.output, options.outDir, { ...exportOptions, ...(exportState ? { incremental: exportState } : {}) });
515
540
  return { ...result, format, outDir: written.outDir, ...(written.incremental ? { incremental: written.incremental } : {}) };
516
541
  }
542
+ if (format === 'swbn') {
543
+ const keyId = result.plan.exportFormat === 'swbn' ? result.plan.exportKey : undefined;
544
+ if (keyId === undefined)
545
+ throw new SitefileError('E_VALIDATION', "swbn export needs a signing key: build with 'EXPORT ... AS swbn KEY <secret-id>' and --secret");
546
+ const pem = options.secrets?.get(keyId);
547
+ if (pem === undefined)
548
+ throw new SitefileError('E_SECRET', `EXPORT ... KEY ${keyId}: no --secret id=${keyId} was given`);
549
+ const signed = writeSignedWebBundle(result.output, pem, keyId);
550
+ const written = await exportFile(signed.bytes, options.outDir, exportOptions);
551
+ return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(signed.bytes), webBundleId: signed.id };
552
+ }
553
+ if (format === 'car') {
554
+ const car = encodeCar(result.output);
555
+ const written = await exportFile(car.bytes, options.outDir, exportOptions);
556
+ return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(car.bytes), rootCid: car.root };
557
+ }
517
558
  const data = encodeTree(result.output, format, {
518
559
  epoch: sourceDateEpoch(),
519
560
  baseUrl: options.baseUrl ?? result.plan.exportBase,
520
- ...(format === 'wbn' ? { compression: options.wbnCompression ?? sitefileCompression(result.plan, 'wbn') } : {}),
561
+ ...(format === 'wbn' || format === 'warc' ? { compression: options.wbnCompression ?? sitefileCompression(result.plan, format) } : {}),
521
562
  });
522
563
  const written = await exportFile(data, options.outDir, exportOptions);
523
564
  return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(data) };
@@ -558,7 +599,15 @@ async function resolveImport(spec, env) {
558
599
  const hit = env.memo?.get(key);
559
600
  if (hit)
560
601
  return hit;
561
- const r = await compute();
602
+ let r = await compute();
603
+ // An archive AS tree: OS metadata files are dropped (keepOsMetadata keeps them).
604
+ if (r.kind === 'tree' && !env.keepOsMetadata) {
605
+ const { tree, skipped } = withoutOsMetadata(r.tree);
606
+ if (skipped > 0) {
607
+ env.warn(osMetadataWarning(`IMPORT ${spec.name}`, skipped));
608
+ r = { ...r, tree };
609
+ }
610
+ }
562
611
  env.memo?.set(key, r);
563
612
  return r;
564
613
  };
@@ -649,9 +698,11 @@ export function warnUnusedSecrets(p, secrets, warn) {
649
698
  if (!secrets)
650
699
  return;
651
700
  const used = new Set(p.imports.flatMap((s) => (s.secrets ?? []).map((x) => x.id)));
701
+ if (p.exportKey !== undefined)
702
+ used.add(p.exportKey);
652
703
  for (const id of [...secrets.keys()].sort())
653
704
  if (!used.has(id))
654
- warn(`--secret ${id} is not used by any IMPORT … SECRET`);
705
+ warn(`--secret ${id} is not used by any IMPORT … SECRET or EXPORT … KEY`);
655
706
  }
656
707
  /**
657
708
  * The bytes of a remote IMPORT, checked against its INTEGRITY and the lockfile (and recorded there):
@@ -667,7 +718,7 @@ export async function fetchRemoteImport(spec, url, env) {
667
718
  env.warn(`${env.label}:${spec.span.line}: IMPORT ${spec.name}: '${url}' is not vendored in ${env.vendor.dir}; fetching it (run 'sitefile vendor' to add it)`);
668
719
  }
669
720
  const fetchIt = () => {
670
- const originHeaders = secretHeaders(spec, env.secrets);
721
+ const originHeaders = secretHeaders(spec, env.secrets, { url, network: env.policy.network });
671
722
  return fetchRemote(url, env.policy, spec.span, originHeaders ? { originHeaders } : {});
672
723
  };
673
724
  const { bytes, finalUrl } = vendored && env.vendor ? await env.vendor.readResource(url, vendored, spec.span) : await fetchIt();
@@ -720,7 +771,7 @@ export async function fetchGitImport(spec, loc, env) {
720
771
  env.warn(`${env.label}:${spec.span.line}: IMPORT ${spec.name}: '${url}' is not vendored in ${env.vendor.dir}${vendored ? ` at commit ${want ?? 'the latest'}` : ''}; fetching it (run 'sitefile vendor' to add it)`);
721
772
  }
722
773
  const limits = env.archiveLimits ?? DEFAULT_ARCHIVE_LIMITS;
723
- const originHeaders = secretHeaders(spec, env.secrets);
774
+ const originHeaders = secretHeaders(spec, env.secrets, { url: loc.repo, network: env.policy.network });
724
775
  const objs = await fetchGitCommit(loc.repo, loc.ref, want, { policy: env.policy, span: spec.span, ...(originHeaders ? { originHeaders } : {}) }, limits);
725
776
  want = objs.commit;
726
777
  selection = selectGitPath(objs, loc, limits, spec.span);
@@ -1288,6 +1339,12 @@ async function executeOp(op, tree, prevKey, env) {
1288
1339
  return { tree: sitemap(op, tree, env), key: '' };
1289
1340
  if (op.kind === 'FINGERPRINT')
1290
1341
  return { ...fingerprintOp(op, tree, env), key: '' };
1342
+ if (op.kind === 'CANONICAL')
1343
+ return { tree: canonicalOp(op, tree, env), key: '' };
1344
+ if (op.kind === 'PRECOMPRESS')
1345
+ return { tree: precompressOp(op, tree, env), key: '' };
1346
+ if (op.kind === 'PRECACHE')
1347
+ return { tree: precacheOp(op, tree, env), key: '' };
1291
1348
  if (op.kind === 'CHECKLINKS') {
1292
1349
  await checkLinks(op, tree, env, env.warn);
1293
1350
  return { tree, key: '' };
@@ -1295,9 +1352,12 @@ async function executeOp(op, tree, prevKey, env) {
1295
1352
  return { tree: tree.withFiles((await produce(op, tree, recording(env), '', '')).files, policy, op.span), key: '' };
1296
1353
  }
1297
1354
  const opId = memoKey('op', env.envKey, valueKey(op));
1298
- if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CHECKLINKS') {
1299
- // Reads the whole tree: only the chain key can say it is unchanged.
1300
- const key = memoKey('chain', prevKey, opId);
1355
+ if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECOMPRESS' || op.kind === 'PRECACHE' || op.kind === 'CHECKLINKS') {
1356
+ // Reads the whole tree: only the chain key can say it is unchanged. With LANGUAGES, also the documents' lists.
1357
+ const langs = (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') && op.languages ? op.languages : undefined;
1358
+ const key = langs
1359
+ ? memoKey('chain', prevKey, opId, namesKey(env, operandNames(langs.sources.map((src) => src.dest), new Set(langs.sources.map((src) => src.list)))))
1360
+ : memoKey('chain', prevKey, opId);
1301
1361
  if (op.kind === 'CHECKLINKS') {
1302
1362
  // The tree is unchanged; a hit skips the check (and its requests) and prints its warnings again.
1303
1363
  const hit = memo.get(key);
@@ -1321,6 +1381,40 @@ async function executeOp(op, tree, prevKey, env) {
1321
1381
  memo.set(key, { ...out, warnings });
1322
1382
  return { ...out, key, memo: 'miss' };
1323
1383
  }
1384
+ if (op.kind === 'CANONICAL') {
1385
+ const hit = memo.get(key);
1386
+ if (hit) {
1387
+ hit.warnings.forEach(env.warn);
1388
+ return { tree: hit.tree, key, memo: 'hit' };
1389
+ }
1390
+ const warnings = [];
1391
+ const out = canonicalOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
1392
+ memo.set(key, { tree: out, warnings });
1393
+ return { tree: out, key, memo: 'miss' };
1394
+ }
1395
+ if (op.kind === 'PRECOMPRESS') {
1396
+ const hit = memo.get(key);
1397
+ if (hit) {
1398
+ hit.warnings.forEach(env.warn);
1399
+ return { tree: hit.tree, key, memo: 'hit' };
1400
+ }
1401
+ const warnings = [];
1402
+ const out = precompressOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
1403
+ memo.set(key, { tree: out, warnings });
1404
+ return { tree: out, key, memo: 'miss' };
1405
+ }
1406
+ if (op.kind === 'PRECACHE') {
1407
+ // The chain key covers the stage's earlier steps, so also what its FINGERPRINTs renamed.
1408
+ const hit = memo.get(key);
1409
+ if (hit) {
1410
+ hit.warnings.forEach(env.warn);
1411
+ return { tree: hit.tree, key, memo: 'hit' };
1412
+ }
1413
+ const warnings = [];
1414
+ const out = precacheOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
1415
+ memo.set(key, { tree: out, warnings });
1416
+ return { tree: out, key, memo: 'miss' };
1417
+ }
1324
1418
  const hit = memo.get(key);
1325
1419
  if (hit)
1326
1420
  return { tree: hit, key, memo: 'hit' };
@@ -1346,17 +1440,60 @@ async function checkLinks(op, tree, env, warn) {
1346
1440
  function fingerprintOp(op, tree, env) {
1347
1441
  return fingerprint(tree, op, `${env.label}:${op.span.line} FINGERPRINT`, env.warn);
1348
1442
  }
1443
+ function canonicalOp(op, tree, env) {
1444
+ return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn, op.languages ? languagesOf(op.languages, 'CANONICAL', op.span, env) : undefined);
1445
+ }
1446
+ /**
1447
+ * LANGUAGES with the translations of the documents of the stage's earlier `RENDER … FOR` lines: an element with
1448
+ * a `translationKey` (text or a number) and a `lang` (text) gives the page its destination names. A `lang` that is
1449
+ * not a language code is `E_VALIDATION`.
1450
+ */
1451
+ function languagesOf(spec, what, span, env) {
1452
+ const docs = new Map();
1453
+ for (const src of spec.sources) {
1454
+ const items = valueOf(src.list, [], span, false, env);
1455
+ if (!Array.isArray(items))
1456
+ continue;
1457
+ items.forEach((item, i) => {
1458
+ if (item === null || typeof item !== 'object' || Array.isArray(item))
1459
+ return;
1460
+ const doc = item;
1461
+ const key = doc['translationKey'];
1462
+ const lang = doc['lang'];
1463
+ if ((typeof key !== 'string' && typeof key !== 'number') || typeof lang !== 'string')
1464
+ return;
1465
+ if (!isLanguageTag(lang)) {
1466
+ const name = typeof doc['path'] === 'string' ? doc['path'] : `#${i + 1}`;
1467
+ throw new SitefileError('E_VALIDATION', `${what}: document '${name}' of '${src.list}' has lang '${lang}', which is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
1468
+ }
1469
+ const target = normalizeVirtual(interpolate(src.dest, { ...env, loop: { name: src.as, value: item } }), src.dest.span, `RENDER destination for ${src.as}`);
1470
+ if (!target.trailingSlash)
1471
+ docs.set(target.path, { lang, key: String(key) });
1472
+ });
1473
+ }
1474
+ return { codes: spec.codes, ...(spec.default !== undefined ? { default: spec.default } : {}), docs };
1475
+ }
1476
+ function precompressOp(op, tree, env) {
1477
+ return precompress(tree, op, `${env.label}:${op.span.line} PRECOMPRESS`, env.warn);
1478
+ }
1479
+ function precacheOp(op, tree, env) {
1480
+ return precache(tree, op, new Set(env.renames?.values() ?? []), `${env.label}:${op.span.line} PRECACHE`, env.warn);
1481
+ }
1349
1482
  function sitemap(op, tree, env) {
1350
1483
  const origin = `${env.label}:${op.span.line} SITEMAP`;
1351
- return tree.withFiles([[op.dest, makeFile(new TextEncoder().encode(sitemapXml(tree, op.base)), origin)]], op.overwrite ? 'overwrite' : 'error', op.span);
1484
+ const alts = op.languages
1485
+ ? alternates(sitemapPages(tree).map((p) => [p, p]), languagesOf(op.languages, 'SITEMAP', op.span, env), 'SITEMAP', op.span)
1486
+ : undefined;
1487
+ const files = sitemapFiles(tree, op.base, op.dest, SITEMAP_LIMITS, alts).map(([p, xml]) => [p, makeFile(new TextEncoder().encode(xml), origin)]);
1488
+ return tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span);
1352
1489
  }
1353
1490
  /** Check a plugin file (sandbox, own folder, integrity) and start its process. */
1354
1491
  async function registerPlugin(spec, local, host, allowed) {
1355
1492
  const { real, bytes } = await local.realFile(spec.path, spec.span);
1356
- if (spec.integrity)
1357
- verifyIntegrity(bytes, spec.integrity, `./${spec.path}`, spec.span);
1358
1493
  if (real.endsWith('.wasm')) {
1359
- // A wasm plugin has no imports, so it reads nothing: no own-folder rule needed.
1494
+ // A wasm plugin has no imports, so it reads nothing: no own-folder rule needed, and INTEGRITY pins the module.
1495
+ if (spec.integrity)
1496
+ verifyIntegrity(bytes, spec.integrity, `./${spec.path}`, spec.span);
1360
1497
  checkWasmPlugin(spec.name, bytes, spec.span);
1361
1498
  host.register(spec.name, real, spec.span, bytes);
1362
1499
  return;
@@ -1367,6 +1504,17 @@ async function registerPlugin(spec, local, host, allowed) {
1367
1504
  if (path.dirname(real) === local.root) {
1368
1505
  throw new SitefileError('E_VALIDATION', `PLUGIN ${spec.name}: put the plugin in its own folder (e.g. ./plugins/${path.basename(real)}); a plugin can read every file next to it`, spec.span);
1369
1506
  }
1507
+ // It can read and import everything in its folder, so INTEGRITY pins the whole folder (#158).
1508
+ if (spec.integrity) {
1509
+ const dir = path.dirname(real);
1510
+ const shown = `./${path.relative(local.root, dir).split(path.sep).join('/')}/`;
1511
+ const r = await pluginFolderIntegrity(dir);
1512
+ if ('problem' in r)
1513
+ throw new SitefileError('E_INTEGRITY', `PLUGIN ${spec.name}: INTEGRITY pins the plugin's folder ${shown}, which ${r.problem}`, spec.span);
1514
+ if (r.digest !== spec.integrity.toLowerCase()) {
1515
+ throw new SitefileError('E_INTEGRITY', `integrity mismatch for ${shown} (PLUGIN ${spec.name}'s folder: INTEGRITY covers every file in it): expected ${spec.integrity}, got ${r.digest}`, spec.span);
1516
+ }
1517
+ }
1370
1518
  host.register(spec.name, real, spec.span);
1371
1519
  }
1372
1520
  /**
@@ -1812,13 +1960,15 @@ async function transformFiles(op, env, dir, ctx) {
1812
1960
  }
1813
1961
  return out;
1814
1962
  }
1815
- /** REDIRECT and HEADER lines become `/_redirects` and `/_headers` at the root of the exported directory. */
1816
1963
  /**
1817
1964
  * REDIRECT and HEADER lines become `/_redirects` and `/_headers` at the root of the exported directory.
1818
1965
  * A HEADER pattern or REDIRECT target that is the URL of a file FINGERPRINT renamed in the exported stage
1819
- * names its new URL.
1966
+ * names its new URL. Unless the plan turns them off, the renamed files (and the pages) also get
1967
+ * `Cache-Control` lines in `/_headers` (after the HEADER lines; see {@link cacheHeaderRules}). A CSP adds a
1968
+ * Content-Security-Policy for every exported page: lines after those, or with META a `<meta>` in each page
1969
+ * (see {@link cspPages}).
1820
1970
  */
1821
- function withSiteRules(tree, p, label, renames) {
1971
+ function withSiteRules(tree, p, label, renames, warn, lossy) {
1822
1972
  const url = new Map();
1823
1973
  for (const [from, to] of renames) {
1824
1974
  const a = urlBelow(p.exportPath, from);
@@ -1828,9 +1978,62 @@ function withSiteRules(tree, p, label, renames) {
1828
1978
  }
1829
1979
  const redirects = p.redirects.map((r) => ({ ...r, to: url.get(r.to) ?? r.to }));
1830
1980
  const headers = p.headers.map((h) => ({ ...h, pattern: url.get(h.pattern) ?? h.pattern }));
1981
+ let headerRules = p.headers;
1982
+ let headerKind = p.headers[0]?.instruction ?? 'HEADER';
1983
+ const headersPath = joinVirtual(p.exportPath, '_headers');
1984
+ if (p.cacheHeaders && url.size > 0) {
1985
+ const files = tree.subtree(p.exportPath).entries().map(([f]) => f);
1986
+ const present = new Set(files);
1987
+ const auto = cacheHeaderRules(files, new Set([...url.values()].filter((u) => present.has(u))));
1988
+ if (auto.length > 0 && p.headers.length === 0 && tree.isFile(headersPath)) {
1989
+ warn(`${label}:${p.cacheHeaders.span.line} FINGERPRINT: ${headersPath} already exists (not written by HEADER), so no Cache-Control lines were added for the fingerprinted files; add them to that file, or use HEADER`);
1990
+ }
1991
+ else if (auto.length > 0) {
1992
+ headers.push(...auto);
1993
+ if (p.headers.length === 0) {
1994
+ headerRules = [{ overwrite: false, span: p.cacheHeaders.span }];
1995
+ headerKind = 'FINGERPRINT';
1996
+ }
1997
+ }
1998
+ }
1999
+ const autoTo = headers.length;
2000
+ if (p.csp) {
2001
+ const origin = `${label}:${p.csp.span.line} CSP`;
2002
+ const r = cspPages(tree, p.exportPath, p.csp.policy, p.csp.meta, origin);
2003
+ if (r.headless.length > 0)
2004
+ warn(`${origin}: ${r.headless.length === 1 ? '1 page has' : `${r.headless.length} pages have`} no <head>, so no policy was added: ${r.headless.join(', ')}`);
2005
+ if (r.pages.length > 0)
2006
+ tree = tree.withFiles(r.pages, 'overwrite', p.csp.span);
2007
+ if (r.rules.length > 0 && headers.length === 0 && tree.isFile(headersPath)) {
2008
+ warn(`${origin}: ${headersPath} already exists (not written by HEADER), so no Content-Security-Policy lines were added; add them to that file, use HEADER, or CSP … META`);
2009
+ }
2010
+ else if (r.rules.length > 0) {
2011
+ if (headers.length === 0) {
2012
+ headerRules = [{ overwrite: false, span: p.csp.span }];
2013
+ headerKind = 'CSP';
2014
+ }
2015
+ headers.push(...r.rules);
2016
+ }
2017
+ }
2018
+ // EXPORT … FOR <host> (not netlify, whose files these are; not with --target, which exports the raw tree).
2019
+ const host = p.target === undefined ? p.exportFor : undefined;
2020
+ if (host && host.host !== 'netlify') {
2021
+ // headers: the HEADER lines (p.headers, in order), FINGERPRINT's cache headers, then CSP's.
2022
+ const autoFrom = p.headers.length;
2023
+ const hostRedirects = redirects.map((r) => ({ from: r.from, to: r.to, status: r.status, span: r.span }));
2024
+ const autoSpan = p.cacheHeaders?.span ?? host.span;
2025
+ const hostHeaders = headers.map((h, i) => ({ pattern: h.pattern, name: h.name, value: h.value, span: i < autoFrom ? p.headers[i].span : i < autoTo ? autoSpan : (p.csp?.span ?? host.span), auto: i >= autoFrom && i < autoTo }));
2026
+ const r = exportForHost(host.host, tree.subtree(p.exportPath), hostRedirects, hostHeaders, { label, lossy, warn, base: p.exportBase, span: host.span });
2027
+ if (host.host !== 'cloudflare')
2028
+ return { tree, output: r.output };
2029
+ // Cloudflare: the same files, without the rules it refused.
2030
+ redirects.splice(0, redirects.length, ...redirects.filter((_, i) => r.redirects.includes(hostRedirects[i])));
2031
+ const keep = headers.filter((_, i) => r.headers.includes(hostHeaders[i]));
2032
+ headers.splice(0, headers.length, ...keep);
2033
+ }
1831
2034
  const files = [
1832
2035
  { name: '_redirects', text: redirectsFile(redirects), rules: redirects, kind: 'REDIRECT' },
1833
- { name: '_headers', text: headersFile(headers), rules: headers, kind: 'HEADER' },
2036
+ { name: '_headers', text: headersFile(headers), rules: headerRules, kind: headerKind },
1834
2037
  ];
1835
2038
  for (const f of files) {
1836
2039
  const first = f.rules[0];
@@ -1840,7 +2043,7 @@ function withSiteRules(tree, p, label, renames) {
1840
2043
  const node = makeFile(new TextEncoder().encode(f.text), `${label}:${first.span.line} ${f.kind}`);
1841
2044
  tree = tree.withFiles([[joinVirtual(p.exportPath, f.name), node]], policy, first.span);
1842
2045
  }
1843
- return tree;
2046
+ return { tree };
1844
2047
  }
1845
2048
  /** The URL path of a tree path below the exported directory, or undefined outside it. */
1846
2049
  function urlBelow(dir, path) {
@@ -1913,6 +2116,10 @@ async function produce(op, tree, env, opId, treeKey) {
1913
2116
  return memoFiles(env, key, async () => feedFiles(op, env));
1914
2117
  }
1915
2118
  const origin = `${env.label}:${op.span.line} ${op.kind}`;
2119
+ // The planner wrote the text; it reads nothing.
2120
+ if (op.kind === 'ROBOTS' || op.kind === 'SECURITY_TXT') {
2121
+ return memoFiles(env, env.memo ? memoKey('text', opId) : undefined, async () => [[op.dest, makeFile(new TextEncoder().encode(op.text), origin)]]);
2122
+ }
1916
2123
  if (op.kind === 'COPY') {
1917
2124
  const exclude = op.exclude ? IgnoreRules.fromPatterns(op.exclude) : undefined;
1918
2125
  const src = await readSource(op.source, origin, env, exclude);
@@ -41,6 +41,15 @@ export function operationLabel(op) {
41
41
  return `FEED ${op.list} ${op.dest}`;
42
42
  case 'FINGERPRINT':
43
43
  return `FINGERPRINT ${op.patterns.join(' ')}`;
44
+ case 'CANONICAL':
45
+ return `CANONICAL ${op.base}${op.pretty ? ' PRETTY' : ''}`;
46
+ case 'PRECOMPRESS':
47
+ return `PRECOMPRESS ${op.formats.join(' ')} ${op.patterns.join(' ')}`;
48
+ case 'ROBOTS':
49
+ case 'SECURITY_TXT':
50
+ return `${op.kind} ${op.dest}`;
51
+ case 'PRECACHE':
52
+ return `PRECACHE ${op.patterns.join(' ')}`;
44
53
  case 'CHECKLINKS':
45
54
  return `CHECKLINKS${op.warn ? ' --warn' : ''}${op.external ? ' --external' : ''}`;
46
55
  }
@@ -403,8 +412,16 @@ export function why(result, raw, contextDir) {
403
412
  inputs.push('the .html files in the tree');
404
413
  else if (op.kind === 'CHECKLINKS')
405
414
  return;
415
+ else if (op.kind === 'CANONICAL')
416
+ inputs.push('the page (canonical link)');
417
+ else if (op.kind === 'ROBOTS' || op.kind === 'SECURITY_TXT')
418
+ inputs.push('the Sitefile');
419
+ else if (op.kind === 'PRECACHE')
420
+ inputs.push(op.into === file ? 'the service worker (manifest injected)' : 'the files it lists');
406
421
  else if (op.kind === 'FINGERPRINT')
407
422
  inputs.push(op.manifest === file ? 'the files it renamed' : 'references to renamed files');
423
+ else if (op.kind === 'PRECOMPRESS')
424
+ inputs.push(`${file.slice(0, -'.gz'.length)} (compressed)`);
408
425
  else
409
426
  inputs.push(`list ${op.list}`);
410
427
  events.push({ location: at(op.span.line), instruction: operationLabel(op), stage: display, path: file, action: prev ? 'overwrite' : 'write', digest: next.digest, inputs });
@@ -420,15 +437,28 @@ export function why(result, raw, contextDir) {
420
437
  const before = finalOf(root, lastIndex).get(full);
421
438
  const after = result.tree.get(full);
422
439
  if (after && !same(before, after)) {
440
+ const site = full === joinVirtual(p.exportPath, '_redirects') || full === joinVirtual(p.exportPath, '_headers');
423
441
  const [rules, kind] = full === joinVirtual(p.exportPath, '_redirects') ? [p.redirects, 'REDIRECT'] : [p.headers, 'HEADER'];
442
+ const inputs = site ? rules.map((r) => `${at(r.span.line)} ${('instruction' in r && r.instruction) || kind}`) : [];
443
+ const text = new TextDecoder().decode(after.bytes);
444
+ // `/_headers` may also hold FINGERPRINT's Cache-Control lines (or only them): with cacheHeaders set, no
445
+ // HEADER sets Cache-Control, so the name in the file means they were added. Likewise CSP's
446
+ // Content-Security-Policy lines; with CSP … META, a page changed at EXPORT got its <meta>.
447
+ const fp = site && kind === 'HEADER' && p.cacheHeaders && text.includes(' Cache-Control: ') ? p.cacheHeaders : undefined;
448
+ if (fp)
449
+ inputs.push(`${at(fp.span.line)} FINGERPRINT`);
450
+ const csp = p.csp && (site ? kind === 'HEADER' && text.includes(' Content-Security-Policy: ') : true) ? p.csp : undefined;
451
+ if (csp)
452
+ inputs.push(site ? `${at(csp.span.line)} CSP` : 'the page (inline scripts and styles)');
453
+ const first = site ? (rules[0] ?? fp ?? csp) : csp;
424
454
  events.push({
425
- location: at(rules[0].span.line),
426
- instruction: kind,
455
+ location: at(first.span.line),
456
+ instruction: site && rules[0] ? ('instruction' in rules[0] && rules[0].instruction) || kind : site && fp ? 'FINGERPRINT' : 'CSP',
427
457
  stage: stageDisplay(p.stages[lastIndex], lastIndex),
428
458
  path: full,
429
459
  action: before ? 'overwrite' : 'write',
430
460
  digest: after.digest,
431
- inputs: rules.map((r) => `${at(r.span.line)} ${kind}`),
461
+ inputs,
432
462
  });
433
463
  }
434
464
  return { path: want, mode: node.mode.toString(8), size: node.bytes.byteLength, digest: node.digest, origin: node.origin, history: events };
@@ -0,0 +1,42 @@
1
+ import { type SourceSpan } from './errors.js';
2
+ import type { ExportHost } from './language/ast.js';
3
+ import { Tree } from './tree.js';
4
+ /**
5
+ * `EXPORT … FOR <host>` (issue #205): write what each host reads for the REDIRECT and HEADER rules (and the
6
+ * FINGERPRINT cache headers), the reverse of `sitefile import-config`. Ported as rust/src/export_for.rs.
7
+ *
8
+ * A rule the host cannot express as `sitefile serve` (and Netlify) apply it is an E_EXPORT error naming the
9
+ * rule, or, with `--lossy`, a warning and the rule is left out. FINGERPRINT's own cache headers are never an
10
+ * error: when the host cannot carry them they are left out with a warning. docs/LANGUAGE.md, "EXPORT … FOR".
11
+ */
12
+ export interface HostRedirect {
13
+ readonly from: string;
14
+ readonly to: string;
15
+ readonly status: number;
16
+ readonly span: SourceSpan;
17
+ }
18
+ export interface HostHeader {
19
+ readonly pattern: string;
20
+ readonly name: string;
21
+ readonly value: string;
22
+ readonly span: SourceSpan;
23
+ /** Written by FINGERPRINT, not a HEADER line. */
24
+ readonly auto: boolean;
25
+ }
26
+ export interface HostOptions {
27
+ readonly label: string;
28
+ readonly lossy: boolean;
29
+ readonly warn: (m: string) => void;
30
+ /** EXPORT's BASE (GitHub Pages: the custom domain for CNAME). */
31
+ readonly base: string | undefined;
32
+ readonly span: SourceSpan;
33
+ }
34
+ export interface HostResult {
35
+ /** The rules that stay (Cloudflare: written as `_redirects` and `_headers`). */
36
+ readonly redirects: readonly HostRedirect[];
37
+ readonly headers: readonly HostHeader[];
38
+ /** The exported files, moved and with the host's files added (unused for Cloudflare). */
39
+ readonly output: Tree;
40
+ }
41
+ /** Apply `EXPORT … FOR <host>` (not `netlify`, which is `_redirects` and `_headers` as they are). */
42
+ export declare function exportForHost(host: Exclude<ExportHost, 'netlify'>, output: Tree, redirects: readonly HostRedirect[], headers: readonly HostHeader[], o: HostOptions): HostResult;