@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-Database.mjs","names":["TypeId","__dxlog_file","TypeId","__dxlog_file","__dxlog_file","getUriFromEntity","TypeId","Error.EntityNotFoundError","queryInternal.makeQueryResultEffect"],"sources":["../../src/internal/common/types/model-symbols.ts","../../src/internal/common/types/typename.ts","../../src/internal/Annotation/annotations.ts","../../src/internal/Entity/util.ts","../../src/internal/Entity/api.ts","../../src/internal/Entity/type-uri.ts","../../src/internal/Query/query-result-effect.ts","../../src/Database.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// TODO(rename): These internal entity-wide symbols/types still use the `Object*` prefix but apply\n// to all entities (objects AND relations). Rename to `Entity*` in a follow-up pass (deferred from the\n// EchoURI→EID / ObjectId→EntityId / ObjectMeta→EntityMeta rename, which covered only public SDK API):\n// ObjectCore, ObjectInternals, ObjectVersion, ObjectVersionId, ObjectDeletedId, ObjectDatabaseId,\n// ObjectLoader, ObjectDocumentLoaded, ObjectUnavailable.\n// (ObjectMigration / ObjectMigrationContext intentionally excluded — object-only, not entity-wide.)\n\n/**\n * Internal symbol/string constants for the echo object model.\n * Defined in common/ so proxy/ can use them without importing from Entity/.\n * Entity/ re-exports these for external consumers.\n */\n\n/**\n * Property name for the object's own URI when serialized to JSON.\n */\nexport const ATTR_SELF_URI = '@uri';\n\n/**\n * @deprecated Legacy JSON property name accepted on read for backward compat.\n */\nexport const ATTR_SELF_URI_LEGACY = '@dxn';\n\n/**\n * Symbol carrying the object's own URI on live entities.\n */\nexport const SelfURIId = Symbol.for('@dxos/echo/URI');\n\n/**\n * Property name for deleted when object is serialized to JSON.\n */\nexport const ATTR_DELETED = '@deleted';\n\n/**\n * Deletion marker.\n */\nexport const ObjectDeletedId = Symbol.for('@dxos/echo/Deleted');\n\n/**\n * Object version accessor symbol.\n */\nexport const ObjectVersionId: unique symbol = Symbol.for('@dxos/echo/Version');\n\n/**\n * Object database accessor symbol.\n */\nexport const ObjectDatabaseId = Symbol.for('@dxos/echo/Database');\n\n/**\n * Branch accessor symbol. Resolves to the branch name this object instance is bound to (`'main'` for\n * the canonical object, or the branch of a `db.branch()` independent instance). Read via `Obj.getBranch`.\n */\nexport const ObjectBranchId = Symbol.for('@dxos/echo/Branch');\n\n/**\n * Property name for relation source when object is serialized to JSON.\n */\nexport const ATTR_RELATION_SOURCE = '@relationSource';\n\n/**\n * Used to access relation source ref on live ECHO objects.\n */\nexport const RelationSourceId: unique symbol = Symbol.for('@dxos/echo/RelationSource');\n\n/**\n * Used to access relation source DXN on live ECHO objects.\n */\nexport const RelationSourceDXNId: unique symbol = Symbol.for('@dxos/echo/RelationSourceDXN');\n\n/**\n * Property name for relation target when object is serialized to JSON.\n */\nexport const ATTR_RELATION_TARGET = '@relationTarget';\n\n/**\n * Used to access relation target ref on live ECHO objects.\n */\nexport const RelationTargetId: unique symbol = Symbol.for('@dxos/echo/RelationTarget');\n\n/**\n * Used to access relation target DXN on live ECHO objects.\n */\nexport const RelationTargetDXNId: unique symbol = Symbol.for('@dxos/echo/RelationTargetDXN');\n\n/**\n * Symbol carrying the entity metadata (EntityMeta) on live ECHO entities.\n * Must be importable by both meta.ts (which depends on the Ref schema) and\n * Entity/api.ts (which is transitively imported by the Ref schema), so it\n * cannot live in either of those files without creating an import cycle.\n */\nexport const MetaId = Symbol.for('@dxos/echo/Meta');\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport type * as SchemaAST from '@dxos/effect/SchemaAST';\n\n/**\n * Property name for typename when object is serialized to JSON.\n */\nexport const ATTR_TYPE = '@type';\n\n/**\n * DXN to the object type.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Type');\n\n/**\n * Reference to the object schema.\n */\nexport const SchemaId = Symbol.for('@dxos/echo/Schema');\n\n/**\n * The schema AST a nested value of a typed object follows, carried instead of a schema of its own.\n * @internal\n */\nexport const SchemaAstId = Symbol.for('@dxos/echo/SchemaAst');\n\n/**\n * Property name for parent when object is serialized to JSON.\n */\nexport const ATTR_PARENT = '@parent';\n\n/**\n * Reference to the object parent.\n */\nexport const ParentId = Symbol.for('@dxos/echo/Parent');\n\n/**\n * Reference to the object's type entity (`Type.Obj`, `Type.Relation`, or\n * `Type.Type`). Set at instance creation by `createObject` / `makeObject`\n * when the entity is known. Public read-back via `Obj.getType` / `Relation.getType`\n * / `Entity.getType`.\n */\nexport const TypeEntityId = Symbol.for('@dxos/echo/TypeEntity');\n\n/**\n * Returns the Effect Schema for the given object if one is defined.\n *\n * @internal\n * Internal callers needing schema-side validation read from `SchemaId`.\n * Public callers should use `Type.getSchema(Obj.getType(obj))` instead.\n */\n// TODO(dmaretskyi): For echo objects, this always returns the root schema.\nexport const getSchema = (obj: unknown | undefined): Schema.Codec<any, any> | undefined => {\n if (obj) {\n const ast: SchemaAST.AST | undefined = (obj as any)[SchemaAstId];\n return ast ? Schema.make(ast) : (obj as any)[SchemaId];\n }\n};\n\n/**\n * @internal\n */\nexport const setSchema = (obj: any, schema: Schema.Codec<any, any>): void => {\n Object.defineProperty(obj, SchemaId, {\n value: schema,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n};\n\n/**\n * Returns the type entity (`Type.AnyEntity`) for the given instance.\n * Set at instance creation; every entity has a type. Defensive: returns\n * undefined for null/undefined input so callers can safely probe arbitrary\n * values via this helper.\n *\n * @internal Re-exported via `Obj.getType` / `Relation.getType` / `Entity.getType`.\n */\nexport const getType = (obj: unknown): unknown => {\n if (obj == null) {\n return undefined;\n }\n return (obj as any)[TypeEntityId];\n};\n\n/**\n * @internal\n */\nexport const setType = (obj: any, type: unknown): void => {\n Object.defineProperty(obj, TypeEntityId, {\n value: type,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaTransformation from 'effect/SchemaTransformation';\nimport * as Struct from 'effect/Struct';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, URI } from '@dxos/keys';\nimport { type Primitive } from '@dxos/util';\n\nimport type * as Annotation from '../../Annotation.ts';\nimport { type Mutable } from '../common/proxy/index.ts';\nimport { type AnyProperties, EntityKind, TypeId, getSchema } from '../common/types/index.ts';\nimport { createAnnotationHelper } from './util.ts';\n\nconst ANNOTATION_TYPE_ID: Annotation.TypeId = '~@dxos/echo/Annotation' as const;\n\n/**\n * @internal\n */\nexport const FIELD_PATH_ANNOTATION = 'path';\n\n/**\n * Sets the path for the field.\n * @param path Data source path in the json path format. This is the field path in the source object.\n */\n// TODO(burdon): Field, vs. path vs. property.\nexport const FieldPath = (path: string) => PropertyMeta(FIELD_PATH_ANNOTATION, path);\n\n//\n// Type\n//\n\n/**\n * ECHO identifier (for a stored schema).\n * Must be an `echo:` URI.\n */\nexport const TypeIdentifierAnnotationId = '~@dxos/schema/annotation/TypeIdentifier';\n\nexport const getTypeIdentifierAnnotation = (schema: Schema.Top): string | undefined =>\n SchemaAST.getAnnotation<string>(schema.ast, TypeIdentifierAnnotationId);\n\n/**\n * @returns The schema's type identifier URI — whichever URI fits.\n *\n * - Stored (dynamic) schemas: the schema-as-object's EID, so loaded objects ride\n * along with their schema as a strong dependency.\n * - Non-stored (static) schemas: the typename DXN built from `TypeAnnotation`.\n *\n * This URI is what gets written to an object's `system.type`; queries that filter by\n * type also use it (see `Filter.type` / `getTypeURIFromSpecifier`), so both sides\n * stay symmetric without per-schema branching.\n */\nexport const getSchemaURI = (schema: Schema.Top): URI.URI | undefined => {\n assertArgument(Schema.isSchema(schema), 'schema', 'invalid schema');\n const id = getTypeIdentifierAnnotation(schema);\n if (id) {\n return URI.make(id);\n }\n const objectAnnotation = getTypeAnnotation(schema);\n if (objectAnnotation) {\n return DXN.make(objectAnnotation.typename, objectAnnotation.version);\n }\n return undefined;\n};\n\n//\n// TypeAnnotation\n//\n\n/**\n * Fully qualified globally unique typename.\n * Example: `org.dxos.type.message`\n */\n// TODO(wittjosiah): Factor out to DXN spec.\nexport const TypenameSchema = Schema.String.pipe(\n Schema.check(\n Schema.isPattern(\n /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)$/u,\n ),\n ),\n).annotate({\n description: 'Fully qualified globally unique typename in reverse-DNS form.',\n example: 'org.dxos.type.message',\n});\n\n/**\n * Semantic version format: `major.minor.patch`\n * Example: `1.0.0`\n */\nexport const VersionSchema = Schema.String.pipe(Schema.check(Schema.isPattern(/^\\d+.\\d+.\\d+$/u))).annotate({\n description: 'Semantic version format: `major.minor.patch`',\n example: '1.0.0',\n});\n\nexport const TypeMeta = Schema.Struct({\n typename: TypenameSchema,\n version: VersionSchema,\n});\n\nexport interface TypeMeta extends Schema.Schema.Type<typeof TypeMeta> {}\n\n/**\n * Entity type.\n */\nexport const TypeAnnotationId = '~@dxos/schema/annotation/Type';\n\n/**\n * Payload stored under {@link TypeAnnotationId}.\n */\nexport const TypeAnnotation = TypeMeta.mapFields(\n Struct.assign({\n kind: Schema.Enum(EntityKind),\n\n /**\n * If this is a relation, the schema of the source object.\n * Must be present if entity kind is {@link EntityKind.Relation}.\n */\n sourceSchema: Schema.optional(DXN.Schema),\n\n /**\n * If this is a relation, the schema of the target object.\n * Must be present if entity kind is {@link EntityKind.Relation}.\n */\n targetSchema: Schema.optional(DXN.Schema),\n }),\n);\n\nexport interface TypeAnnotation extends Schema.Schema.Type<typeof TypeAnnotation> {}\n\n/**\n * @returns {@link TypeAnnotation} from a schema.\n * Schema must have been created with {@link TypedObject} or {@link TypedLink} or manually assigned an appropriate annotation.\n */\nexport const getTypeAnnotation = (schema: Schema.Top): TypeAnnotation | undefined => {\n assertArgument(schema != null && schema.ast != null, 'schema', 'invalid schema');\n return SchemaAST.getAnnotation<TypeAnnotation>(schema.ast, TypeAnnotationId);\n};\n\n/**\n * @returns {@link EntityKind} from a schema.\n */\nexport const getEntityKind = (schema: Schema.Top): EntityKind | undefined => getTypeAnnotation(schema)?.kind;\n\n/**\n * @internal\n * @returns Schema typename (without dxn: prefix or version number).\n */\nexport const getSchemaTypename = (schema: Schema.Top): string | undefined => getTypeAnnotation(schema)?.typename;\n\n/**\n * @internal\n * @returns Schema version in semver format.\n */\nexport const getSchemaVersion = (schema: Schema.Top): string | undefined => getTypeAnnotation(schema)?.version;\n\n/**\n * Gets the typename of the object without the version.\n * Returns only the name portion, not the DXN.\n * @example \"com.example.type.contact\"\n *\n * @internal (use Obj.getTypename)\n */\nexport const getTypename = (obj: AnyProperties): string | undefined => {\n const schema = getSchema(obj);\n if (schema != null) {\n // Try to extract typename from DXN.\n return getSchemaTypename(schema);\n } else {\n // `obj` may be an arbitrary value (e.g. from `isInstanceOf`); read TypeId\n // directly so we return undefined for non-entities instead of throwing.\n const type = (obj as any)?.[TypeId];\n // Parse the URI string to extract typename.\n if (DXN.isDXN(type)) {\n const parsed = DXN.tryMake(type);\n return parsed && DXN.getName(parsed);\n }\n return undefined;\n }\n};\n\n/**\n * @internal (use Type.setTypename)\n */\n// TODO(dmaretskyi): Rename setTypeDXN.\nexport const setTypename = (obj: any, typename: URI.URI): void => {\n assertArgument(typeof typename === 'string', 'typename', 'Invalid type.');\n Object.defineProperty(obj, TypeId, {\n value: typename,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n};\n\n/**\n * @returns Object type URI — either a typename {@link DXN} or an `echo:` reference to a stored Schema object.\n * @returns undefined if the object has no registered type URI (e.g. unresolved query result).\n * @example `dxn:com.example.type.person:1.0.0`\n * @example Stored schema: `echo:///01KKKG2FHWCMTR0BY00GJSVT1X`.\n *\n * @internal (use Obj.getTypeURI)\n */\nexport const getTypeURI = (obj: AnyProperties): URI.URI | undefined => {\n if (obj == null) {\n return undefined;\n }\n const type = (obj as any)[TypeId];\n if (type == null) {\n return undefined;\n }\n invariant(URI.isURI(type), 'Invalid object.');\n return type;\n};\n\n//\n// PropertyMeta\n//\n\n/**\n * PropertyMeta (metadata for dynamic schema properties).\n * For user-defined annotations.\n */\nexport const PropertyMetaAnnotationId = '@dxos/schema/annotation/PropertyMeta';\n\nexport type PropertyMetaValue = Primitive | Record<string, Primitive> | Primitive[];\n\nexport type PropertyMetaAnnotation = {\n [name: string]: PropertyMetaValue;\n};\n\n// TODO(wittjosiah): Align with other annotations.\n// TODO(wittjosiah): Why is this separate from FormatAnnotation?\n/**\n * Apply property-level metadata to an Effect schema. Only accepts\n * `Schema.Top` — apply BEFORE wrapping the schema with\n * `Type.makeObject` / `Type.makeRelation`. To read property meta off a\n * `Type.Type` entity, unwrap it first with `Type.getSchema(entity)`.\n */\nexport const PropertyMeta = (name: string, value: PropertyMetaValue) => {\n return <A, I, R>(self: Schema.Codec<A, I, R>): Schema.Codec<A, I, R> => {\n const existingMeta = SchemaAST.getAnnotation<PropertyMetaAnnotation>(self.ast, PropertyMetaAnnotationId);\n return self.annotate({\n [PropertyMetaAnnotationId]: {\n ...existingMeta,\n [name]: value,\n },\n });\n };\n};\n\n/**\n * Reads one property-meta entry off a property. An optional property's type is a union of the\n * annotated schema and `undefined`, whose own annotations are empty, so the members are read too.\n */\nexport const getPropertyMetaAnnotation = <T>(prop: SchemaAST.PropertySignature, name: string): T | undefined => {\n const candidates = SchemaAST.isUnion(prop.type) ? [prop.type, ...prop.type.types] : [prop.type];\n for (const ast of candidates) {\n const value = SchemaAST.getAnnotation<PropertyMetaAnnotation>(ast, PropertyMetaAnnotationId)?.[name];\n if (value !== undefined) {\n return value as T;\n }\n }\n return undefined;\n};\n\n//\n// Reference\n//\n\n/**\n * Schema reference.\n */\nexport const ReferenceAnnotationId = '@dxos/schema/annotation/Reference';\nexport type ReferenceAnnotationValue = TypeAnnotation;\nexport const ReferenceAnnotation = createAnnotationHelper<ReferenceAnnotationValue>(ReferenceAnnotationId);\n\n/**\n * SchemaMeta.\n */\nexport const SchemaMetaSymbol = Symbol.for('@dxos/schema/SchemaMeta');\nexport type SchemaMeta = TypeMeta & { id: string };\n\n/**\n * Identifies label property or JSON path expression.\n * Either a string or an array of strings representing field accessors each matched in priority order.\n */\nexport const LabelAnnotationId = '@dxos/schema/annotation/Label';\nexport const LabelAnnotation = createAnnotationHelper<string[]>(LabelAnnotationId);\n\n/**\n * Returns the label for a given object based on {@link LabelAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n * Skips empty strings and whitespace-only strings, continuing to the next field.\n */\n// TODO(burdon): Convert to SchemaEx.JsonPath?\nexport const getLabelWithSchema = <S extends Schema.Top>(\n schema: S,\n object: Schema.Schema.Type<S>,\n): string | undefined => {\n const annotation = LabelAnnotation.get(schema).pipe(Option.getOrElse(() => ['name']));\n for (const accessor of annotation) {\n assertArgument(\n typeof accessor === 'string',\n 'accessor',\n 'Label annotation must be a string or an array of strings',\n );\n const value = SchemaEx.getField(object, accessor as SchemaEx.JsonPath);\n switch (typeof value) {\n case 'string': {\n const trimmed = value.trim();\n if (trimmed.length > 0) {\n return value;\n }\n continue;\n }\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n return value.toString();\n case 'undefined':\n case 'object':\n case 'function':\n continue;\n }\n }\n\n return undefined;\n};\n\n/**\n * Sets the label for a given object based on {@link LabelAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\n// `object` is not typed by the schema: the annotation names the property at runtime, and TypeScript\n// cannot index-write a generic type parameter.\nexport const setLabelWithSchema = (schema: Schema.Top, object: AnyProperties, label: string) => {\n const annotation = LabelAnnotation.get(schema).pipe(\n Option.map((field) => field[0]),\n Option.getOrElse(() => 'name'),\n );\n object[annotation] = label;\n};\n\n/**\n * Identifies description property or JSON path expression.\n * A string representing field accessor.\n */\nexport const DescriptionAnnotationId = '@dxos/schema/annotation/Description';\nexport const DescriptionAnnotation = createAnnotationHelper<string>(DescriptionAnnotationId);\n\n/**\n * Returns the description for a given object based on {@link DescriptionAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\n// TODO(burdon): Convert to SchemaEx.JsonPath?\nexport const getDescriptionWithSchema = <S extends Schema.Top>(\n schema: S,\n object: Schema.Schema.Type<S>,\n): string | undefined => {\n const accessor = DescriptionAnnotation.get(schema).pipe(Option.getOrElse(() => 'description'));\n assertArgument(typeof accessor === 'string', 'accessor', 'Description annotation must be a string');\n const value = SchemaEx.getField(object, accessor as SchemaEx.JsonPath);\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n return value.toString();\n case 'undefined':\n case 'object':\n case 'function':\n default:\n return undefined;\n }\n};\n\n/**\n * Sets the description for a given object based on {@link DescriptionAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\nexport const setDescriptionWithSchema = (schema: Schema.Top, object: AnyProperties, description: string) => {\n const accessorOpt = DescriptionAnnotation.get(schema);\n if (Option.isNone(accessorOpt)) {\n return;\n }\n object[accessorOpt.value] = description;\n};\n\n/**\n * Identifies if a property should be included in a form or not.\n * By default, all properties are included in forms, so this is opt-out.\n */\nexport const FormInputAnnotationId = '@dxos/schema/annotation/FormInput';\nexport const FormInputAnnotation = createAnnotationHelper<boolean>(FormInputAnnotationId);\n\n/**\n * When set on a `Ref` property, the form renders the referenced object's own\n * fields inline (a nested form bound to the target) instead of a picker.\n */\nexport const FormInlineAnnotationId = '@dxos/schema/annotation/FormInline';\nexport const FormInlineAnnotation = createAnnotationHelper<boolean>(FormInlineAnnotationId);\n\n/**\n * When set on a `Ref` (or array-of-`Ref`) property, the form OWNS the referenced target(s): \"add\" creates a\n * new object of the annotation's typename (instead of opening the existing-object picker) and each target is\n * rendered inline — its own fields — like {@link FormInlineAnnotation}. The target typename is carried here\n * (rather than inferred from the element type) so the field can stay `Ref.Ref(Obj.Unknown)` and avoid pulling\n * the target's type (e.g. query-AST-laden `Trigger`) into the schema's emitted declaration.\n */\nexport const FormCreateAnnotationId = '@dxos/schema/annotation/FormCreate';\nexport const FormCreateAnnotation = createAnnotationHelper<string>(FormCreateAnnotationId);\n\n/**\n * When set on an array property, the form renders it as an ordered,\n * drag-to-reorder list (drag handles per row). Element order is meaningful and\n * user-controllable; reordering rewrites the array.\n */\nexport const FormOrderedAnnotationId = '@dxos/schema/annotation/FormOrdered';\nexport const FormOrderedAnnotation = createAnnotationHelper<boolean>(FormOrderedAnnotationId);\n\n/**\n * How a form presents an array of references; the two options are independent.\n */\nexport type ArrayPresentation = {\n /** Rows (or chips) reorder by drag and keyboard, and the order is persisted; `false` by default. */\n ordered?: boolean;\n /**\n * `tag`: removable chips in the targets' hues (the default for arrays of `Tag` refs). `title`: a row per target with\n * its type's icon, its label and an optional description (the default otherwise).\n */\n display?: 'tag' | 'title';\n /** A property of the target whose value is the `title` row's description line. */\n description?: string;\n};\n\n/**\n * When set on an array-of-`Ref` property, sets how the form presents it ({@link ArrayPresentation}).\n */\nexport const ArrayPresentationAnnotationId = '@dxos/schema/annotation/ArrayPresentation';\nexport const ArrayPresentationAnnotation = createAnnotationHelper<ArrayPresentation>(ArrayPresentationAnnotationId);\n\n/**\n * Annotation carrying one or more named layout DSL templates that control how a\n * form arranges a schema's fields (consumed by `@dxos/react-ui-form`'s\n * `Form.Layout` / `Form.FieldSet`). Callers select a variant by name; the\n * implicit name is `DEFAULT_LAYOUT_NAME` (`'default'`).\n *\n * Templates use a minimal XML grammar. Example:\n *\n * FormLayoutAnnotation.set({\n * default: `\n * <grid cols=\"2\">\n * <field name=\"origin\"/>\n * <field name=\"destination\"/>\n * <field name=\"provider\" span=\"2\"/>\n * </grid>\n * `,\n * card: `\n * <grid cols=\"1\">\n * <field name=\"provider\"/>\n * <field name=\"number\"/>\n * </grid>\n * `,\n * })\n */\nexport const FormLayoutAnnotationId = '@dxos/react-ui-form/annotation/Layout';\n\nexport type FormLayoutMap = Record<string, string>;\n\nexport const FormLayoutAnnotation = createAnnotationHelper<FormLayoutMap>(FormLayoutAnnotationId);\n\n/** Name used when no explicit form-layout variant is requested. */\nexport const DEFAULT_LAYOUT_NAME = 'default';\n\n/**\n * Default field to be used on referenced schema to lookup the value.\n */\nexport const FieldLookupAnnotationId = '@dxos/schema/annotation/FieldLookup';\n\n/**\n * Generate test data.\n */\nexport const GeneratorAnnotationId = '@dxos/schema/annotation/Generator';\n\nexport type GeneratorAnnotationValue =\n | string\n | {\n generator: string;\n args?: any[];\n probability?: number;\n };\n\nexport const GeneratorAnnotation = createAnnotationHelper<GeneratorAnnotationValue>(GeneratorAnnotationId);\n\ninterface MakeAnnoationsProps<T> {\n id: string;\n schema: Schema.Codec<T, any, never>;\n /** Skips the FQN format check on `id`, for a pre-existing id that may already be embedded in persisted schemas. */\n legacyId?: boolean;\n}\n\n// Annotation ids use the same NSID / reverse-DNS format as TypenameSchema —\n// dot-separated segments, middle segments may be hyphenated, final segment may be camelCase.\n// At least 3 segments are required (e.g. org.dxos.annotation.example).\nexport const makeUserAnnotation = <T>(props: MakeAnnoationsProps<T>): Annotation.Annotation<T> => {\n if (!props.legacyId) {\n assertArgument(\n /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?){2,}(\\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)?$/.test(\n props.id,\n ),\n 'id',\n 'Annotation id must be in the FQN format (org.dxos.annotation.example or org.dxos.space.rootCollection). Pass `legacyId: true` to keep an existing non-FQN id.',\n );\n }\n\n const annotation: Annotation.Annotation<T> = {\n [ANNOTATION_TYPE_ID]: { _Type: {} as T },\n key: props.id as Annotation.Key,\n schema: props.schema,\n get: (schema) => getFromAst(schema.ast, annotation),\n getFromAst: (ast) => getFromAst(ast, annotation),\n set: (value) =>\n PropertyMeta(props.id, Schema.encodeSync(props.schema)(value)) as <S extends Schema.Top>(schema: S) => S,\n };\n\n return annotation;\n};\n\nconst IconAnnotationSchema = Schema.Struct({\n /**\n * Sprite icon name (e.g., 'ph--user--regular', 'ph--cube--regular', 'px--anthropic--regular').\n *\n * `ph--*` is Phosphor; `px--*` and `dx--*` are brand glyphs, which are sprite-only and carry no\n * weight variants. All three are admitted because a type whose subject IS a brand — an Anthropic\n * session, a GitHub repo — has no honest Phosphor equivalent.\n */\n icon: Schema.String.pipe(Schema.check(Schema.isPattern(/^(ph|px|dx)--[a-z0-9-]+--[a-z]+$/u))),\n\n /**\n * Color name.\n *\n * List of colors:\n * - 'red'\n * - 'orange'\n * - 'amber'\n * - 'yellow'\n * - 'lime'\n * - 'green'\n * - 'emerald'\n * - 'teal'\n * - 'cyan'\n * - 'violet'\n * - 'purple'\n * - 'fuchsia'\n * - 'pink'\n * - 'rose'\n */\n hue: Schema.optional(Schema.String),\n});\n\nexport interface IconAnnotation extends Schema.Schema.Type<typeof IconAnnotationSchema> {}\n\n/**\n * Icon to render in the UI.\n */\nexport const IconAnnotation = makeUserAnnotation<IconAnnotation>({\n id: 'org.dxos.annotation.icon',\n schema: IconAnnotationSchema,\n});\n\n/**\n * Indicates that this entity's icon should be resolved from a property whose value is a `Ref`\n * to another entity. Consumers (e.g. graph node builders) resolve the ref target and use that\n * target's schema `IconAnnotation` in place of the static one declared on this schema.\n *\n * Useful for wrapper schemas that delegate their visual identity to a referenced sub-entity\n * (e.g. a generic `Game` whose icon should come from its `variant` ref's typed state).\n */\nexport const IconFromRefAnnotation = makeUserAnnotation<string>({\n id: 'org.dxos.annotation.icon.from-ref',\n schema: Schema.String,\n});\n\n/** Value of {@link SetParentAnnotation}. */\nexport type SetParentAnnotationValue = {\n /** Whether the field owns its targets at all. */\n readonly value: boolean;\n /** Whether a write takes a target that already has a parent. */\n readonly override: boolean;\n};\n\n/**\n * Marks a `Ref` field (or an array-of-`Ref` field) as owning its targets: writing a ref into the\n * field, or creating the holder with one, sets the target's parent to the holding object.\n *\n * `{ override: false }` claims only a target that has no parent, so the first field to reference an\n * object becomes its parent and later fields only reference it.\n *\n * This is NOT an invariant: it does not guarantee that a target held here has this object as its\n * parent, only that a write through this field updates the parent. Nothing stops `Obj.setParent`\n * from re-parenting the target afterwards, a ref whose target is not resolved is left alone, and\n * removing a ref does NOT clear the target's parent — a move between holders would otherwise lose\n * the edge depending on write order; call `Obj.setParent(child, undefined)` explicitly. Read the\n * parent with `Obj.getParent`; never infer it from the field.\n *\n * @example\n * ```ts\n * Schema.Struct({\n * body: Ref.Ref(Text.Text).pipe(Annotation.SetParent.set()),\n * objects: Schema.Array(Ref.Ref(Obj.Unknown)).pipe(Annotation.SetParent.set({ override: false })),\n * })\n * ```\n */\nconst SetParentValueSchema = Schema.Struct({ value: Schema.Boolean, override: Schema.Boolean });\n\nconst setParentAnnotation = makeUserAnnotation<SetParentAnnotationValue>({\n id: 'org.dxos.annotation.setParent',\n // Schemas persisted before the value was structured store a bare boolean.\n schema: Schema.Union([\n SetParentValueSchema,\n Schema.Boolean.pipe(\n Schema.decodeTo(\n SetParentValueSchema,\n SchemaTransformation.transform({\n decode: (value: boolean): SetParentAnnotationValue => ({ value, override: true }),\n encode: ({ value }: SetParentAnnotationValue) => value,\n }),\n ),\n ),\n ]),\n});\n\nexport type SetParentAnnotationOptions = {\n readonly override?: boolean;\n};\n\n/** {@link setParentAnnotation}, with a `set` that owns by default. */\nexport const SetParentAnnotation: Omit<Annotation.Annotation<SetParentAnnotationValue>, 'set'> & {\n set: (options?: SetParentAnnotationOptions) => <S extends Schema.Top>(schema: S) => S;\n} = {\n ...setParentAnnotation,\n set: ({ override = true }: SetParentAnnotationOptions = {}) => setParentAnnotation.set({ value: true, override }),\n};\n\n/** Value of {@link UserTypeAnnotation}. */\nexport type UserTypeAnnotationValue = {\n /** Keys a surface filters on (e.g. which types a collection's create dialog offers); opaque to ECHO. */\n readonly tags?: readonly string[];\n};\n\nconst userTypeAnnotation = makeUserAnnotation<UserTypeAnnotationValue>({\n id: 'org.dxos.annotation.userType',\n schema: Schema.Struct({ tags: Schema.optional(Schema.Array(Schema.String)) }),\n});\n\n/**\n * Marks a static type as user-facing, so it shows in pickers, the nav tree, and collections. Absent, the\n * type is internal (like a dotfile, visible only via an advanced setting); a new type stays out of sight\n * until someone opts it in. Stored as property meta, so it survives persisting the schema.\n *\n * @example\n * ```ts\n * Schema.Struct({ ... }).pipe(Annotation.UserType.set());\n * Schema.Struct({ ... }).pipe(Annotation.UserType.set({ tags: [Collection.ItemTag] }));\n * ```\n */\nexport const UserTypeAnnotation: Omit<Annotation.Annotation<UserTypeAnnotationValue>, 'set'> & {\n set: (value?: UserTypeAnnotationValue) => <S extends Schema.Top>(schema: S) => S;\n} = {\n ...userTypeAnnotation,\n set: (value: UserTypeAnnotationValue = {}) => userTypeAnnotation.set(value),\n};\n\n/**\n * Options for {@link getLabel}.\n */\nexport type GetLabelOptions = {\n /**\n * Strategy for deriving a label when the entity has no `LabelAnnotation` value.\n * - `'typename'`: use the entity's typename (e.g. `org.dxos.type.table`).\n * Useful for Card.Title chrome that must always display something, even\n * for unlabeled objects.\n */\n fallback?: 'typename';\n};\n\n/**\n * Get the label of an entity.\n * Accepts both reactive entities and snapshots.\n *\n * If `options.fallback === 'typename'` and no label is set, returns the\n * entity's typename instead.\n */\nexport const getLabel = (entity: AnyProperties, options?: GetLabelOptions): string | undefined => {\n const schema = getSchema(entity);\n const label = schema != null ? getLabelWithSchema(schema, entity) : undefined;\n if (label != null) {\n return label;\n }\n if (options?.fallback === 'typename') {\n return getTypename(entity);\n }\n return undefined;\n};\n\n/**\n * Set the label of an entity.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setLabel = (entity: Mutable<AnyProperties>, label: string) => {\n const schema = getSchema(entity);\n if (schema != null) {\n setLabelWithSchema(schema, entity, label);\n }\n};\n\n/**\n * Returns the primary label property key for an entity.\n * Reads the first accessor from {@link LabelAnnotation}, defaulting to 'name'.\n */\nexport const getLabelProperty = (entity: AnyProperties): string => {\n const schema = getSchema(entity);\n if (schema == null) {\n return 'name';\n }\n return LabelAnnotation.get(schema).pipe(\n Option.flatMap((fields) => Option.fromNullishOr(fields[0])),\n Option.getOrElse(() => 'name'),\n );\n};\n\n/**\n * Get the description of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const getDescription = (entity: AnyProperties): string | undefined => {\n const schema = getSchema(entity);\n if (schema != null) {\n return getDescriptionWithSchema(schema, entity);\n }\n};\n\n/**\n * Get the icon annotation for an entity, resolved via its type-level `IconAnnotation`.\n * Accepts both reactive entities and snapshots.\n *\n * Returns the full `{ icon, hue }` annotation so callers can use both the phosphor icon\n * name and the suggested colour. Callers wanting just the icon name typically write\n * `Obj.getIcon(obj)?.icon ?? 'ph--cube--regular'`.\n *\n * Note: this is the \"static\" icon from the object's own schema. It does not follow\n * `IconFromRefAnnotation` delegation — call sites needing that (e.g. app-graph node\n * builders) should resolve the ref themselves.\n */\nexport const getIcon = (entity: AnyProperties): IconAnnotation | undefined => {\n const schema = getSchema(entity);\n if (schema == null) {\n return undefined;\n }\n return Option.getOrUndefined(IconAnnotation.get(schema));\n};\n\n/**\n * Set the description of an entity.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setDescription = (entity: Mutable<AnyProperties>, description: string) => {\n const schema = getSchema(entity);\n if (schema != null) {\n setDescriptionWithSchema(schema, entity, description);\n }\n};\n\nexport { Dictionary, Key, getDictionary, setDictionary } from './dictionary.ts';\n\nexport const getFromAst = <T>(\n ast: SchemaAST.AST,\n annotation: Pick<Annotation.Annotation<T>, 'key' | 'schema'>,\n): Option.Option<T> => {\n const meta = SchemaAST.getAnnotation<PropertyMetaAnnotation>(ast, PropertyMetaAnnotationId);\n return Option.fromNullishOr(meta?.[annotation.key]).pipe(Option.map(Schema.decodeUnknownSync(annotation.schema)));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport { type InternalObjectProps, SelfURIId } from './model.ts';\n\n/**\n * Returns the EID of an object.\n *\n * @internal\n */\nexport const getObjectEchoUri = (object: any): EID.EID | undefined => {\n invariant(!Schema.isSchema(object), 'schema not allowed in this function');\n assertArgument(typeof object === 'object' && object != null, 'object', 'expected object');\n assumeType<InternalObjectProps>(object);\n\n if (object[SelfURIId]) {\n invariant(EID.isEID(object[SelfURIId]), 'Invalid object model: invalid self dxn');\n return EID.parse(object[SelfURIId]);\n }\n\n if (!EntityId.isValid(object.id)) {\n throw new TypeError('Object id is not valid.');\n }\n\n return EID.make({ entityId: object.id });\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { DXN, EID, type SpaceId, URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport type { AnyEntity } from '../common/types/index.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport { type InternalObjectProps, ObjectBranchId, ObjectDatabaseId } from './model.ts';\nimport { getObjectEchoUri } from './util.ts';\n\n/**\n * Controls the URI form returned by `getUri` and the public `*.getURI` helpers.\n *\n * - `'named'` — Registry key URI (`dxn:<meta.key>`) when the entity has a key in its meta;\n * falls back to the default EID.\n * - `'absolute'` — Fully-qualified EID with space id (`echo://<spaceId>/<entityId>`);\n * falls back when no space is available.\n * - `'relative'` — Local EID without space id (`echo:/<entityId>`).\n *\n * Omitting `prefer` preserves the existing behaviour.\n */\nexport type GetURIOptions = {\n prefer?: 'named' | 'absolute' | 'relative';\n};\n\n/**\n * Get the URI of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const getUri = (entity: AnyEntity, options?: GetURIOptions): URI.URI => {\n const prefer = options?.prefer;\n\n if (prefer === 'named') {\n const key = (entity as any)[MetaId]?.key;\n if (key) {\n return (DXN.tryMake(`dxn:${key}`) ?? URI.make(key)) as URI.URI;\n }\n const uri = getObjectEchoUri(entity);\n invariant(uri != null, 'Invalid entity.');\n return uri;\n }\n\n if (prefer === 'relative') {\n const eid = getObjectEchoUri(entity);\n invariant(eid != null, 'Invalid entity.');\n const entityId = EID.getEntityId(eid);\n return entityId ? EID.make({ entityId }) : eid;\n }\n\n if (prefer === 'absolute') {\n const eid = getObjectEchoUri(entity);\n invariant(eid != null, 'Invalid entity.');\n const entityId = EID.getEntityId(eid);\n if (!entityId) {\n return eid;\n }\n assumeType<InternalObjectProps>(entity);\n const spaceId: SpaceId | undefined = entity[ObjectDatabaseId]?.spaceId ?? EID.getSpaceId(eid);\n return spaceId ? EID.make({ spaceId, entityId }) : eid;\n }\n\n const uri = getObjectEchoUri(entity);\n invariant(uri != null, 'Invalid entity.');\n return uri;\n};\n\n/**\n * Get the database the entity belongs to.\n * Accepts both reactive entities and snapshots.\n */\nexport const getDatabase = (entity: AnyEntity): any | undefined => {\n assumeType<InternalObjectProps>(entity);\n return entity[ObjectDatabaseId];\n};\n\n/**\n * Get the branch this entity instance is bound to (`'main'` for the canonical object, or the branch\n * of a `db.branch()` independent instance). Reads the branch off the instance, so two instances of the\n * same object id on different branches report their own branch.\n */\nexport const getBranch = (entity: AnyEntity): string => {\n assumeType<InternalObjectProps>(entity);\n return entity[ObjectBranchId] ?? 'main';\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport { assertArgument } from '@dxos/invariant';\nimport { DXN, EID, URI } from '@dxos/keys';\n\nimport { getSchemaURI, getTypename } from '../Annotation/annotations.ts';\nimport { type AnyEntity, InstancePhantomId, KindId, TypeId, getStaticTypeSchema } from '../common/types/index.ts';\nimport { getUri as getUriFromEntity } from './api.ts';\n\n/**\n * @param input schema, `Type.Type` entity, or a type URI (an `echo:` EID or a `dxn:` DXN).\n * @return type identifier URI — see {@link getSchemaURI}. A URI is returned verbatim. For a\n * `Type.Type` entity, the URI of the schema it declares, symmetric with what\n * `Obj.make(typeEntity, ...)` stamps on `system.type`: a static declaration resolves to its\n * typename DXN, a persisted entity to its local `echo:///<objectId>`.\n */\nexport const getTypeURIFromSpecifier = (input: Schema.Top | AnyEntity | URI.URI): URI.URI => {\n if (Schema.isSchema(input)) {\n return getSchemaURI(input) ?? raise(new TypeError('Schema has no URI'));\n }\n // Type entities are normally proxy objects, but class-declared types from\n // `Type.makeObject` are functions whose prototype chain reaches the entity, so accept functions too.\n if (input !== null && (typeof input === 'object' || typeof input === 'function') && KindId in input) {\n // `Type.Type` entity. Both in-memory and persisted forms expose the schema\n // they declare via `StaticTypeSchemaSlot`, whose URI is exactly what\n // `Obj.make` stamps on `system.type` — a static declaration carries\n // `TypeAnnotation` (→ typename DXN), a persisted entity's rebuilt schema\n // carries `TypeIdentifierAnnotation` (→ local `echo:///<objectId>`).\n const schema = getStaticTypeSchema(input);\n if (schema != null) {\n // Static types carry TypeAnnotation → DXN; persisted db types carry\n // TypeIdentifierAnnotation → echo EID. In-memory makeObjectFromJsonSchema\n // entities have neither (plain JSON Schema), so fall through to the EID path.\n const uri = getSchemaURI(schema);\n if (uri != null) {\n return uri;\n }\n }\n return getUriFromEntity(input as AnyEntity);\n }\n // A string specifier is already a branded URI — an `echo:` EID or a `dxn:` DXN.\n assertArgument(EID.isEID(input) || DXN.isDXN(input), 'input', 'expected a type URI (EID or DXN)');\n return input;\n};\n\n/**\n * Checks if the object is an instance of the schema.\n * Only typename is compared, the schema version is ignored.\n *\n * The following cases are considered to mean that the object is an instance of the schema:\n * - Object was created with this exact schema.\n * - Object was created with a different version of this schema.\n * - Object was created with a different schema (maybe dynamic) that has the same typename.\n */\n// TODO(burdon): Can we use `Schema.is`?\nexport const isInstanceOf = <S>(\n schemaOrType: S extends Schema.Codec<any, any> ? S : Schema.Codec<any, any> | AnyEntity,\n object: any,\n): object is S extends Schema.Codec<any, any>\n ? Schema.Schema.Type<S>\n : S extends { readonly [InstancePhantomId]?: infer A }\n ? A\n : unknown => {\n if (object == null) {\n return false;\n }\n\n const schemaURI = getTypeURIFromSpecifier(schemaOrType);\n\n // `object` is arbitrary input — read TypeId directly (it may be missing on\n // non-entities) rather than via `getTypeURI` which asserts the URI is set.\n const type = (object as any)[TypeId];\n if (URI.isURI(type) && type === schemaURI) {\n return true;\n }\n\n const typename = getTypename(object);\n if (!typename) {\n return false;\n }\n\n if (!DXN.isDXN(schemaURI)) {\n // EID-based schema URI — no typename match possible.\n return false;\n }\n\n const parsed = DXN.tryMake(schemaURI);\n return parsed != null && DXN.getName(parsed) === typename;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Effectable from 'effect/Effectable';\nimport * as Option from 'effect/Option';\n\nimport type * as QueryResult from '../../QueryResult.ts';\n\n/**\n * Wraps an effect that produces a {@link QueryResult.QueryResult} into a\n * {@link QueryResult.QueryResultEffect}, exposing `.run` and `.first` shorthands that execute the\n * query once. Shared by `Database.query` and `Feed.query` so both surfaces chain identically.\n */\nexport const makeQueryResultEffect = <T, E, R>(\n eff: Effect.Effect<QueryResult.QueryResult<T>, E, R>,\n): QueryResult.QueryResultEffect<T, E, R> => {\n // Effect 4 replaced the spread-in `CommitPrototype` with `Prototype`, which takes the old\n // `commit()` body as `evaluate` and builds the Effect-shaped base itself.\n const base = Effectable.Prototype<Effect.Effect<QueryResult.QueryResult<T>, E, R>>({\n label: '@dxos/echo/QueryResultEffect',\n evaluate: () => eff,\n });\n\n return Object.assign(base, {\n run: Effect.flatMap(eff, (result) => Effect.promise(() => result.run())),\n first: Effect.flatMap(eff, (result) =>\n Effect.promise(async () => Option.fromNullishOr(await result.firstOrUndefined())),\n ),\n }) as QueryResult.QueryResultEffect<T, E, R>;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Queue from 'effect/Queue';\nimport * as Schema from 'effect/Schema';\nimport * as Stream from 'effect/Stream';\n\nimport type { CleanupFn } from '@dxos/async';\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\nimport { invariant } from '@dxos/invariant';\nimport { type SpaceId, type URI } from '@dxos/keys';\n\nimport type * as Blob from './Blob.ts';\nimport type * as Change from './Change.ts';\nimport type * as Entity from './Entity.ts';\nimport * as Error from './Error.ts';\nimport type * as Feed from './Feed.ts';\nimport type * as Filter from './Filter.ts';\nimport type * as Hypergraph from './Hypergraph.ts';\nimport { type AnyProperties, EntityKind, KindId } from './internal/common/types/index.ts';\n// Deep import (not the `./internal/Entity` barrel) to avoid a cycle:\n// Database → internal/Entity → entity → JsonSchema → Ref → Database.\nimport { isInstanceOf } from './internal/Entity/type-uri.ts';\nimport * as queryInternal from './internal/Query/index.ts';\nimport type { LoadOptions, Ref } from './internal/Ref/ref.ts';\nimport type * as Obj from './Obj.ts';\nimport type * as Query from './Query.ts';\nimport type * as QueryResult from './QueryResult.ts';\nimport type * as Registry from './Registry.ts';\nimport type * as Type from './Type.ts';\n\n/**\n * `query` API function declaration.\n */\n// TODO(burdon): Reconcile Query and Filter (should only have one root type).\nexport interface QueryFn {\n <Q extends Query.Any>(query: Q): QueryResult.QueryResult<Query.Type<Q>>;\n <F extends Filter.Any>(filter: F): QueryResult.QueryResult<Filter.Type<F>>;\n}\n\n/**\n * Common interface for Database, Feed, and Hypergraph.\n */\nexport interface Queryable {\n query: QueryFn;\n}\n\nexport type GetObjectByIdOptions = {\n deleted?: boolean;\n};\n\nexport type ObjectPlacement = 'root-doc' | 'linked-doc';\n\n/**\n * Whether a write was a person's own action, reported with ECHO's trace events. `system` is everything a person\n * did not directly do: agents, syncs and imports, seeded content, migrations and automation. When no origin is\n * given, an object with foreign keys was written by a sync or import (`system`) and anything else is `unknown`:\n * a write path that still needs attributing.\n */\nexport type Origin = 'user' | 'system' | 'unknown';\n\n/**\n * The {@link Origin} the Effect wrappers ({@link add}, {@link remove}, {@link addType}, {@link appendToFeed})\n * attribute their writes to. Provided once around a unit of work, e.g. `system` around seeding code or an\n * agent's operations, rather than at every write.\n */\nexport const Origin: Context.Reference<Origin | undefined> = Context.Reference<Origin | undefined>(\n '@dxos/echo/Database/Origin',\n { defaultValue: () => undefined },\n);\n\n/**\n * The trace events ECHO emits on `trace.events` from `@dxos/tracing` for local writes, each with the write's\n * {@link Origin}. Replicated writes are not reported.\n */\nexport const TraceEvents = {\n objectAdd: 'echo.object.add',\n objectRemove: 'echo.object.remove',\n typeAdd: 'echo.type.add',\n feedAppend: 'echo.feed.append',\n} as const;\n\n/** Options for writes that only carry attribution. */\nexport type WriteOptions = {\n /** See {@link Origin}. */\n origin?: Origin;\n};\n\nexport type AddOptions = {\n /**\n * Where to place the object in the Automerge document tree.\n * Root document is always loaded with the space.\n * Linked documents are loaded lazily.\n * Placing large number of objects in the root document may slow down the initial load.\n *\n * @default 'linked-doc'\n */\n placeIn?: ObjectPlacement;\n\n /** See {@link Origin}. */\n origin?: Origin;\n\n /**\n * Append the object to this feed instead of the automerge-backed space database. The object is\n * returned synchronously (a live feed object) and persisted in the background — confirm the write\n * completed with {@link Database.flush}. Synchronous alternative to the async\n * {@link Database.appendToFeed}; `placeIn` is ignored when set.\n */\n to?: Feed.Feed;\n};\n\n/**\n * Rejects Type entities from {@link Database.add} at compile time via their `[KindId]` brand. Used\n * as `T & RejectTypeEntity<T>` to preserve inference of `T`. Bounding `add` on\n * `Obj.Unknown | Relation.Unknown` instead would reject broadly-typed instance adds (e.g.\n * `Entity.Any`, `Obj.OfShape<T>`), forcing casts repo-wide.\n */\nexport type RejectTypeEntity<T> = T extends { readonly [KindId]: EntityKind.Type }\n ? { __error: 'Type entities must be persisted via db.addType(), not db.add().' }\n : T;\n\nexport type FlushOptions = {\n /**\n * Write any pending changes to disk.\n * @default true\n */\n disk?: boolean;\n\n /**\n * Wait for pending index updates.\n * @default true\n */\n indexes?: boolean;\n\n /**\n * Also wait for the secondary indexes (full text), which lag the primary pass by design.\n * @default false\n */\n secondaryIndexes?: boolean;\n\n /**\n * Flush pending updates to objects and queries.\n * @default false\n */\n updates?: boolean;\n};\n\n/**\n * A caller-owned, writable **independent instance** of one object bound to one branch: a distinct\n * object instance (not a UI surface), separate from the device-global canonical object.\n * @see Database.branch\n */\nexport type BranchBinding<T extends Obj.Unknown = Obj.Unknown> = {\n /** Live object bound to the branch document (`'main'` -> the canonical live object). */\n readonly object: T;\n /** Release the binding (drops the doc-handle listener; never deletes the branch document). */\n dispose(): void;\n};\n\n/**\n * Identifier denoting an ECHO Database.\n *\n * Namespaced (like `@dxos/echo/Database/Service` below) rather than the bare `@dxos/echo/Database`:\n * that key belongs to the `[ObjectDatabaseId]` accessor every ECHO object carries, and a shared\n * registry key would make `TypeId in obj` true for every object in the graph.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Database/TypeId');\nexport type TypeId = typeof TypeId;\n\n/**\n * ECHO Database interface.\n */\nexport interface Database extends Queryable {\n readonly [TypeId]: TypeId;\n\n get spaceId(): SpaceId;\n\n get graph(): Hypergraph.Hypergraph;\n\n /**\n * Registry for this database. Delegates type lookups to the shared hypergraph registry.\n * To persist a schema so it replicates to other clients, add the type entity with\n * {@link addType} (e.g. `await db.addType(Type.makeObjectFromJsonSchema(...))`).\n */\n readonly registry: Registry.Registry;\n\n /**\n * Summary of the database for logging.\n *\n * @performance O(n) in loaded objects; allocates the object-core list to count it.\n */\n toJSON(): object;\n\n /**\n * Return object by local ID.\n * @deprecated Use `db.query(Filter.id(id)).runSync()[0]` for a working-set lookup, or resolve via a {@link Ref}.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\n getObjectById<T extends Obj.Unknown = Obj.OfShape<AnyProperties>>(\n id: string,\n opts?: GetObjectByIdOptions,\n ): T | undefined;\n\n /**\n * Query objects.\n *\n * @performance O(AST size) to key the result cache; returns a shared, lazily executed result, so nothing runs until\n * read.\n */\n query: QueryFn;\n\n /**\n * Creates a reference to an existing object in the database.\n *\n * NOTE: The reference may be dangling if the object is not present in the database.\n * NOTE: Difference from `Ref.fromURI`\n * `Ref.fromURI(dxn)` returns an unhydrated reference. The `.load` and `.target` APIs will not work.\n * `db.makeRef(dxn)` is preferable in cases with access to the database.\n *\n * @performance O(1); allocates a resolver-bound ref without looking the target up.\n */\n makeRef<T extends Entity.Unknown = Entity.Unknown>(uri: URI.URI): Ref<T>;\n\n /**\n * Adds an object or relation to the database.\n *\n * Only Object and Relation entities are accepted. To persist a Type definition use\n * {@link addType} — passing a Type entity is rejected at compile time (and at runtime).\n *\n * Pass `{ to: feed }` to append to a feed instead (synchronous; confirm with {@link flush}).\n *\n * @performance Synchronous; O(n) in object size to write it into a new linked document (or the root), persisted in\n * the background.\n */\n add<T extends Entity.Unknown = Entity.Unknown>(obj: T & RejectTypeEntity<T>, opts?: AddOptions): T;\n\n /**\n * Persists a Type definition (clones/forks the entity) so it replicates to other peers.\n *\n * Runs a conflict query first: if a type with the same typename + version already exists in\n * this space, the existing persisted entity is returned and no duplicate is created. This is\n * the only supported way to add Type entities — {@link add} rejects them.\n *\n * @performance Async; O(t) in the space persisted types, which it queries in full for a duplicate before writing.\n */\n addType<T extends Type.AnyEntity>(type: T, opts?: WriteOptions): Promise<T>;\n\n /**\n * Removes object from the database.\n *\n * @performance O(1); sets the deletion marker (a soft delete).\n */\n // TODO(burdon): Return true if removed (currently throws if not present).\n remove(obj: Entity.Unknown, opts?: WriteOptions): void;\n\n /**\n * Appends entities to a feed.\n *\n * The feed must already be stored in the database (added via {@link add}); its underlying\n * queue is addressed by the feed object's URI.\n *\n * @performance Async; O(n) in entities encoded and appended to the feed in one batch.\n */\n appendToFeed(feed: Feed.Feed, entities: Entity.Unknown[], opts?: WriteOptions): Promise<void>;\n\n /**\n * Removes entities from a feed.\n *\n * @performance Async; O(n) in entities, deleted by id in one batch.\n */\n deleteFromFeed(feed: Feed.Feed, entities: Entity.Unknown[]): Promise<void>;\n\n /**\n * Wait for all pending changes to be saved to disk.\n * Optionaly waits for changes to be propagated to indexes and event handlers.\n *\n * @performance Async; always waits for pending document creation, then only for the disk, index and update work\n * that `opts` selects, so it is as slow as that selected backlog.\n */\n flush(opts?: FlushOptions): Promise<void>;\n\n //\n // Branching. A branch is a writable alternate timeline of an object subtree (same object ids,\n // shared automerge history, true CRDT merge-back). The registry is synced on the space root;\n // the currently-viewed branch stays device-local.\n //\n\n /**\n * The device-global current branch for an object id (`'main'` by default).\n * @deprecated Prefer `Obj.getBranch(obj)` — it takes the object and reports the branch of that\n * specific instance (including `db.branch()` independent instances), not just the device selection.\n *\n * @performance O(1) device-local map lookup.\n */\n getCurrentBranch(objectId: string): string;\n\n /**\n * An immutable snapshot of the object at the given historical heads — a detached instance, not a\n * pin on the live object. Prefer `Obj.getVersion(obj, heads)`.\n *\n * @performance O(object size) plus the Automerge cost of viewing the document at `heads`; nothing is cached.\n */\n getVersion<T extends Obj.Unknown>(obj: T, heads: readonly string[]): Obj.Snapshot<T>;\n\n /**\n * The object's history, oldest first: one entry per document change that touched the object (or,\n * given `property`, that property). Prefer `Obj.getChanges(obj, opts)`.\n *\n * @performance O(document history): diffs every change of the Automerge document and snapshots each match; not\n * cached.\n */\n getChanges<T extends Obj.Unknown>(obj: T, opts?: Obj.GetChangesOptions): Change.ValueChange<unknown>[];\n\n /**\n * All branch names available for an object, including the implicit `'main'` (always first).\n *\n * @performance O(1) for a subtree root; a member scans every branch record in the space to find its root.\n */\n listBranches(objectId: string): string[];\n\n /**\n * Fork the object and its referenced subtree into a new branch (does not switch to it).\n * @param opts.fromHeads Fork from a historical frontier instead of the tip (a bare heads array\n * applies to the root only; a map forks each member from its own frontier).\n *\n * @performance Async; O(subtree size), each member document forked as a full history copy.\n */\n createBranch(\n rootObjectId: string,\n name: string,\n opts?: { fromHeads?: readonly string[] | Record<string, readonly string[]> },\n ): Promise<void>;\n\n /**\n * Switch the object's subtree to a branch (or back to `'main'`). Device-local; cascades to children.\n *\n * @performance Async; O(subtree size) rebinds, serialized with other branch operations.\n */\n switchBranch(rootObjectId: string, name: string): Promise<void>;\n\n /**\n * Merge a branch back into main across the subtree, then switch back to main.\n *\n * @performance Async; O(subtree size) Automerge merges followed by a switch back to main.\n */\n mergeBranch(rootObjectId: string, name: string, opts?: { deleteAfter?: boolean }): Promise<void>;\n\n /**\n * Fold main's changes into a branch across the subtree (the reverse of {@link mergeBranch}).\n *\n * @performance Async; O(subtree size) Automerge merges, serialized with other branch operations.\n */\n syncBranch(rootObjectId: string, name: string): Promise<void>;\n\n /**\n * Delete a branch (its documents lose their sync reference). Cannot delete `'main'`.\n *\n * @performance O(subtree size); one root-document change plus a background rebind of members viewing the branch.\n */\n deleteBranch(rootObjectId: string, name: string): void;\n\n /**\n * Create a caller-owned, writable binding to one branch of one object — a live object whose reads\n * resolve the branch document and whose writes land on the branch document only. Multiple bindings\n * to different branches of the same object may coexist; the device-global current branch and other\n * bindings are unaffected. Binding to `'main'` returns the canonical live object. Bindings are\n * ephemeral and never persisted — the caller must `dispose()`.\n *\n * @performance Async; O(1) for main, otherwise loads and binds the branch document of this one object.\n */\n branch<T extends Obj.Unknown>(obj: T, name: string): Promise<BranchBinding<T>>;\n\n /**\n * Removes feed items by ID.\n *\n * @performance Async; O(n) in ids, deleted in one batch.\n */\n removeFeedItemsByIds(feed: Feed.Feed, ids: string[]): Promise<void>;\n\n /**\n * Syncs a feed with the server.\n *\n * @performance Async; network-bound, proportional to the replication backlog.\n */\n syncFeed(feed: Feed.Feed, options?: Feed.SyncOptions): Promise<void>;\n\n /**\n * Returns queue replication backlog for the feed's namespace.\n *\n * @performance Async; one service round trip.\n */\n getFeedSyncState(feed: Feed.Feed): Promise<Feed.SyncState>;\n\n /**\n * Disposes and drops the in-memory handle (live working-set / core cache) for a feed, so the next\n * access re-reads it cold. Advanced cache-control; primarily used by tests to model a spawned\n * process reading the feed with an empty in-memory cache. Public (not `_`-prefixed) so it survives\n * declaration stripping for cross-package test use.\n *\n * @performance Async; O(1) eviction, and the next access re-reads the feed cold.\n */\n evictFeedHandle(feed: Feed.Feed): Promise<void>;\n\n /**\n * Hashes and uploads `bytes` via the chosen storage backend, returning an un-added Blob object.\n * Rejects with `Error.BlobTooLargeError` (over inline storage's fixed cap, or the backend's own\n * `maxSize`), `Error.BlobWriteError` (backend upload failure), or `Error.BlobNotAvailableError`\n * (`reason: 'backend-not-registered'` — the requested storage name has no registered backend).\n *\n * @performance Async; O(size) to hash, plus the backend upload (a no-op for inline storage).\n */\n createBlob(bytes: Uint8Array, options?: { type?: string; storage?: string }): Promise<Blob.Blob>;\n\n /**\n * Adopts bytes already staged by a direct upload, returning an un-added Blob object.\n *\n * Unlike {@link createBlob} the bytes never enter this process: they were written straight to the\n * store by whoever held the upload URL, which is the point — the uploader is typically an agent's\n * shell moving a file far too large to pass through a model. Size and content type therefore come\n * back from the store rather than from the caller.\n *\n * Rejects with `Error.BlobNotAvailableError` (`reason: 'backend-not-registered'` when the storage\n * name has no backend, `'not-found'` when the backend cannot adopt uploads or the upload is gone)\n * or `Error.BlobWriteError` if adoption fails.\n *\n * @performance Async; one backend round trip, and the bytes never pass through this process.\n */\n createBlobFromUpload(uploadId: string, options?: { storage?: string }): Promise<Blob.Blob>;\n\n /**\n * Loads a blob's bytes. Rejects with `Error.BlobNotAvailableError` if the backend for the blob's\n * storage scheme is not registered, offline, or cannot find the bytes.\n *\n * @performance Async; O(size), read inline or fetched from the backend.\n */\n readBlob(blob: Blob.Blob): Promise<Uint8Array>;\n\n /**\n * Checks whether a blob's bytes are currently available.\n *\n * @performance Async; one backend check, with no byte transfer.\n */\n blobExists(blob: Blob.Blob): Promise<boolean>;\n\n /**\n * Returns a renderable URL for the blob, if one can be produced.\n *\n * @performance Async; an inline blob encodes all of its bytes into a `data:` URL (O(size)), an external one asks the\n * backend.\n */\n getBlobUrl(blob: Blob.Blob): Promise<string | undefined>;\n\n /**\n * Get the current combined (automerge documents + feed blocks) sync state, reported against a\n * single remote peer.\n *\n * @performance Async; two concurrent service round trips (documents and feeds).\n */\n getSyncState(options?: GetSyncStateOptions): Promise<SyncState>;\n\n /**\n * Subscribe to combined sync state changes.\n *\n * @performance O(1) setup of two service streams, each update recombined in O(peers).\n */\n subscribeToSyncState(cb: (state: SyncState) => void, options?: GetSyncStateOptions): CleanupFn;\n\n /**\n * Per-space storage metrics: objects (alive/deleted), automerge documents, feeds, feed blocks.\n * Read-only. Intended as an occasional/administrative call. See garbage-collection design notes\n * in `@dxos/echo-host`.\n *\n * @performance Async; one host round trip plus an O(feeds) client-side tally.\n */\n stats(): Promise<DatabaseStats>;\n\n /**\n * Reclaim storage held by soft-deleted objects and the documents / feed blocks that are no longer\n * reachable. Per-space and destructive; intended as an occasional/administrative call. See\n * garbage-collection design notes in `@dxos/echo-host`.\n *\n * @performance Async; host-side and O(space size), so run it rarely.\n */\n runGarbageCollection(options?: GarbageCollectionOptions): Promise<GarbageCollectionReport>;\n\n /**\n * Replaces the set of objects the space directory tracks, dropping everything not retained.\n *\n * Derived from the directory's own maps, so clearing a space costs one change rather than a scan\n * of its contents. The objects are dropped, not soft-deleted: they are gone from the space and\n * their documents are reclaimed by garbage collection, on this peer and — as the change\n * replicates — on every other. Permanent; there is nothing left to restore from.\n *\n * @returns Ids of the objects dropped from the directory.\n *\n * @performance O(directory size) scan of the space root plus one root-document change, with no object loads.\n */\n retainObjects(keep: Iterable<string>): string[];\n}\n\n/**\n * Type guard for databases.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isDatabase = (obj: unknown): obj is Database => {\n return obj ? typeof obj === 'object' && TypeId in obj && obj[TypeId] === TypeId : false;\n};\n\nexport const Database: Schema.Codec<Database> = Schema.Any.pipe(Schema.refine(isDatabase));\n\n/**\n * Effect service tag for Database dependency injection.\n */\nexport class Service extends Context.Service<\n Service,\n {\n readonly db: Database;\n }\n>()('@dxos/echo/Database/Service') {}\n\n/**\n * Layer that provides a Database service that throws when accessed.\n * Useful as a default layer when no database is available.\n */\nexport const notAvailable = Layer.succeed(Service, {\n get db(): Database {\n throw new globalThis.Error('Database not available');\n },\n});\n\n/**\n * Creates a Database service instance from a Database.\n *\n * @performance O(1).\n */\nexport const makeService = (db: Database): Service['Service'] => {\n return {\n get db() {\n return db;\n },\n };\n};\n\n/**\n * Creates a Layer that provides the Database service.\n *\n * @performance O(1).\n */\nexport const layer = (db: Database): Layer.Layer<Service> => {\n return Layer.succeed(Service, makeService(db));\n};\n\n/**\n * Stamps the database's space on every span the effect opens, so a span can be filtered by the space\n * it ran in. Applied after `Effect.withSpan`, so the span it names is inside the annotated region.\n *\n * @performance O(1) span annotation around the effect.\n */\nexport const withSpaceId = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | Service> =>\n Effect.flatMap(Service, ({ db }) => effect.pipe(Effect.annotateSpans(SpanAttributes.SPACE_ID, db.spaceId)));\n\n/**\n * Returns the space ID of the database.\n *\n * @performance O(1) service read.\n */\nexport const spaceId = Effect.gen(function* () {\n const { db } = yield* Service;\n return db.spaceId;\n});\n\n/**\n * Resolves an object by its DXN.\n *\n * @performance Async; working-set hit is O(1), otherwise loads the object from disk or the network.\n */\nexport const resolve: {\n // No type check.\n (ref: URI.URI | Ref<any>): Effect.Effect<Entity.Unknown, never, Service>;\n // Check matches schema.\n <S extends Type.AnyEntity>(\n ref: URI.URI | Ref<any>,\n schema: S,\n ): Effect.Effect<Type.InstanceType<S>, Error.EntityNotFoundError, Service>;\n} = (<S extends Type.AnyEntity>(\n ref: URI.URI | Ref<any>,\n schema?: S,\n): Effect.Effect<Type.InstanceType<S>, Error.EntityNotFoundError, Service> =>\n Effect.gen(function* () {\n const { db } = yield* Service;\n const dxn = typeof ref === 'string' ? ref : ref.uri;\n const object = yield* Effect.promise(() =>\n db.graph\n .createRefResolver({\n context: {\n space: db.spaceId,\n },\n })\n .resolveLegacy(dxn),\n );\n\n if (!object) {\n return yield* Effect.fail(new Error.EntityNotFoundError(dxn));\n }\n // `isInstanceOf` uses a conditional generic that TS can't resolve through\n // the local `S extends Type.AnyEntity` parameter — runtime accepts it fine.\n invariant(!schema || isInstanceOf(schema as any, object), 'Object type mismatch.');\n return object as any;\n }).pipe(Effect.withSpan('Database.resolve'), withSpaceId)) as any;\n\n/**\n * Loads an object reference. A deleted target reads as absent unless `{ deleted: 'include' }` asks\n * for it.\n *\n * The options parameter means this cannot be passed point-free where the caller supplies a second\n * argument — `Effect.forEach(refs, (ref) => load(ref))`, not `Effect.forEach(refs, load)`, since the\n * iteratee index would land on `options`.\n *\n * Catching not found error:\n *\n * ```ts\n * yield* load(ref).pipe(Effect.catchTag('EntityNotFoundError', () => Effect.succeed(undefined)));\n * ```\n *\n * @performance Async; resolves immediately for a loaded target, otherwise loads from disk or the network.\n */\nexport const load: <T>(ref: Ref<T>, options?: LoadOptions) => Effect.Effect<T, Error.EntityNotFoundError, never> =\n Effect.fn('Database.load')(function* (ref, options) {\n const object = yield* Effect.promise(() => ref.tryLoad(options));\n if (!object) {\n return yield* Effect.fail(new Error.EntityNotFoundError(ref.uri));\n }\n return object;\n });\n\n/**\n * Synchronous working-set read (see {@link Ref.peek}): the materialized target, or `undefined` —\n * never throws and never triggers loading. Compose with {@link load} for a sync-when-materialized\n * read with an async fallback, keeping the effect runnable under `Effect.runSync` when every ref\n * is materialized (e.g. a mutation in a gesture frame):\n *\n * ```ts\n * const task = Database.peek(ref) ?? (yield* Database.load(ref));\n * ```\n *\n * Peek skips {@link load}'s settling — a just-added object can resolve here before it has its own\n * document — so callers that branch (or otherwise need a settled document) must load.\n *\n * @performance O(1) working-set lookup; never loads and never throws.\n */\nexport const peek = <T>(ref: Ref<T>): T | undefined => ref.peek();\n\n/**\n * Makes a reference to an object addressed by URI, resolvable against this database.\n * @see {@link Database.makeRef}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const makeRef = <T extends Entity.Unknown = Entity.Unknown>(\n uri: URI.URI,\n): Effect.Effect<Ref<T>, never, Service> =>\n Service.pipe(Effect.map(({ db }) => db.makeRef<T>(uri))).pipe(Effect.withSpan('Database.makeRef'), withSpaceId);\n\n/**\n * Adds an object or relation to the database.\n * @see {@link Database.add}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\n// The Effect wrapper intentionally omits the method's `opts` (e.g. `{ to: feed }`): it is applied\n// point-free (`Effect.forEach(Database.add)`), where a second parameter would collide with the\n// iteratee index. Effect-style feed appends go through `Database.appendToFeed` / `Feed.append`.\nexport const add = <T extends Entity.Unknown>(obj: T & RejectTypeEntity<T>): Effect.Effect<T, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.map(Origin, (origin) => db.add<T>(obj, { origin })))).pipe(\n Effect.withSpan('Database.add'),\n withSpaceId,\n );\n\n/**\n * Persists a Type definition to the database.\n * @see {@link Database.addType}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const addType = <T extends Type.AnyEntity>(type: T): Effect.Effect<T, never, Service> =>\n Service.pipe(\n Effect.flatMap(({ db }) => Effect.flatMap(Origin, (origin) => Effect.promise(() => db.addType(type, { origin })))),\n ).pipe(Effect.withSpan('Database.addType'), withSpaceId);\n\n/**\n * Removes an object from the database.\n * @see {@link Database.remove}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const remove = <T extends Entity.Unknown>(obj: T): Effect.Effect<void, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.map(Origin, (origin) => db.remove(obj, { origin })))).pipe(\n Effect.withSpan('Database.remove'),\n withSpaceId,\n );\n\n/**\n * Appends entities to a feed.\n * @see {@link Database.appendToFeed}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const appendToFeed = (feed: Feed.Feed, entities: Entity.Unknown[]): Effect.Effect<void, never, Service> =>\n Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.flatMap(Origin, (origin) => Effect.promise(() => db.appendToFeed(feed, entities, { origin }))),\n ),\n ).pipe(Effect.withSpan('Database.appendToFeed'), withSpaceId);\n\n/**\n * Removes entities from a feed.\n * @see {@link Database.deleteFromFeed}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const deleteFromFeed = (feed: Feed.Feed, entities: Entity.Unknown[]): Effect.Effect<void, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.deleteFromFeed(feed, entities)))).pipe(\n Effect.withSpan('Database.deleteFromFeed'),\n withSpaceId,\n );\n\n/**\n * Flushes pending changes to disk.\n * @see {@link Database.flush}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const flush = (opts?: FlushOptions) =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.flush(opts)))).pipe(\n Effect.withSpan('Database.flush'),\n withSpaceId,\n );\n\n/**\n * Reclaims storage held by soft-deleted objects and the documents they orphan.\n * @see {@link Database.runGarbageCollection}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const runGarbageCollection = (options?: GarbageCollectionOptions) =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.runGarbageCollection(options)))).pipe(\n Effect.withSpan('Database.runGarbageCollection'),\n withSpaceId,\n );\n\n/**\n * Drops every object in the space except the retained ones. Permanent.\n * @see {@link Database.retainObjects}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const retainObjects = (keep: Iterable<string>) =>\n Service.pipe(Effect.map(({ db }) => db.retainObjects(keep))).pipe(\n Effect.withSpan('Database.retainObjects'),\n withSpaceId,\n );\n\n/**\n * Per-space storage metrics.\n * @see {@link Database.stats}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const stats = () =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.stats()))).pipe(\n Effect.withSpan('Database.stats'),\n withSpaceId,\n );\n\n/**\n * Creates a `QueryResult` object that can be subscribed to.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const query: {\n <Q extends Query.Any>(query: Q): QueryResult.QueryResultEffect<Query.Type<Q>, never, Service>;\n <F extends Filter.Any>(filter: F): QueryResult.QueryResultEffect<Filter.Type<F>, never, Service>;\n} = (queryOrFilter: Query.Any | Filter.Any) =>\n Service.pipe(\n Effect.map(({ db }) => db.query(queryOrFilter as any) as QueryResult.QueryResult<any>),\n Effect.withSpan('Database.query'),\n withSpaceId,\n queryInternal.makeQueryResultEffect,\n );\n\n/**\n * Sync state of the database in relation to EDGE.\n */\nexport interface SyncState {\n //\n // Automerge\n //\n\n /**\n * Total number of documents locally.\n */\n readonly localDocumentCount: number;\n /**\n * Total number of documents on the remote peer.\n */\n readonly remoteDocumentCount: number;\n /**\n * Total number of documents across this peer and the remote peer.\n */\n readonly totalDocumentCount: number;\n /**\n * Total number of documents that are not synced.\n * Includes documents that are present only locally, only on the remote peer, or whether the peers have different versions.\n */\n readonly unsyncedDocumentCount: number;\n\n //\n // Feeds.\n //\n\n /**\n * Blocks still to pull from remote. 0 when caught up.\n */\n readonly blocksToPull: string;\n /**\n * Unpositioned blocks still to push to remote. 0 when caught up.\n */\n readonly blocksToPush: string;\n /**\n * Total blocks stored locally for this namespace in the space.\n */\n readonly totalBlocks: string;\n}\n\n/**\n * Per-space storage metrics returned by {@link Database.stats}.\n */\nexport interface DatabaseStats {\n readonly objects: {\n /** Live (non-deleted) objects across the root and all linked documents. */\n readonly alive: number;\n /** Soft-deleted objects not yet reclaimed by garbage collection. */\n readonly deleted: number;\n };\n /** Automerge documents owned by the space (root + linked + branch documents). */\n readonly documents: number;\n /** Feeds registered for the space. */\n readonly feeds: number;\n /** Total feed blocks stored locally for the space. */\n readonly feedBlocks: number;\n /**\n * What is resident in memory right now, as opposed to the stored counts above. Split by realm\n * because the client and the host cache independently — a client-side working set that is never\n * released reads as nothing at all in the host's numbers, and vice versa.\n */\n readonly loaded: {\n readonly client: ClientLoadedStats;\n readonly host: HostLoadedStats;\n };\n}\n\n/**\n * Client-side residency. Space-scoped except where noted.\n */\nexport interface ClientLoadedStats {\n /** Document handles held by this space's repo proxy. */\n readonly documents: number;\n /** Object cores held by this space's entity manager. */\n readonly objects: number;\n /** Feed handles cached by this database. */\n readonly feeds: number;\n /** Objects resident across those feed handles — the feeds' working set, not what is stored. */\n readonly feedObjects: number;\n /** Entities in the runtime registry (types and other static entities), across the whole client. */\n readonly registryTotal: number;\n}\n\n/**\n * Host-side residency. A document on disk costs nothing until a handle for it is cached.\n */\nexport interface HostLoadedStats {\n /** Automerge handles cached for this space. */\n readonly documents: number;\n /** Automerge handles cached across every space on this host. */\n readonly documentsTotal: number;\n /** Active reactive queries registered with the host, across every space. */\n readonly queriesTotal: number;\n /** Documents something on the host is using right now, across every space; the rest of `documentsTotal` is idle cache. */\n readonly leases: number;\n}\n\n/**\n * Options for {@link Database.runGarbageCollection}.\n */\nexport interface GarbageCollectionOptions {\n /**\n * Also delete stale index rows for reclaimed documents/objects.\n * @default true\n */\n readonly index?: boolean;\n /**\n * Reserved for feed-block purge (positioned deletion markers). Not yet effective on the local\n * host — see the feed-purge deferral in `@dxos/echo-host` garbage-collection design notes.\n * @default true\n */\n readonly feeds?: boolean;\n}\n\n/**\n * Report of what {@link Database.runGarbageCollection} reclaimed.\n */\nexport interface GarbageCollectionReport {\n /** Soft-deleted objects unlinked from the space directory. */\n readonly unlinkedObjects: number;\n /** Automerge documents wiped from storage (chunks + heads). */\n readonly removedDocuments: number;\n /** Index rows deleted. */\n readonly removedIndexEntries: number;\n /** Feed blocks purged. */\n readonly purgedFeedBlocks: number;\n}\n\n/**\n * Options for reading combined sync state.\n */\nexport interface GetSyncStateOptions {\n /**\n * Peer to report the automerge document backlog against. Defaults to the EDGE peer.\n * Provide explicitly in local/test topologies where there is no EDGE peer.\n */\n readonly peerId?: string;\n}\n\n/**\n * Get the current sync state.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const getSyncState = (options?: GetSyncStateOptions): Effect.Effect<SyncState, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.getSyncState(options))));\n\n/**\n * Subscribe to sync state changes.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const subscribeToSyncState = (options?: GetSyncStateOptions): Stream.Stream<SyncState, never, Service> =>\n Stream.callback<SyncState, never, Service>((queue) =>\n Effect.gen(function* () {\n const { db } = yield* Service;\n const cleanup = db.subscribeToSyncState((state) => Queue.offerUnsafe(queue, state), options);\n yield* Effect.addFinalizer(() => Effect.sync(cleanup));\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,gBAAgB;;;;AAK7B,IAAa,uBAAuB;;;;AAKpC,IAAa,YAAY,OAAO,IAAI,gBAAgB;;;;AAKpD,IAAa,eAAe;;;;AAK5B,IAAa,kBAAkB,OAAO,IAAI,oBAAoB;;;;AAK9D,IAAa,kBAAiC,OAAO,IAAI,oBAAoB;;;;AAK7E,IAAa,mBAAmB,OAAO,IAAI,qBAAqB;;;;;AAMhE,IAAa,iBAAiB,OAAO,IAAI,mBAAmB;;;;AAK5D,IAAa,uBAAuB;;;;AAKpC,IAAa,mBAAkC,OAAO,IAAI,2BAA2B;;;;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AAS,wBAAwB,GACxC,WACF;;;;;;;AAQF,IAAa,cACX,QAAQ,KAAK,OAAO,SAAS,EAAE,SAAS,OAAO,cAAc,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,KACzE,OAAO,SAAS,gBAAgB,GAChC,WACF;;;;;;AAOF,IAAa,SAGR,kBACH,QAAQ,KACN,OAAO,KAAK,EAAE,SAAS,GAAG,MAAM,aAAoB,CAAiC,GACrF,OAAO,SAAS,gBAAgB,GAChC,aACAC,qBACF;;;;;;AAsJF,IAAa,gBAAgB,YAC3B,QAAQ,KAAK,OAAO,SAAS,EAAE,SAAS,OAAO,cAAc,GAAG,aAAa,OAAO,CAAC,CAAC,CAAC;;;;;;AAOzF,IAAa,wBAAwB,YACnC,OAAO,UAAqC,UAC1C,OAAO,IAAI,aAAa;CACtB,MAAM,EAAE,OAAO,OAAO;CACtB,MAAM,UAAU,GAAG,sBAAsB,UAAU,MAAM,YAAY,OAAO,KAAK,GAAG,OAAO;CAC3F,OAAO,OAAO,mBAAmB,OAAO,KAAK,OAAO,CAAC;AACvD,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"chunk-Database.mjs","names":["TypeId","__dxlog_file","TypeId","__dxlog_file","__dxlog_file","getUriFromEntity","TypeId","Error.EntityNotFoundError","Error.MigrationError","queryInternal.makeQueryResultEffect"],"sources":["../../src/internal/common/types/model-symbols.ts","../../src/internal/common/types/typename.ts","../../src/internal/Annotation/annotations.ts","../../src/internal/common/proxy/define-hidden-property.ts","../../src/internal/Entity/util.ts","../../src/internal/Entity/api.ts","../../src/internal/Entity/type-uri.ts","../../src/internal/Query/query-result-effect.ts","../../src/Database.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// TODO(rename): These internal entity-wide symbols/types still use the `Object*` prefix but apply\n// to all entities (objects AND relations). Rename to `Entity*` in a follow-up pass (deferred from the\n// EchoURI→EID / ObjectId→EntityId / ObjectMeta→EntityMeta rename, which covered only public SDK API):\n// ObjectCore, ObjectInternals, ObjectVersion, ObjectVersionId, ObjectDeletedId, ObjectDatabaseId,\n// ObjectLoader, ObjectDocumentLoaded, ObjectUnavailable.\n// (ObjectMigration / ObjectMigrationContext intentionally excluded — object-only, not entity-wide.)\n\n/**\n * Internal symbol/string constants for the echo object model.\n * Defined in common/ so proxy/ can use them without importing from Entity/.\n * Entity/ re-exports these for external consumers.\n */\n\n/**\n * Property name for the object's own URI when serialized to JSON.\n */\nexport const ATTR_SELF_URI = '@uri';\n\n/**\n * @deprecated Legacy JSON property name accepted on read for backward compat.\n */\nexport const ATTR_SELF_URI_LEGACY = '@dxn';\n\n/**\n * Symbol carrying the object's own URI on live entities.\n */\nexport const SelfURIId = Symbol.for('@dxos/echo/URI');\n\n/**\n * Property name for deleted when object is serialized to JSON.\n */\nexport const ATTR_DELETED = '@deleted';\n\n/**\n * Deletion marker.\n */\nexport const ObjectDeletedId = Symbol.for('@dxos/echo/Deleted');\n\n/**\n * Object version accessor symbol.\n */\nexport const ObjectVersionId: unique symbol = Symbol.for('@dxos/echo/Version');\n\n/**\n * Object database accessor symbol.\n */\nexport const ObjectDatabaseId = Symbol.for('@dxos/echo/Database');\n\n/**\n * Hidden, non-reactive feed block keys of a live feed object this client wrote: what a read of its\n * latest block would stamp in `@meta.keys`, set when the store confirms the write. Read via the `Feed`\n * block getters, which prefer it to `@meta.keys`.\n */\nexport const FeedBlockKeysId = Symbol.for('@dxos/echo/FeedBlockKeys');\n\n/**\n * Branch accessor symbol. Resolves to the branch name this object instance is bound to (`'main'` for\n * the canonical object, or the branch of a `db.branch()` independent instance). Read via `Obj.getBranch`.\n */\nexport const ObjectBranchId = Symbol.for('@dxos/echo/Branch');\n\n/**\n * Property name for relation source when object is serialized to JSON.\n */\nexport const ATTR_RELATION_SOURCE = '@relationSource';\n\n/**\n * Used to access relation source ref on live ECHO objects.\n */\nexport const RelationSourceId: unique symbol = Symbol.for('@dxos/echo/RelationSource');\n\n/**\n * Used to access relation source DXN on live ECHO objects.\n */\nexport const RelationSourceDXNId: unique symbol = Symbol.for('@dxos/echo/RelationSourceDXN');\n\n/**\n * Property name for relation target when object is serialized to JSON.\n */\nexport const ATTR_RELATION_TARGET = '@relationTarget';\n\n/**\n * Used to access relation target ref on live ECHO objects.\n */\nexport const RelationTargetId: unique symbol = Symbol.for('@dxos/echo/RelationTarget');\n\n/**\n * Used to access relation target DXN on live ECHO objects.\n */\nexport const RelationTargetDXNId: unique symbol = Symbol.for('@dxos/echo/RelationTargetDXN');\n\n/**\n * Symbol carrying the entity metadata (EntityMeta) on live ECHO entities.\n * Must be importable by both meta.ts (which depends on the Ref schema) and\n * Entity/api.ts (which is transitively imported by the Ref schema), so it\n * cannot live in either of those files without creating an import cycle.\n */\nexport const MetaId = Symbol.for('@dxos/echo/Meta');\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport type * as SchemaAST from '@dxos/effect/SchemaAST';\n\n/**\n * Property name for typename when object is serialized to JSON.\n */\nexport const ATTR_TYPE = '@type';\n\n/**\n * DXN to the object type.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Type');\n\n/**\n * Reference to the object schema.\n */\nexport const SchemaId = Symbol.for('@dxos/echo/Schema');\n\n/**\n * The schema AST a nested value of a typed object follows, carried instead of a schema of its own.\n * @internal\n */\nexport const SchemaAstId = Symbol.for('@dxos/echo/SchemaAst');\n\n/**\n * Property name for parent when object is serialized to JSON.\n */\nexport const ATTR_PARENT = '@parent';\n\n/**\n * Reference to the object parent.\n */\nexport const ParentId = Symbol.for('@dxos/echo/Parent');\n\n/**\n * Reference to the object's type entity (`Type.Obj`, `Type.Relation`, or\n * `Type.Type`). Set at instance creation by `createObject` / `makeObject`\n * when the entity is known. Public read-back via `Obj.getType` / `Relation.getType`\n * / `Entity.getType`.\n */\nexport const TypeEntityId = Symbol.for('@dxos/echo/TypeEntity');\n\n/**\n * Returns the Effect Schema for the given object if one is defined.\n *\n * @internal\n * Internal callers needing schema-side validation read from `SchemaId`.\n * Public callers should use `Type.getSchema(Obj.getType(obj))` instead.\n */\n// TODO(dmaretskyi): For echo objects, this always returns the root schema.\nexport const getSchema = (obj: unknown | undefined): Schema.Codec<any, any> | undefined => {\n if (obj) {\n const ast: SchemaAST.AST | undefined = (obj as any)[SchemaAstId];\n return ast ? Schema.make(ast) : (obj as any)[SchemaId];\n }\n};\n\n/**\n * @internal\n */\nexport const setSchema = (obj: any, schema: Schema.Codec<any, any>): void => {\n Object.defineProperty(obj, SchemaId, {\n value: schema,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n};\n\n/**\n * Returns the type entity (`Type.AnyEntity`) for the given instance.\n * Set at instance creation; every entity has a type. Defensive: returns\n * undefined for null/undefined input so callers can safely probe arbitrary\n * values via this helper.\n *\n * @internal Re-exported via `Obj.getType` / `Relation.getType` / `Entity.getType`.\n */\nexport const getType = (obj: unknown): unknown => {\n if (obj == null) {\n return undefined;\n }\n return (obj as any)[TypeEntityId];\n};\n\n/**\n * @internal\n */\nexport const setType = (obj: any, type: unknown): void => {\n Object.defineProperty(obj, TypeEntityId, {\n value: type,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaTransformation from 'effect/SchemaTransformation';\nimport * as Struct from 'effect/Struct';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, URI } from '@dxos/keys';\nimport { type Primitive } from '@dxos/util';\n\nimport type * as Annotation from '../../Annotation.ts';\nimport { type Mutable } from '../common/proxy/index.ts';\nimport { type AnyProperties, EntityKind, TypeId, getSchema } from '../common/types/index.ts';\nimport { createAnnotationHelper } from './util.ts';\n\nconst ANNOTATION_TYPE_ID: Annotation.TypeId = '~@dxos/echo/Annotation' as const;\n\n/**\n * @internal\n */\nexport const FIELD_PATH_ANNOTATION = 'path';\n\n/**\n * Sets the path for the field.\n * @param path Data source path in the json path format. This is the field path in the source object.\n */\n// TODO(burdon): Field, vs. path vs. property.\nexport const FieldPath = (path: string) => PropertyMeta(FIELD_PATH_ANNOTATION, path);\n\n//\n// Type\n//\n\n/**\n * ECHO identifier (for a stored schema).\n * Must be an `echo:` URI.\n */\nexport const TypeIdentifierAnnotationId = '~@dxos/schema/annotation/TypeIdentifier';\n\nexport const getTypeIdentifierAnnotation = (schema: Schema.Top): string | undefined =>\n SchemaAST.getAnnotation<string>(schema.ast, TypeIdentifierAnnotationId);\n\n/**\n * @returns The schema's type identifier URI — whichever URI fits.\n *\n * - Stored (dynamic) schemas: the schema-as-object's EID, so loaded objects ride\n * along with their schema as a strong dependency.\n * - Non-stored (static) schemas: the typename DXN built from `TypeAnnotation`.\n *\n * This URI is what gets written to an object's `system.type`; queries that filter by\n * type also use it (see `Filter.type` / `getTypeURIFromSpecifier`), so both sides\n * stay symmetric without per-schema branching.\n */\nexport const getSchemaURI = (schema: Schema.Top): URI.URI | undefined => {\n assertArgument(Schema.isSchema(schema), 'schema', 'invalid schema');\n const id = getTypeIdentifierAnnotation(schema);\n if (id) {\n return URI.make(id);\n }\n const objectAnnotation = getTypeAnnotation(schema);\n if (objectAnnotation) {\n return DXN.make(objectAnnotation.typename, objectAnnotation.version);\n }\n return undefined;\n};\n\n//\n// TypeAnnotation\n//\n\n/**\n * Fully qualified globally unique typename.\n * Example: `org.dxos.type.message`\n */\n// TODO(wittjosiah): Factor out to DXN spec.\nexport const TypenameSchema = Schema.String.pipe(\n Schema.check(\n Schema.isPattern(\n /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)$/u,\n ),\n ),\n).annotate({\n description: 'Fully qualified globally unique typename in reverse-DNS form.',\n example: 'org.dxos.type.message',\n});\n\n/**\n * Semantic version format: `major.minor.patch`\n * Example: `1.0.0`\n */\nexport const VersionSchema = Schema.String.pipe(Schema.check(Schema.isPattern(/^\\d+.\\d+.\\d+$/u))).annotate({\n description: 'Semantic version format: `major.minor.patch`',\n example: '1.0.0',\n});\n\nexport const TypeMeta = Schema.Struct({\n typename: TypenameSchema,\n version: VersionSchema,\n});\n\nexport interface TypeMeta extends Schema.Schema.Type<typeof TypeMeta> {}\n\n/**\n * Entity type.\n */\nexport const TypeAnnotationId = '~@dxos/schema/annotation/Type';\n\n/**\n * Payload stored under {@link TypeAnnotationId}.\n */\nexport const TypeAnnotation = TypeMeta.mapFields(\n Struct.assign({\n kind: Schema.Enum(EntityKind),\n\n /**\n * If this is a relation, the schema of the source object.\n * Must be present if entity kind is {@link EntityKind.Relation}.\n */\n sourceSchema: Schema.optional(DXN.Schema),\n\n /**\n * If this is a relation, the schema of the target object.\n * Must be present if entity kind is {@link EntityKind.Relation}.\n */\n targetSchema: Schema.optional(DXN.Schema),\n }),\n);\n\nexport interface TypeAnnotation extends Schema.Schema.Type<typeof TypeAnnotation> {}\n\n/**\n * @returns {@link TypeAnnotation} from a schema.\n * Schema must have been created with {@link TypedObject} or {@link TypedLink} or manually assigned an appropriate annotation.\n */\nexport const getTypeAnnotation = (schema: Schema.Top): TypeAnnotation | undefined => {\n assertArgument(schema != null && schema.ast != null, 'schema', 'invalid schema');\n return SchemaAST.getAnnotation<TypeAnnotation>(schema.ast, TypeAnnotationId);\n};\n\n/**\n * @returns {@link EntityKind} from a schema.\n */\nexport const getEntityKind = (schema: Schema.Top): EntityKind | undefined => getTypeAnnotation(schema)?.kind;\n\n/**\n * @internal\n * @returns Schema typename (without dxn: prefix or version number).\n */\nexport const getSchemaTypename = (schema: Schema.Top): string | undefined => getTypeAnnotation(schema)?.typename;\n\n/**\n * @internal\n * @returns Schema version in semver format.\n */\nexport const getSchemaVersion = (schema: Schema.Top): string | undefined => getTypeAnnotation(schema)?.version;\n\n/**\n * Gets the typename of the object without the version.\n * Returns only the name portion, not the DXN.\n * @example \"com.example.type.contact\"\n *\n * @internal (use Obj.getTypename)\n */\nexport const getTypename = (obj: AnyProperties): string | undefined => {\n const schema = getSchema(obj);\n if (schema != null) {\n // Try to extract typename from DXN.\n return getSchemaTypename(schema);\n } else {\n // `obj` may be an arbitrary value (e.g. from `isInstanceOf`); read TypeId\n // directly so we return undefined for non-entities instead of throwing.\n const type = (obj as any)?.[TypeId];\n // Parse the URI string to extract typename.\n if (DXN.isDXN(type)) {\n const parsed = DXN.tryMake(type);\n return parsed && DXN.getName(parsed);\n }\n return undefined;\n }\n};\n\n/**\n * @internal (use Type.setTypename)\n */\n// TODO(dmaretskyi): Rename setTypeDXN.\nexport const setTypename = (obj: any, typename: URI.URI): void => {\n assertArgument(typeof typename === 'string', 'typename', 'Invalid type.');\n Object.defineProperty(obj, TypeId, {\n value: typename,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n};\n\n/**\n * @returns Object type URI — either a typename {@link DXN} or an `echo:` reference to a stored Schema object.\n * @returns undefined if the object has no registered type URI (e.g. unresolved query result).\n * @example `dxn:com.example.type.person:1.0.0`\n * @example Stored schema: `echo:///01KKKG2FHWCMTR0BY00GJSVT1X`.\n *\n * @internal (use Obj.getTypeURI)\n */\nexport const getTypeURI = (obj: AnyProperties): URI.URI | undefined => {\n if (obj == null) {\n return undefined;\n }\n const type = (obj as any)[TypeId];\n if (type == null) {\n return undefined;\n }\n invariant(URI.isURI(type), 'Invalid object.');\n return type;\n};\n\n//\n// PropertyMeta\n//\n\n/**\n * PropertyMeta (metadata for dynamic schema properties).\n * For user-defined annotations.\n */\nexport const PropertyMetaAnnotationId = '@dxos/schema/annotation/PropertyMeta';\n\nexport type PropertyMetaValue = Primitive | Record<string, Primitive> | Primitive[];\n\nexport type PropertyMetaAnnotation = {\n [name: string]: PropertyMetaValue;\n};\n\n// TODO(wittjosiah): Align with other annotations.\n// TODO(wittjosiah): Why is this separate from FormatAnnotation?\n/**\n * Apply property-level metadata to an Effect schema. Only accepts\n * `Schema.Top` — apply BEFORE wrapping the schema with\n * `Type.makeObject` / `Type.makeRelation`. To read property meta off a\n * `Type.Type` entity, unwrap it first with `Type.getSchema(entity)`.\n */\nexport const PropertyMeta = (name: string, value: PropertyMetaValue) => {\n return <A, I, R>(self: Schema.Codec<A, I, R>): Schema.Codec<A, I, R> => {\n const existingMeta = SchemaAST.getAnnotation<PropertyMetaAnnotation>(self.ast, PropertyMetaAnnotationId);\n return self.annotate({\n [PropertyMetaAnnotationId]: {\n ...existingMeta,\n [name]: value,\n },\n });\n };\n};\n\n/**\n * Reads one property-meta entry off a property. An optional property's type is a union of the\n * annotated schema and `undefined`, whose own annotations are empty, so the members are read too.\n */\nexport const getPropertyMetaAnnotation = <T>(prop: SchemaAST.PropertySignature, name: string): T | undefined => {\n const candidates = SchemaAST.isUnion(prop.type) ? [prop.type, ...prop.type.types] : [prop.type];\n for (const ast of candidates) {\n const value = SchemaAST.getAnnotation<PropertyMetaAnnotation>(ast, PropertyMetaAnnotationId)?.[name];\n if (value !== undefined) {\n return value as T;\n }\n }\n return undefined;\n};\n\n//\n// Reference\n//\n\n/**\n * Schema reference.\n */\nexport const ReferenceAnnotationId = '@dxos/schema/annotation/Reference';\nexport type ReferenceAnnotationValue = TypeAnnotation;\nexport const ReferenceAnnotation = createAnnotationHelper<ReferenceAnnotationValue>(ReferenceAnnotationId);\n\n/**\n * SchemaMeta.\n */\nexport const SchemaMetaSymbol = Symbol.for('@dxos/schema/SchemaMeta');\nexport type SchemaMeta = TypeMeta & { id: string };\n\n/**\n * Identifies label property or JSON path expression.\n * Either a string or an array of strings representing field accessors each matched in priority order.\n */\nexport const LabelAnnotationId = '@dxos/schema/annotation/Label';\nexport const LabelAnnotation = createAnnotationHelper<string[]>(LabelAnnotationId);\n\n/**\n * Returns the label for a given object based on {@link LabelAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n * Skips empty strings and whitespace-only strings, continuing to the next field.\n */\n// TODO(burdon): Convert to SchemaEx.JsonPath?\nexport const getLabelWithSchema = <S extends Schema.Top>(\n schema: S,\n object: Schema.Schema.Type<S>,\n): string | undefined => {\n const annotation = LabelAnnotation.get(schema).pipe(Option.getOrElse(() => ['name']));\n for (const accessor of annotation) {\n assertArgument(\n typeof accessor === 'string',\n 'accessor',\n 'Label annotation must be a string or an array of strings',\n );\n const value = SchemaEx.getField(object, accessor as SchemaEx.JsonPath);\n switch (typeof value) {\n case 'string': {\n const trimmed = value.trim();\n if (trimmed.length > 0) {\n return value;\n }\n continue;\n }\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n return value.toString();\n case 'undefined':\n case 'object':\n case 'function':\n continue;\n }\n }\n\n return undefined;\n};\n\n/**\n * Sets the label for a given object based on {@link LabelAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\n// `object` is not typed by the schema: the annotation names the property at runtime, and TypeScript\n// cannot index-write a generic type parameter.\nexport const setLabelWithSchema = (schema: Schema.Top, object: AnyProperties, label: string) => {\n const annotation = LabelAnnotation.get(schema).pipe(\n Option.map((field) => field[0]),\n Option.getOrElse(() => 'name'),\n );\n object[annotation] = label;\n};\n\n/**\n * Identifies description property or JSON path expression.\n * A string representing field accessor.\n */\nexport const DescriptionAnnotationId = '@dxos/schema/annotation/Description';\nexport const DescriptionAnnotation = createAnnotationHelper<string>(DescriptionAnnotationId);\n\n/**\n * Returns the description for a given object based on {@link DescriptionAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\n// TODO(burdon): Convert to SchemaEx.JsonPath?\nexport const getDescriptionWithSchema = <S extends Schema.Top>(\n schema: S,\n object: Schema.Schema.Type<S>,\n): string | undefined => {\n const accessor = DescriptionAnnotation.get(schema).pipe(Option.getOrElse(() => 'description'));\n assertArgument(typeof accessor === 'string', 'accessor', 'Description annotation must be a string');\n const value = SchemaEx.getField(object, accessor as SchemaEx.JsonPath);\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n return value.toString();\n case 'undefined':\n case 'object':\n case 'function':\n default:\n return undefined;\n }\n};\n\n/**\n * Sets the description for a given object based on {@link DescriptionAnnotationId}.\n * Lower-level version that requires explicit schema parameter.\n */\nexport const setDescriptionWithSchema = (schema: Schema.Top, object: AnyProperties, description: string) => {\n const accessorOpt = DescriptionAnnotation.get(schema);\n if (Option.isNone(accessorOpt)) {\n return;\n }\n object[accessorOpt.value] = description;\n};\n\n/**\n * Identifies if a property should be included in a form or not.\n * By default, all properties are included in forms, so this is opt-out.\n */\nexport const FormInputAnnotationId = '@dxos/schema/annotation/FormInput';\nexport const FormInputAnnotation = createAnnotationHelper<boolean>(FormInputAnnotationId);\n\n/**\n * When set on a `Ref` property, the form renders the referenced object's own\n * fields inline (a nested form bound to the target) instead of a picker.\n */\nexport const FormInlineAnnotationId = '@dxos/schema/annotation/FormInline';\nexport const FormInlineAnnotation = createAnnotationHelper<boolean>(FormInlineAnnotationId);\n\n/**\n * When set on a `Ref` (or array-of-`Ref`) property, the form OWNS the referenced target(s): \"add\" creates a\n * new object of the annotation's typename (instead of opening the existing-object picker) and each target is\n * rendered inline — its own fields — like {@link FormInlineAnnotation}. The target typename is carried here\n * (rather than inferred from the element type) so the field can stay `Ref.Ref(Obj.Unknown)` and avoid pulling\n * the target's type (e.g. query-AST-laden `Trigger`) into the schema's emitted declaration.\n */\nexport const FormCreateAnnotationId = '@dxos/schema/annotation/FormCreate';\nexport const FormCreateAnnotation = createAnnotationHelper<string>(FormCreateAnnotationId);\n\n/**\n * When set on an array property, the form renders it as an ordered,\n * drag-to-reorder list (drag handles per row). Element order is meaningful and\n * user-controllable; reordering rewrites the array.\n */\nexport const FormOrderedAnnotationId = '@dxos/schema/annotation/FormOrdered';\nexport const FormOrderedAnnotation = createAnnotationHelper<boolean>(FormOrderedAnnotationId);\n\n/**\n * How a form presents an array of references, or (`tag` only) of the values its element's `OptionsLookup` offers. The\n * two options are independent.\n */\nexport type ArrayPresentation = {\n /** Rows (or chips) reorder by drag and keyboard, and the order is persisted; `false` by default. */\n ordered?: boolean;\n /**\n * `tag`: removable chips in the targets' hues (the default for arrays of `Tag` refs). `title`: a row per target with\n * its type's icon, its label and an optional description (the default otherwise).\n */\n display?: 'tag' | 'title';\n /** A property of the target whose value is the `title` row's description line. */\n description?: string;\n};\n\n/**\n * When set on an array-of-`Ref` property, sets how the form presents it ({@link ArrayPresentation}).\n */\nexport const ArrayPresentationAnnotationId = '@dxos/schema/annotation/ArrayPresentation';\nexport const ArrayPresentationAnnotation = createAnnotationHelper<ArrayPresentation>(ArrayPresentationAnnotationId);\n\n/**\n * Annotation carrying one or more named layout DSL templates that control how a\n * form arranges a schema's fields (consumed by `@dxos/react-ui-form`'s\n * `Form.Layout` / `Form.FieldSet`). Callers select a variant by name; the\n * implicit name is `DEFAULT_LAYOUT_NAME` (`'default'`).\n *\n * Templates use a minimal XML grammar. Example:\n *\n * FormLayoutAnnotation.set({\n * default: `\n * <grid cols=\"2\">\n * <field name=\"origin\"/>\n * <field name=\"destination\"/>\n * <field name=\"provider\" span=\"2\"/>\n * </grid>\n * `,\n * card: `\n * <grid cols=\"1\">\n * <field name=\"provider\"/>\n * <field name=\"number\"/>\n * </grid>\n * `,\n * })\n */\nexport const FormLayoutAnnotationId = '@dxos/react-ui-form/annotation/Layout';\n\nexport type FormLayoutMap = Record<string, string>;\n\nexport const FormLayoutAnnotation = createAnnotationHelper<FormLayoutMap>(FormLayoutAnnotationId);\n\n/** Name used when no explicit form-layout variant is requested. */\nexport const DEFAULT_LAYOUT_NAME = 'default';\n\n/**\n * Default field to be used on referenced schema to lookup the value.\n */\nexport const FieldLookupAnnotationId = '@dxos/schema/annotation/FieldLookup';\n\n/**\n * Generate test data.\n */\nexport const GeneratorAnnotationId = '@dxos/schema/annotation/Generator';\n\nexport type GeneratorAnnotationValue =\n | string\n | {\n generator: string;\n args?: any[];\n probability?: number;\n };\n\nexport const GeneratorAnnotation = createAnnotationHelper<GeneratorAnnotationValue>(GeneratorAnnotationId);\n\nexport const RawStringAnnotationId = 'org.dxos.annotation.rawString';\n\n/**\n * Stores every string under the annotated field as an immutable Automerge string: one op per write\n * instead of one per character, at the cost of collaborative (character-level) merging. For\n * machine-written state that is replaced wholesale, never edited as text.\n */\nexport const RawStringAnnotation = createAnnotationHelper<boolean>(RawStringAnnotationId);\n\n/** True when `ast` (or, for an optional field, one of its union members) carries {@link RawStringAnnotation}. */\nexport const hasRawStringAnnotation = (ast: SchemaAST.AST): boolean =>\n RawStringAnnotation.getFromAst(ast).pipe(Option.getOrElse(() => false)) ||\n (SchemaAST.isUnion(ast) && ast.types.some(hasRawStringAnnotation));\n\nconst containsRawStringCache = new WeakMap<SchemaAST.AST, boolean>();\n\n/**\n * True when {@link RawStringAnnotation} appears anywhere within `ast`; cached, so a write to a type that\n * never uses it skips the per-value schema walk.\n */\nexport const containsRawStringAnnotation = (ast: SchemaAST.AST): boolean => {\n const cached = containsRawStringCache.get(ast);\n if (cached !== undefined) {\n return cached;\n }\n // Seeded before descending so a recursive (suspended) schema terminates.\n containsRawStringCache.set(ast, false);\n const children: readonly SchemaAST.AST[] = SchemaAST.isObjects(ast)\n ? [...ast.propertySignatures.map((property) => property.type), ...ast.indexSignatures.map((index) => index.type)]\n : SchemaAST.isArrays(ast)\n ? [...ast.elements, ...ast.rest]\n : SchemaAST.isUnion(ast)\n ? ast.types\n : SchemaAST.isSuspend(ast)\n ? [ast.thunk()]\n : [];\n const result = hasRawStringAnnotation(ast) || children.some(containsRawStringAnnotation);\n containsRawStringCache.set(ast, result);\n return result;\n};\n\ninterface MakeAnnoationsProps<T> {\n id: string;\n schema: Schema.Codec<T, any, never>;\n /** Skips the FQN format check on `id`, for a pre-existing id that may already be embedded in persisted schemas. */\n legacyId?: boolean;\n}\n\n// Annotation ids use the same NSID / reverse-DNS format as TypenameSchema —\n// dot-separated segments, middle segments may be hyphenated, final segment may be camelCase.\n// At least 3 segments are required (e.g. org.dxos.annotation.example).\nexport const makeUserAnnotation = <T>(props: MakeAnnoationsProps<T>): Annotation.Annotation<T> => {\n if (!props.legacyId) {\n assertArgument(\n /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?){2,}(\\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)?$/.test(\n props.id,\n ),\n 'id',\n 'Annotation id must be in the FQN format (org.dxos.annotation.example or org.dxos.space.rootCollection). Pass `legacyId: true` to keep an existing non-FQN id.',\n );\n }\n\n const annotation: Annotation.Annotation<T> = {\n [ANNOTATION_TYPE_ID]: { _Type: {} as T },\n key: props.id as Annotation.Key,\n schema: props.schema,\n get: (schema) => getFromAst(schema.ast, annotation),\n getFromAst: (ast) => getFromAst(ast, annotation),\n set: (value) =>\n PropertyMeta(props.id, Schema.encodeSync(props.schema)(value)) as <S extends Schema.Top>(schema: S) => S,\n };\n\n return annotation;\n};\n\nconst IconAnnotationSchema = Schema.Struct({\n /**\n * Sprite icon name (e.g., 'ph--user--regular', 'ph--cube--regular', 'px--anthropic--regular').\n *\n * `ph--*` is Phosphor; `px--*` and `dx--*` are brand glyphs, which are sprite-only and carry no\n * weight variants. All three are admitted because a type whose subject IS a brand — an Anthropic\n * session, a GitHub repo — has no honest Phosphor equivalent.\n */\n icon: Schema.String.pipe(Schema.check(Schema.isPattern(/^(ph|px|dx)--[a-z0-9-]+--[a-z]+$/u))),\n\n /**\n * Color name.\n *\n * List of colors:\n * - 'red'\n * - 'orange'\n * - 'amber'\n * - 'yellow'\n * - 'lime'\n * - 'green'\n * - 'emerald'\n * - 'teal'\n * - 'cyan'\n * - 'violet'\n * - 'purple'\n * - 'fuchsia'\n * - 'pink'\n * - 'rose'\n */\n hue: Schema.optional(Schema.String),\n});\n\nexport interface IconAnnotation extends Schema.Schema.Type<typeof IconAnnotationSchema> {}\n\n/**\n * Icon to render in the UI.\n */\nexport const IconAnnotation = makeUserAnnotation<IconAnnotation>({\n id: 'org.dxos.annotation.icon',\n schema: IconAnnotationSchema,\n});\n\n/**\n * Indicates that this entity's icon should be resolved from a property whose value is a `Ref`\n * to another entity. Consumers (e.g. graph node builders) resolve the ref target and use that\n * target's schema `IconAnnotation` in place of the static one declared on this schema.\n *\n * Useful for wrapper schemas that delegate their visual identity to a referenced sub-entity\n * (e.g. a generic `Game` whose icon should come from its `variant` ref's typed state).\n */\nexport const IconFromRefAnnotation = makeUserAnnotation<string>({\n id: 'org.dxos.annotation.icon.from-ref',\n schema: Schema.String,\n});\n\n/** Value of {@link SetParentAnnotation}. */\nexport type SetParentAnnotationValue = {\n /** Whether the field owns its targets at all. */\n readonly value: boolean;\n /** Whether a write takes a target that already has a parent. */\n readonly override: boolean;\n};\n\n/**\n * Marks a `Ref` field (or an array-of-`Ref` field) as owning its targets: writing a ref into the\n * field, or creating the holder with one, sets the target's parent to the holding object.\n *\n * `{ override: false }` claims only a target that has no parent, so the first field to reference an\n * object becomes its parent and later fields only reference it.\n *\n * This is NOT an invariant: it does not guarantee that a target held here has this object as its\n * parent, only that a write through this field updates the parent. Nothing stops `Obj.setParent`\n * from re-parenting the target afterwards, a ref whose target is not resolved is left alone, and\n * removing a ref does NOT clear the target's parent — a move between holders would otherwise lose\n * the edge depending on write order; call `Obj.setParent(child, undefined)` explicitly. Read the\n * parent with `Obj.getParent`; never infer it from the field.\n *\n * @example\n * ```ts\n * Schema.Struct({\n * body: Ref.Ref(Text.Text).pipe(Annotation.SetParent.set()),\n * objects: Schema.Array(Ref.Ref(Obj.Unknown)).pipe(Annotation.SetParent.set({ override: false })),\n * })\n * ```\n */\nconst SetParentValueSchema = Schema.Struct({ value: Schema.Boolean, override: Schema.Boolean });\n\nconst setParentAnnotation = makeUserAnnotation<SetParentAnnotationValue>({\n id: 'org.dxos.annotation.setParent',\n // Schemas persisted before the value was structured store a bare boolean.\n schema: Schema.Union([\n SetParentValueSchema,\n Schema.Boolean.pipe(\n Schema.decodeTo(\n SetParentValueSchema,\n SchemaTransformation.transform({\n decode: (value: boolean): SetParentAnnotationValue => ({ value, override: true }),\n encode: ({ value }: SetParentAnnotationValue) => value,\n }),\n ),\n ),\n ]),\n});\n\nexport type SetParentAnnotationOptions = {\n readonly override?: boolean;\n};\n\n/** {@link setParentAnnotation}, with a `set` that owns by default. */\nexport const SetParentAnnotation: Omit<Annotation.Annotation<SetParentAnnotationValue>, 'set'> & {\n set: (options?: SetParentAnnotationOptions) => <S extends Schema.Top>(schema: S) => S;\n} = {\n ...setParentAnnotation,\n set: ({ override = true }: SetParentAnnotationOptions = {}) => setParentAnnotation.set({ value: true, override }),\n};\n\n/** Value of {@link ContentVersionAnnotation}. */\nexport type ContentVersionAnnotationValue = {\n /** Sibling fields whose format the annotated field versions. */\n readonly fields: readonly string[];\n};\n\n/**\n * Marks a string field of an object schema as the content version of named sibling fields: the\n * format and revision (e.g. `dxos.org/scene/1`) of data ECHO stores opaquely. Content migrations\n * (`Migration.defineContent`) find the version through it.\n *\n * @example\n * ```ts\n * Schema.Struct({\n * schema: Schema.String.pipe(Annotation.ContentVersionAnnotation.set({ fields: ['content'] }), Schema.optional),\n * content: Schema.Record(Schema.String, Schema.Any),\n * })\n * ```\n */\nexport const ContentVersionAnnotation = makeUserAnnotation<ContentVersionAnnotationValue>({\n id: 'org.dxos.annotation.contentVersion',\n schema: Schema.Struct({ fields: Schema.Array(Schema.String) }),\n});\n\n/** Value of {@link UserTypeAnnotation}. */\nexport type UserTypeAnnotationValue = {\n /** Keys a surface filters on (e.g. which types a collection's create dialog offers); opaque to ECHO. */\n readonly tags?: readonly string[];\n};\n\nconst userTypeAnnotation = makeUserAnnotation<UserTypeAnnotationValue>({\n id: 'org.dxos.annotation.userType',\n schema: Schema.Struct({ tags: Schema.optional(Schema.Array(Schema.String)) }),\n});\n\n/**\n * Marks a static type as user-facing, so it shows in pickers, the nav tree, and collections. Absent, the\n * type is internal (like a dotfile, visible only via an advanced setting); a new type stays out of sight\n * until someone opts it in. Stored as property meta, so it survives persisting the schema.\n *\n * @example\n * ```ts\n * Schema.Struct({ ... }).pipe(Annotation.UserType.set());\n * Schema.Struct({ ... }).pipe(Annotation.UserType.set({ tags: [Collection.ItemTag] }));\n * ```\n */\nexport const UserTypeAnnotation: Omit<Annotation.Annotation<UserTypeAnnotationValue>, 'set'> & {\n set: (value?: UserTypeAnnotationValue) => <S extends Schema.Top>(schema: S) => S;\n} = {\n ...userTypeAnnotation,\n set: (value: UserTypeAnnotationValue = {}) => userTypeAnnotation.set(value),\n};\n\n/**\n * Options for {@link getLabel}.\n */\nexport type GetLabelOptions = {\n /**\n * Strategy for deriving a label when the entity has no `LabelAnnotation` value.\n * - `'typename'`: use the entity's typename (e.g. `org.dxos.type.table`).\n * Useful for Card.Title chrome that must always display something, even\n * for unlabeled objects.\n */\n fallback?: 'typename';\n};\n\n/**\n * Get the label of an entity.\n * Accepts both reactive entities and snapshots.\n *\n * If `options.fallback === 'typename'` and no label is set, returns the\n * entity's typename instead.\n */\nexport const getLabel = (entity: AnyProperties, options?: GetLabelOptions): string | undefined => {\n const schema = getSchema(entity);\n const label = schema != null ? getLabelWithSchema(schema, entity) : undefined;\n if (label != null) {\n return label;\n }\n if (options?.fallback === 'typename') {\n return getTypename(entity);\n }\n return undefined;\n};\n\n/**\n * Set the label of an entity.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setLabel = (entity: Mutable<AnyProperties>, label: string) => {\n const schema = getSchema(entity);\n if (schema != null) {\n setLabelWithSchema(schema, entity, label);\n }\n};\n\n/**\n * Returns the primary label property key for an entity.\n * Reads the first accessor from {@link LabelAnnotation}, defaulting to 'name'.\n */\nexport const getLabelProperty = (entity: AnyProperties): string => {\n const schema = getSchema(entity);\n if (schema == null) {\n return 'name';\n }\n return LabelAnnotation.get(schema).pipe(\n Option.flatMap((fields) => Option.fromNullishOr(fields[0])),\n Option.getOrElse(() => 'name'),\n );\n};\n\n/**\n * Get the description of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const getDescription = (entity: AnyProperties): string | undefined => {\n const schema = getSchema(entity);\n if (schema != null) {\n return getDescriptionWithSchema(schema, entity);\n }\n};\n\n/**\n * Get the icon annotation for an entity, resolved via its type-level `IconAnnotation`.\n * Accepts both reactive entities and snapshots.\n *\n * Returns the full `{ icon, hue }` annotation so callers can use both the phosphor icon\n * name and the suggested colour. Callers wanting just the icon name typically write\n * `Obj.getIcon(obj)?.icon ?? 'ph--cube--regular'`.\n *\n * Note: this is the \"static\" icon from the object's own schema. It does not follow\n * `IconFromRefAnnotation` delegation — call sites needing that (e.g. app-graph node\n * builders) should resolve the ref themselves.\n */\nexport const getIcon = (entity: AnyProperties): IconAnnotation | undefined => {\n const schema = getSchema(entity);\n if (schema == null) {\n return undefined;\n }\n return Option.getOrUndefined(IconAnnotation.get(schema));\n};\n\n/**\n * Set the description of an entity.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const setDescription = (entity: Mutable<AnyProperties>, description: string) => {\n const schema = getSchema(entity);\n if (schema != null) {\n setDescriptionWithSchema(schema, entity, description);\n }\n};\n\nexport { Dictionary, Key, getDictionary, setDictionary } from './dictionary.ts';\n\nexport const getFromAst = <T>(\n ast: SchemaAST.AST,\n annotation: Pick<Annotation.Annotation<T>, 'key' | 'schema'>,\n): Option.Option<T> => {\n const meta = SchemaAST.getAnnotation<PropertyMetaAnnotation>(ast, PropertyMetaAnnotationId);\n return Option.fromNullishOr(meta?.[annotation.key]).pipe(Option.map(Schema.decodeUnknownSync(annotation.schema)));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Define a non-enumerable property on an object.\n */\nexport const defineHiddenProperty = (object: any, key: string | symbol, value: any) => {\n Object.defineProperty(object, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport { type InternalObjectProps, SelfURIId } from './model.ts';\n\n/**\n * Returns the EID of an object.\n *\n * @internal\n */\nexport const getObjectEchoUri = (object: any): EID.EID | undefined => {\n invariant(!Schema.isSchema(object), 'schema not allowed in this function');\n assertArgument(typeof object === 'object' && object != null, 'object', 'expected object');\n assumeType<InternalObjectProps>(object);\n\n if (object[SelfURIId]) {\n invariant(EID.isEID(object[SelfURIId]), 'Invalid object model: invalid self dxn');\n return EID.parse(object[SelfURIId]);\n }\n\n if (!EntityId.isValid(object.id)) {\n throw new TypeError('Object id is not valid.');\n }\n\n return EID.make({ entityId: object.id });\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ForeignKey } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, EID, type SpaceId, URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport { defineHiddenProperty } from '../common/proxy/define-hidden-property.ts';\nimport type { AnyEntity } from '../common/types/index.ts';\nimport { MetaId } from '../common/types/model-symbols.ts';\nimport { FeedBlockKeysId, type InternalObjectProps, ObjectBranchId, ObjectDatabaseId } from './model.ts';\nimport { getObjectEchoUri } from './util.ts';\n\n/**\n * Controls the URI form returned by `getUri` and the public `*.getURI` helpers.\n *\n * - `'named'` — Registry key URI (`dxn:<meta.key>`) when the entity has a key in its meta;\n * falls back to the default EID.\n * - `'absolute'` — Fully-qualified EID with space id (`echo://<spaceId>/<entityId>`);\n * falls back when no space is available.\n * - `'relative'` — Local EID without space id (`echo:/<entityId>`).\n *\n * Omitting `prefer` preserves the existing behaviour.\n */\nexport type GetURIOptions = {\n prefer?: 'named' | 'absolute' | 'relative';\n};\n\n/**\n * Get the URI of an entity.\n * Accepts both reactive entities and snapshots.\n */\nexport const getUri = (entity: AnyEntity, options?: GetURIOptions): URI.URI => {\n const prefer = options?.prefer;\n\n if (prefer === 'named') {\n const key = (entity as any)[MetaId]?.key;\n if (key) {\n return (DXN.tryMake(`dxn:${key}`) ?? URI.make(key)) as URI.URI;\n }\n const uri = getObjectEchoUri(entity);\n invariant(uri != null, 'Invalid entity.');\n return uri;\n }\n\n if (prefer === 'relative') {\n const eid = getObjectEchoUri(entity);\n invariant(eid != null, 'Invalid entity.');\n const entityId = EID.getEntityId(eid);\n return entityId ? EID.make({ entityId }) : eid;\n }\n\n if (prefer === 'absolute') {\n const eid = getObjectEchoUri(entity);\n invariant(eid != null, 'Invalid entity.');\n const entityId = EID.getEntityId(eid);\n if (!entityId) {\n return eid;\n }\n assumeType<InternalObjectProps>(entity);\n const spaceId: SpaceId | undefined = entity[ObjectDatabaseId]?.spaceId ?? EID.getSpaceId(eid);\n return spaceId ? EID.make({ spaceId, entityId }) : eid;\n }\n\n const uri = getObjectEchoUri(entity);\n invariant(uri != null, 'Invalid entity.');\n return uri;\n};\n\n/**\n * The hidden feed block keys a client stamped on a live feed object it wrote; `undefined` when the\n * object's `@meta.keys` describe its latest block.\n */\nexport const getFeedBlockKeys = (entity: AnyEntity): readonly ForeignKey[] | undefined => {\n assumeType<InternalObjectProps>(entity);\n return entity[FeedBlockKeysId];\n};\n\n/**\n * Sets, or with `undefined` clears, the hidden feed block keys of a live feed object. Not reactive:\n * the keys describe the block the store wrote, not a change of the object.\n */\nexport const setFeedBlockKeys = (entity: AnyEntity, keys: readonly ForeignKey[] | undefined): void => {\n defineHiddenProperty(entity, FeedBlockKeysId, keys);\n};\n\n/**\n * Get the database the entity belongs to.\n * Accepts both reactive entities and snapshots.\n */\nexport const getDatabase = (entity: AnyEntity): any | undefined => {\n assumeType<InternalObjectProps>(entity);\n return entity[ObjectDatabaseId];\n};\n\n/**\n * Get the branch this entity instance is bound to (`'main'` for the canonical object, or the branch\n * of a `db.branch()` independent instance). Reads the branch off the instance, so two instances of the\n * same object id on different branches report their own branch.\n */\nexport const getBranch = (entity: AnyEntity): string => {\n assumeType<InternalObjectProps>(entity);\n return entity[ObjectBranchId] ?? 'main';\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport { assertArgument } from '@dxos/invariant';\nimport { DXN, EID, URI } from '@dxos/keys';\n\nimport { getSchemaURI, getTypename } from '../Annotation/annotations.ts';\nimport { type AnyEntity, InstancePhantomId, KindId, TypeId, getStaticTypeSchema } from '../common/types/index.ts';\nimport { getUri as getUriFromEntity } from './api.ts';\n\n/**\n * @param input schema, `Type.Type` entity, or a type URI (an `echo:` EID or a `dxn:` DXN).\n * @return type identifier URI — see {@link getSchemaURI}. A URI is returned verbatim. For a\n * `Type.Type` entity, the URI of the schema it declares, symmetric with what\n * `Obj.make(typeEntity, ...)` stamps on `system.type`: a static declaration resolves to its\n * typename DXN, a persisted entity to its local `echo:///<objectId>`.\n */\nexport const getTypeURIFromSpecifier = (input: Schema.Top | AnyEntity | URI.URI): URI.URI => {\n if (Schema.isSchema(input)) {\n return getSchemaURI(input) ?? raise(new TypeError('Schema has no URI'));\n }\n // Type entities are normally proxy objects, but class-declared types from\n // `Type.makeObject` are functions whose prototype chain reaches the entity, so accept functions too.\n if (input !== null && (typeof input === 'object' || typeof input === 'function') && KindId in input) {\n // `Type.Type` entity. Both in-memory and persisted forms expose the schema\n // they declare via `StaticTypeSchemaSlot`, whose URI is exactly what\n // `Obj.make` stamps on `system.type` — a static declaration carries\n // `TypeAnnotation` (→ typename DXN), a persisted entity's rebuilt schema\n // carries `TypeIdentifierAnnotation` (→ local `echo:///<objectId>`).\n const schema = getStaticTypeSchema(input);\n if (schema != null) {\n // Static types carry TypeAnnotation → DXN; persisted db types carry\n // TypeIdentifierAnnotation → echo EID. In-memory makeObjectFromJsonSchema\n // entities have neither (plain JSON Schema), so fall through to the EID path.\n const uri = getSchemaURI(schema);\n if (uri != null) {\n return uri;\n }\n }\n return getUriFromEntity(input as AnyEntity);\n }\n // A string specifier is already a branded URI — an `echo:` EID or a `dxn:` DXN.\n assertArgument(EID.isEID(input) || DXN.isDXN(input), 'input', 'expected a type URI (EID or DXN)');\n return input;\n};\n\n/**\n * Checks if the object is an instance of the schema.\n * Only typename is compared, the schema version is ignored.\n *\n * The following cases are considered to mean that the object is an instance of the schema:\n * - Object was created with this exact schema.\n * - Object was created with a different version of this schema.\n * - Object was created with a different schema (maybe dynamic) that has the same typename.\n */\n// TODO(burdon): Can we use `Schema.is`?\nexport const isInstanceOf = <S>(\n schemaOrType: S extends Schema.Codec<any, any> ? S : Schema.Codec<any, any> | AnyEntity,\n object: any,\n): object is S extends Schema.Codec<any, any>\n ? Schema.Schema.Type<S>\n : S extends { readonly [InstancePhantomId]?: infer A }\n ? A\n : unknown => {\n if (object == null) {\n return false;\n }\n\n const schemaURI = getTypeURIFromSpecifier(schemaOrType);\n\n // `object` is arbitrary input — read TypeId directly (it may be missing on\n // non-entities) rather than via `getTypeURI` which asserts the URI is set.\n const type = (object as any)[TypeId];\n if (URI.isURI(type) && type === schemaURI) {\n return true;\n }\n\n const typename = getTypename(object);\n if (!typename) {\n return false;\n }\n\n if (!DXN.isDXN(schemaURI)) {\n // EID-based schema URI — no typename match possible.\n return false;\n }\n\n const parsed = DXN.tryMake(schemaURI);\n return parsed != null && DXN.getName(parsed) === typename;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Effectable from 'effect/Effectable';\nimport * as Option from 'effect/Option';\n\nimport type * as QueryResult from '../../QueryResult.ts';\n\n/**\n * Wraps an effect that produces a {@link QueryResult.QueryResult} into a\n * {@link QueryResult.QueryResultEffect}, exposing `.run` and `.first` shorthands that execute the\n * query once. Shared by `Database.query` and `Feed.query` so both surfaces chain identically.\n */\nexport const makeQueryResultEffect = <T, E, R>(\n eff: Effect.Effect<QueryResult.QueryResult<T>, E, R>,\n): QueryResult.QueryResultEffect<T, E, R> => {\n // Effect 4 replaced the spread-in `CommitPrototype` with `Prototype`, which takes the old\n // `commit()` body as `evaluate` and builds the Effect-shaped base itself.\n const base = Effectable.Prototype<Effect.Effect<QueryResult.QueryResult<T>, E, R>>({\n label: '@dxos/echo/QueryResultEffect',\n evaluate: () => eff,\n });\n\n return Object.assign(base, {\n run: Effect.flatMap(eff, (result) => Effect.promise(() => result.run())),\n first: Effect.flatMap(eff, (result) =>\n Effect.promise(async () => Option.fromNullishOr(await result.firstOrUndefined())),\n ),\n }) as QueryResult.QueryResultEffect<T, E, R>;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Queue from 'effect/Queue';\nimport * as Schema from 'effect/Schema';\nimport * as Stream from 'effect/Stream';\n\nimport type { CleanupFn } from '@dxos/async';\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\nimport { invariant } from '@dxos/invariant';\nimport { type SpaceId, type URI } from '@dxos/keys';\n\nimport type * as Blob from './Blob.ts';\nimport type * as Change from './Change.ts';\nimport type * as Entity from './Entity.ts';\nimport * as Error from './Error.ts';\nimport type * as Feed from './Feed.ts';\nimport type * as Filter from './Filter.ts';\nimport type * as Hypergraph from './Hypergraph.ts';\nimport { type AnyProperties, EntityKind, KindId } from './internal/common/types/index.ts';\n// Deep import (not the `./internal/Entity` barrel) to avoid a cycle:\n// Database → internal/Entity → entity → JsonSchema → Ref → Database.\nimport { isInstanceOf } from './internal/Entity/type-uri.ts';\nimport * as queryInternal from './internal/Query/index.ts';\nimport type { LoadOptions, Ref } from './internal/Ref/ref.ts';\nimport type * as Migration from './Migration.ts';\nimport type * as Obj from './Obj.ts';\nimport type * as Query from './Query.ts';\nimport type * as QueryResult from './QueryResult.ts';\nimport type * as Registry from './Registry.ts';\nimport type * as Type from './Type.ts';\n\n/**\n * `query` API function declaration.\n */\n// TODO(burdon): Reconcile Query and Filter (should only have one root type).\nexport interface QueryFn {\n <Q extends Query.Any>(query: Q): QueryResult.QueryResult<Query.Type<Q>>;\n <F extends Filter.Any>(filter: F): QueryResult.QueryResult<Filter.Type<F>>;\n}\n\n/**\n * Common interface for Database, Feed, and Hypergraph.\n */\nexport interface Queryable {\n query: QueryFn;\n}\n\nexport type GetObjectByIdOptions = {\n deleted?: boolean;\n};\n\n/**\n * Whether a write was a person's own action, reported with ECHO's trace events. `system` is everything a person\n * did not directly do: agents, syncs and imports, seeded content, migrations and automation. When no origin is\n * given, an object with foreign keys was written by a sync or import (`system`) and anything else is `unknown`:\n * a write path that still needs attributing.\n */\nexport type Origin = 'user' | 'system' | 'unknown';\n\n/**\n * The {@link Origin} the Effect wrappers ({@link add}, {@link remove}, {@link addType}, {@link appendToFeed})\n * attribute their writes to. Provided once around a unit of work, e.g. `system` around seeding code or an\n * agent's operations, rather than at every write.\n */\nexport const Origin: Context.Reference<Origin | undefined> = Context.Reference<Origin | undefined>(\n '@dxos/echo/Database/Origin',\n { defaultValue: () => undefined },\n);\n\n/**\n * The trace events ECHO emits on `trace.events` from `@dxos/tracing` for local writes, each with the write's\n * {@link Origin}. Replicated writes are not reported.\n */\nexport const TraceEvents = {\n objectAdd: 'echo.object.add',\n objectRemove: 'echo.object.remove',\n typeAdd: 'echo.type.add',\n feedAppend: 'echo.feed.append',\n} as const;\n\n/** Options for writes that only carry attribution. */\nexport type WriteOptions = {\n /** See {@link Origin}. */\n origin?: Origin;\n};\n\nexport type AddOptions = {\n /** See {@link Origin}. */\n origin?: Origin;\n\n /**\n * Append the object to this feed instead of the automerge-backed space database. The object is\n * returned synchronously (a live feed object) and persisted in the background — confirm the write\n * completed with {@link Database.flush}. Synchronous alternative to the async\n * {@link Database.appendToFeed}.\n */\n to?: Feed.Feed;\n};\n\n/**\n * Rejects Type entities from {@link Database.add} at compile time via their `[KindId]` brand. Used\n * as `T & RejectTypeEntity<T>` to preserve inference of `T`. Bounding `add` on\n * `Obj.Unknown | Relation.Unknown` instead would reject broadly-typed instance adds (e.g.\n * `Entity.Any`, `Obj.OfShape<T>`), forcing casts repo-wide.\n */\nexport type RejectTypeEntity<T> = T extends { readonly [KindId]: EntityKind.Type }\n ? { __error: 'Type entities must be persisted via db.addType(), not db.add().' }\n : T;\n\nexport type FlushOptions = {\n /**\n * Write any pending changes to disk.\n * @default true\n */\n disk?: boolean;\n\n /**\n * Wait for pending index updates.\n * @default true\n */\n indexes?: boolean;\n\n /**\n * Also wait for the secondary indexes (full text), which lag the primary pass by design.\n * @default false\n */\n secondaryIndexes?: boolean;\n\n /**\n * Flush pending updates to objects and queries.\n * @default false\n */\n updates?: boolean;\n};\n\n/**\n * A caller-owned, writable **independent instance** of one object bound to one branch: a distinct\n * object instance (not a UI surface), separate from the device-global canonical object.\n * @see Database.branch\n */\nexport type BranchBinding<T extends Obj.Unknown = Obj.Unknown> = {\n /** Live object bound to the branch document (`'main'` -> the canonical live object). */\n readonly object: T;\n /** Release the binding (drops the doc-handle listener; never deletes the branch document). */\n dispose(): void;\n};\n\n/**\n * Identifier denoting an ECHO Database.\n *\n * Namespaced (like `@dxos/echo/Database/Service` below) rather than the bare `@dxos/echo/Database`:\n * that key belongs to the `[ObjectDatabaseId]` accessor every ECHO object carries, and a shared\n * registry key would make `TypeId in obj` true for every object in the graph.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Database/TypeId');\nexport type TypeId = typeof TypeId;\n\n/**\n * ECHO Database interface.\n */\nexport interface Database extends Queryable {\n readonly [TypeId]: TypeId;\n\n get spaceId(): SpaceId;\n\n get graph(): Hypergraph.Hypergraph;\n\n /**\n * Registry for this database. Delegates type lookups to the shared hypergraph registry.\n * To persist a schema so it replicates to other clients, add the type entity with\n * {@link addType} (e.g. `await db.addType(Type.makeObjectFromJsonSchema(...))`).\n */\n readonly registry: Registry.Registry;\n\n /**\n * Summary of the database for logging.\n *\n * @performance O(n) in loaded objects; allocates the object-core list to count it.\n */\n toJSON(): object;\n\n /**\n * Return object by local ID.\n * @deprecated Use `db.query(Filter.id(id)).runSync()[0]` for a working-set lookup, or resolve via a {@link Ref}.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\n getObjectById<T extends Obj.Unknown = Obj.OfShape<AnyProperties>>(\n id: string,\n opts?: GetObjectByIdOptions,\n ): T | undefined;\n\n /**\n * Query objects.\n *\n * @performance O(AST size) to key the result cache; returns a shared, lazily executed result, so nothing runs until\n * read.\n */\n query: QueryFn;\n\n /**\n * Creates a reference to an existing object in the database.\n *\n * NOTE: The reference may be dangling if the object is not present in the database.\n * NOTE: Difference from `Ref.fromURI`\n * `Ref.fromURI(dxn)` returns an unhydrated reference. The `.load` and `.target` APIs will not work.\n * `db.makeRef(dxn)` is preferable in cases with access to the database.\n *\n * @performance O(1); allocates a resolver-bound ref without looking the target up.\n */\n makeRef<T extends Entity.Unknown = Entity.Unknown>(uri: URI.URI): Ref<T>;\n\n /**\n * Adds an object or relation to the database.\n *\n * Only Object and Relation entities are accepted. To persist a Type definition use\n * {@link addType} — passing a Type entity is rejected at compile time (and at runtime).\n *\n * Pass `{ to: feed }` to append to a feed instead (synchronous; confirm with {@link flush}).\n *\n * @performance Synchronous; O(n) in object size to write it into a new linked document (or the root), persisted in\n * the background.\n */\n add<T extends Entity.Unknown = Entity.Unknown>(obj: T & RejectTypeEntity<T>, opts?: AddOptions): T;\n\n /**\n * Persists a Type definition (clones/forks the entity) so it replicates to other peers.\n *\n * Runs a conflict query first: if a type with the same typename + version already exists in\n * this space, the existing persisted entity is returned and no duplicate is created. This is\n * the only supported way to add Type entities — {@link add} rejects them.\n *\n * @performance Async; O(t) in the space persisted types, which it queries in full for a duplicate before writing.\n */\n addType<T extends Type.AnyEntity>(type: T, opts?: WriteOptions): Promise<T>;\n\n /**\n * Removes object from the database.\n *\n * @performance O(1); sets the deletion marker (a soft delete).\n */\n // TODO(burdon): Return true if removed (currently throws if not present).\n remove(obj: Entity.Unknown, opts?: WriteOptions): void;\n\n /**\n * Appends entities to a feed.\n *\n * The feed must already be stored in the database (added via {@link add}); its underlying\n * queue is addressed by the feed object's URI.\n *\n * @performance Async; O(n) in entities encoded and appended to the feed in one batch.\n */\n appendToFeed(feed: Feed.Feed, entities: Entity.Unknown[], opts?: WriteOptions): Promise<void>;\n\n /**\n * Appends `base` as the base block of a new branch of the feed, with the fork point `at` (an item,\n * at the block it was read from, or a block id) as its predecessor. Resolves to the id of the new\n * branch, the block id of the base, once the base is written.\n *\n * @performance Async; one append of one entity.\n */\n forkFeed(\n feed: Feed.Feed,\n base: Entity.Unknown,\n opts: { at: Entity.Unknown | Entity.Snapshot | Feed.BlockId },\n ): Promise<Feed.BranchId>;\n\n /**\n * Removes entities from a feed.\n *\n * @performance Async; O(n) in entities, deleted by id in one batch.\n */\n deleteFromFeed(feed: Feed.Feed, entities: Entity.Unknown[]): Promise<void>;\n\n /**\n * Wait for all pending changes to be saved to disk.\n * Optionaly waits for changes to be propagated to indexes and event handlers.\n *\n * @performance Async; always waits for pending document creation, then only for the disk, index and update work\n * that `opts` selects, so it is as slow as that selected backlog.\n */\n flush(opts?: FlushOptions): Promise<void>;\n\n /**\n * Starts staging structural changes that commit atomically; see {@link Migration.Transaction}.\n *\n * @throws When the database cannot commit with the chosen {@link Migration.TransactionOptions.root}.\n * @performance Async; loads the transaction code on first use, then O(1).\n */\n beginMigration(options?: Migration.TransactionOptions): Promise<Migration.Transaction>;\n\n //\n // Branching. A branch is a writable alternate timeline of an object subtree (same object ids,\n // shared automerge history, true CRDT merge-back). The registry is synced on the space root;\n // the currently-viewed branch stays device-local.\n //\n\n /**\n * The device-global current branch for an object id (`'main'` by default).\n * @deprecated Prefer `Obj.getBranch(obj)` — it takes the object and reports the branch of that\n * specific instance (including `db.branch()` independent instances), not just the device selection.\n *\n * @performance O(1) device-local map lookup.\n */\n getCurrentBranch(objectId: string): string;\n\n /**\n * An immutable snapshot of the object at the given historical heads — a detached instance, not a\n * pin on the live object. Prefer `Obj.getVersion(obj, heads)`.\n *\n * @performance O(object size) plus the Automerge cost of viewing the document at `heads`; nothing is cached.\n */\n getVersion<T extends Obj.Unknown>(obj: T, heads: readonly string[]): Obj.Snapshot<T>;\n\n /**\n * The object's history, oldest first: one entry per document change that touched the object (or,\n * given `property`, that property). Prefer `Obj.getChanges(obj, opts)`.\n *\n * @performance O(document history): diffs every change of the Automerge document and snapshots each match; not\n * cached.\n */\n getChanges<T extends Obj.Unknown>(obj: T, opts?: Obj.GetChangesOptions): Change.ValueChange<unknown>[];\n\n /**\n * All branch names available for an object, including the implicit `'main'` (always first).\n *\n * @performance O(1) for a subtree root; a member scans every branch record in the space to find its root.\n */\n listBranches(objectId: string): string[];\n\n /**\n * Fork the object and its referenced subtree into a new branch (does not switch to it).\n * @param opts.fromHeads Fork from a historical frontier instead of the tip (a bare heads array\n * applies to the root only; a map forks each member from its own frontier).\n *\n * @performance Async; O(subtree size), each member document forked as a full history copy.\n */\n createBranch(\n rootObjectId: string,\n name: string,\n opts?: { fromHeads?: readonly string[] | Record<string, readonly string[]> },\n ): Promise<void>;\n\n /**\n * Switch the object's subtree to a branch (or back to `'main'`). Device-local; cascades to children.\n *\n * @performance Async; O(subtree size) rebinds, serialized with other branch operations.\n */\n switchBranch(rootObjectId: string, name: string): Promise<void>;\n\n /**\n * Merge a branch back into main across the subtree, then switch back to main.\n *\n * @performance Async; O(subtree size) Automerge merges followed by a switch back to main.\n */\n mergeBranch(rootObjectId: string, name: string, opts?: { deleteAfter?: boolean }): Promise<void>;\n\n /**\n * Fold main's changes into a branch across the subtree (the reverse of {@link mergeBranch}).\n *\n * @performance Async; O(subtree size) Automerge merges, serialized with other branch operations.\n */\n syncBranch(rootObjectId: string, name: string): Promise<void>;\n\n /**\n * Delete a branch (its documents lose their sync reference). Cannot delete `'main'`.\n *\n * @performance O(subtree size); one root-document change plus a background rebind of members viewing the branch.\n */\n deleteBranch(rootObjectId: string, name: string): void;\n\n /**\n * Create a caller-owned, writable binding to one branch of one object — a live object whose reads\n * resolve the branch document and whose writes land on the branch document only. Multiple bindings\n * to different branches of the same object may coexist; the device-global current branch and other\n * bindings are unaffected. Binding to `'main'` returns the canonical live object. Bindings are\n * ephemeral and never persisted — the caller must `dispose()`.\n *\n * @performance Async; O(1) for main, otherwise loads and binds the branch document of this one object.\n */\n branch<T extends Obj.Unknown>(obj: T, name: string): Promise<BranchBinding<T>>;\n\n /**\n * Removes feed items by ID. `branches` names the branch of each item by index (`null` for the root),\n * for an item this client holds no live copy of; without it such an item is removed from the root branch.\n *\n * @performance Async; O(n) in ids, deleted in one batch.\n */\n removeFeedItemsByIds(\n feed: Feed.Feed,\n ids: string[],\n options?: { branches?: ReadonlyArray<string | null> },\n ): Promise<void>;\n\n /**\n * Syncs a feed with the server.\n *\n * @performance Async; network-bound, proportional to the replication backlog.\n */\n syncFeed(feed: Feed.Feed, options?: Feed.SyncOptions): Promise<void>;\n\n /**\n * Returns queue replication backlog for the feed's namespace.\n *\n * @performance Async; one service round trip.\n */\n getFeedSyncState(feed: Feed.Feed): Promise<Feed.SyncState>;\n\n /**\n * Disposes and drops the in-memory handle (live working-set / core cache) for a feed, so the next\n * access re-reads it cold. Advanced cache-control; primarily used by tests to model a spawned\n * process reading the feed with an empty in-memory cache. Public (not `_`-prefixed) so it survives\n * declaration stripping for cross-package test use.\n *\n * @performance Async; O(1) eviction, and the next access re-reads the feed cold.\n */\n evictFeedHandle(feed: Feed.Feed): Promise<void>;\n\n /**\n * Hashes and uploads `bytes` via the chosen storage backend, returning an un-added Blob object.\n * Rejects with `Error.BlobTooLargeError` (over inline storage's fixed cap, or the backend's own\n * `maxSize`), `Error.BlobWriteError` (backend upload failure), or `Error.BlobNotAvailableError`\n * (`reason: 'backend-not-registered'` — the requested storage name has no registered backend).\n *\n * @performance Async; O(size) to hash, plus the backend upload (a no-op for inline storage).\n */\n createBlob(bytes: Uint8Array, options?: { type?: string; storage?: string }): Promise<Blob.Blob>;\n\n /**\n * Adopts bytes already staged by a direct upload, returning an un-added Blob object.\n *\n * Unlike {@link createBlob} the bytes never enter this process: they were written straight to the\n * store by whoever held the upload URL, which is the point — the uploader is typically an agent's\n * shell moving a file far too large to pass through a model. Size and content type therefore come\n * back from the store rather than from the caller.\n *\n * Rejects with `Error.BlobNotAvailableError` (`reason: 'backend-not-registered'` when the storage\n * name has no backend, `'not-found'` when the backend cannot adopt uploads or the upload is gone)\n * or `Error.BlobWriteError` if adoption fails.\n *\n * @performance Async; one backend round trip, and the bytes never pass through this process.\n */\n createBlobFromUpload(uploadId: string, options?: { storage?: string }): Promise<Blob.Blob>;\n\n /**\n * Loads a blob's bytes. Rejects with `Error.BlobNotAvailableError` if the backend for the blob's\n * storage scheme is not registered, offline, or cannot find the bytes.\n *\n * @performance Async; O(size), read inline or fetched from the backend.\n */\n readBlob(blob: Blob.Blob): Promise<Uint8Array>;\n\n /**\n * Checks whether a blob's bytes are currently available.\n *\n * @performance Async; one backend check, with no byte transfer.\n */\n blobExists(blob: Blob.Blob): Promise<boolean>;\n\n /**\n * Returns a renderable URL for the blob, if one can be produced.\n *\n * @performance Async; an inline blob encodes all of its bytes into a `data:` URL (O(size)), an external one asks the\n * backend.\n */\n getBlobUrl(blob: Blob.Blob): Promise<string | undefined>;\n\n /**\n * Get the current combined (automerge documents + feed blocks) sync state, reported against a\n * single remote peer.\n *\n * @performance Async; two concurrent service round trips (documents and feeds).\n */\n getSyncState(options?: GetSyncStateOptions): Promise<SyncState>;\n\n /**\n * Subscribe to combined sync state changes.\n *\n * @performance O(1) setup of two service streams, each update recombined in O(peers).\n */\n subscribeToSyncState(cb: (state: SyncState) => void, options?: GetSyncStateOptions): CleanupFn;\n\n /**\n * Per-space storage metrics: objects (alive/deleted), automerge documents, feeds, feed blocks.\n * Read-only. Intended as an occasional/administrative call. See garbage-collection design notes\n * in `@dxos/echo-host`.\n *\n * @performance Async; one host round trip plus an O(feeds) client-side tally.\n */\n stats(): Promise<DatabaseStats>;\n\n /**\n * Reclaim storage held by soft-deleted objects and the documents / feed blocks that are no longer\n * reachable. Per-space and destructive; intended as an occasional/administrative call. See\n * garbage-collection design notes in `@dxos/echo-host`.\n *\n * @performance Async; host-side and O(space size), so run it rarely.\n */\n runGarbageCollection(options?: GarbageCollectionOptions): Promise<GarbageCollectionReport>;\n\n /**\n * Replaces the set of objects the space directory tracks, dropping everything not retained.\n *\n * Derived from the directory's own maps, so clearing a space costs one change rather than a scan\n * of its contents. The objects are dropped, not soft-deleted: they are gone from the space and\n * their documents are reclaimed by garbage collection, on this peer and — as the change\n * replicates — on every other. Permanent; there is nothing left to restore from.\n *\n * @returns Ids of the objects dropped from the directory.\n *\n * @performance O(directory size) scan of the space root plus one root-document change, with no object loads.\n */\n retainObjects(keep: Iterable<string>): string[];\n}\n\n/**\n * Type guard for databases.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isDatabase = (obj: unknown): obj is Database => {\n return obj ? typeof obj === 'object' && TypeId in obj && obj[TypeId] === TypeId : false;\n};\n\nexport const Database: Schema.Codec<Database> = Schema.Any.pipe(Schema.refine(isDatabase));\n\n/**\n * Effect service tag for Database dependency injection.\n */\nexport class Service extends Context.Service<\n Service,\n {\n readonly db: Database;\n }\n>()('@dxos/echo/Database/Service') {}\n\n/**\n * Layer that provides a Database service that throws when accessed.\n * Useful as a default layer when no database is available.\n */\nexport const notAvailable = Layer.succeed(Service, {\n get db(): Database {\n throw new globalThis.Error('Database not available');\n },\n});\n\n/**\n * Creates a Database service instance from a Database.\n *\n * @performance O(1).\n */\nexport const makeService = (db: Database): Service['Service'] => {\n return {\n get db() {\n return db;\n },\n };\n};\n\n/**\n * Creates a Layer that provides the Database service.\n *\n * @performance O(1).\n */\nexport const layer = (db: Database): Layer.Layer<Service> => {\n return Layer.succeed(Service, makeService(db));\n};\n\n/**\n * Stamps the database's space on every span the effect opens, so a span can be filtered by the space\n * it ran in. Applied after `Effect.withSpan`, so the span it names is inside the annotated region.\n *\n * @performance O(1) span annotation around the effect.\n */\nexport const withSpaceId = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | Service> =>\n Effect.flatMap(Service, ({ db }) => effect.pipe(Effect.annotateSpans(SpanAttributes.SPACE_ID, db.spaceId)));\n\n/**\n * Returns the space ID of the database.\n *\n * @performance O(1) service read.\n */\nexport const spaceId = Effect.gen(function* () {\n const { db } = yield* Service;\n return db.spaceId;\n});\n\n/**\n * Resolves an object by its DXN.\n *\n * @performance Async; working-set hit is O(1), otherwise loads the object from disk or the network.\n */\nexport const resolve: {\n // No type check.\n (ref: URI.URI | Ref<any>): Effect.Effect<Entity.Unknown, never, Service>;\n // Check matches schema.\n <S extends Type.AnyEntity>(\n ref: URI.URI | Ref<any>,\n schema: S,\n ): Effect.Effect<Type.InstanceType<S>, Error.EntityNotFoundError, Service>;\n} = (<S extends Type.AnyEntity>(\n ref: URI.URI | Ref<any>,\n schema?: S,\n): Effect.Effect<Type.InstanceType<S>, Error.EntityNotFoundError, Service> =>\n Effect.gen(function* () {\n const { db } = yield* Service;\n const dxn = typeof ref === 'string' ? ref : ref.uri;\n const object = yield* Effect.promise(() =>\n db.graph\n .createRefResolver({\n context: {\n space: db.spaceId,\n },\n })\n .resolveLegacy(dxn),\n );\n\n if (!object) {\n return yield* Effect.fail(new Error.EntityNotFoundError(dxn));\n }\n // `isInstanceOf` uses a conditional generic that TS can't resolve through\n // the local `S extends Type.AnyEntity` parameter — runtime accepts it fine.\n invariant(!schema || isInstanceOf(schema as any, object), 'Object type mismatch.');\n return object as any;\n }).pipe(Effect.withSpan('Database.resolve'), withSpaceId)) as any;\n\n/**\n * Starts staging structural changes in the current database; see {@link Migration.Transaction}.\n *\n * @performance Async; loads the transaction code on first use, then O(1).\n */\nexport const beginMigration = (\n options?: Migration.TransactionOptions,\n): Effect.Effect<Migration.Transaction, Error.MigrationError, Service> =>\n Effect.gen(function* () {\n const { db } = yield* Service;\n return yield* Effect.tryPromise({\n try: () => db.beginMigration(options),\n catch: (cause) => new Error.MigrationError({ operation: 'begin' }, { cause }),\n });\n }).pipe(Effect.withSpan('Database.beginMigration'), withSpaceId);\n\n/**\n * Loads an object reference. A deleted target reads as absent unless `{ deleted: 'include' }` asks\n * for it.\n *\n * The options parameter means this cannot be passed point-free where the caller supplies a second\n * argument — `Effect.forEach(refs, (ref) => load(ref))`, not `Effect.forEach(refs, load)`, since the\n * iteratee index would land on `options`.\n *\n * Catching not found error:\n *\n * ```ts\n * yield* load(ref).pipe(Effect.catchTag('EntityNotFoundError', () => Effect.succeed(undefined)));\n * ```\n *\n * @performance Async; resolves immediately for a loaded target, otherwise loads from disk or the network.\n */\nexport const load: <T>(ref: Ref<T>, options?: LoadOptions) => Effect.Effect<T, Error.EntityNotFoundError, never> =\n Effect.fn('Database.load')(function* (ref, options) {\n const object = yield* Effect.promise(() => ref.tryLoad(options));\n if (!object) {\n return yield* Effect.fail(new Error.EntityNotFoundError(ref.uri));\n }\n return object;\n });\n\n/**\n * Synchronous working-set read (see {@link Ref.peek}): the materialized target, or `undefined` —\n * never throws and never triggers loading. Compose with {@link load} for a sync-when-materialized\n * read with an async fallback, keeping the effect runnable under `Effect.runSync` when every ref\n * is materialized (e.g. a mutation in a gesture frame):\n *\n * ```ts\n * const task = Database.peek(ref) ?? (yield* Database.load(ref));\n * ```\n *\n * Peek skips {@link load}'s settling — a just-added object can resolve here before it has its own\n * document — so callers that branch (or otherwise need a settled document) must load.\n *\n * @performance O(1) working-set lookup; never loads and never throws.\n */\nexport const peek = <T>(ref: Ref<T>): T | undefined => ref.peek();\n\n/**\n * Makes a reference to an object addressed by URI, resolvable against this database.\n * @see {@link Database.makeRef}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const makeRef = <T extends Entity.Unknown = Entity.Unknown>(\n uri: URI.URI,\n): Effect.Effect<Ref<T>, never, Service> =>\n Service.pipe(Effect.map(({ db }) => db.makeRef<T>(uri))).pipe(Effect.withSpan('Database.makeRef'), withSpaceId);\n\n/**\n * Adds an object or relation to the database.\n * @see {@link Database.add}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\n// The Effect wrapper intentionally omits the method's `opts` (e.g. `{ to: feed }`): it is applied\n// point-free (`Effect.forEach(Database.add)`), where a second parameter would collide with the\n// iteratee index. Effect-style feed appends go through `Database.appendToFeed` / `Feed.append`.\nexport const add = <T extends Entity.Unknown>(obj: T & RejectTypeEntity<T>): Effect.Effect<T, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.map(Origin, (origin) => db.add<T>(obj, { origin })))).pipe(\n Effect.withSpan('Database.add'),\n withSpaceId,\n );\n\n/**\n * Persists a Type definition to the database.\n * @see {@link Database.addType}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const addType = <T extends Type.AnyEntity>(type: T): Effect.Effect<T, never, Service> =>\n Service.pipe(\n Effect.flatMap(({ db }) => Effect.flatMap(Origin, (origin) => Effect.promise(() => db.addType(type, { origin })))),\n ).pipe(Effect.withSpan('Database.addType'), withSpaceId);\n\n/**\n * Removes an object from the database.\n * @see {@link Database.remove}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const remove = <T extends Entity.Unknown>(obj: T): Effect.Effect<void, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.map(Origin, (origin) => db.remove(obj, { origin })))).pipe(\n Effect.withSpan('Database.remove'),\n withSpaceId,\n );\n\n/**\n * Appends entities to a feed.\n * @see {@link Database.appendToFeed}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const appendToFeed = (feed: Feed.Feed, entities: Entity.Unknown[]): Effect.Effect<void, never, Service> =>\n Service.pipe(\n Effect.flatMap(({ db }) =>\n Effect.flatMap(Origin, (origin) => Effect.promise(() => db.appendToFeed(feed, entities, { origin }))),\n ),\n ).pipe(Effect.withSpan('Database.appendToFeed'), withSpaceId);\n\n/**\n * Removes entities from a feed.\n * @see {@link Database.deleteFromFeed}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const deleteFromFeed = (feed: Feed.Feed, entities: Entity.Unknown[]): Effect.Effect<void, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.deleteFromFeed(feed, entities)))).pipe(\n Effect.withSpan('Database.deleteFromFeed'),\n withSpaceId,\n );\n\n/**\n * Flushes pending changes to disk.\n * @see {@link Database.flush}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const flush = (opts?: FlushOptions) =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.flush(opts)))).pipe(\n Effect.withSpan('Database.flush'),\n withSpaceId,\n );\n\n/**\n * Reclaims storage held by soft-deleted objects and the documents they orphan.\n * @see {@link Database.runGarbageCollection}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const runGarbageCollection = (options?: GarbageCollectionOptions) =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.runGarbageCollection(options)))).pipe(\n Effect.withSpan('Database.runGarbageCollection'),\n withSpaceId,\n );\n\n/**\n * Drops every object in the space except the retained ones. Permanent.\n * @see {@link Database.retainObjects}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const retainObjects = (keep: Iterable<string>) =>\n Service.pipe(Effect.map(({ db }) => db.retainObjects(keep))).pipe(\n Effect.withSpan('Database.retainObjects'),\n withSpaceId,\n );\n\n/**\n * Per-space storage metrics.\n * @see {@link Database.stats}\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const stats = () =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.stats()))).pipe(\n Effect.withSpan('Database.stats'),\n withSpaceId,\n );\n\n/**\n * Creates a `QueryResult` object that can be subscribed to.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const query: {\n <Q extends Query.Any>(query: Q): QueryResult.QueryResultEffect<Query.Type<Q>, never, Service>;\n <F extends Filter.Any>(filter: F): QueryResult.QueryResultEffect<Filter.Type<F>, never, Service>;\n} = (queryOrFilter: Query.Any | Filter.Any) =>\n Service.pipe(\n Effect.map(({ db }) => db.query(queryOrFilter as any) as QueryResult.QueryResult<any>),\n Effect.withSpan('Database.query'),\n withSpaceId,\n queryInternal.makeQueryResultEffect,\n );\n\n/**\n * Sync state of the database in relation to EDGE.\n */\nexport interface SyncState {\n //\n // Automerge\n //\n\n /**\n * Total number of documents locally.\n */\n readonly localDocumentCount: number;\n /**\n * Total number of documents on the remote peer.\n */\n readonly remoteDocumentCount: number;\n /**\n * Total number of documents across this peer and the remote peer.\n */\n readonly totalDocumentCount: number;\n /**\n * Total number of documents that are not synced.\n * Includes documents that are present only locally, only on the remote peer, or whether the peers have different versions.\n */\n readonly unsyncedDocumentCount: number;\n\n //\n // Feeds.\n //\n\n /**\n * Blocks still to pull from remote. 0 when caught up.\n */\n readonly blocksToPull: string;\n /**\n * Unpositioned blocks still to push to remote. 0 when caught up.\n */\n readonly blocksToPush: string;\n /**\n * Total blocks stored locally for this namespace in the space.\n */\n readonly totalBlocks: string;\n}\n\n/**\n * Per-space storage metrics returned by {@link Database.stats}.\n */\nexport interface DatabaseStats {\n readonly objects: {\n /** Live (non-deleted) objects across the root and all linked documents. */\n readonly alive: number;\n /** Soft-deleted objects not yet reclaimed by garbage collection. */\n readonly deleted: number;\n };\n /** Automerge documents owned by the space (root + linked + branch documents). */\n readonly documents: number;\n /** Feeds registered for the space. */\n readonly feeds: number;\n /** Total feed blocks stored locally for the space. */\n readonly feedBlocks: number;\n /**\n * What is resident in memory right now, as opposed to the stored counts above. Split by realm\n * because the client and the host cache independently — a client-side working set that is never\n * released reads as nothing at all in the host's numbers, and vice versa.\n */\n readonly loaded: {\n readonly client: ClientLoadedStats;\n readonly host: HostLoadedStats;\n };\n}\n\n/**\n * Client-side residency. Space-scoped except where noted.\n */\nexport interface ClientLoadedStats {\n /** Document handles held by this space's repo proxy. */\n readonly documents: number;\n /** Object cores held by this space's entity manager. */\n readonly objects: number;\n /** Feed handles cached by this database. */\n readonly feeds: number;\n /** Objects resident across those feed handles — the feeds' working set, not what is stored. */\n readonly feedObjects: number;\n /** Entities in the runtime registry (types and other static entities), across the whole client. */\n readonly registryTotal: number;\n}\n\n/**\n * Host-side residency. A document on disk costs nothing until a handle for it is cached.\n */\nexport interface HostLoadedStats {\n /** Automerge handles cached for this space. */\n readonly documents: number;\n /** Automerge handles cached across every space on this host. */\n readonly documentsTotal: number;\n /** Active reactive queries registered with the host, across every space. */\n readonly queriesTotal: number;\n /** Documents something on the host is using right now, across every space; the rest of `documentsTotal` is idle cache. */\n readonly leases: number;\n}\n\n/**\n * Options for {@link Database.runGarbageCollection}.\n */\nexport interface GarbageCollectionOptions {\n /**\n * Also delete stale index rows for reclaimed documents/objects.\n * @default true\n */\n readonly index?: boolean;\n /**\n * Reserved for feed-block purge (positioned deletion markers). Not yet effective on the local\n * host — see the feed-purge deferral in `@dxos/echo-host` garbage-collection design notes.\n * @default true\n */\n readonly feeds?: boolean;\n}\n\n/**\n * Report of what {@link Database.runGarbageCollection} reclaimed.\n */\nexport interface GarbageCollectionReport {\n /** Soft-deleted objects unlinked from the space directory. */\n readonly unlinkedObjects: number;\n /** Automerge documents wiped from storage (chunks + heads). */\n readonly removedDocuments: number;\n /** Index rows deleted. */\n readonly removedIndexEntries: number;\n /** Feed blocks purged. */\n readonly purgedFeedBlocks: number;\n}\n\n/**\n * Options for reading combined sync state.\n */\nexport interface GetSyncStateOptions {\n /**\n * Peer to report the automerge document backlog against. Defaults to the EDGE peer.\n * Provide explicitly in local/test topologies where there is no EDGE peer.\n */\n readonly peerId?: string;\n}\n\n/**\n * Get the current sync state.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const getSyncState = (options?: GetSyncStateOptions): Effect.Effect<SyncState, never, Service> =>\n Service.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.getSyncState(options))));\n\n/**\n * Subscribe to sync state changes.\n *\n * @performance O(1) delegation to the database; costs whatever the corresponding method costs.\n */\nexport const subscribeToSyncState = (options?: GetSyncStateOptions): Stream.Stream<SyncState, never, Service> =>\n Stream.callback<SyncState, never, Service>((queue) =>\n Effect.gen(function* () {\n const { db } = yield* Service;\n const cleanup = db.subscribeToSyncState((state) => Queue.offerUnsafe(queue, state), options);\n yield* Effect.addFinalizer(() => Effect.sync(cleanup));\n }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IAAa,wBAAwB,YACnC,OAAO,UAAqC,UAC1C,OAAO,IAAI,aAAa;CACtB,MAAM,EAAE,OAAO,OAAO;CACtB,MAAM,UAAU,GAAG,sBAAsB,UAAU,MAAM,YAAY,OAAO,KAAK,GAAG,OAAO;CAC3F,OAAO,OAAO,mBAAmB,OAAO,KAAK,OAAO,CAAC;AACvD,CAAC,CACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
2
|
import { d as getSchema } from "./chunk-Type.mjs";
|
|
3
3
|
import { R as instanceOf } from "./chunk-Obj.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { o as Feed } from "./chunk-Feed.mjs";
|
|
5
5
|
import { t as Collection } from "./chunk-Collection.mjs";
|
|
6
6
|
import { i as View } from "./chunk-View.mjs";
|
|
7
7
|
import { pipe } from "effect/Function";
|
|
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
|
2
2
|
import { a as addTag$1, c as getMetaChecked, i as isEntity$1, l as removeTag$1, s as getKeys$1 } from "./chunk-entity-dictionary.mjs";
|
|
3
3
|
import { A as objectToJSON, c as makeEntity, l as makeLabelAtom, p as makeTagsAtom, v as isDeleted$1 } from "./chunk-internal.mjs";
|
|
4
4
|
import { d as SnapshotKindId$1, l as KindId$1, m as getEntityKindBrand, o as EntityKind, s as EntityKindSchema } from "./chunk-util.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { At as getIcon$1, Bt as getTypeURI$1, Et as getDescription$1, F as getUri, Kt as setLabel$1, Mt as getLabelProperty, N as getDatabase$1, Ot as getEntityKind, Vt as getTypename$1, fn as MetaId, j as isInstanceOf, jt as getLabel$1, rn as getType$1 } from "./chunk-Database.mjs";
|
|
6
6
|
import { v as change, y as subscribe$1 } from "./chunk-ref.mjs";
|
|
7
7
|
import { f as getTypename$2, n as Type, p as getURI$1 } from "./chunk-Type.mjs";
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
@@ -254,7 +254,7 @@ var update = (entity, callback) => {
|
|
|
254
254
|
* Add a tag to an entity.
|
|
255
255
|
* Must be called within an `Entity.update`, `Obj.update`, or `Relation.update` callback.
|
|
256
256
|
*
|
|
257
|
-
* @performance O(t) in the tag count; dedupes by
|
|
257
|
+
* @performance O(t) in the tag count; dedupes by tag id before appending.
|
|
258
258
|
*/
|
|
259
259
|
var addTag = (entity, tag) => addTag$1(entity, tag);
|
|
260
260
|
/**
|