@johnhenry/sitefile 0.0.7 → 0.0.8

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 (56) hide show
  1. package/CHANGELOG.md +84 -1
  2. package/README.md +5 -0
  3. package/lib/src/attest.d.ts +12 -3
  4. package/lib/src/attest.js +15 -10
  5. package/lib/src/bake.js +2 -1
  6. package/lib/src/base-image.d.ts +2 -0
  7. package/lib/src/base-image.js +8 -0
  8. package/lib/src/cli/build-image.js +4 -2
  9. package/lib/src/cli/images.js +8 -5
  10. package/lib/src/cli/servers.js +59 -21
  11. package/lib/src/cli/watch.d.ts +2 -0
  12. package/lib/src/cli/watch.js +2 -1
  13. package/lib/src/cli.js +6 -3
  14. package/lib/src/dictionary.d.ts +1 -7
  15. package/lib/src/dictionary.js +1 -35
  16. package/lib/src/executor.d.ts +16 -5
  17. package/lib/src/executor.js +127 -58
  18. package/lib/src/index.d.ts +2 -0
  19. package/lib/src/index.js +2 -0
  20. package/lib/src/mime-type.d.ts +6 -0
  21. package/lib/src/mime-type.js +20 -0
  22. package/lib/src/nfc.d.ts +6 -0
  23. package/lib/src/nfc.js +10 -0
  24. package/lib/src/oci.d.ts +65 -1
  25. package/lib/src/oci.js +104 -10
  26. package/lib/src/paths.d.ts +2 -6
  27. package/lib/src/paths.js +2 -8
  28. package/lib/src/plugins/env.d.ts +20 -0
  29. package/lib/src/plugins/env.js +37 -0
  30. package/lib/src/plugins/exec.d.ts +1 -1
  31. package/lib/src/plugins/exec.js +3 -2
  32. package/lib/src/plugins/host.js +3 -2
  33. package/lib/src/precompress.d.ts +6 -0
  34. package/lib/src/precompress.js +6 -0
  35. package/lib/src/recipe.d.ts +37 -0
  36. package/lib/src/recipe.js +96 -0
  37. package/lib/src/registry-ops.d.ts +5 -1
  38. package/lib/src/registry-ops.js +69 -45
  39. package/lib/src/request-path.d.ts +10 -0
  40. package/lib/src/request-path.js +42 -0
  41. package/lib/src/serve-dictionary.d.ts +11 -0
  42. package/lib/src/serve-dictionary.js +45 -0
  43. package/lib/src/serve-rules.js +1 -1
  44. package/lib/src/server.d.ts +16 -229
  45. package/lib/src/server.js +135 -795
  46. package/lib/src/servers.d.ts +15 -0
  47. package/lib/src/servers.js +42 -2
  48. package/lib/src/site-core.d.ts +368 -0
  49. package/lib/src/site-core.js +1065 -0
  50. package/lib/src/site-handler.d.ts +14 -0
  51. package/lib/src/site-handler.js +32 -0
  52. package/lib/src/store.d.ts +31 -2
  53. package/lib/src/store.js +140 -21
  54. package/lib/src/wbn.d.ts +1 -6
  55. package/lib/src/wbn.js +2 -18
  56. package/package.json +5 -1
