@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-Feed.mjs","names":["Type.makeObject","Annotation.make","Obj.make","Obj.getURI","Database.Origin","Database.withSpaceId","internal.getKeys","internal.foreignKey","feed","Query.is","Query.select","Database.query","Scope.feed"],"sources":["../../src/Feed.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { KEY_QUEUE_POSITION } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, EID, EntityId } from '@dxos/keys';\n\nimport * as Annotation from './Annotation.ts';\nimport * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as Filter from './Filter.ts';\nimport * as internal from './internal/index.ts';\nimport * as Obj from './Obj.ts';\nimport * as Query from './Query.ts';\nimport type * as QueryResult from './QueryResult.ts';\nimport * as Scope from './Scope.ts';\nimport * as Type from './Type.ts';\n\n/**\n * Runtime schema for a Feed object.\n *\n * @example\n * ```ts\n * const feed = Obj.make(Feed.Feed, { name: 'notifications', kind: 'org.dxos.plugin.notifications.v1' });\n * ```\n */\nexport class Feed extends Type.makeObject<Feed>(DXN.make('org.dxos.type.feed', '0.1.0'))(\n Schema.Struct({\n /** User-facing display name. */\n name: Schema.String.pipe(Schema.optional),\n\n /** Identifier for the feed's kind (e.g., plugin id). */\n kind: Schema.String.pipe(internal.FormInputAnnotation.set(false), Schema.optional),\n\n /**\n * Feed namespace.\n * Controls how feed data is stored and replicated.\n * - `data`: Data feed (default).\n * - `trace`: Trace feed.\n */\n namespace: Schema.optional(Schema.Literals(['data', 'trace'])),\n\n /**\n * Earliest item a pending rewind discards — set when a soft fork is decided but not yet expressed,\n * because the writer may be a different process than the one that decided it.\n *\n * Stored as the first *discarded* item rather than the new parent so that rewinding to the very\n * first item needs no sentinel: nothing precedes it, so the continuation simply starts a new line.\n * Readers show what precedes it; the next append parents to that and clears this.\n *\n * Transient intent, never a source of truth for history. The fork itself lives in item lineage\n * (see {@link PARENT_KEY}), which is what {@link history} walks and what replicates in a defined\n * order relative to the blocks.\n */\n rewindFrom: Schema.optional(Obj.ID.pipe(internal.FormInputAnnotation.set(false))),\n }).pipe(Annotation.IconAnnotation.set({ icon: 'ph--rows--regular', hue: 'yellow' })),\n) {}\n\n//\n// Types\n//\n\n/**\n * Opaque position of a feed item — the insertion id the position authority assigned its block,\n * as read from an item with {@link getCursor}. Ordering is the feed's append order; a reader\n * resumes by passing the last cursor it processed to {@link query}.\n */\nexport const Cursor = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/Cursor'));\nexport type Cursor = Schema.Schema.Type<typeof Cursor>;\n\n/**\n * Annotation holding a reader's position in a feed — the cursor it has consumed up to.\n *\n * An annotation rather than a `@meta` foreign key: a key identifies the same entity in another\n * system, which a checkpoint is not.\n *\n * @example\n * ```ts\n * const cursor = Annotation.get(reader, Feed.CursorAnnotation).pipe(Option.getOrElse(() => Feed.START));\n * Obj.update(reader, (reader) => Annotation.set(reader, Feed.CursorAnnotation, Feed.getCursor(item)!));\n * ```\n */\nexport const CursorAnnotation: Annotation.Annotation<Cursor> = Annotation.make({\n id: 'org.dxos.annotation.feed-cursor',\n schema: Cursor,\n});\n\n/**\n * Sentinel cursor preceding every item — \"read from the beginning\".\n *\n * A sentinel rather than `undefined` so a stored checkpoint is always a `Cursor`: a reader that has\n * processed nothing yet holds this, and the same code path resumes it as resumes a live cursor.\n */\nexport const START: Cursor = Cursor.make('');\n\n/**\n * Retention options for a feed.\n *\n * Live feed objects persist every `Obj.update` as a whole-object re-append reusing the object's id\n * (see `EchoFeedCodec.encode`), so superseded blocks accumulate indefinitely — retention/compaction\n * of those superseded blocks (driven by these options, once implemented) is the reclaim mechanism.\n * TODO(wittjosiah): Implement when feed retention is supported (see `setRetention` below and\n * `FeedStore.appendLocal`).\n */\nexport interface RetentionOptions {\n /** Retain items after this cursor position. */\n // TODO(wittjosiah): Use FeedCursor from @dxos/feed?\n cursor?: string;\n}\n\n/**\n * Options for {@link append}.\n */\nexport interface AppendOptions {\n /**\n * Explicit lineage parent for the appended items — the soft-fork point.\n * Applies to the first item only; the rest of the batch chain implicitly in append order.\n */\n parent?: Entity.Unknown | Entity.Snapshot | EntityId;\n}\n\n/**\n * Options for {@link history}.\n */\nexport interface HistoryOptions {\n /**\n * Item to walk the history from, as git's `HEAD` selects which commits are reachable.\n * Defaults to the last item, so the most recently appended line of items wins.\n */\n head?: Entity.Unknown | Entity.Snapshot | EntityId;\n}\n\n/**\n * The items reachable from a head by following lineage — a feed's equivalent of\n * `git log --first-parent`.\n */\nexport interface History<T> {\n /** The reachable items, in append order. */\n items: T[];\n /**\n * A parent was referenced but could not be resolved, so the walk stopped at a boundary and\n * earlier history is missing — the same condition as a git shallow clone.\n */\n shallow: boolean;\n}\n\n/**\n * Sync options for a feed.\n */\nexport interface SyncOptions {\n /** Push local changes to the server. Defaults to true. */\n shouldPush?: boolean;\n /** Pull remote changes from the server. Defaults to true. */\n shouldPull?: boolean;\n}\n\n/**\n * Queue replication backlog for a feed namespace.\n * `0` / `0` means caught up on pull and push.\n */\nexport interface SyncState {\n /** Blocks still to pull from remote. */\n blocksToPull: number;\n /** Unpositioned blocks still to push to remote. */\n blocksToPush: number;\n /** Total blocks stored locally for the feed namespace. */\n totalBlocks: number;\n}\n\n/**\n * Effect service tag for injecting a Feed into effect operations.\n * Used to provide a specific feed to operations that operate on it without threading\n * the feed as an explicit parameter through every call site.\n */\nexport class ContextFeedService extends Context.Service<\n ContextFeedService,\n {\n readonly feed: Feed;\n }\n>()('@dxos/echo/Feed/ContextFeedService') {}\n\n/**\n * Provides {@link ContextFeedService} so callers can scope operations to `feed`.\n *\n * @performance O(1).\n */\nexport const layer = (feed: Feed) => Layer.succeed(ContextFeedService, { feed });\n\n//\n// Factory\n//\n\n/**\n * Creates a new feed object.\n *\n * @example\n * ```ts\n * const feed = Feed.make({ name: 'notifications', kind: 'org.dxos.plugin.notifications.v1' });\n * ```\n *\n * @performance O(1); allocates an in-memory feed object.\n */\n// TODO(wittjosiah): How to control the feed namespace (data/trace)? Why do feeds have namespaces?\nexport const make = (props: Obj.MakeProps<typeof Feed> = {}): Feed => Obj.make(Feed, props);\n\n/**\n * Returns the feed object's EID when the feed is stored in a space.\n *\n * Private-ish and on track to be removed — prefer resolving feed scopes via higher-level APIs\n * (e.g. `Feed.query`) rather than threading the raw queue URI. Used internally by the feed service\n * layer.\n *\n * @performance O(1) URI parse.\n */\n// TODO(dmaretskyi): Remove — private-ish, prefer higher-level feed-scope APIs.\nexport const getFeedUri = (feed: Feed): EID.EID | undefined => EID.tryParse(Obj.getURI(feed));\n\n//\n// Operations\n//\n\n/**\n * Appends items to a feed.\n *\n * Pass `options.parent` to soft-fork the feed: the first appended item continues from that item\n * rather than from the feed's tip, so everything appended between the two becomes unreachable from\n * {@link history}. Nothing is removed from the log.\n *\n * @example\n * ```ts\n * yield* Feed.append(feed, [Obj.make(Notification, { title: 'Hello' })]);\n *\n * // Continue from an earlier item, leaving what followed it unreachable.\n * yield* Feed.append(feed, [Obj.make(Notification, { title: 'Take two' })], { parent: earlier });\n * ```\n *\n * @performance Async; O(n) in items encoded and appended in one batch.\n */\nexport const append = (\n feed: Feed,\n items: Entity.Unknown[],\n options?: AppendOptions,\n): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.flatMap(Database.Origin, (origin) =>\n Effect.promise(() => {\n if (options?.parent !== undefined && items.length > 0) {\n setParent(items[0], options.parent);\n }\n return db.appendToFeed(feed, items, { origin });\n }),\n ),\n ),\n ).pipe(Effect.withSpan('Feed.append'), Database.withSpaceId);\n\n/**\n * Removes items from a feed.\n *\n * @example\n * ```ts\n * yield* Feed.remove(feed, [item]);\n * ```\n *\n * @performance Async; O(n) in items, deleted by id in one batch.\n */\n// TODO(dmaretskyi): Should we allow snapshots here? - what does it mean to remove a snapshot?\nexport const remove = (\n feed: Feed,\n items: (Entity.Unknown | Obj.Snapshot)[],\n): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.promise(() =>\n db.removeFeedItemsByIds(\n feed,\n items.map((item) => item.id),\n ),\n ),\n ),\n ).pipe(Effect.withSpan('Feed.remove'), Database.withSpaceId);\n\n//\n// Lineage (soft fork)\n//\n\n/**\n * Foreign-key source for an item's explicit lineage parent within a feed.\n *\n * Lineage is carried in item `@meta` because feed items are arbitrary ECHO objects that the feed\n * does not own and cannot extend; `KEY_QUEUE_POSITION` rides along with feed blocks the same way.\n */\nexport const PARENT_KEY = 'org.dxos.key.feed-parent';\n\n/**\n * Tri-state read of the lineage key, distinguishing an absent key from a present but malformed one.\n * A replicated id that does not parse must not read as \"no parent\" — that would resolve a fork as\n * an implicit continuation and silently expose the items it abandoned.\n */\nconst readParent = (item: Entity.Unknown | Entity.Snapshot): { present: boolean; id?: EntityId } => {\n const id = internal.getKeys(item, PARENT_KEY).at(0)?.id;\n if (id === undefined) {\n return { present: false };\n }\n return EntityId.isValid(id) ? { present: true, id } : { present: true };\n};\n\n/**\n * Foreign-key source for the global position a position authority assigned a feed item.\n * Exposed alongside {@link getPosition} so callers can stamp or inspect it without reaching for\n * `@dxos/protocols`.\n */\nexport const POSITION_KEY = KEY_QUEUE_POSITION;\n\n/**\n * The global position a feed item was assigned, or `+Infinity` when it has none — a block written\n * locally and not yet acknowledged, which sorts last because it is the newest.\n *\n * Use this to put items into append order before calling {@link history}: a query returns an unordered\n * set, and `created` is a wall clock that peers do not agree on.\n *\n * @example\n * ```ts\n * const inAppendOrder = Array.sort(messages, Order.mapInput(Order.number, Feed.getPosition));\n * const { items } = Feed.history(inAppendOrder);\n * ```\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getPosition = (item: Entity.Unknown | Entity.Snapshot): number => {\n const key = internal.getKeys(item, KEY_QUEUE_POSITION).at(0)?.id;\n const position = key !== undefined ? Number(key) : Number.NaN;\n return Number.isNaN(position) ? Number.POSITIVE_INFINITY : position;\n};\n\n/**\n * The item's {@link Cursor}, or `undefined` when it has none — a block written locally and not yet\n * acknowledged by the position authority. Pass it to {@link query} to resume after this item.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getCursor = (item: Entity.Unknown | Entity.Snapshot): Cursor | undefined => {\n const key = internal.getKeys(item, KEY_QUEUE_POSITION).at(0)?.id;\n return key !== undefined ? Cursor.make(key) : undefined;\n};\n\n/**\n * Returns an item's explicit lineage parent, or `undefined` when it continues from the item that\n * precedes it in append order (the default for every feed).\n *\n * Also `undefined` for a malformed stored id; {@link history} tells the two apart and reports\n * a malformed parent as truncation.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getParent = (item: Entity.Unknown | Entity.Snapshot): EntityId | undefined => readParent(item).id;\n\n/**\n * Sets (or, with `undefined`, clears) an item's explicit lineage parent.\n * Call before appending the item; {@link append}'s `parent` option does this for you.\n *\n * @performance O(k) in the item foreign-key count, applied in one change.\n */\nexport const setParent = (\n item: Entity.Unknown,\n parent: Entity.Unknown | Entity.Snapshot | EntityId | undefined,\n): void => {\n internal.change(item, (mutable) => {\n internal.deleteKeys(mutable, PARENT_KEY);\n if (parent !== undefined) {\n const id = typeof parent === 'string' ? parent : parent.id;\n internal.getMetaChecked(mutable).keys.push(internal.foreignKey(PARENT_KEY, id));\n }\n });\n};\n\n/**\n * Returns the items reachable from a head by following lineage — a feed's `git log --first-parent`.\n *\n * Walks backwards from the head: an item with an explicit lineage parent jumps to that item, leaving\n * everything appended in between unreachable; an item without one steps to its predecessor. So a\n * feed appended as `M1, M2, M3, M4, M5(M3)` yields `M1, M2, M3, M5`, with `M4` unreachable but still\n * present in the log — the log is the object store, this function is what HEAD reaches.\n *\n * `items` must be in **append order** — the walk is positional, and pre-sorting by a wall-clock\n * field such as `created` would corrupt it. Lineage is resolved over exactly the list passed in, so\n * a parent excluded by the caller's filter reads as absent (`shallow`), same as one that has not\n * replicated yet or whose stored id does not parse.\n *\n * @example\n * ```ts\n * const messages = yield* Feed.query(feed, Filter.type(Message.Message)).run;\n * const { items, shallow } = Feed.history(messages);\n * ```\n *\n * @performance O(n) in items; one pass to index ids and one backwards walk.\n */\nexport const history = <T extends Entity.Unknown | Entity.Snapshot>(\n items: readonly T[],\n options?: HistoryOptions,\n): History<T> => {\n const indexById = new Map<EntityId, number>();\n items.forEach((item, index) => indexById.set(item.id, index));\n\n const head = options?.head;\n const headIndex = head === undefined ? items.length - 1 : indexById.get(typeof head === 'string' ? head : head.id);\n if (headIndex === undefined) {\n return { items: [], shallow: true };\n }\n\n let cursor = headIndex;\n const reachable: T[] = [];\n let shallow = false;\n while (cursor >= 0) {\n const item = items[cursor];\n reachable.push(item);\n\n const parent = readParent(item);\n if (!parent.present) {\n cursor -= 1;\n continue;\n }\n if (parent.id === undefined) {\n // Key present but unparseable — a fork whose target cannot be identified, so stop rather than\n // fall through to the predecessor and make what this item superseded reachable again.\n shallow = true;\n break;\n }\n\n // A parent at or after its child is a cycle or a forward reference (possible with arbitrary\n // multi-writer data); requiring the cursor to strictly decrease also guarantees termination.\n const parentIndex = indexById.get(parent.id);\n if (parentIndex === undefined || parentIndex >= cursor) {\n shallow = true;\n break;\n }\n cursor = parentIndex;\n }\n\n return { items: reachable.reverse(), shallow };\n};\n\n/**\n * Creates a reactive query over items in a feed.\n *\n * Returns a {@link QueryResult.QueryResultEffect}: yielding it produces a subscribable\n * `QueryResult`, while its `.run` / `.first` shorthands execute the query once. This mirrors\n * `Database.query` so feed and database queries chain identically.\n *\n * Supports both data-first and data-last (curried) forms; the latter composes with `pipe`.\n *\n * In non-Effect code, query a feed directly through the database with a feed scope:\n * `db.query(Query.select(filter).from(Scope.feed(Feed.getFeedUri(feed))))`.\n *\n * @example\n * ```ts\n * const result = yield* Feed.query(feed, Filter.type(Person));\n * result.subscribe(...);\n *\n * const objects = yield* Feed.query(feed, Filter.type(Person)).run;\n * const object = yield* Feed.query(feed, Filter.type(Person)).first;\n *\n * // Data-last (curried) form composes with `pipe`:\n * const objects = yield* pipe(feed, Feed.query(Filter.type(Person))).run;\n *\n * // Resume after a cursor, reading a bounded page of what is new:\n * const objects = yield* Feed.query(feed, Query.select(Filter.feedCursor(cursor)).limit(10)).run;\n * ```\n *\n * @performance O(1) to build; the result is lazy, so nothing executes until read.\n */\nexport const query: {\n <Q extends Query.Any>(feed: Feed, query: Q): QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;\n <F extends Filter.Any>(feed: Feed, filter: F): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;\n <Q extends Query.Any>(\n query: Q,\n ): (feed: Feed) => QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;\n <F extends Filter.Any>(\n filter: F,\n ): (feed: Feed) => QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;\n} = Function.dual(2, (feed: Feed, queryOrFilter: Query.Any | Filter.Any) => {\n const feedUri = getFeedUri(feed);\n invariant(feedUri, 'Feed must be stored in the database before accessing its contents');\n const query = Query.is(queryOrFilter) ? queryOrFilter : Query.select(queryOrFilter);\n return Database.query(query.from(Scope.feed(feedUri.toString())));\n});\n\n/**\n * Syncs the feed with the server.\n *\n * @example\n * ```ts\n * yield* Feed.sync(feed);\n * yield* Feed.sync(feed, { shouldPush: false });\n * ```\n *\n * @performance Async; network-bound, proportional to the replication backlog.\n */\nexport const sync = (feed: Feed, options?: SyncOptions): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.syncFeed(feed, options)))).pipe(\n Effect.withSpan('Feed.sync'),\n Database.withSpaceId,\n );\n\n/**\n * Returns the feed's replication backlog for its namespace.\n *\n * @example\n * ```ts\n * const { blocksToPull, blocksToPush } = yield* Feed.getSyncState(feed);\n * ```\n *\n * @performance Async; one service round trip.\n */\nexport const getSyncState = (feed: Feed): Effect.Effect<SyncState, never, Database.Service> =>\n Database.Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.getFeedSyncState(feed)))).pipe(\n Effect.withSpan('Feed.getSyncState'),\n Database.withSpaceId,\n );\n\n/**\n * Sets the local retention policy for a feed.\n * Currently stubbed — feeds do not yet support retention.\n *\n * @example\n * ```ts\n * yield* Feed.setRetention(feed, { count: 1000 });\n * ```\n *\n * @performance O(1); currently a no-op.\n */\n// TODO(dmaretskyi): Implement when feed retention is supported.\nexport const setRetention = (_feed: Feed, _options: RetentionOptions): Effect.Effect<void, never, Database.Service> =>\n Effect.void;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,OAAb,cAA0BA,WAAsB,IAAI,KAAK,sBAAsB,OAAO,CAAC,CAAC,CACtF,OAAO,OAAO;;CAEZ,MAAM,OAAO,OAAO,KAAK,OAAO,QAAQ;;CAGxC,MAAM,OAAO,OAAO,KAAA,oBAAkC,IAAI,KAAK,GAAG,OAAO,QAAQ;;;;;;;CAQjF,WAAW,OAAO,SAAS,OAAO,SAAS,CAAC,QAAQ,OAAO,CAAC,CAAC;;;;;;;;;;;;;CAc7D,YAAY,OAAO,SAAA,GAAgB,KAAA,oBAAkC,IAAI,KAAK,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC,KAAA,eAA+B,IAAI;CAAE,MAAM;CAAqB,KAAK;AAAS,CAAC,CAAC,CACrF,CAAC,CAAC,CAAC;;;;;;AAWH,IAAa,SAAS,OAAO,OAAO,KAAK,OAAO,MAAM,wBAAwB,CAAC;;;;;;;;;;;;;AAe/E,IAAa,mBAAkDC,OAAgB;CAC7E,IAAI;CACJ,QAAQ;AACV,CAAC;;;;;;;AAQD,IAAa,QAAgB,OAAO,KAAK,EAAE;;;;;;AAiF3C,IAAa,qBAAb,cAAwC,QAAQ,QAK9C,CAAC,CAAC,oCAAoC,CAAC,CAAC,CAAC;;;;;;AAO3C,IAAa,SAAS,SAAe,MAAM,QAAQ,oBAAoB,EAAE,KAAK,CAAC;;;;;;;;;;;AAiB/E,IAAa,QAAQ,QAAoC,CAAC,MAAYC,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;EAAG;CAAQ;AAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,QAST,SAAS,KAAK,IAAI,QAAY,kBAA0C;CAC1E,MAAM,UAAU,WAAWC,MAAI;CAC/B,UAAU,SAAS,qEAAkE;EAAA,YAAA;EAAA,GAAA;EAAA,GAAA;EAAA,GAAA,KAAA;EAAA,GAAA,CAAA,WAAA,qEAAA;CAAA,CAAC;CACtF,MAAM,QAAQC,GAAS,aAAa,IAAI,gBAAgBC,OAAa,aAAa;CAClF,OAAOC,QAAe,MAAM,KAAKC,KAAW,QAAQ,SAAS,CAAC,CAAC,CAAC;AAClE,CAAC;;;;;;;;;;;;AAaD,IAAa,QAAQ,MAAY,YAAA,QACd,KAAK,OAAO,SAAS,EAAE,SAAS,OAAO,cAAc,GAAG,SAAS,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,KAClG,OAAO,SAAS,WAAW,GAC3BP,WACF;;;;;;;;;;;AAYF,IAAa,gBAAgB,SAAA,QACV,KAAK,OAAO,SAAS,EAAE,SAAS,OAAO,cAAc,GAAG,iBAAiB,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KACjG,OAAO,SAAS,mBAAmB,GACnCA,WACF;;;;;;;;;;;;AAcF,IAAa,gBAAgB,OAAa,aACxC,OAAO"}
1
+ {"version":3,"file":"chunk-Feed.mjs","names":["Type.makeObject","Annotation.make","Obj.make","Obj.getURI","Database.Origin","internal.change","Database.withSpaceId","internal.getKeys","internal.foreignKey","internal.getFeedBlockKeys","Database.Service","feed","select","Filter.and","Filter.feedCursor","Query.select","Scope.feed","Order.natural","Database.query","Query.is","Obj.update"],"sources":["../../src/Feed.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Duration from 'effect/Duration';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\n\nimport { KEY_FEED_BLOCK, KEY_FEED_BRANCH, KEY_FEED_FORK, KEY_FEED_PREV, KEY_QUEUE_POSITION } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, EID, EntityId } from '@dxos/keys';\n\nimport * as Annotation from './Annotation.ts';\nimport * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport * as Filter from './Filter.ts';\nimport * as internal from './internal/index.ts';\nimport * as Obj from './Obj.ts';\nimport * as Order from './Order.ts';\nimport * as Query from './Query.ts';\nimport type * as QueryResult from './QueryResult.ts';\nimport * as Scope from './Scope.ts';\nimport * as Type from './Type.ts';\n\n//\n// Options\n//\n\n/** The namespaces a feed can store its data under; `data` is the default. */\nexport const Namespace = Schema.Literals(['data', 'trace']);\nexport type Namespace = Schema.Schema.Type<typeof Namespace>;\n\n/**\n * Indexing options for a feed. Absent on a feed means indexing is enabled.\n *\n * A struct rather than a bare boolean so later options (which indexes to build) need no migration.\n */\nexport const IndexingOptions = Schema.Struct({\n /** When false, the feed's items are not indexed at all; there is no partial mode. */\n enabled: Schema.Boolean,\n /**\n * Which branches the index holds: `main` (the default) or `all`. There is no selected subset.\n * A feed whose items mutate objects keeps `main`; a feed of messages from people can index `all`.\n */\n mode: Schema.optional(Schema.Literals(['all', 'main'])),\n});\nexport type IndexingOptions = Schema.Schema.Type<typeof IndexingOptions>;\n\n/**\n * Retention options for a feed. With both limits set, an item is dropped when it breaks either;\n * an empty struct (or no `retention` on the feed) trims nothing.\n *\n * Live feed objects persist every `Obj.update` as a whole-object re-append, so superseded blocks are\n * trimmed by these limits like any other block; retention does not compact them.\n */\nexport const RetentionOptions = Schema.Struct({\n /** Maximum number of items kept; the oldest beyond it are dropped. */\n maxLength: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(1)), Schema.optional),\n\n /**\n * Maximum age of an item in milliseconds, measured from its append timestamp.\n * Milliseconds rather than a `Duration` because ECHO stores plain JSON; {@link setRetention} converts.\n */\n maxAge: Schema.Finite.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.optional),\n});\nexport type RetentionOptions = Schema.Schema.Type<typeof RetentionOptions>;\n\n/**\n * A feed's indexing and retention options, as the indexer carries them down to the feed store.\n */\nexport const FeedOptions = Schema.Struct({\n indexing: Schema.optional(IndexingOptions),\n retention: Schema.optional(RetentionOptions),\n});\nexport type FeedOptions = Schema.Schema.Type<typeof FeedOptions>;\n\n/**\n * Runtime schema for a Feed object.\n *\n * @example\n * ```ts\n * const feed = Obj.make(Feed.Feed, { name: 'notifications', kind: 'org.dxos.plugin.notifications.v1' });\n * ```\n */\nexport class Feed extends Type.makeObject<Feed>(DXN.make('org.dxos.type.feed', '0.1.0'))(\n Schema.Struct({\n /** User-facing display name. */\n name: Schema.String.pipe(Schema.optional),\n\n /** Identifier for the feed's kind (e.g., plugin id). */\n kind: Schema.String.pipe(internal.FormInputAnnotation.set(false), Schema.optional),\n\n /**\n * Feed namespace.\n * Controls how feed data is stored and replicated.\n * - `data`: Data feed (default).\n * - `trace`: Trace feed.\n */\n namespace: Schema.optional(Namespace),\n\n /**\n * Earliest item a pending rewind discards — set when a soft fork is decided but not yet expressed,\n * because the writer may be a different process than the one that decided it.\n *\n * Stored as the first *discarded* item rather than the new parent so that rewinding to the very\n * first item needs no sentinel: nothing precedes it, so the continuation simply starts a new line.\n * Readers show what precedes it; the next append parents to that and clears this.\n *\n * Transient intent, never a source of truth for history. The fork itself lives in item lineage\n * (see {@link PARENT_KEY}), which is what {@link history} walks and what replicates in a defined\n * order relative to the blocks.\n */\n rewindFrom: Schema.optional(Obj.ID.pipe(internal.FormInputAnnotation.set(false))),\n\n /** Indexing options; absent means indexing is enabled. Set with {@link setIndexing}. */\n indexing: IndexingOptions.pipe(internal.FormInputAnnotation.set(false), Schema.optional),\n\n /** Retention options; absent means nothing is trimmed. Set with {@link setRetention}. */\n retention: RetentionOptions.pipe(internal.FormInputAnnotation.set(false), Schema.optional),\n }).pipe(Annotation.IconAnnotation.set({ icon: 'ph--rows--regular', hue: 'yellow' })),\n) {}\n\n//\n// Types\n//\n\n/**\n * Opaque position of a feed item — the insertion id the position authority assigned its block,\n * as read from an item with {@link getCursor}. Ordering is the feed's append order; a reader\n * resumes by passing the last cursor it processed to {@link query}.\n */\nexport const Cursor = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/Cursor'));\nexport type Cursor = Schema.Schema.Type<typeof Cursor>;\n\n/**\n * Annotation holding a reader's position in a feed — the cursor it has consumed up to.\n *\n * An annotation rather than a `@meta` foreign key: a key identifies the same entity in another\n * system, which a checkpoint is not.\n *\n * @example\n * ```ts\n * const cursor = Annotation.get(reader, Feed.CursorAnnotation).pipe(Option.getOrElse(() => Feed.START));\n * Obj.update(reader, (reader) => Annotation.set(reader, Feed.CursorAnnotation, Feed.getCursor(item)!));\n * ```\n */\nexport const CursorAnnotation: Annotation.Annotation<Cursor> = Annotation.make({\n id: 'org.dxos.annotation.feed-cursor',\n schema: Cursor,\n});\n\n/**\n * Sentinel cursor preceding every item — \"read from the beginning\".\n *\n * A sentinel rather than `undefined` so a stored checkpoint is always a `Cursor`: a reader that has\n * processed nothing yet holds this, and the same code path resumes it as resumes a live cursor.\n */\nexport const START: Cursor = Cursor.make('');\n\n/**\n * Input to {@link setRetention}: {@link RetentionOptions} with `maxAge` as any Duration input.\n */\nexport interface SetRetentionOptions {\n /** Maximum number of items kept; an integer of at least 1. */\n maxLength?: number;\n /** Maximum age of an item, measured from its append timestamp; must be positive and finite. */\n maxAge?: Duration.Input;\n}\n\n/**\n * Options for {@link append}.\n */\nexport interface AppendOptions {\n /**\n * Explicit lineage parent for the appended items — the soft-fork point.\n * Applies to the first item only; the rest of the batch chain implicitly in append order.\n */\n parent?: Entity.Unknown | Entity.Snapshot | EntityId;\n\n /** The branch the appended items continue; omit for the root branch. */\n branch?: BranchId;\n}\n\n/**\n * Options for {@link fork}.\n */\nexport interface ForkOptions {\n /**\n * The fork point: the item (at the block it was read from) or the block id that the new branch\n * continues from. Its branch is the parent of the new branch.\n */\n at: Entity.Unknown | Entity.Snapshot | BlockId;\n}\n\n/**\n * Options for {@link walk}.\n */\nexport interface WalkOptions {\n /**\n * The branch the walk ends on; omit for the root branch, or for the branch of `begin` on a backward walk.\n * `'all'` walks every branch of the feed in local order, each item once at its first block.\n */\n branch?: BranchId | null | 'all';\n /** Starts after this item; read it off the last item of a page with {@link getLocalCursor}. */\n begin?: LocalCursor;\n /** Also gives the base item of each branch that forks at a block the walk gives. */\n forks?: boolean;\n /** `asc` walks from the root base to the branch; `desc` walks back to the root base. Defaults to `asc`. */\n order?: 'asc' | 'desc';\n /** The page size. */\n limit?: number;\n}\n\n/**\n * Options for {@link query}.\n */\nexport interface QueryOptions {\n /**\n * Branches to read: branch ids, `null` for the main branch, or `'all'`. Defaults to the main branch only,\n * so a private branch never reaches a reader that did not ask for it. Read a branch's ancestors with\n * `'all'` (or the branches on its path) and pass the items to {@link readBranch}.\n */\n branches?: Scope.FeedScopeOptions['branches'];\n}\n\n/**\n * Options for {@link history}.\n */\nexport interface HistoryOptions {\n /**\n * Item to walk the history from, as git's `HEAD` selects which commits are reachable.\n * Defaults to the last item, so the most recently appended line of items wins.\n */\n head?: Entity.Unknown | Entity.Snapshot | EntityId;\n}\n\n/**\n * The items reachable from a head by following lineage — a feed's equivalent of\n * `git log --first-parent`.\n */\nexport interface History<T> {\n /** The reachable items, in append order. */\n items: T[];\n /**\n * A parent was referenced but could not be resolved, so the walk stopped at a boundary and\n * earlier history is missing — the same condition as a git shallow clone.\n */\n shallow: boolean;\n}\n\n/**\n * Sync options for a feed.\n */\nexport interface SyncOptions {\n /** Push local changes to the server. Defaults to true. */\n shouldPush?: boolean;\n /** Pull remote changes from the server. Defaults to true. */\n shouldPull?: boolean;\n}\n\n/**\n * Queue replication backlog for a feed namespace.\n * `0` / `0` means caught up on pull and push.\n */\nexport interface SyncState {\n /** Blocks still to pull from remote. */\n blocksToPull: number;\n /** Unpositioned blocks still to push to remote. */\n blocksToPush: number;\n /** Total blocks stored locally for the feed namespace. */\n totalBlocks: number;\n}\n\n/**\n * Effect service tag for injecting a Feed into effect operations.\n * Used to provide a specific feed to operations that operate on it without threading\n * the feed as an explicit parameter through every call site.\n */\nexport class ContextFeedService extends Context.Service<\n ContextFeedService,\n {\n readonly feed: Feed;\n }\n>()('@dxos/echo/Feed/ContextFeedService') {}\n\n/**\n * Provides {@link ContextFeedService} so callers can scope operations to `feed`.\n *\n * @performance O(1).\n */\nexport const layer = (feed: Feed) => Layer.succeed(ContextFeedService, { feed });\n\n//\n// Factory\n//\n\n/**\n * Creates a new feed object.\n *\n * @example\n * ```ts\n * const feed = Feed.make({ name: 'notifications', kind: 'org.dxos.plugin.notifications.v1' });\n * ```\n *\n * @performance O(1); allocates an in-memory feed object.\n */\n// TODO(wittjosiah): How to control the feed namespace (data/trace)? Why do feeds have namespaces?\nexport const make = (props: Obj.MakeProps<typeof Feed> = {}): Feed => Obj.make(Feed, props);\n\n/**\n * Returns the feed object's EID when the feed is stored in a space.\n *\n * Private-ish and on track to be removed — prefer resolving feed scopes via higher-level APIs\n * (e.g. `Feed.query`) rather than threading the raw queue URI. Used internally by the feed service\n * layer.\n *\n * @performance O(1) URI parse.\n */\n// TODO(dmaretskyi): Remove — private-ish, prefer higher-level feed-scope APIs.\nexport const getFeedUri = (feed: Feed): EID.EID | undefined => EID.tryParse(Obj.getURI(feed));\n\n//\n// Operations\n//\n\n/**\n * Appends items to a feed.\n *\n * Pass `options.parent` to soft-fork the feed: the first appended item continues from that item\n * rather than from the feed's tip, so everything appended between the two becomes unreachable from\n * {@link history}. Nothing is removed from the log.\n *\n * @example\n * ```ts\n * yield* Feed.append(feed, [Obj.make(Notification, { title: 'Hello' })]);\n *\n * // Continue from an earlier item, leaving what followed it unreachable.\n * yield* Feed.append(feed, [Obj.make(Notification, { title: 'Take two' })], { parent: earlier });\n * ```\n *\n * @performance Async; O(n) in items encoded and appended in one batch.\n */\nexport const append = (\n feed: Feed,\n items: Entity.Unknown[],\n options?: AppendOptions,\n): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.flatMap(Database.Origin, (origin) =>\n Effect.promise(() => {\n if (options?.parent !== undefined && items.length > 0) {\n setParent(items[0], options.parent);\n }\n if (options?.branch !== undefined) {\n const branch = options.branch;\n items.forEach((item) => internal.change(item, (mutable) => setBranchKey(mutable, branch)));\n }\n return db.appendToFeed(feed, items, { origin });\n }),\n ),\n ),\n ).pipe(Effect.withSpan('Feed.append'), Database.withSpaceId);\n\n/**\n * Removes items from a feed.\n *\n * @example\n * ```ts\n * yield* Feed.remove(feed, [item]);\n * ```\n *\n * @performance Async; O(n) in items, deleted by id in one batch.\n */\n// TODO(dmaretskyi): Should we allow snapshots here? - what does it mean to remove a snapshot?\nexport const remove = (\n feed: Feed,\n items: (Entity.Unknown | Obj.Snapshot)[],\n): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.promise(() =>\n db.removeFeedItemsByIds(\n feed,\n items.map((item) => item.id),\n { branches: items.map((item) => getBranch(item) ?? null) },\n ),\n ),\n ),\n ).pipe(Effect.withSpan('Feed.remove'), Database.withSpaceId);\n\n//\n// Lineage (soft fork)\n//\n\n/**\n * Foreign-key source for an item's explicit lineage parent within a feed.\n *\n * Lineage is carried in item `@meta` because feed items are arbitrary ECHO objects that the feed\n * does not own and cannot extend; `KEY_QUEUE_POSITION` rides along with feed blocks the same way.\n */\nexport const PARENT_KEY = 'org.dxos.key.feed-parent';\n\n/**\n * Tri-state read of the lineage key, distinguishing an absent key from a present but malformed one.\n * A replicated id that does not parse must not read as \"no parent\" — that would resolve a fork as\n * an implicit continuation and silently expose the items it abandoned.\n */\nconst readParent = (item: Entity.Unknown | Entity.Snapshot): { present: boolean; id?: EntityId } => {\n const id = internal.getKeys(item, PARENT_KEY).at(0)?.id;\n if (id === undefined) {\n return { present: false };\n }\n return EntityId.isValid(id) ? { present: true, id } : { present: true };\n};\n\n/**\n * Foreign-key source for the global position a position authority assigned a feed item.\n * Exposed alongside {@link getPosition} so callers can stamp or inspect it without reaching for\n * `@dxos/protocols`.\n */\nexport const POSITION_KEY = KEY_QUEUE_POSITION;\n\n/**\n * The global position a feed item was assigned, or `+Infinity` when it has none — a block written\n * locally and not yet acknowledged, which sorts last because it is the newest.\n *\n * Use this to put items into append order before calling {@link history}: a query returns an unordered\n * set, and `created` is a wall clock that peers do not agree on.\n *\n * @example\n * ```ts\n * const inAppendOrder = Array.sort(messages, Order.mapInput(Order.number, Feed.getPosition));\n * const { items } = Feed.history(inAppendOrder);\n * ```\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getPosition = (item: Entity.Unknown | Entity.Snapshot): number => {\n const key = internal.getKeys(item, KEY_QUEUE_POSITION).at(0)?.id;\n const position = key !== undefined ? Number(key) : Number.NaN;\n return Number.isNaN(position) ? Number.POSITIVE_INFINITY : position;\n};\n\n/**\n * The item's {@link Cursor}, or `undefined` when it has none — a block written locally and not yet\n * acknowledged by the position authority. Pass it to {@link query} to resume after this item.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getCursor = (item: Entity.Unknown | Entity.Snapshot): Cursor | undefined => {\n const key = internal.getKeys(item, KEY_QUEUE_POSITION).at(0)?.id;\n return key !== undefined ? Cursor.make(key) : undefined;\n};\n\n/**\n * Returns an item's explicit lineage parent, or `undefined` when it continues from the item that\n * precedes it in append order (the default for every feed).\n *\n * Also `undefined` for a malformed stored id; {@link history} tells the two apart and reports\n * a malformed parent as truncation.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getParent = (item: Entity.Unknown | Entity.Snapshot): EntityId | undefined => readParent(item).id;\n\n/**\n * Sets (or, with `undefined`, clears) an item's explicit lineage parent.\n * Call before appending the item; {@link append}'s `parent` option does this for you.\n *\n * @performance O(k) in the item foreign-key count, applied in one change.\n */\nexport const setParent = (\n item: Entity.Unknown,\n parent: Entity.Unknown | Entity.Snapshot | EntityId | undefined,\n): void => {\n internal.change(item, (mutable) => {\n internal.deleteKeys(mutable, PARENT_KEY);\n if (parent !== undefined) {\n const id = typeof parent === 'string' ? parent : parent.id;\n internal.getMetaChecked(mutable).keys.push(internal.foreignKey(PARENT_KEY, id));\n }\n });\n};\n\n/**\n * Returns the items reachable from a head by following lineage — a feed's `git log --first-parent`.\n *\n * Walks backwards from the head: an item with an explicit lineage parent jumps to that item, leaving\n * everything appended in between unreachable; an item without one steps to its predecessor. So a\n * feed appended as `M1, M2, M3, M4, M5(M3)` yields `M1, M2, M3, M5`, with `M4` unreachable but still\n * present in the log — the log is the object store, this function is what HEAD reaches.\n *\n * `items` must be in **append order** — the walk is positional, and pre-sorting by a wall-clock\n * field such as `created` would corrupt it. Lineage is resolved over exactly the list passed in, so\n * a parent excluded by the caller's filter reads as absent (`shallow`), same as one that has not\n * replicated yet or whose stored id does not parse.\n *\n * @example\n * ```ts\n * const messages = yield* Feed.query(feed, Filter.type(Message.Message)).run;\n * const { items, shallow } = Feed.history(messages);\n * ```\n *\n * @performance O(n) in items; one pass to index ids and one backwards walk.\n */\nexport const history = <T extends Entity.Unknown | Entity.Snapshot>(\n items: readonly T[],\n options?: HistoryOptions,\n): History<T> => {\n const indexById = new Map<EntityId, number>();\n items.forEach((item, index) => indexById.set(item.id, index));\n\n const head = options?.head;\n const headIndex = head === undefined ? items.length - 1 : indexById.get(typeof head === 'string' ? head : head.id);\n if (headIndex === undefined) {\n return { items: [], shallow: true };\n }\n\n let cursor = headIndex;\n const reachable: T[] = [];\n let shallow = false;\n while (cursor >= 0) {\n const item = items[cursor];\n reachable.push(item);\n\n const parent = readParent(item);\n if (!parent.present) {\n cursor -= 1;\n continue;\n }\n if (parent.id === undefined) {\n // Key present but unparseable — a fork whose target cannot be identified, so stop rather than\n // fall through to the predecessor and make what this item superseded reachable again.\n shallow = true;\n break;\n }\n\n // A parent at or after its child is a cycle or a forward reference (possible with arbitrary\n // multi-writer data); requiring the cursor to strictly decrease also guarantees termination.\n const parentIndex = indexById.get(parent.id);\n if (parentIndex === undefined || parentIndex >= cursor) {\n shallow = true;\n break;\n }\n cursor = parentIndex;\n }\n\n return { items: reachable.reverse(), shallow };\n};\n\n//\n// Branches\n//\n\n/**\n * The id of a branch: the block id (`<sequence>@<actorId>`) of the base block of the branch, as an\n * opaque string. The root branch has no id; scopes and the index name it `null`.\n */\nexport const BranchId = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/BranchId'));\nexport type BranchId = Schema.Schema.Type<typeof BranchId>;\n\n/** The id of a block within its feed, `<sequence>@<actorId>`. */\nexport type BlockId = string;\n\n/**\n * The foreign-key sources a store stamps on an item from the block it was read from: its block id, its\n * branch, its fork flag (as the fork point) and its predecessor. A copy of the item into another feed\n * drops them, since that feed has none of those blocks or branches.\n */\nexport const BLOCK_KEYS: readonly string[] = [KEY_FEED_BLOCK, KEY_FEED_BRANCH, KEY_FEED_FORK, KEY_FEED_PREV];\n\n/**\n * The position of a walk on one device: the branch the walk is on and the last block it gave. Read it\n * off an item with {@link getLocalCursor}; another device cannot use it.\n */\nexport const LocalCursor = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/LocalCursor'));\nexport type LocalCursor = Schema.Schema.Type<typeof LocalCursor>;\n\n// A live object this client wrote carries the keys of its latest block hidden, so they never notify.\nconst keyOf = (item: Entity.Unknown | Entity.Snapshot, source: string): string | undefined =>\n (internal.getFeedBlockKeys(item) ?? internal.getKeys(item, source)).find((key) => key.source === source)?.id;\n\n/** Writes the branch key into an open change, so a caller can batch it with its other writes. */\nconst setBranchKey = (mutable: Entity.Mutable<Entity.Unknown>, branch: BranchId): void => {\n internal.deleteKeys(mutable, KEY_FEED_BRANCH);\n internal.getMetaChecked(mutable).keys.push(internal.foreignKey(KEY_FEED_BRANCH, branch));\n};\n\n/**\n * The foreign key that puts an item on `branch`, for an item built with it in its meta (`Obj.make(…, { [Obj.Meta]: {\n * keys: [Feed.branchKey(branch)] } })`); cheaper than {@link setBranch}, which opens a change on an item made without it.\n *\n * @performance O(1).\n */\nexport const branchKey = (branch: BranchId): { readonly source: string; readonly id: string } => ({\n source: KEY_FEED_BRANCH,\n id: branch,\n});\n\n/**\n * Puts an item on a branch: a later {@link append} of it continues `branch`, so items for several\n * branches can be built before they are written. Must be called within an `Obj.update` callback.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const setBranch = (mutable: Entity.Mutable<Entity.Unknown>, branch: BranchId): void =>\n setBranchKey(mutable, branch);\n\n/**\n * The branch of an item, as the store inferred it from the block the item was read from; `undefined`\n * on the root branch.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getBranch = (item: Entity.Unknown | Entity.Snapshot): BranchId | undefined => {\n const branch = keyOf(item, KEY_FEED_BRANCH);\n return branch === undefined ? undefined : BranchId.make(branch);\n};\n\n/**\n * True when the item was read from the base block of a branch: its fork flag is set, and its\n * predecessor is the fork point.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const isFork = (item: Entity.Unknown | Entity.Snapshot): boolean => keyOf(item, KEY_FEED_FORK) !== undefined;\n\n/**\n * The id of the block the item was read from; `undefined` on an item the store has not echoed yet.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getBlockId = (item: Entity.Unknown | Entity.Snapshot): BlockId | undefined => keyOf(item, KEY_FEED_BLOCK);\n\n/**\n * The id of the predecessor of the block the item was read from: the head of its branch when it was\n * written, or the fork point of a base block; `undefined` on the first block of a feed.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getPredecessor = (item: Entity.Unknown | Entity.Snapshot): BlockId | undefined =>\n keyOf(item, KEY_FEED_PREV);\n\n/**\n * The cursor a walk resumes after this item; `undefined` on an item the store has not echoed yet.\n *\n * @performance O(k) in the item foreign-key count.\n */\nexport const getLocalCursor = (item: Entity.Unknown | Entity.Snapshot): LocalCursor | undefined => {\n const block = getBlockId(item);\n return block === undefined ? undefined : LocalCursor.make(`${getBranch(item) ?? ''}|${block}`);\n};\n\n/**\n * Starts a new branch: the first item is appended as the base block of the branch, with the fork\n * point `at` as its predecessor, and the rest continue the branch. Returns the id of the branch, the\n * block id of its base, once the base is written.\n *\n * @example\n * ```ts\n * const branch = yield* Feed.fork(feed, [reply], { at: message });\n * yield* Feed.append(feed, [followUp], { branch });\n * ```\n *\n * @performance Async; one append for the base, then one for the rest.\n */\nexport const fork = Effect.fn('Feed.fork')(function* (\n feed: Feed,\n items: Entity.Unknown[],\n options: ForkOptions,\n): Effect.fn.Return<BranchId, never, Database.Service> {\n const { db } = yield* Database.Service;\n const [base, ...rest] = items;\n invariant(base !== undefined, 'fork: pass at least the base item');\n const branch = yield* Effect.promise(() => db.forkFeed(feed, base, { at: options.at }));\n if (rest.length > 0) {\n yield* append(feed, rest, { branch });\n }\n return branch;\n}, Database.withSpaceId);\n\n/**\n * Returns what a read of one branch sees: the items of its ancestors up to each fork point, then the\n * items of the branch itself. Omit `branch` for the root branch.\n *\n * A feed appended as `A1, A2, A3, B1(fork at A2), A4, B2` reads `A1, A2, A3, A4` on the root branch and\n * `A1, A2, B1, B2` on branch `B1`.\n *\n * `items` must be in **append order**, as read from the feed with `branches: 'all'`. The read is\n * `shallow` when the base of a branch or its fork point is missing from `items` (a base or fork point\n * that was updated is read at its latest block, which is not the one the branch names); the branch's\n * own items are still returned. A walk ({@link walk}) reads blocks, so it has no such gap.\n *\n * @performance O(n) in items; one pass to group them and one walk up the branch's ancestors.\n */\nexport const readBranch = <T extends Entity.Unknown | Entity.Snapshot>(\n items: readonly T[],\n branch?: BranchId,\n): History<T> => {\n const indexByBlock = new Map<BlockId, number>();\n const byBranch = new Map<BranchId | undefined, number[]>();\n items.forEach((item, index) => {\n const block = getBlockId(item);\n if (block !== undefined) {\n indexByBlock.set(block, index);\n }\n const key = getBranch(item);\n const members = byBranch.get(key) ?? [];\n members.push(index);\n byBranch.set(key, members);\n });\n\n const resolve = (target: BranchId | undefined): { indices: number[]; shallow: boolean } => {\n const own = byBranch.get(target) ?? [];\n if (target === undefined) {\n return { indices: own, shallow: false };\n }\n const baseIndex = indexByBlock.get(target);\n const forkPoint = baseIndex === undefined ? undefined : keyOf(items[baseIndex], KEY_FEED_FORK);\n // A fork point at or after the base is a cycle or a forward reference; requiring it to be strictly\n // earlier also makes each step up the tree move to an earlier base, so the walk ends.\n const forkIndex = forkPoint === undefined ? undefined : indexByBlock.get(forkPoint);\n if (baseIndex === undefined || forkIndex === undefined || forkIndex >= baseIndex) {\n return { indices: own, shallow: true };\n }\n const parent = resolve(getBranch(items[forkIndex]));\n return { indices: [...parent.indices.filter((index) => index <= forkIndex), ...own], shallow: parent.shallow };\n };\n\n const { indices, shallow } = resolve(branch);\n return { items: indices.map((index) => items[index]), shallow };\n};\n\n/**\n * Walks a feed along the path from the root branch to `branch`, in local order: a wrapper of the\n * walk query, which reads the same as\n *\n * ```ts\n * Database.query(\n * Query.select(Filter.and(filter, Filter.feedCursor({ begin, positions: 'local' })))\n * .from(Scope.feed(feedUri, { walk: { branch, forks } }))\n * .orderBy(Order.natural(order))\n * .limit(limit),\n * );\n * ```\n *\n * A forward walk gives each branch on the path up to the fork point of the next; a backward walk\n * goes from `begin` (or the head of `branch`) back to the root base. Each item comes once, at the place\n * of its first block on the path, with the content of its latest one. Resume with {@link getLocalCursor}\n * of the last item of a page.\n *\n * @performance O(1) to build; a page reads every block of the path.\n */\nexport const walk = <F extends Filter.Any>(\n feed: Feed,\n filter: F,\n options: WalkOptions = {},\n): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service> => {\n const feedUri = getFeedUri(feed);\n invariant(feedUri, 'Feed must be stored in the database before accessing its contents');\n const select =\n options.begin === undefined\n ? filter\n : Filter.and(filter, Filter.feedCursor({ begin: options.begin, positions: 'local' }));\n const query = Query.select(select)\n .from(Scope.feed(feedUri.toString(), { walk: { branch: options.branch, forks: options.forks } }))\n .orderBy(Order.natural(options.order ?? 'asc'));\n return Database.query(options.limit === undefined ? query : query.limit(options.limit));\n};\n\n/**\n * Creates a reactive query over items in a feed.\n *\n * Returns a {@link QueryResult.QueryResultEffect}: yielding it produces a subscribable\n * `QueryResult`, while its `.run` / `.first` shorthands execute the query once. This mirrors\n * `Database.query` so feed and database queries chain identically.\n *\n * Supports both data-first and data-last (curried) forms; the latter composes with `pipe`.\n *\n * In non-Effect code, query a feed directly through the database with a feed scope:\n * `db.query(Query.select(filter).from(Scope.feed(Feed.getFeedUri(feed))))`.\n *\n * @example\n * ```ts\n * const result = yield* Feed.query(feed, Filter.type(Person));\n * result.subscribe(...);\n *\n * const objects = yield* Feed.query(feed, Filter.type(Person)).run;\n * const object = yield* Feed.query(feed, Filter.type(Person)).first;\n *\n * // Data-last (curried) form composes with `pipe`:\n * const objects = yield* pipe(feed, Feed.query(Filter.type(Person))).run;\n *\n * // Resume after a cursor, reading a bounded page of what is new:\n * const objects = yield* Feed.query(feed, Query.select(Filter.feedCursor(cursor)).limit(10)).run;\n * ```\n *\n * @performance O(1) to build; the result is lazy, so nothing executes until read.\n */\nexport const query: {\n <Q extends Query.Any>(\n feed: Feed,\n query: Q,\n options?: QueryOptions,\n ): QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;\n <F extends Filter.Any>(\n feed: Feed,\n filter: F,\n options?: QueryOptions,\n ): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;\n <Q extends Query.Any>(\n query: Q,\n ): (feed: Feed) => QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;\n <F extends Filter.Any>(\n filter: F,\n ): (feed: Feed) => QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;\n // Data-first takes two or three arguments; data-last takes one, so arity alone tells them apart.\n} = Function.dual(\n (args) => args.length >= 2,\n (feed: Feed, queryOrFilter: Query.Any | Filter.Any, options?: QueryOptions) => {\n const feedUri = getFeedUri(feed);\n invariant(feedUri, 'Feed must be stored in the database before accessing its contents');\n const query = Query.is(queryOrFilter) ? queryOrFilter : Query.select(queryOrFilter);\n return Database.query(query.from(Scope.feed(feedUri.toString(), { branches: options?.branches })));\n },\n);\n\n/**\n * Syncs the feed with the server.\n *\n * @example\n * ```ts\n * yield* Feed.sync(feed);\n * yield* Feed.sync(feed, { shouldPush: false });\n * ```\n *\n * @performance Async; network-bound, proportional to the replication backlog.\n */\nexport const sync = (feed: Feed, options?: SyncOptions): Effect.Effect<void, never, Database.Service> =>\n Database.Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.syncFeed(feed, options)))).pipe(\n Effect.withSpan('Feed.sync'),\n Database.withSpaceId,\n );\n\n/**\n * Returns the feed's replication backlog for its namespace.\n *\n * @example\n * ```ts\n * const { blocksToPull, blocksToPush } = yield* Feed.getSyncState(feed);\n * ```\n *\n * @performance Async; one service round trip.\n */\nexport const getSyncState = (feed: Feed): Effect.Effect<SyncState, never, Database.Service> =>\n Database.Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.getFeedSyncState(feed)))).pipe(\n Effect.withSpan('Feed.getSyncState'),\n Database.withSpaceId,\n );\n\n/**\n * Sets the feed's indexing options on the feed object, in one change.\n *\n * Returns once the change is applied locally; the store stops indexing on its own index pass, which\n * may run on another device.\n *\n * @example\n * ```ts\n * yield* Feed.setIndexing(feed, { enabled: false });\n * ```\n *\n * @performance O(1); one object change.\n */\nexport const setIndexing = (feed: Feed, options: IndexingOptions): Effect.Effect<void, Schema.SchemaError> =>\n Schema.decodeUnknownEffect(IndexingOptions)(options).pipe(\n Effect.map((indexing) =>\n Obj.update(feed, (feed) => {\n feed.indexing = indexing;\n }),\n ),\n Effect.asVoid,\n Effect.withSpan('Feed.setIndexing'),\n );\n\n/**\n * Sets the feed's retention options on the feed object, in one change.\n *\n * Fails with the schema error, leaving the object unchanged, when `maxLength` is not an integer of\n * at least 1 or `maxAge` is not a positive, finite duration. Returns once the change is applied\n * locally; the store trims on its own index pass, which may run on another device.\n *\n * @example\n * ```ts\n * yield* Feed.setRetention(feed, { maxLength: 1000, maxAge: Duration.days(7) });\n * ```\n *\n * @performance O(1); one object change.\n */\nexport const setRetention = (feed: Feed, options: SetRetentionOptions): Effect.Effect<void, Schema.SchemaError> =>\n Schema.decodeUnknownEffect(RetentionOptions)({\n // Keys are omitted rather than set to undefined, which ECHO does not store.\n ...(options.maxLength !== undefined ? { maxLength: options.maxLength } : {}),\n ...(options.maxAge !== undefined ? { maxAge: durationToMillis(options.maxAge) } : {}),\n }).pipe(\n Effect.map((retention) =>\n Obj.update(feed, (feed) => {\n feed.retention = retention;\n }),\n ),\n Effect.asVoid,\n Effect.withSpan('Feed.setRetention'),\n );\n\n/** An unparseable duration maps to NaN so the schema, not this conversion, reports it. */\nconst durationToMillis = (input: Duration.Input): number =>\n Duration.fromInput(input).pipe(\n Option.map(Duration.toMillis),\n Option.getOrElse(() => Number.NaN),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,YAAY,OAAO,SAAS,CAAC,QAAQ,OAAO,CAAC;;;;;;AAQ1D,IAAa,kBAAkB,OAAO,OAAO;;CAE3C,SAAS,OAAO;;;;;CAKhB,MAAM,OAAO,SAAS,OAAO,SAAS,CAAC,OAAO,MAAM,CAAC,CAAC;AACxD,CAAC;;;;;;;;AAUD,IAAa,mBAAmB,OAAO,OAAO;;CAE5C,WAAW,OAAO,IAAI,KAAK,OAAO,MAAM,OAAO,uBAAuB,CAAC,CAAC,GAAG,OAAO,QAAQ;;;;;CAM1F,QAAQ,OAAO,OAAO,KAAK,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC,GAAG,OAAO,QAAQ;AACnF,CAAC;;;;AAMD,IAAa,cAAc,OAAO,OAAO;CACvC,UAAU,OAAO,SAAS,eAAe;CACzC,WAAW,OAAO,SAAS,gBAAgB;AAC7C,CAAC;;;;;;;;;AAWD,IAAa,OAAb,cAA0BA,WAAsB,IAAI,KAAK,sBAAsB,OAAO,CAAC,CAAC,CACtF,OAAO,OAAO;;CAEZ,MAAM,OAAO,OAAO,KAAK,OAAO,QAAQ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C,CAAC,CAAC,CAAC,KAClG,OAAO,SAAS,WAAW,GAC3BV,WACF;;;;;;;;;;;AAYF,IAAa,gBAAgB,SAAA,QACV,KAAK,OAAO,SAAS,EAAE,SAAS,OAAO,cAAc,GAAG,iBAAiB,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KACjG,OAAO,SAAS,mBAAmB,GACnCA,WACF;;;;;;;;;;;;;;AAeF,IAAa,eAAe,MAAY,YACtC,OAAO,oBAAoB,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,KACnD,OAAO,KAAK,aACVc,OAAW,OAAO,SAAS;CACzB,KAAK,WAAW;AAClB,CAAC,CACH,GACA,OAAO,QACP,OAAO,SAAS,kBAAkB,CACpC;;;;;;;;;;;;;;;AAgBF,IAAa,gBAAgB,MAAY,YACvC,OAAO,oBAAoB,gBAAgB,CAAC,CAAC;CAE3C,GAAI,QAAQ,cAAc,KAAA,IAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;CAC1E,GAAI,QAAQ,WAAW,KAAA,IAAY,EAAE,QAAQ,iBAAiB,QAAQ,MAAM,EAAE,IAAI,CAAC;AACrF,CAAC,CAAC,CAAC,KACD,OAAO,KAAK,cACVA,OAAW,OAAO,SAAS;CACzB,KAAK,YAAY;AACnB,CAAC,CACH,GACA,OAAO,QACP,OAAO,SAAS,mBAAmB,CACrC;;AAGF,IAAM,oBAAoB,UACxB,SAAS,UAAU,KAAK,CAAC,CAAC,KACxB,OAAO,IAAI,SAAS,QAAQ,GAC5B,OAAO,gBAAgB,GAAU,CACnC"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { Ct as prettyFilter, Mt as isProjection, S as filterMatchEntity } from "./chunk-internal.mjs";
3
- import { N as getUri, k as getTypeURIFromSpecifier } from "./chunk-Database.mjs";
2
+ import { Et as prettyFilter, Ft as isProjection, S as filterMatchEntity } from "./chunk-internal.mjs";
3
+ import { A as getTypeURIFromSpecifier, F as getUri } from "./chunk-Database.mjs";
4
4
  import { c as isRef } from "./chunk-Ref2.mjs";
5
5
  import { EID, EntityId } from "@dxos/keys";
6
6
  import * as Function from "effect/Function";
@@ -425,7 +425,8 @@ var created = (range) => _timeRangeFilter("createdAt", range);
425
425
  var feedCursor = (range = {}) => new FilterClass({
426
426
  type: "feed-cursor",
427
427
  ...range.begin !== void 0 ? { begin: range.begin } : {},
428
- ...range.end !== void 0 ? { end: range.end } : {}
428
+ ...range.end !== void 0 ? { end: range.end } : {},
429
+ ...range.positions !== void 0 ? { positions: range.positions } : {}
429
430
  });
430
431
  /**
431
432
  * Filter objects that are children of the specified parent(s).
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Filter.mjs","names":["internal.getTypeURIFromSpecifier","Ref.isRef","internal.isProjection","internal.getUri","internal.prettyFilter","internal.filterMatchEntity"],"sources":["../../src/Filter.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Function from 'effect/Function';\nimport * as Match from 'effect/Match';\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport { type ForeignKey, type QueryAST } from '@dxos/echo-protocol';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\n\nimport type * as Annotation from './Annotation.ts';\nimport type * as Change from './Change.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as Feed from './Feed.ts';\nimport * as internal from './internal/index.ts';\nimport type * as Obj from './Obj.ts';\nimport * as Ref from './Ref.ts';\n// eslint-disable-next-line @dxos/rules/import-as-namespace\nimport type * as Type$ from './Type.ts';\n\nexport const FilterTypeId = '~@dxos/echo/Filter' as const;\nexport type FilterTypeId = typeof FilterTypeId;\n\nexport interface Filter<T> {\n // TODO(dmaretskyi): See new effect-schema approach to variance.\n readonly [FilterTypeId]: { value: Types.Covariant<T> };\n\n ast: QueryAST.Filter;\n}\n\nexport type Props<T> = {\n // Predicate or a value as a shorthand for `eq`.\n [K in keyof T & string]?: Filter<T[K]> | T[K];\n};\n\nexport type Any = Filter<any>;\n\nexport type Type<F extends Any> = F extends Filter<infer T> ? T : never;\n\nclass FilterClass implements Any {\n private static 'variance': Any[FilterTypeId] = {} as Any[FilterTypeId];\n\n constructor(public readonly ast: QueryAST.Filter) {}\n\n [FilterTypeId] = FilterClass.variance;\n}\n\n/**\n * Type guard for filters.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const is = (value: unknown): value is Any => {\n return typeof value === 'object' && value !== null && FilterTypeId in value;\n};\n\n/**\n * Construct a filter from an ast.\n *\n * @performance O(1); wraps the AST without copying it.\n */\nexport const fromAst = (ast: QueryAST.Filter): Any => {\n return new FilterClass(ast);\n};\n\n/**\n * Filter that matches all objects.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\n// TODO(dmaretskyi): `Entity.Any` would be more type-safe, but causes annoying errors in existing code\nexport const everything = (): FilterClass => {\n return new FilterClass({\n type: 'object',\n typename: null,\n props: {},\n });\n};\n\n/**\n * Filter that matches no objects.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const nothing = (): FilterClass => {\n return new FilterClass({\n type: 'not',\n filter: {\n type: 'object',\n typename: null,\n props: {},\n },\n });\n};\n\n/**\n * Filter by EntityId.\n *\n * @performance O(k) in the number of ids (validated); builds the AST without matching anything.\n */\nexport const id = (...ids: EntityId[]): Any => {\n assertArgument(\n ids.every((id) => EntityId.isValid(id)),\n 'ids',\n 'ids must be valid',\n );\n\n if (ids.length === 0) {\n return nothing();\n }\n\n return new FilterClass({\n type: 'object',\n typename: null,\n id: ids,\n props: {},\n });\n};\n\n/**\n * Filter by the id of an entity already in hand, keeping its type for the rest of the chain.\n *\n * @example\n * ```ts\n * db.query(Query.select(Filter.entity(task)).reference('watchers'));\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const entity: {\n <T extends Entity.Unknown>(entity: T): Filter<T>;\n <T extends Obj.Unknown>(snapshot: Obj.Snapshot<T>): Filter<T>;\n} = (entity: Entity.Unknown | Entity.Snapshot): Filter<any> => id(entity.id);\n\n/**\n * Filter by mnemonic — the human-memorable short form of an object's id (see `Obj.getMnemonic`).\n * Input is case-insensitive.\n *\n * @example\n * ```ts\n * const [task] = await db.query(Filter.mnemonic('7qk2zb')).run();\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const mnemonic = (mnemonic: string): Any => {\n const normalized = EntityId.normalizeMnemonic(mnemonic);\n assertArgument(\n EntityId.isValidMnemonic(normalized),\n 'mnemonic',\n `mnemonic must be ${EntityId.mnemonicLength} base32 characters`,\n );\n\n return new FilterClass({\n type: 'mnemonic',\n mnemonic: normalized,\n });\n};\n\n/**\n * Filter by type.\n *\n * Accepts a `Type.Type` entity (the value produced by `Type.makeObject` /\n * `Type.makeRelation`), a `Schema.Union` of such entities (for filtering across a\n * union of ECHO types), or a fully-qualified type URI — an `echo:` EID (stored schema)\n * or a `dxn:` DXN (static schema). To filter by a bare typename, wrap it: `DXN.make(typename)`.\n *\n * @performance O(1) plus O(p) for props (O(k) for a union); builds the AST without matching anything.\n */\nexport const type: {\n <T extends Type$.AnyEntity>(type: T, props?: Props<Type$.InstanceType<T>>): Filter<Type$.InstanceType<T>>;\n // Schema-side overload restricted to the well-known unknown schemas and to\n // `Schema.Union(...)` of `Type.Type` entities (for filtering across a union\n // of ECHO types). Other raw schemas are rejected.\n <S extends internal.UnknownTypeSchema<any, any>>(\n schema: S,\n props?: Props<Schema.Schema.Type<S>>,\n ): Filter<Schema.Schema.Type<S>>;\n <S extends Schema.Union<readonly Schema.Codec<any, any>[]>>(\n union: S,\n props?: Props<Schema.Schema.Type<S>>,\n ): Filter<Schema.Schema.Type<S>>;\n (uri: URI.URI, props?: Props<unknown>): Filter<any>;\n // Passthrough overload for callers that hold a `Type.AnyEntity | URI.URI` union\n // (e.g. Query.type / Query.sourceOf / Query.targetOf impls). Listed last so the\n // typed overloads above still win for monomorphic inputs.\n (input: Type$.AnyEntity | URI.URI, props?: Props<unknown>): Filter<unknown>;\n} = (input: Type$.AnyEntity | Schema.Codec<any, any> | URI.URI, props?: Props<unknown>): any => {\n if (Schema.isSchema(input) && SchemaAST.isUnion(input.ast)) {\n const typenames = input.ast.types.map((t) => internal.getTypeURIFromSpecifier(Schema.make(t)));\n return new FilterClass({\n type: 'or',\n filters: typenames.map((typename) => ({\n type: 'object',\n typename,\n props: {},\n })),\n });\n }\n\n const uri = internal.getTypeURIFromSpecifier(input);\n return new FilterClass({\n type: 'object',\n typename: uri,\n ...propsFilterToAst(props ?? {}),\n });\n};\n\n/**\n * Filter by tag.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const tag = (tag: string): Any => {\n return new FilterClass({\n type: 'tag',\n tag,\n });\n};\n\n/**\n * Filter by an annotation set on the entity with `Annotation.set`.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const annotation: {\n /** Matches entities that carry the annotation, whatever its value. */\n <T>(annotation: Annotation.Annotation<T>): Any;\n /** Matches entities whose value equals `value`; only scalar values can be compared. */\n <T extends string | number | boolean>(annotation: Annotation.Annotation<T>, value: T): Any;\n} = (annotation: Annotation.Annotation<unknown>, value?: string | number | boolean): Any => {\n return new FilterClass({\n type: 'annotation',\n key: annotation.key,\n ...(value !== undefined ? { value } : {}),\n });\n};\n\n/**\n * Options for {@link key} filter.\n */\nexport type KeyFilterOptions = {\n /**\n * Optional semver range expression (e.g. `^1.2.3`, `~2.0.0`, `>=1.0.0 <2.0.0`).\n * Matches the object's meta `version` field against the range.\n * If omitted, matches any version (including objects with no version).\n */\n version?: string;\n};\n\n/**\n * Filter by registry key stored in object meta.\n *\n * @example\n * ```ts\n * Filter.key('com.example.type.foo');\n * Filter.key('com.example.type.foo', { version: '^1.2.3' });\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const key = (key: string, options?: KeyFilterOptions): Any => {\n return new FilterClass({\n type: 'object',\n typename: null,\n props: {},\n metaKey: key,\n metaVersion: options?.version,\n });\n};\n\n/**\n * Filter by properties.\n *\n * @performance O(p) in the number of predicates; builds the AST without matching anything.\n */\nexport const props = <T>(props: Props<T>): Filter<T> => {\n return new FilterClass({\n type: 'object',\n typename: null,\n ...propsFilterToAst(props),\n });\n};\n\nexport type TextSearchOptions = {\n // TODO(dmaretskyi): Hybrid search.\n type?: 'full-text' | 'vector';\n};\n\n/**\n * Full-text or vector search.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const text = (\n // TODO(dmaretskyi): Consider passing a vector here, but really the embedding should be done on the query-executor side.\n text: string,\n options?: TextSearchOptions,\n): Any => {\n return new FilterClass({\n type: 'text-search',\n text,\n searchKind: options?.type,\n });\n};\n\n/**\n * Filter by foreign keys.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const foreignKeys = <S extends Type$.AnyEntity | URI.URI>(\n schema: S,\n keys: ForeignKey[],\n): Filter<S extends Type$.AnyEntity ? Type$.InstanceType<S> : unknown> => {\n const uri = internal.getTypeURIFromSpecifier(schema);\n return new FilterClass({\n type: 'object',\n typename: uri,\n props: {},\n foreignKeys: keys,\n });\n};\n\n/**\n * Predicate for property to be equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const eq = <T>(value: T): Filter<T | undefined> => {\n if (!Ref.isRef(value) && typeof value === 'object' && value !== null) {\n throw new TypeError('Cannot use object as a value for eq filter');\n }\n\n return new FilterClass({\n type: 'compare',\n operator: 'eq',\n value: Ref.isRef(value) ? value.noInline().encode() : value,\n });\n};\n\n/**\n * Predicate for property to be not equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const neq = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'neq',\n value,\n });\n};\n\n/**\n * Predicate for property to be greater than the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const gt = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'gt',\n value,\n });\n};\n\n/**\n * Predicate for property to be greater than or equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const gte = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'gte',\n value,\n });\n};\n\n/**\n * Predicate for property to be less than the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const lt = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'lt',\n value,\n });\n};\n\n/**\n * Predicate for property to be less than or equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const lte = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'lte',\n value,\n });\n};\n\n/**\n * Predicate for property to be in the provided array, or in the set of values projected\n * from a subquery's results (an uncorrelated `col IN (SELECT property FROM ...)` semi-join —\n * see `Query.project`). The subquery may target a different scope than the parent query; it\n * is resolved once at execution time.\n * @param values - Values to check against, or a single subquery projection.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nconst in$: {\n <T>(projection: internal.Projection<T>): Filter<T>;\n <T>(...values: T[]): Filter<T>;\n} = <T>(...args: [internal.Projection<T>] | T[]): Filter<T> => {\n if (args.length === 1 && internal.isProjection(args[0])) {\n const projection = args[0];\n return new FilterClass({\n type: 'in-query',\n subquery: projection.query,\n property: projection.property,\n });\n }\n return new FilterClass({\n type: 'in',\n values: args,\n });\n};\nexport { in$ as in };\n\n/**\n * Predicate for an array property to contain the provided value.\n * @param value - Value to check against.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const contains = <T>(value: T): Filter<readonly T[] | undefined> => {\n return new FilterClass({\n type: 'contains',\n value,\n });\n};\n\n/**\n * Predicate for property to be in the provided range.\n * @param from - Start of the range (inclusive).\n * @param to - End of the range (exclusive).\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const between = <T>(from: T, to: T): Filter<T> => {\n return new FilterClass({\n type: 'range',\n from,\n to,\n });\n};\n\ntype TimeRange = { after?: Date | number; before?: Date | number };\n\nconst _toUnixMs = (date: Date | number): number => (typeof date === 'number' ? date : date.getTime());\n\nconst _timeRangeFilter = (field: 'updatedAt' | 'createdAt', range: TimeRange): Any => {\n const filters: Any[] = [];\n if (range.after != null) {\n filters.push(new FilterClass({ type: 'timestamp', field, operator: 'gte', value: _toUnixMs(range.after) }));\n }\n if (range.before != null) {\n filters.push(new FilterClass({ type: 'timestamp', field, operator: 'lte', value: _toUnixMs(range.before) }));\n }\n if (filters.length === 0) {\n return everything();\n }\n return filters.length === 1 ? filters[0] : and(...filters);\n};\n\n/**\n * Filter objects by updatedAt timestamp.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const updated = (range: TimeRange): Any => _timeRangeFilter('updatedAt', range);\n\n/**\n * Filter objects by createdAt timestamp.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const created = (range: TimeRange): Any => _timeRangeFilter('createdAt', range);\n\n/**\n * Range of feed cursors, as read off items with `Feed.getCursor`.\n * Both bounds name an item and exclude it: `begin` is the last item already consumed, `end` the\n * first item not wanted.\n */\nexport type FeedCursorRange = {\n /** Read after this cursor. Defaults to the start of the feed ({@link Feed.START}). */\n begin?: Feed.Cursor;\n /** Read up to but not including this cursor. Defaults to the end of the feed. */\n end?: Feed.Cursor;\n};\n\n/**\n * Filter feed items to a cursor range — see `Feed.getCursor` for reading a cursor off an item, and\n * `Feed.START` for the sentinel that bounds nothing.\n *\n * The range is pushed into the index scan, so a reader that keeps a cursor pays for what is new\n * rather than for the whole feed. Combine with `limit()` for a bounded page. Results come back in\n * append order and cover positioned items only — an item a peer wrote but the position authority\n * has not yet acknowledged has no place in that order, and `Feed.START` selects the same set from\n * the beginning rather than everything. Only meaningful against a feed scope — an automerge object\n * carries no position, so a query that also selects a space's documents is rejected.\n *\n * @example\n * ```ts\n * // The next 10 items after the last one this reader consumed.\n * db.query(Query.select(Filter.feedCursor({ begin: cursor })).limit(10).from(feed));\n *\n * // Everything between two known items, excluding both.\n * db.query(Query.select(Filter.feedCursor({ begin: first, end: last })).from(feed));\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const feedCursor = (range: FeedCursorRange = {}): Any =>\n new FilterClass({\n type: 'feed-cursor',\n ...(range.begin !== undefined ? { begin: range.begin } : {}),\n ...(range.end !== undefined ? { end: range.end } : {}),\n });\n\nexport type ChildOfOptions = {\n /** Whether to match transitively (grandchildren, etc.). Defaults to true. */\n transitive?: boolean;\n};\n\n/**\n * Filter objects that are children of the specified parent(s).\n * Accepts ECHO objects, Refs, or arrays of either.\n * Refs are resolved to DXNs without loading; objects use {@link Obj.getURI}.\n * With transitive=true (default), also matches grandchildren and beyond.\n *\n * @performance O(k) in the number of parents; refs are read by URI without loading.\n */\nexport const childOf = (\n parents: Obj.Unknown | Ref.Unknown | readonly (Obj.Unknown | Ref.Unknown)[],\n options?: ChildOfOptions,\n): Any => {\n const items = Array.isArray(parents) ? parents : [parents];\n const dxns = items.map((item) => {\n if (Ref.isRef(item)) {\n return EID.parse(item.uri);\n }\n return EID.parse(internal.getUri(item));\n });\n return new FilterClass({\n type: 'child-of',\n parents: dxns,\n transitive: options?.transitive ?? true,\n });\n};\n\n/**\n * Select Automerge changes instead of objects: one {@link Change.Change} per change to the documents\n * holding `targets`, or to every document in the space when called with no argument.\n *\n * Changes belong to documents, not entities. Entities that share a document share its changes, and\n * content held by another entity (a document's `Text`) needs its own target. Only the host answers\n * these queries; a space-wide query must aggregate, and the index answers it only at hour\n * granularity (see `Aggregate.time`).\n *\n * @example\n * ```ts\n * Query.select(Filter.changes()).aggregate({ day: Aggregate.time('time', 'day'), changes: Aggregate.count() });\n * Query.select(Filter.changes([doc, doc.content])).orderBy(Order.property('time', 'desc')).limit(50);\n * ```\n *\n * @performance O(k) in the number of targets; refs are read by URI without loading.\n */\nexport const changes = (\n targets?: Obj.Unknown | Ref.Unknown | readonly (Obj.Unknown | Ref.Unknown)[],\n): Filter<Change.Change> => {\n if (targets === undefined) {\n return new FilterClass({ type: 'changes' });\n }\n const items = Array.isArray(targets) ? targets : [targets];\n return new FilterClass({\n type: 'changes',\n targets: items.map((item) => (Ref.isRef(item) ? EID.parse(item.uri) : EID.parse(internal.getUri(item)))),\n });\n};\n\n/**\n * Filter objects by whether they have a parent, regardless of which object it is.\n * `Filter.hasParent(false)` selects root objects — those never passed to `Obj.setParent`.\n * Unlike {@link childOf} this reads the object's own parent slot, so it costs no traversal.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const hasParent = (value = true): Any =>\n new FilterClass({\n type: 'has-parent',\n value,\n });\n\n/**\n * Negate the filter.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const not = <F extends Any>(filter: F): Filter<Type<F>> => {\n return new FilterClass({\n type: 'not',\n filter: filter.ast,\n });\n};\n\n/**\n * Combine filters with a logical AND.\n *\n * @performance O(k) in the number of filters; builds the AST without matching anything.\n */\nexport const and = <Filters extends readonly Any[]>(...filters: Filters): Filter<Type<Filters[number]>> => {\n return new FilterClass({\n type: 'and',\n filters: filters.map((f) => f.ast),\n });\n};\n\n/**\n * Combine filters with a logical OR.\n *\n * @performance O(k) in the number of filters; builds the AST without matching anything.\n */\nexport const or = <Filters extends readonly Any[]>(...filters: Filters): Filter<Type<Filters[number]>> => {\n return new FilterClass({\n type: 'or',\n filters: filters.map((f) => f.ast),\n });\n};\n\n// TODO(dmaretskyi): Add `Filter.match` to support pattern matching on string props.\n\nconst propsFilterToAst = (predicates: Props<any>): Pick<QueryAST.FilterObject, 'id' | 'props'> => {\n let idFilter: readonly EntityId[] | undefined;\n if ('id' in predicates) {\n assertArgument(\n typeof predicates.id === 'string' || Array.isArray(predicates.id),\n 'predicates.id',\n 'invalid id filter',\n );\n idFilter = typeof predicates.id === 'string' ? [predicates.id] : predicates.id;\n Schema.decodeSync(Schema.toType(Schema.Array(EntityId)))(idFilter);\n }\n\n return {\n id: idFilter,\n props: Object.fromEntries(\n Object.entries(predicates)\n .filter(([prop, _value]) => prop !== 'id')\n .map(([prop, predicate]) => [prop, processPredicate(predicate)]),\n ) as Record<string, QueryAST.Filter>,\n };\n};\n\nconst processPredicate = (predicate: any): QueryAST.Filter => {\n return Match.value(predicate).pipe(\n Match.withReturnType<QueryAST.Filter>(),\n Match.when(is, (predicate) => predicate.ast),\n // TODO(wittjosiah): Add support for array predicates.\n Match.when(Array.isArray, (_predicate) => {\n throw new Error('Array predicates are not yet supported.');\n }),\n Match.when(\n (predicate: any) => !Ref.isRef(predicate) && typeof predicate === 'object' && predicate !== null,\n (predicate) => {\n const nestedProps = Object.fromEntries(\n Object.entries(predicate).map(([key, value]) => [key, processPredicate(value)]),\n );\n\n return {\n type: 'object',\n typename: null,\n props: nestedProps,\n };\n },\n ),\n Match.orElse((value) => eq(value).ast),\n );\n};\n\n/**\n * Returns a human-readable string representation of a Filter AST.\n *\n * @performance O(AST size) string build; meant for logs and tooling, not hot paths.\n */\nexport const pretty = (filter: Any): string => internal.prettyFilter(filter.ast);\n\n/**\n * Create a predicate from a filter.\n *\n * @performance O(filter size) per entity in memory; a text-search clause serializes the whole entity on every match.\n */\nexport const toPredicate: {\n <T extends Entity.Unknown>(filter: Filter<T>): (entity: Entity.Unknown) => entity is T;\n <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>): entity is T;\n} = Function.dual<\n <T extends Entity.Unknown>(filter: Filter<T>) => (entity: Entity.Unknown) => entity is T,\n <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>) => entity is T\n>(2, <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>): entity is T =>\n internal.filterMatchEntity(filter.ast, entity),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,eAAe;AAmB5B,IAAM,cAAN,MAAM,YAA2B;CAGH;CAF5B,OAAe,aAAgC,CAAC;CAEhD,Y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,OAAO;GACL,MAAM;GACN,UAAU;GACV,OAPkB,OAAO,YACzB,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,iBAAiB,KAAK,CAAC,CAAC,CAMvE;EACT;CACF,CACF,GACA,MAAM,QAAQ,UAAU,GAAG,KAAK,CAAC,CAAC,GAAG,CACvC;AACF;;;;;;AAOA,IAAa,UAAU,WAAwBG,aAAsB,OAAO,GAAG;;;;;;AAO/E,IAAa,cAGT,SAAS,KAGX,IAA8B,QAAwB,WACtDC,kBAA2B,OAAO,KAAK,MAAM,CAC/C"}
1
+ {"version":3,"file":"chunk-Filter.mjs","names":["internal.getTypeURIFromSpecifier","Ref.isRef","internal.isProjection","internal.getUri","internal.prettyFilter","internal.filterMatchEntity"],"sources":["../../src/Filter.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Function from 'effect/Function';\nimport * as Match from 'effect/Match';\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport { type ForeignKey, type QueryAST } from '@dxos/echo-protocol';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\n\nimport type * as Annotation from './Annotation.ts';\nimport type * as Change from './Change.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as Feed from './Feed.ts';\nimport * as internal from './internal/index.ts';\nimport type * as Obj from './Obj.ts';\nimport * as Ref from './Ref.ts';\n// eslint-disable-next-line @dxos/rules/import-as-namespace\nimport type * as Type$ from './Type.ts';\n\nexport const FilterTypeId = '~@dxos/echo/Filter' as const;\nexport type FilterTypeId = typeof FilterTypeId;\n\nexport interface Filter<T> {\n // TODO(dmaretskyi): See new effect-schema approach to variance.\n readonly [FilterTypeId]: { value: Types.Covariant<T> };\n\n ast: QueryAST.Filter;\n}\n\nexport type Props<T> = {\n // Predicate or a value as a shorthand for `eq`.\n [K in keyof T & string]?: Filter<T[K]> | T[K];\n};\n\nexport type Any = Filter<any>;\n\nexport type Type<F extends Any> = F extends Filter<infer T> ? T : never;\n\nclass FilterClass implements Any {\n private static 'variance': Any[FilterTypeId] = {} as Any[FilterTypeId];\n\n constructor(public readonly ast: QueryAST.Filter) {}\n\n [FilterTypeId] = FilterClass.variance;\n}\n\n/**\n * Type guard for filters.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const is = (value: unknown): value is Any => {\n return typeof value === 'object' && value !== null && FilterTypeId in value;\n};\n\n/**\n * Construct a filter from an ast.\n *\n * @performance O(1); wraps the AST without copying it.\n */\nexport const fromAst = (ast: QueryAST.Filter): Any => {\n return new FilterClass(ast);\n};\n\n/**\n * Filter that matches all objects.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\n// TODO(dmaretskyi): `Entity.Any` would be more type-safe, but causes annoying errors in existing code\nexport const everything = (): FilterClass => {\n return new FilterClass({\n type: 'object',\n typename: null,\n props: {},\n });\n};\n\n/**\n * Filter that matches no objects.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const nothing = (): FilterClass => {\n return new FilterClass({\n type: 'not',\n filter: {\n type: 'object',\n typename: null,\n props: {},\n },\n });\n};\n\n/**\n * Filter by EntityId.\n *\n * @performance O(k) in the number of ids (validated); builds the AST without matching anything.\n */\nexport const id = (...ids: EntityId[]): Any => {\n assertArgument(\n ids.every((id) => EntityId.isValid(id)),\n 'ids',\n 'ids must be valid',\n );\n\n if (ids.length === 0) {\n return nothing();\n }\n\n return new FilterClass({\n type: 'object',\n typename: null,\n id: ids,\n props: {},\n });\n};\n\n/**\n * Filter by the id of an entity already in hand, keeping its type for the rest of the chain.\n *\n * @example\n * ```ts\n * db.query(Query.select(Filter.entity(task)).reference('watchers'));\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const entity: {\n <T extends Entity.Unknown>(entity: T): Filter<T>;\n <T extends Obj.Unknown>(snapshot: Obj.Snapshot<T>): Filter<T>;\n} = (entity: Entity.Unknown | Entity.Snapshot): Filter<any> => id(entity.id);\n\n/**\n * Filter by mnemonic — the human-memorable short form of an object's id (see `Obj.getMnemonic`).\n * Input is case-insensitive.\n *\n * @example\n * ```ts\n * const [task] = await db.query(Filter.mnemonic('7qk2zb')).run();\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const mnemonic = (mnemonic: string): Any => {\n const normalized = EntityId.normalizeMnemonic(mnemonic);\n assertArgument(\n EntityId.isValidMnemonic(normalized),\n 'mnemonic',\n `mnemonic must be ${EntityId.mnemonicLength} base32 characters`,\n );\n\n return new FilterClass({\n type: 'mnemonic',\n mnemonic: normalized,\n });\n};\n\n/**\n * Filter by type.\n *\n * Accepts a `Type.Type` entity (the value produced by `Type.makeObject` /\n * `Type.makeRelation`), a `Schema.Union` of such entities (for filtering across a\n * union of ECHO types), or a fully-qualified type URI — an `echo:` EID (stored schema)\n * or a `dxn:` DXN (static schema). To filter by a bare typename, wrap it: `DXN.make(typename)`.\n *\n * @performance O(1) plus O(p) for props (O(k) for a union); builds the AST without matching anything.\n */\nexport const type: {\n <T extends Type$.AnyEntity>(type: T, props?: Props<Type$.InstanceType<T>>): Filter<Type$.InstanceType<T>>;\n // Schema-side overload restricted to the well-known unknown schemas and to\n // `Schema.Union(...)` of `Type.Type` entities (for filtering across a union\n // of ECHO types). Other raw schemas are rejected.\n <S extends internal.UnknownTypeSchema<any, any>>(\n schema: S,\n props?: Props<Schema.Schema.Type<S>>,\n ): Filter<Schema.Schema.Type<S>>;\n <S extends Schema.Union<readonly Schema.Codec<any, any>[]>>(\n union: S,\n props?: Props<Schema.Schema.Type<S>>,\n ): Filter<Schema.Schema.Type<S>>;\n (uri: URI.URI, props?: Props<unknown>): Filter<any>;\n // Passthrough overload for callers that hold a `Type.AnyEntity | URI.URI` union\n // (e.g. Query.type / Query.sourceOf / Query.targetOf impls). Listed last so the\n // typed overloads above still win for monomorphic inputs.\n (input: Type$.AnyEntity | URI.URI, props?: Props<unknown>): Filter<unknown>;\n} = (input: Type$.AnyEntity | Schema.Codec<any, any> | URI.URI, props?: Props<unknown>): any => {\n if (Schema.isSchema(input) && SchemaAST.isUnion(input.ast)) {\n const typenames = input.ast.types.map((t) => internal.getTypeURIFromSpecifier(Schema.make(t)));\n return new FilterClass({\n type: 'or',\n filters: typenames.map((typename) => ({\n type: 'object',\n typename,\n props: {},\n })),\n });\n }\n\n const uri = internal.getTypeURIFromSpecifier(input);\n return new FilterClass({\n type: 'object',\n typename: uri,\n ...propsFilterToAst(props ?? {}),\n });\n};\n\n/**\n * Filter by tag.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const tag = (tag: string): Any => {\n return new FilterClass({\n type: 'tag',\n tag,\n });\n};\n\n/**\n * Filter by an annotation set on the entity with `Annotation.set`.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const annotation: {\n /** Matches entities that carry the annotation, whatever its value. */\n <T>(annotation: Annotation.Annotation<T>): Any;\n /** Matches entities whose value equals `value`; only scalar values can be compared. */\n <T extends string | number | boolean>(annotation: Annotation.Annotation<T>, value: T): Any;\n} = (annotation: Annotation.Annotation<unknown>, value?: string | number | boolean): Any => {\n return new FilterClass({\n type: 'annotation',\n key: annotation.key,\n ...(value !== undefined ? { value } : {}),\n });\n};\n\n/**\n * Options for {@link key} filter.\n */\nexport type KeyFilterOptions = {\n /**\n * Optional semver range expression (e.g. `^1.2.3`, `~2.0.0`, `>=1.0.0 <2.0.0`).\n * Matches the object's meta `version` field against the range.\n * If omitted, matches any version (including objects with no version).\n */\n version?: string;\n};\n\n/**\n * Filter by registry key stored in object meta.\n *\n * @example\n * ```ts\n * Filter.key('com.example.type.foo');\n * Filter.key('com.example.type.foo', { version: '^1.2.3' });\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const key = (key: string, options?: KeyFilterOptions): Any => {\n return new FilterClass({\n type: 'object',\n typename: null,\n props: {},\n metaKey: key,\n metaVersion: options?.version,\n });\n};\n\n/**\n * Filter by properties.\n *\n * @performance O(p) in the number of predicates; builds the AST without matching anything.\n */\nexport const props = <T>(props: Props<T>): Filter<T> => {\n return new FilterClass({\n type: 'object',\n typename: null,\n ...propsFilterToAst(props),\n });\n};\n\nexport type TextSearchOptions = {\n // TODO(dmaretskyi): Hybrid search.\n type?: 'full-text' | 'vector';\n};\n\n/**\n * Full-text or vector search.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const text = (\n // TODO(dmaretskyi): Consider passing a vector here, but really the embedding should be done on the query-executor side.\n text: string,\n options?: TextSearchOptions,\n): Any => {\n return new FilterClass({\n type: 'text-search',\n text,\n searchKind: options?.type,\n });\n};\n\n/**\n * Filter by foreign keys.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const foreignKeys = <S extends Type$.AnyEntity | URI.URI>(\n schema: S,\n keys: ForeignKey[],\n): Filter<S extends Type$.AnyEntity ? Type$.InstanceType<S> : unknown> => {\n const uri = internal.getTypeURIFromSpecifier(schema);\n return new FilterClass({\n type: 'object',\n typename: uri,\n props: {},\n foreignKeys: keys,\n });\n};\n\n/**\n * Predicate for property to be equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const eq = <T>(value: T): Filter<T | undefined> => {\n if (!Ref.isRef(value) && typeof value === 'object' && value !== null) {\n throw new TypeError('Cannot use object as a value for eq filter');\n }\n\n return new FilterClass({\n type: 'compare',\n operator: 'eq',\n value: Ref.isRef(value) ? value.noInline().encode() : value,\n });\n};\n\n/**\n * Predicate for property to be not equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const neq = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'neq',\n value,\n });\n};\n\n/**\n * Predicate for property to be greater than the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const gt = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'gt',\n value,\n });\n};\n\n/**\n * Predicate for property to be greater than or equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const gte = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'gte',\n value,\n });\n};\n\n/**\n * Predicate for property to be less than the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const lt = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'lt',\n value,\n });\n};\n\n/**\n * Predicate for property to be less than or equal to the provided value.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const lte = <T>(value: T): Filter<T | undefined> => {\n return new FilterClass({\n type: 'compare',\n operator: 'lte',\n value,\n });\n};\n\n/**\n * Predicate for property to be in the provided array, or in the set of values projected\n * from a subquery's results (an uncorrelated `col IN (SELECT property FROM ...)` semi-join —\n * see `Query.project`). The subquery may target a different scope than the parent query; it\n * is resolved once at execution time.\n * @param values - Values to check against, or a single subquery projection.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nconst in$: {\n <T>(projection: internal.Projection<T>): Filter<T>;\n <T>(...values: T[]): Filter<T>;\n} = <T>(...args: [internal.Projection<T>] | T[]): Filter<T> => {\n if (args.length === 1 && internal.isProjection(args[0])) {\n const projection = args[0];\n return new FilterClass({\n type: 'in-query',\n subquery: projection.query,\n property: projection.property,\n });\n }\n return new FilterClass({\n type: 'in',\n values: args,\n });\n};\nexport { in$ as in };\n\n/**\n * Predicate for an array property to contain the provided value.\n * @param value - Value to check against.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const contains = <T>(value: T): Filter<readonly T[] | undefined> => {\n return new FilterClass({\n type: 'contains',\n value,\n });\n};\n\n/**\n * Predicate for property to be in the provided range.\n * @param from - Start of the range (inclusive).\n * @param to - End of the range (exclusive).\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const between = <T>(from: T, to: T): Filter<T> => {\n return new FilterClass({\n type: 'range',\n from,\n to,\n });\n};\n\ntype TimeRange = { after?: Date | number; before?: Date | number };\n\nconst _toUnixMs = (date: Date | number): number => (typeof date === 'number' ? date : date.getTime());\n\nconst _timeRangeFilter = (field: 'updatedAt' | 'createdAt', range: TimeRange): Any => {\n const filters: Any[] = [];\n if (range.after != null) {\n filters.push(new FilterClass({ type: 'timestamp', field, operator: 'gte', value: _toUnixMs(range.after) }));\n }\n if (range.before != null) {\n filters.push(new FilterClass({ type: 'timestamp', field, operator: 'lte', value: _toUnixMs(range.before) }));\n }\n if (filters.length === 0) {\n return everything();\n }\n return filters.length === 1 ? filters[0] : and(...filters);\n};\n\n/**\n * Filter objects by updatedAt timestamp.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const updated = (range: TimeRange): Any => _timeRangeFilter('updatedAt', range);\n\n/**\n * Filter objects by createdAt timestamp.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const created = (range: TimeRange): Any => _timeRangeFilter('createdAt', range);\n\n/**\n * Range of feed cursors, as read off items with `Feed.getCursor`.\n * Both bounds name an item and exclude it: `begin` is the last item already consumed, `end` the\n * first item not wanted.\n */\nexport type FeedCursorRange = {\n /** Read after this cursor. Defaults to the start of the feed ({@link Feed.START}). */\n begin?: Feed.Cursor | Feed.LocalCursor;\n /** Read up to but not including this cursor. Defaults to the end of the feed. */\n end?: Feed.Cursor;\n /**\n * The order the cursors are positions in: `edge`, the position the authority assigned\n * ({@link Feed.getCursor}), or `local`, a walk's local cursor ({@link Feed.getLocalCursor}).\n * Defaults to `local` in a walk scope and `edge` elsewhere.\n */\n positions?: 'local' | 'edge';\n};\n\n/**\n * Filter feed items to a cursor range — see `Feed.getCursor` for reading a cursor off an item, and\n * `Feed.START` for the sentinel that bounds nothing.\n *\n * The range is pushed into the index scan, so a reader that keeps a cursor pays for what is new\n * rather than for the whole feed. Combine with `limit()` for a bounded page. Results come back in\n * append order and cover positioned items only — an item a peer wrote but the position authority\n * has not yet acknowledged has no place in that order, and `Feed.START` selects the same set from\n * the beginning rather than everything. Only meaningful against a feed scope — an automerge object\n * carries no position, so a query that also selects a space's documents is rejected.\n *\n * @example\n * ```ts\n * // The next 10 items after the last one this reader consumed.\n * db.query(Query.select(Filter.feedCursor({ begin: cursor })).limit(10).from(feed));\n *\n * // Everything between two known items, excluding both.\n * db.query(Query.select(Filter.feedCursor({ begin: first, end: last })).from(feed));\n * ```\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const feedCursor = (range: FeedCursorRange = {}): Any =>\n new FilterClass({\n type: 'feed-cursor',\n ...(range.begin !== undefined ? { begin: range.begin } : {}),\n ...(range.end !== undefined ? { end: range.end } : {}),\n ...(range.positions !== undefined ? { positions: range.positions } : {}),\n });\n\nexport type ChildOfOptions = {\n /** Whether to match transitively (grandchildren, etc.). Defaults to true. */\n transitive?: boolean;\n};\n\n/**\n * Filter objects that are children of the specified parent(s).\n * Accepts ECHO objects, Refs, or arrays of either.\n * Refs are resolved to DXNs without loading; objects use {@link Obj.getURI}.\n * With transitive=true (default), also matches grandchildren and beyond.\n *\n * @performance O(k) in the number of parents; refs are read by URI without loading.\n */\nexport const childOf = (\n parents: Obj.Unknown | Ref.Unknown | readonly (Obj.Unknown | Ref.Unknown)[],\n options?: ChildOfOptions,\n): Any => {\n const items = Array.isArray(parents) ? parents : [parents];\n const dxns = items.map((item) => {\n if (Ref.isRef(item)) {\n return EID.parse(item.uri);\n }\n return EID.parse(internal.getUri(item));\n });\n return new FilterClass({\n type: 'child-of',\n parents: dxns,\n transitive: options?.transitive ?? true,\n });\n};\n\n/**\n * Select Automerge changes instead of objects: one {@link Change.Change} per change to the documents\n * holding `targets`, or to every document in the space when called with no argument.\n *\n * Changes belong to documents, not entities. Entities that share a document share its changes, and\n * content held by another entity (a document's `Text`) needs its own target. Only the host answers\n * these queries; a space-wide query must aggregate, and the index answers it only at hour\n * granularity (see `Aggregate.time`).\n *\n * @example\n * ```ts\n * Query.select(Filter.changes()).aggregate({ day: Aggregate.time('time', 'day'), changes: Aggregate.count() });\n * Query.select(Filter.changes([doc, doc.content])).orderBy(Order.property('time', 'desc')).limit(50);\n * ```\n *\n * @performance O(k) in the number of targets; refs are read by URI without loading.\n */\nexport const changes = (\n targets?: Obj.Unknown | Ref.Unknown | readonly (Obj.Unknown | Ref.Unknown)[],\n): Filter<Change.Change> => {\n if (targets === undefined) {\n return new FilterClass({ type: 'changes' });\n }\n const items = Array.isArray(targets) ? targets : [targets];\n return new FilterClass({\n type: 'changes',\n targets: items.map((item) => (Ref.isRef(item) ? EID.parse(item.uri) : EID.parse(internal.getUri(item)))),\n });\n};\n\n/**\n * Filter objects by whether they have a parent, regardless of which object it is.\n * `Filter.hasParent(false)` selects root objects — those never passed to `Obj.setParent`.\n * Unlike {@link childOf} this reads the object's own parent slot, so it costs no traversal.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const hasParent = (value = true): Any =>\n new FilterClass({\n type: 'has-parent',\n value,\n });\n\n/**\n * Negate the filter.\n *\n * @performance O(1); builds a filter AST node without matching anything.\n */\nexport const not = <F extends Any>(filter: F): Filter<Type<F>> => {\n return new FilterClass({\n type: 'not',\n filter: filter.ast,\n });\n};\n\n/**\n * Combine filters with a logical AND.\n *\n * @performance O(k) in the number of filters; builds the AST without matching anything.\n */\nexport const and = <Filters extends readonly Any[]>(...filters: Filters): Filter<Type<Filters[number]>> => {\n return new FilterClass({\n type: 'and',\n filters: filters.map((f) => f.ast),\n });\n};\n\n/**\n * Combine filters with a logical OR.\n *\n * @performance O(k) in the number of filters; builds the AST without matching anything.\n */\nexport const or = <Filters extends readonly Any[]>(...filters: Filters): Filter<Type<Filters[number]>> => {\n return new FilterClass({\n type: 'or',\n filters: filters.map((f) => f.ast),\n });\n};\n\n// TODO(dmaretskyi): Add `Filter.match` to support pattern matching on string props.\n\nconst propsFilterToAst = (predicates: Props<any>): Pick<QueryAST.FilterObject, 'id' | 'props'> => {\n let idFilter: readonly EntityId[] | undefined;\n if ('id' in predicates) {\n assertArgument(\n typeof predicates.id === 'string' || Array.isArray(predicates.id),\n 'predicates.id',\n 'invalid id filter',\n );\n idFilter = typeof predicates.id === 'string' ? [predicates.id] : predicates.id;\n Schema.decodeSync(Schema.toType(Schema.Array(EntityId)))(idFilter);\n }\n\n return {\n id: idFilter,\n props: Object.fromEntries(\n Object.entries(predicates)\n .filter(([prop, _value]) => prop !== 'id')\n .map(([prop, predicate]) => [prop, processPredicate(predicate)]),\n ) as Record<string, QueryAST.Filter>,\n };\n};\n\nconst processPredicate = (predicate: any): QueryAST.Filter => {\n return Match.value(predicate).pipe(\n Match.withReturnType<QueryAST.Filter>(),\n Match.when(is, (predicate) => predicate.ast),\n // TODO(wittjosiah): Add support for array predicates.\n Match.when(Array.isArray, (_predicate) => {\n throw new Error('Array predicates are not yet supported.');\n }),\n Match.when(\n (predicate: any) => !Ref.isRef(predicate) && typeof predicate === 'object' && predicate !== null,\n (predicate) => {\n const nestedProps = Object.fromEntries(\n Object.entries(predicate).map(([key, value]) => [key, processPredicate(value)]),\n );\n\n return {\n type: 'object',\n typename: null,\n props: nestedProps,\n };\n },\n ),\n Match.orElse((value) => eq(value).ast),\n );\n};\n\n/**\n * Returns a human-readable string representation of a Filter AST.\n *\n * @performance O(AST size) string build; meant for logs and tooling, not hot paths.\n */\nexport const pretty = (filter: Any): string => internal.prettyFilter(filter.ast);\n\n/**\n * Create a predicate from a filter.\n *\n * @performance O(filter size) per entity in memory; a text-search clause serializes the whole entity on every match.\n */\nexport const toPredicate: {\n <T extends Entity.Unknown>(filter: Filter<T>): (entity: Entity.Unknown) => entity is T;\n <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>): entity is T;\n} = Function.dual<\n <T extends Entity.Unknown>(filter: Filter<T>) => (entity: Entity.Unknown) => entity is T,\n <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>) => entity is T\n>(2, <T extends Entity.Unknown>(entity: Entity.Unknown, filter: Filter<T>): entity is T =>\n internal.filterMatchEntity(filter.ast, entity),\n);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KAC5B,MAAM,eAAgC,GACtC,MAAM,KAAK,KAAK,cAAc,UAAU,GAAG,GAE3C,MAAM,KAAK,MAAM,UAAU,eAAe;EACxC,MAAM,IAAI,MAAM,yCAAyC;CAC3D,CAAC,GACD,MAAM,MACH,cAAmB,CAACF,MAAU,SAAS,KAAK,OAAO,cAAc,YAAY,cAAc,OAC3F,cAAc;EAKb,OAAO;GACL,MAAM;GACN,UAAU;GACV,OAPkB,OAAO,YACzB,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,iBAAiB,KAAK,CAAC,CAAC,CAMvE;EACT;CACF,CACF,GACA,MAAM,QAAQ,UAAU,GAAG,KAAK,CAAC,CAAC,GAAG,CACvC;AACF;;;;;;AAOA,IAAa,UAAU,WAAwBG,aAAsB,OAAO,GAAG;;;;;;AAO/E,IAAa,cAGT,SAAS,KAGX,IAA8B,QAAwB,WACtDC,kBAA2B,OAAO,KAAK,MAAM,CAC/C"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { _ as getOptionsAnnotation, c as FormatAnnotationId, d as OptionsAnnotationId, f as PropertyKind, g as getFormatAnnotation, h as formatToType, l as FormatEnums, m as TypeFormat, n as CurrencyAnnotationId, p as TypeEnum, r as DecimalPrecision, s as FormatAnnotation, t as Currency, u as OptionsAnnotation, v as getTypeEnum, y as typeToFormat } from "./chunk-number.mjs";
3
- import { _ as SimpleTime, a as Hostname, b as toSimpleDateTime, c as URL, d as GeoPoint, f as DateOnly, g as SimpleDateTime, h as SimpleDate, i as Formula, l as UUID, m as Duration, n as Format, o as Regex, p as DateTime, r as Email, s as Text, t as SelectOption, u as GeoLocation, v as TimeOnly, x as toSimpleTime, y as toSimpleDate } from "./chunk-select.mjs";
3
+ import { S as toSimpleTime, _ as SimpleDateTime, a as Hostname, b as toSimpleDate, c as Text, d as GeoLocation, f as GeoPoint, g as SimpleDate, h as Duration, i as Formula, l as URL, m as DateTime, n as Format, o as Markdown, p as DateOnly, r as Email, s as Regex, t as SelectOption, u as UUID, v as SimpleTime, x as toSimpleDateTime, y as TimeOnly } from "./chunk-select.mjs";
4
4
  //#region src/Format.ts
5
5
  var Format_exports = /* @__PURE__ */ __exportAll({
6
6
  Currency: () => Currency,
@@ -18,6 +18,7 @@ var Format_exports = /* @__PURE__ */ __exportAll({
18
18
  GeoLocation: () => GeoLocation,
19
19
  GeoPoint: () => GeoPoint,
20
20
  Hostname: () => Hostname,
21
+ Markdown: () => Markdown,
21
22
  OptionsAnnotation: () => OptionsAnnotation,
22
23
  OptionsAnnotationId: () => OptionsAnnotationId,
23
24
  PropertyKind: () => PropertyKind,
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { _ as makeService$1, i as Service$1 } from "./chunk-Database.mjs";
2
+ import { i as Service$1, v as makeService$1 } from "./chunk-Database.mjs";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Context from "effect/Context";
5
5
  import * as Layer from "effect/Layer";
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Hypergraph.mjs","names":["Database.Service","Database.makeService"],"sources":["../../src/Hypergraph.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type CleanupFn } from '@dxos/async';\nimport { type BlobBackend } from '@dxos/blob';\nimport { BaseError } from '@dxos/errors';\nimport { type URI } from '@dxos/keys';\n\nimport * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as Key from './Key.ts';\nimport type * as Ref from './Ref.ts';\nimport type * as Registry from './Registry.ts';\n\n/**\n * Resolution context.\n * Affects how non-absolute DXNs are resolved.\n */\nexport interface RefResolutionContext {\n /**\n * Space that the resolution is happening from.\n */\n space?: Key.SpaceId;\n\n /**\n * Feed that the resolution is happening from.\n * This feed will be searched first, and then the space it belongs to.\n */\n feed?: URI.URI;\n}\n\nexport interface RefResolverOptions {\n /**\n * Resolution context.\n * Affects how non-absolute DXNs are resolved.\n */\n context?: RefResolutionContext;\n}\n\n/**\n * Manages cross-space database interactions.\n */\nexport interface Hypergraph extends Database.Queryable {\n /**\n * In-process registry of keyed objects and static schema types.\n * Populated at startup via `registry.add(objects)` / `registry.add(schemas)`.\n * Queries that include no explicit from() clause will fan out to this registry automatically.\n */\n get registry(): Registry.Registry;\n\n /**\n * Query objects.\n *\n * @performance O(AST size) to key the result cache; returns a shared, lazily executed result, so nothing runs until\n * read.\n */\n query: Database.QueryFn;\n\n /**\n * Creates a reference to an existing object in the database.\n *\n * NOTE: The reference may be dangling if the object is not present in the database.\n * NOTE: Difference from `Ref.fromURI`\n * `Ref.fromURI(dxn)` returns an unhydrated reference. The `.load` and `.target` APIs will not work.\n * `db.makeRef(dxn)` is preferable in cases with access to the database.\n *\n * @performance O(1); allocates a resolver-bound ref without looking the target up.\n */\n makeRef<T extends Entity.Unknown = Entity.Unknown>(uri: URI.URI): Ref.Ref<T>;\n\n /**\n * Create a resolver that dereferences `Ref`s against this graph. Persisted schema objects are\n * surfaced as their registered `Type.Type` entity.\n *\n * @performance O(1); allocates a resolver closure.\n */\n createRefResolver(options: RefResolverOptions): Ref.Resolver;\n\n /**\n * Get a database by space ID.\n * @returns The database for the given space ID, or undefined if not found.\n *\n * @performance O(1) map lookup.\n */\n getDatabase(spaceId: Key.SpaceId): Database.Database | undefined;\n\n /**\n * Registers a pluggable blob storage backend under `name`, claiming its declared URI schemes.\n * Registering a scheme already claimed by another backend is an error.\n *\n * @param options.default - When true, `name` becomes the storage used when\n * `Blob.fromBytes`'s `storage` option is omitted.\n * @returns A cleanup function that unregisters the backend.\n *\n * @performance O(s) in the backend URI schemes.\n */\n registerBlobBackend(name: string, backend: BlobBackend, options?: { default?: boolean }): CleanupFn;\n\n /**\n * Storage name `Blob.fromBytes` uses when its `storage` option is omitted. Starts as `'inline'`;\n * reflects the most recent `registerBlobBackend(name, backend, { default: true })` call.\n */\n get defaultBlobStorage(): string;\n}\n\n/**\n * Effect service tag for Hypergraph dependency injection.\n *\n * Distinct from {@link Database.Service}, which carries one space's database: an operation\n * declaring the database is declaring that it acts on a space, and callers that cannot name one\n * (a harness hook fires a fixed payload) are refused before the handler runs. This service is the\n * cross-space handle — query every space, or reach one by id with `getDatabase` — for the work\n * that has to find its own space rather than be told it.\n */\nexport class Service extends Context.Service<\n Service,\n {\n readonly graph: Hypergraph;\n }\n>()('@dxos/echo/Hypergraph/Service') {}\n\n/**\n * Layer that provides a Hypergraph service that throws when accessed. The default where no graph\n * exists, so a host that never wires one fails loudly at the call rather than silently resolving\n * nothing.\n */\nexport const notAvailable = Layer.succeed(Service, {\n get graph(): Hypergraph {\n throw new globalThis.Error('Hypergraph not available');\n },\n});\n\n/**\n * Creates a Hypergraph service instance from a graph.\n *\n * @performance O(1).\n */\nexport const makeService = (graph: Hypergraph): Service['Service'] => ({\n get graph() {\n return graph;\n },\n});\n\n/**\n * Creates a Layer that provides the Hypergraph service.\n *\n * @performance O(1).\n */\nexport const layer = (graph: Hypergraph): Layer.Layer<Service> => Layer.succeed(Service, makeService(graph));\n\n/** The graph holds no database for the requested space — it is not open, or does not exist. */\nexport class SpaceNotFoundError extends BaseError.extend('SpaceNotFoundError', 'Space not found.') {}\n\n/**\n * Narrows the graph to one space's {@link Database.Service}.\n *\n * The bridge between the two services: work that had to *find* a space still wants to be written\n * with the ordinary space-scoped API once it has one, and every caller doing that by hand would\n * otherwise reimplement the same lookup-and-fail. The space id is resolved when the layer is built,\n * so a missing space fails there rather than at the first query.\n *\n * @performance O(1) map lookup when the layer is built.\n */\nexport const withDatabase = (spaceId: Key.SpaceId): Layer.Layer<Database.Service, SpaceNotFoundError, Service> =>\n Layer.effect(\n Database.Service,\n Effect.gen(function* () {\n const { graph } = yield* Service;\n const db = graph.getDatabase(spaceId);\n if (!db) {\n return yield* Effect.fail(new SpaceNotFoundError({ context: { spaceId } }));\n }\n return Database.makeService(db);\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuHA,IAAa,UAAb,cAA6B,QAAQ,QAKnC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC;;;;;;AAOtC,IAAa,eAAe,MAAM,QAAQ,SAAS,EACjD,IAAI,QAAoB;CACtB,MAAM,IAAI,WAAW,MAAM,0BAA0B;AACvD,EACF,CAAC;;;;;;AAOD,IAAa,eAAe,WAA2C,EACrE,IAAI,QAAQ;CACV,OAAO;AACT,EACF;;;;;;AAOA,IAAa,SAAS,UAA4C,MAAM,QAAQ,SAAS,YAAY,KAAK,CAAC;;AAG3G,IAAa,qBAAb,cAAwC,UAAU,OAAO,sBAAsB,kBAAkB,CAAC,CAAC,CAAC;;;;;;;;;;;AAYpG,IAAa,gBAAgB,YAC3B,MAAM,OACJA,WACA,OAAO,IAAI,aAAa;CACtB,MAAM,EAAE,UAAU,OAAO;CACzB,MAAM,KAAK,MAAM,YAAY,OAAO;CACpC,IAAI,CAAC,IACH,OAAO,OAAO,OAAO,KAAK,IAAI,mBAAmB,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC;CAE5E,OAAOC,cAAqB,EAAE;AAChC,CAAC,CACH"}
1
+ {"version":3,"file":"chunk-Hypergraph.mjs","names":["Database.Service","Database.makeService"],"sources":["../../src/Hypergraph.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type CleanupFn } from '@dxos/async';\nimport { type BlobBackend } from '@dxos/blob';\nimport { BaseError } from '@dxos/errors';\nimport { type URI } from '@dxos/keys';\n\nimport * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as Key from './Key.ts';\nimport type * as Ref from './Ref.ts';\nimport type * as Registry from './Registry.ts';\n\n/**\n * Resolution context.\n * Affects how non-absolute DXNs are resolved.\n */\nexport interface RefResolutionContext {\n /**\n * Space that the resolution is happening from.\n */\n space?: Key.SpaceId;\n\n /**\n * Feed that the resolution is happening from.\n * This feed will be searched first, and then the space it belongs to.\n */\n feed?: URI.URI;\n}\n\nexport interface RefResolverOptions {\n /**\n * Resolution context.\n * Affects how non-absolute DXNs are resolved.\n */\n context?: RefResolutionContext;\n}\n\n/**\n * Manages cross-space database interactions.\n */\nexport interface Hypergraph extends Database.Queryable {\n /**\n * In-process registry of keyed objects and static schema types.\n * Populated at startup via `registry.add(objects)` / `registry.add(schemas)`.\n * A query reads this registry only when its from() clause names `Scope.registry()`.\n */\n get registry(): Registry.Registry;\n\n /**\n * Query objects.\n *\n * @performance O(AST size) to key the result cache; returns a shared, lazily executed result, so nothing runs until\n * read.\n */\n query: Database.QueryFn;\n\n /**\n * Creates a reference to an existing object in the database.\n *\n * NOTE: The reference may be dangling if the object is not present in the database.\n * NOTE: Difference from `Ref.fromURI`\n * `Ref.fromURI(dxn)` returns an unhydrated reference. The `.load` and `.target` APIs will not work.\n * `db.makeRef(dxn)` is preferable in cases with access to the database.\n *\n * @performance O(1); allocates a resolver-bound ref without looking the target up.\n */\n makeRef<T extends Entity.Unknown = Entity.Unknown>(uri: URI.URI): Ref.Ref<T>;\n\n /**\n * Create a resolver that dereferences `Ref`s against this graph. Persisted schema objects are\n * surfaced as their registered `Type.Type` entity.\n *\n * @performance O(1); allocates a resolver closure.\n */\n createRefResolver(options: RefResolverOptions): Ref.Resolver;\n\n /**\n * Get a database by space ID.\n * @returns The database for the given space ID, or undefined if not found.\n *\n * @performance O(1) map lookup.\n */\n getDatabase(spaceId: Key.SpaceId): Database.Database | undefined;\n\n /**\n * Registers a pluggable blob storage backend under `name`, claiming its declared URI schemes.\n * Registering a scheme already claimed by another backend is an error.\n *\n * @param options.default - When true, `name` becomes the storage used when\n * `Blob.fromBytes`'s `storage` option is omitted.\n * @returns A cleanup function that unregisters the backend.\n *\n * @performance O(s) in the backend URI schemes.\n */\n registerBlobBackend(name: string, backend: BlobBackend, options?: { default?: boolean }): CleanupFn;\n\n /**\n * Storage name `Blob.fromBytes` uses when its `storage` option is omitted. Starts as `'inline'`;\n * reflects the most recent `registerBlobBackend(name, backend, { default: true })` call.\n */\n get defaultBlobStorage(): string;\n}\n\n/**\n * Effect service tag for Hypergraph dependency injection.\n *\n * Distinct from {@link Database.Service}, which carries one space's database: an operation\n * declaring the database is declaring that it acts on a space, and callers that cannot name one\n * (a harness hook fires a fixed payload) are refused before the handler runs. This service is the\n * cross-space handle — query every space, or reach one by id with `getDatabase` — for the work\n * that has to find its own space rather than be told it.\n */\nexport class Service extends Context.Service<\n Service,\n {\n readonly graph: Hypergraph;\n }\n>()('@dxos/echo/Hypergraph/Service') {}\n\n/**\n * Layer that provides a Hypergraph service that throws when accessed. The default where no graph\n * exists, so a host that never wires one fails loudly at the call rather than silently resolving\n * nothing.\n */\nexport const notAvailable = Layer.succeed(Service, {\n get graph(): Hypergraph {\n throw new globalThis.Error('Hypergraph not available');\n },\n});\n\n/**\n * Creates a Hypergraph service instance from a graph.\n *\n * @performance O(1).\n */\nexport const makeService = (graph: Hypergraph): Service['Service'] => ({\n get graph() {\n return graph;\n },\n});\n\n/**\n * Creates a Layer that provides the Hypergraph service.\n *\n * @performance O(1).\n */\nexport const layer = (graph: Hypergraph): Layer.Layer<Service> => Layer.succeed(Service, makeService(graph));\n\n/** The graph holds no database for the requested space — it is not open, or does not exist. */\nexport class SpaceNotFoundError extends BaseError.extend('SpaceNotFoundError', 'Space not found.') {}\n\n/**\n * Narrows the graph to one space's {@link Database.Service}.\n *\n * The bridge between the two services: work that had to *find* a space still wants to be written\n * with the ordinary space-scoped API once it has one, and every caller doing that by hand would\n * otherwise reimplement the same lookup-and-fail. The space id is resolved when the layer is built,\n * so a missing space fails there rather than at the first query.\n *\n * @performance O(1) map lookup when the layer is built.\n */\nexport const withDatabase = (spaceId: Key.SpaceId): Layer.Layer<Database.Service, SpaceNotFoundError, Service> =>\n Layer.effect(\n Database.Service,\n Effect.gen(function* () {\n const { graph } = yield* Service;\n const db = graph.getDatabase(spaceId);\n if (!db) {\n return yield* Effect.fail(new SpaceNotFoundError({ context: { spaceId } }));\n }\n return Database.makeService(db);\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuHA,IAAa,UAAb,cAA6B,QAAQ,QAKnC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC;;;;;;AAOtC,IAAa,eAAe,MAAM,QAAQ,SAAS,EACjD,IAAI,QAAoB;CACtB,MAAM,IAAI,WAAW,MAAM,0BAA0B;AACvD,EACF,CAAC;;;;;;AAOD,IAAa,eAAe,WAA2C,EACrE,IAAI,QAAQ;CACV,OAAO;AACT,EACF;;;;;;AAOA,IAAa,SAAS,UAA4C,MAAM,QAAQ,SAAS,YAAY,KAAK,CAAC;;AAG3G,IAAa,qBAAb,cAAwC,UAAU,OAAO,sBAAsB,kBAAkB,CAAC,CAAC,CAAC;;;;;;;;;;;AAYpG,IAAa,gBAAgB,YAC3B,MAAM,OACJA,WACA,OAAO,IAAI,aAAa;CACtB,MAAM,EAAE,UAAU,OAAO;CACzB,MAAM,KAAK,MAAM,YAAY,OAAO;CACpC,IAAI,CAAC,IACH,OAAO,OAAO,OAAO,KAAK,IAAI,mBAAmB,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC;CAE5E,OAAOC,cAAqB,EAAE;AAChC,CAAC,CACH"}
@@ -1,26 +1,36 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { Ot as getSchemaURI } from "./chunk-Database.mjs";
2
+ import { It as getSchemaURI, V as ContentVersionAnnotation } from "./chunk-Database.mjs";
3
3
  import { d as getSchema } from "./chunk-Type.mjs";
4
4
  import { DXN } from "@dxos/keys";
5
+ import * as Option from "effect/Option";
6
+ import * as SchemaAST from "@dxos/effect/SchemaAST";
7
+ import * as SchemaEx from "@dxos/effect/SchemaEx";
5
8
  //#region src/Migration.ts
6
9
  var Migration_exports = /* @__PURE__ */ __exportAll({
7
10
  TypeId: () => TypeId,
11
+ applyContentSteps: () => applyContentSteps,
8
12
  define: () => define,
13
+ defineContent: () => defineContent,
9
14
  defineRename: () => defineRename,
15
+ defineTransaction: () => defineTransaction,
16
+ getContentSteps: () => getContentSteps,
17
+ isContentMigration: () => isContentMigration,
10
18
  isMigration: () => isMigration,
11
19
  isObjectMigration: () => isObjectMigration,
12
- isRenameMigration: () => isRenameMigration
20
+ isRenameMigration: () => isRenameMigration,
21
+ isTransactionMigration: () => isTransactionMigration,
22
+ upgradeContent: () => upgradeContent
13
23
  });
14
24
  var TypeId = "~@dxos/echo/Migration";
15
25
  /**
16
- * Type guard for values produced by {@link define} / {@link defineRename}.
26
+ * Type guard for values produced by {@link define} / {@link defineRename} / {@link defineContent}.
17
27
  *
18
28
  * @performance O(1) brand check; no allocation.
19
29
  */
20
30
  var isMigration = (value) => {
21
31
  if (typeof value !== "object" || value === null) return false;
22
32
  const candidate = value;
23
- return candidate["~@dxos/echo/Migration"] === "~@dxos/echo/Migration" && (candidate.kind === "object" || candidate.kind === "rename");
33
+ return candidate["~@dxos/echo/Migration"] === "~@dxos/echo/Migration" && (candidate.kind === "object" || candidate.kind === "rename" || candidate.kind === "content" || candidate.kind === "transaction");
24
34
  };
25
35
  /**
26
36
  * Narrows a migration to an {@link ObjectMigration}.
@@ -89,7 +99,147 @@ var defineRename = (options) => ({
89
99
  from: DXN.make(options.from),
90
100
  to: DXN.make(options.to)
91
101
  });
102
+ /**
103
+ * Narrows a migration to a {@link ContentMigration}.
104
+ *
105
+ * @performance O(1).
106
+ */
107
+ var isContentMigration = (migration) => migration.kind === "content";
108
+ /** The field a schema's {@link ContentVersionAnnotation} marks, with the fields it versions. */
109
+ var getContentVersionField = (ast) => {
110
+ for (const property of SchemaAST.getPropertySignatures(ast)) {
111
+ if (typeof property.name !== "string") continue;
112
+ const value = Option.getOrUndefined(Option.orElse(ContentVersionAnnotation.getFromAst(property.type), () => ContentVersionAnnotation.getFromAst(SchemaEx.unwrapOptional(property.type))));
113
+ if (value) return {
114
+ field: property.name,
115
+ fields: value.fields
116
+ };
117
+ }
118
+ };
119
+ var isRecordAst = (ast) => SchemaAST.isObjects(ast) && ast.propertySignatures.length === 0 && ast.indexSignatures.length > 0;
120
+ /**
121
+ * Define one step of a content format carried by an object type.
122
+ *
123
+ * The type's schema must mark its version field with {@link ContentVersionAnnotation}. Steps chain
124
+ * by version: an object at `from` is upgraded through every step reachable from it.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * const sceneParams = Migration.defineContent({
129
+ * type: Drawing.Canvas,
130
+ * from: 'dxos.org/scene/1',
131
+ * to: 'dxos.org/scene/2',
132
+ * since: '0.11.0',
133
+ * transform: ({ content }) => ({ content: upgradeRecords(content) }),
134
+ * });
135
+ * ```
136
+ *
137
+ * @performance O(fields) at definition time; walks the schema's top-level properties.
138
+ */
139
+ var defineContent = (options) => {
140
+ const schema = getSchema(options.type);
141
+ const type = getSchemaURI(schema);
142
+ if (!type) throw new Error("Invalid type schema");
143
+ const version = getContentVersionField(schema.ast);
144
+ if (!version) throw new Error(`Type has no ContentVersionAnnotation: ${type}`);
145
+ if (options.from.length === 0 || options.to.length === 0 || options.from === options.to) throw new Error(`Invalid content versions: ${options.from} -> ${options.to}`);
146
+ const properties = new Map(SchemaAST.getPropertySignatures(schema.ast).map((property) => [String(property.name), property]));
147
+ const recordFields = version.fields.filter((field) => {
148
+ const property = properties.get(field);
149
+ if (!property) throw new Error(`ContentVersionAnnotation names an unknown field: ${field}`);
150
+ return isRecordAst(SchemaEx.unwrapOptional(property.type));
151
+ });
152
+ return {
153
+ [TypeId]: TypeId,
154
+ kind: "content",
155
+ type,
156
+ versionField: version.field,
157
+ fields: version.fields,
158
+ recordFields,
159
+ from: options.from,
160
+ to: options.to,
161
+ since: options.since,
162
+ transform: options.transform
163
+ };
164
+ };
165
+ /**
166
+ * The content steps of `type` keyed by `from`.
167
+ *
168
+ * @throws When two steps start at the same version, since the chain would be ambiguous.
169
+ */
170
+ var getContentSteps = (migrations, type) => {
171
+ const steps = /* @__PURE__ */ new Map();
172
+ for (const migration of migrations) {
173
+ if (!isContentMigration(migration) || migration.type !== type) continue;
174
+ const existing = steps.get(migration.from);
175
+ if (existing && existing !== migration) throw new Error(`Ambiguous content migrations from ${migration.from}: ${existing.to}, ${migration.to}`);
176
+ steps.set(migration.from, migration);
177
+ }
178
+ return steps;
179
+ };
180
+ /**
181
+ * Upgrades content in memory through the chain of content steps declared for `type`, from `version`
182
+ * to the newest version reachable. Readers use it for data that synced in before the migration pass
183
+ * ran; the pass itself applies the same chain. Content at a version no step starts from is
184
+ * returned as it is (same reference).
185
+ *
186
+ * @performance O(steps) transforms; each costs what its `transform` does.
187
+ */
188
+ var upgradeContent = (migrations, type, version, content) => {
189
+ const uri = typeof type === "string" ? type : getSchemaURI(getSchema(type));
190
+ if (!uri || version === void 0) return {
191
+ version,
192
+ content
193
+ };
194
+ return applyContentSteps(getContentSteps(migrations, uri), version, content);
195
+ };
196
+ /**
197
+ * Applies the chain of `steps` starting at `version`.
198
+ *
199
+ * @throws When the chain loops back to a version it already passed.
200
+ */
201
+ var applyContentSteps = (steps, version, content) => {
202
+ const visited = /* @__PURE__ */ new Set([version]);
203
+ let current = version;
204
+ let result = content;
205
+ for (let step = steps.get(current); step; step = steps.get(current)) {
206
+ result = step.transform(result);
207
+ current = step.to;
208
+ if (visited.has(current)) throw new Error(`Content migrations loop at ${current}`);
209
+ visited.add(current);
210
+ }
211
+ return {
212
+ version: current,
213
+ content: result
214
+ };
215
+ };
216
+ /**
217
+ * Narrows a migration to a {@link TransactionMigration}.
218
+ *
219
+ * @performance O(1).
220
+ */
221
+ var isTransactionMigration = (migration) => migration.kind === "transaction";
222
+ /**
223
+ * Define a migration that stages structural changes in a {@link Transaction}.
224
+ * A failure of `run` rejects `db.runMigrations` and commits nothing.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * const migration = Migration.defineTransaction((transaction) =>
229
+ * Effect.sync(() => transaction.delete(legacyId)),
230
+ * );
231
+ * await db.runMigrations([migration]);
232
+ * ```
233
+ *
234
+ * @performance O(1) at definition time.
235
+ */
236
+ var defineTransaction = (run, options = {}) => ({
237
+ [TypeId]: TypeId,
238
+ kind: "transaction",
239
+ options,
240
+ run
241
+ });
92
242
  //#endregion
93
- export { isMigration as a, defineRename as i, TypeId as n, isObjectMigration as o, define as r, isRenameMigration as s, Migration_exports as t };
243
+ export { defineContent as a, getContentSteps as c, isObjectMigration as d, isRenameMigration as f, define as i, isContentMigration as l, upgradeContent as m, TypeId as n, defineRename as o, isTransactionMigration as p, applyContentSteps as r, defineTransaction as s, Migration_exports as t, isMigration as u };
94
244
 
95
245
  //# sourceMappingURL=chunk-Migration.mjs.map