@party-stack/ontology-backend 0.5.0 → 0.7.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/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { Context, Schema } from \"effect\";\nimport { ObjectSubsetSchema } from \"./subsetSchema.js\";\nimport type { AttachmentTypeDef, QueryDocument } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { attachment, Encrypted } from \"@party-stack/ontology-spec/values\";\nimport type { Key, Row } from \"@party-stack/ontology-storage\";\nimport type { ByteInput } from \"@party-stack/ontology-storage/blobs\";\nimport type { Scope, Effect, Stream } from \"effect\";\n\nexport {\n schemaValidationIssues,\n BackendError,\n BackendErrorKindSchema,\n backendErrorStatus,\n ValidationIssueSchema,\n ValidationReportSchema,\n unauthenticated,\n isUnauthenticatedError,\n classifyBackendFailure,\n projectBackendError,\n projectValidationIssue,\n isUnknownActionOutcome,\n} from \"./errors.js\";\nexport type {\n BackendErrorKind,\n ReplicationErrorKind,\n ReplicationError,\n ErrorProjection,\n ErrorProjectionContext,\n ValidationReport,\n ValidationIssue,\n UnauthenticatedError,\n ApplyActionError,\n ValidateActionError,\n LoadSubsetError,\n} from \"./errors.js\";\nimport { BackendError } from \"./errors.js\";\nexport { makeOntologyBackend } from \"./query.js\";\n\nexport interface ObjectSelection {\n readonly subsets: readonly ObjectSubset[];\n}\nexport interface BackendSnapshot {\n /** Region represented by these rows, including any window already applied.\n * Omitted means the requested subset. A broader unwindowed region lets the\n * engine finish filtering/ordering/windowing and optionally cache extra objects.\n * Rows may include residual candidates outside this region; consumers discard\n * them before installing its objects or recording complete coverage.\n */\n readonly fulfilledSubset?: ObjectSubset;\n readonly rows: readonly Row<Record<string, unknown>>[];\n /** Complete for fulfilledSubset (or the request when omitted), including its window. */\n readonly complete: boolean;\n /** Rows fetched from the provider, before adapter-side filtering/windowing.\n * Diagnostic only; omitted when the adapter cannot report it. Not a DB scan count.\n */\n readonly fetchedRows?: number;\n /** Diagnostic provider filter, not a query-capability or coverage contract. */\n readonly pushdown?: SourceQueryPlan;\n /** Position coordinated with this snapshot, when the backend exposes a durable change stream. */\n readonly cursor?: string;\n}\nexport const SourceQueryPlanSchema = Schema.Struct({\n source: Schema.String,\n /** Paths into the request's portable where tree: AND/OR child indices, NOT child 0, [] for the root. */\n predicates: Schema.Array(\n Schema.Struct({\n path: Schema.Array(Schema.Int),\n execution: Schema.Literals([\"source\", \"candidate\", \"adapter\", \"engine\"]),\n })\n ),\n sorting: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n pagination: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n rechecksFilter: Schema.Boolean,\n /** Optional native syntax for raw inspection. Consumers must not parse it to infer execution. */\n native: Schema.optional(Schema.Struct({ language: Schema.String, text: Schema.String })),\n});\nexport type SourceQueryPlan = Schema.Schema.Type<typeof SourceQueryPlanSchema>;\nexport type ObjectChange =\n | {\n readonly kind: \"put\";\n readonly objectType: string;\n readonly key: Key;\n readonly value: Record<string, unknown>;\n }\n | { readonly kind: \"delete\"; readonly objectType: string; readonly key: Key };\nexport interface BackendCommit {\n readonly cursor: string;\n readonly changes: readonly ObjectChange[];\n readonly operationId?: string;\n}\nexport interface BackendChangePage {\n readonly commits: readonly BackendCommit[];\n readonly cursor: string;\n readonly hasMore: boolean;\n}\nexport interface AttachmentUpload {\n readonly attachment: attachment;\n readonly blob: ByteInput;\n readonly target?: AttachmentTypeDef;\n}\nexport interface ActionRequest {\n /** Stable across retries. The source must separately guarantee keyed idempotency. */\n readonly id: string;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n readonly attachmentUploads?: readonly AttachmentUpload[];\n /** Portable replay inputs, preserved across rebases, forwarding and authoritative execution. */\n readonly replay?: { readonly now: string; readonly seed: string };\n}\nexport interface ActionReceipt {\n /** The submitted ActionRequest.id, also supplied as the application's idempotencyKey. */\n readonly operationId: string;\n /** Provider commitment is recorded before local read-back/reconciliation. Parent acceptance is separate. */\n readonly outcome: \"committed\";\n /** Encoded authoritative return value, interpreted using the action returnType. Never a journal payload. */\n readonly result?: unknown;\n readonly cursor?: string;\n /** Optional upstream execution ID. Never substitutes for our stable retry identity. */\n readonly providerOperationId?: string;\n /** Read-back targets for a committed non-journal action. Missing keys\n * means the whole type; an empty list means no modeled object changes.\n * Omission conservatively refreshes every modeled type.\n * Targets are complete unless affectedComplete is explicitly false.\n */\n readonly affected?: readonly {\n readonly objectType: string;\n readonly keys?: readonly Key[];\n }[];\n /** False when these are known targets but automation may have changed other\n * modeled records. Confirmation must not use them as an exhaustive edit list.\n */\n readonly affectedComplete?: boolean;\n readonly attachmentIdMappings?: readonly { readonly localId: string; readonly remoteId: string }[];\n}\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nexport const ObjectChangeSchema = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"put\"),\n objectType: Schema.String,\n key: KeySchema,\n value: Schema.Record(Schema.String, Schema.Unknown),\n }),\n Schema.Struct({ kind: Schema.Literal(\"delete\"), objectType: Schema.String, key: KeySchema }),\n]);\nexport const ActionReceiptSchema = Schema.Struct({\n operationId: Schema.String,\n outcome: Schema.Literal(\"committed\"),\n result: Schema.optional(Schema.Unknown),\n cursor: Schema.optional(Schema.String),\n providerOperationId: Schema.optional(Schema.String),\n affected: Schema.optional(\n Schema.Array(\n Schema.Struct({ objectType: Schema.String, keys: Schema.optional(Schema.Array(KeySchema)) })\n )\n ),\n affectedComplete: Schema.optional(Schema.Boolean),\n attachmentIdMappings: Schema.optional(\n Schema.Array(Schema.Struct({ localId: Schema.String, remoteId: Schema.String }))\n ),\n});\nexport const BackendCommitSchema = Schema.Struct({\n cursor: Schema.String,\n changes: Schema.Array(ObjectChangeSchema),\n operationId: Schema.optional(Schema.String),\n});\nexport const BackendSnapshotSchema = Schema.Struct({\n fulfilledSubset: Schema.optional(ObjectSubsetSchema),\n fetchedRows: Schema.optional(Schema.Number),\n pushdown: Schema.optional(SourceQueryPlanSchema),\n rows: Schema.Array(\n Schema.Struct({ key: KeySchema, value: Schema.Record(Schema.String, Schema.Unknown) })\n ),\n complete: Schema.Boolean,\n cursor: Schema.optional(Schema.String),\n});\nexport const BackendChangePageSchema = Schema.Struct({\n commits: Schema.Array(BackendCommitSchema),\n cursor: Schema.String,\n hasMore: Schema.Boolean,\n});\n\nexport interface BackendAttachments {\n /** Optional authoritative staging before a subsequent action references the handle. */\n readonly stage?: (\n value: attachment,\n bytes: ByteInput,\n options?: { readonly target?: AttachmentTypeDef }\n ) => Effect.Effect<attachment, BackendError>;\n /** Keep the caller Scope open through consumption; closing it cancels an unconsumed download too. */\n readonly read: (\n value: attachment,\n options?: { readonly offset?: number; readonly length?: number }\n ) => Effect.Effect<ByteInput, BackendError, Scope.Scope>;\n readonly metadata: (\n value: attachment,\n options?: { readonly select?: readonly (\"size\" | \"type\" | \"name\" | \"dimensions\")[] }\n ) => Effect.Effect<\n {\n readonly size?: number;\n readonly type?: string;\n readonly name?: string;\n readonly dimensions?: { readonly width: number; readonly height: number };\n },\n BackendError\n >;\n}\nexport {\n EncryptedValueSchema,\n DecryptedValueSchema,\n encryptedPropertyCodec,\n makePropertyDecryption,\n} from \"./encrypted.js\";\nexport type { DecryptedValue } from \"./encrypted.js\";\n\nexport interface BackendEncryptedValues {\n /** Explicit operation. Ordinary record loads return handles and never decrypt them. */\n readonly decrypt: (\n value: Encrypted<unknown>\n ) => Effect.Effect<import(\"./encrypted.js\").DecryptedValue, BackendError>;\n}\n/** One object a watch reports, in the watched subset's object type.\n * - `put`: the object is now in the subset with this complete value.\n * - `exit`: the object left the subset. It may have changed or been deleted; the\n * replica reads it back by primary key to tell which.\n * - `delete`: the object no longer exists anywhere.\n */\nexport type SubsetWatchChange =\n | { readonly kind: \"put\"; readonly key: Key; readonly value: Record<string, unknown> }\n | { readonly kind: \"exit\"; readonly key: Key }\n | { readonly kind: \"delete\"; readonly key: Key };\n/** A reset requests repair after starting/restarting a watch; it does not\n * assert that data changed. Ordinary void hints always invalidate coverage.\n * `changes` describes exactly what changed, so the replica can apply it without\n * reloading the subset. Report only what is certain: a `put` must carry every\n * property; anything less precise must be an invalidation hint instead.\n */\nexport type SubsetWatchEvent = void | \"reset\" | { readonly changes: readonly SubsetWatchChange[] };\n\nexport interface OntologyBackendService {\n readonly name: string;\n /** Stable identity for the source whose cursors and receipts this binding returns. */\n readonly sourceId: string;\n /** Durable keyed idempotency within the configured receipt-retention window:\n * repeated IDs return the recorded result, with\n * conflicting payloads rejected. The guarantee must survive source restart.\n * Merely receiving an ID, or an action being naturally idempotent, is insufficient.\n */\n readonly supportsIdempotency: boolean;\n /** Indexed bounded local maintenance; the backend owner schedules it. */\n readonly maintenance?: Effect.Effect<void, BackendError>;\n /** Return the request or explicitly describe the region actually fulfilled.\n * Consumers use the shared subset normalizer before applying requested windows.\n */\n readonly loadSubset: (subset: ObjectSubset) => Effect.Effect<BackendSnapshot, BackendError>;\n /** Finite Query IR execution using this binding's trusted context and read path.\n * Provider adapters may evaluate through subset loads; owned storage uses one\n * read transaction. Callers supply query inputs, never authentication context.\n */\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Optional selected committed rows. Closing the Scope releases demand; delivery state expires by policy. */\n readonly subscribeSelection?: (\n selection: ObjectSelection,\n policy?: import(\"./delivery.js\").DeliveryPolicy,\n resume?: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<import(\"./delivery.js\").DeliverySubscription, BackendError, Scope.Scope>;\n readonly acknowledgeDelivery?: (\n position: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<void, BackendError>;\n /** Read-only defaults and edit prefills; never invokes the action. */\n readonly resolveActionParameters?: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Acquire a demand-scoped watch before reading its snapshot. Completion proves\n * registration and buffering are active, even before the returned stream is pulled.\n * The acquiring Scope owns registration and release. Undefined means polling.\n * Reconnect within the same stream must fail or emit reset/invalidation;\n * reacquisition establishes a new readiness boundary for a fresh read.\n * Must cover every change relevant to the requested subset; broader watches\n * may emit extra hints. It does not maintain broader fulfilledSubset coverage.\n */\n readonly watchSubset?: (\n subset: ObjectSubset\n ) => Effect.Effect<Stream.Stream<SubsetWatchEvent, BackendError>, BackendError, Scope.Scope> | undefined;\n /** Recommended demand refresh defaults. Caller configuration wins; healthy\n * watches/journals keep coverage current independently of snapshot age. */\n readonly refresh?: (subset: ObjectSubset) =>\n | {\n readonly pollIntervalMs?: number | false;\n readonly maxCoverageAgeMs?: number;\n }\n | undefined;\n readonly validateAction?: (\n name: string,\n parameters: Record<string, unknown>,\n options?: { readonly knownParameters?: readonly string[] }\n ) => Effect.Effect<import(\"./errors.js\").ValidationReport, BackendError>;\n readonly applyAction: (invocation: ActionRequest) => Effect.Effect<ActionReceipt, BackendError>;\n readonly queryFunction: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<unknown, BackendError>;\n readonly changes?: {\n readonly pull: (options: {\n readonly cursor?: string;\n readonly limit?: number;\n }) => Effect.Effect<BackendChangePage, BackendError>;\n /** Acquire registered, buffered wake-up hints in the caller's Scope before\n * pulling durable changes. Stream consumption does not initiate registration.\n * Call pull to recover changes after reconnect or restart. */\n readonly watch?: Effect.Effect<Stream.Stream<void, BackendError>, BackendError, Scope.Scope>;\n };\n readonly attachments?: BackendAttachments;\n readonly encrypted?: BackendEncryptedValues;\n}\n\n/** Backend protocol independent of TanStack collections and client lifecycle management. */\nexport class OntologyBackend extends Context.Service<OntologyBackend, OntologyBackendService>()(\n \"@party-stack/ontology-backend/OntologyBackend\"\n) {}\n"],"mappings":";;;;;;AA8DA,MAAa,wBAAwB,OAAO,OAAO;CAC/C,QAAQ,OAAO;;CAEf,YAAY,OAAO,MACf,OAAO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,OAAO,OAAO;CAC7C,QAAQ,OAAO;CACf,SAAS,OAAO,MAAM,kBAAkB;CACxC,aAAa,OAAO,SAAS,OAAO,MAAM;AAC9C,CAAC;AACD,MAAa,wBAAwB,OAAO,OAAO;CAC/C,iBAAiB,OAAO,SAAS,kBAAkB;CACnD,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,UAAU,OAAO,SAAS,qBAAqB;CAC/C,MAAM,OAAO,MACT,OAAO,OAAO;EAAE,KAAK;EAAW,OAAO,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CAAE,CAAC,CACzF;CACA,UAAU,OAAO;CACjB,QAAQ,OAAO,SAAS,OAAO,MAAM;AACzC,CAAC;AACD,MAAa,0BAA0B,OAAO,OAAO;CACjD,SAAS,OAAO,MAAM,mBAAmB;CACzC,QAAQ,OAAO;CACf,SAAS,OAAO;AACpB,CAAC;;AA6ID,IAAa,kBAAb,cAAqC,QAAQ,QAAiD,CAAC,CAC3F,+CACJ,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { Context, Schema } from \"effect\";\nimport { ObjectSubsetSchema } from \"./subsetSchema.js\";\nimport type { AttachmentTypeDef, QueryDocument } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { attachment, Encrypted } from \"@party-stack/ontology-spec/values\";\nimport type { Key, Row } from \"@party-stack/ontology-storage\";\nimport type { ByteInput } from \"@party-stack/ontology-storage/blobs\";\nimport type { Scope, Effect, Stream } from \"effect\";\n\nexport {\n schemaValidationIssues,\n BackendError,\n BackendErrorKindSchema,\n backendErrorStatus,\n ValidationIssueSchema,\n ValidationReportSchema,\n unauthenticated,\n isUnauthenticatedError,\n classifyBackendFailure,\n projectBackendError,\n projectValidationIssue,\n isUnknownActionOutcome,\n} from \"./errors.js\";\nexport type {\n BackendErrorKind,\n ReplicationErrorKind,\n ReplicationError,\n ErrorProjection,\n ErrorProjectionContext,\n ValidationReport,\n ValidationIssue,\n UnauthenticatedError,\n ApplyActionError,\n ValidateActionError,\n LoadSubsetError,\n} from \"./errors.js\";\nimport { BackendError } from \"./errors.js\";\nexport { makeOntologyBackend } from \"./query.js\";\n\nexport interface ObjectSelection {\n readonly subsets: readonly ObjectSubset[];\n}\nexport interface BackendSnapshot {\n /** Region represented by these rows, including any window already applied.\n * Omitted means the requested subset. A broader unwindowed region lets the\n * engine finish filtering/ordering/windowing and optionally cache extra objects.\n * Rows may include residual candidates outside this region; consumers discard\n * them before installing its objects or recording complete coverage.\n */\n readonly fulfilledSubset?: ObjectSubset;\n readonly rows: readonly Row<Record<string, unknown>>[];\n /** Complete for fulfilledSubset (or the request when omitted), including its window. */\n readonly complete: boolean;\n /** Rows fetched from the provider, before adapter-side filtering/windowing.\n * Diagnostic only; omitted when the adapter cannot report it. Not a DB scan count.\n */\n readonly fetchedRows?: number;\n /** Diagnostic provider filter, not a query-capability or coverage contract. */\n readonly pushdown?: SourceQueryPlan;\n /** Position coordinated with this snapshot, when the backend exposes a durable change stream. */\n readonly cursor?: string;\n}\nexport const SourceQueryPlanSchema = Schema.Struct({\n source: Schema.String,\n /** Paths into the request's portable where tree: AND/OR child indices, NOT child 0, [] for the root. */\n predicates: Schema.Array(\n Schema.Struct({\n path: Schema.Array(Schema.Int),\n execution: Schema.Literals([\"source\", \"candidate\", \"adapter\", \"engine\"]),\n })\n ),\n sorting: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n pagination: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n rechecksFilter: Schema.Boolean,\n /** Optional native syntax for raw inspection. Consumers must not parse it to infer execution. */\n native: Schema.optional(Schema.Struct({ language: Schema.String, text: Schema.String })),\n});\nexport type SourceQueryPlan = Schema.Schema.Type<typeof SourceQueryPlanSchema>;\nexport type ObjectChange =\n | {\n readonly kind: \"put\";\n readonly objectType: string;\n readonly key: Key;\n readonly value: Record<string, unknown>;\n }\n | { readonly kind: \"delete\"; readonly objectType: string; readonly key: Key };\nexport interface BackendCommit {\n readonly cursor: string;\n readonly changes: readonly ObjectChange[];\n readonly operationId?: string;\n}\nexport interface BackendChangePage {\n readonly commits: readonly BackendCommit[];\n readonly cursor: string;\n readonly hasMore: boolean;\n}\nexport interface AttachmentUpload {\n readonly attachment: attachment;\n readonly blob: ByteInput;\n readonly target?: AttachmentTypeDef;\n}\nexport interface ActionRequest {\n /** Stable across retries. The source must separately guarantee keyed idempotency. */\n readonly id: string;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n readonly attachmentUploads?: readonly AttachmentUpload[];\n /** Portable replay inputs, preserved across rebases, forwarding and authoritative execution. */\n readonly replay?: { readonly now: string; readonly seed: string };\n}\nexport interface ActionReceipt {\n /** The submitted ActionRequest.id, also supplied as the application's idempotencyKey. */\n readonly operationId: string;\n /** Provider commitment is recorded before local read-back/reconciliation. Parent acceptance is separate. */\n readonly outcome: \"committed\";\n /** Encoded authoritative return value, interpreted using the action returnType. Never a journal payload. */\n readonly result?: unknown;\n readonly cursor?: string;\n /** Optional upstream execution ID. Never substitutes for our stable retry identity. */\n readonly providerOperationId?: string;\n /** Read-back targets for a committed non-journal action. Missing keys\n * means the whole type; an empty list means no modeled object changes.\n * Omission conservatively refreshes every modeled type.\n * Targets are complete unless affectedComplete is explicitly false.\n */\n readonly affected?: readonly {\n readonly objectType: string;\n readonly keys?: readonly Key[];\n }[];\n /** False when these are known targets but automation may have changed other\n * modeled records. Confirmation must not use them as an exhaustive edit list.\n */\n readonly affectedComplete?: boolean;\n readonly attachmentIdMappings?: readonly { readonly localId: string; readonly remoteId: string }[];\n}\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nexport const ObjectChangeSchema = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"put\"),\n objectType: Schema.String,\n key: KeySchema,\n value: Schema.Record(Schema.String, Schema.Unknown),\n }),\n Schema.Struct({ kind: Schema.Literal(\"delete\"), objectType: Schema.String, key: KeySchema }),\n]);\nexport const ActionReceiptSchema = Schema.Struct({\n operationId: Schema.String,\n outcome: Schema.Literal(\"committed\"),\n result: Schema.optional(Schema.Unknown),\n cursor: Schema.optional(Schema.String),\n providerOperationId: Schema.optional(Schema.String),\n affected: Schema.optional(\n Schema.Array(\n Schema.Struct({ objectType: Schema.String, keys: Schema.optional(Schema.Array(KeySchema)) })\n )\n ),\n affectedComplete: Schema.optional(Schema.Boolean),\n attachmentIdMappings: Schema.optional(\n Schema.Array(Schema.Struct({ localId: Schema.String, remoteId: Schema.String }))\n ),\n});\nexport const BackendCommitSchema = Schema.Struct({\n cursor: Schema.String,\n changes: Schema.Array(ObjectChangeSchema),\n operationId: Schema.optional(Schema.String),\n});\nexport const BackendSnapshotSchema = Schema.Struct({\n fulfilledSubset: Schema.optional(ObjectSubsetSchema),\n fetchedRows: Schema.optional(Schema.Number),\n pushdown: Schema.optional(SourceQueryPlanSchema),\n rows: Schema.Array(\n Schema.Struct({ key: KeySchema, value: Schema.Record(Schema.String, Schema.Unknown) })\n ),\n complete: Schema.Boolean,\n cursor: Schema.optional(Schema.String),\n});\nexport const BackendChangePageSchema = Schema.Struct({\n commits: Schema.Array(BackendCommitSchema),\n cursor: Schema.String,\n hasMore: Schema.Boolean,\n});\n\nexport interface BackendAttachments {\n /** Optional authoritative staging before a subsequent action references the handle. */\n readonly stage?: (\n value: attachment,\n bytes: ByteInput,\n options?: { readonly target?: AttachmentTypeDef }\n ) => Effect.Effect<attachment, BackendError>;\n /** Keep the caller Scope open through consumption; closing it cancels an unconsumed download too. */\n readonly read: (\n value: attachment,\n options?: { readonly offset?: number; readonly length?: number }\n ) => Effect.Effect<ByteInput, BackendError, Scope.Scope>;\n readonly metadata: (\n value: attachment,\n options?: { readonly select?: readonly (\"size\" | \"type\" | \"name\" | \"dimensions\")[] }\n ) => Effect.Effect<\n {\n readonly size?: number;\n readonly type?: string;\n readonly name?: string;\n readonly dimensions?: { readonly width: number; readonly height: number };\n },\n BackendError\n >;\n}\nexport {\n EncryptedValueSchema,\n DecryptedValueSchema,\n encryptedPropertyCodec,\n makePropertyDecryption,\n} from \"./encrypted.js\";\nexport type { DecryptedValue } from \"./encrypted.js\";\n\nexport interface BackendEncryptedValues {\n /** Explicit operation. Ordinary record loads return handles and never decrypt them. */\n readonly decrypt: (\n value: Encrypted<unknown>\n ) => Effect.Effect<import(\"./encrypted.js\").DecryptedValue, BackendError>;\n}\n/** One object a watch reports, in the watched subset's object type.\n * - `put`: the object is now in the subset with this complete value.\n * - `exit`: the object left the subset. It may have changed or been deleted; the\n * replica reads it back by primary key to tell which.\n * - `delete`: the object no longer exists anywhere.\n */\nexport type SubsetWatchChange =\n | { readonly kind: \"put\"; readonly key: Key; readonly value: Record<string, unknown> }\n | { readonly kind: \"exit\"; readonly key: Key }\n | { readonly kind: \"delete\"; readonly key: Key };\n/** A reset requests repair after starting/restarting a watch; it does not\n * assert that data changed. Ordinary void hints always invalidate coverage.\n * `changes` describes exactly what changed, so the replica can apply it without\n * reloading the subset. Report only what is certain: a `put` must carry every\n * property; anything less precise must be an invalidation hint instead.\n */\nexport type SubsetWatchEvent = void | \"reset\" | { readonly changes: readonly SubsetWatchChange[] };\n\nexport interface OntologyBackendService {\n readonly name: string;\n /** Stable identity for the source whose cursors and receipts this binding returns. */\n readonly sourceId: string;\n /** Durable keyed idempotency within the configured receipt-retention window:\n * repeated IDs return the recorded result, with\n * conflicting payloads rejected. The guarantee must survive source restart.\n * Merely receiving an ID, or an action being naturally idempotent, is insufficient.\n */\n readonly supportsIdempotency: boolean;\n /**\n * The networks this source is on, such as `\"internet\"`: its replica syncs while a device link\n * reaching one of them is available (the runtime's `links`). Omitted means the internet. A\n * source on the same device (in the same process, a worker or a message port) is on none, so\n * its replicas sync whatever the device's links report.\n */\n readonly networks?: readonly string[];\n /** Indexed bounded local maintenance; the backend owner schedules it. */\n readonly maintenance?: Effect.Effect<void, BackendError>;\n /** Return the request or explicitly describe the region actually fulfilled.\n * Consumers use the shared subset normalizer before applying requested windows.\n */\n readonly loadSubset: (subset: ObjectSubset) => Effect.Effect<BackendSnapshot, BackendError>;\n /** Finite Query IR execution using this binding's trusted context and read path.\n * Provider adapters may evaluate through subset loads; owned storage uses one\n * read transaction. Callers supply query inputs, never authentication context.\n */\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Optional selected committed rows. Closing the Scope releases demand; delivery state expires by policy. */\n readonly subscribeSelection?: (\n selection: ObjectSelection,\n policy?: import(\"./delivery.js\").DeliveryPolicy,\n resume?: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<import(\"./delivery.js\").DeliverySubscription, BackendError, Scope.Scope>;\n readonly acknowledgeDelivery?: (\n position: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<void, BackendError>;\n /** Read-only defaults and edit prefills; never invokes the action. */\n readonly resolveActionParameters?: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Acquire a demand-scoped watch before reading its snapshot. Completion proves\n * registration and buffering are active, even before the returned stream is pulled.\n * The acquiring Scope owns registration and release. Undefined means polling.\n * Reconnect within the same stream must fail or emit reset/invalidation;\n * reacquisition establishes a new readiness boundary for a fresh read.\n * Must cover every change relevant to the requested subset; broader watches\n * may emit extra hints. It does not maintain broader fulfilledSubset coverage.\n */\n readonly watchSubset?: (\n subset: ObjectSubset\n ) => Effect.Effect<Stream.Stream<SubsetWatchEvent, BackendError>, BackendError, Scope.Scope> | undefined;\n /** Recommended demand refresh defaults. Caller configuration wins; healthy\n * watches/journals keep coverage current independently of snapshot age. */\n readonly refresh?: (subset: ObjectSubset) =>\n | {\n readonly pollIntervalMs?: number | false;\n readonly maxCoverageAgeMs?: number;\n }\n | undefined;\n readonly validateAction?: (\n name: string,\n parameters: Record<string, unknown>,\n options?: { readonly knownParameters?: readonly string[] }\n ) => Effect.Effect<import(\"./errors.js\").ValidationReport, BackendError>;\n readonly applyAction: (invocation: ActionRequest) => Effect.Effect<ActionReceipt, BackendError>;\n readonly queryFunction: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<unknown, BackendError>;\n readonly changes?: {\n readonly pull: (options: {\n readonly cursor?: string;\n readonly limit?: number;\n }) => Effect.Effect<BackendChangePage, BackendError>;\n /** Acquire registered, buffered wake-up hints in the caller's Scope before\n * pulling durable changes. Stream consumption does not initiate registration.\n * Call pull to recover changes after reconnect or restart. */\n readonly watch?: Effect.Effect<Stream.Stream<void, BackendError>, BackendError, Scope.Scope>;\n };\n readonly attachments?: BackendAttachments;\n readonly encrypted?: BackendEncryptedValues;\n}\n\n/** Backend protocol independent of TanStack collections and client lifecycle management. */\nexport class OntologyBackend extends Context.Service<OntologyBackend, OntologyBackendService>()(\n \"@party-stack/ontology-backend/OntologyBackend\"\n) {}\n"],"mappings":";;;;;;AA8DA,MAAa,wBAAwB,OAAO,OAAO;CAC/C,QAAQ,OAAO;;CAEf,YAAY,OAAO,MACf,OAAO,OAAO;EACV,MAAM,OAAO,MAAM,OAAO,GAAG;EAC7B,WAAW,OAAO,SAAS;GAAC;GAAU;GAAa;GAAW;EAAQ,CAAC;CAC3E,CAAC,CACL;CACA,SAAS,OAAO,SAAS;EAAC;EAAU;EAAW;EAAU;CAAM,CAAC;CAChE,YAAY,OAAO,SAAS;EAAC;EAAU;EAAW;EAAU;CAAM,CAAC;CACnE,gBAAgB,OAAO;;CAEvB,QAAQ,OAAO,SAAS,OAAO,OAAO;EAAE,UAAU,OAAO;EAAQ,MAAM,OAAO;CAAO,CAAC,CAAC;AAC3F,CAAC;AA2DD,MAAM,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAa,qBAAqB,OAAO,MAAM,CAC3C,OAAO,OAAO;CACV,MAAM,OAAO,QAAQ,KAAK;CAC1B,YAAY,OAAO;CACnB,KAAK;CACL,OAAO,OAAO,OAAO,OAAO,QAAQ,OAAO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CAC3F,+CACJ,CAAC,CAAC,CAAC"}
package/lib/meta.d.ts CHANGED
@@ -1,23 +1,50 @@
1
1
  import { BackendError } from "./errors.js";
