@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 +1 @@
1
- {"version":3,"file":"chunk-Entity.mjs","names":["internal.KindId","internal.SnapshotKindId","internal.EntityKind","internal.EntityKindSchema","internal.isEntity","internal.isInstanceOf","internal.getEntityKind","internal.MetaId","internal.getEntityKindBrand","Type.getURI","internal.getUri","Type.Type","internal.getTypeURI","internal.getType","Type.getTypename","internal.getTypename","internal.getDatabase","internal.getMetaChecked","internal.getKeys","internal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.getIcon","internal.objectToJSON","internal.subscribe","internal.addTag","internal.removeTag","objInternal.makeEntity","objInternal.makeLabelAtom","objInternal.makeTagsAtom","internal.getLabelProperty"],"sources":["../../src/Entity.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport type { EntityId, URI } from '@dxos/keys';\n\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport type * as Ref from './Ref.ts';\nimport type * as Relation from './Relation.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\n// Re-export KindId and SnapshotKindId from internal.\nexport const KindId = internal.KindId;\nexport type KindId = typeof internal.KindId;\nexport const SnapshotKindId = internal.SnapshotKindId;\nexport type SnapshotKindId = typeof internal.SnapshotKindId;\n\n// NOTE: Relation does not extend Obj so that, for example, we can prevent Relations from being used as source and target objects.\n// However, we generally refer to Obj and Relation instances as \"objects\",\n// and many API methods accept both Obj.Unknown and Relation.Unknown (i.e., Entity.Unknown) instances.\n\nexport const Kind = internal.EntityKind;\nexport type Kind = internal.EntityKind;\nexport const KindSchema = internal.EntityKindSchema;\n\n/**\n * Assigns a kind to an Object or Relation instance.\n * NOTE: Needed to make `isRelation` and `isObject` checks work.\n */\nexport interface OfKind<K extends Kind> {\n readonly [KindId]: K;\n readonly id: EntityId;\n}\n\n/**\n * Assigns a snapshot kind to an Object or Relation snapshot.\n */\nexport interface SnapshotOfKind<K extends Kind> {\n readonly [SnapshotKindId]: K;\n readonly id: EntityId;\n}\n\n/**\n * Obj or Relation with a specific set of properties.\n */\nexport type Entity<Props> = OfKind<Kind> & Props;\n\n/**\n * Unknown Obj or Relation (reactive).\n */\nexport interface Unknown extends OfKind<Kind> {}\n\n/**\n * Effect Schema for any ECHO entity (object or relation).\n *\n * Kind-agnostic counterpart to `Obj.Unknown` / `Relation.Unknown` — validates\n * the structural shape (id + properties) without constraining `[KindId]`. Used\n * in operation input schemas that accept any entity flavour (e.g.\n * `Schema.Array(Entity.Unknown)`).\n *\n * The cast bridges the runtime structural schema to the branded `Unknown` type:\n * `[KindId]` is a symbol brand that can't be expressed in a runtime `Struct`,\n * so the entity guarantee is carried at the type level only (same approach as\n * `Obj.Unknown` / `Relation.Unknown`). Unlike those, this is kind-agnostic so it\n * isn't an `UnknownTypeSchema<_, K>` (there's no single `K`) and carries no\n * `TypeAnnotation`.\n */\nexport const Unknown: Schema.Codec<Unknown> = Schema.StructWithRest(Schema.Struct({ id: Schema.String }), [\n Schema.Record(Schema.String, Schema.Unknown),\n]) as unknown as Schema.Codec<Unknown>;\n\n/**\n * Snapshot of an Obj or Relation.\n * Branded with SnapshotKindId instead of KindId.\n */\nexport interface Snapshot extends SnapshotOfKind<Kind> {}\n\n/**\n * Object with arbitrary properties.\n *\n * NOTE: Due to how typescript works, this type is not assignable to a specific schema type.\n * In that case, use `Obj.instanceOf` to check if an object is of a specific type.\n *\n * This type is very permissive and allows accessing any property on the object.\n * We should move to Obj.Unknown that is not permissive and requires explicit instanceof checks..\n */\nexport interface Any extends OfKind<Kind> {\n [key: string]: unknown;\n}\n\n/**\n * Returns all properties of an object or relation except for the id and kind.\n */\nexport type Properties<T> = Omit<T, 'id' | KindId | Relation.Source | Relation.Target>;\n\n/**\n * Check if a value is an ECHO entity (object or relation).\n * Returns `false` for snapshots.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isEntity: (value: unknown) => value is Unknown = internal.isEntity;\n\n/**\n * Test if a value is an instance of a given object or relation type.\n *\n * Kind-agnostic counterpart to `Obj.instanceOf` / `Relation.instanceOf` —\n * use this when the caller's input type is `Type.AnyObj | Type.AnyRelation`.\n *\n * @example\n * ```ts\n * // Caller doesn't know whether `type` is object- or relation-kind.\n * const matches = <T extends Type.AnyObj | Type.AnyRelation>(type: T, value: unknown) =>\n * Entity.instanceOf(type, value);\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n <S extends Type.AnyEntity>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyEntity>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyEntity, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Check if a value is an ECHO entity snapshot.\n * Returns `false` for entities.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (value: unknown): value is Snapshot => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return (value as any)[SnapshotKindId] !== undefined;\n};\n\n// TODO(dmaretskyi): Type introspection -- move to kind.\n/**\n * Get the entity kind declared by a schema type annotation.\n *\n * @performance O(1) schema annotation read.\n */\nexport const getKind = internal.getEntityKind;\n\n/**\n * Property that accesses metadata for an entity.\n */\nexport const Meta: unique symbol = internal.MetaId as any;\n\n/**\n * Property that accesses metadata for an entity.\n */\nexport type Meta = typeof Meta;\n\n//\n// Entity-level functions that work on any entity (object or relation).\n// Use these when you don't know or care about the specific entity kind.\n// For kind-specific functions, use Obj.* or Relation.*.\n//\n\n/**\n * JSON representation of an entity.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Whether the entity is a type-kind entity (a `Type.Type` produced by\n * `Type.makeObject` / `Type.makeRelation`, or a persisted schema). Type entities\n * carry their identity (typename/version) on themselves rather than referencing a\n * separate type, so the accessors below route them through the `Type.*` module.\n */\nconst isTypeEntity = (entity: unknown): boolean => internal.getEntityKindBrand(entity) === internal.EntityKind.Type;\n\n/**\n * Any value the read accessors operate on: a reactive entity or a snapshot.\n * Type entities (`Type.AnyEntity`) are also accepted — they're first-class\n * entities, and `Unknown`'s kind-agnostic brand already subsumes them.\n */\nexport type AnyInput = Unknown | Snapshot;\n\n/**\n * Get the canonical URI of an entity (object, relation, or type). Returns `URI.URI` —\n * an `EID` for object/relation instances and persisted types, or a typename\n * `DXN` for static type entities; narrow with `EID.parse(uri)` or\n * `DXN.tryMake(uri)` at the point of use.\n *\n * @param options.prefer - Controls the URI form (see {@link internal.GetURIOptions}).\n *\n * @performance O(1); returns the stored URI, constructing (and allocating) one only when `options.prefer` asks for\n * another form.\n */\nexport const getURI = (entity: AnyInput, options?: internal.GetURIOptions): URI.URI =>\n isTypeEntity(entity) ? Type.getURI(entity as Type.AnyEntity, options) : internal.getUri(entity as Unknown, options);\n\n/**\n * Get the DXN of an entity's type. For object/relation instances this is the URI\n * of the type they were created from; for a type entity it is the URI of the\n * meta-type ({@link Type.Type}, `dxn:org.dxos.type.schema:0.1.0`).\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI = (entity: AnyInput): URI.URI | undefined =>\n isTypeEntity(entity) ? Type.getURI(Type.Type) : internal.getTypeURI(entity as Unknown);\n\n/**\n * Get the type entity (`Type.AnyEntity`) the instance was created from.\n *\n * Returns `undefined` when the entity's type isn't registered in this runtime\n * (e.g. a freshly deserialized snapshot whose type entity hasn't been wired\n * up yet, or an entity loaded from storage before its schema is known). To\n * get the Effect Schema from the returned entity, use `Type.getSchema(...)`.\n *\n * For a type entity, returns the meta-type {@link Type.Type} (a type entity's\n * type is \"Type\").\n *\n * @performance O(1) read of the type back-reference.\n */\nexport const getType = (entity: AnyInput): Type.AnyEntity | undefined =>\n isTypeEntity(entity) ? Type.Type : (internal.getType(entity) as Type.AnyEntity | undefined);\n\n/**\n * Get the typename of an entity's type. For object/relation instances this is the\n * typename of the type they were created from; for a type entity it is the type's\n * own typename (e.g. `com.example.type.person`).\n *\n * @performance O(1); reads the schema type annotation (database objects resolve the schema by registry URI lookup).\n */\nexport const getTypename = (entity: AnyInput): string | undefined =>\n isTypeEntity(entity) ? Type.getTypename(entity as Type.AnyEntity) : internal.getTypename(entity as Unknown);\n\n/**\n * Get the database an entity belongs to.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Unknown | Snapshot): any | undefined => internal.getDatabase(entity);\n\n/**\n * Get the metadata for an entity.\n * Returns mutable meta when passed a mutable entity (inside change callback).\n * Returns read-only meta when passed a regular entity or snapshot.\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\n// TODO(wittjosiah): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\nexport function getMeta(entity: Mutable<Unknown>): internal.Meta;\nexport function getMeta(entity: Unknown | Snapshot): internal.ReadonlyMeta;\nexport function getMeta(entity: Unknown | Snapshot | Mutable<Unknown>): internal.Meta | internal.ReadonlyMeta {\n return internal.getMetaChecked(entity);\n}\n\n/**\n * Get foreign keys for an entity from the specified source.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys = (entity: Unknown | Snapshot, source: string): ForeignKey[] => internal.getKeys(entity, source);\n\n/**\n * Check if an entity is deleted.\n *\n * @performance O(1) slot read.\n */\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => internal.isDeleted(entity);\n\n/**\n * Get the label of an entity.\n *\n * @param options.fallback `'typename'` returns the entity's typename when no\n * label is set (e.g. `org.dxos.type.table`).\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: Unknown | Snapshot, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * Set the label of an entity.\n * Must be called within an `Entity.update` / `Obj.update` / `Relation.update` callback.\n *\n * @performance O(1); writes the first `LabelAnnotation` accessor, a no-op without a schema.\n */\nexport const setLabel = (entity: Mutable<Unknown>, label: string): void => internal.setLabel(entity, label);\n\n/**\n * Get the description of an entity.\n *\n * @performance O(1); reads the field named by the schema `DescriptionAnnotation`.\n */\nexport const getDescription = (entity: Unknown | Snapshot): string | undefined => internal.getDescription(entity);\n\n/**\n * Get the icon annotation for an entity (object or relation), resolved via its type-level\n * `IconAnnotation`. Returns the full `{ icon, hue }` annotation so callers can use both\n * the phosphor icon name and the suggested colour.\n *\n * @performance O(1) schema annotation lookup, but decodes the annotation value on every call (not cached).\n */\nexport const getIcon = (entity: Unknown | Snapshot): internal.IconAnnotation | undefined => internal.getIcon(entity);\n\n/**\n * Convert an entity to its JSON representation.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\nexport const toJSON = (entity: Unknown | Snapshot): JSON => internal.objectToJSON(entity);\n\n/**\n * Subscribe to changes on an entity (object or relation).\n * @returns Unsubscribe function.\n *\n * @performance O(1) listener registration; the callback runs synchronously after every committed change.\n */\nexport const subscribe = (entity: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(entity, callback);\n};\n\n//\n// Change\n//\n\n/**\n * Used to provide a mutable view of an entity within `Entity.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an entity (object or relation) within a change context.\n *\n * Entities are read-only by default. Mutations are batched and notifications fire\n * when the callback completes. Direct mutations outside of `Entity.update` will throw\n * at runtime.\n *\n * @param entity - The echo entity (object or relation) to mutate.\n * @param callback - Receives a mutable view of the entity. All mutations must occur here.\n *\n * @example\n * ```typescript\n * // Mutate within Entity.update\n * Entity.update(entity, (obj) => {\n * obj.name = 'Updated';\n * obj.count = 42;\n * });\n *\n * // Direct mutation throws\n * entity.name = 'Bob'; // Error: Cannot modify outside Entity.update()\n * ```\n *\n * Note: For type-specific operations, prefer `Obj.update` or `Relation.update`.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = <T extends Unknown>(entity: T, callback: internal.ChangeCallback<T>): void => {\n internal.change(entity, callback);\n};\n\n/**\n * Add a tag to an entity.\n * Must be called within an `Entity.update`, `Obj.update`, or `Relation.update` callback.\n *\n * @performance O(t) in the tag count; dedupes by ref URI before appending.\n */\nexport const addTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.addTag(entity, tag);\n\n/**\n * Remove a tag from an entity.\n * Must be called within an `Entity.update`, `Obj.update`, or `Relation.update` callback.\n *\n * @performance O(t) in the tag count.\n */\nexport const removeTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.removeTag(entity, tag);\n\n//\n// Atoms\n//\n\n/**\n * Create a reactive snapshot atom for an entity (object or relation).\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeEntity;\n/**\n * Create a reactive atom for the label of an entity.\n *\n * @performance O(1) memoized atom-family lookup; recomputes the label on every entity change, emitting only on\n * difference.\n */\nexport const labelAtom = objInternal.makeLabelAtom;\n/**\n * Create a reactive atom for the meta tags of an entity.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the tags on every entity change, emitting only when the\n * tag list changes.\n */\nexport const tagsAtom = objInternal.makeTagsAtom;\n/**\n * Get the name of the property that holds the label of an entity.\n *\n * @performance O(1); reads the first accessor of the schema `LabelAnnotation`.\n */\nexport const labelProperty = internal.getLabelProperty;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,SAASA;AAEtB,IAAa,iBAAiBC;AAO9B,IAAa,OAAOC;AAEpB,IAAa,aAAaC;;;;;;;;;;;;;;;;AA4C1B,IAAa,UAAiC,OAAO,eAAe,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC,GAAG,CACxG,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAC7C,CAAC;;;;;;;AAgCD,IAAa,WAAiDC;;;;;;;;;;;;;;;;AAiB9D,IAAa,eAGP,GAAG,SAAoD;CAC3D,IAAI,KAAK,WAAW,GAClB,QAAQ,WAAoBC,aAAsB,KAAK,IAAI,MAAM;CAEnE,OAAOA,aAAsB,KAAK,IAAI,KAAK,EAAE;AAC/C;;;;;;;AAQA,IAAa,cAAc,UAAsC;CAC/D,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,OAAQ,MAAc,oBAAoB,KAAA;AAC5C;;;;;;AAQA,IAAa,UAAUC;;;;AAKvB,IAAa,OAAsBC;;;;;;;AAwBnC,IAAM,gBAAgB,WAA6BC,mBAA4B,MAAM,MAAA,WAA0B;;;;;;;;;;;;AAoB/G,IAAa,UAAU,QAAkB,YACvC,aAAa,MAAM,IAAIC,SAAY,QAA0B,OAAO,IAAIC,OAAgB,QAAmB,OAAO;;;;;;;;AASpH,IAAa,cAAc,WACzB,aAAa,MAAM,IAAID,SAAYE,IAAS,IAAIC,aAAoB,MAAiB;;;;;;;;;;;;;;AAevF,IAAa,WAAW,WACtB,aAAa,MAAM,IAAID,OAAaE,UAAiB,MAAM;;;;;;;;AAS7D,IAAa,eAAe,WAC1B,aAAa,MAAM,IAAIC,cAAiB,MAAwB,IAAIC,cAAqB,MAAiB;;;;;;AAO5G,IAAa,eAAe,WAAgDC,cAAqB,MAAM;AAYvG,SAAgB,QAAQ,QAAsF;CAC5G,OAAOC,eAAwB,MAAM;AACvC;;;;;;AAOA,IAAa,WAAW,QAA4B,WAAiCC,UAAiB,QAAQ,MAAM;;;;;;AAOpH,IAAa,aAAa,WAAwCC,YAAmB,MAAM;;;;;;;;;AAU3F,IAAa,YAAY,QAA4B,YACnDC,WAAkB,QAAQ,OAAO;;;;;;;AAQnC,IAAa,YAAY,QAA0B,UAAwBC,WAAkB,QAAQ,KAAK;;;;;;AAO1G,IAAa,kBAAkB,WAAmDC,iBAAwB,MAAM;;;;;;;;AAShH,IAAa,WAAW,WAAoEC,UAAiB,MAAM;;;;;;AAOnH,IAAa,UAAU,WAAqCC,aAAsB,MAAM;;;;;;;AAQxF,IAAa,aAAa,QAAiB,aAAuC;CAChF,OAAOC,YAAmB,QAAQ,QAAQ;AAC5C;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,UAA6B,QAAW,aAA+C;CAClG,OAAgB,QAAQ,QAAQ;AAClC;;;;;;;AAQA,IAAa,UAAU,QAA0B,QAAgCC,SAAgB,QAAQ,GAAG;;;;;;;AAQ5G,IAAa,aAAa,QAA0B,QAAgCC,YAAmB,QAAQ,GAAG;;;;;;AAWlH,IAAa,OAAOC;;;;;;;AAOpB,IAAa,YAAYC;;;;;;;AAOzB,IAAa,WAAWC;;;;;;AAMxB,IAAa,gBAAgBC"}
1
+ {"version":3,"file":"chunk-Entity.mjs","names":["internal.KindId","internal.SnapshotKindId","internal.EntityKind","internal.EntityKindSchema","internal.isEntity","internal.isInstanceOf","internal.getEntityKind","internal.MetaId","internal.getEntityKindBrand","Type.getURI","internal.getUri","Type.Type","internal.getTypeURI","internal.getType","Type.getTypename","internal.getTypename","internal.getDatabase","internal.getMetaChecked","internal.getKeys","internal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.getIcon","internal.objectToJSON","internal.subscribe","internal.addTag","internal.removeTag","objInternal.makeEntity","objInternal.makeLabelAtom","objInternal.makeTagsAtom","internal.getLabelProperty"],"sources":["../../src/Entity.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport type { EntityId, URI } from '@dxos/keys';\n\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport type * as Relation from './Relation.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\n// Re-export KindId and SnapshotKindId from internal.\nexport const KindId = internal.KindId;\nexport type KindId = typeof internal.KindId;\nexport const SnapshotKindId = internal.SnapshotKindId;\nexport type SnapshotKindId = typeof internal.SnapshotKindId;\n\n// NOTE: Relation does not extend Obj so that, for example, we can prevent Relations from being used as source and target objects.\n// However, we generally refer to Obj and Relation instances as \"objects\",\n// and many API methods accept both Obj.Unknown and Relation.Unknown (i.e., Entity.Unknown) instances.\n\nexport const Kind = internal.EntityKind;\nexport type Kind = internal.EntityKind;\nexport const KindSchema = internal.EntityKindSchema;\n\n/**\n * Assigns a kind to an Object or Relation instance.\n * NOTE: Needed to make `isRelation` and `isObject` checks work.\n */\nexport interface OfKind<K extends Kind> {\n readonly [KindId]: K;\n readonly id: EntityId;\n}\n\n/**\n * Assigns a snapshot kind to an Object or Relation snapshot.\n */\nexport interface SnapshotOfKind<K extends Kind> {\n readonly [SnapshotKindId]: K;\n readonly id: EntityId;\n}\n\n/**\n * Obj or Relation with a specific set of properties.\n */\nexport type Entity<Props> = OfKind<Kind> & Props;\n\n/**\n * Unknown Obj or Relation (reactive).\n */\nexport interface Unknown extends OfKind<Kind> {}\n\n/**\n * Effect Schema for any ECHO entity (object or relation).\n *\n * Kind-agnostic counterpart to `Obj.Unknown` / `Relation.Unknown` — validates\n * the structural shape (id + properties) without constraining `[KindId]`. Used\n * in operation input schemas that accept any entity flavour (e.g.\n * `Schema.Array(Entity.Unknown)`).\n *\n * The cast bridges the runtime structural schema to the branded `Unknown` type:\n * `[KindId]` is a symbol brand that can't be expressed in a runtime `Struct`,\n * so the entity guarantee is carried at the type level only (same approach as\n * `Obj.Unknown` / `Relation.Unknown`). Unlike those, this is kind-agnostic so it\n * isn't an `UnknownTypeSchema<_, K>` (there's no single `K`) and carries no\n * `TypeAnnotation`.\n */\nexport const Unknown: Schema.Codec<Unknown> = Schema.StructWithRest(Schema.Struct({ id: Schema.String }), [\n Schema.Record(Schema.String, Schema.Unknown),\n]) as unknown as Schema.Codec<Unknown>;\n\n/**\n * Snapshot of an Obj or Relation.\n * Branded with SnapshotKindId instead of KindId.\n */\nexport interface Snapshot extends SnapshotOfKind<Kind> {}\n\n/**\n * Object with arbitrary properties.\n *\n * NOTE: Due to how typescript works, this type is not assignable to a specific schema type.\n * In that case, use `Obj.instanceOf` to check if an object is of a specific type.\n *\n * This type is very permissive and allows accessing any property on the object.\n * We should move to Obj.Unknown that is not permissive and requires explicit instanceof checks..\n */\nexport interface Any extends OfKind<Kind> {\n [key: string]: unknown;\n}\n\n/**\n * Returns all properties of an object or relation except for the id and kind.\n */\nexport type Properties<T> = Omit<T, 'id' | KindId | Relation.Source | Relation.Target>;\n\n/**\n * Check if a value is an ECHO entity (object or relation).\n * Returns `false` for snapshots.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isEntity: (value: unknown) => value is Unknown = internal.isEntity;\n\n/**\n * Test if a value is an instance of a given object or relation type.\n *\n * Kind-agnostic counterpart to `Obj.instanceOf` / `Relation.instanceOf` —\n * use this when the caller's input type is `Type.AnyObj | Type.AnyRelation`.\n *\n * @example\n * ```ts\n * // Caller doesn't know whether `type` is object- or relation-kind.\n * const matches = <T extends Type.AnyObj | Type.AnyRelation>(type: T, value: unknown) =>\n * Entity.instanceOf(type, value);\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n <S extends Type.AnyEntity>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyEntity>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyEntity, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Check if a value is an ECHO entity snapshot.\n * Returns `false` for entities.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (value: unknown): value is Snapshot => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return (value as any)[SnapshotKindId] !== undefined;\n};\n\n// TODO(dmaretskyi): Type introspection -- move to kind.\n/**\n * Get the entity kind declared by a schema type annotation.\n *\n * @performance O(1) schema annotation read.\n */\nexport const getKind = internal.getEntityKind;\n\n/**\n * Property that accesses metadata for an entity.\n */\nexport const Meta: unique symbol = internal.MetaId as any;\n\n/**\n * Property that accesses metadata for an entity.\n */\nexport type Meta = typeof Meta;\n\n//\n// Entity-level functions that work on any entity (object or relation).\n// Use these when you don't know or care about the specific entity kind.\n// For kind-specific functions, use Obj.* or Relation.*.\n//\n\n/**\n * JSON representation of an entity.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Whether the entity is a type-kind entity (a `Type.Type` produced by\n * `Type.makeObject` / `Type.makeRelation`, or a persisted schema). Type entities\n * carry their identity (typename/version) on themselves rather than referencing a\n * separate type, so the accessors below route them through the `Type.*` module.\n */\nconst isTypeEntity = (entity: unknown): boolean => internal.getEntityKindBrand(entity) === internal.EntityKind.Type;\n\n/**\n * Any value the read accessors operate on: a reactive entity or a snapshot.\n * Type entities (`Type.AnyEntity`) are also accepted — they're first-class\n * entities, and `Unknown`'s kind-agnostic brand already subsumes them.\n */\nexport type AnyInput = Unknown | Snapshot;\n\n/**\n * Get the canonical URI of an entity (object, relation, or type). Returns `URI.URI` —\n * an `EID` for object/relation instances and persisted types, or a typename\n * `DXN` for static type entities; narrow with `EID.parse(uri)` or\n * `DXN.tryMake(uri)` at the point of use.\n *\n * @param options.prefer - Controls the URI form (see {@link internal.GetURIOptions}).\n *\n * @performance O(1); returns the stored URI, constructing (and allocating) one only when `options.prefer` asks for\n * another form.\n */\nexport const getURI = (entity: AnyInput, options?: internal.GetURIOptions): URI.URI =>\n isTypeEntity(entity) ? Type.getURI(entity as Type.AnyEntity, options) : internal.getUri(entity as Unknown, options);\n\n/**\n * Get the DXN of an entity's type. For object/relation instances this is the URI\n * of the type they were created from; for a type entity it is the URI of the\n * meta-type ({@link Type.Type}, `dxn:org.dxos.type.schema:0.1.0`).\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI = (entity: AnyInput): URI.URI | undefined =>\n isTypeEntity(entity) ? Type.getURI(Type.Type) : internal.getTypeURI(entity as Unknown);\n\n/**\n * Get the type entity (`Type.AnyEntity`) the instance was created from.\n *\n * Returns `undefined` when the entity's type isn't registered in this runtime\n * (e.g. a freshly deserialized snapshot whose type entity hasn't been wired\n * up yet, or an entity loaded from storage before its schema is known). To\n * get the Effect Schema from the returned entity, use `Type.getSchema(...)`.\n *\n * For a type entity, returns the meta-type {@link Type.Type} (a type entity's\n * type is \"Type\").\n *\n * @performance O(1) read of the type back-reference.\n */\nexport const getType = (entity: AnyInput): Type.AnyEntity | undefined =>\n isTypeEntity(entity) ? Type.Type : (internal.getType(entity) as Type.AnyEntity | undefined);\n\n/**\n * Get the typename of an entity's type. For object/relation instances this is the\n * typename of the type they were created from; for a type entity it is the type's\n * own typename (e.g. `com.example.type.person`).\n *\n * @performance O(1); reads the schema type annotation (database objects resolve the schema by registry URI lookup).\n */\nexport const getTypename = (entity: AnyInput): string | undefined =>\n isTypeEntity(entity) ? Type.getTypename(entity as Type.AnyEntity) : internal.getTypename(entity as Unknown);\n\n/**\n * Get the database an entity belongs to.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Unknown | Snapshot): any | undefined => internal.getDatabase(entity);\n\n/**\n * Get the metadata for an entity.\n * Returns mutable meta when passed a mutable entity (inside change callback).\n * Returns read-only meta when passed a regular entity or snapshot.\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\n// TODO(wittjosiah): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\nexport function getMeta(entity: Mutable<Unknown>): internal.Meta;\nexport function getMeta(entity: Unknown | Snapshot): internal.ReadonlyMeta;\nexport function getMeta(entity: Unknown | Snapshot | Mutable<Unknown>): internal.Meta | internal.ReadonlyMeta {\n return internal.getMetaChecked(entity);\n}\n\n/**\n * Get foreign keys for an entity from the specified source.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys = (entity: Unknown | Snapshot, source: string): ForeignKey[] => internal.getKeys(entity, source);\n\n/**\n * Check if an entity is deleted.\n *\n * @performance O(1) slot read.\n */\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => internal.isDeleted(entity);\n\n/**\n * Get the label of an entity.\n *\n * @param options.fallback `'typename'` returns the entity's typename when no\n * label is set (e.g. `org.dxos.type.table`).\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: Unknown | Snapshot, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * Set the label of an entity.\n * Must be called within an `Entity.update` / `Obj.update` / `Relation.update` callback.\n *\n * @performance O(1); writes the first `LabelAnnotation` accessor, a no-op without a schema.\n */\nexport const setLabel = (entity: Mutable<Unknown>, label: string): void => internal.setLabel(entity, label);\n\n/**\n * Get the description of an entity.\n *\n * @performance O(1); reads the field named by the schema `DescriptionAnnotation`.\n */\nexport const getDescription = (entity: Unknown | Snapshot): string | undefined => internal.getDescription(entity);\n\n/**\n * Get the icon annotation for an entity (object or relation), resolved via its type-level\n * `IconAnnotation`. Returns the full `{ icon, hue }` annotation so callers can use both\n * the phosphor icon name and the suggested colour.\n *\n * @performance O(1) schema annotation lookup, but decodes the annotation value on every call (not cached).\n */\nexport const getIcon = (entity: Unknown | Snapshot): internal.IconAnnotation | undefined => internal.getIcon(entity);\n\n/**\n * Convert an entity to its JSON representation.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\nexport const toJSON = (entity: Unknown | Snapshot): JSON => internal.objectToJSON(entity);\n\n/**\n * Subscribe to changes on an entity (object or relation).\n * @returns Unsubscribe function.\n *\n * @performance O(1) listener registration; the callback runs synchronously after every committed change.\n */\nexport const subscribe = (entity: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(entity, callback);\n};\n\n//\n// Change\n//\n\n/**\n * Used to provide a mutable view of an entity within `Entity.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an entity (object or relation) within a change context.\n *\n * Entities are read-only by default. Mutations are batched and notifications fire\n * when the callback completes. Direct mutations outside of `Entity.update` will throw\n * at runtime.\n *\n * @param entity - The echo entity (object or relation) to mutate.\n * @param callback - Receives a mutable view of the entity. All mutations must occur here.\n *\n * @example\n * ```typescript\n * // Mutate within Entity.update\n * Entity.update(entity, (obj) => {\n * obj.name = 'Updated';\n * obj.count = 42;\n * });\n *\n * // Direct mutation throws\n * entity.name = 'Bob'; // Error: Cannot modify outside Entity.update()\n * ```\n *\n * Note: For type-specific operations, prefer `Obj.update` or `Relation.update`.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = <T extends Unknown>(entity: T, callback: internal.ChangeCallback<T>): void => {\n internal.change(entity, callback);\n};\n\n/**\n * Add a tag to an entity.\n * Must be called within an `Entity.update`, `Obj.update`, or `Relation.update` callback.\n *\n * @performance O(t) in the tag count; dedupes by tag id before appending.\n */\nexport const addTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.addTag(entity, tag);\n\n/**\n * Remove a tag from an entity.\n * Must be called within an `Entity.update`, `Obj.update`, or `Relation.update` callback.\n *\n * @performance O(t) in the tag count.\n */\nexport const removeTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.removeTag(entity, tag);\n\n//\n// Atoms\n//\n\n/**\n * Create a reactive snapshot atom for an entity (object or relation).\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeEntity;\n/**\n * Create a reactive atom for the label of an entity.\n *\n * @performance O(1) memoized atom-family lookup; recomputes the label on every entity change, emitting only on\n * difference.\n */\nexport const labelAtom = objInternal.makeLabelAtom;\n/**\n * Create a reactive atom for the meta tags of an entity.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the tags on every entity change, emitting only when the\n * tag list changes.\n */\nexport const tagsAtom = objInternal.makeTagsAtom;\n/**\n * Get the name of the property that holds the label of an entity.\n *\n * @performance O(1); reads the first accessor of the schema `LabelAnnotation`.\n */\nexport const labelProperty = internal.getLabelProperty;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,SAASA;AAEtB,IAAa,iBAAiBC;AAO9B,IAAa,OAAOC;AAEpB,IAAa,aAAaC;;;;;;;;;;;;;;;;AA4C1B,IAAa,UAAiC,OAAO,eAAe,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC,GAAG,CACxG,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAC7C,CAAC;;;;;;;AAgCD,IAAa,WAAiDC;;;;;;;;;;;;;;;;AAiB9D,IAAa,eAGP,GAAG,SAAoD;CAC3D,IAAI,KAAK,WAAW,GAClB,QAAQ,WAAoBC,aAAsB,KAAK,IAAI,MAAM;CAEnE,OAAOA,aAAsB,KAAK,IAAI,KAAK,EAAE;AAC/C;;;;;;;AAQA,IAAa,cAAc,UAAsC;CAC/D,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,OAAQ,MAAc,oBAAoB,KAAA;AAC5C;;;;;;AAQA,IAAa,UAAUC;;;;AAKvB,IAAa,OAAsBC;;;;;;;AAwBnC,IAAM,gBAAgB,WAA6BC,mBAA4B,MAAM,MAAA,WAA0B;;;;;;;;;;;;AAoB/G,IAAa,UAAU,QAAkB,YACvC,aAAa,MAAM,IAAIC,SAAY,QAA0B,OAAO,IAAIC,OAAgB,QAAmB,OAAO;;;;;;;;AASpH,IAAa,cAAc,WACzB,aAAa,MAAM,IAAID,SAAYE,IAAS,IAAIC,aAAoB,MAAiB;;;;;;;;;;;;;;AAevF,IAAa,WAAW,WACtB,aAAa,MAAM,IAAID,OAAaE,UAAiB,MAAM;;;;;;;;AAS7D,IAAa,eAAe,WAC1B,aAAa,MAAM,IAAIC,cAAiB,MAAwB,IAAIC,cAAqB,MAAiB;;;;;;AAO5G,IAAa,eAAe,WAAgDC,cAAqB,MAAM;AAYvG,SAAgB,QAAQ,QAAsF;CAC5G,OAAOC,eAAwB,MAAM;AACvC;;;;;;AAOA,IAAa,WAAW,QAA4B,WAAiCC,UAAiB,QAAQ,MAAM;;;;;;AAOpH,IAAa,aAAa,WAAwCC,YAAmB,MAAM;;;;;;;;;AAU3F,IAAa,YAAY,QAA4B,YACnDC,WAAkB,QAAQ,OAAO;;;;;;;AAQnC,IAAa,YAAY,QAA0B,UAAwBC,WAAkB,QAAQ,KAAK;;;;;;AAO1G,IAAa,kBAAkB,WAAmDC,iBAAwB,MAAM;;;;;;;;AAShH,IAAa,WAAW,WAAoEC,UAAiB,MAAM;;;;;;AAOnH,IAAa,UAAU,WAAqCC,aAAsB,MAAM;;;;;;;AAQxF,IAAa,aAAa,QAAiB,aAAuC;CAChF,OAAOC,YAAmB,QAAQ,QAAQ;AAC5C;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,UAA6B,QAAW,aAA+C;CAClG,OAAgB,QAAQ,QAAQ;AAClC;;;;;;;AAQA,IAAa,UAAU,QAA0B,QAAuBC,SAAgB,QAAQ,GAAG;;;;;;;AAQnG,IAAa,aAAa,QAA0B,QAAuBC,YAAmB,QAAQ,GAAG;;;;;;AAWzG,IAAa,OAAOC;;;;;;;AAOpB,IAAa,YAAYC;;;;;;;AAOzB,IAAa,WAAWC;;;;;;AAMxB,IAAa,gBAAgBC"}
@@ -7,6 +7,7 @@ var Error_exports = /* @__PURE__ */ __exportAll({
7
7
  BlobWriteError: () => BlobWriteError,
8
8
  EntityNotFoundError: () => EntityNotFoundError,
9
9
  GetReactiveError: () => GetReactiveError,
10
+ MigrationError: () => MigrationError,
10
11
  SchemaNotFoundError: () => SchemaNotFoundError,
11
12
  TextEditNotFoundError: () => TextEditNotFoundError,
12
13
  TextNotSupportedError: () => TextNotSupportedError
@@ -99,7 +100,18 @@ var GetReactiveError = class extends BaseError.extend("GetReactiveError", "Faile
99
100
  });
100
101
  }
101
102
  };
103
+ /**
104
+ * Thrown when a migration transaction cannot read or write the documents it stages.
105
+ */
106
+ var MigrationError = class extends BaseError.extend("MigrationError", "Migration failed") {
107
+ constructor(context, options) {
108
+ super({
109
+ context,
110
+ ...options
111
+ });
112
+ }
113
+ };
102
114
  //#endregion
103
- export { Error_exports as a, TextEditNotFoundError as c, EntityNotFoundError as i, TextNotSupportedError as l, BlobTooLargeError as n, GetReactiveError as o, BlobWriteError as r, SchemaNotFoundError as s, BlobNotAvailableError as t };
115
+ export { Error_exports as a, SchemaNotFoundError as c, EntityNotFoundError as i, TextEditNotFoundError as l, BlobTooLargeError as n, GetReactiveError as o, BlobWriteError as r, MigrationError as s, BlobNotAvailableError as t, TextNotSupportedError as u };
104
116
 
105
117
  //# sourceMappingURL=chunk-Error.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Error.mjs","names":[],"sources":["../../src/Error.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { BaseError, type BaseErrorOptions } from '@dxos/errors';\nimport { type URI } from '@dxos/keys';\n\nexport class SchemaNotFoundError extends BaseError.extend('SchemaNotFoundError', 'Schema not found') {\n constructor(schema: string, options?: BaseErrorOptions) {\n super({ context: { schema }, ...options });\n }\n}\n\nexport class EntityNotFoundError extends BaseError.extend('EntityNotFoundError', 'Entity not found') {\n constructor(uri: URI.URI, options?: BaseErrorOptions) {\n super({ context: { uri }, ...options });\n }\n}\n\n/**\n * Thrown when a `Text` mutation is attempted on an object whose reactive handler does not implement\n * string CRDT editing (e.g. a snapshot or a non-reactive value).\n */\nexport class TextNotSupportedError extends BaseError.extend(\n 'TextNotSupportedError',\n 'Text operation is not supported for this object',\n) {\n constructor(operation: string, options?: BaseErrorOptions) {\n super({ context: { operation }, ...options });\n }\n}\n\n/**\n * Thrown by `Text.apply` when a non-`replaceAll` edit's `oldString` is not found in the text.\n */\nexport class TextEditNotFoundError extends BaseError.extend('TextEditNotFoundError', 'Edit text not found') {\n constructor(oldString: string, options?: BaseErrorOptions) {\n super({ context: { oldString }, ...options });\n }\n}\n\n/**\n * Thrown when a blob's bytes exceed the size limit of the storage backend writing them (inline\n * storage's fixed cap, or a registered backend's own `maxSize`).\n */\nexport class BlobTooLargeError extends BaseError.extend('BlobTooLargeError', 'Blob is too large for its backend') {\n constructor(context: { size: number; limit: number }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Reason why a blob's bytes could not be read.\n * - `offline`: The backend's transport failed (e.g. network unavailable).\n * - `not-found`: The backend could not locate the bytes for the given URI.\n * - `backend-not-registered`: No backend is registered for the URI's scheme.\n */\nexport type BlobNotAvailableReason = 'offline' | 'not-found' | 'backend-not-registered';\n\n/**\n * Thrown when a blob's bytes cannot be read from its backend.\n */\nexport class BlobNotAvailableError extends BaseError.extend('BlobNotAvailableError', 'Blob is not available') {\n constructor(context: { backend: string; key: string; reason: BlobNotAvailableReason }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Thrown when a blob's bytes fail to upload to its backend.\n */\nexport class BlobWriteError extends BaseError.extend('BlobWriteError', 'Failed to write blob') {\n constructor(context: { backend: string }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Reason why getting a reactive object from a snapshot failed.\n * - `no-database`: The snapshot is not associated with a database.\n * - `object-not-found`: The object was removed or does not exist in the database.\n */\nexport type GetReactiveErrorReason = 'no-database' | 'object-not-found';\n\n/**\n * Error thrown when a reactive object cannot be resolved from a snapshot.\n * Extends `BaseError` with a `reason` and optional `snapshotId` in its context.\n */\nexport class GetReactiveError extends BaseError.extend(\n 'GetReactiveError',\n 'Failed to get reactive object from snapshot',\n) {\n constructor(options: { reason: GetReactiveErrorReason; snapshotId?: string } & BaseErrorOptions) {\n super({ context: { reason: options.reason, snapshotId: options.snapshotId }, ...options });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,UAAU,OAAO,uBAAuB,kBAAkB,CAAC,CAAC;CACnG,YAAY,QAAgB,SAA4B;EACtD,MAAM;GAAE,SAAS,EAAE,OAAO;GAAG,GAAG;EAAQ,CAAC;CAC3C;AACF;AAEA,IAAa,sBAAb,cAAyC,UAAU,OAAO,uBAAuB,kBAAkB,CAAC,CAAC;CACnG,YAAY,KAAc,SAA4B;EACpD,MAAM;GAAE,SAAS,EAAE,IAAI;GAAG,GAAG;EAAQ,CAAC;CACxC;AACF;;;;;AAMA,IAAa,wBAAb,cAA2C,UAAU,OACnD,yBACA,iDACF,CAAC,CAAC;CACA,YAAY,WAAmB,SAA4B;EACzD,MAAM;GAAE,SAAS,EAAE,UAAU;GAAG,GAAG;EAAQ,CAAC;CAC9C;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,UAAU,OAAO,yBAAyB,qBAAqB,CAAC,CAAC;CAC1G,YAAY,WAAmB,SAA4B;EACzD,MAAM;GAAE,SAAS,EAAE,UAAU;GAAG,GAAG;EAAQ,CAAC;CAC9C;AACF;;;;;AAMA,IAAa,oBAAb,cAAuC,UAAU,OAAO,qBAAqB,mCAAmC,CAAC,CAAC;CAChH,YAAY,SAA0C,SAA4B;EAChF,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;AAaA,IAAa,wBAAb,cAA2C,UAAU,OAAO,yBAAyB,uBAAuB,CAAC,CAAC;CAC5G,YAAY,SAA2E,SAA4B;EACjH,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;AAKA,IAAa,iBAAb,cAAoC,UAAU,OAAO,kBAAkB,sBAAsB,CAAC,CAAC;CAC7F,YAAY,SAA8B,SAA4B;EACpE,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;;AAaA,IAAa,mBAAb,cAAsC,UAAU,OAC9C,oBACA,6CACF,CAAC,CAAC;CACA,YAAY,SAAqF;EAC/F,MAAM;GAAE,SAAS;IAAE,QAAQ,QAAQ;IAAQ,YAAY,QAAQ;GAAW;GAAG,GAAG;EAAQ,CAAC;CAC3F;AACF"}
1
+ {"version":3,"file":"chunk-Error.mjs","names":[],"sources":["../../src/Error.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { BaseError, type BaseErrorOptions } from '@dxos/errors';\nimport { type URI } from '@dxos/keys';\n\nexport class SchemaNotFoundError extends BaseError.extend('SchemaNotFoundError', 'Schema not found') {\n constructor(schema: string, options?: BaseErrorOptions) {\n super({ context: { schema }, ...options });\n }\n}\n\nexport class EntityNotFoundError extends BaseError.extend('EntityNotFoundError', 'Entity not found') {\n constructor(uri: URI.URI, options?: BaseErrorOptions) {\n super({ context: { uri }, ...options });\n }\n}\n\n/**\n * Thrown when a `Text` mutation is attempted on an object whose reactive handler does not implement\n * string CRDT editing (e.g. a snapshot or a non-reactive value).\n */\nexport class TextNotSupportedError extends BaseError.extend(\n 'TextNotSupportedError',\n 'Text operation is not supported for this object',\n) {\n constructor(operation: string, options?: BaseErrorOptions) {\n super({ context: { operation }, ...options });\n }\n}\n\n/**\n * Thrown by `Text.apply` when a non-`replaceAll` edit's `oldString` is not found in the text.\n */\nexport class TextEditNotFoundError extends BaseError.extend('TextEditNotFoundError', 'Edit text not found') {\n constructor(oldString: string, options?: BaseErrorOptions) {\n super({ context: { oldString }, ...options });\n }\n}\n\n/**\n * Thrown when a blob's bytes exceed the size limit of the storage backend writing them (inline\n * storage's fixed cap, or a registered backend's own `maxSize`).\n */\nexport class BlobTooLargeError extends BaseError.extend('BlobTooLargeError', 'Blob is too large for its backend') {\n constructor(context: { size: number; limit: number }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Reason why a blob's bytes could not be read.\n * - `offline`: The backend's transport failed (e.g. network unavailable).\n * - `not-found`: The backend could not locate the bytes for the given URI.\n * - `backend-not-registered`: No backend is registered for the URI's scheme.\n */\nexport type BlobNotAvailableReason = 'offline' | 'not-found' | 'backend-not-registered';\n\n/**\n * Thrown when a blob's bytes cannot be read from its backend.\n */\nexport class BlobNotAvailableError extends BaseError.extend('BlobNotAvailableError', 'Blob is not available') {\n constructor(context: { backend: string; key: string; reason: BlobNotAvailableReason }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Thrown when a blob's bytes fail to upload to its backend.\n */\nexport class BlobWriteError extends BaseError.extend('BlobWriteError', 'Failed to write blob') {\n constructor(context: { backend: string }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n\n/**\n * Reason why getting a reactive object from a snapshot failed.\n * - `no-database`: The snapshot is not associated with a database.\n * - `object-not-found`: The object was removed or does not exist in the database.\n */\nexport type GetReactiveErrorReason = 'no-database' | 'object-not-found';\n\n/**\n * Error thrown when a reactive object cannot be resolved from a snapshot.\n * Extends `BaseError` with a `reason` and optional `snapshotId` in its context.\n */\nexport class GetReactiveError extends BaseError.extend(\n 'GetReactiveError',\n 'Failed to get reactive object from snapshot',\n) {\n constructor(options: { reason: GetReactiveErrorReason; snapshotId?: string } & BaseErrorOptions) {\n super({ context: { reason: options.reason, snapshotId: options.snapshotId }, ...options });\n }\n}\n\n/**\n * Thrown when a migration transaction cannot read or write the documents it stages.\n */\nexport class MigrationError extends BaseError.extend('MigrationError', 'Migration failed') {\n constructor(context: { operation: string; id?: string }, options?: BaseErrorOptions) {\n super({ context, ...options });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,UAAU,OAAO,uBAAuB,kBAAkB,CAAC,CAAC;CACnG,YAAY,QAAgB,SAA4B;EACtD,MAAM;GAAE,SAAS,EAAE,OAAO;GAAG,GAAG;EAAQ,CAAC;CAC3C;AACF;AAEA,IAAa,sBAAb,cAAyC,UAAU,OAAO,uBAAuB,kBAAkB,CAAC,CAAC;CACnG,YAAY,KAAc,SAA4B;EACpD,MAAM;GAAE,SAAS,EAAE,IAAI;GAAG,GAAG;EAAQ,CAAC;CACxC;AACF;;;;;AAMA,IAAa,wBAAb,cAA2C,UAAU,OACnD,yBACA,iDACF,CAAC,CAAC;CACA,YAAY,WAAmB,SAA4B;EACzD,MAAM;GAAE,SAAS,EAAE,UAAU;GAAG,GAAG;EAAQ,CAAC;CAC9C;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,UAAU,OAAO,yBAAyB,qBAAqB,CAAC,CAAC;CAC1G,YAAY,WAAmB,SAA4B;EACzD,MAAM;GAAE,SAAS,EAAE,UAAU;GAAG,GAAG;EAAQ,CAAC;CAC9C;AACF;;;;;AAMA,IAAa,oBAAb,cAAuC,UAAU,OAAO,qBAAqB,mCAAmC,CAAC,CAAC;CAChH,YAAY,SAA0C,SAA4B;EAChF,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;AAaA,IAAa,wBAAb,cAA2C,UAAU,OAAO,yBAAyB,uBAAuB,CAAC,CAAC;CAC5G,YAAY,SAA2E,SAA4B;EACjH,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;AAKA,IAAa,iBAAb,cAAoC,UAAU,OAAO,kBAAkB,sBAAsB,CAAC,CAAC;CAC7F,YAAY,SAA8B,SAA4B;EACpE,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF;;;;;AAaA,IAAa,mBAAb,cAAsC,UAAU,OAC9C,oBACA,6CACF,CAAC,CAAC;CACA,YAAY,SAAqF;EAC/F,MAAM;GAAE,SAAS;IAAE,QAAQ,QAAQ;IAAQ,YAAY,QAAQ;GAAW;GAAG,GAAG;EAAQ,CAAC;CAC3F;AACF;;;;AAKA,IAAa,iBAAb,cAAoC,UAAU,OAAO,kBAAkB,kBAAkB,CAAC,CAAC;CACzF,YAAY,SAA6C,SAA4B;EACnF,MAAM;GAAE;GAAS,GAAG;EAAQ,CAAC;CAC/B;AACF"}
@@ -1,45 +1,106 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { c as getMetaChecked, m as foreignKey, o as deleteKeys, s as getKeys } from "./chunk-entity-dictionary.mjs";
3
- import { O as withSpaceId, b as query$1, i as Service, q as FormInputAnnotation, r as Origin, tt as IconAnnotation } from "./chunk-Database.mjs";
3
+ import { P as getFeedBlockKeys, Q as FormInputAnnotation, i as Service, k as withSpaceId, ot as IconAnnotation, r as Origin, x as query$1 } from "./chunk-Database.mjs";
4
4
  import { v as change } from "./chunk-ref.mjs";
5
5
  import { d as make$1 } from "./chunk-Annotation.mjs";
6
6
  import { y as makeObject } from "./chunk-Type.mjs";
7
- import { F as getURI, G as make$2, t as ID } from "./chunk-Obj.mjs";
7
+ import { F as getURI, G as make$2, at as update, t as ID } from "./chunk-Obj.mjs";
8
+ import { p as feedCursor, r as and } from "./chunk-Filter.mjs";
9
+ import { a as natural } from "./chunk-Order.mjs";
8
10
  import { s as is, u as select } from "./chunk-Query.mjs";
9
11
  import { n as feed } from "./chunk-Scope.mjs";
10
- import { KEY_QUEUE_POSITION } from "@dxos/echo-protocol";
12
+ import { KEY_FEED_BLOCK, KEY_FEED_BRANCH, KEY_FEED_FORK, KEY_FEED_PREV, KEY_QUEUE_POSITION } from "@dxos/echo-protocol";
11
13
  import { DXN, EID, EntityId } from "@dxos/keys";
12
14
  import * as Function from "effect/Function";
15
+ import * as Option from "effect/Option";
13
16
  import * as Schema from "effect/Schema";
14
17
  import { invariant } from "@dxos/invariant";
15
18
  import * as Effect from "effect/Effect";
16
19
  import * as Context from "effect/Context";
17
20
  import * as Layer from "effect/Layer";
21
+ import * as Duration from "effect/Duration";
18
22
  //#region src/Feed.ts
19
23
  var Feed_exports = /* @__PURE__ */ __exportAll({
24
+ BLOCK_KEYS: () => BLOCK_KEYS,
25
+ BranchId: () => BranchId,
20
26
  ContextFeedService: () => ContextFeedService,
21
27
  Cursor: () => Cursor,
22
28
  CursorAnnotation: () => CursorAnnotation,
23
29
  Feed: () => Feed,
30
+ FeedOptions: () => FeedOptions,
31
+ IndexingOptions: () => IndexingOptions,
32
+ LocalCursor: () => LocalCursor,
33
+ Namespace: () => Namespace,
24
34
  PARENT_KEY: () => PARENT_KEY,
25
35
  POSITION_KEY: () => POSITION_KEY,
36
+ RetentionOptions: () => RetentionOptions,
26
37
  START: () => START,
27
38
  append: () => append,
39
+ branchKey: () => branchKey,
40
+ fork: () => fork,
41
+ getBlockId: () => getBlockId,
42
+ getBranch: () => getBranch,
28
43
  getCursor: () => getCursor,
29
44
  getFeedUri: () => getFeedUri,
45
+ getLocalCursor: () => getLocalCursor,
30
46
  getParent: () => getParent,
31
47
  getPosition: () => getPosition,
48
+ getPredecessor: () => getPredecessor,
32
49
  getSyncState: () => getSyncState,
33
50
  history: () => history,
51
+ isFork: () => isFork,
34
52
  layer: () => layer,
35
53
  make: () => make,
36
54
  query: () => query,
55
+ readBranch: () => readBranch,
37
56
  remove: () => remove,
57
+ setBranch: () => setBranch,
58
+ setIndexing: () => setIndexing,
38
59
  setParent: () => setParent,
39
60
  setRetention: () => setRetention,
40
- sync: () => sync
61
+ sync: () => sync,
62
+ walk: () => walk
41
63
  });
42
64
  var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo/src/Feed.ts";
65
+ /** The namespaces a feed can store its data under; `data` is the default. */
66
+ var Namespace = Schema.Literals(["data", "trace"]);
67
+ /**
68
+ * Indexing options for a feed. Absent on a feed means indexing is enabled.
69
+ *
70
+ * A struct rather than a bare boolean so later options (which indexes to build) need no migration.
71
+ */
72
+ var IndexingOptions = Schema.Struct({
73
+ /** When false, the feed's items are not indexed at all; there is no partial mode. */
74
+ enabled: Schema.Boolean,
75
+ /**
76
+ * Which branches the index holds: `main` (the default) or `all`. There is no selected subset.
77
+ * A feed whose items mutate objects keeps `main`; a feed of messages from people can index `all`.
78
+ */
79
+ mode: Schema.optional(Schema.Literals(["all", "main"]))
80
+ });
81
+ /**
82
+ * Retention options for a feed. With both limits set, an item is dropped when it breaks either;
83
+ * an empty struct (or no `retention` on the feed) trims nothing.
84
+ *
85
+ * Live feed objects persist every `Obj.update` as a whole-object re-append, so superseded blocks are
86
+ * trimmed by these limits like any other block; retention does not compact them.
87
+ */
88
+ var RetentionOptions = Schema.Struct({
89
+ /** Maximum number of items kept; the oldest beyond it are dropped. */
90
+ maxLength: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(1)), Schema.optional),
91
+ /**
92
+ * Maximum age of an item in milliseconds, measured from its append timestamp.
93
+ * Milliseconds rather than a `Duration` because ECHO stores plain JSON; {@link setRetention} converts.
94
+ */
95
+ maxAge: Schema.Finite.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.optional)
96
+ });
97
+ /**
98
+ * A feed's indexing and retention options, as the indexer carries them down to the feed store.
99
+ */
100
+ var FeedOptions = Schema.Struct({
101
+ indexing: Schema.optional(IndexingOptions),
102
+ retention: Schema.optional(RetentionOptions)
103
+ });
43
104
  /**
44
105
  * Runtime schema for a Feed object.
45
106
  *
@@ -59,7 +120,7 @@ var Feed = class extends makeObject(DXN.make("org.dxos.type.feed", "0.1.0"))(Sch
59
120
  * - `data`: Data feed (default).
60
121
  * - `trace`: Trace feed.
61
122
  */
