@draht/chord 2026.10.31 → 2026.11.5-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.
Files changed (70) hide show
  1. package/dist/cell.d.ts +7 -7
  2. package/dist/cell.d.ts.map +1 -1
  3. package/dist/cell.js.map +1 -1
  4. package/dist/context/index.d.ts +1 -1
  5. package/dist/context/index.d.ts.map +1 -1
  6. package/dist/context/index.js +1 -1
  7. package/dist/context/index.js.map +1 -1
  8. package/dist/contract.d.ts +51 -52
  9. package/dist/contract.d.ts.map +1 -1
  10. package/dist/contract.js +19 -24
  11. package/dist/contract.js.map +1 -1
  12. package/dist/delta/apply-immutable-trusted.js +3 -4
  13. package/dist/delta/apply-immutable-trusted.js.map +1 -1
  14. package/dist/delta/diff.d.ts.map +1 -1
  15. package/dist/delta/diff.js +5 -3
  16. package/dist/delta/diff.js.map +1 -1
  17. package/dist/delta/index.d.ts +9 -1
  18. package/dist/delta/index.d.ts.map +1 -1
  19. package/dist/delta/index.js +15 -11
  20. package/dist/delta/index.js.map +1 -1
  21. package/dist/delta/pending.d.ts +36 -0
  22. package/dist/delta/pending.d.ts.map +1 -0
  23. package/dist/delta/pending.js +143 -0
  24. package/dist/delta/pending.js.map +1 -0
  25. package/dist/delta/tracker.d.ts +12 -0
  26. package/dist/delta/tracker.d.ts.map +1 -1
  27. package/dist/delta/tracker.js +109 -39
  28. package/dist/delta/tracker.js.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/object.d.ts +4 -4
  34. package/dist/object.d.ts.map +1 -1
  35. package/dist/object.js +3 -4
  36. package/dist/object.js.map +1 -1
  37. package/dist/output.d.ts +1 -1
  38. package/dist/output.d.ts.map +1 -1
  39. package/dist/output.js +4 -2
  40. package/dist/output.js.map +1 -1
  41. package/dist/remote.d.ts.map +1 -1
  42. package/dist/remote.js +2 -2
  43. package/dist/remote.js.map +1 -1
  44. package/dist/schema.d.ts +8 -4
  45. package/dist/schema.d.ts.map +1 -1
  46. package/dist/schema.js +180 -5
  47. package/dist/schema.js.map +1 -1
  48. package/dist/sqlite/cloudflare.d.ts +2 -0
  49. package/dist/sqlite/cloudflare.d.ts.map +1 -1
  50. package/dist/sqlite/cloudflare.js +10 -0
  51. package/dist/sqlite/cloudflare.js.map +1 -1
  52. package/dist/sqlite/database.d.ts +5 -2
  53. package/dist/sqlite/database.d.ts.map +1 -1
  54. package/dist/sqlite/database.js.map +1 -1
  55. package/dist/sqlite/node.d.ts +4 -1
  56. package/dist/sqlite/node.d.ts.map +1 -1
  57. package/dist/sqlite/node.js +22 -5
  58. package/dist/sqlite/node.js.map +1 -1
  59. package/dist/watch.d.ts +194 -0
  60. package/dist/watch.d.ts.map +1 -0
  61. package/dist/watch.js +383 -0
  62. package/dist/watch.js.map +1 -0
  63. package/dist/wire.d.ts +174 -193
  64. package/dist/wire.d.ts.map +1 -1
  65. package/dist/wire.js +81 -80
  66. package/dist/wire.js.map +1 -1
  67. package/docs/guide.md +15 -15
  68. package/docs/spec.md +8 -8
  69. package/docs/tutorial.md +26 -25
  70. package/package.json +4 -5
@@ -1,6 +1,6 @@
1
1
  import { copyJson } from "../json.js";
2
2
  import { applyImmutableTrusted } from "./apply-immutable-trusted.js";
3
- import { applyImmutable, overlap, RESERVED_SEGMENTS } from "./index.js";
3
+ import { applyImmutable, overlap, ownedSlice, RESERVED_SEGMENTS, } from "./index.js";
4
4
  const NODE = Symbol("chord.delta.overlay.node");
5
5
  const PREPARED = new WeakMap();
6
6
  const RELEASED = {};
@@ -91,9 +91,20 @@ class ChangeImpl {
91
91
  this.#context = undefined;
92
92
  }
93
93
  }
