@git-stunts/git-cas 6.0.1 → 6.2.0

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 (70) hide show
  1. package/ARCHITECTURE.md +120 -6
  2. package/CHANGELOG.md +98 -1
  3. package/GUIDE.md +114 -13
  4. package/README.md +60 -4
  5. package/UPGRADING.md +71 -1
  6. package/build-info.json +2 -2
  7. package/docs/API.md +934 -7
  8. package/docs/WALKTHROUGH.md +46 -0
  9. package/docs/releases/v6.1.0.md +75 -0
  10. package/docs/releases/v6.2.0.md +131 -0
  11. package/index.d.ts +974 -1
  12. package/index.js +354 -1
  13. package/package.json +8 -6
  14. package/src/domain/errors/Codes.js +48 -0
  15. package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
  16. package/src/domain/helpers/handleTarget.js +48 -0
  17. package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
  18. package/src/domain/services/AssetService.js +213 -0
  19. package/src/domain/services/BundleDescriptorCodec.js +286 -0
  20. package/src/domain/services/BundleFanoutBuilder.js +247 -0
  21. package/src/domain/services/BundleService.js +848 -0
  22. package/src/domain/services/CacheCandidateHeap.js +71 -0
  23. package/src/domain/services/CacheIndex.js +362 -0
  24. package/src/domain/services/CacheMetadataCodec.js +164 -0
  25. package/src/domain/services/CachePolicyEnforcer.js +144 -0
  26. package/src/domain/services/CacheSet.js +703 -0
  27. package/src/domain/services/CacheSetRegistry.js +88 -0
  28. package/src/domain/services/CasService.d.ts +3 -1
  29. package/src/domain/services/ExpiringSet.js +496 -0
  30. package/src/domain/services/ExpiringSetIndex.js +254 -0
  31. package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
  32. package/src/domain/services/ExpiringSetRegistry.js +101 -0
  33. package/src/domain/services/PageService.js +175 -0
  34. package/src/domain/services/PublicationService.js +315 -0
  35. package/src/domain/services/RepositoryDoctor.js +649 -0
  36. package/src/domain/services/RetentionService.js +120 -0
  37. package/src/domain/services/RootSet.js +281 -0
  38. package/src/domain/services/RootSetMetadataCodec.js +259 -0
  39. package/src/domain/services/RootSetPersistence.js +335 -0
  40. package/src/domain/services/RootSetRegistry.js +44 -0
  41. package/src/domain/services/RootSetRetryPolicy.js +87 -0
  42. package/src/domain/services/RootSetTreeCodec.js +95 -0
  43. package/src/domain/services/StagingEvidence.js +39 -0
  44. package/src/domain/value-objects/ApplicationHandle.js +40 -0
  45. package/src/domain/value-objects/AssetHandle.js +163 -0
  46. package/src/domain/value-objects/BundleHandle.js +32 -0
  47. package/src/domain/value-objects/BundleLimits.js +80 -0
  48. package/src/domain/value-objects/BundlePath.js +78 -0
  49. package/src/domain/value-objects/CacheHit.js +93 -0
  50. package/src/domain/value-objects/CacheKey.js +32 -0
  51. package/src/domain/value-objects/CachePolicy.js +59 -0
  52. package/src/domain/value-objects/CacheSetRef.js +40 -0
  53. package/src/domain/value-objects/CollectionNamespace.js +54 -0
  54. package/src/domain/value-objects/ExpiringMarker.js +81 -0
  55. package/src/domain/value-objects/ExpiringSetKey.js +28 -0
  56. package/src/domain/value-objects/ExpiringSetRef.js +42 -0
  57. package/src/domain/value-objects/OpaqueHandle.js +171 -0
  58. package/src/domain/value-objects/PageHandle.js +34 -0
  59. package/src/domain/value-objects/RetentionWitness.js +101 -0
  60. package/src/domain/value-objects/RootSetRef.js +88 -0
  61. package/src/domain/value-objects/StagedAsset.js +63 -0
  62. package/src/domain/value-objects/StagedBundle.js +66 -0
  63. package/src/domain/value-objects/StagedPage.js +47 -0
  64. package/src/infrastructure/adapters/GitPersistenceAdapter.js +57 -0
  65. package/src/infrastructure/adapters/GitRefAdapter.js +26 -5
  66. package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +164 -0
  67. package/src/package-version.js +1 -1
  68. package/src/ports/GitPersistencePort.js +20 -1
  69. package/src/ports/GitRefPort.js +10 -0
  70. package/src/ports/RepositoryInspectionPort.js +33 -0
