@dxos/echo 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/lib/Annotation.mjs +2 -2
  2. package/dist/lib/Database.mjs +1 -1
  3. package/dist/lib/Error.mjs +1 -1
  4. package/dist/lib/Feed.mjs +1 -1
  5. package/dist/lib/Format.mjs +2 -2
  6. package/dist/lib/Migration.mjs +1 -1
  7. package/dist/lib/chunk-Annotation.mjs +14 -11
  8. package/dist/lib/chunk-Annotation.mjs.map +1 -1
  9. package/dist/lib/chunk-Blob.mjs +1 -1
  10. package/dist/lib/chunk-Collection.mjs +1 -1
  11. package/dist/lib/chunk-Database.mjs +93 -7
  12. package/dist/lib/chunk-Database.mjs.map +1 -1
  13. package/dist/lib/chunk-Dataset.mjs +1 -1
  14. package/dist/lib/chunk-Entity.mjs +2 -2
  15. package/dist/lib/chunk-Entity.mjs.map +1 -1
  16. package/dist/lib/chunk-Error.mjs +13 -1
  17. package/dist/lib/chunk-Error.mjs.map +1 -1
  18. package/dist/lib/chunk-Feed.mjs +311 -17
  19. package/dist/lib/chunk-Feed.mjs.map +1 -1
  20. package/dist/lib/chunk-Filter.mjs +4 -3
  21. package/dist/lib/chunk-Filter.mjs.map +1 -1
  22. package/dist/lib/chunk-Format.mjs +2 -1
  23. package/dist/lib/chunk-Hypergraph.mjs +1 -1
  24. package/dist/lib/chunk-Hypergraph.mjs.map +1 -1
  25. package/dist/lib/chunk-Migration.mjs +155 -5
  26. package/dist/lib/chunk-Migration.mjs.map +1 -1
  27. package/dist/lib/chunk-Obj.mjs +12 -5
  28. package/dist/lib/chunk-Obj.mjs.map +1 -1
  29. package/dist/lib/chunk-Query.mjs +2 -2
  30. package/dist/lib/chunk-QueryResult.mjs.map +1 -1
  31. package/dist/lib/chunk-Ref2.mjs +2 -2
  32. package/dist/lib/chunk-Registry.mjs +1 -1
  33. package/dist/lib/chunk-Registry.mjs.map +1 -1
  34. package/dist/lib/chunk-Relation.mjs +5 -5
  35. package/dist/lib/chunk-Relation.mjs.map +1 -1
  36. package/dist/lib/chunk-Scope.mjs +16 -2
  37. package/dist/lib/chunk-Scope.mjs.map +1 -1
  38. package/dist/lib/chunk-Tag.mjs +4 -4
  39. package/dist/lib/chunk-Tag.mjs.map +1 -1
  40. package/dist/lib/chunk-Text.mjs +2 -2
  41. package/dist/lib/chunk-Type.mjs +26 -7
  42. package/dist/lib/chunk-Type.mjs.map +1 -1
  43. package/dist/lib/chunk-View.mjs +1 -1
  44. package/dist/lib/chunk-atom-snapshot.mjs +29 -1
  45. package/dist/lib/chunk-atom-snapshot.mjs.map +1 -1
  46. package/dist/lib/chunk-entity-dictionary.mjs +28 -19
  47. package/dist/lib/chunk-entity-dictionary.mjs.map +1 -1
  48. package/dist/lib/chunk-internal.mjs +231 -79
  49. package/dist/lib/chunk-internal.mjs.map +1 -1
  50. package/dist/lib/chunk-json-schema.mjs +1 -1
  51. package/dist/lib/chunk-ref.mjs +38 -34
  52. package/dist/lib/chunk-ref.mjs.map +1 -1
  53. package/dist/lib/chunk-select.mjs +7 -3
  54. package/dist/lib/chunk-select.mjs.map +1 -1
  55. package/dist/lib/index.mjs +2 -2
  56. package/dist/lib/internal.mjs +6 -6
  57. package/dist/lib/testing.mjs +2 -2
  58. package/dist/lib/testing.mjs.map +1 -1
  59. package/dist/types/src/Annotation.d.ts +1 -1
  60. package/dist/types/src/Annotation.d.ts.map +1 -1
  61. package/dist/types/src/Database.d.ts +30 -13
  62. package/dist/types/src/Database.d.ts.map +1 -1
  63. package/dist/types/src/Entity.d.ts +3 -4
  64. package/dist/types/src/Entity.d.ts.map +1 -1
  65. package/dist/types/src/Error.d.ts +36 -0
  66. package/dist/types/src/Error.d.ts.map +1 -1
  67. package/dist/types/src/Feed.d.ts +261 -18
  68. package/dist/types/src/Feed.d.ts.map +1 -1
  69. package/dist/types/src/Filter.d.ts +7 -1
  70. package/dist/types/src/Filter.d.ts.map +1 -1
  71. package/dist/types/src/Hypergraph.d.ts +1 -1
  72. package/dist/types/src/Migration.d.ts +213 -2
  73. package/dist/types/src/Migration.d.ts.map +1 -1
  74. package/dist/types/src/Migration.test.d.ts +2 -0
  75. package/dist/types/src/Migration.test.d.ts.map +1 -0
  76. package/dist/types/src/Obj.d.ts +4 -4
  77. package/dist/types/src/Obj.d.ts.map +1 -1
  78. package/dist/types/src/QueryResult.d.ts +16 -0
  79. package/dist/types/src/QueryResult.d.ts.map +1 -1
  80. package/dist/types/src/Relation.d.ts +3 -4
  81. package/dist/types/src/Relation.d.ts.map +1 -1
  82. package/dist/types/src/Scope.d.ts +32 -1
  83. package/dist/types/src/Scope.d.ts.map +1 -1
  84. package/dist/types/src/Tag.d.ts.map +1 -1
  85. package/dist/types/src/Type.d.ts +27 -2
  86. package/dist/types/src/Type.d.ts.map +1 -1
  87. package/dist/types/src/internal/Annotation/annotations.d.ts +35 -1
  88. package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
  89. package/dist/types/src/internal/Annotation/atoms.d.ts +2 -2
  90. package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -1
  91. package/dist/types/src/internal/Entity/api.d.ts +11 -0
  92. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  93. package/dist/types/src/internal/Entity/model.d.ts +3 -2
  94. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  95. package/dist/types/src/internal/Format/string.d.ts +5 -1
  96. package/dist/types/src/internal/Format/string.d.ts.map +1 -1
  97. package/dist/types/src/internal/Obj/atoms.d.ts +1 -1
  98. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  99. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  100. package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
  101. package/dist/types/src/internal/Ref/ref.d.ts +5 -1
  102. package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
  103. package/dist/types/src/internal/Ref/strong-deps.d.ts +3 -1
  104. package/dist/types/src/internal/Ref/strong-deps.d.ts.map +1 -1
  105. package/dist/types/src/internal/common/api/meta.d.ts +4 -5
  106. package/dist/types/src/internal/common/api/meta.d.ts.map +1 -1
  107. package/dist/types/src/internal/common/atom-snapshot.d.ts +10 -0
  108. package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -1
  109. package/dist/types/src/internal/common/proxy/change-context.d.ts +4 -0
  110. package/dist/types/src/internal/common/proxy/change-context.d.ts.map +1 -1
  111. package/dist/types/src/internal/common/proxy/ownership.d.ts +5 -0
  112. package/dist/types/src/internal/common/proxy/ownership.d.ts.map +1 -1
  113. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
  114. package/dist/types/src/internal/common/proxy/schema-validator.d.ts +17 -2
  115. package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
  116. package/dist/types/src/internal/common/proxy/symbols.d.ts +10 -0
  117. package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
  118. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +0 -1
  119. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  120. package/dist/types/src/internal/common/types/meta.d.ts +8 -4
  121. package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
  122. package/dist/types/src/internal/common/types/model-symbols.d.ts +6 -0
  123. package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
  124. package/dist/types/src/internal/index.d.ts.map +1 -1
  125. package/dist/types/tsconfig.tsbuildinfo +1 -1
  126. package/package.json +19 -15
  127. package/src/Annotation.test.ts +34 -0
  128. package/src/Annotation.ts +3 -0
  129. package/src/Database.ts +46 -15
  130. package/src/Entity.ts +3 -4
  131. package/src/Error.ts +9 -0
  132. package/src/Feed.test.ts +160 -0
  133. package/src/Feed.ts +412 -29
  134. package/src/Filter.ts +8 -1
  135. package/src/Hypergraph.ts +1 -1
  136. package/src/Migration.test.ts +137 -0
  137. package/src/Migration.ts +376 -4
  138. package/src/Obj.test.ts +44 -4
  139. package/src/Obj.ts +19 -5
  140. package/src/QueryResult.ts +14 -0
  141. package/src/Relation.ts +3 -4
  142. package/src/Scope.ts +43 -1
  143. package/src/Tag.md +5 -6
  144. package/src/Tag.ts +3 -2
  145. package/src/Type.test.ts +52 -0
  146. package/src/Type.ts +75 -22
  147. package/src/Type.tst.ts +155 -0
  148. package/src/internal/Annotation/annotations.test.ts +19 -0
  149. package/src/internal/Annotation/annotations.ts +67 -1
  150. package/src/internal/Annotation/atoms.ts +10 -9
  151. package/src/internal/Entity/api.ts +20 -1
  152. package/src/internal/Entity/model.ts +3 -0
  153. package/src/internal/Filter/match.ts +2 -2
  154. package/src/internal/Format/string.ts +7 -2
  155. package/src/internal/JsonSchema/json-schema.test.ts +2 -2
  156. package/src/internal/Obj/atoms.ts +9 -5
  157. package/src/internal/Obj/json-serializer.test.ts +34 -7
  158. package/src/internal/Obj/json-serializer.ts +18 -3
  159. package/src/internal/Query/pretty.ts +3 -2
  160. package/src/internal/Ref/ref.test.ts +27 -2
  161. package/src/internal/Ref/ref.ts +18 -2
  162. package/src/internal/Ref/strong-deps.ts +21 -2
  163. package/src/internal/common/api/meta.ts +7 -8
  164. package/src/internal/common/atom-snapshot.ts +61 -0
  165. package/src/internal/common/proxy/change-context.ts +5 -0
  166. package/src/internal/common/proxy/change.test.ts +62 -31
  167. package/src/internal/common/proxy/json-serializer.ts +3 -2
  168. package/src/internal/common/proxy/ownership.ts +14 -1
  169. package/src/internal/common/proxy/proxy-utils.ts +7 -1
  170. package/src/internal/common/proxy/schema-validator.ts +116 -27
  171. package/src/internal/common/proxy/symbols.ts +12 -0
  172. package/src/internal/common/proxy/typed-handler.test.ts +43 -0
  173. package/src/internal/common/proxy/typed-handler.ts +105 -33
  174. package/src/internal/common/types/meta.ts +25 -20
  175. package/src/internal/common/types/model-symbols.ts +7 -0
  176. package/src/internal/index.ts +1 -2
@@ -1,5 +1,5 @@
1
1
  import { a as ANY_OBJECT_VERSION, g as getStaticTypeSchema, i as ANY_OBJECT_TYPENAME, n as makeTypeJsonSchemaAnnotation, o as EntityKind, s as EntityKindSchema } from "./chunk-util.mjs";
2
- import { K as FormInlineAnnotationId, et as GeneratorAnnotationId, ft as TypeAnnotationId, it as LabelAnnotationId, ot as PropertyMetaAnnotationId, pt as TypeIdentifierAnnotationId } from "./chunk-Database.mjs";
2
+ import { Z as FormInlineAnnotationId, at as GeneratorAnnotationId, bt as TypeIdentifierAnnotationId, dt as PropertyMetaAnnotationId, lt as LabelAnnotationId, yt as TypeAnnotationId } from "./chunk-Database.mjs";
3
3
  import { f as isRefIdentifier, o as createEchoReferenceSchema } from "./chunk-ref.mjs";
4
4
  import { c as FormatAnnotationId, m as TypeFormat, n as CurrencyAnnotationId, s as FormatAnnotation } from "./chunk-number.mjs";
5
5
  import { DXN, EID, EntityId } from "@dxos/keys";
@@ -1,5 +1,5 @@
1
1
  import { g as getStaticTypeSchema } from "./chunk-util.mjs";
2
- import { At as getTypeAnnotation, Ot as getSchemaURI, an as ObjectDeletedId, ct as ReferenceAnnotationId, i as Service, jt as getTypeIdentifierAnnotation } from "./chunk-Database.mjs";
2
+ import { It as getSchemaURI, R as defineHiddenProperty, Rt as getTypeAnnotation, hn as ObjectDeletedId, ht as ReferenceAnnotationId, i as Service, zt as getTypeIdentifierAnnotation } from "./chunk-Database.mjs";
3
3
  import { EncodedReference } from "@dxos/echo-protocol";
4
4
  import { DXN, EID, EntityId } from "@dxos/keys";
5
5
  import * as Option from "effect/Option";
@@ -8,6 +8,7 @@ import * as SchemaAST from "@dxos/effect/SchemaAST";
8
8
  import { assertArgument, invariant } from "@dxos/invariant";
9
9
  import * as SchemaTransformation from "effect/SchemaTransformation";
10
10
  import { isNonNullable } from "@dxos/util";
11
+ import * as Atom from "effect/reactivity/Atom";
11
12
  import * as Effect from "effect/Effect";
12
13
  import * as Equal from "effect/Equal";
13
14
  import * as Hash from "effect/Hash";
@@ -15,18 +16,26 @@ import * as Pipeable from "effect/Pipeable";
15
16
  import * as SchemaIssue from "effect/SchemaIssue";
16
17
  import { Event } from "@dxos/async";
17
18
  import { inspectCustom } from "@dxos/debug";
18
- import * as Atom from "effect/reactivity/Atom";
19
- //#region src/internal/common/proxy/define-hidden-property.ts
19
+ //#region src/internal/common/proxy/symbols.ts
20
+ var EventId = Symbol.for("@dxos/live-object/EventId");
21
+ var ChangeId = Symbol.for("@dxos/live-object/ChangeId");
20
22
  /**
21
- * Define a non-enumerable property on an object.
23
+ * The key this object's change context is opened under, or `undefined` while the object is not yet
24
+ * initialized and is therefore freely mutable. Answered by each variant's behaviour prototype — the
25
+ * in-memory objects key by their root target, database-backed ones by their `ObjectCore` — so the
26
+ * shared proxy handler can enforce the read-only gate for every variant without dispatching.
22
27
  */
23
- var defineHiddenProperty = (object, key, value) => {
24
- Object.defineProperty(object, key, {
25
- enumerable: false,
26
- configurable: true,
27
- value
28
- });
29
- };
28
+ var ChangeKeyId = Symbol.for("@dxos/live-object/ChangeKey");
29
+ /**
30
+ * Marks an array whose elements are root entities held by identity (e.g. `meta.tags`), so the
31
+ * ownership, copy and reactify walkers treat each element as an opaque reference, not nested data.
32
+ */
33
+ var EntityElementsId = Symbol.for("@dxos/live-object/EntityElements");
34
+ /**
35
+ * Schema annotation on a declaration whose values are root entities held by identity; an array of
36
+ * them is marked with {@link EntityElementsId} when a typed target is prepared or assigned.
37
+ */
38
+ var EntityValueAnnotationId = "@dxos/echo/annotation/EntityValue";
30
39
  //#endregion
31
40
  //#region src/internal/common/proxy/errors.ts
