@git-stunts/git-warp 10.3.2 → 10.7.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 (108) hide show
  1. package/README.md +6 -3
  2. package/SECURITY.md +89 -1
  3. package/bin/warp-graph.js +574 -208
  4. package/index.d.ts +55 -0
  5. package/index.js +4 -0
  6. package/package.json +8 -4
  7. package/src/domain/WarpGraph.js +334 -161
  8. package/src/domain/crdt/LWW.js +1 -1
  9. package/src/domain/crdt/ORSet.js +10 -6
  10. package/src/domain/crdt/VersionVector.js +5 -1
  11. package/src/domain/errors/EmptyMessageError.js +2 -4
  12. package/src/domain/errors/ForkError.js +4 -0
  13. package/src/domain/errors/IndexError.js +4 -0
  14. package/src/domain/errors/OperationAbortedError.js +4 -0
  15. package/src/domain/errors/QueryError.js +4 -0
  16. package/src/domain/errors/SchemaUnsupportedError.js +4 -0
  17. package/src/domain/errors/ShardCorruptionError.js +2 -6
  18. package/src/domain/errors/ShardLoadError.js +2 -6
  19. package/src/domain/errors/ShardValidationError.js +2 -7
  20. package/src/domain/errors/StorageError.js +2 -6
  21. package/src/domain/errors/SyncError.js +4 -0
  22. package/src/domain/errors/TraversalError.js +4 -0
  23. package/src/domain/errors/WarpError.js +2 -4
  24. package/src/domain/errors/WormholeError.js +4 -0
  25. package/src/domain/services/AnchorMessageCodec.js +1 -4
  26. package/src/domain/services/BitmapIndexBuilder.js +10 -6
  27. package/src/domain/services/BitmapIndexReader.js +27 -21
  28. package/src/domain/services/BoundaryTransitionRecord.js +22 -15
  29. package/src/domain/services/CheckpointMessageCodec.js +1 -7
  30. package/src/domain/services/CheckpointSerializerV5.js +20 -19
  31. package/src/domain/services/CheckpointService.js +18 -18
  32. package/src/domain/services/CommitDagTraversalService.js +13 -1
  33. package/src/domain/services/DagPathFinding.js +40 -18
  34. package/src/domain/services/DagTopology.js +7 -6
  35. package/src/domain/services/DagTraversal.js +5 -3
  36. package/src/domain/services/Frontier.js +7 -6
  37. package/src/domain/services/HealthCheckService.js +15 -14
  38. package/src/domain/services/HookInstaller.js +64 -13
  39. package/src/domain/services/HttpSyncServer.js +88 -19
  40. package/src/domain/services/IndexRebuildService.js +12 -12
  41. package/src/domain/services/IndexStalenessChecker.js +13 -6
  42. package/src/domain/services/JoinReducer.js +28 -27
  43. package/src/domain/services/LogicalTraversal.js +7 -6
  44. package/src/domain/services/MessageCodecInternal.js +2 -0
  45. package/src/domain/services/ObserverView.js +6 -6
  46. package/src/domain/services/PatchBuilderV2.js +9 -9
  47. package/src/domain/services/PatchMessageCodec.js +1 -7
  48. package/src/domain/services/ProvenanceIndex.js +6 -8
  49. package/src/domain/services/ProvenancePayload.js +1 -2
  50. package/src/domain/services/QueryBuilder.js +29 -23
  51. package/src/domain/services/StateDiff.js +7 -7
  52. package/src/domain/services/StateSerializerV5.js +8 -6
  53. package/src/domain/services/StreamingBitmapIndexBuilder.js +29 -23
  54. package/src/domain/services/SyncAuthService.js +396 -0
  55. package/src/domain/services/SyncProtocol.js +23 -26
  56. package/src/domain/services/TemporalQuery.js +4 -3
  57. package/src/domain/services/TranslationCost.js +4 -4
  58. package/src/domain/services/WormholeService.js +19 -15
  59. package/src/domain/types/TickReceipt.js +10 -6
  60. package/src/domain/types/WarpTypesV2.js +2 -3
  61. package/src/domain/utils/CachedValue.js +1 -1
  62. package/src/domain/utils/LRUCache.js +3 -3
  63. package/src/domain/utils/MinHeap.js +2 -2
  64. package/src/domain/utils/RefLayout.js +19 -0
  65. package/src/domain/utils/WriterId.js +2 -2
  66. package/src/domain/utils/defaultCodec.js +9 -2
  67. package/src/domain/utils/defaultCrypto.js +36 -0
  68. package/src/domain/utils/roaring.js +5 -5
  69. package/src/domain/utils/seekCacheKey.js +32 -0
  70. package/src/domain/warp/PatchSession.js +3 -3
  71. package/src/domain/warp/Writer.js +2 -2
  72. package/src/infrastructure/adapters/BunHttpAdapter.js +21 -8
  73. package/src/infrastructure/adapters/CasSeekCacheAdapter.js +311 -0
  74. package/src/infrastructure/adapters/ClockAdapter.js +2 -2
  75. package/src/infrastructure/adapters/DenoHttpAdapter.js +22 -9
  76. package/src/infrastructure/adapters/GitGraphAdapter.js +25 -83
  77. package/src/infrastructure/adapters/InMemoryGraphAdapter.js +488 -0
  78. package/src/infrastructure/adapters/NodeCryptoAdapter.js +16 -3
  79. package/src/infrastructure/adapters/NodeHttpAdapter.js +33 -11
  80. package/src/infrastructure/adapters/WebCryptoAdapter.js +21 -11
  81. package/src/infrastructure/adapters/adapterValidation.js +90 -0
  82. package/src/infrastructure/codecs/CborCodec.js +16 -8
  83. package/src/ports/BlobPort.js +2 -2
  84. package/src/ports/CodecPort.js +2 -2
  85. package/src/ports/CommitPort.js +8 -21
  86. package/src/ports/ConfigPort.js +3 -3
  87. package/src/ports/CryptoPort.js +7 -7
  88. package/src/ports/GraphPersistencePort.js +12 -14
  89. package/src/ports/HttpServerPort.js +1 -5
  90. package/src/ports/IndexStoragePort.js +1 -0
  91. package/src/ports/LoggerPort.js +9 -9
  92. package/src/ports/RefPort.js +5 -5
  93. package/src/ports/SeekCachePort.js +73 -0
  94. package/src/ports/TreePort.js +3 -3
  95. package/src/visualization/layouts/converters.js +14 -7
  96. package/src/visualization/layouts/elkAdapter.js +17 -4
  97. package/src/visualization/layouts/elkLayout.js +23 -7
  98. package/src/visualization/layouts/index.js +3 -3
  99. package/src/visualization/renderers/ascii/check.js +30 -17
  100. package/src/visualization/renderers/ascii/graph.js +92 -1
  101. package/src/visualization/renderers/ascii/history.js +28 -26
  102. package/src/visualization/renderers/ascii/info.js +9 -7
  103. package/src/visualization/renderers/ascii/materialize.js +20 -16
  104. package/src/visualization/renderers/ascii/opSummary.js +15 -7
  105. package/src/visualization/renderers/ascii/path.js +1 -1
  106. package/src/visualization/renderers/ascii/seek.js +187 -23
  107. package/src/visualization/renderers/ascii/table.js +1 -1
  108. package/src/visualization/renderers/svg/index.js +5 -1
