@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
@@ -9,7 +9,7 @@ import { assertArgument } from '@dxos/invariant';
9
9
 
10
10
  import type * as Annotation from '../../Annotation.ts';
11
11
  import type * as Entity from '../../Entity.ts';
12
- import { snapshotEquals, snapshotForComparison } from '../common/atom-snapshot.ts';
12
+ import { snapshotDeep, snapshotDeepEquals } from '../common/atom-snapshot.ts';
13
13
  import { subscribe } from '../common/proxy/reactive.ts';
14
14
  import { isEntity } from '../Entity/index.ts';
15
15
  import { get as getAnnotation } from './entity-dictionary.ts';
@@ -17,11 +17,12 @@ import { get as getAnnotation } from './entity-dictionary.ts';
17
17
  /**
18
18
  * Atom family for an annotation value on an entity instance.
19
19
  * Mirrors the object-property atom family: re-emits a fresh reference whenever the entity changes
20
- * (so an in-place array mutation is observed) and dedupes primitive values via `!==`.
20
+ * (so an in-place array mutation is observed) and dedupes unchanged content. The snapshot is deep, so a
21
+ * record nested in the value is a new reference too once it changes in place.
21
22
  */
22
23
  const annotationFamily = Atom.family(
23
24
  ([target, annotation]: readonly [Entity.Unknown, Annotation.Annotation<any>]): Atom.Atom<Option.Option<any>> => {
24
- const read = (): Option.Option<any> => Option.map(getAnnotation(target, annotation), snapshotForComparison);
25
+ const read = (): Option.Option<any> => Option.map(getAnnotation(target, annotation), snapshotDeep);
25
26
 
26
27
  return Atom.make<Option.Option<any>>((get) => {
27
28
  let previous = read();
@@ -52,7 +53,7 @@ const annotationPropertyFamily = Atom.family(
52
53
  ]): Atom.Atom<any> => {
53
54
  const read = (): unknown =>
54
55
  getAnnotation(target, annotation).pipe(
55
- Option.map((value) => snapshotForComparison(value[key])),
56
+ Option.map((value) => snapshotDeep(value[key])),
56
57
  Option.getOrUndefined,
57
58
  );
58
59
 
@@ -62,7 +63,7 @@ const annotationPropertyFamily = Atom.family(
62
63
  const unsubscribe = subscribe(target, () => {
63
64
  const next = read();
64
65
  // Content comparison — `read()` snapshots, so identity never matches for arrays/objects.
65
- if (!snapshotEquals(next, previous)) {
66
+ if (!snapshotDeepEquals(next, previous)) {
66
67
  previous = next;
67
68
  get.setSelf(next);
68
69
  }
@@ -74,13 +75,13 @@ const annotationPropertyFamily = Atom.family(
74
75
  },
75
76
  );
76
77
 
77
- /** Equal when both empty, or both present with shallow-equal content (see `snapshotEquals`). */
78
+ /** Equal when both empty, or both present with equal content at every depth. */
78
79
  const sameOption = <T>(a: Option.Option<T>, b: Option.Option<T>): boolean =>
79
- Option.isNone(a) || Option.isNone(b) ? Option.isNone(a) && Option.isNone(b) : snapshotEquals(a.value, b.value);
80
+ Option.isNone(a) || Option.isNone(b) ? Option.isNone(a) && Option.isNone(b) : snapshotDeepEquals(a.value, b.value);
80
81
 
81
82
  /**
82
- * Reactive atom for an annotation value on an entity instance. Emits a shallow snapshot (a fresh
83
- * reference for objects/arrays) so dependent atoms recompute on change. Mirrors {@link makeProperty}.
83
+ * Reactive atom for an annotation value on an entity instance. Emits a deep snapshot (fresh references
84
+ * for objects and arrays at every depth) so dependent atoms recompute on change. Mirrors {@link makeProperty}.
84
85
  */
85
86
  export const makeAtom = <T>(
86
87
  target: Entity.Unknown,
@@ -2,13 +2,15 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import { type ForeignKey } from '@dxos/echo-protocol';
5
6
  import { invariant } from '@dxos/invariant';
6
7
  import { DXN, EID, type SpaceId, URI } from '@dxos/keys';
7
8
  import { assumeType } from '@dxos/util';
8
9
 
10
+ import { defineHiddenProperty } from '../common/proxy/define-hidden-property.ts';
9
11
  import type { AnyEntity } from '../common/types/index.ts';
10
12
  import { MetaId } from '../common/types/model-symbols.ts';
11
- import { type InternalObjectProps, ObjectBranchId, ObjectDatabaseId } from './model.ts';
13
+ import { FeedBlockKeysId, type InternalObjectProps, ObjectBranchId, ObjectDatabaseId } from './model.ts';
12
14
  import { getObjectEchoUri } from './util.ts';
13
15
 
14
16
  /**
@@ -67,6 +69,23 @@ export const getUri = (entity: AnyEntity, options?: GetURIOptions): URI.URI => {
67
69
  return uri;
68
70
  };
69
71
 
72
+ /**
73
+ * The hidden feed block keys a client stamped on a live feed object it wrote; `undefined` when the
74
+ * object's `@meta.keys` describe its latest block.
75
+ */
76
+ export const getFeedBlockKeys = (entity: AnyEntity): readonly ForeignKey[] | undefined => {
77
+ assumeType<InternalObjectProps>(entity);
78
+ return entity[FeedBlockKeysId];
79
+ };
80
+
81
+ /**
82
+ * Sets, or with `undefined` clears, the hidden feed block keys of a live feed object. Not reactive:
83
+ * the keys describe the block the store wrote, not a change of the object.
84
+ */
85
+ export const setFeedBlockKeys = (entity: AnyEntity, keys: readonly ForeignKey[] | undefined): void => {
86
+ defineHiddenProperty(entity, FeedBlockKeysId, keys);
87
+ };
88
+
70
89
  /**
71
90
  * Get the database the entity belongs to.
72
91
  * Accepts both reactive entities and snapshots.
@@ -19,6 +19,7 @@ import {
19
19
  ATTR_SELF_URI_LEGACY,
20
20
  type ATTR_TYPE,
21
21
  EntityKind,
22
+ FeedBlockKeysId,
22
23
  KindId,
23
24
  ObjectBranchId,
24
25
  ObjectDatabaseId,
@@ -41,6 +42,7 @@ export {
41
42
  ATTR_DELETED,
42
43
  ATTR_SELF_URI,
43
44
  ATTR_SELF_URI_LEGACY,
45
+ FeedBlockKeysId,
44
46
  ObjectBranchId,
45
47
  ObjectDatabaseId,
46
48
  ObjectDeletedId,
@@ -62,6 +64,7 @@ export interface InternalObjectProps {
62
64
  readonly [MetaId]?: EntityMeta;
63
65
  [ParentId]?: InternalObjectProps;
64
66
  readonly [ObjectDatabaseId]?: Database.Database;
67
+ readonly [FeedBlockKeysId]?: readonly ForeignKey[];
65
68
  readonly [ObjectBranchId]?: string;
66
69
  readonly [ObjectDeletedId]?: boolean;
67
70
  readonly [ObjectVersionId]?: Version;
@@ -399,9 +399,9 @@ const entityAccessor: FilterRecordAccessor<AnyEntity> = {
399
399
  key: meta.key,
400
400
  version: meta.version,
401
401
  annotations: meta.annotations,
402
- // Lazy: meta tags surface as `Ref`s on a live proxy and only the `tag` arm needs them encoded.
402
+ // Lazy: meta tags surface as entities on a live proxy and only the `tag` arm needs their ids.
403
403
  get tags() {
404
- return meta.tags.map((tag: any) => (typeof tag?.encode === 'function' ? tag.encode() : tag));
404
+ return meta.tags.map((tag) => tag.id);
405
405
  },
406
406
  };
407
407
  },
@@ -9,11 +9,11 @@ import * as SchemaAST from '@dxos/effect/SchemaAST';
9
9
  import { FormatAnnotation, TypeFormat } from './types.ts';
10
10
 
11
11
  /**
12
- * Email address (RFC 5321)
12
+ * Email address (RFC 5321). The local part also allows an apostrophe, which real mail carries (`o'day@corp.com`).
13
13
  * https://datatracker.ietf.org/doc/html/rfc5321#section-4.1.2
14
14
  */
15
15
  export const Email = Schema.String.pipe(
16
- Schema.check(Schema.isPattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/u)),
16
+ Schema.check(Schema.isPattern(/^[a-zA-Z0-9._%+'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/u)),
17
17
  FormatAnnotation.set(TypeFormat.Email),
18
18
  Schema.annotate({
19
19
  title: 'Email',
@@ -46,6 +46,11 @@ export const Regex = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Regex));
46
46
  */
47
47
  export const Text = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Text));
48
48
 
49
+ /**
50
+ * Multi-line text written as Markdown; a form renders it in an editor with Markdown decorations.
51
+ */
52
+ export const Markdown = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Markdown));
53
+
49
54
  const URL_PATTERN = /^(\w+?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/i;
50
55
 
51
56
  /**
@@ -478,7 +478,7 @@ describe('effect-to-json', () => {
478
478
  "$schema": "http://json-schema.org/draft-07/schema#",
479
479
  "description": "Email address",
480
480
  "format": "email",
481
- "pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
481
+ "pattern": "^[a-zA-Z0-9._%+'-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
482
482
  "title": "Email",
483
483
  "type": "string",
484
484
  }
@@ -508,7 +508,7 @@ describe('json-to-effect', () => {
508
508
  title: 'Email',
509
509
  description: 'Email address',
510
510
  // TODO(dmaretskyi): omit pattern.
511
- pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
511
+ pattern: "^[a-zA-Z0-9._%+'-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
512
512
  });
513
513
  });
514
514
  });
@@ -297,15 +297,19 @@ export const makeLabelAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<st
297
297
  return labelAtomFamily(entity);
298
298
  };
299
299
 
300
- const readTags = (entity: Entity.Unknown): readonly Ref.Ref<Tag.Tag>[] => [...getMeta(entity).tags];
300
+ const readTags = (entity: Entity.Unknown): readonly Tag.Tag[] => [...getMeta(entity).tags];
301
301
 
302
- const tagsAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Ref.Ref<Tag.Tag>[]> => {
303
- return Atom.make<readonly Ref.Ref<Tag.Tag>[]>((get) => {
302
+ /** Tags are entities held by identity, so the list is unchanged while every element is the same entity. */
303
+ const sameTags = (next: readonly Tag.Tag[], previous: readonly Tag.Tag[]): boolean =>
304
+ next.length === previous.length && next.every((tag, index) => tag === previous[index]);
305
+
306
+ const tagsAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Tag.Tag[]> => {
307
+ return Atom.make<readonly Tag.Tag[]>((get) => {
304
308
  let previous = readTags(entity);
305
309
 
306
310
  const unsubscribe = subscribe(entity, () => {
307
311
  const next = readTags(entity);
308
- if (!snapshotEquals(next, previous)) {
312
+ if (!sameTags(next, previous)) {
309
313
  previous = next;
310
314
  get.setSelf(next);
311
315
  }
@@ -320,7 +324,7 @@ const tagsAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.A
320
324
  * Create a read-only atom for the meta tags of a reactive ECHO entity.
321
325
  * Re-reads on entity mutation; only propagates when the tag list changes.
322
326
  */
323
- export const makeTagsAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Ref.Ref<Tag.Tag>[]> => {
327
+ export const makeTagsAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Tag.Tag[]> => {
324
328
  assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');
325
329
  return tagsAtomFamily(entity);
326
330
  };
@@ -6,15 +6,17 @@ import * as Schema from 'effect/Schema';
6
6
  import { describe, expect, test } from 'vitest';
7
7
 
8
8
  import { type EntityStructure } from '@dxos/echo-protocol';
9
+ import { invariant } from '@dxos/invariant';
9
10
  import { DXN, EID, EntityId, URI } from '@dxos/keys';
10
11
 
11
12
  import * as Obj from '../../Obj.ts';
12
13
  import * as Relation from '../../Relation.ts';
14
+ import * as Tag from '../../Tag.ts';
13
15
  import { TestSchema } from '../../testing/index.ts';
14
16
  import * as Type from '../../Type.ts';
15
17
  import { getTypename, getTypeURI } from '../Annotation/index.ts';
16
18
  import { getMetaChecked } from '../common/api/index.ts';
17
- import { makeDecodedEntityLive } from '../common/proxy/index.ts';
19
+ import { getProxyTarget, makeDecodedEntityLive } from '../common/proxy/index.ts';
18
20
  import { type AnyEntity, ATTR_TYPE, EntityKind, KindId, TypeId, getSchema } from '../common/types/index.ts';
19
21
  import { ATTR_DELETED, MetaId } from '../common/types/model-symbols.ts';
20
22
  import { RelationSourceId, RelationTargetId, getObjectEchoUri } from '../Entity/index.ts';
@@ -110,15 +112,23 @@ describe('Object JSON serializer', () => {
110
112
  expect(getTypeURI(contactFromJson)).toEqual(Type.getURI(TestSchema.Person));
111
113
  });
112
114
 
113
- test('upgrades bare string tags to encoded references on deserialize', async () => {
115
+ test('resolves tags to Tag objects on deserialize, including legacy bare string tags', async () => {
116
+ const urgent = Tag.make({ label: 'urgent' });
117
+ const legacy = Tag.make({ label: 'legacy' });
114
118
  const expando = Obj.make(TestSchema.Expando, { message: 'hi' });
119
+ Obj.update(expando, (expando) => Obj.addTag(expando, urgent));
115
120
  const json = objectToJSON(expando) as any;
116
- // Simulate data serialized before the tags-as-refs migration: bare id strings.
117
- json['@meta'] = { keys: [], tags: ['echo:/TAGLEGACY'] };
121
+ expect(json['@meta'].tags).toEqual([{ '/': EID.make({ entityId: urgent.id }) }]);
122
+ // Data serialized before tags became references held bare id strings.
123
+ json['@meta'].tags.push(EID.make({ entityId: legacy.id }));
118
124
 
119
- const fromJson = (await objectFromJSON(json)) as any;
120
- // Decodes to a materialized `Ref` (the shared ref codec), not a raw encoded reference.
121
- expect(fromJson[MetaId].tags.map((ref: any) => ref.uri)).toEqual(['echo:/TAGLEGACY']);
125
+ const refResolver = new StaticRefResolver().addObject(urgent).addObject(legacy);
126
+ const fromJson = (await objectFromJSON(json, { refResolver })) as any;
127
+ expect(fromJson[MetaId].tags).toEqual([urgent, legacy]);
128
+
129
+ // Without a resolver a tag cannot be held as an entity, so it is dropped.
130
+ const unresolved = (await objectFromJSON(json)) as any;
131
+ expect(unresolved[MetaId].tags).toEqual([]);
122
132
  });
123
133
 
124
134
  test('deserializes expando without leaking internal json keys', async () => {
@@ -170,6 +180,23 @@ describe('Object JSON serializer', () => {
170
180
  });
171
181
 
172
182
  describe('live decode', () => {
183
+ test('nested records share the prototype of nested records made in memory', async () => {
184
+ const made = Obj.make(TestSchema.Example, { nested: { field: 'a' } });
185
+ const refResolver = new StaticRefResolver().addSchema(TestSchema.Example);
186
+ const live = await decodeLive(objectToJSON(made), { refResolver });
187
+ invariant(Obj.instanceOf(TestSchema.Example)(live));
188
+ invariant(made.nested && live.nested);
189
+ expect(Object.getPrototypeOf(getProxyTarget<object>(live.nested))).toBe(
190
+ Object.getPrototypeOf(getProxyTarget<object>(made.nested)),
191
+ );
192
+
193
+ Obj.update(live, (live) => {
194
+ invariant(live.nested);
195
+ live.nested.field = 'b';
196
+ });
197
+ expect(live.nested.field).toBe('b');
198
+ });
199
+
173
200
  test('decodes as a live proxy, not a plain snapshot', async () => {
174
201
  const contact = Obj.make(TestSchema.Person, { name: 'Alice' });
175
202
  const contactJson = objectToJSON(contact);
@@ -31,7 +31,7 @@ import {
31
31
  setSchema,
32
32
  setType,
33
33
  } from '../common/types/index.ts';
34
- import { ATTR_META, EntityMetaSchema, SCALAR_META_FIELDS } from '../common/types/meta.ts';
34
+ import { ATTR_META, EntityMetaSchema, SCALAR_META_FIELDS, isTagEntity } from '../common/types/meta.ts';
35
35
  import { MetaId } from '../common/types/model-symbols.ts';
36
36
  import {
37
37
  ATTR_DELETED,
@@ -154,9 +154,10 @@ export const objectFromJSON = async (
154
154
  }
155
155
 
156
156
  if (typeof jsonData[ATTR_META] === 'object') {
157
- const meta = await Schema.decodeUnknownPromise(EntityMetaSchema)(normalizeMeta(jsonData[ATTR_META]));
157
+ const { tags: encodedTags, ...encodedMeta } = normalizeMeta(jsonData[ATTR_META]);
158
+ const meta = await Schema.decodeUnknownPromise(EntityMetaSchema)({ ...encodedMeta, tags: [] });
158
159
  invariant(Array.isArray(meta.keys));
159
- defineHiddenProperty(obj, MetaId, meta);
160
+ defineHiddenProperty(obj, MetaId, { ...meta, tags: await resolveTags(encodedTags, refResolver) });
160
161
  } else {
161
162
  defineHiddenProperty(obj, MetaId, {
162
163
  keys: [],
@@ -197,6 +198,20 @@ export const objectFromJSON = async (
197
198
  return obj;
198
199
  };
199
200
 
201
+ /**
202
+ * Resolves the encoded tag references of a serialized meta to {@link Tag} entities. A tag the
203
+ * resolver cannot supply is dropped, as an unresolved parent is: `meta.tags` holds entities only.
204
+ */
205
+ const resolveTags = async (encodedTags: readonly unknown[], refResolver: RefResolver | undefined) => {
206
+ if (refResolver == null || encodedTags.length === 0) {
207
+ return [];
208
+ }
209
+ const resolved = await Promise.all(
210
+ encodedTags.map((tag) => (isEncodedReference(tag) ? refResolver.resolveLegacy(URI.make(tag['/'])) : undefined)),
211
+ );
212
+ return resolved.filter(isTagEntity);
213
+ };
214
+
200
215
  /**
201
216
  * Backfills required meta fields and upgrades legacy `tags` (bare URI strings) to encoded references
202
217
  * so serialized data produced before the tags-as-refs migration still decodes.
@@ -69,7 +69,7 @@ export const prettyFilter = (filter: QueryAST.Filter): string => {
69
69
  case 'timestamp':
70
70
  return `Filter.${filter.field}.${filter.operator}(${filter.value})`;
71
71
  case 'feed-cursor':
72
- return `Filter.feedCursor(${JSON.stringify({ begin: filter.begin, end: filter.end })})`;
72
+ return `Filter.feedCursor(${JSON.stringify({ begin: filter.begin, end: filter.end, positions: filter.positions })})`;
73
73
  case 'child-of':
74
74
  return `Filter.childOf([${filter.parents.map((p) => JSON.stringify(p)).join(', ')}], { transitive: ${filter.transitive} })`;
75
75
  case 'mnemonic':
@@ -167,7 +167,8 @@ export const prettyQuery = (query: QueryAST.Query): string => {
167
167
  : `{ space: ${JSON.stringify(scope.spaceId)} }`;
168
168
  }
169
169
  if (scope._tag === 'feed') {
170
- return `{ feed: ${JSON.stringify(String(scope.feedUri))} }`;
170
+ const branches = scope.branches !== undefined ? `, branches: ${JSON.stringify(scope.branches)}` : '';
171
+ return `{ feed: ${JSON.stringify(String(scope.feedUri))}${branches} }`;
171
172
  }
172
173
  return `{ registry: ${JSON.stringify(scope.location)} }`;
173
174
  });
@@ -2,15 +2,17 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import * as Equal from 'effect/Equal';
6
+ import * as Hash from 'effect/Hash';
5
7
  import * as Schema from 'effect/Schema';
6
8
  import { describe, expect, test } from 'vitest';
7
9
 
8
- import { DXN, EID, EntityId } from '@dxos/keys';
10
+ import { DXN, EID, EntityId, SpaceId } from '@dxos/keys';
9
11
 
10
12
  import * as Type from '../../Type.ts';
11
13
  import { EchoObjectSchema, getObjectEchoUri } from '../Entity/index.ts';
12
14
  import { createObject } from '../Obj/index.ts';
13
- import { Ref, getReferenceAst } from './ref.ts';
15
+ import { Ref, StaticRefResolver, getReferenceAst, setRefResolver } from './ref.ts';
14
16
 
15
17
  const Task = Schema.Struct({
16
18
  title: Schema.optional(Schema.String),
@@ -27,6 +29,22 @@ const Contact = Schema.Struct({
27
29
  type Contact = Type.InstanceType<typeof Contact>;
28
30
 
29
31
  describe('Ref', () => {
32
+ test('refs to one object are equal only within one resolver', ({ expect }) => {
33
+ const { uri } = Ref.make(createObject(Task, { title: 'Shared' }));
34
+ const [first, second] = [new StaticRefResolver(), new StaticRefResolver()];
35
+ const make = (resolver: StaticRefResolver) => {
36
+ const ref = Ref.fromURI(uri);
37
+ setRefResolver(ref, resolver);
38
+ return ref;
39
+ };
40
+
41
+ // One database mints a fresh ref per change; those must share a cache entry.
42
+ expect(Equal.equals(make(first), make(first))).toBe(true);
43
+ // Two clients in one page hold the same object; each must resolve through its own database.
44
+ expect(Equal.equals(make(first), make(second))).toBe(false);
45
+ expect(Hash.hash(make(first))).toBe(Hash.hash(make(second)));
46
+ });
47
+
30
48
  test('Schema is', () => {
31
49
  Ref(Contact).pipe(Schema.is)(Ref.fromURI(EID.make({ entityId: EntityId.random() })));
32
50
  });
@@ -89,6 +107,13 @@ describe('Ref', () => {
89
107
  expect(contact.tasks[0].uri.toString()).toEqual(`echo:/${id}`);
90
108
  });
91
109
 
110
+ test('decode rejects a malformed echo URI', ({ expect }) => {
111
+ const uri = `echo:///${EID.make({ spaceId: SpaceId.random(), entityId: EntityId.random() })}`;
112
+ const decode = Schema.decodeUnknownSync(Schema.Struct({ task: Ref(Task) }));
113
+
114
+ expect(() => decode({ task: { '/': uri } })).toThrow(`Invalid echo URI: ${uri}`);
115
+ });
116
+
92
117
  // A rejection message is what a remote caller gets back: `InvalidOperationInput` interpolates it
93
118
  // verbatim, and the caller cannot see its own payload in our logs.
94
119
  describe('rejection diagnostics', () => {
@@ -438,6 +438,13 @@ export const createEchoReferenceSchema = (
438
438
  }
439
439
 
440
440
  const uri = EncodedReference.toURI(candidate);
441
+ // Rejected here so a malformed URI from a caller (e.g. a full URI wrapped in `echo:///`)
442
+ // never reaches the document, where it would resolve to nothing.
443
+ if (EID.isEID(uri) && EID.tryParse(uri) === undefined) {
444
+ return yield* Effect.fail(
445
+ new SchemaIssue.InvalidValue({ message: `Invalid echo URI: ${uri}` }, candidate),
446
+ );
447
+ }
441
448
  return Option.isSome(dbService) ? dbService.value.db.makeRef(uri) : Ref.fromURI(uri);
442
449
  }),
443
450
  encode: (value) => {
@@ -717,9 +724,18 @@ export class RefImpl<T> implements Ref<T> {
717
724
  return Hash.hash(this.#uri.toString());
718
725
  }
719
726
 
720
- /** Effect Equal trait. See {@link Hash.symbol} for rationale. */
727
+ /**
728
+ * Effect Equal trait. See {@link Hash.symbol} for rationale. The resolver and target take part, so
729
+ * refs to one object from different clients (same URI, different databases) are separate cache
730
+ * entries rather than all resolving through whichever client's ref was cached first.
731
+ */
721
732
  [Equal.symbol](that: Equal.Equal): boolean {
722
- return that instanceof RefImpl && this.#uri === that.uri;
733
+ return (
734
+ that instanceof RefImpl &&
735
+ this.#uri === that.uri &&
736
+ this.#resolver === that.#resolver &&
737
+ this.#target === that.#target
738
+ );
723
739
  }
724
740
 
725
741
  pipe() {
@@ -5,7 +5,7 @@
5
5
  import { EID, type SpaceId, type URI } from '@dxos/keys';
6
6
 
7
7
  import { EntityKind } from '../common/types/entity.ts';
8
- import { RelationSourceDXNId, RelationTargetDXNId } from '../common/types/model-symbols.ts';
8
+ import { MetaId, RelationSourceDXNId, RelationTargetDXNId } from '../common/types/model-symbols.ts';
9
9
  import { ParentId, TypeId } from '../common/types/typename.ts';
10
10
  import { getObjectEchoUri } from '../Entity/util.ts';
11
11
 
@@ -24,11 +24,13 @@ export interface StrongDepRefs {
24
24
  target?: URI.URI;
25
25
  /** Parent reference URI. */
26
26
  parent?: URI.URI;
27
+ /** Reference URIs of the {@link Tag}s in `meta.tags`. */
28
+ tags?: readonly URI.URI[];
27
29
  }
28
30
 
29
31
  /**
30
32
  * Direct strong-dependency URIs of an entity: the schema (only when stored as an object), the
31
- * relation source/target, and the parent. Returns URIs (cross-space `echo:` EIDs and queue-item
33
+ * relation source/target, the parent, and the tags. Returns URIs (cross-space `echo:` EIDs and queue-item
32
34
  * EIDs included); a persisted schema is an `echo:` URI, a static/registry type is a `dxn:` URI.
33
35
  *
34
36
  * A static/registry type (`dxn:`) is intentionally NOT a strong dep: it is always synchronously
@@ -55,6 +57,10 @@ export const getStrongDependencyUris = (refs: StrongDepRefs, owningSpaceId?: Spa
55
57
  res.push(qualifyToSpace(refs.parent, owningSpaceId));
56
58
  }
57
59
 
60
+ for (const tag of refs.tags ?? []) {
61
+ res.push(qualifyToSpace(tag, owningSpaceId));
62
+ }
63
+
58
64
  return res;
59
65
  };
60
66
 
@@ -75,6 +81,18 @@ const qualifyToSpace = (uri: URI.URI, owningSpaceId: SpaceId | undefined): URI.U
75
81
  return entityId != null ? EID.make({ spaceId: owningSpaceId, entityId }) : uri;
76
82
  };
77
83
 
84
+ /** URIs of the tags a decoded entity's meta holds, which are resolved entities like its parent. */
85
+ const getTagUris = (meta: unknown): URI.URI[] => {
86
+ const tags = meta != null && typeof meta === 'object' ? Reflect.get(meta, 'tags') : undefined;
87
+ if (!Array.isArray(tags)) {
88
+ return [];
89
+ }
90
+ return tags.flatMap((tag) => {
91
+ const uri = getObjectEchoUri(tag);
92
+ return uri != null ? [uri] : [];
93
+ });
94
+ };
95
+
78
96
  /**
79
97
  * Direct strong-dependency URIs of a live (decoded) entity — a queue item, cross-space proxy, or
80
98
  * snapshot. Reads the reference URIs off the entity's hidden model symbols. ECHO db cores compute
@@ -101,6 +119,7 @@ export const getStrongDependencies = (entity: unknown): URI.URI[] => {
101
119
  target: props[RelationTargetDXNId] as URI.URI | undefined,
102
120
  // A parent is held as the resolved entity; derive its absolute URI for the dependency edge.
103
121
  parent: parent != null ? getObjectEchoUri(parent) : undefined,
122
+ tags: getTagUris(props[MetaId]),
104
123
  },
105
124
  owningSpaceId,
106
125
  );
@@ -7,7 +7,6 @@ import { assertArgument, invariant } from '@dxos/invariant';
7
7
  import type { DeepReadonly } from '@dxos/util';
8
8
 
9
9
  import type * as Tag from '../../../Tag.ts';
10
- import type { Ref } from '../../Ref/ref.ts';
11
10
  import { type Mutable } from '../proxy/index.ts';
12
11
  import { type AnyProperties } from '../types/index.ts';
13
12
  import { type EntityMeta, getMeta as getMeta$ } from '../types/meta.ts';
@@ -64,25 +63,25 @@ export const deleteKeys = (entity: Mutable<AnyProperties>, source: string) => {
64
63
  };
65
64
 
66
65
  /**
67
- * Add a tag (a reference to a {@link Tag} object) to the entity. Idempotent.
66
+ * Add a {@link Tag} to the entity. Idempotent.
68
67
  * Must be called within an Obj.update or Relation.update callback.
69
68
  */
70
- export const addTag = (entity: Mutable<AnyProperties>, tag: Ref<Tag.Tag>) => {
69
+ export const addTag = (entity: Mutable<AnyProperties>, tag: Tag.Tag) => {
71
70
  const meta = getMetaChecked(entity);
72
- // Two refs to the same target are not `===`; dedupe by URI.
73
- if (!meta.tags.some((existing) => existing.uri === tag.uri)) {
71
+ // Deduped by id: a snapshot or a mutable view of the same tag is not `===` to the live entity.
72
+ if (!meta.tags.some((existing) => existing.id === tag.id)) {
74
73
  meta.tags.push(tag);
75
74
  }
76
75
  };
77
76
 
78
77
  /**
79
- * Remove a tag (a reference to a {@link Tag} object) from the entity. No-op when not present.
78
+ * Remove a {@link Tag} from the entity. No-op when not present.
80
79
  * Must be called within an Obj.update or Relation.update callback.
81
80
  */
82
- export const removeTag = (entity: Mutable<AnyProperties>, tag: Ref<Tag.Tag>) => {
81
+ export const removeTag = (entity: Mutable<AnyProperties>, tag: Tag.Tag) => {
83
82
  const meta = getMetaChecked(entity);
84
83
  for (let i = 0; i < meta.tags.length; i++) {
85
- if (meta.tags[i].uri === tag.uri) {
84
+ if (meta.tags[i].id === tag.id) {
86
85
  meta.tags.splice(i, 1);
87
86
  i--;
88
87
  }
@@ -38,6 +38,30 @@ export const snapshotForComparison = <V>(value: V): V => {
38
38
  return value;
39
39
  };
40
40
 
41
+ /**
42
+ * {@link snapshotForComparison} at every depth, for a value whose readers hold on to its nested records and arrays: a
43
+ * shallow copy would hand them the same nested reference after an in-place change below the top level.
44
+ */
45
+ export const snapshotDeep = <V>(value: V): V => {
46
+ if (Array.isArray(value)) {
47
+ return value.map(snapshotDeep) as V;
48
+ }
49
+ if (isRefLike(value)) {
50
+ return value;
51
+ }
52
+ // Bytes and dates keep their class: the record branch below would turn them into plain objects.
53
+ if (value instanceof Uint8Array) {
54
+ return new Uint8Array(value) as V;
55
+ }
56
+ if (value instanceof Date) {
57
+ return new Date(value.getTime()) as V;
58
+ }
59
+ if (value !== null && typeof value === 'object') {
60
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, snapshotDeep(entry)])) as V;
61
+ }
62
+ return value;
63
+ };
64
+
41
65
  // Refs compare by URI: `RefImpl` mints a fresh wrapper on every property read, so `Object.is` never
42
66
  // matches two reads of the same ref. The inlined target is part of the ref's encoded value
43
67
  // (`{'/': uri, target}` for an object not yet in the database), so `Ref.make(target)` and a
@@ -61,6 +85,43 @@ const valueEquals = (a: unknown, b: unknown): boolean => {
61
85
  return Object.is(a, b);
62
86
  };
63
87
 
88
+ /**
89
+ * Structural equality between two {@link snapshotDeep} results, which share no references below the top level, so
90
+ * records and arrays compare by content at every depth. Refs compare as in {@link snapshotEquals}.
91
+ */
92
+ export const snapshotDeepEquals = (a: unknown, b: unknown): boolean => {
93
+ if (isRefLike(a) || isRefLike(b)) {
94
+ return valueEquals(a, b);
95
+ }
96
+ if (a instanceof Date || b instanceof Date) {
97
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
98
+ }
99
+ if (a instanceof Uint8Array || b instanceof Uint8Array) {
100
+ return (
101
+ a instanceof Uint8Array && b instanceof Uint8Array && a.length === b.length && a.every((byte, i) => byte === b[i])
102
+ );
103
+ }
104
+ if (Array.isArray(a) || Array.isArray(b)) {
105
+ return (
106
+ Array.isArray(a) &&
107
+ Array.isArray(b) &&
108
+ a.length === b.length &&
109
+ a.every((item, index) => snapshotDeepEquals(item, b[index]))
110
+ );
111
+ }
112
+ if (isRecord(a) || isRecord(b)) {
113
+ if (!isRecord(a) || !isRecord(b)) {
114
+ return false;
115
+ }
116
+ const keys = Object.keys(a);
117
+ return (
118
+ keys.length === Object.keys(b).length &&
119
+ keys.every((key) => Object.hasOwn(b, key) && snapshotDeepEquals(a[key], b[key]))
120
+ );
121
+ }
122
+ return Object.is(a, b);
123
+ };
124
+
64
125
  /**
65
126
  * Change-detection equality between a live value and a previously emitted snapshot. Identity cannot
66
127
  * serve, because `snapshotForComparison` mints a fresh reference on every read, so unchanged content
@@ -59,6 +59,11 @@ export const isInChangeContext = (key: object): boolean => {
59
59
  return currentChangeContext === key;
60
60
  };
61
61
 
62
+ /**
63
+ * Whether any object is in a change context; only one can be at a time, so a change entered now would end it.
64
+ */
65
+ export const isAnyChangeContextActive = (): boolean => currentChangeContext !== null;
66
+
62
67
  /**
63
68
  * Queue a notification for the given key to be fired when the change context exits.
64
69
  *