2
2
  import { OntologyBackendService } from "./index.js";
3
- import { Effect, Scope } from "effect";
4
- import { OntologyIR } from "@party-stack/ontology-spec";
3
+ import { Effect, Scope, Stream } from "effect";
4
+ import { OmittedDefinition, OntologyIR } from "@party-stack/ontology-spec";
5
5
  //#region src/meta.d.ts
6
6
  export interface PullOptions {
7
7
  /** Omitted selects all definitions of this kind; an empty array selects none. */
8
8
  objectTypeNames?: string[];
9
9
  actionTypeNames?: string[];
10
10
  queryFunctionTypeNames?: string[];
11
- /** App-specific definition edits, applied before the final IR validation. */
12
- transformPulledOntology?: (ontology: OntologyIR) => OntologyIR | Promise<OntologyIR>;
11
+ /** App-specific definition edits, applied before invalid definitions are omitted. */
12
+ transform?: (ontology: OntologyIR) => OntologyIR | Promise<OntologyIR>;
13
+ /** Resolve to `{ ontology, omitted }` instead of the IR alone. */
14
+ includeOmitted?: boolean;
13
15
  }
14
- /** Pull selected definitions directly from a metadata backend, without a replica or UI collections. */
15
- export declare const pull: (backend: Pick<OntologyBackendService, "query">, options?: PullOptions | undefined) => Effect.Effect<OntologyIR, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
16
+ /** Which definitions to take from the metadata, and app-specific edits to apply to them. */
17
+ export type DefinitionSelection = Omit<PullOptions, "includeOmitted">;
18
+ export interface PullResult {
19
+ /** A valid Ontology. */
20
+ readonly ontology: OntologyIR;
21
+ /**
22
+ * Definitions (or action parameter defaults) the provider exposes but the IR could not
23
+ * represent, and why. A caller that needs the complete Ontology treats any entry as a failure.
24
+ */
25
+ readonly omitted: readonly OmittedDefinition[];
26
+ }
27
+ /**
28
+ * Pull selected definitions directly from a metadata backend, without a replica or UI collections.
29
+ *
30
+ * Definitions the IR cannot represent are omitted (see `omitInvalid`) and logged as a warning,
31
+ * rather than failing the pull. Pass `includeOmitted: true` to also receive what was omitted.
32
+ */
33
+ export declare function pull(backend: Pick<OntologyBackendService, "query">, options: PullOptions & {
34
+ readonly includeOmitted: true;
35
+ }): Effect.Effect<PullResult, BackendError>;
36
+ export declare function pull(backend: Pick<OntologyBackendService, "query">, options?: PullOptions): Effect.Effect<OntologyIR, BackendError>;
16
37
  /** Assemble a runtime definition through ordinary metadata queries. Completeness
17
38
  * is the adapter's query contract; this does not invent an atomic provider revision.
18
39
  */
