@johnhenry/sitefile 0.0.7 → 0.0.9

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 (68) hide show
  1. package/CHANGELOG.md +104 -1
  2. package/README.md +12 -1
  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/bucket-follow.d.ts +22 -0
  9. package/lib/src/bucket-follow.js +65 -0
  10. package/lib/src/bucket.d.ts +270 -0
  11. package/lib/src/bucket.js +1130 -0
  12. package/lib/src/cache-limit.d.ts +3 -3
  13. package/lib/src/cache-limit.js +21 -0
  14. package/lib/src/cli/bucket.d.ts +2 -0
  15. package/lib/src/cli/bucket.js +312 -0
  16. package/lib/src/cli/build-image.js +4 -2
  17. package/lib/src/cli/images.js +8 -5
  18. package/lib/src/cli/index.d.ts +1 -1
  19. package/lib/src/cli/index.js +13 -2
  20. package/lib/src/cli/serve-worker.js +63 -11
  21. package/lib/src/cli/servers.js +117 -29
  22. package/lib/src/cli/up.js +2 -0
  23. package/lib/src/cli/watch.d.ts +2 -0
  24. package/lib/src/cli/watch.js +2 -1
  25. package/lib/src/cli.js +6 -3
  26. package/lib/src/dictionary.d.ts +1 -7
  27. package/lib/src/dictionary.js +1 -35
  28. package/lib/src/executor.d.ts +16 -5
  29. package/lib/src/executor.js +127 -58
  30. package/lib/src/index.d.ts +2 -0
  31. package/lib/src/index.js +2 -0
  32. package/lib/src/mime-type.d.ts +6 -0
  33. package/lib/src/mime-type.js +20 -0
  34. package/lib/src/nfc.d.ts +6 -0
  35. package/lib/src/nfc.js +10 -0
  36. package/lib/src/oci.d.ts +65 -1
  37. package/lib/src/oci.js +104 -10
  38. package/lib/src/paths.d.ts +2 -6
  39. package/lib/src/paths.js +2 -8
  40. package/lib/src/plugins/env.d.ts +20 -0
  41. package/lib/src/plugins/env.js +37 -0
  42. package/lib/src/plugins/exec.d.ts +1 -1
  43. package/lib/src/plugins/exec.js +3 -2
  44. package/lib/src/plugins/host.js +3 -2
  45. package/lib/src/precompress.d.ts +6 -0
  46. package/lib/src/precompress.js +6 -0
  47. package/lib/src/recipe.d.ts +37 -0
  48. package/lib/src/recipe.js +96 -0
  49. package/lib/src/registry-ops.d.ts +5 -1
  50. package/lib/src/registry-ops.js +69 -45
  51. package/lib/src/request-path.d.ts +10 -0
  52. package/lib/src/request-path.js +42 -0
  53. package/lib/src/serve-dictionary.d.ts +11 -0
  54. package/lib/src/serve-dictionary.js +45 -0
  55. package/lib/src/serve-rules.js +1 -1
  56. package/lib/src/server.d.ts +16 -229
  57. package/lib/src/server.js +135 -795
  58. package/lib/src/servers.d.ts +25 -0
  59. package/lib/src/servers.js +62 -2
  60. package/lib/src/site-core.d.ts +368 -0
  61. package/lib/src/site-core.js +1065 -0
  62. package/lib/src/site-handler.d.ts +14 -0
  63. package/lib/src/site-handler.js +32 -0
  64. package/lib/src/store.d.ts +31 -2
  65. package/lib/src/store.js +140 -21
  66. package/lib/src/wbn.d.ts +1 -6
  67. package/lib/src/wbn.js +2 -18
  68. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,109 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.0.9 (2026-12-01)