62
- namespace: Schema.optional(Schema.Literals(["data", "trace"])),
123
+ namespace: Schema.optional(Namespace),
63
124
  /**
64
125
  * Earliest item a pending rewind discards — set when a soft fork is decided but not yet expressed,
65
126
  * because the writer may be a different process than the one that decided it.
@@ -72,7 +133,11 @@ var Feed = class extends makeObject(DXN.make("org.dxos.type.feed", "0.1.0"))(Sch
72
133
  * (see {@link PARENT_KEY}), which is what {@link history} walks and what replicates in a defined
73
134
  * order relative to the blocks.
74
135
  */
75
- rewindFrom: Schema.optional(ID.pipe(FormInputAnnotation.set(false)))
136
+ rewindFrom: Schema.optional(ID.pipe(FormInputAnnotation.set(false))),
137
+ /** Indexing options; absent means indexing is enabled. Set with {@link setIndexing}. */
138
+ indexing: IndexingOptions.pipe(FormInputAnnotation.set(false), Schema.optional),
139
+ /** Retention options; absent means nothing is trimmed. Set with {@link setRetention}. */
140
+ retention: RetentionOptions.pipe(FormInputAnnotation.set(false), Schema.optional)
76
141
  }).pipe(IconAnnotation.set({
77
142
  icon: "ph--rows--regular",
78
143
  hue: "yellow"
@@ -158,6 +223,10 @@ var getFeedUri = (feed) => EID.tryParse(getURI(feed));
158
223
  */
159
224
  var append = (feed, items, options) => Service.pipe(Effect.flatMap(({ db }) => Effect.flatMap(Origin, (origin) => Effect.promise(() => {
160
225
  if (options?.parent !== void 0 && items.length > 0) setParent(items[0], options.parent);
226
+ if (options?.branch !== void 0) {
227
+ const branch = options.branch;
228
+ items.forEach((item) => change(item, (mutable) => setBranchKey(mutable, branch)));
229
+ }
161
230
  return db.appendToFeed(feed, items, { origin });
162
231
  })))).pipe(Effect.withSpan("Feed.append"), withSpaceId);
163
232
  /**
@@ -170,7 +239,7 @@ var append = (feed, items, options) => Service.pipe(Effect.flatMap(({ db }) => E
170
239
  *
171
240
  * @performance Async; O(n) in items, deleted by id in one batch.
172
241
  */
173
- var remove = (feed, items) => Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.removeFeedItemsByIds(feed, items.map((item) => item.id))))).pipe(Effect.withSpan("Feed.remove"), withSpaceId);
242
+ var remove = (feed, items) => Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.removeFeedItemsByIds(feed, items.map((item) => item.id), { branches: items.map((item) => getBranch(item) ?? null) })))).pipe(Effect.withSpan("Feed.remove"), withSpaceId);
174
243
  /**
175
244
  * Foreign-key source for an item's explicit lineage parent within a feed.
176
245
  *
@@ -310,6 +379,205 @@ var history = (items, options) => {
310
379
  };
311
380
  };
312
381
  /**
382
+ * The id of a branch: the block id (`<sequence>@<actorId>`) of the base block of the branch, as an
383
+ * opaque string. The root branch has no id; scopes and the index name it `null`.
384
+ */
385
+ var BranchId = Schema.String.pipe(Schema.brand("@dxos/echo/Feed/BranchId"));
386
+ /**
387
+ * The foreign-key sources a store stamps on an item from the block it was read from: its block id, its
388
+ * branch, its fork flag (as the fork point) and its predecessor. A copy of the item into another feed
389
+ * drops them, since that feed has none of those blocks or branches.
390
+ */
391
+ var BLOCK_KEYS = [
392
+ KEY_FEED_BLOCK,
393
+ KEY_FEED_BRANCH,
394
+ KEY_FEED_FORK,
395
+ KEY_FEED_PREV
396
+ ];
397
+ /**
398
+ * The position of a walk on one device: the branch the walk is on and the last block it gave. Read it
399
+ * off an item with {@link getLocalCursor}; another device cannot use it.
400
+ */
401
+ var LocalCursor = Schema.String.pipe(Schema.brand("@dxos/echo/Feed/LocalCursor"));
402
+ var keyOf = (item, source) => (getFeedBlockKeys(item) ?? getKeys(item, source)).find((key) => key.source === source)?.id;
403
+ /** Writes the branch key into an open change, so a caller can batch it with its other writes. */
404
+ var setBranchKey = (mutable, branch) => {
405
+ deleteKeys(mutable, KEY_FEED_BRANCH);
406
+ getMetaChecked(mutable).keys.push(foreignKey(KEY_FEED_BRANCH, branch));
407
+ };
408
+ /**
409
+ * The foreign key that puts an item on `branch`, for an item built with it in its meta (`Obj.make(…, { [Obj.Meta]: {
410
+ * keys: [Feed.branchKey(branch)] } })`); cheaper than {@link setBranch}, which opens a change on an item made without it.
411
+ *
412
+ * @performance O(1).
413
+ */
414
+ var branchKey = (branch) => ({
415
+ source: KEY_FEED_BRANCH,
416
+ id: branch
417
+ });
418
+ /**
419
+ * Puts an item on a branch: a later {@link append} of it continues `branch`, so items for several
420
+ * branches can be built before they are written. Must be called within an `Obj.update` callback.
421
+ *
422
+ * @performance O(k) in the item foreign-key count.
423
+ */
424
+ var setBranch = (mutable, branch) => setBranchKey(mutable, branch);
425
+ /**
426
+ * The branch of an item, as the store inferred it from the block the item was read from; `undefined`
427
+ * on the root branch.
428
+ *
429
+ * @performance O(k) in the item foreign-key count.
430
+ */
431
+ var getBranch = (item) => {
432
+ const branch = keyOf(item, KEY_FEED_BRANCH);
433
+ return branch === void 0 ? void 0 : BranchId.make(branch);
434
+ };
435
+ /**
436
+ * True when the item was read from the base block of a branch: its fork flag is set, and its
437
+ * predecessor is the fork point.
438
+ *
439
+ * @performance O(k) in the item foreign-key count.
440
+ */
441
+ var isFork = (item) => keyOf(item, KEY_FEED_FORK) !== void 0;
442
+ /**
443
+ * The id of the block the item was read from; `undefined` on an item the store has not echoed yet.
444
+ *
445
+ * @performance O(k) in the item foreign-key count.
446
+ */
447
+ var getBlockId = (item) => keyOf(item, KEY_FEED_BLOCK);
448
+ /**
449
+ * The id of the predecessor of the block the item was read from: the head of its branch when it was
450
+ * written, or the fork point of a base block; `undefined` on the first block of a feed.
451
+ *
452
+ * @performance O(k) in the item foreign-key count.
453
+ */
454
+ var getPredecessor = (item) => keyOf(item, KEY_FEED_PREV);
455
+ /**
456
+ * The cursor a walk resumes after this item; `undefined` on an item the store has not echoed yet.
457
+ *
458
+ * @performance O(k) in the item foreign-key count.
459
+ */
460
+ var getLocalCursor = (item) => {
461
+ const block = getBlockId(item);
462
+ return block === void 0 ? void 0 : LocalCursor.make(`${getBranch(item) ?? ""}|${block}`);
463
+ };
464
+ /**
465
+ * Starts a new branch: the first item is appended as the base block of the branch, with the fork
466
+ * point `at` as its predecessor, and the rest continue the branch. Returns the id of the branch, the
467
+ * block id of its base, once the base is written.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * const branch = yield* Feed.fork(feed, [reply], { at: message });
472
+ * yield* Feed.append(feed, [followUp], { branch });
473
+ * ```
474
+ *
475
+ * @performance Async; one append for the base, then one for the rest.
476
+ */
477
+ var fork = Effect.fn("Feed.fork")(function* (feed, items, options) {
478
+ const { db } = yield* Service;
479
+ const [base, ...rest] = items;
480
+ invariant(base !== void 0, "fork: pass at least the base item", {
481
+ "~LogMeta": "~LogMeta",
482
+ F: __dxlog_file,
483
+ L: 681,
484
+ S: this,
485
+ A: ["base !== undefined", "'fork: pass at least the base item'"]
486
+ });
487
+ const branch = yield* Effect.promise(() => db.forkFeed(feed, base, { at: options.at }));
488
+ if (rest.length > 0) yield* append(feed, rest, { branch });
489
+ return branch;
490
+ }, withSpaceId);
491
+ /**
492
+ * Returns what a read of one branch sees: the items of its ancestors up to each fork point, then the
493
+ * items of the branch itself. Omit `branch` for the root branch.
494
+ *
495
+ * A feed appended as `A1, A2, A3, B1(fork at A2), A4, B2` reads `A1, A2, A3, A4` on the root branch and
496
+ * `A1, A2, B1, B2` on branch `B1`.
497
+ *
498
+ * `items` must be in **append order**, as read from the feed with `branches: 'all'`. The read is
499
+ * `shallow` when the base of a branch or its fork point is missing from `items` (a base or fork point
500
+ * that was updated is read at its latest block, which is not the one the branch names); the branch's
501
+ * own items are still returned. A walk ({@link walk}) reads blocks, so it has no such gap.
502
+ *
503
+ * @performance O(n) in items; one pass to group them and one walk up the branch's ancestors.
504
+ */
505
+ var readBranch = (items, branch) => {
506
+ const indexByBlock = /* @__PURE__ */ new Map();
507
+ const byBranch = /* @__PURE__ */ new Map();
508
+ items.forEach((item, index) => {
509
+ const block = getBlockId(item);
510
+ if (block !== void 0) indexByBlock.set(block, index);
511
+ const key = getBranch(item);
512
+ const members = byBranch.get(key) ?? [];
513
+ members.push(index);
514
+ byBranch.set(key, members);
515
+ });
516
+ const resolve = (target) => {
517
+ const own = byBranch.get(target) ?? [];
518
+ if (target === void 0) return {
519
+ indices: own,
520
+ shallow: false
521
+ };
522
+ const baseIndex = indexByBlock.get(target);
523
+ const forkPoint = baseIndex === void 0 ? void 0 : keyOf(items[baseIndex], KEY_FEED_FORK);
524
+ const forkIndex = forkPoint === void 0 ? void 0 : indexByBlock.get(forkPoint);
525
+ if (baseIndex === void 0 || forkIndex === void 0 || forkIndex >= baseIndex) return {
526
+ indices: own,
527
+ shallow: true
528
+ };
529
+ const parent = resolve(getBranch(items[forkIndex]));
530
+ return {
531
+ indices: [...parent.indices.filter((index) => index <= forkIndex), ...own],
532
+ shallow: parent.shallow
533
+ };
534
+ };
535
+ const { indices, shallow } = resolve(branch);
536
+ return {
537
+ items: indices.map((index) => items[index]),
538
+ shallow
539
+ };
540
+ };
541
+ /**
542
+ * Walks a feed along the path from the root branch to `branch`, in local order: a wrapper of the
543
+ * walk query, which reads the same as
544
+ *
545
+ * ```ts
546
+ * Database.query(
547
+ * Query.select(Filter.and(filter, Filter.feedCursor({ begin, positions: 'local' })))
548
+ * .from(Scope.feed(feedUri, { walk: { branch, forks } }))
549
+ * .orderBy(Order.natural(order))
550
+ * .limit(limit),
551
+ * );
552
+ * ```
553
+ *
554
+ * A forward walk gives each branch on the path up to the fork point of the next; a backward walk
555
+ * goes from `begin` (or the head of `branch`) back to the root base. Each item comes once, at the place
556
+ * of its first block on the path, with the content of its latest one. Resume with {@link getLocalCursor}
557
+ * of the last item of a page.
558
+ *
559
+ * @performance O(1) to build; a page reads every block of the path.
560
+ */
561
+ var walk = (feed$1, filter, options = {}) => {
562
+ const feedUri = getFeedUri(feed$1);
563
+ invariant(feedUri, "Feed must be stored in the database before accessing its contents", {
564
+ "~LogMeta": "~LogMeta",
565
+ F: __dxlog_file,
566
+ L: 767,
567
+ S: void 0,
568
+ A: ["feedUri", "'Feed must be stored in the database before accessing its contents'"]
569
+ });
570
+ const select$1 = options.begin === void 0 ? filter : and(filter, feedCursor({
571
+ begin: options.begin,
572
+ positions: "local"
573
+ }));
574
+ const query = select(select$1).from(feed(feedUri.toString(), { walk: {
575
+ branch: options.branch,
576
+ forks: options.forks
577
+ } })).orderBy(natural(options.order ?? "asc"));
578
+ return query$1(options.limit === void 0 ? query : query.limit(options.limit));
579
+ };
580
+ /**
313
581
  * Creates a reactive query over items in a feed.
314
582
  *
315
583
  * Returns a {@link QueryResult.QueryResultEffect}: yielding it produces a subscribable
@@ -338,17 +606,17 @@ var history = (items, options) => {
338
606
  *
339
607
  * @performance O(1) to build; the result is lazy, so nothing executes until read.
340
608
  */