19
40
  export declare const loadDefinition: (backend: Pick<OntologyBackendService, "query">) => Effect.Effect<OntologyIR, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
20
- export declare function makeMetadataBackend(ir: OntologyIR): OntologyBackendService;
41
+ export interface MetadataBackendOptions {
42
+ /** Emits when the definition this backend describes has been replaced. Watches report it as
43
+ * a reset, so a replica of the metadata reloads it. */
44
+ readonly replaced?: Stream.Stream<unknown, BackendError>;
45
+ }
46
+ /** Serve a definition as meta ontology rows. */
47
+ export declare function makeMetadataBackend(ir: OntologyIR, options?: MetadataBackendOptions): OntologyBackendService;
21
48
  export interface OntologyPullConfig<R = never> extends Omit<PullOptions, "queryFunctionTypeNames"> {
22
49
  readonly queryFunctionTypeNames?: string[];
23
50
  readonly backend: Effect.Effect<OntologyBackendService, BackendError, R | Scope.Scope>;
package/lib/meta.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"meta.d.ts","names":[],"sources":["../src/meta.ts"],"mappings":";;;;;iBA4DiB;;EAEb;EACA;EACA;;EAEA,2BAA2B,UAAU,eAAe,aAAa,QAAQ;;;qBAIhE,OAAI,SAAA,KAAA,kCAAA,UAAA,4BAAA,OAAA,OAAA,YAAA;;;;qBA2IJ,iBAAc,SAAa,KAAK,qCAAgC,OAAA,OAAA,YAAA;wBAM7D,oBAAoB,IAAI,aAAa;iBAkFpC,mBAAmB,mBAAmB,KAAK;WAC/C;WACA,SAAS,OAAO,OAAO,wBAAwB,cAAc,IAAI,MAAM"}
1
+ {"version":3,"file":"meta.d.ts","names":[],"sources":["../src/meta.ts"],"mappings":";;;;;iBAiEiB;;EAEb;EACA;EACA;;EAEA,aAAa,UAAU,eAAe,aAAa,QAAQ;;EAE3D;;;YAGQ,sBAAsB,KAAK;iBAEtB;;WAEJ,UAAU;;;;;WAKV,kBAAkB;;;;;;;;wBAyKf,KACZ,SAAS,KAAK,kCACd,SAAS;WAAyB;IACnC,OAAO,OAAO,YAAY;wBACb,KACZ,SAAS,KAAK,kCACd,UAAU,cACX,OAAO,OAAO,YAAY;;;;qBAYhB,iBAAc,SAAa,KAAK,qCAAgC,OAAA,OAAA,YAAA;iBAE5D;;;WAGJ,WAAW,OAAO,gBAAgB;;;wBAG/B,oBACZ,IAAI,YACJ,UAAS,yBACV;iBA0Ec,mBAAmB,mBAAmB,KAAK;WAC/C;WACA,SAAS,OAAO,OAAO,wBAAwB,cAAc,IAAI,MAAM"}
package/lib/meta.js CHANGED
@@ -4,8 +4,8 @@ import { compileObjectSubset, objectSubset } from "./subset.js";
4
4
  import { makeOntologyBackend } from "./query.js";
