doxum 0.1.28 → 0.1.30

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 (39) hide show
  1. package/README.md +3 -2
  2. package/dist/advanced.cjs +1 -1
  3. package/dist/advanced.js +1 -1
  4. package/dist/{driver-B5vdPohL.js → driver-B7RR-VfX.js} +31 -12
  5. package/dist/driver-B7RR-VfX.js.map +1 -0
  6. package/dist/{driver-BL91gn7_.cjs → driver-CN3dGxQI.cjs} +31 -12
  7. package/dist/driver-CN3dGxQI.cjs.map +1 -0
  8. package/dist/index.cjs +206 -133
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.js +206 -133
  11. package/dist/index.js.map +1 -1
  12. package/dist/local-sync.cjs +1 -1
  13. package/dist/local-sync.js +1 -1
  14. package/dist/{transform-DUleAsG0.cjs → transform-B6YxfR0R.cjs} +176 -50
  15. package/dist/transform-B6YxfR0R.cjs.map +1 -0
  16. package/dist/{transform-B4T3AcJr.js → transform-BQY9I6il.js} +147 -51
  17. package/dist/transform-BQY9I6il.js.map +1 -0
  18. package/package.json +3 -2
  19. package/skills/doxum-runtime/SKILL.md +64 -82
  20. package/skills/doxum-runtime/agents/openai.yaml +2 -2
  21. package/skills/doxum-runtime/references/document-runtime.md +370 -0
  22. package/skills/doxum-runtime/references/integrations.md +215 -0
  23. package/skills/doxum-runtime/references/{invariants.en.md → invariants.md} +5 -2
  24. package/skills/doxum-runtime/references/projections.md +467 -0
  25. package/skills/doxum-runtime/references/public-api.md +623 -0
  26. package/skills/doxum-runtime/references/recipes.md +493 -0
  27. package/dist/driver-B5vdPohL.js.map +0 -1
  28. package/dist/driver-BL91gn7_.cjs.map +0 -1
  29. package/dist/transform-B4T3AcJr.js.map +0 -1
  30. package/dist/transform-DUleAsG0.cjs.map +0 -1
  31. package/skills/doxum-runtime/references/api.en.md +0 -283
  32. package/skills/doxum-runtime/references/api.zh-CN.md +0 -276
  33. package/skills/doxum-runtime/references/guide.en.md +0 -138
  34. package/skills/doxum-runtime/references/guide.zh-CN.md +0 -116
  35. package/skills/doxum-runtime/references/invariants.zh-CN.md +0 -53
  36. package/skills/doxum-runtime/references/patterns.en.md +0 -162
  37. package/skills/doxum-runtime/references/patterns.zh-CN.md +0 -159
  38. package/skills/doxum-runtime/references/projections.en.md +0 -313
  39. package/skills/doxum-runtime/references/projections.zh-CN.md +0 -306