@@ -43,7 +43,7 @@ function validateSha(sha, paramName) {
43
43
 
44
44
  /**
45
45
  * Verifies that a SHA exists in the repository.
46
- * @param {Object} persistence - Git persistence adapter
46
+ * @param {{ nodeExists: (sha: string) => Promise<boolean> }} persistence - Git persistence adapter
47
47
  * @param {string} sha - The SHA to verify
48
48
  * @param {string} paramName - Parameter name for error messages
49
49
  * @throws {WormholeError} If SHA doesn't exist
@@ -62,10 +62,11 @@ async function verifyShaExists(persistence, sha, paramName) {
62
62
  /**
63
63
  * Processes a single commit in the wormhole chain.
64
64
  * @param {Object} opts - Options
65
- * @param {Object} opts.persistence - Git persistence adapter
65
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/CommitPort.js').default & import('../../ports/BlobPort.js').default} opts.persistence - Git persistence adapter
66
66
  * @param {string} opts.sha - The commit SHA
67
67
  * @param {string} opts.graphName - Expected graph name
68
68
  * @param {string|null} opts.expectedWriter - Expected writer ID (null for first commit)
69
+ * @param {import('../../ports/CodecPort.js').default} [opts.codec] - Codec for deserialization
69
70
  * @returns {Promise<{patch: Object, sha: string, writerId: string, parentSha: string|null}>}
70
71
  * @throws {WormholeError} On validation errors
71
72
  * @private
@@ -100,7 +101,7 @@ async function processCommit({ persistence, sha, graphName, expectedWriter, code
100
101
  }
101
102
 
102
103
  const patchBuffer = await persistence.readBlob(patchMeta.patchOid);
103
- const patch = codec.decode(patchBuffer);
104
+ const patch = /** @type {Object} */ (codec.decode(patchBuffer));
104
105
 
105
106
  return {
106
107
  patch,
@@ -135,10 +136,11 @@ async function processCommit({ persistence, sha, graphName, expectedWriter, code
135
136
  * are inclusive in the wormhole.
136
137
  *
137
138
  * @param {Object} options - Wormhole creation options
138
- * @param {import('../../ports/GraphPersistencePort.js').default} options.persistence - Git persistence adapter
139
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/CommitPort.js').default & import('../../ports/BlobPort.js').default} options.persistence - Git persistence adapter
139
140
  * @param {string} options.graphName - Name of the graph
140
141
  * @param {string} options.fromSha - SHA of the first (oldest) patch commit
141
142
  * @param {string} options.toSha - SHA of the last (newest) patch commit
143
+ * @param {import('../../ports/CodecPort.js').default} [options.codec] - Codec for deserialization
142
144
  * @returns {Promise<WormholeEdge>} The created wormhole
143
145
  * @throws {WormholeError} If fromSha or toSha doesn't exist (E_WORMHOLE_SHA_NOT_FOUND)
144
146
  * @throws {WormholeError} If fromSha is not an ancestor of toSha (E_WORMHOLE_INVALID_RANGE)
@@ -156,7 +158,7 @@ export async function createWormhole({ persistence, graphName, fromSha, toSha, c
156
158
  // Reverse to get oldest-first order (as required by ProvenancePayload)
157
159
  patches.reverse();
158
160
 
159
- const writerId = patches.length > 0 ? patches[0].writerId : null;
161
+ const writerId = patches.length > 0 ? patches[0].writerId : /** @type {string} */ ('');
160
162
  // Strip writerId to match ProvenancePayload's PatchEntry typedef ({patch, sha})
161
163
  const payload = new ProvenancePayload(patches.map(({ patch, sha }) => ({ patch, sha })));
162
164
 
@@ -170,10 +172,11 @@ export async function createWormhole({ persistence, graphName, fromSha, toSha, c
170
172
  * validating each commit along the way.
171
173
  *
172
174
  * @param {Object} options
173
- * @param {import('../../ports/GraphPersistencePort.js').default} options.persistence - Git persistence adapter
175
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/CommitPort.js').default & import('../../ports/BlobPort.js').default} options.persistence - Git persistence adapter
174
176
  * @param {string} options.graphName - Expected graph name
175
177
  * @param {string} options.fromSha - SHA of the first (oldest) patch commit
176
178
  * @param {string} options.toSha - SHA of the last (newest) patch commit
179
+ * @param {import('../../ports/CodecPort.js').default} [options.codec] - Codec for deserialization
177
180
  * @returns {Promise<Array<{patch: Object, sha: string, writerId: string}>>} Patches in newest-first order
178
181
  * @throws {WormholeError} If fromSha is not an ancestor of toSha or range is empty
179
182
  * @private
@@ -230,7 +233,7 @@ async function collectPatchRange({ persistence, graphName, fromSha, toSha, codec
230
233
  * @param {WormholeEdge} first - The earlier (older) wormhole
231
234
  * @param {WormholeEdge} second - The later (newer) wormhole
232
235
  * @param {Object} [options] - Composition options
233
- * @param {import('../../ports/GraphPersistencePort.js').default} [options.persistence] - Git persistence adapter (for validation)
236
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/CommitPort.js').default} [options.persistence] - Git persistence adapter (for validation)
234
237
  * @returns {Promise<WormholeEdge>} The composed wormhole
235
238
  * @throws {WormholeError} If wormholes are from different writers (E_WORMHOLE_MULTI_WRITER)
236
239
  * @throws {WormholeError} If wormholes are not consecutive (E_WORMHOLE_INVALID_RANGE)
@@ -318,9 +321,10 @@ export function deserializeWormhole(json) {
318
321
  });
319
322
  }
320
323
 
324
+ const /** @type {Record<string, *>} */ typedJson = /** @type {Record<string, *>} */ (json);
321
325
  const requiredFields = ['fromSha', 'toSha', 'writerId', 'patchCount', 'payload'];
322
326
  for (const field of requiredFields) {
323
- if (json[field] === undefined) {
327
+ if (typedJson[field] === undefined) {
324
328
  throw new WormholeError(`Invalid wormhole JSON: missing required field '${field}'`, {
325
329
  code: 'E_INVALID_WORMHOLE_JSON',
326
330
  context: { missingField: field },
@@ -328,19 +332,19 @@ export function deserializeWormhole(json) {
328
332
  }
329
333
  }
330
334
 
331
- if (typeof json.patchCount !== 'number' || json.patchCount < 0) {
335
+ if (typeof typedJson.patchCount !== 'number' || typedJson.patchCount < 0) {
332
336
  throw new WormholeError('Invalid wormhole JSON: patchCount must be a non-negative number', {
333
337
  code: 'E_INVALID_WORMHOLE_JSON',
334
- context: { patchCount: json.patchCount },
338
+ context: { patchCount: typedJson.patchCount },
335
339
  });
336
340
  }
337
341
 
338
342
  return {
339
- fromSha: json.fromSha,
340
- toSha: json.toSha,
341
- writerId: json.writerId,
342
- patchCount: json.patchCount,
343
- payload: ProvenancePayload.fromJSON(json.payload),
343
+ fromSha: typedJson.fromSha,
344
+ toSha: typedJson.toSha,
345
+ writerId: typedJson.writerId,
346
+ patchCount: typedJson.patchCount,
347
+ payload: ProvenancePayload.fromJSON(typedJson.payload),
344
348
  };
345
349
  }
346
350
 
@@ -67,11 +67,12 @@ function validateOp(op, index) {
67
67
  throw new Error(`ops[${index}] must be an object`);
68
68
  }
69
69
 
70
- validateOpType(op.op, index);
71
- validateOpTarget(op.target, index);
72
- validateOpResult(op.result, index);
70
+ const entry = /** @type {Record<string, *>} */ (op);
71
+ validateOpType(entry.op, index);
72
+ validateOpTarget(entry.target, index);
73
+ validateOpResult(entry.result, index);
73
74
 
74
- if (op.reason !== undefined && typeof op.reason !== 'string') {
75
+ if (entry.reason !== undefined && typeof entry.reason !== 'string') {
75
76
  throw new Error(`ops[${index}].reason must be a string or undefined`);
76
77
  }
77
78
  }
@@ -208,6 +209,7 @@ export function createTickReceipt({ patchSha, writer, lamport, ops }) {
208
209
  // Build frozen op copies (defensive: don't alias caller's objects)
209
210
  const frozenOps = Object.freeze(
210
211
  ops.map((o) => {
212
+ /** @type {{ op: string, target: string, result: 'applied' | 'superseded' | 'redundant', reason?: string }} */
211
213
  const entry = { op: o.op, target: o.target, result: o.result };
212
214
  if (o.reason !== undefined) {
213
215
  entry.reason = o.reason;
@@ -275,9 +277,11 @@ export function canonicalJson(receipt) {
275
277
  */
276
278
  function sortedReplacer(_key, value) {
277
279
  if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
280
+ /** @type {{ [x: string]: * }} */
278
281
  const sorted = {};
279
- for (const k of Object.keys(value).sort()) {
280
- sorted[k] = value[k];
282
+ const obj = /** @type {{ [x: string]: * }} */ (value);
283
+ for (const k of Object.keys(obj).sort()) {
284
+ sorted[k] = obj[k];
281
285
  }
282
286
  return sorted;
283
287
  }
@@ -25,9 +25,7 @@
25
25
 
26
26
  /**
27
27
  * Dot - causal identifier for an add operation
28
- * @typedef {Object} Dot
29
- * @property {string} writer - Writer ID that created this dot
30
- * @property {number} seq - Sequence number for this writer
28
+ * @typedef {import('../crdt/Dot.js').Dot} Dot
31
29
  */
32
30
 
33
31
  /**
@@ -182,6 +180,7 @@ export function createPropSetV2(node, key, value) {
182
180
  * @returns {PatchV2} PatchV2 object
183
181
  */
184
182
  export function createPatchV2({ schema = 2, writer, lamport, context, ops, reads, writes }) {
183
+ /** @type {PatchV2} */
185
184
  const patch = {
186
185
  schema,
187
186
  writer,
@@ -68,7 +68,7 @@ class CachedValue {
68
68
  */
69
69
  async get() {
70
70
  if (this._isValid()) {
71
- return this._value;
71
+ return /** @type {T} */ (this._value);
72
72
  }
73
73
 
74
74
  const value = await this._compute();
@@ -35,7 +35,7 @@ class LRUCache {
35
35
  return undefined;
36
36
  }
37
37
  // Move to end (most recently used) by deleting and re-inserting
38
- const value = this._cache.get(key);
38
+ const value = /** @type {V} */ (this._cache.get(key));
39
39
  this._cache.delete(key);
40
40
  this._cache.set(key, value);
41
41
  return value;
@@ -48,7 +48,7 @@ class LRUCache {
48
48
  *
49
49
  * @param {K} key - The key to set
50
50
  * @param {V} value - The value to cache
51
- * @returns {LRUCache} The cache instance for chaining
51
+ * @returns {LRUCache<K, V>} The cache instance for chaining
52
52
  */
53
53
  set(key, value) {
54
54
  // If key exists, delete it first so it moves to the end
@@ -61,7 +61,7 @@ class LRUCache {
61
61
 
62
62
  // Evict oldest entry if over capacity
63
63
  if (this._cache.size > this.maxSize) {
64
- const oldestKey = this._cache.keys().next().value;
64
+ const oldestKey = /** @type {K} */ (this._cache.keys().next().value);
65
65
  this._cache.delete(oldestKey);
66
66
  }
67
67
 
@@ -32,10 +32,10 @@ class MinHeap {
32
32
  */
33
33
  extractMin() {
34
34
  if (this.heap.length === 0) { return undefined; }
35
- if (this.heap.length === 1) { return this.heap.pop().item; }
35
+ if (this.heap.length === 1) { return /** @type {{item: *, priority: number}} */ (this.heap.pop()).item; }
36
36
 
37
37
  const min = this.heap[0];
38
- this.heap[0] = this.heap.pop();
38
+ this.heap[0] = /** @type {{item: *, priority: number}} */ (this.heap.pop());
39
39
  this._bubbleDown(0);
40
40
  return min.item;
41
41
  }
@@ -291,6 +291,25 @@ export function buildCursorSavedPrefix(graphName) {
291
291
  return `${REF_PREFIX}/${graphName}/cursor/saved/`;
292
292
  }
293
293
 
294
+ /**
295
+ * Builds the seek cache ref path for the given graph.
296
+ *
297
+ * The seek cache ref points to a blob containing a JSON index of
298
+ * cached materialization states, keyed by (ceiling, frontier) tuples.
299
+ *
300
+ * @param {string} graphName - The name of the graph
301
+ * @returns {string} The full ref path, e.g. `refs/warp/<graphName>/seek-cache`
302
+ * @throws {Error} If graphName is invalid
303
+ *
304
+ * @example
305
+ * buildSeekCacheRef('events');
306
+ * // => 'refs/warp/events/seek-cache'
307
+ */
308
+ export function buildSeekCacheRef(graphName) {
309
+ validateGraphName(graphName);
310
+ return `${REF_PREFIX}/${graphName}/seek-cache`;
311
+ }
312
+
294
313
  // -----------------------------------------------------------------------------
295
314
  // Parsers
296
315
  // -----------------------------------------------------------------------------
@@ -178,7 +178,7 @@ export async function resolveWriterId({ graphName, explicitWriterId, configGet,
178
178
  try {
179
179
  existing = await configGet(key);
180
180
  } catch (e) {
181
- throw new WriterIdError('CONFIG_READ_FAILED', `Failed to read git config key ${key}`, e);
181
+ throw new WriterIdError('CONFIG_READ_FAILED', `Failed to read git config key ${key}`, /** @type {Error|undefined} */ (e));
182
182
  }
183
183
 
184
184
  if (existing) {
@@ -198,7 +198,7 @@ export async function resolveWriterId({ graphName, explicitWriterId, configGet,
198
198
  try {
199
199
  await configSet(key, fresh);
200
200
  } catch (e) {
201
- throw new WriterIdError('CONFIG_WRITE_FAILED', `Failed to persist writerId to git config key ${key}`, e);
201
+ throw new WriterIdError('CONFIG_WRITE_FAILED', `Failed to persist writerId to git config key ${key}`, /** @type {Error|undefined} */ (e));
202
202
  }
203
203
 
204
204
  return fresh;
@@ -18,20 +18,27 @@ const encoder = new Encoder({
18
18
  mapsAsObjects: true,
19
19
  });
20
20
 
21
+ /**
22
+ * Recursively sorts object keys for deterministic CBOR encoding.
23
+ * @param {unknown} value - The value to sort keys of
24
+ * @returns {unknown} The value with sorted keys
25
+ */
21
26
  function sortKeys(value) {
22
27
  if (value === null || value === undefined) { return value; }
23
28
  if (Array.isArray(value)) { return value.map(sortKeys); }
24
29
  if (value instanceof Map) {
30
+ /** @type {Record<string, unknown>} */
25
31
  const sorted = {};
26
32
  for (const key of Array.from(value.keys()).sort()) {
27
33
  sorted[key] = sortKeys(value.get(key));
28
34
  }
29
35
  return sorted;
30
36
  }
31
- if (typeof value === 'object' && (value.constructor === Object || value.constructor === undefined)) {
37
+ if (typeof value === 'object' && (/** @type {Object} */ (value).constructor === Object || /** @type {Object} */ (value).constructor === undefined)) {
38
+ /** @type {Record<string, unknown>} */
32
39
  const sorted = {};
33
40
  for (const key of Object.keys(value).sort()) {
34
- sorted[key] = sortKeys(value[key]);
41
+ sorted[key] = sortKeys(/** @type {Record<string, unknown>} */ (value)[key]);
35
42
  }
36
43
  return sorted;
37
44
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Default crypto implementation for domain services.
3
+ *
4
+ * Provides SHA hashing, HMAC, and timing-safe comparison using
5
+ * node:crypto directly, avoiding concrete adapter imports from
6
+ * the infrastructure layer. This follows the same pattern as
7
+ * defaultCodec.js and defaultClock.js.
8
+ *
9
+ * Since git-warp requires Git (and therefore Node 22+, Deno, or Bun),
10
+ * node:crypto is always available.
11
+ *
12
+ * @module domain/utils/defaultCrypto
13
+ */
14
+
15
+ import {
16
+ createHash,
17
+ createHmac,
18
+ timingSafeEqual as nodeTimingSafeEqual,
19
+ } from 'node:crypto';
20
+
21
+ /** @type {import('../../ports/CryptoPort.js').default} */
22
+ const defaultCrypto = {
23
+ // eslint-disable-next-line @typescript-eslint/require-await -- async matches CryptoPort contract
24
+ async hash(algorithm, data) {
25
+ return createHash(algorithm).update(data).digest('hex');
26
+ },
27
+ // eslint-disable-next-line @typescript-eslint/require-await -- async matches CryptoPort contract
28
+ async hmac(algorithm, key, data) {
29
+ return createHmac(algorithm, key).update(data).digest();
30
+ },
31
+ timingSafeEqual(a, b) {
32
+ return nodeTimingSafeEqual(a, b);
33
+ },
34
+ };
35
+
36
+ export default defaultCrypto;
@@ -32,7 +32,7 @@ const NOT_CHECKED = Symbol('NOT_CHECKED');
32
32
 
33
33
  /**
34
34
  * Cached reference to the loaded roaring module.
35
- * @type {Object|null}
35
+ * @type {any} // TODO(ts-cleanup): type lazy singleton
36
36
  * @private
37
37
  */
38
38
  let roaringModule = null;
@@ -51,7 +51,7 @@ let nativeAvailability = NOT_CHECKED;
51
51
  * Uses a top-level-await-friendly pattern with dynamic import.
52
52
  * The module is cached after first load.
53
53
  *
54
- * @returns {Object} The roaring module exports
54
+ * @returns {any} The roaring module exports
55
55
  * @throws {Error} If the roaring package is not installed or fails to load
56
56
  * @private
57
57
  */
@@ -151,7 +151,7 @@ export function getRoaringBitmap32() {
151
151
  */
152
152
  export function getNativeRoaringAvailable() {
153
153
  if (nativeAvailability !== NOT_CHECKED) {
154
- return nativeAvailability;
154
+ return /** @type {boolean|null} */ (nativeAvailability);
155
155
  }
156
156
 
157
157
  try {
@@ -161,13 +161,13 @@ export function getNativeRoaringAvailable() {
161
161
  // Try the method-based API first (roaring >= 2.x)
162
162
  if (typeof RoaringBitmap32.isNativelyInstalled === 'function') {
163
163
  nativeAvailability = RoaringBitmap32.isNativelyInstalled();
164
- return nativeAvailability;
164
+ return /** @type {boolean|null} */ (nativeAvailability);
165
165
  }
166
166
 
167
167
  // Fall back to property-based API (roaring 1.x)
168
168
  if (roaring.isNativelyInstalled !== undefined) {
169
169
  nativeAvailability = roaring.isNativelyInstalled;
170
- return nativeAvailability;
170
+ return /** @type {boolean|null} */ (nativeAvailability);
171
171
  }
172
172
 
173
173
  // Could not determine - leave as null (indeterminate)
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Deterministic cache key for seek materialization cache.
3
+ *
4
+ * Key format: `v1:t<ceiling>-<frontierHash>`
5
+ * where frontierHash = hex SHA-256 of sorted writerId:tipSha pairs.
6
+ *
7
+ * The `v1` prefix ensures future schema/codec changes produce distinct keys
8
+ * without needing to flush existing caches.
9
+ *
10
+ * @module domain/utils/seekCacheKey
11
+ */
12
+
13
+ import { createHash } from 'node:crypto';
14
+
15
+ const KEY_VERSION = 'v1';
16
+
17
+ /**
18
+ * Builds a deterministic, collision-resistant cache key from a ceiling tick
19
+ * and writer frontier snapshot.
20
+ *
21
+ * @param {number} ceiling - Lamport ceiling tick
22
+ * @param {Map<string, string>} frontier - Map of writerId → tip SHA
23
+ * @returns {string} Cache key, e.g. `v1:t42-a1b2c3d4...` (32+ hex chars in hash)
24
+ */
25
+ export function buildSeekCacheKey(ceiling, frontier) {
26
+ const sorted = [...frontier.entries()].sort((a, b) =>
27
+ a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0
28
+ );
29
+ const payload = sorted.map(([w, sha]) => `${w}:${sha}`).join('\n');
30
+ const hash = createHash('sha256').update(payload).digest('hex');
31
+ return `${KEY_VERSION}:t${ceiling}-${hash}`;
32
+ }
@@ -21,7 +21,7 @@ export class PatchSession {
21
21
  *
22
22
  * @param {Object} options
23
23
  * @param {import('../services/PatchBuilderV2.js').PatchBuilderV2} options.builder - Internal builder
24
- * @param {import('../../ports/GraphPersistencePort.js').default} options.persistence - Git adapter
24
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/RefPort.js').default} options.persistence - Git adapter
25
25
  * @param {string} options.graphName - Graph namespace
26
26
  * @param {string} options.writerId - Writer ID
27
27
  * @param {string|null} options.expectedOldHead - Expected parent SHA for CAS
@@ -30,7 +30,7 @@ export class PatchSession {
30
30
  /** @type {import('../services/PatchBuilderV2.js').PatchBuilderV2} */
31
31
  this._builder = builder;
32
32
 
33
- /** @type {import('../../ports/GraphPersistencePort.js').default} */
33
+ /** @type {import('../../ports/GraphPersistencePort.js').default & import('../../ports/RefPort.js').default} */
34
34
  this._persistence = persistence;
35
35
 
36
36
  /** @type {string} */
@@ -176,7 +176,7 @@ export class PatchSession {
176
176
  const sha = await this._builder.commit();
177
177
  this._committed = true;
178
178
  return sha;
179
- } catch (err) {
179
+ } catch (/** @type {any} */ err) { // TODO(ts-cleanup): type error
180
180
  // Check if it's a concurrent commit error from PatchBuilderV2
181
181
  if (err.message?.includes('Concurrent commit detected') ||
182
182
  err.message?.includes('has advanced')) {
@@ -36,7 +36,7 @@ export class Writer {
36
36
  * Creates a new Writer instance.
37
37
  *
38
38
  * @param {Object} options
39
- * @param {import('../../ports/GraphPersistencePort.js').default} options.persistence - Git adapter
39
+ * @param {import('../../ports/GraphPersistencePort.js').default & import('../../ports/RefPort.js').default & import('../../ports/CommitPort.js').default} options.persistence - Git adapter
40
40
  * @param {string} options.graphName - Graph namespace
41
41
  * @param {string} options.writerId - This writer's ID
42
42
  * @param {import('../crdt/VersionVector.js').VersionVector} options.versionVector - Current version vector
@@ -48,7 +48,7 @@ export class Writer {
48
48
  constructor({ persistence, graphName, writerId, versionVector, getCurrentState, onCommitSuccess, onDeleteWithData = 'warn', codec }) {
49
49
  validateWriterId(writerId);
50
50
 
51
- /** @type {import('../../ports/GraphPersistencePort.js').default} */
51
+ /** @type {import('../../ports/GraphPersistencePort.js').default & import('../../ports/RefPort.js').default & import('../../ports/CommitPort.js').default} */
52
52
  this._persistence = persistence;
53
53
 
54
54
  /** @type {string} */
@@ -50,9 +50,10 @@ async function readStreamBody(bodyStream) {
50
50
  * HttpServerPort request handlers.
51
51
  *
52
52
  * @param {Request} request - Bun fetch Request
53
- * @returns {Promise<{ method: string, url: string, headers: Object, body: Buffer|undefined }>}
53
+ * @returns {Promise<{ method: string, url: string, headers: Record<string, string>, body: Uint8Array|undefined }>}
54
54
  */
55
55
  async function toPortRequest(request) {
56
+ /** @type {Record<string, string>} */
56
57
  const headers = {};
57
58
  request.headers.forEach((value, key) => {
58
59
  headers[key] = value;
@@ -81,11 +82,11 @@ async function toPortRequest(request) {
81
82
  /**
82
83
  * Converts a plain-object port response into a Bun Response.
83
84
  *
84
- * @param {{ status?: number, headers?: Object, body?: string|Uint8Array }} portResponse
85
+ * @param {{ status?: number, headers?: Record<string, string>, body?: string|Uint8Array|null }} portResponse
85
86
  * @returns {Response}
86
87
  */
87
88
  function toResponse(portResponse) {
88
- return new Response(portResponse.body ?? null, {
89
+ return new Response(/** @type {BodyInit | null} */ (portResponse.body ?? null), {
89
90
  status: portResponse.status || 200,
90
91
  headers: portResponse.headers || {},
91
92
  });
@@ -105,7 +106,7 @@ function createFetchHandler(requestHandler, logger) {
105
106
  const portReq = await toPortRequest(request);
106
107
  const portRes = await requestHandler(portReq);
107
108
  return toResponse(portRes);
108
- } catch (err) {
109
+ } catch (/** @type {*} */ err) { // TODO(ts-cleanup): type error
109
110
  if (err.status === 413) {
110
111
  return new Response(PAYLOAD_TOO_LARGE, {
111
112
  status: 413,
@@ -131,11 +132,12 @@ function createFetchHandler(requestHandler, logger) {
131
132
  * Note: Bun.serve() is synchronous, so cb fires on the same tick
132
133
  * (unlike Node's server.listen which defers via the event loop).
133
134
  *
134
- * @param {{ port: number, hostname?: string, fetch: Function }} serveOptions
135
+ * @param {*} serveOptions
135
136
  * @param {Function|undefined} cb - Node-style callback
136
- * @returns {Object} The Bun server instance
137
+ * @returns {*} The Bun server instance
137
138
  */
138
139
  function startServer(serveOptions, cb) {
140
+ // @ts-expect-error — Bun global is only available in Bun runtime
139
141
  const server = globalThis.Bun.serve(serveOptions);
140
142
  if (cb) {
141
143
  cb(null);
@@ -146,7 +148,7 @@ function startServer(serveOptions, cb) {
146
148
  /**
147
149
  * Safely stops a Bun server, forwarding errors to the callback.
148
150
  *
149
- * @param {{ server: Object|null }} state - Shared mutable state
151
+ * @param {{ server: * }} state - Shared mutable state
150
152
  * @param {Function} [callback]
151
153
  */
152
154
  function stopServer(state, callback) {
@@ -184,15 +186,25 @@ export default class BunHttpAdapter extends HttpServerPort {
184
186
  this._logger = logger || noopLogger;
185
187
  }
186
188
 
187
- /** @inheritdoc */
189
+ /**
190
+ * @param {Function} requestHandler
191
+ * @returns {{ listen: Function, close: Function, address: Function }}
192
+ */
188
193
  createServer(requestHandler) {
189
194
  const fetchHandler = createFetchHandler(requestHandler, this._logger);
195
+ /** @type {{ server: * }} */
190
196
  const state = { server: null };
191
197
 
192
198
  return {
199
+ /**
200
+ * @param {number} port
201
+ * @param {string|Function} [host]
202
+ * @param {Function} [callback]
203
+ */
193
204
  listen(port, host, callback) {
194
205
  const cb = typeof host === 'function' ? host : callback;
195
206
  const bindHost = typeof host === 'string' ? host : undefined;
207
+ /** @type {*} */ // TODO(ts-cleanup): type Bun.serve options
196
208
  const serveOptions = { port, fetch: fetchHandler };
197
209
 
198
210
  if (bindHost !== undefined) {
@@ -208,6 +220,7 @@ export default class BunHttpAdapter extends HttpServerPort {
208
220
  }
209
221
  },
210
222
 
223
+ /** @param {Function} [callback] */
211
224
  close: (callback) => stopServer(state, callback),
212
225
 
213
226
  address() {