32
41
  /**
@@ -114,7 +123,7 @@ var getProxyTarget = (proxy) => {
114
123
  invariant(target, "Not a reactive proxy.", {
115
124
  "~LogMeta": "~LogMeta",
116
125
  F: __dxlog_file$1,
117
- L: 76,
126
+ L: 77,
118
127
  S: void 0,
119
128
  A: ["target", "'Not a reactive proxy.'"]
120
129
  });
@@ -125,7 +134,7 @@ var getProxyHandler = (proxy) => {
125
134
  invariant(handler, "Not a reactive proxy.", {
126
135
  "~LogMeta": "~LogMeta",
127
136
  F: __dxlog_file$1,
128
- L: 82,
137
+ L: 83,
129
138
  S: void 0,
130
139
  A: ["handler", "'Not a reactive proxy.'"]
131
140
  });
@@ -230,7 +239,8 @@ var normalizeForStorage = (value, seen = /* @__PURE__ */ new Set()) => {
230
239
  var MUTABLE_PROXY_HANDLER = {
231
240
  get: (target, property, receiver) => {
232
241
  const value = Reflect.get(target, property, receiver);
233
- return isProxy(value) ? getMutableProxy(value) : value;
242
+ if (isProxy(value) && !(Array.isArray(target) && Reflect.get(target, EntityElementsId) === true)) return getMutableProxy(value);
243
+ return value;
234
244
  },
235
245
  set: (target, property, value, receiver) => {
236
246
  const handler = Reflect.get(target, symbolReactiveHandler);
@@ -297,17 +307,6 @@ var REACTIVE_PROXY_HANDLER = {
297
307
  getPrototypeOf: (target) => Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype
298
308
  };
299
309
  //#endregion
300
- //#region src/internal/common/proxy/symbols.ts
301
- var EventId = Symbol.for("@dxos/live-object/EventId");
302
- var ChangeId = Symbol.for("@dxos/live-object/ChangeId");
303
- /**
304
- * The key this object's change context is opened under, or `undefined` while the object is not yet
305
- * initialized and is therefore freely mutable. Answered by each variant's behaviour prototype — the
306
- * in-memory objects key by their root target, database-backed ones by their `ObjectCore` — so the
307
- * shared proxy handler can enforce the read-only gate for every variant without dispatching.
308
- */
309
- var ChangeKeyId = Symbol.for("@dxos/live-object/ChangeKey");
310
- //#endregion
311
310
  //#region src/internal/common/proxy/reactive.ts
312
311
  /**
313
312
  * Subscribe to changes on a reactive object.
@@ -501,6 +500,7 @@ var createEchoReferenceSchema = (echoUri, typename, version) => {
501
500
  if (Ref.isRef(candidate)) return Option.isSome(dbService) ? dbService.value.db.makeRef(candidate.uri) : candidate;
502
501
  if (!EncodedReference.isEncodedReference(candidate)) return yield* Effect.fail(new SchemaIssue.InvalidValue(void 0, candidate));
503
502
  const uri = EncodedReference.toURI(candidate);
503
+ if (EID.isEID(uri) && EID.tryParse(uri) === void 0) return yield* Effect.fail(new SchemaIssue.InvalidValue({ message: `Invalid echo URI: ${uri}` }, candidate));
504
504
  return Option.isSome(dbService) ? dbService.value.db.makeRef(uri) : Ref.fromURI(uri);
505
505
  }),
506
506
  encode: (value) => {
@@ -558,7 +558,7 @@ var RefImpl = class RefImpl {
558
558
  invariant(this.#resolver, "Resolver is not set", {
559
559
  "~LogMeta": "~LogMeta",
560
560
  F: __dxlog_file,
561
- L: 607,
561
+ L: 614,
562
562
  S: this,
563
563
  A: ["this.#resolver", "'Resolver is not set'"]
564
564
  });
@@ -601,7 +601,7 @@ var RefImpl = class RefImpl {
601
601
  invariant(this.#resolver, "Resolver is not set", {
602
602
  "~LogMeta": "~LogMeta",
603
603
  F: __dxlog_file,
604
- L: 659,
604
+ L: 666,
605
605
  S: this,
606
606
  A: ["this.#resolver", "'Resolver is not set'"]
607
607
  });
@@ -654,9 +654,13 @@ var RefImpl = class RefImpl {
654
654
  [Hash.symbol]() {
655
655
  return Hash.hash(this.#uri.toString());
656
656
  }
657
- /** Effect Equal trait. See {@link Hash.symbol} for rationale. */
657
+ /**
658
+ * Effect Equal trait. See {@link Hash.symbol} for rationale. The resolver and target take part, so
659
+ * refs to one object from different clients (same URI, different databases) are separate cache
660
+ * entries rather than all resolving through whichever client's ref was cached first.
661
+ */
658
662
  [Equal.symbol](that) {
659
- return that instanceof RefImpl && this.#uri === that.uri;
663
+ return that instanceof RefImpl && this.#uri === that.uri && this.#resolver === that.#resolver && this.#target === that.#target;
660
664
  }
661
665
  pipe() {
662
666
  return Pipeable.pipeArguments(this, arguments);
@@ -681,7 +685,7 @@ var setRefResolver = (ref, resolver) => {
681
685
  invariant(ref instanceof RefImpl, "Ref is not an instance of RefImpl", {
682
686
  "~LogMeta": "~LogMeta",
683
687
  F: __dxlog_file,
684
- L: 749,
688
+ L: 765,
685
689
  S: void 0,
686
690
  A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"]
687
691
  });
@@ -694,7 +698,7 @@ var getRefSavedTarget = (ref) => {
694
698
  invariant(ref instanceof RefImpl, "Ref is not an instance of RefImpl", {
695
699
  "~LogMeta": "~LogMeta",
696
700
  F: __dxlog_file,
697
- L: 757,
701
+ L: 773,
698
702
  S: void 0,
699
703
  A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"]
700
704
  });
@@ -718,7 +722,7 @@ var StaticRefResolver = class {
718
722
  invariant(schema, "Type entity is missing its source schema", {
719
723
  "~LogMeta": "~LogMeta",
720
724
  F: __dxlog_file,
721
- L: 789,
725
+ L: 805,
722
726
  S: this,
723
727
  A: ["schema", "'Type entity is missing its source schema'"]
724
728
  });
@@ -726,7 +730,7 @@ var StaticRefResolver = class {
726
730
  invariant(uri, "Schema has no URI", {
727
731
  "~LogMeta": "~LogMeta",
728
732
  F: __dxlog_file,
729
- L: 791,
733
+ L: 807,
730
734
  S: this,
731
735
  A: ["uri", "'Schema has no URI'"]
732
736
  });
@@ -754,6 +758,6 @@ var StaticRefResolver = class {
754
758
  }
755
759
  };
756
760
  //#endregion
757
- export { isValidProxyTarget as A, canonicalOf as C, getProxyTarget as D, getProxyHandler as E, createArrayMethodError as F, createPropertyDeleteError as I, createPropertySetError as L, setProxyHandler as M, symbolReactivePrototype as N, isProxy as O, MutationOutsideChangeContextError as P, createTextMethodError as R, EventId as S, getMutableProxy as T, loadRefTarget as _, StaticRefResolver as a, ChangeId as b, getRefSavedTarget as c, getSchemaReferenceDXN as d, isRefIdentifier as f, refArrayFamily as g, setRefResolver as h, RefTypeId as i, normalizeSpliceRange as j, isReactiveRecord as k, getReferenceAst as l, refFromEncodedReference as m, Ref as n, createEchoReferenceSchema as o, makeSettledRequest as p, RefImpl as r, createSchemaReference as s, JSON_SCHEMA_ECHO_REF_ID as t, getSchemaReference as u, change as v, createProxy as w, ChangeKeyId as x, subscribe as y, defineHiddenProperty as z };
761
+ export { symbolReactivePrototype as A, EventId as B, getProxyHandler as C, isValidProxyTarget as D, isReactiveRecord as E, createTextMethodError as F, ChangeId as I, ChangeKeyId as L, createArrayMethodError as M, createPropertyDeleteError as N, normalizeSpliceRange as O, createPropertySetError as P, EntityElementsId as R, getMutableProxy as S, isProxy as T, loadRefTarget as _, StaticRefResolver as a, canonicalOf as b, getRefSavedTarget as c, getSchemaReferenceDXN as d, isRefIdentifier as f, refArrayFamily as g, setRefResolver as h, RefTypeId as i, MutationOutsideChangeContextError as j, setProxyHandler as k, getReferenceAst as l, refFromEncodedReference as m, Ref as n, createEchoReferenceSchema as o, makeSettledRequest as p, RefImpl as r, createSchemaReference as s, JSON_SCHEMA_ECHO_REF_ID as t, getSchemaReference as u, change as v, getProxyTarget as w, createProxy as x, subscribe as y, EntityValueAnnotationId as z };
758
762
 
759
763
  //# sourceMappingURL=chunk-ref.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-ref.mjs","names":["__dxlog_file","raw","Database.Service","RefAtoms.refFamily"],"sources":["../../src/internal/common/proxy/define-hidden-property.ts","../../src/internal/common/proxy/errors.ts","../../src/internal/common/proxy/proxy-utils.ts","../../src/internal/common/proxy/symbols.ts","../../src/internal/common/proxy/reactive.ts","../../src/internal/Ref/utils.ts","../../src/internal/Ref/atoms.ts","../../src/internal/Ref/ref.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Define a non-enumerable property on an object.\n */\nexport const defineHiddenProperty = (object: any, key: string | symbol, value: any) => {\n Object.defineProperty(object, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Error thrown when attempting to mutate an object outside of an Obj.update() context.\n */\nexport class MutationOutsideChangeContextError extends Error {\n constructor(operation: string, suggestion: string) {\n super(\n `Cannot ${operation} outside of Obj.update(). Use Obj.update(obj, (mutableObj) => { ${suggestion} }) instead.`,\n );\n this.name = 'MutationOutsideChangeContextError';\n }\n}\n\n/**\n * Create an error for attempting to set a property outside of a change context.\n */\nexport const createPropertySetError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `modify object property \"${String(prop)}\"`,\n `mutableObj.${String(prop)} = value;`,\n );\n};\n\n/**\n * Create an error for attempting to delete a property outside of a change context.\n */\nexport const createPropertyDeleteError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `delete object property \"${String(prop)}\"`,\n `delete mutableObj.${String(prop)};`,\n );\n};\n\n/**\n * Create an error for attempting to call an array method outside of a change context.\n */\nexport const createArrayMethodError = (method: string): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(`call array.${method}()`, `mutableObj.array.${method}(...);`);\n};\n\n/**\n * Create an error for attempting a text CRDT mutation outside of a change context.\n */\nexport const createTextMethodError = (method: string): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(`call Text.${method}()`, `Text.${method}(mutableObj, path, ...);`);\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { createPropertyDeleteError, createPropertySetError } from './errors.ts';\nimport { type ReactiveHandler } from './proxy-types.ts';\n\n/**\n * Carries a proxy on its own target, so `value[symbolProxy] === value` identifies a proxy: read through\n * the proxy it forwards to the target and answers the proxy, read on the raw target it answers something\n * else. A registry symbol rather than module state because a remote plugin can evaluate this module\n * twice, and a proxy made by one instance must still be recognized by the other.\n */\nconst symbolProxy = Symbol.for('@dxos/echo/Proxy');\n\n/** A proxy's raw target, reachable through the proxy (which forwards the read to it) and off the target. */\nconst symbolTarget = Symbol.for('@dxos/echo/ProxyTarget');\n\n/** The {@link ReactiveHandler} backing a target. Rewritten by {@link setProxyHandler}. */\nconst symbolReactiveHandler = Symbol.for('@dxos/echo/ReactiveHandler');\n\n/**\n * A target's mutable view — the reference an `Obj.update` callback is handed. Writability belongs to the\n * reference, not to the callback's dynamic extent: the proxy named outside the callback stays read-only\n * for the callback's whole duration, so the only way to mutate is through what the callback was given.\n */\nconst symbolMutableProxy = Symbol.for('@dxos/echo/MutableProxy');\n\n/**\n * Marker placed on a reactive-object behaviour prototype (e.g. the typed handler's\n * `TypedObject` prototype). A record target whose prototype chain carries this marker\n * is a reactive data record — equivalent, for the purposes of the \"plain object\" gates\n * below, to one rooted directly at `Object.prototype`. This lets a handler move its\n * per-object metadata onto an intermediate prototype without those gates mistaking the\n * record for a foreign class instance.\n */\nexport const symbolReactivePrototype = Symbol.for('@dxos/echo/ReactivePrototype');\n\n/**\n * Internal api.\n */\nexport const isProxy = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && (value as any)[symbolProxy] === value;\n\n/**\n * True if `value` is a plain data record — either rooted at `Object.prototype` or carrying\n * a reactive behaviour prototype (see {@link symbolReactivePrototype}).\n */\nexport const isReactiveRecord = (value: any): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || (proto != null && !!proto[symbolReactivePrototype]);\n};\n\nexport const isValidProxyTarget = (value: any): value is object => {\n // Settled before the symbol probe: a symbol lookup on a primitive boxes it and walks its wrapper\n // prototype, and this runs on every proxy read. Functions never qualify either — their prototype\n // chain is neither `Object.prototype` nor reactive.\n if (value == null || typeof value !== 'object') {\n return false;\n }\n if (value[symbolProxy] === value) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n\n return isReactiveRecord(value);\n};\n\nexport const getProxyTarget = <T extends object>(proxy: any): T => {\n const target = Reflect.get(proxy, symbolTarget);\n invariant(target, 'Not a reactive proxy.');\n return target;\n};\n\nexport const getProxyHandler = <T extends object>(proxy: any): ReactiveHandler<T> => {\n const handler = Reflect.get(proxy, symbolReactiveHandler);\n invariant(handler, 'Not a reactive proxy.');\n return handler;\n};\n\n/**\n * Hands a target to a different handler, keeping the proxy — `db.add` converting an in-memory typed\n * object into a database-backed one, where the object's identity has to survive the conversion.\n */\nexport const setProxyHandler = <T extends object>(proxy: any, handler: ReactiveHandler<T>): void => {\n defineHiddenProperty(getProxyTarget(proxy), symbolReactiveHandler, handler);\n};\n\n/**\n * Clamp a splice range to `Array.prototype.splice` semantics for a string of the given `length`:\n * a negative `start` counts from the end, a `start` past the end appends, and `deleteCount` is bounded\n * to the remaining characters. Shared by both reactive handlers so the string CRDT API behaves\n * identically across the in-memory and Automerge backends (Automerge's `splice` otherwise throws on\n * out-of-range indices).\n */\nexport const normalizeSpliceRange = (\n length: number,\n start: number,\n deleteCount: number,\n): { start: number; deleteCount: number } => {\n const safeStart = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);\n const safeDeleteCount = Math.max(0, Math.min(deleteCount, length - safeStart));\n return { start: safeStart, deleteCount: safeDeleteCount };\n};\n\n/**\n * Create a reactive proxy object.\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\n *\n * @param target Object or array. Passing in array will enable array methods.\n * @param handler ReactiveHandler instance.\n */\n// TODO(burdon): Document.\n// TODO(burdon): Tests for low-level functions.\nexport const createProxy = <T extends object>(target: T, handler: ReactiveHandler<T>): T => {\n // The target carries its own proxy, so it is also the memo — a per-handler `WeakMap` would answer the\n // same question, and wrongly after `setProxyHandler` moved a target between handlers.\n const raw: object = target;\n const existingProxy: T | undefined = Reflect.get(raw, symbolProxy);\n if (existingProxy) {\n return existingProxy;\n }\n\n const proxy = new Proxy(target, REACTIVE_PROXY_HANDLER);\n // All three live on the target rather than on a per-proxy handler: the proxy has no `get` trap, so a\n // read of any of them forwards straight here, and one shared handler can serve every proxy. Stamped\n // before `init`, which recurses into nested values: a graph that reaches back to this target must find\n // the proxy already memoized rather than build a second one.\n defineHiddenProperty(target, symbolTarget, target);\n defineHiddenProperty(target, symbolReactiveHandler, handler);\n defineHiddenProperty(target, symbolProxy, proxy);\n handler.init(target);\n return proxy;\n};\n\n/**\n * The mutable view of `value`, memoized on its target beside the read-only proxy. Handed to an\n * `Obj.update` callback, and reached from there by navigation: the `get` trap below hands back the\n * mutable twin of any nested proxy, so `obj.rec.list` inside a callback is mutable all the way down\n * while the same path off the outer reference stays read-only.\n */\nexport const getMutableProxy = <T extends object>(value: T): T => {\n const target: object = isProxy(value) ? getProxyTarget(value) : value;\n const existing: T | undefined = Reflect.get(target, symbolMutableProxy);\n if (existing) {\n return existing;\n }\n\n const proxy = new Proxy(target, MUTABLE_PROXY_HANDLER);\n defineHiddenProperty(target, symbolMutableProxy, proxy);\n return proxy as T;\n};\n\n/**\n * True for a mutable view itself. Distinguishable from a read-only proxy because the `get` trap twins\n * this read too, so a view answers itself where a read-only proxy answers the view (or nothing).\n */\nconst isMutableProxy = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && (value as any)[symbolMutableProxy] === value;\n\n/**\n * The reference to store for a value being written. A mutable view is a callback-scoped handle and must\n * never enter the graph — storing one would hand a permanent write capability to every later reader, and\n * would break identity for code that kept the read-only reference. Read off the raw target rather than\n * through the view, whose `get` would twin the answer straight back into a view.\n */\nexport const canonicalOf = (value: any): any => {\n if (!isMutableProxy(value)) {\n return value;\n }\n const target = Reflect.get(value, symbolTarget);\n return Reflect.get(target, symbolProxy) ?? target;\n};\n\n/**\n * {@link canonicalOf}, applied through the literal being assigned. A view can sit anywhere inside it\n * (`obj.rows = [obj.rec]`), and normalizing only the top level would let one into the graph. Descends\n * only into plain containers: a proxy is already canonical, and rewriting one would be a stray write.\n */\nconst normalizeForStorage = (value: any, seen = new Set<object>()): any => {\n const canonical = canonicalOf(value);\n if (canonical == null || typeof canonical !== 'object' || isProxy(canonical) || seen.has(canonical)) {\n return canonical;\n }\n seen.add(canonical);\n\n // Written back only where normalizing actually changed something: the value may be a frozen or\n // shared constant, and rewriting a key with the value it already holds would throw on the former\n // and be a stray mutation of the latter.\n if (Array.isArray(canonical)) {\n canonical.forEach((element, index) => {\n const normalized = normalizeForStorage(element, seen);\n if (normalized !== element) {\n canonical[index] = normalized;\n }\n });\n } else {\n for (const key of Object.keys(canonical)) {\n const normalized = normalizeForStorage(canonical[key], seen);\n if (normalized !== canonical[key]) {\n canonical[key] = normalized;\n }\n }\n }\n return canonical;\n};\n\n/**\n * The handler behind a mutable view. Writes reach the variant's logic with no gate — being here is the\n * permission — and reads hand back mutable twins so navigation stays mutable.\n *\n * `[symbolProxy]` is twinned like any other proxy-valued read, which is what makes `isProxy` answer true\n * for a mutable view without knowing it exists: the read forwards to the target, finds the read-only\n * proxy, and comes back as this proxy, so `view[symbolProxy] === view` holds. `[symbolTarget]` is not a\n * proxy, so it still answers the raw target and `getRawTarget` unwraps a view correctly.\n */\nconst MUTABLE_PROXY_HANDLER: ProxyHandler<any> = {\n get: (target, property, receiver) => {\n const value = Reflect.get(target, property, receiver);\n return isProxy(value) ? getMutableProxy(value) : value;\n },\n set: (target, property, value, receiver) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n const stored = normalizeForStorage(value);\n return handler?.set\n ? handler.set(target, property, stored, receiver)\n : Reflect.set(target, property, stored, receiver);\n },\n defineProperty: (target, property, attributes) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n const stored = { ...attributes, value: normalizeForStorage(attributes.value) };\n return handler?.defineProperty\n ? handler.defineProperty(target, property, stored)\n : Reflect.defineProperty(target, property, stored);\n },\n deleteProperty: (target, property) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.deleteProperty\n ? handler.deleteProperty(target, property)\n : Reflect.deleteProperty(target, property);\n },\n getPrototypeOf: (target) => (Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype),\n};\n\n/**\n * This reference is read-only, and no state can change that: a mutation is allowed by holding the\n * mutable view (which `Obj.update` hands its callback), never by when it happens. Constant-cost and\n * fail-closed — there is no state to be wrong about, which is what a context lookup could not promise.\n *\n * Symbols are exempt because they are never user data: the system stamps `[ParentId]`, `[SelfURIId]`\n * and the schema-slot cache outside any change context, on objects consumers hold read-only.\n */\nconst assertReadOnly = (property: string | symbol, createError: (property: string | symbol) => Error): void => {\n if (typeof property !== 'symbol') {\n throw createError(property);\n }\n};\n\n/**\n * The handler behind every reactive proxy — one object, shared by every variant, with five traps.\n *\n * There is no `get`, `has` or `getOwnPropertyDescriptor`: a target carries its data as own properties,\n * so the engine answers all of those off the target itself with no JavaScript call. What is left is the\n * write gate, which exists because only a `Proxy` can make an assignment throw, plus two traps that\n * hide internals — `getPrototypeOf` (the instance-state prototype, so consumers see a plain object) and\n * `ownKeys` (see below).\n *\n * The read-only path through this handler is therefore identical for every variant and dispatches\n * nowhere: `getPrototypeOf` is one `Array.isArray`, `ownKeys` one `Reflect.ownKeys` and a filter, and a\n * string-keyed write outside `Obj.update` — all user data — throws before any handler is consulted.\n * Dispatch happens through the mutable view, for a mutation that is actually allowed, or here for a\n * symbol-keyed write, which `assertReadOnly` exempts as the system's own bookkeeping.\n */\nconst REACTIVE_PROXY_HANDLER: ProxyHandler<any> = {\n set: (target, property, value, receiver) => {\n assertReadOnly(property, createPropertySetError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.set\n ? handler.set(target, property, value, receiver)\n : Reflect.set(target, property, value, receiver);\n },\n defineProperty: (target, property, attributes) => {\n assertReadOnly(property, createPropertySetError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.defineProperty\n ? handler.defineProperty(target, property, attributes)\n : Reflect.defineProperty(target, property, attributes);\n },\n deleteProperty: (target, property) => {\n assertReadOnly(property, createPropertyDeleteError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.deleteProperty\n ? handler.deleteProperty(target, property)\n : Reflect.deleteProperty(target, property);\n },\n // Symbol keys are hidden from enumeration. A symbol on a target is always internal bookkeeping — the\n // same invariant the write gate relies on — and every one of them leads somewhere a generic walker\n // must not go: `[symbolReactiveHandler]` to the handler, `[EventId]` to an `Event`, `[symbolInternals]`\n // to the `ObjectCore`. A consumer that enumerates own keys and reads each value, as structural hashing\n // and deep-equality do, otherwise walks into one of those, on to its prototype methods, and dies\n // reading `Function.prototype.caller`. Filtering is legal because these are all configurable; the\n // proxy invariant only compels a handler to report non-configurable own keys.\n ownKeys: (target) =>\n Reflect.ownKeys(target).filter(\n (key) =>\n typeof key !== 'symbol' ||\n // A non-configurable own key must be reported or the engine rejects the trap result;\n // `[TypeId]` and `[SchemaId]` are locked by `setTypename`/`setSchema`.\n Reflect.getOwnPropertyDescriptor(target, key)?.configurable === false,\n ),\n // An array's real prototype chain is already what a consumer should see; only a record hides an\n // instance-state prototype behind `Object.prototype`.\n getPrototypeOf: (target) => (Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype),\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\n// TODO(dmaretskyi): Rename all symbols that are props to end with *Key.\nexport const EventId = Symbol.for('@dxos/live-object/EventId');\n\nexport const ChangeId = Symbol.for('@dxos/live-object/ChangeId');\n\n/**\n * The key this object's change context is opened under, or `undefined` while the object is not yet\n * initialized and is therefore freely mutable. Answered by each variant's behaviour prototype — the\n * in-memory objects key by their root target, database-backed ones by their `ObjectCore` — so the\n * shared proxy handler can enforce the read-only gate for every variant without dispatching.\n */\nexport const ChangeKeyId = Symbol.for('@dxos/live-object/ChangeKey');\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type RefTypeId } from '../../Ref/ref.ts';\nimport { getProxyTarget, isProxy } from './proxy-utils.ts';\nimport { ChangeId, EventId } from './symbols.ts';\n\n/**\n * Subscribe to changes on a reactive object.\n * @param obj - The reactive object to subscribe to.\n * @param callback - Called when the object changes.\n * @returns Unsubscribe function.\n */\n// TODO(wittjosiah): Consider throwing if obj doesn't have EventId instead of returning no-op.\nexport const subscribe = (obj: unknown, callback: () => void): (() => void) => {\n // Guard against non-reactive inputs (queue-stored typed objects, snapshots, plain shapes\n // with branded symbols) before `getProxyTarget`'s invariant kicks in.\n // `Obj.isObject` (KindId-based) is satisfied by these inputs, so callers like\n // `Atom.family((obj) => Atom.make((get) => Obj.subscribe(obj, ...)))` legitimately reach\n // here with a non-proxy. Falling back to a no-op preserves the documented contract that\n // values without subscription support get a no-op unsubscribe.\n if (!isProxy(obj)) {\n return () => {};\n }\n const target = getProxyTarget(obj as any);\n if (target && EventId in target) {\n return (target as any)[EventId].on(callback);\n }\n return () => {};\n};\n\n/**\n * Deeply removes readonly modifiers from all properties of T.\n * Inside Obj.update, all properties are fully mutable regardless of schema definition.\n * Ref types are preserved as-is since they are value-like objects that are replaced, not mutated.\n * Primitive types (including branded primitives) are preserved as-is.\n */\nexport type Mutable<T> = T extends string | number | boolean | bigint | symbol | null | undefined\n ? T // Primitives (including branded primitives like JsonPath) stay as-is.\n : T extends { [RefTypeId]: any }\n ? T // Keep Ref types as-is (they're value-like, not mutated in place).\n : T extends object\n ? T extends readonly (infer U)[]\n ? Mutable<U>[]\n : { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\n/**\n * Callback type for the change function.\n */\nexport type ChangeCallback<T> = (mutableObj: Mutable<T>) => void;\n\n/**\n * Perform mutations on a reactive object within a change context.\n *\n * If the object has a change handler (via ChangeId), it will be called with the callback.\n * This allows handlers to implement features like:\n * - Readonly enforcement (mutations only allowed within change context)\n * - Batched notifications (single notification for all mutations in the callback)\n * - Transaction semantics\n *\n * If the object doesn't have a change handler, the callback is called directly.\n *\n * @param obj - The reactive object to mutate.\n * @param callback - Callback that receives a mutable view of the object.\n */\nexport const change = <T>(obj: T, callback: ChangeCallback<T>): void => {\n // Check proxy first (allows handler to intercept), then fall back to target.\n // This order is important for EchoReactiveHandler which handles ChangeId in the proxy trap.\n //\n // The direct-callback fallback (no `[ChangeId]`) now only applies to true snapshots and\n // schemaless feed items (unresolvable type at decode time, see `makeDecodedEntityLive`) — live\n // feed-backed objects carry a `[ChangeId]` (via `TypedReactiveHandler`) same as any other typed\n // reactive object, so they take the `changeFn` branch above like automerge-backed objects do.\n const changeFn = (obj as any)[ChangeId];\n if (changeFn) {\n changeFn(callback);\n } else {\n callback(obj as Mutable<T>);\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Atom from 'effect/reactivity/Atom';\n\nimport { ObjectDeletedId } from '../common/types/model-symbols.ts';\nimport type { LoadOptions, Ref } from './ref.ts';\n\n/** Reads the deletion marker off a value of unconstrained target type. */\nexport const isTargetDeleted = (target: unknown): boolean =>\n typeof target === 'object' && target !== null && (target as Record<symbol, unknown>)[ObjectDeletedId] === true;\n\n/**\n * Internal helper for loading ref targets in atoms.\n * Handles the common pattern of checking for loaded target and triggering async load.\n */\nexport const loadRefTarget = <T, R>(\n ref: Ref<T>,\n get: Atom.AtomContext,\n onTargetAvailable: (target: T) => R,\n options?: LoadOptions,\n): R | undefined => {\n // Accessing `ref.target` registers a resolution callback when the target is\n // not yet loaded, so resolution can be observed via `ref.onResolved` below.\n const currentTarget = ref.target;\n if (currentTarget) {\n return onTargetAvailable(currentTarget);\n }\n\n // Subscribe to the ref's resolution event in case the target loads later.\n const unsubscribe = ref.onResolved(() => {\n const target = ref.target;\n if (target) {\n get.setSelf(onTargetAvailable(target));\n }\n });\n get.addFinalizer(unsubscribe);\n\n // Also try async load (e.g. for objects that need disk loading). `ref.target` above never yields a\n // deleted target, so this is the only path that reaches one.\n void ref\n .load(options)\n .then((loadedTarget) => {\n get.setSelf(onTargetAvailable(loadedTarget));\n })\n .catch(() => {\n // Loading failed; the resolution subscription above will pick up cross-client updates.\n });\n\n return undefined;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport { isNonNullable } from '@dxos/util';\n\nimport { subscribe } from '../common/proxy/reactive.ts';\nimport type { LoadOptions, Ref } from './ref.ts';\nimport { isTargetDeleted, loadRefTarget } from './utils.ts';\n\nconst toOptions = (includeDeleted: boolean): LoadOptions | undefined =>\n includeDeleted ? { deleted: 'include' } : undefined;\n\n/**\n * Atom family for ECHO refs, keyed by `[ref, includeDeleted]`.\n * Subscribes to target object changes; a deleted target reads as `undefined` unless included.\n */\nexport const refFamily = Atom.family(\n <T>([ref, includeDeleted]: readonly [Ref<T>, boolean]): Atom.Atom<T | undefined> => {\n return Atom.make<T | undefined>((get) => {\n let unsubscribeTarget: (() => void) | undefined;\n\n const read = (target: T): T | undefined => (!includeDeleted && isTargetDeleted(target) ? undefined : target);\n\n const setupSubscription = (target: T): T | undefined => {\n // Release any previous subscription before re-subscribing (loadRefTarget may call this more than once).\n unsubscribeTarget?.();\n unsubscribeTarget = subscribe(target, () => {\n get.setSelf(read(target));\n });\n // Runs at once when the node was disposed while the target loaded.\n get.addFinalizer(unsubscribeTarget);\n return read(target);\n };\n\n return loadRefTarget(ref, get, setupSubscription, toOptions(includeDeleted));\n });\n },\n);\n\n/**\n * Atom family for arrays of ECHO refs, keyed by `[refs, includeDeleted]` (arrays compare structurally).\n * Holds the targets in ref order, omitting those not loaded yet and, unless included, deleted ones.\n */\nexport const refArrayFamily = Atom.family(\n <T>([refs, includeDeleted]: readonly [readonly Ref<T>[], boolean]): Atom.Atom<T[]> =>\n Atom.make<T[]>((get) => refs.map((ref) => get(refFamily([ref, includeDeleted]))).filter(isNonNullable)),\n);\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Hash from 'effect/Hash';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport type * as Atom from 'effect/reactivity/Atom';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaIssue from 'effect/SchemaIssue';\nimport * as SchemaTransformation from 'effect/SchemaTransformation';\nimport type * as Types from 'effect/Types';\n\nimport { Event } from '@dxos/async';\nimport { type CustomInspectFunction, inspectCustom } from '@dxos/debug';\nimport { EncodedReference } from '@dxos/echo-protocol';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, EntityId, type URI } from '@dxos/keys';\n\nimport * as Database from '../../Database.ts';\nimport type * as Type from '../../Type.ts';\nimport {\n ReferenceAnnotationId,\n getSchemaURI,\n getTypeAnnotation,\n getTypeIdentifierAnnotation,\n} from '../Annotation/annotations.ts';\nimport {\n type AnyEntity,\n type AnyProperties,\n type UnknownTypeSchema,\n getStaticTypeSchema,\n} from '../common/types/index.ts';\nimport { type JsonSchemaType } from '../JsonSchema/index.ts';\nimport * as RefAtoms from './atoms.ts';\nimport { isTargetDeleted } from './utils.ts';\n\n/**\n * The `$id` and `$ref` fields for an ECHO reference schema.\n */\nexport const JSON_SCHEMA_ECHO_REF_ID = '/schemas/echo/ref';\n\nexport const getSchemaReference = (property: JsonSchemaType): { typename: string } | undefined => {\n const { $id, reference: { schema: { $ref } = {} } = {} } = property;\n if ($id === JSON_SCHEMA_ECHO_REF_ID && $ref) {\n const parsed = DXN.tryMake($ref);\n const typename = parsed ? DXN.getName(parsed) : undefined;\n return typename ? { typename } : undefined;\n }\n};\n\n/**\n * The reference target as a DXN, preserving the version that {@link getSchemaReference} drops.\n */\nexport const getSchemaReferenceDXN = (property: JsonSchemaType): DXN.DXN | undefined => {\n const { $id, reference: { schema: { $ref } = {} } = {} } = property;\n return $id === JSON_SCHEMA_ECHO_REF_ID && $ref ? DXN.tryMake($ref) : undefined;\n};\n\nexport const createSchemaReference = (typename: string): Types.DeepMutable<JsonSchemaType> => {\n return {\n $id: JSON_SCHEMA_ECHO_REF_ID,\n reference: {\n schema: {\n $ref: DXN.make(typename),\n },\n },\n };\n};\n\n/**\n * Runtime type-info for a reference extracted from effect AST.\n */\nexport type RefereneAST = {\n /**\n * Typename of linked schema.\n */\n typename: string;\n\n /**\n * Version of linked schema.\n */\n version: string;\n};\n\nexport const getReferenceAst = (ast: SchemaAST.AST): RefereneAST | undefined => {\n const reference = SchemaAST.getAnnotation<{ typename: string; version: string }>(ast, ReferenceAnnotationId);\n if (ast._tag !== 'Declaration' || !reference) {\n return undefined;\n }\n return { typename: reference.typename, version: reference.version };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const RefTypeId: unique symbol = Symbol.for('@dxos/echo/internal/Ref') as any;\n\n/**\n * Reference Schema.\n */\nexport interface RefSchema<T extends AnyEntity> extends Schema.Codec<Ref<T>, EncodedReference> {}\n\n/**\n * Type of the `Ref` function and extra methods attached to it.\n */\nexport interface RefFn {\n // A reference target is a `Type.AnyEntity` entity (the canonical Option B\n // input) or one of the well-known \"any object\" / \"any relation\" branded\n // schemas (`Obj.Unknown` / `Relation.Unknown`). Arbitrary raw schemas are\n // rejected.\n //\n // Referencing a type-kind entity (a meta-schema, e.g. `Type.Type`) yields a\n // reference to a stored schema record; its loaded target is any registered\n // entity (`Type.AnyEntity`), since a stored object/relation schema is itself a\n // `Type.Type` record. Referencing an object/relation type yields a reference\n // to an instance of that type.\n <S extends Type.AnyEntity | UnknownTypeSchema<any, any> = Type.AnyEntity>(\n schema: S,\n ): RefSchema<\n S extends Type.AnyType\n ? Type.AnyEntity\n : S extends Type.AnyObj | Type.AnyRelation\n ? Type.InstanceType<S>\n : S extends UnknownTypeSchema<infer A, any>\n ? A\n : never\n >;\n\n /**\n * @returns True if the object is a reference.\n */\n isRef: (obj: unknown) => obj is Ref<any>;\n\n /**\n * @returns True if the reference points to the given object id.\n */\n hasEntityId: (id: EntityId) => (ref: Ref<any>) => boolean;\n\n /**\n * @returns True if the schema is a reference schema.\n */\n isRefSchema: (schema: Schema.Codec<any, any>) => schema is RefSchema<any>;\n\n /**\n * @returns True if the schema AST is a reference schema.\n */\n isRefSchemaAST: (ast: SchemaAST.AST) => boolean;\n\n /**\n * Constructs a reference that points to the given object.\n */\n // TODO(burdon): Narrow to Obj.Unknown?\n make: <T extends AnyEntity>(object: T) => Ref<T>;\n\n /**\n * Constructs a reference that points to the object specified by the provided URI\n * (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n */\n fromURI: (uri: URI.URI) => Ref<any>;\n}\n\n/**\n * Schema builder for references.\n */\nexport const Ref: RefFn = (input: any): RefSchema<any> => {\n // `Type.Type` entities carry their source schema on the hidden slot; the\n // branded `Obj.Unknown` / `Relation.Unknown` schemas are used directly.\n const schema = getStaticTypeSchema(input) ?? input;\n assertArgument(Schema.isSchema(schema), 'schema', 'Must call with an instance of effect-schema');\n const annotation = getTypeAnnotation(schema);\n if (annotation == null) {\n throw new Error('Reference target must be an ECHO schema.');\n }\n\n return createEchoReferenceSchema(getTypeIdentifierAnnotation(schema), annotation.typename, annotation.version);\n};\n\n/**\n * Disposition of a deleted target, mirroring the query option of the same name.\n */\nexport type LoadOptions = {\n deleted?: 'exclude' | 'include';\n};\n\n/**\n * Represents materialized reference to a target.\n * This is the data type for the fields marked as ref.\n */\nexport interface Ref<T> extends Pipeable.Pipeable {\n /**\n * Target URI (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n *\n * @performance O(1) field read.\n */\n get uri(): URI.URI;\n\n /**\n * Returns true if the reference has a target available (inlined or resolver set).\n *\n * @performance O(1) field read.\n */\n get isAvailable(): boolean;\n\n /**\n * @returns The reference target.\n * May return `undefined` if the object is not loaded in the working set.\n * Accessing this property, even if it returns `undefined` will trigger the object to be loaded to the working set.\n * @deprecated A read with side effects (triggers loading, registers a resolution callback) that\n * can also throw. Use {@link peek} for a side-effect-free synchronous read, {@link load} to\n * resolve asynchronously, or the ref's atom for reactive access.\n *\n * @performance O(1) working-set lookup, but on a miss it schedules a load and registers a resolution callback.\n */\n get target(): T | undefined;\n\n /**\n * @returns The target when it is already materialized: the pinned target, or a side-effect-free\n * working-set lookup. Never throws and never triggers loading — the synchronous counterpart of\n * {@link tryLoad}. A just-added object can resolve here before it has settled into its own\n * document; callers that need a settled document must load instead.\n *\n * @performance O(1) working-set lookup; never loads and never throws.\n */\n peek(): T | undefined;\n\n /**\n * @returns Promise that will resolves with the target object.\n * Will load the object from disk if it is not present in the working set.\n * Short-circuits immediately when the target is already loaded.\n * @throws If the object is not available locally.\n *\n * @idiom org.dxos.echo.refLoad\n * applies: Resolving a ref inside an async function or Effect handler — guarantees the object is available before proceeding\n * instead-of: `ref.target` — not guaranteed to be defined in async contexts; use `await ref.load()` (or `yield* Database.load(ref)` in Effect) to ensure the target is present\n * uses: {@link load}\n * related: org.dxos.echo-react.useObjectReactive\n *\n * @performance Async; resolves immediately for an inlined or loaded target, otherwise loads from disk or the network.\n */\n load(options?: LoadOptions): Promise<T>;\n\n /**\n * @returns Promise that will resolves with the target object or undefined if the object is not loaded locally.\n *\n * @performance Async; resolves immediately for an inlined or loaded target, otherwise loads from disk or the network.\n */\n\n tryLoad(options?: LoadOptions): Promise<T | undefined>;\n\n /**\n * Subscribe to the ref's resolution event.\n * The callback fires when the target object becomes available in the working set\n * (e.g. when its document is loaded after sibling-client mutation).\n * Note: the resolver only schedules a notification when the target is requested\n * via {@link target} while it is not yet loaded.\n * @returns Function that unsubscribes the callback.\n *\n * @performance O(1) listener registration.\n */\n onResolved(callback: () => void): () => void;\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n *\n * When serialized with toJSON, the difference is between:\n * `{ \"/\": \"dxn:...\" }`\n * and\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n *\n * Clones the reference object.\n *\n * @performance O(1); allocates a new ref sharing the resolver.\n */\n noInline(): Ref<T>;\n\n /**\n * Read-only atom for the ref target.\n * Resolves once when the target loads; does NOT subscribe to target object mutations.\n * Use `Obj.atom(ref)` if you need reactive snapshots that update on every object mutation.\n *\n * @performance O(1) memoized atom-family lookup keyed by the ref URI.\n */\n get atom(): Atom.Atom<T | undefined>;\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n *\n * Examples:\n * `{ \"/\": \"dxn:...\" }`\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n *\n * @performance O(1); allocates the encoded object, inlining the saved target by reference.\n */\n encode(): EncodedReference;\n\n [RefTypeId]: {\n _T: T;\n };\n}\n\nexport declare namespace Ref {\n /**\n * Target of the reference.\n */\n export type Target<R> = R extends Ref<infer U> ? U : never;\n}\n\nRef.isRef = (obj: any): obj is Ref<any> => {\n return obj != null && typeof obj === 'object' && RefTypeId in obj;\n};\n\nRef.hasEntityId = (id: EntityId) => (ref: Ref<any>) => {\n const uri = EID.tryParse(ref.uri);\n return uri !== undefined && EID.isLocal(uri) && EID.getEntityId(uri) === id;\n};\n\nRef.isRefSchema = (schema: Schema.Codec<any, any>): schema is RefSchema<any> => {\n return Ref.isRefSchemaAST(schema.ast);\n};\n\nRef.isRefSchemaAST = (ast: SchemaAST.AST): boolean => {\n return SchemaAST.getAnnotation(ast, ReferenceAnnotationId) !== undefined;\n};\n\nRef.make = <T extends AnyProperties>(obj: T): Ref<T> => {\n if (typeof obj !== 'object' || obj === null) {\n throw new TypeError('Expected: ECHO object.');\n }\n\n // TODO(dmaretskyi): Extract to `getObjectEchoUri` function.\n const id = obj.id;\n invariant(EntityId.isValid(id), 'Invalid object ID');\n const uri = EID.make({ entityId: id });\n const ref = new RefImpl(uri, obj);\n return ref;\n};\n\nRef.fromURI = (uri: URI.URI): Ref<any> => {\n assertArgument(typeof uri === 'string', 'uri', 'Expected URI string');\n return new RefImpl(uri);\n};\n\n/**\n * `reference` field on the schema object.\n */\nexport type JsonSchemaReferenceInfo = {\n schema: { $ref: string };\n schemaVersion?: string;\n};\n\n/**\n * Wire form of a reference: the `{ '/': uri }` shape stored in the Automerge document.\n *\n * A `Struct` rather than a `declare`: Effect 4 gives declarations no JSON-schema representation, so\n * a declared encoded side serializes to an opaque placeholder and the reference annotations on the\n * outer schema never reach the generated document.\n */\n// The struct's field is a plain string while `EncodedReference` brands it as a `URI`; the values\n// this encodes are URIs by construction, and the brand carries no runtime representation.\nconst EncodedReferenceSchema = Schema.Struct({ '/': Schema.String }) as unknown as Schema.Codec<EncodedReference> &\n Schema.Struct<{ readonly '/': Schema.String }>;\n\n/** The `identifier` annotation every ref declaration carries, naming the type it points at. */\nconst refIdentifier = (target: string): string => `Ref<${target}>`;\n\n/**\n * Whether a schema identifier names a ref declaration.\n *\n * A JSON-schema generator's default reference policy hoists anything carrying an identifier into\n * `$defs`, which would replace a ref property with a `$ref` and strip the annotations readers key\n * off; generators use this to keep refs inline while still naming genuinely recursive schemas.\n */\nexport const isRefIdentifier = (identifier: string | undefined): boolean => identifier?.startsWith('Ref<') ?? false;\n\n/**\n * @internal\n */\n// TODO(burdon): Move to json schema and make private?\nexport const createEchoReferenceSchema = (\n echoUri: string | undefined,\n typename: string | undefined,\n version: string | undefined,\n): Schema.Codec<Ref<any>, EncodedReference> => {\n if (!echoUri && !typename) {\n throw new TypeError('Either echoUri or typename must be provided.');\n }\n\n const referenceInfo: JsonSchemaReferenceInfo = {\n schema: {\n // TODO(dmaretskyi): Include version?\n $ref: echoUri ?? DXN.make(typename!),\n },\n schemaVersion: version,\n };\n\n // Effect 4 splits what v3's three-parameter `declare` did into two steps: `declare` states the\n // decoded type, `encodeTo` attaches the wire form and the transformation between them.\n const refSchema = Schema.declare<Ref<any>>(Ref.isRef)\n .annotate({\n // Without an `identifier` Effect renders every rejection of a ref field as the placeholder\n // `Expected <Declaration>`, which names neither the target type nor that a reference was\n // wanted; `InvalidOperationInput` interpolates that message verbatim to remote callers.\n // `identifier` only, since `title` and `description` travel into the generated JSON schema\n // and would overwrite whatever the field's own annotations say. Built from the same value as\n // `$ref` so it survives a JSON-schema round trip, which reconstructs the schema from `echoUri`\n // where the original had only a typename.\n identifier: refIdentifier(referenceInfo.schema.$ref),\n })\n .pipe(\n Schema.encodeTo(\n // The JSON-schema keys live on the encoded node: `toJsonSchemaDocument` serializes the\n // encoded side of a transformed schema and does not see annotations on the type side.\n EncodedReferenceSchema.annotate({\n // TODO(dmaretskyi): We should remove `$id` and keep `$ref` with a fully qualified name.\n $id: JSON_SCHEMA_ECHO_REF_ID,\n $ref: JSON_SCHEMA_ECHO_REF_ID,\n reference: referenceInfo,\n }),\n SchemaTransformation.transformEffect({\n decode: (encoded) =>\n Effect.gen(function* () {\n const dbService = yield* Effect.serviceOption(Database.Service);\n // Widened because the runtime value is not always the declared encoded shape:\n // `Schema.is` routes an already-decoded `Ref` back through here.\n const candidate: unknown = encoded;\n\n if (Ref.isRef(candidate)) {\n return Option.isSome(dbService) ? dbService.value.db.makeRef(candidate.uri) : candidate;\n }\n if (!EncodedReference.isEncodedReference(candidate)) {\n return yield* Effect.fail(new SchemaIssue.InvalidValue(undefined, candidate));\n }\n\n const uri = EncodedReference.toURI(candidate);\n return Option.isSome(dbService) ? dbService.value.db.makeRef(uri) : Ref.fromURI(uri);\n }),\n encode: (value) => {\n const candidate: unknown = value;\n if (Ref.isRef(candidate)) {\n return Effect.succeed(EncodedReference.fromURI(candidate.uri));\n }\n return EncodedReference.isEncodedReference(candidate)\n ? Effect.succeed(candidate)\n : Effect.fail(new SchemaIssue.InvalidValue(undefined, candidate));\n },\n }),\n ),\n )\n .annotate({\n [ReferenceAnnotationId]: {\n typename: typename ?? '',\n version,\n },\n });\n\n return refSchema;\n};\n\n/**\n * Load-source ceiling for a resolution request. Cheaper tiers are always probed first; the\n * ceiling caps how far a request is allowed to reach:\n * - `working-set`: synchronous, in-memory only. A miss settles `unavailable` immediately.\n * - `disk`: probe the working set, then local storage; never the network.\n * - `network`: probe the working set, disk, then fetch from peers.\n *\n * `unavailable` is always relative to the requested ceiling (disk-unavailable ≠ network-unavailable).\n */\nexport type RefSource = 'working-set' | 'disk' | 'network';\n\n/**\n * A stateful, closure-aware handle to an in-flight (or settled) reference resolution.\n *\n * `ready` means the entity is FULLY USABLE: its own body and its strong-dependency closure are all\n * materialized. The body-vs-closure split is internal; `requesting` transparently covers \"a\n * dependency is still loading\".\n */\nexport interface RefResolverRequest {\n /**\n * `pending` is a one-way entry state (never re-entered). `requesting` means the body and/or\n * closure is still loading. `ready` means fully usable. `unavailable` means unreachable at the\n * requested ceiling.\n */\n readonly state: 'pending' | 'requesting' | 'ready' | 'unavailable';\n\n /**\n * Fires (deferred to a microtask) whenever {@link state} changes.\n */\n readonly stateChanged: Event<void>;\n\n /**\n * Synchronous snapshot of the resolved entity; defined iff `state === 'ready'`.\n */\n getResult(): AnyProperties | undefined;\n\n /**\n * Settles when `state ∈ {ready, unavailable}`.\n */\n wait(): Promise<AnyProperties | undefined>;\n\n /**\n * Decrements the refcount on the shared load op(s); cancels the underlying IO at zero.\n */\n abort(): void;\n}\n\nexport interface RefResolver {\n /**\n * Resolve a reference, returning a stateful handle. `source` is a required ceiling; cheaper\n * tiers are always probed first.\n */\n resolve(uri: URI.URI, options: { source: RefSource }): RefResolverRequest;\n\n /**\n * Resolve ref synchronously from the objects in the working set.\n *\n * @param uri\n * @param load If true the resolver should attempt to load the object from disk.\n * @param onLoad Callback to call when the object is loaded.\n * @deprecated Use {@link resolve} with `{ source: 'working-set' }`. Removed in Task 11.\n */\n resolveSync(uri: URI.URI, load: boolean, onLoad?: () => void): AnyProperties | undefined;\n\n /**\n * Resolver ref asynchronously.\n * @deprecated Use {@link resolve} with `{ source: 'network' }`. Removed in Task 11.\n */\n resolveLegacy(uri: URI.URI, options?: LoadOptions): Promise<AnyProperties | undefined>;\n\n /**\n * @deprecated Use {@link resolve} + `Type.getSchema`. Removed in Task 11.\n */\n resolveSchema(uri: URI.URI): Promise<Schema.Codec<any, any> | undefined>;\n\n /**\n * Resolve the source `Type.AnyEntity` entity for a type URI. Used by\n * deserialization paths (`Obj.fromJSON`) to set the back-reference accessed\n * via `Obj.getType` / `Entity.getType`. Optional — resolvers that only\n * carry raw schemas may leave this unimplemented; the deserializer falls\n * back to leaving the type entity unset.\n * @deprecated Use {@link resolve}. Removed in Task 11.\n */\n resolveType?(uri: URI.URI): Promise<unknown | undefined>;\n}\n\n/**\n * A settled {@link RefResolverRequest} with a fixed `state` and `result`, used by resolvers\n * whose backends are fully synchronous (e.g. {@link StaticRefResolver}).\n */\nexport const makeSettledRequest = (\n state: RefResolverRequest['state'],\n result: AnyProperties | undefined,\n): RefResolverRequest => ({\n state,\n stateChanged: new Event<void>(),\n getResult: () => (state === 'ready' ? result : undefined),\n wait: async () => (state === 'ready' ? result : undefined),\n abort: () => {},\n});\n\nexport class RefImpl<T> implements Ref<T> {\n [RefTypeId] = refVariance;\n\n #uri: URI.URI;\n\n /**\n * Target is set when the reference is created from a specific object.\n * In this case, the target might not be in the database.\n */\n #target: T | undefined = undefined;\n\n #resolver?: RefResolver = undefined;\n #resolved = new Event<void>();\n\n /**\n * Callback to issue a reactive notification when object is resolved.\n */\n #resolverCallback = () => {\n this.#resolved.emit();\n };\n\n constructor(uri: URI.URI, target?: T) {\n this.#uri = uri;\n this.#target = target;\n }\n\n /**\n * @inheritdoc\n */\n get uri(): URI.URI {\n return this.#uri;\n }\n\n /**\n * @inheritdoc\n */\n get target(): T | undefined {\n if (this.#target) {\n return this.#target;\n }\n\n invariant(this.#resolver, 'Resolver is not set');\n return this.#resolver.resolveSync(this.#uri, true, this.#resolverCallback) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n peek(): T | undefined {\n if (this.#target) {\n return this.#target;\n }\n if (!this.#resolver) {\n return undefined;\n }\n try {\n return this.#resolver.resolveSync(this.#uri, false, undefined) as T | undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * @inheritdoc\n */\n get isAvailable(): boolean {\n return this.#target !== undefined || this.#resolver !== undefined;\n }\n\n get atom(): Atom.Atom<T | undefined> {\n return RefAtoms.refFamily([this, false]);\n }\n\n /**\n * @inheritdoc\n */\n async load(options?: LoadOptions): Promise<T> {\n const obj = await this.tryLoad(options);\n if (obj == null) {\n throw new Error('Object not found');\n }\n return obj;\n }\n\n /**\n * @inheritdoc\n */\n async tryLoad(options?: LoadOptions): Promise<T | undefined> {\n if (this.#target) {\n // An inlined target never reaches the resolver, so it is checked here instead.\n const hidden = options?.deleted !== 'include' && isTargetDeleted(this.#target);\n return hidden ? undefined : this.#target;\n }\n invariant(this.#resolver, 'Resolver is not set');\n return (await this.#resolver.resolveLegacy(this.#uri, options)) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n onResolved(callback: () => void): () => void {\n return this.#resolved.on(callback);\n }\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n * Clones the reference object.\n */\n noInline(): RefImpl<T> {\n const ref = new RefImpl<T>(this.#uri, undefined);\n ref.#resolver = this.#resolver;\n return ref;\n }\n\n encode(): EncodedReference {\n return {\n '/': this.#uri,\n ...(this.#target ? { target: this.#target } : {}),\n };\n }\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n */\n toJSON(): EncodedReference {\n return this.encode();\n }\n\n toString(): string {\n if (this.#target) {\n return `Ref(${this.#target.toString()})`;\n }\n\n return `Ref(${this.#uri.toString()})`;\n }\n\n [inspectCustom]: CustomInspectFunction = (depth, options, inspect) => {\n return this.toString();\n };\n\n /**\n * Effect Hash trait. Required for MutableHashMap-based caches (e.g., Atom.family)\n * to deduplicate Ref instances that point to the same object.\n * ECHO proxies mint a new RefImpl whenever the object changes,\n * so without this, each one would create a separate cache entry.\n */\n [Hash.symbol](): number {\n return Hash.hash(this.#uri.toString());\n }\n\n /** Effect Equal trait. See {@link Hash.symbol} for rationale. */\n [Equal.symbol](that: Equal.Equal): boolean {\n return that instanceof RefImpl && this.#uri === that.uri;\n }\n\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n }\n\n /**\n * @internal\n */\n _setResolver(resolver: RefResolver): void {\n this.#resolver = resolver;\n }\n\n /**\n * @internal\n */\n _getSavedTarget(): T | undefined {\n return this.#target;\n }\n}\n\n/**\n * Internal API for setting the reference resolver.\n */\nexport const setRefResolver = (ref: Ref<any>, resolver: RefResolver) => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n ref._setResolver(resolver);\n};\n\n/**\n * Internal API for getting the saved target on a reference.\n */\nexport const getRefSavedTarget = (ref: Ref<any>): AnyProperties | undefined => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n return ref._getSavedTarget();\n};\n\n// Used to validate reference target type.\nconst refVariance: Ref<any>[typeof RefTypeId] = {\n _T: null as any,\n};\n\nexport const refFromEncodedReference = (encodedReference: EncodedReference, resolver?: RefResolver): Ref<any> => {\n const uri = EncodedReference.toURI(encodedReference);\n const ref = new RefImpl(uri);\n\n // TODO(dmaretskyi): Handle inline target in the encoded reference.\n\n if (resolver) {\n setRefResolver(ref, resolver);\n }\n return ref;\n};\n\nexport class StaticRefResolver implements RefResolver {\n public objects = new Map<EntityId, AnyProperties>();\n public schemas = new Map<URI.URI, Schema.Codec<any, any>>();\n\n addObject(obj: AnyProperties): this {\n this.objects.set(obj.id, obj);\n return this;\n }\n\n addSchema(input: Type.AnyEntity): this {\n const schema = getStaticTypeSchema(input);\n invariant(schema, 'Type entity is missing its source schema');\n const uri = getSchemaURI(schema);\n invariant(uri, 'Schema has no URI');\n this.schemas.set(uri, schema);\n return this;\n }\n\n resolve(uri: URI.URI, _options: { source: RefSource }): RefResolverRequest {\n const obj = this.#lookup(uri);\n return makeSettledRequest(obj ? 'ready' : 'unavailable', obj);\n }\n\n resolveSync(uri: URI.URI, _load: boolean, _onLoad?: () => void): AnyProperties | undefined {\n return this.#lookup(uri);\n }\n\n async resolveLegacy(uri: URI.URI): Promise<AnyProperties | undefined> {\n return this.#lookup(uri);\n }\n\n async resolveSchema(uri: URI.URI): Promise<Schema.Codec<any, any> | undefined> {\n return this.schemas.get(uri);\n }\n\n #lookup(uri: URI.URI): AnyProperties | undefined {\n const echoUri = EID.tryParse(uri);\n const id = echoUri ? EID.getEntityId(echoUri) : undefined;\n if (id == null) {\n return undefined;\n }\n return this.objects.get(id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,wBAAwB,QAAa,KAAsB,UAAe;CACrF,OAAO,eAAe,QAAQ,KAAK;EACjC,YAAY;EACZ,cAAc;EACd;CACF,CAAC;AACH;;;;;;ACNA,IAAa,oCAAb,cAAuD,MAAM;CAC3D,YAAY,WAAmB,YAAoB;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AAA,GAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA,CAAA,OAAA,qBAAA;EAAA,CAAC;EAClC,KAAK,QAAQ,IAAI,KAAK,MAAM;EAC5B,OAAO;CACT;CAEA,QAAQ,KAAc,UAAqD;EACzE,MAAM,MAAM,KAAK,QAAQ,GAAG;EAC5B,OAAO,mBAAmB,MAAM,UAAU,eAAe,GAAG;CAC9D;CAEA,YAAY,KAAc,OAAgB,SAAiD;EACzF,OAAO,KAAK,QAAQ,GAAG;CACzB;CAEA,MAAM,cAAc,KAAkD;EACpE,OAAO,KAAK,QAAQ,GAAG;CACzB;CAEA,MAAM,cAAc,KAA2D;EAC7E,OAAO,KAAK,QAAQ,IAAI,GAAG;CAC7B;CAEA,QAAQ,KAAyC;EAC/C,MAAM,UAAU,IAAI,SAAS,GAAG;EAChC,MAAM,KAAK,UAAU,IAAI,YAAY,OAAO,IAAI,KAAA;EAChD,IAAI,MAAM,MACR;EAEF,OAAO,KAAK,QAAQ,IAAI,EAAE;CAC5B;AACF"}
1
+ {"version":3,"file":"chunk-ref.mjs","names":["__dxlog_file","raw","Database.Service","RefAtoms.refFamily"],"sources":["../../src/internal/common/proxy/symbols.ts","../../src/internal/common/proxy/errors.ts","../../src/internal/common/proxy/proxy-utils.ts","../../src/internal/common/proxy/reactive.ts","../../src/internal/Ref/utils.ts","../../src/internal/Ref/atoms.ts","../../src/internal/Ref/ref.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\n// TODO(dmaretskyi): Rename all symbols that are props to end with *Key.\nexport const EventId = Symbol.for('@dxos/live-object/EventId');\n\nexport const ChangeId = Symbol.for('@dxos/live-object/ChangeId');\n\n/**\n * The key this object's change context is opened under, or `undefined` while the object is not yet\n * initialized and is therefore freely mutable. Answered by each variant's behaviour prototype — the\n * in-memory objects key by their root target, database-backed ones by their `ObjectCore` — so the\n * shared proxy handler can enforce the read-only gate for every variant without dispatching.\n */\nexport const ChangeKeyId = Symbol.for('@dxos/live-object/ChangeKey');\n\n/**\n * Marks an array whose elements are root entities held by identity (e.g. `meta.tags`), so the\n * ownership, copy and reactify walkers treat each element as an opaque reference, not nested data.\n */\nexport const EntityElementsId = Symbol.for('@dxos/live-object/EntityElements');\n\n/**\n * Schema annotation on a declaration whose values are root entities held by identity; an array of\n * them is marked with {@link EntityElementsId} when a typed target is prepared or assigned.\n */\nexport const EntityValueAnnotationId = '@dxos/echo/annotation/EntityValue';\n","//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Error thrown when attempting to mutate an object outside of an Obj.update() context.\n */\nexport class MutationOutsideChangeContextError extends Error {\n constructor(operation: string, suggestion: string) {\n super(\n `Cannot ${operation} outside of Obj.update(). Use Obj.update(obj, (mutableObj) => { ${suggestion} }) instead.`,\n );\n this.name = 'MutationOutsideChangeContextError';\n }\n}\n\n/**\n * Create an error for attempting to set a property outside of a change context.\n */\nexport const createPropertySetError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `modify object property \"${String(prop)}\"`,\n `mutableObj.${String(prop)} = value;`,\n );\n};\n\n/**\n * Create an error for attempting to delete a property outside of a change context.\n */\nexport const createPropertyDeleteError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `delete object property \"${String(prop)}\"`,\n `delete mutableObj.${String(prop)};`,\n );\n};\n\n/**\n * Create an error for attempting to call an array method outside of a change context.\n */\nexport const createArrayMethodError = (method: string): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(`call array.${method}()`, `mutableObj.array.${method}(...);`);\n};\n\n/**\n * Create an error for attempting a text CRDT mutation outside of a change context.\n */\nexport const createTextMethodError = (method: string): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(`call Text.${method}()`, `Text.${method}(mutableObj, path, ...);`);\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { createPropertyDeleteError, createPropertySetError } from './errors.ts';\nimport { type ReactiveHandler } from './proxy-types.ts';\nimport { EntityElementsId } from './symbols.ts';\n\n/**\n * Carries a proxy on its own target, so `value[symbolProxy] === value` identifies a proxy: read through\n * the proxy it forwards to the target and answers the proxy, read on the raw target it answers something\n * else. A registry symbol rather than module state because a remote plugin can evaluate this module\n * twice, and a proxy made by one instance must still be recognized by the other.\n */\nconst symbolProxy = Symbol.for('@dxos/echo/Proxy');\n\n/** A proxy's raw target, reachable through the proxy (which forwards the read to it) and off the target. */\nconst symbolTarget = Symbol.for('@dxos/echo/ProxyTarget');\n\n/** The {@link ReactiveHandler} backing a target. Rewritten by {@link setProxyHandler}. */\nconst symbolReactiveHandler = Symbol.for('@dxos/echo/ReactiveHandler');\n\n/**\n * A target's mutable view — the reference an `Obj.update` callback is handed. Writability belongs to the\n * reference, not to the callback's dynamic extent: the proxy named outside the callback stays read-only\n * for the callback's whole duration, so the only way to mutate is through what the callback was given.\n */\nconst symbolMutableProxy = Symbol.for('@dxos/echo/MutableProxy');\n\n/**\n * Marker placed on a reactive-object behaviour prototype (e.g. the typed handler's\n * `TypedObject` prototype). A record target whose prototype chain carries this marker\n * is a reactive data record — equivalent, for the purposes of the \"plain object\" gates\n * below, to one rooted directly at `Object.prototype`. This lets a handler move its\n * per-object metadata onto an intermediate prototype without those gates mistaking the\n * record for a foreign class instance.\n */\nexport const symbolReactivePrototype = Symbol.for('@dxos/echo/ReactivePrototype');\n\n/**\n * Internal api.\n */\nexport const isProxy = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && (value as any)[symbolProxy] === value;\n\n/**\n * True if `value` is a plain data record — either rooted at `Object.prototype` or carrying\n * a reactive behaviour prototype (see {@link symbolReactivePrototype}).\n */\nexport const isReactiveRecord = (value: any): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || (proto != null && !!proto[symbolReactivePrototype]);\n};\n\nexport const isValidProxyTarget = (value: any): value is object => {\n // Settled before the symbol probe: a symbol lookup on a primitive boxes it and walks its wrapper\n // prototype, and this runs on every proxy read. Functions never qualify either — their prototype\n // chain is neither `Object.prototype` nor reactive.\n if (value == null || typeof value !== 'object') {\n return false;\n }\n if (value[symbolProxy] === value) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n\n return isReactiveRecord(value);\n};\n\nexport const getProxyTarget = <T extends object>(proxy: any): T => {\n const target = Reflect.get(proxy, symbolTarget);\n invariant(target, 'Not a reactive proxy.');\n return target;\n};\n\nexport const getProxyHandler = <T extends object>(proxy: any): ReactiveHandler<T> => {\n const handler = Reflect.get(proxy, symbolReactiveHandler);\n invariant(handler, 'Not a reactive proxy.');\n return handler;\n};\n\n/**\n * Hands a target to a different handler, keeping the proxy — `db.add` converting an in-memory typed\n * object into a database-backed one, where the object's identity has to survive the conversion.\n */\nexport const setProxyHandler = <T extends object>(proxy: any, handler: ReactiveHandler<T>): void => {\n defineHiddenProperty(getProxyTarget(proxy), symbolReactiveHandler, handler);\n};\n\n/**\n * Clamp a splice range to `Array.prototype.splice` semantics for a string of the given `length`:\n * a negative `start` counts from the end, a `start` past the end appends, and `deleteCount` is bounded\n * to the remaining characters. Shared by both reactive handlers so the string CRDT API behaves\n * identically across the in-memory and Automerge backends (Automerge's `splice` otherwise throws on\n * out-of-range indices).\n */\nexport const normalizeSpliceRange = (\n length: number,\n start: number,\n deleteCount: number,\n): { start: number; deleteCount: number } => {\n const safeStart = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);\n const safeDeleteCount = Math.max(0, Math.min(deleteCount, length - safeStart));\n return { start: safeStart, deleteCount: safeDeleteCount };\n};\n\n/**\n * Create a reactive proxy object.\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\n *\n * @param target Object or array. Passing in array will enable array methods.\n * @param handler ReactiveHandler instance.\n */\n// TODO(burdon): Document.\n// TODO(burdon): Tests for low-level functions.\nexport const createProxy = <T extends object>(target: T, handler: ReactiveHandler<T>): T => {\n // The target carries its own proxy, so it is also the memo — a per-handler `WeakMap` would answer the\n // same question, and wrongly after `setProxyHandler` moved a target between handlers.\n const raw: object = target;\n const existingProxy: T | undefined = Reflect.get(raw, symbolProxy);\n if (existingProxy) {\n return existingProxy;\n }\n\n const proxy = new Proxy(target, REACTIVE_PROXY_HANDLER);\n // All three live on the target rather than on a per-proxy handler: the proxy has no `get` trap, so a\n // read of any of them forwards straight here, and one shared handler can serve every proxy. Stamped\n // before `init`, which recurses into nested values: a graph that reaches back to this target must find\n // the proxy already memoized rather than build a second one.\n defineHiddenProperty(target, symbolTarget, target);\n defineHiddenProperty(target, symbolReactiveHandler, handler);\n defineHiddenProperty(target, symbolProxy, proxy);\n handler.init(target);\n return proxy;\n};\n\n/**\n * The mutable view of `value`, memoized on its target beside the read-only proxy. Handed to an\n * `Obj.update` callback, and reached from there by navigation: the `get` trap below hands back the\n * mutable twin of any nested proxy, so `obj.rec.list` inside a callback is mutable all the way down\n * while the same path off the outer reference stays read-only.\n */\nexport const getMutableProxy = <T extends object>(value: T): T => {\n const target: object = isProxy(value) ? getProxyTarget(value) : value;\n const existing: T | undefined = Reflect.get(target, symbolMutableProxy);\n if (existing) {\n return existing;\n }\n\n const proxy = new Proxy(target, MUTABLE_PROXY_HANDLER);\n defineHiddenProperty(target, symbolMutableProxy, proxy);\n return proxy as T;\n};\n\n/**\n * True for a mutable view itself. Distinguishable from a read-only proxy because the `get` trap twins\n * this read too, so a view answers itself where a read-only proxy answers the view (or nothing).\n */\nconst isMutableProxy = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && (value as any)[symbolMutableProxy] === value;\n\n/**\n * The reference to store for a value being written. A mutable view is a callback-scoped handle and must\n * never enter the graph — storing one would hand a permanent write capability to every later reader, and\n * would break identity for code that kept the read-only reference. Read off the raw target rather than\n * through the view, whose `get` would twin the answer straight back into a view.\n */\nexport const canonicalOf = (value: any): any => {\n if (!isMutableProxy(value)) {\n return value;\n }\n const target = Reflect.get(value, symbolTarget);\n return Reflect.get(target, symbolProxy) ?? target;\n};\n\n/**\n * {@link canonicalOf}, applied through the literal being assigned. A view can sit anywhere inside it\n * (`obj.rows = [obj.rec]`), and normalizing only the top level would let one into the graph. Descends\n * only into plain containers: a proxy is already canonical, and rewriting one would be a stray write.\n */\nconst normalizeForStorage = (value: any, seen = new Set<object>()): any => {\n const canonical = canonicalOf(value);\n if (canonical == null || typeof canonical !== 'object' || isProxy(canonical) || seen.has(canonical)) {\n return canonical;\n }\n seen.add(canonical);\n\n // Written back only where normalizing actually changed something: the value may be a frozen or\n // shared constant, and rewriting a key with the value it already holds would throw on the former\n // and be a stray mutation of the latter.\n if (Array.isArray(canonical)) {\n canonical.forEach((element, index) => {\n const normalized = normalizeForStorage(element, seen);\n if (normalized !== element) {\n canonical[index] = normalized;\n }\n });\n } else {\n for (const key of Object.keys(canonical)) {\n const normalized = normalizeForStorage(canonical[key], seen);\n if (normalized !== canonical[key]) {\n canonical[key] = normalized;\n }\n }\n }\n return canonical;\n};\n\n/**\n * The handler behind a mutable view. Writes reach the variant's logic with no gate — being here is the\n * permission — and reads hand back mutable twins so navigation stays mutable.\n *\n * `[symbolProxy]` is twinned like any other proxy-valued read, which is what makes `isProxy` answer true\n * for a mutable view without knowing it exists: the read forwards to the target, finds the read-only\n * proxy, and comes back as this proxy, so `view[symbolProxy] === view` holds. `[symbolTarget]` is not a\n * proxy, so it still answers the raw target and `getRawTarget` unwraps a view correctly.\n */\nconst MUTABLE_PROXY_HANDLER: ProxyHandler<any> = {\n get: (target, property, receiver) => {\n const value = Reflect.get(target, property, receiver);\n // An entity held by identity (e.g. a tag in `meta.tags`) is not part of this object, so editing\n // the holder must not hand out write access to it.\n if (isProxy(value) && !(Array.isArray(target) && Reflect.get(target, EntityElementsId) === true)) {\n return getMutableProxy(value);\n }\n return value;\n },\n set: (target, property, value, receiver) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n const stored = normalizeForStorage(value);\n return handler?.set\n ? handler.set(target, property, stored, receiver)\n : Reflect.set(target, property, stored, receiver);\n },\n defineProperty: (target, property, attributes) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n const stored = { ...attributes, value: normalizeForStorage(attributes.value) };\n return handler?.defineProperty\n ? handler.defineProperty(target, property, stored)\n : Reflect.defineProperty(target, property, stored);\n },\n deleteProperty: (target, property) => {\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.deleteProperty\n ? handler.deleteProperty(target, property)\n : Reflect.deleteProperty(target, property);\n },\n getPrototypeOf: (target) => (Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype),\n};\n\n/**\n * This reference is read-only, and no state can change that: a mutation is allowed by holding the\n * mutable view (which `Obj.update` hands its callback), never by when it happens. Constant-cost and\n * fail-closed — there is no state to be wrong about, which is what a context lookup could not promise.\n *\n * Symbols are exempt because they are never user data: the system stamps `[ParentId]`, `[SelfURIId]`\n * and the schema-slot cache outside any change context, on objects consumers hold read-only.\n */\nconst assertReadOnly = (property: string | symbol, createError: (property: string | symbol) => Error): void => {\n if (typeof property !== 'symbol') {\n throw createError(property);\n }\n};\n\n/**\n * The handler behind every reactive proxy — one object, shared by every variant, with five traps.\n *\n * There is no `get`, `has` or `getOwnPropertyDescriptor`: a target carries its data as own properties,\n * so the engine answers all of those off the target itself with no JavaScript call. What is left is the\n * write gate, which exists because only a `Proxy` can make an assignment throw, plus two traps that\n * hide internals — `getPrototypeOf` (the instance-state prototype, so consumers see a plain object) and\n * `ownKeys` (see below).\n *\n * The read-only path through this handler is therefore identical for every variant and dispatches\n * nowhere: `getPrototypeOf` is one `Array.isArray`, `ownKeys` one `Reflect.ownKeys` and a filter, and a\n * string-keyed write outside `Obj.update` — all user data — throws before any handler is consulted.\n * Dispatch happens through the mutable view, for a mutation that is actually allowed, or here for a\n * symbol-keyed write, which `assertReadOnly` exempts as the system's own bookkeeping.\n */\nconst REACTIVE_PROXY_HANDLER: ProxyHandler<any> = {\n set: (target, property, value, receiver) => {\n assertReadOnly(property, createPropertySetError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.set\n ? handler.set(target, property, value, receiver)\n : Reflect.set(target, property, value, receiver);\n },\n defineProperty: (target, property, attributes) => {\n assertReadOnly(property, createPropertySetError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.defineProperty\n ? handler.defineProperty(target, property, attributes)\n : Reflect.defineProperty(target, property, attributes);\n },\n deleteProperty: (target, property) => {\n assertReadOnly(property, createPropertyDeleteError);\n const handler: ReactiveHandler<any> | undefined = Reflect.get(target, symbolReactiveHandler);\n return handler?.deleteProperty\n ? handler.deleteProperty(target, property)\n : Reflect.deleteProperty(target, property);\n },\n // Symbol keys are hidden from enumeration. A symbol on a target is always internal bookkeeping — the\n // same invariant the write gate relies on — and every one of them leads somewhere a generic walker\n // must not go: `[symbolReactiveHandler]` to the handler, `[EventId]` to an `Event`, `[symbolInternals]`\n // to the `ObjectCore`. A consumer that enumerates own keys and reads each value, as structural hashing\n // and deep-equality do, otherwise walks into one of those, on to its prototype methods, and dies\n // reading `Function.prototype.caller`. Filtering is legal because these are all configurable; the\n // proxy invariant only compels a handler to report non-configurable own keys.\n ownKeys: (target) =>\n Reflect.ownKeys(target).filter(\n (key) =>\n typeof key !== 'symbol' ||\n // A non-configurable own key must be reported or the engine rejects the trap result;\n // `[TypeId]` and `[SchemaId]` are locked by `setTypename`/`setSchema`.\n Reflect.getOwnPropertyDescriptor(target, key)?.configurable === false,\n ),\n // An array's real prototype chain is already what a consumer should see; only a record hides an\n // instance-state prototype behind `Object.prototype`.\n getPrototypeOf: (target) => (Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype),\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type RefTypeId } from '../../Ref/ref.ts';\nimport { getProxyTarget, isProxy } from './proxy-utils.ts';\nimport { ChangeId, EventId } from './symbols.ts';\n\n/**\n * Subscribe to changes on a reactive object.\n * @param obj - The reactive object to subscribe to.\n * @param callback - Called when the object changes.\n * @returns Unsubscribe function.\n */\n// TODO(wittjosiah): Consider throwing if obj doesn't have EventId instead of returning no-op.\nexport const subscribe = (obj: unknown, callback: () => void): (() => void) => {\n // Guard against non-reactive inputs (queue-stored typed objects, snapshots, plain shapes\n // with branded symbols) before `getProxyTarget`'s invariant kicks in.\n // `Obj.isObject` (KindId-based) is satisfied by these inputs, so callers like\n // `Atom.family((obj) => Atom.make((get) => Obj.subscribe(obj, ...)))` legitimately reach\n // here with a non-proxy. Falling back to a no-op preserves the documented contract that\n // values without subscription support get a no-op unsubscribe.\n if (!isProxy(obj)) {\n return () => {};\n }\n const target = getProxyTarget(obj as any);\n if (target && EventId in target) {\n return (target as any)[EventId].on(callback);\n }\n return () => {};\n};\n\n/**\n * Deeply removes readonly modifiers from all properties of T.\n * Inside Obj.update, all properties are fully mutable regardless of schema definition.\n * Ref types are preserved as-is since they are value-like objects that are replaced, not mutated.\n * Primitive types (including branded primitives) are preserved as-is.\n */\nexport type Mutable<T> = T extends string | number | boolean | bigint | symbol | null | undefined\n ? T // Primitives (including branded primitives like JsonPath) stay as-is.\n : T extends { [RefTypeId]: any }\n ? T // Keep Ref types as-is (they're value-like, not mutated in place).\n : T extends object\n ? T extends readonly (infer U)[]\n ? Mutable<U>[]\n : { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\n/**\n * Callback type for the change function.\n */\nexport type ChangeCallback<T> = (mutableObj: Mutable<T>) => void;\n\n/**\n * Perform mutations on a reactive object within a change context.\n *\n * If the object has a change handler (via ChangeId), it will be called with the callback.\n * This allows handlers to implement features like:\n * - Readonly enforcement (mutations only allowed within change context)\n * - Batched notifications (single notification for all mutations in the callback)\n * - Transaction semantics\n *\n * If the object doesn't have a change handler, the callback is called directly.\n *\n * @param obj - The reactive object to mutate.\n * @param callback - Callback that receives a mutable view of the object.\n */\nexport const change = <T>(obj: T, callback: ChangeCallback<T>): void => {\n // Check proxy first (allows handler to intercept), then fall back to target.\n // This order is important for EchoReactiveHandler which handles ChangeId in the proxy trap.\n //\n // The direct-callback fallback (no `[ChangeId]`) now only applies to true snapshots and\n // schemaless feed items (unresolvable type at decode time, see `makeDecodedEntityLive`) — live\n // feed-backed objects carry a `[ChangeId]` (via `TypedReactiveHandler`) same as any other typed\n // reactive object, so they take the `changeFn` branch above like automerge-backed objects do.\n const changeFn = (obj as any)[ChangeId];\n if (changeFn) {\n changeFn(callback);\n } else {\n callback(obj as Mutable<T>);\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Atom from 'effect/reactivity/Atom';\n\nimport { ObjectDeletedId } from '../common/types/model-symbols.ts';\nimport type { LoadOptions, Ref } from './ref.ts';\n\n/** Reads the deletion marker off a value of unconstrained target type. */\nexport const isTargetDeleted = (target: unknown): boolean =>\n typeof target === 'object' && target !== null && (target as Record<symbol, unknown>)[ObjectDeletedId] === true;\n\n/**\n * Internal helper for loading ref targets in atoms.\n * Handles the common pattern of checking for loaded target and triggering async load.\n */\nexport const loadRefTarget = <T, R>(\n ref: Ref<T>,\n get: Atom.AtomContext,\n onTargetAvailable: (target: T) => R,\n options?: LoadOptions,\n): R | undefined => {\n // Accessing `ref.target` registers a resolution callback when the target is\n // not yet loaded, so resolution can be observed via `ref.onResolved` below.\n const currentTarget = ref.target;\n if (currentTarget) {\n return onTargetAvailable(currentTarget);\n }\n\n // Subscribe to the ref's resolution event in case the target loads later.\n const unsubscribe = ref.onResolved(() => {\n const target = ref.target;\n if (target) {\n get.setSelf(onTargetAvailable(target));\n }\n });\n get.addFinalizer(unsubscribe);\n\n // Also try async load (e.g. for objects that need disk loading). `ref.target` above never yields a\n // deleted target, so this is the only path that reaches one.\n void ref\n .load(options)\n .then((loadedTarget) => {\n get.setSelf(onTargetAvailable(loadedTarget));\n })\n .catch(() => {\n // Loading failed; the resolution subscription above will pick up cross-client updates.\n });\n\n return undefined;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport { isNonNullable } from '@dxos/util';\n\nimport { subscribe } from '../common/proxy/reactive.ts';\nimport type { LoadOptions, Ref } from './ref.ts';\nimport { isTargetDeleted, loadRefTarget } from './utils.ts';\n\nconst toOptions = (includeDeleted: boolean): LoadOptions | undefined =>\n includeDeleted ? { deleted: 'include' } : undefined;\n\n/**\n * Atom family for ECHO refs, keyed by `[ref, includeDeleted]`.\n * Subscribes to target object changes; a deleted target reads as `undefined` unless included.\n */\nexport const refFamily = Atom.family(\n <T>([ref, includeDeleted]: readonly [Ref<T>, boolean]): Atom.Atom<T | undefined> => {\n return Atom.make<T | undefined>((get) => {\n let unsubscribeTarget: (() => void) | undefined;\n\n const read = (target: T): T | undefined => (!includeDeleted && isTargetDeleted(target) ? undefined : target);\n\n const setupSubscription = (target: T): T | undefined => {\n // Release any previous subscription before re-subscribing (loadRefTarget may call this more than once).\n unsubscribeTarget?.();\n unsubscribeTarget = subscribe(target, () => {\n get.setSelf(read(target));\n });\n // Runs at once when the node was disposed while the target loaded.\n get.addFinalizer(unsubscribeTarget);\n return read(target);\n };\n\n return loadRefTarget(ref, get, setupSubscription, toOptions(includeDeleted));\n });\n },\n);\n\n/**\n * Atom family for arrays of ECHO refs, keyed by `[refs, includeDeleted]` (arrays compare structurally).\n * Holds the targets in ref order, omitting those not loaded yet and, unless included, deleted ones.\n */\nexport const refArrayFamily = Atom.family(\n <T>([refs, includeDeleted]: readonly [readonly Ref<T>[], boolean]): Atom.Atom<T[]> =>\n Atom.make<T[]>((get) => refs.map((ref) => get(refFamily([ref, includeDeleted]))).filter(isNonNullable)),\n);\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Hash from 'effect/Hash';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport type * as Atom from 'effect/reactivity/Atom';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaIssue from 'effect/SchemaIssue';\nimport * as SchemaTransformation from 'effect/SchemaTransformation';\nimport type * as Types from 'effect/Types';\n\nimport { Event } from '@dxos/async';\nimport { type CustomInspectFunction, inspectCustom } from '@dxos/debug';\nimport { EncodedReference } from '@dxos/echo-protocol';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, EntityId, type URI } from '@dxos/keys';\n\nimport * as Database from '../../Database.ts';\nimport type * as Type from '../../Type.ts';\nimport {\n ReferenceAnnotationId,\n getSchemaURI,\n getTypeAnnotation,\n getTypeIdentifierAnnotation,\n} from '../Annotation/annotations.ts';\nimport {\n type AnyEntity,\n type AnyProperties,\n type UnknownTypeSchema,\n getStaticTypeSchema,\n} from '../common/types/index.ts';\nimport { type JsonSchemaType } from '../JsonSchema/index.ts';\nimport * as RefAtoms from './atoms.ts';\nimport { isTargetDeleted } from './utils.ts';\n\n/**\n * The `$id` and `$ref` fields for an ECHO reference schema.\n */\nexport const JSON_SCHEMA_ECHO_REF_ID = '/schemas/echo/ref';\n\nexport const getSchemaReference = (property: JsonSchemaType): { typename: string } | undefined => {\n const { $id, reference: { schema: { $ref } = {} } = {} } = property;\n if ($id === JSON_SCHEMA_ECHO_REF_ID && $ref) {\n const parsed = DXN.tryMake($ref);\n const typename = parsed ? DXN.getName(parsed) : undefined;\n return typename ? { typename } : undefined;\n }\n};\n\n/**\n * The reference target as a DXN, preserving the version that {@link getSchemaReference} drops.\n */\nexport const getSchemaReferenceDXN = (property: JsonSchemaType): DXN.DXN | undefined => {\n const { $id, reference: { schema: { $ref } = {} } = {} } = property;\n return $id === JSON_SCHEMA_ECHO_REF_ID && $ref ? DXN.tryMake($ref) : undefined;\n};\n\nexport const createSchemaReference = (typename: string): Types.DeepMutable<JsonSchemaType> => {\n return {\n $id: JSON_SCHEMA_ECHO_REF_ID,\n reference: {\n schema: {\n $ref: DXN.make(typename),\n },\n },\n };\n};\n\n/**\n * Runtime type-info for a reference extracted from effect AST.\n */\nexport type RefereneAST = {\n /**\n * Typename of linked schema.\n */\n typename: string;\n\n /**\n * Version of linked schema.\n */\n version: string;\n};\n\nexport const getReferenceAst = (ast: SchemaAST.AST): RefereneAST | undefined => {\n const reference = SchemaAST.getAnnotation<{ typename: string; version: string }>(ast, ReferenceAnnotationId);\n if (ast._tag !== 'Declaration' || !reference) {\n return undefined;\n }\n return { typename: reference.typename, version: reference.version };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const RefTypeId: unique symbol = Symbol.for('@dxos/echo/internal/Ref') as any;\n\n/**\n * Reference Schema.\n */\nexport interface RefSchema<T extends AnyEntity> extends Schema.Codec<Ref<T>, EncodedReference> {}\n\n/**\n * Type of the `Ref` function and extra methods attached to it.\n */\nexport interface RefFn {\n // A reference target is a `Type.AnyEntity` entity (the canonical Option B\n // input) or one of the well-known \"any object\" / \"any relation\" branded\n // schemas (`Obj.Unknown` / `Relation.Unknown`). Arbitrary raw schemas are\n // rejected.\n //\n // Referencing a type-kind entity (a meta-schema, e.g. `Type.Type`) yields a\n // reference to a stored schema record; its loaded target is any registered\n // entity (`Type.AnyEntity`), since a stored object/relation schema is itself a\n // `Type.Type` record. Referencing an object/relation type yields a reference\n // to an instance of that type.\n <S extends Type.AnyEntity | UnknownTypeSchema<any, any> = Type.AnyEntity>(\n schema: S,\n ): RefSchema<\n S extends Type.AnyType\n ? Type.AnyEntity\n : S extends Type.AnyObj | Type.AnyRelation\n ? Type.InstanceType<S>\n : S extends UnknownTypeSchema<infer A, any>\n ? A\n : never\n >;\n\n /**\n * @returns True if the object is a reference.\n */\n isRef: (obj: unknown) => obj is Ref<any>;\n\n /**\n * @returns True if the reference points to the given object id.\n */\n hasEntityId: (id: EntityId) => (ref: Ref<any>) => boolean;\n\n /**\n * @returns True if the schema is a reference schema.\n */\n isRefSchema: (schema: Schema.Codec<any, any>) => schema is RefSchema<any>;\n\n /**\n * @returns True if the schema AST is a reference schema.\n */\n isRefSchemaAST: (ast: SchemaAST.AST) => boolean;\n\n /**\n * Constructs a reference that points to the given object.\n */\n // TODO(burdon): Narrow to Obj.Unknown?\n make: <T extends AnyEntity>(object: T) => Ref<T>;\n\n /**\n * Constructs a reference that points to the object specified by the provided URI\n * (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n */\n fromURI: (uri: URI.URI) => Ref<any>;\n}\n\n/**\n * Schema builder for references.\n */\nexport const Ref: RefFn = (input: any): RefSchema<any> => {\n // `Type.Type` entities carry their source schema on the hidden slot; the\n // branded `Obj.Unknown` / `Relation.Unknown` schemas are used directly.\n const schema = getStaticTypeSchema(input) ?? input;\n assertArgument(Schema.isSchema(schema), 'schema', 'Must call with an instance of effect-schema');\n const annotation = getTypeAnnotation(schema);\n if (annotation == null) {\n throw new Error('Reference target must be an ECHO schema.');\n }\n\n return createEchoReferenceSchema(getTypeIdentifierAnnotation(schema), annotation.typename, annotation.version);\n};\n\n/**\n * Disposition of a deleted target, mirroring the query option of the same name.\n */\nexport type LoadOptions = {\n deleted?: 'exclude' | 'include';\n};\n\n/**\n * Represents materialized reference to a target.\n * This is the data type for the fields marked as ref.\n */\nexport interface Ref<T> extends Pipeable.Pipeable {\n /**\n * Target URI (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n *\n * @performance O(1) field read.\n */\n get uri(): URI.URI;\n\n /**\n * Returns true if the reference has a target available (inlined or resolver set).\n *\n * @performance O(1) field read.\n */\n get isAvailable(): boolean;\n\n /**\n * @returns The reference target.\n * May return `undefined` if the object is not loaded in the working set.\n * Accessing this property, even if it returns `undefined` will trigger the object to be loaded to the working set.\n * @deprecated A read with side effects (triggers loading, registers a resolution callback) that\n * can also throw. Use {@link peek} for a side-effect-free synchronous read, {@link load} to\n * resolve asynchronously, or the ref's atom for reactive access.\n *\n * @performance O(1) working-set lookup, but on a miss it schedules a load and registers a resolution callback.\n */\n get target(): T | undefined;\n\n /**\n * @returns The target when it is already materialized: the pinned target, or a side-effect-free\n * working-set lookup. Never throws and never triggers loading — the synchronous counterpart of\n * {@link tryLoad}. A just-added object can resolve here before it has settled into its own\n * document; callers that need a settled document must load instead.\n *\n * @performance O(1) working-set lookup; never loads and never throws.\n */\n peek(): T | undefined;\n\n /**\n * @returns Promise that will resolves with the target object.\n * Will load the object from disk if it is not present in the working set.\n * Short-circuits immediately when the target is already loaded.\n * @throws If the object is not available locally.\n *\n * @idiom org.dxos.echo.refLoad\n * applies: Resolving a ref inside an async function or Effect handler — guarantees the object is available before proceeding\n * instead-of: `ref.target` — not guaranteed to be defined in async contexts; use `await ref.load()` (or `yield* Database.load(ref)` in Effect) to ensure the target is present\n * uses: {@link load}\n * related: org.dxos.echo-react.useObjectReactive\n *\n * @performance Async; resolves immediately for an inlined or loaded target, otherwise loads from disk or the network.\n */\n load(options?: LoadOptions): Promise<T>;\n\n /**\n * @returns Promise that will resolves with the target object or undefined if the object is not loaded locally.\n *\n * @performance Async; resolves immediately for an inlined or loaded target, otherwise loads from disk or the network.\n */\n\n tryLoad(options?: LoadOptions): Promise<T | undefined>;\n\n /**\n * Subscribe to the ref's resolution event.\n * The callback fires when the target object becomes available in the working set\n * (e.g. when its document is loaded after sibling-client mutation).\n * Note: the resolver only schedules a notification when the target is requested\n * via {@link target} while it is not yet loaded.\n * @returns Function that unsubscribes the callback.\n *\n * @performance O(1) listener registration.\n */\n onResolved(callback: () => void): () => void;\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n *\n * When serialized with toJSON, the difference is between:\n * `{ \"/\": \"dxn:...\" }`\n * and\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n *\n * Clones the reference object.\n *\n * @performance O(1); allocates a new ref sharing the resolver.\n */\n noInline(): Ref<T>;\n\n /**\n * Read-only atom for the ref target.\n * Resolves once when the target loads; does NOT subscribe to target object mutations.\n * Use `Obj.atom(ref)` if you need reactive snapshots that update on every object mutation.\n *\n * @performance O(1) memoized atom-family lookup keyed by the ref URI.\n */\n get atom(): Atom.Atom<T | undefined>;\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n *\n * Examples:\n * `{ \"/\": \"dxn:...\" }`\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n *\n * @performance O(1); allocates the encoded object, inlining the saved target by reference.\n */\n encode(): EncodedReference;\n\n [RefTypeId]: {\n _T: T;\n };\n}\n\nexport declare namespace Ref {\n /**\n * Target of the reference.\n */\n export type Target<R> = R extends Ref<infer U> ? U : never;\n}\n\nRef.isRef = (obj: any): obj is Ref<any> => {\n return obj != null && typeof obj === 'object' && RefTypeId in obj;\n};\n\nRef.hasEntityId = (id: EntityId) => (ref: Ref<any>) => {\n const uri = EID.tryParse(ref.uri);\n return uri !== undefined && EID.isLocal(uri) && EID.getEntityId(uri) === id;\n};\n\nRef.isRefSchema = (schema: Schema.Codec<any, any>): schema is RefSchema<any> => {\n return Ref.isRefSchemaAST(schema.ast);\n};\n\nRef.isRefSchemaAST = (ast: SchemaAST.AST): boolean => {\n return SchemaAST.getAnnotation(ast, ReferenceAnnotationId) !== undefined;\n};\n\nRef.make = <T extends AnyProperties>(obj: T): Ref<T> => {\n if (typeof obj !== 'object' || obj === null) {\n throw new TypeError('Expected: ECHO object.');\n }\n\n // TODO(dmaretskyi): Extract to `getObjectEchoUri` function.\n const id = obj.id;\n invariant(EntityId.isValid(id), 'Invalid object ID');\n const uri = EID.make({ entityId: id });\n const ref = new RefImpl(uri, obj);\n return ref;\n};\n\nRef.fromURI = (uri: URI.URI): Ref<any> => {\n assertArgument(typeof uri === 'string', 'uri', 'Expected URI string');\n return new RefImpl(uri);\n};\n\n/**\n * `reference` field on the schema object.\n */\nexport type JsonSchemaReferenceInfo = {\n schema: { $ref: string };\n schemaVersion?: string;\n};\n\n/**\n * Wire form of a reference: the `{ '/': uri }` shape stored in the Automerge document.\n *\n * A `Struct` rather than a `declare`: Effect 4 gives declarations no JSON-schema representation, so\n * a declared encoded side serializes to an opaque placeholder and the reference annotations on the\n * outer schema never reach the generated document.\n */\n// The struct's field is a plain string while `EncodedReference` brands it as a `URI`; the values\n// this encodes are URIs by construction, and the brand carries no runtime representation.\nconst EncodedReferenceSchema = Schema.Struct({ '/': Schema.String }) as unknown as Schema.Codec<EncodedReference> &\n Schema.Struct<{ readonly '/': Schema.String }>;\n\n/** The `identifier` annotation every ref declaration carries, naming the type it points at. */\nconst refIdentifier = (target: string): string => `Ref<${target}>`;\n\n/**\n * Whether a schema identifier names a ref declaration.\n *\n * A JSON-schema generator's default reference policy hoists anything carrying an identifier into\n * `$defs`, which would replace a ref property with a `$ref` and strip the annotations readers key\n * off; generators use this to keep refs inline while still naming genuinely recursive schemas.\n */\nexport const isRefIdentifier = (identifier: string | undefined): boolean => identifier?.startsWith('Ref<') ?? false;\n\n/**\n * @internal\n */\n// TODO(burdon): Move to json schema and make private?\nexport const createEchoReferenceSchema = (\n echoUri: string | undefined,\n typename: string | undefined,\n version: string | undefined,\n): Schema.Codec<Ref<any>, EncodedReference> => {\n if (!echoUri && !typename) {\n throw new TypeError('Either echoUri or typename must be provided.');\n }\n\n const referenceInfo: JsonSchemaReferenceInfo = {\n schema: {\n // TODO(dmaretskyi): Include version?\n $ref: echoUri ?? DXN.make(typename!),\n },\n schemaVersion: version,\n };\n\n // Effect 4 splits what v3's three-parameter `declare` did into two steps: `declare` states the\n // decoded type, `encodeTo` attaches the wire form and the transformation between them.\n const refSchema = Schema.declare<Ref<any>>(Ref.isRef)\n .annotate({\n // Without an `identifier` Effect renders every rejection of a ref field as the placeholder\n // `Expected <Declaration>`, which names neither the target type nor that a reference was\n // wanted; `InvalidOperationInput` interpolates that message verbatim to remote callers.\n // `identifier` only, since `title` and `description` travel into the generated JSON schema\n // and would overwrite whatever the field's own annotations say. Built from the same value as\n // `$ref` so it survives a JSON-schema round trip, which reconstructs the schema from `echoUri`\n // where the original had only a typename.\n identifier: refIdentifier(referenceInfo.schema.$ref),\n })\n .pipe(\n Schema.encodeTo(\n // The JSON-schema keys live on the encoded node: `toJsonSchemaDocument` serializes the\n // encoded side of a transformed schema and does not see annotations on the type side.\n EncodedReferenceSchema.annotate({\n // TODO(dmaretskyi): We should remove `$id` and keep `$ref` with a fully qualified name.\n $id: JSON_SCHEMA_ECHO_REF_ID,\n $ref: JSON_SCHEMA_ECHO_REF_ID,\n reference: referenceInfo,\n }),\n SchemaTransformation.transformEffect({\n decode: (encoded) =>\n Effect.gen(function* () {\n const dbService = yield* Effect.serviceOption(Database.Service);\n // Widened because the runtime value is not always the declared encoded shape:\n // `Schema.is` routes an already-decoded `Ref` back through here.\n const candidate: unknown = encoded;\n\n if (Ref.isRef(candidate)) {\n return Option.isSome(dbService) ? dbService.value.db.makeRef(candidate.uri) : candidate;\n }\n if (!EncodedReference.isEncodedReference(candidate)) {\n return yield* Effect.fail(new SchemaIssue.InvalidValue(undefined, candidate));\n }\n\n const uri = EncodedReference.toURI(candidate);\n // Rejected here so a malformed URI from a caller (e.g. a full URI wrapped in `echo:///`)\n // never reaches the document, where it would resolve to nothing.\n if (EID.isEID(uri) && EID.tryParse(uri) === undefined) {\n return yield* Effect.fail(\n new SchemaIssue.InvalidValue({ message: `Invalid echo URI: ${uri}` }, candidate),\n );\n }\n return Option.isSome(dbService) ? dbService.value.db.makeRef(uri) : Ref.fromURI(uri);\n }),\n encode: (value) => {\n const candidate: unknown = value;\n if (Ref.isRef(candidate)) {\n return Effect.succeed(EncodedReference.fromURI(candidate.uri));\n }\n return EncodedReference.isEncodedReference(candidate)\n ? Effect.succeed(candidate)\n : Effect.fail(new SchemaIssue.InvalidValue(undefined, candidate));\n },\n }),\n ),\n )\n .annotate({\n [ReferenceAnnotationId]: {\n typename: typename ?? '',\n version,\n },\n });\n\n return refSchema;\n};\n\n/**\n * Load-source ceiling for a resolution request. Cheaper tiers are always probed first; the\n * ceiling caps how far a request is allowed to reach:\n * - `working-set`: synchronous, in-memory only. A miss settles `unavailable` immediately.\n * - `disk`: probe the working set, then local storage; never the network.\n * - `network`: probe the working set, disk, then fetch from peers.\n *\n * `unavailable` is always relative to the requested ceiling (disk-unavailable ≠ network-unavailable).\n */\nexport type RefSource = 'working-set' | 'disk' | 'network';\n\n/**\n * A stateful, closure-aware handle to an in-flight (or settled) reference resolution.\n *\n * `ready` means the entity is FULLY USABLE: its own body and its strong-dependency closure are all\n * materialized. The body-vs-closure split is internal; `requesting` transparently covers \"a\n * dependency is still loading\".\n */\nexport interface RefResolverRequest {\n /**\n * `pending` is a one-way entry state (never re-entered). `requesting` means the body and/or\n * closure is still loading. `ready` means fully usable. `unavailable` means unreachable at the\n * requested ceiling.\n */\n readonly state: 'pending' | 'requesting' | 'ready' | 'unavailable';\n\n /**\n * Fires (deferred to a microtask) whenever {@link state} changes.\n */\n readonly stateChanged: Event<void>;\n\n /**\n * Synchronous snapshot of the resolved entity; defined iff `state === 'ready'`.\n */\n getResult(): AnyProperties | undefined;\n\n /**\n * Settles when `state ∈ {ready, unavailable}`.\n */\n wait(): Promise<AnyProperties | undefined>;\n\n /**\n * Decrements the refcount on the shared load op(s); cancels the underlying IO at zero.\n */\n abort(): void;\n}\n\nexport interface RefResolver {\n /**\n * Resolve a reference, returning a stateful handle. `source` is a required ceiling; cheaper\n * tiers are always probed first.\n */\n resolve(uri: URI.URI, options: { source: RefSource }): RefResolverRequest;\n\n /**\n * Resolve ref synchronously from the objects in the working set.\n *\n * @param uri\n * @param load If true the resolver should attempt to load the object from disk.\n * @param onLoad Callback to call when the object is loaded.\n * @deprecated Use {@link resolve} with `{ source: 'working-set' }`. Removed in Task 11.\n */\n resolveSync(uri: URI.URI, load: boolean, onLoad?: () => void): AnyProperties | undefined;\n\n /**\n * Resolver ref asynchronously.\n * @deprecated Use {@link resolve} with `{ source: 'network' }`. Removed in Task 11.\n */\n resolveLegacy(uri: URI.URI, options?: LoadOptions): Promise<AnyProperties | undefined>;\n\n /**\n * @deprecated Use {@link resolve} + `Type.getSchema`. Removed in Task 11.\n */\n resolveSchema(uri: URI.URI): Promise<Schema.Codec<any, any> | undefined>;\n\n /**\n * Resolve the source `Type.AnyEntity` entity for a type URI. Used by\n * deserialization paths (`Obj.fromJSON`) to set the back-reference accessed\n * via `Obj.getType` / `Entity.getType`. Optional — resolvers that only\n * carry raw schemas may leave this unimplemented; the deserializer falls\n * back to leaving the type entity unset.\n * @deprecated Use {@link resolve}. Removed in Task 11.\n */\n resolveType?(uri: URI.URI): Promise<unknown | undefined>;\n}\n\n/**\n * A settled {@link RefResolverRequest} with a fixed `state` and `result`, used by resolvers\n * whose backends are fully synchronous (e.g. {@link StaticRefResolver}).\n */\nexport const makeSettledRequest = (\n state: RefResolverRequest['state'],\n result: AnyProperties | undefined,\n): RefResolverRequest => ({\n state,\n stateChanged: new Event<void>(),\n getResult: () => (state === 'ready' ? result : undefined),\n wait: async () => (state === 'ready' ? result : undefined),\n abort: () => {},\n});\n\nexport class RefImpl<T> implements Ref<T> {\n [RefTypeId] = refVariance;\n\n #uri: URI.URI;\n\n /**\n * Target is set when the reference is created from a specific object.\n * In this case, the target might not be in the database.\n */\n #target: T | undefined = undefined;\n\n #resolver?: RefResolver = undefined;\n #resolved = new Event<void>();\n\n /**\n * Callback to issue a reactive notification when object is resolved.\n */\n #resolverCallback = () => {\n this.#resolved.emit();\n };\n\n constructor(uri: URI.URI, target?: T) {\n this.#uri = uri;\n this.#target = target;\n }\n\n /**\n * @inheritdoc\n */\n get uri(): URI.URI {\n return this.#uri;\n }\n\n /**\n * @inheritdoc\n */\n get target(): T | undefined {\n if (this.#target) {\n return this.#target;\n }\n\n invariant(this.#resolver, 'Resolver is not set');\n return this.#resolver.resolveSync(this.#uri, true, this.#resolverCallback) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n peek(): T | undefined {\n if (this.#target) {\n return this.#target;\n }\n if (!this.#resolver) {\n return undefined;\n }\n try {\n return this.#resolver.resolveSync(this.#uri, false, undefined) as T | undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * @inheritdoc\n */\n get isAvailable(): boolean {\n return this.#target !== undefined || this.#resolver !== undefined;\n }\n\n get atom(): Atom.Atom<T | undefined> {\n return RefAtoms.refFamily([this, false]);\n }\n\n /**\n * @inheritdoc\n */\n async load(options?: LoadOptions): Promise<T> {\n const obj = await this.tryLoad(options);\n if (obj == null) {\n throw new Error('Object not found');\n }\n return obj;\n }\n\n /**\n * @inheritdoc\n */\n async tryLoad(options?: LoadOptions): Promise<T | undefined> {\n if (this.#target) {\n // An inlined target never reaches the resolver, so it is checked here instead.\n const hidden = options?.deleted !== 'include' && isTargetDeleted(this.#target);\n return hidden ? undefined : this.#target;\n }\n invariant(this.#resolver, 'Resolver is not set');\n return (await this.#resolver.resolveLegacy(this.#uri, options)) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n onResolved(callback: () => void): () => void {\n return this.#resolved.on(callback);\n }\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n * Clones the reference object.\n */\n noInline(): RefImpl<T> {\n const ref = new RefImpl<T>(this.#uri, undefined);\n ref.#resolver = this.#resolver;\n return ref;\n }\n\n encode(): EncodedReference {\n return {\n '/': this.#uri,\n ...(this.#target ? { target: this.#target } : {}),\n };\n }\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n */\n toJSON(): EncodedReference {\n return this.encode();\n }\n\n toString(): string {\n if (this.#target) {\n return `Ref(${this.#target.toString()})`;\n }\n\n return `Ref(${this.#uri.toString()})`;\n }\n\n [inspectCustom]: CustomInspectFunction = (depth, options, inspect) => {\n return this.toString();\n };\n\n /**\n * Effect Hash trait. Required for MutableHashMap-based caches (e.g., Atom.family)\n * to deduplicate Ref instances that point to the same object.\n * ECHO proxies mint a new RefImpl whenever the object changes,\n * so without this, each one would create a separate cache entry.\n */\n [Hash.symbol](): number {\n return Hash.hash(this.#uri.toString());\n }\n\n /**\n * Effect Equal trait. See {@link Hash.symbol} for rationale. The resolver and target take part, so\n * refs to one object from different clients (same URI, different databases) are separate cache\n * entries rather than all resolving through whichever client's ref was cached first.\n */\n [Equal.symbol](that: Equal.Equal): boolean {\n return (\n that instanceof RefImpl &&\n this.#uri === that.uri &&\n this.#resolver === that.#resolver &&\n this.#target === that.#target\n );\n }\n\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n }\n\n /**\n * @internal\n */\n _setResolver(resolver: RefResolver): void {\n this.#resolver = resolver;\n }\n\n /**\n * @internal\n */\n _getSavedTarget(): T | undefined {\n return this.#target;\n }\n}\n\n/**\n * Internal API for setting the reference resolver.\n */\nexport const setRefResolver = (ref: Ref<any>, resolver: RefResolver) => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n ref._setResolver(resolver);\n};\n\n/**\n * Internal API for getting the saved target on a reference.\n */\nexport const getRefSavedTarget = (ref: Ref<any>): AnyProperties | undefined => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n return ref._getSavedTarget();\n};\n\n// Used to validate reference target type.\nconst refVariance: Ref<any>[typeof RefTypeId] = {\n _T: null as any,\n};\n\nexport const refFromEncodedReference = (encodedReference: EncodedReference, resolver?: RefResolver): Ref<any> => {\n const uri = EncodedReference.toURI(encodedReference);\n const ref = new RefImpl(uri);\n\n // TODO(dmaretskyi): Handle inline target in the encoded reference.\n\n if (resolver) {\n setRefResolver(ref, resolver);\n }\n return ref;\n};\n\nexport class StaticRefResolver implements RefResolver {\n public objects = new Map<EntityId, AnyProperties>();\n public schemas = new Map<URI.URI, Schema.Codec<any, any>>();\n\n addObject(obj: AnyProperties): this {\n this.objects.set(obj.id, obj);\n return this;\n }\n\n addSchema(input: Type.AnyEntity): this {\n const schema = getStaticTypeSchema(input);\n invariant(schema, 'Type entity is missing its source schema');\n const uri = getSchemaURI(schema);\n invariant(uri, 'Schema has no URI');\n this.schemas.set(uri, schema);\n return this;\n }\n\n resolve(uri: URI.URI, _options: { source: RefSource }): RefResolverRequest {\n const obj = this.#lookup(uri);\n return makeSettledRequest(obj ? 'ready' : 'unavailable', obj);\n }\n\n resolveSync(uri: URI.URI, _load: boolean, _onLoad?: () => void): AnyProperties | undefined {\n return this.#lookup(uri);\n }\n\n async resolveLegacy(uri: URI.URI): Promise<AnyProperties | undefined> {\n return this.#lookup(uri);\n }\n\n async resolveSchema(uri: URI.URI): Promise<Schema.Codec<any, any> | undefined> {\n return this.schemas.get(uri);\n }\n\n #lookup(uri: URI.URI): AnyProperties | undefined {\n const echoUri = EID.tryParse(uri);\n const id = echoUri ? EID.getEntityId(echoUri) : undefined;\n if (id == null) {\n return undefined;\n }\n return this.objects.get(id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,IAAa,UAAU,OAAO,IAAI,2BAA2B;AAE7D,IAAa,WAAW,OAAO,IAAI,4BAA4B;;;;;;;AAQ/D,IAAa,cAAc,OAAO,IAAI,6BAA6B;;;;;AAMnE,IAAa,mBAAmB,OAAO,IAAI,kCAAkC;;;;;AAM7E,IAAa,0BAA0B;;;;;;ACpBvC,IAAa,oCAAb,cAAuD,MAAM;CAC3D,YAAY,WAAmB,YAAoB;EACjD,MACE,UAAU,UAAU,kEAAkE,WAAW,aACnG;EACA,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,0BAA0B,SAA6D;CAClG,OAAO,IAAI,kCACT,2BAA2B,OAAO,IAAI,EAAE,IACxC,cAAc,OAAO,IAAI,EAAE,UAC7B;AACF;;;;AAKA,IAAa,6BAA6B,SAA6D;CACrG,OAAO,IAAI,kCACT,2BAA2B,OAAO,IAAI,EAAE,IACxC,qBAAqB,OAAO,IAAI,EAAE,EACpC;AACF;;;;AAKA,IAAa,0BAA0B,WAAsD;CAC3F,OAAO,IAAI,kCAAkC,cAAc,OAAO,KAAK,oBAAoB,OAAO,OAAO;AAC3G;;;;AAKA,IAAa,yBAAyB,W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D;EACzF,OAAO,KAAK,QAAQ,GAAG;CACzB;CAEA,MAAM,cAAc,KAAkD;EACpE,OAAO,KAAK,QAAQ,GAAG;CACzB;CAEA,MAAM,cAAc,KAA2D;EAC7E,OAAO,KAAK,QAAQ,IAAI,GAAG;CAC7B;CAEA,QAAQ,KAAyC;EAC/C,MAAM,UAAU,IAAI,SAAS,GAAG;EAChC,MAAM,KAAK,UAAU,IAAI,YAAY,OAAO,IAAI,KAAA;EAChD,IAAI,MAAM,MACR;EAEF,OAAO,KAAK,QAAQ,IAAI,EAAE;CAC5B;AACF"}
@@ -132,10 +132,10 @@ var GeoLocation;
132
132
  //#endregion
133
133
  //#region src/internal/Format/string.ts
134
134
  /**
135
- * Email address (RFC 5321)
135
+ * Email address (RFC 5321). The local part also allows an apostrophe, which real mail carries (`o'day@corp.com`).
136
136
  * https://datatracker.ietf.org/doc/html/rfc5321#section-4.1.2
137
137
  */
138
- var Email = Schema.String.pipe(Schema.check(Schema.isPattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/u)), FormatAnnotation.set(TypeFormat.Email), Schema.annotate({
138
+ var Email = Schema.String.pipe(Schema.check(Schema.isPattern(/^[a-zA-Z0-9._%+'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/u)), FormatAnnotation.set(TypeFormat.Email), Schema.annotate({
139
139
  title: "Email",
140
140
  description: "Email address"
141
141
  }));
@@ -157,6 +157,10 @@ var Regex = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Regex));
157
157
  * Multi-line text.
158
158
  */
159
159
  var Text = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Text));
160
+ /**
161
+ * Multi-line text written as Markdown; a form renders it in an editor with Markdown decorations.
162
+ */
163
+ var Markdown = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Markdown));
160
164
  var URL_PATTERN = /^(\w+?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/i;
161
165
  /**
162
166
  * https://datatracker.ietf.org/doc/html/rfc3986#section-1.1.3
@@ -206,6 +210,6 @@ var SelectOption = Schema.Struct({
206
210
  color: Schema.String
207
211
  });
208
212
  //#endregion
209
- export { SimpleTime as _, Hostname as a, toSimpleDateTime as b, URL as c, GeoPoint as d, DateOnly as f, SimpleDateTime as g, SimpleDate as h, Formula as i, UUID as l, Duration as m, Format as n, Regex as o, DateTime as p, Email as r, Text as s, SelectOption as t, GeoLocation as u, TimeOnly as v, toSimpleTime as x, toSimpleDate as y };
213
+ export { toSimpleTime as S, SimpleDateTime as _, Hostname as a, toSimpleDate as b, Text as c, GeoLocation as d, GeoPoint as f, SimpleDate as g, Duration as h, Formula as i, URL as l, DateTime as m, Format as n, Markdown as o, DateOnly as p, Email as r, Regex as s, SelectOption as t, UUID as u, SimpleTime as v, toSimpleDateTime as x, TimeOnly as y };
210
214
 
211
215
  //# sourceMappingURL=chunk-select.mjs.map