doxum 0.1.21 → 0.1.22

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 (65) hide show
  1. package/README.md +21 -2
  2. package/dist/{access-BeSV5ve-.js → access-CZXv_DIF.js} +179 -37
  3. package/dist/access-CZXv_DIF.js.map +1 -0
  4. package/dist/{access-Bienf28h.cjs → access-D64MFRSm.cjs} +228 -38
  5. package/dist/access-D64MFRSm.cjs.map +1 -0
  6. package/dist/{advanced-COFJtWMT.js → advanced-BTStm2cW.js} +29 -25
  7. package/dist/advanced-BTStm2cW.js.map +1 -0
  8. package/dist/{advanced-FgdTwu5b.d.ts → advanced-CqrR_4dh.d.ts} +3 -3
  9. package/dist/{advanced-DfKc7TZR.d.cts → advanced-CyR5o3Xr.d.cts} +3 -3
  10. package/dist/{advanced-BRL5pN0y.cjs → advanced-GKZ-CZ6a.cjs} +29 -25
  11. package/dist/advanced-GKZ-CZ6a.cjs.map +1 -0
  12. package/dist/advanced.cjs +1 -1
  13. package/dist/advanced.d.cts +1 -1
  14. package/dist/advanced.d.ts +1 -1
  15. package/dist/advanced.js +1 -1
  16. package/dist/{contract-KG5XnQZt.d.ts → contract-CRrZ-3sF.d.cts} +64 -34
  17. package/dist/{contract-CdmDHRUq.d.cts → contract-CxiNcqMn.d.ts} +64 -34
  18. package/dist/{driver-Djr3BVvo.cjs → driver-BC06FEMF.cjs} +2 -2
  19. package/dist/{driver-Djr3BVvo.cjs.map → driver-BC06FEMF.cjs.map} +1 -1
  20. package/dist/{driver-CLYJOGDQ.js → driver-BqRjwFmU.js} +2 -2
  21. package/dist/{driver-CLYJOGDQ.js.map → driver-BqRjwFmU.js.map} +1 -1
  22. package/dist/index.cjs +480 -117
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +2 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +478 -115
  27. package/dist/index.js.map +1 -1
  28. package/dist/{integration-Z6MsfFI7.cjs → integration-BqDw7e2w.cjs} +3 -4
  29. package/dist/{integration-Z6MsfFI7.cjs.map → integration-BqDw7e2w.cjs.map} +1 -1
  30. package/dist/{integration-C4Isp8lJ.js → integration-CSXaF8HP.js} +2 -3
  31. package/dist/{integration-C4Isp8lJ.js.map → integration-CSXaF8HP.js.map} +1 -1
  32. package/dist/integration.cjs +5 -4
  33. package/dist/integration.d.cts +1 -1
  34. package/dist/integration.d.ts +1 -1
  35. package/dist/integration.js +4 -3
  36. package/dist/{issue-W0hT8u8D.js → issue-9U6YLYz3.js} +11 -6
  37. package/dist/issue-9U6YLYz3.js.map +1 -0
  38. package/dist/{issue-DjK1xp5K.cjs → issue-Bo0FIO3b.cjs} +11 -6
  39. package/dist/issue-Bo0FIO3b.cjs.map +1 -0
  40. package/dist/local-sync.cjs +2 -2
  41. package/dist/local-sync.d.cts +1 -1
  42. package/dist/local-sync.d.ts +1 -1
  43. package/dist/local-sync.js +2 -2
  44. package/dist/{notification-Bkjau6B6.js → notification-CrZHVx3a.js} +3 -59
  45. package/dist/notification-CrZHVx3a.js.map +1 -0
  46. package/dist/{notification-DJfouMEb.cjs → notification-DFoA9bQY.cjs} +3 -77
  47. package/dist/notification-DFoA9bQY.cjs.map +1 -0
  48. package/dist/react.cjs +4 -3
  49. package/dist/react.cjs.map +1 -1
  50. package/dist/react.js +3 -2
  51. package/dist/react.js.map +1 -1
  52. package/package.json +1 -1
  53. package/skills/doxum-runtime/SKILL.md +5 -0
  54. package/skills/doxum-runtime/references/guide.en.md +9 -0
  55. package/skills/doxum-runtime/references/guide.zh-CN.md +8 -0
  56. package/skills/doxum-runtime/references/projections.en.md +5 -0
  57. package/skills/doxum-runtime/references/projections.zh-CN.md +5 -0
  58. package/dist/access-BeSV5ve-.js.map +0 -1
  59. package/dist/access-Bienf28h.cjs.map +0 -1
  60. package/dist/advanced-BRL5pN0y.cjs.map +0 -1
  61. package/dist/advanced-COFJtWMT.js.map +0 -1
  62. package/dist/issue-DjK1xp5K.cjs.map +0 -1
  63. package/dist/issue-W0hT8u8D.js.map +0 -1
  64. package/dist/notification-Bkjau6B6.js.map +0 -1
  65. package/dist/notification-DJfouMEb.cjs.map +0 -1
@@ -1,60 +1,4 @@
1
- const require_issue = require("./issue-DjK1xp5K.cjs");
2
- //#region core/src/impact-target.ts
3
- const address = (target) => "at" in target ? target.at : target.address;
4
- const id = (target) => target.kind === "collection" && "id" in target ? target.id : void 0;
5
- const belongs = (target, schema) => !("schema" in target) || target.schema === schema;
6
- const same = (left, right) => {
7
- if (left.kind !== right.kind) return false;
8
- if ("schema" in left && "schema" in right && left.schema !== right.schema) return false;
9
- const leftAddress = address(left);
10
- const rightAddress = address(right);
11
- if (leftAddress.length !== rightAddress.length) return false;
12
- for (let index = 0; index < leftAddress.length; index += 1) if (leftAddress[index] !== rightAddress[index]) return false;
13
- return left.kind !== "collection" || id(left) === id(right);
14
- };
15
- const indexedAddress = (target) => {
16
- const key = id(target);
17
- return key === void 0 ? address(target) : [...address(target), key];
18
- };
19
- const affected = (target, values, orders) => {
20
- const at = indexedAddress(target);
21
- return id(target) !== void 0 ? values.hasAncestor(at) : values.overlaps(at) || orders.hasDescendant(at);
22
- };
23
- /** Targets are classified once; commit matching never builds a reverse impact index. */
24
- var SubscriptionIndex = class {
25
- ordinary = new require_issue.AddressIndex();
26
- membership = new require_issue.AddressIndex();
27
- constructor(schema) {
28
- this.schema = schema;
29
- }
30
- add(target, value) {
31
- if (belongs(target, this.schema)) (id(target) === void 0 ? this.ordinary : this.membership).add(indexedAddress(target), value);
32
- }
33
- delete(target, value) {
34
- if (belongs(target, this.schema)) (id(target) === void 0 ? this.ordinary : this.membership).delete(indexedAddress(target), value);
35
- }
36
- collect(changes, visit) {
37
- const values = this.ordinary.query(visit);
38
- const members = this.membership.query(visit, "descendants");
39
- const orders = this.ordinary.query(visit, "ancestors");
40
- for (const change of changes.changes) if (change.kind === "reset") {
41
- values([]);
42
- members([]);
43
- } else if (change.kind === "members") {
44
- values(change.at, change.members);
45
- members(change.at, change.members);
46
- if (change.order) orders(change.at);
47
- } else {
48
- values(change.at);
49
- members(change.at);
50
- }
51
- }
52
- clear() {
53
- this.ordinary.clear();
54
- this.membership.clear();
55
- }
56
- };
57
- //#endregion
1
+ const require_access = require("./access-D64MFRSm.cjs");
58
2
  //#region core/src/runtime/notification.ts
59
3
  const notifications = /* @__PURE__ */ new WeakMap();
60
4
  const readableOwners = /* @__PURE__ */ new WeakMap();
