@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,120 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import RootSetMetadataCodec from './RootSetMetadataCodec.js';
4
+ import RootSetRef, { ROOT_SET_REF_PREFIX } from '../value-objects/RootSetRef.js';
5
+ import RetentionWitness from '../value-objects/RetentionWitness.js';
6
+
7
+ const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
8
+
9
+ /**
10
+ * Converts a validated content handle into a RootSet reachability edge.
11
+ */
12
+ export default class RetentionService {
13
+ #clock;
14
+ #resolveRoot;
15
+ #rootSets;
16
+
17
+ /**
18
+ * @param {object} options
19
+ * @param {{ open(options: object): import('./RootSet.js').default }} options.rootSets
20
+ * @param {(handle: unknown) => Promise<object>} options.resolveRoot
21
+ * @param {{ now(): Date }} [options.clock]
22
+ */
23
+ constructor({ rootSets, resolveRoot, clock = DEFAULT_CLOCK }) {
24
+ RetentionService.#assertDependencies(rootSets, resolveRoot, clock);
25
+ this.#rootSets = rootSets;
26
+ this.#resolveRoot = resolveRoot;
27
+ this.#clock = clock;
28
+ }
29
+
30
+ /**
31
+ * @param {object} options
32
+ * @param {unknown} options.handle
33
+ * @param {{ ref: string, name: string }} options.root
34
+ * @param {'pinned'|'evictable'} [options.policy]
35
+ * @returns {Promise<{ changed: boolean, witness: RetentionWitness }>}
36
+ */
37
+ async retain({ handle, root, policy = 'pinned' }) {
38
+ RetentionService.#assertRoot(root);
39
+ const target = await this.#resolveRoot(handle);
40
+ const rootSet = this.#rootSets.open({ ref: root.ref });
41
+ const result = await rootSet.put({
42
+ name: root.name,
43
+ oid: target.oid,
44
+ type: target.type,
45
+ retention: policy,
46
+ });
47
+ const path = RetentionService.#evidencePath(result.entries, root.name);
48
+ const witness = new RetentionWitness({
49
+ handle: target.handle,
50
+ policy,
51
+ reachability: 'anchored',
52
+ root: {
53
+ kind: 'root-set',
54
+ namespace: root.ref.slice(ROOT_SET_REF_PREFIX.length),
55
+ ref: root.ref,
56
+ generation: result.commitOid,
57
+ path,
58
+ },
59
+ observedAt: this.#observedAt(),
60
+ });
61
+ return Object.freeze({ changed: result.changed, witness });
62
+ }
63
+
64
+ #observedAt() {
65
+ const now = this.#clock.now();
66
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
67
+ throw createCasError(
68
+ 'RetentionService clock returned an invalid Date',
69
+ ErrorCodes.INVALID_OPTIONS
70
+ );
71
+ }
72
+ return now.toISOString();
73
+ }
74
+
75
+ static #evidencePath(entries, name) {
76
+ const index = entries.findIndex((entry) => entry.name === name);
77
+ if (index === -1) {
78
+ throw createCasError(
79
+ 'Retained entry is absent from the committed root generation',
80
+ ErrorCodes.ROOT_SET_TREE_INVALID,
81
+ { name }
82
+ );
83
+ }
84
+ return RootSetMetadataCodec.slotFor(index);
85
+ }
86
+
87
+ static #assertRoot(root) {
88
+ if (!root || typeof root !== 'object' || Array.isArray(root)) {
89
+ throw createCasError('Retention root must be an object', ErrorCodes.INVALID_OPTIONS, {
90
+ root,
91
+ });
92
+ }
93
+ if (typeof root.ref !== 'string' || typeof root.name !== 'string' || root.name.length === 0) {
94
+ throw createCasError(
95
+ 'Retention root requires ref and name strings',
96
+ ErrorCodes.INVALID_OPTIONS,
97
+ { root }
98
+ );
99
+ }
100
+ RootSetRef.from(root.ref);
101
+ }
102
+
103
+ static #assertDependencies(rootSets, resolveRoot, clock) {
104
+ if (!rootSets || typeof rootSets.open !== 'function') {
105
+ throw createCasError(
106
+ 'RetentionService requires a RootSet registry',
107
+ ErrorCodes.INVALID_OPTIONS
108
+ );
109
+ }
110
+ if (typeof resolveRoot !== 'function') {
111
+ throw createCasError(
112
+ 'RetentionService requires a handle resolver',
113
+ ErrorCodes.INVALID_OPTIONS
114
+ );
115
+ }
116
+ if (!clock || typeof clock.now !== 'function') {
117
+ throw createCasError('RetentionService clock must provide now()', ErrorCodes.INVALID_OPTIONS);
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,281 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import Oid from '../value-objects/Oid.js';
4
+ import RootSetRef from '../value-objects/RootSetRef.js';
5
+ import RootSetMetadataCodec from './RootSetMetadataCodec.js';
6
+ import RootSetRetryPolicy from './RootSetRetryPolicy.js';
7
+
8
+ const EXPECTED_HEAD_UNSET = Symbol('expected-head-unset');
9
+
10
+ /**
11
+ * Mutable, current-generation set of Git reachability roots.
12
+ */
13
+ export default class RootSet {
14
+ #metadataCodec;
15
+ #retry;
16
+
17
+ /**
18
+ * @param {object} options
19
+ * @param {string} options.ref
20
+ * @param {object} options.persistence
21
+ * @param {RootSetRetryPolicy|object} [options.retry]
22
+ * @param {RootSetMetadataCodec} [options.metadataCodec]
23
+ */
24
+ constructor({
25
+ ref,
26
+ persistence,
27
+ retry,
28
+ refType = RootSetRef,
29
+ metadataCodec = new RootSetMetadataCodec({ refType }),
30
+ }) {
31
+ this.ref = refType.from(ref).toString();
32
+ RootSet.#validatePersistence(persistence);
33
+ this.persistence = persistence;
34
+ this.#metadataCodec = metadataCodec;
35
+ this.#retry = retry instanceof RootSetRetryPolicy ? retry : new RootSetRetryPolicy(retry);
36
+ Object.freeze(this);
37
+ }
38
+
39
+ /**
40
+ * @returns {Promise<{ ref: string, headOid: string|null, treeOid: string|null, entries: Array<object> }>}
41
+ */
42
+ async read() {
43
+ const state = await this.persistence.read();
44
+ return { ...state, entries: state.entries.map((entry) => ({ ...entry })) };
45
+ }
46
+
47
+ /**
48
+ * @returns {Promise<Array<object>>}
49
+ */
50
+ async list() {
51
+ return (await this.read()).entries;
52
+ }
53
+
54
+ /**
55
+ * @param {string} name
56
+ * @returns {Promise<boolean>}
57
+ */
58
+ async contains(name) {
59
+ return (await this.list()).some((entry) => entry.name === name);
60
+ }
61
+
62
+ /**
63
+ * @param {object} entry
64
+ * @returns {Promise<object>}
65
+ */
66
+ async put(entry) {
67
+ const normalizedEntry = this.#metadataCodec.normalizeEntries([entry])[0];
68
+ let previous = null;
69
+ const result = await this.#mutateEntries((entries) => {
70
+ const byName = new Map(entries.map((current) => [current.name, current]));
71
+ previous = byName.get(normalizedEntry.name) ?? null;
72
+ byName.set(normalizedEntry.name, normalizedEntry);
73
+ return byName.values();
74
+ }, `root-set: put ${normalizedEntry.name}`);
75
+ return { ...result, entry: normalizedEntry, previous };
76
+ }
77
+
78
+ /**
79
+ * @param {{ name: string }} options
80
+ * @returns {Promise<object>}
81
+ */
82
+ async remove({ name }) {
83
+ let removed = null;
84
+ const result = await this.#mutateEntries((entries) => {
85
+ const next = [];
86
+ for (const entry of entries) {
87
+ if (entry.name === name) {
88
+ removed = entry;
89
+ } else {
90
+ next.push(entry);
91
+ }
92
+ }
93
+ return next;
94
+ }, `root-set: remove ${name}`);
95
+ return { ...result, removed };
96
+ }
97
+
98
+ /**
99
+ * @param {{ entries: Iterable<object>, expectedHeadOid?: string|null }} options
100
+ * @returns {Promise<object>}
101
+ */
102
+ async replace({ entries, expectedHeadOid = EXPECTED_HEAD_UNSET }) {
103
+ const desired = this.#metadataCodec.normalizeEntries(entries);
104
+ return await this.#mutateEntries(
105
+ () => desired,
106
+ 'root-set: replace current roots',
107
+ RootSet.#normalizeExpectedHead(expectedHeadOid),
108
+ );
109
+ }
110
+
111
+ /**
112
+ * @param {(entries: ReadonlyArray<object>, state: Readonly<object>) => Iterable<object>|Promise<Iterable<object>>} mutator
113
+ * @param {{ expectedHeadOid?: string|null }} [options]
114
+ * @returns {Promise<object>}
115
+ */
116
+ async mutate(mutator, { expectedHeadOid = EXPECTED_HEAD_UNSET } = {}) {
117
+ if (typeof mutator !== 'function') {
118
+ throw new CasError(
119
+ 'Root-set mutator must be a function',
120
+ ErrorCodes.ROOT_SET_ENTRY_INVALID,
121
+ { mutatorType: typeof mutator },
122
+ );
123
+ }
124
+ return await this.#mutateEntries(async (entries, state) => (
125
+ await mutator(
126
+ Object.freeze(entries.map((entry) => Object.freeze({ ...entry }))),
127
+ Object.freeze({ ref: state.ref, headOid: state.headOid, treeOid: state.treeOid }),
128
+ )
129
+ ), 'root-set: mutate current roots', RootSet.#normalizeExpectedHead(expectedHeadOid));
130
+ }
131
+
132
+ /**
133
+ * Reports whether the current ref, commit, metadata, and reachability tree
134
+ * agree. It does not mutate the repository.
135
+ *
136
+ * @returns {Promise<object>}
137
+ */
138
+ async doctor() {
139
+ try {
140
+ const state = await this.read();
141
+ const targetReport = await this.persistence.inspectTargets(state.entries);
142
+ return {
143
+ healthy: targetReport.healthy,
144
+ ref: this.ref,
145
+ headOid: state.headOid,
146
+ treeOid: state.treeOid,
147
+ entryCount: state.entries.length,
148
+ entries: state.entries,
149
+ policyCounts: RootSet.#policyCounts(state.entries),
150
+ reachabilityCounts: {
151
+ anchored: targetReport.targets.filter((target) => target.exists === true).length,
152
+ missing: targetReport.targets.filter((target) => target.exists === false).length,
153
+ unknown: targetReport.targets.filter((target) => target.exists === null).length,
154
+ orphaned: 0,
155
+ volatile: 0,
156
+ },
157
+ targets: targetReport.targets,
158
+ issues: targetReport.issues.map(RootSet.#publicIssue),
159
+ };
160
+ } catch (err) {
161
+ return {
162
+ healthy: false,
163
+ ref: this.ref,
164
+ error: {
165
+ code: err?.code ?? ErrorCodes.ROOT_SET_HEAD_INVALID,
166
+ message: err instanceof Error ? err.message : String(err),
167
+ },
168
+ };
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Replaces a missing or malformed head from an authoritative entry list.
174
+ * This deliberately does not trust the current metadata.
175
+ *
176
+ * @param {{ entries: Iterable<object> }} options
177
+ * @returns {Promise<object>}
178
+ */
179
+ async repair({ entries }) {
180
+ const desired = this.#metadataCodec.normalizeEntries(entries);
181
+ for (let attempt = 0; attempt < this.#retry.maxAttempts; attempt++) {
182
+ const expectedHeadOid = await this.persistence.resolveRefOnly();
183
+ try {
184
+ const written = await this.persistence.write({
185
+ entries: desired,
186
+ expectedHeadOid,
187
+ message: 'root-set: repair current roots',
188
+ });
189
+ return { repaired: true, ...written };
190
+ } catch (err) {
191
+ await this.#handleConflict(err, attempt);
192
+ }
193
+ }
194
+ throw new CasError('Root-set repair attempts exhausted', ErrorCodes.ROOT_SET_CONFLICT);
195
+ }
196
+
197
+ async #mutateEntries(transform, message, expectedHeadOid = EXPECTED_HEAD_UNSET) {
198
+ for (let attempt = 0; attempt < this.#retry.maxAttempts; attempt++) {
199
+ const state = await this.read();
200
+ this.#assertExpectedHead(state.headOid, expectedHeadOid);
201
+ const entries = this.#metadataCodec.normalizeEntries(await transform(state.entries, state));
202
+ if (RootSet.#entriesEqual(state.entries, entries)) {
203
+ return {
204
+ changed: false,
205
+ commitOid: state.headOid,
206
+ treeOid: state.treeOid,
207
+ entries,
208
+ };
209
+ }
210
+ try {
211
+ const written = await this.persistence.write({
212
+ entries,
213
+ expectedHeadOid: state.headOid,
214
+ message,
215
+ });
216
+ return { changed: true, ...written };
217
+ } catch (err) {
218
+ if (expectedHeadOid !== EXPECTED_HEAD_UNSET) {
219
+ throw err;
220
+ }
221
+ await this.#handleConflict(err, attempt);
222
+ }
223
+ }
224
+ throw new CasError('Root-set mutation attempts exhausted', ErrorCodes.ROOT_SET_CONFLICT);
225
+ }
226
+
227
+ async #handleConflict(err, attempt) {
228
+ const finalAttempt = attempt + 1 >= this.#retry.maxAttempts;
229
+ if (!this.#retry.isRetryable(err) || finalAttempt) {
230
+ throw err;
231
+ }
232
+ await this.#retry.waitBeforeRetry(attempt);
233
+ }
234
+
235
+ #assertExpectedHead(actualHeadOid, expectedHeadOid) {
236
+ if (expectedHeadOid === EXPECTED_HEAD_UNSET || actualHeadOid === expectedHeadOid) {
237
+ return;
238
+ }
239
+ throw new CasError(
240
+ 'Root-set head does not match the caller expectation',
241
+ ErrorCodes.ROOT_SET_CONFLICT,
242
+ { ref: this.ref, expectedHeadOid, actualHeadOid },
243
+ );
244
+ }
245
+
246
+ static #normalizeExpectedHead(expectedHeadOid) {
247
+ if (expectedHeadOid === EXPECTED_HEAD_UNSET || expectedHeadOid === null) {
248
+ return expectedHeadOid;
249
+ }
250
+ return Oid.from(expectedHeadOid).toString();
251
+ }
252
+
253
+ static #entriesEqual(left, right) {
254
+ return JSON.stringify(left) === JSON.stringify(right);
255
+ }
256
+
257
+ static #policyCounts(entries) {
258
+ return entries.reduce((counts, entry) => ({
259
+ ...counts,
260
+ [entry.retention]: counts[entry.retention] + 1,
261
+ }), { pinned: 0, evictable: 0 });
262
+ }
263
+
264
+ static #publicIssue(issue) {
265
+ return Object.fromEntries(
266
+ Object.entries(issue).filter(([key]) => key !== 'originalError'),
267
+ );
268
+ }
269
+
270
+ static #validatePersistence(persistence) {
271
+ const missing = ['read', 'write', 'resolveRefOnly', 'inspectTargets']
272
+ .filter((method) => typeof persistence?.[method] !== 'function');
273
+ if (missing.length > 0) {
274
+ throw new CasError(
275
+ 'RootSet requires a complete RootSetPersistence',
276
+ ErrorCodes.ROOT_SET_DEPENDENCY_INVALID,
277
+ { missing },
278
+ );
279
+ }
280
+ }
281
+ }
@@ -0,0 +1,259 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { utf8Decode, utf8Encode } from '../encoding/utf8.js';
4
+ import Oid from '../value-objects/Oid.js';
5
+ import RootSetRef from '../value-objects/RootSetRef.js';
6
+
7
+ export const ROOT_SET_METADATA_VERSION = 1;
8
+ export const ROOT_SET_METADATA_ENTRY = '.rootset.json';
9
+ export const ROOT_SET_ENTRY_TYPES = Object.freeze(['blob', 'tree']);
10
+ export const ROOT_SET_RETENTION_POLICIES = Object.freeze(['pinned', 'evictable']);
11
+ const SLOT_PATTERN = /^root-[0-9]{8}$/;
12
+
13
+ /**
14
+ * Canonical JSON codec for `.rootset.json` snapshots.
15
+ */
16
+ export default class RootSetMetadataCodec {
17
+ #refType;
18
+
19
+ constructor({ refType = RootSetRef } = {}) {
20
+ this.#refType = refType;
21
+ }
22
+
23
+ /**
24
+ * @param {{ ref: string, entries: Iterable<object> }} options
25
+ * @returns {Uint8Array}
26
+ */
27
+ encode({ ref, entries }) {
28
+ return utf8Encode(JSON.stringify(this.create({ ref, entries }), null, 2));
29
+ }
30
+
31
+ /**
32
+ * @param {{ ref: string, entries: Iterable<object> }} options
33
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
34
+ */
35
+ create({ ref, entries }) {
36
+ const rootSetRef = this.#refType.from(ref).toString();
37
+ return {
38
+ version: ROOT_SET_METADATA_VERSION,
39
+ ref: rootSetRef,
40
+ entries: this.normalizeEntries(entries).map((entry, index) => ({
41
+ slot: RootSetMetadataCodec.slotFor(index),
42
+ ...entry,
43
+ })),
44
+ };
45
+ }
46
+
47
+ /**
48
+ * @param {Uint8Array} bytes
49
+ * @param {{ expectedRef?: string }} [options]
50
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
51
+ */
52
+ decode(bytes, { expectedRef } = {}) {
53
+ let metadata;
54
+ try {
55
+ metadata = JSON.parse(utf8Decode(bytes));
56
+ } catch (err) {
57
+ throw this.#metadataError('Failed to parse .rootset.json', { originalError: err });
58
+ }
59
+ return this.validate(metadata, { expectedRef });
60
+ }
61
+
62
+ /**
63
+ * @param {unknown} metadata
64
+ * @param {{ expectedRef?: string }} [options]
65
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
66
+ */
67
+ validate(metadata, { expectedRef } = {}) {
68
+ this.#assertMetadataEnvelope(metadata);
69
+ const canonical = this.#canonicalizeStoredMetadata(metadata);
70
+ this.#assertExpectedRef(canonical.ref, expectedRef);
71
+ this.#assertCanonicalStorage(metadata, canonical);
72
+ return canonical;
73
+ }
74
+
75
+ /**
76
+ * @param {Iterable<object>} entries
77
+ * @returns {Array<{ name: string, oid: string, type: 'blob'|'tree', retention: 'pinned'|'evictable' }>}
78
+ */
79
+ normalizeEntries(entries) {
80
+ if (!entries || typeof entries[Symbol.iterator] !== 'function') {
81
+ throw this.#entryError('Root-set entries must be iterable', { entries });
82
+ }
83
+
84
+ const normalized = [...entries].map((entry) => this.#normalizeEntry(entry));
85
+ normalized.sort(RootSetMetadataCodec.#compareNames);
86
+ for (let index = 1; index < normalized.length; index++) {
87
+ if (normalized[index - 1].name === normalized[index].name) {
88
+ throw this.#entryError('Root-set entry names must be unique', {
89
+ name: normalized[index].name,
90
+ });
91
+ }
92
+ }
93
+ return normalized;
94
+ }
95
+
96
+ /**
97
+ * @param {number} index
98
+ * @returns {string}
99
+ */
100
+ static slotFor(index) {
101
+ if (!Number.isSafeInteger(index) || index < 0 || index > 99_999_999) {
102
+ throw new CasError(
103
+ 'Root-set entry count exceeds the supported slot range',
104
+ ErrorCodes.ROOT_SET_ENTRY_INVALID,
105
+ { index },
106
+ );
107
+ }
108
+ return `root-${String(index).padStart(8, '0')}`;
109
+ }
110
+
111
+ /**
112
+ * @param {object} entry
113
+ * @returns {{ name: string, oid: string, type: 'blob'|'tree', retention: 'pinned'|'evictable' }}
114
+ */
115
+ #normalizeEntry(entry) {
116
+ this.#assertEntryObject(entry);
117
+ this.#assertEntryName(entry);
118
+ this.#assertEntryType(entry);
119
+ const retention = entry.retention ?? 'pinned';
120
+ if (!ROOT_SET_RETENTION_POLICIES.includes(retention)) {
121
+ throw this.#entryError('Root-set retention must be pinned or evictable', { entry });
122
+ }
123
+ return {
124
+ name: entry.name,
125
+ oid: this.#normalizeOid(entry),
126
+ type: entry.type,
127
+ retention,
128
+ };
129
+ }
130
+
131
+ #assertMetadataEnvelope(metadata) {
132
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
133
+ throw this.#metadataError('Root-set metadata must be an object', { metadata });
134
+ }
135
+ if (metadata.version !== ROOT_SET_METADATA_VERSION) {
136
+ throw this.#metadataError(`Unsupported root-set metadata version: ${metadata.version}`, {
137
+ metadata,
138
+ });
139
+ }
140
+ }
141
+
142
+ #canonicalizeStoredMetadata(metadata) {
143
+ try {
144
+ return this.create({ ref: metadata.ref, entries: metadata.entries });
145
+ } catch (err) {
146
+ if (err instanceof CasError && err.code === ErrorCodes.ROOT_SET_ENTRY_INVALID) {
147
+ throw err;
148
+ }
149
+ throw this.#metadataError('Root-set metadata fields are invalid', {
150
+ metadata,
151
+ originalError: err,
152
+ });
153
+ }
154
+ }
155
+
156
+ #assertExpectedRef(actualRef, expectedRef) {
157
+ if (expectedRef === undefined || actualRef === this.#refType.from(expectedRef).toString()) {
158
+ return;
159
+ }
160
+ throw this.#metadataError('Root-set metadata ref does not match the requested ref', {
161
+ expectedRef,
162
+ actualRef,
163
+ });
164
+ }
165
+
166
+ #assertCanonicalStorage(metadata, canonical) {
167
+ if (!RootSetMetadataCodec.#isCanonicalStoredMetadata(metadata, canonical)) {
168
+ throw this.#metadataError('Root-set metadata is not canonical', { metadata });
169
+ }
170
+ }
171
+
172
+ #assertEntryObject(entry) {
173
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
174
+ throw this.#entryError('Root-set entry must be an object', { entry });
175
+ }
176
+ }
177
+
178
+ #assertEntryName(entry) {
179
+ if (
180
+ typeof entry.name !== 'string' ||
181
+ entry.name.length === 0 ||
182
+ RootSetMetadataCodec.#hasControlCharacters(entry.name)
183
+ ) {
184
+ throw this.#entryError('Root-set entry name must be a non-empty string without control characters', {
185
+ entry,
186
+ });
187
+ }
188
+ }
189
+
190
+ #assertEntryType(entry) {
191
+ if (!ROOT_SET_ENTRY_TYPES.includes(entry.type)) {
192
+ throw this.#entryError('Root-set entry type must be blob or tree', { entry });
193
+ }
194
+ }
195
+
196
+ #normalizeOid(entry) {
197
+ try {
198
+ return Oid.from(entry.oid).toString();
199
+ } catch (err) {
200
+ throw this.#entryError('Root-set entry OID is invalid', { entry, originalError: err });
201
+ }
202
+ }
203
+
204
+ static #hasControlCharacters(value) {
205
+ for (const character of value) {
206
+ const codePoint = character.codePointAt(0);
207
+ if (codePoint < 0x20 || codePoint === 0x7f) {
208
+ return true;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+
214
+ static #compareNames(left, right) {
215
+ if (left.name < right.name) {
216
+ return -1;
217
+ }
218
+ return left.name > right.name ? 1 : 0;
219
+ }
220
+
221
+ /**
222
+ * @param {unknown} stored
223
+ * @param {object} canonical
224
+ * @returns {boolean}
225
+ */
226
+ static #isCanonicalStoredMetadata(stored, canonical) {
227
+ if (Object.keys(stored).sort().join(',') !== 'entries,ref,version') {
228
+ return false;
229
+ }
230
+ if (!Array.isArray(stored.entries) || stored.entries.length !== canonical.entries.length) {
231
+ return false;
232
+ }
233
+ return stored.entries.every((entry, index) => (
234
+ entry &&
235
+ typeof entry === 'object' &&
236
+ Object.keys(entry).sort().join(',') === 'name,oid,retention,slot,type' &&
237
+ SLOT_PATTERN.test(entry.slot) &&
238
+ JSON.stringify(entry) === JSON.stringify(canonical.entries[index])
239
+ ));
240
+ }
241
+
242
+ /**
243
+ * @param {string} message
244
+ * @param {object} meta
245
+ * @returns {CasError}
246
+ */
247
+ #metadataError(message, meta) {
248
+ return new CasError(message, ErrorCodes.ROOT_SET_METADATA_INVALID, meta);
249
+ }
250
+
251
+ /**
252
+ * @param {string} message
253
+ * @param {object} meta
254
+ * @returns {CasError}
255
+ */
256
+ #entryError(message, meta) {
257
+ return new CasError(message, ErrorCodes.ROOT_SET_ENTRY_INVALID, meta);
258
+ }
259
+ }