5
5
  import * as q from "@party-stack/ontology-spec/query";
6
6
  import { and, evaluateQuery, field, inArray } from "@party-stack/ontology-storage";
7
- import { Effect } from "effect";
8
- import { validate } from "@party-stack/ontology-spec";
7
+ import { Effect, Stream } from "effect";
8
+ import { cloneDefinition, omitInvalid, withDefinitionIds, withoutDefaultIds } from "@party-stack/ontology-spec";
9
9
  import metaOntology from "@party-stack/ontology-spec/meta";
10
10
  //#region src/meta.ts
11
11
  function getValueTypes(type) {
@@ -30,15 +30,11 @@ function getActionTypeValueTypes(actionType) {
30
30
  function getQueryFunctionTypeValueTypes(queryFunctionType) {
31
31
  return [...queryFunctionType.parameters.flatMap((parameter) => getValueTypes(parameter.type)), ...getValueTypes(queryFunctionType.returnType)];
32
32
  }
33
- /** Pull selected definitions directly from a metadata backend, without a replica or UI collections. */
34
- const pull = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
33
+ const pullDefinitions = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
35
34
  const select = (objectType, scan) => ({
36
35
  ...objectSubset(objectType, scan),
37
36
  select: metaOntology.objectTypes.find((type) => type.name === objectType).properties.map((property) => q.selectField(property.name, q.field("row", property.name)))
38
37
  });
39
- const load = Effect.fnUntraced(function* (objectType, scan) {
40
- return (yield* backend.query({ select: [q.sub("rows", select(objectType, scan))] })).rows;
41
- });
42
38
  const { objectTypeNames, actionTypeNames, queryFunctionTypeNames } = options;
43
39
  const result = yield* backend.query({ select: [
44
40
  q.sub("objectTypes", select("ObjectType", { where: objectTypeNames && inArray(field("name"), objectTypeNames) })),
@@ -51,13 +47,16 @@ const pull = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
51
47
  })),
52
48
  q.sub("linkTypes", select("LinkType", { where: objectTypeNames && and(inArray(field("source", "objectType"), objectTypeNames), inArray(field("target", "objectType"), objectTypeNames)) })),
53
49
  q.sub("actionTypes", select("ActionType", { where: actionTypeNames && inArray(field("name"), actionTypeNames) })),
54
- q.sub("queryFunctionTypes", select("QueryFunctionType", { where: queryFunctionTypeNames && inArray(field("name"), queryFunctionTypeNames) }))
50
+ q.sub("queryFunctionTypes", select("QueryFunctionType", { where: queryFunctionTypeNames && inArray(field("name"), queryFunctionTypeNames) })),
51
+ q.sub("valueTypes", select("ValueType", {}))
55
52
  ] });
56
- const objectTypes = result.objectTypes;
57
- const descriptors = result.descriptors;
58
- const linkTypes = result.linkTypes;
59
- const actionTypes = result.actionTypes;
60
- const queryFunctionTypes = result.queryFunctionTypes;
53
+ const rows = (value) => value.map((row) => Object.fromEntries(Object.entries(row).filter(([, field]) => field !== void 0)));
54
+ const objectTypes = rows(result.objectTypes);
55
+ const descriptors = rows(result.descriptors);
56
+ const linkTypes = rows(result.linkTypes);
57
+ const actionTypes = rows(result.actionTypes);
58
+ const queryFunctionTypes = rows(result.queryFunctionTypes);
59
+ const valueTypes = new Map(rows(result.valueTypes).map((type) => [type.name, type]));
61
60
  const invalid = (message) => new BackendError({
62
61
  operation: "metadata.pull",
63
62
  kind: "InvalidResponse",
@@ -94,20 +93,23 @@ const pull = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
94
93
  ...queryFunctionTypes.flatMap(getQueryFunctionTypeValueTypes),
95
94
  ...descriptor?.context?.type ? getValueTypes(descriptor.context.type) : []
96
95
  ]));