94
+ /**
95
+ * Open drafts are tracked so that adopting one change makes its open competitors stale at once. Prepared contexts need
96
+ * no tracking: `prepare()` releases their overlay, and `adopt()` rejects them by revision.
97
+ *
98
+ * The most recent open context is held strongly in `#open`: with one transaction at a time per tracker, the common case,
99
+ * that is the only one, and it costs no `WeakRef` (each `WeakRef` target survives the scavenges of the current job, and
100
+ * V8 then pretenures the context allocation site). A second `beginChange()` while one is open moves the older context
101
+ * into `#competitors` through a `WeakRef`, so a draft the caller drops can be collected. A dropped draft that was never
102
+ * settled stays held by `#open` until the tracker's next `beginChange()` or `adopt()`: at most one per tracker.
103
+ */
94
104
  class TrackerImpl {
95
105
  #owner = {};
96
- #contexts = new Set();
106
+ #open;
107
+ #competitors;
97
108
  #selfRef;
98
109
  #value;
99
110
  #revision = 0;
@@ -110,13 +121,15 @@ class TrackerImpl {
110
121
  }
111
122
  beginChange() {
112
123
  const context = createContext(this.#selfRef, this.#owner, this.#revision, this.#value, false, this.#value);
113
- this.#register(context);
124
+ if (this.#open !== undefined)
125
+ this.#demote(this.#open);
126
+ this.#open = context;
114
127
  return new ChangeImpl(context);
115
128
  }
116
129
  prepareReplace(value) {
130
+ // Not tracked: materialization below releases the context before this returns, as `prepare()` does.
117
131
  const context = createContext(this.#selfRef, this.#owner, this.#revision, value, true, this.#value);
118
132
  context.status.value = "prepared";
119
- this.#register(context);
120
133
  try {
121
134
  return materializePrepared(context);
122
135
  }
@@ -155,49 +168,90 @@ class TrackerImpl {
155
168
  this.#invalidate(context);
156
169
  }
157
170
  releaseContext(context) {
158
- if (context.registryRef !== undefined)
159
- this.#contexts.delete(context.registryRef);
171
+ if (this.#open === context)
172
+ this.#open = undefined;
173
+ else if (context.registryRef !== undefined)
174
+ this.#competitors?.delete(context.registryRef);
160
175
  context.registryRef = undefined;
161
176
  }
162
- #register(context) {
177
+ #demote(context) {
163
178
  const reference = new WeakRef(context);
164
179
  context.registryRef = reference;
165
- this.#contexts.add(reference);
180
+ this.#competitors ??= new Set();
181
+ this.#competitors.add(reference);
166
182
  this.#pruneBudget -= 1;
167
183
  if (this.#pruneBudget === 0) {
168
- this.#prune();
169
- this.#pruneBudget = Math.max(256, this.#contexts.size);
170
- }
171
- }
172
- #prune() {
173
- for (const reference of this.#contexts) {
174
- if (reference.deref() === undefined)
175
- this.#contexts.delete(reference);
184
+ for (const entry of this.#competitors) {
185
+ if (entry.deref() === undefined)
186
+ this.#competitors.delete(entry);
187
+ }
188
+ this.#pruneBudget = Math.max(256, this.#competitors.size);
176
189
  }
177
190
  }
178
191
  #invalidate(winner) {
179
- for (const reference of this.#contexts) {
192
+ const open = this.#open;
193
+ const competitors = this.#competitors;
194
+ this.#open = undefined;
195
+ this.#competitors = undefined;
196
+ this.#pruneBudget = 256;
197
+ if (open !== undefined)
198
+ staleCompetitor(open, winner);
199
+ if (competitors === undefined)
200
+ return;
201
+ for (const reference of competitors) {
180
202
  const context = reference.deref();
181
- if (context === undefined || context === winner)
182
- continue;
183
- if (context.status.value === "open" || context.status.value === "prepared")
184
- context.status.value = "stale";
185
- // Adoption must not walk every node touched by a competing draft. Drop the
186
- // context's strong overlay references in O(1); externally retained proxies
187
- // still see the stale status and are reclaimed with their holders.
188
- releaseOverlayReferences(context);
203
+ if (context !== undefined)
204
+ staleCompetitor(context, winner);
189
205
  }
190
- this.#contexts.clear();
191
- this.#pruneBudget = 256;
192
206
  }
193
207
  replacementBase(context) {
194
208
  return context.baseRevision === this.#revision ? this.#value : undefined;
195
209
  }
196
210
  }
211
+ function staleCompetitor(context, winner) {
212
+ if (context === winner)
213
+ return;
214
+ if (context.status.value === "open" || context.status.value === "prepared")
215
+ context.status.value = "stale";
216
+ // Adoption must not walk every node touched by a competing draft. Drop the
217
+ // context's strong overlay references in O(1); externally retained proxies
218
+ // still see the stale status and are reclaimed with their holders.
219
+ context.registryRef = undefined;
220
+ releaseOverlayReferences(context);
221
+ }
197
222
  /** Take immutable ownership of an alias-free strict-JSON root in O(1). */
198
223
  export function track(initial) {
199
224
  return new TrackerImpl(initial);
200
225
  }
226
+ /**
227
+ * Append `text` to the string at `draft[key]`, costing O(text.length). The change is recorded as one append op
228
+ * (several appends to the same key in one change join into one op) without comparing the old and new strings. A plain
229
+ * assignment such as `draft[key] += text` gives the same op, but `prepare()` then has to check that the new string
230
+ * extends the old one, which reads the whole string: O(length) per change. A plain assignment or deletion of the key in
231
+ * the same change falls back to that check.
232
+ */
233
+ export function appendText(draft, key, text) {
234
+ // Trust boundary: JavaScript callers can pass any object and key; the types cover TypeScript callers.
235
+ const node = draft[NODE];
236
+ if (node === undefined)
237
+ throw new TypeError("appendText() needs a draft");
238
+ assertWritable(node.context);
239
+ const name = String(key);
240
+ const current = Array.isArray(nodeBase(node)) || !objectHas(node, name) ? undefined : objectValue(node, name);
241
+ if (typeof current !== "string")
242
+ throw new TypeError(`appendText() needs a string at ${JSON.stringify(name)}`);
243
+ if (text.length === 0)
244
+ return;
245
+ // The op and the new value keep the text; a copy, so they never keep a larger string the caller cut it from alive.
246
+ const owned = ownedSlice(text, 0);
247
+ const appended = node.appends?.get(name) ?? (hasObjectWrite(node, name) ? undefined : "");
248
+ setObjectWrite(node, name, current + owned);
249
+ markDirty(node);
250
+ if (appended !== undefined) {
251
+ node.appends ??= new Map();
252
+ node.appends.set(name, appended + owned);
253
+ }
254
+ }
201
255
  function materializePrepared(context) {
202
256
  const operations = ensureOperations(context);
203
257
  const base = context.baseValue;
@@ -232,10 +286,10 @@ function createContext(tracker, owner, baseRevision, root, replacement, base) {
232
286
  status: { value: "open" },
233
287
  root: undefined,
234
288
  bases: [],
235
- stored: [],
289
+ stored: undefined,
236
290
  dirty: [],
237
291
  nodes: [],
238
- rawNodes: new WeakMap(),
292
+ rawNodes: undefined,
239
293
  ops: undefined,
240
294
  replacement,
241
295
  replacementNoop: false,
@@ -298,7 +352,7 @@ const sharedObjectHandler = {
298
352
  };
299
353
  const sharedArrayHandler = sharedObjectHandler;
300
354
  function createNode(context, base, parent, parentKind = 0, parentKey = "", parentSource = undefined, parentPlacement = false) {
301
- const existing = context.rawNodes.get(base);
355
+ const existing = context.rawNodes?.get(base);
302
356
  if (existing !== undefined)
303
357
  return existing;
304
358
  const target = Array.isArray(base) ? [] : {};
@@ -319,7 +373,12 @@ function createNode(context, base, parent, parentKind = 0, parentKey = "", paren
319
373
  node.parentSource = parentSource;
320
374
  target[NODE] = node;
321
375
  node.proxy = new Proxy(target, Array.isArray(base) ? sharedArrayHandler : sharedObjectHandler);
322
- context.rawNodes.set(base, node);
376
+ // The root is never reached again through a child value (tracked values are alias-free), so a change that touches
377
+ // only the root needs no map.
378
+ if (parent !== undefined) {
379
+ context.rawNodes ??= new WeakMap();
380
+ context.rawNodes.set(base, node);
381
+ }
323
382
  context.nodes.push(node);
324
383
  return node;
325
384
  }
@@ -332,6 +391,8 @@ function nodeParent(node) {
332
391
  function storeValue(context, value) {
333
392
  if (!isContainer(value))
334
393
  return value;
394
+ // Created on the first container write: primitive writes never store.
395
+ context.stored ??= [];
335
396
  const index = context.stored.length;
336
397
  context.stored.push(value);
337
398
  return { index };
@@ -438,6 +499,7 @@ function setProperty(node, property, supplied) {
438
499
  const wasDeleted = isObjectDeleted(node, key);
439
500
  if (!wasDeleted && !isContainer(stored) && current === stored)
440
501
  return true;
502
+ node.appends?.delete(key);
441
503
  setObjectWrite(node, key, stored);
442
504
  if (wasDeleted && Object.hasOwn(nodeBase(node), key)) {
443
505
  if (node.readded === undefined)
@@ -457,6 +519,7 @@ function deleteProperty(node, property) {
457
519
  const key = String(property);
458
520
  if (!objectHas(node, key))
459
521
  return true;
522
+ node.appends?.delete(key);
460
523
  deleteObjectWrite(node, key);
461
524
  node.readded?.delete(key);
462
525
  setObjectDeletion(node, key);
@@ -930,13 +993,14 @@ function insertPiece(node, items, start = 0) {
930
993
  function insertPlacementPiece(node, values, start = 0) {
931
994
  if (values.length === start)
932
995
  return [];
933
- const storedLength = node.context.stored.length;
996
+ const storedLength = node.context.stored?.length ?? 0;
934
997
  try {
935
998
  for (let index = start; index < values.length; index++)
936
999
  values[index] = storeValue(node.context, clonePlacement(values[index]));
937
1000
  }
938
1001
  catch (error) {
939
- node.context.stored.length = storedLength;
1002
+ if (node.context.stored !== undefined)
1003
+ node.context.stored.length = storedLength;
940
1004
  throw error;
941
1005
  }
942
1006
  return [
@@ -1396,7 +1460,7 @@ function cloneNode(node) {
1396
1460
  function cloneStored(value, context) {
1397
1461
  if (!isContainer(value))
1398
1462
  return value;
1399
- const node = context.rawNodes.get(value);
1463
+ const node = context.rawNodes?.get(value);
1400
1464
  return node === undefined || (!node.dirty && !node.subtreeDirty) ? value : cloneNode(node);
1401
1465
  }
1402
1466
  function clonePlacementNode(node) {
@@ -1420,7 +1484,7 @@ function clonePlacementNode(node) {
1420
1484
  function clonePlacementStored(value, context) {
1421
1485
  if (!isContainer(value))
1422
1486
  return copyJson(value);
1423
- const node = context.rawNodes.get(value);
1487
+ const node = context.rawNodes?.get(value);
1424
1488
  return node === undefined ? copyJson(value) : clonePlacementNode(node);
1425
1489
  }
1426
1490
  function defineData(target, key, value) {
@@ -1696,6 +1760,11 @@ function hasPlacementAncestor(node) {
1696
1760
  }
1697
1761
  function emitObjectWrite(node, path, operations, key, value) {
1698
1762
  const nextPath = [...path, key];
1763
+ const appended = node.appends?.get(key);
1764
+ if (appended !== undefined) {
1765
+ operations.push(["a", nextPath, appended]);
1766
+ return false;
1767
+ }
1699
1768
  const before = node.readded?.has(key) || !Object.hasOwn(nodeBase(node), key)
1700
1769
  ? undefined
1701
1770
  : nodeBase(node)[key];
@@ -1895,17 +1964,18 @@ function emitChangedValue(operations, path, before, after) {
1895
1964
  if (isContainer(before) && isContainer(after) && equalTrustedJson(before, after))
1896
1965
  return false;
1897
1966
  if (typeof before === "string" && typeof after === "string") {
1898
- // Slice/equality stays on V8's rope fast path; startsWith scans the entire
1899
- // accumulated prefix on every append.
1967
+ // O(length): any slice of a rope makes V8 flatten all of it, so this prefix check copies the whole string once per
1968
+ // change, even when the writer only appended. Streaming writers use appendText(), which skips it. The op text gets
1969
+ // a copy of its own, so it does not keep the whole of `after` alive.
1900
1970
  if (after.length > before.length && after.slice(0, before.length) === before) {
1901
- operations.push(["a", path, after.slice(before.length)]);
1971
+ operations.push(["a", path, ownedSlice(after, before.length)]);
1902
1972
  return true;
1903
1973
  }
1904
1974
  const shared = overlap(before, after, 65_536);
1905
1975
  if (shared > 0) {
1906
1976
  operations.push(["t", path, before.length - shared]);
1907
1977
  if (after.length > shared)
1908
- operations.push(["a", path, after.slice(shared)]);
1978
+ operations.push(["a", path, ownedSlice(after, shared)]);
1909
1979
  return true;
1910
1980
  }
1911
1981
  }