341
- var query = Function.dual(2, (feed$1, queryOrFilter) => {
342
- const feedUri = getFeedUri(feed$1);
609
+ var query = Function.dual((args) => args.length >= 2, (feed$2, queryOrFilter, options) => {
610
+ const feedUri = getFeedUri(feed$2);
343
611
  invariant(feedUri, "Feed must be stored in the database before accessing its contents", {
344
612
  "~LogMeta": "~LogMeta",
345
613
  F: __dxlog_file,
346
- L: 492,
614
+ L: 829,
347
615
  S: void 0,
348
616
  A: ["feedUri", "'Feed must be stored in the database before accessing its contents'"]
349
617
  });
350
618
  const query = is(queryOrFilter) ? queryOrFilter : select(queryOrFilter);
351
- return query$1(query.from(feed(feedUri.toString())));
619
+ return query$1(query.from(feed(feedUri.toString(), { branches: options?.branches })));
352
620
  });
353
621
  /**
354
622
  * Syncs the feed with the server.
@@ -374,18 +642,44 @@ var sync = (feed, options) => Service.pipe(Effect.flatMap(({ db }) => Effect.pro
374
642
  */
375
643
  var getSyncState = (feed) => Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.getFeedSyncState(feed)))).pipe(Effect.withSpan("Feed.getSyncState"), withSpaceId);