@@ -0,0 +1,335 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { errorDetailsText, isGitMissingRefError } from '../helpers/gitRefErrors.js';
4
+ import RootSetRef from '../value-objects/RootSetRef.js';
5
+ import RootSetMetadataCodec, { ROOT_SET_METADATA_ENTRY } from './RootSetMetadataCodec.js';
6
+ import RootSetTreeCodec from './RootSetTreeCodec.js';
7
+
8
+ const UPDATE_REF_CONFLICT_MARKERS = Object.freeze({
9
+ butExpected: 'but expected',
10
+ cannotLockRef: 'cannot lock ref',
11
+ referenceAlreadyExists: 'reference already exists',
12
+ });
13
+
14
+ /**
15
+ * Stateless persistence boundary for one root-set ref and snapshot format.
16
+ */
17
+ export default class RootSetPersistence {
18
+ /**
19
+ * @param {object} options
20
+ * @param {string} options.rootSetRef
21
+ * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
22
+ * @param {import('../../ports/GitRefPort.js').default} options.ref
23
+ * @param {RootSetMetadataCodec} [options.metadataCodec]
24
+ * @param {RootSetTreeCodec} [options.treeCodec]
25
+ */
26
+ constructor({
27
+ rootSetRef,
28
+ persistence,
29
+ ref,
30
+ refType = RootSetRef,
31
+ metadataCodec = new RootSetMetadataCodec({ refType }),
32
+ treeCodec = new RootSetTreeCodec(),
33
+ }) {
34
+ this.rootSetRef = refType.from(rootSetRef).toString();
35
+ RootSetPersistence.#validateDependencies(persistence, ref);
36
+ this.persistence = persistence;
37
+ this.ref = ref;
38
+ this.metadataCodec = metadataCodec;
39
+ this.treeCodec = treeCodec;
40
+ Object.freeze(this);
41
+ }
42
+
43
+ /**
44
+ * @returns {Promise<{ commitOid: string, treeOid: string }|null>}
45
+ */
46
+ async resolveHead() {
47
+ const commitOid = await this.resolveRefOnly();
48
+ if (commitOid === null) {
49
+ return null;
50
+ }
51
+ try {
52
+ const parentOids = await this.ref.resolveParents(commitOid);
53
+ if (parentOids.length !== 0) {
54
+ throw new CasError(
55
+ 'Root-set head must be a parentless current-generation commit',
56
+ ErrorCodes.ROOT_SET_HEAD_INVALID,
57
+ { ref: this.rootSetRef, commitOid, parentOids },
58
+ );
59
+ }
60
+ return { commitOid, treeOid: await this.ref.resolveTree(commitOid) };
61
+ } catch (err) {
62
+ if (err?.code === ErrorCodes.ROOT_SET_HEAD_INVALID) {
63
+ throw err;
64
+ }
65
+ throw this.#headError('Root-set head commit does not resolve to a tree', err, { commitOid });
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Resolves the ref without requiring its commit or tree to be healthy.
71
+ * Used by authoritative repair.
72
+ *
73
+ * @returns {Promise<string|null>}
74
+ */
75
+ async resolveRefOnly() {
76
+ try {
77
+ return await this.ref.resolveRef(this.rootSetRef);
78
+ } catch (err) {
79
+ if (this.#isMissingRefError(err)) {
80
+ return null;
81
+ }
82
+ throw this.#headError('Root-set ref could not be resolved', err);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * @returns {Promise<{ ref: string, headOid: string|null, treeOid: string|null, entries: Array<object> }>}
88
+ */
89
+ async read() {
90
+ const head = await this.resolveHead();
91
+ if (!head) {
92
+ return { ref: this.rootSetRef, headOid: null, treeOid: null, entries: [] };
93
+ }
94
+
95
+ let rawEntries;
96
+ try {
97
+ rawEntries = await this.persistence.readTree(head.treeOid);
98
+ } catch (err) {
99
+ throw new CasError(
100
+ 'Root-set tree could not be read',
101
+ ErrorCodes.ROOT_SET_TREE_INVALID,
102
+ { ref: this.rootSetRef, ...head, originalError: err },
103
+ );
104
+ }
105
+ const metadataEntry = rawEntries.find((entry) => entry.name === ROOT_SET_METADATA_ENTRY);
106
+ if (!metadataEntry) {
107
+ throw new CasError(
108
+ 'Root-set tree is missing .rootset.json',
109
+ ErrorCodes.ROOT_SET_TREE_INVALID,
110
+ { ref: this.rootSetRef, ...head },
111
+ );
112
+ }
113
+
114
+ const metadata = this.metadataCodec.decode(
115
+ await this.persistence.readBlob(metadataEntry.oid),
116
+ { expectedRef: this.rootSetRef },
117
+ );
118
+ this.treeCodec.validate(rawEntries, metadata);
119
+ return {
120
+ ref: this.rootSetRef,
121
+ headOid: head.commitOid,
122
+ treeOid: head.treeOid,
123
+ entries: metadata.entries.map(RootSetPersistence.#publicEntry),
124
+ };
125
+ }
126
+
127
+ /**
128
+ * @param {object} options
129
+ * @param {Iterable<object>} options.entries
130
+ * @param {string|null} options.expectedHeadOid
131
+ * @param {string} [options.message]
132
+ * @returns {Promise<{ commitOid: string, treeOid: string, entries: Array<object> }>}
133
+ */
134
+ async write({ entries, expectedHeadOid, message = 'root-set: replace current roots' }) {
135
+ const metadata = this.metadataCodec.create({ ref: this.rootSetRef, entries });
136
+ await this.#assertTargets(metadata.entries.map(RootSetPersistence.#publicEntry));
137
+ const metadataBlobOid = await this.persistence.writeBlob(
138
+ this.metadataCodec.encode({ ref: this.rootSetRef, entries }),
139
+ );
140
+ const treeOid = await this.persistence.writeTree(
141
+ this.treeCodec.toTreeLines(metadata, metadataBlobOid),
142
+ );
143
+ const commitOid = await this.ref.createCommit({
144
+ treeOid,
145
+ parentOid: null,
146
+ message,
147
+ });
148
+ await this.#updateRef({ commitOid, expectedHeadOid });
149
+ return {
150
+ commitOid,
151
+ treeOid,
152
+ entries: metadata.entries.map(RootSetPersistence.#publicEntry),
153
+ };
154
+ }
155
+
156
+ /**
157
+ * @param {Iterable<object>} entries
158
+ * @returns {Promise<{ healthy: boolean, targets: Array<object>, issues: Array<object> }>}
159
+ */
160
+ async inspectTargets(entries) {
161
+ const targets = [];
162
+ const issues = [];
163
+ for (const entry of entries) {
164
+ try {
165
+ const actualType = await this.persistence.readObjectType(entry.oid);
166
+ const target = {
167
+ ...entry,
168
+ exists: true,
169
+ actualType,
170
+ reachability: 'anchored',
171
+ };
172
+ targets.push(target);
173
+ if (actualType !== entry.type) {
174
+ issues.push({
175
+ code: ErrorCodes.ROOT_SET_TARGET_TYPE_MISMATCH,
176
+ name: entry.name,
177
+ oid: entry.oid,
178
+ expectedType: entry.type,
179
+ actualType,
180
+ });
181
+ }
182
+ } catch (err) {
183
+ const missing = err?.code === ErrorCodes.GIT_OBJECT_NOT_FOUND;
184
+ const issueCode = missing
185
+ ? ErrorCodes.ROOT_SET_TARGET_MISSING
186
+ : ErrorCodes.ROOT_SET_TARGET_UNREADABLE;
187
+ targets.push({
188
+ ...entry,
189
+ exists: missing ? false : null,
190
+ actualType: null,
191
+ reachability: missing ? 'missing' : 'unknown',
192
+ });
193
+ issues.push({
194
+ code: issueCode,
195
+ name: entry.name,
196
+ oid: entry.oid,
197
+ expectedType: entry.type,
198
+ originalError: err,
199
+ });
200
+ }
201
+ }
202
+ return { healthy: issues.length === 0, targets, issues };
203
+ }
204
+
205
+ /**
206
+ * @param {{ commitOid: string, expectedHeadOid: string|null }} options
207
+ */
208
+ async #updateRef({ commitOid, expectedHeadOid }) {
209
+ try {
210
+ await this.ref.updateRef({
211
+ ref: this.rootSetRef,
212
+ newOid: commitOid,
213
+ expectedOldOid: expectedHeadOid,
214
+ });
215
+ } catch (err) {
216
+ const meta = await this.#updateFailureMeta(err, commitOid, expectedHeadOid);
217
+ if (this.#isConflict(err)) {
218
+ throw new CasError(
219
+ 'Concurrent root-set update detected',
220
+ ErrorCodes.ROOT_SET_CONFLICT,
221
+ meta,
222
+ );
223
+ }
224
+ throw new CasError('Root-set ref update failed', ErrorCodes.ROOT_SET_REF_UPDATE_FAILED, meta);
225
+ }
226
+ }
227
+
228
+ async #updateFailureMeta(originalError, newCommit, expectedHeadOid) {
229
+ const errorMeta = originalError?.meta && typeof originalError.meta === 'object'
230
+ ? originalError.meta
231
+ : {};
232
+ let actualHeadOid = Object.hasOwn(errorMeta, 'actualOldOid')
233
+ ? errorMeta.actualOldOid
234
+ : undefined;
235
+ if (actualHeadOid === undefined) {
236
+ try {
237
+ actualHeadOid = await this.ref.resolveRef(this.rootSetRef);
238
+ } catch {
239
+ actualHeadOid = null;
240
+ }
241
+ }
242
+ return {
243
+ ref: this.rootSetRef,
244
+ expectedHeadOid,
245
+ actualHeadOid,
246
+ newCommit,
247
+ originalError,
248
+ };
249
+ }
250
+
251
+ #isConflict(err) {
252
+ const meta = err?.meta && typeof err.meta === 'object' ? err.meta : {};
253
+ if (Object.hasOwn(meta, 'expectedOldOid') && Object.hasOwn(meta, 'actualOldOid')) {
254
+ return true;
255
+ }
256
+ const normalized = errorDetailsText(err).toLowerCase();
257
+ if (!normalized.includes(this.rootSetRef.toLowerCase())) {
258
+ return false;
259
+ }
260
+ return normalized.includes(UPDATE_REF_CONFLICT_MARKERS.cannotLockRef) && (
261
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.butExpected) ||
262
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.referenceAlreadyExists)
263
+ );
264
+ }
265
+
266
+ #isMissingRefError(err) {
267
+ if (err?.code === ErrorCodes.GIT_REF_NOT_FOUND) {
268
+ return true;
269
+ }
270
+ return isGitMissingRefError(err, this.rootSetRef);
271
+ }
272
+
273
+ #headError(message, originalError, meta = {}) {
274
+ return new CasError(message, ErrorCodes.ROOT_SET_HEAD_INVALID, {
275
+ ref: this.rootSetRef,
276
+ ...meta,
277
+ originalError,
278
+ });
279
+ }
280
+
281
+ static #publicEntry(entry) {
282
+ return {
283
+ name: entry.name,
284
+ oid: entry.oid,
285
+ type: entry.type,
286
+ retention: entry.retention,
287
+ };
288
+ }
289
+
290
+ static #validateDependencies(persistence, ref) {
291
+ const persistenceMethods = [
292
+ 'writeBlob',
293
+ 'writeTree',
294
+ 'readBlob',
295
+ 'readTree',
296
+ 'readObjectType',
297
+ ];
298
+ const refMethods = [
299
+ 'resolveRef',
300
+ 'resolveTree',
301
+ 'resolveParents',
302
+ 'createCommit',
303
+ 'updateRef',
304
+ ];
305
+ const missing = [
306
+ ...persistenceMethods.filter((method) => typeof persistence?.[method] !== 'function'),
307
+ ...refMethods.filter((method) => typeof ref?.[method] !== 'function'),
308
+ ];
309
+ if (missing.length > 0) {
310
+ throw new CasError(
311
+ 'RootSetPersistence requires complete Git persistence and ref ports',
312
+ ErrorCodes.ROOT_SET_DEPENDENCY_INVALID,
313
+ { missing },
314
+ );
315
+ }
316
+ }
317
+
318
+ async #assertTargets(entries) {
319
+ const report = await this.inspectTargets(entries);
320
+ const issue = report.issues[0];
321
+ if (!issue) {
322
+ return;
323
+ }
324
+ const messages = {
325
+ [ErrorCodes.ROOT_SET_TARGET_MISSING]: `Root-set target does not exist: ${issue.oid}`,
326
+ [ErrorCodes.ROOT_SET_TARGET_UNREADABLE]: `Root-set target could not be inspected: ${issue.oid}`,
327
+ [ErrorCodes.ROOT_SET_TARGET_TYPE_MISMATCH]: `Root-set target type mismatch for ${issue.oid}`,
328
+ };
329
+ const message = messages[issue.code];
330
+ throw new CasError(message, issue.code, {
331
+ ref: this.rootSetRef,
332
+ ...issue,
333
+ });
334
+ }
335
+ }
@@ -0,0 +1,44 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import RootSet from './RootSet.js';
4
+ import RootSetPersistence from './RootSetPersistence.js';
5
+
6
+ /**
7
+ * Opens ref-backed RootSet instances over shared Git adapters.
8
+ */
9
+ export default class RootSetRegistry {
10
+ /**
11
+ * @param {object} options
12
+ * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
13
+ * @param {import('../../ports/GitRefPort.js').default} options.ref
14
+ */
15
+ constructor({ persistence, ref }) {
16
+ if (!persistence || !ref) {
17
+ throw new CasError(
18
+ 'RootSetRegistry requires Git persistence and ref adapters',
19
+ ErrorCodes.ROOT_SET_DEPENDENCY_INVALID,
20
+ );
21
+ }
22
+ this.persistence = persistence;
23
+ this.ref = ref;
24
+ Object.freeze(this);
25
+ }
26
+
27
+ /**
28
+ * @param {object} options
29
+ * @param {string} options.ref
30
+ * @param {object} [options.retry]
31
+ * @returns {RootSet}
32
+ */
33
+ open({ ref, retry } = {}) {
34
+ return new RootSet({
35
+ ref,
36
+ retry,
37
+ persistence: new RootSetPersistence({
38
+ rootSetRef: ref,
39
+ persistence: this.persistence,
40
+ ref: this.ref,
41
+ }),
42
+ });
43
+ }
44
+ }
@@ -0,0 +1,87 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+
4
+ export const DEFAULT_ROOT_SET_RETRY_MAX_ATTEMPTS = 3;
5
+ export const DEFAULT_ROOT_SET_RETRY_BASE_DELAY_MS = 25;
6
+
7
+ /**
8
+ * Retry policy for optimistic root-set mutations.
9
+ */
10
+ export default class RootSetRetryPolicy {
11
+ #maxAttempts;
12
+ #baseDelayMs;
13
+ #random;
14
+ #sleep;
15
+
16
+ /**
17
+ * @param {object} [options]
18
+ * @param {number} [options.maxAttempts]
19
+ * @param {number} [options.baseDelayMs]
20
+ * @param {() => number} [options.random]
21
+ * @param {(delayMs: number) => Promise<void>} [options.sleep]
22
+ */
23
+ constructor({
24
+ maxAttempts = DEFAULT_ROOT_SET_RETRY_MAX_ATTEMPTS,
25
+ baseDelayMs = DEFAULT_ROOT_SET_RETRY_BASE_DELAY_MS,
26
+ random = Math.random,
27
+ sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),
28
+ } = {}) {
29
+ RootSetRetryPolicy.#assertPositiveInteger('maxAttempts', maxAttempts);
30
+ RootSetRetryPolicy.#assertNonNegativeNumber('baseDelayMs', baseDelayMs);
31
+ RootSetRetryPolicy.#assertFunction('random', random);
32
+ RootSetRetryPolicy.#assertFunction('sleep', sleep);
33
+ this.#maxAttempts = maxAttempts;
34
+ this.#baseDelayMs = baseDelayMs;
35
+ this.#random = random;
36
+ this.#sleep = sleep;
37
+ Object.freeze(this);
38
+ }
39
+
40
+ get maxAttempts() {
41
+ return this.#maxAttempts;
42
+ }
43
+
44
+ /**
45
+ * @param {unknown} err
46
+ * @returns {boolean}
47
+ */
48
+ isRetryable(err) {
49
+ return err instanceof CasError && err.code === ErrorCodes.ROOT_SET_CONFLICT;
50
+ }
51
+
52
+ /**
53
+ * @param {number} attempt
54
+ * @returns {Promise<void>}
55
+ */
56
+ async waitBeforeRetry(attempt) {
57
+ const exponentialDelay = this.#baseDelayMs * (2 ** attempt);
58
+ const jitter = Math.floor(this.#random() * (exponentialDelay / 2));
59
+ await this.#sleep(exponentialDelay + jitter);
60
+ }
61
+
62
+ static #assertPositiveInteger(label, value) {
63
+ if (!Number.isInteger(value) || value < 1) {
64
+ throw RootSetRetryPolicy.#invalid(label, value, 'a positive integer');
65
+ }
66
+ }
67
+
68
+ static #assertNonNegativeNumber(label, value) {
69
+ if (!Number.isFinite(value) || value < 0) {
70
+ throw RootSetRetryPolicy.#invalid(label, value, 'a non-negative number');
71
+ }
72
+ }
73
+
74
+ static #assertFunction(label, value) {
75
+ if (typeof value !== 'function') {
76
+ throw RootSetRetryPolicy.#invalid(label, value, 'a function');
77
+ }
78
+ }
79
+
80
+ static #invalid(label, value, expectation) {
81
+ return new CasError(
82
+ `Root-set retry ${label} must be ${expectation}`,
83
+ ErrorCodes.ROOT_SET_RETRY_POLICY_INVALID,
84
+ { [label]: value },
85
+ );
86
+ }
87
+ }
@@ -0,0 +1,95 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { ROOT_SET_METADATA_ENTRY } from './RootSetMetadataCodec.js';
4
+
5
+ const GIT_TREE_MODE = '040000';
6
+ const GIT_BLOB_MODE = '100644';
7
+
8
+ /**
9
+ * Encodes and validates the Git tree that provides root-set reachability.
10
+ */
11
+ export default class RootSetTreeCodec {
12
+ /**
13
+ * @param {object} metadata
14
+ * @param {string} metadataBlobOid
15
+ * @returns {string[]}
16
+ */
17
+ toTreeLines(metadata, metadataBlobOid) {
18
+ const lines = [`${GIT_BLOB_MODE} blob ${metadataBlobOid}\t${ROOT_SET_METADATA_ENTRY}`];
19
+ for (const entry of metadata.entries) {
20
+ const mode = entry.type === 'tree' ? GIT_TREE_MODE : GIT_BLOB_MODE;
21
+ lines.push(`${mode} ${entry.type} ${entry.oid}\t${entry.slot}`);
22
+ }
23
+ return lines;
24
+ }
25
+
26
+ /**
27
+ * @param {Array<object>} rawEntries
28
+ * @param {object} metadata
29
+ */
30
+ validate(rawEntries, metadata) {
31
+ if (!Array.isArray(rawEntries)) {
32
+ throw this.#treeError('Root-set tree entries must be an array', { rawEntries });
33
+ }
34
+ const { actual, metadataCount } = this.#indexTreeEntries(rawEntries);
35
+ this.#assertEntryCounts(actual, metadataCount, metadata);
36
+ this.#assertReachabilityEdges(actual, metadata.entries);
37
+ }
38
+
39
+ #indexTreeEntries(rawEntries) {
40
+ const actual = new Map();
41
+ let metadataCount = 0;
42
+ for (const entry of rawEntries) {
43
+ if (entry.name === ROOT_SET_METADATA_ENTRY) {
44
+ metadataCount++;
45
+ if (entry.type !== 'blob' || entry.mode !== GIT_BLOB_MODE) {
46
+ throw this.#treeError('Root-set metadata entry must be a regular blob', { entry });
47
+ }
48
+ continue;
49
+ }
50
+ if (actual.has(entry.name)) {
51
+ throw this.#treeError('Root-set tree contains duplicate entry slots', {
52
+ slot: entry.name,
53
+ });
54
+ }
55
+ actual.set(entry.name, entry);
56
+ }
57
+ return { actual, metadataCount };
58
+ }
59
+
60
+ #assertEntryCounts(actual, metadataCount, metadata) {
61
+ if (metadataCount !== 1) {
62
+ throw this.#treeError('Root-set tree must contain exactly one metadata blob', {
63
+ metadataCount,
64
+ });
65
+ }
66
+ if (actual.size !== metadata.entries.length) {
67
+ throw this.#treeError('Root-set metadata and tree entry counts differ', {
68
+ metadataEntryCount: metadata.entries.length,
69
+ treeEntryCount: actual.size,
70
+ });
71
+ }
72
+ }
73
+
74
+ #assertReachabilityEdges(actual, expectedEntries) {
75
+ for (const expected of expectedEntries) {
76
+ const entry = actual.get(expected.slot);
77
+ const mode = expected.type === 'tree' ? GIT_TREE_MODE : GIT_BLOB_MODE;
78
+ if (!entry || entry.oid !== expected.oid || entry.type !== expected.type || entry.mode !== mode) {
79
+ throw this.#treeError('Root-set metadata does not match its Git reachability edge', {
80
+ expected,
81
+ actual: entry ?? null,
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ /**
88
+ * @param {string} message
89
+ * @param {object} meta
90
+ * @returns {CasError}
91
+ */
92
+ #treeError(message, meta) {
93
+ return new CasError(message, ErrorCodes.ROOT_SET_TREE_INVALID, meta);
94
+ }
95
+ }
@@ -0,0 +1,39 @@
1
+ const SAMPLE_LIMIT = 32;
2
+
3
+ /**
4
+ * Bounded evidence about objects written before a durable root exists.
5
+ */
6
+ export default class StagingEvidence {
7
+ #handles = [];
8
+ #handleCount = 0;
9
+ #objectCount = 0;
10
+ #objects = [];
11
+
12
+ /** @param {string} oid @param {string} type */
13
+ record(oid, type) {
14
+ this.#objectCount += 1;
15
+ if (this.#objects.length < SAMPLE_LIMIT) {
16
+ this.#objects.push(Object.freeze({ oid, type }));
17
+ }
18
+ }
19
+
20
+ /** @param {{ toString(): string }} handle */
21
+ recordHandle(handle) {
22
+ this.#handleCount += 1;
23
+ if (this.#handles.length < SAMPLE_LIMIT) {
24
+ this.#handles.push(handle.toString());
25
+ }
26
+ }
27
+
28
+ /** @returns {object} */
29
+ snapshot() {
30
+ return Object.freeze({
31
+ objectCount: this.#objectCount,
32
+ stagedHandleCount: this.#handleCount,
33
+ objectSample: Object.freeze([...this.#objects]),
34
+ stagedHandleSample: Object.freeze([...this.#handles]),
35
+ sampleTruncated:
36
+ this.#objectCount > this.#objects.length || this.#handleCount > this.#handles.length,
37
+ });
38
+ }
39
+ }
@@ -0,0 +1,40 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import AssetHandle from './AssetHandle.js';
4
+ import BundleHandle from './BundleHandle.js';
5
+ import PageHandle from './PageHandle.js';
6
+
7
+ const TYPES = Object.freeze({
8
+ asset: AssetHandle,
9
+ bundle: BundleHandle,
10
+ page: PageHandle,
11
+ });
12
+
13
+ /**
14
+ * Parses any supported application-facing content handle.
15
+ *
16
+ * @param {unknown} value
17
+ * @returns {AssetHandle|BundleHandle|PageHandle}
18
+ */
19
+ export default function parseApplicationHandle(value) {
20
+ if (value instanceof AssetHandle || value instanceof BundleHandle || value instanceof PageHandle) {
21
+ return value;
22
+ }
23
+ const kind = kindOf(value);
24
+ const Type = TYPES[kind];
25
+ if (!Type) {
26
+ throw createCasError('Handle kind is not supported', ErrorCodes.HANDLE_KIND_MISMATCH, {
27
+ expectedKinds: Object.keys(TYPES),
28
+ actualKind: kind ?? null,
29
+ });
30
+ }
31
+ return Type.from(value);
32
+ }
33
+
34
+ function kindOf(value) {
35
+ if (typeof value === 'string') {
36
+ const fields = value.split(':');
37
+ return fields.length === 7 && fields[0] === 'git-cas' ? fields[2] : null;
38
+ }
39
+ return value && typeof value === 'object' && !Array.isArray(value) ? value.kind : null;
40
+ }