@@ -66,7 +10,7 @@ const createNotification = (runtime) => {
66
10
  const notification = {
67
11
  root: /* @__PURE__ */ new Set(),
68
12
  filtered: /* @__PURE__ */ new Set(),
69
- index: new SubscriptionIndex(runtime.schema),
13
+ index: new require_access.SubscriptionIndex(runtime.schema),
70
14
  cleanups: /* @__PURE__ */ new Set(),
71
15
  processors: [],
72
16
  candidates: /* @__PURE__ */ new Set(),
@@ -227,24 +171,12 @@ const disposeNotification = (notification) => {
227
171
  if (errors.length) throw new AggregateError(errors, "Projection disposal notification failed.");
228
172
  };
229
173
  //#endregion
230
- Object.defineProperty(exports, "affected", {
231
- enumerable: true,
232
- get: function() {
233
- return affected;
234
- }
235
- });
236
174
  Object.defineProperty(exports, "attachProjection", {
237
175
  enumerable: true,
238
176
  get: function() {
239
177
  return attachProjection;
240
178
  }
241
179
  });
242
- Object.defineProperty(exports, "belongs", {
243
- enumerable: true,
244
- get: function() {
245
- return belongs;
246
- }
247
- });
248
180
  Object.defineProperty(exports, "bindDocumentReadable", {
249
181
  enumerable: true,
250
182
  get: function() {
@@ -275,12 +207,6 @@ Object.defineProperty(exports, "notify", {
275
207
  return notify;
276
208
  }
277
209
  });
278
- Object.defineProperty(exports, "same", {
279
- enumerable: true,
280
- get: function() {
281
- return same;
282
- }
283
- });
284
210
  Object.defineProperty(exports, "shareNotification", {
285
211
  enumerable: true,
286
212
  get: function() {
@@ -306,4 +232,4 @@ Object.defineProperty(exports, "subscribeTargets", {
306
232
  }
307
233
  });
308
234
 
309
- //# sourceMappingURL=notification-DJfouMEb.cjs.map
235
+ //# sourceMappingURL=notification-DFoA9bQY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notification-DFoA9bQY.cjs","names":[],"sources":["../core/src/runtime/notification.ts"],"sourcesContent":["import type { ObjectNode, ImpactTarget } from '../schema';\nimport type {\n CommitListener,\n DocumentCommit,\n DocumentReadable,\n DocumentRuntime,\n Unsubscribe,\n ObserverError,\n} from './contract';\nimport * as target from '../impact-target';\n\nexport type ProjectionAttachment<TSchema extends ObjectNode> = {\n capture(commit: DocumentCommit<TSchema>): void;\n settle(): void;\n flush(): readonly ObserverError[];\n dispose(): void;\n};\ntype ProcessorEntry<TSchema extends ObjectNode> = {\n readonly processor: ProjectionAttachment<TSchema>;\n active: boolean;\n};\ntype RootEntry<TSchema extends ObjectNode> = {\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype FilteredEntry<TSchema extends ObjectNode> = {\n readonly targets: readonly ImpactTarget<unknown>[];\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\nexport type RuntimeNotification<TSchema extends ObjectNode> = {\n readonly root: Set<RootEntry<TSchema>>;\n readonly filtered: Set<FilteredEntry<TSchema>>;\n readonly index: target.SubscriptionIndex<FilteredEntry<TSchema>>;\n readonly cleanups: Set<() => void>;\n readonly processors: ProcessorEntry<TSchema>[];\n readonly candidates: Set<FilteredEntry<TSchema>>;\n readonly rootSnapshot: RootEntry<TSchema>[];\n notifying: boolean;\n};\n\nconst notifications = new WeakMap<object, RuntimeNotification<ObjectNode>>();\nconst readableOwners = new WeakMap<object, DocumentReadable<ObjectNode>>();\n\nexport const bindDocumentReadable = (\n readable: object,\n runtime: DocumentReadable<ObjectNode>\n): void => {\n readableOwners.set(readable, runtime);\n};\nexport const documentReadableOwner = (readable: object): DocumentReadable<ObjectNode> | undefined =>\n readableOwners.get(readable);\n\nexport const createNotification = <TSchema extends ObjectNode>(\n runtime: DocumentRuntime<TSchema>\n): RuntimeNotification<TSchema> => {\n const notification: RuntimeNotification<TSchema> = {\n root: new Set(),\n filtered: new Set(),\n index: new target.SubscriptionIndex(runtime.schema),\n cleanups: new Set(),\n processors: [],\n candidates: new Set(),\n rootSnapshot: [],\n notifying: false,\n };\n notifications.set(runtime as object, notification as RuntimeNotification<ObjectNode>);\n return notification;\n};\n\nconst notificationOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeNotification<TSchema> => {\n const value = notifications.get(runtime as object);\n if (!value) throw new Error('Unknown Doxum runtime.');\n return value as RuntimeNotification<TSchema>;\n};\n\nexport const shareNotification = <TSchema extends ObjectNode>(\n source: DocumentRuntime<TSchema>,\n target: DocumentReadable<TSchema>\n): void => {\n notifications.set(target as object, notificationOf(source) as RuntimeNotification<ObjectNode>);\n};\n\nexport const attachProjection = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n processor: ProjectionAttachment<TSchema>\n): Unsubscribe => {\n const notification = notificationOf(runtime);\n const entry: ProcessorEntry<TSchema> = { processor, active: true };\n notification.processors.push(entry);\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (!notification.notifying) {\n const index = notification.processors.indexOf(entry);\n if (index >= 0) notification.processors.splice(index, 1);\n }\n };\n};\n\nexport const subscribeRoot = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: RootEntry<TSchema> = { listener, active: true };\n notification.root.add(entry);\n return () => {\n entry.active = false;\n if (!notification.notifying) notification.root.delete(entry);\n else\n notification.cleanups.add(() => {\n notification.root.delete(entry);\n });\n };\n};\n\nexport const subscribeTargets = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: FilteredEntry<TSchema> = {\n targets: Object.freeze(targets.slice()),\n listener,\n active: true,\n };\n notification.filtered.add(entry);\n entry.targets.forEach(value => notification.index.add(value, entry));\n const remove = () => {\n notification.filtered.delete(entry);\n entry.targets.forEach(value => notification.index.delete(value, entry));\n };\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (notification.notifying) notification.cleanups.add(remove);\n else remove();\n };\n};\n\nexport const notify = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n): readonly ObserverError[] => {\n notification.notifying = true;\n const errors: ObserverError[] = [];\n const call = (listener: CommitListener<TSchema>): void => {\n try {\n listener(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'listener', error }));\n }\n };\n try {\n const processorCount = notification.processors.length;\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.capture(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.settle();\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n errors.push(...entry.processor.flush());\n } catch (error) {\n errors.push(Object.freeze({ phase: 'flush', error }));\n }\n }\n\n if (afterSettle) errors.push(...afterSettle());\n const candidates = notification.candidates;\n candidates.clear();\n if (notification.filtered.size)\n notification.index.collect(commit.changes, entry => candidates.add(entry));\n candidates.forEach(entry => {\n if (entry.active) call(entry.listener);\n });\n const rootSnapshot = notification.rootSnapshot;\n rootSnapshot.length = 0;\n notification.root.forEach(entry => rootSnapshot.push(entry));\n for (const entry of rootSnapshot) if (entry.active) call(entry.listener);\n } finally {\n notification.notifying = false;\n let writeIndex = 0;\n for (const entry of notification.processors)\n if (entry.active) notification.processors[writeIndex++] = entry;\n notification.processors.length = writeIndex;\n notification.cleanups.forEach(cleanup => cleanup());\n notification.cleanups.clear();\n }\n return Object.freeze(errors);\n};\n\nexport const subscribeDependencies = <S extends ObjectNode>(\n runtime: DocumentReadable<S>,\n targets: readonly ImpactTarget[],\n listener: CommitListener<S>\n): Unsubscribe => subscribeTargets(notificationOf(runtime), targets, listener);\n\nexport const disposeNotification = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>\n): void => {\n const attachments = notification.processors.slice();\n notification.root.clear();\n notification.filtered.clear();\n notification.index.clear();\n notification.cleanups.clear();\n notification.processors.length = 0;\n notification.candidates.clear();\n notification.rootSnapshot.length = 0;\n const errors: unknown[] = [];\n attachments.forEach(entry => {\n if (!entry.active) return;\n try {\n entry.processor.dispose();\n } catch (error) {\n errors.push(error);\n }\n });\n if (errors.length) throw new AggregateError(errors, 'Projection disposal notification failed.');\n};\n"],"mappings":";;AAyCA,MAAM,gCAAgB,IAAI,SAAkD;AAC5E,MAAM,iCAAiB,IAAI,SAA+C;AAE1E,MAAa,wBACX,UACA,YACS;AACT,gBAAe,IAAI,UAAU,QAAQ;;AAEvC,MAAa,yBAAyB,aACpC,eAAe,IAAI,SAAS;AAE9B,MAAa,sBACX,YACiC;CACjC,MAAM,eAA6C;EACjD,sBAAM,IAAI,KAAK;EACf,0BAAU,IAAI,KAAK;EACnB,OAAO,IAAA,eAAA,kBAA6B,QAAQ,OAAO;EACnD,0BAAU,IAAI,KAAK;EACnB,YAAY,EAAE;EACd,4BAAY,IAAI,KAAK;EACrB,cAAc,EAAE;EAChB,WAAW;EACZ;AACD,eAAc,IAAI,SAAmB,aAAgD;AACrF,QAAO;;AAGT,MAAM,kBACJ,YACiC;CACjC,MAAM,QAAQ,cAAc,IAAI,QAAkB;AAClD,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,yBAAyB;AACrD,QAAO;;AAGT,MAAa,qBACX,QACA,WACS;AACT,eAAc,IAAI,QAAkB,eAAe,OAAO,CAAoC;;AAGhG,MAAa,oBACX,SACA,cACgB;CAChB,MAAM,eAAe,eAAe,QAAQ;CAC5C,MAAM,QAAiC;EAAE;EAAW,QAAQ;EAAM;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AAa,WAAW,gBAAgB;AAC5D,eAAa,WAAW,SAAS;AACjC,eAAa,SAAS,SAAQ,YAAW,SAAS,CAAC;AACnD,eAAa,SAAS,OAAO;;AAE/B,QAAO,OAAO,OAAO,OAAO;;AAG9B,MAAa,yBACX,SACA,SACA,aACgB,iBAAiB,eAAe,QAAQ,EAAE,SAAS,SAAS;AAE9E,MAAa,uBACX,iBACS;CACT,MAAM,cAAc,aAAa,WAAW,OAAO;AACnD,cAAa,KAAK,OAAO;AACzB,cAAa,SAAS,OAAO;AAC7B,cAAa,MAAM,OAAO;AAC1B,cAAa,SAAS,OAAO;AAC7B,cAAa,WAAW,SAAS;AACjC,cAAa,WAAW,OAAO;AAC/B,cAAa,aAAa,SAAS;CACnC,MAAM,SAAoB,EAAE;AAC5B,aAAY,SAAQ,UAAS;AAC3B,MAAI,CAAC,MAAM,OAAQ;AACnB,MAAI;AACF,SAAM,UAAU,SAAS;WAClB,OAAO;AACd,UAAO,KAAK,MAAM;;GAEpB;AACF,KAAI,OAAO,OAAQ,OAAM,IAAI,eAAe,QAAQ,2CAA2C"}
package/dist/react.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_notification = require("./notification-DJfouMEb.cjs");
3
- const require_integration = require("./integration-Z6MsfFI7.cjs");
2
+ const require_access = require("./access-D64MFRSm.cjs");
3
+ const require_notification = require("./notification-DFoA9bQY.cjs");
4
+ const require_integration = require("./integration-BqDw7e2w.cjs");
4
5
  let react = require("react");
5
6
  //#region react/src/hooks.ts
6
7
  const ProjectionContext = (0, react.createContext)(void 0);
@@ -25,7 +26,7 @@ function useInput(input) {
25
26
  const objectIs = (previous, next) => Object.is(previous, next);
26
27
  const sameTargets = (left, right) => {
27
28
  if (left.length !== right.length) return false;
28
- for (let index = 0; index < left.length; index += 1) if (!require_notification.same(left[index], right[index])) return false;
29
+ for (let index = 0; index < left.length; index += 1) if (!require_access.same(left[index], right[index])) return false;
29
30
  return true;
30
31
  };
31
32
  function useDocumentSelector(runtime, selector, options) {
@@ -1 +1 @@
1
- {"version":3,"file":"react.cjs","names":["sameTarget","track","subscribeDependencies"],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n DocumentReadable,\n ObjectNode,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n} from 'doxum';\nimport { track, subscribeDependencies, sameTarget, type ImpactTarget } from 'doxum/integration';\nimport {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T, unknown>): T;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.readable(projection, selector, equality) : owner.readable(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const set = useCallback((next: T) => owner.set(input, next), [input, owner]);\n return useMemo(() => [value, set] as const, [set, value]);\n}\n\nexport type DocumentSelectorOptions<TResult> = {\n readonly isEqual?: (previous: TResult, next: TResult) => boolean;\n readonly server?: () => TResult;\n};\n\ntype SelectorCache<TSchema extends ObjectNode, TResult> = {\n readonly runtime: DocumentReadable<TSchema>;\n readonly value: TResult;\n readonly targets: readonly ImpactTarget<unknown>[];\n};\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\nconst sameTargets = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!sameTarget(left[index], right[index])) return false;\n return true;\n};\n\nexport function useDocumentSelector<TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n options?: DocumentSelectorOptions<TResult>\n): TResult {\n const equality = options?.isEqual ?? objectIs;\n const cache = useRef<SelectorCache<TSchema, TResult> | undefined>(undefined);\n const serverCache = useRef<\n | {\n readonly runtime: DocumentReadable<TSchema>;\n readonly selector: DocumentSelector<TSchema, TResult>;\n readonly source: (() => TResult) | undefined;\n readonly value: TResult;\n }\n | undefined\n >(undefined);\n\n const read = useMemo(() => {\n // Each selector closure owns its revision cache, including inline selectors\n // that allocate arrays or objects. Equality only compares distinct snapshots.\n let snapshot: { readonly revision: number; readonly value: TResult } | undefined;\n return (): TResult => {\n const revision = runtime.revision();\n if (snapshot?.revision === revision) return snapshot.value;\n const selection = track(runtime, selector);\n const previous = cache.current;\n const value =\n previous && previous.runtime === runtime && equality(previous.value, selection.value)\n ? previous.value\n : selection.value;\n cache.current = { runtime, value, targets: selection.targets };\n snapshot = { revision, value };\n return value;\n };\n }, [equality, runtime, selector]);\n\n const subscribe = useCallback(\n (listener: () => void) => {\n read();\n let targets = cache.current?.targets ?? [];\n let unsubscribe: () => void = () => undefined;\n const install = () => {\n if (targets.length === 0) return () => undefined;\n return subscribeDependencies(runtime, targets, onCommit);\n };\n const onCommit = () => {\n const previous = cache.current;\n const next = read();\n const nextTargets = cache.current?.targets ?? [];\n if (!sameTargets(targets, nextTargets)) {\n unsubscribe();\n targets = nextTargets;\n unsubscribe = install();\n }\n if (previous && !Object.is(previous.value, next)) listener();\n };\n unsubscribe = install();\n return () => unsubscribe();\n },\n [read, runtime]\n );\n\n const server = options?.server;\n const readServer = useCallback((): TResult => {\n const previous = serverCache.current;\n if (\n previous &&\n previous.source === server &&\n previous.runtime === runtime &&\n previous.selector === selector\n )\n return previous.value;\n const value = server ? server() : read();\n serverCache.current = { runtime, selector, source: server, value };\n return value;\n }, [read, server, runtime, selector]);\n\n return useSyncExternalStore(subscribe, read, readServer);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;;;;AAuBA,MAAM,qBAAA,GAAA,MAAA,eAAmF,KAAA,EAAU;AACnG,MAAa,qBAAqB,kBAAkB;AAQpD,SAAgB,cACd,YACA,UACA,WAA8C,OAAO,IAC9C;CAEP,MAAM,SAAA,GAAA,MAAA,YADqB,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;AAK7D,QAAO,aAAA,GAAA,MAAA,eAHE,WAAW,MAAM,SAAS,YAAY,UAAU,SAAS,GAAG,MAAM,SAAS,WAAW,EAC7F;EAAC;EAAU;EAAO;EAAY;EAAS,CAEd,CAAoB;;AAGjD,SAAgB,SAAY,OAAmD;CAE7E,MAAM,SAAA,GAAA,MAAA,YADqB,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;CAC7D,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,OAAA,GAAA,MAAA,cAAm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A,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,SAAA,GAAA,MAAA,gBAAsB;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
1
+ {"version":3,"file":"react.cjs","names":["sameTarget","track","subscribeDependencies"],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n DocumentReadable,\n ObjectNode,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n} from 'doxum';\nimport { track, subscribeDependencies, sameTarget, type ImpactTarget } from 'doxum/integration';\nimport {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T, unknown>): T;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.readable(projection, selector, equality) : owner.readable(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const set = useCallback((next: T) => owner.set(input, next), [input, owner]);\n return useMemo(() => [value, set] as const, [set, value]);\n}\n\nexport type DocumentSelectorOptions<TResult> = {\n readonly isEqual?: (previous: TResult, next: TResult) => boolean;\n readonly server?: () => TResult;\n};\n\ntype SelectorCache<TSchema extends ObjectNode, TResult> = {\n readonly runtime: DocumentReadable<TSchema>;\n readonly value: TResult;\n readonly targets: readonly ImpactTarget<unknown>[];\n};\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\nconst sameTargets = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!sameTarget(left[index], right[index])) return false;\n return true;\n};\n\nexport function useDocumentSelector<TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n options?: DocumentSelectorOptions<TResult>\n): TResult {\n const equality = options?.isEqual ?? objectIs;\n const cache = useRef<SelectorCache<TSchema, TResult> | undefined>(undefined);\n const serverCache = useRef<\n | {\n readonly runtime: DocumentReadable<TSchema>;\n readonly selector: DocumentSelector<TSchema, TResult>;\n readonly source: (() => TResult) | undefined;\n readonly value: TResult;\n }\n | undefined\n >(undefined);\n\n const read = useMemo(() => {\n // Each selector closure owns its revision cache, including inline selectors\n // that allocate arrays or objects. Equality only compares distinct snapshots.\n let snapshot: { readonly revision: number; readonly value: TResult } | undefined;\n return (): TResult => {\n const revision = runtime.revision();\n if (snapshot?.revision === revision) return snapshot.value;\n const selection = track(runtime, selector);\n const previous = cache.current;\n const value =\n previous && previous.runtime === runtime && equality(previous.value, selection.value)\n ? previous.value\n : selection.value;\n cache.current = { runtime, value, targets: selection.targets };\n snapshot = { revision, value };\n return value;\n };\n }, [equality, runtime, selector]);\n\n const subscribe = useCallback(\n (listener: () => void) => {\n read();\n let targets = cache.current?.targets ?? [];\n let unsubscribe: () => void = () => undefined;\n const install = () => {\n if (targets.length === 0) return () => undefined;\n return subscribeDependencies(runtime, targets, onCommit);\n };\n const onCommit = () => {\n const previous = cache.current;\n const next = read();\n const nextTargets = cache.current?.targets ?? [];\n if (!sameTargets(targets, nextTargets)) {\n unsubscribe();\n targets = nextTargets;\n unsubscribe = install();\n }\n if (previous && !Object.is(previous.value, next)) listener();\n };\n unsubscribe = install();\n return () => unsubscribe();\n },\n [read, runtime]\n );\n\n const server = options?.server;\n const readServer = useCallback((): TResult => {\n const previous = serverCache.current;\n if (\n previous &&\n previous.source === server &&\n previous.runtime === runtime &&\n previous.selector === selector\n )\n return previous.value;\n const value = server ? server() : read();\n serverCache.current = { runtime, selector, source: server, value };\n return value;\n }, [read, server, runtime, selector]);\n\n return useSyncExternalStore(subscribe, read, readServer);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;;;;;AAuBA,MAAM,qBAAA,GAAA,MAAA,eAAmF,KAAA,EAAU;AACnG,MAAa,qBAAqB,kBAAkB;AAQpD,SAAgB,cACd,YACA,UACA,WAA8C,OAAO,IAC9C;CAEP,MAAM,SAAA,GAAA,MAAA,YADqB,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;AAK7D,QAAO,aAAA,GAAA,MAAA,eAHE,WAAW,MAAM,SAAS,YAAY,UAAU,SAAS,GAAG,MAAM,SAAS,WAAW,EAC7F;EAAC;EAAU;EAAO;EAAY;EAAS,CAEd,CAAoB;;AAGjD,SAAgB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AC,QAAQ,CAAC;CAC/F,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC5D,MAAM,SAAA,GAAA,MAAA,sBAA6B,WAAW,MAAM,KAAK;CACzD,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,SAAA,GAAA,MAAA,gBAAsB;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
package/dist/react.js CHANGED
@@ -1,5 +1,6 @@
1
- import { c as subscribeDependencies, p as same } from "./notification-Bkjau6B6.js";
2
- import { t as track } from "./integration-C4Isp8lJ.js";
1
+ import { m as same } from "./access-CZXv_DIF.js";
2
+ import { c as subscribeDependencies } from "./notification-CrZHVx3a.js";
3
+ import { t as track } from "./integration-CSXaF8HP.js";
3
4
  import { createContext, useCallback, useContext, useMemo, useRef, useSyncExternalStore } from "react";
4
5
  //#region react/src/hooks.ts
5
6
  const ProjectionContext = createContext(void 0);
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":["sameTarget"],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n DocumentReadable,\n ObjectNode,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n} from 'doxum';\nimport { track, subscribeDependencies, sameTarget, type ImpactTarget } from 'doxum/integration';\nimport {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T, unknown>): T;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.readable(projection, selector, equality) : owner.readable(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const set = useCallback((next: T) => owner.set(input, next), [input, owner]);\n return useMemo(() => [value, set] as const, [set, value]);\n}\n\nexport type DocumentSelectorOptions<TResult> = {\n readonly isEqual?: (previous: TResult, next: TResult) => boolean;\n readonly server?: () => TResult;\n};\n\ntype SelectorCache<TSchema extends ObjectNode, TResult> = {\n readonly runtime: DocumentReadable<TSchema>;\n readonly value: TResult;\n readonly targets: readonly ImpactTarget<unknown>[];\n};\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\nconst sameTargets = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!sameTarget(left[index], right[index])) return false;\n return true;\n};\n\nexport function useDocumentSelector<TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n options?: DocumentSelectorOptions<TResult>\n): TResult {\n const equality = options?.isEqual ?? objectIs;\n const cache = useRef<SelectorCache<TSchema, TResult> | undefined>(undefined);\n const serverCache = useRef<\n | {\n readonly runtime: DocumentReadable<TSchema>;\n readonly selector: DocumentSelector<TSchema, TResult>;\n readonly source: (() => TResult) | undefined;\n readonly value: TResult;\n }\n | undefined\n >(undefined);\n\n const read = useMemo(() => {\n // Each selector closure owns its revision cache, including inline selectors\n // that allocate arrays or objects. Equality only compares distinct snapshots.\n let snapshot: { readonly revision: number; readonly value: TResult } | undefined;\n return (): TResult => {\n const revision = runtime.revision();\n if (snapshot?.revision === revision) return snapshot.value;\n const selection = track(runtime, selector);\n const previous = cache.current;\n const value =\n previous && previous.runtime === runtime && equality(previous.value, selection.value)\n ? previous.value\n : selection.value;\n cache.current = { runtime, value, targets: selection.targets };\n snapshot = { revision, value };\n return value;\n };\n }, [equality, runtime, selector]);\n\n const subscribe = useCallback(\n (listener: () => void) => {\n read();\n let targets = cache.current?.targets ?? [];\n let unsubscribe: () => void = () => undefined;\n const install = () => {\n if (targets.length === 0) return () => undefined;\n return subscribeDependencies(runtime, targets, onCommit);\n };\n const onCommit = () => {\n const previous = cache.current;\n const next = read();\n const nextTargets = cache.current?.targets ?? [];\n if (!sameTargets(targets, nextTargets)) {\n unsubscribe();\n targets = nextTargets;\n unsubscribe = install();\n }\n if (previous && !Object.is(previous.value, next)) listener();\n };\n unsubscribe = install();\n return () => unsubscribe();\n },\n [read, runtime]\n );\n\n const server = options?.server;\n const readServer = useCallback((): TResult => {\n const previous = serverCache.current;\n if (\n previous &&\n previous.source === server &&\n previous.runtime === runtime &&\n previous.selector === selector\n )\n return previous.value;\n const value = server ? server() : read();\n serverCache.current = { runtime, selector, source: server, value };\n return value;\n }, [read, server, runtime, selector]);\n\n return useSyncExternalStore(subscribe, read, readServer);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;;;AAuBA,MAAM,oBAAoB,cAA+D,KAAA,EAAU;AACnG,MAAa,qBAAqB,kBAAkB;AAQpD,SAAgB,cACd,YACA,UACA,WAA8C,OAAO,IAC9C;CAEP,MAAM,QADU,WAAW,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;AAK7D,QAAO,YAJU,cACR,WAAW,MAAM,SAAS,YAAY,UAAU,SAAS,GAAG,MAAM,SAAS,WAAW,EAC7F;EAAC;EAAU;EAAO;EAAY;EAAS,CAEd,CAAoB;;AAGjD,SAAgB,SAAY,OAAmD;CAE7E,MAAM,QADU,WAAW,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;CAC7D,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,MAAM,aAAa,SAAY,MAAM,IAAI,OAAO,KAAK,EAAE,CAAC,OAAO,MAAM,CAAC;AAC5E,QAAO,cAAc,CAAC,OAAO,IAAI,EAAW,CAAC,KAAK,MAAM,CAAC;;AAc3D,MAAM,YAAe,UAAa,SAAqB,OAAO,GAAG,UAAU,KAAK;AAChF,MAAM,eACJ,MACA,UACY;AACZ,KAAI,KAAK,WAAW,MAAM,OAAQ,QAAO;AACzC,MAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,EAChD,KAAI,CAACA,KAAW,KAAK,QAAQ,MAAM,OAAO,CAAE,QAAO;AACrD,QAAO;;AAGT,SAAgB,oBACd,SACA,UACA,SACS;CACT,MAAM,WAAW,SAAS,WAAW;CACrC,MAAM,QAAQ,OAAoD,KAAA,EAAU;CAC5E,MAAM,cAAc,OAQlB,KAAA,EAAU;CAEZ,MAAM,OAAO,cAAc;EAGzB,IAAI;AACJ,eAAsB;GACpB,MAAM,WAAW,QAA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;AAG1D,SAAgB,YAAe,UAA0B;CACvD,MAAM,YAAY,aAAa,aAAyB,SAAS,UAAU,SAAS,EAAE,CAAC,SAAS,CAAC;CACjG,MAAM,OAAO,kBAAkB,SAAS,SAAS,EAAE,CAAC,SAAS,CAAC;AAC9D,QAAO,qBAAqB,WAAW,MAAM,KAAK;;AAGpD,SAAgB,WAAoB,SAGlC;CACA,MAAM,YAAY,aAAa,aAAyB,QAAQ,UAAU,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC/F,MAAM,OAAO,kBAAkB,QAAQ,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC5D,MAAM,QAAQ,qBAAqB,WAAW,MAAM,KAAK;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,QAAO,eAAe;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
1
+ {"version":3,"file":"react.js","names":["sameTarget"],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n DocumentReadable,\n ObjectNode,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n} from 'doxum';\nimport { track, subscribeDependencies, sameTarget, type ImpactTarget } from 'doxum/integration';\nimport {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T, unknown>): T;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T, unknown>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.readable(projection, selector, equality) : owner.readable(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const set = useCallback((next: T) => owner.set(input, next), [input, owner]);\n return useMemo(() => [value, set] as const, [set, value]);\n}\n\nexport type DocumentSelectorOptions<TResult> = {\n readonly isEqual?: (previous: TResult, next: TResult) => boolean;\n readonly server?: () => TResult;\n};\n\ntype SelectorCache<TSchema extends ObjectNode, TResult> = {\n readonly runtime: DocumentReadable<TSchema>;\n readonly value: TResult;\n readonly targets: readonly ImpactTarget<unknown>[];\n};\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\nconst sameTargets = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!sameTarget(left[index], right[index])) return false;\n return true;\n};\n\nexport function useDocumentSelector<TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n options?: DocumentSelectorOptions<TResult>\n): TResult {\n const equality = options?.isEqual ?? objectIs;\n const cache = useRef<SelectorCache<TSchema, TResult> | undefined>(undefined);\n const serverCache = useRef<\n | {\n readonly runtime: DocumentReadable<TSchema>;\n readonly selector: DocumentSelector<TSchema, TResult>;\n readonly source: (() => TResult) | undefined;\n readonly value: TResult;\n }\n | undefined\n >(undefined);\n\n const read = useMemo(() => {\n // Each selector closure owns its revision cache, including inline selectors\n // that allocate arrays or objects. Equality only compares distinct snapshots.\n let snapshot: { readonly revision: number; readonly value: TResult } | undefined;\n return (): TResult => {\n const revision = runtime.revision();\n if (snapshot?.revision === revision) return snapshot.value;\n const selection = track(runtime, selector);\n const previous = cache.current;\n const value =\n previous && previous.runtime === runtime && equality(previous.value, selection.value)\n ? previous.value\n : selection.value;\n cache.current = { runtime, value, targets: selection.targets };\n snapshot = { revision, value };\n return value;\n };\n }, [equality, runtime, selector]);\n\n const subscribe = useCallback(\n (listener: () => void) => {\n read();\n let targets = cache.current?.targets ?? [];\n let unsubscribe: () => void = () => undefined;\n const install = () => {\n if (targets.length === 0) return () => undefined;\n return subscribeDependencies(runtime, targets, onCommit);\n };\n const onCommit = () => {\n const previous = cache.current;\n const next = read();\n const nextTargets = cache.current?.targets ?? [];\n if (!sameTargets(targets, nextTargets)) {\n unsubscribe();\n targets = nextTargets;\n unsubscribe = install();\n }\n if (previous && !Object.is(previous.value, next)) listener();\n };\n unsubscribe = install();\n return () => unsubscribe();\n },\n [read, runtime]\n );\n\n const server = options?.server;\n const readServer = useCallback((): TResult => {\n const previous = serverCache.current;\n if (\n previous &&\n previous.source === server &&\n previous.runtime === runtime &&\n previous.selector === selector\n )\n return previous.value;\n const value = server ? server() : read();\n serverCache.current = { runtime, selector, source: server, value };\n return value;\n }, [read, server, runtime, selector]);\n\n return useSyncExternalStore(subscribe, read, readServer);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;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,SAAS,SAAS,EAAE,CAAC,SAAS,CAAC;AAC9D,QAAO,qBAAqB,WAAW,MAAM,KAAK;;AAGpD,SAAgB,WAAoB,SAGlC;CACA,MAAM,YAAY,aAAa,aAAyB,QAAQ,UAAU,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC/F,MAAM,OAAO,kBAAkB,QAAQ,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC5D,MAAM,QAAQ,qBAAqB,WAAW,MAAM,KAAK;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,QAAO,eAAe;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doxum",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Doxum is a typed runtime for complex mutable documents.",
@@ -24,6 +24,11 @@ Before runtime changes read [invariants](references/invariants.en.md) or
24
24
  object or variant members whose Draft type contains collection tools.
25
25
  - Ordered table/list Drafts use move(key | readonly key[], anchor?) for relative
26
26
  movement and reorder(keys) for an exact full-membership permutation.
27
+ - Trees may be empty. `tree(field(...))` requires every existing node to own `value`;
28
+ use `tree(optional(field(...)))` only when node payload absence is part of the model.
29
+ `optional(tree(...))` controls whole-tree presence independently.
30
+ - Tree projection paths reuse ordinary source protocols: `tree.rootId` is scalar,
31
+ `tree.nodes` is keyed, and `tree.nodes.item(id)` is a single-node value.
27
32
  - Expected business failure throws TransactionRejected. Other exceptions roll back
28
33
  and rethrow unchanged. Callback returns carry business values and notices.
29
34
  - Commits contain final reversible ChangeSets. History and impact share those facts.
@@ -66,6 +66,9 @@ present undefined. Variant tags are readonly; change branch by whole replacement
66
66
  For table/list, `move(key | readonly key[], anchor?)` preserves a moved selection's
67
67
  current relative order and resolves the anchor after removal. `reorder(keys)` requires
68
68
  an exact permutation of current membership and changes only order.
69
+ Trees may be empty. `tree(field(...))` requires an own `value` on every existing
70
+ node; `tree(optional(field(...)))` explicitly permits missing node payloads, while
71
+ `optional(tree(...))` independently permits the whole tree member to be absent.
69
72
 
70
73
  Pure synchronous functions and Standard Schema v1 validators receive original input.
71
74
  They must not mutate it; successful output is ignored, with no copy or deep conversion
@@ -97,6 +100,12 @@ remain explicit. Retained state, reverse indexes and keyed output patches belong
97
100
  the isolated `doxum/advanced` incremental entry points. See the [projection
98
101
  reference](projections.en.md) for lifecycle, draft semantics, selector tracking,
99
102
  batching and recovery.
103
+ Tree structure uses the same projection source protocols: observe `path.tree.rootId`
104
+ as a scalar, `path.tree.nodes` as a keyed collection, or
105
+ `path.tree.nodes.item(id)` as a single node. Committed tree-node groups route directly
106
+ to affected keyed entries and the existing `CollectionOutput` publishes ordinary
107
+ `CollectionChange` entries; unrelated nodes keep stable snapshot references instead
108
+ of being resnapshotted.
100
109
  `input` and `observe(source)` connect external boundary values, including
101
110
  eventful value and collection sources. Dispose the
102
111
  Runtime with the owning service. `runtime.batch` defers projection settlement and
@@ -58,6 +58,9 @@ table/list/tree 的 `replace(id, value)` 只替换已存在成员,保持 table
58
58
  table/list 的 `move(key | readonly key[], anchor?)` 会保持 moved selection 当前的相对顺序,
59
59
  并在移除 selection 后解析 anchor;`reorder(keys)` 要求与当前 membership 完全一致的排列,
60
60
  只改变顺序而不改变成员值。
61
+ tree 可以为空。`tree(field(...))` 要求每个已存在节点都拥有自己的 `value`;只有
62
+ `tree(optional(field(...)))` 才允许节点缺失 payload,而 `optional(tree(...))` 独立控制整棵
63
+ tree 成员是否可以缺失。
61
64
 
62
65
  校验器是纯同步函数或 Standard Schema v1,直接接收原始引用且不得修改它。
63
66
  成功返回值被忽略,不复制输入,也不深度检查转换;数据转换在进入 Doxum 前完成。
@@ -83,6 +86,11 @@ observerErrors 属于已提交结果。
83
86
  `createProjectionRuntime({ onError })` owner 物化和管理。保留状态、反向索引和
84
87
  keyed patch 放在隔离的 `doxum/advanced` incremental 入口。生命周期、draft、
85
88
  selector 追踪、batch 与故障恢复见 [Projection 参考](projections.zh-CN.md)。
89
+ tree 结构复用同一套 projection source 协议:`path.tree.rootId` 是 scalar,
90
+ `path.tree.nodes` 是 keyed collection,`path.tree.nodes.item(id)` 是单节点 value。
91
+ committed tree node group 直接路由到受影响的 keyed entry,由现有
92
+ `CollectionOutput` 发布普通 `CollectionChange`;未变化节点保持稳定的 snapshot
93
+ 引用,不再因单节点变化而全部重新 snapshot。
86
94
  `input` 与 `observe(source)` 接入外部边界值,包括带事件的 value 和 collection
87
95
  source。随所属服务 dispose Runtime。
88
96
  `runtime.batch` 推迟投影结算与通知,但不推迟文档提交和文档通知;内部读取上次发布值,
@@ -25,6 +25,11 @@ sources use `kind: 'value'` or `kind: 'collection'`; the caller still uses only
25
25
  Schema maps, tables, and `list(field, { keyOf })` nodes are all keyed collection
26
26
  paths. A list uses its schema `keyOf` identity and preserves document order in
27
27
  iteration; array-valued fields remain scalar value observations.
28
+ Tree structure reuses the same source kinds: `path.tree.rootId` is a scalar,
29
+ `path.tree.nodes` is a keyed collection, and `path.tree.nodes.item(id)` is a
30
+ single-node value. Committed tree-node groups route directly to affected keyed
31
+ entries, and the existing `CollectionOutput` publishes ordinary `CollectionChange`
32
+ entries, so unrelated node snapshots keep their identity.
28
33
 
29
34
  External events are smaller than Runtime contexts. A value event carries the new
30
35
  `value` and `revision`; a collection event carries a stable `previous` read,
@@ -23,6 +23,11 @@ source 通过 `kind: 'value'` 或 `kind: 'collection'` 区分语义,但调用
23
23
  schema map、table 和 `list(field, { keyOf })` 都是 keyed collection path。list
24
24
  直接使用 schema 的 `keyOf` 作为稳定 identity,并按文档顺序迭代;数组类型的普通
25
25
  `field(...)` 仍然是 scalar value observation。
26
+ tree 结构复用相同的 source 类型:`path.tree.rootId` 是 scalar,
27
+ `path.tree.nodes` 是 keyed collection,`path.tree.nodes.item(id)` 是单节点 value。
28
+ tree 的 committed node group 直接路由到受影响的 keyed entry,由现有
29
+ `CollectionOutput` 生成普通 `CollectionChange`;未变化节点的 snapshot identity
30
+ 保持稳定。
26
31
 
27
32
  External event 不再复用 Runtime context:value event 提供新 `value` 和
28
33
  `revision`;collection event 提供稳定的 `previous` read、`revision` 和可选的
@@ -1 +0,0 @@
1
- {"version":3,"file":"access-BeSV5ve-.js","names":["anchor.keys","validTree","anchor.equal","remove","anchor.valid","index","anchor.index","remove","replace","insert","keys","anchor.keys","anchor.valid","anchor.index","replace","anchor.indexedKeys","remove","replace","move","anchor.moveSelection","anchor.equal","anchor.listSequence","anchor.matches","anchor.indexedKeys","tree.contains","tree.parent","children","tree.children"],"sources":["../core/src/schema-value.ts","../core/src/mutation/operations/map.ts","../core/src/mutation/operations/table.ts","../core/src/mutation/operations/list.ts","../core/src/mutation/operations/tree.ts","../core/src/mutation/operations/order.ts","../core/src/access/scope.ts","../core/src/runtime/contract.ts","../core/src/runtime/access.ts"],"sourcesContent":["import type { DocumentAddress, DocumentNode, Infer } from './schema';\nimport { compiledShape } from './address';\nimport { isPlainObject, isRecord } from './value/ownership';\nimport { validate as validTree } from './mutation/tree';\nimport * as anchor from './mutation/anchor';\nimport { profile } from './profile';\n\n/** Pure synchronous validation. Successful output is ignored; input is never transformed. */\nexport type Validator<T> =\n | ((value: unknown) => T)\n | {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: unknown; readonly output: T };\n validate(value: unknown):\n | { readonly value: T; readonly issues?: undefined }\n | {\n readonly issues: readonly {\n readonly message: string;\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[];\n }[];\n }\n | PromiseLike<unknown>;\n };\n };\n\nexport type ParseIssue = {\n readonly address: DocumentAddress;\n readonly code: 'invalid-value' | 'invalid-key' | 'missing-validator' | 'invalid-tree';\n readonly message: string;\n};\nexport class ParseError extends TypeError {\n readonly issues: readonly ParseIssue[];\n constructor(issue: ParseIssue) {\n super(`${issue.message} at ${JSON.stringify(issue.address)}`);\n this.name = 'ParseError';\n this.issues = Object.freeze([\n Object.freeze({ ...issue, address: Object.freeze([...issue.address]) }),\n ]);\n }\n}\n\nconst issue = (\n address: DocumentAddress,\n message: string,\n code: ParseIssue['code'] = 'invalid-value'\n): ParseIssue => ({ address, message, code });\n\nexport const checkScalar = (\n validator: Validator<unknown> | undefined,\n value: unknown,\n address: DocumentAddress,\n strict: boolean\n): ParseIssue | undefined => {\n if (!validator)\n return strict\n ? issue(address, 'A validator is required to parse an opaque value.', 'missing-validator')\n : undefined;\n try {\n const result =\n typeof validator === 'function' ? validator(value) : validator['~standard'].validate(value);\n if (\n result &&\n (typeof result === 'object' || typeof result === 'function') &&\n 'then' in result &&\n typeof result.then === 'function'\n )\n return issue(address, 'Validators must be synchronous.');\n if (typeof validator !== 'function') {\n if (!isRecord(result)) return issue(address, 'Malformed validator result.');\n if (Array.isArray(result.issues)) {\n const first = result.issues[0];\n return issue(\n [\n ...address,\n ...(first?.path ?? []).map((part: PropertyKey | { key: PropertyKey }) =>\n String(typeof part === 'object' ? part.key : part)\n ),\n ],\n first?.message ?? 'Value validation failed.'\n );\n }\n if (!Object.hasOwn(result, 'value')) return issue(address, 'Malformed validator result.');\n }\n return undefined;\n } catch (error) {\n return issue(address, error instanceof Error ? error.message : 'Value validation failed.');\n }\n};\n\nexport const checkKey = (\n validator: Validator<string> | undefined,\n value: unknown,\n address: DocumentAddress\n): ParseIssue | undefined => {\n if (typeof value !== 'string')\n return issue(address, 'Collection keys must be strings.', 'invalid-key');\n const failure = checkScalar(validator, value, address, false);\n return failure ? { ...failure, code: 'invalid-key' } : undefined;\n};\n\nexport const checkValue = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress = [],\n strict = false\n): ParseIssue | undefined => {\n if (node.optional && value === undefined) return undefined;\n if (node.kind === 'field') return checkScalar(node.validator, value, address, strict);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isPlainObject(value)) return issue(address, 'Expected an object.');\n if (node.kind === 'variant') {\n const tag = value[node.tag];\n if (\n !Object.hasOwn(value, node.tag) ||\n typeof tag !== 'string' ||\n !Object.hasOwn(node.variants, tag)\n )\n return issue([...address, node.tag], 'Unknown variant tag.');\n }\n const { members } = compiledShape(node, value)!;\n for (const key of Reflect.ownKeys(value)) {\n if (node.kind === 'variant' && key === node.tag) continue;\n if (typeof key !== 'string' || !members.has(key))\n return issue([...address, String(key)], 'Property is not declared in the object schema.');\n }\n for (const [key, member] of members) {\n const child = member.node;\n if (!Object.prototype.hasOwnProperty.call(value, key) && !child.optional)\n return issue([...address, key], 'Required property is missing.');\n const failure = checkValue(child, value[key], [...address, key], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'table' || node.kind === 'map') {\n if (!isPlainObject(value)) return issue(address, 'Expected a collection object.');\n const entries = node.kind === 'table' ? value.byId : value;\n if (!isPlainObject(entries)) return issue(address, 'Expected a byId object.');\n if (node.kind === 'table') {\n if (!Array.isArray(value.ids) || value.ids.length !== Object.keys(entries).length)\n return issue(address, 'Table ids and entries must agree.');\n const seen = new Set<string>();\n for (const id of value.ids) {\n const failure = checkKey(node.key, id, address);\n if (failure) return failure;\n if (seen.has(id) || !Object.prototype.hasOwnProperty.call(entries, id))\n return issue(address, 'Table ids must be unique and reference existing entries.');\n seen.add(id);\n }\n }\n for (const id of Object.keys(entries)) {\n const failure =\n checkKey(node.key, id, [...address, id]) ??\n checkValue(node.value, entries[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'list') {\n if (!Array.isArray(value)) return issue(address, 'Expected a list.');\n const seen = new Set<string>();\n const order = anchor.keys(value, node.keyOf);\n for (let i = 0; i < value.length; i++) {\n const failure = checkValue(node.value, value[i], [...address, String(i)], strict);\n if (failure) return failure;\n let key: unknown;\n try {\n key = order.at(i);\n } catch {\n return issue(address, 'List keyOf failed.');\n }\n if (typeof key !== 'string' || seen.has(key))\n return issue(address, 'List keys must be unique strings.', 'invalid-key');\n seen.add(key);\n }\n return undefined;\n }\n if (!validTree(value)) return issue(address, 'Invalid tree structure.', 'invalid-tree');\n if (isRecord(value) && isRecord(value.nodes)) {\n for (const id of Object.keys(value.nodes)) {\n const entry = value.nodes[id];\n if (isRecord(entry) && Object.prototype.hasOwnProperty.call(entry, 'value')) {\n const failure = checkValue(node.value, entry.value, [...address, id], strict);\n if (failure) return failure;\n }\n }\n }\n return undefined;\n};\n\n/** Copy editable structure; atomic payloads retain their immutable ownership contract. */\nexport const copyValue = (node: DocumentNode, value: unknown): unknown => {\n if (value === undefined || node.kind === 'field') return value;\n profile.copy.structure();\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(value)) {\n const result = Object.create(Object.getPrototypeOf(value));\n const { members } = compiledShape(node, value)!;\n for (const key of Object.getOwnPropertyNames(value)) {\n Object.defineProperty(result, key, {\n value:\n node.kind === 'variant' && key === node.tag\n ? value[key]\n : copyValue(members.get(key)!.node, value[key]),\n writable: true,\n enumerable: Object.getOwnPropertyDescriptor(value, key)?.enumerable,\n configurable: true,\n });\n }\n return result;\n }\n if ((node.kind === 'table' || node.kind === 'map') && isRecord(value)) {\n const entries = (node.kind === 'table' ? value.byId : value) as Record<string, unknown>;\n const result = Object.fromEntries(\n Object.keys(entries).map(id => [id, copyValue(node.value, entries[id])])\n );\n return node.kind === 'table' ? { ids: [...(value.ids as string[])], byId: result } : result;\n }\n if (node.kind === 'list') return [...(value as unknown[])];\n if (node.kind === 'tree' && isRecord(value)) {\n const entries = value.nodes as Record<string, { children: readonly string[] }>;\n return {\n ...value,\n nodes: Object.fromEntries(\n Object.entries(entries).map(([id, n]) => [id, { ...n, children: [...n.children] }])\n ),\n };\n }\n return value;\n};\n\nexport const equalValue = (node: DocumentNode, left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true;\n if (node.kind === 'field' || left === undefined || right === undefined) return false;\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(left) && isRecord(right)) {\n if (node.kind === 'variant' && left[node.tag] !== right[node.tag]) return false;\n for (const [key, member] of compiledShape(node, left)!.members) {\n if (Object.hasOwn(left, key) !== Object.hasOwn(right, key)) return false;\n if (!equalValue(member.node, left[key], right[key])) return false;\n }\n return true;\n }\n if (node.kind === 'list' && Array.isArray(left) && Array.isArray(right))\n return (\n left.length === right.length && left.every((v, i) => equalValue(node.value, v, right[i]))\n );\n if (node.kind === 'table' && isRecord(left) && isRecord(right))\n return (\n anchor.equal(left.ids as string[], right.ids as string[]) &&\n equalValue({ kind: 'map', value: node.value }, left.byId, right.byId)\n );\n if (node.kind === 'tree' && isRecord(left) && isRecord(right)) {\n if (left.rootId !== right.rootId) return false;\n const a = left.nodes as Record<\n string,\n { parentId?: string; children: string[]; value?: unknown }\n >,\n b = right.nodes as typeof a;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(\n id =>\n Object.hasOwn(b, id) &&\n a[id].parentId === b[id].parentId &&\n anchor.equal(a[id].children, b[id].children) &&\n Object.hasOwn(a[id], 'value') === Object.hasOwn(b[id], 'value') &&\n equalValue(node.value, a[id].value, b[id].value)\n )\n );\n }\n if (node.kind === 'map' && isRecord(left) && isRecord(right)) {\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && equalValue(node.value, left[key], right[key]))\n );\n }\n return false;\n};\n\nexport const parse = <N extends DocumentNode>(node: N, input: unknown): Infer<N> => {\n const valueNode: DocumentNode = node;\n const failure = checkValue(valueNode, input, [], true);\n if (failure) throw new ParseError(failure);\n return copyValue(valueNode, input) as Infer<N>;\n};\n","import type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport { fail } from '../issue';\n\nexport function put(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n if (container.node.kind !== 'map')\n return fail(container.at, 'invalid-collection', 'Expected a map.');\n session.writeMember(container, id, value, 'set');\n}\n\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n if (container.node.kind !== 'map')\n return fail(container.at, 'invalid-collection', 'Expected a map.');\n session.writeMember(container, id, undefined, 'remove');\n}\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\nexport function create(\n session: MutationSession,\n container: ResolvedContainer,\n entries: readonly { id: string; value: unknown }[],\n position?: DocumentAnchor\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n if (!anchor.valid(table.ids, position))\n return fail(at, 'invalid-anchor', 'Unknown table anchor.');\n const ids = new Set<string>();\n for (const entry of entries) {\n if (Object.hasOwn(table.byId, entry.id) || ids.has(entry.id))\n return fail(at, 'duplicate-entity', 'Table key already exists.');\n ids.add(entry.id);\n }\n if (!entries.length) return;\n const index = anchor.index(table.ids, position);\n for (const entry of entries) session.writeMember(container, entry.id, entry.value, 'set');\n const length = table.ids.length;\n table.ids.length += entries.length;\n table.ids.copyWithin(index + entries.length, index, length);\n for (let i = 0; i < entries.length; i++) table.ids[index + i] = entries[i].id;\n}\nexport function remove(\n session: MutationSession,\n container: ResolvedContainer,\n ids: readonly string[]\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n for (const id of ids)\n if (!Object.hasOwn(table.byId, id))\n return fail(at, 'missing-entity', 'Table key does not exist.');\n if (!ids.length) return;\n const removed = new Set(ids);\n for (const id of removed) session.writeMember(container, id, undefined, 'remove');\n table.ids = table.ids.filter(id => !removed.has(id));\n}\n\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: tableValue } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = tableValue as { byId: Record<string, unknown> };\n if (!Object.hasOwn(table.byId, id))\n return fail(at.concat(id), 'missing-entity', 'Table key does not exist.');\n session.writeMember(container, id, value, 'set');\n}\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\nexport function insert(\n session: MutationSession,\n container: ResolvedContainer,\n value: unknown,\n position?: DocumentAnchor\n): void {\n const { at, node, value: current } = container;\n if (node.kind !== 'list') return fail(at, 'invalid-list-key', 'Expected a list.');\n session.validate(node.value, value, at);\n const id = node.keyOf(value);\n if (typeof id !== 'string') return fail(at, 'invalid-list-key', 'List key must be a string.');\n const items = current as unknown[],\n keys = anchor.keys(items, node.keyOf);\n if (keys.index(id) >= 0) return fail(at, 'duplicate-list-item', 'List key already exists.');\n if (!anchor.valid(keys, position)) return fail(at, 'invalid-anchor', 'Unknown list anchor.');\n session.recorder.order(container);\n session.recorder.member(container, id, session.definition(container, id), -1);\n anchor.insert(items, anchor.index(keys, position), value);\n session.invalidate();\n}\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: items } = container;\n if (node.kind !== 'list') return fail(at, 'invalid-list-key', 'Expected a list.');\n const index = anchor.indexedKeys(items as unknown[], node.keyOf).index(id);\n if (index < 0) return fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, value, 'set', index);\n}\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n const { at, node, value } = container;\n if (node.kind !== 'list') return fail(at, 'missing-list-item', 'List key does not exist.');\n const index = anchor.keys(value as unknown[], node.keyOf).index(id);\n if (index < 0) return fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, undefined, 'remove', index);\n}\n","import type { DocumentAddress } from '../../schema';\nimport type { ResolvedTreeContainer } from '../../address';\nimport type { MutationSession } from '../session';\nimport { contains, type MutableTree, type TreePosition } from '../tree';\nimport { fail } from '../issue';\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nconst positionIndex = (index: number | undefined, length: number, at: DocumentAddress): number => {\n if (index !== undefined && (!Number.isInteger(index) || index < 0))\n return fail(at, 'invalid-tree-index', 'Tree index must be nonnegative.');\n return Math.min(index ?? length, length);\n};\nexport const insert = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown,\n position: TreePosition | undefined\n): void => {\n const { at, node: schema, value: tree } = container;\n if (typeof id !== 'string') return fail(at, 'invalid-key', 'Tree keys must be strings.');\n if (contains(tree, id)) return fail(at, 'duplicate-tree-node', 'Tree node already exists.');\n const parentId = position?.parentId;\n const parent = parentId === undefined ? undefined : node(tree, parentId);\n if (\n (tree.rootId !== undefined && !parent) ||\n (tree.rootId === undefined && parentId !== undefined)\n )\n return fail(at, 'missing-tree-parent', 'A nonempty tree requires an existing parent.');\n const index = positionIndex(position?.index, parent?.children.length ?? 0, at);\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n if (parentId !== undefined) session.recorder.tree(container, parentId);\n Object.defineProperty(tree.nodes, id, {\n value: { ...(parentId === undefined ? {} : { parentId }), children: [], value },\n writable: true,\n configurable: true,\n enumerable: true,\n });\n if (parent) parent.children.splice(index, 0, id);\n else tree.rootId = id;\n session.invalidate();\n};\nexport const replace = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown\n): void => {\n const { at, node: schema, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (Object.is(entry.value, value) && Object.hasOwn(entry, 'value')) return;\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n entry.value = value;\n};\nexport const remove = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n const ids: string[] = [],\n stack = [id];\n while (stack.length) {\n const current = stack.pop()!;\n ids.push(current);\n for (const child of tree.nodes[current].children) stack.push(child);\n }\n for (const key of ids) session.recorder.tree(container, key);\n if (entry.parentId !== undefined) session.recorder.tree(container, entry.parentId);\n if (entry.parentId === undefined) delete tree.rootId;\n else {\n const children = tree.nodes[entry.parentId].children;\n children.splice(children.indexOf(id), 1);\n }\n for (const key of ids) delete tree.nodes[key];\n session.invalidate();\n};\nexport const move = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n position: TreePosition | undefined\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id),\n parentId = position?.parentId;\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (entry.parentId === undefined || parentId === undefined || !contains(tree, parentId))\n return fail(\n at,\n 'missing-tree-parent',\n 'Moving requires a non-root node and an existing parent.'\n );\n for (\n let ancestor: string | undefined = parentId;\n ancestor !== undefined;\n ancestor = tree.nodes[ancestor].parentId\n )\n if (ancestor === id) return fail(at, 'tree-cycle', 'Cannot move a node under its descendant.');\n const old = tree.nodes[entry.parentId],\n next = tree.nodes[parentId];\n const index = positionIndex(position?.index, next.children.length - (old === next ? 1 : 0), at);\n const previous = old.children.indexOf(id);\n if (old === next && previous === index) return;\n session.recorder.tree(container, id);\n session.recorder.tree(container, entry.parentId);\n session.recorder.tree(container, parentId);\n old.children.splice(previous, 1);\n next.children.splice(index, 0, id);\n entry.parentId = parentId;\n session.invalidate();\n};\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\n\nconst assertOrdered = (\n container: ResolvedContainer\n): Extract<ResolvedContainer['node'], { kind: 'table' | 'list' }> => {\n const { at, node } = container;\n if (node.kind !== 'table' && node.kind !== 'list')\n return fail(at, 'invalid-collection', 'Expected an ordered container.');\n return node;\n};\n\nconst plannedOrder = (\n at: ResolvedContainer['at'],\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): readonly string[] => {\n const plan = anchor.moveSelection(current, selection, position);\n switch (plan.kind) {\n case 'ok':\n return plan.order;\n case 'duplicate':\n return fail(at, 'invalid-key', 'Moved keys must be unique.');\n case 'missing':\n return fail(at, 'missing-entity', 'Ordered key does not exist.');\n case 'invalid-anchor':\n return fail(at, 'invalid-anchor', 'Unknown order anchor.');\n }\n};\n\nexport function move(\n session: MutationSession,\n container: ResolvedContainer,\n ids: string | readonly string[],\n position?: DocumentAnchor\n): void {\n const node = assertOrdered(container);\n const selection = typeof ids === 'string' ? [ids] : ids;\n if (!selection.length) return;\n\n if (node.kind === 'table') {\n const order = (container.value as { ids: string[] }).ids;\n const next = plannedOrder(container.at, order, selection, position);\n if (anchor.equal(order, next)) return;\n session.recorder.order(container);\n anchor.installKeys(order, next);\n } else {\n const items = container.value as unknown[];\n const sequence = anchor.listSequence(items, node.keyOf);\n const next = plannedOrder(container.at, sequence.order, selection, position);\n if (anchor.equal(sequence.order, next)) return;\n session.recorder.order(container);\n anchor.installList(items, node.keyOf, sequence, next);\n }\n session.invalidate();\n}\n\nexport function reorder(\n session: MutationSession,\n container: ResolvedContainer,\n next: readonly string[]\n): void {\n const node = assertOrdered(container);\n if (node.kind === 'table') {\n const current = (container.value as { ids: string[] }).ids;\n if (!anchor.matches(next, current))\n return fail(container.at, 'invalid-collection', 'Order must contain every key exactly once.');\n if (anchor.equal(current, next)) return;\n session.recorder.order(container);\n anchor.installKeys(current, next);\n } else {\n const items = container.value as unknown[];\n const sequence = anchor.listSequence(items, node.keyOf);\n if (!anchor.matches(next, sequence.order))\n return fail(container.at, 'invalid-collection', 'Order must contain every key exactly once.');\n if (anchor.equal(sequence.order, next)) return;\n session.recorder.order(container);\n anchor.installList(items, node.keyOf, sequence, next);\n }\n session.invalidate();\n}\n","import type {\n DocumentAddress,\n DocumentAnchor,\n DocumentNode,\n DocumentTreeValue,\n FieldNode,\n Infer,\n ListNode,\n MapNode,\n ObjectNode,\n ObjectShape,\n ReadonlyValue,\n TableNode,\n TreeNode,\n ValueSchemaNode,\n VariantNode,\n} from '../schema';\nimport {\n nodeAt,\n resolveChild,\n resolveLocated,\n compiledShape,\n type FixedMember,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n} from '../address';\nimport { copyValue } from '../schema-value';\nimport type { DependencyTracker } from './dependency';\nimport type { CanonicalState } from '../mutation/state';\nimport type { MutationSession } from '../mutation/session';\nimport * as mapOperations from '../mutation/operations/map';\nimport * as tableOperations from '../mutation/operations/table';\nimport * as listOperations from '../mutation/operations/list';\nimport * as treeOperations from '../mutation/operations/tree';\nimport * as orderOperations from '../mutation/operations/order';\nimport * as tree from '../mutation/tree';\nimport * as anchor from '../mutation/anchor';\nimport { profile } from '../profile';\n\ndeclare const scopeValue: unique symbol;\ntype Scoped<N extends DocumentNode, W extends boolean, V = Infer<N>> = {\n readonly [scopeValue]?: readonly [node: N, writable: W, value: V];\n};\ntype ShapeAccess<S extends ObjectShape, W extends boolean> = W extends true\n ? { -readonly [K in keyof S]: Access<S[K], W> }\n : { readonly [K in keyof S]: Access<S[K], W> };\ntype MapAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n put(id: K, value: Infer<N>): void;\n remove(id: K): void;\n replace(value: Readonly<Record<K, Infer<N>>>): void;\n }\n : {});\ntype TableAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n create(id: K, value: Infer<N>, anchor?: DocumentAnchor<K>): void;\n create(\n entries: readonly { readonly id: K; readonly value: Infer<N> }[],\n anchor?: DocumentAnchor<K>\n ): void;\n remove(ids: K | readonly K[]): void;\n move(ids: K | readonly K[], anchor?: DocumentAnchor<K>): void;\n reorder(ids: readonly K[]): void;\n replace(value: {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Infer<N>>>;\n }): void;\n replace(id: K, value: Infer<N>): void;\n }\n : {});\ntype ListAccess<T, W extends boolean> = {\n get(key: string): ReadonlyValue<T> | undefined;\n has(key: string): boolean;\n ids(): readonly string[];\n} & (W extends true\n ? {\n insert(value: ReadonlyValue<T>, anchor?: DocumentAnchor): void;\n remove(key: string): void;\n move(keys: string | readonly string[], anchor?: DocumentAnchor): void;\n reorder(keys: readonly string[]): void;\n replace(value: readonly ReadonlyValue<T>[]): void;\n replace(key: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype TreeAccess<T, W extends boolean> = {\n rootId(): string | undefined;\n get(id: string): ReadonlyValue<T> | undefined;\n has(id: string): boolean;\n parent(id: string): string | undefined;\n children(id: string): readonly string[] | undefined;\n} & (W extends true\n ? {\n insert(id: string, value: ReadonlyValue<T>, position?: tree.TreePosition): void;\n move(id: string, position?: tree.TreePosition): void;\n remove(id: string): void;\n replace(value: DocumentTreeValue<T>): void;\n replace(id: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype NodeAccess<N extends DocumentNode, W extends boolean> =\n N extends FieldNode<infer T, boolean>\n ? ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeAccess<S, W> & Scoped<N, W>\n : N extends VariantNode<infer Tag, infer V>\n ? {\n [K in keyof V & string]: ShapeAccess<V[K]['shape'], W> & {\n readonly [P in Tag]: K;\n } & Scoped<N, W, Extract<Infer<N>, Record<Tag, K>>>;\n }[keyof V & string]\n : N extends MapNode<infer V, infer K>\n ? MapAccess<K, V, W> & Scoped<N, W>\n : N extends TableNode<infer V, infer K>\n ? TableAccess<K, V, W> & Scoped<N, W>\n : N extends ListNode<infer T>\n ? ListAccess<T, W> & Scoped<N, W>\n : N extends TreeNode<infer T>\n ? TreeAccess<T, W> & Scoped<N, W>\n : never;\ntype Access<N extends DocumentNode, W extends boolean> = N extends { readonly optional: true }\n ? NodeAccess<N, W> | undefined\n : NodeAccess<N, W>;\nexport type Read<N extends DocumentNode> = Access<N, false>;\nexport type Draft<N extends DocumentNode> = Access<N, true>;\ntype Snapshot<T> = T extends {\n readonly [scopeValue]?: readonly [DocumentNode, boolean, infer V];\n}\n ? V\n : ReadonlyValue<T>;\ntype Target = {\n at?: DocumentAddress;\n parent?: Target;\n key: string;\n node: DocumentNode | undefined;\n value: unknown;\n generation: number;\n children:\n | { kind: 'fixed'; schema: DocumentNode; slots: (Target | undefined)[] }\n | { kind: 'dynamic'; keys: Map<string, Target> }\n | undefined;\n proxy: object | undefined;\n container?: ResolvedContainer | ResolvedTreeContainer;\n};\ntype Location = { readonly context: AccessContext; readonly target: Target };\nconst locations = new WeakMap<object, Location>();\nconst locationOf = (value: object): Location | undefined => locations.get(value);\nconst addressOf = (target: Target): DocumentAddress => {\n if (target.at) return target.at;\n profile.access('addresses');\n return (target.at = addressOf(target.parent!).concat(target.key));\n};\nexport type AccessContext = {\n readonly state: CanonicalState;\n /** Omitted for borrowed synchronous Draft and readers that must not escape. */\n readonly active?: () => boolean;\n readonly dependencies?: DependencyTracker;\n readonly session?: MutationSession;\n};\nconst assertActive = (context: AccessContext) => {\n if (context.active && !context.active()) throw new Error('Document access scope has expired.');\n};\nconst collect = (\n context: AccessContext,\n at: DocumentAddress,\n kind: 'value' | 'collection' = 'value',\n id?: string\n) => {\n context.dependencies?.record(\n kind === 'value' ? { kind, at } : { kind, at, ...(id === undefined ? {} : { id }) }\n );\n};\nexport const snapshot = <T>(value: T): Snapshot<T> => {\n const location = value && typeof value === 'object' ? locationOf(value) : undefined;\n if (!location) return value as Snapshot<T>;\n const { context } = location;\n const at = addressOf(location.target);\n profile.access('snapshots');\n collect(context, at);\n const resolved = resolve(context, location.target);\n if (!resolved.node) throw new Error('The selected schema address no longer exists.');\n return copyValue(resolved.node, resolved.value) as Snapshot<T>;\n};\n/** Replace a member with its plain Infer value through the owning draft session. */\ntype ReplaceParentAccess = {\n readonly [scopeValue]?: readonly [\n Extract<DocumentNode, { readonly kind: 'object' | 'variant' }>,\n true,\n unknown,\n ];\n};\nexport const replace = <T extends object & ReplaceParentAccess, K extends keyof Snapshot<T>>(\n container: T,\n key: K,\n value: NoInfer<Snapshot<T>[K]>\n): void => {\n const location = locationOf(container);\n if (!location) throw new TypeError('replace requires scoped document access.');\n if (typeof key !== 'string') throw new TypeError('Document keys must be strings.');\n Reflect.set(container, key, value);\n};\n/** Projection collection contexts use the same scoped access, with explicit collection tools. */\nexport type CollectionAccess<K extends string, N extends ValueSchemaNode> = TableAccess<\n K,\n N,\n false\n>;\nconst resolve = (context: AccessContext, target: Target): Target => {\n assertActive(context);\n const generation = context.session?.generation ?? 0;\n if (target.generation !== generation) {\n profile.access('resolutions');\n if (!target.parent && !target.at!.length) {\n target.node = context.state.schema;\n target.value = context.state.document;\n } else {\n const parent = target.parent && resolve(context, target.parent);\n const location = parent\n ? resolveChild(parent.node, parent.value, target.key)\n : resolveLocated(context.state.schema, context.state.document, target.at!);\n target.node =\n location?.node ?? nodeAt(context.state.schema, addressOf(target), context.state.document);\n target.value =\n location && Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined;\n }\n target.generation = generation;\n }\n return target;\n};\n\nexport const createAccess = (context: AccessContext, initial: DocumentAddress = []): unknown => {\n profile.access('scopes');\n const mutable = (): MutationSession => {\n assertActive(context);\n if (!context.session) throw new TypeError('Cannot modify read-only document access.');\n return context.session;\n };\n const writableContainer = (target: Target, session: MutationSession): ResolvedContainer => {\n if (target.container?.generation === session.generation && 'layout' in target.container)\n return target.container;\n return (target.container = session.bind(addressOf(target), target.node, target.value));\n };\n const childAt = (target: Target, key: string): DocumentAddress => {\n profile.access('addresses');\n return addressOf(target).concat(key);\n };\n const access = (target: Target): unknown => {\n if (target.proxy) return target.proxy;\n const proxy = new Proxy(target, handler);\n profile.access('proxies');\n locations.set(proxy, { context, target });\n target.proxy = proxy;\n return proxy;\n };\n const createTarget = (\n at: DocumentAddress | undefined,\n parent: Target | undefined,\n key: string\n ): Target => ({\n at,\n parent,\n key,\n node: undefined,\n value: undefined,\n generation: -1,\n children: undefined,\n proxy: undefined,\n });\n const childAccess = (\n target: Target,\n member: string | FixedMember,\n node: DocumentNode,\n value: unknown\n ) => {\n const key = typeof member === 'string' ? member : member.key;\n if (node.kind === 'field' || value === undefined) {\n if (context.dependencies) collect(context, childAt(target, key));\n return value;\n }\n let children = target.children;\n let child: Target;\n if (typeof member !== 'string') {\n if (children?.kind !== 'fixed' || children.schema !== target.node)\n children = {\n kind: 'fixed',\n schema: target.node!,\n slots: new Array(compiledShape(target.node!, target.value)!.members.size),\n };\n child = children.slots[member.slot] ??= createTarget(undefined, target, key);\n } else {\n if (children?.kind !== 'dynamic') children = { kind: 'dynamic', keys: new Map() };\n const retained = children.keys.get(key);\n child = retained ?? createTarget(undefined, target, key);\n if (!retained) children.keys.set(key, child);\n }\n target.children = children;\n if (child.generation === target.generation) return child.proxy;\n child.node = node;\n child.value = value;\n child.generation = target.generation;\n return access(child);\n };\n const collectionValue = (target: Target, node: DocumentNode) => {\n const current = resolve(context, target);\n if (current.node !== node || current.value === undefined)\n throw new TypeError('The collection method belongs to a replaced schema branch.');\n return current.value;\n };\n const writableCollection = (target: Target, node: DocumentNode): ResolvedContainer => {\n const session = mutable();\n collectionValue(target, node);\n return writableContainer(target, session);\n };\n const writableTree = (target: Target, node: DocumentNode): ResolvedTreeContainer => {\n const session = mutable();\n collectionValue(target, node);\n if (target.container?.generation === session.generation && !('layout' in target.container))\n return target.container;\n return (target.container = session.bindTree(addressOf(target), target.node, target.value));\n };\n const replaceCollection = (target: Target, node: DocumentNode, value: unknown) => {\n const session = mutable();\n collectionValue(target, node);\n session.replace(addressOf(target), value);\n };\n const mapMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'map' }>\n ): unknown => {\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection');\n return Object.keys(current);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n return Object.hasOwn(current, id);\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n if (!Object.hasOwn(current, id)) return undefined;\n if (node.value.kind === 'field') {\n if (context.dependencies) collect(context, childAt(target, id));\n return current[id];\n }\n return childAccess(target, id, node.value, current[id]);\n };\n if (property === 'put')\n return (id: string, value: unknown) => {\n const writable = writableCollection(target, node);\n mapOperations.put(context.session!, writable, id, value);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n mapOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace') return (value: unknown) => replaceCollection(target, node, value);\n return undefined;\n };\n const orderedMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' | 'list' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection');\n return node.kind === 'table'\n ? [...(current as { ids: string[] }).ids]\n : (current as unknown[]).map(node.keyOf);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n return node.kind === 'table'\n ? Object.hasOwn((current as { byId: object }).byId, id)\n : anchor.indexedKeys(current as unknown[], node.keyOf).index(id) >= 0;\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n const location = resolveChild(node, current, id);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return childAccess(\n target,\n id,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n };\n if (property === 'move')\n return (ids: string | readonly string[], position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n orderOperations.move(context.session!, writable, ids, position);\n };\n if (property === 'reorder')\n return (ids: readonly string[]) => {\n const writable = writableCollection(target, node);\n orderOperations.reorder(context.session!, writable, ids);\n };\n return undefined;\n };\n const tableMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' }>\n ): unknown => {\n if (property === 'create')\n return (\n input: string | readonly { id: string; value: unknown }[],\n valueOrPosition?: unknown,\n position?: DocumentAnchor\n ) => {\n const writable = writableCollection(target, node);\n tableOperations.create(\n context.session!,\n writable,\n Array.isArray(input) ? input : [{ id: input as string, value: valueOrPosition }],\n Array.isArray(input) ? (valueOrPosition as DocumentAnchor | undefined) : position\n );\n };\n if (property === 'remove')\n return (ids: string | readonly string[]) => {\n const writable = writableCollection(target, node);\n tableOperations.remove(context.session!, writable, typeof ids === 'string' ? [ids] : ids);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n tableOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const listMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'list' }>\n ): unknown => {\n if (property === 'insert')\n return (value: unknown, position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n listOperations.insert(context.session!, writable, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n listOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n listOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const treeMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'tree' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'insert')\n return (id: string, value: unknown, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.insert(context.session!, writable, id, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableTree(target, node);\n treeOperations.remove(context.session!, writable, id);\n };\n if (property === 'move')\n return (id: string, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.move(context.session!, writable, id, position);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableTree(target, node);\n treeOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n const current = () => {\n collect(context, at);\n return collectionValue(target, node) as tree.MutableTree;\n };\n if (property === 'rootId') return () => current().rootId;\n if (property === 'get')\n return (id: string) => {\n const value = current();\n return tree.contains(value, id) ? value.nodes[id].value : undefined;\n };\n if (property === 'has') return (id: string) => tree.contains(current(), id);\n if (property === 'parent') return (id: string) => tree.parent(current(), id);\n if (property === 'children')\n return (id: string) => {\n const children = tree.children(current(), id);\n return children ? [...children] : undefined;\n };\n return undefined;\n };\n const handler: ProxyHandler<Target> = {\n get: (target, property) => {\n const { node, value } = resolve(context, target);\n if (!node || value === undefined) return undefined;\n if (typeof property !== 'string') return undefined;\n if (node.kind === 'map') return mapMethod(target, property, node);\n if (node.kind === 'table') return tableMethod(target, property, node);\n if (node.kind === 'list') return listMethod(target, property, node);\n if (node.kind === 'tree') return treeMethod(target, property, node);\n if (node.kind === 'variant' && property === node.tag) {\n collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n const member = compiledShape(node, value)?.members.get(property);\n if (!member) return undefined;\n if (member.field) {\n if (context.dependencies) collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n return childAccess(\n target,\n node.kind === 'object' ? member : property,\n member.node,\n (value as Record<string, unknown>)[property]\n );\n },\n set: (target, property, value) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n !node ||\n (node.kind !== 'object' && node.kind !== 'variant')\n )\n throw new TypeError('Invalid structural assignment.');\n if (node.kind === 'variant' && node.tag === property)\n throw new TypeError('Variant discriminants are read-only.');\n session.assignMember(writableContainer(target, session), property, value);\n return true;\n },\n deleteProperty: (target, property) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n node?.kind === 'map' ||\n (node?.kind === 'variant' && node.tag === property)\n )\n throw new TypeError('Invalid structural deletion.');\n session.removeMember(writableContainer(target, session), property);\n return true;\n },\n has: (target, property) => {\n const { node, value } = resolve(context, target);\n if (typeof property !== 'string') return false;\n if (node?.kind === 'map') return false;\n collect(context, addressOf(target));\n return value !== undefined && Object.hasOwn(value as object, property);\n },\n ownKeys: target => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return [];\n if (context.dependencies) collect(context, addressOf(target));\n return value && typeof value === 'object' ? Object.keys(value) : [];\n },\n getOwnPropertyDescriptor: (target, property) => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return undefined;\n return value && Object.hasOwn(value as object, property)\n ? { enumerable: true, configurable: true }\n : undefined;\n },\n defineProperty: () => {\n assertActive(context);\n throw new TypeError('Use schema assignments.');\n },\n setPrototypeOf: () => {\n assertActive(context);\n throw new TypeError('Document prototypes are immutable.');\n },\n preventExtensions: () => {\n assertActive(context);\n throw new TypeError('Document access cannot be frozen.');\n },\n };\n const root = resolve(context, createTarget(initial, undefined, ''));\n if (!root.node || root.node.kind === 'field' || root.value === undefined) {\n if (context.dependencies) collect(context, initial);\n return root.value;\n }\n return access(root);\n};\nexport const collectionAccess = (\n context: AccessContext,\n at: DocumentAddress\n): CollectionAccess<string, ValueSchemaNode> => {\n const value = createAccess(context, at);\n if (value === undefined)\n return {\n get: () => {\n assertActive(context);\n return undefined;\n },\n has: () => {\n assertActive(context);\n return false;\n },\n ids: () => {\n assertActive(context);\n return [];\n },\n };\n return value as CollectionAccess<string, ValueSchemaNode>;\n};\n","import type { DocumentAddress, ObjectNode, PathPick, Infer } from '../schema';\nimport type { AddressRef } from '../address';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable } from '../projection/readable';\nexport type Unsubscribe = () => void;\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectNode> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectNode> = (commit: DocumentCommit<S>) => void;\nexport type DocumentReadable<S extends ObjectNode> = {\n readonly address: {\n resolve(address: DocumentAddress): AddressRef | undefined;\n read(address: DocumentAddress): unknown;\n contains(parent: DocumentAddress, child: DocumentAddress): boolean;\n overlaps(left: DocumentAddress, right: DocumentAddress): boolean;\n debugKey(address: DocumentAddress): string;\n };\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectNode> = DocumentReadable<S> & {\n readonly schema: S;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options: {\n readonly expectedRevision: number;\n readonly source?: Exclude<CommitSource, 'history'>;\n readonly history?: boolean;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ObjectNode, Infer } from '../schema';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { DocumentReadable } from './contract';\n\nexport type RuntimeAccessState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks?: number;\n};\n\nconst states = new WeakMap<object, RuntimeAccessState<ObjectNode>>();\n\nexport const bindRuntimeAccess = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n state: RuntimeAccessState<TSchema>\n): void => {\n states.set(runtime as object, state as RuntimeAccessState<ObjectNode>);\n};\n\nexport const accessOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeAccessState<TSchema> => {\n const state = states.get(runtime as object);\n if (!state) throw new Error('Unknown Doxum runtime.');\n return state as RuntimeAccessState<TSchema>;\n};\n\nexport const readWith = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = accessOf(runtime);\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks = (state.projectionLocks ?? 0) + 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks!--;\n }\n};\n"],"mappings":";;AAgCA,IAAa,aAAb,cAAgC,UAAU;CACxC;CACA,YAAY,OAAmB;AAC7B,QAAM,GAAG,MAAM,QAAQ,MAAM,KAAK,UAAU,MAAM,QAAQ,GAAG;AAC7D,OAAK,OAAO;AACZ,OAAK,SAAS,OAAO,OAAO,CAC1B,OAAO,OAAO;GAAE,GAAG;GAAO,SAAS,OAAO,OAAO,CAAC,GAAG,MAAM,QAAQ,CAAC;GAAE,CAAC,CACxE,CAAC;;;AAIN,MAAM,SACJ,SACA,SACA,OAA2B,qBACX;CAAE;CAAS;CAAS;CAAM;AAE5C,MAAa,eACX,WACA,OACA,SACA,WAC2B;AAC3B,KAAI,CAAC,UACH,QAAO,SACH,MAAM,SAAS,qDAAqD,oBAAoB,GACxF,KAAA;AACN,KAAI;EACF,MAAM,SACJ,OAAO,cAAc,aAAa,UAAU,MAAM,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