376
644
  /**
377
- * Sets the local retention policy for a feed.
378
- * Currently stubbed — feeds do not yet support retention.
645
+ * Sets the feed's indexing options on the feed object, in one change.
646
+ *
647
+ * Returns once the change is applied locally; the store stops indexing on its own index pass, which
648
+ * may run on another device.
649
+ *
650
+ * @example
651
+ * ```ts
652
+ * yield* Feed.setIndexing(feed, { enabled: false });
653
+ * ```
654
+ *
655
+ * @performance O(1); one object change.
656
+ */
657
+ var setIndexing = (feed, options) => Schema.decodeUnknownEffect(IndexingOptions)(options).pipe(Effect.map((indexing) => update(feed, (feed) => {
658
+ feed.indexing = indexing;
659
+ })), Effect.asVoid, Effect.withSpan("Feed.setIndexing"));
660
+ /**
661
+ * Sets the feed's retention options on the feed object, in one change.
662
+ *
663
+ * Fails with the schema error, leaving the object unchanged, when `maxLength` is not an integer of
664
+ * at least 1 or `maxAge` is not a positive, finite duration. Returns once the change is applied
665
+ * locally; the store trims on its own index pass, which may run on another device.
379
666
  *
380
667
  * @example
381
668
  * ```ts
382
- * yield* Feed.setRetention(feed, { count: 1000 });
669
+ * yield* Feed.setRetention(feed, { maxLength: 1000, maxAge: Duration.days(7) });
383
670
  * ```
384
671
  *
385
- * @performance O(1); currently a no-op.
672
+ * @performance O(1); one object change.
386
673
  */