@@ -21,8 +21,13 @@ import type { TemplateNode } from './render.js';
21
21
  export interface BuildOptions {
22
22
  /** Build context directory; local paths resolve from here. */
23
23
  readonly contextDir: string;
24
- /** Sitefile path. Default: `<contextDir>/Sitefile`. */
24
+ /** Sitefile path. Default: the first of `recipeNames` that exists in `contextDir`. */
25
25
  readonly sitefile?: string;
26
+ /**
27
+ * The file names searched, in order, in `contextDir` when `sitefile` is not given (default: the
28
+ * process-wide list, `recipeNames()`, `["Sitefile"]` unless changed). An empty list is the same as none.
29
+ */
30
+ readonly recipeNames?: readonly string[];
26
31
  /** How messages name the Sitefile (default: its path relative to the working directory). */
27
32
  readonly label?: string;
28
33
  /**
@@ -135,6 +140,8 @@ export interface BuildResult {
135
140
  readonly lockfileWritten: boolean;
136
141
  /** The resolved BASE image (EXPORT ... AS oci BASE <image> or --base), whose blobs are in the store. */
137
142
  readonly base?: BaseImage;
143
+ /** With two or more `--platform`s: each platform's resolved BASE (`base` is the first platform's). */
144
+ readonly bases?: ReadonlyMap<string, BaseImage>;
138
145
  /** The `FROM image` stage bases this build read, in stage order (name and image digest). */
139
146
  readonly images?: readonly FromImageUse[];
140
147
  /** Allow-listed tools this build resolved. */
@@ -181,7 +188,7 @@ interface Loaded {
181
188
  readonly source: string;
182
189
  }
183
190
  /** Read, parse and validate a Sitefile. */
184
- export declare function loadProgram(options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label'>): Promise<Loaded>;
191
+ export declare function loadProgram(options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'recipeNames'>): Promise<Loaded>;
185
192
  /** Parse, validate and evaluate variables, without reading any sources. */
186
193
  export declare function planBuild(options: BuildOptions): Promise<Plan>;
187
194
  /** `validate`'s lint warnings (src/lint.ts) for the whole Sitefile (a `--target` does not narrow them). */
@@ -272,7 +279,9 @@ export declare function sitefileCompression(plan: Pick<Plan, 'exportFormat' | 'e
272
279
  * The attestations (`--provenance`, `--sbom`) of an image built from `result`: in-toto statements
273
280
  * whose subject is the image manifest. They never change the image itself.
274
281
  */
275
- export declare function imageAttestations(result: BuildResult, img: Pick<OciImage, 'manifestDigest' | 'manifestBytes' | 'configBytes' | 'root'>, options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'buildArgs' | 'platform'>, request: AttestRequest): Promise<Referrer[]>;
282
+ export declare function imageAttestations(result: BuildResult, img: Pick<OciImage, 'manifestDigest' | 'manifestBytes' | 'configBytes' | 'root'> & {
283
+ readonly mediaType?: string;
284
+ }, options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'buildArgs' | 'platform'>, request: AttestRequest): Promise<Referrer[]>;
276
285
  /** What fetching a remote IMPORT needs: the network policy and the lockfile rules (and, for builds, the vendor directory). */
277
286
  export interface RemoteEnv {
278
287
  readonly policy: FetchPolicy;
@@ -322,7 +331,7 @@ export interface LabelScope {
322
331
  readonly dir: string;
323
332
  }
324
333
  /** The label an imported Sitefile's messages and file origins use. */
325
- export declare function sitefileLabel(scope: LabelScope): string;
334
+ export declare function sitefileLabel(scope: LabelScope, name?: string): string;
326
335
  /** The ARG values an `IMPORT … AS sitefile` passes, checked against the imported Sitefile's ARGs. */
327
336
  export declare function importedArgs(spec: ImportSpec, program: Program): Record<string, string>;
328
337
  /**
@@ -361,6 +370,8 @@ export interface ImportedSitefile {
361
370
  * a local context, or a directory of a Git tree held in memory.
362
371
  */
363
372
  export type SitefileSource = {
373
+ readonly names: readonly string[];
374
+ } & ({
364
375
  readonly kind: 'local';
365
376
  readonly local: LocalContext;
366
377
  readonly scope: LabelScope;
@@ -379,7 +390,7 @@ export type SitefileSource = {
379
390
  readonly id: string;
380
391
  readonly label: string;
381
392
  }>;
382
- };
393
+ });
383
394
  /** The source of the build's own Sitefile, for {@link readImportedSitefile}. */
384
395
  export declare function rootSitefileSource(options: BuildOptions, label: string, sitefilePath: string): Promise<SitefileSource>;
385
396
  /**
@@ -33,9 +33,10 @@ import { lint } from './lint.js';
33
33
  import { exportDirectory, exportFile, isExporterTempName } from './exporter.js';
34
34
  import { sourceDateEpoch } from './archive-writers.js';
35
35
  import { encodeTree, isArchiveFormat } from './export-formats.js';
36
+ import { effectiveRecipeNames, isDefaultRecipeNames, isFileSync, recipeNotFound, recipePath } from './recipe.js';
36
37
  import { buildFacts, makeAttestations } from './attest.js';
37
- import { ANN, buildOciImage, imageMeta, layoutTree, ociArchive, parseConfig } from './oci.js';
38
- import { baseRef as parseBaseRef, readLayerBlobs, resolveBase, resolveFromImage } from './base-image.js';
38
+ import { ANN, MEDIA, buildOciImage, buildOciIndex, imageMeta, layoutTree, layoutTreeIndex, ociArchive, ociIndexArchive, parseConfig, parsePlatforms } from './oci.js';
39
+ import { baseRef as parseBaseRef, readBaseBlobs, readLayerBlobs, resolveBase, resolveFromImage } from './base-image.js';
39
40
  import { Store } from './store.js';
40
41
  import { begin, reserve } from './profile.js';
41
42
  import { BuildMemo, memoKey, valueKey } from './memo.js';
@@ -54,7 +55,15 @@ import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirec
54
55
  import { cspPages } from './csp.js';
55
56
  /** Read, parse and validate a Sitefile. */
56
57
  export async function loadProgram(options) {
57
- const sitefilePath = path.resolve(options.sitefile ?? path.join(options.contextDir, 'Sitefile'));
58
+ let given = options.sitefile;
59
+ if (given === undefined) {
60
+ const names = effectiveRecipeNames(options.recipeNames);
61
+ given = recipePath(options.contextDir, names);
62
+ // A Git context's directory is a temporary one: name the label, not it.
63
+ if (!isDefaultRecipeNames(names) && !isFileSync(given))
64
+ throw recipeNotFound(options.label === undefined ? options.contextDir : undefined, names);
65
+ }
66
+ const sitefilePath = path.resolve(given);
58
67
  let source;
59
68
  try {
60
69
  source = await readFile(sitefilePath, 'utf8');
@@ -87,7 +96,7 @@ function lockPathFor(options, sitefilePath) {
87
96
  }
88
97
  /** `validate --strict-pins`: check the pins of `p` against the lockfile without building or fetching. */
89
98
  export async function checkPlanPins(options, p) {
90
- const sitefilePath = path.resolve(options.sitefile ?? path.join(options.contextDir, 'Sitefile'));
99
+ const sitefilePath = path.resolve(options.sitefile ?? recipePath(options.contextDir, options.recipeNames));
91
100
  const lockPath = lockPathFor(options, sitefilePath);
92
101
  const lock = lockPath ? await Lockfile.load(lockPath) : undefined;
93
102
  void checkPins(p, lock, options.skipBase ? undefined : (options.baseImage ?? (p.exportFormat === 'oci' ? p.exportBase : undefined)));
@@ -241,7 +250,8 @@ async function buildWith(options, tempDirs) {
241
250
  imageStore ??= options.store ?? (await Store.open());
242
251
  const r = await resolveFromImage(b.ref, b.at, b.local, {
243
252
  store: imageStore,
244
- platform: options.platform,
253
+ // Only the files are read, the same for every platform: a list narrows an index to its first platform.
254
+ platform: parsePlatforms(options.platform)[0] ?? options.platform,
245
255
  lock,
246
256
  frozen: !!options.frozenLockfile,
247
257
  update: !!options.updateLock,
@@ -278,6 +288,7 @@ async function buildWith(options, tempDirs) {
278
288
  pins: {},
279
289
  exec: { plugins, toolPolicy, stats, fetchPolicy: policy },
280
290
  fromImage,
291
+ recipeNames: effectiveRecipeNames(options.recipeNames),
281
292
  };
282
293
  const root = {
283
294
  name: undefined,
@@ -400,21 +411,36 @@ async function buildWith(options, tempDirs) {
400
411
  // BASE: the image to build on. Resolved after the files so a failing build never pulls anything; its
401
412
  // lockfile entry is saved together with the imports'.
402
413
  const baseSpan = baseRef ? begin(prof, `BASE ${baseRef}`, 'import') : undefined;
403
- const base = baseRef
404
- ? await resolveBase(baseRef, {
405
- store: options.store ?? (await Store.open()),
406
- platform: options.platform,
407
- lock,
408
- frozen: !!options.frozenLockfile,
409
- update: !!options.updateLock,
410
- vendor,
411
- registry: {
412
- ...options.registry,
413
- allowPrivateNetwork: options.registry?.allowPrivateNetwork ?? policy.allowPrivateNetwork, network: options.registry?.network ?? policy.network,
414
- },
415
- warn,
416
- })
417
- : undefined;
414
+ const resolveFor = async (platform) => resolveBase(baseRef, {
415
+ store: options.store ?? (await Store.open()),
416
+ platform,
417
+ lock,
418
+ frozen: !!options.frozenLockfile,
419
+ update: !!options.updateLock,
420
+ vendor,
421
+ registry: {
422
+ ...options.registry,
423
+ allowPrivateNetwork: options.registry?.allowPrivateNetwork ?? policy.allowPrivateNetwork, network: options.registry?.network ?? policy.network,
424
+ },
425
+ warn,
426
+ });
427
+ // Several platforms (`--platform a,b`): the BASE is resolved for each, one after the other (the tag is
428
+ // resolved and recorded once), and each platform's manifest builds on its own.
429
+ let base;
430
+ let bases;
431
+ if (baseRef) {
432
+ // The flag is checked only here, where a BASE needs it (a directory export with no BASE ignores it, as it always did).
433
+ const basePlatforms = parsePlatforms(options.platform);
434
+ if (basePlatforms.length > 1) {
435
+ bases = new Map();
436
+ for (const platform of basePlatforms)
437
+ bases.set(platform, await resolveFor(platform));
438
+ base = bases.get(basePlatforms[0]);
439
+ }
440
+ else {
441
+ base = await resolveFor(options.platform);
442
+ }
443
+ }
418
444
  baseSpan?.end();
419
445
  const lockfileWritten = lock && !options.frozenLockfile ? await lock.save() : false;
420
446
  return {
@@ -428,6 +454,7 @@ async function buildWith(options, tempDirs) {
428
454
  tools,
429
455
  transformStats: stats,
430
456
  ...(base ? { base } : {}),
457
+ ...(bases ? { bases } : {}),
431
458
  ...(images.length ? { images } : {}),
432
459
  ...(steps ? { steps } : {}),
433
460
  ...(pins ? { pins } : {}),
@@ -514,15 +541,31 @@ async function exportBuild(built, format, options) {
514
541
  if (format !== 'directory')
515
542
  exportState?.clear();
516
543
  if (format === 'oci') {
517
- const img = buildOciImage(result.output, {
544
+ const ociOptions = {
518
545
  root: options.ociRoot ?? result.plan.exportRoot,
519
546
  compression: options.ociCompression ?? sitefileCompression(result.plan, 'oci'),
520
547
  ...(options.ociLayers !== undefined ? { layers: options.ociLayers } : {}),
521
548
  platform: options.platform,
522
549
  epoch: sourceDateEpoch(),
523
550
  base: result.base,
551
+ ...(result.bases ? { bases: result.bases } : {}),
524
552
  ...(await imageMeta(options.contextDir, { git: !!options.gitLabels, ...(options.imageLabels ? { labels: options.imageLabels } : {}) })),
525
- });
553
+ };
554
+ // Two or more platforms: one image index over a manifest per platform, the site layers shared.
555
+ if (parsePlatforms(options.platform).length > 1) {
556
+ const idx = buildOciIndex(result.output, ociOptions);
557
+ const baseBlobs = result.base ? await readBaseBlobs(options.store ?? (await Store.open()), idx.images.map((i) => i.image.baseLayers)) : undefined;
558
+ const first = idx.images[0].image;
559
+ const referrers = options.attest ? await imageAttestations(result, { manifestDigest: idx.indexDigest, manifestBytes: idx.indexBytes, configBytes: first.configBytes, root: first.root, mediaType: MEDIA.index }, options, options.attest) : [];
560
+ if (options.outDir.toLowerCase().endsWith('.tar')) {
561
+ const data = ociIndexArchive(idx, options.ociRefName, sourceDateEpoch(), baseBlobs, referrers);
562
+ const written = await exportFile(data, options.outDir, exportOptions);
563
+ return { ...result, format, outDir: written.outFile, bytes: written.bytes, fileDigest: sha256(data), manifestDigest: idx.indexDigest };
564
+ }
565
+ const written = await exportDirectory(layoutTreeIndex(idx, options.ociRefName, baseBlobs, referrers), options.outDir, exportOptions);
566
+ return { ...result, format, outDir: written.outDir, manifestDigest: idx.indexDigest };
567
+ }
568
+ const img = buildOciImage(result.output, ociOptions);
526
569
  // An image built on a BASE carries the base's layers: copy them in so the export is self-contained.
527
570
  const baseBlobs = result.base ? await readLayerBlobs(options.store ?? (await Store.open()), img.baseLayers) : undefined;
528
571
  const referrers = options.attest ? await imageAttestations(result, img, options, options.attest) : [];
@@ -579,7 +622,7 @@ export async function imageAttestations(result, img, options, request) {
579
622
  return [];
580
623
  const facts = await buildFacts(result, options);
581
624
  const title = parseConfig(img.configBytes).labels[ANN.title];
582
- return makeAttestations({ digest: img.manifestDigest, size: img.manifestBytes.byteLength, files: result.output, root: img.root, title }, facts, request, sourceDateEpoch());
625
+ return makeAttestations({ digest: img.manifestDigest, size: img.manifestBytes.byteLength, ...(img.mediaType !== undefined ? { mediaType: img.mediaType } : {}), files: result.output, root: img.root, title }, facts, request, sourceDateEpoch());
583
626
  }
584
627
  /**
585
628
  * Read an import. `key` identifies the result for incremental rebuilds: the import's spec
@@ -786,8 +829,43 @@ export async function fetchGitImport(spec, loc, env) {
786
829
  /** How deep Sitefile imports may nest (an imported Sitefile importing another counts one more level). */
787
830
  export const MAX_SITEFILE_IMPORT_DEPTH = 8;
788
831
  /** The label an imported Sitefile's messages and file origins use. */
789
- export function sitefileLabel(scope) {
790
- return scope.prefix + path.posix.join(scope.dir, 'Sitefile');
832
+ export function sitefileLabel(scope, name = 'Sitefile') {
833
+ return scope.prefix + path.posix.join(scope.dir, name);
834
+ }
835
+ /**
836
+ * The recipe an `IMPORT … AS sitefile` reads from a directory (#334): the first of `names` that exists
837
+ * there, same list as the build's own (`BuildOptions.recipeNames`, `setRecipeNames`, `$SITEFILE_RECIPE_NAMES`).
838
+ * A missing name and a directory of that name are skipped (as for the build's own recipe); a symlink escape or
839
+ * any other failure is an error.
840
+ */
841
+ async function readRecipeIn(local, names, span) {
842
+ for (const name of names) {
843
+ try {
844
+ if ((await local.stat(name, span)) !== 'file')
845
+ continue;
846
+ return { name, bytes: (await local.readFile(name, span)).bytes };
847
+ }
848
+ catch (e) {
849
+ if (!(e instanceof SitefileError && e.code === 'E_NOT_FOUND'))
850
+ throw e;
851
+ }
852
+ }
853
+ return undefined;
854
+ }
855
+ /** The first of `names` that is a file of `tree` at directory `at` (`/` or `/dir`). */
856
+ function findRecipeInTree(tree, at, names) {
857
+ for (const name of names) {
858
+ const file = at === '/' ? `/${name}` : `${at}/${name}`;
859
+ const bytes = tree.isFile(file) ? tree.get(file)?.bytes : undefined;
860
+ if (bytes !== undefined)
861
+ return { name, bytes };
862
+ }
863
+ return undefined;
864
+ }
865
+ /** `IMPORT x: <dir> has no Sitefile` with the default list (its original text), else naming every name tried. */
866
+ function noRecipeInImport(spec, display, names) {
867
+ const what = isDefaultRecipeNames(names) ? 'has no Sitefile' : `has no recipe (tried: ${names.join(', ')})`;
868
+ return new SitefileError('E_NOT_FOUND', `IMPORT ${spec.name}: ${display} ${what}`, spec.span);
791
869
  }
792
870
  /** The label scope of the build's own Sitefile. */
793
871
  function rootScope(options, label) {
@@ -889,15 +967,6 @@ async function loadSitefileImport(spec, importer, refs, env) {
889
967
  else {
890
968
  throw new SitefileError('E_PROTOCOL', `IMPORT ${spec.name}: AS sitefile reads a context directory or a git+https:// repository, not a URL`, spec.span);
891
969
  }
892
- const label = sitefileLabel(scope);
893
- const seen = importer.chain.findIndex((c) => c.id === id);
894
- if (seen !== -1) {
895
- const cycle = [...importer.chain.slice(seen).map((c) => c.label), label];
896
- throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile import cycle: ${cycle.join(' -> ')}`, spec.span);
897
- }
898
- if (importer.chain.length > MAX_SITEFILE_IMPORT_DEPTH) {
899
- throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile imports nest more than ${MAX_SITEFILE_IMPORT_DEPTH} levels deep`, spec.span);
900
- }
901
970
  // Its context: the directory, sandboxed (its own .sitefileignore applies; what the build writes is skipped).
902
971
  const ignore = ['.git'];
903
972
  for (const s of env.skip) {
@@ -906,15 +975,18 @@ async function loadSitefileImport(spec, importer, refs, env) {
906
975
  ignore.push(rel.split(path.sep).join('/'));
907
976
  }
908
977
  const local = await LocalContext.open(hostDir, { ignore, allowHardlinks: env.allowHardlinks });
909
- let sitefileBytes;
910
- try {
911
- sitefileBytes = (await local.readFile('Sitefile', spec.span)).bytes;
978
+ const found = await readRecipeIn(local, env.recipeNames, spec.span);
979
+ if (found === undefined)
980
+ throw noRecipeInImport(spec, display, env.recipeNames);
981
+ const sitefileBytes = found.bytes;
982
+ const label = sitefileLabel(scope, found.name);
983
+ const seen = importer.chain.findIndex((c) => c.id === id);
984
+ if (seen !== -1) {
985
+ const cycle = [...importer.chain.slice(seen).map((c) => c.label), label];
986
+ throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile import cycle: ${cycle.join(' -> ')}`, spec.span);
912
987
  }
913
- catch (e) {
914
- if (e instanceof SitefileError && e.code === 'E_NOT_FOUND') {
915
- throw new SitefileError('E_NOT_FOUND', `IMPORT ${spec.name}: ${display} has no Sitefile`, spec.span, { cause: e });
916
- }
917
- throw e;
988
+ if (importer.chain.length > MAX_SITEFILE_IMPORT_DEPTH) {
989
+ throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile imports nest more than ${MAX_SITEFILE_IMPORT_DEPTH} levels deep`, spec.span);
918
990
  }
919
991
  const { plan: p } = planImportedSitefile(spec, new TextDecoder().decode(sitefileBytes), label, refs);
920
992
  p.warnings.forEach(env.remote.warn);
@@ -981,7 +1053,7 @@ async function loadSitefileImport(spec, importer, refs, env) {
981
1053
  }
982
1054
  /** The resource an `AS sitefile` import stands for (provenance): its Sitefile, with the unit's digest. */
983
1055
  function unitResource(unit) {
984
- return { kind: 'file', bytes: unit.sitefileBytes, mode: 0o644, basename: 'Sitefile', provenance: { ...unit.provenance, digest: unit.digest } };
1056
+ return { kind: 'file', bytes: unit.sitefileBytes, mode: 0o644, basename: path.posix.basename(unit.label), provenance: { ...unit.provenance, digest: unit.digest } };
985
1057
  }
986
1058
  function isHostDirectory(p) {
987
1059
  try {
@@ -998,7 +1070,7 @@ export async function rootSitefileSource(options, label, sitefilePath) {
998
1070
  });
999
1071
  const local = await LocalContext.open(contextReal, { ignore: ['.git'], allowHardlinks: options.allowHardlinks ?? false });
1000
1072
  const id = options.sitefile === undefined ? contextReal : await realpathLoose(sitefilePath);
1001
- return { kind: 'local', local, scope: rootScope(options, label), label, chain: [{ id, label }] };
1073
+ return { kind: 'local', names: effectiveRecipeNames(options.recipeNames), local, scope: rootScope(options, label), label, chain: [{ id, label }] };
1002
1074
  }
1003
1075
  /**
1004
1076
  * Read and plan the Sitefile an `IMPORT … AS sitefile` of `from` names, without building it (for `vendor`
@@ -1009,7 +1081,7 @@ export async function readImportedSitefile(spec, from, refs, fetchGit) {
1009
1081
  let scope;
1010
1082
  let id;
1011
1083
  let display;
1012
- let bytes;
1084
+ let found;
1013
1085
  let make;
1014
1086
  if (spec.location.kind === 'git') {
1015
1087
  const loc = spec.location;
@@ -1021,8 +1093,8 @@ export async function readImportedSitefile(spec, from, refs, fetchGit) {
1021
1093
  const tree = Tree.fromFiles(selection.files.map(([p, f]) => [p, makeFile(f.bytes, 'git', f.mode)]));
1022
1094
  scope = { prefix: `git+${loc.repo}#${commit}:`, dir: loc.path };
1023
1095
  id = `${scope.prefix}${loc.path}`;
1024
- bytes = tree.get('/Sitefile')?.bytes;
1025
- make = (label, chain) => ({ kind: 'tree', tree, dir: '', scope, label, chain });
1096
+ found = findRecipeInTree(tree, '/', from.names);
1097
+ make = (label, chain) => ({ kind: 'tree', names: from.names, tree, dir: '', scope, label, chain });
1026
1098
  }
1027
1099
  else if (spec.location.kind === 'local') {
1028
1100
  const rel = spec.location.path;
@@ -1035,12 +1107,8 @@ export async function readImportedSitefile(spec, from, refs, fetchGit) {
1035
1107
  const real = await from.local.realPath(rel, spec.span);
1036
1108
  id = real;
1037
1109
  const local = await LocalContext.open(real, { ignore: ['.git'] });
1038
- bytes = await local.readFile('Sitefile', spec.span).then((f) => f.bytes, (e) => {
1039
- if (e instanceof SitefileError && e.code === 'E_NOT_FOUND')
1040
- return undefined;
1041
- throw e;
1042
- });
1043
- make = (label, chain) => ({ kind: 'local', local, scope, label, chain });
1110
+ found = await readRecipeIn(local, from.names, spec.span);
1111
+ make = (label, chain) => ({ kind: 'local', names: from.names, local, scope, label, chain });
1044
1112
  }
1045
1113
  else {
1046
1114
  const dir = path.posix.join(from.dir, rel).replace(/^\.$/, '');
@@ -1051,15 +1119,18 @@ export async function readImportedSitefile(spec, from, refs, fetchGit) {
1051
1119
  if (!from.tree.isDirectory(at))
1052
1120
  throw new SitefileError('E_NOT_FOUND', `'${display.slice(1, -1)}' does not exist in the build context`, spec.span);
1053
1121
  id = `${from.scope.prefix}${scope.dir}`;
1054
- bytes = from.tree.get(at === '/' ? '/Sitefile' : `${at}/Sitefile`)?.bytes;
1122
+ found = findRecipeInTree(from.tree, at, from.names);
1055
1123
  const tree = from.tree;
1056
- make = (label, chain) => ({ kind: 'tree', tree, dir, scope, label, chain });
1124
+ make = (label, chain) => ({ kind: 'tree', names: from.names, tree, dir, scope, label, chain });
1057
1125
  }
1058
1126
  }
1059
1127
  else {
1060
1128
  throw new SitefileError('E_PROTOCOL', `IMPORT ${spec.name}: AS sitefile reads a context directory or a git+https:// repository, not a URL`, spec.span);
1061
1129
  }
1062
- const label = sitefileLabel(scope);
1130
+ if (found === undefined)
1131
+ throw noRecipeInImport(spec, display, from.names);
1132
+ const bytes = found.bytes;
1133
+ const label = sitefileLabel(scope, found.name);
1063
1134
  const seen = from.chain.findIndex((c) => c.id === id);
1064
1135
  if (seen !== -1) {
1065
1136
  throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile import cycle: ${[...from.chain.slice(seen).map((c) => c.label), label].join(' -> ')}`, spec.span);
@@ -1067,8 +1138,6 @@ export async function readImportedSitefile(spec, from, refs, fetchGit) {
1067
1138
  if (from.chain.length > MAX_SITEFILE_IMPORT_DEPTH) {
1068
1139
  throw new SitefileError('E_VALIDATION', `IMPORT ${spec.name}: Sitefile imports nest more than ${MAX_SITEFILE_IMPORT_DEPTH} levels deep`, spec.span);
1069
1140
  }
1070
- if (bytes === undefined)
1071
- throw new SitefileError('E_NOT_FOUND', `IMPORT ${spec.name}: ${display} has no Sitefile`, spec.span);
1072
1141
  const { plan: p } = planImportedSitefile(spec, new TextDecoder().decode(bytes), label, refs);
1073
1142
  return { plan: p, source: make(label, [...from.chain, { id, label }]) };
1074
1143
  }
@@ -4,6 +4,7 @@ export { parseSitefile } from './language/parser.js';
4
4
  export { validate, parseProgram } from './language/validate.js';
5
5
  export { plan, type Plan, type Operation, type ImportSpec, type SourceRef } from './planner.js';
6
6
  export { build, buildToDirectory, planBuild, loadProgram, type BuildOptions, type BuildResult } from './executor.js';
7
+ export { DEFAULT_RECIPE_NAMES, setRecipeNames, recipeNames, resolveRecipe } from './recipe.js';
7
8
  export { exportDirectory } from './exporter.js';
8
9
  export { BuildMemo, type MemoStats } from './memo.js';
9
10
  export { Profiler } from './profile.js';
@@ -11,3 +12,4 @@ export { Tree, makeFile, type FileNode, type ConflictPolicy } from './tree.js';
11
12
  export { DEFAULT_ARCHIVE_LIMITS, DEFAULT_FETCH_POLICY, type ArchiveLimits, type FetchPolicy, type Resource } from './resources/types.js';
12
13
  export { networkFromEnv, mergeNetwork, networkProblem, hostMatches, type NetworkSettings } from './resources/network.js';
13
14
  export { extractArchive } from './resources/archive.js';
15
+ export { createSiteHandler, createSiteResponder, type CachePreview, type HtmlHandling, type RoutingProfile, type SiteContent, type SiteFile, type SiteHandlerOptions, type SiteProxy, type SiteProxyResponse, type SiteReply, type SiteRequest, type SiteTree } from './site-handler.js';
package/lib/src/index.js CHANGED
@@ -3,6 +3,7 @@ export { parseSitefile } from './language/parser.js';
3
3
  export { validate, parseProgram } from './language/validate.js';
4
4
  export { plan } from './planner.js';
5
5
  export { build, buildToDirectory, planBuild, loadProgram } from './executor.js';
6
+ export { DEFAULT_RECIPE_NAMES, setRecipeNames, recipeNames, resolveRecipe } from './recipe.js';
6
7
  export { exportDirectory } from './exporter.js';
7
8
  export { BuildMemo } from './memo.js';
8
9
  export { Profiler } from './profile.js';
@@ -10,4 +11,5 @@ export { Tree, makeFile } from './tree.js';
10
11
  export { DEFAULT_ARCHIVE_LIMITS, DEFAULT_FETCH_POLICY } from './resources/types.js';
11
12
  export { networkFromEnv, mergeNetwork, networkProblem, hostMatches } from './resources/network.js';
12
13
  export { extractArchive } from './resources/archive.js';
14
+ export { createSiteHandler, createSiteResponder } from './site-handler.js';
13
15
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The content type `serve` and Web Bundle export give a tree path: a well-known extensionless path
3
+ * (`/.well-known/apple-app-site-association`, ...) by its exact name, else by the extension, ASCII
4
+ * case-insensitively (`application/octet-stream` when unknown).
5
+ */
6
+ export declare function mimeTypeFor(path: string): string;
@@ -0,0 +1,20 @@
1
+ // Content types for tree paths. Pure: no `node:` import, so the site handler can use it anywhere.
2
+ import { MIME_TYPES, WELL_KNOWN_TYPES } from './mime-data.js';
3
+ /** Content types by extension and well-known path (tools/gen-mime.mjs; the same tables as rust/src/mime_data.rs). */
4
+ const MIME = new Map(MIME_TYPES);
5
+ const WELL_KNOWN = new Map(WELL_KNOWN_TYPES);
6
+ /**
7
+ * The content type `serve` and Web Bundle export give a tree path: a well-known extensionless path
8
+ * (`/.well-known/apple-app-site-association`, ...) by its exact name, else by the extension, ASCII
9
+ * case-insensitively (`application/octet-stream` when unknown).
10
+ */
11
+ export function mimeTypeFor(path) {
12
+ const known = WELL_KNOWN.get(path);
13
+ if (known !== undefined)
14
+ return known;
15
+ const base = path.slice(path.lastIndexOf('/') + 1);
16
+ const dot = base.lastIndexOf('.');
17
+ const ext = dot < 0 ? '' : base.slice(dot + 1).replace(/[A-Z]/g, (c) => c.toLowerCase());
18
+ return MIME.get(ext) ?? 'application/octet-stream';
19
+ }
20
+ //# sourceMappingURL=mime-type.js.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Unicode NFC. Every virtual path (Sitefile operands, names read from the
3
+ * context, archive entries, plugin outputs) is stored in NFC, so NFC and NFD
4
+ * spellings of a name are the same path on every OS.
5
+ */
6
+ export declare function nfc(s: string): string;
package/lib/src/nfc.js ADDED
@@ -0,0 +1,10 @@
1
+ const ASCII = /^[\x00-\x7f]*$/;
2
+ /**
3
+ * Unicode NFC. Every virtual path (Sitefile operands, names read from the
4
+ * context, archive entries, plugin outputs) is stored in NFC, so NFC and NFD
5
+ * spellings of a name are the same path on every OS.
6
+ */
7
+ export function nfc(s) {
8
+ return ASCII.test(s) ? s : s.normalize('NFC');
9
+ }
10
+ //# sourceMappingURL=nfc.js.map
package/lib/src/oci.d.ts CHANGED
@@ -62,6 +62,11 @@ export interface OciOptions {
62
62
  * The base's blobs must already be in the store (see base-image.ts).
63
63
  */
64
64
  readonly base?: BaseImage | undefined;
65
+ /**
66
+ * The base per platform for a multi-platform build ({@link buildOciIndex}): each platform's manifest
67
+ * builds on its own entry; a platform with no entry uses `base`.
68
+ */
69
+ readonly bases?: ReadonlyMap<string, BaseImage> | undefined;
65
70
  /** Site layer encoding: gzip (default, `tar+gzip`) or none (plain `tar`). Base layers are kept as they are. */
66
71
  readonly compression?: OciCompression | undefined;
67
72
  /**
@@ -109,11 +114,59 @@ export declare function parsePlatform(p: string | undefined): {
109
114
  os: string;
110
115
  arch: string;
111
116
  };
117
+ /**
118
+ * `--platform` as a list: `os/arch[,os/arch...]`, each element checked like {@link parsePlatform}, duplicates
119
+ * dropped, sorted (so the order on the command line never changes the image). Nothing given: an empty list.
120
+ * One platform is the image it has always been; two or more make an image index ({@link buildOciIndex}).
121
+ */
122
+ export declare function parsePlatforms(p: string | undefined): string[];
112
123
  /** Validate an in-image root path (absolute, no `..`); returns the normalized form. */
113
124
  export declare function normalizeOciRoot(raw: string | undefined): string;
125
+ /** The site's layers (see {@link buildSiteLayers}): the same bytes whatever the platform. */
126
+ interface SiteLayers {
127
+ readonly root: string;
128
+ readonly uncompressed: boolean;
129
+ readonly n: number;
130
+ readonly layers: ReadonlyArray<{
131
+ readonly bytes: Uint8Array;
132
+ readonly diffId: string;
133
+ readonly digest: string;
134
+ }>;
135
+ }
114
136
  /** Build the single-layer image for `tree` (the site's files, rooted at `/`). */
115
- export declare function buildOciImage(tree: Tree, options?: OciOptions): OciImage;
137
+ export declare function buildOciImage(tree: Tree, options?: OciOptions, prebuilt?: SiteLayers): OciImage;
138
+ /** A multi-platform image: one image index over one manifest per platform. */
139
+ export interface OciIndexImage {
140
+ readonly indexBytes: Uint8Array;
141
+ /** The image ID of a multi-platform image. */
142
+ readonly indexDigest: string;
143
+ /** One image per platform, in index order (sorted by `os/arch`). */
144
+ readonly images: ReadonlyArray<{
145
+ readonly platform: string;
146
+ readonly image: OciImage;
147
+ }>;
148
+ }
149
+ /**
150
+ * Build the image for every platform in `options.platform` (`os/arch,os/arch...`, two or more): the site layers
151
+ * are built once and shared by every manifest, each manifest builds on that platform's base
152
+ * (`options.bases`, else `options.base`), and one image index lists them sorted by `os/arch`. The index is
153
+ * canonical JSON like every other hashed document, so the bytes are the same in both implementations.
154
+ */
155
+ export declare function buildOciIndex(tree: Tree, options?: OciOptions): OciIndexImage;
156
+ export interface ParsedIndex {
157
+ /** The platform manifests, in index order. */
158
+ readonly manifests: ReadonlyArray<{
159
+ readonly digest: string;
160
+ readonly size: number;
161
+ readonly platform: string;
162
+ }>;
163
+ readonly annotations: Readonly<Record<string, string>>;
164
+ }
165
+ /** Read an image index (OCI) or manifest list (Docker): each child's digest, size and `os/arch[/variant]`. */
166
+ export declare function parseIndex(bytes: Uint8Array): ParsedIndex;
116
167
  export interface IndexEntry {
168
+ /** The entry's media type: absent means an image manifest; an image index (multi-platform image) is {@link MEDIA.index}. */
169
+ readonly mediaType?: string | undefined;
117
170
  readonly digest: string;
118
171
  readonly size: number;
119
172
  readonly refName?: string | undefined;
@@ -144,8 +197,18 @@ export declare function blobPathOf(digest: string): string;
144
197
  export declare function layoutTree(img: Pick<OciImage, 'manifestBytes' | 'manifestDigest' | 'configBytes' | 'configDigest' | 'layerBytes' | 'layerDigest' | 'extraLayers'>, refName?: string,
145
198
  /** Blobs of the layers below the site layer (digest -> bytes), for images built on a BASE. */
146
199
  baseBlobs?: ReadonlyMap<string, Uint8Array>, referrers?: readonly Referrer[]): Tree;
200
+ /**
201
+ * The layout of a multi-platform image: index.json names the image index, and the blobs hold the index,
202
+ * every platform's manifest and config, and every layer (the site layers once). `baseBlobs` are the layers
203
+ * below the site layers, of every platform.
204
+ */
205
+ export declare function layoutTreeIndex(img: Pick<OciIndexImage, 'indexBytes' | 'indexDigest' | 'images'>, refName?: string, baseBlobs?: ReadonlyMap<string, Uint8Array>, referrers?: readonly Referrer[]): Tree;
206
+ /** index.json naming the root (image or index), `oci-layout`, and the blobs. */
207
+ export declare function layoutFromBlobs(rootDigest: string, rootSize: number, rootType: string | undefined, blobs: ReadonlyMap<string, Uint8Array>, refName: string | undefined, referrers: readonly Referrer[]): Tree;
147
208
  /** Deterministic tar of {@link layoutTree}: an "OCI archive" (`.oci.tar`). */
148
209
  export declare function ociArchive(img: Parameters<typeof layoutTree>[0], refName: string | undefined, epoch: number | undefined, baseBlobs?: ReadonlyMap<string, Uint8Array>, referrers?: readonly Referrer[]): Uint8Array;
210
+ /** Deterministic tar of {@link layoutTreeIndex}. */
211
+ export declare function ociIndexArchive(img: Parameters<typeof layoutTreeIndex>[0], refName: string | undefined, epoch: number | undefined, baseBlobs?: ReadonlyMap<string, Uint8Array>, referrers?: readonly Referrer[]): Uint8Array;
149
212
  export interface ParsedManifest {
150
213
  readonly config: Descriptor;
151
214
  readonly layers: readonly Descriptor[];
@@ -194,3 +257,4 @@ export declare function gitInfo(contextDir: string): Promise<{
194
257
  source?: string;
195
258
  revision?: string;
196
259
  }>;
260
+ export {};