@@ -0,0 +1,493 @@
1
+ # Doxum Recipes
2
+
3
+ These are end-to-end public-API patterns. Adapt names and domain types; keep ownership and lifecycle semantics intact. Exact signatures live in [Public API](public-api.md).
4
+
5
+ ## Canonical document with dynamic entities
6
+
7
+ ```ts
8
+ import { createDocument, field, map, object, read, snapshot, type Infer } from 'doxum';
9
+
10
+ const task = object({
11
+ title: field<string>(),
12
+ done: field<boolean>(),
13
+ });
14
+
15
+ export const model = object({
16
+ tasks: map(task),
17
+ });
18
+
19
+ export type DocumentValue = Infer<typeof model>;
20
+
21
+ const document = createDocument({
22
+ schema: model,
23
+ initial: {
24
+ tasks: {
25
+ a: { title: 'Write', done: false },
26
+ },
27
+ },
28
+ });
29
+
30
+ document.update(draft => {
31
+ const task = draft.tasks.get('a');
32
+ if (task) task.done = true;
33
+ draft.tasks.put('b', { title: 'Review', done: false });
34
+ });
35
+
36
+ const done = read(document, value => value.tasks.get('a')?.done);
37
+ const durableTasks = read(document, value => snapshot(value.tasks));
38
+ ```
39
+
40
+ Use `object` for addressable structure, `map` for dynamic membership, and `field` for atomic payloads.
41
+
42
+ ## Atomic payload versus addressable structure
43
+
44
+ ```ts
45
+ const position = object({
46
+ x: field<number>(),
47
+ y: field<number>(),
48
+ });
49
+
50
+ const model = object({
51
+ position,
52
+ stroke: field<readonly { x: number; y: number }[]>(),
53
+ rows: list(field<{ id: string; label: string }>(), {
54
+ keyOf: row => row.id,
55
+ }),
56
+ });
57
+ ```
58
+
59
+ Mutate `position.x` independently. Replace `stroke` whole. Edit `rows` through keyed list methods.
60
+
61
+ ## Replace a nested member that contains collections
62
+
63
+ ```ts
64
+ import { createDocument, field, map, object, replace, table } from 'doxum';
65
+
66
+ const model = object({
67
+ entries: map(
68
+ object({
69
+ rows: table(object({ title: field<string>() })),
70
+ })
71
+ ),
72
+ });
73
+
74
+ const document = createDocument({
75
+ schema: model,
76
+ initial: {
77
+ entries: {
78
+ a: {
79
+ rows: {
80
+ ids: ['x'],
81
+ byId: { x: { title: 'First' } },
82
+ },
83
+ },
84
+ },
85
+ },
86
+ });
87
+
88
+ document.update(draft => {
89
+ const entry = draft.entries.get('a')!;
90
+ replace(entry, 'rows', {
91
+ ids: ['y'],
92
+ byId: { y: { title: 'Replacement' } },
93
+ });
94
+ });
95
+ ```
96
+
97
+ Use top-level `replace(parent,key,value)` for object/variant members whose Draft representation contains collection tools. Use a collection's own `replace(next)` when the collection itself is the mutation target.
98
+
99
+ ## Branded domain keys
100
+
101
+ ```ts
102
+ type PersonId = string & { readonly __person: unique symbol };
103
+
104
+ const personId = (value: unknown): value is PersonId =>
105
+ typeof value === 'string' && value.startsWith('person:');
106
+
107
+ const model = object({
108
+ people: map(object({ name: field<string>() }), { key: personId }),
109
+ });
110
+
111
+ const initial = parse(model, {
112
+ people: {
113
+ 'person:1': { name: 'Ada' },
114
+ },
115
+ });
116
+ ```
117
+
118
+ The branded key type flows through map/table methods, typed paths, impact, `observe`, and keyed projections.
119
+
120
+ ## Ordered table edits
121
+
122
+ ```ts
123
+ document.update(draft => {
124
+ draft.rows.create('c', { title: 'C' }, { after: 'b' });
125
+ draft.rows.move(['a', 'c'], { at: 'start' });
126
+ draft.rows.replace('b', { title: 'Updated B' });
127
+ });
128
+ ```
129
+
130
+ A multi-key move preserves the selected members' current relative order. `reorder(ids)` is for an exact full-membership permutation.
131
+
132
+ ## Ordered list edits
133
+
134
+ ```ts
135
+ const rows = list(field<{ id: string; label: string }>(), {
136
+ keyOf: row => row.id,
137
+ });
138
+
139
+ document.update(draft => {
140
+ draft.rows.insert({ id: 'c', label: 'C' }, { at: 'start' });
141
+ draft.rows.move('c', { after: 'a' });
142
+ draft.rows.replace('a', { id: 'a', label: 'A+' });
143
+ });
144
+ ```
145
+
146
+ Member replacement keeps the addressed stable key.
147
+
148
+ ## Tree edits
149
+
150
+ ```ts
151
+ const model = object({
152
+ outline: tree(field<{ title: string }>()),
153
+ });
154
+
155
+ document.update(draft => {
156
+ draft.outline.insert('root', { title: 'Root' });
157
+ draft.outline.insert('child', { title: 'Child' }, { parentId: 'root', index: 0 });
158
+ draft.outline.move('child', { index: 0 });
159
+ draft.outline.replace('child', { title: 'Renamed' });
160
+ });
161
+ ```
162
+
163
+ Use tree operations for topology. Never manually patch `rootId`, `parentId`, or `children` records.
164
+
165
+ ## Expected transaction rejection
166
+
167
+ ```ts
168
+ const result = document.update(draft => {
169
+ const row = draft.rows.get(id);
170
+ if (!row) {
171
+ throw new TransactionRejected({
172
+ code: 'missing-row',
173
+ message: 'Row does not exist',
174
+ });
175
+ }
176
+ row.title = title;
177
+ });
178
+
179
+ if (result.status === 'rejected') {
180
+ showIssues(result.issues);
181
+ }
182
+ ```
183
+
184
+ Use `TransactionRejected` only for expected application rejection. Ordinary exceptions are bugs/infrastructure failures and are rethrown after rollback.
185
+
186
+ ## Fine-grained document selector
187
+
188
+ ```ts
189
+ const selectedTitle = select(document, value => value.rows.get(activeId)?.title);
190
+
191
+ const stop = selectedTitle.subscribe(() => {
192
+ render(selectedTitle.current());
193
+ });
194
+ ```
195
+
196
+ The selector dynamically tracks what it actually reads and rebinds when branches change.
197
+
198
+ ## Commit path subscription
199
+
200
+ ```ts
201
+ const stop = document.subscribe(
202
+ path => path.rows.item(rowId).title,
203
+ commit => {
204
+ console.log(commit.revision, commit.changes);
205
+ }
206
+ );
207
+ ```
208
+
209
+ Use path subscription when the consumer cares about canonical commit occurrence at a known schema location.
210
+
211
+ ## History group
212
+
213
+ ```ts
214
+ const group = document.history.group();
215
+ try {
216
+ document.update(draft => editPartA(draft));
217
+ document.update(draft => editPartB(draft));
218
+ group.end();
219
+ } catch (error) {
220
+ group.cancel();
221
+ throw error;
222
+ }
223
+ ```
224
+
225
+ Undo/redo travels committed ChangeSets. Grouping is a history concern, not a cross-transaction rollback mechanism for arbitrary external side effects.
226
+
227
+ ## Apply external ChangeSet
228
+
229
+ ```ts
230
+ const result = document.apply(incomingChanges, {
231
+ expectedRevision: document.revision(),
232
+ source: 'remote',
233
+ });
234
+
235
+ if (result.status === 'rejected') {
236
+ handleMutationIssues(result.issues);
237
+ }
238
+ ```
239
+
240
+ Always provide the baseline revision. Do not trust incoming `before` fields as authority over local state.
241
+
242
+ ## Basic projection pipeline
243
+
244
+ ```ts
245
+ const rows = observe(document, path => path.rows);
246
+ const filter = input<'all' | 'open'>('all');
247
+
248
+ const visible = derive.keyed.filter(
249
+ rows,
250
+ { filter },
251
+ (row, _id, { filter }) => filter === 'all' || !row.done
252
+ );
253
+
254
+ const labels = derive.keyed(visible, row => row.title);
255
+ const count = derive({ labels }, ({ labels }) => labels.size);
256
+
257
+ const runtime = createProjectionRuntime({ onError: reportProjectionError });
258
+
259
+ runtime.read(labels);
260
+ runtime.read(count);
261
+ runtime.update(filter, 'open');
262
+ ```
263
+
264
+ Use projection input for Runtime-local UI/application state. Keep it out of the canonical document unless the state needs document history/persistence/replay semantics.
265
+
266
+ ## Dynamic keyed join
267
+
268
+ ```ts
269
+ const cards = derive.keyed(
270
+ items,
271
+ {
272
+ record: { source: records, key: item => item.recordId },
273
+ related: { source: records, keys: item => item.relatedRecordIds },
274
+ density,
275
+ },
276
+ (item, itemId, { record, related, density }) => buildCard(itemId, item, record, related, density)
277
+ );
278
+ ```
279
+
280
+ The Runtime owns reverse invalidation. Do not subscribe to `records` and manually maintain `recordId -> itemIds` just for dependency routing.
281
+
282
+ ## Ordered keyed entries as a scalar value
283
+
284
+ ```ts
285
+ const entries = derive.keyed.entries(records);
286
+ ```
287
+
288
+ Use this instead of a two-stage `derive.keyed(records, (value,key) => [key,value])` followed by `values`.
289
+
290
+ ## Active keyed lookup
291
+
292
+ ```ts
293
+ const activeId = input<RowId | undefined>(undefined);
294
+ const activeRow = derive.keyed.get(rows, activeId);
295
+ ```
296
+
297
+ The binding remains meaningful while the selected key is absent and reacts if that key appears later.
298
+
299
+ ## Reverse index / groupBy
300
+
301
+ ```ts
302
+ const recordIdsBySection = derive.keyed.groupBy(records, record => record.sectionIds);
303
+ ```
304
+
305
+ Output is keyed by section id; each value is ordered source record ids. Use this instead of maintaining a global reverse-index Map in application code.
306
+
307
+ ## Optional scalar to keyed singleton
308
+
309
+ ```ts
310
+ const activeRecordCollection = derive.keyed.singleton(activeRecord, record => record.id);
311
+ ```
312
+
313
+ `undefined` becomes empty membership; present value becomes one keyed member.
314
+
315
+ ## Stable keyed item Readables
316
+
317
+ ```ts
318
+ const items = runtime.items(rows);
319
+ const row = items.get(rowId);
320
+
321
+ const stop = row.subscribe(() => {
322
+ renderRow(row.current());
323
+ });
324
+ ```
325
+
326
+ Use `items.keys` for ordered membership and `items.get(key)` for one membership-lifecycle readable. Avoid business/React layers maintaining their own selector cache.
327
+
328
+ ## Runtime-local keyed UI state
329
+
330
+ ```ts
331
+ const selection = input.collection<RowId, boolean>();
332
+
333
+ runtime.update(selection, draft => {
334
+ draft.set(rowId, true);
335
+ draft.remove(previousId);
336
+ });
337
+ ```
338
+
339
+ If the edit callback or entry equality throws, no partial next collection state is installed.
340
+
341
+ ## Scoped projection lifecycle
342
+
343
+ ```ts
344
+ const scope = runtime.scope();
345
+
346
+ const localFilter = scope.own(input<'all' | 'open'>('all'));
347
+ const localVisible = scope.own(
348
+ derive.keyed.filter(
349
+ rows,
350
+ { filter: localFilter },
351
+ (row, _id, { filter }) => filter === 'all' || !row.done
352
+ )
353
+ );
354
+
355
+ scope.read(localVisible);
356
+ scope.update(localFilter, 'open');
357
+ scope.dispose();
358
+ ```
359
+
360
+ Own the definition before it is first materialized as a root. Use scope for lifecycle, not as a second graph implementation.
361
+
362
+ ## Stateful keyed calculation
363
+
364
+ ```ts
365
+ import { incremental } from 'doxum/advanced';
366
+
367
+ const sectionTotals = incremental.keyed(
368
+ sections,
369
+ {
370
+ records: { source: records, keys: section => section.recordIds },
371
+ },
372
+ {
373
+ state: () => ({ runs: 0 }),
374
+ process: ({ dependencies, state }) => {
375
+ state.runs++;
376
+ let total = 0;
377
+ for (const record of dependencies.records.values()) total += record.amount;
378
+ return total;
379
+ },
380
+ }
381
+ );
382
+ ```
383
+
384
+ Use this when each driver key truly needs retained state. If the value is a pure function of current dependencies, ordinary `derive.keyed` is simpler.
385
+
386
+ ## Direct incremental collection patch
387
+
388
+ ```ts
389
+ const projected = incremental.collection(
390
+ { rows },
391
+ {
392
+ process: ({ values, changes, output, reset }) => {
393
+ if (reset) {
394
+ for (const [id, row] of values.rows) output.set(id, project(row));
395
+ output.order([...values.rows.keys()]);
396
+ return;
397
+ }
398
+
399
+ const change = changes.rows;
400
+ if (!change || change.kind === 'reset') return;
401
+ for (const item of change.added) output.set(item.key, project(item.after));
402
+ for (const item of change.updated) output.set(item.key, project(item.after));
403
+ for (const item of change.removed) output.remove(item.key);
404
+ if (change.order) output.order([...values.rows.keys()]);
405
+ },
406
+ }
407
+ );
408
+ ```
409
+
410
+ Prefer ordinary keyed derive for pure per-entry projection. Use direct patching when the incremental algorithm itself is the requirement.
411
+
412
+ ## Multi-output incremental processor
413
+
414
+ ```ts
415
+ const render = incremental.group(
416
+ { scene },
417
+ {
418
+ output: define => ({
419
+ cards: define.collection<CardId, Card>(),
420
+ count: define.value<number>(),
421
+ }),
422
+ state: () => ({ runs: 0 }),
423
+ process: ({ values, output, state }) => {
424
+ state.runs++;
425
+ const cards = buildCards(values.scene);
426
+ for (const [id, card] of cards) output.cards.set(id, card);
427
+ output.cards.order([...cards.keys()]);
428
+ output.count.set(cards.size);
429
+ },
430
+ }
431
+ );
432
+ ```
433
+
434
+ Use one group only when outputs actually share retained state or incremental work.
435
+
436
+ ## React provider and hooks
437
+
438
+ ```tsx
439
+ const runtime = useMemo(() => createProjectionRuntime({ onError: report }), []);
440
+ useEffect(() => () => runtime.dispose(), [runtime]);
441
+
442
+ return (
443
+ <ProjectionProvider value={runtime}>
444
+ <Rows />
445
+ </ProjectionProvider>
446
+ );
447
+ ```
448
+
449
+ Inside components:
450
+
451
+ ```tsx
452
+ const rows = useProjection(visibleRows);
453
+ const active = useProjection(rowsProjection, rows => rows.get(activeId));
454
+ const [filter, setFilter] = useInput(filterInput);
455
+ const title = useDocumentSelector(document, value => value.title);
456
+ ```
457
+
458
+ Keep Runtime creation/disposal at a stable application/component boundary.
459
+
460
+ ## External source adapter
461
+
462
+ ```ts
463
+ const external: ExternalValueSource<number> = {
464
+ kind: 'value',
465
+ current: () => current,
466
+ revision: () => revision,
467
+ subscribe(listener) {
468
+ listeners.add(listener);
469
+ return () => listeners.delete(listener);
470
+ },
471
+ };
472
+
473
+ const projected = observe(external);
474
+ ```
475
+
476
+ On update, update the source's current state/revision, then notify listeners with `{ value, revision, cause? }`.
477
+
478
+ ## Local sync
479
+
480
+ ```ts
481
+ const sync = await attachLocalSync({
482
+ runtime: document,
483
+ database: 'app',
484
+ documentId: 'doc:1',
485
+ schemaVersion: 1,
486
+ onError: reportSyncError,
487
+ });
488
+
489
+ await sync.flush();
490
+ await sync.dispose();
491
+ ```
492
+
493
+ Local-sync provides browser durability and leadership. Keep network collaboration, server authorization, and distributed merge policy in a separate boundary.
@@ -1 +0,0 @@
1
- {"version":3,"file":"driver-B5vdPohL.js","names":["issue.fail","tree.validNode"],"sources":["../core/src/tree/topology.ts","../core/src/mutation/issue.ts","../core/src/address/index.ts","../core/src/mutation/changes.ts","../core/src/runtime/context.ts","../core/src/runtime/driver.ts"],"sourcesContent":["import { isRecord } from '@/value/record';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { DocumentAddress } from '@/schema/model';\nimport type { ParseIssue } from '@/schema/value';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-value'\n | 'invalid-key'\n | 'invalid-changes'\n | 'baseline-mismatch'\n | 'required-field'\n | 'invalid-anchor'\n | 'duplicate-entity'\n | 'missing-entity'\n | 'invalid-collection'\n | 'invalid-list-keys'\n | 'invalid-list-key'\n | 'duplicate-list-item'\n | 'missing-list-item'\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n};\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string\n): MutationIssue =>\n Object.freeze({ source: 'mutation', code, address: Object.freeze([...address]), message });\nexport class MutationRejected extends Error {\n constructor(readonly issue: MutationIssue) {\n super(issue.message);\n }\n}\nexport const fail = (address: DocumentAddress, code: MutationIssueCode, message: string): never => {\n throw new MutationRejected(at(address, code, message));\n};\n\nexport const invalidValue = (issue: ParseIssue, address = issue.address): never =>\n fail(address, issue.code === 'missing-validator' ? 'invalid-value' : issue.code, issue.message);\n","import type { DocumentAddress } from '@/schema/model';\n\ntype AddressIndexNode<T> = {\n readonly children: Map<string, AddressIndexNode<T>>;\n readonly values: Set<T>;\n};\n\nexport class AddressIndex<T> {\n private readonly root: AddressIndexNode<T> = { children: new Map(), values: new Set() };\n\n add(address: DocumentAddress, value: T, member?: string): void {\n let node = this.root;\n for (let index = 0; index < address.length + (member === undefined ? 0 : 1); index++) {\n const segment = index < address.length ? address[index] : member!;\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), values: new Set() };\n node.children.set(segment, child);\n }\n node = child;\n }\n node.values.add(value);\n }\n\n delete(address: DocumentAddress, value: T, member?: string): void {\n const parents: AddressIndexNode<T>[] = [];\n let node = this.root;\n const segments = member === undefined ? address : [...address, member];\n for (const segment of segments) {\n const child = node.children.get(segment);\n if (!child) return;\n parents.push(node);\n node = child;\n }\n node.values.delete(value);\n for (\n let index = segments.length - 1;\n index >= 0 && !node.values.size && !node.children.size;\n index--\n ) {\n node = parents[index];\n node.children.delete(segments[index]);\n }\n }\n\n exact(address: DocumentAddress): ReadonlySet<T> | undefined {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return undefined;\n node = child;\n }\n return node.values;\n }\n\n hasAncestor(address: DocumentAddress, strict = false): boolean {\n let node = this.root;\n for (let index = 0; index < address.length; index++) {\n if (node.values.size) return true;\n const child = node.children.get(address[index]);\n if (!child) return false;\n node = child;\n }\n return !strict && node.values.size > 0;\n }\n\n someAncestor(address: DocumentAddress, predicate: (value: T) => boolean): boolean {\n let node = this.root;\n for (let index = 0; ; index++) {\n for (const value of node.values) if (predicate(value)) return true;\n if (index === address.length) return false;\n const child = node.children.get(address[index]);\n if (!child) return false;\n node = child;\n }\n }\n\n overlaps(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n if (node.values.size) return true;\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n hasDescendant(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n query(\n visit: (value: T) => void,\n relation: 'overlap' | 'ancestors' | 'descendants' = 'overlap'\n ): (address: DocumentAddress, members?: readonly { readonly key: string }[]) => void {\n const visited = new Set<AddressIndexNode<T>>();\n const subtrees = new Set<AddressIndexNode<T>>();\n const values = (node: AddressIndexNode<T>) => {\n if (visited.has(node)) return;\n visited.add(node);\n node.values.forEach(visit);\n };\n const descend = (current: AddressIndexNode<T>): void => {\n if (subtrees.has(current)) return;\n subtrees.add(current);\n values(current);\n current.children.forEach(descend);\n };\n const terminal = (node: AddressIndexNode<T>) =>\n relation === 'ancestors' ? values(node) : descend(node);\n return (address, members) => {\n let node = this.root;\n for (const segment of address) {\n if (subtrees.has(node)) return;\n if (relation !== 'descendants') values(node);\n const child = node.children.get(segment);\n if (!child) return;\n node = child;\n }\n if (!members) terminal(node);\n else {\n if (relation !== 'descendants') values(node);\n for (const member of members) {\n const child = node.children.get(member.key);\n if (child) terminal(child);\n }\n }\n };\n }\n\n clear(): void {\n this.root.values.clear();\n this.root.children.clear();\n }\n}\n","import type { Change, ChangeSet, MemberChange, ValueTransition } from '@/changes';\nimport { AddressIndex } from '@/address/index';\nimport { isPlainObject } from '@/value/record';\nimport * as issue from './issue';\nimport * as tree from '@/tree/topology';\n\nconst validated = new WeakSet<ChangeSet>();\n\nconst compareChanges = (a: Change, b: Change): number => {\n if (a.kind === 'reset' || b.kind === 'reset')\n return a.kind === b.kind ? 0 : a.kind === 'reset' ? -1 : 1;\n const length = Math.min(a.at.length, b.at.length);\n for (let i = 0; i < length; i++) if (a.at[i] !== b.at[i]) return lexical(a.at[i], b.at[i]);\n return a.at.length - b.at.length || lexical(a.kind, b.kind);\n};\n\nconst publication = (changes: Change[]): ChangeSet => {\n const result = { changes };\n validated.add(result);\n return result;\n};\n\n/** Register complete recorder groups; unknown input is validated separately. */\nexport const sealChanges = (changes: Change[]): ChangeSet => {\n changes.sort(compareChanges);\n return publication(changes);\n};\n\nconst keys = (value: Record<string, unknown>, expected: readonly string[]) =>\n Object.keys(value).every(key => expected.includes(key));\nconst strings = (value: unknown): value is readonly string[] => {\n if (!Array.isArray(value)) return false;\n for (const item of value) if (typeof item !== 'string') return false;\n return true;\n};\nconst order = (value: unknown): value is readonly string[] =>\n strings(value) && new Set(value).size === value.length;\nconst transition = (\n value: unknown,\n key: 'key' | 'id'\n): value is ValueTransition & Record<string, unknown> => {\n if (!isPlainObject(value) || typeof value[key] !== 'string') return false;\n if (value.kind === 'added')\n return keys(value, ['kind', key, 'after']) && Object.hasOwn(value, 'after');\n if (value.kind === 'removed')\n return keys(value, ['kind', key, 'before']) && Object.hasOwn(value, 'before');\n return (\n value.kind === 'updated' &&\n keys(value, ['kind', key, 'before', 'after']) &&\n Object.hasOwn(value, 'before') &&\n Object.hasOwn(value, 'after')\n );\n};\nconst lexical = (a: string, b: string) => (a < b ? -1 : a === b ? 0 : 1);\n\n/** The sole unknown ChangeSet boundary, including normalized logical-address conflicts. */\nexport const decodeChanges = (input: unknown): ChangeSet => {\n if (typeof input === 'object' && input !== null && validated.has(input as ChangeSet))\n return input as ChangeSet;\n if (!isPlainObject(input) || !keys(input, ['changes']) || !Array.isArray(input.changes))\n return issue.fail([], 'invalid-changes', 'Expected a ChangeSet.');\n const result: Change[] = [];\n for (const entry of input.changes) {\n if (!isPlainObject(entry)) return issue.fail([], 'invalid-changes', 'Expected a change.');\n if (entry.kind === 'reset') {\n if (\n input.changes.length !== 1 ||\n !keys(entry, ['kind', 'before', 'after']) ||\n !Object.hasOwn(entry, 'before') ||\n !Object.hasOwn(entry, 'after')\n )\n return issue.fail(\n [],\n 'invalid-changes',\n 'A reset must be the only change and contain both values.'\n );\n return sealChanges([{ kind: 'reset', before: entry.before, after: entry.after }]);\n }\n if (!strings(entry.at))\n return issue.fail([], 'invalid-changes', 'Change addresses must contain strings.');\n const at = entry.at;\n if (\n entry.kind === 'members' &&\n keys(entry, ['kind', 'at', 'members', 'order']) &&\n Array.isArray(entry.members) &&\n (entry.members.length || Object.hasOwn(entry, 'order'))\n ) {\n const seen = new Set<string>();\n const members: MemberChange[] = [];\n for (const member of entry.members) {\n if (!transition(member, 'key') || typeof member.key !== 'string' || seen.has(member.key))\n return issue.fail(at, 'invalid-changes', 'Malformed or duplicate member transition.');\n seen.add(member.key);\n members.push({ ...member, key: member.key });\n }\n const change: Extract<Change, { kind: 'members' }> = {\n kind: 'members',\n at,\n members: members.sort((a, b) => lexical(a.key, b.key)),\n };\n if (Object.hasOwn(entry, 'order')) {\n if (\n !isPlainObject(entry.order) ||\n !keys(entry.order, ['before', 'after']) ||\n !order(entry.order.before) ||\n !order(entry.order.after)\n )\n return issue.fail(at, 'invalid-changes', 'Malformed container order.');\n result.push({ ...change, order: { before: entry.order.before, after: entry.order.after } });\n } else result.push(change);\n } else if (\n entry.kind === 'tree' &&\n keys(entry, ['kind', 'at', 'before', 'after', 'nodes']) &&\n (entry.before === null || typeof entry.before === 'string') &&\n (entry.after === null || typeof entry.after === 'string') &&\n Array.isArray(entry.nodes)\n ) {\n const seen = new Set<string>();\n for (const node of entry.nodes) {\n if (\n !transition(node, 'id') ||\n typeof node.id !== 'string' ||\n seen.has(node.id) ||\n (node.kind !== 'added' && !tree.validNode(node.before)) ||\n (node.kind !== 'removed' && !tree.validNode(node.after))\n )\n return issue.fail(at, 'invalid-changes', 'Malformed or duplicate tree transition.');\n seen.add(node.id);\n }\n const nodes = entry.nodes as Extract<Change, { kind: 'tree' }>['nodes'];\n result.push({\n kind: 'tree',\n at,\n before: entry.before,\n after: entry.after,\n nodes: [...nodes].sort((a, b) => lexical(a.id, b.id)),\n });\n } else return issue.fail(at, 'invalid-changes', 'Unknown or malformed change.');\n }\n return publication(normalizeChanges(result));\n};\n\nconst normalizeChanges = (changes: Change[]): Change[] => {\n const sorted = changes.sort(compareChanges);\n const groups = new AddressIndex<true>();\n const replacements = new AddressIndex<true>();\n const orders = new AddressIndex<true>();\n for (const change of sorted) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n if (groups.exact(change.at)?.size)\n return issue.fail(change.at, 'invalid-changes', 'Duplicate member group.');\n groups.add(change.at, true);\n if (change.order) {\n if (replacements.hasAncestor(change.at))\n return issue.fail(change.at, 'invalid-changes', 'Overlapping container order.');\n orders.add(change.at, true);\n }\n for (const member of change.members) {\n const at = change.at.concat(member.key);\n if (replacements.overlaps(at) || orders.hasDescendant(at))\n return issue.fail(at, 'invalid-changes', 'Overlapping member transitions.');\n replacements.add(at, true);\n }\n } else if (change.kind === 'tree') {\n if (replacements.overlaps(change.at) || orders.hasDescendant(change.at))\n return issue.fail(change.at, 'invalid-changes', 'Overlapping tree transitions.');\n replacements.add(change.at, true);\n }\n }\n return sorted;\n};\n\nexport const changeCount = (changes: ChangeSet): number => {\n let count = 0;\n for (const change of changes.changes)\n count +=\n change.kind === 'members'\n ? change.members.length + (change.order ? 1 : 0)\n : change.kind === 'tree'\n ? 1 + change.nodes.length\n : 1;\n return count;\n};\n","import type { Infer, ObjectSchema, RootNodeOf } from '@/schema/model';\nimport type { DocumentRuntime } from './contract';\nimport type { RuntimeWriteDriver } from './driver';\nimport type { NotificationCenter } from './notification';\n\nexport type RuntimeState<TSchema extends ObjectSchema<object>> = {\n readonly schema: RootNodeOf<TSchema>;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks: number;\n};\n\nexport type RuntimeContext<TSchema extends ObjectSchema<object>> = {\n readonly state: RuntimeState<TSchema>;\n readonly owner: DocumentRuntime<TSchema>;\n readonly notifications: NotificationCenter<TSchema>;\n driver: RuntimeWriteDriver | undefined;\n bypassDepth: number;\n};\n\nconst contexts = new WeakMap<object, RuntimeContext<ObjectSchema<object>>>();\n\nexport const bindContext = <TSchema extends ObjectSchema<object>>(\n subject: object,\n context: RuntimeContext<TSchema>\n): void => {\n contexts.set(subject, context as unknown as RuntimeContext<ObjectSchema<object>>);\n};\n\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required?: true\n): RuntimeContext<TSchema>;\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required: false\n): RuntimeContext<TSchema> | undefined;\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required = true\n): RuntimeContext<TSchema> | undefined {\n const context = contexts.get(subject);\n if (!context && required) throw new Error('Unknown Doxum runtime.');\n return context as unknown as RuntimeContext<TSchema> | undefined;\n}\n","import type { CommitSource, DocumentRuntime } from './contract';\nimport type { ObjectSchema } from '@/schema/model';\nimport { contextOf } from './context';\n\nexport type RuntimeWriteIntent =\n | { readonly kind: 'update'; readonly source: Extract<CommitSource, 'local' | 'system'> }\n | { readonly kind: 'apply'; readonly source: CommitSource }\n | { readonly kind: 'replace'; readonly source: Extract<CommitSource, 'system' | 'remote'> };\n\nexport type RuntimeWriteDriver = {\n readonly assertWritable: (intent: RuntimeWriteIntent) => void;\n};\n\nexport type RuntimeWriteDriverLease = {\n readonly run: <TResult>(run: () => TResult) => TResult;\n readonly dispose: () => void;\n};\n\nexport const assertRuntimeWritable = (runtime: object, intent: RuntimeWriteIntent): void => {\n const context = contextOf(runtime);\n if (context.bypassDepth === 0) context.driver?.assertWritable(intent);\n};\n\nexport const installRuntimeWriteDriver = <TSchema extends ObjectSchema<object>>(\n runtime: DocumentRuntime<TSchema>,\n driver: RuntimeWriteDriver\n): RuntimeWriteDriverLease => {\n const context = contextOf(runtime);\n if (context.driver) throw new Error('Doxum runtime already has a write driver.');\n context.driver = driver;\n let active = true;\n return Object.freeze({\n run: <TResult>(run: () => TResult): TResult => {\n if (!active) throw new Error('Doxum runtime write driver is no longer active.');\n context.bypassDepth += 1;\n try {\n return run();\n } finally {\n context.bypassDepth -= 1;\n }\n },\n dispose: (): void => {\n if (!active) return;\n active = false;\n if (context.driver === driver) context.driver = undefined;\n },\n });\n};\n"],"mappings":";;AAGA,MAAM,QAAQ,MAAmB,OAC/B,OAAO,OAAO,KAAK,OAAO,GAAG,GAAG,KAAK,MAAM,MAAM,KAAA;AACnD,MAAa,MAAM,UACjB,SAAS,MAAM,IAAI,SAAS,MAAM,MAAM;AAE1C,MAAa,aAAa,UAA6C;AACrE,KAAI,CAAC,SAAS,MAAM,IAAI,CAAC,MAAM,QAAQ,MAAM,SAAS,CAAE,QAAO;AAC/D,KAAI,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa,SAAU,QAAO;CAC/E,MAAM,2BAAW,IAAI,KAAa;AAClC,MAAK,MAAM,MAAM,MAAM,UAAU;AAC/B,MAAI,OAAO,OAAO,YAAY,SAAS,IAAI,GAAG,CAAE,QAAO;AACvD,WAAS,IAAI,GAAG;;AAElB,QAAO;;AAGT,MAAa,YAAY,MAAmB,OAAwB,OAAO,OAAO,KAAK,OAAO,GAAG;AAEjG,MAAa,UAAU,MAAmB,OACxC,KAAK,MAAM,GAAG,EAAE;AAElB,MAAa,YAAY,MAAmB,OAC1C,KAAK,MAAM,GAAG,EAAE;AAElB,MAAa,YAAY,UAAyC;AAChE,KAAI,CAAC,GAAG,MAAM,CAAE,QAAO;CACvB,MAAM,MAAM,OAAO,KAAK,MAAM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SACA,YACS;AACT,UAAS,IAAI,SAAS,QAA2D;;AAWnF,SAAgB,UACd,SACA,WAAW,MAC0B;CACrC,MAAM,UAAU,SAAS,IAAI,QAAQ;AACrC,KAAI,CAAC,WAAW,SAAU,OAAM,IAAI,MAAM,yBAAyB;AACnE,QAAO;;;;ACzBT,MAAa,yBAAyB,SAAiB,WAAqC;CAC1F,MAAM,UAAU,UAAU,QAAQ;AAClC,KAAI,QAAQ,gBAAgB,EAAG,SAAQ,QAAQ,eAAe,OAAO;;AAGvE,MAAa,6BACX,SACA,WAC4B;CAC5B,MAAM,UAAU,UAAU,QAAQ;AAClC,KAAI,QAAQ,OAAQ,OAAM,IAAI,MAAM,4CAA4C;AAChF,SAAQ,SAAS;CACjB,IAAI,SAAS;AACb,QAAO,OAAO,OAAO;EACnB,MAAe,QAAgC;AAC7C,OAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,kDAAkD;AAC/E,WAAQ,eAAe;AACvB,OAAI;AACF,WAAO,KAAK;aACJ;AACR,YAAQ,eAAe;;;EAG3B,eAAqB;AACnB,OAAI,CAAC,OAAQ;AACb,YAAS;AACT,OAAI,QAAQ,WAAW,OAAQ,SAAQ,SAAS,KAAA;;EAEnD,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"driver-BL91gn7_.cjs","names":["isRecord","isPlainObject","issue.fail","tree.validNode"],"sources":["../core/src/tree/topology.ts","../core/src/mutation/issue.ts","../core/src/address/index.ts","../core/src/mutation/changes.ts","../core/src/runtime/context.ts","../core/src/runtime/driver.ts"],"sourcesContent":["import { isRecord } from '@/value/record';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { DocumentAddress } from '@/schema/model';\nimport type { ParseIssue } from '@/schema/value';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-value'\n | 'invalid-key'\n | 'invalid-changes'\n | 'baseline-mismatch'\n | 'required-field'\n | 'invalid-anchor'\n | 'duplicate-entity'\n | 'missing-entity'\n | 'invalid-collection'\n | 'invalid-list-keys'\n | 'invalid-list-key'\n | 'duplicate-list-item'\n | 'missing-list-item'\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n};\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string\n): MutationIssue =>\n Object.freeze({ source: 'mutation', code, address: Object.freeze([...address]), message });\nexport class MutationRejected extends Error {\n constructor(readonly issue: MutationIssue) {\n super(issue.message);\n }\n}\nexport const fail = (address: DocumentAddress, code: MutationIssueCode, message: string): never => {\n throw new MutationRejected(at(address, code, message));\n};\n\nexport const invalidValue = (issue: ParseIssue, address = issue.address): never =>\n fail(address, issue.code === 'missing-validator' ? 'invalid-value' : issue.code, issue.message);\n","import type { DocumentAddress } from '@/schema/model';\n\ntype AddressIndexNode<T> = {\n readonly children: Map<string, AddressIndexNode<T>>;\n readonly values: Set<T>;\n};\n\nexport class AddressIndex<T> {\n private readonly root: AddressIndexNode<T> = { children: new Map(), values: new Set() };\n\n add(address: DocumentAddress, value: T, member?: string): void {\n let node = this.root;\n for (let index = 0; index < address.length + (member === undefined ? 0 : 1); index++) {\n const segment = index < address.length ? address[index] : member!;\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), values: new Set() };\n node.children.set(segment, child);\n }\n node = child;\n }\n node.values.add(value);\n }\n\n delete(address: DocumentAddress, value: T, member?: string): void {\n const parents: AddressIndexNode<T>[] = [];\n let node = this.root;\n const segments = member === undefined ? address : [...address, member];\n for (const segment of segments) {\n const child = node.children.get(segment);\n if (!child) return;\n parents.push(node);\n node = child;\n }\n node.values.delete(value);\n for (\n let index = segments.length - 1;\n index >= 0 && !node.values.size && !node.children.size;\n index--\n ) {\n node = parents[index];\n node.children.delete(segments[index]);\n }\n }\n\n exact(address: DocumentAddress): ReadonlySet<T> | undefined {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return undefined;\n node = child;\n }\n return node.values;\n }\n\n hasAncestor(address: DocumentAddress, strict = false): boolean {\n let node = this.root;\n for (let index = 0; index < address.length; index++) {\n if (node.values.size) return true;\n const child = node.children.get(address[index]);\n if (!child) return false;\n node = child;\n }\n return !strict && node.values.size > 0;\n }\n\n someAncestor(address: DocumentAddress, predicate: (value: T) => boolean): boolean {\n let node = this.root;\n for (let index = 0; ; index++) {\n for (const value of node.values) if (predicate(value)) return true;\n if (index === address.length) return false;\n const child = node.children.get(address[index]);\n if (!child) return false;\n node = child;\n }\n }\n\n overlaps(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n if (node.values.size) return true;\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n hasDescendant(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n query(\n visit: (value: T) => void,\n relation: 'overlap' | 'ancestors' | 'descendants' = 'overlap'\n ): (address: DocumentAddress, members?: readonly { readonly key: string }[]) => void {\n const visited = new Set<AddressIndexNode<T>>();\n const subtrees = new Set<AddressIndexNode<T>>();\n const values = (node: AddressIndexNode<T>) => {\n if (visited.has(node)) return;\n visited.add(node);\n node.values.forEach(visit);\n };\n const descend = (current: AddressIndexNode<T>): void => {\n if (subtrees.has(current)) return;\n subtrees.add(current);\n values(current);\n current.children.forEach(descend);\n };\n const terminal = (node: AddressIndexNode<T>) =>\n relation === 'ancestors' ? values(node) : descend(node);\n return (address, members) => {\n let node = this.root;\n for (const segment of address) {\n if (subtrees.has(node)) return;\n if (relation !== 'descendants') values(node);\n const child = node.children.get(segment);\n if (!child) return;\n node = child;\n }\n if (!members) terminal(node);\n else {\n if (relation !== 'descendants') values(node);\n for (const member of members) {\n const child = node.children.get(member.key);\n if (child) terminal(child);\n }\n }\n };\n }\n\n clear(): void {\n this.root.values.clear();\n this.root.children.clear();\n }\n}\n","import type { Change, ChangeSet, MemberChange, ValueTransition } from '@/changes';\nimport { AddressIndex } from '@/address/index';\nimport { isPlainObject } from '@/value/record';\nimport * as issue from './issue';\nimport * as tree from '@/tree/topology';\n\nconst validated = new WeakSet<ChangeSet>();\n\nconst compareChanges = (a: Change, b: Change): number => {\n if (a.kind === 'reset' || b.kind === 'reset')\n return a.kind === b.kind ? 0 : a.kind === 'reset' ? -1 : 1;\n const length = Math.min(a.at.length, b.at.length);\n for (let i = 0; i < length; i++) if (a.at[i] !== b.at[i]) return lexical(a.at[i], b.at[i]);\n return a.at.length - b.at.length || lexical(a.kind, b.kind);\n};\n\nconst publication = (changes: Change[]): ChangeSet => {\n const result = { changes };\n validated.add(result);\n return result;\n};\n\n/** Register complete recorder groups; unknown input is validated separately. */\nexport const sealChanges = (changes: Change[]): ChangeSet => {\n changes.sort(compareChanges);\n return publication(changes);\n};\n\nconst keys = (value: Record<string, unknown>, expected: readonly string[]) =>\n Object.keys(value).every(key => expected.includes(key));\nconst strings = (value: unknown): value is readonly string[] => {\n if (!Array.isArray(value)) return false;\n for (const item of value) if (typeof item !== 'string') return false;\n return true;\n};\nconst order = (value: unknown): value is readonly string[] =>\n strings(value) && new Set(value).size === value.length;\nconst transition = (\n value: unknown,\n key: 'key' | 'id'\n): value is ValueTransition & Record<string, unknown> => {\n if (!isPlainObject(value) || typeof value[key] !== 'string') return false;\n if (value.kind === 'added')\n return keys(value, ['kind', key, 'after']) && Object.hasOwn(value, 'after');\n if (value.kind === 'removed')\n return keys(value, ['kind', key, 'before']) && Object.hasOwn(value, 'before');\n return (\n value.kind === 'updated' &&\n keys(value, ['kind', key, 'before', 'after']) &&\n Object.hasOwn(value, 'before') &&\n Object.hasOwn(value, 'after')\n );\n};\nconst lexical = (a: string, b: string) => (a < b ? -1 : a === b ? 0 : 1);\n\n/** The sole unknown ChangeSet boundary, including normalized logical-address conflicts. */\nexport const decodeChanges = (input: unknown): ChangeSet => {\n if (typeof input === 'object' && input !== null && validated.has(input as ChangeSet))\n return input as ChangeSet;\n if (!isPlainObject(input) || !keys(input, ['changes']) || !Array.isArray(input.changes))\n return issue.fail([], 'invalid-changes', 'Expected a ChangeSet.');\n const result: Change[] = [];\n for (const entry of input.changes) {\n if (!isPlainObject(entry)) return issue.fail([], 'invalid-changes', 'Expected a change.');\n if (entry.kind === 'reset') {\n if (\n input.changes.length !== 1 ||\n !keys(entry, ['kind', 'before', 'after']) ||\n !Object.hasOwn(entry, 'before') ||\n !Object.hasOwn(entry, 'after')\n )\n return issue.fail(\n [],\n 'invalid-changes',\n 'A reset must be the only change and contain both values.'\n );\n return sealChanges([{ kind: 'reset', before: entry.before, after: entry.after }]);\n }\n if (!strings(entry.at))\n return issue.fail([], 'invalid-changes', 'Change addresses must contain strings.');\n const at = entry.at;\n if (\n entry.kind === 'members' &&\n keys(entry, ['kind', 'at', 'members', 'order']) &&\n Array.isArray(entry.members) &&\n (entry.members.length || Object.hasOwn(entry, 'order'))\n ) {\n const seen = new Set<string>();\n const members: MemberChange[] = [];\n for (const member of entry.members) {\n if (!transition(member, 'key') || typeof member.key !== 'string' || seen.has(member.key))\n return issue.fail(at, 'invalid-changes', 'Malformed or duplicate member transition.');\n seen.add(member.key);\n members.push({ ...member, key: member.key });\n }\n const change: Extract<Change, { kind: 'members' }> = {\n kind: 'members',\n at,\n members: members.sort((a, b) => lexical(a.key, b.key)),\n };\n if (Object.hasOwn(entry, 'order')) {\n if (\n !isPlainObject(entry.order) ||\n !keys(entry.order, ['before', 'after']) ||\n !order(entry.order.before) ||\n !order(entry.order.after)\n )\n return issue.fail(at, 'invalid-changes', 'Malformed container order.');\n result.push({ ...change, order: { before: entry.order.before, after: entry.order.after } });\n } else result.push(change);\n } else if (\n entry.kind === 'tree' &&\n keys(entry, ['kind', 'at', 'before', 'after', 'nodes']) &&\n (entry.before === null || typeof entry.before === 'string') &&\n (entry.after === null || typeof entry.after === 'string') &&\n Array.isArray(entry.nodes)\n ) {\n const seen = new Set<string>();\n for (const node of entry.nodes) {\n if (\n !transition(node, 'id') ||\n typeof node.id !== 'string' ||\n seen.has(node.id) ||\n (node.kind !== 'added' && !tree.validNode(node.before)) ||\n (node.kind !== 'removed' && !tree.validNode(node.after))\n )\n return issue.fail(at, 'invalid-changes', 'Malformed or duplicate tree transition.');\n seen.add(node.id);\n }\n const nodes = entry.nodes as Extract<Change, { kind: 'tree' }>['nodes'];\n result.push({\n kind: 'tree',\n at,\n before: entry.before,\n after: entry.after,\n nodes: [...nodes].sort((a, b) => lexical(a.id, b.id)),\n });\n } else return issue.fail(at, 'invalid-changes', 'Unknown or malformed change.');\n }\n return publication(normalizeChanges(result));\n};\n\nconst normalizeChanges = (changes: Change[]): Change[] => {\n const sorted = changes.sort(compareChanges);\n const groups = new AddressIndex<true>();\n const replacements = new AddressIndex<true>();\n const orders = new AddressIndex<true>();\n for (const change of sorted) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n if (groups.exact(change.at)?.size)\n return issue.fail(change.at, 'invalid-changes', 'Duplicate member group.');\n groups.add(change.at, true);\n if (change.order) {\n if (replacements.hasAncestor(change.at))\n return issue.fail(change.at, 'invalid-changes', 'Overlapping container order.');\n orders.add(change.at, true);\n }\n for (const member of change.members) {\n const at = change.at.concat(member.key);\n if (replacements.overlaps(at) || orders.hasDescendant(at))\n return issue.fail(at, 'invalid-changes', 'Overlapping member transitions.');\n replacements.add(at, true);\n }\n } else if (change.kind === 'tree') {\n if (replacements.overlaps(change.at) || orders.hasDescendant(change.at))\n return issue.fail(change.at, 'invalid-changes', 'Overlapping tree transitions.');\n replacements.add(change.at, true);\n }\n }\n return sorted;\n};\n\nexport const changeCount = (changes: ChangeSet): number => {\n let count = 0;\n for (const change of changes.changes)\n count +=\n change.kind === 'members'\n ? change.members.length + (change.order ? 1 : 0)\n : change.kind === 'tree'\n ? 1 + change.nodes.length\n : 1;\n return count;\n};\n","import type { Infer, ObjectSchema, RootNodeOf } from '@/schema/model';\nimport type { DocumentRuntime } from './contract';\nimport type { RuntimeWriteDriver } from './driver';\nimport type { NotificationCenter } from './notification';\n\nexport type RuntimeState<TSchema extends ObjectSchema<object>> = {\n readonly schema: RootNodeOf<TSchema>;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks: number;\n};\n\nexport type RuntimeContext<TSchema extends ObjectSchema<object>> = {\n readonly state: RuntimeState<TSchema>;\n readonly owner: DocumentRuntime<TSchema>;\n readonly notifications: NotificationCenter<TSchema>;\n driver: RuntimeWriteDriver | undefined;\n bypassDepth: number;\n};\n\nconst contexts = new WeakMap<object, RuntimeContext<ObjectSchema<object>>>();\n\nexport const bindContext = <TSchema extends ObjectSchema<object>>(\n subject: object,\n context: RuntimeContext<TSchema>\n): void => {\n contexts.set(subject, context as unknown as RuntimeContext<ObjectSchema<object>>);\n};\n\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required?: true\n): RuntimeContext<TSchema>;\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required: false\n): RuntimeContext<TSchema> | undefined;\nexport function contextOf<TSchema extends ObjectSchema<object>>(\n subject: object,\n required = true\n): RuntimeContext<TSchema> | undefined {\n const context = contexts.get(subject);\n if (!context && required) throw new Error('Unknown Doxum runtime.');\n return context as unknown as RuntimeContext<TSchema> | undefined;\n}\n","import type { CommitSource, DocumentRuntime } from './contract';\nimport type { ObjectSchema } from '@/schema/model';\nimport { contextOf } from './context';\n\nexport type RuntimeWriteIntent =\n | { readonly kind: 'update'; readonly source: Extract<CommitSource, 'local' | 'system'> }\n | { readonly kind: 'apply'; readonly source: CommitSource }\n | { readonly kind: 'replace'; readonly source: Extract<CommitSource, 'system' | 'remote'> };\n\nexport type RuntimeWriteDriver = {\n readonly assertWritable: (intent: RuntimeWriteIntent) => void;\n};\n\nexport type RuntimeWriteDriverLease = {\n readonly run: <TResult>(run: () => TResult) => TResult;\n readonly dispose: () => void;\n};\n\nexport const assertRuntimeWritable = (runtime: object, intent: RuntimeWriteIntent): void => {\n const context = contextOf(runtime);\n if (context.bypassDepth === 0) context.driver?.assertWritable(intent);\n};\n\nexport const installRuntimeWriteDriver = <TSchema extends ObjectSchema<object>>(\n runtime: DocumentRuntime<TSchema>,\n driver: RuntimeWriteDriver\n): RuntimeWriteDriverLease => {\n const context = contextOf(runtime);\n if (context.driver) throw new Error('Doxum runtime already has a write driver.');\n context.driver = driver;\n let active = true;\n return Object.freeze({\n run: <TResult>(run: () => TResult): TResult => {\n if (!active) throw new Error('Doxum runtime write driver is no longer active.');\n context.bypassDepth += 1;\n try {\n return run();\n } finally {\n context.bypassDepth -= 1;\n }\n },\n dispose: (): void => {\n if (!active) return;\n active = false;\n if (context.driver === driver) context.driver = undefined;\n },\n });\n};\n"],"mappings":";;AAGA,MAAM,QAAQ,MAAmB,OAC/B,OAAO,OAAO,KAAK,OAAO,GAAG,GAAG,KAAK,MAAM,MAAM,KAAA;AACnD,MAAa,MAAM,UACjBA,eAAAA,SAAS,MAAM,IAAIA,eAAAA,SAAS,MAAM,MAAM;AAE1C,MAAa,aAAa,UAA6C;AACrE,KAAI,CAACA,eAAAA,SAAS,MAAM,IAAI,CAAC,MAAM,QAAQ,MAAM,SAAS,CAAE,QAAO;AAC/D,KAAI,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa,SAAU,QAAO;CAC/E,MAAM,2BAAW,IAAI,KAAa;AAClC,MAAK,MAAM,MAAM,MAAM,UAAU;AAC/B,MAAI,OAAO,OAAO,YAAY,SAAS,IAAI,GAAG,CAAE,QAAO;AACvD,WAAS,IAAI,GAAG;;AAElB,QAAO;;AAGT,MAAa,YAAY,MAAmB,OAAwB,OAAO,OAAO,KAAK,OAAO,GAAG;AAEjG,MAAa,UAAU,MAAmB,OACxC,KAAK,MAAM,GAAG,EAAE;AAElB,MAAa,YAAY,MAAmB,OAC1C,KAAK,MAAM,GAAG,EAAE;AAElB,MAAa,YAAY,UAAyC;AAChE,KAAI,CAAC,GAAG,MAAM,CAAE,QAAO;CACvB,MAAM,MAAM,OAAO,KAAK,MAAM,MAAM;AACpC,KAAI,IAAI,WAAW,EA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