4
+
5
+ - **Buckets: mutable named file trees in the store, served by name and snapshotted to images** (johnhenry/sitefile#340, PR #351, commit 6a6102a0):
6
+ `sitefile bucket create|ls|rm <name>`, `bucket put|get|rm <name>/<path>`, `bucket ls <name>[/prefix]`,
7
+ `bucket snapshot <name> -t <tag>` (an image of the bucket's current files: the image `build -t` makes from a recipe
8
+ that copies them, same ID) and `bucket restore <tag> <name>`. A bucket is plain files under
9
+ `$SITEFILE_HOME/buckets/<name>/` with its metadata beside the tree; `sitefile serve bucket:<name>[/prefix]` serves it
10
+ (also in a servers file, as `source: bucket:docs`, and with `-d`) through the site handler, so `_redirects`,
11
+ `_headers` and every serve option work as for a folder, and **follows changes** (a request after a put sees it within
12
+ 250 ms; `--reload`/`--watch` also reload open pages). Files are written by temp file and rename under the store lock;
13
+ `put --batch` and `restore --batch` publish a set of changes with one rename. Bucket names are lowercase and one path
14
+ segment; paths refuse `..`, absolute and backslash paths, NUL, non-portable names and case collisions; a bucket never
15
+ follows a symbolic link nor reads a hard-linked file; `restore` and a directory `put` never replace different content
16
+ without `--overwrite`; `put` from stdin is limited (`--max-bytes`, default 256 MiB); `rm` of a bucket that holds files
17
+ or is served needs `-f`. `bucket snapshot` leaves hidden files out by default (an image serves every file it holds; `--include-hidden` opts in), a `--batch` swap is journaled (a data-only journal, fsynced before the first rename) and recovered from the directory state, journal or not, so neither a crash nor a power cut loses the old tree (and `bucket rm` removes what could bring a bucket back before the bucket, a sweep never takes a staged tree a journal names, a failed flush stops the swap before its first rename), a read never writes when the bucket is intact, every read of a file (the staged copy included) goes through one guarded no-follow, non-blocking, size-bounded open, every conflict of `restore` and `put <dir>` (empty directories included) is found before the first write, one planted link marks only its own bucket in `bucket ls`, a reload reads only the files that changed, and `--max-bytes` caps what `serve`, `snapshot` and `restore` hold in memory. an undeletable scratch leftover is warned about once and never blocks a write, `bucket ls` reports a broken swap entry as its own problem, `bucket rm` warns before removing, says "IS removed" on a late failure and unlinks a planted link, and a staged file is flushed before it is made read-only. `cache du` lists the `buckets` (never evictable). Both implementations, with conformance
18
+ cases `ok-bucket` and `err-bucket-*`, `examples/buckets/`, and the decisions in docs/CLI.md, "Buckets". The
19
+ conformance step cases gained `stdin`, `scrub` and `expect`.
20
+
21
+ - Fix: `serve -d --watch <context>` reported itself ready, and answered requests with 404 from an empty tree, while its first build was still running (seen once in CI as conformance `watch/detached-build` step 1: TypeScript 404, Rust 200). The detached worker now builds first and starts listening, and records `ready`, only when the first build has finished (a failed first build still counts: the server then shows the error, as before), so `serve -d` returns when the site is there. Until then nothing is bound, so a connection is refused rather than answered. The wait for a build context is up to 120 seconds instead of 15. Both implementations (`src/cli/serve-worker.ts`, `rust/src/cli/servers.rs`), each with a test that holds the first build back on a named pipe and asserts nothing is answered meanwhile (johnhenry/sitefile#354).
22
+
23
+ ## 0.0.8 (2026-12-01)
24
+
25
+ - Fix: on Windows, a plugin or tool that starts Node exited with code 134 (`Assertion failed: ncrypto::CSPRNG(nullptr, 0)`) on Node 26.14.0, because the scrubbed environment had no `SystemRoot`. On Windows only, the environment of a JavaScript plugin's Node process (and its `--version` check) and of a `TOOL` now also holds `SystemRoot`, copied from the build's environment (nothing is added if it has none); on other platforms the environment is unchanged, and no other variable is passed on. Both implementations (`src/plugins/env.ts`, `rust/src/plugins/env.rs`), with unit tests that run the Windows case on any system (johnhenry/sitefile#350).
26
+
27
+ - **`IMPORT … AS sitefile` and the language server use the recipe name list** (johnhenry/sitefile#334): a
28
+ Sitefile imported from a local directory, a Git repository or a directory nested in either is the first
29
+ existing name of the configured list (`SITEFILE_RECIPE_NAMES`, `BuildOptions.recipeNames` / `recipe_names`,
30
+ `setRecipeNames` / `set_recipe_names`) instead of a literal `Sitefile`, in build, `vendor`, `outdated`,
31
+ `why` and `inspect`; messages and origins of the imported recipe use the name read. The error for a
32
+ directory with none of them names every file tried; with the default list it is unchanged. The language
33
+ server's go to definition on `name+stage` uses the list too. The TypeScript side of the list was already
34
+ in place (PR #333); there is nothing left under Known differences. Both implementations, with conformance
35
+ cases `recipe-names-import`, `recipe-names-import-inspect`, `err-recipe-names-import-missing` and
36
+ `net-recipe-names-import-git`.
37
+
38
+ - Fix: `serve -d` reported a worker that failed at once (for example `port N on 127.0.0.1 is already in use`) as `the server process exited before it was ready`, losing the reason. The worker writes its `error` to its record and then exits; the starter read the record first and asked whether the process had exited second, so it could see the old record and the exit. It now asks about the exit first and reads the record after, in both implementations (`awaitReady` in `src/servers.ts`, `await_ready` in `rust/src/servers.rs`). Regression tests model the interleaving exactly (#331, PR #348).
39
+
40
+ - Design note, no code: docs/design/attachments.md decides serve-time attachments against the gateway pattern (johnhenry/sitefile#341) and sketches the ABI, limits, ordering with `_redirects`, `_headers` and the 404 page, and how an image suggests attachments.
41
+
42
+ - **`createSiteHandler`: what `serve` answers, as a `(Request) => Response`** (johnhenry/sitefile#339, PR #347): the rules that
43
+ decide what a path answers (clean URLs, `404.html`, `_redirects`, `_headers`, ETags and `304`, byte ranges,
44
+ precompressed sidecars, `.dcz` deltas, `--compress`, `--spa`, `--base`, `--rewrite-base`, host profiles, CORS,
45
+ `--isolate`, cache previews, proxy rules) moved out of the Node listener into `src/site-core.ts` (with `src/site-handler.ts` as its public face), which import no
46
+ `node:` module and do not use `Buffer`. `createSiteHandler(tree, options)` is exported from the package and from
47
+ `@johnhenry/sitefile/site-handler`; `createSiteResponder` is the same on request parts, which `serve` uses. The tree
48
+ is any `SiteTree` (`get`, `isFile`, `isDirectory`, `entries`); a large file and a byte range are a stream of views of
49
+ the tree's bytes. `src/server.ts` keeps what needs a socket or Node: listener, `Host` allow-list, IP rules, basic
50
+ auth, connection limits, throttling, early hints, the access log and the live-reload endpoints. Proxying goes through
51
+ a `fetch` the host supplies (the server's enforces the fetch policy). Rust: `server::handle_site_request` /
52
+ `respond_site` are the same function with no I/O (`handle_request` and `respond` add `check_request`: Host and auth),
53
+ and `Response::body` is a `Body` whose whole files and ranges are windows onto the tree's bytes, not copies. Output
54
+ over a port does not change by one byte (the serve tests and conformance are unchanged); the conformance runner now
55
+ also answers every serve case's requests with the handler alone (`serve --respond-stdin`, a hidden flag) and requires
56
+ the same bytes, in both implementations. The handler is a library entry point, so it does not rely on the CLI having
57
+ checked anything: `base` and `rewriteBase` are normalized by the handler and it throws at construction for a value it
58
+ cannot normalize (never "serve everything at `/`"); a proxy target must be https and public by its literal host
59
+ (`proxy.allow` widens that) before the injected `fetch` is called, which gets `redirect: 'manual'` and no cookie,
60
+ authorization or host, and a failed or refused proxy request is a `502` whose body never says why; the `Host` header is
61
+ used, and checked, only with `allowedHosts` (otherwise the origin written by `--rewrite-base` is the request URL's).
62
+ `@johnhenry/sitefile/site-handler` exports `createSiteHandler`, `createSiteResponder` and their types, and nothing else.
63
+ `serve --respond-stdin` is refused with `-d`, `--watch`, `-p`, TLS and auth flags; `--throttle` streams a large file in
64
+ slices instead of reading it whole. Over a port the bytes are unchanged. docs/CLI.md, "The site handler".
65
+
66
+ - **Multi-platform images** (johnhenry/sitefile#342): `--platform` takes a list (`--platform linux/amd64,linux/arm64`).
67
+ With two or more platforms the build writes one OCI image index over one manifest per platform. The site layer is one
68
+ blob shared by every manifest; with `BASE` each platform's manifest uses that platform's base layers (the base is
69
+ resolved per platform; `Sitefile.lock` records its tag once). The index lists the platforms sorted by `os/arch`, so the
70
+ order given never changes the image, and both implementations write the same index bytes. The image ID is the index
71
+ digest; `-t`, `images` (one row, a `PLATFORMS` column that appears only when such an image is stored),
72
+ `image inspect`, `save --format oci` / `build -o x.oci.tar` (the index, every manifest, the layers once), `serve`,
73
+ `rmi`, `image prune` and the cache size limit treat it as one image, `push` sends the index (each manifest by digest,
74
+ shared and base layers once or mounted), and `--provenance` / `--sbom` attest the index (the provenance and the SBOM
75
+ record each platform's base, as `base:linux/amd64`, `base:linux/arm64`, ...; a single-platform build keeps its one
76
+ `base` entry, byte for byte). `pull --platform` narrows an
77
+ index as before. A build with no `--platform`, one platform, or a list naming one platform produces exactly the bytes
78
+ and image ID it did. Both implementations, with conformance cases `example/blog:oci-platforms-*`, `net-oci-platforms`, `net-oci-platforms-single` and
79
+ `err-platform-list`. docs/CLI.md, "Multi-platform images". Not done: running the result on real amd64 and arm64
80
+ engines needs a container engine (CI's `engine:` tests); the index is checked against the image-spec structure and
81
+ pushed to and pulled from the in-process test registry. **Open decision, not changed**: for a files-only image with no
82
+ `--platform`, dropping the amd64 claim (or writing an index over the common pair) would change every existing image
83
+ ID, so the default stays `linux/amd64`. `--platform` is still checked only where an image, a `BASE` or an
84
+ attestation needs it: `sitefile build -o dist/ --platform bogus` on a directory export builds as before.
85
+ **Downgrade hazard**: the store has no format version that an older sitefile checks (`oci-layout` is only created,
86
+ never read), so an older sitefile that runs `tag`, `rmi` or `build -t` on a store holding a multi-platform image
87
+ rewrites that entry as a plain image. A newer sitefile then refuses the image with an `E_STORE` that says what
88
+ happened; rebuild it (`build -t <name> --platform ...`) or pull it again. Do not share one `SITEFILE_HOME` between
89
+ versions.
90
+
91
+ - Fix (Windows): concurrent writers could fail with `cannot lock the store … Access is denied (os error 5)` when one created the lock file while another was deleting it. A lock file pending deletion now counts as busy, in both implementations; any other error is unchanged, and a denial that lasts past the 20 s deadline is still reported (#337).
92
+
93
+ - Tests: the Brotli parity check accepts node:zlib Brotli 1.2.1, which newer Node 26 releases bundle: it writes the same bytes as the vendored 1.2.0 (pinned digests and a 130-file corpus). The bytes are checked first, and an unverified version still fails (#335, #336).
94
+
95
+ - **Configurable default recipe file names** (johnhenry/sitefile#332, PR #333): the file read when no
96
+ `-f` is given is the first existing name of an ordered list, `["Sitefile"]` by default, so the CLI is
97
+ unchanged. Embedders set the list with `sitefile::set_recipe_names(&["Stockerfile", "Sitefile"])` in Rust, `setRecipeNames(["Stockerfile", "Sitefile"])` in TypeScript (one
98
+ process-wide default, which also reaches `sitefile::cli::main` and detached `serve` workers) or
99
+ per build with `BuildOptions::recipe_names` / `recipeNames`; a CLI user can opt in with `SITEFILE_RECIPE_NAMES`
100
+ (comma-separated). `recipe::resolve_recipe` / `resolveRecipe` is the one resolver per implementation, used by build, validate, inspect, graph,
101
+ why, hosts, vendor, outdated, bake, attestations, `serve` (project or plain folder) and watch mode (a
102
+ change to the recipe in use rebuilds). When none exists the error names the files tried (`no recipe
103
+ found in 'dir' (tried: Stockerfile, Sitefile)`); with the default list the message is unchanged.
104
+ `Sitefile.lock` and `IMPORT … AS sitefile` keep their names. docs/CLI.md, "Which file is the recipe",
105
+ and docs/RUST.md, "Embedding the crate". New public items only; Rust `BuildOptions` gains a field (use
106
+ `..Default::default()`). Both implementations, with conformance cases `recipe-names` and `err-recipe-names-missing`; `IMPORT … AS sitefile` is the follow-up johnhenry/sitefile#334.
4
107
 
5
108
  ## 0.0.7 (2026-11-10)
6
109
 
package/README.md CHANGED
@@ -223,7 +223,8 @@ sitefile build [context] -t name[:tag] # also store the build as an image
223
223
  sitefile images | image inspect|diff|prune | tag | rmi | save
224
224
  sitefile cache info | cache prune [--older-than days] # TRANSFORM result cache
225
225
  sitefile cache du # cache sizes; SITEFILE_CACHE_MAX bounds them (default 1G)
226
- sitefile serve [-d] [--name n] [-p [host:]port] [--spa] <image|./dir|site.zip>
226
+ sitefile serve [-d] [--name n] [-p [host:]port] [--spa] <image|./dir|site.zip|bucket:name>
227
+ sitefile bucket create|ls|rm <name> | put|get|rm <name>/<path> | snapshot <name> -t <tag> | restore <tag> <name> # mutable named file trees
227
228
  sitefile serve --watch [-p [host:]port] [--spa] [context] # build in memory, serve, live reload
228
229
  sitefile servers [-a] | server stop|rm [-f]|restart|logs [-f] <name>
229
230
  sitefile up | down | ps [-f sitefile.servers.yaml] # several servers from one file, like docker compose
@@ -261,6 +262,10 @@ Targets also take `context`, `file`, `target` (a stage), `format`, `tags` and `i
261
262
  when one fails (then the exit code is 1); outputs that overlap or a tag used twice are refused before anything is
262
263
  built. See [docs/CLI.md](docs/CLI.md#variants-sitefile-bake).
263
264
 
265
+ ## Recipe file name
266
+
267
+ Without `-f`, the recipe is the first existing name of `["Sitefile"]`. `SITEFILE_RECIPE_NAMES=Stockerfile,Sitefile` changes the list for a CLI run; programs that embed the library call `setRecipeNames` (TypeScript) or `sitefile::set_recipe_names` (Rust). See [docs/CLI.md](docs/CLI.md#which-file-is-the-recipe).
268
+
264
269
  ## Watch mode
265
270
 
266
271
  ```bash
@@ -302,6 +307,11 @@ sitefile serve -d --name site -p 8080 hello:1 # serve it, in the background
302
307
  sitefile servers; sitefile server logs site; sitefile server stop site; sitefile server rm site
303
308
  ```
304
309
 
310
+ A **bucket** is the mutable counterpart: a named tree of files in the same store, where files are put and changed
311
+ (`sitefile bucket create site; sitefile bucket put site ./dist; sitefile serve bucket:site`). A server on a bucket
312
+ follows its changes, and `sitefile bucket snapshot site -t site:1` writes an image of its current files, the image
313
+ `build` would make from a recipe that copies them. See [docs/CLI.md](docs/CLI.md#buckets).
314
+
305
315
  `serve` serves GET/HEAD only on `127.0.0.1` (never `0.0.0.0` unless you ask for it in `-p`), with ETags,
306
316
  correct MIME types and no directory listings; it serves `/404.html` for missing paths, `/about` from
307
317
  `/about.html`, and honours the site's `_redirects` and `_headers` (exact paths and `/*` splats). `EXPORT / AS oci` (or `build -o site.oci.tar`) writes the
@@ -374,6 +384,7 @@ stopgap in VS Code.
374
384
  - [docs/PLUGINS.md](docs/PLUGINS.md) — writing renderer plugins, and the sandbox
375
385
  - [docs/DOCKER.md](docs/DOCKER.md) — sitefile next to Docker: site images Docker runs, Dockerfile stages, shared registries
376
386
  - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — invariants and module layout
387
+ - [docs/design/attachments.md](docs/design/attachments.md) — design note: serve-time attachments or the gateway pattern (#341)
377
388
  - [docs/MILESTONES.md](docs/MILESTONES.md), [docs/TASKS.md](docs/TASKS.md)
378
389
  - [AGENTS.md](AGENTS.md) — the verification loop and rules for anyone (human or agent) changing this repo
379
390
 
@@ -76,6 +76,12 @@ export interface BuildFacts {
76
76
  readonly name: string;
77
77
  readonly digest: string;
78
78
  } | undefined;
79
+ /** With two or more platforms: each platform's BASE (name and manifest digest), in platform order. `base` is the first one's. */
80
+ readonly bases?: ReadonlyArray<{
81
+ readonly platform: string;
82
+ readonly name: string;
83
+ readonly digest: string;
84
+ }> | undefined;
79
85
  /** `FROM image` stage bases, in stage order (FROM line, image name, image digest). */
80
86
  /** `import`: the qualified name of the imported Sitefile (IMPORT … AS sitefile) whose stage it is. */
81
87
  readonly images?: ReadonlyArray<{
@@ -93,6 +99,8 @@ export interface BuildFacts {
93
99
  export interface AttestSubject {
94
100
  readonly digest: string;
95
101
  readonly size: number;
102
+ /** The subject's media type: an image manifest (default) or, for a multi-platform image, an image index. */
103
+ readonly mediaType?: string | undefined;
96
104
  /** The site's files (rooted at `/`) and where they sit in the image. */
97
105
  readonly files: Tree;
98
106
  readonly root: string;
@@ -102,11 +110,12 @@ export interface AttestSubject {
102
110
  /** Whether a build-arg name looks like it holds a secret (any `_`-separated word is key, token, password, ...). */
103
111
  export declare function isSecretArgName(name: string): boolean;
104
112
  /** The Sitefile path the build used, as `build` resolves it. */
105
- export declare function sitefilePathOf(contextDir: string, sitefile: string | undefined): string;
113
+ export declare function sitefilePathOf(contextDir: string, sitefile: string | undefined, recipeNames?: readonly string[]): string;
106
114
  /** Collect the facts for a finished build. Reads the Sitefile again to digest it. */
107
- export declare function buildFacts(result: Pick<BuildResult, 'resources' | 'base' | 'pins' | 'images'>, options: {
115
+ export declare function buildFacts(result: Pick<BuildResult, 'resources' | 'base' | 'bases' | 'pins' | 'images'>, options: {
108
116
  readonly contextDir: string;
109
117
  readonly sitefile?: string | undefined;
118
+ readonly recipeNames?: readonly string[] | undefined;
110
119
  readonly label?: string | undefined;
111
120
  readonly buildArgs?: Readonly<Record<string, string>> | undefined;
112
121
  readonly platform?: string | undefined;
@@ -116,7 +125,7 @@ export declare function provenancePredicate(facts: BuildFacts, epoch: number | u
116
125
  /** CycloneDX 1.6 SBOM: the image, its BASE and every file of the site layer. */
117
126
  export declare function sbomPredicate(subject: AttestSubject, facts: BuildFacts, epoch: number | undefined): Record<string, unknown>;
118
127
  /** Wrap a predicate in an in-toto statement about `subject` and an OCI artifact manifest. */
119
- export declare function attestationReferrer(subject: Pick<AttestSubject, 'digest' | 'size'>, predicateType: string, predicate: unknown): Referrer;
128
+ export declare function attestationReferrer(subject: Pick<AttestSubject, 'digest' | 'size' | 'mediaType'>, predicateType: string, predicate: unknown): Referrer;
120
129
  /** The requested attestations for an image, provenance first. */
121
130
  export declare function makeAttestations(subject: AttestSubject, facts: BuildFacts, request: AttestRequest, epoch: number | undefined): Referrer[];
122
131
  /** An OCI image index listing referrers (the store's referrers file and the registry fallback tag). */
package/lib/src/attest.js CHANGED
@@ -2,7 +2,8 @@ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { sha256 } from './digest.js';
4
4
  import { SitefileError } from './errors.js';
5
- import { canonicalJson, MEDIA } from './oci.js';
5
+ import { recipePath } from './recipe.js';
6
+ import { canonicalJson, MEDIA, parsePlatforms } from './oci.js';
6
7
  import { SITEFILE_VERSION } from './version.js';
7
8
  /**
8
9
  * Build attestations for OCI site images (`build --provenance` / `--sbom`).
@@ -48,12 +49,12 @@ export function isSecretArgName(name) {
48
49
  .some((w) => SECRET_WORDS.has(w));
49
50
  }
50
51
  /** The Sitefile path the build used, as `build` resolves it. */
51
- export function sitefilePathOf(contextDir, sitefile) {
52
- return path.resolve(sitefile ?? path.join(contextDir, 'Sitefile'));
52
+ export function sitefilePathOf(contextDir, sitefile, recipeNames) {
53
+ return path.resolve(sitefile ?? recipePath(contextDir, recipeNames));
53
54
  }
54
55
  /** Collect the facts for a finished build. Reads the Sitefile again to digest it. */
55
56
  export async function buildFacts(result, options) {
56
- const file = sitefilePathOf(options.contextDir, options.sitefile);
57
+ const file = sitefilePathOf(options.contextDir, options.sitefile, options.recipeNames);
57
58
  let bytes;
58
59
  try {
59
60
  bytes = new Uint8Array(await readFile(file));
@@ -79,9 +80,11 @@ export async function buildFacts(result, options) {
79
80
  sitefileDigest: sha256(bytes),
80
81
  args,
81
82
  redactedArgs,
82
- platform: options.platform ?? 'linux/amd64',
83
+ // A list is recorded sorted and without repeats, as the image index lists it.
84
+ platform: options.platform === undefined ? 'linux/amd64' : parsePlatforms(options.platform).join(','),
83
85
  imports,
84
86
  base: result.base ? { name: result.base.name, digest: result.base.manifestDigest } : undefined,
87
+ ...(result.bases && result.bases.size > 1 ? { bases: [...result.bases].map(([platform, b]) => ({ platform, name: b.name, digest: b.manifestDigest })) } : {}),
85
88
  images: result.images?.map((i) => ({ line: i.line, name: i.name, digest: i.digest, ...(i.import !== undefined ? { import: i.import } : {}) })),
86
89
  pins: result.pins,
87
90
  label: options.label ?? (path.relative(process.cwd(), file) || path.basename(file)),
@@ -114,8 +117,9 @@ export function provenancePredicate(facts, epoch) {
114
117
  const pin = i.import === undefined ? facts.pins?.images?.[i.line] : undefined;
115
118
  deps.push({ name: i.import === undefined ? `from:${i.line}` : `from:${i.import}:${i.line}`, uri: i.name, digest: { sha256: hex(i.digest) }, ...(pin ? { annotations: { 'dev.sitefile.pin': pin } } : {}) });
116
119
  }
117
- if (facts.base) {
118
- deps.push({ name: 'base', uri: facts.base.name, digest: { sha256: hex(facts.base.digest) }, ...(facts.pins?.base ? { annotations: { 'dev.sitefile.pin': facts.pins.base } } : {}) });
120
+ // One BASE per platform when there are several (`base:<os>/<arch>`); a single-platform build keeps its one `base`.
121
+ for (const b of facts.bases ?? (facts.base ? [{ platform: undefined, ...facts.base }] : [])) {
122
+ deps.push({ name: b.platform === undefined ? 'base' : `base:${b.platform}`, uri: b.name, digest: { sha256: hex(b.digest) }, ...(facts.pins?.base ? { annotations: { 'dev.sitefile.pin': facts.pins.base } } : {}) });
119
123
  }
120
124
  const runDetails = { builder: { id: ATTEST.builderId, version: { sitefile: SITEFILE_VERSION } } };
121
125
  if (epoch !== undefined)
@@ -131,8 +135,9 @@ export function sbomPredicate(subject, facts, epoch) {
131
135
  if (epoch !== undefined)
132
136
  metadata.timestamp = isoOf(epoch);
133
137
  const components = [];
134
- if (facts.base)
135
- components.push({ type: 'container', 'bom-ref': 'base', name: facts.base.name, version: facts.base.digest });
138
+ for (const b of facts.bases ?? (facts.base ? [{ platform: undefined, ...facts.base }] : [])) {
139
+ components.push({ type: 'container', 'bom-ref': b.platform === undefined ? 'base' : `base:${b.platform}`, name: b.name, version: b.digest });
140
+ }
136
141
  const prefix = `${facts.label}:`;
137
142
  for (const [p, n] of subject.files.entries()) {
138
143
  const name = subject.root === '/' ? p : subject.root + p;
@@ -162,7 +167,7 @@ export function attestationReferrer(subject, predicateType, predicate) {
162
167
  artifactType: ATTEST.inToto,
163
168
  config: { mediaType: ATTEST.emptyConfig, digest: EMPTY_DIGEST, size: EMPTY_JSON.byteLength },
164
169
  layers: [{ mediaType: ATTEST.inToto, digest: layerDigest, size: statement.byteLength, annotations }],
165
- subject: { mediaType: MEDIA.manifest, digest: subject.digest, size: subject.size },
170
+ subject: { mediaType: subject.mediaType ?? MEDIA.manifest, digest: subject.digest, size: subject.size },
166
171
  annotations,
167
172
  }));
168
173
  const digest = sha256(manifest);
package/lib/src/bake.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { SitefileError } from './errors.js';
4
+ import { recipePath } from './recipe.js';
4
5
  import { collectBuildArgs } from './build-args.js';
5
6
  import { planBuild, sitefileCompression } from './executor.js';
6
7
  import { defaultOutName } from './export-formats.js';
@@ -228,7 +229,7 @@ function expand(def, bakeDir) {
228
229
  list.push({
229
230
  name,
230
231
  context,
231
- file: fields.file !== undefined ? joinTo(bakeDir, sub('file', fields.file)) : path.join(context, 'Sitefile'),
232
+ file: fields.file !== undefined ? joinTo(bakeDir, sub('file', fields.file)) : recipePath(context),
232
233
  args,
233
234
  argFiles: (fields['arg-files'] ?? []).map((f) => joinTo(bakeDir, sub('arg-files', f))),
234
235
  target: fields.target !== undefined ? sub('target', fields.target) : null,
@@ -74,3 +74,5 @@ export interface FromImage {
74
74
  export declare function resolveFromImage(input: string, at: string | undefined, local: boolean, o: ResolveBaseOptions): Promise<FromImage>;
75
75
  /** Read the blobs of `layers` from the store (verifying each digest), for writing a self-contained layout. */
76
76
  export declare function readLayerBlobs(store: Store, layers: readonly Descriptor[]): Promise<Map<string, Uint8Array>>;
77
+ /** {@link readLayerBlobs} for the base layers of several platforms (layers they share are read once). */
78
+ export declare function readBaseBlobs(store: Store, layers: ReadonlyArray<readonly Descriptor[]>): Promise<Map<string, Uint8Array>>;
@@ -135,4 +135,12 @@ export async function readLayerBlobs(store, layers) {
135
135
  out.set(l.digest, await store.readBlob(l.digest, l.size));
136
136
  return out;
137
137
  }
138
+ /** {@link readLayerBlobs} for the base layers of several platforms (layers they share are read once). */
139
+ export async function readBaseBlobs(store, layers) {
140
+ const out = new Map();
141
+ for (const l of layers)
142
+ for (const [d, b] of await readLayerBlobs(store, l))
143
+ out.set(d, b);
144
+ return out;
145
+ }
138
146
  //# sourceMappingURL=base-image.js.map
@@ -0,0 +1,22 @@
1
+ import type { ServerState } from './servers.js';
2
+ import type { Store } from './store.js';
3
+ /** How often a server on a bucket looks for changes. */
4
+ export declare const BUCKET_POLL_MS = 250;
5
+ /**
6
+ * Keep a server on `bucket:<name>[/prefix]` current. Every {@link BUCKET_POLL_MS} the bucket directory is
7
+ * compared with what was last read (size, mtime, ctime and inode of every entry; links are never followed): the
8
+ * poll only `lstat`s, so its cost is proportional to the number of entries, never to their size. On a change
9
+ * `reload` runs (it reads only the files whose stamp changed, see `BucketReadCache`), so a request made after a put
10
+ * sees the new files within that interval. A reload that fails (a symbolic link planted in the bucket, the bucket
11
+ * removed, a file gone mid-read) is reported once through `onError` and the last good copy stays; it is tried again
12
+ * on the next change and after a second. Returns a function that stops it.
13
+ * Twin: `follow_bucket` in rust/src/bucket.rs.
14
+ */
15
+ export declare function followBucket(store: Store, source: Extract<ServerState['source'], {
16
+ kind: 'bucket';
17
+ }>, o: {
18
+ readonly reload: () => Promise<void>;
19
+ readonly onError: (e: unknown) => void;
20
+ readonly pollMs?: number;
21
+ readonly retryMs?: number;
22
+ }): () => void;
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ import { Buckets } from './bucket.js';
3
+ import { SitefileError } from './errors.js';
4
+ import { pollSnapshot } from './watch.js';
5
+ /** How often a server on a bucket looks for changes. */
6
+ export const BUCKET_POLL_MS = 250;
7
+ /**
8
+ * Keep a server on `bucket:<name>[/prefix]` current. Every {@link BUCKET_POLL_MS} the bucket directory is
9
+ * compared with what was last read (size, mtime, ctime and inode of every entry; links are never followed): the
10
+ * poll only `lstat`s, so its cost is proportional to the number of entries, never to their size. On a change
11
+ * `reload` runs (it reads only the files whose stamp changed, see `BucketReadCache`), so a request made after a put
12
+ * sees the new files within that interval. A reload that fails (a symbolic link planted in the bucket, the bucket
13
+ * removed, a file gone mid-read) is reported once through `onError` and the last good copy stays; it is tried again
14
+ * on the next change and after a second. Returns a function that stops it.
15
+ * Twin: `follow_bucket` in rust/src/bucket.rs.
16
+ */
17
+ export function followBucket(store, source, o) {
18
+ const dir = path.join(Buckets.open(store).root, source.name);
19
+ let stopped = false;
20
+ let timer;
21
+ let last;
22
+ let lastError = '';
23
+ let failedAt;
24
+ const stamp = async () => {
25
+ const snap = await pollSnapshot({ dirs: [dir], files: [dir] });
26
+ return [...snap.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([p, s]) => `${p}\0${s}`).join('\n');
27
+ };
28
+ const tick = async () => {
29
+ try {
30
+ const now = await stamp();
31
+ if (stopped)
32
+ return;
33
+ // The first look reloads too: the server read the bucket before this stamp was taken, and a change in
34
+ // between must not be missed (`reload` keeps the tree it has when nothing differs).
35
+ // A reload that failed is tried again a second later even if nothing changed since: the failure may have been
36
+ // a file that vanished mid-read (a change made while we looked), which leaves nothing new to see.
37
+ const retry = failedAt !== undefined && Date.now() - failedAt >= (o.retryMs ?? 1000);
38
+ if (now !== last || retry) {
39
+ last = now;
40
+ try {
41
+ await o.reload();
42
+ lastError = '';
43
+ failedAt = undefined;
44
+ }
45
+ catch (e) {
46
+ failedAt = Date.now();
47
+ const text = e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : String(e?.message ?? e);
48
+ if (text !== lastError)
49
+ o.onError(e);
50
+ lastError = text;
51
+ }
52
+ }
53
+ }
54
+ finally {
55
+ if (!stopped)
56
+ timer = setTimeout(() => void tick(), o.pollMs ?? BUCKET_POLL_MS);
57
+ }
58
+ };
59
+ void tick();
60
+ return () => {
61
+ stopped = true;
62
+ clearTimeout(timer);
63
+ };
64
+ }
65
+ //# sourceMappingURL=bucket-follow.js.map