@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/executor.js
CHANGED
|
@@ -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,14 @@ 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';
|
|
43
47
|
import { composeRenames, fingerprint } from './fingerprint.js';
|
|
44
|
-
import {
|
|
48
|
+
import { exportForHost } from './export-for.js';
|
|
49
|
+
import { portabilityProblems } from './portable.js';
|
|
50
|
+
import { precache } from './precache.js';
|
|
51
|
+
import { precompress } from './precompress.js';
|
|
52
|
+
import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles } from './site.js';
|
|
53
|
+
import { cspPages } from './csp.js';
|
|
45
54
|
/** Read, parse and validate a Sitefile. */
|
|
46
55
|
export async function loadProgram(options) {
|
|
47
56
|
const sitefilePath = path.resolve(options.sitefile ?? path.join(options.contextDir, 'Sitefile'));
|
|
@@ -194,6 +203,7 @@ async function buildWith(options, tempDirs) {
|
|
|
194
203
|
local,
|
|
195
204
|
policy,
|
|
196
205
|
archiveLimits,
|
|
206
|
+
keepOsMetadata: !!options.keepOsMetadata,
|
|
197
207
|
lock,
|
|
198
208
|
label,
|
|
199
209
|
warn,
|
|
@@ -246,7 +256,11 @@ async function buildWith(options, tempDirs) {
|
|
|
246
256
|
images.push({ name: r.name, digest: r.digest, line: b.span.line, local: b.local, ...(unit !== undefined ? { import: unit } : {}) });
|
|
247
257
|
return r;
|
|
248
258
|
};
|
|
249
|
-
const plugins = new PluginHost({ ...DEFAULT_PLUGIN_POLICY, ...options.pluginPolicy }, warn
|
|
259
|
+
const plugins = new PluginHost({ ...DEFAULT_PLUGIN_POLICY, ...options.pluginPolicy }, warn, {
|
|
260
|
+
...(options.node !== undefined ? { node: options.node } : {}),
|
|
261
|
+
...(options.onNotice ? { onNotice: options.onNotice } : {}),
|
|
262
|
+
reusesResults: options.cacheDir !== undefined || memo !== undefined,
|
|
263
|
+
});
|
|
250
264
|
const cache = options.cacheDir !== undefined ? new TransformCache(options.cacheDir, options.remoteCache) : undefined;
|
|
251
265
|
const stats = { hits: 0, misses: 0, writes: 0, corrupt: 0, pluginsSpawned: 0, pluginCalls: 0, toolRuns: 0 };
|
|
252
266
|
const toolPolicy = { ...DEFAULT_TOOL_POLICY, ...options.toolPolicy };
|
|
@@ -371,8 +385,15 @@ async function buildWith(options, tempDirs) {
|
|
|
371
385
|
if (tree.isFile(p.exportPath)) {
|
|
372
386
|
throw new SitefileError('E_EXPORT', `EXPORT path '${p.exportPath}' is a file; export a directory`);
|
|
373
387
|
}
|
|
374
|
-
|
|
375
|
-
|
|
388
|
+
const site = withSiteRules(tree, p, label, currentRenames, warn, !!options.lossy);
|
|
389
|
+
tree = site.tree;
|
|
390
|
+
const output = site.output ?? tree.subtree(p.exportPath);
|
|
391
|
+
const portability = portabilityProblems(output.entries().map(([f]) => f).sort((a, b) => Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'))));
|
|
392
|
+
if (portability.length > 0 && options.strictPaths) {
|
|
393
|
+
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('')}`);
|
|
394
|
+
}
|
|
395
|
+
for (const m of portability)
|
|
396
|
+
warn(`EXPORT ${p.exportPath}: ${m}`);
|
|
376
397
|
if (output.size === 0)
|
|
377
398
|
warn(p.target === undefined ? `EXPORT ${p.exportPath} contains no files` : `--target ${p.target}: stage '${p.target}' contains no files`);
|
|
378
399
|
// BASE: the image to build on. Resolved after the files so a failing build never pulls anything; its
|
|
@@ -483,7 +504,9 @@ export async function buildToDirectory(options) {
|
|
|
483
504
|
span.end();
|
|
484
505
|
}
|
|
485
506
|
}
|
|
486
|
-
async function exportBuild(
|
|
507
|
+
async function exportBuild(built, format, options) {
|
|
508
|
+
const dictionary = options.dictionaryFrom ? addDictionaryDeltas(built.output, options.dictionaryFrom) : undefined;
|
|
509
|
+
const result = dictionary ? { ...built, output: dictionary.tree, dictionaryDeltas: dictionary.deltas } : built;
|
|
487
510
|
const exportOptions = { contextDir: options.contextDir, ...(options.force ? { force: true } : {}) };
|
|
488
511
|
// Watch mode: a directory export writes only what changed since the session's last one.
|
|
489
512
|
const exportState = options.memo?.exportState;
|
|
@@ -493,6 +516,7 @@ async function exportBuild(result, format, options) {
|
|
|
493
516
|
const img = buildOciImage(result.output, {
|
|
494
517
|
root: options.ociRoot ?? result.plan.exportRoot,
|
|
495
518
|
compression: options.ociCompression ?? sitefileCompression(result.plan, 'oci'),
|
|
519
|
+
...(options.ociLayers !== undefined ? { layers: options.ociLayers } : {}),
|
|
496
520
|
platform: options.platform,
|
|
497
521
|
epoch: sourceDateEpoch(),
|
|
498
522
|
base: result.base,
|
|
@@ -514,10 +538,26 @@ async function exportBuild(result, format, options) {
|
|
|
514
538
|
const written = await exportDirectory(result.output, options.outDir, { ...exportOptions, ...(exportState ? { incremental: exportState } : {}) });
|
|
515
539
|
return { ...result, format, outDir: written.outDir, ...(written.incremental ? { incremental: written.incremental } : {}) };
|
|
516
540
|
}
|
|
541
|
+
if (format === 'swbn') {
|
|
542
|
+
const keyId = result.plan.exportFormat === 'swbn' ? result.plan.exportKey : undefined;
|
|
543
|
+
if (keyId === undefined)
|
|
544
|
+
throw new SitefileError('E_VALIDATION', "swbn export needs a signing key: build with 'EXPORT ... AS swbn KEY <secret-id>' and --secret");
|
|
545
|
+
const pem = options.secrets?.get(keyId);
|
|
546
|
+
if (pem === undefined)
|
|
547
|
+
throw new SitefileError('E_SECRET', `EXPORT ... KEY ${keyId}: no --secret id=${keyId} was given`);
|
|
548
|
+
const signed = writeSignedWebBundle(result.output, pem, keyId);
|
|
549
|
+
const written = await exportFile(signed.bytes, options.outDir, exportOptions);
|
|
550
|
+
return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(signed.bytes), webBundleId: signed.id };
|
|
551
|
+
}
|
|
552
|
+
if (format === 'car') {
|
|
553
|
+
const car = encodeCar(result.output);
|
|
554
|
+
const written = await exportFile(car.bytes, options.outDir, exportOptions);
|
|
555
|
+
return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(car.bytes), rootCid: car.root };
|
|
556
|
+
}
|
|
517
557
|
const data = encodeTree(result.output, format, {
|
|
518
558
|
epoch: sourceDateEpoch(),
|
|
519
559
|
baseUrl: options.baseUrl ?? result.plan.exportBase,
|
|
520
|
-
...(format === 'wbn' ? { compression: options.wbnCompression ?? sitefileCompression(result.plan,
|
|
560
|
+
...(format === 'wbn' || format === 'warc' ? { compression: options.wbnCompression ?? sitefileCompression(result.plan, format) } : {}),
|
|
521
561
|
});
|
|
522
562
|
const written = await exportFile(data, options.outDir, exportOptions);
|
|
523
563
|
return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(data) };
|
|
@@ -558,7 +598,15 @@ async function resolveImport(spec, env) {
|
|
|
558
598
|
const hit = env.memo?.get(key);
|
|
559
599
|
if (hit)
|
|
560
600
|
return hit;
|
|
561
|
-
|
|
601
|
+
let r = await compute();
|
|
602
|
+
// An archive AS tree: OS metadata files are dropped (keepOsMetadata keeps them).
|
|
603
|
+
if (r.kind === 'tree' && !env.keepOsMetadata) {
|
|
604
|
+
const { tree, skipped } = withoutOsMetadata(r.tree);
|
|
605
|
+
if (skipped > 0) {
|
|
606
|
+
env.warn(osMetadataWarning(`IMPORT ${spec.name}`, skipped));
|
|
607
|
+
r = { ...r, tree };
|
|
608
|
+
}
|
|
609
|
+
}
|
|
562
610
|
env.memo?.set(key, r);
|
|
563
611
|
return r;
|
|
564
612
|
};
|
|
@@ -649,9 +697,11 @@ export function warnUnusedSecrets(p, secrets, warn) {
|
|
|
649
697
|
if (!secrets)
|
|
650
698
|
return;
|
|
651
699
|
const used = new Set(p.imports.flatMap((s) => (s.secrets ?? []).map((x) => x.id)));
|
|
700
|
+
if (p.exportKey !== undefined)
|
|
701
|
+
used.add(p.exportKey);
|
|
652
702
|
for (const id of [...secrets.keys()].sort())
|
|
653
703
|
if (!used.has(id))
|
|
654
|
-
warn(`--secret ${id} is not used by any IMPORT … SECRET`);
|
|
704
|
+
warn(`--secret ${id} is not used by any IMPORT … SECRET or EXPORT … KEY`);
|
|
655
705
|
}
|
|
656
706
|
/**
|
|
657
707
|
* The bytes of a remote IMPORT, checked against its INTEGRITY and the lockfile (and recorded there):
|
|
@@ -667,7 +717,7 @@ export async function fetchRemoteImport(spec, url, env) {
|
|
|
667
717
|
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
718
|
}
|
|
669
719
|
const fetchIt = () => {
|
|
670
|
-
const originHeaders = secretHeaders(spec, env.secrets);
|
|
720
|
+
const originHeaders = secretHeaders(spec, env.secrets, { url, network: env.policy.network });
|
|
671
721
|
return fetchRemote(url, env.policy, spec.span, originHeaders ? { originHeaders } : {});
|
|
672
722
|
};
|
|
673
723
|
const { bytes, finalUrl } = vendored && env.vendor ? await env.vendor.readResource(url, vendored, spec.span) : await fetchIt();
|
|
@@ -720,7 +770,7 @@ export async function fetchGitImport(spec, loc, env) {
|
|
|
720
770
|
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
771
|
}
|
|
722
772
|
const limits = env.archiveLimits ?? DEFAULT_ARCHIVE_LIMITS;
|
|
723
|
-
const originHeaders = secretHeaders(spec, env.secrets);
|
|
773
|
+
const originHeaders = secretHeaders(spec, env.secrets, { url: loc.repo, network: env.policy.network });
|
|
724
774
|
const objs = await fetchGitCommit(loc.repo, loc.ref, want, { policy: env.policy, span: spec.span, ...(originHeaders ? { originHeaders } : {}) }, limits);
|
|
725
775
|
want = objs.commit;
|
|
726
776
|
selection = selectGitPath(objs, loc, limits, spec.span);
|
|
@@ -1288,6 +1338,12 @@ async function executeOp(op, tree, prevKey, env) {
|
|
|
1288
1338
|
return { tree: sitemap(op, tree, env), key: '' };
|
|
1289
1339
|
if (op.kind === 'FINGERPRINT')
|
|
1290
1340
|
return { ...fingerprintOp(op, tree, env), key: '' };
|
|
1341
|
+
if (op.kind === 'CANONICAL')
|
|
1342
|
+
return { tree: canonicalOp(op, tree, env), key: '' };
|
|
1343
|
+
if (op.kind === 'PRECOMPRESS')
|
|
1344
|
+
return { tree: precompressOp(op, tree, env), key: '' };
|
|
1345
|
+
if (op.kind === 'PRECACHE')
|
|
1346
|
+
return { tree: precacheOp(op, tree, env), key: '' };
|
|
1291
1347
|
if (op.kind === 'CHECKLINKS') {
|
|
1292
1348
|
await checkLinks(op, tree, env, env.warn);
|
|
1293
1349
|
return { tree, key: '' };
|
|
@@ -1295,7 +1351,7 @@ async function executeOp(op, tree, prevKey, env) {
|
|
|
1295
1351
|
return { tree: tree.withFiles((await produce(op, tree, recording(env), '', '')).files, policy, op.span), key: '' };
|
|
1296
1352
|
}
|
|
1297
1353
|
const opId = memoKey('op', env.envKey, valueKey(op));
|
|
1298
|
-
if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CHECKLINKS') {
|
|
1354
|
+
if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECOMPRESS' || op.kind === 'PRECACHE' || op.kind === 'CHECKLINKS') {
|
|
1299
1355
|
// Reads the whole tree: only the chain key can say it is unchanged.
|
|
1300
1356
|
const key = memoKey('chain', prevKey, opId);
|
|
1301
1357
|
if (op.kind === 'CHECKLINKS') {
|
|
@@ -1321,6 +1377,40 @@ async function executeOp(op, tree, prevKey, env) {
|
|
|
1321
1377
|
memo.set(key, { ...out, warnings });
|
|
1322
1378
|
return { ...out, key, memo: 'miss' };
|
|
1323
1379
|
}
|
|
1380
|
+
if (op.kind === 'CANONICAL') {
|
|
1381
|
+
const hit = memo.get(key);
|
|
1382
|
+
if (hit) {
|
|
1383
|
+
hit.warnings.forEach(env.warn);
|
|
1384
|
+
return { tree: hit.tree, key, memo: 'hit' };
|
|
1385
|
+
}
|
|
1386
|
+
const warnings = [];
|
|
1387
|
+
const out = canonicalOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
|
|
1388
|
+
memo.set(key, { tree: out, warnings });
|
|
1389
|
+
return { tree: out, key, memo: 'miss' };
|
|
1390
|
+
}
|
|
1391
|
+
if (op.kind === 'PRECOMPRESS') {
|
|
1392
|
+
const hit = memo.get(key);
|
|
1393
|
+
if (hit) {
|
|
1394
|
+
hit.warnings.forEach(env.warn);
|
|
1395
|
+
return { tree: hit.tree, key, memo: 'hit' };
|
|
1396
|
+
}
|
|
1397
|
+
const warnings = [];
|
|
1398
|
+
const out = precompressOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
|
|
1399
|
+
memo.set(key, { tree: out, warnings });
|
|
1400
|
+
return { tree: out, key, memo: 'miss' };
|
|
1401
|
+
}
|
|
1402
|
+
if (op.kind === 'PRECACHE') {
|
|
1403
|
+
// The chain key covers the stage's earlier steps, so also what its FINGERPRINTs renamed.
|
|
1404
|
+
const hit = memo.get(key);
|
|
1405
|
+
if (hit) {
|
|
1406
|
+
hit.warnings.forEach(env.warn);
|
|
1407
|
+
return { tree: hit.tree, key, memo: 'hit' };
|
|
1408
|
+
}
|
|
1409
|
+
const warnings = [];
|
|
1410
|
+
const out = precacheOp(op, tree, { ...env, warn: (m) => (warnings.push(m), env.warn(m)) });
|
|
1411
|
+
memo.set(key, { tree: out, warnings });
|
|
1412
|
+
return { tree: out, key, memo: 'miss' };
|
|
1413
|
+
}
|
|
1324
1414
|
const hit = memo.get(key);
|
|
1325
1415
|
if (hit)
|
|
1326
1416
|
return { tree: hit, key, memo: 'hit' };
|
|
@@ -1346,17 +1436,27 @@ async function checkLinks(op, tree, env, warn) {
|
|
|
1346
1436
|
function fingerprintOp(op, tree, env) {
|
|
1347
1437
|
return fingerprint(tree, op, `${env.label}:${op.span.line} FINGERPRINT`, env.warn);
|
|
1348
1438
|
}
|
|
1439
|
+
function canonicalOp(op, tree, env) {
|
|
1440
|
+
return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn);
|
|
1441
|
+
}
|
|
1442
|
+
function precompressOp(op, tree, env) {
|
|
1443
|
+
return precompress(tree, op, `${env.label}:${op.span.line} PRECOMPRESS`, env.warn);
|
|
1444
|
+
}
|
|
1445
|
+
function precacheOp(op, tree, env) {
|
|
1446
|
+
return precache(tree, op, new Set(env.renames?.values() ?? []), `${env.label}:${op.span.line} PRECACHE`, env.warn);
|
|
1447
|
+
}
|
|
1349
1448
|
function sitemap(op, tree, env) {
|
|
1350
1449
|
const origin = `${env.label}:${op.span.line} SITEMAP`;
|
|
1351
|
-
|
|
1450
|
+
const files = sitemapFiles(tree, op.base, op.dest).map(([p, xml]) => [p, makeFile(new TextEncoder().encode(xml), origin)]);
|
|
1451
|
+
return tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span);
|
|
1352
1452
|
}
|
|
1353
1453
|
/** Check a plugin file (sandbox, own folder, integrity) and start its process. */
|
|
1354
1454
|
async function registerPlugin(spec, local, host, allowed) {
|
|
1355
1455
|
const { real, bytes } = await local.realFile(spec.path, spec.span);
|
|
1356
|
-
if (spec.integrity)
|
|
1357
|
-
verifyIntegrity(bytes, spec.integrity, `./${spec.path}`, spec.span);
|
|
1358
1456
|
if (real.endsWith('.wasm')) {
|
|
1359
|
-
// A wasm plugin has no imports, so it reads nothing: no own-folder rule needed.
|
|
1457
|
+
// A wasm plugin has no imports, so it reads nothing: no own-folder rule needed, and INTEGRITY pins the module.
|
|
1458
|
+
if (spec.integrity)
|
|
1459
|
+
verifyIntegrity(bytes, spec.integrity, `./${spec.path}`, spec.span);
|
|
1360
1460
|
checkWasmPlugin(spec.name, bytes, spec.span);
|
|
1361
1461
|
host.register(spec.name, real, spec.span, bytes);
|
|
1362
1462
|
return;
|
|
@@ -1367,6 +1467,17 @@ async function registerPlugin(spec, local, host, allowed) {
|
|
|
1367
1467
|
if (path.dirname(real) === local.root) {
|
|
1368
1468
|
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
1469
|
}
|
|
1470
|
+
// It can read and import everything in its folder, so INTEGRITY pins the whole folder (#158).
|
|
1471
|
+
if (spec.integrity) {
|
|
1472
|
+
const dir = path.dirname(real);
|
|
1473
|
+
const shown = `./${path.relative(local.root, dir).split(path.sep).join('/')}/`;
|
|
1474
|
+
const r = await pluginFolderIntegrity(dir);
|
|
1475
|
+
if ('problem' in r)
|
|
1476
|
+
throw new SitefileError('E_INTEGRITY', `PLUGIN ${spec.name}: INTEGRITY pins the plugin's folder ${shown}, which ${r.problem}`, spec.span);
|
|
1477
|
+
if (r.digest !== spec.integrity.toLowerCase()) {
|
|
1478
|
+
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);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1370
1481
|
host.register(spec.name, real, spec.span);
|
|
1371
1482
|
}
|
|
1372
1483
|
/**
|
|
@@ -1812,13 +1923,15 @@ async function transformFiles(op, env, dir, ctx) {
|
|
|
1812
1923
|
}
|
|
1813
1924
|
return out;
|
|
1814
1925
|
}
|
|
1815
|
-
/** REDIRECT and HEADER lines become `/_redirects` and `/_headers` at the root of the exported directory. */
|
|
1816
1926
|
/**
|
|
1817
1927
|
* REDIRECT and HEADER lines become `/_redirects` and `/_headers` at the root of the exported directory.
|
|
1818
1928
|
* A HEADER pattern or REDIRECT target that is the URL of a file FINGERPRINT renamed in the exported stage
|
|
1819
|
-
* names its new URL.
|
|
1929
|
+
* names its new URL. Unless the plan turns them off, the renamed files (and the pages) also get
|
|
1930
|
+
* `Cache-Control` lines in `/_headers` (after the HEADER lines; see {@link cacheHeaderRules}). A CSP adds a
|
|
1931
|
+
* Content-Security-Policy for every exported page: lines after those, or with META a `<meta>` in each page
|
|
1932
|
+
* (see {@link cspPages}).
|
|
1820
1933
|
*/
|
|
1821
|
-
function withSiteRules(tree, p, label, renames) {
|
|
1934
|
+
function withSiteRules(tree, p, label, renames, warn, lossy) {
|
|
1822
1935
|
const url = new Map();
|
|
1823
1936
|
for (const [from, to] of renames) {
|
|
1824
1937
|
const a = urlBelow(p.exportPath, from);
|
|
@@ -1828,9 +1941,62 @@ function withSiteRules(tree, p, label, renames) {
|
|
|
1828
1941
|
}
|
|
1829
1942
|
const redirects = p.redirects.map((r) => ({ ...r, to: url.get(r.to) ?? r.to }));
|
|
1830
1943
|
const headers = p.headers.map((h) => ({ ...h, pattern: url.get(h.pattern) ?? h.pattern }));
|
|
1944
|
+
let headerRules = p.headers;
|
|
1945
|
+
let headerKind = p.headers[0]?.instruction ?? 'HEADER';
|
|
1946
|
+
const headersPath = joinVirtual(p.exportPath, '_headers');
|
|
1947
|
+
if (p.cacheHeaders && url.size > 0) {
|
|
1948
|
+
const files = tree.subtree(p.exportPath).entries().map(([f]) => f);
|
|
1949
|
+
const present = new Set(files);
|
|
1950
|
+
const auto = cacheHeaderRules(files, new Set([...url.values()].filter((u) => present.has(u))));
|
|
1951
|
+
if (auto.length > 0 && p.headers.length === 0 && tree.isFile(headersPath)) {
|
|
1952
|
+
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`);
|
|
1953
|
+
}
|
|
1954
|
+
else if (auto.length > 0) {
|
|
1955
|
+
headers.push(...auto);
|
|
1956
|
+
if (p.headers.length === 0) {
|
|
1957
|
+
headerRules = [{ overwrite: false, span: p.cacheHeaders.span }];
|
|
1958
|
+
headerKind = 'FINGERPRINT';
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
const autoTo = headers.length;
|
|
1963
|
+
if (p.csp) {
|
|
1964
|
+
const origin = `${label}:${p.csp.span.line} CSP`;
|
|
1965
|
+
const r = cspPages(tree, p.exportPath, p.csp.policy, p.csp.meta, origin);
|
|
1966
|
+
if (r.headless.length > 0)
|
|
1967
|
+
warn(`${origin}: ${r.headless.length === 1 ? '1 page has' : `${r.headless.length} pages have`} no <head>, so no policy was added: ${r.headless.join(', ')}`);
|
|
1968
|
+
if (r.pages.length > 0)
|
|
1969
|
+
tree = tree.withFiles(r.pages, 'overwrite', p.csp.span);
|
|
1970
|
+
if (r.rules.length > 0 && headers.length === 0 && tree.isFile(headersPath)) {
|
|
1971
|
+
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`);
|
|
1972
|
+
}
|
|
1973
|
+
else if (r.rules.length > 0) {
|
|
1974
|
+
if (headers.length === 0) {
|
|
1975
|
+
headerRules = [{ overwrite: false, span: p.csp.span }];
|
|
1976
|
+
headerKind = 'CSP';
|
|
1977
|
+
}
|
|
1978
|
+
headers.push(...r.rules);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
// EXPORT … FOR <host> (not netlify, whose files these are; not with --target, which exports the raw tree).
|
|
1982
|
+
const host = p.target === undefined ? p.exportFor : undefined;
|
|
1983
|
+
if (host && host.host !== 'netlify') {
|
|
1984
|
+
// headers: the HEADER lines (p.headers, in order), FINGERPRINT's cache headers, then CSP's.
|
|
1985
|
+
const autoFrom = p.headers.length;
|
|
1986
|
+
const hostRedirects = redirects.map((r) => ({ from: r.from, to: r.to, status: r.status, span: r.span }));
|
|
1987
|
+
const autoSpan = p.cacheHeaders?.span ?? host.span;
|
|
1988
|
+
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 }));
|
|
1989
|
+
const r = exportForHost(host.host, tree.subtree(p.exportPath), hostRedirects, hostHeaders, { label, lossy, warn, base: p.exportBase, span: host.span });
|
|
1990
|
+
if (host.host !== 'cloudflare')
|
|
1991
|
+
return { tree, output: r.output };
|
|
1992
|
+
// Cloudflare: the same files, without the rules it refused.
|
|
1993
|
+
redirects.splice(0, redirects.length, ...redirects.filter((_, i) => r.redirects.includes(hostRedirects[i])));
|
|
1994
|
+
const keep = headers.filter((_, i) => r.headers.includes(hostHeaders[i]));
|
|
1995
|
+
headers.splice(0, headers.length, ...keep);
|
|
1996
|
+
}
|
|
1831
1997
|
const files = [
|
|
1832
1998
|
{ name: '_redirects', text: redirectsFile(redirects), rules: redirects, kind: 'REDIRECT' },
|
|
1833
|
-
{ name: '_headers', text: headersFile(headers), rules:
|
|
1999
|
+
{ name: '_headers', text: headersFile(headers), rules: headerRules, kind: headerKind },
|
|
1834
2000
|
];
|
|
1835
2001
|
for (const f of files) {
|
|
1836
2002
|
const first = f.rules[0];
|
|
@@ -1840,7 +2006,7 @@ function withSiteRules(tree, p, label, renames) {
|
|
|
1840
2006
|
const node = makeFile(new TextEncoder().encode(f.text), `${label}:${first.span.line} ${f.kind}`);
|
|
1841
2007
|
tree = tree.withFiles([[joinVirtual(p.exportPath, f.name), node]], policy, first.span);
|
|
1842
2008
|
}
|
|
1843
|
-
return tree;
|
|
2009
|
+
return { tree };
|
|
1844
2010
|
}
|
|
1845
2011
|
/** The URL path of a tree path below the exported directory, or undefined outside it. */
|
|
1846
2012
|
function urlBelow(dir, path) {
|
|
@@ -1913,6 +2079,10 @@ async function produce(op, tree, env, opId, treeKey) {
|
|
|
1913
2079
|
return memoFiles(env, key, async () => feedFiles(op, env));
|
|
1914
2080
|
}
|
|
1915
2081
|
const origin = `${env.label}:${op.span.line} ${op.kind}`;
|
|
2082
|
+
// The planner wrote the text; it reads nothing.
|
|
2083
|
+
if (op.kind === 'ROBOTS' || op.kind === 'SECURITY_TXT') {
|
|
2084
|
+
return memoFiles(env, env.memo ? memoKey('text', opId) : undefined, async () => [[op.dest, makeFile(new TextEncoder().encode(op.text), origin)]]);
|
|
2085
|
+
}
|
|
1916
2086
|
if (op.kind === 'COPY') {
|
|
1917
2087
|
const exclude = op.exclude ? IgnoreRules.fromPatterns(op.exclude) : undefined;
|
|
1918
2088
|
const src = await readSource(op.source, origin, env, exclude);
|
package/lib/src/explain.js
CHANGED
|
@@ -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(
|
|
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
|
|
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;
|