@git-stunts/git-cas 7.1.0 → 8.0.0-rc.1

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/ARCHITECTURE.md CHANGED
@@ -487,8 +487,8 @@ Its cursor is a position, not a pin: GC may make an older snapshot unavailable.
487
487
  Point inspection observes ledger and custody separately; it makes no multi-ref
488
488
  snapshot claim. See the [public contract](docs/API.md#durable-reservations)
489
489
  and [cycle0063 design](https://github.com/git-stunts/git-cas/blob/4782052214269c72acc95f63191e89897059bb56/docs/design/0063-durable-reservations/durable-reservations.md).
490
- The implementation is merged; [#162](https://github.com/git-stunts/git-cas/issues/162)
491
- tracks release publication separately.
490
+ The capability is published in v7.1.0; [#162](https://github.com/git-stunts/git-cas/issues/162)
491
+ retains release and registry-consumer evidence.
492
492
 
493
493
  High-level retention, CacheSet, cache acquisition, ExpiringSet, and application
494
494
  publication operations return generation-scoped retention evidence. Replacing
package/CHANGELOG.md CHANGED
@@ -7,9 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [7.1.0] — 2026-11-02
10
+ ## [8.0.0-rc.1] — 2026-12-01
11
+
12
+ ### Breaking Changes
13
+
14
+ - git-cas depends on `@git-stunts/plumbing` 4 (`^4.0.0-rc.1`) instead of 3.x. Plumbing 4 itself changes behavior for applications that also call it directly; see `UPGRADING.md`.
15
+ - An application that passes its own plumbing instance to git-cas must use plumbing 4, installed as the same copy git-cas uses. git-cas recognises plumbing's errors by class, so an instance from a separate 3.x copy turns, for example, a missing object into plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`.
16
+ - `GitPersistenceAdapter.readBlobStream()` starts its one-shot `git cat-file blob` command when the caller first reads the returned stream, not when the stream is returned. A stream that is never read starts no git process, and a stream first read after the adapter closed fails with `RESOURCE_CLOSED`.
17
+
18
+ ### Added
11
19
 
12
- Release candidate: publication is tracked in [#162](https://github.com/git-stunts/git-cas/issues/162).
20
+ - Optional `@git-stunts/git-cas/files` helper `materializeFile()` streams an async byte source to a private sibling file, then renames on success, and resolves if and only if the file was published. It does not fsync. It supports cancellation, which rejects with `signal.reason` until the rename starts, and optional whole-plaintext SHA-256 verification. It follows a destination symlink, including a dangling one, that resolves inside the base and replaces or creates the file it names. It reuses restore path confinement, rejects an output path that resolves to the base directory before reading the source, rejects source chunks that are not `Uint8Array` with `INVALID_OPTIONS`, and leaves the core byte-stream and buffer APIs unchanged. `restoreFile()` changes only by the path fixes listed under Fixed.
21
+
22
+ ### Changed
23
+
24
+ - `@git-stunts/plumbing` moves from `^3.3.3` to `^4.0.0-rc.1`, which accepts the first 4.0.0 release candidate (npm `next` tag) and every later 4.x release, including 4.0.0 final. The lockfile resolves `4.0.0-rc.1`. An application that passes its own plumbing instance to git-cas must use plumbing 4 resolved to the same installed copy, so that git-cas recognises plumbing's errors; see `UPGRADING.md`. git-cas already accepts 40- and 64-digit object ids, installs no signal handlers, supplies no custom command runner, and does not retry on plumbing timeouts. The unit and integration suites pass on Node, Bun and Deno, and 500 consecutive two-writer guarded root-set replacements (`scripts/diagnostics/stress-root-set-replacement.js`) each accept exactly one winner.
25
+ - With 4.0.0-rc.1, a guarded `update-ref` that loses a compare-and-swap race through `plumbing.execute()` reports git's complete stderr and arrives as `GitRepositoryLockedError` (git-stunts/plumbing#9). Root-set persistence keeps its fallback that treats an exit-128 failure with empty stderr and an observed head advance as a conflict.
26
+ - Manifests record `formatVersion` as the `MAJOR.MINOR.PATCH` core of the package version, so 8.0.0-rc.1 writes `"8.0.0"`. The manifest schema, in this release and every release since 6.0.0, accepts only three numeric components; stamping `8.0.0-rc.1` would have made every new manifest fail validation. The encryption migration script stamps the same value. Stable versions are unchanged.
27
+ - The release workflow publishes a version that contains a hyphen, such as `8.0.0-rc.1`, to npm under the `next` dist-tag and marks its GitHub Release as a prerelease. A plain version publishes under `latest` as before. The publish step refuses to run if the dist-tag does not match the version.
28
+
29
+ ### Performance
30
+
31
+ - The default JSON façade uses a runtime adapter for native UTF-8 decoding; the exported portable JsonCodec stays unchanged. `test/benchmark/json-decode.bench.js` measured decoding of generated manifest-shaped metadata 2.6x to 6x faster on Node 22, rising with payload size. Runtimes whose `TextDecoder` rejects the `fatal` option, such as Node builds without ICU, use the portable decoder. Malformed-byte fallback, BOM handling, JSON parsing, validation and stored encoding remain compatible.
32
+
33
+ ### Fixed
34
+
35
+ - `restoreFile()` and `materializeFile()` accept output names inside the base directory that begin with two dots, such as `..cache`. Only `..` and paths that begin with `..` plus a separator are treated as escapes.
36
+ - `restoreFile()` rejects an output path that is a dangling symlink to a location outside the base directory with `SECURITY_BOUNDARY_VIOLATION`. Before, the boundary check treated the missing link target as an ordinary new file inside the base, and the restore wrote through the link to the outside location. A dangling link to a path inside the base is now followed in every restore mode, creating the file it names and keeping the link; before, a bounded (buffered) restore replaced such a link with a regular file. Link text is resolved one component at a time, as the kernel resolves it, so in `dir/../file` the `..` applies after the symlink `dir` is followed. Link text that passes through a regular file, such as `file.txt/../x` or `file.txt/`, is rejected with `ENOTDIR`.
37
+ - When `GitPersistenceAdapter.readBlobStream()` reads a blob with a one-shot `git cat-file blob` command, it now starts that command when the caller first reads the stream, not when the stream is returned. It uses that command for a blob over 10 MiB, when its `cat-file` session cannot report the object's type and size, reports a type other than blob, or fails to read the blob, and with plumbing that has no object sessions. Plumbing 4 fails a command's stdout with `UnreadOutputLimitError` once more than 10 MiB arrives unread, so with the old eager start a blob over 10 MiB whose caller waited before reading would fail. Such a stream starts no `git cat-file blob` if it is never read, and fails with `RESOURCE_CLOSED` if first read after the adapter closed. A blob of 10 MiB or less that the adapter's `cat-file` session reads is still read into memory before `readBlobStream()` returns, and its stream still yields after close.
38
+
39
+ ## [7.2.0] — 2026-11-06
40
+
41
+ ### Changed
42
+
43
+ - The reservation index is now a path-compressed trie (#167). A record sits at
44
+ the shortest route prefix no other record shares, so a ledger update writes
45
+ one record blob and about log16(records) trees instead of 64. A 7.1.0 index
46
+ still reads and updates without migration. git-cas 7.1.0 refuses an index
47
+ written by this version as corrupt on read, list and recovery, so every
48
+ process that reads or writes a clone's reservation ledger must upgrade
49
+ together.
50
+
51
+ ## [7.1.0] — 2026-11-02
13
52
 
14
53
  ### Added
15
54
 
package/README.md CHANGED
@@ -58,12 +58,19 @@ and [release notes](./docs/releases/v7.0.0.md). This release requires
58
58
  published Plumbing 3.3.3. [Release and registry evidence](https://github.com/git-stunts/git-cas/issues/154)
59
59
  records its publication.
60
60
 
61
- The v7.1.0 release candidate adds [durable reservations](./docs/API.md#durable-reservations):
61
+ Published v7.1.0 adds [durable reservations](./docs/API.md#durable-reservations):
62
62
  hard record-slot admission before an application effect, pinned evidence and
63
- bounded recovery/inspection. It is not in the published v7.0.0 package.
64
- The implementation is merged; [release notes](./docs/releases/v7.1.0.md) describe
65
- the contract and [#162](https://github.com/git-stunts/git-cas/issues/162)
66
- tracks publication and fresh registry-consumer verification.
63
+ bounded recovery/inspection. See the [release notes](./docs/releases/v7.1.0.md)
64
+ and [publication and fresh registry-consumer evidence](https://github.com/git-stunts/git-cas/issues/162).
65
+ The signed tag, npm gitHead and successful release workflow agree on `18f87dd`.
66
+
67
+ Published v7.2.0 path-compresses the reservation index, so a ledger
68
+ update writes about log16(records) trees instead of 64. A 7.1.0 index still
69
+ reads and updates, but 7.1.0 refuses an index 7.2.0 has written; see the
70
+ [release notes](./docs/releases/v7.2.0.md) and
71
+ [#169](https://github.com/git-stunts/git-cas/issues/169).
72
+
73
+ The v8.0.0-rc.1 release candidate moves git-cas to `@git-stunts/plumbing` 4 and is bound for npm's `next` dist-tag; `latest` stays on 7.2.0. An application that passes its own plumbing instance must use plumbing 4 too, and `readBlobStream()` now starts git on first read. See the [migration guidance](./UPGRADING.md#v720-to-v800-rc1) and [release notes](./docs/releases/v8.0.0-rc.1.md).
67
74
 
68
75
  The published v6.5.12 release bounds object-metadata requests so root sets with more than 1000 targets (936 for SHA-256) validate within Plumbing's cat-file request limits. Admission still rejects missing and mismatched targets before publication; see [v6.5.12 Release Notes](./docs/releases/v6.5.12.md).
69
76
 
@@ -118,6 +125,33 @@ retention witness identifies the exact Git generation and tree edge that made
118
125
  the asset reachable. `close()` releases local resources only; it never deletes
119
126
  objects, updates refs, or changes retention.
120
127
 
128
+ ### Optional atomic file output
129
+
130
+ Byte streaming remains the default. Applications that want a complete file
131
+ published only after streaming succeeds can opt into a separate helper.
132
+ The CAS session must stay open until the helper finishes:
133
+
134
+ ```js
135
+ import ContentAddressableStore from '@git-stunts/git-cas';
136
+ import { materializeFile } from '@git-stunts/git-cas/files';
137
+
138
+ // `handle` is the content locator returned by an earlier cas.assets.put().
139
+ async function materializeAsset(handle) {
140
+ const cas = await ContentAddressableStore.open({ cwd: '.' });
141
+ try {
142
+ await materializeFile({
143
+ source: cas.assets.open({ handle }),
144
+ baseDirectory: '/existing/cache',
145
+ outputPath: 'asset.bin',
146
+ });
147
+ } finally {
148
+ await cas.close();
149
+ }
150
+ }
151
+ ```
152
+
153
+ The helper stages beside the destination, renames on success, and resolves if and only if the file was published. It does not fsync, so after a crash or power loss the destination can hold the old contents, the new contents, or an empty or truncated file on some filesystems. After cancellation, a source that was blocked in a pull may finish that one pull after the helper settles; its result or error is discarded, so closing the session once the helper settles, as above, is safe. See the [contract, cancellation and optional SHA-256 check](./docs/API.md#optional-file-materialization-git-stuntsgit-casfiles). The application owns cache policy and durability requirements.
154
+
121
155
  ## Capability Map
122
156
 
123
157
  The README is the front door. Detailed mechanics live in the guide set:
package/UPGRADING.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  This guide covers breaking changes and migration steps for git-cas releases.
4
4
 
5
+ ## v7.2.0 To v8.0.0-rc.1
6
+
7
+ git-cas 8.0.0-rc.1 is a release candidate on npm's `next` dist-tag (`npm install @git-stunts/git-cas@next`); `latest` stays on 7.2.0. It depends on `@git-stunts/plumbing` `^4.0.0-rc.1`, which accepts plumbing 4.0.0 final and later 4.x releases. The stored data format and the public API's signatures do not change, but three behaviors are breaking for consumers. See the [release notes](./docs/releases/v8.0.0-rc.1.md).
8
+
9
+ ### Plumbing 4
10
+
11
+ If your application also uses plumbing directly, read the plumbing 4.0.0 changelog: a deadline now kills git's whole process group and is not retried, more than 10 MiB of unread stdout fails with `UnreadOutputLimitError`, `GitSha` accepts SHA-256 ids, and plumbing forwards `SIGINT`, `SIGTERM` and `SIGHUP` to running git commands (declare a handler plumbing cannot see with `declareSignalHandler()`).
12
+
13
+ ### Injected plumbing instances
14
+
15
+ If you pass your own plumbing instance to `ContentAddressableStore` (or to `GitPersistenceAdapter`, `GitRefAdapter` or `GitRepositoryInspectionAdapter`), change your application's `@git-stunts/plumbing` dependency to a plumbing 4 range that resolves to the same version git-cas uses, such as `^4.0.0-rc.1`, so that your package manager installs one copy shared with git-cas. Check with `npm ls @git-stunts/plumbing` or `pnpm why @git-stunts/plumbing` that only one copy is installed. git-cas recognises plumbing's errors (`GitObjectMissingError`, `GitProtocolError`, `InvalidArgumentError`) by class. An instance from a separately installed 3.x copy throws errors of other classes, so, for example, reading a missing object reports plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`, and git-cas's one-time recovery of a failed object session does not run.
16
+
17
+ ### Lazy `readBlobStream()`
18
+
19
+ `GitPersistenceAdapter.readBlobStream()` now starts its one-shot `git cat-file blob` command when you first read the returned stream, not when the call returns. This path serves blobs over 10 MiB, blobs the adapter's `cat-file` session cannot describe or read, and plumbing without object sessions. Code that obtained such a stream and read it only after closing the adapter (or the store that owns it) now gets `RESOURCE_CLOSED`; read the stream before closing. A stream you never read no longer starts a git process. Blobs of 10 MiB or less that the session reads are unchanged: they are read into memory before the call returns, and their streams still yield after close.
20
+
21
+ ### Manifest `formatVersion`
22
+
23
+ New manifests record `formatVersion: "8.0.0"`, the `MAJOR.MINOR.PATCH` core of the package version, not `8.0.0-rc.1`. The manifest schema accepts only three numeric components, so 7.x readers accept manifests this candidate writes.
24
+
5
25
  ## v6.5.12 To v7.0.0 (candidate)
6
26
 
7
27
  This is a breaking migration because the
package/build-info.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "18f87dd",
3
- "timestamp": "2026-11-02T16:45:35.044Z"
2
+ "sha": "7d14b11",
3
+ "timestamp": "2026-12-01T12:03:31.536Z"
4
4
  }
package/docs/API.md CHANGED
@@ -1035,6 +1035,41 @@ Encrypted restore behavior follows the existing streaming matrix; explicit
1035
1035
  Missing transferred objects fail with `HANDLE_TARGET_MISSING`. A handle created
1036
1036
  for a different manifest codec fails with `HANDLE_CODEC_MISMATCH`.
1037
1037
 
1038
+ ### Optional file materialization (`@git-stunts/git-cas/files`)
1039
+
1040
+ ```javascript
1041
+ import { materializeFile } from '@git-stunts/git-cas/files';
1042
+
1043
+ const result = await materializeFile({
1044
+ source: cas.assets.open({ handle, encryptionKey }),
1045
+ baseDirectory: '/existing/cache',
1046
+ outputPath: 'document.md',
1047
+ // Optional extra whole-plaintext verification, for example from a catalog:
1048
+ expectedSha256: catalog.sha256,
1049
+ signal: controller.signal,
1050
+ });
1051
+ // result: { bytesWritten }
1052
+ ```
1053
+
1054
+ This opt-in filesystem helper consumes an `AsyncIterable<Uint8Array>` with
1055
+ backpressure. It works with `assets.open()` and `restoreStream()` or another
1056
+ byte source. `assets.open()`, `restoreStream()`, `restore()` and the existing
1057
+ `restoreFile()` keep their contracts. No caller is switched to file output.
1058
+
1059
+ `source`, `baseDirectory` and `outputPath` are required. The base and output parent must exist. Absolute output paths must remain inside the base. The output path must name a file inside the base, not the base directory itself; that path is rejected before the source is read. Existing symlink prefixes are resolved using the same path boundary as `restoreFile()`. Parent directories are trusted local application directories; this check does not make concurrent hostile path replacement safe.
1060
+
1061
+ If `outputPath` itself is a symlink, the helper follows it, even when it dangles: the path it names must resolve inside the base, the file there is replaced or created, and the link is left in place. A link that names a path outside the base is rejected with `SECURITY_BOUNDARY_VIOLATION` before the source is read, and a symlink loop is rejected with the runtime's `ELOOP` error. Link text is resolved one component at a time, as the kernel resolves it; text that passes through a regular file, such as `file.txt/../x`, is rejected with `ENOTDIR` before the source is read. The helper never replaces the link itself.
1062
+
1063
+ The helper writes a private, uniquely named sibling temporary file, waits for the source and write pipeline to complete, optionally compares the plaintext SHA-256, checks cancellation, then renames into place. It does not collect the whole file. Encryption authentication and existing buffering limits belong to the source: whole-object `assets.open()` retains its existing buffer limits. Without `expectedSha256`, there is no additional whole-file digest check beyond what the source provides. Digest hex is case-insensitive. Each chunk is copied when it is pulled, so the published file, and any digest check, hold exactly the bytes the source yielded, even if the source reuses a buffer after yielding it.
1064
+
1065
+ The helper does not iterate the source until the options and path checks have passed, so a rejected call starts no read. `assets.open()` does no work, and starts no `git cat-file`, before its first pull. Once started, the helper pulls continuously, limited only by write backpressure.
1066
+
1067
+ The call resolves if and only if the file was published. Rename is the publication point. Source, authentication, write, digest and cancellation failures before rename reject and leave an existing destination untouched. Cancellation and write failures settle the call even while the source is waiting to produce its next chunk; the helper then asks the source to return, without waiting for it to resume. A source that was blocked in a pull may therefore finish that one pull after the call settles, and that late pull's bytes or error are discarded, so closing the CAS session once the call settles is safe. Temporary output is removed on success and failure. If removing the empty temporary directory fails after publication, the call still resolves and the directory can remain. If cleanup also fails after an earlier failure, the earlier failure is reported and the private temporary directory can remain. The final file has permissions no broader than `0600`. Concurrent successful publishers use last-rename-wins behavior.
1068
+
1069
+ This guarantees atomic visibility of one file on filesystems supporting atomic same-filesystem rename. It does not fsync the file or its directory. After a crash or power loss, the destination can therefore hold the previous contents, the new contents, or, on some filesystems, an empty or truncated file, and a private `.git-cas-materialize-*` temporary directory can remain beside it. An application that needs durability must fsync itself; it may delete leftover `.git-cas-materialize-*` directories after establishing that no active writer owns them. The helper does not create parents, transfer retention, change Git refs, enforce cache quotas, manage eviction, or transact a whole directory. Applications own those policies.
1070
+
1071
+ Errors: malformed options, digest syntax, a `signal` that is not an `AbortSignal` or a source chunk that is not a `Uint8Array` use `INVALID_OPTIONS`; an escaping path or an output path that resolves to the base directory uses `SECURITY_BOUNDARY_VIOLATION`; a full-file digest mismatch uses `INTEGRITY_ERROR`. Cancellation observed before the rename rejects with `signal.reason`. The helper checks the signal last just before the rename; once the rename has started, cancellation cannot stop publication, and the call resolves with the published file. Source errors are propagated unchanged, including falsy rejection values; filesystem errors retain their underlying runtime error forms.
1072
+
1038
1073
  ### `assets.adopt()`
1039
1074
 
1040
1075
  ```javascript
@@ -3649,9 +3684,9 @@ Different error codes include different metadata:
3649
3684
 
3650
3685
  ## Durable Reservations
3651
3686
 
3652
- This API is part of the merged v7.1.0 release candidate. It is absent from
3653
- published v7.0.0. [Issue #162](https://github.com/git-stunts/git-cas/issues/162)
3654
- tracks publication and fresh registry-consumer verification.
3687
+ This API is available in published v7.1.0 and is absent from v7.0.0.
3688
+ [Issue #162](https://github.com/git-stunts/git-cas/issues/162) retains publication
3689
+ and fresh registry-consumer verification.
3655
3690
 
3656
3691
  `cas.reservations.open({ namespace, capacity: { unit: 'record-slot', limit } })`
3657
3692
  installs or verifies an immutable namespace policy, including an empty ledger
@@ -1,8 +1,6 @@
1
1
  # git-cas v7.1.0: durable reservation admission
2
2
 
3
- This release candidate adds `cas.reservations.open()` for applications that must reserve permanent record capacity before an irreversible effect. The implementation merged in [PR #158](https://github.com/git-stunts/git-cas/pull/158). [Issue #162](https://github.com/git-stunts/git-cas/issues/162) records release gates, publication and fresh public-registry consumer verification. Candidate metadata alone does not establish publication.
4
-
5
- This candidate document claims no published 7.1.0 artifact.
3
+ This release adds `cas.reservations.open()` for applications that must reserve permanent record capacity before an irreversible effect. The implementation merged in [PR #158](https://github.com/git-stunts/git-cas/pull/158). [Issue #162](https://github.com/git-stunts/git-cas/issues/162) records the completed release gates, publication and fresh public-registry consumer verification. Signed tag `v7.1.0`, npm gitHead and the successful [release workflow](https://github.com/git-stunts/git-cas/actions/runs/41483019826) identify source `18f87ddb08857209d9e2e6ff30337515c0eaee4d`. The [GitHub Release](https://github.com/git-stunts/git-cas/releases/tag/v7.1.0) is published.
6
4
 
7
5
  ## Contract
8
6
 
@@ -22,6 +20,6 @@ Deno CI and release commands now install the frozen pnpm project graph and execu
22
20
 
23
21
  The [implementation witnesses](https://github.com/git-stunts/git-cas/blob/4782052214269c72acc95f63191e89897059bb56/docs/design/0063-durable-reservations/witness/README.md) separate state-machine tests, selected corruption, native multi-process races, injected write-boundary failures, process death, reopen and real Git GC in SHA-1 and SHA-256 stores. The [finite cost witness](https://github.com/git-stunts/git-cas/blob/4782052214269c72acc95f63191e89897059bb56/docs/design/0063-durable-reservations/witness/native-cost.md) measures stores of 1, 17 and 129 attempts using 4 KiB pages. It does not claim universal constant memory or performance parity across runtimes.
24
22
 
25
- PR #158's current-head hosted lint, unit and Node/Bun/Deno jobs passed. The maintainer explicitly authorized an admin merge after reviewer quota and file-count limits prevented independent approval. The [cycle retrospective](https://github.com/git-stunts/git-cas/blob/028c7fee56a8c4fa1c1ac1221fb7efb23289c8bf/docs/method/retro/0063-durable-reservations/durable-reservations.md) preserves that distinction. Full release-source validation, artifact identities and fresh registry-consumer evidence belong to #162.
23
+ PR #158's current-head hosted lint, unit and Node/Bun/Deno jobs passed. The maintainer explicitly authorized an admin merge after reviewer quota and file-count limits prevented independent approval. The [cycle retrospective](https://github.com/git-stunts/git-cas/blob/d50c77238e8b956fb70c2d51d2dcf9663c09c789/docs/method/retro/0063-durable-reservations/durable-reservations.md) preserves that distinction. All 14 release steps passed on merged main across separate runtime phases, with 8,265 passing test observations and 18 existing runtime-specific skips. The earlier combined-worker Deno failure remains recorded; fresh isolated Deno verification and the tagged release workflow passed. A fresh npm consumer verified lifecycle, refusal, original/final evidence, close/reopen and real Git GC in SHA-1 and SHA-256 stores. #162 retains both candidate and published artifact identities; they are separate builds.
26
24
 
27
- git-warp must install the published artifact before claiming adoption. WARP authorization, observation receipts, Coordinates and shared custody integration remain outside this storage release.
25
+ git-warp must install this published artifact before claiming adoption. WARP authorization, observation receipts, Coordinates and shared custody integration remain outside this storage release.
@@ -0,0 +1,21 @@
1
+ # git-cas v7.2.0: path-compressed reservation index
2
+
3
+ This release makes each reservation ledger update write about log16(records) index trees instead of 64. The change merged in [PR #168](https://github.com/git-stunts/git-cas/pull/168) for [#167](https://github.com/git-stunts/git-cas/issues/167). [Issue #169](https://github.com/git-stunts/git-cas/issues/169) tracks the release, and its [verification record](https://github.com/git-stunts/git-cas/issues/169#issuecomment-7308539667) holds the gate results and publication identity. Signed tag `v7.2.0`, npm gitHead and the successful [release workflow](https://github.com/git-stunts/git-cas/actions/runs/42249242979) identify source `3008b4a17603c44e0cf191e37f65db6f79409be3`. The [GitHub Release](https://github.com/git-stunts/git-cas/releases/tag/v7.2.0) is published.
4
+
5
+ ## Change
6
+
7
+ The reservation index was a 16-way trie with one tree per hex digit of a key's 64-digit route, so every record sat 64 trees deep and every update rewrote all 64. A record now sits at the shortest route prefix no other record shares. Inserting a key that meets another key's record pushes both down to the first digit where their routes differ. Sixty-four levels remain the worst case, so the documented listing and node bounds are unchanged.
8
+
9
+ Measured in a native repository after 400 prior records, one `reserve` wrote 68 objects under 7.1.0 and writes 7 under this release, in both SHA-1 and SHA-256 stores (`test/integration/reservation-index-cost.test.js`).
10
+
11
+ ## Compatibility
12
+
13
+ The public API is unchanged. An index written by 7.1.0 places every record at full depth, which is a valid uncompressed trie: it reads, updates and lists without migration, and new keys branch off early.
14
+
15
+ git-cas 7.1.0 refuses an index written by this release as `RESERVATION_CORRUPT` on read, list and recovery. The failure is loud rather than silent, but every process that reads or writes a clone's reservation ledger must upgrade together, and downgrading after 7.2.0 has written a ledger is not supported.
16
+
17
+ ## Evidence
18
+
19
+ All 14 release verifier steps pass at the tag on merged main, with the test suites in Docker: lint, 2,416 unit tests on Node and Bun (3 skips each) and 2,407 on Deno (12 skips), the three examples, public type compatibility, 353 integration tests on each runtime, the build stamp, npm pack and the JSR dry-run ([verification record](https://github.com/git-stunts/git-cas/issues/169#issuecomment-7308539667)). PR #168 also had an independent correctness review, whose probe of insertion-order independence, final-digit splits and paging across a later split passed.
20
+
21
+ git-warp installed the published artifact by its registry integrity and passed 333 custody, `Warp` and migration-golden tests ([git-stunts/git-warp#1083](https://github.com/git-stunts/git-warp/pull/1083)). A Docker probe there, which was not committed, measured 53 loose objects per retained `Warp` write across 100 writes, down from about 301 per write on 7.1.0 ([git-stunts/git-warp#1080](https://github.com/git-stunts/git-warp/issues/1080)).
@@ -0,0 +1,25 @@
1
+ # git-cas v8.0.0-rc.1: plumbing 4 release candidate
2
+
3
+ This release candidate moves git-cas onto `@git-stunts/plumbing` 4. It is a major release because applications that share a plumbing instance with git-cas must move to plumbing 4 with it, and because `GitPersistenceAdapter.readBlobStream()` now starts git lazily. Plumbing 4.0.0 is itself only a release candidate, so this version publishes to npm under the `next` dist-tag and leaves `latest` on 7.2.0. The plumbing upgrade merged in [PR #177](https://github.com/git-stunts/git-cas/pull/177). This document claims no published 8.0.0-rc.1 artifact. See [UPGRADING.md](../../UPGRADING.md#v720-to-v800-rc1) before adopting it.
4
+
5
+ ## Breaking changes
6
+
7
+ git-cas depends on `@git-stunts/plumbing` `^4.0.0-rc.1` instead of `^3.3.3`. The range accepts plumbing 4.0.0 final and later 4.x releases without a new git-cas release. Plumbing 4 changes behavior for applications that also call it directly: a deadline kills git's whole process group and is not retried, more than 10 MiB of unread stdout fails with `UnreadOutputLimitError`, `GitSha` accepts SHA-256 ids, and plumbing forwards `SIGINT`, `SIGTERM` and `SIGHUP` to running git commands.
8
+
9
+ An application that passes its own plumbing instance to `ContentAddressableStore`, `GitPersistenceAdapter`, `GitRefAdapter` or `GitRepositoryInspectionAdapter` must use plumbing 4, installed as the same copy git-cas uses. git-cas recognises plumbing's errors by class. An instance from a separate 3.x copy throws errors of other classes, so a missing object reports plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`, and git-cas's one-time recovery of a failed object session does not run.
10
+
11
+ `GitPersistenceAdapter.readBlobStream()` starts its one-shot `git cat-file blob` command when the caller first reads the returned stream, not when the stream is returned. That path serves a blob over 10 MiB, a blob the adapter's `cat-file` session cannot describe or read, and plumbing without object sessions. A stream that is never read starts no git process. A stream first read after the adapter closed fails with `RESOURCE_CLOSED`. A blob of 10 MiB or less that the session reads is still read into memory before the call returns, and its stream still yields after close.
12
+
13
+ ## Other changes
14
+
15
+ The optional `@git-stunts/git-cas/files` entrypoint adds `materializeFile()`, which streams an async byte source to a private sibling file and renames it on success. `restoreFile()` and `materializeFile()` resolve destination symlinks one component at a time, refuse a dangling link that points outside the base directory, and accept names such as `..cache`. The default JSON façade decodes UTF-8 natively, 2.6x to 6x faster on Node 22 for manifest-shaped metadata. [CHANGELOG.md](../../CHANGELOG.md) lists each change.
16
+
17
+ ## Stored data
18
+
19
+ Stored objects, refs and manifests keep their format. New manifests record `formatVersion: "8.0.0"`, the `MAJOR.MINOR.PATCH` core of the package version. The manifest schema has accepted only three numeric components since 6.0.0, so stamping `8.0.0-rc.1` would have made every new manifest fail validation, and 6.x and 7.x readers would refuse it. With the core version, 7.x readers accept manifests written by this candidate.
20
+
21
+ ## Publication
22
+
23
+ The release workflow now chooses the npm dist-tag from the version. A version that contains a hyphen publishes with `npm publish --access public --tag next`, and its GitHub Release is marked as a prerelease. A plain version publishes under `latest`. The publish step refuses to run if the dist-tag and the version disagree.
24
+
25
+ This candidate does not contain the planned v8.0.0 Cleave workspace split ([#133](https://github.com/git-stunts/git-cas/issues/133)). Merge approval, a signed tag, a successful release workflow and registry-consumer evidence remain required before any claim of publication.
package/files.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export interface MaterializeFileOptions {
2
+ /** Stream completion must include any required source authentication. */
3
+ source: AsyncIterable<Uint8Array>;
4
+ /** Existing directory boundary for the caller-selected destination. */
5
+ baseDirectory: string;
6
+ /** Relative to baseDirectory, or an absolute path inside it. Parent must exist. */
7
+ outputPath: string;
8
+ /** Optional whole-plaintext SHA-256, checked before the rename. */
9
+ expectedSha256?: string;
10
+ /** Cancellation before the rename starts rejects with `signal.reason`; after that, publication completes. */
11
+ signal?: AbortSignal;
12
+ }
13
+
14
+ /**
15
+ * Stream to a private sibling temporary file, then atomically replace the destination.
16
+ * Resolves if and only if the file was published. A destination symlink, even a dangling
17
+ * one, is followed: the in-base file it names is replaced or created and the link is kept.
18
+ * Does not fsync, create parents, manage retention or make a directory transaction.
19
+ */
20
+ export function materializeFile(options: MaterializeFileOptions): Promise<{ bytesWritten: number }>;
package/files.js ADDED
@@ -0,0 +1,2 @@
1
+ // Optional filesystem convenience layer; byte-stream APIs remain independent.
2
+ export { materializeFile } from './src/infrastructure/adapters/materializeFile.js';
package/index.js CHANGED
@@ -36,13 +36,14 @@ import createCryptoAdapter from './src/infrastructure/adapters/createCryptoAdapt
36
36
  import { createGitPlumbing } from './src/infrastructure/createGitPlumbing.js';
37
37
  import { storeFile, restoreFile } from './src/infrastructure/adapters/FileIOHelper.js';
38
38
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
39
+ import RuntimeJsonCodec from './src/infrastructure/adapters/RuntimeJsonCodec.js';
39
40
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
40
41
  import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
41
42
  import resolveChunker from './src/infrastructure/chunkers/resolveChunker.js';
42
43
  import { CasError, createCasError, ErrorCodes } from './src/domain/errors/index.js';
43
44
  import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
44
45
  import NodeCompressionAdapter from './src/infrastructure/adapters/NodeCompressionAdapter.js';
45
- import { PACKAGE_VERSION } from './src/package-version.js';
46
+ import { MANIFEST_FORMAT_VERSION, PACKAGE_VERSION } from './src/package-version.js';
46
47
  import parseApplicationHandle from './src/domain/value-objects/ApplicationHandle.js';
47
48
 
48
49
  /** @typedef {import('./src/domain/value-objects/Manifest.js').default} Manifest */
@@ -326,7 +327,7 @@ export default class ContentAddressableStore {
326
327
  this.service = new CasService({
327
328
  persistence,
328
329
  chunkSize,
329
- codec: cfg.codec || new JsonCodec(),
330
+ codec: cfg.codec || new RuntimeJsonCodec(),
330
331
  crypto,
331
332
  observability: cfg.observability || new SilentObserver(),
332
333
  merkleThreshold: cfg.merkleThreshold,
@@ -335,7 +336,7 @@ export default class ContentAddressableStore {
335
336
  maxRestoreBufferSize: cfg.maxRestoreBufferSize,
336
337
  maxBlobSize: cfg.maxBlobSize,
337
338
  compressionAdapter: cfg.compressionAdapter || new NodeCompressionAdapter(),
338
- formatVersion: PKG_VERSION,
339
+ formatVersion: MANIFEST_FORMAT_VERSION,
339
340
  });
340
341
 
341
342
  const ref = new GitRefAdapter({
@@ -745,7 +746,7 @@ export default class ContentAddressableStore {
745
746
  * @returns {ContentAddressableStore}
746
747
  */
747
748
  static createJson({ plumbing, ...options }) {
748
- return new ContentAddressableStore({ ...options, plumbing, codec: new JsonCodec() });
749
+ return new ContentAddressableStore({ ...options, plumbing, codec: new RuntimeJsonCodec() });
749
750
  }
750
751
 
751
752
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "7.1.0",
3
+ "version": "8.0.0-rc.1",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -9,12 +9,18 @@
9
9
  },
10
10
  "exports": {
11
11
  ".": "./index.js",
12
+ "./files": {
13
+ "types": "./files.d.ts",
14
+ "import": "./files.js"
15
+ },
12
16
  "./service": "./src/domain/services/CasService.js",
13
17
  "./schema": "./src/domain/schemas/ManifestSchema.js"
14
18
  },
15
19
  "files": [
16
20
  "index.js",
17
21
  "index.d.ts",
22
+ "files.js",
23
+ "files.d.ts",
18
24
  "build-info.json",
19
25
  "bin/",
20
26
  "src/",
@@ -59,7 +65,9 @@
59
65
  "docs/releases/v6.5.11.md",
60
66
  "docs/releases/v6.5.12.md",
61
67
  "docs/releases/v7.0.0.md",
62
- "docs/releases/v7.1.0.md"
68
+ "docs/releases/v7.1.0.md",
69
+ "docs/releases/v7.2.0.md",
70
+ "docs/releases/v8.0.0-rc.1.md"
63
71
  ],
64
72
  "engines": {
65
73
  "node": ">=22.0.0"
@@ -116,7 +124,7 @@
116
124
  "@flyingrobots/bijou-tui": "^7.2.0",
117
125
  "@flyingrobots/bijou-tui-app": "^7.2.0",
118
126
  "@git-stunts/alfred": "^0.10.0",
119
- "@git-stunts/plumbing": "^3.3.3",
127
+ "@git-stunts/plumbing": "^4.0.0-rc.1",
120
128
  "@git-stunts/vault": "^1.0.1",
121
129
  "cbor-x": "^1.6.0",
122
130
  "commander": "14.0.3",
@@ -489,9 +489,7 @@ async function buildLegacyDeps(plumbing) {
489
489
  const { default: NodeCompressionAdapter } = await import(
490
490
  '../src/infrastructure/adapters/NodeCompressionAdapter.js'
491
491
  );
492
- const { createRequire } = await import('node:module');
493
- const require = createRequire(import.meta.url);
494
- const { version } = require('../package.json');
492
+ const { MANIFEST_FORMAT_VERSION } = await import('../src/package-version.js');
495
493
 
496
494
  return {
497
495
  persistence: new GitPersistenceAdapter({ plumbing }),
@@ -500,7 +498,7 @@ async function buildLegacyDeps(plumbing) {
500
498
  chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
501
499
  compressionAdapter: new NodeCompressionAdapter(),
502
500
  chunkSize: 256 * 1024,
503
- formatVersion: version,
501
+ formatVersion: MANIFEST_FORMAT_VERSION,
504
502
  };
505
503
  }
506
504
 
@@ -4,7 +4,7 @@ import ReservationRecordCodecPort, { RESERVATION_RECORD_MAX_BYTES } from '../../
4
4
  import InvalidOptionsError from '../errors/InvalidOptionsError.js';
5
5
  import ReservationStorageError from '../errors/ReservationStorageError.js';
6
6
  import Oid from '../value-objects/Oid.js';
7
- import ReservationKey, { RESERVATION_ROUTE_DIGITS } from '../value-objects/ReservationKey.js';
7
+ import ReservationKey from '../value-objects/ReservationKey.js';
8
8
  import ReservationRecord from './ReservationRecord.js';
9
9
  import ReservationIndexNode from './ReservationIndexNode.js';
10
10
  import ReservationScan from './ReservationScan.js';
@@ -12,9 +12,13 @@ import ReservationScan from './ReservationScan.js';
12
12
  const NODE_BYTES = 2 * 1024;
13
13
 
14
14
  /**
15
- * Private immutable point index. It produces candidate trees, never publishes
16
- * refs or admits capacity. The ledger owner enforces lifecycle and binding.
17
- * Reads validate only the selected path, not every unvisited subtree.
15
+ * Private immutable point index: a path-compressed hexadecimal trie over key
16
+ * routes. Each record sits at the shortest route prefix it shares with no
17
+ * other record, so a point read or update touches about log16(records) trees.
18
+ * A 7.1.0 index, which placed every record at full depth, reads and updates
19
+ * unchanged. It produces candidate trees, never publishes refs or admits
20
+ * capacity; the ledger owner enforces lifecycle and binding. Reads validate
21
+ * only the selected path, not every unvisited subtree.
18
22
  */
19
23
  export default class ReservationIndex {
20
24
  #persistence;
@@ -35,8 +39,16 @@ export default class ReservationIndex {
35
39
  async get(root, key) {
36
40
  const identity = new ReservationKey(key);
37
41
  const route = await identity.route(this.#crypto);
38
- const { leaf } = await this.#walk(root, route);
39
- return leaf === null ? null : await this.#record(leaf, identity.value);
42
+ const { nodes, leaf } = await this.#walk(root, route);
43
+ if (leaf === null) {
44
+ return null;
45
+ }
46
+ const record = await this.#readRecord(leaf);
47
+ if (record.key === identity.value) {
48
+ return record;
49
+ }
50
+ await this.#resident(record, route.slice(0, nodes.length), route);
51
+ return null;
40
52
  }
41
53
 
42
54
  async empty() {
@@ -45,87 +57,147 @@ export default class ReservationIndex {
45
57
 
46
58
  async scan(root, request) {
47
59
  const scan = new ReservationScan(request);
48
- const complete = await this.#scanNode(checkedOid(root), '', scan);
60
+ const complete = await this.#scanNode({ oid: checkedOid(root), type: 'tree' }, '', scan);
49
61
  if (!complete && scan.after === (request.cursor?.after ?? null)) {
50
62
  throw new ReservationStorageError('Reservation traversal made no progress within its budget');
51
63
  }
52
64
  return scan.finish(complete);
53
65
  }
54
66
 
55
- async #scanNode(oid, prefix, scan) {
67
+ async #scanNode(entry, prefix, scan) {
56
68
  if (scan.skip(prefix)) {
57
69
  return true;
58
70
  }
59
71
  if (!scan.visit()) {
60
72
  return false;
61
73
  }
62
- if (prefix.length === RESERVATION_ROUTE_DIGITS) {
63
- const record = await this.#readRecord(oid);
64
- if (await new ReservationKey(record.key).route(this.#crypto) !== prefix) {
65
- throw new ReservationStorageError('Reservation record does not belong at its indexed route');
66
- }
67
- scan.accept(record, prefix);
74
+ if (entry.type === 'blob') {
75
+ await this.#scanRecord(entry.oid, prefix, scan);
68
76
  return true;
69
77
  }
70
- const node = await this.#node(oid, prefix.length);
78
+ const node = await this.#node(entry.oid, prefix.length);
71
79
  if (prefix.length > 0 && node.entries.length === 0) {
72
80
  throw new ReservationStorageError('Reservation index contains an empty internal branch');
73
81
  }
74
- for (const entry of node.entries) {
75
- if (!await this.#scanNode(entry.oid, prefix + entry.name, scan)) {
82
+ for (const child of node.entries) {
83
+ if (!await this.#scanNode(child, prefix + child.name, scan)) {
76
84
  return false;
77
85
  }
78
86
  }
79
87
  return true;
80
88
  }
81
89
 
90
+ async #scanRecord(oid, prefix, scan) {
91
+ const record = await this.#readRecord(oid);
92
+ const route = await this.#placed(record, prefix);
93
+ if (!scan.listed(route)) {
94
+ scan.accept(record, route);
95
+ }
96
+ }
97
+
82
98
  async put(root, record) {
83
99
  if (!(record instanceof ReservationRecord)) {
84
100
  throw new InvalidOptionsError('Reservation index writes require a validated record');
85
101
  }
86
102
  const route = await new ReservationKey(record.key).route(this.#crypto);
87
103
  const { nodes, leaf } = await this.#walk(root, route);
88
- if (leaf !== null) {
89
- await this.#record(leaf, record.key);
90
- }
104
+ const depth = Math.max(nodes.length - 1, 0);
105
+ const displaced = leaf === null ? null : await this.#displaced(leaf, { record, route, depth });
106
+ const oid = await this.#writeRecord(record, root);
107
+ let child = { oid, type: 'blob' };
108
+ if (displaced !== null) {
109
+ child = await this.#split({ route, depth, child, displaced });
110
+ }
111
+ for (let at = depth; at >= 0; at--) {
112
+ const node = nodes[at] ?? this.#emptyNode(at, oid.length);
113
+ child = { oid: await this.#writeNode(node.withChild(route[at], child)), type: 'tree' };
114
+ }
115
+ return child.oid;
116
+ }
117
+
118
+ /** Returns the other record a new key must share a subtree with, or null for an update. */
119
+ async #displaced(leaf, { record, route, depth }) {
120
+ const resident = await this.#readRecord(leaf);
121
+ if (resident.key === record.key) {
122
+ return null;
123
+ }
124
+ const residentRoute = await this.#resident(resident, route.slice(0, depth + 1), route);
125
+ return { route: residentRoute, child: { oid: leaf, type: 'blob' } };
126
+ }
127
+
128
+ /** Pushes two records down to the first digit at which their routes part. */
129
+ async #split({ route, depth, child, displaced }) {
130
+ let fork = depth + 1;
131
+ while (route[fork] === displaced.route[fork]) {
132
+ fork++;
133
+ }
134
+ const oidLength = child.oid.length;
135
+ const pair = this.#emptyNode(fork, oidLength)
136
+ .withChild(route[fork], child)
137
+ .withChild(displaced.route[fork], displaced.child);
138
+ let subtree = { oid: await this.#writeNode(pair), type: 'tree' };
139
+ for (let at = fork - 1; at > depth; at--) {
140
+ const chain = this.#emptyNode(at, oidLength).withChild(route[at], subtree);
141
+ subtree = { oid: await this.#writeNode(chain), type: 'tree' };
142
+ }
143
+ return subtree;
144
+ }
145
+
146
+ async #writeRecord(record, root) {
91
147
  const bytes = this.#codec.encode(record);
92
148
  if (!(bytes instanceof Uint8Array) || bytes.length > RESERVATION_RECORD_MAX_BYTES) {
93
149
  throw new ReservationStorageError('Encoded reservation record exceeds its byte limit');
94
150
  }
95
- let oid = checkedOid(await this.#persistence.writeBlob(bytes));
151
+ const oid = checkedOid(await this.#persistence.writeBlob(bytes));
96
152
  assertFormat(record, oid.length);
97
153
  if (root !== null && root.length !== oid.length) {
98
154
  throw new ReservationStorageError('Reservation update changed Git object format');
99
155
  }
100
- for (let depth = RESERVATION_ROUTE_DIGITS - 1; depth >= 0; depth--) {
101
- const node = nodes[depth] ?? new ReservationIndexNode({ entries: [], depth, oidLength: oid.length });
102
- const updated = node.withChild(route[depth], oid);
103
- const next = checkedOid(await this.#persistence.writeTree(updated.toTreeLines()));
104
- if (next.length !== oid.length) {
105
- throw new ReservationStorageError('Reservation tree writer changed Git object format');
106
- }
107
- oid = next;
156
+ return oid;
157
+ }
158
+
159
+ async #writeNode(node) {
160
+ const oid = checkedOid(await this.#persistence.writeTree(node.toTreeLines()));
161
+ if (oid.length !== node.oidLength) {
162
+ throw new ReservationStorageError('Reservation tree writer changed Git object format');
108
163
  }
109
164
  return oid;
110
165
  }
111
166
 
167
+ #emptyNode(depth, oidLength) {
168
+ return new ReservationIndexNode({ entries: [], depth, oidLength });
169
+ }
170
+
171
+ /** Walks the route until it reaches an empty slot or a record blob. */
112
172
  async #walk(root, route) {
113
- let oid = root === null ? null : checkedOid(root);
114
173
  const nodes = [];
115
- for (let depth = 0; depth < RESERVATION_ROUTE_DIGITS && oid !== null; depth++) {
116
- const node = await this.#node(oid, depth);
174
+ let entry = root === null ? null : { oid: checkedOid(root), type: 'tree' };
175
+ while (entry !== null && entry.type === 'tree') {
176
+ const node = await this.#node(entry.oid, nodes.length);
177
+ entry = node.child(route[nodes.length]);
117
178
  nodes.push(node);
118
- oid = node.child(route[depth]);
119
179
  }
120
- return { nodes, leaf: nodes.length === RESERVATION_ROUTE_DIGITS ? oid : null };
180
+ return { nodes, leaf: entry?.oid ?? null };
121
181
  }
122
182
 
123
- async #record(oid, key) {
124
- const record = await this.#readRecord(oid);
125
- if (record.key !== key) {
183
+ /**
184
+ * Proves that a record found on another key's route belongs there: its own
185
+ * route shares the walked prefix and differs from the sought route.
186
+ */
187
+ async #resident(record, prefix, route) {
188
+ const residentRoute = await this.#placed(record, prefix);
189
+ if (residentRoute === route) {
126
190
  throw new ReservationStorageError('Reservation route resolves to another key');
127
191
  }
128
- return record;
192
+ return residentRoute;
193
+ }
194
+
195
+ async #placed(record, prefix) {
196
+ const route = await new ReservationKey(record.key).route(this.#crypto);
197
+ if (!route.startsWith(prefix)) {
198
+ throw new ReservationStorageError('Reservation record does not belong at its indexed route');
199
+ }
200
+ return route;
129
201
  }
130
202
 
131
203
  async #node(oid, depth) {
@@ -4,8 +4,13 @@ import { RESERVATION_ROUTE_DIGITS } from '../value-objects/ReservationKey.js';
4
4
 
5
5
  const FANOUT = 16;
6
6
  const DIGIT = /^[0-9a-f]$/u;
7
+ const MODES = Object.freeze({ blob: '100644', tree: '040000' });
7
8
 
8
- /** A bounded, ordered routing node; final-depth children are record blobs. */
9
+ /**
10
+ * A bounded, ordered routing node. A record blob sits at the shortest route
11
+ * prefix that no other record shares, so a child above the final digit is a
12
+ * subtree or a record. A final-depth child is always a record.
13
+ */
9
14
  export default class ReservationIndexNode {
10
15
  #entries;
11
16
 
@@ -13,8 +18,7 @@ export default class ReservationIndexNode {
13
18
  assertShape(entries, depth, oidLength);
14
19
  this.depth = depth;
15
20
  this.oidLength = oidLength;
16
- const type = depth === RESERVATION_ROUTE_DIGITS - 1 ? 'blob' : 'tree';
17
- this.#entries = Object.freeze(entries.map((entry) => checkedEntry(entry, type, oidLength)));
21
+ this.#entries = Object.freeze(entries.map((entry) => checkedEntry(entry, depth, oidLength)));
18
22
  for (let i = 1; i < this.#entries.length; i++) {
19
23
  if (this.#entries[i - 1].name >= this.#entries[i].name) {
20
24
  throw new ReservationStorageError('Reservation node entries must be ordered and unique');
@@ -24,16 +28,15 @@ export default class ReservationIndexNode {
24
28
  }
25
29
 
26
30
  child(digit) {
27
- return this.#entries.find((entry) => entry.name === digit)?.oid ?? null;
31
+ return this.#entries.find((entry) => entry.name === digit) ?? null;
28
32
  }
29
33
 
30
34
  get entries() {
31
35
  return this.#entries;
32
36
  }
33
37
 
34
- withChild(digit, oid) {
35
- const type = this.depth === RESERVATION_ROUTE_DIGITS - 1 ? 'blob' : 'tree';
36
- const entry = { name: digit, oid, type, mode: type === 'blob' ? '100644' : '040000' };
38
+ withChild(digit, { oid, type }) {
39
+ const entry = { name: digit, oid, type, mode: MODES[type] };
37
40
  const entries = [...this.#entries.filter((item) => item.name !== digit), entry];
38
41
  entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
39
42
  return new ReservationIndexNode({ entries, depth: this.depth, oidLength: this.oidLength });
@@ -56,16 +59,16 @@ function assertShape(entries, depth, oidLength) {
56
59
  }
57
60
  }
58
61
 
59
- function checkedEntry(entry, type, oidLength) {
62
+ function checkedEntry(entry, depth, oidLength) {
60
63
  assertRoutingName(entry);
61
- const mode = type === 'blob' ? '100644' : '040000';
62
- if (entry.type !== type || entry.mode !== mode) {
64
+ const final = depth === RESERVATION_ROUTE_DIGITS - 1;
65
+ if ((entry.type !== 'blob' && (final || entry.type !== 'tree')) || entry.mode !== MODES[entry.type]) {
63
66
  throw new ReservationStorageError('Reservation index entry type or mode is invalid');
64
67
  }
65
68
  if (!Oid.isValid(entry.oid) || entry.oid.length !== oidLength || Oid.from(entry.oid).toString() !== entry.oid) {
66
69
  throw new ReservationStorageError('Reservation index entry OID is invalid');
67
70
  }
68
- return Object.freeze({ name: entry.name, mode, type, oid: entry.oid });
71
+ return Object.freeze({ name: entry.name, mode: entry.mode, type: entry.type, oid: entry.oid });
69
72
  }
70
73
 
71
74
  function assertRoutingName(entry) {
@@ -22,6 +22,11 @@ export default class ReservationScan {
22
22
  return this.#after !== null && prefix.padEnd(64, 'f') <= this.#after;
23
23
  }
24
24
 
25
+ /** A record above full depth can hold a route an earlier page already listed. */
26
+ listed(route) {
27
+ return this.#after !== null && route <= this.#after;
28
+ }
29
+
25
30
  visit() {
26
31
  if (this.#visited === this.#request.nodeBudget || this.#records.length === this.#request.limit) {
27
32
  return false;
@@ -6,14 +6,13 @@
6
6
  * @typedef {import('../../domain/value-objects/Manifest.js').EncryptionMeta} EncryptionMeta
7
7
  */
8
8
  import { createReadStream, createWriteStream } from 'node:fs';
9
- import { mkdtemp, realpath, rename, rm } from 'node:fs/promises';
9
+ import { mkdtemp, rename, rm } from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
  import { Readable, Transform } from 'node:stream';
12
12
  import { pipeline } from 'node:stream/promises';
13
13
  import CasError from '../../domain/errors/CasError.js';
14
14
  import { ErrorCodes } from '../../domain/errors/index.js';
15
-
16
- const FILE_NOT_FOUND_CODE = 'ENOENT';
15
+ import { resolveSafeRestorePath } from './RestorePath.js';
17
16
 
18
17
  /**
19
18
  * Reads a file from disk and stores it in Git as chunked blobs via
@@ -117,53 +116,6 @@ export async function restoreFile(
117
116
  return { bytesWritten };
118
117
  }
119
118
 
120
- /**
121
- * @param {{ baseDirectory: string, outputPath: string }} options
122
- * @returns {Promise<string>}
123
- */
124
- async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
125
- const resolvedBase = path.resolve(baseDirectory);
126
- const resolvedPath = path.resolve(resolvedBase, outputPath);
127
- const canonicalBase = await realpath(resolvedBase);
128
- const canonicalPath = await canonicalizeTargetPath(resolvedPath);
129
-
130
- if (!isInsideBaseDirectory(canonicalPath, canonicalBase)) {
131
- throw new CasError(
132
- `Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
133
- ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
134
- { outputPath, baseDirectory }
135
- );
136
- }
137
- return canonicalPath;
138
- }
139
-
140
- /**
141
- * Resolves symlinks in the existing path prefix while allowing the leaf path
142
- * not to exist yet.
143
- *
144
- * @param {string} targetPath
145
- * @returns {Promise<string>}
146
- */
147
- async function canonicalizeTargetPath(targetPath) {
148
- const missingParts = [];
149
- let current = targetPath;
150
- while (true) {
151
- try {
152
- return path.join(await realpath(current), ...missingParts.reverse());
153
- } catch (err) {
154
- if (!isNotFoundError(err)) {
155
- throw err;
156
- }
157
- const parent = path.dirname(current);
158
- if (parent === current) {
159
- throw err;
160
- }
161
- missingParts.push(path.basename(current));
162
- current = parent;
163
- }
164
- }
165
- }
166
-
167
119
  /**
168
120
  * Restores buffered modes through a temp-file path so whole-object auth can
169
121
  * stay intact without publishing partial output.
@@ -203,24 +155,6 @@ async function restoreBufferedFile(service, { manifest, outputPath, source, encr
203
155
  }
204
156
  }
205
157
 
206
- /**
207
- * @param {string} resolvedPath
208
- * @param {string} resolvedBase
209
- * @returns {boolean}
210
- */
211
- function isInsideBaseDirectory(resolvedPath, resolvedBase) {
212
- const relativePath = path.relative(resolvedBase, resolvedPath);
213
- return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
214
- }
215
-
216
- /**
217
- * @param {unknown} err
218
- * @returns {boolean}
219
- */
220
- function isNotFoundError(err) {
221
- return Boolean(err && typeof err === 'object' && err.code === FILE_NOT_FOUND_CODE);
222
- }
223
-
224
158
  function createByteCounter(onChunk) {
225
159
  return new Transform({
226
160
  transform(chunk, _encoding, cb) {
@@ -289,22 +289,22 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
289
289
  async readBlobStream(oid) {
290
290
  return await this.#runOperation(async () => {
291
291
  if (!this.#sessions.supports('catFile')) {
292
- return await this.#openBlobStream(oid);
292
+ return this.#openBlobStream(oid);
293
293
  }
294
294
  let info;
295
295
  try {
296
296
  info = await this.#readObjectInfo(oid);
297
297
  } catch {
298
- return await this.#openBlobStream(oid);
298
+ return this.#openBlobStream(oid);
299
299
  }
300
300
  if (info.type !== 'blob' || info.size > MAX_SESSION_STREAM_BLOB_BYTES) {
301
- return await this.#openBlobStream(oid);
301
+ return this.#openBlobStream(oid);
302
302
  }
303
303
  try {
304
304
  const content = await this.#readBlobFromSession(oid, MAX_SESSION_STREAM_BLOB_BYTES);
305
305
  return GitPersistenceAdapter.#singleBufferStream(content);
306
306
  } catch {
307
- return await this.#openBlobStream(oid);
307
+ return this.#openBlobStream(oid);
308
308
  }
309
309
  });
310
310
  }
@@ -327,8 +327,18 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
327
327
  return GitPersistenceAdapter.#toBuffer(object.content);
328
328
  }
329
329
 
330
- async #openBlobStream(oid) {
331
- return await this.#openBufferStream(['cat-file', 'blob', oid]);
330
+ /**
331
+ * Returns a blob stream whose `git cat-file blob` starts on the first read.
332
+ *
333
+ * Plumbing drains a command's stdout while nobody reads it and fails the
334
+ * stream once more than 10 MiB is unread, so starting the command before
335
+ * the caller reads would fail a large blob read by a caller that waits.
336
+ *
337
+ * @param {string} oid
338
+ * @returns {AsyncIterable<Buffer>}
339
+ */
340
+ async *#openBlobStream(oid) {
341
+ yield* await this.#runOperation(() => this.#openBufferStream(['cat-file', 'blob', oid]));
332
342
  }
333
343
 
334
344
  /**
@@ -0,0 +1,144 @@
1
+ import { lstat, readlink, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import CasError from '../../domain/errors/CasError.js';
4
+ import { ErrorCodes } from '../../domain/errors/index.js';
5
+
6
+ const FILE_NOT_FOUND_CODE = 'ENOENT';
7
+ /** Matches the usual kernel limit on symlinks followed while resolving one path. */
8
+ const MAX_SYMLINK_HOPS = 40;
9
+ /** Marks a path component that does not exist. */
10
+ const MISSING = Symbol('missing');
11
+
12
+ /**
13
+ * @param {{ baseDirectory: string, outputPath: string }} options
14
+ * @returns {Promise<string>}
15
+ */
16
+ export async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
17
+ const resolvedBase = path.resolve(baseDirectory);
18
+ const resolvedPath = path.resolve(resolvedBase, outputPath);
19
+ const canonicalBase = await realpath(resolvedBase);
20
+ const canonicalPath = await canonicalizeTargetPath(resolvedPath);
21
+
22
+ if (!isInsideBaseDirectory(canonicalPath, canonicalBase)) {
23
+ throw new CasError(
24
+ `Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
25
+ ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
26
+ { outputPath, baseDirectory }
27
+ );
28
+ }
29
+ return canonicalPath;
30
+ }
31
+
32
+ /**
33
+ * Resolves a target path one component at a time, as the kernel does: every
34
+ * symlink, including a dangling one, is followed before any later `..` is
35
+ * applied, and `..` steps to the physical parent. The leaf, and any missing
36
+ * components after it, need not exist yet. A dangling link resolves to the
37
+ * path it names, so that path is what the boundary check sees.
38
+ *
39
+ * @param {string} targetPath - Absolute, lexically normalised path.
40
+ * @returns {Promise<string>}
41
+ */
42
+ async function canonicalizeTargetPath(targetPath) {
43
+ const walk = { resolved: path.parse(targetPath).root, isDirectory: true, pending: splitPath(targetPath), hops: 0 };
44
+ while (walk.pending.length > 0) {
45
+ const part = walk.pending.shift();
46
+ // Any further component, including `.` and `..`, needs the path so far to be a directory.
47
+ if (!walk.isDirectory) { throw fsError('ENOTDIR', `Not a directory: "${walk.resolved}"`); }
48
+ if (part === '..') {
49
+ walk.resolved = path.dirname(walk.resolved);
50
+ } else if (part !== '.') {
51
+ const next = path.join(walk.resolved, part);
52
+ const entry = await inspect(next);
53
+ if (entry === MISSING) { return joinMissing(next, walk.pending); }
54
+ if (typeof entry === 'string') {
55
+ followLink(walk, entry, targetPath);
56
+ } else {
57
+ // `next` is not a symlink and its parent is canonical, so realpath() only
58
+ // returns the filesystem's own spelling, which case-insensitive volumes need.
59
+ walk.resolved = await realpath(next);
60
+ walk.isDirectory = entry.isDirectory();
61
+ }
62
+ }
63
+ }
64
+ return walk.resolved;
65
+ }
66
+
67
+ /**
68
+ * @param {string} candidate
69
+ * @returns {Promise<string | import('node:fs').Stats | typeof MISSING>} Link text for a
70
+ * symlink, the stats of anything else, or MISSING.
71
+ */
72
+ async function inspect(candidate) {
73
+ let stats;
74
+ try {
75
+ stats = await lstat(candidate);
76
+ } catch (err) {
77
+ if (isNotFoundError(err)) { return MISSING; }
78
+ throw err;
79
+ }
80
+ return stats.isSymbolicLink() ? readlink(candidate) : stats;
81
+ }
82
+
83
+ /** Queues the link's own components ahead of the rest, from the root if it is absolute. */
84
+ function followLink(walk, linkText, targetPath) {
85
+ walk.hops += 1;
86
+ if (walk.hops > MAX_SYMLINK_HOPS) {
87
+ throw fsError('ELOOP', `Too many symbolic links resolving "${targetPath}"`);
88
+ }
89
+ if (path.isAbsolute(linkText)) { walk.resolved = path.parse(path.resolve(linkText)).root; }
90
+ // A trailing separator requires a directory, as `/.` does.
91
+ const endsWithSeparator = linkText.endsWith('/') || (path.sep === '\\' && linkText.endsWith('\\'));
92
+ const trailing = endsWithSeparator && splitPath(linkText).length > 0 ? ['.'] : [];
93
+ walk.pending.unshift(...splitPath(linkText), ...trailing);
94
+ }
95
+
96
+ /**
97
+ * Past a missing component the kernel cannot look further, so the remaining
98
+ * names are appended as they are. A `.` or `..` there would need a missing directory.
99
+ */
100
+ function joinMissing(missing, rest) {
101
+ if (rest.includes('..') || rest.includes('.')) {
102
+ throw fsError(FILE_NOT_FOUND_CODE, `No such directory: "${missing}"`);
103
+ }
104
+ return path.join(missing, ...rest);
105
+ }
106
+
107
+ /**
108
+ * Splits without normalising: link text such as `dir/../x` must keep its `..`
109
+ * until `dir` has been followed.
110
+ *
111
+ * @param {string} value
112
+ */
113
+ function splitPath(value) {
114
+ const separators = path.sep === '\\' ? /[\\/]/u : /\//u;
115
+ return value.slice(path.parse(value).root.length).split(separators).filter((part) => part.length > 0);
116
+ }
117
+
118
+ /**
119
+ * @param {string} resolvedPath
120
+ * @param {string} resolvedBase
121
+ * @returns {boolean}
122
+ */
123
+ function isInsideBaseDirectory(resolvedPath, resolvedBase) {
124
+ const relativePath = path.relative(resolvedBase, resolvedPath);
125
+ const escapes = relativePath === '..' || relativePath.startsWith(`..${path.sep}`);
126
+ return !escapes && !path.isAbsolute(relativePath);
127
+ }
128
+
129
+ /**
130
+ * @param {unknown} err
131
+ * @returns {boolean}
132
+ */
133
+ function isNotFoundError(err) {
134
+ return Boolean(err && typeof err === 'object' && err.code === FILE_NOT_FOUND_CODE);
135
+ }
136
+
137
+
138
+ /**
139
+ * @param {string} code - The errno-style code the kernel would report.
140
+ * @param {string} message
141
+ */
142
+ function fsError(code, message) {
143
+ return Object.assign(new Error(message), { code });
144
+ }
@@ -0,0 +1,30 @@
1
+ import JsonCodec from '../codecs/JsonCodec.js';
2
+
3
+ const decoder = createFatalDecoder();
4
+
5
+ /** Builds without ICU reject `fatal`; the portable decoder then handles all input. */
6
+ function createFatalDecoder() {
7
+ if (typeof globalThis.TextDecoder !== 'function') { return null; }
8
+ try {
9
+ return new globalThis.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
10
+ } catch {
11
+ return null;
12
+ }
13
+ }
14
+
15
+ /** Runtime text conversion over the unchanged portable JSON codec contract. */
16
+ export default class RuntimeJsonCodec extends JsonCodec {
17
+ decode(buffer) {
18
+ if (decoder && buffer instanceof Uint8Array) {
19
+ let text;
20
+ try {
21
+ text = decoder.decode(buffer);
22
+ } catch {
23
+ // Preserve legacy consumption of malformed UTF-8.
24
+ return super.decode(buffer);
25
+ }
26
+ return JSON.parse(text);
27
+ }
28
+ return super.decode(buffer);
29
+ }
30
+ }
@@ -0,0 +1,172 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { mkdtemp, realpath, rename, rm } from 'node:fs/promises';
3
+ import { createHash } from 'node:crypto';
4
+ import path from 'node:path';
5
+ import { types } from 'node:util';
6
+ import { Readable, Transform } from 'node:stream';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { setImmediate as nextMacrotask } from 'node:timers/promises';
9
+ import CasError from '../../domain/errors/CasError.js';
10
+ import { ErrorCodes } from '../../domain/errors/index.js';
11
+ import { resolveSafeRestorePath } from './RestorePath.js';
12
+
13
+ /** @param {import('../../../files.js').MaterializeFileOptions} options */
14
+ export async function materializeFile(options = {}) {
15
+ const { source, baseDirectory, outputPath, expectedSha256, signal } = validateOptions(options);
16
+ signal?.throwIfAborted();
17
+ const destination = await resolveSafeRestorePath({ baseDirectory, outputPath });
18
+ if (destination === await realpath(path.resolve(baseDirectory))) {
19
+ throw new CasError(`Materialization path "${outputPath}" names base directory "${baseDirectory}"`,
20
+ ErrorCodes.SECURITY_BOUNDARY_VIOLATION, { outputPath, baseDirectory });
21
+ }
22
+ const temporary = await mkdtemp(path.join(path.dirname(destination), '.git-cas-materialize-'));
23
+ const staged = path.join(temporary, 'content');
24
+ const hash = expectedSha256 ? createHash('sha256') : null;
25
+ let bytesWritten = 0;
26
+ const counter = new Transform({
27
+ transform(chunk, _encoding, done) {
28
+ bytesWritten += chunk.length;
29
+ hash?.update(chunk);
30
+ done(null, chunk);
31
+ },
32
+ });
33
+ try {
34
+ await writeStaged({ source, staged, counter, signal });
35
+ if (hash && hash.digest('hex') !== expectedSha256.toLowerCase()) {
36
+ throw new CasError('Materialized file SHA-256 does not match expectedSha256', ErrorCodes.INTEGRITY_ERROR);
37
+ }
38
+ signal?.throwIfAborted();
39
+ await rename(staged, destination);
40
+ } catch (error) {
41
+ // The original failure is the diagnosis; a leftover private directory is documented.
42
+ await rm(temporary, { recursive: true, force: true }).catch(() => {});
43
+ throw error;
44
+ }
45
+ // Rename is the publication point: resolve if and only if the file was published.
46
+ // An empty private directory left by a failed cleanup is documented reclaimable residue.
47
+ await rm(temporary, { recursive: true, force: true }).catch(() => {});
48
+ return { bytesWritten };
49
+ }
50
+
51
+ /**
52
+ * Pulls stop when the caller aborts or the file fails, so neither has to wait
53
+ * for a blocked producer before the pipeline can settle.
54
+ */
55
+ async function writeStaged({ source, staged, counter, signal }) {
56
+ const pulls = new globalThis.AbortController();
57
+ const forward = () => pulls.abort(signal.reason);
58
+ signal?.addEventListener('abort', forward, { once: true });
59
+ const file = createWriteStream(staged, { flags: 'wx', mode: 0o600 });
60
+ file.once('error', (error) => pulls.abort(error));
61
+ let sourceFailure = null;
62
+ const chunks = byteChunks(source, pulls.signal, (error) => { sourceFailure = { error }; });
63
+ try {
64
+ await pipeline(Readable.from(chunks, { objectMode: false }), counter, file, { signal });
65
+ } catch (error) {
66
+ // Cancellation always rejects with the caller's reason, not the pipeline's own AbortError.
67
+ if (signal?.aborted) { throw signal.reason; }
68
+ // Streams report a falsy error as a premature close; keep the value the source threw.
69
+ throw sourceFailure ? sourceFailure.error : error;
70
+ } finally {
71
+ signal?.removeEventListener('abort', forward);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Reads each option once and returns that snapshot, so a getter cannot pass validation
77
+ * and then change. The source is bound to the iterator method read here, as for await does.
78
+ */
79
+ function validateOptions(options) {
80
+ const { source, baseDirectory, outputPath, expectedSha256, signal } = options ?? {};
81
+ const iteratorMethod = source?.[Symbol.asyncIterator];
82
+ if (!options || !isPath(baseDirectory) || !isPath(outputPath) || typeof iteratorMethod !== 'function') {
83
+ throw new CasError('source, baseDirectory and outputPath are required', ErrorCodes.INVALID_OPTIONS);
84
+ }
85
+ validateSignal(signal);
86
+ validateDigest(expectedSha256);
87
+ return {
88
+ source: { [Symbol.asyncIterator]: () => Reflect.apply(iteratorMethod, source, []) },
89
+ baseDirectory, outputPath, expectedSha256, signal,
90
+ };
91
+ }
92
+
93
+ const readAborted = Object.getOwnPropertyDescriptor(globalThis.AbortSignal.prototype, 'aborted').get;
94
+
95
+ /** A brand check: the platform getter rejects objects that only inherit from AbortSignal. */
96
+ function validateSignal(signal) {
97
+ if (signal === undefined) { return; }
98
+ try {
99
+ readAborted.call(signal);
100
+ } catch {
101
+ throw new CasError('signal must be an AbortSignal', ErrorCodes.INVALID_OPTIONS);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Rejects anything but byte chunks, so a misbehaving source cannot publish text.
107
+ * Each pull races the abort signal: cancellation settles even while the producer
108
+ * is blocked. The source is then asked to return without waiting for it.
109
+ */
110
+ async function* byteChunks(source, signal, onSourceFailure) {
111
+ let iterator;
112
+ let finished = false;
113
+ try {
114
+ iterator = source[Symbol.asyncIterator]();
115
+ // Captured once, as for await does, so the iterator may replace its own next.
116
+ const next = iterator.next;
117
+ const pull = () => Reflect.apply(next, iterator, []);
118
+ while (true) {
119
+ const step = await nextChunk(pull, signal);
120
+ if (step.done) { finished = true; return; }
121
+ // Read once, so a getter cannot pass validation and then yield something else.
122
+ const chunk = step.value;
123
+ // Realm-independent: a Uint8Array from another context is still bytes.
124
+ if (!types.isUint8Array(chunk)) {
125
+ throw new CasError('source must yield Uint8Array chunks', ErrorCodes.INVALID_OPTIONS);
126
+ }
127
+ // Copied before the next pull: streams queue references, and a producer may reuse its buffer.
128
+ // The typed-array constructor reads the bytes directly; Buffer.from(chunk) would honour valueOf().
129
+ const bytes = Buffer.from(new Uint8Array(chunk).buffer);
130
+ // Empty chunks never fill a stream buffer, so yield to the event loop for cancellation and I/O.
131
+ if (bytes.length === 0) { await nextMacrotask(); }
132
+ yield bytes;
133
+ }
134
+ } catch (error) {
135
+ if (!signal.aborted) { onSourceFailure(error); }
136
+ throw error;
137
+ } finally {
138
+ // Deferred, so a return() that throws synchronously cannot replace the pull's error.
139
+ if (!finished) { Promise.resolve().then(() => iterator?.return?.()).catch(() => {}); }
140
+ }
141
+ }
142
+
143
+ /** One abort race per pull, so completed pulls leave no reactions on a long-lived promise. */
144
+ async function nextChunk(pull, signal) {
145
+ const abort = abortRejection(signal);
146
+ try {
147
+ return await (abort ? Promise.race([pull(), abort.promise]) : pull());
148
+ } finally {
149
+ abort?.dispose();
150
+ }
151
+ }
152
+
153
+ /** A rejection that follows `signal`, marked handled so a late abort is not reported. */
154
+ function abortRejection(signal) {
155
+ if (!signal) { return null; }
156
+ let onAbort;
157
+ const promise = new Promise((_resolve, reject) => {
158
+ onAbort = () => reject(signal.reason);
159
+ if (signal.aborted) { onAbort(); } else { signal.addEventListener('abort', onAbort, { once: true }); }
160
+ });
161
+ promise.catch(() => {});
162
+ return { promise, dispose: () => signal.removeEventListener('abort', onAbort) };
163
+ }
164
+
165
+ function isPath(value) { return typeof value === 'string' && value.length > 0; }
166
+
167
+ function validateDigest(expectedSha256) {
168
+ if (expectedSha256 !== undefined
169
+ && (typeof expectedSha256 !== 'string' || !/^[a-f0-9]{64}$/iu.test(expectedSha256))) {
170
+ throw new CasError('expectedSha256 must be a 64-digit hexadecimal digest', ErrorCodes.INVALID_OPTIONS);
171
+ }
172
+ }
@@ -1 +1,16 @@
1
- export const PACKAGE_VERSION = '7.1.0';
1
+ export const PACKAGE_VERSION = '8.0.0-rc.1';
2
+
3
+ /**
4
+ * Returns the `MAJOR.MINOR.PATCH` core of a package version. Manifests record
5
+ * this as `formatVersion`, whose schema (and every earlier reader) accepts
6
+ * only three numeric components, so a prerelease such as `8.0.0-rc.1` stamps
7
+ * `8.0.0`.
8
+ *
9
+ * @param {string} version
10
+ * @returns {string}
11
+ */
12
+ export function manifestFormatVersion(version) {
13
+ return version.replace(/[-+].*$/u, '');
14
+ }
15
+
16
+ export const MANIFEST_FORMAT_VERSION = manifestFormatVersion(PACKAGE_VERSION);