@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.
- package/dist/lib/Annotation.mjs +2 -2
- package/dist/lib/Database.mjs +1 -1
- package/dist/lib/Error.mjs +1 -1
- package/dist/lib/Feed.mjs +1 -1
- package/dist/lib/Format.mjs +2 -2
- package/dist/lib/Migration.mjs +1 -1
- package/dist/lib/chunk-Annotation.mjs +14 -11
- package/dist/lib/chunk-Annotation.mjs.map +1 -1
- package/dist/lib/chunk-Blob.mjs +1 -1
- package/dist/lib/chunk-Collection.mjs +1 -1
- package/dist/lib/chunk-Database.mjs +93 -7
- package/dist/lib/chunk-Database.mjs.map +1 -1
- package/dist/lib/chunk-Dataset.mjs +1 -1
- package/dist/lib/chunk-Entity.mjs +2 -2
- package/dist/lib/chunk-Entity.mjs.map +1 -1
- package/dist/lib/chunk-Error.mjs +13 -1
- package/dist/lib/chunk-Error.mjs.map +1 -1
- package/dist/lib/chunk-Feed.mjs +311 -17
- package/dist/lib/chunk-Feed.mjs.map +1 -1
- package/dist/lib/chunk-Filter.mjs +4 -3
- package/dist/lib/chunk-Filter.mjs.map +1 -1
- package/dist/lib/chunk-Format.mjs +2 -1
- package/dist/lib/chunk-Hypergraph.mjs +1 -1
- package/dist/lib/chunk-Hypergraph.mjs.map +1 -1
- package/dist/lib/chunk-Migration.mjs +155 -5
- package/dist/lib/chunk-Migration.mjs.map +1 -1
- package/dist/lib/chunk-Obj.mjs +12 -5
- package/dist/lib/chunk-Obj.mjs.map +1 -1
- package/dist/lib/chunk-Query.mjs +2 -2
- package/dist/lib/chunk-QueryResult.mjs.map +1 -1
- package/dist/lib/chunk-Ref2.mjs +2 -2
- package/dist/lib/chunk-Registry.mjs +1 -1
- package/dist/lib/chunk-Registry.mjs.map +1 -1
- package/dist/lib/chunk-Relation.mjs +5 -5
- package/dist/lib/chunk-Relation.mjs.map +1 -1
- package/dist/lib/chunk-Scope.mjs +16 -2
- package/dist/lib/chunk-Scope.mjs.map +1 -1
- package/dist/lib/chunk-Tag.mjs +4 -4
- package/dist/lib/chunk-Tag.mjs.map +1 -1
- package/dist/lib/chunk-Text.mjs +2 -2
- package/dist/lib/chunk-Type.mjs +26 -7
- package/dist/lib/chunk-Type.mjs.map +1 -1
- package/dist/lib/chunk-View.mjs +1 -1
- package/dist/lib/chunk-atom-snapshot.mjs +29 -1
- package/dist/lib/chunk-atom-snapshot.mjs.map +1 -1
- package/dist/lib/chunk-entity-dictionary.mjs +28 -19
- package/dist/lib/chunk-entity-dictionary.mjs.map +1 -1
- package/dist/lib/chunk-internal.mjs +231 -79
- package/dist/lib/chunk-internal.mjs.map +1 -1
- package/dist/lib/chunk-json-schema.mjs +1 -1
- package/dist/lib/chunk-ref.mjs +38 -34
- package/dist/lib/chunk-ref.mjs.map +1 -1
- package/dist/lib/chunk-select.mjs +7 -3
- package/dist/lib/chunk-select.mjs.map +1 -1
- package/dist/lib/index.mjs +2 -2
- package/dist/lib/internal.mjs +6 -6
- package/dist/lib/testing.mjs +2 -2
- package/dist/lib/testing.mjs.map +1 -1
- package/dist/types/src/Annotation.d.ts +1 -1
- package/dist/types/src/Annotation.d.ts.map +1 -1
- package/dist/types/src/Database.d.ts +30 -13
- package/dist/types/src/Database.d.ts.map +1 -1
- package/dist/types/src/Entity.d.ts +3 -4
- package/dist/types/src/Entity.d.ts.map +1 -1
- package/dist/types/src/Error.d.ts +36 -0
- package/dist/types/src/Error.d.ts.map +1 -1
- package/dist/types/src/Feed.d.ts +261 -18
- package/dist/types/src/Feed.d.ts.map +1 -1
- package/dist/types/src/Filter.d.ts +7 -1
- package/dist/types/src/Filter.d.ts.map +1 -1
- package/dist/types/src/Hypergraph.d.ts +1 -1
- package/dist/types/src/Migration.d.ts +213 -2
- package/dist/types/src/Migration.d.ts.map +1 -1
- package/dist/types/src/Migration.test.d.ts +2 -0
- package/dist/types/src/Migration.test.d.ts.map +1 -0
- package/dist/types/src/Obj.d.ts +4 -4
- package/dist/types/src/Obj.d.ts.map +1 -1
- package/dist/types/src/QueryResult.d.ts +16 -0
- package/dist/types/src/QueryResult.d.ts.map +1 -1
- package/dist/types/src/Relation.d.ts +3 -4
- package/dist/types/src/Relation.d.ts.map +1 -1
- package/dist/types/src/Scope.d.ts +32 -1
- package/dist/types/src/Scope.d.ts.map +1 -1
- package/dist/types/src/Tag.d.ts.map +1 -1
- package/dist/types/src/Type.d.ts +27 -2
- package/dist/types/src/Type.d.ts.map +1 -1
- package/dist/types/src/internal/Annotation/annotations.d.ts +35 -1
- package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
- package/dist/types/src/internal/Annotation/atoms.d.ts +2 -2
- package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/api.d.ts +11 -0
- package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/model.d.ts +3 -2
- package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
- package/dist/types/src/internal/Format/string.d.ts +5 -1
- package/dist/types/src/internal/Format/string.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/atoms.d.ts +1 -1
- package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
- package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
- package/dist/types/src/internal/Ref/ref.d.ts +5 -1
- package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
- package/dist/types/src/internal/Ref/strong-deps.d.ts +3 -1
- package/dist/types/src/internal/Ref/strong-deps.d.ts.map +1 -1
- package/dist/types/src/internal/common/api/meta.d.ts +4 -5
- package/dist/types/src/internal/common/api/meta.d.ts.map +1 -1
- package/dist/types/src/internal/common/atom-snapshot.d.ts +10 -0
- package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/change-context.d.ts +4 -0
- package/dist/types/src/internal/common/proxy/change-context.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/ownership.d.ts +5 -0
- package/dist/types/src/internal/common/proxy/ownership.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/schema-validator.d.ts +17 -2
- package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/symbols.d.ts +10 -0
- package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/typed-handler.d.ts +0 -1
- package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
- package/dist/types/src/internal/common/types/meta.d.ts +8 -4
- package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
- package/dist/types/src/internal/common/types/model-symbols.d.ts +6 -0
- package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
- package/dist/types/src/internal/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -15
- package/src/Annotation.test.ts +34 -0
- package/src/Annotation.ts +3 -0
- package/src/Database.ts +46 -15
- package/src/Entity.ts +3 -4
- package/src/Error.ts +9 -0
- package/src/Feed.test.ts +160 -0
- package/src/Feed.ts +412 -29
- package/src/Filter.ts +8 -1
- package/src/Hypergraph.ts +1 -1
- package/src/Migration.test.ts +137 -0
- package/src/Migration.ts +376 -4
- package/src/Obj.test.ts +44 -4
- package/src/Obj.ts +19 -5
- package/src/QueryResult.ts +14 -0
- package/src/Relation.ts +3 -4
- package/src/Scope.ts +43 -1
- package/src/Tag.md +5 -6
- package/src/Tag.ts +3 -2
- package/src/Type.test.ts +52 -0
- package/src/Type.ts +75 -22
- package/src/Type.tst.ts +155 -0
- package/src/internal/Annotation/annotations.test.ts +19 -0
- package/src/internal/Annotation/annotations.ts +67 -1
- package/src/internal/Annotation/atoms.ts +10 -9
- package/src/internal/Entity/api.ts +20 -1
- package/src/internal/Entity/model.ts +3 -0
- package/src/internal/Filter/match.ts +2 -2
- package/src/internal/Format/string.ts +7 -2
- package/src/internal/JsonSchema/json-schema.test.ts +2 -2
- package/src/internal/Obj/atoms.ts +9 -5
- package/src/internal/Obj/json-serializer.test.ts +34 -7
- package/src/internal/Obj/json-serializer.ts +18 -3
- package/src/internal/Query/pretty.ts +3 -2
- package/src/internal/Ref/ref.test.ts +27 -2
- package/src/internal/Ref/ref.ts +18 -2
- package/src/internal/Ref/strong-deps.ts +21 -2
- package/src/internal/common/api/meta.ts +7 -8
- package/src/internal/common/atom-snapshot.ts +61 -0
- package/src/internal/common/proxy/change-context.ts +5 -0
- package/src/internal/common/proxy/change.test.ts +62 -31
- package/src/internal/common/proxy/json-serializer.ts +3 -2
- package/src/internal/common/proxy/ownership.ts +14 -1
- package/src/internal/common/proxy/proxy-utils.ts +7 -1
- package/src/internal/common/proxy/schema-validator.ts +116 -27
- package/src/internal/common/proxy/symbols.ts +12 -0
- package/src/internal/common/proxy/typed-handler.test.ts +43 -0
- package/src/internal/common/proxy/typed-handler.ts +105 -33
- package/src/internal/common/types/meta.ts +25 -20
- package/src/internal/common/types/model-symbols.ts +7 -0
- package/src/internal/index.ts +1 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-internal.mjs","names":["__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file"],"sources":["../../src/internal/common/types/base.ts","../../src/internal/common/types/projection.ts","../../src/internal/common/types/version.ts","../../src/internal/Annotation/sorting.ts","../../src/internal/Entity/model.ts","../../src/internal/Query/pretty.ts","../../src/internal/Ref/strong-deps.ts","../../src/internal/common/proxy/json-serializer.ts","../../src/internal/common/proxy/commit-scope.ts","../../src/internal/common/proxy/event-batch.ts","../../src/internal/common/proxy/change-context.ts","../../src/internal/common/proxy/ownership.ts","../../src/internal/common/proxy/reactive-array.ts","../../src/internal/common/proxy/schema-validator.ts","../../src/internal/common/proxy/typed-handler.ts","../../src/internal/common/proxy/make-object.ts","../../src/internal/Entity/entity.ts","../../src/internal/JsonSchema/json-schema-normalize.ts","../../src/internal/Entity/object.ts","../../src/internal/Entity/relation.ts","../../src/internal/Entity/type-kind.ts","../../src/internal/Entity/version.ts","../../src/internal/common/merge.ts","../../src/internal/Obj/json-serializer.ts","../../src/internal/Filter/match.ts","../../src/internal/Obj/common.ts","../../src/internal/Obj/inspect.ts","../../src/internal/Obj/create-object.ts","../../src/internal/Obj/deleted.ts","../../src/internal/Obj/parent-annotation.ts","../../src/internal/Obj/set-value.ts","../../src/internal/Obj/snapshot.ts","../../src/internal/Obj/atoms.ts","../../src/internal/Obj/clone.ts","../../src/internal/Type/manipulation.ts","../../src/internal/Type/type-schema.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { type EntityId } from '@dxos/keys';\n\nimport { type ATTR_META, type EntityMeta } from './meta.ts';\n\n/**\n * Base type for all data objects (reactive, ECHO, and other raw objects).\n * NOTE: This describes the base type for all database objects.\n * It is stricter than `T extends {}` or `T extends object`.\n */\n// TODO(burdon): Prefer Record<string, unknown>.\nexport type AnyProperties = Record<string, any>;\n\n/**\n * Canonical type for all ECHO entities (objects and relations).\n * @depreacted Remove, use Entity.Unknown instead.\n */\n// TODO(wittjosiah): Remove. Prefer higher level types (e.g. Entity.Unknown).\nexport interface AnyEntity {\n readonly id: EntityId;\n}\n\nexport type ExcludeId<T extends AnyProperties> = Omit<T, 'id'>;\n\nexport type PropertyKey<T extends AnyProperties> = Extract<keyof ExcludeId<T>, string>;\n\n// TODO(dmaretskyi): Remove. This should be using the symbol type.\ntype WithMeta = { [ATTR_META]?: EntityMeta };\n\n/**\n * The raw object should not include the ECHO id, but may include metadata.\n */\n// `Schema.Top` leaves `Type` as `unknown`, which `ExcludeId` cannot accept; pinning it here states\n// the object-shape requirement that v3's `Schema.Schema.Type<S>` carried implicitly.\nexport const RawObject = <S extends Schema.Top & { readonly Type: AnyProperties }>(\n schema: S,\n): Schema.Codec<ExcludeId<S['Type']> & WithMeta, S['Encoded']> => {\n return Schema.make<Schema.Codec<ExcludeId<S['Type']> & WithMeta, S['Encoded']>>(SchemaAST.omit(schema.ast, ['id']));\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Types from 'effect/Types';\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\n/**\n * Brand for a query projected to a single scalar property (`Query.project`), consumed by\n * `Filter.in` to build a subquery-membership predicate — an uncorrelated\n * `col IN (SELECT property FROM ...)` semi-join. Defined in common/ (not in Query/) so\n * Filter.ts can recognize the brand without importing Query.ts as a value: Query.ts already\n * imports Filter.ts as a value, so a reverse value import would create a cycle. Both\n * Filter.ts and Query.ts import this shared leaf module instead.\n *\n * A string-literal id (not a `Symbol.for`), matching `FilterTypeId`/`QueryTypeId`/`OrderTypeId` so\n * that structurally-compatible objects can be constructed without importing this module's runtime.\n */\nexport const ProjectionTypeId = '~@dxos/echo/Query.Projection' as const;\nexport type ProjectionTypeId = typeof ProjectionTypeId;\n\n/**\n * `V` is the projected property's value type — carried only as a phantom brand (like\n * `Filter<T>`'s `[FilterTypeId]: { value: Types.Covariant<T> }`) so `Filter.in(query.project(k))`\n * infers its own type parameter from the projected property instead of defaulting to `unknown`.\n */\nexport interface Projection<V = unknown> {\n readonly [ProjectionTypeId]: { value: Types.Covariant<V> };\n readonly query: QueryAST.Query;\n readonly property: string;\n}\n\nexport const isProjection = (value: unknown): value is Projection =>\n typeof value === 'object' && value !== null && ProjectionTypeId in value;\n\nconst variance: Projection<any>[ProjectionTypeId] = {} as Projection<any>[ProjectionTypeId];\n\nexport const makeProjection = <V>(query: QueryAST.Query, property: string): Projection<V> => ({\n [ProjectionTypeId]: variance,\n query,\n property,\n});\n","//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Version type identifier.\n */\nexport const VersionTypeId = '~@dxos/echo/VersionTypeId' as const;\nexport type VersionTypeId = typeof VersionTypeId;\n\n/**\n * Represents the object version.\n * May be backed by Automerge.\n * Objects with no history are not versioned.\n */\nexport interface Version {\n [VersionTypeId]: {};\n automergeHeads?: string[];\n}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { AnyEntity } from '../common/types/index.ts';\nimport { getLabel, getTypename } from './annotations.ts';\n\n/**\n * String comparison helper for sorting.\n */\nexport const compare = (a?: string, b?: string): number => {\n if (a == null) {\n return b == null ? 0 : 1;\n }\n if (b == null) {\n return -1;\n }\n return a.localeCompare(b);\n};\n\n/**\n * Comparator function type for sorting entities.\n * Accepts both reactive entities and snapshots.\n */\nexport type Comparator<T extends AnyEntity = AnyEntity> = (a: T, b: T) => number;\n\n/**\n * Sort entities by label.\n */\nexport const sortByLabel: Comparator = (a: AnyEntity, b: AnyEntity) => compare(getLabel(a), getLabel(b));\n\n/**\n * Sort entities by typename.\n */\nexport const sortByTypename: Comparator = (a: AnyEntity, b: AnyEntity) => compare(getTypename(a), getTypename(b));\n\n/**\n * Compose multiple comparators into one.\n * Applies comparators in order until one returns non-zero.\n */\nexport const sort = <T extends AnyEntity>(...comparators: Comparator<T>[]): Comparator<T> => {\n return (a: T, b: T) => {\n for (const comparator of comparators) {\n const result = comparator(a, b);\n if (result !== 0) {\n return result;\n }\n }\n return 0;\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Schema from 'effect/Schema';\n\nimport { type ForeignKey } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport type * as Database from '../../Database.ts';\nimport {\n ATTR_DELETED,\n type ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n type ATTR_TYPE,\n EntityKind,\n KindId,\n ObjectBranchId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ObjectVersionId,\n type ParentId,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n type SchemaId,\n SelfURIId,\n TypeId,\n type Version,\n} from '../common/types/index.ts';\nimport { type ATTR_META, type EntityMeta } from '../common/types/meta.ts';\nimport { type MetaId } from '../common/types/model-symbols.ts';\n\nexport {\n ATTR_DELETED,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n ObjectBranchId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ObjectVersionId,\n SelfURIId,\n};\n\n/**\n * Internal runtime representation of an object.\n * The fields are accessed through getter functions.\n */\n// NOTE: Each symbol has a jsdoc describing its purpose.\nexport interface InternalObjectProps {\n readonly id: EntityId;\n readonly [SelfURIId]: EID.EID;\n readonly [KindId]: EntityKind;\n readonly [SchemaId]: Schema.Codec<any, any>;\n readonly [TypeId]: URI.URI;\n readonly [MetaId]?: EntityMeta;\n [ParentId]?: InternalObjectProps;\n readonly [ObjectDatabaseId]?: Database.Database;\n readonly [ObjectBranchId]?: string;\n readonly [ObjectDeletedId]?: boolean;\n readonly [ObjectVersionId]?: Version;\n readonly [RelationSourceDXNId]?: EID.EID;\n readonly [RelationTargetDXNId]?: EID.EID;\n readonly [RelationSourceId]?: InternalObjectProps;\n readonly [RelationTargetId]?: InternalObjectProps;\n}\n\n/**\n * Entity metadata.\n */\nexport interface EntityMetaJSON {\n keys: ForeignKey[];\n tags?: string[];\n key?: string;\n version?: string;\n annotations?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * JSON representation of an object or relation metadata.\n */\nexport interface ObjectJSON {\n id: EntityId;\n [ATTR_TYPE]?: URI.URI;\n [ATTR_SELF_URI]?: EID.EID;\n [ATTR_PARENT]?: EID.EID; // Encoded reference\n [ATTR_DELETED]?: boolean;\n [ATTR_META]?: EntityMetaJSON;\n [ATTR_RELATION_SOURCE]?: EID.EID;\n [ATTR_RELATION_TARGET]?: EID.EID;\n\n /**\n * Application-specific properties.\n */\n [key: string]: unknown;\n}\n\n/**\n * NOTE: Keep as `function` to avoid type inference issues.\n */\nexport function assertObjectModel(obj: unknown): asserts obj is InternalObjectProps {\n invariant(typeof obj === 'object' && obj !== null, 'Invalid object model: not an object');\n assumeType<InternalObjectProps>(obj);\n invariant(EntityId.isValid(obj.id), 'Invalid object model: invalid id');\n invariant(obj[TypeId] === undefined || typeof obj[TypeId] === 'string', 'Invalid object model: invalid type');\n invariant(\n obj[KindId] === EntityKind.Object || obj[KindId] === EntityKind.Relation || obj[KindId] === EntityKind.Type,\n 'Invalid object model: invalid entity kind',\n );\n\n if (obj[KindId] === EntityKind.Relation) {\n invariant(EID.isEID(obj[RelationSourceDXNId]), 'Invalid object model: invalid relation source');\n invariant(EID.isEID(obj[RelationTargetDXNId]), 'Invalid object model: invalid relation target');\n invariant(!EID.isEID(obj[RelationSourceId]), 'Invalid object model: source pointer is a DXN');\n invariant(!EID.isEID(obj[RelationTargetId]), 'Invalid object model: target pointer is a DXN');\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\n/**\n * Returns a human-readable string representation of a Filter AST.\n */\nexport const prettyFilter = (filter: QueryAST.Filter): string => {\n switch (filter.type) {\n case 'object': {\n // A type-less object filter with only a meta-key constraint is `Filter.key(...)`.\n if (\n filter.typename === null &&\n (filter.id === undefined || filter.id.length === 0) &&\n Object.keys(filter.props).length === 0 &&\n (filter.foreignKeys === undefined || filter.foreignKeys.length === 0) &&\n filter.metaKey !== undefined\n ) {\n return filter.metaVersion !== undefined\n ? `Filter.key(${JSON.stringify(filter.metaKey)}, { version: ${JSON.stringify(filter.metaVersion)} })`\n : `Filter.key(${JSON.stringify(filter.metaKey)})`;\n }\n const parts: string[] = [];\n if (filter.typename !== null) {\n parts.push(String(filter.typename));\n }\n if (filter.id !== undefined && filter.id.length > 0) {\n parts.push(`id: [${filter.id.join(', ')}]`);\n }\n const propEntries = Object.entries(filter.props);\n if (propEntries.length > 0) {\n const propsStr = propEntries.map(([k, v]) => `${k}: ${prettyFilter(v)}`).join(', ');\n parts.push(`{ ${propsStr} }`);\n }\n if (filter.foreignKeys !== undefined && filter.foreignKeys.length > 0) {\n parts.push(`foreignKeys: [${filter.foreignKeys.map((fk) => JSON.stringify(fk)).join(', ')}]`);\n }\n if (filter.metaKey !== undefined) {\n parts.push(\n filter.metaVersion !== undefined\n ? `metaKey: ${JSON.stringify(filter.metaKey)} (${filter.metaVersion})`\n : `metaKey: ${JSON.stringify(filter.metaKey)}`,\n );\n }\n return parts.length > 0 ? `Filter.type(${parts.join(', ')})` : 'Filter.everything()';\n }\n case 'compare':\n return `Filter.${filter.operator}(${JSON.stringify(filter.value)})`;\n case 'in':\n return `Filter.in([${filter.values.map((v) => JSON.stringify(v)).join(', ')}])`;\n case 'in-query':\n return `Filter.in(${prettyQuery(filter.subquery)}.project(${JSON.stringify(filter.property)}))`;\n case 'contains':\n return `Filter.contains(${JSON.stringify(filter.value)})`;\n case 'tag':\n return `Filter.tag(${JSON.stringify(filter.tag)})`;\n case 'annotation':\n return filter.value === undefined\n ? `Filter.annotation(${JSON.stringify(filter.key)})`\n : `Filter.annotation(${JSON.stringify(filter.key)}, ${JSON.stringify(filter.value)})`;\n case 'range':\n return `Filter.range(${JSON.stringify(filter.from)}, ${JSON.stringify(filter.to)})`;\n case 'text-search':\n return filter.searchKind\n ? `Filter.textSearch(${JSON.stringify(filter.text)}, ${JSON.stringify(filter.searchKind)})`\n : `Filter.textSearch(${JSON.stringify(filter.text)})`;\n case 'timestamp':\n return `Filter.${filter.field}.${filter.operator}(${filter.value})`;\n case 'feed-cursor':\n return `Filter.feedCursor(${JSON.stringify({ begin: filter.begin, end: filter.end })})`;\n case 'child-of':\n return `Filter.childOf([${filter.parents.map((p) => JSON.stringify(p)).join(', ')}], { transitive: ${filter.transitive} })`;\n case 'mnemonic':\n return `Filter.mnemonic(${JSON.stringify(filter.mnemonic)})`;\n case 'changes':\n return filter.targets\n ? `Filter.changes([${filter.targets.map((target) => JSON.stringify(target)).join(', ')}])`\n : 'Filter.changes()';\n case 'has-parent':\n return `Filter.hasParent(${filter.value})`;\n case 'not':\n return `Filter.not(${prettyFilter(filter.filter)})`;\n case 'and':\n return `Filter.and(${filter.filters.map(prettyFilter).join(', ')})`;\n case 'or':\n return `Filter.or(${filter.filters.map(prettyFilter).join(', ')})`;\n }\n};\n\n/**\n * Returns a human-readable string representation of a Query AST.\n */\nexport const prettyQuery = (query: QueryAST.Query): string => {\n switch (query.type) {\n case 'select':\n return `Query.select(${prettyFilter(query.filter)})`;\n case 'filter':\n return `${prettyQuery(query.selection)}.select(${prettyFilter(query.filter)})`;\n case 'reference-traversal':\n return `${prettyQuery(query.anchor)}.reference(${JSON.stringify(query.property)})`;\n case 'incoming-references': {\n const args: string[] = [];\n if (query.typename !== null) {\n args.push(String(query.typename));\n }\n if (query.property !== null) {\n args.push(JSON.stringify(query.property));\n }\n return `${prettyQuery(query.anchor)}.referencedBy(${args.join(', ')})`;\n }\n case 'relation': {\n const method =\n query.direction === 'outgoing' ? 'sourceOf' : query.direction === 'incoming' ? 'targetOf' : 'relationOf';\n const filterStr = query.filter !== undefined ? prettyFilter(query.filter) : '';\n return `${prettyQuery(query.anchor)}.${method}(${filterStr})`;\n }\n case 'relation-traversal':\n return `${prettyQuery(query.anchor)}.${query.direction}()`;\n case 'hierarchy-traversal':\n return query.direction === 'to-parent'\n ? `${prettyQuery(query.anchor)}.parent()`\n : `${prettyQuery(query.anchor)}.children()`;\n case 'union':\n return `Query.all(${query.queries.map(prettyQuery).join(', ')})`;\n case 'set-difference':\n return `Query.without(${prettyQuery(query.source)}, ${prettyQuery(query.exclude)})`;\n case 'order': {\n const orders = query.order.map((o) => {\n if (o.kind === 'natural') {\n return `Order.natural(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'rank') {\n return `Order.rank(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'timestamp') {\n const fn = o.field === 'updatedAt' ? 'updated' : 'created';\n return `Order.${fn}(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'annotation') {\n const path = o.path !== undefined ? `, ${JSON.stringify(o.path)}` : '';\n return `Order.annotation(${JSON.stringify(o.key)}, ${JSON.stringify(o.direction)}${path})`;\n } else {\n return `Order.property(${JSON.stringify(o.property)}, ${JSON.stringify(o.direction)})`;\n }\n });\n return `${prettyQuery(query.query)}.orderBy(${orders.join(', ')})`;\n }\n case 'options': {\n const opts = query.options;\n const parts: string[] = [];\n if (opts.deleted !== undefined) {\n parts.push(`deleted: ${JSON.stringify(opts.deleted)}`);\n }\n if (opts.debugLabel !== undefined) {\n parts.push(`debugLabel: ${JSON.stringify(opts.debugLabel)}`);\n }\n return `${prettyQuery(query.query)}.options({ ${parts.join(', ')} })`;\n }\n case 'from': {\n if (query.from._tag === 'scope') {\n if (query.from.scopes.length === 0) {\n return `${prettyQuery(query.query)}.from('all-accessible-spaces')`;\n }\n const scopeStrs = query.from.scopes.map((scope) => {\n if (scope._tag === 'space') {\n return scope.includeAllFeeds\n ? `{ space: ${JSON.stringify(scope.spaceId)}, includeAllFeeds: true }`\n : `{ space: ${JSON.stringify(scope.spaceId)} }`;\n }\n if (scope._tag === 'feed') {\n return `{ feed: ${JSON.stringify(String(scope.feedUri))} }`;\n }\n return `{ registry: ${JSON.stringify(scope.location)} }`;\n });\n return `${prettyQuery(query.query)}.from([${scopeStrs.join(', ')}])`;\n }\n return `${prettyQuery(query.query)}.from(${prettyQuery(query.from.query)})`;\n }\n case 'limit':\n return `${prettyQuery(query.query)}.limit(${query.limit})`;\n case 'skip':\n return `${prettyQuery(query.query)}.skip(${query.skip})`;\n case 'aggregate': {\n const aggregates = query.aggregates.map((aggregate) => {\n return `${JSON.stringify(aggregate.name)}: Aggregate.${prettyAggregateName(aggregate)}(${prettyAggregateArg(aggregate)})`;\n });\n return `${prettyQuery(query.query)}.aggregate({ ${aggregates.join(', ')} })`;\n }\n }\n};\n\n/** The `Aggregate.*` constructor that produced an aggregate. */\nconst prettyAggregateName = (aggregate: QueryAST.GroupAggregate): string =>\n aggregate.kind === 'timestamp' ? (aggregate.field === 'updatedAt' ? 'updated' : 'created') : aggregate.kind;\n\n/** Renders one aggregate's constructor argument, mirroring the `Aggregate.*` call that produced it. */\nconst prettyAggregateArg = (aggregate: QueryAST.GroupAggregate): string => {\n switch (aggregate.kind) {\n case 'count':\n case 'type':\n return '';\n case 'timestamp':\n return JSON.stringify(aggregate.unit);\n case 'time':\n return `${JSON.stringify(aggregate.property)}, ${JSON.stringify(aggregate.unit)}`;\n case 'items':\n return aggregate.limit !== undefined ? `{ limit: ${aggregate.limit} }` : '';\n case 'group':\n return aggregate.properties.length === 1\n ? JSON.stringify(aggregate.properties[0])\n : `{ coalesce: ${JSON.stringify(aggregate.properties)} }`;\n case 'max':\n case 'min':\n case 'sum':\n return JSON.stringify(aggregate.property);\n }\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { EID, type SpaceId, type URI } from '@dxos/keys';\n\nimport { EntityKind } from '../common/types/entity.ts';\nimport { RelationSourceDXNId, RelationTargetDXNId } from '../common/types/model-symbols.ts';\nimport { ParentId, TypeId } from '../common/types/typename.ts';\nimport { getObjectEchoUri } from '../Entity/util.ts';\n\n/**\n * Normalized view of the references that make up an entity's strong-dependency set, store-agnostic\n * so it can be filled from an {@link ObjectCore} (db) or a decoded entity (queue item / snapshot).\n */\nexport interface StrongDepRefs {\n /** Entity kind — relations additionally depend on their source/target. */\n kind: EntityKind;\n /** Type reference URI (`echo:` for a persisted stored schema, `dxn:` for a static/registry type). */\n type?: URI.URI;\n /** Relation source reference URI. */\n source?: URI.URI;\n /** Relation target reference URI. */\n target?: URI.URI;\n /** Parent reference URI. */\n parent?: URI.URI;\n}\n\n/**\n * Direct strong-dependency URIs of an entity: the schema (only when stored as an object), the\n * relation source/target, and the parent. Returns URIs (cross-space `echo:` EIDs and queue-item\n * EIDs included); a persisted schema is an `echo:` URI, a static/registry type is a `dxn:` URI.\n *\n * A static/registry type (`dxn:`) is intentionally NOT a strong dep: it is always synchronously\n * available through the registry, so gating on it would needlessly delay surfacing. Only a\n * persisted (db-backed) schema, addressed by an `echo:` URI, must load before its instances.\n */\nexport const getStrongDependencyUris = (refs: StrongDepRefs, owningSpaceId?: SpaceId): URI.URI[] => {\n const res: URI.URI[] = [];\n\n if (refs.type != null && EID.tryParse(refs.type) != null) {\n res.push(qualifyToSpace(refs.type, owningSpaceId));\n }\n\n if (refs.kind === EntityKind.Relation) {\n if (refs.source != null) {\n res.push(qualifyToSpace(refs.source, owningSpaceId));\n }\n if (refs.target != null) {\n res.push(qualifyToSpace(refs.target, owningSpaceId));\n }\n }\n\n if (refs.parent != null) {\n res.push(qualifyToSpace(refs.parent, owningSpaceId));\n }\n\n return res;\n};\n\n/**\n * Qualifies a space-less (relative) `echo:` dependency URI with the space of the entity that owns it.\n * Same-space references are persisted relative; resolution needs them absolute to route to a single\n * space. Already-qualified URIs (cross-space) and non-`echo:` URIs (registry `dxn:`) pass through.\n */\nconst qualifyToSpace = (uri: URI.URI, owningSpaceId: SpaceId | undefined): URI.URI => {\n if (owningSpaceId == null) {\n return uri;\n }\n const eid = EID.tryParse(uri);\n if (eid == null || !EID.isLocal(eid)) {\n return uri;\n }\n const entityId = EID.getEntityId(eid);\n return entityId != null ? EID.make({ spaceId: owningSpaceId, entityId }) : uri;\n};\n\n/**\n * Direct strong-dependency URIs of a live (decoded) entity — a queue item, cross-space proxy, or\n * snapshot. Reads the reference URIs off the entity's hidden model symbols. ECHO db cores compute\n * the same set from their raw encoded references via {@link getStrongDependencyUris}.\n */\nexport const getStrongDependencies = (entity: unknown): URI.URI[] => {\n if (entity == null || typeof entity !== 'object') {\n return [];\n }\n const props = entity as Record<symbol, unknown>;\n const kind =\n props[RelationSourceDXNId] != null || props[RelationTargetDXNId] != null ? EntityKind.Relation : EntityKind.Object;\n const parent = props[ParentId];\n\n // The entity's own space qualifies any relative dependency URIs it carries.\n const selfUri = getObjectEchoUri(entity);\n const owningSpaceId = selfUri != null ? EID.getSpaceId(selfUri) : undefined;\n\n return getStrongDependencyUris(\n {\n kind,\n type: typeof props[TypeId] === 'string' ? (props[TypeId] as URI.URI) : undefined,\n source: props[RelationSourceDXNId] as URI.URI | undefined,\n target: props[RelationTargetDXNId] as URI.URI | undefined,\n // A parent is held as the resolved entity; derive its absolute URI for the dependency edge.\n parent: parent != null ? getObjectEchoUri(parent) : undefined,\n },\n owningSpaceId,\n );\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { EID } from '@dxos/keys';\nimport { deepMapValues, encodeUint8ArrayToJson } from '@dxos/util';\n\nimport { Ref } from '../../Ref/index.ts';\nimport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_TYPE,\n RelationSourceDXNId,\n RelationTargetDXNId,\n SelfURIId,\n TypeId,\n} from '../types/index.ts';\nimport { ATTR_META, type EntityMeta } from '../types/meta.ts';\nimport { ATTR_DELETED, MetaId, ObjectDeletedId } from '../types/model-symbols.ts';\n\n/**\n * Attaches a toJSON method to the object for typed serialization.\n */\nexport const attachTypedJsonSerializer = (obj: any) => {\n const descriptor = Object.getOwnPropertyDescriptor(obj, 'toJSON');\n if (descriptor) {\n return;\n }\n\n Object.defineProperty(obj, 'toJSON', {\n value: typedJsonSerializer,\n writable: false,\n enumerable: false,\n // Setting `configurable` to false breaks proxy invariants, should be fixable.\n configurable: true,\n });\n};\n\n// NOTE: KEEP as function.\n// Exported for use in objectToJSON.\nexport const typedJsonSerializer = function (this: any) {\n const { id, ...rest } = this;\n const result: any = {\n id,\n };\n\n if (this[TypeId]) {\n result[ATTR_TYPE] = this[TypeId];\n }\n\n if (this[MetaId]) {\n result[ATTR_META] = serializeMeta(this[MetaId]);\n }\n\n if (this[SelfURIId]) {\n result[ATTR_SELF_URI] = this[SelfURIId];\n }\n\n // Emitted only when set, mirroring `objectFromJSON`'s `=== true` read: without it a tombstone\n // snapshot round-tripped through JSON came back as a live object.\n if (this[ObjectDeletedId]) {\n result[ATTR_DELETED] = true;\n }\n\n if (this[RelationSourceDXNId]) {\n const sourceDXN = this[RelationSourceDXNId];\n invariant(EID.isEID(sourceDXN));\n result[ATTR_RELATION_SOURCE] = sourceDXN;\n }\n if (this[RelationTargetDXNId]) {\n const targetDXN = this[RelationTargetDXNId];\n invariant(EID.isEID(targetDXN));\n result[ATTR_RELATION_TARGET] = targetDXN;\n }\n\n Object.assign(result, serializeData(rest));\n return result;\n};\n\nconst serializeData = (data: unknown) => {\n return deepMapValues(data, (value, recurse) => {\n if (Ref.isRef(value)) {\n // TODO(dmaretskyi): Should this be configurable?\n return value.noInline().encode();\n }\n if (value instanceof Uint8Array) {\n return encodeUint8ArrayToJson(value);\n }\n\n return recurse(value);\n });\n};\n\nconst serializeMeta = (meta: EntityMeta) => {\n // Omit empty `tags`/`annotations` to keep serialized output minimal; `objectFromJSON` backfills\n // the required defaults on read.\n const { tags, annotations, ...rest } = meta;\n const compact = {\n ...rest,\n ...(tags != null && tags.length > 0 ? { tags } : {}),\n ...(annotations != null && Object.keys(annotations).length > 0 ? { annotations } : {}),\n };\n // Use `serializeData` so `meta.tags` `Ref<Tag>` values encode to the on-wire reference form.\n return serializeData(compact);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\n/**\n * Commit scope: groups the synchronous document writes of one user-level mutation (an `Obj.update`, a\n * `db.add`, a single property write) into one commit, and runs post-commit callbacks once the outermost\n * commit has ended.\n *\n * Post-commit callbacks run after every document semaphore is released and every change event has been\n * delivered, but before the writing call returns. That is the one point where a subscriber may observe\n * the committed state and write again without re-entering a document change.\n */\n\nlet depth = 0;\nlet draining = false;\nconst pending = new Set<() => void>();\n\n/**\n * Opens a commit. Returns the function that closes it; closing the outermost commit drains the\n * post-commit queue.\n */\nexport const beginCommit = (): (() => void) => {\n depth++;\n let ended = false;\n return () => {\n if (ended) {\n return;\n }\n ended = true;\n depth--;\n if (depth === 0) {\n drainCommitQueue();\n }\n };\n};\n\n/** Runs `body` as one commit. */\nexport const runInCommit = <T>(body: () => T): T => {\n const endCommit = beginCommit();\n try {\n return body();\n } finally {\n endCommit();\n }\n};\n\n/**\n * Requests `callback` after the current outermost commit. Outside any commit it runs at once. A callback\n * requested several times before the drain runs once, so it must read its own pending state.\n */\nexport const afterCommit = (callback: () => void): void => {\n pending.add(callback);\n if (depth === 0) {\n drainCommitQueue();\n }\n};\n\nconst drainCommitQueue = (): void => {\n // A write made by a callback ends its own commit inside this loop; its callbacks join the queue and run\n // in a later round, after every callback of the current round has seen the earlier commit.\n if (draining) {\n return;\n }\n draining = true;\n try {\n while (pending.size > 0) {\n const round = [...pending];\n pending.clear();\n for (const callback of round) {\n try {\n callback();\n } catch (error) {\n // The write has committed; a failing subscriber must not make the writer's call throw, and must\n // not stop the callbacks after it. Rethrown outside the commit so it still surfaces as unhandled.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n } finally {\n draining = false;\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { EventId } from './symbols.ts';\n\n/**\n * Simple batching mechanism for EventId emissions.\n * When batch depth > 0, events are collected instead of emitted immediately.\n * When batch depth returns to 0, pending events are emitted.\n */\nlet eventBatchDepth = 0;\nconst pendingEventTargets = new Set<object>();\n\n/**\n * Run a callback in a batched context for EventId emissions.\n * Multiple mutations within the batch will only emit one event per target.\n */\nexport const batchEvents = (callback: () => void): void => {\n eventBatchDepth++;\n try {\n callback();\n } finally {\n eventBatchDepth--;\n if (eventBatchDepth === 0) {\n // Emit pending events.\n for (const target of pendingEventTargets) {\n (target as any)[EventId]?.emit();\n }\n pendingEventTargets.clear();\n }\n }\n};\n\n/**\n * Emit an event on a target, respecting batching.\n */\nexport const emitEvent = (target: object): void => {\n if (eventBatchDepth > 0) {\n pendingEventTargets.add(target);\n } else {\n (target as any)[EventId]?.emit();\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { beginCommit } from './commit-scope.ts';\nimport { batchEvents } from './event-batch.ts';\nimport { getMutableProxy } from './proxy-utils.ts';\nimport { ChangeKeyId, EventId } from './symbols.ts';\n\n/**\n * Generic change context tracking.\n * Only one object can be in a change context at a time (synchronous changes).\n *\n * This module provides a unified change context mechanism used by both:\n * - TypedReactiveHandler (for non-database objects, using target as key)\n * - EchoReactiveHandler (for database objects, using ObjectCore as key)\n */\n\n/**\n * The object currently in a change context.\n * Can be a target object (for typed reactive) or ObjectCore (for database objects).\n */\nlet currentChangeContext: object | null = null;\n\n/**\n * The primary object that has pending notifications, if any.\n * This uses the contextKey (target or ObjectCore).\n */\nlet pendingNotificationKey: object | null = null;\n\n/**\n * Additional objects (owner chain) that need notifications.\n * These are separate from the primary notification because they use EventId directly.\n */\nconst pendingOwnerNotifications = new Set<object>();\n\n/**\n * Enter a change context for the given key.\n * While in a change context, mutations are allowed on the associated object.\n * Nested Obj.update calls are not supported.\n *\n * @param key - The key to enter the change context for (target object or ObjectCore).\n * @returns A cleanup function that exits the change context.\n */\nexport const enterChangeContext = (key: object): (() => void) => {\n currentChangeContext = key;\n return () => {\n currentChangeContext = null;\n };\n};\n\n/**\n * Check if the given key is currently in a change context.\n *\n * @param key - The key to check (target object or ObjectCore).\n * @returns True if the key is in a change context, false otherwise.\n */\nexport const isInChangeContext = (key: object): boolean => {\n return currentChangeContext === key;\n};\n\n/**\n * Queue a notification for the given key to be fired when the change context exits.\n *\n * @param key - The key to queue a notification for.\n */\nexport const queueNotification = (key: object): void => {\n if (currentChangeContext === key) {\n pendingNotificationKey = key;\n }\n};\n\n/**\n * Queue an owner notification. Owner notifications are for objects in the ownership\n * chain that should be notified when a nested object changes.\n * These objects have EventId and emit directly.\n * Skip if the target is already the current change context (to avoid duplicate notifications).\n *\n * @param target - The owner target that has EventId.\n */\nexport const queueOwnerNotification = (target: object): void => {\n // Skip if this is the object already being changed (primary notification handles it).\n if (currentChangeContext !== null && target !== currentChangeContext) {\n pendingOwnerNotifications.add(target);\n }\n};\n\n/**\n * Check if there are any pending notifications for the given key.\n *\n * @param key - The key to check.\n * @returns True if there are pending notifications, false otherwise.\n */\nexport const hasPendingNotifications = (key: object): boolean => {\n return pendingNotificationKey === key;\n};\n\n/**\n * Clear any pending notifications for the given key.\n *\n * @param key - The key to clear notifications for.\n */\nexport const clearPendingNotifications = (key: object): void => {\n if (pendingNotificationKey === key) {\n pendingNotificationKey = null;\n }\n};\n\n/**\n * Execute a callback within a change context.\n * This is the shared implementation used by both TypedReactiveHandler and EchoReactiveHandler.\n *\n * @param contextKey - The key for the change context (target for typed, ObjectCore for db).\n * @param eventTarget - The object that has the EventId for notifications.\n * @param proxy - The proxy object to pass to the callback.\n * @param callback - The callback to execute with mutations allowed.\n */\nexport const executeChange = (\n contextKey: object,\n eventTarget: object,\n proxy: any,\n callback: (proxy: any) => void,\n): void => {\n // One commit for the whole callback: a subscriber must never observe the state between two of its writes.\n const endCommit = beginCommit();\n try {\n const exitContext = enterChangeContext(contextKey);\n try {\n // The callback is handed the mutable view, not `proxy`: writability travels with the reference, so\n // the object named outside stays read-only even while this runs. The context is still entered —\n // it is what batches notifications and what the array and text gates read.\n batchEvents(() => callback(getMutableProxy(proxy)));\n } finally {\n exitContext();\n // Fire the primary notification (a real change).\n if (hasPendingNotifications(contextKey)) {\n clearPendingNotifications(contextKey);\n (eventTarget as any)[EventId]?.emit();\n }\n // Fire owner chain notifications.\n for (const ownerTarget of pendingOwnerNotifications) {\n (ownerTarget as any)[EventId]?.emit();\n }\n pendingOwnerNotifications.clear();\n }\n } finally {\n endCommit();\n }\n};\n\n/**\n * The read-only gate, and the whole of it — every variant is gated here and nowhere else. A symbol is\n * never user data (the system stamps `[ParentId]` and friends outside any change context), and a target\n * whose `[ChangeKeyId]` is undefined is still under construction and not yet gated. Everything else may\n * only be mutated inside the `Obj.update` that opened a context for *this* object.\n *\n * No dispatch: the key comes from the target's behaviour prototype, so nothing here knows or cares which\n * variant it is looking at. Lives here rather than beside the proxy handler because it needs the change\n * context, and the handler module must not depend on this one.\n *\n * `name` is the property for a trap and the method name for a mutation a proxy cannot intercept (an\n * array method, a text CRDT op), which call this directly — the same predicate either way.\n */\nexport const assertMutable = <T extends string | symbol>(\n target: object,\n name: T,\n createError: (name: T) => Error,\n): void => {\n if (typeof name === 'symbol') {\n return;\n }\n const changeKey: object | undefined = Reflect.get(target, ChangeKeyId);\n if (changeKey !== undefined && !isInChangeContext(changeKey)) {\n throw createError(name);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { KindId } from '../types/index.ts';\nimport { queueOwnerNotification } from './change-context.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { getProxyTarget, isProxy, isValidProxyTarget } from './proxy-utils.ts';\nimport { EventId } from './symbols.ts';\n\n/**\n * Symbol to store the owning ECHO object reference on nested JS objects (records).\n * Every nested record is attributed to exactly one ECHO object.\n * This achieves:\n * - No cycles in the object graph (cyclical Refs are still allowed).\n * - No multiple inbound pointers to one record.\n * - Centralized reactivity for entire ECHO object.\n */\nconst EchoOwner = Symbol.for('@dxos/echo/Owner');\n\n/**\n * Get the raw target from a value, unwrapping proxy if needed.\n */\nexport const getRawTarget = (value: any): any => {\n return isProxy(value) ? getProxyTarget(value) : value;\n};\n\n/**\n * Get the ECHO object that owns this nested record.\n *\n * The owner is always the raw target object (not a proxy) of the root ECHO object.\n * For example, if you have `echoObject.nested.deep`, both `nested` and `deep`\n * will have their owner set to the raw target of `echoObject`.\n *\n * @param value - The nested record to check (can be a proxy or raw target).\n * @returns The raw target of the owning root ECHO object, or undefined if not owned.\n */\nexport const getOwner = (value: object | null | undefined): object | undefined => {\n return (value as any)?.[EchoOwner];\n};\n\n/**\n * Set the owner of a meta object to its parent.\n * This allows meta mutations to respect the parent's change context.\n * @internal\n */\nexport const setMetaOwner = (metaTarget: object, parent: object): void => {\n defineHiddenProperty(metaTarget, EchoOwner, parent);\n};\n\n/**\n * Set the ECHO object owner on a value and all its nested records.\n * All nested JS objects point directly to the root ECHO object.\n *\n * @param value - The value to set ownership on (can be a proxy or raw target).\n * @param owner - The raw target of the root ECHO object that will own this value.\n * @param options.visited - Set of already-visited objects to avoid infinite loops.\n * @param options.depth - Current recursion depth (unused, kept for debugging).\n * @param options.allowedPreviousOwner - When reassigning a root ECHO object, its nested structures\n * are allowed to have this as their previous owner without triggering the invariant.\n */\nexport const setOwnerRecursive = (\n value: any,\n owner: object,\n options: {\n visited?: Set<object>;\n depth?: number;\n allowedPreviousOwner?: object;\n } = {},\n): void => {\n const { visited = new Set<object>(), depth = 0, allowedPreviousOwner } = options;\n if (value == null || typeof value !== 'object') {\n return;\n }\n\n const actualValue = getRawTarget(value);\n if (visited.has(actualValue)) {\n return;\n }\n visited.add(actualValue);\n\n // Check that we're not stealing a nested record owned by a different ECHO object.\n // Root ECHO objects (those with EventId) can be reassigned - they maintain their own\n // identity and choosing to embed them in another object is a valid operation.\n // When reassigning a root, its nested records (owned by that root) are also allowed.\n const existingOwner = getOwner(actualValue);\n const isRootEchoObject = EventId in actualValue;\n\n // Track if this is a root being assigned - its nested structures are allowed to transfer.\n let newAllowedPreviousOwner = allowedPreviousOwner;\n if (isRootEchoObject && depth === 0) {\n // This is the top-level root being assigned; allow its nested structures to transfer.\n newAllowedPreviousOwner = actualValue;\n }\n\n if (!isRootEchoObject) {\n const ownershipAllowed =\n existingOwner == null || existingOwner === owner || existingOwner === newAllowedPreviousOwner;\n invariant(\n ownershipAllowed,\n 'Cannot reassign ownership of a nested record to a different ECHO object. Use deep copy first.',\n );\n }\n\n // Set owner directly to the root ECHO object.\n defineHiddenProperty(actualValue, EchoOwner, owner);\n\n // Recursively set owner on nested objects and array elements.\n const recursiveOptions = {\n visited,\n depth: depth + 1,\n allowedPreviousOwner: newAllowedPreviousOwner,\n };\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (isValidProxyTarget(item) || isProxy(item)) {\n setOwnerRecursive(item, owner, recursiveOptions);\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n const nested = actualValue[key];\n if (isValidProxyTarget(nested) || isProxy(nested)) {\n setOwnerRecursive(nested, owner, recursiveOptions);\n }\n }\n }\n }\n};\n\n/**\n * Traverse an object graph, calling the visitor on each object.\n * Handles proxy unwrapping and cycle detection.\n *\n * @param value - The value to traverse (can be a proxy or raw target).\n * @param visitor - Called for each object. Return true to stop traversal (early exit).\n * @returns true if the visitor returns true for any object.\n */\nexport const traverseObjectGraph = (\n value: any,\n visitor: (actualValue: any) => boolean,\n visited = new Set<object>(),\n): boolean => {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n\n const actualValue = getRawTarget(value);\n\n if (visited.has(actualValue)) {\n return false;\n }\n visited.add(actualValue);\n\n if (visitor(actualValue)) {\n return true;\n }\n\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (traverseObjectGraph(item, visitor, visited)) {\n return true;\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n if (traverseObjectGraph(actualValue[key], visitor, visited)) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Check if a value would create a cycle when assigned to a target ECHO object.\n * Returns true if the value (or any nested object) IS the target root.\n */\nexport const wouldCreateCycle = (targetRoot: object, value: any): boolean =>\n traverseObjectGraph(value, (v) => v === targetRoot);\n\n/**\n * Check if a value or any of its nested objects has an owner different from the target.\n * Used to determine if deep copy is needed during init.\n */\nexport const hasForeignOwner = (value: any, target: object): boolean =>\n traverseObjectGraph(value, (v) => {\n const owner = getOwner(v);\n if (owner != null && owner !== target) {\n return true;\n }\n // Root ECHO objects (with EventId) have their nested structures owned by them.\n if (EventId in v && v !== target) {\n return true;\n }\n return false;\n });\n\n/**\n * Maximum depth for owner chain traversal.\n * This is a defensive measure against malformed circular ownership.\n * Primary cycle detection is handled by wouldCreateCycle() before assignment.\n */\nconst MAX_OWNER_DEPTH = 100;\n\n/**\n * Get the root ECHO object for a target.\n * Follows the owner chain to find the ultimate root.\n * An object may have EventId (from being created standalone) but if it now\n * has an owner, it's nested and we should use its owner's root instead.\n * @internal\n */\nexport const getEchoRoot = (target: object, depth = 0): object => {\n invariant(depth < MAX_OWNER_DEPTH, 'Owner chain too deep - possible circular ownership');\n\n // Root ECHO objects (those created with Obj.make or Relation.make) have KindId set.\n // They maintain their own change context identity even when nested inside another object.\n // Nested helper objects like EntityMeta don't have KindId and should follow their owner.\n if (KindId in target) {\n return target;\n }\n\n // For non-root objects (nested records, EntityMeta, etc.), follow the owner chain.\n const owner = getOwner(target);\n if (owner) {\n return getEchoRoot(owner, depth + 1);\n }\n\n // No owner means this is an unowned object (e.g., during initialization).\n return target;\n};\n\n/**\n * The in-memory variant's read-only gate key (see `assertMutable`): the root target that a change\n * context is opened against, or `undefined` while the root does not yet own an `[EventId]` — an object\n * under construction is not gated, which is what lets `init` fill it before any context exists.\n *\n * Every target of one object answers the same key, so a nested record and an array are gated by the\n * context their root opens.\n */\nexport const changeKeyOf = (target: object): object | undefined => {\n const root = getEchoRoot(getRawTarget(target));\n return EventId in root ? root : undefined;\n};\n\n/**\n * Notify all owners in the ownership chain.\n * When a nested object changes, its parent should also be notified.\n * This handles the case where a root ECHO object is nested inside another object.\n */\nexport const notifyOwnerChain = (target: object): void => {\n const owner = getOwner(target);\n if (owner) {\n // Queue notification for the owner's root (which has EventId).\n queueOwnerNotification(getEchoRoot(owner));\n // Continue up the chain (owner might also be nested).\n notifyOwnerChain(owner);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { assertMutable } from './change-context.ts';\nimport { createArrayMethodError } from './errors.ts';\nimport { batchEvents } from './event-batch.ts';\nimport { changeKeyOf } from './ownership.ts';\nimport { canonicalOf } from './proxy-utils.ts';\nimport { ChangeKeyId } from './symbols.ts';\n\n/**\n * Extends the native array to make sure that arrays methods are correctly reactive.\n * Enforces that mutations only happen within Obj.update() context.\n */\nexport class ReactiveArray<T> extends Array<T> {\n static override get [Symbol.species]() {\n return Array;\n }\n\n /**\n * The read-only gate's key. An array keeps this prototype chain rather than being compacted onto the\n * record behaviour prototype, so it answers for itself; the key is the same root the record holding\n * it is gated by.\n */\n get [ChangeKeyId](): object | undefined {\n return changeKeyOf(this);\n }\n\n static {\n /**\n * These methods will trigger proxy traps like `set` and `defineProperty` and emit event notifications.\n * We wrap them in a batch to avoid unnecessary event notifications.\n * Change context is checked before allowing mutations.\n *\n * Note: When called on a proxy, `this` will be the proxy, so array mutations\n * go through the proxy's set trap which handles event emission.\n */\n const BATCHED_METHODS = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const;\n\n for (const method of BATCHED_METHODS) {\n Object.defineProperty(this.prototype, method, {\n enumerable: false,\n value: function (this: ReactiveArray<any>, ...args: any[]) {\n // A method call is invisible to the proxy, so it runs the same gate the traps run.\n assertMutable(this, method, createArrayMethodError);\n\n let result!: any;\n batchEvents(() => {\n result = Array.prototype[method].apply(this, args);\n });\n // `sort`/`reverse` answer the receiver. Inside `Obj.update` that is the mutable view, which is\n // callback-scoped: hand back the array's canonical identity so `arr.sort() === arr` holds.\n return result === this ? canonicalOf(this) : result;\n },\n });\n }\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaIssue from 'effect/SchemaIssue';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { invariant } from '@dxos/invariant';\n\nimport { SchemaAstId, SchemaId } from '../types/index.ts';\n\n// TODO(burdon): Reconcile with @dxos/effect visit().\n\n/** Formats v4 schema issues; the thrown validation error carries the issue as its `cause`. */\nconst formatIssue = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/**\n * Asserts a value against a schema, naming the offending field.\n *\n * v4's `Schema.asserts` throws the fixed message \"Schema validation failed\" and puts the detail on\n * the error's `cause`, which leaves nothing actionable in a stack trace or a UI toast.\n */\nexport const assertsWithDetail = (schema: Schema.Top, value: unknown): void => {\n try {\n Schema.asserts(schema, value);\n } catch (err) {\n const issue = err instanceof Error ? err.cause : undefined;\n if (!SchemaIssue.isIssue(issue)) {\n throw err;\n }\n const detail = formatIssue(issue)\n .issues.map(({ message, path }) => (path && path.length > 0 ? `${path.join('.')}: ${message}` : message))\n .join('; ');\n throw new Error(detail.length > 0 ? `Schema validation failed — ${detail}` : 'Schema validation failed', {\n cause: issue,\n });\n }\n};\n\nexport class SchemaValidator {\n /**\n * Recursively check that schema specifies constructions we can handle.\n * Validates there are no ambiguous discriminated union types.\n */\n public static validateSchema(schema: Schema.Top): void {\n validateAst(schema.ast);\n }\n\n public static hasTypeAnnotation(rootObjectSchema: Schema.Top, property: string, annotation: string): boolean {\n try {\n let type = this.getPropertySchema(rootObjectSchema, [property]);\n if (SchemaAST.isArrays(type.ast)) {\n type = this.getPropertySchema(rootObjectSchema, [property, '0']);\n }\n\n return SchemaAST.getAnnotation(type.ast, annotation) != null;\n } catch {\n return false;\n }\n }\n\n public static getPropertySchema(\n rootObjectSchema: Schema.Top,\n propertyPath: KeyPath,\n getProperty: (path: KeyPath) => any = () => null,\n ): Schema.Top {\n let ast = rootObjectSchema.ast;\n for (let i = 0; i < propertyPath.length; i++) {\n const propertyName = propertyPath[i];\n const tupleAst = unwrapArray(ast);\n if (tupleAst != null) {\n ast = getArrayElementAst(tupleAst, propertyName);\n } else {\n const propertyType = getPropertyType(ast, propertyName.toString(), (propertyName) =>\n getProperty([...propertyPath.slice(0, i), propertyName]),\n );\n if (propertyType == null) {\n const indexSignatureType = getIndexSignatureValueType(ast);\n if (indexSignatureType != null) {\n ast = indexSignatureType;\n continue;\n }\n\n throw new TypeError(`Unknown property: ${formatPropertyPath([...propertyPath.slice(0, i), propertyName])}`);\n }\n\n ast = propertyType;\n }\n }\n\n return ast === rootObjectSchema.ast ? rootObjectSchema : Schema.make<Schema.Top>(ast);\n }\n\n /**\n * Rejects properties not declared on the schema. Types with index signatures allow extra keys.\n */\n public static assertExactProperties(\n ast: SchemaAST.AST,\n value: unknown,\n getProperty: (path: KeyPath) => unknown = () => undefined,\n path: KeyPath = [],\n ): void {\n if (!isPlainRecord(value)) {\n return;\n }\n\n const typeLiteral = resolveTypeLiteral(ast, (propertyName) => getProperty([...path, propertyName]));\n if (typeLiteral == null) {\n return;\n }\n\n const propertySignatures = SchemaAST.getPropertySignatures(typeLiteral);\n const allowedKeys = new Set(propertySignatures.map((property) => String(property.name)));\n const indexSignatureType = typeLiteral.indexSignatures[0]?.type;\n\n for (const key of Object.keys(value)) {\n const propertyPath = [...path, key];\n if (!allowedKeys.has(key)) {\n if (indexSignatureType == null) {\n throw new TypeError(`Unknown property: ${formatPropertyPath(propertyPath)}`);\n }\n\n this.assertExactProperties(indexSignatureType, value[key], getProperty, propertyPath);\n continue;\n }\n\n const propertySignature = propertySignatures.find((property) => String(property.name) === key);\n invariant(propertySignature, 'Property signature must exist.');\n this.assertExactProperties(propertySignature.type, value[key], getProperty, propertyPath);\n }\n }\n\n public static getIndexedElementAst(ast: SchemaAST.AST, index: number | string): SchemaAST.AST | null {\n const arrayAst = unwrapArray(ast);\n if (arrayAst != null) {\n return getArrayElementAst(arrayAst, index);\n }\n\n const unionAst = unwrapAst(\n ast,\n (candidate) => SchemaAST.isUnion(candidate) && candidate.types.some((member) => unwrapArray(member) != null),\n );\n if (unionAst != null && SchemaAST.isUnion(unionAst)) {\n for (const member of unionAst.types) {\n const memberArrayAst = unwrapArray(member);\n if (memberArrayAst != null) {\n return getArrayElementAst(memberArrayAst, index);\n }\n }\n }\n\n return null;\n }\n\n /**\n * Whether the property may be cleared.\n *\n * v4 records optionality as `context.isOptional` on the property's own type rather than widening\n * it to `T | undefined`, so the property's schema alone no longer admits `undefined`.\n */\n public static isOptionalProperty(target: any, prop: string | symbol): boolean {\n const ast = getTargetAst(target);\n if (!ast || typeof prop === 'symbol') {\n return false;\n }\n const property = SchemaAST.getPropertySignatures(ast).find((candidate) => candidate.name === prop);\n return property != null && SchemaAST.isOptional(property.type);\n }\n\n /** The AST that property `prop` of a typed target follows. */\n public static getTargetPropertyAst(target: any, prop: string | symbol): SchemaAST.AST {\n const ast = getTargetAst(target);\n invariant(ast, 'target has no schema');\n\n if (Array.isArray(target)) {\n if (prop === 'length') {\n return Schema.Number.ast;\n }\n\n if (typeof prop !== 'symbol') {\n const indexedAst = this.getIndexedElementAst(ast, prop);\n if (indexedAst != null) {\n return indexedAst;\n }\n }\n\n // Arrays sometimes carry the element struct as their stamped schema.\n if (SchemaAST.isObjects(ast)) {\n return ast;\n }\n }\n\n if (typeof prop === 'number' || (typeof prop === 'string' && /^\\d+$/.test(prop))) {\n const indexedAst = this.getIndexedElementAst(ast, prop);\n if (indexedAst != null) {\n return indexedAst;\n }\n }\n\n const arrayAst = unwrapArray(ast);\n if (arrayAst != null) {\n return getArrayElementAst(arrayAst, prop);\n }\n\n const propertyType = getPropertyType(ast, prop.toString(), (prop) => target[prop]);\n if (propertyType == null) {\n const indexSignatureType = getIndexSignatureValueType(ast);\n if (indexSignatureType != null) {\n return indexSignatureType;\n }\n\n throw new TypeError(`Unknown property: ${String(prop)}`);\n }\n\n return propertyType;\n }\n}\n\n/** A root carries its schema; a nested value carries only its AST (see {@link SchemaAstId}). */\nconst getTargetAst = (target: any): SchemaAST.AST | undefined =>\n target[SchemaAstId] ?? (target[SchemaId] as Schema.Top | undefined)?.ast;\n\nconst validateAst = (ast: SchemaAST.AST): void => {\n if (SchemaAST.isUnion(ast)) {\n const typeAstList = ast.types.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n // Check we can handle a discriminated union.\n if (typeAstList.length > 1) {\n getTypeDiscriminators(typeAstList);\n }\n typeAstList.forEach(validateAst);\n } else if (SchemaAST.isArrays(ast)) {\n [...ast.elements, ...ast.rest].forEach(validateAst);\n } else if (SchemaAST.isObjects(ast)) {\n SchemaAST.getPropertySignatures(ast).forEach((property) => validateAst(property.type));\n }\n};\n\n/**\n * Tuple AST is used both for:\n * fixed-length tuples ([string, number]) in which case AST will be { elements: [Schema.String, Schema.Number] }\n * variable-length arrays (Array<string | number>) in which case AST will be { rest: [Schema.Union([Schema.String, Schema.Number])] }\n */\nconst getArrayElementAst = (tupleAst: SchemaAST.Arrays, property: string | symbol | number): SchemaAST.AST => {\n const elementIndex =\n typeof property === 'number' ? property : typeof property === 'string' ? parseInt(property, 10) : Number.NaN;\n if (Number.isNaN(elementIndex)) {\n invariant(property === 'length', `invalid array property: ${String(property)}`);\n return Schema.Number.ast;\n }\n if (elementIndex < tupleAst.elements.length) {\n return tupleAst.elements[elementIndex];\n }\n\n return tupleAst.rest[0];\n};\n\nconst flattenUnion = (typeAst: SchemaAST.AST): SchemaAST.AST[] =>\n SchemaAST.isUnion(typeAst) ? typeAst.types.flatMap(flattenUnion) : [typeAst];\n\nconst getProperties = (\n typeAst: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => any,\n): ReadonlyArray<SchemaAST.PropertySignature> => {\n const astCandidates = flattenUnion(typeAst);\n const typeAstList = astCandidates.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n if (typeAstList.length === 0) {\n return [];\n }\n if (typeAstList.length === 1) {\n return SchemaAST.getPropertySignatures(typeAstList[0]);\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = typeDiscriminators.findIndex((p) => targetPropertyValue === (p.type as SchemaAST.Literal).literal);\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return SchemaAST.getPropertySignatures(typeAstList[typeIndex]);\n};\n\nconst getPropertyType = (\n ast: SchemaAST.AST,\n propertyName: string,\n getTargetPropertyFn: (propertyName: string) => any,\n): SchemaAST.AST | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return ast;\n }\n\n const typeOrDiscriminatedUnion = unwrapAst(ast, (t) => {\n return SchemaAST.isObjects(t) || (SchemaAST.isUnion(t) && t.types.some((t) => SchemaAST.isObjects(t)));\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n const targetProperty = getProperties(typeOrDiscriminatedUnion, getTargetPropertyFn).find(\n (p) => p.name === propertyName,\n );\n if (targetProperty != null) {\n return unwrapAst(targetProperty.type);\n }\n\n const indexSignatureType = unwrapAst(ast, SchemaAST.isObjects);\n if (indexSignatureType && SchemaAST.isObjects(indexSignatureType) && indexSignatureType.indexSignatures.length > 0) {\n return unwrapAst(indexSignatureType.indexSignatures[0].type);\n }\n\n return null;\n};\n\n/**\n * Unwraps the shapes a tag takes on after a JSON schema round-trip: optional (its constructor\n * default leaves it out of `required`) and single-member union (a one-entry `anyOf`).\n */\nconst unwrapDiscriminator = (ast: SchemaAST.AST): SchemaAST.AST => {\n const unwrapped = SchemaEx.unwrapOptional(ast);\n return SchemaAST.isUnion(unwrapped) && unwrapped.types.length === 1\n ? unwrapDiscriminator(unwrapped.types[0])\n : unwrapped;\n};\n\nconst getTypeDiscriminators = (typeAstList: SchemaAST.Objects[]): SchemaAST.PropertySignature[] => {\n const discriminatorPropCandidates = typeAstList\n .flatMap(SchemaAST.getPropertySignatures)\n .filter((p) => SchemaAST.isLiteral(unwrapDiscriminator(p.type)));\n const propertyName = discriminatorPropCandidates[0]?.name;\n // Optionality cannot disqualify a candidate: a round-tripped discriminator's constructor default\n // leaves it optional, and the round trip erases what would distinguish it from an authored one.\n const isValidDiscriminator =\n propertyName !== undefined && discriminatorPropCandidates.every((p) => p.name === propertyName);\n const everyTypeHasDiscriminator = discriminatorPropCandidates.length === typeAstList.length;\n const isDiscriminatedUnion = isValidDiscriminator && everyTypeHasDiscriminator;\n invariant(isDiscriminatedUnion, 'type ambiguity: every type in a union must have a single unique-literal field');\n return discriminatorPropCandidates;\n};\n\n/**\n * Used to check that rootAst is for a type matching the provided predicate.\n * That's not always straightforward because types of optionality and recursive types.\n * const Task = Schema.Struct({\n * ...,\n * previous?: Schema.optional(Schema.suspend(() => Task)),\n * });\n * Here the AST for `previous` field is going to be Union(Suspend(Type), Undefined).\n * SchemaAST.isObjects(field) will return false, but unwrapAst(field, (ast) => SchemaAST.isObjects(ast))\n * will return true.\n */\nconst unwrapAst = (rootAst: SchemaAST.AST, predicate?: (ast: SchemaAST.AST) => boolean): SchemaAST.AST | null => {\n let ast: SchemaAST.AST | undefined = rootAst;\n while (ast != null) {\n if (predicate?.(ast)) {\n return ast;\n }\n\n if (SchemaAST.isUnion(ast)) {\n const next: any = ast.types.find((t) => (predicate != null && predicate(t)) || SchemaAST.isSuspend(t));\n if (next != null) {\n ast = next;\n continue;\n }\n }\n\n if (SchemaAST.isSuspend(ast)) {\n ast = ast.thunk();\n } else {\n return predicate == null ? ast : null;\n }\n }\n\n return null;\n};\n\nconst unwrapArray = (ast: SchemaAST.AST) => unwrapAst(ast, SchemaAST.isArrays) as SchemaAST.Arrays | null;\n\nconst getIndexSignatureValueType = (ast: SchemaAST.AST): SchemaAST.AST | null => {\n const typeLiteral = unwrapAst(ast, SchemaAST.isObjects);\n if (typeLiteral == null || !SchemaAST.isObjects(typeLiteral) || typeLiteral.indexSignatures.length === 0) {\n return null;\n }\n\n return unwrapAst(typeLiteral.indexSignatures[0].type);\n};\n\nconst resolveTypeLiteral = (\n ast: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => unknown,\n): SchemaAST.Objects | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return null;\n }\n\n const typeOrDiscriminatedUnion = unwrapAst(ast, (type) => {\n return (\n SchemaAST.isObjects(type) || (SchemaAST.isUnion(type) && type.types.some((member) => SchemaAST.isObjects(member)))\n );\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n if (SchemaAST.isObjects(typeOrDiscriminatedUnion)) {\n return typeOrDiscriminatedUnion;\n }\n\n if (!SchemaAST.isUnion(typeOrDiscriminatedUnion)) {\n return null;\n }\n\n const typeAstList = typeOrDiscriminatedUnion.types.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n if (typeAstList.length === 1) {\n return typeAstList[0];\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = typeDiscriminators.findIndex(\n (property) => targetPropertyValue === (property.type as SchemaAST.Literal).literal,\n );\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return typeAstList[typeIndex];\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value) || value instanceof Uint8Array) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\nconst formatPropertyPath = (path: KeyPath): string => path.map(String).join('.');\n\nexport const checkIdNotPresentOnSchema = (schema: Schema.Codec<any, any, any>) => {\n invariant(SchemaAST.isObjects(schema.ast));\n const idProperty = SchemaAST.getPropertySignatures(schema.ast).find((prop) => prop.name === 'id');\n if (idProperty != null) {\n throw new Error('\"id\" property name is reserved');\n }\n};\n\n// TODO(burdon): Reconcile with JsonPath.\ntype KeyPath = readonly (string | number)[];\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Equal from 'effect/Equal';\nimport * as Hash from 'effect/Hash';\nimport * as Schema from 'effect/Schema';\nimport { type InspectOptionsStylized } from 'node:util';\n\nimport { Event } from '@dxos/async';\nimport { inspectCustom } from '@dxos/debug';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { getDeep } from '@dxos/util';\n\nimport { getSchemaURI } from '../../Annotation/annotations.ts';\nimport { isEntity } from '../../Entity/guard.ts';\nimport { toEffectSchema } from '../../JsonSchema/json-schema.ts';\nimport {\n ObjectDeletedId,\n ParentId,\n SchemaAstId,\n SchemaId,\n StaticTypeSchemaSlot,\n TypeEntityId,\n TypeId,\n} from '../types/index.ts';\nimport { assertMutable, executeChange, queueNotification } from './change-context.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { createTextMethodError } from './errors.ts';\nimport { batchEvents } from './event-batch.ts';\nimport {\n changeKeyOf,\n getEchoRoot,\n getOwner,\n getRawTarget,\n hasForeignOwner,\n notifyOwnerChain,\n setOwnerRecursive,\n wouldCreateCycle,\n} from './ownership.ts';\nimport { type ReactiveHandler } from './proxy-types.ts';\nimport {\n createProxy,\n isProxy,\n isReactiveRecord,\n isValidProxyTarget,\n normalizeSpliceRange,\n symbolReactivePrototype,\n} from './proxy-utils.ts';\nimport { ReactiveArray } from './reactive-array.ts';\nimport { SchemaValidator, assertsWithDetail } from './schema-validator.ts';\nimport { ChangeId, ChangeKeyId, EventId } from './symbols.ts';\n\n// Re-export for external consumers.\nexport { getEchoRoot, setMetaOwner } from './ownership.ts';\n\ntype ProxyTarget = {\n /**\n * Typename or type DXN.\n */\n [TypeId]: string;\n\n /**\n * Schema for the root.\n */\n [SchemaId]?: Schema.Top;\n\n /**\n * AST for a nested value.\n */\n [SchemaAstId]?: SchemaAST.AST;\n [ParentId]?: any;\n\n /**\n * For modifications.\n */\n [EventId]: Event<void>;\n} & ({ [key: keyof any]: any } | any[]);\n\n/**\n * Deep copy a value, handling arrays and nested objects.\n * Preserves ReactiveArray type and hidden properties (SchemaId, TypeId).\n * Does not copy class instances or functions (except ReactiveArray).\n *\n * Note: Cannot use structuredClone because we need to:\n * - Unwrap proxies\n * - Preserve ReactiveArray instances\n * - Copy Symbol-keyed hidden properties (SchemaId, TypeId)\n * - Convert plain arrays to ReactiveArray\n *\n * Performance: O(n) where n is the total number of nested objects/arrays.\n * For large structures, consider using Refs for frequently reassigned subtrees.\n */\nconst deepCopy = <T>(value: T, visited = new Map<object, object>()): T => {\n if (value == null || typeof value !== 'object') {\n return value;\n }\n\n // Handle proxies - get the underlying target.\n const actualValue = getRawTarget(value);\n\n // Check for circular references in the copy.\n if (visited.has(actualValue)) {\n return visited.get(actualValue) as T;\n }\n\n // Handle ReactiveArray specially to preserve reactivity.\n if (actualValue instanceof ReactiveArray) {\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n // Copy hidden properties.\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n }\n\n // Don't copy other class instances (objects with non-Object prototype). A reactive record\n // (its metadata moved onto a behaviour prototype) still counts as a plain data record here.\n const proto = Object.getPrototypeOf(actualValue);\n if (proto !== Array.prototype && proto !== null && !isReactiveRecord(actualValue)) {\n return value; // Return as-is, don't copy class instances.\n }\n\n if (Array.isArray(actualValue)) {\n // Plain arrays become ReactiveArrays.\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n return copy as T;\n }\n\n const copy: Record<string, any> = {};\n visited.set(actualValue, copy);\n for (const key of Object.keys(actualValue)) {\n copy[key] = deepCopy((actualValue as any)[key], visited);\n }\n // Copy hidden properties (SchemaId, TypeId).\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n};\n\n/**\n * Write `value` at `path`, unwrapping each hop to its raw target. A nested record is stored as its\n * sub-proxy, and writing through one would re-impose the per-delta validation the text path exists to\n * skip.\n */\nconst setDeepOnRawTargets = (target: object, path: readonly (string | number)[], value: unknown): void => {\n let parent: any = getRawTarget(target);\n for (const key of path.slice(0, -1)) {\n parent = getRawTarget(parent[key]);\n }\n parent[path[path.length - 1]] = value;\n};\n\n/**\n * Copy hidden properties (SchemaId, SchemaAstId, TypeId) from source to target.\n */\nconst copyHiddenProperties = (source: any, target: any): void => {\n if (SchemaId in source) {\n defineHiddenProperty(target, SchemaId, source[SchemaId]);\n }\n if (SchemaAstId in source) {\n defineHiddenProperty(target, SchemaAstId, source[SchemaAstId]);\n }\n if (TypeId in source) {\n defineHiddenProperty(target, TypeId, source[TypeId]);\n }\n};\n\n//\n// Object layering for an in-memory typed reactive object (`TypedReactiveHandler`).\n//\n// Unlike the database-backed handler (echo-client/echo-prototypes.ts), here USER DATA lives as\n// real OWN properties on the target — there is no document behind it. Only the per-object metadata\n// is relocated onto a prototype, so swapping handlers doesn't disturb the data shape:\n//\n// proxy ──Proxy(target, REACTIVE_PROXY_HANDLER → TypedReactiveHandler)\n// │ set/has/... traps run here; there is no `get` trap, so reads land on the target\n// ▼\n// target the user's object. OWN enumerable props = user data ({ name, age, ... });\n// │ [[Prototype]] OWN symbol props are removed by `compactMetadataToInstanceState` after init.\n// ▼\n// instanceState `Object.create(TypedObjectPrototype)`. Holds the relocated symbol-keyed\n// │ [[Prototype]] metadata as hidden props: [EventId] (root only), [ObjectDeletedId], [SchemaId],\n// │ [TypeId], [TypeEntityId], cached [StaticTypeSchemaSlot], ... (Arrays are\n// │ exempt — they keep their ReactiveArray chain and are never compacted.)\n// ▼\n// TypedObjectPrototype shared behaviour. Carries [symbolReactivePrototype]=true (so the\n// │ [[Prototype]] \"plain object\" gates still treat the record as data) plus the system\n// │ accessors [ChangeId], [ChangeKeyId], [StaticTypeSchemaSlot]. There is no get\n// │ trap: a read of any of them resolves off this chain by ordinary lookup.\n// ▼\n// Object.prototype ──▶ null a `getPrototypeOf` trap reports `Object.prototype` so consumers\n// see a plain object; the real instanceState prototype stays hidden.\n//\n// Root vs nested: a root object owns an `[EventId]`; nested records share their root's reactivity\n// and have none. That presence is the \"is this an initialized root\" signal (it replaced an earlier\n// `[ChangeId] === true` marker).\n//\n// `this` in the accessors below: the get trap calls `Reflect.get(target, prop, receiver)`, so\n// `this` is the PROXY (receiver) on the common path, or the raw target when read directly.\n// `getRawTarget(this)` normalizes to the underlying target — needed here because user data and the\n// metadata chain both hang off the raw target, and `executeChange` keys the change context by it.\n//\n/**\n * Behaviour prototype for typed reactive records. A record's per-object metadata is moved onto an\n * intermediate instance-state object whose prototype is this, so that swapping the handler that\n * backs an object (e.g. an in-memory object becoming database-backed) is a prototype re-point that\n * doesn't perturb the target's own-property shape. Marked as a reactive prototype so the \"plain\n * object\" gates (`isValidProxyTarget` / `deepCopy`) still treat such targets as data records.\n */\nconst TypedObjectPrototype: object = Object.create(Object.prototype);\ndefineHiddenProperty(TypedObjectPrototype, symbolReactivePrototype, true);\n\n// The ECHO system surface is exposed as accessors on the behaviour prototype rather than as\n// branches in the `get` trap. `this` is the proxy receiver (or the raw target when read directly);\n// `getRawTarget` resolves either to the underlying target.\nObject.defineProperties(TypedObjectPrototype, {\n [ChangeKeyId]: {\n get(this: ProxyTarget) {\n return changeKeyOf(this);\n },\n },\n [ChangeId]: {\n // A function that runs a mutation inside a controlled change context. Only root objects (which\n // own an `EventId`) expose one; nested records share their root's reactivity and return undefined.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n if (!(EventId in target)) {\n return undefined;\n }\n return (callback: (obj: any) => void) => executeChange(target, target, this, callback);\n },\n },\n // Effect `Hash`/`Equal` traits, keyed by entity id: an entity has exactly one live proxy, and the\n // bare `id` spells that invariant without the throw a derived URI risks on a malformed id.\n // Effect's structural default would instead deep-read the record and go stale on the next mutation.\n // Selected by the `[KindId]` brand, not by the presence of an `id`, since a nested record sharing\n // this prototype may carry an application-level one; those keep reference identity.\n [Hash.symbol]: {\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n return () => (isEntity(target) ? Hash.hash(target.id) : Hash.random(target));\n },\n },\n [Equal.symbol]: {\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n return isEntity(target)\n ? (that: unknown) => isEntity(that) && that.id === target.id\n : (that: unknown) => getRawTarget(that) === target;\n },\n },\n [StaticTypeSchemaSlot]: {\n // Lazily rebuild the source Effect Schema from `jsonSchema` and cache it as an own (hidden)\n // property so subsequent reads short-circuit this accessor; the set-trap deletes the cache when\n // `jsonSchema` is mutated.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n const jsonSchema = (target as any).jsonSchema;\n if (jsonSchema == null) {\n return undefined;\n }\n const rebuilt = toEffectSchema(jsonSchema);\n defineHiddenProperty(target, StaticTypeSchemaSlot, rebuilt);\n return rebuilt;\n },\n },\n});\n\n/**\n * True once the root owns an `[EventId]`, i.e. is past construction and notifies on change. The\n * read-only gate itself lives in the shared proxy handler (`assertMutable`), keyed by `[ChangeKeyId]`.\n */\nconst isInitialized = (echoRoot: object): boolean => EventId in echoRoot;\n\n/**\n * Move a record's per-object metadata (symbol-keyed hidden properties) onto a fresh instance-state\n * object inserted between the target and {@link TypedObjectPrototype}. The target keeps only its\n * user data as own properties. Arrays are exempt — they keep their own (ReactiveArray) prototype chain.\n */\nconst compactMetadataToInstanceState = (target: ProxyTarget): void => {\n if (Array.isArray(target) || Object.getPrototypeOf(target) !== Object.prototype) {\n return;\n }\n const state = Object.create(TypedObjectPrototype);\n for (const symbol of Object.getOwnPropertySymbols(target)) {\n const descriptor = Object.getOwnPropertyDescriptor(target, symbol)!;\n Object.defineProperty(state, symbol, descriptor);\n // Non-configurable symbols (e.g. `SchemaId`/`TypeId`, locked by `setSchema`/`setTypename` on\n // objects decoded from JSON) cannot be deleted — leave them as an own property on the target,\n // shadowing the copy on `state`; reads still resolve correctly since own properties take\n // precedence over the prototype chain.\n if (descriptor.configurable) {\n // Dynamic delete over arbitrary symbol keys: `ProxyTarget` declares these as required, so the\n // statically-typed view cannot express deleting them; the symbol set is only known at runtime.\n delete (target as any)[symbol];\n }\n }\n Object.setPrototypeOf(target, state);\n};\n\n/**\n * Typed in-memory reactive store (with Schema).\n * Reactivity is based on Event subscriptions, not signals.\n */\nexport class TypedReactiveHandler implements ReactiveHandler<ProxyTarget> {\n public static readonly instance: ReactiveHandler<any> = new TypedReactiveHandler();\n\n private _inSet = false;\n\n private constructor() {}\n\n init(target: ProxyTarget): void {\n assertArgument(typeof target === 'object' && target !== null, 'target');\n invariant(SchemaId in target || SchemaAstId in target, 'Schema is not defined for the target');\n\n // Only set EventId on root objects (those without an owner).\n // Nested objects share their root's EventId for centralized reactivity.\n const hasOwner = !!getOwner(target);\n if (!(EventId in target) && !hasOwner) {\n defineHiddenProperty(target, EventId, new Event());\n }\n\n // Default to not-deleted, but preserve a deletion marker already stamped on the target (e.g. by\n // `objectFromJSON` when hydrating a tombstone snapshot).\n if (!(ObjectDeletedId in target)) {\n defineHiddenProperty(target, ObjectDeletedId, false);\n }\n\n // Only set owners if this is a root object (no existing owner).\n // Nested objects already have owners set by their root's initialization.\n // If we re-set owners here for nested objects, we'd incorrectly point\n // array elements to the array instead of the true root ECHO object.\n if (!hasOwner) {\n // Set owner on all nested objects to this root ECHO object.\n // All nested records point directly to this root for centralized reactivity.\n for (const key in target) {\n if (isProxy(target)) {\n continue;\n }\n let value = (target as any)[key];\n if (isValidProxyTarget(value) || isProxy(value)) {\n // Deep copy values that have foreign owners (owned by a different object,\n // or are root ECHO objects whose nested structures would be owned by them).\n // This recursively checks all nested objects.\n if (hasForeignOwner(value, target)) {\n value = deepCopy(value);\n (target as any)[key] = value;\n }\n setOwnerRecursive(value, target);\n }\n }\n }\n\n // Maybe have been set by `create`.\n Object.defineProperty(target, inspectCustom, {\n enumerable: false,\n configurable: true,\n value: this._inspect.bind(target),\n });\n\n // Relocate per-object metadata onto an instance-state prototype, leaving only user data as own\n // properties on the target. Done last so all metadata set above (and by `prepareTypedTarget`) moves.\n compactMetadataToInstanceState(target);\n\n // After compaction and ownership, so each child is stamped and owned before it gets a proxy of its\n // own. Recursive: wrapping a child runs its `init`, which wraps that child's children.\n this._wrapNestedValues(target);\n }\n\n /**\n * Replaces every raw nested record and array on the target with the sub-proxy a read returns, so a\n * forwarded read hands out the same reactive view the `get` trap used to build. Class instances,\n * `Ref`s and primitives are not proxy targets and stay as they are.\n */\n private _wrapNestedValues(target: ProxyTarget): void {\n for (const key of Object.keys(target)) {\n // The descriptor first: reading an own getter here would invoke it, and a type entity's\n // `jsonSchema` getter can reach a schema still inside its own `const` initializer.\n if (Object.getOwnPropertyDescriptor(target, key)?.get) {\n continue;\n }\n const value = (target as any)[key];\n if (isValidProxyTarget(value)) {\n (target as any)[key] = createProxy(value, this);\n }\n }\n }\n\n set(target: ProxyTarget, prop: string | symbol, value: any, receiver: any): boolean {\n const echoRoot = getEchoRoot(target);\n const initialized = isInitialized(echoRoot);\n\n let result: boolean = false;\n this._inSet = true;\n try {\n batchEvents(() => {\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, prop, value);\n result = Reflect.set(target, prop, preparedValue, receiver);\n // Invalidate the cached source Effect Schema when `jsonSchema` changes\n // (e.g. `Type.addFields`) so `Type.getSchema` rebuilds from the new shape.\n if (prop === 'jsonSchema') {\n Reflect.deleteProperty(target, StaticTypeSchemaSlot);\n }\n // Queue notification instead of emitting immediately (batched).\n if (initialized) {\n queueNotification(echoRoot);\n // Also notify the owner chain so parent objects are updated when nested objects change.\n notifyOwnerChain(target);\n }\n });\n } finally {\n this._inSet = false;\n }\n return result;\n }\n\n deleteProperty(target: ProxyTarget, property: string | symbol): boolean {\n const echoRoot = getEchoRoot(target);\n\n const initialized = isInitialized(echoRoot);\n const result = Reflect.deleteProperty(target, property);\n if (initialized) {\n queueNotification(echoRoot);\n }\n return result;\n }\n\n defineProperty(target: ProxyTarget, property: string | symbol, attributes: PropertyDescriptor): boolean {\n const echoRoot = getEchoRoot(target);\n const initialized = isInitialized(echoRoot);\n\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, property, attributes.value);\n const result = Reflect.defineProperty(target, property, {\n ...attributes,\n value: preparedValue,\n });\n if (!this._inSet && initialized) {\n // Queue notification instead of emitting immediately (batched).\n queueNotification(echoRoot);\n }\n return result;\n }\n\n textUpdate(target: ProxyTarget, path: readonly (string | number)[], newText: string): void {\n this._applyTextMutation(target, 'update', path, () => newText);\n }\n\n textSplice(\n target: ProxyTarget,\n path: readonly (string | number)[],\n start: number,\n deleteCount: number,\n insert: string,\n ): string {\n let removed = '';\n this._applyTextMutation(target, 'splice', path, (current) => {\n const range = normalizeSpliceRange(current.length, start, deleteCount);\n removed = current.slice(range.start, range.start + range.deleteCount);\n return current.slice(0, range.start) + insert + current.slice(range.start + range.deleteCount);\n });\n return removed;\n }\n\n /**\n * Shared read-modify-write for the in-memory string CRDT path. A method call is invisible to the proxy,\n * so it runs the same `assertMutable` gate the traps run, then mutates and notifies through the same\n * batched notification path so reactivity fires.\n *\n * Writes on the raw targets, intentionally bypassing `_prepareValueForAssignment` /\n * `_validateValue`: a string CRDT delta produces a string, and per-delta schema checks (pattern,\n * maxLength) would reject valid intermediate states during incremental edits. Such constraints are\n * enforced at the initial assignment or as application-level invariants, mirroring the Automerge path.\n */\n private _applyTextMutation(\n target: ProxyTarget,\n method: string,\n path: readonly (string | number)[],\n compute: (current: string) => string,\n ): void {\n assertMutable(target, method, createTextMethodError);\n\n const echoRoot = getEchoRoot(target);\n const keyPath = [...path];\n invariant(keyPath.length > 0, 'Text path must be non-empty');\n const current = getDeep(target, keyPath);\n if (typeof current !== 'string') {\n throw new TypeError(`Text mutation target at \"${keyPath.join('.')}\" is not a string.`);\n }\n\n const next = compute(current);\n batchEvents(() => {\n // Write directly on the raw target (not the proxy) and notify through the same batched path\n // the `set` trap uses, so subscribers fire once per `Obj.update`.\n setDeepOnRawTargets(target, keyPath, next);\n queueNotification(echoRoot);\n notifyOwnerChain(target);\n });\n }\n\n /**\n * Prepare a value for assignment to a typed object property.\n * Handles cycle detection, copy-on-assign, array conversion, validation, and ownership.\n */\n private _prepareValueForAssignment(\n target: ProxyTarget,\n prop: string | symbol,\n value: any,\n ): { echoRoot: object; preparedValue: any } {\n const echoRoot = getEchoRoot(target);\n\n if (typeof prop === 'symbol') {\n return { echoRoot, preparedValue: value };\n }\n\n // Check for cycles before assignment.\n if (isValidProxyTarget(value) || isProxy(value)) {\n if (wouldCreateCycle(echoRoot, value)) {\n throw new Error('Cannot create cycles in typed object graph. Consider using Ref for circular references.');\n }\n }\n\n // Prevent direct assignment of root ECHO objects (those created with Obj.make/Relation.make).\n // These must be wrapped with Ref.make for proper reference handling.\n // This matches database object behavior for consistency.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const isRootEchoObject = EventId in actualValue;\n if (isRootEchoObject) {\n throw new Error('Object references must be wrapped with `Ref.make`');\n }\n }\n\n // Copy-on-assign: If the value is a nested record owned by a different ECHO object, deep copy it.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const existingOwner = getOwner(actualValue);\n if (existingOwner != null && existingOwner !== echoRoot) {\n value = deepCopy(value);\n }\n }\n\n // Convert arrays to reactive arrays — the whole subtree, as construction does, not just the top\n // level: an array reached through an assigned record is proxied like any other and must be gated\n // and reactive too.\n if (Array.isArray(value) && !(value instanceof ReactiveArray)) {\n value = ReactiveArray.from(value);\n }\n if (value != null && typeof value === 'object' && !isProxy(value)) {\n makeArraysReactive(value);\n }\n\n const validatedValue = this._validateValue(target, prop, value);\n\n // Set owner on new value to the root ECHO object.\n if (isValidProxyTarget(validatedValue) || isProxy(validatedValue)) {\n setOwnerRecursive(validatedValue, echoRoot);\n }\n\n // Stored wrapped, for the same reason `init` wraps: the target is what a forwarded read sees.\n return {\n echoRoot,\n preparedValue: isValidProxyTarget(validatedValue) ? createProxy(validatedValue, this) : validatedValue,\n };\n }\n\n private _validateValue(target: any, prop: string | symbol, value: any) {\n if (prop === ParentId) {\n return value;\n }\n const ast = SchemaValidator.getTargetPropertyAst(target, prop);\n // Clearing an optional property is admitted here rather than by the property's own schema: v4\n // keeps optionality on the property's context instead of widening its type to `T | undefined`.\n if (value !== undefined || !SchemaValidator.isOptionalProperty(target, prop)) {\n assertsWithDetail(Schema.make(ast), value);\n }\n SchemaValidator.assertExactProperties(ast, value, (path) => getDeep(value, path));\n if (isValidProxyTarget(value)) {\n setNestedSchema(value, ast);\n }\n\n return value;\n }\n\n private _inspect(\n _: number,\n options: InspectOptionsStylized,\n inspectFn: (value: any, options?: InspectOptionsStylized) => string,\n ): string {\n const inspected = inspectFn(this, {\n ...options,\n showHidden: false,\n customInspect: false,\n });\n\n return `Typed ${inspected}`;\n }\n}\n\n/**\n * Pointer to a `Type.Type` entity, stamped as the back-reference (`TypeEntityId`)\n * on instances and read by the `SchemaId` getter installed below.\n *\n * Structural shape (not `Type.AnyEntity`) because `internal/common/proxy/`\n * can't import the top-level `Type` module without a cycle. Every kind of\n * `Type.Type` entity satisfies this shape:\n * - Static (`Type.makeObject(dxn)` pipe) — slot set directly on the object.\n * - Persisted (echo-handler-wrapped) — slot exposed via that handler's\n * `get` trap (rebuilds from `data.jsonSchema`).\n * - In-memory pre-persist (`Type.makeObjectFromJsonSchema`) — slot exposed\n * via the `case StaticTypeSchemaSlot:` arm in this file's `get` trap.\n */\nexport type TypeSource = { readonly [StaticTypeSchemaSlot]?: Schema.Top };\n\n/**\n * Stamps a root target with its schema, and each nested proxy target below it with the AST it follows.\n *\n * @param skipOwnStamp Skip stamping `TypeId`/`SchemaId` on `obj` itself (still recurses into\n * children, which always get stamped). Used for objects decoded from JSON, whose own `TypeId`/\n * `SchemaId` are already set by `setTypename`/`setSchema` as `configurable: false` — redefining\n * them here (with `configurable: true`) would throw.\n */\nconst setSchemaProperties = (obj: any, schema: Schema.Top, typeSource?: TypeSource, skipOwnStamp = false) => {\n if (!skipOwnStamp) {\n const schemaType = getSchemaURI(schema);\n if (schemaType != null) {\n defineHiddenProperty(obj, TypeId, schemaType);\n }\n\n if (typeSource != null) {\n // Keep a back-reference to the type entity so `Obj.getType` /\n // `Relation.getType` / `Entity.getType` can return it.\n defineHiddenProperty(obj, TypeEntityId, typeSource);\n\n // Install `SchemaId` as a getter that reads through the entity's static\n // schema slot. The three entity shapes (static / persisted / in-memory\n // pre-persist) each populate the slot via their own get-trap path, so\n // `Type.update` / `Type.addFields` mutations propagate into validation\n // for objects created via `Obj.make(typeEntity, ...)` without this file\n // having to rebuild from `jsonSchema` itself.\n Object.defineProperty(obj, SchemaId, {\n get: () => typeSource[StaticTypeSchemaSlot] ?? schema,\n enumerable: false,\n configurable: true,\n });\n } else {\n defineHiddenProperty(obj, SchemaId, schema);\n }\n }\n\n setChildSchemas(obj, schema.ast);\n};\n\n/** Stamps a nested proxy target, and those below it, with the AST it follows. */\nconst setNestedSchema = (obj: any, ast: SchemaAST.AST) => {\n const schemaType = getSchemaURI(Schema.make(ast));\n if (schemaType != null) {\n defineHiddenProperty(obj, TypeId, schemaType);\n }\n defineHiddenProperty(obj, SchemaAstId, ast);\n setChildSchemas(obj, ast);\n};\n\nconst setChildSchemas = (obj: any, ast: SchemaAST.AST) => {\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n if (isValidProxyTarget(obj[index])) {\n setNestedSchema(obj[index], SchemaValidator.getIndexedElementAst(ast, index) ?? Schema.Any.ast);\n }\n }\n return;\n }\n\n for (const key in obj) {\n if (isValidProxyTarget(obj[key])) {\n let elementAst: SchemaAST.AST;\n try {\n elementAst = SchemaValidator.getTargetPropertyAst(obj, key);\n } catch {\n // Property not in schema — treat as untyped so the proxy can still wrap it.\n elementAst = Schema.Any.ast;\n }\n setNestedSchema(obj[key], elementAst);\n }\n }\n};\n\nexport type PrepareTargetOptions = {\n /** Validate the target against its schema (default). See `Obj.MakeOptions.skipValidation`. */\n validate?: boolean;\n};\n\n// Accepts any encoded type: the typed handler operates on the decoded representation, so schemas\n// whose encoded form differs (e.g. refs encode as `{ '/': uri }`) are valid here.\nexport const prepareTypedTarget = <T>(\n target: T,\n schema: Schema.Schema<T>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n) => {\n validateAndReactifyTarget(target, schema, options);\n setSchemaProperties(target, schema, typeSource);\n};\n\n/**\n * Validate a target against its schema and convert nested arrays to `ReactiveArray`. Shared by\n * {@link prepareTypedTarget} and {@link prepareDecodedTypedTarget}.\n */\nexport const validateAndReactifyTarget = <T>(target: T, schema: Schema.Schema<T>, options?: PrepareTargetOptions) => {\n if (!SchemaAST.isObjects(schema.ast)) {\n throw new Error('schema has to describe an object type');\n }\n\n if (options?.validate !== false) {\n SchemaValidator.validateSchema(schema);\n assertsWithDetail(schema, target);\n SchemaValidator.assertExactProperties(schema.ast, target, (path) => getDeep(target, path));\n }\n makeArraysReactive(target);\n};\n\n/**\n * Like {@link prepareTypedTarget}, for a target whose own `SchemaId`/`TypeId` are already stamped\n * and locked `configurable: false` — e.g. an object decoded from JSON via `setSchema`/`setTypename`\n * (see `objectFromJSON`). Validates and reactifies as usual, then stamps `SchemaId`/`TypeId` on\n * nested records/arrays only, leaving the target's own (locked) stamps untouched.\n */\nexport const prepareDecodedTypedTarget = <T>(target: T, schema: Schema.Schema<T>) => {\n validateAndReactifyTarget(target, schema);\n setSchemaProperties(target, schema, undefined, true);\n};\n\n/**\n * Convert every plain array in a subtree to a {@link ReactiveArray}, in place. A plain array has\n * neither the batched mutating methods nor the `[ChangeKeyId]` the read-only gate reads off its\n * prototype, so one left in the tree would mutate silently and notify nobody.\n *\n * An already-proxied child is skipped: it belongs to the graph already and writing through its proxy\n * would run the whole assignment path again.\n */\nconst makeArraysReactive = (target: any) => {\n for (const key in target) {\n const value = target[key];\n if (value == null || typeof value !== 'object' || isProxy(value)) {\n continue;\n }\n if (Array.isArray(value) && !(value instanceof ReactiveArray)) {\n target[key] = ReactiveArray.from(value);\n }\n makeArraysReactive(target[key]);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport type * as Schema from 'effect/Schema';\n\nimport { EntityId } from '@dxos/keys';\n\nimport { getTypeAnnotation } from '../../Annotation/annotations.ts';\nimport { type AnyProperties, KindId, ParentId, SchemaId, SchemaKindId, StaticTypeSchemaSlot } from '../types/index.ts';\nimport { type EntityMeta, EntityMetaSchema } from '../types/meta.ts';\nimport { MetaId } from '../types/model-symbols.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { attachTypedJsonSerializer } from './json-serializer.ts';\nimport { createProxy, getProxyTarget, isProxy, isValidProxyTarget } from './proxy-utils.ts';\nimport {\n type PrepareTargetOptions,\n TypedReactiveHandler,\n TypeSource,\n prepareDecodedTypedTarget,\n prepareTypedTarget,\n setMetaOwner,\n} from './typed-handler.ts';\n\n/**\n *\n */\n// TODO(burdon): Make internal\n// Omits the brand slots — those get stamped on the instance by the entity\n// handler (KindId via setKind, SchemaKindId derived in the proxy `get` trap\n// from kind + jsonSchema.entityKind, StaticTypeSchemaSlot lazily via the\n// proxy), not supplied by the caller.\nexport type MakeObjectProps<T extends AnyProperties> = Omit<T, 'id' | KindId | SchemaKindId | StaticTypeSchemaSlot>;\n\n/**\n * Creates a reactive object from a plain Javascript object.\n * Requires a TS-effect schema.\n *\n * Callers that have a `Type.Type` entity (not a raw schema) must unwrap it\n * themselves — `Obj.make` / `Relation.make` do this via `Type.getSchema(...)`\n * and pass the entity through as `typeSource` so the instance carries a\n * back-reference for `Obj.getType` and resolves the live source schema\n * uniformly via the entity's `[StaticTypeSchemaSlot]`.\n */\n// TODO(burdon): Make internal\n// TODO(dmaretskyi): Deep mutability.\n// TODO(dmaretskyi): Invert generics (generic over schema) to have better error messages.\n// TODO(dmaretskyi): Could mutate original object making it unusable.\nexport const makeObject = <T extends AnyProperties>(\n // Matches what this forwards to. Effect 4's `Schema.Schema<T>` pins only `Type` and leaves the\n // service channels open, so narrowing to `Codec<T, any, never>` here rejected ordinary callers\n // and needed a cast to get past.\n schema: Schema.Schema<T>,\n obj: NoInfer<MakeObjectProps<T>>,\n meta?: Partial<EntityMeta>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n): T => {\n // Use Object.assign to copy symbol properties (like ParentId) that spread operator doesn't copy.\n return createReactiveObject<T>(Object.assign({}, obj) as T, meta, schema, typeSource, options);\n};\n\nconst createReactiveObject = <T extends AnyProperties>(\n obj: T,\n meta?: Partial<EntityMeta>,\n schema?: Schema.Schema<T>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n): T => {\n if (!isValidProxyTarget(obj)) {\n throw new Error('Value cannot be made into a reactive object.');\n }\n\n if (!schema) {\n throw new Error('Schema is required for reactive objects. Use Atom for untyped reactive state.');\n }\n\n // Extract parent from props (can be set via [Obj.Parent]).\n const parent = (obj as any)[ParentId];\n if (parent !== undefined) {\n delete (obj as any)[ParentId];\n }\n\n const annotation = getTypeAnnotation(schema);\n if (annotation) {\n setIdOnTarget(obj);\n defineHiddenProperty(obj, KindId, annotation.kind);\n }\n initMeta(obj, meta, options);\n if (parent !== undefined) {\n defineHiddenProperty(obj, ParentId, parent);\n }\n prepareTypedTarget(obj, schema, typeSource, options);\n attachTypedJsonSerializer(obj);\n const proxy = createProxy<T>(obj, TypedReactiveHandler.instance);\n\n // Set meta's owner to the main object so meta mutations respect the parent's change context.\n // For non-database objects using TypedReactiveHandler, this links the meta to the main object's\n // change context. For database objects, meta is handled by EchoReactiveHandler.getMeta().\n const metaProxy = (obj as any)[MetaId];\n if (metaProxy) {\n const metaTarget = getProxyTarget(metaProxy);\n if (metaTarget) {\n setMetaOwner(metaTarget, obj);\n }\n }\n\n return proxy;\n};\n\n/**\n * Rewrap an object decoded from JSON (via `objectFromJSON`) into a live reactive proxy, so that\n * `Obj.update` synchronously mutates it and `Obj.subscribe`/atoms fire — the same contract as\n * automerge-backed objects. Unlike {@link makeObject}, the target already carries `SchemaId`/\n * `TypeId` stamped by `setSchema`/`setTypename` (both `configurable: false`), so this does not\n * re-derive or re-stamp them — it only validates against the schema, reactifies nested arrays,\n * rewraps `[MetaId]` as a live nested proxy, and wraps the whole object in a proxy.\n *\n * Objects whose type could not be resolved at decode time (no `SchemaId`) are returned unchanged —\n * they remain plain snapshots and `Obj.update` on them stays a no-op, since there is no schema to\n * validate mutations against.\n */\nexport const makeDecodedEntityLive = <T extends AnyProperties>(obj: T): T => {\n const schema = (obj as any)[SchemaId] as Schema.Codec<T, any> | undefined;\n if (!schema) {\n return obj;\n }\n\n prepareDecodedTypedTarget(obj, schema);\n\n const meta = (obj as any)[MetaId];\n if (meta != null && typeof meta === 'object' && !isProxy(meta)) {\n prepareTypedTarget(meta, EntityMetaSchema);\n const metaProxy = createProxy(meta, TypedReactiveHandler.instance);\n defineHiddenProperty(obj, MetaId, metaProxy);\n const metaTarget = getProxyTarget(metaProxy);\n setMetaOwner(metaTarget, obj);\n }\n\n attachTypedJsonSerializer(obj);\n return createProxy(obj, TypedReactiveHandler.instance);\n};\n\n/**\n * Set ID on ECHO object targets during creation.\n * Used for objects with schema and the ones explicitly marked as Expando.\n */\nconst setIdOnTarget = (target: any) => {\n // invariant(!('id' in target), 'Object already has an `id` field, which is reserved.');\n if ('id' in target && target.id !== undefined && target.id !== null) {\n if (!EntityId.isValid(target.id)) {\n throw new Error('Invalid object id format.');\n }\n } else {\n target.id = EntityId.random();\n }\n};\n\n/**\n * Set metadata on object.\n */\n// TODO(dmaretskyi): Move to echo-schema.\nconst initMeta = <T>(obj: T, meta?: Partial<EntityMeta>, options?: PrepareTargetOptions) => {\n // Backfill required fields so callers may pass a partial meta, or one whose `keys`/`tags`/\n // `annotations` are explicitly `undefined` (coalesce, don't let a spread reintroduce undefined).\n const fullMeta: EntityMeta = {\n ...meta,\n keys: meta?.keys ?? [],\n tags: meta?.tags ?? [],\n annotations: meta?.annotations ?? {},\n };\n prepareTypedTarget(fullMeta, EntityMetaSchema, undefined, options);\n defineHiddenProperty(obj, MetaId, createProxy(fullMeta, TypedReactiveHandler.instance as any));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { DXN, EntityId } from '@dxos/keys';\nimport { type ToMutable } from '@dxos/util';\n\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { defineHiddenProperty } from '../common/proxy/define-hidden-property.ts';\nimport { makeObject } from '../common/proxy/make-object.ts';\nimport { getProxyTarget } from '../common/proxy/proxy-utils.ts';\nimport { type AnyProperties } from '../common/types/base.ts';\nimport {\n type AnyEntity,\n EntityKind,\n InstancePhantomId,\n KindId,\n SchemaKindId,\n StaticTypeSchemaSlot,\n} from '../common/types/index.ts';\nimport { type EntityMeta } from '../common/types/meta.ts';\nimport { JsonSchemaType } from '../JsonSchema/json-schema-type.ts';\n\n// TODO(burdon): Define Schema type for `typename` and use consistently for all DXN-like properties.\n\n// type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];\nexport type EchoTypeSchemaProps<T, ExtraFields = {}> = Types.Simplify<AnyEntity & ToMutable<T> & ExtraFields>;\n\n/**\n * Options accepted by every `Type.makeObject` / `Type.makeRelation` / type-kind\n * factory. Defaults are derived from `(typename, version)` so callers normally\n * pass nothing.\n */\nexport type EchoTypeOptions = {\n /**\n * Override the entity id stamped on the in-memory `Type.Type` value.\n *\n * Defaults to `EntityId.deterministic(typename, version)` — stable across processes\n * and workerd-safe (no `crypto.getRandomValues()` at module-evaluation time).\n * Pass an explicit id (typically `EntityId.random()`) to opt out of the\n * deterministic default.\n */\n id?: EntityId;\n};\n\n/**\n * In-memory `Type.Type` entity shape produced by `Type.makeObject(dxn)` /\n * `Type.makeRelation({...})`. A live reactive `TypeSchema` instance —\n * identical to a persisted `Type.Type` except for database attachment.\n *\n * NOT a `Schema.Schema`. The underlying Effect Schema is cached on the hidden\n * `StaticTypeSchemaSlot` slot — retrieve it via `Type.getSchema(...)`.\n */\n// TODO(burdon): Rename EchoEntitySchema.\nexport interface EchoTypeSchema<\n Self extends Schema.Top,\n ExtraFields = {},\n K extends EntityKind = EntityKind,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n /**\n * Entity-kind brand. Type entities are their own kind (`Type`) regardless of\n * the kind of instance they describe — `[SchemaKindId]` carries the latter.\n * This lets predicates like `Obj.isObject` / `Relation.isRelation` cleanly\n * reject type entities without also having to inspect `[SchemaKindId]`.\n */\n readonly [KindId]: EntityKind.Type;\n\n /** Schema-kind brand indicating what kind of instance this type describes. */\n readonly [SchemaKindId]: K;\n\n /**\n * Entity id. Always present — stamped at construction — but NOT the type's\n * identity while in-memory: an unattached type resolves its URI to the typename\n * DXN, switching to `echo:///<id>` only once attached to a database (see\n * `getTypeURIFromSpecifier`, which discriminates by database attachment).\n */\n readonly id: EntityId;\n\n /** Source Effect Schema (kept on a hidden slot for `Type.getSchema`). */\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n // NOTE: `typename` / `version` are intentionally NOT fields. They live in\n // `EntityMeta` (`key` / `version`); read via `Type.getTypename(self)` /\n // `Type.getVersion(self)`.\n readonly jsonSchema: JsonSchemaType;\n\n /** Struct fields for introspection. */\n readonly fields: Fields;\n\n /** Phantom — instance type produced by `Obj.make(self, ...)`. */\n readonly _instance?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields>;\n\n /**\n * Phantom slot mirroring `Type<A>` so internal helpers (`makeObject`,\n * `createObject`, `Ref.make`) infer the instance type uniformly whether\n * the caller passes an `EchoTypeSchema` or a top-level `Type.Type` entity.\n *\n * Includes the instance-kind brand (`[KindId]`) so the phantom is assignable\n * to the matching public-side interface in `Type.ts` (`Type.Obj` /\n * `Type.Relation` / `Type.Type`). Each kind projects identity: instances of\n * an object-kind schema are object-kind entities, type-kind schemas produce\n * type-kind (persisted Type.Type) entities — the latter additionally carry\n * the `[SchemaKindId]` / `[StaticTypeSchemaSlot]` brands the echo-handler\n * proxy exposes on persisted Type entities.\n */\n readonly [InstancePhantomId]?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields> & {\n readonly [KindId]: K;\n } & (K extends EntityKind.Type\n ? {\n readonly [SchemaKindId]: EntityKind.Type;\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n }\n : {});\n}\n\n/**\n * Identity (typename + version) of the type meta-schema — the `Type.Type` that\n * every ECHO type entity is itself an instance of. Shared by the materialisation\n * vehicle ({@link persistentEntitySchema}) and `TypeSchema` so the two cannot\n * drift on identity.\n */\nexport const TypeMetaSchemaDXN = DXN.make('org.dxos.type.schema', '0.1.0');\n\n/**\n * Effect Schema that every `Type.Type` entity is an instance of: the meta-schema\n * struct `{ name?, jsonSchema, id }` branded as a type-kind ECHO entity. This is\n * the materialisation vehicle for `makeObject` below — the canonical user-facing\n * entity is `Type/type-schema.ts`'s `TypeSchema`, which carries the same shape\n * plus UI annotations.\n *\n * Kept self-contained (no import of `TypeSchema`) to avoid a bootstrap cycle:\n * `TypeSchema` is itself produced via `makeEchoTypeSchema`, so this builder must\n * not depend on it. `jsonSchema` is declared optional here (only on the\n * materialisation vehicle — the canonical `TypeSchema` keeps it required) so the\n * construction-time `Schema.asserts` does not force the field before it is\n * attached; it is populated immediately after via a lazy accessor (see\n * `makeEchoTypeSchema`).\n */\n// TODO(wittjosiah): Reconcile with `TypeSchema` (`Type/type-schema.ts`).\n// Both describe the same `org.dxos.type.schema` shape.\nconst persistentEntitySchema: Schema.Codec<AnyProperties, any> = (() => {\n const typename = DXN.getName(TypeMetaSchemaDXN);\n const version = DXN.getVersion(TypeMetaSchemaDXN)!;\n const struct = Schema.Struct({\n name: Schema.optional(Schema.String),\n jsonSchema: JsonSchemaType.pipe(Schema.optional),\n id: EntityId,\n });\n const ast = SchemaAST.annotate(struct.ast, {\n [TypeAnnotationId]: { kind: EntityKind.Type, typename, version } satisfies TypeAnnotation,\n ...makeTypeJsonSchemaAnnotation({ kind: EntityKind.Type, typename, version }),\n });\n return Schema.make<Schema.Codec<AnyProperties, any>>(ast);\n})();\n\n/**\n * @internal\n *\n * Build an in-memory `Type.Type` entity (the value returned by `Type.makeObject`\n * / `Type.makeRelation`). The result is a LIVE reactive `TypeSchema`\n * instance — identical in every respect to a persisted `Type.Type` except that\n * it is not yet attached to a database. It is mutable via `Type.update`, can be\n * passed to `db.add(...)` (which keeps the same proxy and swaps the handler),\n * and round-trips through `jsonSchema`.\n *\n * The source Effect Schema describing the user's type is cached on\n * `[StaticTypeSchemaSlot]` so `Type.getSchema(...)` returns it without a\n * jsonSchema round-trip; the cache is invalidated by the proxy set-trap when\n * `jsonSchema` is mutated (see `typed-handler.ts`).\n */\nexport const makeEchoTypeSchema = <\n Self extends Schema.Top,\n K extends EntityKind = EntityKind,\n // TODO(wittjosiah): Can this be inferred from the schema?\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n>(\n fields: Fields,\n ast: SchemaAST.AST,\n typename: string,\n version: string,\n kind: K,\n computeJsonSchema: () => JsonSchemaType,\n explicitId?: EntityId,\n): EchoTypeSchema<Self, {}, K, Fields> => {\n // Source Effect Schema describing the user's type — cached for `Type.getSchema`.\n // v4's `Schema.make` takes the whole schema type as one parameter, and a schema exposes its\n // channels as properties rather than through `Schema.Schema.*` helpers.\n const sourceSchema =\n Schema.make<\n Schema.Codec<\n EchoTypeSchemaProps<Self['Type']>,\n EchoTypeSchemaProps<Self['Encoded']>,\n Self['DecodingServices'],\n Self['EncodingServices']\n >\n >(ast);\n\n // `typename` / `version` route through `EntityMeta` (`key` / `version`) — the\n // canonical registry-provenance pair — not data fields. `keys` is empty for\n // in-memory declarations until persisted.\n const meta: Partial<EntityMeta> = { keys: [], key: typename, version };\n\n // Default to a deterministic id derived from `(typename, version)` so that\n // constructing a `Type.Type` entity never reaches `crypto.getRandomValues()`.\n // Cloudflare workerd forbids RNG calls in global scope, and the ~hundreds of\n // `Type.makeObject(...)` call sites across the monorepo execute at module top.\n // `setIdOnTarget` (see `proxy/make-object.ts`) short-circuits on a pre-supplied\n // valid id, so this also bypasses the `EntityId.random()` path inside `makeObject`.\n // Callers can override via `Type.makeObject(dxn, { id })` when they want a fresh\n // random id (e.g. inside a request handler where workerd does allow RNG).\n const id = explicitId ?? EntityId.deterministic(typename, version);\n\n // Materialise as a live reactive meta-schema instance. `jsonSchema` is attached\n // below as a getter (not passed here as data) for two reasons; see that accessor.\n const entity = makeObject(persistentEntitySchema, { id } as any, meta);\n\n const target = getProxyTarget(entity)!;\n // `jsonSchema` is always available, but computed once on first read rather than at\n // construction: serializing the AST walks `Schema.suspend(...)` thunks, and for a\n // self-referential type (`Schema.suspend(() => Self)`) that thunk hits `Self`'s TDZ\n // while we're still inside its `const` initializer. A getter also lets reads return\n // the raw object instead of a child reactive proxy.\n let memoizedJsonSchema: JsonSchemaType | undefined;\n Object.defineProperty(target, 'jsonSchema', {\n configurable: true,\n enumerable: true,\n get() {\n return (memoizedJsonSchema ??= computeJsonSchema());\n },\n set(value: JsonSchemaType) {\n memoizedJsonSchema = value;\n },\n });\n // Cache the source Effect Schema (read by `Type.getSchema` via the proxy's\n // `[StaticTypeSchemaSlot]` get-trap; invalidated on `jsonSchema` mutation).\n defineHiddenProperty(target, StaticTypeSchemaSlot, sourceSchema);\n // Schema-kind brand: what kind of instance this type describes. There is no\n // database handler to derive it for in-memory entities, so stamp it directly.\n defineHiddenProperty(target, SchemaKindId, kind);\n // Struct fields for introspection. A getter (not a data property) so reads return\n // the raw fields object rather than a child reactive proxy.\n Object.defineProperty(target, 'fields', { configurable: true, enumerable: false, get: () => fields });\n\n return entity as unknown as EchoTypeSchema<Self, {}, K, Fields>;\n};\n\nexport { isEntity } from './guard.ts';\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Types from 'effect/Types';\n\nimport { JsonSchemaFields, type JsonSchemaType } from './json-schema-type.ts';\n\n/**\n * Normalize schema to to draft-07 format.\n * Note: the input type does not necessarily match the {@link JsonSchemaType} type.\n */\nexport const normalizeSchema = (schema: JsonSchemaType): JsonSchemaType => {\n const copy = structuredClone(schema) as Types.DeepMutable<JsonSchemaType>;\n go(copy);\n return copy;\n};\n\nconst go = (schema: Types.DeepMutable<JsonSchemaType>) => {\n if (typeof schema !== 'object' || schema === null) {\n return;\n }\n\n if ((schema as any).exclusiveMaximum === true) {\n schema.exclusiveMaximum = schema.maximum;\n delete (schema as any).exclusiveMaximum;\n } else if ((schema as any).exclusiveMaximum === false) {\n delete (schema as any).exclusiveMaximum;\n }\n\n if ((schema as any).exclusiveMinimum === true) {\n schema.exclusiveMinimum = schema.minimum;\n delete (schema as any).exclusiveMinimum;\n } else if ((schema as any).exclusiveMinimum === false) {\n delete (schema as any).exclusiveMinimum;\n }\n\n // Delete all properties that are not in the JsonSchemaFields.\n for (const key of Object.keys(schema)) {\n if (!JsonSchemaFields.includes(key)) {\n delete (schema as any)[key];\n }\n }\n\n // Recursively normalize the schema.\n // Recursively normalize the schema.\n if (schema.properties) {\n goOnRecord(schema.properties);\n }\n if (schema.patternProperties) {\n goOnRecord(schema.patternProperties);\n }\n if (schema.propertyNames) {\n go(schema.propertyNames);\n }\n if (schema.definitions) {\n goOnRecord(schema.definitions);\n }\n if (schema.items) {\n maybeGoOnArray(schema.items);\n }\n if (schema.additionalItems) {\n maybeGoOnArray(schema.additionalItems);\n }\n if (schema.contains) {\n go(schema.contains);\n }\n if (schema.if) {\n go(schema.if);\n }\n if (schema.then) {\n go(schema.then);\n }\n if (schema.else) {\n go(schema.else);\n }\n if (schema.allOf) {\n maybeGoOnArray(schema.allOf);\n }\n if (schema.anyOf) {\n maybeGoOnArray(schema.anyOf);\n }\n if (schema.oneOf) {\n maybeGoOnArray(schema.oneOf);\n }\n if (schema.not) {\n go(schema.not);\n }\n if (schema.$defs) {\n goOnRecord(schema.$defs);\n }\n if (schema.reference) {\n go(schema.reference.schema);\n }\n};\n\nconst maybeGoOnArray = (value: any) => {\n if (Array.isArray(value)) {\n for (const item of value) {\n go(item);\n }\n } else if (typeof value === 'object' && value !== null) {\n go(value);\n }\n};\n\nconst goOnRecord = (record: Record<string, any>) => {\n for (const key of Object.keys(record)) {\n go(record[key]);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, type EntityId } from '@dxos/keys';\n\nimport type * as Type from '../../Type.ts';\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { EntityKind } from '../common/types/index.ts';\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeOptions, type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Object schema type with kind marker.\n */\nexport type EchoObjectSchema<\n Self extends Schema.Top,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, {}, EntityKind.Object, Fields>;\n\n/**\n * Schema for Obj entity types.\n * Pipeable function to add ECHO object annotations to a schema.\n */\nexport const EchoObjectSchema: {\n (\n dxn: DXN.DXN,\n options?: EchoTypeOptions,\n ): <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ) => EchoObjectSchema<Self, Fields>;\n} = (dxn, options) => {\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type.makeObject requires a versioned DXN: ${dxn}`);\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoObjectSchema<Self, Fields> => {\n // Annotation ids are string keys in Effect 4; this guards against a bundling mishap that\n // leaves the id undefined, which would silently drop the annotation.\n invariant(typeof TypeAnnotationId === 'string', 'Sanity.');\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n // Struct schemas expose `.fields`; retained for the schema's public field map.\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how `Expando` and other record-shaped types are\n // declared. (`mapFields` is unavailable here -- it is a `Struct` method and `self` is generic.)\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n // TODO(dmaretskyi): `extend` kills the annotations.\n ...self.ast.annotations,\n [TypeAnnotationId]: { kind: EntityKind.Object, typename, version } satisfies TypeAnnotation,\n // TODO(dmaretskyi): TypeIdentifierAnnotationId?\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Object,\n typename,\n version,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Object, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Object,\n () => toJsonSchema(Schema.make(ast)),\n options?.id,\n );\n };\n};\n\nexport const makeObjectType = <Self, _Schema extends Schema.Top>(\n dxn: DXN.DXN,\n schema: _Schema,\n options?: { id?: EntityId },\n): Type.ObjClass<Self, Schema.Schema.Type<_Schema>, {}> => {\n const type = EchoObjectSchema(dxn, options)(schema);\n const constructor = function ObjectType() {};\n Object.setPrototypeOf(constructor, type);\n // Boundary cast: constructor/prototype wiring cannot be expressed in TypeScript's type system.\n return constructor as unknown as Type.ObjClass<Self, Schema.Schema.Type<_Schema>, {}>;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, type EntityId } from '@dxos/keys';\n\n// Type-only imports (erased at runtime — no import cycle); `internal` may depend\n// on the top-level `Obj` / `Type` API at the type level only.\nimport type * as Obj from '../../Obj.ts';\nimport type * as Type from '../../Type.ts';\nimport {\n type TypeAnnotation,\n TypeAnnotationId,\n getEntityKind,\n getSchemaTypename,\n getTypeIdentifierAnnotation,\n} from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n EntityKind,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n type UnknownTypeSchema,\n getStaticTypeSchema,\n} from '../common/types/index.ts';\n\nexport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n};\n\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Source and target props on relations.\n */\n// TODO(burdon): any?\nexport type RelationSourceTargetRefs<Source = any, Target = any> = {\n /**\n * Source ECHO live object.\n */\n [RelationSourceId]: Source;\n\n /**\n * Target ECHO live object.\n */\n [RelationTargetId]: Target;\n};\n\nexport type RelationSource<R> = R extends RelationSourceTargetRefs<infer Source, infer _Target> ? Source : never;\nexport type RelationTarget<R> = R extends RelationSourceTargetRefs<infer _Source, infer Target> ? Target : never;\n\n/**\n * Accepted relation endpoint: an object-kind `Type.Type` entity (slot-backed)\n * or the branded `Obj.Unknown` schema. Source/target are constrained to these\n * — relations only connect object-kind entities.\n */\nexport type RelationEndpoint = Type.AnyObj | UnknownTypeSchema<any, EntityKind.Object>;\n\n/**\n * Resolves a relation endpoint to the instance type it describes — the source /\n * target instance recorded on the relation's `RelationSourceTargetRefs`.\n */\nexport type RelationEndpointInstance<S> =\n S extends UnknownTypeSchema<infer A, any> ? A : S extends Type.AnyObj ? Type.InstanceType<S> : unknown;\n\nexport type EchoRelationSchemaOptions<TSource extends RelationEndpoint, TTarget extends RelationEndpoint> = {\n dxn: DXN.DXN;\n source: TSource;\n target: TTarget;\n /**\n * Override the entity id stamped on the in-memory `Type.Type` value.\n *\n * Defaults to `EntityId.deterministic(typename, version)` — stable across processes\n * and workerd-safe (no `crypto.getRandomValues()` at module-evaluation time).\n */\n id?: EntityId;\n};\n\n/**\n * Relation schema type with kind marker. `SourceInstance` / `TargetInstance`\n * are the resolved endpoint instance types (see {@link RelationEndpointInstance}).\n */\nexport type EchoRelationSchema<\n Self extends Schema.Top,\n SourceInstance extends Obj.Unknown,\n TargetInstance extends Obj.Unknown,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, RelationSourceTargetRefs<SourceInstance, TargetInstance>, EntityKind.Relation, Fields>;\n\n/**\n * Schema for Relation entity types.\n */\nexport const EchoRelationSchema = <Source extends RelationEndpoint, Target extends RelationEndpoint>({\n dxn,\n source,\n target,\n id: explicitId,\n}: EchoRelationSchemaOptions<Source, Target>) => {\n // `source` / `target` are `Type.Type` entities (slot-backed) or the branded\n // `Obj.Unknown` schema (used directly); resolve each to its Effect Schema for\n // the schema-side machinery (DXN ref + entity-kind checks).\n const sourceSchema = source != null ? (getStaticTypeSchema(source) ?? source) : source;\n const targetSchema = target != null ? (getStaticTypeSchema(target) ?? target) : target;\n assertArgument(Schema.isSchema(sourceSchema), 'source');\n assertArgument(Schema.isSchema(targetSchema), 'target');\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type.makeRelation requires a versioned DXN: ${dxn}`);\n const sourceDXN = getDXNForRelationSchemaRef(sourceSchema);\n const targetDXN = getDXNForRelationSchemaRef(targetSchema);\n if (getEntityKind(sourceSchema) !== EntityKind.Object) {\n raise(new Error('Source schema must be an echo object schema.'));\n }\n if (getEntityKind(targetSchema) !== EntityKind.Object) {\n raise(new Error('Target schema must be an echo object schema.'));\n }\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoRelationSchema<Self, RelationEndpointInstance<Source>, RelationEndpointInstance<Target>, Fields> => {\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n // Struct schemas expose `.fields`; retained for the schema's public field map.\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how `Expando` and other record-shaped types are\n // declared. (`mapFields` is unavailable here -- it is a `Struct` method and `self` is generic.)\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n // TODO(dmaretskyi): `extend` kills the annotations.\n ...self.ast.annotations,\n [TypeAnnotationId]: {\n kind: EntityKind.Relation,\n typename,\n version,\n sourceSchema: sourceDXN,\n targetSchema: targetDXN,\n } satisfies TypeAnnotation,\n // TODO(dmaretskyi): TypeIdentifierAnnotationId?\n\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Relation,\n typename,\n version,\n relationSource: sourceDXN,\n relationTarget: targetDXN,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Relation, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Relation,\n () => toJsonSchema(Schema.make(ast)),\n explicitId,\n );\n };\n};\n\nexport const getDXNForRelationSchemaRef = (schema: Schema.Top): DXN.DXN => {\n assertArgument(Schema.isSchema(schema), 'schema');\n const identifier = getTypeIdentifierAnnotation(schema);\n if (identifier) {\n return DXN.tryMake(identifier) ?? raise(new Error(`Invalid schema identifier: ${identifier}`));\n }\n\n const typename = getSchemaTypename(schema);\n if (!typename) {\n throw new Error('Schema must have a typename');\n }\n\n return DXN.make(typename);\n};\n\nexport const makeRelationType = (options: {\n dxn: DXN.DXN;\n source: RelationEndpoint;\n target: RelationEndpoint;\n schema: Schema.Top;\n id?: EntityId;\n}): Type.RelationClass<unknown, unknown, unknown, unknown, {}> => {\n const type = EchoRelationSchema({\n dxn: options.dxn,\n source: options.source,\n target: options.target,\n id: options.id,\n })(options.schema);\n const constructor = function RelationType() {};\n Object.setPrototypeOf(constructor, type);\n // Boundary cast: constructor/prototype wiring cannot be expressed in TypeScript's type system.\n return constructor as unknown as Type.RelationClass<unknown, unknown, unknown, unknown, {}>;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\nimport { DXN } from '@dxos/keys';\n\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { EntityKind } from '../common/types/index.ts';\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeOptions, type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Type-kind schema marker — produced by {@link EchoTypeKindSchema}.\n *\n * Distinguishes meta-schemas (entities of `EntityKind.Type`, such as the\n * built-in `Type.Type` TypeSchema) from object and relation types.\n */\nexport type EchoTypeKindSchema<\n Self extends Schema.Top,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, {}, EntityKind.Type, Fields>;\n\n/**\n * Pipeable that brands a schema as a type-kind ECHO entity. Mirrors\n * {@link EchoObjectSchema} / {@link EchoRelationSchema}, but stamps the\n * resulting entity with `[SchemaKindId]: EntityKind.Type` and a matching\n * `TypeAnnotation.kind = 'type'` so meta-schemas surface uniformly through\n * `Type.isTypeKind`, `Filter.type`, etc.\n */\nexport const EchoTypeKindSchema: {\n (\n dxn: DXN.DXN,\n options?: EchoTypeOptions,\n ): <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ) => EchoTypeKindSchema<Self, Fields>;\n} = (dxn, options) => {\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type-kind schemas require a versioned DXN: ${dxn}`);\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoTypeKindSchema<Self, Fields> => {\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how record-shaped types are declared.\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n ...self.ast.annotations,\n [TypeAnnotationId]: { kind: EntityKind.Type, typename, version } satisfies TypeAnnotation,\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Type,\n typename,\n version,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Type, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Type,\n () => toJsonSchema(Schema.make(ast)),\n options?.id,\n );\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { assertArgument } from '@dxos/invariant';\n\nimport { type AnyEntity, VersionTypeId } from '../common/types/index.ts';\nimport { ObjectVersionId } from './model.ts';\n\n/**\n * Represent entity version.\n * May be backed by Automerge.\n * Entities with no history are not versioned.\n * Named EntityVersion to avoid conflict with types/version.ts.\n */\nexport interface EntityVersion {\n [VersionTypeId]: {};\n\n /**\n * Whether the entity is versioned.\n */\n versioned: boolean;\n\n /**\n * Automerge heads.\n */\n automergeHeads?: string[];\n}\n\nconst unversioned: EntityVersion = {\n [VersionTypeId]: {},\n versioned: false,\n};\n\n/**\n * Checks that `obj` is a version object.\n */\nexport const isVersion = (entity: unknown): entity is EntityVersion => {\n return entity != null && typeof entity === 'object' && VersionTypeId in entity;\n};\n\n/**\n * Returns the version of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const version = (entity: AnyEntity): EntityVersion => {\n const ver = (entity as any)[ObjectVersionId];\n if (ver === undefined) {\n return unversioned;\n }\n return ver;\n};\n\n/**\n * Checks that `version` is a valid version object.\n */\nexport const versionValid = (ver: EntityVersion): boolean => {\n assertArgument(isVersion(ver), 'version', 'Invalid version object');\n return !!ver.versioned;\n};\n\nexport type VersionCompareResult = 'unversioned' | 'equal' | 'different';\n\n/**\n * Compares two versions.\n * @param version1\n * @param version2\n * @returns 'unversioned' if either entity is unversioned, 'equal' if the versions are equal, 'different' if the versions are different.\n */\nexport const compareVersions = (version1: EntityVersion, version2: EntityVersion): VersionCompareResult => {\n assertArgument(isVersion(version1), 'version1', 'Invalid version object');\n assertArgument(isVersion(version2), 'version2', 'Invalid version object');\n\n if (!versionValid(version1) || !versionValid(version2)) {\n return 'unversioned';\n }\n\n if (version1.automergeHeads?.length !== version2.automergeHeads?.length) {\n return 'different';\n }\n if (version1.automergeHeads?.some((head) => !version2.automergeHeads?.includes(head))) {\n return 'different';\n }\n\n return 'equal';\n};\n\nexport const encodeVersion = (ver: EntityVersion): string => {\n return JSON.stringify(ver);\n};\n\nexport const decodeVersion = (ver: string): EntityVersion => {\n const parsed = JSON.parse(ver);\n parsed[VersionTypeId] = {};\n return parsed;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type EntityId } from '@dxos/keys';\n\n/**\n * Follow `system.mergedInto` from `start` to the entity that finally survives.\n *\n * This is the one piece of the convergence-key merge the client needs: resolution and the\n * transitive-deletion walks follow redirects, while the merge itself (winner selection, the\n * field-wise merge function) runs in the worker — see `echo-host`'s merge core.\n *\n * Concurrent merges on different views leave chains rather than a single hop: a peer seeing\n * `{X, Y}` writes `Y -> X` while a peer that also sees a smaller `Z` writes `X -> Z`, so `Y`\n * reaches `Z` only transitively.\n *\n * Termination does not rely on the id-decreasing invariant holding in the data: an edge that\n * fails to decrease the id is treated as the end of the chain, which stops both cycles and\n * forward references without reading unbounded history.\n *\n * @param lookup Returns the `mergedInto` of an entity, or `undefined` if it was not merged away.\n */\nexport const resolveMergeRedirect = (start: EntityId, lookup: (id: EntityId) => EntityId | undefined): EntityId => {\n let current = start;\n for (;;) {\n const next = lookup(current);\n if (next === undefined || next >= current) {\n return current;\n }\n current = next;\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport { type EncodedReference, EntityStructure, isEncodedReference } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId, URI } from '@dxos/keys';\nimport {\n assumeType,\n decodeUint8ArrayFromJson,\n deepMapValues,\n encodeUint8ArrayToJson,\n isEncodedUint8Array,\n visitValues,\n} from '@dxos/util';\n\nimport type * as Database from '../../Database.ts';\nimport type * as Obj from '../../Obj.ts';\nimport { getTypeAnnotation, getTypeURI, setTypename } from '../Annotation/index.ts';\nimport { defineHiddenProperty, typedJsonSerializer } from '../common/proxy/index.ts';\nimport {\n type AnyEntity,\n ATTR_PARENT,\n ATTR_TYPE,\n EntityKind,\n KindId,\n ParentId,\n setSchema,\n setType,\n} from '../common/types/index.ts';\nimport { ATTR_META, EntityMetaSchema, SCALAR_META_FIELDS } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport {\n ATTR_DELETED,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n ObjectDatabaseId,\n ObjectDeletedId,\n type ObjectJSON,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n SelfURIId,\n TypeMetaSchemaDXN,\n assertObjectModel,\n} from '../Entity/index.ts';\nimport { Ref, type RefResolver, refFromEncodedReference, setRefResolver } from '../Ref/index.ts';\n\ntype DeepReplaceRef<T> =\n T extends Ref<any>\n ? EncodedReference\n : T extends object\n ? {\n [K in keyof T]: DeepReplaceRef<T[K]>;\n }\n : T;\n\ntype SerializedObject<T extends { id: string }> = {\n [K in keyof T]: DeepReplaceRef<T[K]>;\n} & ObjectJSON;\n\n/**\n * Converts object to it's JSON representation.\n */\nexport const objectToJSON = <T extends AnyEntity>(obj: T): SerializedObject<T> => {\n const typename = getTypeURI(obj);\n invariant(typename && typeof typename === 'string');\n return typedJsonSerializer.call(obj);\n};\n\n/**\n * Creates an object from it's json representation.\n * Performs schema validation.\n * References and schema will be resolvable if the `refResolver` is provided.\n * The function need to be async to support resolving the schema as well as the relation endpoints.\n *\n * @param jsonData - JSON representation of the object.\n * @param options.refResolver - Resolver for references.\n * @param options.uri - Override object URI.\n * @param options.database - Database to associate with the object.\n */\nexport const objectFromJSON = async (\n jsonData: unknown,\n {\n refResolver,\n uri,\n database,\n parent,\n }: { refResolver?: RefResolver; uri?: URI.URI; database?: Database.Database; parent?: Obj.Unknown } = {},\n): Promise<AnyEntity> => {\n assumeType<ObjectJSON>(jsonData);\n assertArgument(typeof jsonData === 'object' && jsonData !== null, 'jsonData', 'expect object');\n assertArgument(typeof jsonData[ATTR_TYPE] === 'string', 'jsonData[ATTR_TYPE]', 'expected object to have a type');\n assertArgument(typeof jsonData.id === 'string', 'jsonData.id', 'expected object to have an id');\n\n const type = URI.make(jsonData[ATTR_TYPE]);\n const schema = await refResolver?.resolveSchema(type);\n invariant(schema === undefined || Schema.isSchema(schema));\n const decodedInput = restoreUint8Arrays(stripInternalJsonKeys(jsonData));\n\n let obj: any;\n if (schema != null) {\n obj = await Schema.decodeUnknownPromise(schema)(decodedInput);\n if (refResolver) {\n setRefResolverOnData(obj, refResolver);\n }\n } else {\n obj = decodeGeneric(decodedInput, { refResolver });\n }\n\n invariant(EntityId.isValid(obj.id), 'Invalid object id');\n setTypename(obj, type);\n if (schema) {\n setSchema(obj, schema);\n }\n // Resolve and stamp the source type entity, if the resolver provides one.\n // Lets `Obj.getType` / `Entity.getType` return a stable entity for objects\n // loaded via `Obj.fromJSON` (serializer / queue paths).\n if (refResolver?.resolveType) {\n const typeEntity = await refResolver.resolveType(type);\n if (typeEntity != null) {\n setType(obj, typeEntity);\n }\n }\n\n const isRelation =\n typeof jsonData[ATTR_RELATION_SOURCE] === 'string' || typeof jsonData[ATTR_RELATION_TARGET] === 'string';\n if (isRelation) {\n const sourceDxn = jsonData[ATTR_RELATION_SOURCE] ?? raise(new TypeError('Missing relation source'));\n const targetDxn = jsonData[ATTR_RELATION_TARGET] ?? raise(new TypeError('Missing relation target'));\n\n const source = (await refResolver?.resolveLegacy(sourceDxn)) as AnyEntity | undefined;\n const target = (await refResolver?.resolveLegacy(targetDxn)) as AnyEntity | undefined;\n\n defineHiddenProperty(obj, KindId, EntityKind.Relation);\n defineHiddenProperty(obj, RelationSourceDXNId, sourceDxn);\n defineHiddenProperty(obj, RelationTargetDXNId, targetDxn);\n defineHiddenProperty(obj, RelationSourceId, source);\n defineHiddenProperty(obj, RelationTargetId, target);\n } else {\n // Honour the schema's TypeAnnotation kind — persisted `Type.Type` entities\n // (e.g. dynamic schemas loaded from a snapshot import) must brand as\n // `KindId = Type`, not Object, otherwise `Filter.type(Type.Type)` /\n // `Type.isType` skip them and the schema registry never picks them up.\n // Mirrors the kind resolution in `createObject` (the in-memory path).\n const annotationKind = schema != null ? getTypeAnnotation(schema)?.kind : undefined;\n defineHiddenProperty(obj, KindId, annotationKind === EntityKind.Type ? EntityKind.Type : EntityKind.Object);\n }\n\n if (typeof jsonData[ATTR_META] === 'object') {\n const meta = await Schema.decodeUnknownPromise(EntityMetaSchema)(normalizeMeta(jsonData[ATTR_META]));\n invariant(Array.isArray(meta.keys));\n defineHiddenProperty(obj, MetaId, meta);\n } else {\n defineHiddenProperty(obj, MetaId, {\n keys: [],\n tags: [],\n annotations: {},\n });\n }\n\n if (jsonData[ATTR_PARENT]) {\n const parentDxn = jsonData[ATTR_PARENT];\n const resolvedParent = (await refResolver?.resolveLegacy(parentDxn)) as Obj.Unknown | undefined;\n defineHiddenProperty(obj, ParentId, resolvedParent);\n } else if (parent) {\n defineHiddenProperty(obj, ParentId, parent);\n }\n\n if (uri) {\n defineHiddenProperty(obj, SelfURIId, uri);\n }\n\n if (database) {\n defineHiddenProperty(obj, ObjectDatabaseId, database);\n }\n\n // Carry the deletion marker so a tombstone snapshot (e.g. a feed item removed via `Feed.remove`)\n // hydrates with `Obj.isDeleted === true` rather than as a live object.\n defineHiddenProperty(obj, ObjectDeletedId, jsonData[ATTR_DELETED] === true);\n\n assertObjectModel(obj);\n invariant((obj as any)[ATTR_TYPE] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_META] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_DELETED] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_SELF_URI] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_SELF_URI_LEGACY] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_RELATION_SOURCE] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_RELATION_TARGET] === undefined, 'Invalid object model');\n\n return obj;\n};\n\n/**\n * Backfills required meta fields and upgrades legacy `tags` (bare URI strings) to encoded references\n * so serialized data produced before the tags-as-refs migration still decodes.\n */\nconst normalizeMeta = (meta: any): any => {\n const tags = Array.isArray(meta?.tags)\n ? meta.tags.map((tag: unknown) => (typeof tag === 'string' ? { '/': URI.make(tag) } : tag))\n : [];\n // Coalesce required fields so explicit `undefined` in legacy input doesn't override the defaults.\n return {\n ...meta,\n keys: Array.isArray(meta?.keys) ? meta.keys : [],\n tags,\n annotations: meta?.annotations ?? {},\n };\n};\n\nconst decodeGeneric = (jsonData: unknown, options: { refResolver?: RefResolver }) => {\n const props = stripInternalJsonKeys(jsonData);\n\n return deepMapValues(props, (value, visitor) => {\n if (isEncodedReference(value)) {\n return refFromEncodedReference(value, options.refResolver);\n }\n if (isEncodedUint8Array(value)) {\n return decodeUint8ArrayFromJson(value);\n }\n\n return visitor(value);\n });\n};\n\n/**\n * Recursively replaces encoded `Uint8Array` JSON markers with actual `Uint8Array` instances.\n * Runs before schema decoding so `Schema.Uint8Array` sees real bytes.\n */\nconst restoreUint8Arrays = (data: unknown): any =>\n deepMapValues(data, (value, recurse) => {\n if (isEncodedUint8Array(value)) {\n return decodeUint8ArrayFromJson(value);\n }\n return recurse(value);\n });\n\nconst stripInternalJsonKeys = (jsonData: unknown) => {\n const {\n [ATTR_TYPE]: _type,\n [ATTR_META]: _meta,\n [ATTR_DELETED]: _deleted,\n [ATTR_SELF_URI]: _selfUri,\n [ATTR_SELF_URI_LEGACY]: _legacySelfUri,\n [ATTR_RELATION_SOURCE]: _relationSource,\n [ATTR_RELATION_TARGET]: _relationTarget,\n ...props\n } = jsonData as any;\n\n return props;\n};\n\nexport const setRefResolverOnData = (obj: AnyEntity, refResolver: RefResolver) => {\n const visitor = (value: unknown) => {\n if (Ref.isRef(value)) {\n setRefResolver(value, refResolver);\n } else {\n visitValues(value, visitor);\n }\n };\n\n visitor(obj);\n};\n\n/**\n * Convert EntityStructure to JSON data for indexing.\n * Different from {@link objectToJSON} as it takes the internal {@link EntityStructure} representation directly\n */\nexport const objectStructureToJson = (objectId: EntityId, structure: EntityStructure): Obj.JSON => {\n const typeRef = EntityStructure.getTypeReference(structure)?.['/'];\n const parent = EntityStructure.getParent(structure)?.['/'];\n const source = EntityStructure.getRelationSource(structure)?.['/'];\n const target = EntityStructure.getRelationTarget(structure)?.['/'];\n // Included so the indexer sees the meta section (notably `convergenceKey`, the merge trigger) —\n // matching the feed path, whose blocks carry `@meta` wholesale.\n const meta = structure.meta;\n const metaNotEmpty =\n meta !== undefined &&\n (meta.keys?.length > 0 ||\n (meta.tags?.length ?? 0) > 0 ||\n (meta.annotations !== undefined && Object.keys(meta.annotations).length > 0) ||\n SCALAR_META_FIELDS.some((field) => (meta as Record<string, unknown>)[field] !== undefined));\n return {\n ...encodeBytes(structure.data),\n id: objectId,\n [ATTR_META]: metaNotEmpty ? (meta as Obj.JSON[typeof ATTR_META]) : undefined,\n [ATTR_TYPE]: typeRef ? URI.make(typeRef) : undefined,\n [ATTR_DELETED]: EntityStructure.isDeleted(structure),\n [ATTR_PARENT]: parent !== undefined ? EID.tryParse(parent) : undefined,\n [ATTR_RELATION_SOURCE]: source !== undefined ? EID.tryParse(source) : undefined,\n [ATTR_RELATION_TARGET]: target !== undefined ? EID.tryParse(target) : undefined,\n };\n};\n\n/**\n * Bytes in the DAG-JSON `{ '/': { bytes } }` form the feed serializer writes, which plain JSON would flatten.\n * Only arrays and plain objects are walked, so a document's raw strings keep the `toJSON` that writes them as text.\n */\nconst encodeBytes = <T>(value: T): T =>\n (value instanceof Uint8Array\n ? encodeUint8ArrayToJson(value)\n : Array.isArray(value)\n ? value.map(encodeBytes)\n : typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeBytes(item)]))\n : value) as T;\n\nconst STRUCTURE_JSON_KEYS: ReadonlySet<string> = new Set([\n 'id',\n ATTR_TYPE,\n ATTR_META,\n ATTR_DELETED,\n ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n]);\n\n/**\n * Inverse of {@link objectStructureToJson}, for reading an object from the index's JSON. The JSON carries\n * no `system.kind`, so it is inferred from the relation endpoints and the type; nor the merge fields, and\n * `createdAt` comes from the caller.\n */\nexport const objectStructureFromJson = (\n json: Obj.JSON,\n { createdAt }: { createdAt?: number } = {},\n): EntityStructure => {\n const record = json as Record<string, unknown>;\n const data = Object.fromEntries(\n Object.entries(record)\n .filter(([key]) => !STRUCTURE_JSON_KEYS.has(key))\n .map(([key, value]) => [\n key,\n deepMapValues(value, (value, recurse) =>\n isEncodedUint8Array(value) ? decodeUint8ArrayFromJson(value) : recurse(value),\n ),\n ]),\n );\n const reference = (value: unknown): EncodedReference | undefined =>\n typeof value === 'string' ? { '/': URI.make(value) } : undefined;\n const type = reference(record[ATTR_TYPE]);\n const source = reference(record[ATTR_RELATION_SOURCE]);\n const target = reference(record[ATTR_RELATION_TARGET]);\n const parent = reference(record[ATTR_PARENT]);\n const meta = record[ATTR_META] as Partial<EntityStructure['meta']> | undefined;\n return {\n system: {\n kind:\n source || target\n ? EntityKind.Relation\n : type?.['/'] === TypeMetaSchemaDXN.toString()\n ? EntityKind.Type\n : EntityKind.Object,\n ...(type && { type }),\n ...(parent && { parent }),\n ...(source && { source }),\n ...(target && { target }),\n ...(record[ATTR_DELETED] === true && { deleted: true }),\n ...(createdAt !== undefined && { createdAt }),\n },\n meta: { ...meta, keys: meta?.keys ?? [] },\n data,\n };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as semver from 'semver';\n\nimport { EncodedReference, type QueryAST, isEncodedReference } from '@dxos/echo-protocol';\nimport { DXN, EID, EntityId } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport { getTypeURI } from '../Annotation/annotations.ts';\nimport { getMetaChecked } from '../common/api/meta.ts';\nimport { type AnyEntity, ParentId } from '../common/types/index.ts';\nimport { type InternalObjectProps } from '../Entity/model.ts';\nimport { objectToJSON } from '../Obj/json-serializer.ts';\n\n/**\n * Matches a tag filter against an object's stored tags. Tags may be stored as encoded references or\n * (in legacy data) bare URI strings, and those URIs may be in legacy DXN form. Both sides are\n * normalized to the canonical EID before comparing.\n */\nexport const matchesTag = (tags: readonly unknown[], filterTag: string): boolean => {\n const canonical = (uri: string): string => {\n const eid = EID.tryParse(uri);\n return (eid && EID.getEntityId(eid)) || uri;\n };\n const normalize = (tag: unknown): string =>\n canonical(isEncodedReference(tag) ? EncodedReference.toURI(tag) : (tag as string));\n const target = canonical(filterTag);\n return tags.some((tag) => normalize(tag) === target);\n};\n\n/**\n * Matches a meta `key` / `version` constraint against an object's meta `key` and `version`.\n */\nexport const matchMetaKey = (\n key: string,\n versionRange: string | undefined,\n objKey: string | undefined,\n objVersion: string | undefined,\n): boolean => {\n if (objKey !== key) {\n return false;\n }\n if (versionRange === undefined) {\n return true;\n }\n if (objVersion === undefined || semver.valid(objVersion) === null) {\n return false;\n }\n if (semver.validRange(versionRange) === null) {\n return false;\n }\n return semver.satisfies(objVersion, versionRange, { includePrerelease: true });\n};\n\n/**\n * Compares a filter's type discriminator against the value stored on an object's `system.type`.\n */\nexport const compareTypenameStrings = (expectedStr: string, actualStr: string): boolean => {\n // Identical strings agree under every branch below, and a type query compares the same pair once\n // per candidate, so the parse is skipped rather than repeated.\n if (expectedStr === actualStr) {\n return true;\n }\n\n const expectedEid = EID.tryParse(expectedStr);\n if (expectedEid) {\n const actualEid = EID.tryParse(actualStr);\n if (!actualEid) {\n return false;\n }\n if (EID.getEntityId(expectedEid) !== EID.getEntityId(actualEid)) {\n return false;\n }\n const expectedSpaceId = EID.getSpaceId(expectedEid);\n const actualSpaceId = EID.getSpaceId(actualEid);\n return expectedSpaceId === undefined || actualSpaceId === undefined || expectedSpaceId === actualSpaceId;\n }\n\n const expectedDxn = DXN.tryMake(expectedStr);\n if (expectedDxn) {\n const actualDxn = DXN.tryMake(actualStr);\n if (!actualDxn) {\n return false;\n }\n if (DXN.getName(expectedDxn) !== DXN.getName(actualDxn)) {\n return false;\n }\n const expectedVersion = DXN.getVersion(expectedDxn);\n const actualVersion = DXN.getVersion(actualDxn);\n return expectedVersion === undefined || actualVersion === undefined || expectedVersion === actualVersion;\n }\n\n return expectedStr === actualStr;\n};\n\nconst structuralMatch = (filterObj: any, targetObj: any, strict = true): boolean => {\n if (typeof filterObj !== 'object' || filterObj === null) {\n return filterObj === targetObj;\n }\n\n if (typeof targetObj !== 'object' || targetObj === null) {\n return false;\n }\n\n const filterKeys = Object.keys(filterObj);\n const targetKeys = Object.keys(targetObj);\n if (strict && filterKeys.length !== targetKeys.length) {\n return false;\n }\n\n return filterKeys.every((key) => {\n if (!(key in targetObj)) {\n return false;\n }\n const filterValue = filterObj[key];\n const targetValue = targetObj[key];\n\n if (typeof filterValue === 'object' && filterValue !== null) {\n return structuralMatch(filterValue, targetValue);\n }\n\n return filterValue === targetValue;\n });\n};\n\n/** Normalizes an encoded reference to its URI string so ref-valued properties compare by identity. */\nconst _normalizeInValue = (value: unknown): unknown =>\n isEncodedReference(value) ? EncodedReference.toURI(value) : value;\n\n/**\n * Memoizes a `Set` per `values` array so `Filter.in` membership is O(1) rather than\n * `Array.includes`'s O(n) — this matters most for large sets projected from a subquery\n * (`Filter.in(query.project(...))`, resolved to a literal `in` by the query executor), but\n * also speeds up ordinary literal-list `Filter.in`. Keyed by array identity: the planner and\n * executor never mutate a filter's `values` array in place, so the cache stays valid for the\n * array's lifetime.\n */\nconst _inSetCache = new WeakMap<readonly unknown[], Set<unknown>>();\nconst _getInSet = (values: readonly unknown[]): Set<unknown> => {\n let set = _inSetCache.get(values);\n if (!set) {\n set = new Set(values.map(_normalizeInValue));\n _inSetCache.set(values, set);\n }\n return set;\n};\n\nexport const filterMatchValue = (filter: QueryAST.Filter, value: unknown): boolean => {\n switch (filter.type) {\n case 'compare': {\n const compareValue = filter.value as any;\n switch (filter.operator) {\n case 'eq':\n if (isEncodedReference(compareValue)) {\n if (!isEncodedReference(value)) {\n return false;\n }\n return EncodedReference.toURI(value) === EncodedReference.toURI(compareValue);\n }\n return value === compareValue;\n case 'neq':\n return value !== compareValue;\n case 'gt':\n return (value as any) > compareValue;\n case 'gte':\n return (value as any) >= compareValue;\n case 'lt':\n return (value as any) < compareValue;\n case 'lte':\n return (value as any) <= compareValue;\n default:\n return false;\n }\n }\n case 'object': {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n if (filter.props) {\n for (const [key, valueFilter] of Object.entries(filter.props)) {\n const nestedValue = (value as any)[key];\n if (!filterMatchValue(valueFilter, nestedValue)) {\n return false;\n }\n }\n }\n\n return true;\n }\n case 'in': {\n return _getInSet(filter.values).has(_normalizeInValue(value));\n }\n case 'in-query': {\n throw new Error('in-query filters must be resolved to a literal `in` by the query executor before matching.');\n }\n case 'contains': {\n if (!Array.isArray(value)) {\n return false;\n }\n\n return value.some((element) => {\n if (typeof filter.value === 'object' && filter.value !== null && !Array.isArray(filter.value)) {\n return structuralMatch(filter.value, element);\n }\n\n return element === filter.value;\n });\n }\n case 'range': {\n return (value as any) >= filter.from && (value as any) <= filter.to;\n }\n case 'not': {\n return !filterMatchValue(filter.filter, value);\n }\n case 'and': {\n return filter.filters.every((f) => filterMatchValue(f, value));\n }\n case 'or': {\n return filter.filters.some((f) => filterMatchValue(f, value));\n }\n default:\n return false;\n }\n};\n\n/**\n * Meta as the filter walker needs it, flattened out of whichever representation supplies it.\n */\nexport type FilterRecordMeta = {\n keys?: readonly { source?: string; id?: string }[];\n key?: string;\n version?: string;\n /** Encoded references or bare URI strings — {@link matchesTag} normalizes both. */\n tags?: readonly unknown[];\n annotations?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Reads the fields a filter needs out of one representation of an entity.\n *\n * The representations an executor matches against — a live proxy, a raw Automerge document, the\n * `ObjectJSON` form — walk the filter AST identically and differ only in where each field lives, so\n * one walker over an accessor replaces a copy of the walk per representation.\n */\nexport interface FilterRecordAccessor<T> {\n getId(record: T): string;\n getTypeURI(record: T): string | undefined;\n\n /** Filterable data properties by name, or `undefined` when the record cannot be read at all. */\n getProps(record: T): Record<string, unknown> | undefined;\n getMeta(record: T): FilterRecordMeta;\n hasParent(record: T): boolean;\n\n /**\n * In-memory full-text match. Only representations backed by no index implement it; the rest\n * return `false` and leave text search to the index.\n */\n matchTextSearch(filter: QueryAST.Filter & { type: 'text-search' }, record: T): boolean;\n}\n\n/**\n * Builds a filter matcher over one record representation.\n * The leaf predicates ({@link filterMatchValue}, {@link compareTypenameStrings}, {@link matchesTag},\n * {@link matchMetaKey}) are shared regardless — this shares the tree walk around them.\n */\nexport const makeFilterMatcher = <T>(\n accessor: FilterRecordAccessor<T>,\n): ((filter: QueryAST.Filter, record: T) => boolean) => {\n const match = (filter: QueryAST.Filter, record: T): boolean => {\n switch (filter.type) {\n case 'object': {\n if (filter.typename !== null) {\n const typeURI = accessor.getTypeURI(record);\n if (!typeURI || !compareTypenameStrings(filter.typename, typeURI)) {\n return false;\n }\n }\n\n if (filter.id && filter.id.length > 0 && !filter.id.includes(accessor.getId(record))) {\n return false;\n }\n\n if (filter.props) {\n const props = accessor.getProps(record);\n if (props === undefined) {\n return false;\n }\n for (const [key, valueFilter] of Object.entries(filter.props)) {\n // `@`-prefixed keys address annotations (`@type`, `@meta`), never data.\n if (key.startsWith('@')) {\n continue;\n }\n if (!filterMatchValue(valueFilter, props[key])) {\n return false;\n }\n }\n }\n\n // Meta is read lazily: on a live proxy it costs a sub-proxy walk that most filters never need.\n const foreignKeys =\n filter.foreignKeys != null && filter.foreignKeys.length > 0 ? filter.foreignKeys : undefined;\n if (foreignKeys !== undefined || filter.metaKey !== undefined) {\n const meta = accessor.getMeta(record);\n if (\n foreignKeys !== undefined &&\n !foreignKeys.some((fk) => meta.keys?.some((key) => key.source === fk.source && key.id === fk.id))\n ) {\n return false;\n }\n if (\n filter.metaKey !== undefined &&\n !matchMetaKey(filter.metaKey, filter.metaVersion, meta.key, meta.version)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n case 'tag': {\n return matchesTag(accessor.getMeta(record).tags ?? [], filter.tag);\n }\n\n case 'annotation': {\n const annotations = accessor.getMeta(record).annotations;\n if (annotations === undefined || !(filter.key in annotations)) {\n return false;\n }\n return filter.value === undefined || annotations[filter.key] === filter.value;\n }\n\n case 'text-search': {\n return accessor.matchTextSearch(filter, record);\n }\n\n case 'timestamp': {\n throw new Error('Timestamp filters must be handled at the index level, not in-memory matching.');\n }\n\n case 'child-of': {\n throw new Error('child-of filters must be handled at the executor level, not in-memory matching.');\n }\n\n case 'changes': {\n throw new Error('changes filters select change records on the host; they never match an object.');\n }\n\n case 'has-parent': {\n return accessor.hasParent(record) === filter.value;\n }\n\n case 'mnemonic': {\n return EntityId.getMnemonic(accessor.getId(record)) === filter.mnemonic;\n }\n\n case 'in-query': {\n throw new Error('in-query filters must be resolved to a literal `in` by the query executor before matching.');\n }\n\n case 'not': {\n return !match(filter.filter, record);\n }\n\n case 'and': {\n return filter.filters.every((f) => match(f, record));\n }\n\n case 'or': {\n return filter.filters.some((f) => match(f, record));\n }\n\n default:\n return false;\n }\n };\n\n return match;\n};\n\nconst entityAccessor: FilterRecordAccessor<AnyEntity> = {\n getId: (entity) => entity.id,\n getTypeURI: (entity) => getTypeURI(entity),\n getProps: (entity) => {\n try {\n return objectToJSON(entity);\n } catch {\n // Serialization of complex static-type entities may throw.\n return undefined;\n }\n },\n getMeta: (entity) => {\n const meta = getMetaChecked(entity);\n return {\n keys: meta.keys,\n key: meta.key,\n version: meta.version,\n annotations: meta.annotations,\n // Lazy: meta tags surface as `Ref`s on a live proxy and only the `tag` arm needs them encoded.\n get tags() {\n return meta.tags.map((tag: any) => (typeof tag?.encode === 'function' ? tag.encode() : tag));\n },\n };\n },\n hasParent: (entity) => {\n assumeType<InternalObjectProps>(entity);\n return entity[ParentId] !== undefined;\n },\n matchTextSearch: (filter, entity) => matchesTextSearch(filter, entity),\n};\n\n/**\n * Matches a filter against an entity proxy without full JSON serialization when possible.\n *\n * Text filters evaluate in memory here because this matcher serves executors with no index behind\n * them (the registry, `Filter.toPredicate`); index-backed paths use `filterMatchDoc` instead.\n */\nexport const filterMatchEntity: (filter: QueryAST.Filter, entity: AnyEntity) => boolean =\n makeFilterMatcher(entityAccessor);\n\n/**\n * In-memory full-text match: every term must appear (case-insensitive) in the entity's serialized\n * strings, meta included so a registry key is searchable. Containment, not tokenized ranking.\n */\nconst matchesTextSearch = (filter: QueryAST.Filter & { type: 'text-search' }, entity: AnyEntity): boolean => {\n // A vector query is meaningless without an embedding index, whatever the executor.\n if (filter.searchKind === 'vector') {\n return false;\n }\n const terms = filter.text\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n if (terms.length === 0) {\n return true;\n }\n let json: unknown;\n try {\n json = objectToJSON(entity);\n } catch {\n return false;\n }\n const haystack: string[] = [];\n collectStrings(json, haystack, new Set());\n const text = haystack.join('\\n').toLowerCase();\n return terms.every((term) => text.includes(term));\n};\n\nconst collectStrings = (value: unknown, out: string[], seen: Set<unknown>): void => {\n if (typeof value === 'string') {\n out.push(value);\n return;\n }\n if (value === null || typeof value !== 'object' || seen.has(value)) {\n return;\n }\n seen.add(value);\n for (const entry of Array.isArray(value) ? value : Object.values(value)) {\n collectStrings(entry, out, seen);\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as Struct from 'effect/Struct';\n\nimport { getTypename } from '../Annotation/index.ts';\nimport { type AnyProperties } from '../common/types/index.ts';\n\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\nexport type TypedObjectOptions = {\n // TODO(burdon): Document.\n partial?: true;\n // TODO(burdon): Document.\n record?: true;\n};\n\n/**\n *\n */\n// TODO(burdon): Comment required.\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\ntype SimplifiedSchemaFields<\n SchemaFields extends Schema.Struct.Fields,\n Options extends TypedObjectOptions,\n> = Options['partial'] extends boolean\n ? Struct.Simplify<Struct.Mutable<Partial<Schema.Struct.Type<SchemaFields>>>>\n : Struct.Simplify<Struct.Mutable<Schema.Struct.Type<SchemaFields>>>;\n\n/**\n *\n */\n// TODO(burdon): Comment required.\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\nexport type TypedObjectFields<\n SchemaFields extends Schema.Struct.Fields,\n Options extends TypedObjectOptions,\n> = SimplifiedSchemaFields<SchemaFields, Options> & { id: string } & (Options['record'] extends boolean\n ? Record<string, any>\n : {});\n\nexport const makeTypedEntityClass = (typename: string, version: string, baseSchema: Schema.Top): Schema.Codec<any> => {\n return class {\n // Implement TypedObject properties.\n static readonly typename = typename;\n static readonly version = version;\n\n // Implement Schema.Schema properties.\n // Effect 4 marks a schema with a string key carrying its own name, replacing v3's variance\n // object; `annotations` became `annotate`.\n static readonly [SCHEMA_TYPE_ID] = SCHEMA_TYPE_ID;\n static readonly ast = baseSchema.ast;\n static readonly annotate = baseSchema.annotate.bind(baseSchema);\n static readonly pipe = baseSchema.pipe.bind(baseSchema);\n\n // TODO(burdon): Comment required.\n static [Symbol.hasInstance](obj: AnyProperties) {\n return obj != null && getTypename(obj) === typename;\n }\n\n // TODO(burdon): Throw APIError.\n private constructor() {\n throw new Error('Use live(Typename, { ...fields }) to instantiate an object.');\n }\n } as any;\n};\n\n/** Effect 4's schema marker; the module declares it privately, so the literal is repeated here. */\nconst SCHEMA_TYPE_ID = '~effect/Schema/Schema';\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { InspectOptionsStylized, inspect as inspectFn } from 'node:util';\n\nimport { type CustomInspectFunction, inspectCustom } from '@dxos/debug';\n\nimport { getTypeURI } from '../Annotation/index.ts';\nimport { type AnyEntity, ATTR_TYPE } from '../common/types/index.ts';\nimport { ATTR_META } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\n\n/*\n * @internal\n */\nexport const attachedTypedObjectInspector = (obj: any) => {\n const descriptor = Object.getOwnPropertyDescriptor(obj, inspectCustom);\n if (descriptor) {\n return;\n }\n\n Object.defineProperty(obj, inspectCustom, {\n value: typedObjectInspectFunction,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n};\n\n// NOTE: KEEP as function.\nconst typedObjectInspectFunction: CustomInspectFunction<AnyEntity> = function (\n this: AnyEntity,\n depth: number,\n options: InspectOptionsStylized,\n inspect: typeof inspectFn,\n) {\n const { id, ...props } = this;\n return inspect(\n {\n id,\n [ATTR_TYPE]: getTypeURI(this),\n ...props,\n [ATTR_META]: (this as any)[MetaId], // TODO(dmaretskyi): Couldn't use getMeta since that throw's if the object has no meta.\n },\n options,\n );\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { raise } from '@dxos/debug';\nimport { assertArgument, failedInvariant } from '@dxos/invariant';\nimport { EntityId } from '@dxos/keys';\n\nimport type * as Type from '../../Type.ts';\nimport { getSchemaURI, getTypeAnnotation, setTypename } from '../Annotation/index.ts';\nimport { attachTypedJsonSerializer, defineHiddenProperty } from '../common/proxy/index.ts';\nimport {\n EntityKind,\n KindId,\n SchemaKindId,\n StaticTypeSchemaSlot,\n getStaticTypeSchema,\n setSchema,\n setType,\n} from '../common/types/index.ts';\nimport { type EntityMeta } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport {\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n assertObjectModel,\n getObjectEchoUri,\n} from '../Entity/index.ts';\nimport { attachedTypedObjectInspector } from './inspect.ts';\n\n// Omits the brand slots — those get stamped on the instance by the entity\n// handler (KindId via setKind, SchemaKindId derived in the proxy `get` trap\n// from kind + jsonSchema.entityKind, StaticTypeSchemaSlot lazily via the\n// proxy), not supplied by the caller. Allows `[Obj.Meta]` (MetaId symbol) for\n// seeding registry-provenance meta at construction (mirrors `Obj.make`).\nexport type CreateObjectProps<T> = (T extends { id: string }\n ? Omit<T, 'id' | KindId | SchemaKindId | StaticTypeSchemaSlot> & { id?: string }\n : Omit<T, KindId | SchemaKindId | StaticTypeSchemaSlot>) & {\n readonly [MetaId]?: Partial<EntityMeta>;\n};\n\n/**\n * Creates a new object instance from a schema and data, without signal reactivity.\n * This static version creates plain JavaScript objects that are not reactive/observable.\n * For reactive objects that automatically update UI when changed, use the regular live() function.\n *\n * @param schema - The Effect schema that defines the object's structure and type, piped into EchoObjectSchema\n * @param data - The data to initialize the object with. The id and @type fields are handled automatically.\n * @returns A new non-reactive object instance conforming to the schema\n * @throws {Error} If the schema is not an object schema\n * @throws {TypeError} If data contains an @type field\n *\n * @example\n * ```ts\n * class Contact extends Type.makeObject<Contact>(DXN.make('com.example.type.person', '0.1.0'))(\n * Schema.Struct({ name: Schema.String, email: Schema.String }),\n * ) {}\n *\n * const contact = createObject(Contact, {\n * name: \"John\",\n * email: \"john@example.com\",\n * })\n * ```\n */\n// TODO(burdon): Make internal.\nexport const createObject: {\n <T extends Type.AnyEntity>(input: T, props: NoInfer<CreateObjectProps<Type.InstanceType<T>>>): Type.InstanceType<T>;\n} = (input: any, props: any): any => {\n // `Type.Type` entities aren't `Schema.Schema` themselves; read the source\n // schema off the hidden slot (persisted entities synthesize it lazily via\n // the proxy `get` trap).\n const schema = getStaticTypeSchema(input) ?? failedInvariant('Type entity is missing its source schema');\n const annotation = getTypeAnnotation(schema);\n if (!annotation) {\n throw new Error('Schema is not an ECHO schema');\n }\n assertArgument(!('@type' in props), 'data', '@type is not allowed');\n assertArgument(!(RelationSourceDXNId in props), 'data', 'Relation source DXN is not allowed in the constructor');\n assertArgument(!(RelationTargetDXNId in props), 'data', 'Relation target DXN is not allowed in the constructor');\n assertArgument(\n RelationSourceId in props === RelationTargetId in props,\n 'data',\n 'Relation source and target must be provided together',\n );\n\n // Pull `[Obj.Meta]` (MetaId-symbol) off props before spreading so it doesn't\n // leak into data. Callers use this to seed registry-provenance meta fields\n // (`key`, `version`) and foreign keys / tags at construction time, mirroring\n // `Obj.make`'s symbol-keyed meta convention.\n const metaOverride = props[MetaId];\n if (metaOverride !== undefined) {\n delete props[MetaId];\n }\n\n // Raw object.\n const obj = { ...props, id: props.id ?? EntityId.random() };\n\n // Metadata. Instance-kind is read from the schema's TypeAnnotation (set by\n // EchoObjectSchema / EchoRelationSchema / EchoTypeKindSchema): instances of\n // a type-kind meta-schema are themselves type-kind entities, etc. The\n // RelationSourceId-in-props check covers the legacy path where the schema\n // annotation isn't authoritative.\n const kind =\n annotation.kind === EntityKind.Type\n ? EntityKind.Type\n : annotation.kind === EntityKind.Relation || RelationSourceId in props\n ? EntityKind.Relation\n : EntityKind.Object;\n defineHiddenProperty(obj, KindId, kind);\n defineHiddenProperty(obj, MetaId, {\n ...metaOverride,\n keys: metaOverride?.keys ?? [],\n tags: metaOverride?.tags ?? [],\n annotations: metaOverride?.annotations ?? {},\n });\n setSchema(obj, schema);\n // If the caller passed a type entity (recognised via the schema slot), keep\n // a reference to it on the instance for `Obj.getType` / `Relation.getType`.\n if (input !== schema) {\n setType(obj, input);\n }\n setTypename(obj, getSchemaURI(schema) ?? failedInvariant('Missing schema URI'));\n attachTypedJsonSerializer(obj);\n attachedTypedObjectInspector(obj);\n\n // Relation.\n if (kind === EntityKind.Relation) {\n const sourceDXN = getObjectEchoUri(props[RelationSourceId]) ?? raise(new Error('Unresolved relation source'));\n const targetDXN = getObjectEchoUri(props[RelationTargetId]) ?? raise(new Error('Unresolved relation target'));\n defineHiddenProperty(obj, RelationSourceDXNId, sourceDXN);\n defineHiddenProperty(obj, RelationTargetDXNId, targetDXN);\n }\n\n assertObjectModel(obj);\n return obj;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AnyProperties } from '../common/types/index.ts';\nimport { ObjectDeletedId } from '../Entity/index.ts';\n\n/**\n * @returns `true` if the object has been marked as deleted.\n */\nexport const isDeleted = (obj: AnyProperties): boolean => {\n if ((obj as any)[ObjectDeletedId] === undefined) {\n // TODO(dmaretskyi): Return to prior behavior of throwing.\n // throw new Error('Object does not support deletion marker');\n return false;\n }\n\n return (obj as any)[ObjectDeletedId] ?? false;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\n\nimport { SetParentAnnotation, getFromAst } from '../Annotation/index.ts';\nimport { EntityKind } from '../common/types/entity.ts';\nimport { KindId, ParentId, getSchema } from '../common/types/index.ts';\nimport { Ref } from '../Ref/ref.ts';\n\n/** An owning field; `path` is relative to the parent and may nest inside plain structs, e.g. `backend.config`. */\ntype OwningField = { readonly path: readonly string[]; readonly override: boolean };\n\n/**\n * Owning-field paths relative to an AST node, per {@link SetParentAnnotation}. Memoized per node —\n * a schema's annotations do not change once it is built (a dynamic type rebuilds its AST, yielding\n * fresh keys) — which also keeps the walk linear in nodes over a schema whose nested types repeat.\n */\nconst cache = new WeakMap<SchemaAST.AST, readonly OwningField[]>();\n\nconst getOwnership = (ast: SchemaAST.AST): { override: boolean } | undefined => {\n const value = Option.getOrUndefined(getFromAst(ast, SetParentAnnotation));\n return value?.value ? { override: value.override } : undefined;\n};\n\nconst collect = (ast: SchemaAST.AST): readonly OwningField[] => {\n const cached = cache.get(ast);\n if (cached) {\n return cached;\n }\n // Seed before recursing: a self-referencing `Schema.suspend` field resolves back to this node, and\n // an owned field is declared at the level it appears on, so the cycle contributes nothing further.\n cache.set(ast, []);\n\n const fields: OwningField[] = [];\n // A union of structs (e.g. a discriminated `spec`) contributes each member's fields at this path.\n if (SchemaAST.isUnion(ast)) {\n for (const member of ast.types) {\n fields.push(...collect(member));\n }\n } else {\n for (const property of SchemaAST.getPropertySignatures(ast)) {\n if (typeof property.name !== 'string') {\n continue;\n }\n // Optionality wraps the field schema in a union; for an array of refs the annotation may sit\n // on either the array or its element.\n const unwrapped = SchemaEx.unwrapOptional(property.type);\n const element = SchemaEx.getArrayElementType(unwrapped);\n const ownership =\n getOwnership(property.type) ?? getOwnership(unwrapped) ?? (element != null ? getOwnership(element) : undefined);\n if (ownership) {\n fields.push({ path: [property.name], override: ownership.override });\n } else {\n // Recurse into nested structs and unions of structs (a ref is a Declaration, which\n // terminates the walk).\n const name = property.name;\n fields.push(...collect(unwrapped).map((field): OwningField => ({ ...field, path: [name, ...field.path] })));\n }\n }\n }\n\n cache.set(ast, fields);\n return fields;\n};\n\nconst setParent = (value: unknown, parent: unknown, override: boolean): void => {\n if (!Ref.isRef(value)) {\n return;\n }\n // Only an already-resolved target can be re-parented synchronously; an unresolved ref names an\n // object whose parent edge is either already written or not this holder's to write. `.target`\n // throws on a ref with neither an inlined target nor a resolver, so gate on `isAvailable`.\n const target: any = value.isAvailable ? value.target : undefined;\n if (target == null || target[KindId] !== EntityKind.Object) {\n return;\n }\n // By id, not identity: the database resolves a parent edge through the working set, which may\n // hand back a different proxy for the same entity — an identity compare would miss the\n // short-circuit and re-write the unchanged edge on every update of the holder.\n const current = target[ParentId];\n if (current?.id === (parent as any)?.id) {\n return;\n }\n if (!override && current != null) {\n return;\n }\n target[ParentId] = parent;\n};\n\n/**\n * Propagates the parent edge declared by an object's {@link SetParentAnnotation} fields: every\n * resolved ref target held in an owning field gets its parent set to the holding object.\n *\n * Called after object creation (`Obj.make`) and after every change transaction (`Obj.update`) —\n * idempotent, so re-running it over unchanged fields is a no-op.\n */\nexport const propagateParentAnnotations = (obj: unknown): void => {\n const schema = getSchema(obj);\n if (schema == null) {\n return;\n }\n\n for (const { path, override } of collect(schema.ast)) {\n let value: any = obj;\n for (const key of path) {\n value = value?.[key];\n }\n if (Array.isArray(value)) {\n for (const element of value) {\n setParent(element, obj, override);\n }\n } else {\n setParent(value, obj, override);\n }\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { invariant } from '@dxos/invariant';\n\nimport { type Mutable } from '../common/proxy/index.ts';\nimport { getSchema } from '../common/types/index.ts';\n\n/**\n * Set a deeply nested property on an object.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setValue = (obj: Mutable<any>, path: readonly (string | number)[], value: any): void => {\n invariant(path.length > 0, 'Path must not be empty');\n\n const schema = getSchema(obj);\n invariant(schema != null, 'Object must have a schema');\n\n let parent = obj;\n let currentAST: SchemaAST.AST | undefined = schema.ast;\n\n // Navigate to the parent of the target property.\n for (let i = 0; i < path.length - 1; i++) {\n const part = path[i];\n const key = typeof part === 'number' ? part : String(part);\n if (parent[key] === undefined) {\n const propertyAST = getPropertyAST(currentAST, String(part));\n const shouldBeArray = propertyAST ? SchemaEx.isArrayType(propertyAST) : false;\n\n if (shouldBeArray) {\n // Create array.\n parent[key] = [];\n } else {\n // TODO(wittjosiah): Is there a better way to handle this than creating an object with defaults?\n // Perhaps properties on objects should be optional by default?\n // Create object with defaults for required fields.\n const objWithDefaults = createObjectWithDefaults(propertyAST);\n parent[key] = objWithDefaults;\n }\n }\n\n parent = parent[key];\n currentAST = getPropertyAST(currentAST, String(part));\n }\n\n const finalKey = path[path.length - 1];\n parent[finalKey] = value;\n\n return value;\n};\n\n/**\n * Helper to get the AST of a nested property.\n * @param ast - Current schema AST.\n * @param propertyName - Name of the property to get.\n * @returns The AST of the nested property, or undefined if not found.\n */\nconst getPropertyAST = (ast: SchemaAST.AST | undefined, propertyName: string): SchemaAST.AST | undefined => {\n if (!ast) {\n return undefined;\n }\n\n if (SchemaEx.isNestedType(ast)) {\n const properties = SchemaEx.getProperties(ast);\n const property = properties.find((p) => p.name.toString() === propertyName);\n if (property) {\n return property.type;\n }\n }\n\n if (SchemaEx.isArrayType(ast)) {\n const elementType = SchemaEx.getArrayElementType(ast);\n return elementType;\n }\n\n return undefined;\n};\n\n/**\n * Get all required properties from a schema AST.\n * A property is required if it's not optional.\n *\n * @param ast - Schema AST to inspect.\n * @returns Array of required properties with their types.\n */\nconst getRequiredProperties = (ast: SchemaAST.AST | undefined): SchemaEx.SchemaProperty[] => {\n if (!ast) {\n return [];\n }\n\n // Only objects/structs have properties with optional/required distinction.\n if (!SchemaEx.isNestedType(ast)) {\n return [];\n }\n\n const properties = SchemaEx.getProperties(ast);\n\n // Filter to only required properties (where isOptional === false).\n return properties.filter((p) => !p.isOptional);\n};\n\n/**\n * Get the default value for a primitive type.\n * Returns undefined for non-primitive or unsupported types.\n *\n * @param ast - Type AST.\n * @returns Default value for the type, or undefined.\n */\nconst getDefaultValueForType = (ast: SchemaAST.AST | undefined): any => {\n if (!ast) {\n return undefined;\n }\n\n const defaultValue = SchemaAST.getDefaultAnnotation(ast);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n // A plain switch rather than `Match.when({ _tag })`: matching an object pattern against Effect 4's\n // mutually recursive AST union expands into a mapped type the checker cannot resolve.\n switch (ast._tag) {\n case 'String':\n return '';\n case 'Number':\n return 0;\n case 'Boolean':\n return false;\n default:\n return undefined;\n }\n};\n\n/**\n * Create an object with default values for all required properties.\n * Handles primitive types (String, Number, Boolean) and recursively initializes required nested objects.\n *\n * @param ast - Schema AST describing the object structure.\n * @returns Object with required fields populated with defaults.\n */\nconst createObjectWithDefaults = (ast: SchemaAST.AST | undefined): any => {\n if (!ast) {\n return {};\n }\n\n const requiredProps = getRequiredProperties(ast);\n const obj: any = {};\n\n for (const prop of requiredProps) {\n const defaultValue = getDefaultValueForType(prop.type);\n if (defaultValue !== undefined) {\n obj[prop.name] = defaultValue;\n } else if (SchemaEx.isNestedType(prop.type)) {\n obj[prop.name] = createObjectWithDefaults(prop.type);\n }\n }\n\n return obj;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { assertArgument } from '@dxos/invariant';\nimport { deepMapValues } from '@dxos/util';\n\nimport {\n EntityKind,\n KindId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ParentId,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n SchemaId,\n SelfURIId,\n SnapshotKindId,\n TypeEntityId,\n TypeId,\n} from '../common/types/index.ts';\nimport { SCALAR_META_FIELDS } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\n\n/**\n * Copy a Symbol-keyed property from source to target if it has a defined value.\n * Handles both plain objects (symbol in source) and proxies where get returns a value\n * but has/in returns false (e.g. ObjectDatabaseId on echo-db proxies).\n * Optional transform clones or mutates the value before assignment (e.g. for MetaId).\n */\nconst copySymbolProperty = (\n source: any,\n target: any,\n symbol: symbol,\n transform?: (value: unknown) => unknown,\n): void => {\n let value: unknown;\n // Echo-db proxy getters (e.g. RelationSourceId, RelationTargetId) can throw in certain states.\n try {\n value = source[symbol];\n } catch {\n return;\n }\n if (value !== undefined) {\n const finalValue = transform ? transform(value) : value;\n Object.defineProperty(target, symbol, {\n value: finalValue,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n }\n};\n\n/**\n * Returns an immutable snapshot of the reactive object.\n * The snapshot is branded with SnapshotKindId (not KindId).\n */\nexport const getSnapshot = <T extends object>(obj: T): T => {\n assertArgument(typeof obj === 'object' && obj !== null && KindId in obj, 'obj', 'must be an entity');\n\n const snapshot = deepMapValues(obj, (value, recurse) => {\n // Do not recurse on references (but do recurse on arrays).\n if (\n typeof value === 'object' &&\n value !== null &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n !Array.isArray(value)\n ) {\n return value;\n }\n\n return recurse(value);\n }) as any;\n\n // Add SnapshotKindId brand based on original KindId.\n if (obj != null && typeof obj === 'object' && KindId in obj) {\n snapshot[SnapshotKindId] = (obj as any)[KindId];\n }\n\n // Preserve Symbol-keyed properties that are important for type introspection.\n // These are not copied by deepMapValues since Object.keys() doesn't include symbols.\n const source = obj as any;\n\n // Type introspection symbols.\n copySymbolProperty(source, snapshot, TypeId);\n copySymbolProperty(source, snapshot, SchemaId);\n copySymbolProperty(source, snapshot, TypeEntityId);\n copySymbolProperty(source, snapshot, SelfURIId);\n\n // Database reference (required for Obj.getDatabase to work on snapshots).\n copySymbolProperty(source, snapshot, ObjectDatabaseId);\n copySymbolProperty(source, snapshot, ObjectDeletedId);\n\n // Parent reference (required for Obj.getParent to work on snapshots).\n copySymbolProperty(source, snapshot, ParentId);\n\n // Metadata symbol. Copy arrays/objects so the snapshot is not affected by mutations to the live meta.\n copySymbolProperty(source, snapshot, MetaId, (meta: any) => {\n const copy: Record<string, unknown> = {\n keys: [...(meta?.keys ?? [])],\n tags: [...(meta?.tags ?? [])],\n ...(meta?.annotations ? { annotations: { ...meta.annotations } } : {}),\n };\n // Enumerated from the schema so a newly added meta field is carried without touching this.\n for (const field of SCALAR_META_FIELDS) {\n if (meta?.[field] != null) {\n copy[field] = meta[field];\n }\n }\n return copy;\n });\n\n // Relation endpoint symbols, read only on a relation: on any other object the echo-db getters throw an invariant\n // violation, so every snapshot of a plain object paid for two caught, stack-traced errors.\n if (source[KindId] === EntityKind.Relation) {\n copySymbolProperty(source, snapshot, RelationSourceDXNId);\n copySymbolProperty(source, snapshot, RelationTargetDXNId);\n copySymbolProperty(source, snapshot, RelationSourceId);\n copySymbolProperty(source, snapshot, RelationTargetId);\n }\n\n return Object.freeze(snapshot) as T;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as AsyncResult from 'effect/reactivity/AsyncResult';\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport { assertArgument } from '@dxos/invariant';\n\nimport type * as Entity from '../../Entity.ts';\nimport type * as Obj from '../../Obj.ts';\nimport type * as Ref from '../../Ref.ts';\nimport type * as Relation from '../../Relation.ts';\nimport type * as Tag from '../../Tag.ts';\nimport { getLabel } from '../Annotation/index.ts';\nimport { snapshotEquals, snapshotForComparison } from '../common/atom-snapshot.ts';\nimport { subscribe } from '../common/proxy/reactive.ts';\nimport { ParentId } from '../common/types/index.ts';\nimport { getMeta } from '../common/types/meta.ts';\nimport { getDatabase, isEntity } from '../Entity/index.ts';\nimport { refArrayFamily } from '../Ref/atoms.ts';\nimport { RefTypeId } from '../Ref/ref.ts';\nimport { loadRefTarget } from '../Ref/utils.ts';\nimport { isDeleted } from './deleted.ts';\nimport { getSnapshot } from './snapshot.ts';\n\nconst isRef = (obj: unknown): obj is Ref.Ref<any> =>\n obj != null && typeof obj === 'object' && RefTypeId in (obj as object);\n\nconst getReactiveOption = <T extends Obj.Unknown>(snapshot: Obj.Snapshot<T>): Effect.Effect<Option.Option<T>, never> =>\n Effect.gen(function* () {\n const db = getDatabase(snapshot as any);\n if (!db) {\n return Option.none();\n }\n const obj = db.getObjectById((snapshot as any).id);\n return obj ? Option.some(obj as T) : Option.none();\n });\n\n/**\n * Atom family for ECHO objects.\n * Uses object reference as key — same object returns same atom.\n */\nconst objectFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Snapshot<T>> => {\n return Atom.make<Obj.Snapshot<T>>((get) => {\n const unsubscribe = subscribe(obj, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(obj) as unknown as Obj.Snapshot<T>);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(obj) as unknown as Obj.Snapshot<T>;\n });\n});\n\n/**\n * Atom family for ECHO refs (snapshot version).\n * Keyed by a structurally-equal tuple `[ref, includeDeleted]` so nested families are avoided.\n * Subscribes to target object changes after loading.\n */\nconst refFamily = Atom.family(\n <T extends Obj.Unknown>([ref, includeDeleted]: readonly [Ref.Ref<T>, boolean]): Atom.Atom<\n Obj.Snapshot<T> | undefined\n > => {\n return Atom.make<Obj.Snapshot<T> | undefined>((get) => {\n let unsubscribeTarget: (() => void) | undefined;\n\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n const read = (target: T): Obj.Snapshot<T> | undefined =>\n !includeDeleted && isDeleted(target) ? undefined : (getSnapshot(target) as unknown as Obj.Snapshot<T>);\n\n const setupTargetSubscription = (target: T): Obj.Snapshot<T> | undefined => {\n unsubscribeTarget?.();\n unsubscribeTarget = subscribe(target, () => {\n get.setSelf(read(target));\n });\n // Runs at once when the node was disposed while the target loaded.\n get.addFinalizer(unsubscribeTarget);\n return read(target);\n };\n\n return loadRefTarget(ref, get, setupTargetSubscription, includeDeleted ? { deleted: 'include' } : undefined);\n });\n },\n);\n\n/**\n * Atom family for ECHO object properties, keyed by `[object, key]`.\n */\nconst propertyFamily = Atom.family(([obj, key]: readonly [Obj.Unknown, PropertyKey]): Atom.Atom<any> => {\n return Atom.make<any>((get) => {\n let previousSnapshot = snapshotForComparison((obj as any)[key]);\n\n const unsubscribe2 = subscribe(obj, () => {\n const newValue = (obj as any)[key];\n // Content comparison against the last emitted snapshot: identity would be unequal for every\n // array/object, firing on any mutation of `obj` (see `snapshotEquals`).\n if (!snapshotEquals(newValue, previousSnapshot)) {\n previousSnapshot = snapshotForComparison(newValue);\n get.setSelf(previousSnapshot);\n }\n });\n\n get.addFinalizer(() => unsubscribe2());\n\n return snapshotForComparison((obj as any)[key]);\n });\n});\n\n/**\n * Atom family for ECHO objects — returns the live object, not a snapshot.\n */\nconst objectWithReactiveFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<T> => {\n return Atom.make<T>((get) => {\n const unsubscribe = subscribe(obj, () => {\n get.setSelf(obj);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return obj;\n });\n});\n\n/**\n * Atom family for ECHO refs — returns the live reactive object, not a snapshot.\n */\nconst refWithReactiveFamily = Atom.family(<T extends Obj.Unknown>(ref: Ref.Ref<T>): Atom.Atom<T | undefined> => {\n const effect = (get: Atom.AtomContext) =>\n Effect.gen(function* () {\n const snapshot = get(makeAtom(ref));\n if (snapshot == null) {\n return undefined;\n }\n const option = yield* getReactiveOption(snapshot);\n return Option.getOrElse(option, () => undefined);\n });\n\n return Function.pipe(\n Atom.make(effect),\n Atom.map((result) => AsyncResult.getOrElse(result, () => undefined)),\n );\n});\n\n/**\n * Atom family for a property of a ref's target object.\n * Resolves the ref (reactively) then projects the property atom, so it fires when the ref resolves or when\n * that property changes. Yields `undefined` while the target is unresolved.\n */\nconst refPropertyFamily = Atom.family(([ref, key]: readonly [Ref.Ref<any>, PropertyKey]): Atom.Atom<any> =>\n Atom.make((get) => {\n const target = get(refWithReactiveFamily(ref));\n return target ? get(propertyFamily([target, key])) : undefined;\n }),\n);\n\n/**\n * Atom family for any ECHO entity (obj or relation) — returns a snapshot.\n */\nconst entityFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<Entity.Snapshot> => {\n return Atom.make<Entity.Snapshot>((get) => {\n const unsubscribe = subscribe(entity, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(entity) as unknown as Entity.Snapshot);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(entity) as unknown as Entity.Snapshot;\n });\n});\n\n/**\n * Atom family for ECHO relations — returns a typed relation snapshot.\n */\nconst relationFamily = Atom.family(<T extends Relation.Unknown>(relation: T): Atom.Atom<Relation.Snapshot<T>> => {\n return Atom.make<Relation.Snapshot<T>>((get) => {\n const unsubscribe = subscribe(relation, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(relation) as unknown as Relation.Snapshot<T>);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(relation) as unknown as Relation.Snapshot<T>;\n });\n});\n\n/**\n * Create a read-only snapshot atom for a reactive object or ref.\n * Updates automatically when the object is mutated.\n * For refs, subscribes to target object changes after loading.\n */\nexport const makeAtom: {\n <T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Snapshot<T>>;\n <T extends Obj.Unknown>(ref: Ref.Ref<T>, options?: Ref.LoadOptions): Atom.Atom<Obj.Snapshot<T> | undefined>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any>, options?: Ref.LoadOptions): Atom.Atom<any> => {\n if (isRef(objOrRef)) {\n return refFamily([objOrRef, options?.deleted === 'include']);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return objectFamily(obj as any);\n};\n\n/**\n * Create a read-only atom for a specific property of a reactive object, or of a ref's target.\n * Only fires updates when the property value actually changes. Given a ref, the atom resolves the target\n * first and yields `undefined` until it loads.\n */\nexport const makeProperty: {\n <T extends Obj.Unknown, K extends keyof T>(obj: T, key: K): Atom.Atom<T[K]>;\n <T extends Obj.Unknown, K extends keyof T>(ref: Ref.Ref<T>, key: K): Atom.Atom<T[K] | undefined>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any>, key: any): Atom.Atom<any> => {\n if (isRef(objOrRef)) {\n return refPropertyFamily([objOrRef as Ref.Ref<any>, key]);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return propertyFamily([obj, key]);\n};\n\n/**\n * Like `makeAtom` but returns the live reactive object instead of a snapshot.\n * Prefer `makeAtom` (snapshot) unless you need the live Obj for generic mutations.\n * Given a ref array, yields the loaded targets in ref order, without deleted ones unless included.\n */\nexport const makeWithReactive: {\n <T extends Obj.Unknown>(obj: T): Atom.Atom<T>;\n <T extends Obj.Unknown>(ref: Ref.Ref<T>): Atom.Atom<T | undefined>;\n <T extends Obj.Unknown>(refs: readonly Ref.Ref<T>[], options?: Ref.LoadOptions): Atom.Atom<T[]>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any> | readonly Ref.Ref<any>[], options?: Ref.LoadOptions): Atom.Atom<any> => {\n if (Array.isArray(objOrRef)) {\n // Copied: a live ECHO array would mutate under the family key.\n return refArrayFamily([[...objOrRef], options?.deleted === 'include']);\n }\n if (isRef(objOrRef)) {\n return refWithReactiveFamily(objOrRef as Ref.Ref<any>);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return objectWithReactiveFamily(obj);\n};\n\n/**\n * Create a read-only snapshot atom for any ECHO entity (obj or relation).\n * Updates automatically when the entity is mutated.\n */\nexport const makeEntity = <T extends Entity.Unknown>(entity: T): Atom.Atom<Entity.Snapshot> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return entityFamily(entity);\n};\n\n/**\n * Create a read-only snapshot atom for a reactive relation.\n * Updates automatically when the relation is mutated.\n */\nexport const makeRelation = <T extends Relation.Unknown>(relation: T): Atom.Atom<Relation.Snapshot<T>> => {\n assertArgument(isEntity(relation), 'relation', 'Must be a reactive ECHO relation');\n return relationFamily(relation);\n};\n\n/**\n * Atom family for an entity's label string.\n * Fires only when the computed label actually changes, not on every entity mutation.\n */\nconst labelAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<string | undefined> => {\n return Atom.make<string | undefined>((get) => {\n let previous = getLabel(entity);\n\n const unsubscribe = subscribe(entity, () => {\n const next = getLabel(entity);\n if (next !== previous) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the label of a reactive ECHO entity.\n * Re-evaluates on entity mutation; only propagates when the label string changes.\n */\nexport const makeLabelAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<string | undefined> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return labelAtomFamily(entity);\n};\n\nconst readTags = (entity: Entity.Unknown): readonly Ref.Ref<Tag.Tag>[] => [...getMeta(entity).tags];\n\nconst tagsAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Ref.Ref<Tag.Tag>[]> => {\n return Atom.make<readonly Ref.Ref<Tag.Tag>[]>((get) => {\n let previous = readTags(entity);\n\n const unsubscribe = subscribe(entity, () => {\n const next = readTags(entity);\n if (!snapshotEquals(next, previous)) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the meta tags of a reactive ECHO entity.\n * Re-reads on entity mutation; only propagates when the tag list changes.\n */\nexport const makeTagsAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Ref.Ref<Tag.Tag>[]> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return tagsAtomFamily(entity);\n};\n\nconst readParent = (obj: Obj.Unknown): Obj.Unknown | undefined => (obj as any)[ParentId];\n\n/**\n * Atom family for an object's parent.\n * Fires only when the parent changes, compared by id since the database may hand back a different proxy.\n */\nconst parentAtomFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Unknown | undefined> => {\n return Atom.make<Obj.Unknown | undefined>((get) => {\n let previous = readParent(obj);\n\n const unsubscribe = subscribe(obj, () => {\n const next = readParent(obj);\n if (next?.id !== previous?.id) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the parent of a reactive ECHO object.\n * Re-evaluates on object mutation; only propagates when the parent changes.\n */\nexport const makeParentAtom = <T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Unknown | undefined> => {\n assertArgument(isEntity(obj), 'obj', 'Must be a reactive ECHO object');\n return parentAtomFamily(obj);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { assumeType, deepMapValues } from '@dxos/util';\n\nimport type * as Obj from '../../Obj.ts';\nimport { makeObject } from '../common/proxy/index.ts';\nimport { ParentId, getSchema, getStaticTypeSchema, getType } from '../common/types/index.ts';\nimport { getMeta } from '../common/types/meta.ts';\nimport { type InternalObjectProps } from '../Entity/model.ts';\nimport { Ref } from '../Ref/index.ts';\n\n/**\n * Clones an object or relation.\n * By default this does not clone referenced objects, only the properties in the object; pass `opts.deep`\n * to recurse into refs (see {@link Obj.CloneOptions}).\n * @returns A new object with the same schema and properties.\n */\nexport const clone = <T extends Obj.Any>(obj: T, opts?: Obj.CloneOptions): T =>\n cloneInner(obj, opts, obj, new Map(), new Set());\n\n/**\n * Recursive clone worker threaded with two cycle-guard structures:\n * - `cache`: id → already-finished clone; reused when the same object appears more than once in a DAG.\n * - `inProgress`: ids of objects whose clone is currently being computed; a ref back into this set means\n * a true cycle — the original ref is kept rather than recursing forever.\n */\nconst cloneInner = <T extends Obj.Any>(\n obj: T,\n opts: Obj.CloneOptions | undefined,\n root: Obj.Any,\n cache: Map<string, Obj.Any>,\n inProgress: Set<string>,\n): T => {\n if (cache.has(obj.id)) {\n return cache.get(obj.id) as T;\n }\n inProgress.add(obj.id);\n\n const { id, ...data } = obj;\n // Prefer cloning through the type entity so the cloned instance preserves\n // `Obj.getType` identity. Falls back to the raw schema for older instances\n // that don't have a type-entity back-reference set (e.g. deserialized).\n const typeEntity = getType(obj);\n const schema = typeEntity != null ? getStaticTypeSchema(typeEntity) : getSchema(obj);\n invariant(schema != null, 'Object should have a type or schema');\n\n const mapRef = (value: unknown, recurse: (value: unknown) => unknown): unknown => {\n if (Ref.isRef(value)) {\n const target = value.target;\n // A ref back to an in-progress object means a cycle — keep the original ref to break it.\n if (\n target != null &&\n !inProgress.has(target.id) &&\n (opts?.deep === 'all' || (opts?.deep === 'parent' && isChildOf(target, root)))\n ) {\n return Ref.make(cloneInner(target, opts, root, cache, inProgress));\n }\n return value;\n }\n return recurse(value);\n };\n\n const props: any = deepMapValues(data, mapRef);\n if (opts?.retainId) {\n props.id = id;\n }\n const meta = deepMapValues(getMeta(obj), mapRef);\n const result = makeObject(schema, props, meta, typeEntity as object | undefined);\n\n inProgress.delete(obj.id);\n cache.set(obj.id, result);\n return result;\n};\n\n/**\n * Whether `entity`'s parent chain reaches `root` — i.e. it is an owned descendant that cascade-deletes with\n * the root. Walks the `ParentId` back-links (a finite tree); guarded against cycles defensively.\n */\nconst isChildOf = (entity: unknown, root: Obj.Any): boolean => {\n const seen = new Set<InternalObjectProps>();\n assumeType<InternalObjectProps>(entity);\n let parent = entity[ParentId];\n while (parent != null && !seen.has(parent)) {\n if (parent.id === root.id) {\n return true;\n }\n seen.add(parent);\n parent = parent[ParentId];\n }\n return false;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as Struct from 'effect/Struct';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\n\n// TODO(ZaymonFC): Do this one at a time. This might be dangerous.\nexport const addFieldsToSchema = (schema: Schema.Top, fields: Schema.Struct.Fields): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n // Rebuilt through the AST like its siblings below: `mapFields` is a `Struct` operation and this\n // takes any `Schema.Top`.\n const added = (Schema.Struct(fields).mapFields(Struct.map(Schema.optional)).ast as SchemaAST.Objects)\n .propertySignatures;\n\n return Schema.make<Schema.Top>(\n new SchemaAST.Objects([...ast.propertySignatures, ...added], ast.indexSignatures, ast.annotations),\n );\n};\n\nexport const updateFieldsInSchema = (schema: Schema.Top, fields: Schema.Struct.Fields): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n const updatedProperties = [...ast.propertySignatures];\n const propertiesToUpdate = (Schema.Struct(fields).mapFields(Struct.map(Schema.optional)).ast as SchemaAST.Objects)\n .propertySignatures;\n for (const property of propertiesToUpdate) {\n const index = updatedProperties.findIndex((p) => p.name === property.name);\n if (index !== -1) {\n updatedProperties[index] = property;\n } else {\n updatedProperties.push(property);\n }\n }\n\n return Schema.make<Schema.Top>(new SchemaAST.Objects(updatedProperties, ast.indexSignatures, ast.annotations));\n};\n\nexport const removeFieldsFromSchema = (schema: Schema.Top, fieldNames: string[]): Schema.Top => {\n return Schema.make<Schema.Top>(SchemaAST.omit(schema.ast, fieldNames));\n};\n\nexport const updateFieldNameInSchema = (\n schema: Schema.Top,\n { before, after }: { before: PropertyKey; after: PropertyKey },\n): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n return Schema.make<Schema.Top>(\n new SchemaAST.Objects(\n ast.propertySignatures.map((p) => (p.name === before ? new SchemaAST.PropertySignature(after, p.type) : p)),\n ast.indexSignatures,\n ast.annotations,\n ),\n );\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { IconAnnotation, LabelAnnotation } from '../Annotation/index.ts';\nimport { EntityKind, KindId, SchemaKindId, StaticTypeSchemaSlot } from '../common/types/index.ts';\nimport { EchoTypeKindSchema, TypeMetaSchemaDXN } from '../Entity/index.ts';\nimport { JsonSchemaType } from '../JsonSchema/index.ts';\n\n/**\n * Raw struct backing {@link TypeSchema}. Exposed only so `TypeSchema`\n * (the TS type) can derive its data fields via `Schema.Schema.Type<typeof ...>`;\n * runtime callers should use {@link TypeSchema} (the piped, branded entity).\n *\n * `typename` and `version` are NOT data fields — they live in `EntityMeta.key` /\n * `EntityMeta.version` (the canonical registry-provenance pair, queryable via\n * `Filter.key(...)`). The same `jsonSchema` payload also embeds them so a\n * standalone JSON-Schema export remains self-describing, but the schema-registry\n * reads/writes them through meta.\n */\nconst TypeSchemaStruct = Schema.Struct({\n name: Schema.optional(Schema.String),\n jsonSchema: JsonSchemaType,\n});\n\n/**\n * Persistent representation of a schema.\n */\nexport const TypeSchema = TypeSchemaStruct.pipe(\n LabelAnnotation.set(['name']),\n IconAnnotation.set({\n icon: 'ph--database--regular',\n hue: 'green',\n }),\n EchoTypeKindSchema(TypeMetaSchemaDXN),\n);\n\n/**\n * Persistent representation of a schema — the runtime shape that\n * `db.addType(Type.makeObjectFromJsonSchema(...))` produces\n * and `Filter.type(Type.Type).run()` returns.\n *\n * Structurally identical to a static `Type.Type` entity: the entity-handler's\n * `get` trap exposes `[SchemaKindId]` (derived from `system.kind` and\n * `data.jsonSchema.entityKind`) and rebuilds `[StaticTypeSchemaSlot]` lazily\n * from `jsonSchema`, so a persisted instance satisfies the public `Type<A>`\n * interface without casting.\n */\nexport type TypeSchema = Schema.Schema.Type<typeof TypeSchemaStruct> & {\n /** Object identifier — injected by `EchoTypeKindSchema` and stamped at construction. */\n readonly id: string;\n /** Entity-kind discriminator (object/relation/type) carried on every entity instance. */\n readonly [KindId]: EntityKind.Type;\n /** Kind of schema described by this meta-instance — always `EntityKind.Type` for `Type.Type` itself. */\n readonly [SchemaKindId]: EntityKind.Type;\n /** Effect Schema rebuilt lazily from `jsonSchema`; satisfies `Type.getSchema(...)` without an extra cast. */\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,aACX,WACgE;CAChE,OAAO,OAAO,KAAkE,UAAU,KAAK,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC;AACpH;;;;;;;;;;;;;;ACzBA,IAAa,mBAAmB;AAchC,IAAa,gBAAgB,UAC3B,OAAO,UAAU,YAAY,UAAU,QAAA,kCAA4B;AAErE,IAAM,WAA8C,CAAC;AAErD,IAAa,kBAAqB,OAAuB,cAAqC;EAC3F,mBAAmB;CACpB;CACA;AACF;;;;;;ACnCA,IAAa,gBAAgB;;;;;;ACG7B,IAAa,WAAW,GAAY,MAAuB;CACzD,IAAI,KAAK,MACP,OAAO,KAAK,OAAO,IAAI;CAEzB,IAAI,KAAK,MACP,OAAO;CAET,OAAO,EAAE,cAAc,CAAC;AAC1B;;;;AAWA,IAAa,eAA2B,GAAc,MAAiB,QAAQ,SAAS,CAAC,GAAG,SAAS,CAAC,CAAC;;;;AAKvG,IAAa,kBAA8B,GAAc,MAAiB,QAAQ,YAAY,CAAC,GAAG,YAAY,CAAC,CAAC;;;;;AAMhH,IAAa,QAA6B,GAAG,gBAAgD;CAC3F,QAAQ,G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,OAAO,QAAQ,CAAC,CAAC,CAAC,IACtF;CACH,KAAK,MAAM,YAAY,oBAAoB;EACzC,MAAM,QAAQ,kBAAkB,WAAW,MAAM,EAAE,SAAS,SAAS,IAAI;EACzE,IAAI,UAAU,IACZ,kBAAkB,SAAS;OAE3B,kBAAkB,KAAK,QAAQ;CAEnC;CAEA,OAAO,OAAO,KAAiB,IAAI,UAAU,QAAQ,mBAAmB,IAAI,iBAAiB,IAAI,WAAW,CAAC;AAC/G;AAEA,IAAa,0BAA0B,QAAoB,eAAqC;CAC9F,OAAO,OAAO,KAAiB,UAAU,KAAK,OAAO,KAAK,UAAU,CAAC;AACvE;AAEA,IAAa,2BACX,QACA,EAAE,QAAQ,YACK;CACf,MAAM,MAAM,OAAO;CACnB,UAAU,UAAU,UAAU,GAAG,GAAA,KAAA,GAAA;EAAA,YAAA;EAAA,GAAA;EAAA,GAAA;EAAA,GAAA,KAAA;EAAA,GAAA,CAAA,4BAAA,EAAA;CAAA,CAAC;CAElC,OAAO,OAAO,KACZ,IAAI,UAAU,QACZ,IAAI,mBAAmB,KAAK,MAAO,EAAE,SAAS,SAAS,IAAI,UAAU,kBAAkB,OAAO,EAAE,IAAI,IAAI,CAAE,GAC1G,IAAI,iBACJ,IAAI,WACN,CACF;AACF;;;;AChCA,IAAa,aARY,OAAO,OAAO;CACrC,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,YAAY;AACd,CAK0B,CAAA,CAAiB,KACzC,gBAAgB,IAAI,CAAC,MAAM,CAAC,GAC5B,eAAe,IAAI;CACjB,MAAM;CACN,KAAK;AACP,CAAC,GACD,mBAAmB,iBAAiB,CACtC"}
|
|
1
|
+
{"version":3,"file":"chunk-internal.mjs","names":["__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file","__dxlog_file"],"sources":["../../src/internal/common/types/base.ts","../../src/internal/common/types/projection.ts","../../src/internal/common/types/version.ts","../../src/internal/Annotation/sorting.ts","../../src/internal/Entity/model.ts","../../src/internal/Query/pretty.ts","../../src/internal/Ref/strong-deps.ts","../../src/internal/common/proxy/json-serializer.ts","../../src/internal/common/proxy/commit-scope.ts","../../src/internal/common/proxy/event-batch.ts","../../src/internal/common/proxy/change-context.ts","../../src/internal/common/proxy/ownership.ts","../../src/internal/common/proxy/reactive-array.ts","../../src/internal/common/proxy/schema-validator.ts","../../src/internal/common/proxy/typed-handler.ts","../../src/internal/common/proxy/make-object.ts","../../src/internal/Entity/entity.ts","../../src/internal/JsonSchema/json-schema-normalize.ts","../../src/internal/Entity/object.ts","../../src/internal/Entity/relation.ts","../../src/internal/Entity/type-kind.ts","../../src/internal/Entity/version.ts","../../src/internal/common/merge.ts","../../src/internal/Obj/json-serializer.ts","../../src/internal/Filter/match.ts","../../src/internal/Obj/common.ts","../../src/internal/Obj/inspect.ts","../../src/internal/Obj/create-object.ts","../../src/internal/Obj/deleted.ts","../../src/internal/Obj/parent-annotation.ts","../../src/internal/Obj/set-value.ts","../../src/internal/Obj/snapshot.ts","../../src/internal/Obj/atoms.ts","../../src/internal/Obj/clone.ts","../../src/internal/Type/manipulation.ts","../../src/internal/Type/type-schema.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { type EntityId } from '@dxos/keys';\n\nimport { type ATTR_META, type EntityMeta } from './meta.ts';\n\n/**\n * Base type for all data objects (reactive, ECHO, and other raw objects).\n * NOTE: This describes the base type for all database objects.\n * It is stricter than `T extends {}` or `T extends object`.\n */\n// TODO(burdon): Prefer Record<string, unknown>.\nexport type AnyProperties = Record<string, any>;\n\n/**\n * Canonical type for all ECHO entities (objects and relations).\n * @depreacted Remove, use Entity.Unknown instead.\n */\n// TODO(wittjosiah): Remove. Prefer higher level types (e.g. Entity.Unknown).\nexport interface AnyEntity {\n readonly id: EntityId;\n}\n\nexport type ExcludeId<T extends AnyProperties> = Omit<T, 'id'>;\n\nexport type PropertyKey<T extends AnyProperties> = Extract<keyof ExcludeId<T>, string>;\n\n// TODO(dmaretskyi): Remove. This should be using the symbol type.\ntype WithMeta = { [ATTR_META]?: EntityMeta };\n\n/**\n * The raw object should not include the ECHO id, but may include metadata.\n */\n// `Schema.Top` leaves `Type` as `unknown`, which `ExcludeId` cannot accept; pinning it here states\n// the object-shape requirement that v3's `Schema.Schema.Type<S>` carried implicitly.\nexport const RawObject = <S extends Schema.Top & { readonly Type: AnyProperties }>(\n schema: S,\n): Schema.Codec<ExcludeId<S['Type']> & WithMeta, S['Encoded']> => {\n return Schema.make<Schema.Codec<ExcludeId<S['Type']> & WithMeta, S['Encoded']>>(SchemaAST.omit(schema.ast, ['id']));\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Types from 'effect/Types';\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\n/**\n * Brand for a query projected to a single scalar property (`Query.project`), consumed by\n * `Filter.in` to build a subquery-membership predicate — an uncorrelated\n * `col IN (SELECT property FROM ...)` semi-join. Defined in common/ (not in Query/) so\n * Filter.ts can recognize the brand without importing Query.ts as a value: Query.ts already\n * imports Filter.ts as a value, so a reverse value import would create a cycle. Both\n * Filter.ts and Query.ts import this shared leaf module instead.\n *\n * A string-literal id (not a `Symbol.for`), matching `FilterTypeId`/`QueryTypeId`/`OrderTypeId` so\n * that structurally-compatible objects can be constructed without importing this module's runtime.\n */\nexport const ProjectionTypeId = '~@dxos/echo/Query.Projection' as const;\nexport type ProjectionTypeId = typeof ProjectionTypeId;\n\n/**\n * `V` is the projected property's value type — carried only as a phantom brand (like\n * `Filter<T>`'s `[FilterTypeId]: { value: Types.Covariant<T> }`) so `Filter.in(query.project(k))`\n * infers its own type parameter from the projected property instead of defaulting to `unknown`.\n */\nexport interface Projection<V = unknown> {\n readonly [ProjectionTypeId]: { value: Types.Covariant<V> };\n readonly query: QueryAST.Query;\n readonly property: string;\n}\n\nexport const isProjection = (value: unknown): value is Projection =>\n typeof value === 'object' && value !== null && ProjectionTypeId in value;\n\nconst variance: Projection<any>[ProjectionTypeId] = {} as Projection<any>[ProjectionTypeId];\n\nexport const makeProjection = <V>(query: QueryAST.Query, property: string): Projection<V> => ({\n [ProjectionTypeId]: variance,\n query,\n property,\n});\n","//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Version type identifier.\n */\nexport const VersionTypeId = '~@dxos/echo/VersionTypeId' as const;\nexport type VersionTypeId = typeof VersionTypeId;\n\n/**\n * Represents the object version.\n * May be backed by Automerge.\n * Objects with no history are not versioned.\n */\nexport interface Version {\n [VersionTypeId]: {};\n automergeHeads?: string[];\n}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { AnyEntity } from '../common/types/index.ts';\nimport { getLabel, getTypename } from './annotations.ts';\n\n/**\n * String comparison helper for sorting.\n */\nexport const compare = (a?: string, b?: string): number => {\n if (a == null) {\n return b == null ? 0 : 1;\n }\n if (b == null) {\n return -1;\n }\n return a.localeCompare(b);\n};\n\n/**\n * Comparator function type for sorting entities.\n * Accepts both reactive entities and snapshots.\n */\nexport type Comparator<T extends AnyEntity = AnyEntity> = (a: T, b: T) => number;\n\n/**\n * Sort entities by label.\n */\nexport const sortByLabel: Comparator = (a: AnyEntity, b: AnyEntity) => compare(getLabel(a), getLabel(b));\n\n/**\n * Sort entities by typename.\n */\nexport const sortByTypename: Comparator = (a: AnyEntity, b: AnyEntity) => compare(getTypename(a), getTypename(b));\n\n/**\n * Compose multiple comparators into one.\n * Applies comparators in order until one returns non-zero.\n */\nexport const sort = <T extends AnyEntity>(...comparators: Comparator<T>[]): Comparator<T> => {\n return (a: T, b: T) => {\n for (const comparator of comparators) {\n const result = comparator(a, b);\n if (result !== 0) {\n return result;\n }\n }\n return 0;\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Schema from 'effect/Schema';\n\nimport { type ForeignKey } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport type * as Database from '../../Database.ts';\nimport {\n ATTR_DELETED,\n type ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n type ATTR_TYPE,\n EntityKind,\n FeedBlockKeysId,\n KindId,\n ObjectBranchId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ObjectVersionId,\n type ParentId,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n type SchemaId,\n SelfURIId,\n TypeId,\n type Version,\n} from '../common/types/index.ts';\nimport { type ATTR_META, type EntityMeta } from '../common/types/meta.ts';\nimport { type MetaId } from '../common/types/model-symbols.ts';\n\nexport {\n ATTR_DELETED,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n FeedBlockKeysId,\n ObjectBranchId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ObjectVersionId,\n SelfURIId,\n};\n\n/**\n * Internal runtime representation of an object.\n * The fields are accessed through getter functions.\n */\n// NOTE: Each symbol has a jsdoc describing its purpose.\nexport interface InternalObjectProps {\n readonly id: EntityId;\n readonly [SelfURIId]: EID.EID;\n readonly [KindId]: EntityKind;\n readonly [SchemaId]: Schema.Codec<any, any>;\n readonly [TypeId]: URI.URI;\n readonly [MetaId]?: EntityMeta;\n [ParentId]?: InternalObjectProps;\n readonly [ObjectDatabaseId]?: Database.Database;\n readonly [FeedBlockKeysId]?: readonly ForeignKey[];\n readonly [ObjectBranchId]?: string;\n readonly [ObjectDeletedId]?: boolean;\n readonly [ObjectVersionId]?: Version;\n readonly [RelationSourceDXNId]?: EID.EID;\n readonly [RelationTargetDXNId]?: EID.EID;\n readonly [RelationSourceId]?: InternalObjectProps;\n readonly [RelationTargetId]?: InternalObjectProps;\n}\n\n/**\n * Entity metadata.\n */\nexport interface EntityMetaJSON {\n keys: ForeignKey[];\n tags?: string[];\n key?: string;\n version?: string;\n annotations?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * JSON representation of an object or relation metadata.\n */\nexport interface ObjectJSON {\n id: EntityId;\n [ATTR_TYPE]?: URI.URI;\n [ATTR_SELF_URI]?: EID.EID;\n [ATTR_PARENT]?: EID.EID; // Encoded reference\n [ATTR_DELETED]?: boolean;\n [ATTR_META]?: EntityMetaJSON;\n [ATTR_RELATION_SOURCE]?: EID.EID;\n [ATTR_RELATION_TARGET]?: EID.EID;\n\n /**\n * Application-specific properties.\n */\n [key: string]: unknown;\n}\n\n/**\n * NOTE: Keep as `function` to avoid type inference issues.\n */\nexport function assertObjectModel(obj: unknown): asserts obj is InternalObjectProps {\n invariant(typeof obj === 'object' && obj !== null, 'Invalid object model: not an object');\n assumeType<InternalObjectProps>(obj);\n invariant(EntityId.isValid(obj.id), 'Invalid object model: invalid id');\n invariant(obj[TypeId] === undefined || typeof obj[TypeId] === 'string', 'Invalid object model: invalid type');\n invariant(\n obj[KindId] === EntityKind.Object || obj[KindId] === EntityKind.Relation || obj[KindId] === EntityKind.Type,\n 'Invalid object model: invalid entity kind',\n );\n\n if (obj[KindId] === EntityKind.Relation) {\n invariant(EID.isEID(obj[RelationSourceDXNId]), 'Invalid object model: invalid relation source');\n invariant(EID.isEID(obj[RelationTargetDXNId]), 'Invalid object model: invalid relation target');\n invariant(!EID.isEID(obj[RelationSourceId]), 'Invalid object model: source pointer is a DXN');\n invariant(!EID.isEID(obj[RelationTargetId]), 'Invalid object model: target pointer is a DXN');\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\n/**\n * Returns a human-readable string representation of a Filter AST.\n */\nexport const prettyFilter = (filter: QueryAST.Filter): string => {\n switch (filter.type) {\n case 'object': {\n // A type-less object filter with only a meta-key constraint is `Filter.key(...)`.\n if (\n filter.typename === null &&\n (filter.id === undefined || filter.id.length === 0) &&\n Object.keys(filter.props).length === 0 &&\n (filter.foreignKeys === undefined || filter.foreignKeys.length === 0) &&\n filter.metaKey !== undefined\n ) {\n return filter.metaVersion !== undefined\n ? `Filter.key(${JSON.stringify(filter.metaKey)}, { version: ${JSON.stringify(filter.metaVersion)} })`\n : `Filter.key(${JSON.stringify(filter.metaKey)})`;\n }\n const parts: string[] = [];\n if (filter.typename !== null) {\n parts.push(String(filter.typename));\n }\n if (filter.id !== undefined && filter.id.length > 0) {\n parts.push(`id: [${filter.id.join(', ')}]`);\n }\n const propEntries = Object.entries(filter.props);\n if (propEntries.length > 0) {\n const propsStr = propEntries.map(([k, v]) => `${k}: ${prettyFilter(v)}`).join(', ');\n parts.push(`{ ${propsStr} }`);\n }\n if (filter.foreignKeys !== undefined && filter.foreignKeys.length > 0) {\n parts.push(`foreignKeys: [${filter.foreignKeys.map((fk) => JSON.stringify(fk)).join(', ')}]`);\n }\n if (filter.metaKey !== undefined) {\n parts.push(\n filter.metaVersion !== undefined\n ? `metaKey: ${JSON.stringify(filter.metaKey)} (${filter.metaVersion})`\n : `metaKey: ${JSON.stringify(filter.metaKey)}`,\n );\n }\n return parts.length > 0 ? `Filter.type(${parts.join(', ')})` : 'Filter.everything()';\n }\n case 'compare':\n return `Filter.${filter.operator}(${JSON.stringify(filter.value)})`;\n case 'in':\n return `Filter.in([${filter.values.map((v) => JSON.stringify(v)).join(', ')}])`;\n case 'in-query':\n return `Filter.in(${prettyQuery(filter.subquery)}.project(${JSON.stringify(filter.property)}))`;\n case 'contains':\n return `Filter.contains(${JSON.stringify(filter.value)})`;\n case 'tag':\n return `Filter.tag(${JSON.stringify(filter.tag)})`;\n case 'annotation':\n return filter.value === undefined\n ? `Filter.annotation(${JSON.stringify(filter.key)})`\n : `Filter.annotation(${JSON.stringify(filter.key)}, ${JSON.stringify(filter.value)})`;\n case 'range':\n return `Filter.range(${JSON.stringify(filter.from)}, ${JSON.stringify(filter.to)})`;\n case 'text-search':\n return filter.searchKind\n ? `Filter.textSearch(${JSON.stringify(filter.text)}, ${JSON.stringify(filter.searchKind)})`\n : `Filter.textSearch(${JSON.stringify(filter.text)})`;\n case 'timestamp':\n return `Filter.${filter.field}.${filter.operator}(${filter.value})`;\n case 'feed-cursor':\n return `Filter.feedCursor(${JSON.stringify({ begin: filter.begin, end: filter.end, positions: filter.positions })})`;\n case 'child-of':\n return `Filter.childOf([${filter.parents.map((p) => JSON.stringify(p)).join(', ')}], { transitive: ${filter.transitive} })`;\n case 'mnemonic':\n return `Filter.mnemonic(${JSON.stringify(filter.mnemonic)})`;\n case 'changes':\n return filter.targets\n ? `Filter.changes([${filter.targets.map((target) => JSON.stringify(target)).join(', ')}])`\n : 'Filter.changes()';\n case 'has-parent':\n return `Filter.hasParent(${filter.value})`;\n case 'not':\n return `Filter.not(${prettyFilter(filter.filter)})`;\n case 'and':\n return `Filter.and(${filter.filters.map(prettyFilter).join(', ')})`;\n case 'or':\n return `Filter.or(${filter.filters.map(prettyFilter).join(', ')})`;\n }\n};\n\n/**\n * Returns a human-readable string representation of a Query AST.\n */\nexport const prettyQuery = (query: QueryAST.Query): string => {\n switch (query.type) {\n case 'select':\n return `Query.select(${prettyFilter(query.filter)})`;\n case 'filter':\n return `${prettyQuery(query.selection)}.select(${prettyFilter(query.filter)})`;\n case 'reference-traversal':\n return `${prettyQuery(query.anchor)}.reference(${JSON.stringify(query.property)})`;\n case 'incoming-references': {\n const args: string[] = [];\n if (query.typename !== null) {\n args.push(String(query.typename));\n }\n if (query.property !== null) {\n args.push(JSON.stringify(query.property));\n }\n return `${prettyQuery(query.anchor)}.referencedBy(${args.join(', ')})`;\n }\n case 'relation': {\n const method =\n query.direction === 'outgoing' ? 'sourceOf' : query.direction === 'incoming' ? 'targetOf' : 'relationOf';\n const filterStr = query.filter !== undefined ? prettyFilter(query.filter) : '';\n return `${prettyQuery(query.anchor)}.${method}(${filterStr})`;\n }\n case 'relation-traversal':\n return `${prettyQuery(query.anchor)}.${query.direction}()`;\n case 'hierarchy-traversal':\n return query.direction === 'to-parent'\n ? `${prettyQuery(query.anchor)}.parent()`\n : `${prettyQuery(query.anchor)}.children()`;\n case 'union':\n return `Query.all(${query.queries.map(prettyQuery).join(', ')})`;\n case 'set-difference':\n return `Query.without(${prettyQuery(query.source)}, ${prettyQuery(query.exclude)})`;\n case 'order': {\n const orders = query.order.map((o) => {\n if (o.kind === 'natural') {\n return `Order.natural(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'rank') {\n return `Order.rank(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'timestamp') {\n const fn = o.field === 'updatedAt' ? 'updated' : 'created';\n return `Order.${fn}(${JSON.stringify(o.direction)})`;\n } else if (o.kind === 'annotation') {\n const path = o.path !== undefined ? `, ${JSON.stringify(o.path)}` : '';\n return `Order.annotation(${JSON.stringify(o.key)}, ${JSON.stringify(o.direction)}${path})`;\n } else {\n return `Order.property(${JSON.stringify(o.property)}, ${JSON.stringify(o.direction)})`;\n }\n });\n return `${prettyQuery(query.query)}.orderBy(${orders.join(', ')})`;\n }\n case 'options': {\n const opts = query.options;\n const parts: string[] = [];\n if (opts.deleted !== undefined) {\n parts.push(`deleted: ${JSON.stringify(opts.deleted)}`);\n }\n if (opts.debugLabel !== undefined) {\n parts.push(`debugLabel: ${JSON.stringify(opts.debugLabel)}`);\n }\n return `${prettyQuery(query.query)}.options({ ${parts.join(', ')} })`;\n }\n case 'from': {\n if (query.from._tag === 'scope') {\n if (query.from.scopes.length === 0) {\n return `${prettyQuery(query.query)}.from('all-accessible-spaces')`;\n }\n const scopeStrs = query.from.scopes.map((scope) => {\n if (scope._tag === 'space') {\n return scope.includeAllFeeds\n ? `{ space: ${JSON.stringify(scope.spaceId)}, includeAllFeeds: true }`\n : `{ space: ${JSON.stringify(scope.spaceId)} }`;\n }\n if (scope._tag === 'feed') {\n const branches = scope.branches !== undefined ? `, branches: ${JSON.stringify(scope.branches)}` : '';\n return `{ feed: ${JSON.stringify(String(scope.feedUri))}${branches} }`;\n }\n return `{ registry: ${JSON.stringify(scope.location)} }`;\n });\n return `${prettyQuery(query.query)}.from([${scopeStrs.join(', ')}])`;\n }\n return `${prettyQuery(query.query)}.from(${prettyQuery(query.from.query)})`;\n }\n case 'limit':\n return `${prettyQuery(query.query)}.limit(${query.limit})`;\n case 'skip':\n return `${prettyQuery(query.query)}.skip(${query.skip})`;\n case 'aggregate': {\n const aggregates = query.aggregates.map((aggregate) => {\n return `${JSON.stringify(aggregate.name)}: Aggregate.${prettyAggregateName(aggregate)}(${prettyAggregateArg(aggregate)})`;\n });\n return `${prettyQuery(query.query)}.aggregate({ ${aggregates.join(', ')} })`;\n }\n }\n};\n\n/** The `Aggregate.*` constructor that produced an aggregate. */\nconst prettyAggregateName = (aggregate: QueryAST.GroupAggregate): string =>\n aggregate.kind === 'timestamp' ? (aggregate.field === 'updatedAt' ? 'updated' : 'created') : aggregate.kind;\n\n/** Renders one aggregate's constructor argument, mirroring the `Aggregate.*` call that produced it. */\nconst prettyAggregateArg = (aggregate: QueryAST.GroupAggregate): string => {\n switch (aggregate.kind) {\n case 'count':\n case 'type':\n return '';\n case 'timestamp':\n return JSON.stringify(aggregate.unit);\n case 'time':\n return `${JSON.stringify(aggregate.property)}, ${JSON.stringify(aggregate.unit)}`;\n case 'items':\n return aggregate.limit !== undefined ? `{ limit: ${aggregate.limit} }` : '';\n case 'group':\n return aggregate.properties.length === 1\n ? JSON.stringify(aggregate.properties[0])\n : `{ coalesce: ${JSON.stringify(aggregate.properties)} }`;\n case 'max':\n case 'min':\n case 'sum':\n return JSON.stringify(aggregate.property);\n }\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { EID, type SpaceId, type URI } from '@dxos/keys';\n\nimport { EntityKind } from '../common/types/entity.ts';\nimport { MetaId, RelationSourceDXNId, RelationTargetDXNId } from '../common/types/model-symbols.ts';\nimport { ParentId, TypeId } from '../common/types/typename.ts';\nimport { getObjectEchoUri } from '../Entity/util.ts';\n\n/**\n * Normalized view of the references that make up an entity's strong-dependency set, store-agnostic\n * so it can be filled from an {@link ObjectCore} (db) or a decoded entity (queue item / snapshot).\n */\nexport interface StrongDepRefs {\n /** Entity kind — relations additionally depend on their source/target. */\n kind: EntityKind;\n /** Type reference URI (`echo:` for a persisted stored schema, `dxn:` for a static/registry type). */\n type?: URI.URI;\n /** Relation source reference URI. */\n source?: URI.URI;\n /** Relation target reference URI. */\n target?: URI.URI;\n /** Parent reference URI. */\n parent?: URI.URI;\n /** Reference URIs of the {@link Tag}s in `meta.tags`. */\n tags?: readonly URI.URI[];\n}\n\n/**\n * Direct strong-dependency URIs of an entity: the schema (only when stored as an object), the\n * relation source/target, the parent, and the tags. Returns URIs (cross-space `echo:` EIDs and queue-item\n * EIDs included); a persisted schema is an `echo:` URI, a static/registry type is a `dxn:` URI.\n *\n * A static/registry type (`dxn:`) is intentionally NOT a strong dep: it is always synchronously\n * available through the registry, so gating on it would needlessly delay surfacing. Only a\n * persisted (db-backed) schema, addressed by an `echo:` URI, must load before its instances.\n */\nexport const getStrongDependencyUris = (refs: StrongDepRefs, owningSpaceId?: SpaceId): URI.URI[] => {\n const res: URI.URI[] = [];\n\n if (refs.type != null && EID.tryParse(refs.type) != null) {\n res.push(qualifyToSpace(refs.type, owningSpaceId));\n }\n\n if (refs.kind === EntityKind.Relation) {\n if (refs.source != null) {\n res.push(qualifyToSpace(refs.source, owningSpaceId));\n }\n if (refs.target != null) {\n res.push(qualifyToSpace(refs.target, owningSpaceId));\n }\n }\n\n if (refs.parent != null) {\n res.push(qualifyToSpace(refs.parent, owningSpaceId));\n }\n\n for (const tag of refs.tags ?? []) {\n res.push(qualifyToSpace(tag, owningSpaceId));\n }\n\n return res;\n};\n\n/**\n * Qualifies a space-less (relative) `echo:` dependency URI with the space of the entity that owns it.\n * Same-space references are persisted relative; resolution needs them absolute to route to a single\n * space. Already-qualified URIs (cross-space) and non-`echo:` URIs (registry `dxn:`) pass through.\n */\nconst qualifyToSpace = (uri: URI.URI, owningSpaceId: SpaceId | undefined): URI.URI => {\n if (owningSpaceId == null) {\n return uri;\n }\n const eid = EID.tryParse(uri);\n if (eid == null || !EID.isLocal(eid)) {\n return uri;\n }\n const entityId = EID.getEntityId(eid);\n return entityId != null ? EID.make({ spaceId: owningSpaceId, entityId }) : uri;\n};\n\n/** URIs of the tags a decoded entity's meta holds, which are resolved entities like its parent. */\nconst getTagUris = (meta: unknown): URI.URI[] => {\n const tags = meta != null && typeof meta === 'object' ? Reflect.get(meta, 'tags') : undefined;\n if (!Array.isArray(tags)) {\n return [];\n }\n return tags.flatMap((tag) => {\n const uri = getObjectEchoUri(tag);\n return uri != null ? [uri] : [];\n });\n};\n\n/**\n * Direct strong-dependency URIs of a live (decoded) entity — a queue item, cross-space proxy, or\n * snapshot. Reads the reference URIs off the entity's hidden model symbols. ECHO db cores compute\n * the same set from their raw encoded references via {@link getStrongDependencyUris}.\n */\nexport const getStrongDependencies = (entity: unknown): URI.URI[] => {\n if (entity == null || typeof entity !== 'object') {\n return [];\n }\n const props = entity as Record<symbol, unknown>;\n const kind =\n props[RelationSourceDXNId] != null || props[RelationTargetDXNId] != null ? EntityKind.Relation : EntityKind.Object;\n const parent = props[ParentId];\n\n // The entity's own space qualifies any relative dependency URIs it carries.\n const selfUri = getObjectEchoUri(entity);\n const owningSpaceId = selfUri != null ? EID.getSpaceId(selfUri) : undefined;\n\n return getStrongDependencyUris(\n {\n kind,\n type: typeof props[TypeId] === 'string' ? (props[TypeId] as URI.URI) : undefined,\n source: props[RelationSourceDXNId] as URI.URI | undefined,\n target: props[RelationTargetDXNId] as URI.URI | undefined,\n // A parent is held as the resolved entity; derive its absolute URI for the dependency edge.\n parent: parent != null ? getObjectEchoUri(parent) : undefined,\n tags: getTagUris(props[MetaId]),\n },\n owningSpaceId,\n );\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { EID } from '@dxos/keys';\nimport { deepMapValues, encodeUint8ArrayToJson } from '@dxos/util';\n\nimport { Ref } from '../../Ref/index.ts';\nimport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_TYPE,\n RelationSourceDXNId,\n RelationTargetDXNId,\n SelfURIId,\n TypeId,\n} from '../types/index.ts';\nimport { ATTR_META, type EntityMeta } from '../types/meta.ts';\nimport { ATTR_DELETED, MetaId, ObjectDeletedId } from '../types/model-symbols.ts';\n\n/**\n * Attaches a toJSON method to the object for typed serialization.\n */\nexport const attachTypedJsonSerializer = (obj: any) => {\n const descriptor = Object.getOwnPropertyDescriptor(obj, 'toJSON');\n if (descriptor) {\n return;\n }\n\n Object.defineProperty(obj, 'toJSON', {\n value: typedJsonSerializer,\n writable: false,\n enumerable: false,\n // Setting `configurable` to false breaks proxy invariants, should be fixable.\n configurable: true,\n });\n};\n\n// NOTE: KEEP as function.\n// Exported for use in objectToJSON.\nexport const typedJsonSerializer = function (this: any) {\n const { id, ...rest } = this;\n const result: any = {\n id,\n };\n\n if (this[TypeId]) {\n result[ATTR_TYPE] = this[TypeId];\n }\n\n if (this[MetaId]) {\n result[ATTR_META] = serializeMeta(this[MetaId]);\n }\n\n if (this[SelfURIId]) {\n result[ATTR_SELF_URI] = this[SelfURIId];\n }\n\n // Emitted only when set, mirroring `objectFromJSON`'s `=== true` read: without it a tombstone\n // snapshot round-tripped through JSON came back as a live object.\n if (this[ObjectDeletedId]) {\n result[ATTR_DELETED] = true;\n }\n\n if (this[RelationSourceDXNId]) {\n const sourceDXN = this[RelationSourceDXNId];\n invariant(EID.isEID(sourceDXN));\n result[ATTR_RELATION_SOURCE] = sourceDXN;\n }\n if (this[RelationTargetDXNId]) {\n const targetDXN = this[RelationTargetDXNId];\n invariant(EID.isEID(targetDXN));\n result[ATTR_RELATION_TARGET] = targetDXN;\n }\n\n Object.assign(result, serializeData(rest));\n return result;\n};\n\nconst serializeData = (data: unknown) => {\n return deepMapValues(data, (value, recurse) => {\n if (Ref.isRef(value)) {\n // TODO(dmaretskyi): Should this be configurable?\n return value.noInline().encode();\n }\n if (value instanceof Uint8Array) {\n return encodeUint8ArrayToJson(value);\n }\n\n return recurse(value);\n });\n};\n\nconst serializeMeta = (meta: EntityMeta) => {\n // Omit empty `tags`/`annotations` to keep serialized output minimal; `objectFromJSON` backfills\n // the required defaults on read.\n const { tags, annotations, ...rest } = meta;\n const compact = {\n ...rest,\n // Tags are entities held by identity; they serialize as references, like relation endpoints.\n ...(tags != null && tags.length > 0 ? { tags: tags.map((tag) => Ref.make(tag)) } : {}),\n ...(annotations != null && Object.keys(annotations).length > 0 ? { annotations } : {}),\n };\n // Use `serializeData` so the tag refs encode to the on-wire reference form.\n return serializeData(compact);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\n/**\n * Commit scope: groups the synchronous document writes of one user-level mutation (an `Obj.update`, a\n * `db.add`, a single property write) into one commit, and runs post-commit callbacks once the outermost\n * commit has ended.\n *\n * Post-commit callbacks run after every document semaphore is released and every change event has been\n * delivered, but before the writing call returns. That is the one point where a subscriber may observe\n * the committed state and write again without re-entering a document change.\n */\n\nlet depth = 0;\nlet draining = false;\nconst pending = new Set<() => void>();\n\n/**\n * Opens a commit. Returns the function that closes it; closing the outermost commit drains the\n * post-commit queue.\n */\nexport const beginCommit = (): (() => void) => {\n depth++;\n let ended = false;\n return () => {\n if (ended) {\n return;\n }\n ended = true;\n depth--;\n if (depth === 0) {\n drainCommitQueue();\n }\n };\n};\n\n/** Runs `body` as one commit. */\nexport const runInCommit = <T>(body: () => T): T => {\n const endCommit = beginCommit();\n try {\n return body();\n } finally {\n endCommit();\n }\n};\n\n/**\n * Requests `callback` after the current outermost commit. Outside any commit it runs at once. A callback\n * requested several times before the drain runs once, so it must read its own pending state.\n */\nexport const afterCommit = (callback: () => void): void => {\n pending.add(callback);\n if (depth === 0) {\n drainCommitQueue();\n }\n};\n\nconst drainCommitQueue = (): void => {\n // A write made by a callback ends its own commit inside this loop; its callbacks join the queue and run\n // in a later round, after every callback of the current round has seen the earlier commit.\n if (draining) {\n return;\n }\n draining = true;\n try {\n while (pending.size > 0) {\n const round = [...pending];\n pending.clear();\n for (const callback of round) {\n try {\n callback();\n } catch (error) {\n // The write has committed; a failing subscriber must not make the writer's call throw, and must\n // not stop the callbacks after it. Rethrown outside the commit so it still surfaces as unhandled.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n } finally {\n draining = false;\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { EventId } from './symbols.ts';\n\n/**\n * Simple batching mechanism for EventId emissions.\n * When batch depth > 0, events are collected instead of emitted immediately.\n * When batch depth returns to 0, pending events are emitted.\n */\nlet eventBatchDepth = 0;\nconst pendingEventTargets = new Set<object>();\n\n/**\n * Run a callback in a batched context for EventId emissions.\n * Multiple mutations within the batch will only emit one event per target.\n */\nexport const batchEvents = (callback: () => void): void => {\n eventBatchDepth++;\n try {\n callback();\n } finally {\n eventBatchDepth--;\n if (eventBatchDepth === 0) {\n // Emit pending events.\n for (const target of pendingEventTargets) {\n (target as any)[EventId]?.emit();\n }\n pendingEventTargets.clear();\n }\n }\n};\n\n/**\n * Emit an event on a target, respecting batching.\n */\nexport const emitEvent = (target: object): void => {\n if (eventBatchDepth > 0) {\n pendingEventTargets.add(target);\n } else {\n (target as any)[EventId]?.emit();\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { beginCommit } from './commit-scope.ts';\nimport { batchEvents } from './event-batch.ts';\nimport { getMutableProxy } from './proxy-utils.ts';\nimport { ChangeKeyId, EventId } from './symbols.ts';\n\n/**\n * Generic change context tracking.\n * Only one object can be in a change context at a time (synchronous changes).\n *\n * This module provides a unified change context mechanism used by both:\n * - TypedReactiveHandler (for non-database objects, using target as key)\n * - EchoReactiveHandler (for database objects, using ObjectCore as key)\n */\n\n/**\n * The object currently in a change context.\n * Can be a target object (for typed reactive) or ObjectCore (for database objects).\n */\nlet currentChangeContext: object | null = null;\n\n/**\n * The primary object that has pending notifications, if any.\n * This uses the contextKey (target or ObjectCore).\n */\nlet pendingNotificationKey: object | null = null;\n\n/**\n * Additional objects (owner chain) that need notifications.\n * These are separate from the primary notification because they use EventId directly.\n */\nconst pendingOwnerNotifications = new Set<object>();\n\n/**\n * Enter a change context for the given key.\n * While in a change context, mutations are allowed on the associated object.\n * Nested Obj.update calls are not supported.\n *\n * @param key - The key to enter the change context for (target object or ObjectCore).\n * @returns A cleanup function that exits the change context.\n */\nexport const enterChangeContext = (key: object): (() => void) => {\n currentChangeContext = key;\n return () => {\n currentChangeContext = null;\n };\n};\n\n/**\n * Check if the given key is currently in a change context.\n *\n * @param key - The key to check (target object or ObjectCore).\n * @returns True if the key is in a change context, false otherwise.\n */\nexport const isInChangeContext = (key: object): boolean => {\n return currentChangeContext === key;\n};\n\n/**\n * Whether any object is in a change context; only one can be at a time, so a change entered now would end it.\n */\nexport const isAnyChangeContextActive = (): boolean => currentChangeContext !== null;\n\n/**\n * Queue a notification for the given key to be fired when the change context exits.\n *\n * @param key - The key to queue a notification for.\n */\nexport const queueNotification = (key: object): void => {\n if (currentChangeContext === key) {\n pendingNotificationKey = key;\n }\n};\n\n/**\n * Queue an owner notification. Owner notifications are for objects in the ownership\n * chain that should be notified when a nested object changes.\n * These objects have EventId and emit directly.\n * Skip if the target is already the current change context (to avoid duplicate notifications).\n *\n * @param target - The owner target that has EventId.\n */\nexport const queueOwnerNotification = (target: object): void => {\n // Skip if this is the object already being changed (primary notification handles it).\n if (currentChangeContext !== null && target !== currentChangeContext) {\n pendingOwnerNotifications.add(target);\n }\n};\n\n/**\n * Check if there are any pending notifications for the given key.\n *\n * @param key - The key to check.\n * @returns True if there are pending notifications, false otherwise.\n */\nexport const hasPendingNotifications = (key: object): boolean => {\n return pendingNotificationKey === key;\n};\n\n/**\n * Clear any pending notifications for the given key.\n *\n * @param key - The key to clear notifications for.\n */\nexport const clearPendingNotifications = (key: object): void => {\n if (pendingNotificationKey === key) {\n pendingNotificationKey = null;\n }\n};\n\n/**\n * Execute a callback within a change context.\n * This is the shared implementation used by both TypedReactiveHandler and EchoReactiveHandler.\n *\n * @param contextKey - The key for the change context (target for typed, ObjectCore for db).\n * @param eventTarget - The object that has the EventId for notifications.\n * @param proxy - The proxy object to pass to the callback.\n * @param callback - The callback to execute with mutations allowed.\n */\nexport const executeChange = (\n contextKey: object,\n eventTarget: object,\n proxy: any,\n callback: (proxy: any) => void,\n): void => {\n // One commit for the whole callback: a subscriber must never observe the state between two of its writes.\n const endCommit = beginCommit();\n try {\n const exitContext = enterChangeContext(contextKey);\n try {\n // The callback is handed the mutable view, not `proxy`: writability travels with the reference, so\n // the object named outside stays read-only even while this runs. The context is still entered —\n // it is what batches notifications and what the array and text gates read.\n batchEvents(() => callback(getMutableProxy(proxy)));\n } finally {\n exitContext();\n // Fire the primary notification (a real change).\n if (hasPendingNotifications(contextKey)) {\n clearPendingNotifications(contextKey);\n (eventTarget as any)[EventId]?.emit();\n }\n // Fire owner chain notifications.\n for (const ownerTarget of pendingOwnerNotifications) {\n (ownerTarget as any)[EventId]?.emit();\n }\n pendingOwnerNotifications.clear();\n }\n } finally {\n endCommit();\n }\n};\n\n/**\n * The read-only gate, and the whole of it — every variant is gated here and nowhere else. A symbol is\n * never user data (the system stamps `[ParentId]` and friends outside any change context), and a target\n * whose `[ChangeKeyId]` is undefined is still under construction and not yet gated. Everything else may\n * only be mutated inside the `Obj.update` that opened a context for *this* object.\n *\n * No dispatch: the key comes from the target's behaviour prototype, so nothing here knows or cares which\n * variant it is looking at. Lives here rather than beside the proxy handler because it needs the change\n * context, and the handler module must not depend on this one.\n *\n * `name` is the property for a trap and the method name for a mutation a proxy cannot intercept (an\n * array method, a text CRDT op), which call this directly — the same predicate either way.\n */\nexport const assertMutable = <T extends string | symbol>(\n target: object,\n name: T,\n createError: (name: T) => Error,\n): void => {\n if (typeof name === 'symbol') {\n return;\n }\n const changeKey: object | undefined = Reflect.get(target, ChangeKeyId);\n if (changeKey !== undefined && !isInChangeContext(changeKey)) {\n throw createError(name);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { KindId } from '../types/index.ts';\nimport { queueOwnerNotification } from './change-context.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { getProxyTarget, isProxy, isValidProxyTarget } from './proxy-utils.ts';\nimport { EntityElementsId, EventId } from './symbols.ts';\n\n/**\n * Symbol to store the owning ECHO object reference on nested JS objects (records).\n * Every nested record is attributed to exactly one ECHO object.\n * This achieves:\n * - No cycles in the object graph (cyclical Refs are still allowed).\n * - No multiple inbound pointers to one record.\n * - Centralized reactivity for entire ECHO object.\n */\nconst EchoOwner = Symbol.for('@dxos/echo/Owner');\n\n/**\n * Whether the array holds root entities by identity (see {@link EntityElementsId}); its elements are\n * never owned, copied or walked as nested data.\n */\nexport const hasEntityElements = (value: unknown): boolean =>\n Array.isArray(value) && Reflect.get(value, EntityElementsId) === true;\n\n/**\n * Get the raw target from a value, unwrapping proxy if needed.\n */\nexport const getRawTarget = (value: any): any => {\n return isProxy(value) ? getProxyTarget(value) : value;\n};\n\n/**\n * Get the ECHO object that owns this nested record.\n *\n * The owner is always the raw target object (not a proxy) of the root ECHO object.\n * For example, if you have `echoObject.nested.deep`, both `nested` and `deep`\n * will have their owner set to the raw target of `echoObject`.\n *\n * @param value - The nested record to check (can be a proxy or raw target).\n * @returns The raw target of the owning root ECHO object, or undefined if not owned.\n */\nexport const getOwner = (value: object | null | undefined): object | undefined => {\n return (value as any)?.[EchoOwner];\n};\n\n/**\n * Set the owner of a meta object to its parent.\n * This allows meta mutations to respect the parent's change context.\n * @internal\n */\nexport const setMetaOwner = (metaTarget: object, parent: object): void => {\n defineHiddenProperty(metaTarget, EchoOwner, parent);\n};\n\n/**\n * Set the ECHO object owner on a value and all its nested records.\n * All nested JS objects point directly to the root ECHO object.\n *\n * @param value - The value to set ownership on (can be a proxy or raw target).\n * @param owner - The raw target of the root ECHO object that will own this value.\n * @param options.visited - Set of already-visited objects to avoid infinite loops.\n * @param options.depth - Current recursion depth (unused, kept for debugging).\n * @param options.allowedPreviousOwner - When reassigning a root ECHO object, its nested structures\n * are allowed to have this as their previous owner without triggering the invariant.\n */\nexport const setOwnerRecursive = (\n value: any,\n owner: object,\n options: {\n visited?: Set<object>;\n depth?: number;\n allowedPreviousOwner?: object;\n } = {},\n): void => {\n const { visited = new Set<object>(), depth = 0, allowedPreviousOwner } = options;\n if (value == null || typeof value !== 'object') {\n return;\n }\n\n const actualValue = getRawTarget(value);\n if (visited.has(actualValue)) {\n return;\n }\n visited.add(actualValue);\n\n // Check that we're not stealing a nested record owned by a different ECHO object.\n // Root ECHO objects (those with EventId) can be reassigned - they maintain their own\n // identity and choosing to embed them in another object is a valid operation.\n // When reassigning a root, its nested records (owned by that root) are also allowed.\n const existingOwner = getOwner(actualValue);\n const isRootEchoObject = EventId in actualValue;\n\n // Track if this is a root being assigned - its nested structures are allowed to transfer.\n let newAllowedPreviousOwner = allowedPreviousOwner;\n if (isRootEchoObject && depth === 0) {\n // This is the top-level root being assigned; allow its nested structures to transfer.\n newAllowedPreviousOwner = actualValue;\n }\n\n if (!isRootEchoObject) {\n const ownershipAllowed =\n existingOwner == null || existingOwner === owner || existingOwner === newAllowedPreviousOwner;\n invariant(\n ownershipAllowed,\n 'Cannot reassign ownership of a nested record to a different ECHO object. Use deep copy first.',\n );\n }\n\n // Set owner directly to the root ECHO object.\n defineHiddenProperty(actualValue, EchoOwner, owner);\n\n // Recursively set owner on nested objects and array elements.\n const recursiveOptions = {\n visited,\n depth: depth + 1,\n allowedPreviousOwner: newAllowedPreviousOwner,\n };\n if (hasEntityElements(actualValue)) {\n return;\n }\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (isValidProxyTarget(item) || isProxy(item)) {\n setOwnerRecursive(item, owner, recursiveOptions);\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n const nested = actualValue[key];\n if (isValidProxyTarget(nested) || isProxy(nested)) {\n setOwnerRecursive(nested, owner, recursiveOptions);\n }\n }\n }\n }\n};\n\n/**\n * Traverse an object graph, calling the visitor on each object.\n * Handles proxy unwrapping and cycle detection.\n *\n * @param value - The value to traverse (can be a proxy or raw target).\n * @param visitor - Called for each object. Return true to stop traversal (early exit).\n * @returns true if the visitor returns true for any object.\n */\nexport const traverseObjectGraph = (\n value: any,\n visitor: (actualValue: any) => boolean,\n visited = new Set<object>(),\n): boolean => {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n\n const actualValue = getRawTarget(value);\n\n if (visited.has(actualValue)) {\n return false;\n }\n visited.add(actualValue);\n\n if (visitor(actualValue)) {\n return true;\n }\n\n if (hasEntityElements(actualValue)) {\n return false;\n }\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (traverseObjectGraph(item, visitor, visited)) {\n return true;\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n if (traverseObjectGraph(actualValue[key], visitor, visited)) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Check if a value would create a cycle when assigned to a target ECHO object.\n * Returns true if the value (or any nested object) IS the target root.\n */\nexport const wouldCreateCycle = (targetRoot: object, value: any): boolean =>\n traverseObjectGraph(value, (v) => v === targetRoot);\n\n/**\n * Check if a value or any of its nested objects has an owner different from the target.\n * Used to determine if deep copy is needed during init.\n */\nexport const hasForeignOwner = (value: any, target: object): boolean =>\n traverseObjectGraph(value, (v) => {\n const owner = getOwner(v);\n if (owner != null && owner !== target) {\n return true;\n }\n // Root ECHO objects (with EventId) have their nested structures owned by them.\n if (EventId in v && v !== target) {\n return true;\n }\n return false;\n });\n\n/**\n * Maximum depth for owner chain traversal.\n * This is a defensive measure against malformed circular ownership.\n * Primary cycle detection is handled by wouldCreateCycle() before assignment.\n */\nconst MAX_OWNER_DEPTH = 100;\n\n/**\n * Get the root ECHO object for a target.\n * Follows the owner chain to find the ultimate root.\n * An object may have EventId (from being created standalone) but if it now\n * has an owner, it's nested and we should use its owner's root instead.\n * @internal\n */\nexport const getEchoRoot = (target: object, depth = 0): object => {\n invariant(depth < MAX_OWNER_DEPTH, 'Owner chain too deep - possible circular ownership');\n\n // Root ECHO objects (those created with Obj.make or Relation.make) have KindId set.\n // They maintain their own change context identity even when nested inside another object.\n // Nested helper objects like EntityMeta don't have KindId and should follow their owner.\n if (KindId in target) {\n return target;\n }\n\n // For non-root objects (nested records, EntityMeta, etc.), follow the owner chain.\n const owner = getOwner(target);\n if (owner) {\n return getEchoRoot(owner, depth + 1);\n }\n\n // No owner means this is an unowned object (e.g., during initialization).\n return target;\n};\n\n/**\n * The in-memory variant's read-only gate key (see `assertMutable`): the root target that a change\n * context is opened against, or `undefined` while the root does not yet own an `[EventId]` — an object\n * under construction is not gated, which is what lets `init` fill it before any context exists.\n *\n * Every target of one object answers the same key, so a nested record and an array are gated by the\n * context their root opens.\n */\nexport const changeKeyOf = (target: object): object | undefined => {\n const root = getEchoRoot(getRawTarget(target));\n return EventId in root ? root : undefined;\n};\n\n/**\n * Notify all owners in the ownership chain.\n * When a nested object changes, its parent should also be notified.\n * This handles the case where a root ECHO object is nested inside another object.\n */\nexport const notifyOwnerChain = (target: object): void => {\n const owner = getOwner(target);\n if (owner) {\n // Queue notification for the owner's root (which has EventId).\n queueOwnerNotification(getEchoRoot(owner));\n // Continue up the chain (owner might also be nested).\n notifyOwnerChain(owner);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { assertMutable } from './change-context.ts';\nimport { createArrayMethodError } from './errors.ts';\nimport { batchEvents } from './event-batch.ts';\nimport { changeKeyOf } from './ownership.ts';\nimport { canonicalOf } from './proxy-utils.ts';\nimport { ChangeKeyId } from './symbols.ts';\n\n/**\n * Extends the native array to make sure that arrays methods are correctly reactive.\n * Enforces that mutations only happen within Obj.update() context.\n */\nexport class ReactiveArray<T> extends Array<T> {\n static override get [Symbol.species]() {\n return Array;\n }\n\n /**\n * The read-only gate's key. An array keeps this prototype chain rather than being compacted onto the\n * record behaviour prototype, so it answers for itself; the key is the same root the record holding\n * it is gated by.\n */\n get [ChangeKeyId](): object | undefined {\n return changeKeyOf(this);\n }\n\n static {\n /**\n * These methods will trigger proxy traps like `set` and `defineProperty` and emit event notifications.\n * We wrap them in a batch to avoid unnecessary event notifications.\n * Change context is checked before allowing mutations.\n *\n * Note: When called on a proxy, `this` will be the proxy, so array mutations\n * go through the proxy's set trap which handles event emission.\n */\n const BATCHED_METHODS = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const;\n\n for (const method of BATCHED_METHODS) {\n Object.defineProperty(this.prototype, method, {\n enumerable: false,\n value: function (this: ReactiveArray<any>, ...args: any[]) {\n // A method call is invisible to the proxy, so it runs the same gate the traps run.\n assertMutable(this, method, createArrayMethodError);\n\n let result!: any;\n batchEvents(() => {\n result = Array.prototype[method].apply(this, args);\n });\n // `sort`/`reverse` answer the receiver. Inside `Obj.update` that is the mutable view, which is\n // callback-scoped: hand back the array's canonical identity so `arr.sort() === arr` holds.\n return result === this ? canonicalOf(this) : result;\n },\n });\n }\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaIssue from 'effect/SchemaIssue';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { invariant } from '@dxos/invariant';\n\nimport { SchemaAstId, SchemaId } from '../types/index.ts';\nimport { EntityValueAnnotationId } from './symbols.ts';\n\n// TODO(burdon): Reconcile with @dxos/effect visit().\n\n/** Formats v4 schema issues; the thrown validation error carries the issue as its `cause`. */\nconst formatIssue = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/**\n * Asserts a value against a schema, naming the offending field.\n *\n * v4's `Schema.asserts` throws the fixed message \"Schema validation failed\" and puts the detail on\n * the error's `cause`, which leaves nothing actionable in a stack trace or a UI toast. `basePath` is\n * where `value` sits in its object, for a caller that validates one property's value on its own.\n */\nexport const assertsWithDetail = (schema: Schema.Top, value: unknown, basePath: readonly PropertyKey[] = []): void => {\n try {\n Schema.asserts(schema, value);\n } catch (err) {\n const issue = err instanceof Error ? err.cause : undefined;\n if (!SchemaIssue.isIssue(issue)) {\n throw err;\n }\n const detail = formatIssue(issue)\n .issues.map(({ message, path = [] }) => {\n const fullPath = [...basePath, ...path];\n return fullPath.length > 0 ? `${fullPath.map(String).join('.')}: ${message}` : message;\n })\n .join('; ');\n throw new Error(detail.length > 0 ? `Schema validation failed — ${detail}` : 'Schema validation failed', {\n cause: issue,\n });\n }\n};\n\nexport class SchemaValidator {\n /**\n * Recursively check that schema specifies constructions we can handle.\n * Validates there are no ambiguous discriminated union types.\n */\n public static validateSchema(schema: Schema.Top): void {\n validateAst(schema.ast);\n }\n\n public static hasTypeAnnotation(rootObjectSchema: Schema.Top, property: string, annotation: string): boolean {\n try {\n let type = this.getPropertySchema(rootObjectSchema, [property]);\n if (SchemaAST.isArrays(type.ast)) {\n type = this.getPropertySchema(rootObjectSchema, [property, '0']);\n }\n\n return SchemaAST.getAnnotation(type.ast, annotation) != null;\n } catch {\n return false;\n }\n }\n\n public static getPropertySchema(\n rootObjectSchema: Schema.Top,\n propertyPath: KeyPath,\n getProperty: (path: KeyPath) => any = () => null,\n ): Schema.Top {\n const ast = this.getPropertyAstChain(rootObjectSchema, propertyPath, getProperty).at(-1) ?? rootObjectSchema.ast;\n return ast === rootObjectSchema.ast ? rootObjectSchema : Schema.make<Schema.Top>(ast);\n }\n\n /**\n * The AST of every property along `propertyPath`, outermost first (one per path segment), so a caller\n * can find an annotation set on an enclosing field rather than on the written leaf.\n */\n public static getPropertyAstChain(\n rootObjectSchema: Schema.Top,\n propertyPath: KeyPath,\n getProperty: (path: KeyPath) => any = () => null,\n ): SchemaAST.AST[] {\n const chain: SchemaAST.AST[] = [];\n let ast = rootObjectSchema.ast;\n for (let i = 0; i < propertyPath.length; i++) {\n const propertyName = propertyPath[i];\n const tupleAst = unwrapArray(ast);\n if (tupleAst != null) {\n ast = getArrayElementAst(tupleAst, propertyName);\n } else {\n const propertyType = getPropertyType(ast, propertyName.toString(), (propertyName) =>\n getProperty([...propertyPath.slice(0, i), propertyName]),\n );\n if (propertyType != null) {\n ast = propertyType;\n } else {\n const indexSignatureType = getIndexSignatureValueType(ast);\n if (indexSignatureType == null) {\n throw new TypeError(`Unknown property: ${formatPropertyPath([...propertyPath.slice(0, i), propertyName])}`);\n }\n ast = indexSignatureType;\n }\n }\n chain.push(ast);\n }\n\n return chain;\n }\n\n /**\n * Rejects properties not declared on the schema. Types with index signatures allow extra keys.\n */\n public static assertExactProperties(\n ast: SchemaAST.AST,\n value: unknown,\n getProperty: (path: KeyPath) => unknown = () => undefined,\n path: KeyPath = [],\n ): void {\n if (!isPlainRecord(value)) {\n return;\n }\n\n const typeLiteral = resolveTypeLiteral(ast, (propertyName) => getProperty([...path, propertyName]));\n if (typeLiteral == null) {\n return;\n }\n\n const propertySignatures = SchemaAST.getPropertySignatures(typeLiteral);\n const allowedKeys = new Set(propertySignatures.map((property) => String(property.name)));\n const indexSignatureType = typeLiteral.indexSignatures[0]?.type;\n\n for (const key of Object.keys(value)) {\n const propertyPath = [...path, key];\n if (!allowedKeys.has(key)) {\n if (indexSignatureType == null) {\n throw new TypeError(`Unknown property: ${formatPropertyPath(propertyPath)}`);\n }\n\n this.assertExactProperties(indexSignatureType, value[key], getProperty, propertyPath);\n continue;\n }\n\n const propertySignature = propertySignatures.find((property) => String(property.name) === key);\n invariant(propertySignature, 'Property signature must exist.');\n this.assertExactProperties(propertySignature.type, value[key], getProperty, propertyPath);\n }\n }\n\n public static getIndexedElementAst(ast: SchemaAST.AST, index: number | string): SchemaAST.AST | null {\n const arrayAst = unwrapArray(ast);\n if (arrayAst != null) {\n return getArrayElementAst(arrayAst, index);\n }\n\n const unionAst = unwrapAst(\n ast,\n (candidate) => SchemaAST.isUnion(candidate) && candidate.types.some((member) => unwrapArray(member) != null),\n );\n if (unionAst != null && SchemaAST.isUnion(unionAst)) {\n for (const member of unionAst.types) {\n const memberArrayAst = unwrapArray(member);\n if (memberArrayAst != null) {\n return getArrayElementAst(memberArrayAst, index);\n }\n }\n }\n\n return null;\n }\n\n /**\n * Whether the property may be cleared.\n *\n * v4 records optionality as `context.isOptional` on the property's own type rather than widening\n * it to `T | undefined`, so the property's schema alone no longer admits `undefined`.\n */\n public static isOptionalProperty(target: any, prop: string | symbol): boolean {\n const ast = getTargetAst(target);\n if (!ast || typeof prop === 'symbol') {\n return false;\n }\n const property = SchemaAST.getPropertySignatures(ast).find((candidate) => candidate.name === prop);\n return property != null && SchemaAST.isOptional(property.type);\n }\n\n /** What writing `undefined` at `propertyPath` deletes: an optional key, a union member's tag, or a key validated as a value. */\n public static getClearedKey(\n rootObjectSchema: Schema.Top,\n propertyPath: KeyPath,\n getProperty: (path: KeyPath) => unknown,\n ): 'optional' | 'union-tag' | 'other' {\n const propertyName = propertyPath.at(-1);\n if (propertyName === undefined) {\n return 'other';\n }\n const parentPath = propertyPath.slice(0, -1);\n const parentAst =\n this.getPropertyAstChain(rootObjectSchema, parentPath, getProperty).at(-1) ?? rootObjectSchema.ast;\n const property = getPropertySignature(parentAst, propertyName.toString(), (name) =>\n getProperty([...parentPath, name]),\n );\n if (property == null) {\n return 'other';\n }\n if (isUnionTag(parentAst, property.name)) {\n return 'union-tag';\n }\n return SchemaAST.isOptional(property.type) ? 'optional' : 'other';\n }\n\n /** The AST that property `prop` of a typed target follows. */\n public static getTargetPropertyAst(target: any, prop: string | symbol): SchemaAST.AST {\n const ast = getTargetAst(target);\n invariant(ast, 'target has no schema');\n\n if (Array.isArray(target)) {\n if (prop === 'length') {\n return Schema.Number.ast;\n }\n\n if (typeof prop !== 'symbol') {\n const indexedAst = this.getIndexedElementAst(ast, prop);\n if (indexedAst != null) {\n return indexedAst;\n }\n }\n\n // Arrays sometimes carry the element struct as their stamped schema.\n if (SchemaAST.isObjects(ast)) {\n return ast;\n }\n }\n\n if (typeof prop === 'number' || (typeof prop === 'string' && /^\\d+$/.test(prop))) {\n const indexedAst = this.getIndexedElementAst(ast, prop);\n if (indexedAst != null) {\n return indexedAst;\n }\n }\n\n const arrayAst = unwrapArray(ast);\n if (arrayAst != null) {\n return getArrayElementAst(arrayAst, prop);\n }\n\n const propertyType = getPropertyType(ast, prop.toString(), (prop) => target[prop]);\n if (propertyType == null) {\n const indexSignatureType = getIndexSignatureValueType(ast);\n if (indexSignatureType != null) {\n return indexSignatureType;\n }\n\n throw new TypeError(`Unknown property: ${String(prop)}`);\n }\n\n return propertyType;\n }\n}\n\n/** A root carries its schema; a nested value carries only its AST (see {@link SchemaAstId}). */\nconst getTargetAst = (target: any): SchemaAST.AST | undefined =>\n target[SchemaAstId] ?? (target[SchemaId] as Schema.Top | undefined)?.ast;\n\nconst validateAst = (ast: SchemaAST.AST): void => {\n if (SchemaAST.isUnion(ast)) {\n const typeAstList = ast.types.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n // Check we can handle a discriminated union.\n if (typeAstList.length > 1) {\n getTypeDiscriminators(typeAstList);\n }\n typeAstList.forEach(validateAst);\n } else if (SchemaAST.isArrays(ast)) {\n [...ast.elements, ...ast.rest].forEach(validateAst);\n } else if (SchemaAST.isObjects(ast)) {\n SchemaAST.getPropertySignatures(ast).forEach((property) => validateAst(property.type));\n }\n};\n\n/**\n * Tuple AST is used both for:\n * fixed-length tuples ([string, number]) in which case AST will be { elements: [Schema.String, Schema.Number] }\n * variable-length arrays (Array<string | number>) in which case AST will be { rest: [Schema.Union([Schema.String, Schema.Number])] }\n */\nconst getArrayElementAst = (tupleAst: SchemaAST.Arrays, property: string | symbol | number): SchemaAST.AST => {\n const elementIndex =\n typeof property === 'number' ? property : typeof property === 'string' ? parseInt(property, 10) : Number.NaN;\n if (Number.isNaN(elementIndex)) {\n invariant(property === 'length', `invalid array property: ${String(property)}`);\n return Schema.Number.ast;\n }\n if (elementIndex < tupleAst.elements.length) {\n return tupleAst.elements[elementIndex];\n }\n\n return tupleAst.rest[0];\n};\n\nconst flattenUnion = (typeAst: SchemaAST.AST): SchemaAST.AST[] =>\n SchemaAST.isUnion(typeAst) ? typeAst.types.flatMap(flattenUnion) : [typeAst];\n\nconst getProperties = (\n typeAst: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => any,\n): ReadonlyArray<SchemaAST.PropertySignature> => {\n const astCandidates = flattenUnion(typeAst);\n const typeAstList = astCandidates.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n if (typeAstList.length === 0) {\n return [];\n }\n if (typeAstList.length === 1) {\n return SchemaAST.getPropertySignatures(typeAstList[0]);\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = selectMember(typeDiscriminators, targetPropertyValue);\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return SchemaAST.getPropertySignatures(typeAstList[typeIndex]);\n};\n\nconst getPropertyType = (\n ast: SchemaAST.AST,\n propertyName: string,\n getTargetPropertyFn: (propertyName: string) => any,\n): SchemaAST.AST | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return ast;\n }\n\n const targetProperty = getPropertySignature(ast, propertyName, getTargetPropertyFn);\n if (targetProperty != null) {\n return unwrapAst(targetProperty.type);\n }\n\n const indexSignatureType = unwrapAst(ast, SchemaAST.isObjects);\n if (indexSignatureType && SchemaAST.isObjects(indexSignatureType) && indexSignatureType.indexSignatures.length > 0) {\n return unwrapAst(indexSignatureType.indexSignatures[0].type);\n }\n\n return null;\n};\n\n/**\n * The signature of `propertyName` on a struct, or on the member of a discriminated union that the target's\n * current discriminator selects.\n */\nconst getPropertySignature = (\n ast: SchemaAST.AST,\n propertyName: string,\n getTargetPropertyFn: (propertyName: string) => any,\n): SchemaAST.PropertySignature | null => {\n const typeOrDiscriminatedUnion = unwrapAst(ast, (t) => {\n return SchemaAST.isObjects(t) || (SchemaAST.isUnion(t) && t.types.some((t) => SchemaAST.isObjects(t)));\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n return getProperties(typeOrDiscriminatedUnion, getTargetPropertyFn).find((p) => p.name === propertyName) ?? null;\n};\n\n/** Whether `propertyName` is the tag selecting a member of the discriminated union at `ast`. */\nconst isUnionTag = (ast: SchemaAST.AST, propertyName: PropertyKey): boolean => {\n const union = unwrapAst(ast, (t) => SchemaAST.isUnion(t) && t.types.some((member) => SchemaAST.isObjects(member)));\n const members = union == null ? [] : flattenUnion(union).filter((member) => SchemaAST.isObjects(member));\n return members.length > 1 && getTypeDiscriminators(members)[0].name === propertyName;\n};\n\n/**\n * Unwraps the shapes a tag takes on after a JSON schema round-trip: optional (its constructor\n * default leaves it out of `required`) and single-member union (a one-entry `anyOf`).\n */\nconst unwrapDiscriminator = (ast: SchemaAST.AST): SchemaAST.AST => {\n const unwrapped = SchemaEx.unwrapOptional(ast);\n return SchemaAST.isUnion(unwrapped) && unwrapped.types.length === 1\n ? unwrapDiscriminator(unwrapped.types[0])\n : unwrapped;\n};\n\n/** The tag a union member's discriminator property declares, seen through {@link unwrapDiscriminator}. */\nconst discriminatorValue = (property: SchemaAST.PropertySignature): unknown => {\n const tag = unwrapDiscriminator(property.type);\n return SchemaAST.isLiteral(tag) ? tag.literal : undefined;\n};\n\n/**\n * The index of the union member a target's tag selects; with no tag, the one member whose tag may be omitted (-1 when\n * none or several may be).\n */\nconst selectMember = (typeDiscriminators: SchemaAST.PropertySignature[], tag: unknown): number => {\n if (tag === undefined) {\n const omittable = typeDiscriminators.flatMap((property, index) =>\n SchemaAST.isOptional(property.type) ? [index] : [],\n );\n return omittable.length === 1 ? omittable[0] : -1;\n }\n return typeDiscriminators.findIndex((property) => tag === discriminatorValue(property));\n};\n\nconst getTypeDiscriminators = (typeAstList: SchemaAST.Objects[]): SchemaAST.PropertySignature[] => {\n const discriminatorPropCandidates = typeAstList\n .flatMap(SchemaAST.getPropertySignatures)\n .filter((p) => SchemaAST.isLiteral(unwrapDiscriminator(p.type)));\n const propertyName = discriminatorPropCandidates[0]?.name;\n // Optionality cannot disqualify a candidate: a round-tripped discriminator's constructor default\n // leaves it optional, and the round trip erases what would distinguish it from an authored one.\n const isValidDiscriminator =\n propertyName !== undefined && discriminatorPropCandidates.every((p) => p.name === propertyName);\n const everyTypeHasDiscriminator = discriminatorPropCandidates.length === typeAstList.length;\n const isDiscriminatedUnion = isValidDiscriminator && everyTypeHasDiscriminator;\n invariant(isDiscriminatedUnion, 'type ambiguity: every type in a union must have a single unique-literal field');\n return discriminatorPropCandidates;\n};\n\n/**\n * Used to check that rootAst is for a type matching the provided predicate.\n * That's not always straightforward because types of optionality and recursive types.\n * const Task = Schema.Struct({\n * ...,\n * previous?: Schema.optional(Schema.suspend(() => Task)),\n * });\n * Here the AST for `previous` field is going to be Union(Suspend(Type), Undefined).\n * SchemaAST.isObjects(field) will return false, but unwrapAst(field, (ast) => SchemaAST.isObjects(ast))\n * will return true.\n */\nconst unwrapAst = (rootAst: SchemaAST.AST, predicate?: (ast: SchemaAST.AST) => boolean): SchemaAST.AST | null => {\n let ast: SchemaAST.AST | undefined = rootAst;\n while (ast != null) {\n if (predicate?.(ast)) {\n return ast;\n }\n\n if (SchemaAST.isUnion(ast)) {\n const next: any = ast.types.find((t) => (predicate != null && predicate(t)) || SchemaAST.isSuspend(t));\n if (next != null) {\n ast = next;\n continue;\n }\n }\n\n if (SchemaAST.isSuspend(ast)) {\n ast = ast.thunk();\n } else {\n return predicate == null ? ast : null;\n }\n }\n\n return null;\n};\n\nconst unwrapArray = (ast: SchemaAST.AST) => unwrapAst(ast, SchemaAST.isArrays) as SchemaAST.Arrays | null;\n\nconst getIndexSignatureValueType = (ast: SchemaAST.AST): SchemaAST.AST | null => {\n const typeLiteral = unwrapAst(ast, SchemaAST.isObjects);\n if (typeLiteral == null || !SchemaAST.isObjects(typeLiteral) || typeLiteral.indexSignatures.length === 0) {\n return null;\n }\n\n return unwrapAst(typeLiteral.indexSignatures[0].type);\n};\n\nconst resolveTypeLiteral = (\n ast: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => unknown,\n): SchemaAST.Objects | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return null;\n }\n\n const typeOrDiscriminatedUnion = unwrapAst(ast, (type) => {\n return (\n SchemaAST.isObjects(type) || (SchemaAST.isUnion(type) && type.types.some((member) => SchemaAST.isObjects(member)))\n );\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n if (SchemaAST.isObjects(typeOrDiscriminatedUnion)) {\n return typeOrDiscriminatedUnion;\n }\n\n if (!SchemaAST.isUnion(typeOrDiscriminatedUnion)) {\n return null;\n }\n\n const typeAstList = typeOrDiscriminatedUnion.types.filter((type) => SchemaAST.isObjects(type)) as SchemaAST.Objects[];\n if (typeAstList.length === 1) {\n return typeAstList[0];\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = selectMember(typeDiscriminators, targetPropertyValue);\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return typeAstList[typeIndex];\n};\n\n/** True for an object literal (or `Object.create(null)`), as opposed to an array, byte array or class instance. */\nexport const isPlainRecord = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value) || value instanceof Uint8Array) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\nconst formatPropertyPath = (path: KeyPath): string => path.map(String).join('.');\n\nexport const checkIdNotPresentOnSchema = (schema: Schema.Codec<any, any, any>) => {\n invariant(SchemaAST.isObjects(schema.ast));\n const idProperty = SchemaAST.getPropertySignatures(schema.ast).find((prop) => prop.name === 'id');\n if (idProperty != null) {\n throw new Error('\"id\" property name is reserved');\n }\n};\n\n// TODO(burdon): Reconcile with JsonPath.\ntype KeyPath = readonly (string | number)[];\n\n/**\n * Whether the AST describes an array of root entities held by identity (elements annotated with\n * {@link EntityValueAnnotationId}).\n */\nexport const isEntityArrayAst = (ast: SchemaAST.AST): boolean => {\n const arrayAst = unwrapArray(ast);\n const elementAst = arrayAst?.rest[0];\n return elementAst != null && SchemaAST.getAnnotation<boolean>(elementAst, EntityValueAnnotationId) === true;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Equal from 'effect/Equal';\nimport * as Hash from 'effect/Hash';\nimport * as Schema from 'effect/Schema';\nimport { type InspectOptionsStylized } from 'node:util';\n\nimport { Event } from '@dxos/async';\nimport { inspectCustom } from '@dxos/debug';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { getDeep } from '@dxos/util';\n\nimport { getSchemaURI } from '../../Annotation/annotations.ts';\nimport { isEntity } from '../../Entity/guard.ts';\nimport { toEffectSchema } from '../../JsonSchema/json-schema.ts';\nimport {\n ObjectDeletedId,\n ParentId,\n SchemaAstId,\n SchemaId,\n StaticTypeSchemaSlot,\n TypeEntityId,\n TypeId,\n} from '../types/index.ts';\nimport { assertMutable, executeChange, queueNotification } from './change-context.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { createTextMethodError } from './errors.ts';\nimport { batchEvents } from './event-batch.ts';\nimport {\n changeKeyOf,\n getEchoRoot,\n getOwner,\n getRawTarget,\n hasEntityElements,\n hasForeignOwner,\n notifyOwnerChain,\n setOwnerRecursive,\n wouldCreateCycle,\n} from './ownership.ts';\nimport { type ReactiveHandler } from './proxy-types.ts';\nimport {\n createProxy,\n isProxy,\n isReactiveRecord,\n isValidProxyTarget,\n normalizeSpliceRange,\n symbolReactivePrototype,\n} from './proxy-utils.ts';\nimport { ReactiveArray } from './reactive-array.ts';\nimport { SchemaValidator, assertsWithDetail, isEntityArrayAst } from './schema-validator.ts';\nimport { ChangeId, ChangeKeyId, EntityElementsId, EventId } from './symbols.ts';\n\n// Re-export for external consumers.\nexport { getEchoRoot, setMetaOwner } from './ownership.ts';\n\ntype ProxyTarget = {\n /**\n * Typename or type DXN.\n */\n [TypeId]: string;\n\n /**\n * Schema for the root.\n */\n [SchemaId]?: Schema.Top;\n\n /**\n * AST for a nested value.\n */\n [SchemaAstId]?: SchemaAST.AST;\n [ParentId]?: any;\n\n /**\n * For modifications.\n */\n [EventId]: Event<void>;\n} & ({ [key: keyof any]: any } | any[]);\n\n/**\n * Deep copy a value, handling arrays and nested objects.\n * Preserves ReactiveArray type and hidden properties (SchemaId, TypeId).\n * Does not copy class instances or functions (except ReactiveArray).\n *\n * Note: Cannot use structuredClone because we need to:\n * - Unwrap proxies\n * - Preserve ReactiveArray instances\n * - Copy Symbol-keyed hidden properties (SchemaId, TypeId)\n * - Convert plain arrays to ReactiveArray\n *\n * Performance: O(n) where n is the total number of nested objects/arrays.\n * For large structures, consider using Refs for frequently reassigned subtrees.\n */\nconst deepCopy = <T>(value: T, visited = new Map<object, object>()): T => {\n if (value == null || typeof value !== 'object') {\n return value;\n }\n\n // Handle proxies - get the underlying target.\n const actualValue = getRawTarget(value);\n\n // Check for circular references in the copy.\n if (visited.has(actualValue)) {\n return visited.get(actualValue) as T;\n }\n\n // Entities held by identity are shared, not copied.\n if (hasEntityElements(actualValue)) {\n const copy = toEntityArray(actualValue);\n visited.set(actualValue, copy);\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n }\n\n // Handle ReactiveArray specially to preserve reactivity.\n if (actualValue instanceof ReactiveArray) {\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n // Copy hidden properties.\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n }\n\n // Don't copy other class instances (objects with non-Object prototype). A reactive record\n // (its metadata moved onto a behaviour prototype) still counts as a plain data record here.\n const proto = Object.getPrototypeOf(actualValue);\n if (proto !== Array.prototype && proto !== null && !isReactiveRecord(actualValue)) {\n return value; // Return as-is, don't copy class instances.\n }\n\n if (Array.isArray(actualValue)) {\n // Plain arrays become ReactiveArrays.\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n return copy as T;\n }\n\n const copy: Record<string, any> = {};\n visited.set(actualValue, copy);\n for (const key of Object.keys(actualValue)) {\n copy[key] = deepCopy((actualValue as any)[key], visited);\n }\n // Copy hidden properties (SchemaId, TypeId).\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n};\n\n/**\n * Write `value` at `path`, unwrapping each hop to its raw target. A nested record is stored as its\n * sub-proxy, and writing through one would re-impose the per-delta validation the text path exists to\n * skip.\n */\nconst setDeepOnRawTargets = (target: object, path: readonly (string | number)[], value: unknown): void => {\n let parent: any = getRawTarget(target);\n for (const key of path.slice(0, -1)) {\n parent = getRawTarget(parent[key]);\n }\n parent[path[path.length - 1]] = value;\n};\n\n/** A fresh reactive array of the given entities, marked so they stay held by identity. */\nconst toEntityArray = (items: readonly unknown[]): ReactiveArray<unknown> => {\n const array = new ReactiveArray<unknown>();\n for (const item of items) {\n array[array.length] = item;\n }\n defineHiddenProperty(array, EntityElementsId, true);\n return array;\n};\n\n/**\n * Copy hidden properties (SchemaId, SchemaAstId, TypeId) from source to target.\n */\nconst copyHiddenProperties = (source: any, target: any): void => {\n if (SchemaId in source) {\n defineHiddenProperty(target, SchemaId, source[SchemaId]);\n }\n if (SchemaAstId in source) {\n defineHiddenProperty(target, SchemaAstId, source[SchemaAstId]);\n }\n if (TypeId in source) {\n defineHiddenProperty(target, TypeId, source[TypeId]);\n }\n};\n\n/**\n * Node inspector for typed targets. Forces `showHidden: false` so a target's hidden metadata, including its owner and\n * through it unrelated fields of the root, never prints.\n */\nfunction inspectTypedTarget(\n this: ProxyTarget,\n _depth: number,\n options: InspectOptionsStylized,\n inspectFn: (value: any, options?: InspectOptionsStylized) => string,\n): string {\n const inspected = inspectFn(getRawTarget(this), { ...options, showHidden: false, customInspect: false });\n return `Typed ${inspected}`;\n}\n\n//\n// Object layering for an in-memory typed reactive object (`TypedReactiveHandler`).\n//\n// Unlike the database-backed handler (echo-client/echo-prototypes.ts), here USER DATA lives as\n// real OWN properties on the target — there is no document behind it. Only the per-object metadata\n// is relocated onto a prototype, so swapping handlers doesn't disturb the data shape:\n//\n// proxy ──Proxy(target, REACTIVE_PROXY_HANDLER → TypedReactiveHandler)\n// │ set/has/... traps run here; there is no `get` trap, so reads land on the target\n// ▼\n// target the user's object. OWN enumerable props = user data ({ name, age, ... });\n// │ [[Prototype]] a root's OWN symbol props are removed by `compactMetadataToInstanceState` after init.\n// ▼\n// instanceState `Object.create(TypedObjectPrototype)`. Holds the relocated symbol-keyed\n// │ [[Prototype]] metadata as hidden props: [EventId] (root only), [ObjectDeletedId], [SchemaId],\n// │ [TypeId], [TypeEntityId], cached [StaticTypeSchemaSlot], ... (Arrays are\n// │ exempt — they keep their ReactiveArray chain and are never compacted.)\n// ▼\n// TypedObjectPrototype shared behaviour. Carries [symbolReactivePrototype]=true (so the\n// │ [[Prototype]] \"plain object\" gates still treat the record as data) plus the system\n// │ accessors [ChangeId], [ChangeKeyId], [StaticTypeSchemaSlot]. There is no get\n// │ trap: a read of any of them resolves off this chain by ordinary lookup.\n// ▼\n// Object.prototype ──▶ null a `getPrototypeOf` trap reports `Object.prototype` so consumers\n// see a plain object; the real instanceState prototype stays hidden.\n//\n// Root vs nested: a root object owns an `[EventId]`; nested records share their root's reactivity\n// and have none. That presence is the \"is this an initialized root\" signal (it replaced an earlier\n// `[ChangeId] === true` marker). Only a root gets an instanceState: a nested record never changes\n// handler, so it keeps its metadata as own properties and points straight at TypedObjectPrototype\n// (`shareTypedObjectPrototype`).\n//\n// `this` in the accessors below: the get trap calls `Reflect.get(target, prop, receiver)`, so\n// `this` is the PROXY (receiver) on the common path, or the raw target when read directly.\n// `getRawTarget(this)` normalizes to the underlying target — needed here because user data and the\n// metadata chain both hang off the raw target, and `executeChange` keys the change context by it.\n//\n/**\n * Behaviour prototype for typed reactive records. A root's per-object metadata is moved onto an\n * intermediate instance-state object whose prototype is this, so that swapping the handler that\n * backs an object (e.g. an in-memory object becoming database-backed) is a prototype re-point that\n * doesn't perturb the target's own-property shape. A nested record never swaps handler, so it points\n * here directly and keeps its metadata as own properties. Marked as a reactive prototype so the\n * \"plain object\" gates (`isValidProxyTarget` / `deepCopy`) still treat such targets as data records.\n */\nconst TypedObjectPrototype: object = Object.create(Object.prototype);\ndefineHiddenProperty(TypedObjectPrototype, symbolReactivePrototype, true);\n\n// The ECHO system surface is exposed as accessors on the behaviour prototype rather than as\n// branches in the `get` trap. `this` is the proxy receiver (or the raw target when read directly);\n// `getRawTarget` resolves either to the underlying target.\nObject.defineProperties(TypedObjectPrototype, {\n [ChangeKeyId]: {\n get(this: ProxyTarget) {\n return changeKeyOf(this);\n },\n },\n [ChangeId]: {\n // A function that runs a mutation inside a controlled change context. Only root objects (which\n // own an `EventId`) expose one; nested records share their root's reactivity and return undefined.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n if (!(EventId in target)) {\n return undefined;\n }\n return (callback: (obj: any) => void) => executeChange(target, target, this, callback);\n },\n },\n // Effect `Hash`/`Equal` traits, keyed by entity id: an entity has exactly one live proxy, and the\n // bare `id` spells that invariant without the throw a derived URI risks on a malformed id.\n // Effect's structural default would instead deep-read the record and go stale on the next mutation.\n // Selected by the `[KindId]` brand, not by the presence of an `id`, since a nested record sharing\n // this prototype may carry an application-level one; those keep reference identity.\n [Hash.symbol]: {\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n return () => (isEntity(target) ? Hash.hash(target.id) : Hash.random(target));\n },\n },\n [Equal.symbol]: {\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n return isEntity(target)\n ? (that: unknown) => isEntity(that) && that.id === target.id\n : (that: unknown) => getRawTarget(that) === target;\n },\n },\n // One shared inspector rather than a bound function per record: a nested JSON Schema alone is dozens of records.\n [inspectCustom]: { value: inspectTypedTarget },\n [StaticTypeSchemaSlot]: {\n // Lazily rebuild the source Effect Schema from `jsonSchema` and cache it as an own (hidden)\n // property so subsequent reads short-circuit this accessor; the set-trap deletes the cache when\n // `jsonSchema` is mutated.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n const jsonSchema = (target as any).jsonSchema;\n if (jsonSchema == null) {\n return undefined;\n }\n const rebuilt = toEffectSchema(jsonSchema);\n defineHiddenProperty(target, StaticTypeSchemaSlot, rebuilt);\n return rebuilt;\n },\n },\n});\n\n/**\n * True once the root owns an `[EventId]`, i.e. is past construction and notifies on change. The\n * read-only gate itself lives in the shared proxy handler (`assertMutable`), keyed by `[ChangeKeyId]`.\n */\nconst isInitialized = (echoRoot: object): boolean => EventId in echoRoot;\n\n/**\n * Move a record's per-object metadata (symbol-keyed hidden properties) onto a fresh instance-state\n * object inserted between the target and {@link TypedObjectPrototype}. The target keeps only its\n * user data as own properties. Arrays are exempt — they keep their own (ReactiveArray) prototype chain.\n */\nconst compactMetadataToInstanceState = (target: ProxyTarget): void => {\n if (Array.isArray(target) || Object.getPrototypeOf(target) !== Object.prototype) {\n return;\n }\n const state = Object.create(TypedObjectPrototype);\n for (const symbol of Object.getOwnPropertySymbols(target)) {\n const descriptor = Object.getOwnPropertyDescriptor(target, symbol)!;\n Object.defineProperty(state, symbol, descriptor);\n // Non-configurable symbols (e.g. `SchemaId`/`TypeId`, locked by `setSchema`/`setTypename` on\n // objects decoded from JSON) cannot be deleted — leave them as an own property on the target,\n // shadowing the copy on `state`; reads still resolve correctly since own properties take\n // precedence over the prototype chain.\n if (descriptor.configurable) {\n // Dynamic delete over arbitrary symbol keys: `ProxyTarget` declares these as required, so the\n // statically-typed view cannot express deleting them; the symbol set is only known at runtime.\n delete (target as any)[symbol];\n }\n }\n Object.setPrototypeOf(target, state);\n};\n\n/**\n * Point a nested record straight at {@link TypedObjectPrototype}, keeping its metadata as own properties.\n *\n * Unlike {@link compactMetadataToInstanceState} this keeps the record in V8's fast-property mode: deleting the moved\n * properties would turn the target into a dictionary, and so would making the per-record state a prototype. Both\n * cost ~0.5 KiB a record, which for an object holding JSON Schema (one record per schema node) is most of its heap.\n */\nconst shareTypedObjectPrototype = (target: ProxyTarget): void => {\n // `isValidProxyTarget` admits only records rooted at `Object.prototype` or at a prototype carrying\n // `symbolReactivePrototype`, which only `TypedObjectPrototype` sets, so a record skipped here already inherits it.\n if (Array.isArray(target) || Object.getPrototypeOf(target) !== Object.prototype) {\n return;\n }\n Object.setPrototypeOf(target, TypedObjectPrototype);\n};\n\n/**\n * Typed in-memory reactive store (with Schema).\n * Reactivity is based on Event subscriptions, not signals.\n */\nexport class TypedReactiveHandler implements ReactiveHandler<ProxyTarget> {\n public static readonly instance: ReactiveHandler<any> = new TypedReactiveHandler();\n\n private _inSet = false;\n\n private constructor() {}\n\n init(target: ProxyTarget): void {\n assertArgument(typeof target === 'object' && target !== null, 'target');\n invariant(SchemaId in target || SchemaAstId in target, 'Schema is not defined for the target');\n\n // Only set EventId on root objects (those without an owner).\n // Nested objects share their root's EventId for centralized reactivity.\n const hasOwner = !!getOwner(target);\n if (!(EventId in target) && !hasOwner) {\n defineHiddenProperty(target, EventId, new Event());\n }\n\n // Default to not-deleted, but preserve a deletion marker already stamped on the target (e.g. by\n // `objectFromJSON` when hydrating a tombstone snapshot). Only entities are deleted, never a nested record.\n if (!hasOwner && !(ObjectDeletedId in target)) {\n defineHiddenProperty(target, ObjectDeletedId, false);\n }\n\n // Only set owners if this is a root object (no existing owner).\n // Nested objects already have owners set by their root's initialization.\n // If we re-set owners here for nested objects, we'd incorrectly point\n // array elements to the array instead of the true root ECHO object.\n if (!hasOwner) {\n // Set owner on all nested objects to this root ECHO object.\n // All nested records point directly to this root for centralized reactivity.\n for (const key in target) {\n if (isProxy(target)) {\n continue;\n }\n let value = (target as any)[key];\n if (isValidProxyTarget(value) || isProxy(value)) {\n // Deep copy values that have foreign owners (owned by a different object,\n // or are root ECHO objects whose nested structures would be owned by them).\n // This recursively checks all nested objects.\n if (hasForeignOwner(value, target)) {\n value = deepCopy(value);\n (target as any)[key] = value;\n }\n setOwnerRecursive(value, target);\n }\n }\n }\n\n // Relocate a root's metadata onto an instance-state prototype, leaving only user data as own properties on the\n // target. Done last so all metadata set above (and by `prepareTypedTarget`) moves. A nested record never changes\n // handler, so it needs no state of its own: see `shareTypedObjectPrototype`.\n if (Array.isArray(target)) {\n // Arrays keep their `ReactiveArray` prototype, so they carry the shared inspector themselves.\n defineHiddenProperty(target, inspectCustom, inspectTypedTarget);\n } else if (hasOwner) {\n shareTypedObjectPrototype(target);\n } else {\n compactMetadataToInstanceState(target);\n }\n\n // After compaction and ownership, so each child is stamped and owned before it gets a proxy of its\n // own. Recursive: wrapping a child runs its `init`, which wraps that child's children.\n this._wrapNestedValues(target);\n }\n\n /**\n * Replaces every raw nested record and array on the target with the sub-proxy a read returns, so a\n * forwarded read hands out the same reactive view the `get` trap used to build. Class instances,\n * `Ref`s and primitives are not proxy targets and stay as they are.\n */\n private _wrapNestedValues(target: ProxyTarget): void {\n for (const key of Object.keys(target)) {\n // The descriptor first: reading an own getter here would invoke it, and a type entity's\n // `jsonSchema` getter can reach a schema still inside its own `const` initializer.\n if (Object.getOwnPropertyDescriptor(target, key)?.get) {\n continue;\n }\n const value = (target as any)[key];\n if (isValidProxyTarget(value)) {\n (target as any)[key] = createProxy(value, this);\n }\n }\n }\n\n set(target: ProxyTarget, prop: string | symbol, value: any, receiver: any): boolean {\n const echoRoot = getEchoRoot(target);\n const initialized = isInitialized(echoRoot);\n\n let result: boolean = false;\n this._inSet = true;\n try {\n batchEvents(() => {\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, prop, value);\n result = Reflect.set(target, prop, preparedValue, receiver);\n // Invalidate the cached source Effect Schema when `jsonSchema` changes\n // (e.g. `Type.addFields`) so `Type.getSchema` rebuilds from the new shape.\n if (prop === 'jsonSchema') {\n Reflect.deleteProperty(target, StaticTypeSchemaSlot);\n }\n // Queue notification instead of emitting immediately (batched).\n if (initialized) {\n queueNotification(echoRoot);\n // Also notify the owner chain so parent objects are updated when nested objects change.\n notifyOwnerChain(target);\n }\n });\n } finally {\n this._inSet = false;\n }\n return result;\n }\n\n deleteProperty(target: ProxyTarget, property: string | symbol): boolean {\n const echoRoot = getEchoRoot(target);\n\n const initialized = isInitialized(echoRoot);\n const result = Reflect.deleteProperty(target, property);\n if (initialized) {\n queueNotification(echoRoot);\n }\n return result;\n }\n\n defineProperty(target: ProxyTarget, property: string | symbol, attributes: PropertyDescriptor): boolean {\n const echoRoot = getEchoRoot(target);\n const initialized = isInitialized(echoRoot);\n\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, property, attributes.value);\n const result = Reflect.defineProperty(target, property, {\n ...attributes,\n value: preparedValue,\n });\n if (!this._inSet && initialized) {\n // Queue notification instead of emitting immediately (batched).\n queueNotification(echoRoot);\n }\n return result;\n }\n\n textUpdate(target: ProxyTarget, path: readonly (string | number)[], newText: string): void {\n this._applyTextMutation(target, 'update', path, () => newText);\n }\n\n textSplice(\n target: ProxyTarget,\n path: readonly (string | number)[],\n start: number,\n deleteCount: number,\n insert: string,\n ): string {\n let removed = '';\n this._applyTextMutation(target, 'splice', path, (current) => {\n const range = normalizeSpliceRange(current.length, start, deleteCount);\n removed = current.slice(range.start, range.start + range.deleteCount);\n return current.slice(0, range.start) + insert + current.slice(range.start + range.deleteCount);\n });\n return removed;\n }\n\n /**\n * Shared read-modify-write for the in-memory string CRDT path. A method call is invisible to the proxy,\n * so it runs the same `assertMutable` gate the traps run, then mutates and notifies through the same\n * batched notification path so reactivity fires.\n *\n * Writes on the raw targets, intentionally bypassing `_prepareValueForAssignment` /\n * `_validateValue`: a string CRDT delta produces a string, and per-delta schema checks (pattern,\n * maxLength) would reject valid intermediate states during incremental edits. Such constraints are\n * enforced at the initial assignment or as application-level invariants, mirroring the Automerge path.\n */\n private _applyTextMutation(\n target: ProxyTarget,\n method: string,\n path: readonly (string | number)[],\n compute: (current: string) => string,\n ): void {\n assertMutable(target, method, createTextMethodError);\n\n const echoRoot = getEchoRoot(target);\n const keyPath = [...path];\n invariant(keyPath.length > 0, 'Text path must be non-empty');\n const current = getDeep(target, keyPath);\n if (typeof current !== 'string') {\n throw new TypeError(`Text mutation target at \"${keyPath.join('.')}\" is not a string.`);\n }\n\n const next = compute(current);\n batchEvents(() => {\n // Write directly on the raw target (not the proxy) and notify through the same batched path\n // the `set` trap uses, so subscribers fire once per `Obj.update`.\n setDeepOnRawTargets(target, keyPath, next);\n queueNotification(echoRoot);\n notifyOwnerChain(target);\n });\n }\n\n /**\n * Prepare a value for assignment to a typed object property.\n * Handles cycle detection, copy-on-assign, array conversion, validation, and ownership.\n */\n private _prepareValueForAssignment(\n target: ProxyTarget,\n prop: string | symbol,\n value: any,\n ): { echoRoot: object; preparedValue: any } {\n const echoRoot = getEchoRoot(target);\n\n if (typeof prop === 'symbol') {\n return { echoRoot, preparedValue: value };\n }\n\n // An element of an entity array is a reference to another root: validated, never owned or copied.\n if (hasEntityElements(target)) {\n return { echoRoot, preparedValue: this._validateValue(target, prop, value) };\n }\n if (Array.isArray(value) && isEntityArrayAst(SchemaValidator.getTargetPropertyAst(target, prop))) {\n const entities = toEntityArray(value);\n const validated = this._validateValue(target, prop, entities);\n setOwnerRecursive(validated, echoRoot);\n return { echoRoot, preparedValue: createProxy(validated, this) };\n }\n\n // Check for cycles before assignment.\n if (isValidProxyTarget(value) || isProxy(value)) {\n if (wouldCreateCycle(echoRoot, value)) {\n throw new Error('Cannot create cycles in typed object graph. Consider using Ref for circular references.');\n }\n }\n\n // Prevent direct assignment of root ECHO objects (those created with Obj.make/Relation.make).\n // These must be wrapped with Ref.make for proper reference handling.\n // This matches database object behavior for consistency.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const isRootEchoObject = EventId in actualValue;\n if (isRootEchoObject) {\n throw new Error('Object references must be wrapped with `Ref.make`');\n }\n }\n\n // Copy-on-assign: If the value is a nested record owned by a different ECHO object, deep copy it.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const existingOwner = getOwner(actualValue);\n if (existingOwner != null && existingOwner !== echoRoot) {\n value = deepCopy(value);\n }\n }\n\n // Convert arrays to reactive arrays — the whole subtree, as construction does, not just the top\n // level: an array reached through an assigned record is proxied like any other and must be gated\n // and reactive too.\n if (Array.isArray(value) && !(value instanceof ReactiveArray)) {\n value = ReactiveArray.from(value);\n }\n if (value != null && typeof value === 'object' && !isProxy(value)) {\n makeArraysReactive(value);\n }\n\n const validatedValue = this._validateValue(target, prop, value);\n\n // Set owner on new value to the root ECHO object.\n if (isValidProxyTarget(validatedValue) || isProxy(validatedValue)) {\n setOwnerRecursive(validatedValue, echoRoot);\n }\n\n // Stored wrapped, for the same reason `init` wraps: the target is what a forwarded read sees.\n return {\n echoRoot,\n preparedValue: isValidProxyTarget(validatedValue) ? createProxy(validatedValue, this) : validatedValue,\n };\n }\n\n private _validateValue(target: any, prop: string | symbol, value: any) {\n if (prop === ParentId) {\n return value;\n }\n const ast = SchemaValidator.getTargetPropertyAst(target, prop);\n // Clearing an optional property is admitted here rather than by the property's own schema: v4\n // keeps optionality on the property's context instead of widening its type to `T | undefined`.\n if (value !== undefined || !SchemaValidator.isOptionalProperty(target, prop)) {\n assertsWithDetail(Schema.make(ast), value);\n }\n SchemaValidator.assertExactProperties(ast, value, (path) => getDeep(value, path));\n if (isValidProxyTarget(value)) {\n setNestedSchema(value, ast);\n }\n\n return value;\n }\n}\n\n/**\n * Pointer to a `Type.Type` entity, stamped as the back-reference (`TypeEntityId`)\n * on instances and read by the `SchemaId` getter installed below.\n *\n * Structural shape (not `Type.AnyEntity`) because `internal/common/proxy/`\n * can't import the top-level `Type` module without a cycle. Every kind of\n * `Type.Type` entity satisfies this shape:\n * - Static (`Type.makeObject(dxn)` pipe) — slot set directly on the object.\n * - Persisted (echo-handler-wrapped) — slot exposed via that handler's\n * `get` trap (rebuilds from `data.jsonSchema`).\n * - In-memory pre-persist (`Type.makeObjectFromJsonSchema`) — slot exposed\n * via the `case StaticTypeSchemaSlot:` arm in this file's `get` trap.\n */\nexport type TypeSource = { readonly [StaticTypeSchemaSlot]?: Schema.Top };\n\n/**\n * Stamps a root target with its schema, and each nested proxy target below it with the AST it follows.\n *\n * @param skipOwnStamp Skip stamping `TypeId`/`SchemaId` on `obj` itself (still recurses into\n * children, which always get stamped). Used for objects decoded from JSON, whose own `TypeId`/\n * `SchemaId` are already set by `setTypename`/`setSchema` as `configurable: false` — redefining\n * them here (with `configurable: true`) would throw.\n */\nconst setSchemaProperties = (obj: any, schema: Schema.Top, typeSource?: TypeSource, skipOwnStamp = false) => {\n if (!skipOwnStamp) {\n const schemaType = getSchemaURI(schema);\n if (schemaType != null) {\n defineHiddenProperty(obj, TypeId, schemaType);\n }\n\n if (typeSource != null) {\n // Keep a back-reference to the type entity so `Obj.getType` /\n // `Relation.getType` / `Entity.getType` can return it.\n defineHiddenProperty(obj, TypeEntityId, typeSource);\n\n // Install `SchemaId` as a getter that reads through the entity's static\n // schema slot. The three entity shapes (static / persisted / in-memory\n // pre-persist) each populate the slot via their own get-trap path, so\n // `Type.update` / `Type.addFields` mutations propagate into validation\n // for objects created via `Obj.make(typeEntity, ...)` without this file\n // having to rebuild from `jsonSchema` itself.\n Object.defineProperty(obj, SchemaId, {\n get: () => typeSource[StaticTypeSchemaSlot] ?? schema,\n enumerable: false,\n configurable: true,\n });\n } else {\n defineHiddenProperty(obj, SchemaId, schema);\n }\n }\n\n setChildSchemas(obj, schema.ast);\n};\n\n/** Stamps a nested proxy target, and those below it, with the AST it follows. */\nconst setNestedSchema = (obj: any, ast: SchemaAST.AST) => {\n const schemaType = getSchemaURI(Schema.make(ast));\n if (schemaType != null) {\n defineHiddenProperty(obj, TypeId, schemaType);\n }\n defineHiddenProperty(obj, SchemaAstId, ast);\n setChildSchemas(obj, ast);\n};\n\nconst setChildSchemas = (obj: any, ast: SchemaAST.AST) => {\n if (hasEntityElements(obj)) {\n return;\n }\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n if (isValidProxyTarget(obj[index])) {\n setNestedSchema(obj[index], SchemaValidator.getIndexedElementAst(ast, index) ?? Schema.Any.ast);\n }\n }\n return;\n }\n\n for (const key in obj) {\n if (isValidProxyTarget(obj[key])) {\n let elementAst: SchemaAST.AST;\n try {\n elementAst = SchemaValidator.getTargetPropertyAst(obj, key);\n } catch {\n // Property not in schema — treat as untyped so the proxy can still wrap it.\n elementAst = Schema.Any.ast;\n }\n setNestedSchema(obj[key], elementAst);\n }\n }\n};\n\nexport type PrepareTargetOptions = {\n /** Validate the target against its schema (default). See `Obj.MakeOptions.skipValidation`. */\n validate?: boolean;\n};\n\n// Accepts any encoded type: the typed handler operates on the decoded representation, so schemas\n// whose encoded form differs (e.g. refs encode as `{ '/': uri }`) are valid here.\nexport const prepareTypedTarget = <T>(\n target: T,\n schema: Schema.Schema<T>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n) => {\n validateAndReactifyTarget(target, schema, options);\n setSchemaProperties(target, schema, typeSource);\n};\n\n/**\n * Validate a target against its schema and convert nested arrays to `ReactiveArray`. Shared by\n * {@link prepareTypedTarget} and {@link prepareDecodedTypedTarget}.\n */\nexport const validateAndReactifyTarget = <T>(target: T, schema: Schema.Schema<T>, options?: PrepareTargetOptions) => {\n if (!SchemaAST.isObjects(schema.ast)) {\n throw new Error('schema has to describe an object type');\n }\n\n if (options?.validate !== false) {\n SchemaValidator.validateSchema(schema);\n assertsWithDetail(schema, target);\n SchemaValidator.assertExactProperties(schema.ast, target, (path) => getDeep(target, path));\n }\n markEntityArrays(target, schema.ast);\n makeArraysReactive(target);\n};\n\n/** Marks the target's top-level entity-array properties (e.g. `meta.tags`) as held by identity. */\nconst markEntityArrays = (target: any, ast: SchemaAST.AST) => {\n if (!SchemaAST.isObjects(ast)) {\n return;\n }\n for (const property of ast.propertySignatures) {\n const value = target[property.name];\n if (Array.isArray(value) && !hasEntityElements(value) && isEntityArrayAst(property.type)) {\n target[property.name] = toEntityArray(value);\n }\n }\n};\n\n/**\n * Like {@link prepareTypedTarget}, for a target whose own `SchemaId`/`TypeId` are already stamped\n * and locked `configurable: false` — e.g. an object decoded from JSON via `setSchema`/`setTypename`\n * (see `objectFromJSON`). Validates and reactifies as usual, then stamps `SchemaId`/`TypeId` on\n * nested records/arrays only, leaving the target's own (locked) stamps untouched.\n */\nexport const prepareDecodedTypedTarget = <T>(target: T, schema: Schema.Schema<T>) => {\n validateAndReactifyTarget(target, schema);\n setSchemaProperties(target, schema, undefined, true);\n};\n\n/**\n * Convert every plain array in a subtree to a {@link ReactiveArray}, in place. A plain array has\n * neither the batched mutating methods nor the `[ChangeKeyId]` the read-only gate reads off its\n * prototype, so one left in the tree would mutate silently and notify nobody.\n *\n * An already-proxied child is skipped: it belongs to the graph already and writing through its proxy\n * would run the whole assignment path again.\n */\nconst makeArraysReactive = (target: any) => {\n for (const key in target) {\n const value = target[key];\n if (value == null || typeof value !== 'object' || isProxy(value)) {\n continue;\n }\n if (hasEntityElements(value)) {\n continue;\n }\n if (Array.isArray(value) && !(value instanceof ReactiveArray)) {\n target[key] = ReactiveArray.from(value);\n }\n makeArraysReactive(target[key]);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport type * as Schema from 'effect/Schema';\n\nimport { EntityId } from '@dxos/keys';\n\nimport { getTypeAnnotation } from '../../Annotation/annotations.ts';\nimport { type AnyProperties, KindId, ParentId, SchemaId, SchemaKindId, StaticTypeSchemaSlot } from '../types/index.ts';\nimport { type EntityMeta, EntityMetaSchema } from '../types/meta.ts';\nimport { MetaId } from '../types/model-symbols.ts';\nimport { defineHiddenProperty } from './define-hidden-property.ts';\nimport { attachTypedJsonSerializer } from './json-serializer.ts';\nimport { createProxy, getProxyTarget, isProxy, isValidProxyTarget } from './proxy-utils.ts';\nimport {\n type PrepareTargetOptions,\n TypedReactiveHandler,\n TypeSource,\n prepareDecodedTypedTarget,\n prepareTypedTarget,\n setMetaOwner,\n} from './typed-handler.ts';\n\n/**\n *\n */\n// TODO(burdon): Make internal\n// Omits the brand slots — those get stamped on the instance by the entity\n// handler (KindId via setKind, SchemaKindId derived in the proxy `get` trap\n// from kind + jsonSchema.entityKind, StaticTypeSchemaSlot lazily via the\n// proxy), not supplied by the caller.\nexport type MakeObjectProps<T extends AnyProperties> = Omit<T, 'id' | KindId | SchemaKindId | StaticTypeSchemaSlot>;\n\n/**\n * Creates a reactive object from a plain Javascript object.\n * Requires a TS-effect schema.\n *\n * Callers that have a `Type.Type` entity (not a raw schema) must unwrap it\n * themselves — `Obj.make` / `Relation.make` do this via `Type.getSchema(...)`\n * and pass the entity through as `typeSource` so the instance carries a\n * back-reference for `Obj.getType` and resolves the live source schema\n * uniformly via the entity's `[StaticTypeSchemaSlot]`.\n */\n// TODO(burdon): Make internal\n// TODO(dmaretskyi): Deep mutability.\n// TODO(dmaretskyi): Invert generics (generic over schema) to have better error messages.\n// TODO(dmaretskyi): Could mutate original object making it unusable.\nexport const makeObject = <T extends AnyProperties>(\n // Matches what this forwards to. Effect 4's `Schema.Schema<T>` pins only `Type` and leaves the\n // service channels open, so narrowing to `Codec<T, any, never>` here rejected ordinary callers\n // and needed a cast to get past.\n schema: Schema.Schema<T>,\n obj: NoInfer<MakeObjectProps<T>>,\n meta?: Partial<EntityMeta>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n): T => {\n // Use Object.assign to copy symbol properties (like ParentId) that spread operator doesn't copy.\n return createReactiveObject<T>(Object.assign({}, obj) as T, meta, schema, typeSource, options);\n};\n\nconst createReactiveObject = <T extends AnyProperties>(\n obj: T,\n meta?: Partial<EntityMeta>,\n schema?: Schema.Schema<T>,\n typeSource?: TypeSource,\n options?: PrepareTargetOptions,\n): T => {\n if (!isValidProxyTarget(obj)) {\n throw new Error('Value cannot be made into a reactive object.');\n }\n\n if (!schema) {\n throw new Error('Schema is required for reactive objects. Use Atom for untyped reactive state.');\n }\n\n // Extract parent from props (can be set via [Obj.Parent]).\n const parent = (obj as any)[ParentId];\n if (parent !== undefined) {\n delete (obj as any)[ParentId];\n }\n\n const annotation = getTypeAnnotation(schema);\n if (annotation) {\n setIdOnTarget(obj);\n defineHiddenProperty(obj, KindId, annotation.kind);\n }\n initMeta(obj, meta, options);\n if (parent !== undefined) {\n defineHiddenProperty(obj, ParentId, parent);\n }\n prepareTypedTarget(obj, schema, typeSource, options);\n attachTypedJsonSerializer(obj);\n const proxy = createProxy<T>(obj, TypedReactiveHandler.instance);\n\n // Set meta's owner to the main object so meta mutations respect the parent's change context.\n // For non-database objects using TypedReactiveHandler, this links the meta to the main object's\n // change context. For database objects, meta is handled by EchoReactiveHandler.getMeta().\n const metaProxy = (obj as any)[MetaId];\n if (metaProxy) {\n const metaTarget = getProxyTarget(metaProxy);\n if (metaTarget) {\n setMetaOwner(metaTarget, obj);\n }\n }\n\n return proxy;\n};\n\n/**\n * Rewrap an object decoded from JSON (via `objectFromJSON`) into a live reactive proxy, so that\n * `Obj.update` synchronously mutates it and `Obj.subscribe`/atoms fire — the same contract as\n * automerge-backed objects. Unlike {@link makeObject}, the target already carries `SchemaId`/\n * `TypeId` stamped by `setSchema`/`setTypename` (both `configurable: false`), so this does not\n * re-derive or re-stamp them — it only validates against the schema, reactifies nested arrays,\n * rewraps `[MetaId]` as a live nested proxy, and wraps the whole object in a proxy.\n *\n * Objects whose type could not be resolved at decode time (no `SchemaId`) are returned unchanged —\n * they remain plain snapshots and `Obj.update` on them stays a no-op, since there is no schema to\n * validate mutations against.\n */\nexport const makeDecodedEntityLive = <T extends AnyProperties>(obj: T): T => {\n const schema = (obj as any)[SchemaId] as Schema.Codec<T, any> | undefined;\n if (!schema) {\n return obj;\n }\n\n prepareDecodedTypedTarget(obj, schema);\n\n const meta = (obj as any)[MetaId];\n if (meta != null && typeof meta === 'object' && !isProxy(meta)) {\n prepareTypedTarget(meta, EntityMetaSchema);\n const metaProxy = createProxy(meta, TypedReactiveHandler.instance);\n defineHiddenProperty(obj, MetaId, metaProxy);\n const metaTarget = getProxyTarget(metaProxy);\n setMetaOwner(metaTarget, obj);\n }\n\n attachTypedJsonSerializer(obj);\n return createProxy(obj, TypedReactiveHandler.instance);\n};\n\n/**\n * Set ID on ECHO object targets during creation.\n * Used for objects with schema and the ones explicitly marked as Expando.\n */\nconst setIdOnTarget = (target: any) => {\n // invariant(!('id' in target), 'Object already has an `id` field, which is reserved.');\n if ('id' in target && target.id !== undefined && target.id !== null) {\n if (!EntityId.isValid(target.id)) {\n throw new Error('Invalid object id format.');\n }\n } else {\n target.id = EntityId.random();\n }\n};\n\n/**\n * Set metadata on object.\n */\n// TODO(dmaretskyi): Move to echo-schema.\nconst initMeta = <T>(obj: T, meta?: Partial<EntityMeta>, options?: PrepareTargetOptions) => {\n // Backfill required fields so callers may pass a partial meta, or one whose `keys`/`tags`/\n // `annotations` are explicitly `undefined` (coalesce, don't let a spread reintroduce undefined).\n const fullMeta: EntityMeta = {\n ...meta,\n keys: meta?.keys ?? [],\n tags: meta?.tags ?? [],\n annotations: meta?.annotations ?? {},\n };\n prepareTypedTarget(fullMeta, EntityMetaSchema, undefined, options);\n defineHiddenProperty(obj, MetaId, createProxy(fullMeta, TypedReactiveHandler.instance as any));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { DXN, EntityId } from '@dxos/keys';\nimport { type ToMutable } from '@dxos/util';\n\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { defineHiddenProperty } from '../common/proxy/define-hidden-property.ts';\nimport { makeObject } from '../common/proxy/make-object.ts';\nimport { getProxyTarget } from '../common/proxy/proxy-utils.ts';\nimport { type AnyProperties } from '../common/types/base.ts';\nimport {\n type AnyEntity,\n EntityKind,\n InstancePhantomId,\n KindId,\n SchemaKindId,\n StaticTypeSchemaSlot,\n} from '../common/types/index.ts';\nimport { type EntityMeta } from '../common/types/meta.ts';\nimport { JsonSchemaType } from '../JsonSchema/json-schema-type.ts';\n\n// TODO(burdon): Define Schema type for `typename` and use consistently for all DXN-like properties.\n\n// type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];\nexport type EchoTypeSchemaProps<T, ExtraFields = {}> = Types.Simplify<AnyEntity & ToMutable<T> & ExtraFields>;\n\n/**\n * Options accepted by every `Type.makeObject` / `Type.makeRelation` / type-kind\n * factory. Defaults are derived from `(typename, version)` so callers normally\n * pass nothing.\n */\nexport type EchoTypeOptions = {\n /**\n * Override the entity id stamped on the in-memory `Type.Type` value.\n *\n * Defaults to `EntityId.deterministic(typename, version)` — stable across processes\n * and workerd-safe (no `crypto.getRandomValues()` at module-evaluation time).\n * Pass an explicit id (typically `EntityId.random()`) to opt out of the\n * deterministic default.\n */\n id?: EntityId;\n};\n\n/**\n * In-memory `Type.Type` entity shape produced by `Type.makeObject(dxn)` /\n * `Type.makeRelation({...})`. A live reactive `TypeSchema` instance —\n * identical to a persisted `Type.Type` except for database attachment.\n *\n * NOT a `Schema.Schema`. The underlying Effect Schema is cached on the hidden\n * `StaticTypeSchemaSlot` slot — retrieve it via `Type.getSchema(...)`.\n */\n// TODO(burdon): Rename EchoEntitySchema.\nexport interface EchoTypeSchema<\n Self extends Schema.Top,\n ExtraFields = {},\n K extends EntityKind = EntityKind,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n /**\n * Entity-kind brand. Type entities are their own kind (`Type`) regardless of\n * the kind of instance they describe — `[SchemaKindId]` carries the latter.\n * This lets predicates like `Obj.isObject` / `Relation.isRelation` cleanly\n * reject type entities without also having to inspect `[SchemaKindId]`.\n */\n readonly [KindId]: EntityKind.Type;\n\n /** Schema-kind brand indicating what kind of instance this type describes. */\n readonly [SchemaKindId]: K;\n\n /**\n * Entity id. Always present — stamped at construction — but NOT the type's\n * identity while in-memory: an unattached type resolves its URI to the typename\n * DXN, switching to `echo:///<id>` only once attached to a database (see\n * `getTypeURIFromSpecifier`, which discriminates by database attachment).\n */\n readonly id: EntityId;\n\n /** Source Effect Schema (kept on a hidden slot for `Type.getSchema`). */\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n // NOTE: `typename` / `version` are intentionally NOT fields. They live in\n // `EntityMeta` (`key` / `version`); read via `Type.getTypename(self)` /\n // `Type.getVersion(self)`.\n readonly jsonSchema: JsonSchemaType;\n\n /** Struct fields for introspection. */\n readonly fields: Fields;\n\n /** Phantom — instance type produced by `Obj.make(self, ...)`. */\n readonly _instance?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields>;\n\n /**\n * Phantom slot mirroring `Type<A>` so internal helpers (`makeObject`,\n * `createObject`, `Ref.make`) infer the instance type uniformly whether\n * the caller passes an `EchoTypeSchema` or a top-level `Type.Type` entity.\n *\n * Includes the instance-kind brand (`[KindId]`) so the phantom is assignable\n * to the matching public-side interface in `Type.ts` (`Type.Obj` /\n * `Type.Relation` / `Type.Type`). Each kind projects identity: instances of\n * an object-kind schema are object-kind entities, type-kind schemas produce\n * type-kind (persisted Type.Type) entities — the latter additionally carry\n * the `[SchemaKindId]` / `[StaticTypeSchemaSlot]` brands the echo-handler\n * proxy exposes on persisted Type entities.\n */\n readonly [InstancePhantomId]?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields> & {\n readonly [KindId]: K;\n } & (K extends EntityKind.Type\n ? {\n readonly [SchemaKindId]: EntityKind.Type;\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n }\n : {});\n}\n\n/**\n * Identity (typename + version) of the type meta-schema — the `Type.Type` that\n * every ECHO type entity is itself an instance of. Shared by the materialisation\n * vehicle ({@link persistentEntitySchema}) and `TypeSchema` so the two cannot\n * drift on identity.\n */\nexport const TypeMetaSchemaDXN = DXN.make('org.dxos.type.schema', '0.1.0');\n\n/**\n * Effect Schema that every `Type.Type` entity is an instance of: the meta-schema\n * struct `{ name?, jsonSchema, id }` branded as a type-kind ECHO entity. This is\n * the materialisation vehicle for `makeObject` below — the canonical user-facing\n * entity is `Type/type-schema.ts`'s `TypeSchema`, which carries the same shape\n * plus UI annotations.\n *\n * Kept self-contained (no import of `TypeSchema`) to avoid a bootstrap cycle:\n * `TypeSchema` is itself produced via `makeEchoTypeSchema`, so this builder must\n * not depend on it. `jsonSchema` is declared optional here (only on the\n * materialisation vehicle — the canonical `TypeSchema` keeps it required) so the\n * construction-time `Schema.asserts` does not force the field before it is\n * attached; it is populated immediately after via a lazy accessor (see\n * `makeEchoTypeSchema`).\n */\n// TODO(wittjosiah): Reconcile with `TypeSchema` (`Type/type-schema.ts`).\n// Both describe the same `org.dxos.type.schema` shape.\nconst persistentEntitySchema: Schema.Codec<AnyProperties, any> = (() => {\n const typename = DXN.getName(TypeMetaSchemaDXN);\n const version = DXN.getVersion(TypeMetaSchemaDXN)!;\n const struct = Schema.Struct({\n name: Schema.optional(Schema.String),\n jsonSchema: JsonSchemaType.pipe(Schema.optional),\n id: EntityId,\n });\n const ast = SchemaAST.annotate(struct.ast, {\n [TypeAnnotationId]: { kind: EntityKind.Type, typename, version } satisfies TypeAnnotation,\n ...makeTypeJsonSchemaAnnotation({ kind: EntityKind.Type, typename, version }),\n });\n return Schema.make<Schema.Codec<AnyProperties, any>>(ast);\n})();\n\n/**\n * @internal\n *\n * Build an in-memory `Type.Type` entity (the value returned by `Type.makeObject`\n * / `Type.makeRelation`). The result is a LIVE reactive `TypeSchema`\n * instance — identical in every respect to a persisted `Type.Type` except that\n * it is not yet attached to a database. It is mutable via `Type.update`, can be\n * passed to `db.add(...)` (which keeps the same proxy and swaps the handler),\n * and round-trips through `jsonSchema`.\n *\n * The source Effect Schema describing the user's type is cached on\n * `[StaticTypeSchemaSlot]` so `Type.getSchema(...)` returns it without a\n * jsonSchema round-trip; the cache is invalidated by the proxy set-trap when\n * `jsonSchema` is mutated (see `typed-handler.ts`).\n */\nexport const makeEchoTypeSchema = <\n Self extends Schema.Top,\n K extends EntityKind = EntityKind,\n // TODO(wittjosiah): Can this be inferred from the schema?\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n>(\n fields: Fields,\n ast: SchemaAST.AST,\n typename: string,\n version: string,\n kind: K,\n computeJsonSchema: () => JsonSchemaType,\n explicitId?: EntityId,\n): EchoTypeSchema<Self, {}, K, Fields> => {\n // Source Effect Schema describing the user's type — cached for `Type.getSchema`.\n // v4's `Schema.make` takes the whole schema type as one parameter, and a schema exposes its\n // channels as properties rather than through `Schema.Schema.*` helpers.\n const sourceSchema =\n Schema.make<\n Schema.Codec<\n EchoTypeSchemaProps<Self['Type']>,\n EchoTypeSchemaProps<Self['Encoded']>,\n Self['DecodingServices'],\n Self['EncodingServices']\n >\n >(ast);\n\n // `typename` / `version` route through `EntityMeta` (`key` / `version`) — the\n // canonical registry-provenance pair — not data fields. `keys` is empty for\n // in-memory declarations until persisted.\n const meta: Partial<EntityMeta> = { keys: [], key: typename, version };\n\n // Default to a deterministic id derived from `(typename, version)` so that\n // constructing a `Type.Type` entity never reaches `crypto.getRandomValues()`.\n // Cloudflare workerd forbids RNG calls in global scope, and the ~hundreds of\n // `Type.makeObject(...)` call sites across the monorepo execute at module top.\n // `setIdOnTarget` (see `proxy/make-object.ts`) short-circuits on a pre-supplied\n // valid id, so this also bypasses the `EntityId.random()` path inside `makeObject`.\n // Callers can override via `Type.makeObject(dxn, { id })` when they want a fresh\n // random id (e.g. inside a request handler where workerd does allow RNG).\n const id = explicitId ?? EntityId.deterministic(typename, version);\n\n // Materialise as a live reactive meta-schema instance. `jsonSchema` is attached\n // below as a getter (not passed here as data) for two reasons; see that accessor.\n const entity = makeObject(persistentEntitySchema, { id } as any, meta);\n\n const target = getProxyTarget(entity)!;\n // `jsonSchema` is always available, but computed once on first read rather than at\n // construction: serializing the AST walks `Schema.suspend(...)` thunks, and for a\n // self-referential type (`Schema.suspend(() => Self)`) that thunk hits `Self`'s TDZ\n // while we're still inside its `const` initializer. A getter also lets reads return\n // the raw object instead of a child reactive proxy.\n let memoizedJsonSchema: JsonSchemaType | undefined;\n Object.defineProperty(target, 'jsonSchema', {\n configurable: true,\n enumerable: true,\n get() {\n return (memoizedJsonSchema ??= computeJsonSchema());\n },\n set(value: JsonSchemaType) {\n memoizedJsonSchema = value;\n },\n });\n // Cache the source Effect Schema (read by `Type.getSchema` via the proxy's\n // `[StaticTypeSchemaSlot]` get-trap; invalidated on `jsonSchema` mutation).\n defineHiddenProperty(target, StaticTypeSchemaSlot, sourceSchema);\n // Schema-kind brand: what kind of instance this type describes. There is no\n // database handler to derive it for in-memory entities, so stamp it directly.\n defineHiddenProperty(target, SchemaKindId, kind);\n // Struct fields for introspection. A getter (not a data property) so reads return\n // the raw fields object rather than a child reactive proxy.\n Object.defineProperty(target, 'fields', { configurable: true, enumerable: false, get: () => fields });\n\n return entity as unknown as EchoTypeSchema<Self, {}, K, Fields>;\n};\n\nexport { isEntity } from './guard.ts';\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Types from 'effect/Types';\n\nimport { JsonSchemaFields, type JsonSchemaType } from './json-schema-type.ts';\n\n/**\n * Normalize schema to to draft-07 format.\n * Note: the input type does not necessarily match the {@link JsonSchemaType} type.\n */\nexport const normalizeSchema = (schema: JsonSchemaType): JsonSchemaType => {\n const copy = structuredClone(schema) as Types.DeepMutable<JsonSchemaType>;\n go(copy);\n return copy;\n};\n\nconst go = (schema: Types.DeepMutable<JsonSchemaType>) => {\n if (typeof schema !== 'object' || schema === null) {\n return;\n }\n\n if ((schema as any).exclusiveMaximum === true) {\n schema.exclusiveMaximum = schema.maximum;\n delete (schema as any).exclusiveMaximum;\n } else if ((schema as any).exclusiveMaximum === false) {\n delete (schema as any).exclusiveMaximum;\n }\n\n if ((schema as any).exclusiveMinimum === true) {\n schema.exclusiveMinimum = schema.minimum;\n delete (schema as any).exclusiveMinimum;\n } else if ((schema as any).exclusiveMinimum === false) {\n delete (schema as any).exclusiveMinimum;\n }\n\n // Delete all properties that are not in the JsonSchemaFields.\n for (const key of Object.keys(schema)) {\n if (!JsonSchemaFields.includes(key)) {\n delete (schema as any)[key];\n }\n }\n\n // Recursively normalize the schema.\n // Recursively normalize the schema.\n if (schema.properties) {\n goOnRecord(schema.properties);\n }\n if (schema.patternProperties) {\n goOnRecord(schema.patternProperties);\n }\n if (schema.propertyNames) {\n go(schema.propertyNames);\n }\n if (schema.definitions) {\n goOnRecord(schema.definitions);\n }\n if (schema.items) {\n maybeGoOnArray(schema.items);\n }\n if (schema.additionalItems) {\n maybeGoOnArray(schema.additionalItems);\n }\n if (schema.contains) {\n go(schema.contains);\n }\n if (schema.if) {\n go(schema.if);\n }\n if (schema.then) {\n go(schema.then);\n }\n if (schema.else) {\n go(schema.else);\n }\n if (schema.allOf) {\n maybeGoOnArray(schema.allOf);\n }\n if (schema.anyOf) {\n maybeGoOnArray(schema.anyOf);\n }\n if (schema.oneOf) {\n maybeGoOnArray(schema.oneOf);\n }\n if (schema.not) {\n go(schema.not);\n }\n if (schema.$defs) {\n goOnRecord(schema.$defs);\n }\n if (schema.reference) {\n go(schema.reference.schema);\n }\n};\n\nconst maybeGoOnArray = (value: any) => {\n if (Array.isArray(value)) {\n for (const item of value) {\n go(item);\n }\n } else if (typeof value === 'object' && value !== null) {\n go(value);\n }\n};\n\nconst goOnRecord = (record: Record<string, any>) => {\n for (const key of Object.keys(record)) {\n go(record[key]);\n }\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, type EntityId } from '@dxos/keys';\n\nimport type * as Type from '../../Type.ts';\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { EntityKind } from '../common/types/index.ts';\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeOptions, type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Object schema type with kind marker.\n */\nexport type EchoObjectSchema<\n Self extends Schema.Top,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, {}, EntityKind.Object, Fields>;\n\n/**\n * Schema for Obj entity types.\n * Pipeable function to add ECHO object annotations to a schema.\n */\nexport const EchoObjectSchema: {\n (\n dxn: DXN.DXN,\n options?: EchoTypeOptions,\n ): <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ) => EchoObjectSchema<Self, Fields>;\n} = (dxn, options) => {\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type.makeObject requires a versioned DXN: ${dxn}`);\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoObjectSchema<Self, Fields> => {\n // Annotation ids are string keys in Effect 4; this guards against a bundling mishap that\n // leaves the id undefined, which would silently drop the annotation.\n invariant(typeof TypeAnnotationId === 'string', 'Sanity.');\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n // Struct schemas expose `.fields`; retained for the schema's public field map.\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how `Expando` and other record-shaped types are\n // declared. (`mapFields` is unavailable here -- it is a `Struct` method and `self` is generic.)\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n // TODO(dmaretskyi): `extend` kills the annotations.\n ...self.ast.annotations,\n [TypeAnnotationId]: { kind: EntityKind.Object, typename, version } satisfies TypeAnnotation,\n // TODO(dmaretskyi): TypeIdentifierAnnotationId?\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Object,\n typename,\n version,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Object, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Object,\n () => toJsonSchema(Schema.make(ast)),\n options?.id,\n );\n };\n};\n\nexport const makeObjectType = <Self, _Schema extends Schema.Top>(\n dxn: DXN.DXN,\n schema: _Schema,\n options?: { id?: EntityId },\n): Type.ObjClass<Self, Schema.Schema.Type<_Schema>, {}> => {\n const type = EchoObjectSchema(dxn, options)(schema);\n const constructor = function ObjectType() {};\n Object.setPrototypeOf(constructor, type);\n // Boundary cast: constructor/prototype wiring cannot be expressed in TypeScript's type system.\n return constructor as unknown as Type.ObjClass<Self, Schema.Schema.Type<_Schema>, {}>;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, type EntityId } from '@dxos/keys';\n\n// Type-only imports (erased at runtime — no import cycle); `internal` may depend\n// on the top-level `Obj` / `Type` API at the type level only.\nimport type * as Obj from '../../Obj.ts';\nimport type * as Type from '../../Type.ts';\nimport {\n type TypeAnnotation,\n TypeAnnotationId,\n getEntityKind,\n getSchemaTypename,\n getTypeIdentifierAnnotation,\n} from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n EntityKind,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n type UnknownTypeSchema,\n getStaticTypeSchema,\n} from '../common/types/index.ts';\n\nexport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n};\n\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Source and target props on relations.\n */\n// TODO(burdon): any?\nexport type RelationSourceTargetRefs<Source = any, Target = any> = {\n /**\n * Source ECHO live object.\n */\n [RelationSourceId]: Source;\n\n /**\n * Target ECHO live object.\n */\n [RelationTargetId]: Target;\n};\n\nexport type RelationSource<R> = R extends RelationSourceTargetRefs<infer Source, infer _Target> ? Source : never;\nexport type RelationTarget<R> = R extends RelationSourceTargetRefs<infer _Source, infer Target> ? Target : never;\n\n/**\n * Accepted relation endpoint: an object-kind `Type.Type` entity (slot-backed)\n * or the branded `Obj.Unknown` schema. Source/target are constrained to these\n * — relations only connect object-kind entities.\n */\nexport type RelationEndpoint = Type.AnyObj | UnknownTypeSchema<any, EntityKind.Object>;\n\n/**\n * Resolves a relation endpoint to the instance type it describes — the source /\n * target instance recorded on the relation's `RelationSourceTargetRefs`.\n */\nexport type RelationEndpointInstance<S> =\n S extends UnknownTypeSchema<infer A, any> ? A : S extends Type.AnyObj ? Type.InstanceType<S> : unknown;\n\nexport type EchoRelationSchemaOptions<TSource extends RelationEndpoint, TTarget extends RelationEndpoint> = {\n dxn: DXN.DXN;\n source: TSource;\n target: TTarget;\n /**\n * Override the entity id stamped on the in-memory `Type.Type` value.\n *\n * Defaults to `EntityId.deterministic(typename, version)` — stable across processes\n * and workerd-safe (no `crypto.getRandomValues()` at module-evaluation time).\n */\n id?: EntityId;\n};\n\n/**\n * Relation schema type with kind marker. `SourceInstance` / `TargetInstance`\n * are the resolved endpoint instance types (see {@link RelationEndpointInstance}).\n */\nexport type EchoRelationSchema<\n Self extends Schema.Top,\n SourceInstance extends Obj.Unknown,\n TargetInstance extends Obj.Unknown,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, RelationSourceTargetRefs<SourceInstance, TargetInstance>, EntityKind.Relation, Fields>;\n\n/**\n * Schema for Relation entity types.\n */\nexport const EchoRelationSchema = <Source extends RelationEndpoint, Target extends RelationEndpoint>({\n dxn,\n source,\n target,\n id: explicitId,\n}: EchoRelationSchemaOptions<Source, Target>) => {\n // `source` / `target` are `Type.Type` entities (slot-backed) or the branded\n // `Obj.Unknown` schema (used directly); resolve each to its Effect Schema for\n // the schema-side machinery (DXN ref + entity-kind checks).\n const sourceSchema = source != null ? (getStaticTypeSchema(source) ?? source) : source;\n const targetSchema = target != null ? (getStaticTypeSchema(target) ?? target) : target;\n assertArgument(Schema.isSchema(sourceSchema), 'source');\n assertArgument(Schema.isSchema(targetSchema), 'target');\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type.makeRelation requires a versioned DXN: ${dxn}`);\n const sourceDXN = getDXNForRelationSchemaRef(sourceSchema);\n const targetDXN = getDXNForRelationSchemaRef(targetSchema);\n if (getEntityKind(sourceSchema) !== EntityKind.Object) {\n raise(new Error('Source schema must be an echo object schema.'));\n }\n if (getEntityKind(targetSchema) !== EntityKind.Object) {\n raise(new Error('Target schema must be an echo object schema.'));\n }\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoRelationSchema<Self, RelationEndpointInstance<Source>, RelationEndpointInstance<Target>, Fields> => {\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n // Struct schemas expose `.fields`; retained for the schema's public field map.\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how `Expando` and other record-shaped types are\n // declared. (`mapFields` is unavailable here -- it is a `Struct` method and `self` is generic.)\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n // TODO(dmaretskyi): `extend` kills the annotations.\n ...self.ast.annotations,\n [TypeAnnotationId]: {\n kind: EntityKind.Relation,\n typename,\n version,\n sourceSchema: sourceDXN,\n targetSchema: targetDXN,\n } satisfies TypeAnnotation,\n // TODO(dmaretskyi): TypeIdentifierAnnotationId?\n\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Relation,\n typename,\n version,\n relationSource: sourceDXN,\n relationTarget: targetDXN,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Relation, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Relation,\n () => toJsonSchema(Schema.make(ast)),\n explicitId,\n );\n };\n};\n\nexport const getDXNForRelationSchemaRef = (schema: Schema.Top): DXN.DXN => {\n assertArgument(Schema.isSchema(schema), 'schema');\n const identifier = getTypeIdentifierAnnotation(schema);\n if (identifier) {\n return DXN.tryMake(identifier) ?? raise(new Error(`Invalid schema identifier: ${identifier}`));\n }\n\n const typename = getSchemaTypename(schema);\n if (!typename) {\n throw new Error('Schema must have a typename');\n }\n\n return DXN.make(typename);\n};\n\nexport const makeRelationType = (options: {\n dxn: DXN.DXN;\n source: RelationEndpoint;\n target: RelationEndpoint;\n schema: Schema.Top;\n id?: EntityId;\n}): Type.RelationClass<unknown, unknown, unknown, unknown, {}> => {\n const type = EchoRelationSchema({\n dxn: options.dxn,\n source: options.source,\n target: options.target,\n id: options.id,\n })(options.schema);\n const constructor = function RelationType() {};\n Object.setPrototypeOf(constructor, type);\n // Boundary cast: constructor/prototype wiring cannot be expressed in TypeScript's type system.\n return constructor as unknown as Type.RelationClass<unknown, unknown, unknown, unknown, {}>;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\nimport { DXN } from '@dxos/keys';\n\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations.ts';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util.ts';\nimport { EntityKind } from '../common/types/index.ts';\nimport { toJsonSchema } from '../JsonSchema/index.ts';\nimport { type EchoTypeOptions, type EchoTypeSchema, makeEchoTypeSchema } from './entity.ts';\n\n/**\n * Type-kind schema marker — produced by {@link EchoTypeKindSchema}.\n *\n * Distinguishes meta-schemas (entities of `EntityKind.Type`, such as the\n * built-in `Type.Type` TypeSchema) from object and relation types.\n */\nexport type EchoTypeKindSchema<\n Self extends Schema.Top,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> = EchoTypeSchema<Self, {}, EntityKind.Type, Fields>;\n\n/**\n * Pipeable that brands a schema as a type-kind ECHO entity. Mirrors\n * {@link EchoObjectSchema} / {@link EchoRelationSchema}, but stamps the\n * resulting entity with `[SchemaKindId]: EntityKind.Type` and a matching\n * `TypeAnnotation.kind = 'type'` so meta-schemas surface uniformly through\n * `Type.isTypeKind`, `Filter.type`, etc.\n */\nexport const EchoTypeKindSchema: {\n (\n dxn: DXN.DXN,\n options?: EchoTypeOptions,\n ): <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ) => EchoTypeKindSchema<Self, Fields>;\n} = (dxn, options) => {\n const typename = DXN.getName(dxn);\n const version = DXN.getVersion(dxn);\n invariant(version, `Type-kind schemas require a versioned DXN: ${dxn}`);\n\n return <Self extends Schema.Top, Fields extends Schema.Struct.Fields = Schema.Struct.Fields>(\n self: Self & { fields?: Fields },\n ): EchoTypeKindSchema<Self, Fields> => {\n invariant(SchemaAST.isObjects(self.ast), 'Schema must be a TypeLiteral.');\n\n const fields = ((self as any).fields ?? {}) as Fields;\n\n // The id is prepended to the existing object node rather than rebuilt from `.fields`:\n // rebuilding drops index signatures, which is how record-shaped types are declared.\n const schemaWithId = new SchemaAST.Objects(\n self.ast.propertySignatures.some((property) => property.name === 'id')\n ? self.ast.propertySignatures\n : [...self.ast.propertySignatures, new SchemaAST.PropertySignature('id', Schema.String.ast)],\n self.ast.indexSignatures,\n );\n const ast = SchemaAST.annotate(schemaWithId, {\n ...self.ast.annotations,\n [TypeAnnotationId]: { kind: EntityKind.Type, typename, version } satisfies TypeAnnotation,\n ...makeTypeJsonSchemaAnnotation({\n kind: EntityKind.Type,\n typename,\n version,\n }),\n });\n\n return makeEchoTypeSchema<Self, EntityKind.Type, Fields>(\n fields,\n ast,\n typename,\n version,\n EntityKind.Type,\n () => toJsonSchema(Schema.make(ast)),\n options?.id,\n );\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { assertArgument } from '@dxos/invariant';\n\nimport { type AnyEntity, VersionTypeId } from '../common/types/index.ts';\nimport { ObjectVersionId } from './model.ts';\n\n/**\n * Represent entity version.\n * May be backed by Automerge.\n * Entities with no history are not versioned.\n * Named EntityVersion to avoid conflict with types/version.ts.\n */\nexport interface EntityVersion {\n [VersionTypeId]: {};\n\n /**\n * Whether the entity is versioned.\n */\n versioned: boolean;\n\n /**\n * Automerge heads.\n */\n automergeHeads?: string[];\n}\n\nconst unversioned: EntityVersion = {\n [VersionTypeId]: {},\n versioned: false,\n};\n\n/**\n * Checks that `obj` is a version object.\n */\nexport const isVersion = (entity: unknown): entity is EntityVersion => {\n return entity != null && typeof entity === 'object' && VersionTypeId in entity;\n};\n\n/**\n * Returns the version of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const version = (entity: AnyEntity): EntityVersion => {\n const ver = (entity as any)[ObjectVersionId];\n if (ver === undefined) {\n return unversioned;\n }\n return ver;\n};\n\n/**\n * Checks that `version` is a valid version object.\n */\nexport const versionValid = (ver: EntityVersion): boolean => {\n assertArgument(isVersion(ver), 'version', 'Invalid version object');\n return !!ver.versioned;\n};\n\nexport type VersionCompareResult = 'unversioned' | 'equal' | 'different';\n\n/**\n * Compares two versions.\n * @param version1\n * @param version2\n * @returns 'unversioned' if either entity is unversioned, 'equal' if the versions are equal, 'different' if the versions are different.\n */\nexport const compareVersions = (version1: EntityVersion, version2: EntityVersion): VersionCompareResult => {\n assertArgument(isVersion(version1), 'version1', 'Invalid version object');\n assertArgument(isVersion(version2), 'version2', 'Invalid version object');\n\n if (!versionValid(version1) || !versionValid(version2)) {\n return 'unversioned';\n }\n\n if (version1.automergeHeads?.length !== version2.automergeHeads?.length) {\n return 'different';\n }\n if (version1.automergeHeads?.some((head) => !version2.automergeHeads?.includes(head))) {\n return 'different';\n }\n\n return 'equal';\n};\n\nexport const encodeVersion = (ver: EntityVersion): string => {\n return JSON.stringify(ver);\n};\n\nexport const decodeVersion = (ver: string): EntityVersion => {\n const parsed = JSON.parse(ver);\n parsed[VersionTypeId] = {};\n return parsed;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type EntityId } from '@dxos/keys';\n\n/**\n * Follow `system.mergedInto` from `start` to the entity that finally survives.\n *\n * This is the one piece of the convergence-key merge the client needs: resolution and the\n * transitive-deletion walks follow redirects, while the merge itself (winner selection, the\n * field-wise merge function) runs in the worker — see `echo-host`'s merge core.\n *\n * Concurrent merges on different views leave chains rather than a single hop: a peer seeing\n * `{X, Y}` writes `Y -> X` while a peer that also sees a smaller `Z` writes `X -> Z`, so `Y`\n * reaches `Z` only transitively.\n *\n * Termination does not rely on the id-decreasing invariant holding in the data: an edge that\n * fails to decrease the id is treated as the end of the chain, which stops both cycles and\n * forward references without reading unbounded history.\n *\n * @param lookup Returns the `mergedInto` of an entity, or `undefined` if it was not merged away.\n */\nexport const resolveMergeRedirect = (start: EntityId, lookup: (id: EntityId) => EntityId | undefined): EntityId => {\n let current = start;\n for (;;) {\n const next = lookup(current);\n if (next === undefined || next >= current) {\n return current;\n }\n current = next;\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport { type EncodedReference, EntityStructure, isEncodedReference } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId, URI } from '@dxos/keys';\nimport {\n assumeType,\n decodeUint8ArrayFromJson,\n deepMapValues,\n encodeUint8ArrayToJson,\n isEncodedUint8Array,\n visitValues,\n} from '@dxos/util';\n\nimport type * as Database from '../../Database.ts';\nimport type * as Obj from '../../Obj.ts';\nimport { getTypeAnnotation, getTypeURI, setTypename } from '../Annotation/index.ts';\nimport { defineHiddenProperty, typedJsonSerializer } from '../common/proxy/index.ts';\nimport {\n type AnyEntity,\n ATTR_PARENT,\n ATTR_TYPE,\n EntityKind,\n KindId,\n ParentId,\n setSchema,\n setType,\n} from '../common/types/index.ts';\nimport { ATTR_META, EntityMetaSchema, SCALAR_META_FIELDS, isTagEntity } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport {\n ATTR_DELETED,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_SELF_URI_LEGACY,\n ObjectDatabaseId,\n ObjectDeletedId,\n type ObjectJSON,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n SelfURIId,\n TypeMetaSchemaDXN,\n assertObjectModel,\n} from '../Entity/index.ts';\nimport { Ref, type RefResolver, refFromEncodedReference, setRefResolver } from '../Ref/index.ts';\n\ntype DeepReplaceRef<T> =\n T extends Ref<any>\n ? EncodedReference\n : T extends object\n ? {\n [K in keyof T]: DeepReplaceRef<T[K]>;\n }\n : T;\n\ntype SerializedObject<T extends { id: string }> = {\n [K in keyof T]: DeepReplaceRef<T[K]>;\n} & ObjectJSON;\n\n/**\n * Converts object to it's JSON representation.\n */\nexport const objectToJSON = <T extends AnyEntity>(obj: T): SerializedObject<T> => {\n const typename = getTypeURI(obj);\n invariant(typename && typeof typename === 'string');\n return typedJsonSerializer.call(obj);\n};\n\n/**\n * Creates an object from it's json representation.\n * Performs schema validation.\n * References and schema will be resolvable if the `refResolver` is provided.\n * The function need to be async to support resolving the schema as well as the relation endpoints.\n *\n * @param jsonData - JSON representation of the object.\n * @param options.refResolver - Resolver for references.\n * @param options.uri - Override object URI.\n * @param options.database - Database to associate with the object.\n */\nexport const objectFromJSON = async (\n jsonData: unknown,\n {\n refResolver,\n uri,\n database,\n parent,\n }: { refResolver?: RefResolver; uri?: URI.URI; database?: Database.Database; parent?: Obj.Unknown } = {},\n): Promise<AnyEntity> => {\n assumeType<ObjectJSON>(jsonData);\n assertArgument(typeof jsonData === 'object' && jsonData !== null, 'jsonData', 'expect object');\n assertArgument(typeof jsonData[ATTR_TYPE] === 'string', 'jsonData[ATTR_TYPE]', 'expected object to have a type');\n assertArgument(typeof jsonData.id === 'string', 'jsonData.id', 'expected object to have an id');\n\n const type = URI.make(jsonData[ATTR_TYPE]);\n const schema = await refResolver?.resolveSchema(type);\n invariant(schema === undefined || Schema.isSchema(schema));\n const decodedInput = restoreUint8Arrays(stripInternalJsonKeys(jsonData));\n\n let obj: any;\n if (schema != null) {\n obj = await Schema.decodeUnknownPromise(schema)(decodedInput);\n if (refResolver) {\n setRefResolverOnData(obj, refResolver);\n }\n } else {\n obj = decodeGeneric(decodedInput, { refResolver });\n }\n\n invariant(EntityId.isValid(obj.id), 'Invalid object id');\n setTypename(obj, type);\n if (schema) {\n setSchema(obj, schema);\n }\n // Resolve and stamp the source type entity, if the resolver provides one.\n // Lets `Obj.getType` / `Entity.getType` return a stable entity for objects\n // loaded via `Obj.fromJSON` (serializer / queue paths).\n if (refResolver?.resolveType) {\n const typeEntity = await refResolver.resolveType(type);\n if (typeEntity != null) {\n setType(obj, typeEntity);\n }\n }\n\n const isRelation =\n typeof jsonData[ATTR_RELATION_SOURCE] === 'string' || typeof jsonData[ATTR_RELATION_TARGET] === 'string';\n if (isRelation) {\n const sourceDxn = jsonData[ATTR_RELATION_SOURCE] ?? raise(new TypeError('Missing relation source'));\n const targetDxn = jsonData[ATTR_RELATION_TARGET] ?? raise(new TypeError('Missing relation target'));\n\n const source = (await refResolver?.resolveLegacy(sourceDxn)) as AnyEntity | undefined;\n const target = (await refResolver?.resolveLegacy(targetDxn)) as AnyEntity | undefined;\n\n defineHiddenProperty(obj, KindId, EntityKind.Relation);\n defineHiddenProperty(obj, RelationSourceDXNId, sourceDxn);\n defineHiddenProperty(obj, RelationTargetDXNId, targetDxn);\n defineHiddenProperty(obj, RelationSourceId, source);\n defineHiddenProperty(obj, RelationTargetId, target);\n } else {\n // Honour the schema's TypeAnnotation kind — persisted `Type.Type` entities\n // (e.g. dynamic schemas loaded from a snapshot import) must brand as\n // `KindId = Type`, not Object, otherwise `Filter.type(Type.Type)` /\n // `Type.isType` skip them and the schema registry never picks them up.\n // Mirrors the kind resolution in `createObject` (the in-memory path).\n const annotationKind = schema != null ? getTypeAnnotation(schema)?.kind : undefined;\n defineHiddenProperty(obj, KindId, annotationKind === EntityKind.Type ? EntityKind.Type : EntityKind.Object);\n }\n\n if (typeof jsonData[ATTR_META] === 'object') {\n const { tags: encodedTags, ...encodedMeta } = normalizeMeta(jsonData[ATTR_META]);\n const meta = await Schema.decodeUnknownPromise(EntityMetaSchema)({ ...encodedMeta, tags: [] });\n invariant(Array.isArray(meta.keys));\n defineHiddenProperty(obj, MetaId, { ...meta, tags: await resolveTags(encodedTags, refResolver) });\n } else {\n defineHiddenProperty(obj, MetaId, {\n keys: [],\n tags: [],\n annotations: {},\n });\n }\n\n if (jsonData[ATTR_PARENT]) {\n const parentDxn = jsonData[ATTR_PARENT];\n const resolvedParent = (await refResolver?.resolveLegacy(parentDxn)) as Obj.Unknown | undefined;\n defineHiddenProperty(obj, ParentId, resolvedParent);\n } else if (parent) {\n defineHiddenProperty(obj, ParentId, parent);\n }\n\n if (uri) {\n defineHiddenProperty(obj, SelfURIId, uri);\n }\n\n if (database) {\n defineHiddenProperty(obj, ObjectDatabaseId, database);\n }\n\n // Carry the deletion marker so a tombstone snapshot (e.g. a feed item removed via `Feed.remove`)\n // hydrates with `Obj.isDeleted === true` rather than as a live object.\n defineHiddenProperty(obj, ObjectDeletedId, jsonData[ATTR_DELETED] === true);\n\n assertObjectModel(obj);\n invariant((obj as any)[ATTR_TYPE] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_META] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_DELETED] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_SELF_URI] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_SELF_URI_LEGACY] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_RELATION_SOURCE] === undefined, 'Invalid object model');\n invariant((obj as any)[ATTR_RELATION_TARGET] === undefined, 'Invalid object model');\n\n return obj;\n};\n\n/**\n * Resolves the encoded tag references of a serialized meta to {@link Tag} entities. A tag the\n * resolver cannot supply is dropped, as an unresolved parent is: `meta.tags` holds entities only.\n */\nconst resolveTags = async (encodedTags: readonly unknown[], refResolver: RefResolver | undefined) => {\n if (refResolver == null || encodedTags.length === 0) {\n return [];\n }\n const resolved = await Promise.all(\n encodedTags.map((tag) => (isEncodedReference(tag) ? refResolver.resolveLegacy(URI.make(tag['/'])) : undefined)),\n );\n return resolved.filter(isTagEntity);\n};\n\n/**\n * Backfills required meta fields and upgrades legacy `tags` (bare URI strings) to encoded references\n * so serialized data produced before the tags-as-refs migration still decodes.\n */\nconst normalizeMeta = (meta: any): any => {\n const tags = Array.isArray(meta?.tags)\n ? meta.tags.map((tag: unknown) => (typeof tag === 'string' ? { '/': URI.make(tag) } : tag))\n : [];\n // Coalesce required fields so explicit `undefined` in legacy input doesn't override the defaults.\n return {\n ...meta,\n keys: Array.isArray(meta?.keys) ? meta.keys : [],\n tags,\n annotations: meta?.annotations ?? {},\n };\n};\n\nconst decodeGeneric = (jsonData: unknown, options: { refResolver?: RefResolver }) => {\n const props = stripInternalJsonKeys(jsonData);\n\n return deepMapValues(props, (value, visitor) => {\n if (isEncodedReference(value)) {\n return refFromEncodedReference(value, options.refResolver);\n }\n if (isEncodedUint8Array(value)) {\n return decodeUint8ArrayFromJson(value);\n }\n\n return visitor(value);\n });\n};\n\n/**\n * Recursively replaces encoded `Uint8Array` JSON markers with actual `Uint8Array` instances.\n * Runs before schema decoding so `Schema.Uint8Array` sees real bytes.\n */\nconst restoreUint8Arrays = (data: unknown): any =>\n deepMapValues(data, (value, recurse) => {\n if (isEncodedUint8Array(value)) {\n return decodeUint8ArrayFromJson(value);\n }\n return recurse(value);\n });\n\nconst stripInternalJsonKeys = (jsonData: unknown) => {\n const {\n [ATTR_TYPE]: _type,\n [ATTR_META]: _meta,\n [ATTR_DELETED]: _deleted,\n [ATTR_SELF_URI]: _selfUri,\n [ATTR_SELF_URI_LEGACY]: _legacySelfUri,\n [ATTR_RELATION_SOURCE]: _relationSource,\n [ATTR_RELATION_TARGET]: _relationTarget,\n ...props\n } = jsonData as any;\n\n return props;\n};\n\nexport const setRefResolverOnData = (obj: AnyEntity, refResolver: RefResolver) => {\n const visitor = (value: unknown) => {\n if (Ref.isRef(value)) {\n setRefResolver(value, refResolver);\n } else {\n visitValues(value, visitor);\n }\n };\n\n visitor(obj);\n};\n\n/**\n * Convert EntityStructure to JSON data for indexing.\n * Different from {@link objectToJSON} as it takes the internal {@link EntityStructure} representation directly\n */\nexport const objectStructureToJson = (objectId: EntityId, structure: EntityStructure): Obj.JSON => {\n const typeRef = EntityStructure.getTypeReference(structure)?.['/'];\n const parent = EntityStructure.getParent(structure)?.['/'];\n const source = EntityStructure.getRelationSource(structure)?.['/'];\n const target = EntityStructure.getRelationTarget(structure)?.['/'];\n // Included so the indexer sees the meta section (notably `convergenceKey`, the merge trigger) —\n // matching the feed path, whose blocks carry `@meta` wholesale.\n const meta = structure.meta;\n const metaNotEmpty =\n meta !== undefined &&\n (meta.keys?.length > 0 ||\n (meta.tags?.length ?? 0) > 0 ||\n (meta.annotations !== undefined && Object.keys(meta.annotations).length > 0) ||\n SCALAR_META_FIELDS.some((field) => (meta as Record<string, unknown>)[field] !== undefined));\n return {\n ...encodeBytes(structure.data),\n id: objectId,\n [ATTR_META]: metaNotEmpty ? (meta as Obj.JSON[typeof ATTR_META]) : undefined,\n [ATTR_TYPE]: typeRef ? URI.make(typeRef) : undefined,\n [ATTR_DELETED]: EntityStructure.isDeleted(structure),\n [ATTR_PARENT]: parent !== undefined ? EID.tryParse(parent) : undefined,\n [ATTR_RELATION_SOURCE]: source !== undefined ? EID.tryParse(source) : undefined,\n [ATTR_RELATION_TARGET]: target !== undefined ? EID.tryParse(target) : undefined,\n };\n};\n\n/**\n * Bytes in the DAG-JSON `{ '/': { bytes } }` form the feed serializer writes, which plain JSON would flatten.\n * Only arrays and plain objects are walked, so a document's raw strings keep the `toJSON` that writes them as text.\n */\nconst encodeBytes = <T>(value: T): T =>\n (value instanceof Uint8Array\n ? encodeUint8ArrayToJson(value)\n : Array.isArray(value)\n ? value.map(encodeBytes)\n : typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeBytes(item)]))\n : value) as T;\n\nconst STRUCTURE_JSON_KEYS: ReadonlySet<string> = new Set([\n 'id',\n ATTR_TYPE,\n ATTR_META,\n ATTR_DELETED,\n ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n]);\n\n/**\n * Inverse of {@link objectStructureToJson}, for reading an object from the index's JSON. The JSON carries\n * no `system.kind`, so it is inferred from the relation endpoints and the type; nor the merge fields, and\n * `createdAt` comes from the caller.\n */\nexport const objectStructureFromJson = (\n json: Obj.JSON,\n { createdAt }: { createdAt?: number } = {},\n): EntityStructure => {\n const record = json as Record<string, unknown>;\n const data = Object.fromEntries(\n Object.entries(record)\n .filter(([key]) => !STRUCTURE_JSON_KEYS.has(key))\n .map(([key, value]) => [\n key,\n deepMapValues(value, (value, recurse) =>\n isEncodedUint8Array(value) ? decodeUint8ArrayFromJson(value) : recurse(value),\n ),\n ]),\n );\n const reference = (value: unknown): EncodedReference | undefined =>\n typeof value === 'string' ? { '/': URI.make(value) } : undefined;\n const type = reference(record[ATTR_TYPE]);\n const source = reference(record[ATTR_RELATION_SOURCE]);\n const target = reference(record[ATTR_RELATION_TARGET]);\n const parent = reference(record[ATTR_PARENT]);\n const meta = record[ATTR_META] as Partial<EntityStructure['meta']> | undefined;\n return {\n system: {\n kind:\n source || target\n ? EntityKind.Relation\n : type?.['/'] === TypeMetaSchemaDXN.toString()\n ? EntityKind.Type\n : EntityKind.Object,\n ...(type && { type }),\n ...(parent && { parent }),\n ...(source && { source }),\n ...(target && { target }),\n ...(record[ATTR_DELETED] === true && { deleted: true }),\n ...(createdAt !== undefined && { createdAt }),\n },\n meta: { ...meta, keys: meta?.keys ?? [] },\n data,\n };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as semver from 'semver';\n\nimport { EncodedReference, type QueryAST, isEncodedReference } from '@dxos/echo-protocol';\nimport { DXN, EID, EntityId } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport { getTypeURI } from '../Annotation/annotations.ts';\nimport { getMetaChecked } from '../common/api/meta.ts';\nimport { type AnyEntity, ParentId } from '../common/types/index.ts';\nimport { type InternalObjectProps } from '../Entity/model.ts';\nimport { objectToJSON } from '../Obj/json-serializer.ts';\n\n/**\n * Matches a tag filter against an object's stored tags. Tags may be stored as encoded references or\n * (in legacy data) bare URI strings, and those URIs may be in legacy DXN form. Both sides are\n * normalized to the canonical EID before comparing.\n */\nexport const matchesTag = (tags: readonly unknown[], filterTag: string): boolean => {\n const canonical = (uri: string): string => {\n const eid = EID.tryParse(uri);\n return (eid && EID.getEntityId(eid)) || uri;\n };\n const normalize = (tag: unknown): string =>\n canonical(isEncodedReference(tag) ? EncodedReference.toURI(tag) : (tag as string));\n const target = canonical(filterTag);\n return tags.some((tag) => normalize(tag) === target);\n};\n\n/**\n * Matches a meta `key` / `version` constraint against an object's meta `key` and `version`.\n */\nexport const matchMetaKey = (\n key: string,\n versionRange: string | undefined,\n objKey: string | undefined,\n objVersion: string | undefined,\n): boolean => {\n if (objKey !== key) {\n return false;\n }\n if (versionRange === undefined) {\n return true;\n }\n if (objVersion === undefined || semver.valid(objVersion) === null) {\n return false;\n }\n if (semver.validRange(versionRange) === null) {\n return false;\n }\n return semver.satisfies(objVersion, versionRange, { includePrerelease: true });\n};\n\n/**\n * Compares a filter's type discriminator against the value stored on an object's `system.type`.\n */\nexport const compareTypenameStrings = (expectedStr: string, actualStr: string): boolean => {\n // Identical strings agree under every branch below, and a type query compares the same pair once\n // per candidate, so the parse is skipped rather than repeated.\n if (expectedStr === actualStr) {\n return true;\n }\n\n const expectedEid = EID.tryParse(expectedStr);\n if (expectedEid) {\n const actualEid = EID.tryParse(actualStr);\n if (!actualEid) {\n return false;\n }\n if (EID.getEntityId(expectedEid) !== EID.getEntityId(actualEid)) {\n return false;\n }\n const expectedSpaceId = EID.getSpaceId(expectedEid);\n const actualSpaceId = EID.getSpaceId(actualEid);\n return expectedSpaceId === undefined || actualSpaceId === undefined || expectedSpaceId === actualSpaceId;\n }\n\n const expectedDxn = DXN.tryMake(expectedStr);\n if (expectedDxn) {\n const actualDxn = DXN.tryMake(actualStr);\n if (!actualDxn) {\n return false;\n }\n if (DXN.getName(expectedDxn) !== DXN.getName(actualDxn)) {\n return false;\n }\n const expectedVersion = DXN.getVersion(expectedDxn);\n const actualVersion = DXN.getVersion(actualDxn);\n return expectedVersion === undefined || actualVersion === undefined || expectedVersion === actualVersion;\n }\n\n return expectedStr === actualStr;\n};\n\nconst structuralMatch = (filterObj: any, targetObj: any, strict = true): boolean => {\n if (typeof filterObj !== 'object' || filterObj === null) {\n return filterObj === targetObj;\n }\n\n if (typeof targetObj !== 'object' || targetObj === null) {\n return false;\n }\n\n const filterKeys = Object.keys(filterObj);\n const targetKeys = Object.keys(targetObj);\n if (strict && filterKeys.length !== targetKeys.length) {\n return false;\n }\n\n return filterKeys.every((key) => {\n if (!(key in targetObj)) {\n return false;\n }\n const filterValue = filterObj[key];\n const targetValue = targetObj[key];\n\n if (typeof filterValue === 'object' && filterValue !== null) {\n return structuralMatch(filterValue, targetValue);\n }\n\n return filterValue === targetValue;\n });\n};\n\n/** Normalizes an encoded reference to its URI string so ref-valued properties compare by identity. */\nconst _normalizeInValue = (value: unknown): unknown =>\n isEncodedReference(value) ? EncodedReference.toURI(value) : value;\n\n/**\n * Memoizes a `Set` per `values` array so `Filter.in` membership is O(1) rather than\n * `Array.includes`'s O(n) — this matters most for large sets projected from a subquery\n * (`Filter.in(query.project(...))`, resolved to a literal `in` by the query executor), but\n * also speeds up ordinary literal-list `Filter.in`. Keyed by array identity: the planner and\n * executor never mutate a filter's `values` array in place, so the cache stays valid for the\n * array's lifetime.\n */\nconst _inSetCache = new WeakMap<readonly unknown[], Set<unknown>>();\nconst _getInSet = (values: readonly unknown[]): Set<unknown> => {\n let set = _inSetCache.get(values);\n if (!set) {\n set = new Set(values.map(_normalizeInValue));\n _inSetCache.set(values, set);\n }\n return set;\n};\n\nexport const filterMatchValue = (filter: QueryAST.Filter, value: unknown): boolean => {\n switch (filter.type) {\n case 'compare': {\n const compareValue = filter.value as any;\n switch (filter.operator) {\n case 'eq':\n if (isEncodedReference(compareValue)) {\n if (!isEncodedReference(value)) {\n return false;\n }\n return EncodedReference.toURI(value) === EncodedReference.toURI(compareValue);\n }\n return value === compareValue;\n case 'neq':\n return value !== compareValue;\n case 'gt':\n return (value as any) > compareValue;\n case 'gte':\n return (value as any) >= compareValue;\n case 'lt':\n return (value as any) < compareValue;\n case 'lte':\n return (value as any) <= compareValue;\n default:\n return false;\n }\n }\n case 'object': {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n if (filter.props) {\n for (const [key, valueFilter] of Object.entries(filter.props)) {\n const nestedValue = (value as any)[key];\n if (!filterMatchValue(valueFilter, nestedValue)) {\n return false;\n }\n }\n }\n\n return true;\n }\n case 'in': {\n return _getInSet(filter.values).has(_normalizeInValue(value));\n }\n case 'in-query': {\n throw new Error('in-query filters must be resolved to a literal `in` by the query executor before matching.');\n }\n case 'contains': {\n if (!Array.isArray(value)) {\n return false;\n }\n\n return value.some((element) => {\n if (typeof filter.value === 'object' && filter.value !== null && !Array.isArray(filter.value)) {\n return structuralMatch(filter.value, element);\n }\n\n return element === filter.value;\n });\n }\n case 'range': {\n return (value as any) >= filter.from && (value as any) <= filter.to;\n }\n case 'not': {\n return !filterMatchValue(filter.filter, value);\n }\n case 'and': {\n return filter.filters.every((f) => filterMatchValue(f, value));\n }\n case 'or': {\n return filter.filters.some((f) => filterMatchValue(f, value));\n }\n default:\n return false;\n }\n};\n\n/**\n * Meta as the filter walker needs it, flattened out of whichever representation supplies it.\n */\nexport type FilterRecordMeta = {\n keys?: readonly { source?: string; id?: string }[];\n key?: string;\n version?: string;\n /** Encoded references or bare URI strings — {@link matchesTag} normalizes both. */\n tags?: readonly unknown[];\n annotations?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Reads the fields a filter needs out of one representation of an entity.\n *\n * The representations an executor matches against — a live proxy, a raw Automerge document, the\n * `ObjectJSON` form — walk the filter AST identically and differ only in where each field lives, so\n * one walker over an accessor replaces a copy of the walk per representation.\n */\nexport interface FilterRecordAccessor<T> {\n getId(record: T): string;\n getTypeURI(record: T): string | undefined;\n\n /** Filterable data properties by name, or `undefined` when the record cannot be read at all. */\n getProps(record: T): Record<string, unknown> | undefined;\n getMeta(record: T): FilterRecordMeta;\n hasParent(record: T): boolean;\n\n /**\n * In-memory full-text match. Only representations backed by no index implement it; the rest\n * return `false` and leave text search to the index.\n */\n matchTextSearch(filter: QueryAST.Filter & { type: 'text-search' }, record: T): boolean;\n}\n\n/**\n * Builds a filter matcher over one record representation.\n * The leaf predicates ({@link filterMatchValue}, {@link compareTypenameStrings}, {@link matchesTag},\n * {@link matchMetaKey}) are shared regardless — this shares the tree walk around them.\n */\nexport const makeFilterMatcher = <T>(\n accessor: FilterRecordAccessor<T>,\n): ((filter: QueryAST.Filter, record: T) => boolean) => {\n const match = (filter: QueryAST.Filter, record: T): boolean => {\n switch (filter.type) {\n case 'object': {\n if (filter.typename !== null) {\n const typeURI = accessor.getTypeURI(record);\n if (!typeURI || !compareTypenameStrings(filter.typename, typeURI)) {\n return false;\n }\n }\n\n if (filter.id && filter.id.length > 0 && !filter.id.includes(accessor.getId(record))) {\n return false;\n }\n\n if (filter.props) {\n const props = accessor.getProps(record);\n if (props === undefined) {\n return false;\n }\n for (const [key, valueFilter] of Object.entries(filter.props)) {\n // `@`-prefixed keys address annotations (`@type`, `@meta`), never data.\n if (key.startsWith('@')) {\n continue;\n }\n if (!filterMatchValue(valueFilter, props[key])) {\n return false;\n }\n }\n }\n\n // Meta is read lazily: on a live proxy it costs a sub-proxy walk that most filters never need.\n const foreignKeys =\n filter.foreignKeys != null && filter.foreignKeys.length > 0 ? filter.foreignKeys : undefined;\n if (foreignKeys !== undefined || filter.metaKey !== undefined) {\n const meta = accessor.getMeta(record);\n if (\n foreignKeys !== undefined &&\n !foreignKeys.some((fk) => meta.keys?.some((key) => key.source === fk.source && key.id === fk.id))\n ) {\n return false;\n }\n if (\n filter.metaKey !== undefined &&\n !matchMetaKey(filter.metaKey, filter.metaVersion, meta.key, meta.version)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n case 'tag': {\n return matchesTag(accessor.getMeta(record).tags ?? [], filter.tag);\n }\n\n case 'annotation': {\n const annotations = accessor.getMeta(record).annotations;\n if (annotations === undefined || !(filter.key in annotations)) {\n return false;\n }\n return filter.value === undefined || annotations[filter.key] === filter.value;\n }\n\n case 'text-search': {\n return accessor.matchTextSearch(filter, record);\n }\n\n case 'timestamp': {\n throw new Error('Timestamp filters must be handled at the index level, not in-memory matching.');\n }\n\n case 'child-of': {\n throw new Error('child-of filters must be handled at the executor level, not in-memory matching.');\n }\n\n case 'changes': {\n throw new Error('changes filters select change records on the host; they never match an object.');\n }\n\n case 'has-parent': {\n return accessor.hasParent(record) === filter.value;\n }\n\n case 'mnemonic': {\n return EntityId.getMnemonic(accessor.getId(record)) === filter.mnemonic;\n }\n\n case 'in-query': {\n throw new Error('in-query filters must be resolved to a literal `in` by the query executor before matching.');\n }\n\n case 'not': {\n return !match(filter.filter, record);\n }\n\n case 'and': {\n return filter.filters.every((f) => match(f, record));\n }\n\n case 'or': {\n return filter.filters.some((f) => match(f, record));\n }\n\n default:\n return false;\n }\n };\n\n return match;\n};\n\nconst entityAccessor: FilterRecordAccessor<AnyEntity> = {\n getId: (entity) => entity.id,\n getTypeURI: (entity) => getTypeURI(entity),\n getProps: (entity) => {\n try {\n return objectToJSON(entity);\n } catch {\n // Serialization of complex static-type entities may throw.\n return undefined;\n }\n },\n getMeta: (entity) => {\n const meta = getMetaChecked(entity);\n return {\n keys: meta.keys,\n key: meta.key,\n version: meta.version,\n annotations: meta.annotations,\n // Lazy: meta tags surface as entities on a live proxy and only the `tag` arm needs their ids.\n get tags() {\n return meta.tags.map((tag) => tag.id);\n },\n };\n },\n hasParent: (entity) => {\n assumeType<InternalObjectProps>(entity);\n return entity[ParentId] !== undefined;\n },\n matchTextSearch: (filter, entity) => matchesTextSearch(filter, entity),\n};\n\n/**\n * Matches a filter against an entity proxy without full JSON serialization when possible.\n *\n * Text filters evaluate in memory here because this matcher serves executors with no index behind\n * them (the registry, `Filter.toPredicate`); index-backed paths use `filterMatchDoc` instead.\n */\nexport const filterMatchEntity: (filter: QueryAST.Filter, entity: AnyEntity) => boolean =\n makeFilterMatcher(entityAccessor);\n\n/**\n * In-memory full-text match: every term must appear (case-insensitive) in the entity's serialized\n * strings, meta included so a registry key is searchable. Containment, not tokenized ranking.\n */\nconst matchesTextSearch = (filter: QueryAST.Filter & { type: 'text-search' }, entity: AnyEntity): boolean => {\n // A vector query is meaningless without an embedding index, whatever the executor.\n if (filter.searchKind === 'vector') {\n return false;\n }\n const terms = filter.text\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n if (terms.length === 0) {\n return true;\n }\n let json: unknown;\n try {\n json = objectToJSON(entity);\n } catch {\n return false;\n }\n const haystack: string[] = [];\n collectStrings(json, haystack, new Set());\n const text = haystack.join('\\n').toLowerCase();\n return terms.every((term) => text.includes(term));\n};\n\nconst collectStrings = (value: unknown, out: string[], seen: Set<unknown>): void => {\n if (typeof value === 'string') {\n out.push(value);\n return;\n }\n if (value === null || typeof value !== 'object' || seen.has(value)) {\n return;\n }\n seen.add(value);\n for (const entry of Array.isArray(value) ? value : Object.values(value)) {\n collectStrings(entry, out, seen);\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as Struct from 'effect/Struct';\n\nimport { getTypename } from '../Annotation/index.ts';\nimport { type AnyProperties } from '../common/types/index.ts';\n\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\nexport type TypedObjectOptions = {\n // TODO(burdon): Document.\n partial?: true;\n // TODO(burdon): Document.\n record?: true;\n};\n\n/**\n *\n */\n// TODO(burdon): Comment required.\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\ntype SimplifiedSchemaFields<\n SchemaFields extends Schema.Struct.Fields,\n Options extends TypedObjectOptions,\n> = Options['partial'] extends boolean\n ? Struct.Simplify<Struct.Mutable<Partial<Schema.Struct.Type<SchemaFields>>>>\n : Struct.Simplify<Struct.Mutable<Schema.Struct.Type<SchemaFields>>>;\n\n/**\n *\n */\n// TODO(burdon): Comment required.\n// TODO(dmaretskyi): Rename to represent commonality between objects and relations (e.g. `entity`).\nexport type TypedObjectFields<\n SchemaFields extends Schema.Struct.Fields,\n Options extends TypedObjectOptions,\n> = SimplifiedSchemaFields<SchemaFields, Options> & { id: string } & (Options['record'] extends boolean\n ? Record<string, any>\n : {});\n\nexport const makeTypedEntityClass = (typename: string, version: string, baseSchema: Schema.Top): Schema.Codec<any> => {\n return class {\n // Implement TypedObject properties.\n static readonly typename = typename;\n static readonly version = version;\n\n // Implement Schema.Schema properties.\n // Effect 4 marks a schema with a string key carrying its own name, replacing v3's variance\n // object; `annotations` became `annotate`.\n static readonly [SCHEMA_TYPE_ID] = SCHEMA_TYPE_ID;\n static readonly ast = baseSchema.ast;\n static readonly annotate = baseSchema.annotate.bind(baseSchema);\n static readonly pipe = baseSchema.pipe.bind(baseSchema);\n\n // TODO(burdon): Comment required.\n static [Symbol.hasInstance](obj: AnyProperties) {\n return obj != null && getTypename(obj) === typename;\n }\n\n // TODO(burdon): Throw APIError.\n private constructor() {\n throw new Error('Use live(Typename, { ...fields }) to instantiate an object.');\n }\n } as any;\n};\n\n/** Effect 4's schema marker; the module declares it privately, so the literal is repeated here. */\nconst SCHEMA_TYPE_ID = '~effect/Schema/Schema';\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { InspectOptionsStylized, inspect as inspectFn } from 'node:util';\n\nimport { type CustomInspectFunction, inspectCustom } from '@dxos/debug';\n\nimport { getTypeURI } from '../Annotation/index.ts';\nimport { type AnyEntity, ATTR_TYPE } from '../common/types/index.ts';\nimport { ATTR_META } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\n\n/*\n * @internal\n */\nexport const attachedTypedObjectInspector = (obj: any) => {\n const descriptor = Object.getOwnPropertyDescriptor(obj, inspectCustom);\n if (descriptor) {\n return;\n }\n\n Object.defineProperty(obj, inspectCustom, {\n value: typedObjectInspectFunction,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n};\n\n// NOTE: KEEP as function.\nconst typedObjectInspectFunction: CustomInspectFunction<AnyEntity> = function (\n this: AnyEntity,\n depth: number,\n options: InspectOptionsStylized,\n inspect: typeof inspectFn,\n) {\n const { id, ...props } = this;\n return inspect(\n {\n id,\n [ATTR_TYPE]: getTypeURI(this),\n ...props,\n [ATTR_META]: (this as any)[MetaId], // TODO(dmaretskyi): Couldn't use getMeta since that throw's if the object has no meta.\n },\n options,\n );\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { raise } from '@dxos/debug';\nimport { assertArgument, failedInvariant } from '@dxos/invariant';\nimport { EntityId } from '@dxos/keys';\n\nimport type * as Type from '../../Type.ts';\nimport { getSchemaURI, getTypeAnnotation, setTypename } from '../Annotation/index.ts';\nimport { attachTypedJsonSerializer, defineHiddenProperty } from '../common/proxy/index.ts';\nimport {\n EntityKind,\n KindId,\n SchemaKindId,\n StaticTypeSchemaSlot,\n getStaticTypeSchema,\n setSchema,\n setType,\n} from '../common/types/index.ts';\nimport { type EntityMeta } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport {\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n assertObjectModel,\n getObjectEchoUri,\n} from '../Entity/index.ts';\nimport { attachedTypedObjectInspector } from './inspect.ts';\n\n// Omits the brand slots — those get stamped on the instance by the entity\n// handler (KindId via setKind, SchemaKindId derived in the proxy `get` trap\n// from kind + jsonSchema.entityKind, StaticTypeSchemaSlot lazily via the\n// proxy), not supplied by the caller. Allows `[Obj.Meta]` (MetaId symbol) for\n// seeding registry-provenance meta at construction (mirrors `Obj.make`).\nexport type CreateObjectProps<T> = (T extends { id: string }\n ? Omit<T, 'id' | KindId | SchemaKindId | StaticTypeSchemaSlot> & { id?: string }\n : Omit<T, KindId | SchemaKindId | StaticTypeSchemaSlot>) & {\n readonly [MetaId]?: Partial<EntityMeta>;\n};\n\n/**\n * Creates a new object instance from a schema and data, without signal reactivity.\n * This static version creates plain JavaScript objects that are not reactive/observable.\n * For reactive objects that automatically update UI when changed, use the regular live() function.\n *\n * @param schema - The Effect schema that defines the object's structure and type, piped into EchoObjectSchema\n * @param data - The data to initialize the object with. The id and @type fields are handled automatically.\n * @returns A new non-reactive object instance conforming to the schema\n * @throws {Error} If the schema is not an object schema\n * @throws {TypeError} If data contains an @type field\n *\n * @example\n * ```ts\n * class Contact extends Type.makeObject<Contact>(DXN.make('com.example.type.person', '0.1.0'))(\n * Schema.Struct({ name: Schema.String, email: Schema.String }),\n * ) {}\n *\n * const contact = createObject(Contact, {\n * name: \"John\",\n * email: \"john@example.com\",\n * })\n * ```\n */\n// TODO(burdon): Make internal.\nexport const createObject: {\n <T extends Type.AnyEntity>(input: T, props: NoInfer<CreateObjectProps<Type.InstanceType<T>>>): Type.InstanceType<T>;\n} = (input: any, props: any): any => {\n // `Type.Type` entities aren't `Schema.Schema` themselves; read the source\n // schema off the hidden slot (persisted entities synthesize it lazily via\n // the proxy `get` trap).\n const schema = getStaticTypeSchema(input) ?? failedInvariant('Type entity is missing its source schema');\n const annotation = getTypeAnnotation(schema);\n if (!annotation) {\n throw new Error('Schema is not an ECHO schema');\n }\n assertArgument(!('@type' in props), 'data', '@type is not allowed');\n assertArgument(!(RelationSourceDXNId in props), 'data', 'Relation source DXN is not allowed in the constructor');\n assertArgument(!(RelationTargetDXNId in props), 'data', 'Relation target DXN is not allowed in the constructor');\n assertArgument(\n RelationSourceId in props === RelationTargetId in props,\n 'data',\n 'Relation source and target must be provided together',\n );\n\n // Pull `[Obj.Meta]` (MetaId-symbol) off props before spreading so it doesn't\n // leak into data. Callers use this to seed registry-provenance meta fields\n // (`key`, `version`) and foreign keys / tags at construction time, mirroring\n // `Obj.make`'s symbol-keyed meta convention.\n const metaOverride = props[MetaId];\n if (metaOverride !== undefined) {\n delete props[MetaId];\n }\n\n // Raw object.\n const obj = { ...props, id: props.id ?? EntityId.random() };\n\n // Metadata. Instance-kind is read from the schema's TypeAnnotation (set by\n // EchoObjectSchema / EchoRelationSchema / EchoTypeKindSchema): instances of\n // a type-kind meta-schema are themselves type-kind entities, etc. The\n // RelationSourceId-in-props check covers the legacy path where the schema\n // annotation isn't authoritative.\n const kind =\n annotation.kind === EntityKind.Type\n ? EntityKind.Type\n : annotation.kind === EntityKind.Relation || RelationSourceId in props\n ? EntityKind.Relation\n : EntityKind.Object;\n defineHiddenProperty(obj, KindId, kind);\n defineHiddenProperty(obj, MetaId, {\n ...metaOverride,\n keys: metaOverride?.keys ?? [],\n tags: metaOverride?.tags ?? [],\n annotations: metaOverride?.annotations ?? {},\n });\n setSchema(obj, schema);\n // If the caller passed a type entity (recognised via the schema slot), keep\n // a reference to it on the instance for `Obj.getType` / `Relation.getType`.\n if (input !== schema) {\n setType(obj, input);\n }\n setTypename(obj, getSchemaURI(schema) ?? failedInvariant('Missing schema URI'));\n attachTypedJsonSerializer(obj);\n attachedTypedObjectInspector(obj);\n\n // Relation.\n if (kind === EntityKind.Relation) {\n const sourceDXN = getObjectEchoUri(props[RelationSourceId]) ?? raise(new Error('Unresolved relation source'));\n const targetDXN = getObjectEchoUri(props[RelationTargetId]) ?? raise(new Error('Unresolved relation target'));\n defineHiddenProperty(obj, RelationSourceDXNId, sourceDXN);\n defineHiddenProperty(obj, RelationTargetDXNId, targetDXN);\n }\n\n assertObjectModel(obj);\n return obj;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AnyProperties } from '../common/types/index.ts';\nimport { ObjectDeletedId } from '../Entity/index.ts';\n\n/**\n * @returns `true` if the object has been marked as deleted.\n */\nexport const isDeleted = (obj: AnyProperties): boolean => {\n if ((obj as any)[ObjectDeletedId] === undefined) {\n // TODO(dmaretskyi): Return to prior behavior of throwing.\n // throw new Error('Object does not support deletion marker');\n return false;\n }\n\n return (obj as any)[ObjectDeletedId] ?? false;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\n\nimport { SetParentAnnotation, getFromAst } from '../Annotation/index.ts';\nimport { EntityKind } from '../common/types/entity.ts';\nimport { KindId, ParentId, getSchema } from '../common/types/index.ts';\nimport { Ref } from '../Ref/ref.ts';\n\n/** An owning field; `path` is relative to the parent and may nest inside plain structs, e.g. `backend.config`. */\ntype OwningField = { readonly path: readonly string[]; readonly override: boolean };\n\n/**\n * Owning-field paths relative to an AST node, per {@link SetParentAnnotation}. Memoized per node —\n * a schema's annotations do not change once it is built (a dynamic type rebuilds its AST, yielding\n * fresh keys) — which also keeps the walk linear in nodes over a schema whose nested types repeat.\n */\nconst cache = new WeakMap<SchemaAST.AST, readonly OwningField[]>();\n\nconst getOwnership = (ast: SchemaAST.AST): { override: boolean } | undefined => {\n const value = Option.getOrUndefined(getFromAst(ast, SetParentAnnotation));\n return value?.value ? { override: value.override } : undefined;\n};\n\nconst collect = (ast: SchemaAST.AST): readonly OwningField[] => {\n const cached = cache.get(ast);\n if (cached) {\n return cached;\n }\n // Seed before recursing: a self-referencing `Schema.suspend` field resolves back to this node, and\n // an owned field is declared at the level it appears on, so the cycle contributes nothing further.\n cache.set(ast, []);\n\n const fields: OwningField[] = [];\n // A union of structs (e.g. a discriminated `spec`) contributes each member's fields at this path.\n if (SchemaAST.isUnion(ast)) {\n for (const member of ast.types) {\n fields.push(...collect(member));\n }\n } else {\n for (const property of SchemaAST.getPropertySignatures(ast)) {\n if (typeof property.name !== 'string') {\n continue;\n }\n // Optionality wraps the field schema in a union; for an array of refs the annotation may sit\n // on either the array or its element.\n const unwrapped = SchemaEx.unwrapOptional(property.type);\n const element = SchemaEx.getArrayElementType(unwrapped);\n const ownership =\n getOwnership(property.type) ?? getOwnership(unwrapped) ?? (element != null ? getOwnership(element) : undefined);\n if (ownership) {\n fields.push({ path: [property.name], override: ownership.override });\n } else {\n // Recurse into nested structs and unions of structs (a ref is a Declaration, which\n // terminates the walk).\n const name = property.name;\n fields.push(...collect(unwrapped).map((field): OwningField => ({ ...field, path: [name, ...field.path] })));\n }\n }\n }\n\n cache.set(ast, fields);\n return fields;\n};\n\nconst setParent = (value: unknown, parent: unknown, override: boolean): void => {\n if (!Ref.isRef(value)) {\n return;\n }\n // Only an already-resolved target can be re-parented synchronously; an unresolved ref names an\n // object whose parent edge is either already written or not this holder's to write. `.target`\n // throws on a ref with neither an inlined target nor a resolver, so gate on `isAvailable`.\n const target: any = value.isAvailable ? value.target : undefined;\n if (target == null || target[KindId] !== EntityKind.Object) {\n return;\n }\n // By id, not identity: the database resolves a parent edge through the working set, which may\n // hand back a different proxy for the same entity — an identity compare would miss the\n // short-circuit and re-write the unchanged edge on every update of the holder.\n const current = target[ParentId];\n if (current?.id === (parent as any)?.id) {\n return;\n }\n if (!override && current != null) {\n return;\n }\n target[ParentId] = parent;\n};\n\n/**\n * Propagates the parent edge declared by an object's {@link SetParentAnnotation} fields: every\n * resolved ref target held in an owning field gets its parent set to the holding object.\n *\n * Called after object creation (`Obj.make`) and after every change transaction (`Obj.update`) —\n * idempotent, so re-running it over unchanged fields is a no-op.\n */\nexport const propagateParentAnnotations = (obj: unknown): void => {\n const schema = getSchema(obj);\n if (schema == null) {\n return;\n }\n\n for (const { path, override } of collect(schema.ast)) {\n let value: any = obj;\n for (const key of path) {\n value = value?.[key];\n }\n if (Array.isArray(value)) {\n for (const element of value) {\n setParent(element, obj, override);\n }\n } else {\n setParent(value, obj, override);\n }\n }\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { invariant } from '@dxos/invariant';\n\nimport { type Mutable } from '../common/proxy/index.ts';\nimport { getSchema } from '../common/types/index.ts';\n\n/**\n * Set a deeply nested property on an object.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setValue = (obj: Mutable<any>, path: readonly (string | number)[], value: any): void => {\n invariant(path.length > 0, 'Path must not be empty');\n\n const schema = getSchema(obj);\n invariant(schema != null, 'Object must have a schema');\n\n let parent = obj;\n let currentAST: SchemaAST.AST | undefined = schema.ast;\n\n // Navigate to the parent of the target property.\n for (let i = 0; i < path.length - 1; i++) {\n const part = path[i];\n const key = typeof part === 'number' ? part : String(part);\n if (parent[key] === undefined) {\n const propertyAST = getPropertyAST(currentAST, String(part));\n const shouldBeArray = propertyAST ? SchemaEx.isArrayType(propertyAST) : false;\n\n if (shouldBeArray) {\n // Create array.\n parent[key] = [];\n } else {\n // TODO(wittjosiah): Is there a better way to handle this than creating an object with defaults?\n // Perhaps properties on objects should be optional by default?\n // Create object with defaults for required fields.\n const objWithDefaults = createObjectWithDefaults(propertyAST);\n parent[key] = objWithDefaults;\n }\n }\n\n parent = parent[key];\n currentAST = getPropertyAST(currentAST, String(part));\n }\n\n const finalKey = path[path.length - 1];\n parent[finalKey] = value;\n\n return value;\n};\n\n/**\n * Helper to get the AST of a nested property.\n * @param ast - Current schema AST.\n * @param propertyName - Name of the property to get.\n * @returns The AST of the nested property, or undefined if not found.\n */\nconst getPropertyAST = (ast: SchemaAST.AST | undefined, propertyName: string): SchemaAST.AST | undefined => {\n if (!ast) {\n return undefined;\n }\n\n if (SchemaEx.isNestedType(ast)) {\n const properties = SchemaEx.getProperties(ast);\n const property = properties.find((p) => p.name.toString() === propertyName);\n if (property) {\n return property.type;\n }\n }\n\n if (SchemaEx.isArrayType(ast)) {\n const elementType = SchemaEx.getArrayElementType(ast);\n return elementType;\n }\n\n return undefined;\n};\n\n/**\n * Get all required properties from a schema AST.\n * A property is required if it's not optional.\n *\n * @param ast - Schema AST to inspect.\n * @returns Array of required properties with their types.\n */\nconst getRequiredProperties = (ast: SchemaAST.AST | undefined): SchemaEx.SchemaProperty[] => {\n if (!ast) {\n return [];\n }\n\n // Only objects/structs have properties with optional/required distinction.\n if (!SchemaEx.isNestedType(ast)) {\n return [];\n }\n\n const properties = SchemaEx.getProperties(ast);\n\n // Filter to only required properties (where isOptional === false).\n return properties.filter((p) => !p.isOptional);\n};\n\n/**\n * Get the default value for a primitive type.\n * Returns undefined for non-primitive or unsupported types.\n *\n * @param ast - Type AST.\n * @returns Default value for the type, or undefined.\n */\nconst getDefaultValueForType = (ast: SchemaAST.AST | undefined): any => {\n if (!ast) {\n return undefined;\n }\n\n const defaultValue = SchemaAST.getDefaultAnnotation(ast);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n // A plain switch rather than `Match.when({ _tag })`: matching an object pattern against Effect 4's\n // mutually recursive AST union expands into a mapped type the checker cannot resolve.\n switch (ast._tag) {\n case 'String':\n return '';\n case 'Number':\n return 0;\n case 'Boolean':\n return false;\n default:\n return undefined;\n }\n};\n\n/**\n * Create an object with default values for all required properties.\n * Handles primitive types (String, Number, Boolean) and recursively initializes required nested objects.\n *\n * @param ast - Schema AST describing the object structure.\n * @returns Object with required fields populated with defaults.\n */\nconst createObjectWithDefaults = (ast: SchemaAST.AST | undefined): any => {\n if (!ast) {\n return {};\n }\n\n const requiredProps = getRequiredProperties(ast);\n const obj: any = {};\n\n for (const prop of requiredProps) {\n const defaultValue = getDefaultValueForType(prop.type);\n if (defaultValue !== undefined) {\n obj[prop.name] = defaultValue;\n } else if (SchemaEx.isNestedType(prop.type)) {\n obj[prop.name] = createObjectWithDefaults(prop.type);\n }\n }\n\n return obj;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { assertArgument } from '@dxos/invariant';\nimport { deepMapValues } from '@dxos/util';\n\nimport {\n EntityKind,\n KindId,\n ObjectDatabaseId,\n ObjectDeletedId,\n ParentId,\n RelationSourceDXNId,\n RelationSourceId,\n RelationTargetDXNId,\n RelationTargetId,\n SchemaId,\n SelfURIId,\n SnapshotKindId,\n TypeEntityId,\n TypeId,\n} from '../common/types/index.ts';\nimport { SCALAR_META_FIELDS } from '../common/types/meta.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\n\n/**\n * Copy a Symbol-keyed property from source to target if it has a defined value.\n * Handles both plain objects (symbol in source) and proxies where get returns a value\n * but has/in returns false (e.g. ObjectDatabaseId on echo-db proxies).\n * Optional transform clones or mutates the value before assignment (e.g. for MetaId).\n */\nconst copySymbolProperty = (\n source: any,\n target: any,\n symbol: symbol,\n transform?: (value: unknown) => unknown,\n): void => {\n let value: unknown;\n // Echo-db proxy getters (e.g. RelationSourceId, RelationTargetId) can throw in certain states.\n try {\n value = source[symbol];\n } catch {\n return;\n }\n if (value !== undefined) {\n const finalValue = transform ? transform(value) : value;\n Object.defineProperty(target, symbol, {\n value: finalValue,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n }\n};\n\n/**\n * Returns an immutable snapshot of the reactive object.\n * The snapshot is branded with SnapshotKindId (not KindId).\n */\nexport const getSnapshot = <T extends object>(obj: T): T => {\n assertArgument(typeof obj === 'object' && obj !== null && KindId in obj, 'obj', 'must be an entity');\n\n const snapshot = deepMapValues(obj, (value, recurse) => {\n // Do not recurse on references (but do recurse on arrays).\n if (\n typeof value === 'object' &&\n value !== null &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n !Array.isArray(value)\n ) {\n return value;\n }\n\n return recurse(value);\n }) as any;\n\n // Add SnapshotKindId brand based on original KindId.\n if (obj != null && typeof obj === 'object' && KindId in obj) {\n snapshot[SnapshotKindId] = (obj as any)[KindId];\n }\n\n // Preserve Symbol-keyed properties that are important for type introspection.\n // These are not copied by deepMapValues since Object.keys() doesn't include symbols.\n const source = obj as any;\n\n // Type introspection symbols.\n copySymbolProperty(source, snapshot, TypeId);\n copySymbolProperty(source, snapshot, SchemaId);\n copySymbolProperty(source, snapshot, TypeEntityId);\n copySymbolProperty(source, snapshot, SelfURIId);\n\n // Database reference (required for Obj.getDatabase to work on snapshots).\n copySymbolProperty(source, snapshot, ObjectDatabaseId);\n copySymbolProperty(source, snapshot, ObjectDeletedId);\n\n // Parent reference (required for Obj.getParent to work on snapshots).\n copySymbolProperty(source, snapshot, ParentId);\n\n // Metadata symbol. Copy arrays/objects so the snapshot is not affected by mutations to the live meta.\n copySymbolProperty(source, snapshot, MetaId, (meta: any) => {\n const copy: Record<string, unknown> = {\n keys: [...(meta?.keys ?? [])],\n tags: [...(meta?.tags ?? [])],\n ...(meta?.annotations ? { annotations: { ...meta.annotations } } : {}),\n };\n // Enumerated from the schema so a newly added meta field is carried without touching this.\n for (const field of SCALAR_META_FIELDS) {\n if (meta?.[field] != null) {\n copy[field] = meta[field];\n }\n }\n return copy;\n });\n\n // Relation endpoint symbols, read only on a relation: on any other object the echo-db getters throw an invariant\n // violation, so every snapshot of a plain object paid for two caught, stack-traced errors.\n if (source[KindId] === EntityKind.Relation) {\n copySymbolProperty(source, snapshot, RelationSourceDXNId);\n copySymbolProperty(source, snapshot, RelationTargetDXNId);\n copySymbolProperty(source, snapshot, RelationSourceId);\n copySymbolProperty(source, snapshot, RelationTargetId);\n }\n\n return Object.freeze(snapshot) as T;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as AsyncResult from 'effect/reactivity/AsyncResult';\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport { assertArgument } from '@dxos/invariant';\n\nimport type * as Entity from '../../Entity.ts';\nimport type * as Obj from '../../Obj.ts';\nimport type * as Ref from '../../Ref.ts';\nimport type * as Relation from '../../Relation.ts';\nimport type * as Tag from '../../Tag.ts';\nimport { getLabel } from '../Annotation/index.ts';\nimport { snapshotEquals, snapshotForComparison } from '../common/atom-snapshot.ts';\nimport { subscribe } from '../common/proxy/reactive.ts';\nimport { ParentId } from '../common/types/index.ts';\nimport { getMeta } from '../common/types/meta.ts';\nimport { getDatabase, isEntity } from '../Entity/index.ts';\nimport { refArrayFamily } from '../Ref/atoms.ts';\nimport { RefTypeId } from '../Ref/ref.ts';\nimport { loadRefTarget } from '../Ref/utils.ts';\nimport { isDeleted } from './deleted.ts';\nimport { getSnapshot } from './snapshot.ts';\n\nconst isRef = (obj: unknown): obj is Ref.Ref<any> =>\n obj != null && typeof obj === 'object' && RefTypeId in (obj as object);\n\nconst getReactiveOption = <T extends Obj.Unknown>(snapshot: Obj.Snapshot<T>): Effect.Effect<Option.Option<T>, never> =>\n Effect.gen(function* () {\n const db = getDatabase(snapshot as any);\n if (!db) {\n return Option.none();\n }\n const obj = db.getObjectById((snapshot as any).id);\n return obj ? Option.some(obj as T) : Option.none();\n });\n\n/**\n * Atom family for ECHO objects.\n * Uses object reference as key — same object returns same atom.\n */\nconst objectFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Snapshot<T>> => {\n return Atom.make<Obj.Snapshot<T>>((get) => {\n const unsubscribe = subscribe(obj, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(obj) as unknown as Obj.Snapshot<T>);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(obj) as unknown as Obj.Snapshot<T>;\n });\n});\n\n/**\n * Atom family for ECHO refs (snapshot version).\n * Keyed by a structurally-equal tuple `[ref, includeDeleted]` so nested families are avoided.\n * Subscribes to target object changes after loading.\n */\nconst refFamily = Atom.family(\n <T extends Obj.Unknown>([ref, includeDeleted]: readonly [Ref.Ref<T>, boolean]): Atom.Atom<\n Obj.Snapshot<T> | undefined\n > => {\n return Atom.make<Obj.Snapshot<T> | undefined>((get) => {\n let unsubscribeTarget: (() => void) | undefined;\n\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n const read = (target: T): Obj.Snapshot<T> | undefined =>\n !includeDeleted && isDeleted(target) ? undefined : (getSnapshot(target) as unknown as Obj.Snapshot<T>);\n\n const setupTargetSubscription = (target: T): Obj.Snapshot<T> | undefined => {\n unsubscribeTarget?.();\n unsubscribeTarget = subscribe(target, () => {\n get.setSelf(read(target));\n });\n // Runs at once when the node was disposed while the target loaded.\n get.addFinalizer(unsubscribeTarget);\n return read(target);\n };\n\n return loadRefTarget(ref, get, setupTargetSubscription, includeDeleted ? { deleted: 'include' } : undefined);\n });\n },\n);\n\n/**\n * Atom family for ECHO object properties, keyed by `[object, key]`.\n */\nconst propertyFamily = Atom.family(([obj, key]: readonly [Obj.Unknown, PropertyKey]): Atom.Atom<any> => {\n return Atom.make<any>((get) => {\n let previousSnapshot = snapshotForComparison((obj as any)[key]);\n\n const unsubscribe2 = subscribe(obj, () => {\n const newValue = (obj as any)[key];\n // Content comparison against the last emitted snapshot: identity would be unequal for every\n // array/object, firing on any mutation of `obj` (see `snapshotEquals`).\n if (!snapshotEquals(newValue, previousSnapshot)) {\n previousSnapshot = snapshotForComparison(newValue);\n get.setSelf(previousSnapshot);\n }\n });\n\n get.addFinalizer(() => unsubscribe2());\n\n return snapshotForComparison((obj as any)[key]);\n });\n});\n\n/**\n * Atom family for ECHO objects — returns the live object, not a snapshot.\n */\nconst objectWithReactiveFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<T> => {\n return Atom.make<T>((get) => {\n const unsubscribe = subscribe(obj, () => {\n get.setSelf(obj);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return obj;\n });\n});\n\n/**\n * Atom family for ECHO refs — returns the live reactive object, not a snapshot.\n */\nconst refWithReactiveFamily = Atom.family(<T extends Obj.Unknown>(ref: Ref.Ref<T>): Atom.Atom<T | undefined> => {\n const effect = (get: Atom.AtomContext) =>\n Effect.gen(function* () {\n const snapshot = get(makeAtom(ref));\n if (snapshot == null) {\n return undefined;\n }\n const option = yield* getReactiveOption(snapshot);\n return Option.getOrElse(option, () => undefined);\n });\n\n return Function.pipe(\n Atom.make(effect),\n Atom.map((result) => AsyncResult.getOrElse(result, () => undefined)),\n );\n});\n\n/**\n * Atom family for a property of a ref's target object.\n * Resolves the ref (reactively) then projects the property atom, so it fires when the ref resolves or when\n * that property changes. Yields `undefined` while the target is unresolved.\n */\nconst refPropertyFamily = Atom.family(([ref, key]: readonly [Ref.Ref<any>, PropertyKey]): Atom.Atom<any> =>\n Atom.make((get) => {\n const target = get(refWithReactiveFamily(ref));\n return target ? get(propertyFamily([target, key])) : undefined;\n }),\n);\n\n/**\n * Atom family for any ECHO entity (obj or relation) — returns a snapshot.\n */\nconst entityFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<Entity.Snapshot> => {\n return Atom.make<Entity.Snapshot>((get) => {\n const unsubscribe = subscribe(entity, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(entity) as unknown as Entity.Snapshot);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(entity) as unknown as Entity.Snapshot;\n });\n});\n\n/**\n * Atom family for ECHO relations — returns a typed relation snapshot.\n */\nconst relationFamily = Atom.family(<T extends Relation.Unknown>(relation: T): Atom.Atom<Relation.Snapshot<T>> => {\n return Atom.make<Relation.Snapshot<T>>((get) => {\n const unsubscribe = subscribe(relation, () => {\n // getSnapshot adds SnapshotKindId brand at runtime; cast bridges static types.\n get.setSelf(getSnapshot(relation) as unknown as Relation.Snapshot<T>);\n });\n\n get.addFinalizer(() => unsubscribe());\n\n return getSnapshot(relation) as unknown as Relation.Snapshot<T>;\n });\n});\n\n/**\n * Create a read-only snapshot atom for a reactive object or ref.\n * Updates automatically when the object is mutated.\n * For refs, subscribes to target object changes after loading.\n */\nexport const makeAtom: {\n <T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Snapshot<T>>;\n <T extends Obj.Unknown>(ref: Ref.Ref<T>, options?: Ref.LoadOptions): Atom.Atom<Obj.Snapshot<T> | undefined>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any>, options?: Ref.LoadOptions): Atom.Atom<any> => {\n if (isRef(objOrRef)) {\n return refFamily([objOrRef, options?.deleted === 'include']);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return objectFamily(obj as any);\n};\n\n/**\n * Create a read-only atom for a specific property of a reactive object, or of a ref's target.\n * Only fires updates when the property value actually changes. Given a ref, the atom resolves the target\n * first and yields `undefined` until it loads.\n */\nexport const makeProperty: {\n <T extends Obj.Unknown, K extends keyof T>(obj: T, key: K): Atom.Atom<T[K]>;\n <T extends Obj.Unknown, K extends keyof T>(ref: Ref.Ref<T>, key: K): Atom.Atom<T[K] | undefined>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any>, key: any): Atom.Atom<any> => {\n if (isRef(objOrRef)) {\n return refPropertyFamily([objOrRef as Ref.Ref<any>, key]);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return propertyFamily([obj, key]);\n};\n\n/**\n * Like `makeAtom` but returns the live reactive object instead of a snapshot.\n * Prefer `makeAtom` (snapshot) unless you need the live Obj for generic mutations.\n * Given a ref array, yields the loaded targets in ref order, without deleted ones unless included.\n */\nexport const makeWithReactive: {\n <T extends Obj.Unknown>(obj: T): Atom.Atom<T>;\n <T extends Obj.Unknown>(ref: Ref.Ref<T>): Atom.Atom<T | undefined>;\n <T extends Obj.Unknown>(refs: readonly Ref.Ref<T>[], options?: Ref.LoadOptions): Atom.Atom<T[]>;\n} = (objOrRef: Obj.Unknown | Ref.Ref<any> | readonly Ref.Ref<any>[], options?: Ref.LoadOptions): Atom.Atom<any> => {\n if (Array.isArray(objOrRef)) {\n // Copied: a live ECHO array would mutate under the family key.\n return refArrayFamily([[...objOrRef], options?.deleted === 'include']);\n }\n if (isRef(objOrRef)) {\n return refWithReactiveFamily(objOrRef as Ref.Ref<any>);\n }\n\n const obj = objOrRef as Obj.Unknown;\n assertArgument(isEntity(obj), 'obj', 'Object must be a reactive object');\n return objectWithReactiveFamily(obj);\n};\n\n/**\n * Create a read-only snapshot atom for any ECHO entity (obj or relation).\n * Updates automatically when the entity is mutated.\n */\nexport const makeEntity = <T extends Entity.Unknown>(entity: T): Atom.Atom<Entity.Snapshot> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return entityFamily(entity);\n};\n\n/**\n * Create a read-only snapshot atom for a reactive relation.\n * Updates automatically when the relation is mutated.\n */\nexport const makeRelation = <T extends Relation.Unknown>(relation: T): Atom.Atom<Relation.Snapshot<T>> => {\n assertArgument(isEntity(relation), 'relation', 'Must be a reactive ECHO relation');\n return relationFamily(relation);\n};\n\n/**\n * Atom family for an entity's label string.\n * Fires only when the computed label actually changes, not on every entity mutation.\n */\nconst labelAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<string | undefined> => {\n return Atom.make<string | undefined>((get) => {\n let previous = getLabel(entity);\n\n const unsubscribe = subscribe(entity, () => {\n const next = getLabel(entity);\n if (next !== previous) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the label of a reactive ECHO entity.\n * Re-evaluates on entity mutation; only propagates when the label string changes.\n */\nexport const makeLabelAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<string | undefined> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return labelAtomFamily(entity);\n};\n\nconst readTags = (entity: Entity.Unknown): readonly Tag.Tag[] => [...getMeta(entity).tags];\n\n/** Tags are entities held by identity, so the list is unchanged while every element is the same entity. */\nconst sameTags = (next: readonly Tag.Tag[], previous: readonly Tag.Tag[]): boolean =>\n next.length === previous.length && next.every((tag, index) => tag === previous[index]);\n\nconst tagsAtomFamily = Atom.family(<T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Tag.Tag[]> => {\n return Atom.make<readonly Tag.Tag[]>((get) => {\n let previous = readTags(entity);\n\n const unsubscribe = subscribe(entity, () => {\n const next = readTags(entity);\n if (!sameTags(next, previous)) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the meta tags of a reactive ECHO entity.\n * Re-reads on entity mutation; only propagates when the tag list changes.\n */\nexport const makeTagsAtom = <T extends Entity.Unknown>(entity: T): Atom.Atom<readonly Tag.Tag[]> => {\n assertArgument(isEntity(entity), 'entity', 'Must be a reactive ECHO entity');\n return tagsAtomFamily(entity);\n};\n\nconst readParent = (obj: Obj.Unknown): Obj.Unknown | undefined => (obj as any)[ParentId];\n\n/**\n * Atom family for an object's parent.\n * Fires only when the parent changes, compared by id since the database may hand back a different proxy.\n */\nconst parentAtomFamily = Atom.family(<T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Unknown | undefined> => {\n return Atom.make<Obj.Unknown | undefined>((get) => {\n let previous = readParent(obj);\n\n const unsubscribe = subscribe(obj, () => {\n const next = readParent(obj);\n if (next?.id !== previous?.id) {\n previous = next;\n get.setSelf(next);\n }\n });\n\n get.addFinalizer(() => unsubscribe());\n return previous;\n });\n});\n\n/**\n * Create a read-only atom for the parent of a reactive ECHO object.\n * Re-evaluates on object mutation; only propagates when the parent changes.\n */\nexport const makeParentAtom = <T extends Obj.Unknown>(obj: T): Atom.Atom<Obj.Unknown | undefined> => {\n assertArgument(isEntity(obj), 'obj', 'Must be a reactive ECHO object');\n return parentAtomFamily(obj);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { assumeType, deepMapValues } from '@dxos/util';\n\nimport type * as Obj from '../../Obj.ts';\nimport { makeObject } from '../common/proxy/index.ts';\nimport { ParentId, getSchema, getStaticTypeSchema, getType } from '../common/types/index.ts';\nimport { getMeta } from '../common/types/meta.ts';\nimport { type InternalObjectProps } from '../Entity/model.ts';\nimport { Ref } from '../Ref/index.ts';\n\n/**\n * Clones an object or relation.\n * By default this does not clone referenced objects, only the properties in the object; pass `opts.deep`\n * to recurse into refs (see {@link Obj.CloneOptions}).\n * @returns A new object with the same schema and properties.\n */\nexport const clone = <T extends Obj.Any>(obj: T, opts?: Obj.CloneOptions): T =>\n cloneInner(obj, opts, obj, new Map(), new Set());\n\n/**\n * Recursive clone worker threaded with two cycle-guard structures:\n * - `cache`: id → already-finished clone; reused when the same object appears more than once in a DAG.\n * - `inProgress`: ids of objects whose clone is currently being computed; a ref back into this set means\n * a true cycle — the original ref is kept rather than recursing forever.\n */\nconst cloneInner = <T extends Obj.Any>(\n obj: T,\n opts: Obj.CloneOptions | undefined,\n root: Obj.Any,\n cache: Map<string, Obj.Any>,\n inProgress: Set<string>,\n): T => {\n if (cache.has(obj.id)) {\n return cache.get(obj.id) as T;\n }\n inProgress.add(obj.id);\n\n const { id, ...data } = obj;\n // Prefer cloning through the type entity so the cloned instance preserves\n // `Obj.getType` identity. Falls back to the raw schema for older instances\n // that don't have a type-entity back-reference set (e.g. deserialized).\n const typeEntity = getType(obj);\n const schema = typeEntity != null ? getStaticTypeSchema(typeEntity) : getSchema(obj);\n invariant(schema != null, 'Object should have a type or schema');\n\n const mapRef = (value: unknown, recurse: (value: unknown) => unknown): unknown => {\n if (Ref.isRef(value)) {\n const target = value.target;\n // A ref back to an in-progress object means a cycle — keep the original ref to break it.\n if (\n target != null &&\n !inProgress.has(target.id) &&\n (opts?.deep === 'all' || (opts?.deep === 'parent' && isChildOf(target, root)))\n ) {\n return Ref.make(cloneInner(target, opts, root, cache, inProgress));\n }\n return value;\n }\n return recurse(value);\n };\n\n const props: any = deepMapValues(data, mapRef);\n if (opts?.retainId) {\n props.id = id;\n }\n const meta = deepMapValues(getMeta(obj), mapRef);\n const result = makeObject(schema, props, meta, typeEntity as object | undefined);\n\n inProgress.delete(obj.id);\n cache.set(obj.id, result);\n return result;\n};\n\n/**\n * Whether `entity`'s parent chain reaches `root` — i.e. it is an owned descendant that cascade-deletes with\n * the root. Walks the `ParentId` back-links (a finite tree); guarded against cycles defensively.\n */\nconst isChildOf = (entity: unknown, root: Obj.Any): boolean => {\n const seen = new Set<InternalObjectProps>();\n assumeType<InternalObjectProps>(entity);\n let parent = entity[ParentId];\n while (parent != null && !seen.has(parent)) {\n if (parent.id === root.id) {\n return true;\n }\n seen.add(parent);\n parent = parent[ParentId];\n }\n return false;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as Struct from 'effect/Struct';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport { invariant } from '@dxos/invariant';\n\n// TODO(ZaymonFC): Do this one at a time. This might be dangerous.\nexport const addFieldsToSchema = (schema: Schema.Top, fields: Schema.Struct.Fields): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n // Rebuilt through the AST like its siblings below: `mapFields` is a `Struct` operation and this\n // takes any `Schema.Top`.\n const added = (Schema.Struct(fields).mapFields(Struct.map(Schema.optional)).ast as SchemaAST.Objects)\n .propertySignatures;\n\n return Schema.make<Schema.Top>(\n new SchemaAST.Objects([...ast.propertySignatures, ...added], ast.indexSignatures, ast.annotations),\n );\n};\n\nexport const updateFieldsInSchema = (schema: Schema.Top, fields: Schema.Struct.Fields): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n const updatedProperties = [...ast.propertySignatures];\n const propertiesToUpdate = (Schema.Struct(fields).mapFields(Struct.map(Schema.optional)).ast as SchemaAST.Objects)\n .propertySignatures;\n for (const property of propertiesToUpdate) {\n const index = updatedProperties.findIndex((p) => p.name === property.name);\n if (index !== -1) {\n updatedProperties[index] = property;\n } else {\n updatedProperties.push(property);\n }\n }\n\n return Schema.make<Schema.Top>(new SchemaAST.Objects(updatedProperties, ast.indexSignatures, ast.annotations));\n};\n\nexport const removeFieldsFromSchema = (schema: Schema.Top, fieldNames: string[]): Schema.Top => {\n return Schema.make<Schema.Top>(SchemaAST.omit(schema.ast, fieldNames));\n};\n\nexport const updateFieldNameInSchema = (\n schema: Schema.Top,\n { before, after }: { before: PropertyKey; after: PropertyKey },\n): Schema.Top => {\n const ast = schema.ast as SchemaAST.Objects;\n invariant(SchemaAST.isObjects(ast));\n\n return Schema.make<Schema.Top>(\n new SchemaAST.Objects(\n ast.propertySignatures.map((p) => (p.name === before ? new SchemaAST.PropertySignature(after, p.type) : p)),\n ast.indexSignatures,\n ast.annotations,\n ),\n );\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { IconAnnotation, LabelAnnotation } from '../Annotation/index.ts';\nimport { EntityKind, KindId, SchemaKindId, StaticTypeSchemaSlot } from '../common/types/index.ts';\nimport { EchoTypeKindSchema, TypeMetaSchemaDXN } from '../Entity/index.ts';\nimport { JsonSchemaType } from '../JsonSchema/index.ts';\n\n/**\n * Raw struct backing {@link TypeSchema}. Exposed only so `TypeSchema`\n * (the TS type) can derive its data fields via `Schema.Schema.Type<typeof ...>`;\n * runtime callers should use {@link TypeSchema} (the piped, branded entity).\n *\n * `typename` and `version` are NOT data fields — they live in `EntityMeta.key` /\n * `EntityMeta.version` (the canonical registry-provenance pair, queryable via\n * `Filter.key(...)`). The same `jsonSchema` payload also embeds them so a\n * standalone JSON-Schema export remains self-describing, but the schema-registry\n * reads/writes them through meta.\n */\nconst TypeSchemaStruct = Schema.Struct({\n name: Schema.optional(Schema.String),\n jsonSchema: JsonSchemaType,\n});\n\n/**\n * Persistent representation of a schema.\n */\nexport const TypeSchema = TypeSchemaStruct.pipe(\n LabelAnnotation.set(['name']),\n IconAnnotation.set({\n icon: 'ph--database--regular',\n hue: 'green',\n }),\n EchoTypeKindSchema(TypeMetaSchemaDXN),\n);\n\n/**\n * Persistent representation of a schema — the runtime shape that\n * `db.addType(Type.makeObjectFromJsonSchema(...))` produces\n * and `Filter.type(Type.Type).run()` returns.\n *\n * Structurally identical to a static `Type.Type` entity: the entity-handler's\n * `get` trap exposes `[SchemaKindId]` (derived from `system.kind` and\n * `data.jsonSchema.entityKind`) and rebuilds `[StaticTypeSchemaSlot]` lazily\n * from `jsonSchema`, so a persisted instance satisfies the public `Type<A>`\n * interface without casting.\n */\nexport type TypeSchema = Schema.Schema.Type<typeof TypeSchemaStruct> & {\n /** Object identifier — injected by `EchoTypeKindSchema` and stamped at construction. */\n readonly id: string;\n /** Entity-kind discriminator (object/relation/type) carried on every entity instance. */\n readonly [KindId]: EntityKind.Type;\n /** Kind of schema described by this meta-instance — always `EntityKind.Type` for `Type.Type` itself. */\n readonly [SchemaKindId]: EntityKind.Type;\n /** Effect Schema rebuilt lazily from `jsonSchema`; satisfies `Type.getSchema(...)` without an extra cast. */\n readonly [StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,aACX,WACgE;CAChE,OAAO,OAAO,KAAkE,UAAU,KAAK,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC;AACpH;;;;;;;;;;;;;;ACzBA,IAAa,mBAAmB;AAchC,IAAa,gBAAgB,UAC3B,OAAO,UAAU,YAAY,UAAU,QAAA,kCAA4B;AAErE,IAAM,WAA8C,CAAC;AAErD,IAAa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