97
- const types = [];
98
- const loaded = /* @__PURE__ */ new Set();
99
- let pending = valueTypeNames;
100
- while (pending.length) {
101
- const batch = yield* load("ValueType", { where: inArray(field("name"), pending) });
102
- for (const type of batch) {
103
- loaded.add(type.name);
104
- types.push(type);
96
+ const selected = objectTypeNames ?? actionTypeNames ?? queryFunctionTypeNames;
97
+ const types = selected === void 0 ? [...valueTypes.values()] : [];
98
+ if (selected !== void 0) {
99
+ const loaded = /* @__PURE__ */ new Set();
100
+ let pending = valueTypeNames;
101
+ while (pending.length) {
102
+ const missing = pending.filter((name) => !valueTypes.has(name));
103
+ if (missing.length) return yield* invalid(`Missing metadata value types: ${missing.join(", ")}.`);
104
+ const batch = pending.map((name) => valueTypes.get(name));
105
+ for (const type of batch) {
106
+ loaded.add(type.name);
107
+ types.push(type);
108
+ }
109
+ pending = [...new Set(batch.flatMap((type) => getValueTypes(type.type)))].filter((name) => !loaded.has(name));
105
110
  }
106
- const missing = pending.filter((name) => !loaded.has(name));
107
- if (missing.length) return yield* invalid(`Missing metadata value types: ${missing.join(", ")}.`);
108
- pending = [...new Set(batch.flatMap((type) => getValueTypes(type.type)))].filter((name) => !loaded.has(name));
109
111
  }
110
- const pulled = {
112
+ const pulled = withoutDefaultIds({
111
113
  types,
112
114
  objectTypes,
113
115
  linkTypes,
@@ -117,9 +119,9 @@ const pull = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
117
119
  ...descriptor?.description === void 0 ? {} : { description: descriptor.description },
118
120
  ...descriptor?.context === void 0 ? {} : { context: descriptor.context },
119
121
  ...descriptor?.policy === void 0 ? {} : { policy: descriptor.policy }
120
- };
121
- const definition = options.transformPulledOntology ? yield* Effect.tryPromise({
122
- try: async () => options.transformPulledOntology(pulled),
122
+ });
123
+ const definition = options.transform ? yield* Effect.tryPromise({
124
+ try: async () => options.transform(pulled),
123
125
  catch: (cause) => new BackendError({
124
126
  operation: "metadata.pull.transform",
125
127
  kind: "InvalidConfiguration",
@@ -128,36 +130,31 @@ const pull = Effect.fn("Metadata.pull")(function* (backend, options = {}) {
128
130
  cause
129
131
  })
130
132
  }) : pulled;
131
- const valid = validate(definition);
132
- if (valid.kind === "err") return yield* new BackendError({
133
+ const repaired = omitInvalid(definition);
134
+ if (repaired.issues.length) return yield* new BackendError({
133
135
  operation: "metadata.pull",
134
- kind: options.transformPulledOntology ? "InvalidConfiguration" : "InvalidResponse",
136
+ kind: options.transform ? "InvalidConfiguration" : "InvalidResponse",
135
137
  retryable: false,
136
- message: `Pulled ontology is incomplete or invalid: ${valid.value.map((issue) => issue.message).join(" ")}`
138
+ message: `Pulled ontology is invalid: ${repaired.issues.map((issue) => issue.message).join(" ")}`,
139
+ issues: repaired.issues
137
140
  });
138
- return definition;
141
+ if (repaired.omitted.length) yield* Effect.logWarning("Omitted definitions the Ontology IR cannot represent.").pipe(Effect.annotateLogs({ omitted: repaired.omitted.map((entry) => `${entry.name}${entry.parameter ? `.${entry.parameter}` : ""}: ${entry.issues.map((issue) => issue.message).join(" ")}`) }));
142
+ return {
143
+ ontology: repaired.ontology,
144
+ omitted: repaired.omitted
145
+ };
139
146
  });
147
+ function pull(backend, options = {}) {
148
+ const result = pullDefinitions(backend, options);
149
+ return options.includeOmitted ? result : Effect.map(result, (pulled) => pulled.ontology);
150
+ }
140
151
  /** Assemble a runtime definition through ordinary metadata queries. Completeness
141
152
  * is the adapter's query contract; this does not invent an atomic provider revision.
142
153
  */
143
154
  const loadDefinition = (backend) => pull(backend);
144
- function localId(kind, name) {
145
- return `local:${kind}:${encodeURIComponent(name)}`;
146
- }
147
- function makeMetadataBackend(ir) {
148
- ir = structuredClone(ir);
149
- const objectTypes = ir.objectTypes.map((objectType) => ({
150
- ...objectType,
151
- id: localId("ObjectType", objectType.name),
152
- properties: objectType.properties.map((property) => ({
153
- ...property,
154
- id: localId("Property", `${objectType.name}.${property.name}`)
155
- }))
156
- }));
157
- const actionTypes = ir.actionTypes.map((actionType) => ({
158
- ...actionType,
159
- id: localId("ActionType", actionType.name)
160
- }));
155
+ /** Serve a definition as meta ontology rows. */
156
+ function makeMetadataBackend(ir, options = {}) {
157
+ ir = withDefinitionIds(cloneDefinition(ir));
161
158
  return makeOntologyBackend({
162
159
  ir: metaOntology,
163
160
  name: "local-metadata",
@@ -172,10 +169,10 @@ function makeMetadataBackend(ir) {
172
169
  context: ir.context,
173
170
  policy: ir.policy
174
171
  }],
175
- ObjectType: objectTypes,
172
+ ObjectType: ir.objectTypes,
176
173
  ValueType: ir.types,
177
174
  LinkType: ir.linkTypes,
178
- ActionType: actionTypes,
175
+ ActionType: ir.actionTypes,
179
176
  QueryFunctionType: ir.queryFunctionTypes
180
177
  };
181
178
  const type = metaOntology.objectTypes.find((type) => type.name === subset.objectType);
@@ -193,6 +190,7 @@ function makeMetadataBackend(ir) {
193
190
  complete: true
194
191
  });
195
192
  })),
193
+ ...options.replaced && { watchSubset: () => Effect.succeed(Stream.map(options.replaced, () => "reset")) },
196
194
  applyAction: () => Effect.fail(new BackendError({
197
195
  operation: "applyAction",
198
196
  kind: "NotImplemented",
package/lib/meta.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"meta.js","names":[],"sources":["../src/meta.ts"],"sourcesContent":["import { validate } from \"@party-stack/ontology-spec\";\nimport metaOntology from \"@party-stack/ontology-spec/meta\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { and, inArray, field, evaluateQuery } from \"@party-stack/ontology-storage\";\nimport { Effect } from \"effect\";\nimport { makeOntologyBackend } from \"./query.js\";\nimport { compileObjectSubset, objectSubset } from \"./subset.js\";\nimport { BackendError } from \"./index.js\";\nimport type { OntologyBackendService } from \"./index.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type {\n ActionType,\n ObjectType,\n QueryFunctionType,\n TypeDef,\n Ontology as OntologyDescriptor,\n} from \"@party-stack/ontology-spec/meta\";\nimport type { Scope } from \"effect\";\n\nfunction getValueTypes(type: TypeDef): string[] {\n switch (type.kind) {\n case \"list\":\n return getValueTypes(type.value.elementType);\n case \"map\":\n return [...getValueTypes(type.value.keyType), ...getValueTypes(type.value.valueType)];\n case \"optional\":\n return getValueTypes(type.value.type);\n case \"encrypted\":\n return getValueTypes(type.value.type);\n case \"result\":\n return [...getValueTypes(type.value.okType), ...getValueTypes(type.value.errType)];\n case \"struct\":\n return type.value.fields.flatMap((field) => getValueTypes(field.type));\n case \"union\":\n return type.value.variants.flatMap((variant) => getValueTypes(variant.type));\n case \"ref\":\n return [type.value.name];\n default:\n return [];\n }\n}\n\nfunction getObjectTypeValueTypes(objectType: ObjectType): string[] {\n return Array.from(new Set(objectType.properties.flatMap((p) => getValueTypes(p.type))));\n}\n\nfunction getActionTypeValueTypes(actionType: ActionType): string[] {\n return [\n ...actionType.parameters.flatMap((parameter) => getValueTypes(parameter.type)),\n ...(actionType.returnType ? getValueTypes(actionType.returnType) : []),\n ];\n}\n\nfunction getQueryFunctionTypeValueTypes(queryFunctionType: QueryFunctionType): string[] {\n return [\n ...queryFunctionType.parameters.flatMap((parameter) => getValueTypes(parameter.type)),\n ...getValueTypes(queryFunctionType.returnType),\n ];\n}\n\nexport interface PullOptions {\n /** Omitted selects all definitions of this kind; an empty array selects none. */\n objectTypeNames?: string[];\n actionTypeNames?: string[];\n queryFunctionTypeNames?: string[];\n /** App-specific definition edits, applied before the final IR validation. */\n transformPulledOntology?: (ontology: OntologyIR) => OntologyIR | Promise<OntologyIR>;\n}\n\n/** Pull selected definitions directly from a metadata backend, without a replica or UI collections. */\nexport const pull = Effect.fn(\"Metadata.pull\")(function* (\n backend: Pick<OntologyBackendService, \"query\">,\n options: PullOptions = {}\n) {\n const select = (objectType: string, scan: Parameters<typeof objectSubset>[1]) => ({\n ...objectSubset(objectType, scan),\n select: metaOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) => q.selectField(property.name, q.field(\"row\", property.name))),\n });\n const load = Effect.fnUntraced(function* <A>(\n objectType: string,\n scan: Parameters<typeof objectSubset>[1]\n ) {\n const result = yield* backend.query({ select: [q.sub(\"rows\", select(objectType, scan))] });\n return result.rows as A[];\n });\n const { objectTypeNames, actionTypeNames, queryFunctionTypeNames } = options;\n const result = yield* backend.query({\n select: [\n q.sub(\n \"objectTypes\",\n select(\"ObjectType\", { where: objectTypeNames && inArray(field(\"name\"), objectTypeNames) })\n ),\n q.sub(\n \"descriptors\",\n select(\"Ontology\", { orderBy: [{ field: field(\"id\"), direction: \"asc\" }], limit: 2 })\n ),\n q.sub(\n \"linkTypes\",\n select(\"LinkType\", {\n where:\n objectTypeNames &&\n and(\n inArray(field(\"source\", \"objectType\"), objectTypeNames),\n inArray(field(\"target\", \"objectType\"), objectTypeNames)\n ),\n })\n ),\n q.sub(\n \"actionTypes\",\n select(\"ActionType\", { where: actionTypeNames && inArray(field(\"name\"), actionTypeNames) })\n ),\n q.sub(\n \"queryFunctionTypes\",\n select(\"QueryFunctionType\", {\n where: queryFunctionTypeNames && inArray(field(\"name\"), queryFunctionTypeNames),\n })\n ),\n ],\n });\n const objectTypes = result.objectTypes as ObjectType[];\n const descriptors = result.descriptors as OntologyDescriptor[];\n const linkTypes = result.linkTypes as OntologyIR[\"linkTypes\"];\n const actionTypes = result.actionTypes as ActionType[];\n const queryFunctionTypes = result.queryFunctionTypes as QueryFunctionType[];\n const invalid = (message: string) =>\n new BackendError({ operation: \"metadata.pull\", kind: \"InvalidResponse\", retryable: false, message });\n if (descriptors.length !== 1 || descriptors[0]?.id !== \"ontology\")\n return yield* invalid(\"Metadata must expose exactly one Ontology descriptor with id ontology.\");\n const descriptor = descriptors[0];\n\n for (const [kind, requested, definitions] of [\n [\"object types\", objectTypeNames, objectTypes],\n [\"action types\", actionTypeNames, actionTypes],\n [\"query function types\", queryFunctionTypeNames, queryFunctionTypes],\n ] as const) {\n if (!requested) continue;\n const returned = new Set(definitions.map((definition) => definition.name));\n const missing = [...new Set(requested)].filter((name) => !returned.has(name));\n if (missing.length)\n return yield* invalid(`Missing requested metadata ${kind}: ${missing.join(\", \")}.`);\n }\n\n const valueTypeNames = Array.from(\n new Set([\n ...objectTypes.flatMap(getObjectTypeValueTypes),\n ...actionTypes.flatMap(getActionTypeValueTypes),\n ...queryFunctionTypes.flatMap(getQueryFunctionTypeValueTypes),\n ...(descriptor?.context?.type ? getValueTypes(descriptor.context.type) : []),\n ])\n );\n\n const types: OntologyIR[\"types\"] = [];\n const loaded = new Set<string>();\n let pending = valueTypeNames;\n while (pending.length) {\n const batch = yield* load<OntologyIR[\"types\"][number]>(\"ValueType\", {\n where: inArray(field(\"name\"), pending),\n });\n for (const type of batch) {\n loaded.add(type.name);\n types.push(type);\n }\n const missing = pending.filter((name) => !loaded.has(name));\n if (missing.length) return yield* invalid(`Missing metadata value types: ${missing.join(\", \")}.`);\n pending = [...new Set(batch.flatMap((type) => getValueTypes(type.type)))].filter(\n (name) => !loaded.has(name)\n );\n }\n\n const pulled: OntologyIR = {\n types,\n objectTypes,\n linkTypes,\n actionTypes,\n queryFunctionTypes,\n ...(descriptor?.displayName === undefined ? {} : { displayName: descriptor.displayName }),\n ...(descriptor?.description === undefined ? {} : { description: descriptor.description }),\n ...(descriptor?.context === undefined ? {} : { context: descriptor.context }),\n ...(descriptor?.policy === undefined ? {} : { policy: descriptor.policy }),\n };\n const definition = options.transformPulledOntology\n ? yield* Effect.tryPromise({\n try: async () => options.transformPulledOntology!(pulled),\n catch: (cause) =>\n new BackendError({\n operation: \"metadata.pull.transform\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: cause instanceof Error ? cause.message : \"The ontology transform failed.\",\n cause,\n }),\n })\n : pulled;\n const valid = validate(definition);\n if (valid.kind === \"err\")\n return yield* new BackendError({\n operation: \"metadata.pull\",\n kind: options.transformPulledOntology ? \"InvalidConfiguration\" : \"InvalidResponse\",\n retryable: false,\n message: `Pulled ontology is incomplete or invalid: ${valid.value.map((issue) => issue.message).join(\" \")}`,\n });\n return definition;\n});\n\n/** Assemble a runtime definition through ordinary metadata queries. Completeness\n * is the adapter's query contract; this does not invent an atomic provider revision.\n */\nexport const loadDefinition = (backend: Pick<OntologyBackendService, \"query\">) => pull(backend);\n\nfunction localId(kind: \"ActionType\" | \"ObjectType\" | \"Property\", name: string): string {\n return `local:${kind}:${encodeURIComponent(name)}`;\n}\n\nexport function makeMetadataBackend(ir: OntologyIR): OntologyBackendService {\n ir = structuredClone(ir);\n const objectTypes: ObjectType[] = ir.objectTypes.map((objectType) => ({\n ...objectType,\n id: localId(\"ObjectType\", objectType.name),\n properties: objectType.properties.map((property) => ({\n ...property,\n id: localId(\"Property\", `${objectType.name}.${property.name}`),\n })),\n }));\n const actionTypes: ActionType[] = ir.actionTypes.map((actionType) => ({\n ...actionType,\n id: localId(\"ActionType\", actionType.name),\n }));\n\n return makeOntologyBackend({\n ir: metaOntology,\n name: \"local-metadata\",\n sourceId: \"local-metadata\",\n supportsIdempotency: false,\n loadSubset: (request) =>\n Effect.flatMap(compileObjectSubset(metaOntology, request), (subset) =>\n Effect.suspend(() => {\n const rows: Record<string, readonly object[]> = {\n Ontology: [\n {\n id: \"ontology\",\n displayName: ir.displayName,\n description: ir.description,\n context: ir.context,\n policy: ir.policy,\n },\n ],\n ObjectType: objectTypes,\n ValueType: ir.types,\n LinkType: ir.linkTypes,\n ActionType: actionTypes,\n QueryFunctionType: ir.queryFunctionTypes,\n };\n const type = metaOntology.objectTypes.find((type) => type.name === subset.objectType);\n if (!type)\n return Effect.fail(\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Unknown metadata object type.\",\n retryable: false,\n })\n );\n return Effect.succeed({\n rows: evaluateQuery(\n rows[subset.objectType]!.map((row) => ({\n key: (row as Record<string, unknown>)[type.primaryKey] as string,\n value: row as Record<string, unknown>,\n })),\n subset.query ?? {}\n ),\n complete: true,\n });\n })\n ),\n applyAction: () =>\n Effect.fail(\n new BackendError({\n operation: \"applyAction\",\n kind: \"NotImplemented\",\n message: \"Metadata is read-only.\",\n retryable: false,\n })\n ),\n queryFunction: () =>\n Effect.fail(\n new BackendError({\n operation: \"queryFunction\",\n kind: \"NotImplemented\",\n message: \"Local metadata has no query functions.\",\n retryable: false,\n })\n ),\n });\n}\n\nexport interface OntologyPullConfig<R = never> extends Omit<PullOptions, \"queryFunctionTypeNames\"> {\n readonly queryFunctionTypeNames?: string[];\n readonly backend: Effect.Effect<OntologyBackendService, BackendError, R | Scope.Scope>;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAS,cAAc,MAAyB;CAC5C,QAAQ,KAAK,MAAb;EACI,KAAK,QACD,OAAO,cAAc,KAAK,MAAM,WAAW;EAC/C,KAAK,OACD,OAAO,CAAC,GAAG,cAAc,KAAK,MAAM,OAAO,GAAG,GAAG,cAAc,KAAK,MAAM,SAAS,CAAC;EACxF,KAAK,YACD,OAAO,cAAc,KAAK,MAAM,IAAI;EACxC,KAAK,aACD,OAAO,cAAc,KAAK,MAAM,IAAI;EACxC,KAAK,UACD,OAAO,CAAC,GAAG,cAAc,KAAK,MAAM,MAAM,GAAG,GAAG,cAAc,KAAK,MAAM,OAAO,CAAC;EACrF,KAAK,UACD,OAAO,KAAK,MAAM,OAAO,SAAS,UAAU,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,cAAc;GACjB,MAAM,OAA0C;IAC5C,UAAU,CACN;KACI,IAAI;KACJ,aAAa,GAAG;KAChB,aAAa,GAAG;KAChB,SAAS,GAAG;KACZ,QAAQ,GAAG;IACf,CACJ;IACA,YAAY;IACZ,WAAW,GAAG;IACd,UAAU,GAAG;IACb,YAAY;IACZ,mBAAmB,GAAG;GAC1B;GACA,MAAM,OAAO,aAAa,YAAY,MAAM,SAAS,KAAK,SAAS,OAAO,UAAU;GACpF,IAAI,CAAC,MACD,OAAO,OAAO,KACV,IAAI,aAAa;IACb,WAAW;IACX,MAAM;IACN,SAAS;IACT,WAAW;GACf,CAAC,CACL;GACJ,OAAO,OAAO,QAAQ;IAClB,MAAM,cACF,KAAK,OAAO,WAAW,CAAE,KAAK,SAAS;KACnC,KAAM,IAAgC,KAAK;KAC3C,OAAO;IACX,EAAE,GACF,OAAO,SAAS,CAAC,CACrB;IACA,UAAU;GACd,CAAC;EACL,CAAC,CACL;EACJ,mBACI,OAAO,KACH,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,SAAS;GACT,WAAW;EACf,CAAC,CACL;EACJ,qBACI,OAAO,KACH,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,SAAS;GACT,WAAW;EACf,CAAC,CACL;CACR,CAAC;AACL"}
1
+ {"version":3,"file":"meta.js","names":[],"sources":["../src/meta.ts"],"sourcesContent":["import {\n cloneDefinition,\n omitInvalid,\n withDefinitionIds,\n withoutDefaultIds,\n} from \"@party-stack/ontology-spec\";\nimport metaOntology from \"@party-stack/ontology-spec/meta\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { and, inArray, field, evaluateQuery } from \"@party-stack/ontology-storage\";\nimport { Effect, Stream } from \"effect\";\nimport { makeOntologyBackend } from \"./query.js\";\nimport { compileObjectSubset, objectSubset } from \"./subset.js\";\nimport { BackendError } from \"./index.js\";\nimport type { OntologyBackendService, SubsetWatchEvent } from \"./index.js\";\nimport type { OmittedDefinition, OntologyIR } from \"@party-stack/ontology-spec\";\nimport type {\n ActionType,\n ObjectType,\n QueryFunctionType,\n TypeDef,\n Ontology as OntologyDescriptor,\n} from \"@party-stack/ontology-spec/meta\";\nimport type { Scope } from \"effect\";\n\nfunction getValueTypes(type: TypeDef): string[] {\n switch (type.kind) {\n case \"list\":\n return getValueTypes(type.value.elementType);\n case \"map\":\n return [...getValueTypes(type.value.keyType), ...getValueTypes(type.value.valueType)];\n case \"optional\":\n return getValueTypes(type.value.type);\n case \"encrypted\":\n return getValueTypes(type.value.type);\n case \"result\":\n return [...getValueTypes(type.value.okType), ...getValueTypes(type.value.errType)];\n case \"struct\":\n return type.value.fields.flatMap((field) => getValueTypes(field.type));\n case \"union\":\n return type.value.variants.flatMap((variant) => getValueTypes(variant.type));\n case \"ref\":\n return [type.value.name];\n default:\n return [];\n }\n}\n\nfunction getObjectTypeValueTypes(objectType: ObjectType): string[] {\n return Array.from(new Set(objectType.properties.flatMap((p) => getValueTypes(p.type))));\n}\n\nfunction getActionTypeValueTypes(actionType: ActionType): string[] {\n return [\n ...actionType.parameters.flatMap((parameter) => getValueTypes(parameter.type)),\n ...(actionType.returnType ? getValueTypes(actionType.returnType) : []),\n ];\n}\n\nfunction getQueryFunctionTypeValueTypes(queryFunctionType: QueryFunctionType): string[] {\n return [\n ...queryFunctionType.parameters.flatMap((parameter) => getValueTypes(parameter.type)),\n ...getValueTypes(queryFunctionType.returnType),\n ];\n}\n\nexport interface PullOptions {\n /** Omitted selects all definitions of this kind; an empty array selects none. */\n objectTypeNames?: string[];\n actionTypeNames?: string[];\n queryFunctionTypeNames?: string[];\n /** App-specific definition edits, applied before invalid definitions are omitted. */\n transform?: (ontology: OntologyIR) => OntologyIR | Promise<OntologyIR>;\n /** Resolve to `{ ontology, omitted }` instead of the IR alone. */\n includeOmitted?: boolean;\n}\n/** Which definitions to take from the metadata, and app-specific edits to apply to them. */\nexport type DefinitionSelection = Omit<PullOptions, \"includeOmitted\">;\n\nexport interface PullResult {\n /** A valid Ontology. */\n readonly ontology: OntologyIR;\n /**\n * Definitions (or action parameter defaults) the provider exposes but the IR could not\n * represent, and why. A caller that needs the complete Ontology treats any entry as a failure.\n */\n readonly omitted: readonly OmittedDefinition[];\n}\n\nconst pullDefinitions = Effect.fn(\"Metadata.pull\")(function* (\n backend: Pick<OntologyBackendService, \"query\">,\n options: PullOptions = {}\n) {\n const select = (objectType: string, scan: Parameters<typeof objectSubset>[1]) => ({\n ...objectSubset(objectType, scan),\n select: metaOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) => q.selectField(property.name, q.field(\"row\", property.name))),\n });\n const { objectTypeNames, actionTypeNames, queryFunctionTypeNames } = options;\n const result = yield* backend.query({\n select: [\n q.sub(\n \"objectTypes\",\n select(\"ObjectType\", { where: objectTypeNames && inArray(field(\"name\"), objectTypeNames) })\n ),\n q.sub(\n \"descriptors\",\n select(\"Ontology\", { orderBy: [{ field: field(\"id\"), direction: \"asc\" }], limit: 2 })\n ),\n q.sub(\n \"linkTypes\",\n select(\"LinkType\", {\n where:\n objectTypeNames &&\n and(\n inArray(field(\"source\", \"objectType\"), objectTypeNames),\n inArray(field(\"target\", \"objectType\"), objectTypeNames)\n ),\n })\n ),\n q.sub(\n \"actionTypes\",\n select(\"ActionType\", { where: actionTypeNames && inArray(field(\"name\"), actionTypeNames) })\n ),\n q.sub(\n \"queryFunctionTypes\",\n select(\"QueryFunctionType\", {\n where: queryFunctionTypeNames && inArray(field(\"name\"), queryFunctionTypeNames),\n })\n ),\n // Value types are referenced by name from inside other definitions' types, which a\n // query cannot follow. There are few, so read them all in the same request and keep\n // the ones the selection uses.\n q.sub(\"valueTypes\", select(\"ValueType\", {})),\n ],\n });\n // A projection reads every meta property; one a row does not set is absent, not undefined.\n const rows = <A>(value: unknown) =>\n (value as Record<string, unknown>[]).map(\n (row) => Object.fromEntries(Object.entries(row).filter(([, field]) => field !== undefined)) as A\n );\n const objectTypes = rows<ObjectType>(result.objectTypes);\n const descriptors = rows<OntologyDescriptor>(result.descriptors);\n const linkTypes = rows<OntologyIR[\"linkTypes\"][number]>(result.linkTypes);\n const actionTypes = rows<ActionType>(result.actionTypes);\n const queryFunctionTypes = rows<QueryFunctionType>(result.queryFunctionTypes);\n const valueTypes = new Map(\n rows<OntologyIR[\"types\"][number]>(result.valueTypes).map((type) => [type.name, type])\n );\n const invalid = (message: string) =>\n new BackendError({ operation: \"metadata.pull\", kind: \"InvalidResponse\", retryable: false, message });\n if (descriptors.length !== 1 || descriptors[0]?.id !== \"ontology\")\n return yield* invalid(\"Metadata must expose exactly one Ontology descriptor with id ontology.\");\n const descriptor = descriptors[0];\n\n for (const [kind, requested, definitions] of [\n [\"object types\", objectTypeNames, objectTypes],\n [\"action types\", actionTypeNames, actionTypes],\n [\"query function types\", queryFunctionTypeNames, queryFunctionTypes],\n ] as const) {\n if (!requested) continue;\n const returned = new Set(definitions.map((definition) => definition.name));\n const missing = [...new Set(requested)].filter((name) => !returned.has(name));\n if (missing.length)\n return yield* invalid(`Missing requested metadata ${kind}: ${missing.join(\", \")}.`);\n }\n\n const valueTypeNames = Array.from(\n new Set([\n ...objectTypes.flatMap(getObjectTypeValueTypes),\n ...actionTypes.flatMap(getActionTypeValueTypes),\n ...queryFunctionTypes.flatMap(getQueryFunctionTypeValueTypes),\n ...(descriptor?.context?.type ? getValueTypes(descriptor.context.type) : []),\n ])\n );\n\n // Everything when nothing is selected, so a definition round-trips whole; otherwise the\n // value types the selection uses, and the ones those use.\n const selected = objectTypeNames ?? actionTypeNames ?? queryFunctionTypeNames;\n const types: OntologyIR[\"types\"] = selected === undefined ? [...valueTypes.values()] : [];\n if (selected !== undefined) {\n const loaded = new Set<string>();\n let pending = valueTypeNames;\n while (pending.length) {\n const missing = pending.filter((name) => !valueTypes.has(name));\n if (missing.length) return yield* invalid(`Missing metadata value types: ${missing.join(\", \")}.`);\n const batch = pending.map((name) => valueTypes.get(name)!);\n for (const type of batch) {\n loaded.add(type.name);\n types.push(type);\n }\n pending = [...new Set(batch.flatMap((type) => getValueTypes(type.type)))].filter(\n (name) => !loaded.has(name)\n );\n }\n }\n // Rows carry every id; one equal to its default is left out, so a definition reads back as\n // it was written. Provider ids are kept.\n const pulled: OntologyIR = withoutDefaultIds({\n types,\n objectTypes,\n linkTypes,\n actionTypes,\n queryFunctionTypes,\n ...(descriptor?.displayName === undefined ? {} : { displayName: descriptor.displayName }),\n ...(descriptor?.description === undefined ? {} : { description: descriptor.description }),\n ...(descriptor?.context === undefined ? {} : { context: descriptor.context }),\n ...(descriptor?.policy === undefined ? {} : { policy: descriptor.policy }),\n });\n const definition = options.transform\n ? yield* Effect.tryPromise({\n try: async () => options.transform!(pulled),\n catch: (cause) =>\n new BackendError({\n operation: \"metadata.pull.transform\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: cause instanceof Error ? cause.message : \"The ontology transform failed.\",\n cause,\n }),\n })\n : pulled;\n // One definition the IR cannot represent should not make the whole Ontology unusable.\n const repaired = omitInvalid(definition);\n if (repaired.issues.length)\n return yield* new BackendError({\n operation: \"metadata.pull\",\n kind: options.transform ? \"InvalidConfiguration\" : \"InvalidResponse\",\n retryable: false,\n message: `Pulled ontology is invalid: ${repaired.issues.map((issue) => issue.message).join(\" \")}`,\n issues: repaired.issues,\n });\n if (repaired.omitted.length)\n yield* Effect.logWarning(\"Omitted definitions the Ontology IR cannot represent.\").pipe(\n Effect.annotateLogs({\n // With the reason, so an omission can be fixed at its source without a debugger.\n omitted: repaired.omitted.map(\n (entry) =>\n `${entry.name}${entry.parameter ? `.${entry.parameter}` : \"\"}: ${entry.issues\n .map((issue) => issue.message)\n .join(\" \")}`\n ),\n })\n );\n const pulledResult: PullResult = { ontology: repaired.ontology, omitted: repaired.omitted };\n return pulledResult;\n});\n\n/**\n * Pull selected definitions directly from a metadata backend, without a replica or UI collections.\n *\n * Definitions the IR cannot represent are omitted (see `omitInvalid`) and logged as a warning,\n * rather than failing the pull. Pass `includeOmitted: true` to also receive what was omitted.\n */\nexport function pull(\n backend: Pick<OntologyBackendService, \"query\">,\n options: PullOptions & { readonly includeOmitted: true }\n): Effect.Effect<PullResult, BackendError>;\nexport function pull(\n backend: Pick<OntologyBackendService, \"query\">,\n options?: PullOptions\n): Effect.Effect<OntologyIR, BackendError>;\nexport function pull(\n backend: Pick<OntologyBackendService, \"query\">,\n options: PullOptions = {}\n): Effect.Effect<OntologyIR | PullResult, BackendError> {\n const result = pullDefinitions(backend, options);\n return options.includeOmitted ? result : Effect.map(result, (pulled) => pulled.ontology);\n}\n\n/** Assemble a runtime definition through ordinary metadata queries. Completeness\n * is the adapter's query contract; this does not invent an atomic provider revision.\n */\nexport const loadDefinition = (backend: Pick<OntologyBackendService, \"query\">) => pull(backend);\n\nexport interface MetadataBackendOptions {\n /** Emits when the definition this backend describes has been replaced. Watches report it as\n * a reset, so a replica of the metadata reloads it. */\n readonly replaced?: Stream.Stream<unknown, BackendError>;\n}\n/** Serve a definition as meta ontology rows. */\nexport function makeMetadataBackend(\n ir: OntologyIR,\n options: MetadataBackendOptions = {}\n): OntologyBackendService {\n // Meta rows always carry ids; a definition without them is given its defaults.\n ir = withDefinitionIds(cloneDefinition(ir));\n\n return makeOntologyBackend({\n ir: metaOntology,\n name: \"local-metadata\",\n sourceId: \"local-metadata\",\n supportsIdempotency: false,\n loadSubset: (request) =>\n Effect.flatMap(compileObjectSubset(metaOntology, request), (subset) =>\n Effect.suspend(() => {\n const rows: Record<string, readonly object[]> = {\n Ontology: [\n {\n id: \"ontology\",\n displayName: ir.displayName,\n description: ir.description,\n context: ir.context,\n policy: ir.policy,\n },\n ],\n ObjectType: ir.objectTypes,\n ValueType: ir.types,\n LinkType: ir.linkTypes,\n ActionType: ir.actionTypes,\n QueryFunctionType: ir.queryFunctionTypes,\n };\n const type = metaOntology.objectTypes.find((type) => type.name === subset.objectType);\n if (!type)\n return Effect.fail(\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Unknown metadata object type.\",\n retryable: false,\n })\n );\n return Effect.succeed({\n rows: evaluateQuery(\n rows[subset.objectType]!.map((row) => ({\n key: (row as Record<string, unknown>)[type.primaryKey] as string,\n value: row as Record<string, unknown>,\n })),\n subset.query ?? {}\n ),\n complete: true,\n });\n })\n ),\n ...(options.replaced && {\n watchSubset: () => Effect.succeed(Stream.map(options.replaced!, (): SubsetWatchEvent => \"reset\")),\n }),\n applyAction: () =>\n Effect.fail(\n new BackendError({\n operation: \"applyAction\",\n kind: \"NotImplemented\",\n message: \"Metadata is read-only.\",\n retryable: false,\n })\n ),\n queryFunction: () =>\n Effect.fail(\n new BackendError({\n operation: \"queryFunction\",\n kind: \"NotImplemented\",\n message: \"Local metadata has no query functions.\",\n retryable: false,\n })\n ),\n });\n}\n\nexport interface OntologyPullConfig<R = never> extends Omit<PullOptions, \"queryFunctionTypeNames\"> {\n readonly queryFunctionTypeNames?: string[];\n readonly backend: Effect.Effect<OntologyBackendService, BackendError, R | Scope.Scope>;\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAS,cAAc,MAAyB;CAC5C,QAAQ,KAAK,MAAb;EACI,KAAK,QACD,OAAO,cAAc,KAAK,MAAM,WAAW;EAC/C,KAAK,OACD,OAAO,CAAC,GAAG,cAAc,KAAK,MAAM,OAAO,GAAG,GAAG,cAAc,KAAK,MAAM,SAAS,CAAC;EACxF,KAAK,YACD,OAAO,cAAc,KAAK,MAAM,IAAI;EACxC,KAAK,aACD,OAAO,cAAc,KAAK,MAAM,IAAI;EACxC,KAAK,UACD,OAAO,CAAC,GAAG,cAAc,KAAK,MAAM,MAAM,GAAG,GAAG,cAAc,KAAK,MAAM,OAAO,CAAC;EACrF,KAAK,UACD,OAAO,KAAK,MAAM,OAAO,SAAS,UAAU,cAAc,MAAM,IAAI,CAAC;EACzE,KAAK,SACD,OAAO,KAAK,MAAM,SAAS,SAAS,YAAY,cAAc,QAAQ,IAAI,CAAC;EAC/E,KAAK,OACD,OAAO,CAAC,KAAK,MAAM,IAAI;EAC3B,SACI,OAAO,CAAC;CAChB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ACN,OAAO;aACY,KAAK;aAAc,OAAO;mBAC9C;EAEJ,IAAI,oBAAoB,KAAK,MAAM,OAAO,OAAO,qCAAqC;EACtF,WACI,oBACA,QAAQ,QACT,OAAO;aAA2B,KAAK;aAAc,OAAO;OAA6B;;iBAE/E,yBAAyB;EACtC,IAAI,oBAAoB,OAAO,0BAA0B,OAAO,aAAa;;EAE7E,MACI,oBACA,KAAK,KACL;aAA6B;aAAkC;QAChE,OAAO,aAAa;EACvB,OAAO,oBAAoB,KAAK,MAAM,OAAO,aAAa;;;iBAG7C,gCAAgC;EAC7C,YAAY,oBAAoB,OAAO,QAAQ,OAAO,aAAa;;iBAEtD;WACJ,IAAI;WACJ,OAAO,GAAG,GAAG,GAClB,OAAO,IAAI,yBAAyB,OAAO,OAAO,GAAG,GAAG,OACvD,OAAO,OAAO,GAAG,IAAI,cAAc;;WAE/B,cAAc,GAAG,GAAG,GACzB,OAAO,IAAI,4BAA4B,OAAO,OAAO,GAAG,GAAG,OAC1D,OAAO,OAAO,GAAG,IAAI,cAAc;;iBAE3B;WACJ;WACA,IAAI;WACJ,QAAQ;WACR,sDAAsD;;WAEtD;WACA,WAAW;;WAEX;aAAqB;aAA8B;;;WAEnD;;;;WAIA;aAAiC;;WACjC,UAAU,SACf,gBAEK,IAAI,kBAAkB,YAAY,kBAAkB,OAAO,gBAAgB;WAG3E,iBAAiB,SACtB,gBAGQ,IAAI,sBACJ,YAAY,4BACX,OAAO,gBAAgB;WAG3B,cAAc;WACd,YAAY;;WAEZ,kBACL,YAAY,kBACX,OAAO,OAAO,OAAO,aAAa,eAAe;;iBAEzC,4BAA4B;WAChC,SAAS;;;qBA0CT,mBAAgB,SAAA,wBAAA,OAAA,OAAA,qBAAA,iWAAA,MAAA"}
package/lib/owned.js CHANGED
@@ -13,6 +13,7 @@ import { byteSource, digestBytes } from "@party-stack/ontology-storage/blobs";
13
13
  import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
14
14
  import { Table, gt } from "@party-stack/ontology-storage/tables";
15
15
  //#region src/owned.ts
16
+ const selectionIdentity = Table.make({ name: "delivery-selection" });
16
17
  const fault = (operation, kind, message, cause) => new BackendError({
17
18
  operation,
18
19
  kind,
@@ -438,7 +439,7 @@ const makeOwnedBackend = Effect.fnUntraced(function* (options) {
438
439
  },
439
440
  resume,
440
441
  binding: JSON.stringify([source, schemaHash]),
441
- identity: JSON.stringify(selection),
442
+ identity: selectionIdentity.encode(selection),
442
443
  changes: PubSub.subscribe(wakes).pipe(Effect.map(Stream.fromSubscription)),
443
444
  capture: (_tx, emit) => boundary(Effect.gen(function* () {
444
445
  for (const subset of subsets) {