387
- var setRetention = (_feed, _options) => Effect.void;
674
+ var setRetention = (feed, options) => Schema.decodeUnknownEffect(RetentionOptions)({
675
+ ...options.maxLength !== void 0 ? { maxLength: options.maxLength } : {},
676
+ ...options.maxAge !== void 0 ? { maxAge: durationToMillis(options.maxAge) } : {}
677
+ }).pipe(Effect.map((retention) => update(feed, (feed) => {
678
+ feed.retention = retention;
679
+ })), Effect.asVoid, Effect.withSpan("Feed.setRetention"));
680
+ /** An unparseable duration maps to NaN so the schema, not this conversion, reports it. */
681
+ var durationToMillis = (input) => Duration.fromInput(input).pipe(Option.map(Duration.toMillis), Option.getOrElse(() => NaN));
388
682
  //#endregion
389
- export { sync as S, make as _, Feed_exports as a, setParent as b, START as c, getFeedUri as d, getParent as f, layer as g, history as h, Feed as i, append as l, getSyncState as m, Cursor as n, PARENT_KEY as o, getPosition as p, CursorAnnotation as r, POSITION_KEY as s, ContextFeedService as t, getCursor as u, query as v, setRetention as x, remove as y };
683
+ export { layer as A, walk as B, getLocalCursor as C, getSyncState as D, getPredecessor as E, setBranch as F, setIndexing as I, setParent as L, query as M, readBranch as N, history as O, remove as P, setRetention as R, getFeedUri as S, getPosition as T, branchKey as _, CursorAnnotation as a, getBranch as b, Feed_exports as c, Namespace as d, PARENT_KEY as f, append as g, START as h, Cursor as i, make as j, isFork as k, IndexingOptions as l, RetentionOptions as m, BranchId as n, Feed as o, POSITION_KEY as p, ContextFeedService as r, FeedOptions as s, BLOCK_KEYS as t, LocalCursor as u, fork as v, getParent as w, getCursor as x, getBlockId as y, sync as z };
390
684
 
391
685
  //# sourceMappingURL=chunk-Feed.mjs.map