@prisma-next/framework-components 0.12.0 → 0.13.0-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/authoring.d.mts +2 -2
  2. package/dist/authoring.mjs +2 -2
  3. package/dist/{codec-BFOsuHKK.d.mts → codec-DCQAerzB.d.mts} +1 -1
  4. package/dist/{codec-BFOsuHKK.d.mts.map → codec-DCQAerzB.d.mts.map} +1 -1
  5. package/dist/codec.d.mts +1 -1
  6. package/dist/codec.d.mts.map +1 -1
  7. package/dist/components.d.mts +1 -1
  8. package/dist/components.mjs +1 -1
  9. package/dist/components.mjs.map +1 -1
  10. package/dist/control.d.mts +85 -13
  11. package/dist/control.d.mts.map +1 -1
  12. package/dist/control.mjs +89 -7
  13. package/dist/control.mjs.map +1 -1
  14. package/dist/{emission-types-CMv_053d.d.mts → emission-types-vfpSTe63.d.mts} +2 -2
  15. package/dist/{emission-types-CMv_053d.d.mts.map → emission-types-vfpSTe63.d.mts.map} +1 -1
  16. package/dist/emission.d.mts +3 -3
  17. package/dist/execution.d.mts +1 -1
  18. package/dist/execution.d.mts.map +1 -1
  19. package/dist/execution.mjs +1 -1
  20. package/dist/{framework-authoring-DcEZ5Lin.mjs → framework-authoring-CnwPJCO4.mjs} +76 -5
  21. package/dist/framework-authoring-CnwPJCO4.mjs.map +1 -0
  22. package/dist/framework-authoring-R0TYCkvG.d.mts +380 -0
  23. package/dist/framework-authoring-R0TYCkvG.d.mts.map +1 -0
  24. package/dist/{framework-components-CuoUhyB5.d.mts → framework-components-DDQXmW0b.d.mts} +6 -5
  25. package/dist/{framework-components-CuoUhyB5.d.mts.map → framework-components-DDQXmW0b.d.mts.map} +1 -1
  26. package/dist/{framework-components-FdqmlGUj.mjs → framework-components-DbCS57go.mjs} +1 -1
  27. package/dist/{framework-components-FdqmlGUj.mjs.map → framework-components-DbCS57go.mjs.map} +1 -1
  28. package/dist/ir.d.mts +20 -18
  29. package/dist/ir.d.mts.map +1 -1
  30. package/dist/ir.mjs +17 -14
  31. package/dist/ir.mjs.map +1 -1
  32. package/dist/{psl-ast-BDXL7iCg.d.mts → psl-ast-Cn50B-UG.d.mts} +90 -18
  33. package/dist/psl-ast-Cn50B-UG.d.mts.map +1 -0
  34. package/dist/psl-ast.d.mts +37 -2
  35. package/dist/psl-ast.d.mts.map +1 -0
  36. package/dist/psl-ast.mjs +222 -4
  37. package/dist/psl-ast.mjs.map +1 -1
  38. package/dist/runtime.d.mts +1 -1
  39. package/dist/runtime.d.mts.map +1 -1
  40. package/dist/runtime.mjs.map +1 -1
  41. package/dist/{types-import-spec-BxI5cSQy.d.mts → types-import-spec-DRKzrJ20.d.mts} +1 -1
  42. package/dist/{types-import-spec-BxI5cSQy.d.mts.map → types-import-spec-DRKzrJ20.d.mts.map} +1 -1
  43. package/dist/utils.mjs.map +1 -1
  44. package/package.json +9 -9
  45. package/src/control/control-instances.ts +15 -5
  46. package/src/control/control-migration-types.ts +20 -2
  47. package/src/control/control-result-types.ts +4 -1
  48. package/src/control/control-stack.ts +123 -4
  49. package/src/control/psl-ast.ts +234 -34
  50. package/src/control/psl-extension-block-validator.ts +324 -0
  51. package/src/control/verifier-disposition.ts +62 -0
  52. package/src/exports/authoring.ts +16 -0
  53. package/src/exports/control.ts +7 -0
  54. package/src/exports/psl-ast.ts +2 -0
  55. package/src/ir/namespace.ts +15 -13
  56. package/src/ir/storage.ts +8 -7
  57. package/src/shared/framework-authoring.ts +215 -2
  58. package/src/shared/framework-components.ts +2 -0
  59. package/src/shared/psl-extension-block.ts +184 -0
  60. package/dist/framework-authoring-BPPe9C9D.d.mts +0 -183
  61. package/dist/framework-authoring-BPPe9C9D.d.mts.map +0 -1
  62. package/dist/framework-authoring-DcEZ5Lin.mjs.map +0 -1
  63. package/dist/psl-ast-BDXL7iCg.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"psl-ast.mjs","names":[],"sources":["../src/control/psl-ast.ts"],"sourcesContent":["export interface PslPosition {\n readonly offset: number;\n readonly line: number;\n readonly column: number;\n}\n\nexport interface PslSpan {\n readonly start: PslPosition;\n readonly end: PslPosition;\n}\n\nexport type PslDiagnosticCode =\n | 'PSL_UNTERMINATED_BLOCK'\n | 'PSL_UNSUPPORTED_TOP_LEVEL_BLOCK'\n | 'PSL_INVALID_NAMESPACE_BLOCK'\n | 'PSL_INVALID_ATTRIBUTE_SYNTAX'\n | 'PSL_INVALID_MODEL_MEMBER'\n | 'PSL_UNSUPPORTED_MODEL_ATTRIBUTE'\n | 'PSL_UNSUPPORTED_FIELD_ATTRIBUTE'\n | 'PSL_INVALID_RELATION_ATTRIBUTE'\n | 'PSL_INVALID_REFERENTIAL_ACTION'\n | 'PSL_INVALID_DEFAULT_VALUE'\n | 'PSL_INVALID_ENUM_MEMBER'\n | 'PSL_INVALID_TYPES_MEMBER'\n | 'PSL_INVALID_QUALIFIED_TYPE';\n\nexport interface PslDiagnostic {\n readonly code: PslDiagnosticCode;\n readonly message: string;\n readonly sourceId: string;\n readonly span: PslSpan;\n}\n\nexport interface PslDefaultFunctionValue {\n readonly kind: 'function';\n readonly name: 'autoincrement' | 'now';\n}\n\nexport interface PslDefaultLiteralValue {\n readonly kind: 'literal';\n readonly value: string | number | boolean;\n}\n\nexport type PslDefaultValue = PslDefaultFunctionValue | PslDefaultLiteralValue;\n\nexport type PslAttributeTarget = 'field' | 'model' | 'enum' | 'namedType';\n\nexport interface PslAttributePositionalArgument {\n readonly kind: 'positional';\n readonly value: string;\n readonly span: PslSpan;\n}\n\nexport interface PslAttributeNamedArgument {\n readonly kind: 'named';\n readonly name: string;\n readonly value: string;\n readonly span: PslSpan;\n}\n\nexport type PslAttributeArgument = PslAttributePositionalArgument | PslAttributeNamedArgument;\n\nexport interface PslTypeConstructorCall {\n readonly kind: 'typeConstructor';\n readonly path: readonly string[];\n readonly args: readonly PslAttributeArgument[];\n readonly span: PslSpan;\n}\n\nexport interface PslAttribute {\n readonly kind: 'attribute';\n readonly target: PslAttributeTarget;\n readonly name: string;\n readonly args: readonly PslAttributeArgument[];\n readonly span: PslSpan;\n}\n\nexport type PslReferentialAction = string;\n\nexport type PslFieldAttribute = PslAttribute;\n\nexport interface PslField {\n readonly kind: 'field';\n readonly name: string;\n /** Unqualified type name, e.g. `\"User\"` for both `User` and `auth.User`. */\n readonly typeName: string;\n /** Namespace qualifier from a dot-qualified type reference, e.g. `\"auth\"` for `auth.User`. Absent for unqualified types. */\n readonly typeNamespaceId?: string;\n readonly typeConstructor?: PslTypeConstructorCall;\n readonly optional: boolean;\n readonly list: boolean;\n readonly typeRef?: string;\n readonly attributes: readonly PslFieldAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslUniqueConstraint {\n readonly kind: 'unique';\n readonly fields: readonly string[];\n readonly span: PslSpan;\n}\n\nexport interface PslIndexConstraint {\n readonly kind: 'index';\n readonly fields: readonly string[];\n readonly span: PslSpan;\n}\n\nexport type PslModelAttribute = PslAttribute;\n\nexport interface PslModel {\n readonly kind: 'model';\n readonly name: string;\n readonly fields: readonly PslField[];\n readonly attributes: readonly PslModelAttribute[];\n readonly span: PslSpan;\n /**\n * Optional leading comment line emitted above the `model` keyword by the\n * printer. Producers (e.g. `sqlSchemaIrToPslAst`) attach introspection\n * advisories such as \"// WARNING: This table has no primary key in the\n * database\" here. The parser leaves this field unset; round-tripping a\n * parsed schema does not re-attach comments.\n */\n readonly comment?: string;\n}\n\nexport interface PslEnumValue {\n readonly kind: 'enumValue';\n readonly name: string;\n /**\n * Optional storage label for the enum member, captured from a trailing\n * `@map(\"...\")` attribute on the member line. The parser populates this\n * when the source PSL carries an explicit `@map`. Producers (e.g.\n * `sqlSchemaIrToPslAst`) leave it unset; the printer emits `@map(...)`\n * automatically when normalisation would change the printed member name\n * (so an enum value `'in-progress'` becomes `inProgress @map(\"in-progress\")`\n * in PSL, preserving the round-trip).\n */\n readonly mapName?: string;\n readonly span: PslSpan;\n}\n\nexport interface PslEnum {\n readonly kind: 'enum';\n readonly name: string;\n readonly values: readonly PslEnumValue[];\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslCompositeType {\n readonly kind: 'compositeType';\n readonly name: string;\n readonly fields: readonly PslField[];\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslNamedTypeDeclaration {\n readonly kind: 'namedType';\n readonly name: string;\n /**\n * Parser invariant: exactly one of `baseType` and `typeConstructor` is set.\n * Expressing this as a discriminated union trips TypeScript narrowing when\n * the declaration flows through helpers that accept the full union.\n */\n readonly baseType?: string;\n readonly typeConstructor?: PslTypeConstructorCall;\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslTypesBlock {\n readonly kind: 'types';\n readonly declarations: readonly PslNamedTypeDeclaration[];\n readonly span: PslSpan;\n}\n\n/**\n * Name of the synthesised namespace bucket the framework parser uses for\n * top-level declarations that appear outside any `namespace { … }` block.\n * The double-underscore decoration signals that the identifier is parser-\n * synthesised and never appears in user-authored PSL source — writing\n * `namespace __unspecified__ { … }` is a parse error.\n *\n * Distinct from the IR sentinel `__unbound__`: the PSL bucket describes\n * syntactic absence at the parser layer; the IR sentinel describes a late-\n * bound storage slot at the IR layer. Per-target interpreters decide how\n * (or whether) to map the PSL bucket to the IR sentinel.\n */\nexport const UNSPECIFIED_PSL_NAMESPACE_ID = '__unspecified__';\n\n/**\n * A named namespace block from a PSL document, or the parser's synthesised\n * `__unspecified__` bucket for declarations that appear outside any\n * `namespace { … }` block. Multiple `namespace foo { … }` blocks for the\n * same name across one or more files reopen-merge into a single entry;\n * `span` points at the first opening.\n */\nexport interface PslNamespace {\n readonly kind: 'namespace';\n readonly name: string;\n readonly models: readonly PslModel[];\n readonly enums: readonly PslEnum[];\n readonly compositeTypes: readonly PslCompositeType[];\n readonly span: PslSpan;\n}\n\nexport interface PslDocumentAst {\n readonly kind: 'document';\n readonly sourceId: string;\n readonly namespaces: readonly PslNamespace[];\n readonly types?: PslTypesBlock;\n readonly span: PslSpan;\n}\n\n/**\n * Returns all models from every namespace in document order. Convenience\n * for consumers that don't (yet) need namespace-awareness.\n */\nexport function flatPslModels(ast: PslDocumentAst): readonly PslModel[] {\n return ast.namespaces.flatMap((ns) => ns.models);\n}\n\n/**\n * Returns all enums from every namespace in document order.\n */\nexport function flatPslEnums(ast: PslDocumentAst): readonly PslEnum[] {\n return ast.namespaces.flatMap((ns) => ns.enums);\n}\n\n/**\n * Returns all composite types from every namespace in document order.\n */\nexport function flatPslCompositeTypes(ast: PslDocumentAst): readonly PslCompositeType[] {\n return ast.namespaces.flatMap((ns) => ns.compositeTypes);\n}\n\nexport interface ParsePslDocumentInput {\n readonly schema: string;\n readonly sourceId: string;\n}\n\nexport interface ParsePslDocumentResult {\n readonly ast: PslDocumentAst;\n readonly diagnostics: readonly PslDiagnostic[];\n readonly ok: boolean;\n}\n"],"mappings":";;;;;;;;;;;;;AA8LA,MAAa,+BAA+B;;;;;AA8B5C,SAAgB,cAAc,KAA0C;CACtE,OAAO,IAAI,WAAW,SAAS,OAAO,GAAG,MAAM;AACjD;;;;AAKA,SAAgB,aAAa,KAAyC;CACpE,OAAO,IAAI,WAAW,SAAS,OAAO,GAAG,KAAK;AAChD;;;;AAKA,SAAgB,sBAAsB,KAAkD;CACtF,OAAO,IAAI,WAAW,SAAS,OAAO,GAAG,cAAc;AACzD"}
1
+ {"version":3,"file":"psl-ast.mjs","names":[],"sources":["../src/control/psl-ast.ts","../src/control/psl-extension-block-validator.ts"],"sourcesContent":["export type { AuthoringPslBlockDescriptorNamespace } from '../shared/framework-authoring';\nexport type {\n PslBlockParam,\n PslBlockParamList,\n PslBlockParamOption,\n PslBlockParamRef,\n PslBlockParamValue,\n PslDiagnosticCode,\n PslExtensionBlock,\n PslExtensionBlockParamList,\n PslExtensionBlockParamOption,\n PslExtensionBlockParamRef,\n PslExtensionBlockParamScalarValue,\n PslExtensionBlockParamValue,\n PslPosition,\n PslSpan,\n} from '../shared/psl-extension-block';\n\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { CodecLookup } from '../shared/codec-types';\nimport type { AuthoringPslBlockDescriptorNamespace } from '../shared/framework-authoring';\nimport type { PslDiagnosticCode, PslExtensionBlock, PslSpan } from '../shared/psl-extension-block';\n\nexport interface PslDiagnostic {\n readonly code: PslDiagnosticCode;\n readonly message: string;\n readonly sourceId: string;\n readonly span: PslSpan;\n}\n\nexport interface PslDefaultFunctionValue {\n readonly kind: 'function';\n readonly name: 'autoincrement' | 'now';\n}\n\nexport interface PslDefaultLiteralValue {\n readonly kind: 'literal';\n readonly value: string | number | boolean;\n}\n\nexport type PslDefaultValue = PslDefaultFunctionValue | PslDefaultLiteralValue;\n\nexport type PslAttributeTarget = 'field' | 'model' | 'enum' | 'namedType';\n\nexport interface PslAttributePositionalArgument {\n readonly kind: 'positional';\n readonly value: string;\n readonly span: PslSpan;\n}\n\nexport interface PslAttributeNamedArgument {\n readonly kind: 'named';\n readonly name: string;\n readonly value: string;\n readonly span: PslSpan;\n}\n\nexport type PslAttributeArgument = PslAttributePositionalArgument | PslAttributeNamedArgument;\n\nexport interface PslTypeConstructorCall {\n readonly kind: 'typeConstructor';\n readonly path: readonly string[];\n readonly args: readonly PslAttributeArgument[];\n readonly span: PslSpan;\n}\n\nexport interface PslAttribute {\n readonly kind: 'attribute';\n readonly target: PslAttributeTarget;\n readonly name: string;\n readonly args: readonly PslAttributeArgument[];\n readonly span: PslSpan;\n}\n\nexport type PslReferentialAction = string;\n\nexport type PslFieldAttribute = PslAttribute;\n\nexport interface PslField {\n readonly kind: 'field';\n readonly name: string;\n /** Unqualified type name, e.g. `\"User\"` for both `User`, `auth.User`, and `supabase:auth.User`. */\n readonly typeName: string;\n /** Namespace qualifier from a dot-qualified type reference, e.g. `\"auth\"` for `auth.User` or `supabase:auth.User`. Absent for unqualified types. */\n readonly typeNamespaceId?: string;\n /**\n * Contract-space qualifier from a colon-prefix type reference, e.g. `\"supabase\"` for\n * `supabase:auth.User` or `supabase:User`. Absent for local (same-space) type references.\n *\n * When present, the field references a model from a different contract space. The namespace\n * (`typeNamespaceId`) and model name (`typeName`) identify the target within that space.\n * Physical table resolution against the extension contract is deferred to the aggregate stage (M3).\n */\n readonly typeContractSpaceId?: string;\n readonly typeConstructor?: PslTypeConstructorCall;\n readonly optional: boolean;\n readonly list: boolean;\n readonly typeRef?: string;\n readonly attributes: readonly PslFieldAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslUniqueConstraint {\n readonly kind: 'unique';\n readonly fields: readonly string[];\n readonly span: PslSpan;\n}\n\nexport interface PslIndexConstraint {\n readonly kind: 'index';\n readonly fields: readonly string[];\n readonly span: PslSpan;\n}\n\nexport type PslModelAttribute = PslAttribute;\n\nexport interface PslModel {\n readonly kind: 'model';\n readonly name: string;\n readonly fields: readonly PslField[];\n readonly attributes: readonly PslModelAttribute[];\n readonly span: PslSpan;\n /**\n * Optional leading comment line emitted above the `model` keyword by the\n * printer. Producers (e.g. `sqlSchemaIrToPslAst`) attach introspection\n * advisories such as \"// WARNING: This table has no primary key in the\n * database\" here. The parser leaves this field unset; round-tripping a\n * parsed schema does not re-attach comments.\n */\n readonly comment?: string;\n}\n\nexport interface PslEnumValue {\n readonly kind: 'enumValue';\n readonly name: string;\n /**\n * Optional storage label for the enum member, captured from a trailing\n * `@map(\"...\")` attribute on the member line. The parser populates this\n * when the source PSL carries an explicit `@map`. Producers (e.g.\n * `sqlSchemaIrToPslAst`) leave it unset; the printer emits `@map(...)`\n * automatically when normalisation would change the printed member name\n * (so an enum value `'in-progress'` becomes `inProgress @map(\"in-progress\")`\n * in PSL, preserving the round-trip).\n */\n readonly mapName?: string;\n readonly span: PslSpan;\n}\n\nexport interface PslEnum {\n readonly kind: 'enum';\n readonly name: string;\n readonly values: readonly PslEnumValue[];\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\n/**\n * A reusable group of fields embedded in a model (a `type Name { … }` block) —\n * e.g. a MongoDB embedded document or a Postgres composite type. Unlike\n * {@link PslModel} it has no storage or identity of its own.\n */\nexport interface PslCompositeType {\n readonly kind: 'compositeType';\n readonly name: string;\n readonly fields: readonly PslField[];\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslNamedTypeDeclaration {\n readonly kind: 'namedType';\n readonly name: string;\n /**\n * Parser invariant: exactly one of `baseType` and `typeConstructor` is set.\n * Expressing this as a discriminated union trips TypeScript narrowing when\n * the declaration flows through helpers that accept the full union.\n */\n readonly baseType?: string;\n readonly typeConstructor?: PslTypeConstructorCall;\n readonly attributes: readonly PslAttribute[];\n readonly span: PslSpan;\n}\n\nexport interface PslTypesBlock {\n readonly kind: 'types';\n readonly declarations: readonly PslNamedTypeDeclaration[];\n readonly span: PslSpan;\n}\n\n/**\n * Name of the synthesised namespace bucket the framework parser uses for\n * top-level declarations that appear outside any `namespace { … }` block.\n * The double-underscore decoration signals that the identifier is parser-\n * synthesised and never appears in user-authored PSL source — writing\n * `namespace __unspecified__ { … }` is a parse error.\n *\n * Distinct from the IR sentinel `__unbound__`: the PSL bucket describes\n * syntactic absence at the parser layer; the IR sentinel describes a late-\n * bound storage slot at the IR layer. Per-target interpreters decide how\n * (or whether) to map the PSL bucket to the IR sentinel.\n */\nexport const UNSPECIFIED_PSL_NAMESPACE_ID = '__unspecified__';\n\n/** A value in {@link PslNamespace.entries}: a built-in entity node or an extension-contributed {@link PslExtensionBlock}. */\nexport type PslNamespaceEntry = PslModel | PslEnum | PslCompositeType | PslExtensionBlock;\n\n/**\n * A namespace block, or the parser's synthesised `__unspecified__` bucket for\n * declarations outside any `namespace { … }`. Same-name blocks reopen-merge;\n * `span` points at the first opening.\n *\n * Entities are stored canonically (ADR 224) in `entries[kind][name]`, where\n * `kind` is the PSL keyword for built-ins or the block discriminator for\n * extension kinds, e.g. `entries['policy_select']['ReadPosts']`.\n */\nexport interface PslNamespace {\n readonly kind: 'namespace';\n readonly name: string;\n /** Canonical store: a frozen container of frozen per-kind maps. The accessors below derive from it. */\n readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;\n /** Built-in models, from `entries['model']`. Extension kinds: {@link namespacePslExtensionBlocks}. */\n readonly models: readonly PslModel[];\n /** Built-in enums, from `entries['enum']`. */\n readonly enums: readonly PslEnum[];\n /** Built-in composite types, from `entries['compositeType']`. */\n readonly compositeTypes: readonly PslCompositeType[];\n readonly span: PslSpan;\n}\n\n/**\n * Stores `entries`; exposes `models`/`enums`/`compositeTypes` as getters over\n * it. The getters are prototype members (non-enumerable), so spreading or\n * `JSON.stringify`-ing a namespace copies only `entries`, never a duplicate view.\n */\nclass PslNamespaceNode implements PslNamespace {\n readonly kind = 'namespace' as const;\n readonly name: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;\n readonly span: PslSpan;\n\n constructor(init: {\n readonly name: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;\n readonly span: PslSpan;\n }) {\n this.name = init.name;\n this.entries = init.entries;\n this.span = init.span;\n Object.freeze(this);\n }\n\n get models(): readonly PslModel[] {\n return blindCast<readonly PslModel[], 'entries[model] holds only PslModel by construction'>(\n Object.values(this.entries['model'] ?? {}),\n );\n }\n\n get enums(): readonly PslEnum[] {\n return blindCast<readonly PslEnum[], 'entries[enum] holds only PslEnum by construction'>(\n Object.values(this.entries['enum'] ?? {}),\n );\n }\n\n get compositeTypes(): readonly PslCompositeType[] {\n return blindCast<\n readonly PslCompositeType[],\n 'entries[compositeType] holds only PslCompositeType by construction'\n >(Object.values(this.entries['compositeType'] ?? {}));\n }\n}\n\n/** Constructs a {@link PslNamespace}. Use this, never a namespace literal — the accessors must derive from `entries`. */\nexport function makePslNamespace(init: {\n readonly kind: 'namespace';\n readonly name: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>>;\n readonly span: PslSpan;\n}): PslNamespace {\n return new PslNamespaceNode(init);\n}\n\n/**\n * Builds the frozen `entries[kind][name]` container from per-kind arrays.\n * Built-ins key on their PSL keyword; extension blocks key on their `kind`\n * discriminator. Call this rather than hand-building the literal.\n */\nexport function makePslNamespaceEntries(\n models: readonly PslModel[],\n enums: readonly PslEnum[],\n compositeTypes: readonly PslCompositeType[],\n extensionBlocks: readonly PslExtensionBlock[],\n): Readonly<Record<string, Readonly<Record<string, PslNamespaceEntry>>>> {\n const container: Record<string, Readonly<Record<string, PslNamespaceEntry>>> = {};\n\n if (models.length > 0) {\n const map: Record<string, PslModel> = {};\n for (const m of models) {\n map[m.name] = m;\n }\n container['model'] = Object.freeze(map);\n }\n\n if (enums.length > 0) {\n const map: Record<string, PslEnum> = {};\n for (const e of enums) {\n map[e.name] = e;\n }\n container['enum'] = Object.freeze(map);\n }\n\n if (compositeTypes.length > 0) {\n const map: Record<string, PslCompositeType> = {};\n for (const ct of compositeTypes) {\n map[ct.name] = ct;\n }\n container['compositeType'] = Object.freeze(map);\n }\n\n for (const block of extensionBlocks) {\n const existing = container[block.kind];\n const newMap: Record<string, PslExtensionBlock> = existing\n ? blindCast<Record<string, PslExtensionBlock>, 'kind map holds only PslExtensionBlock'>({\n ...existing,\n })\n : {};\n newMap[block.name] = block;\n container[block.kind] = Object.freeze(newMap);\n }\n\n return Object.freeze(container);\n}\n\nexport interface PslDocumentAst {\n readonly kind: 'document';\n readonly sourceId: string;\n readonly namespaces: readonly PslNamespace[];\n readonly types?: PslTypesBlock;\n readonly span: PslSpan;\n}\n\n/**\n * Returns all models from every namespace in document order. Convenience\n * for consumers that don't (yet) need namespace-awareness.\n */\nexport function flatPslModels(ast: PslDocumentAst): readonly PslModel[] {\n return ast.namespaces.flatMap((ns) =>\n blindCast<PslModel[], 'model kind map contains only PslModel by construction'>(\n Object.values(ns.entries['model'] ?? {}),\n ),\n );\n}\n\n/**\n * Returns all enums from every namespace in document order.\n */\nexport function flatPslEnums(ast: PslDocumentAst): readonly PslEnum[] {\n return ast.namespaces.flatMap((ns) =>\n blindCast<PslEnum[], 'enum kind map contains only PslEnum by construction'>(\n Object.values(ns.entries['enum'] ?? {}),\n ),\n );\n}\n\n/**\n * Returns all composite types from every namespace in document order.\n */\nexport function flatPslCompositeTypes(ast: PslDocumentAst): readonly PslCompositeType[] {\n return ast.namespaces.flatMap((ns) =>\n blindCast<\n PslCompositeType[],\n 'compositeType kind map contains only PslCompositeType by construction'\n >(Object.values(ns.entries['compositeType'] ?? {})),\n );\n}\n\n/**\n * The set of `entries` kind keys that the framework parser reserves for\n * built-in PSL entity kinds. Any own-enumerable key on `PslNamespace.entries`\n * that is **not** in this set was contributed by an extension-block descriptor.\n *\n * Built-in keys match the PSL keyword used on each block type:\n * `'model'`, `'enum'`, `'compositeType'`.\n */\nexport const BUILTIN_PSL_KIND_KEYS: ReadonlySet<string> = new Set([\n 'model',\n 'enum',\n 'compositeType',\n]);\n\n/**\n * Returns all extension-contributed blocks in the given namespace, in\n * insertion order (the order the parser encountered them in the source).\n *\n * Reads from `namespace.entries`, skipping the three built-in kind keys\n * (`'model'`, `'enum'`, `'compositeType'`). All remaining kind maps contain\n * only `PslExtensionBlock` nodes by construction (see `makePslNamespaceEntries`).\n */\nexport function namespacePslExtensionBlocks(ns: PslNamespace): readonly PslExtensionBlock[] {\n const result: PslExtensionBlock[] = [];\n for (const [kindKey, kindMap] of Object.entries(ns.entries)) {\n if (BUILTIN_PSL_KIND_KEYS.has(kindKey)) continue;\n for (const entry of Object.values(kindMap)) {\n result.push(\n blindCast<\n PslExtensionBlock,\n 'non-builtin kind maps contain only PslExtensionBlock by construction'\n >(entry),\n );\n }\n }\n return result;\n}\n\nexport interface ParsePslDocumentInput {\n readonly schema: string;\n readonly sourceId: string;\n /**\n * Registry of declarative block descriptors, keyed by arbitrary path\n * segments with {@link AuthoringPslBlockDescriptor} leaves. The registry\n * teaches the parser which top-level keywords belong to extension\n * contributions: when the parser encounters an unknown keyword, it looks\n * it up here and, when found, reads the block generically into a\n * {@link PslExtensionBlock} node. Absent or undefined means no extension\n * blocks are registered and any unknown keyword yields\n * `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK`.\n *\n * Contrast with the parsed block nodes themselves, which live in\n * {@link PslNamespace.entries} under their discriminator key (read them with\n * {@link namespacePslExtensionBlocks}); this field holds the registry of\n * descriptors that teach the parser how to read those blocks.\n */\n readonly pslBlockDescriptors?: AuthoringPslBlockDescriptorNamespace;\n /**\n * Codec lookup for validating `value`-kind extension block parameters.\n * When provided alongside `pslBlockDescriptors`, the generic validator runs\n * over every parsed extension block after the full AST is assembled,\n * appending any diagnostics to the parse result. Absent or undefined means\n * no codec validation runs; `ref` resolution still runs when namespace\n * context is available (built from the assembled namespaces).\n */\n readonly codecLookup?: CodecLookup;\n}\n\nexport interface ParsePslDocumentResult {\n readonly ast: PslDocumentAst;\n readonly diagnostics: readonly PslDiagnostic[];\n readonly ok: boolean;\n}\n","/**\n * Generic validator for extension-contributed top-level PSL blocks.\n *\n * One function — {@link validateExtensionBlock} — takes a parsed\n * {@link PslExtensionBlock}, its {@link AuthoringPslBlockDescriptor}, a\n * {@link CodecLookup} (for `value` parameters), and the set of\n * {@link PslNamespace} objects from the document (for `ref` resolution), and\n * returns the full list of {@link PslDiagnostic} objects for the block.\n *\n * Detection logic per failure mode:\n *\n * 1. **Unknown parameter** — keys present in `node.parameters` that are absent\n * from `descriptor.parameters` (key-set difference). The parser stores\n * unknown parameters as `kind:'value'` stubs; the validator discovers them\n * by comparing the key sets, not by inspecting the captured kind.\n *\n * 2. **Missing required parameter** — `descriptor.parameters` entries with\n * `required: true` whose key is absent from `node.parameters`.\n *\n * 3. **`option` value outside its set** — the captured `token` is not in\n * `descriptor.values`.\n *\n * 4. **`value` rejected by its codec** — the raw string is first parsed as\n * JSON (`JSON.parse(raw)`). If `JSON.parse` throws, the literal is not valid\n * JSON and a `PSL_EXTENSION_INVALID_VALUE` diagnostic is emitted. If parsing\n * succeeds but `codec.decodeJson(jsonValue)` throws, the JSON value is not\n * acceptable to the codec and a `PSL_EXTENSION_INVALID_VALUE` diagnostic is\n * emitted. If `codecLookup.get(codecId)` returns `undefined` (unknown codec\n * id), a `PSL_EXTENSION_INVALID_VALUE` diagnostic is also emitted.\n *\n * 5. **`ref` that does not resolve within its scope** — the captured\n * `identifier` is looked up in the PSL document's `PslNamespace` objects\n * according to `param.scope`:\n * - `same-namespace`: the referent must be in the same namespace as the\n * block (the namespace containing the block).\n * - `same-space`: the referent may be in any namespace in the document.\n * - `cross-space`: pass-through — enforcement is scoped to first-consumer\n * need (RLS roles). This case is documented and clearly flagged; the\n * caller is responsible for wiring cross-space resolution when needed.\n *\n * 6. **`list`** — each element is validated against `param.of` recursively.\n *\n * ### `char`/`varchar` length\n * Not enforced. RLS `using`/`check` strings are unbounded text and the codec\n * already rejects structurally invalid literals; length constraints are a\n * database-side concern, not a PSL authoring constraint.\n *\n * ### `cross-space` scope\n * Implemented as a documented pass-through. The spec permits scoping\n * cross-space enforcement to first-consumer need (RLS roles). When RLS roles\n * arrive, wire `cross-space` resolution through the cross-contract-space\n * coordinate model `(spaceId, namespaceId, entityKind, entityName)`.\n */\n\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { CodecLookup } from '../shared/codec-types';\nimport type { AuthoringPslBlockDescriptor } from '../shared/framework-authoring';\nimport type {\n PslBlockParam,\n PslBlockParamRef,\n PslExtensionBlock,\n PslExtensionBlockParamValue,\n PslSpan,\n} from '../shared/psl-extension-block';\nimport type { PslDiagnostic, PslNamespace } from './psl-ast';\n\n/**\n * Context for ref resolution during extension-block validation.\n *\n * - `ownerNamespace` is the `PslNamespace` that contains the block being\n * validated. Used for `same-namespace` scope checks.\n * - `allNamespaces` is every namespace in the document. Used for `same-space`\n * scope checks.\n */\nexport interface ExtensionBlockRefResolutionContext {\n readonly ownerNamespace: PslNamespace;\n readonly allNamespaces: readonly PslNamespace[];\n}\n\n/**\n * Validate a single parsed extension block against its descriptor.\n *\n * Returns an array of {@link PslDiagnostic} objects (possibly empty). The\n * caller is responsible for threading `sourceId` into each returned diagnostic\n * — the returned objects already have `sourceId` set from the `sourceId`\n * parameter.\n *\n * @param node - The parsed block node produced by the generic framework parser.\n * @param descriptor - The descriptor that claims this block's keyword.\n * @param sourceId - The PSL source file identifier (threaded into diagnostics).\n * @param codecLookup - Used to validate `value`-kind parameter literals via\n * `codecLookup.get(codecId)?.decodeJson(JSON.parse(raw))`.\n * @param refCtx - Namespace context for `ref`-kind scope resolution. Required\n * when any descriptor parameter is `kind: 'ref'`; may be omitted if none are.\n */\nexport function validateExtensionBlock(\n node: PslExtensionBlock,\n descriptor: AuthoringPslBlockDescriptor,\n sourceId: string,\n codecLookup: CodecLookup,\n refCtx?: ExtensionBlockRefResolutionContext,\n): readonly PslDiagnostic[] {\n const diagnostics: PslDiagnostic[] = [];\n\n const descriptorKeys = new Set(Object.keys(descriptor.parameters));\n const nodeKeys = new Set(Object.keys(node.parameters));\n\n // 1. Unknown parameters — keys in the node not in the descriptor.\n for (const key of nodeKeys) {\n if (!descriptorKeys.has(key)) {\n const captured = node.parameters[key];\n diagnostics.push({\n code: 'PSL_EXTENSION_UNKNOWN_PARAMETER',\n message: `Unknown parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\". The descriptor does not declare this parameter.`,\n sourceId,\n span: captured?.span ?? node.span,\n });\n }\n }\n\n // 2. Missing required parameters — required descriptor keys absent from the node.\n for (const [key, param] of Object.entries(descriptor.parameters)) {\n if (param.required === true && !nodeKeys.has(key)) {\n diagnostics.push({\n code: 'PSL_EXTENSION_MISSING_REQUIRED_PARAMETER',\n message: `Required parameter \"${key}\" is missing from \"${descriptor.keyword}\" block \"${node.name}\".`,\n sourceId,\n span: node.span,\n });\n }\n }\n\n // 3–5. Per-parameter validation for parameters that are present.\n for (const [key, param] of Object.entries(descriptor.parameters)) {\n const captured = node.parameters[key];\n if (captured === undefined) {\n continue;\n }\n validateParam(\n node,\n descriptor,\n key,\n param,\n captured,\n sourceId,\n codecLookup,\n refCtx,\n diagnostics,\n );\n }\n\n return diagnostics;\n}\n\nfunction validateParam(\n node: PslExtensionBlock,\n descriptor: AuthoringPslBlockDescriptor,\n key: string,\n param: PslBlockParam,\n captured: PslExtensionBlockParamValue,\n sourceId: string,\n codecLookup: CodecLookup,\n refCtx: ExtensionBlockRefResolutionContext | undefined,\n diagnostics: PslDiagnostic[],\n): void {\n switch (param.kind) {\n case 'option': {\n if (captured.kind !== 'option') {\n return;\n }\n if (!param.values.includes(captured.token)) {\n diagnostics.push({\n code: 'PSL_EXTENSION_OPTION_OUT_OF_SET',\n message: `Parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\" has value \"${captured.token}\" which is not one of the allowed values: ${param.values.map((v) => `\"${v}\"`).join(', ')}.`,\n sourceId,\n span: captured.span,\n });\n }\n return;\n }\n\n case 'value': {\n if (captured.kind !== 'value') {\n return;\n }\n const codec = codecLookup.get(param.codecId);\n if (codec === undefined) {\n diagnostics.push({\n code: 'PSL_EXTENSION_INVALID_VALUE',\n message: `Parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\" references unknown codec \"${param.codecId}\".`,\n sourceId,\n span: captured.span,\n });\n return;\n }\n let jsonValue: unknown;\n try {\n jsonValue = JSON.parse(captured.raw);\n } catch {\n diagnostics.push({\n code: 'PSL_EXTENSION_INVALID_VALUE',\n message: `Parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\" is not a valid JSON literal (expected a JSON string, number, boolean, or null): ${captured.raw}`,\n sourceId,\n span: captured.span,\n });\n return;\n }\n try {\n codec.decodeJson(\n blindCast<JsonValue, 'JSON.parse returns a JsonValue-compatible value'>(jsonValue),\n );\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n diagnostics.push({\n code: 'PSL_EXTENSION_INVALID_VALUE',\n message: `Parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\" was rejected by codec \"${param.codecId}\": ${reason}`,\n sourceId,\n span: captured.span,\n });\n }\n return;\n }\n\n case 'ref': {\n if (captured.kind !== 'ref') {\n return;\n }\n validateRef(\n node,\n descriptor,\n key,\n param,\n captured.identifier,\n captured.span,\n sourceId,\n refCtx,\n diagnostics,\n );\n return;\n }\n\n case 'list': {\n if (captured.kind !== 'list') {\n return;\n }\n for (const item of captured.items) {\n validateParam(\n node,\n descriptor,\n key,\n param.of,\n item,\n sourceId,\n codecLookup,\n refCtx,\n diagnostics,\n );\n }\n return;\n }\n }\n}\n\nfunction validateRef(\n node: PslExtensionBlock,\n descriptor: AuthoringPslBlockDescriptor,\n key: string,\n param: PslBlockParamRef,\n identifier: string,\n span: PslSpan,\n sourceId: string,\n refCtx: ExtensionBlockRefResolutionContext | undefined,\n diagnostics: PslDiagnostic[],\n): void {\n if (param.scope === 'cross-space') {\n // cross-space enforcement is a documented pass-through. The spec permits\n // scoping cross-space resolution to first-consumer need (RLS roles). When\n // that consumer arrives, wire resolution here through the\n // cross-contract-space coordinate model\n // (spaceId, namespaceId, entityKind, entityName).\n // For now, cross-space refs pass validation unconditionally.\n return;\n }\n\n if (refCtx === undefined) {\n // If no resolution context was provided, skip ref resolution. This matches\n // the closed-grammar invariant: callers that register ref parameters must\n // provide resolution context; callers without namespaces (e.g. unit tests\n // that only exercise other validation modes) can omit it.\n return;\n }\n\n const namespacesToSearch: readonly PslNamespace[] =\n param.scope === 'same-namespace' ? [refCtx.ownerNamespace] : refCtx.allNamespaces;\n\n if (!resolveEntityInNamespaces(identifier, param.refKind, namespacesToSearch)) {\n const scopeLabel =\n param.scope === 'same-namespace' ? 'the same namespace' : 'any namespace in the schema';\n diagnostics.push({\n code: 'PSL_EXTENSION_UNRESOLVED_REF',\n message: `Parameter \"${key}\" in \"${descriptor.keyword}\" block \"${node.name}\" refers to \"${identifier}\" (expected ${param.refKind}), but no entity with that name and kind was found in ${scopeLabel}.`,\n sourceId,\n span,\n });\n }\n}\n\n/**\n * True if an entity named `name` of kind `refKind` exists in any of the given\n * namespaces. Built-in and extension kinds resolve the same way, through\n * `entries[refKind]`.\n */\nfunction resolveEntityInNamespaces(\n name: string,\n refKind: string,\n namespaces: readonly PslNamespace[],\n): boolean {\n for (const ns of namespaces) {\n const kindMap = ns.entries[refKind];\n if (kindMap !== undefined && Object.hasOwn(kindMap, name)) return true;\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyMA,MAAa,+BAA+B;;;;;;AAiC5C,IAAM,mBAAN,MAA+C;CAC7C,OAAgB;CAChB;CACA;CACA;CAEA,YAAY,MAIT;EACD,KAAK,OAAO,KAAK;EACjB,KAAK,UAAU,KAAK;EACpB,KAAK,OAAO,KAAK;EACjB,OAAO,OAAO,IAAI;CACpB;CAEA,IAAI,SAA8B;EAChC,OAAO,UACL,OAAO,OAAO,KAAK,QAAQ,YAAY,CAAC,CAAC,CAC3C;CACF;CAEA,IAAI,QAA4B;EAC9B,OAAO,UACL,OAAO,OAAO,KAAK,QAAQ,WAAW,CAAC,CAAC,CAC1C;CACF;CAEA,IAAI,iBAA8C;EAChD,OAAO,UAGL,OAAO,OAAO,KAAK,QAAQ,oBAAoB,CAAC,CAAC,CAAC;CACtD;AACF;;AAGA,SAAgB,iBAAiB,MAKhB;CACf,OAAO,IAAI,iBAAiB,IAAI;AAClC;;;;;;AAOA,SAAgB,wBACd,QACA,OACA,gBACA,iBACuE;CACvE,MAAM,YAAyE,CAAC;CAEhF,IAAI,OAAO,SAAS,GAAG;EACrB,MAAM,MAAgC,CAAC;EACvC,KAAK,MAAM,KAAK,QACd,IAAI,EAAE,QAAQ;EAEhB,UAAU,WAAW,OAAO,OAAO,GAAG;CACxC;CAEA,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,KAAK,OACd,IAAI,EAAE,QAAQ;EAEhB,UAAU,UAAU,OAAO,OAAO,GAAG;CACvC;CAEA,IAAI,eAAe,SAAS,GAAG;EAC7B,MAAM,MAAwC,CAAC;EAC/C,KAAK,MAAM,MAAM,gBACf,IAAI,GAAG,QAAQ;EAEjB,UAAU,mBA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,MAAM;GACN,SAAS,cAAc,IAAI,QAAQ,WAAW,QAAQ,WAAW,KAAK,KAAK,eAAe,WAAW,cAAc,MAAM,QAAQ,wDAAwD,WAAW;GACpM;GACA;EACF,CAAC;CACH;AACF;;;;;;AAOA,SAAS,0BACP,MACA,SACA,YACS;CACT,KAAK,MAAM,MAAM,YAAY;EAC3B,MAAM,UAAU,GAAG,QAAQ;EAC3B,IAAI,YAAY,KAAA,KAAa,OAAO,OAAO,SAAS,IAAI,GAAG,OAAO;CACpE;CACA,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { o as CodecCallContext } from "./codec-BFOsuHKK.mjs";
1
+ import { o as CodecCallContext } from "./codec-DCQAerzB.mjs";
2
2
  import { PlanMeta } from "@prisma-next/contract/types";
3
3
 
4
4
  //#region src/annotations.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/query-plan.ts","../src/execution/runtime-middleware.ts","../src/execution/before-execute-chain.ts","../src/execution/runtime-error.ts","../src/execution/race-against-abort.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/meta-builder.ts"],"mappings":";;;;;;;;AAmBA;;;;AAAyB;AAazB;;;;;;;;KAbY,aAAA;;;;;;;;;;;;UAaK,eAAA,wBAAuC,aAAA;EAAA,SAC7C,YAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA,EAAO,OAAA;EAAA,SACP,YAAA,EAAc,WAAA,CAAY,KAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDxB;AAyBb;;;;;;;;;;AAEuC;AAwCvC;UAzEiB,gBAAA,wBAAwC,aAAA;EAAA,CACtD,KAAA,EAAO,OAAA,GAAU,eAAA,CAAgB,OAAA,EAAS,KAAA;EAAA,SAClC,SAAA;EAAA,SACA,YAAA,EAAc,WAAA,CAAY,KAAA;EACnC,IAAA,CAAK,IAAA;IAAA,SACM,IAAA;MAAA,SA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+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/query-plan.ts","../src/execution/runtime-middleware.ts","../src/execution/before-execute-chain.ts","../src/execution/runtime-error.ts","../src/execution/race-against-abort.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/meta-builder.ts"],"mappings":";;;;;;;;AAmBA;;;;AAAyB;AAazB;;;;;;;;KAbY,aAAA;;;;;;;;;;;;UAaK,eAAA,wBAAuC,aAAA;EAAA,SAC7C,YAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA,EAAO,OAAA;EAAA,SACP,YAAA,EAAc,WAAA,CAAY,KAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDxB;AAyBb;;;;;;;;;;AAEuC;AAwCvC;UAzEiB,gBAAA,wBAAwC,aAAA;EAAA,CACtD,KAAA,EAAO,OAAA,GAAU,eAAA,CAAgB,OAAA,EAAS,KAAA;EAAA,SAClC,SAAA;EAAA,SACA,YAAA,EAAc,WAAA,CAAY,KAAA;EACnC,IAAA,CAAK,IAAA;IAAA,SACM,IAAA;MAAA,SAAiB,WAAA,GAAc,MAAA;IAAA;EAAA,IACtC,OAAA;AAAA;;;;;;;;;;;AAqE8B;AA6FpC;;;;;;;;;;;UAzIiB,uBAAA,eAAsC,aAAA;EAAA,SAC5C,SAAA;EAAA,SACA,YAAA,WAAuB,KAAK;AAAA;;;;;;;;;;;;;;;;;;;;AA6IP;AA4BhC;;;;;;;;;;;;;;;AAGsB;;iBApIN,gBAAA,kCAAkD,aAAA,EAChE,OAAA,EAAS,uBAAA,CAAwB,KAAA,MAC9B,gBAAA,CAAiB,OAAA,EAAS,KAAA;;ACzJ/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KDsPY,gBAAA,WACA,aAAA,sBACU,eAAA,UAAyB,aAAA,8BAExB,EAAA,GAAK,EAAA,CAAG,CAAA,UAAW,eAAA,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IAAA,EAAM,KAAA,GAAQ,aAAA,CAAc,MAAA;EAAA,SAEhD,KAAA,IAAS,OAAA;EAElB,OAAA,MACE,IAAA,EAAM,KAAA;IAAA,SAAmB,IAAA,GAAO,GAAA;EAAA,GAChC,OAAA,GAAU,qBAAA,GACT,mBAAA,CAAoB,GAAA;AAAA;;;;;;AR7FzB;;;;AAAyB;AAazB;;;;;;;;;;;;;;;;;;;;AAI0C;AA4C1C;US5CiB,WAAA,WAAsB,aAAA;EACrC,QAAA,kBAA0B,aAAA,EACxB,UAAA,EAAY,CAAA,SAAU,KAAA,GAAQ,eAAA,CAAgB,CAAA,EAAG,KAAA;AAAA;;;;;;;;;;;UAcpC,eAAA,WAA0B,aAAA,UAAuB,WAAA,CAAY,CAAA;EAAA,SACnE,WAAA,EAAa,WAAA,SAAoB,eAAA,UAAyB,aAAA;AAAA;;;;;;;;;;iBA0CrD,iBAAA,WAA4B,aAAA,EAC1C,IAAA,EAAM,CAAA,EACN,YAAA,WACC,eAAA,CAAgB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["candidate","#kind","#terminalName","#annotations"],"sources":["../src/execution/runtime-error.ts","../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/race-against-abort.ts","../src/execution/before-execute-chain.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/execution/runtime-middleware.ts","../src/meta-builder.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Stable code emitted by the runtime when an in-flight `execute()`\n * is cancelled via the per-query `AbortSignal`. The envelope's\n * `details.phase` distinguishes where the abort was observed:\n *\n * - `'encode'` — abort fired during `encodeParams` (SQL) or\n * `resolveValue` (Mongo).\n * - `'decode'` — abort fired during `decodeRow` / `decodeField`.\n * - `'stream'` — abort fired between rows or before any codec call\n * (already-aborted at entry).\n * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired\n * on entry to or during the corresponding middleware phase\n * (cooperative cancellation per the param-transform seam).\n */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase =\n | 'encode'\n | 'decode'\n | 'stream'\n | 'beforeExecute'\n | 'afterExecute'\n | 'onRow';\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n\n/**\n * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the\n * abort was observed — codec call sites (`encode` / `decode` / `stream`)\n * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as\n * enumerated on {@link RuntimeAbortedPhase}. Cause carries\n * `signal.reason` verbatim from the platform — native abort produces a\n * `DOMException`, explicit `controller.abort(reason)` produces whatever\n * the caller passed. No synthesis happens here.\n */\nexport function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {\n const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });\n return Object.assign(envelope, { cause });\n}\n","import { runtimeError } from './execution/runtime-error';\n\n/**\n * The kinds of operations an annotation may apply to.\n *\n * - `'read'` — `SELECT` / `find` / `first` / `all` / `count` / aggregates.\n * - `'write'` — `INSERT` / `UPDATE` / `DELETE` / `create` / `update` / `delete` / `upsert`.\n *\n * Annotations declare which kinds they apply to via `defineAnnotation`'s\n * `applicableTo` option; lane terminals enforce the constraint at both the\n * type level (via `ValidAnnotations`) and at runtime (via\n * `assertAnnotationsApplicable`).\n *\n * Finer-grained kinds (`'select' | 'insert' | 'update' | 'delete' | 'upsert'`)\n * are deliberately deferred. The binary covers the common case (the cache\n * middleware applies to reads; an audit annotation would apply to writes;\n * tracing/OTel applies to both). When a real annotation surfaces that needs\n * a finer split, the union widens and existing handles remain typecheckable.\n */\nexport type OperationKind = 'read' | 'write';\n\n/**\n * An applied annotation. Carries the namespace, the typed payload, and the\n * `applicableTo` set the underlying handle declared. The `__annotation`\n * brand lets `read` distinguish branded user annotations from arbitrary\n * data that may happen to live under the same namespace key in\n * `plan.meta.annotations` (e.g. framework-internal metadata such as\n * `meta.annotations.codecs`).\n *\n * Constructed by calling an `AnnotationHandle` directly (e.g.\n * `cacheAnnotation({ ttl: 60 })`); never instantiated by hand.\n */\nexport interface AnnotationValue<Payload, Kinds extends OperationKind> {\n readonly __annotation: true;\n readonly namespace: string;\n readonly value: Payload;\n readonly applicableTo: ReadonlySet<Kinds>;\n}\n\n/**\n * Handle returned by `defineAnnotation`. The handle is **callable**: the\n * call signature wraps a `Payload` into an `AnnotationValue` ready to\n * pass to a lane terminal's variadic `annotations` argument. The handle\n * also carries static metadata as own properties:\n *\n * - `namespace` — the namespace string the handle was declared with.\n * - `applicableTo` — the frozen `ReadonlySet<Kinds>` consumed by both\n * the type-level `ValidAnnotations` gate and the runtime\n * `assertAnnotationsApplicable` gate.\n * - `read(plan)` — extract the `Payload` from a plan's `meta.annotations`\n * if a value was previously written under this handle's namespace.\n * Returns `undefined` when the annotation is absent or when the stored\n * value is not a branded `AnnotationValue` (e.g. framework-internal\n * metadata under the same namespace key).\n *\n * Handles are the only supported public entry point for reading and\n * writing annotations. Direct mutation of `plan.meta.annotations` is not\n * part of the public API.\n *\n * ```typescript\n * const cacheAnnotation = defineAnnotation<{ ttl: number }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * });\n *\n * // Call the handle to construct a value:\n * const applied = cacheAnnotation({ ttl: 60 });\n *\n * // Read a stored value off a plan:\n * const payload = cacheAnnotation.read(plan);\n * ```\n *\n * Note on the inherited `Function.prototype.apply`: because the handle is\n * a function, the property name `apply` resolves to JavaScript's built-in\n * `Function.prototype.apply` (which lets you invoke a function with an\n * array of arguments). This is **not** the construction entry point — to\n * build an `AnnotationValue`, call the handle directly. The\n * `AnnotationHandle` interface deliberately does not declare an `apply`\n * member of its own.\n */\nexport interface AnnotationHandle<Payload, Kinds extends OperationKind> {\n (value: Payload): AnnotationValue<Payload, Kinds>;\n readonly namespace: string;\n readonly applicableTo: ReadonlySet<Kinds>;\n read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined;\n}\n\n/**\n * Options accepted by `defineAnnotation`.\n *\n * `namespace` is the string key under which the annotation is stored in\n * `plan.meta.annotations`. **Reserved namespaces** include framework-\n * internal metadata keys; user handles must not use them:\n *\n * - `codecs` — used by the SQL emitter to record per-alias codec ids\n * (`meta.annotations.codecs[alias] = 'pg/text@1'`); the SQL runtime's\n * `decodeRow` reads from this key. A user `defineAnnotation('codecs')`\n * handle is not structurally prevented, but its behavior with the\n * emitter and the runtime is undefined and we make no compatibility\n * guarantees about it.\n * - Target-specific keys such as `pg` (and equivalents on other\n * targets) are similarly reserved for adapter / target use.\n *\n * `applicableTo` declares which operation kinds the annotation may attach\n * to. The lane terminals' type-level `ValidAnnotations<K, As>` gate rejects\n * annotations whose `Kinds` does not include the terminal's `K`; the\n * runtime helper `assertAnnotationsApplicable` does the equivalent at\n * runtime so casts and `any` cannot bypass the gate.\n */\nexport interface DefineAnnotationOptions<Kinds extends OperationKind> {\n readonly namespace: string;\n readonly applicableTo: readonly Kinds[];\n}\n\n/**\n * Defines a typed annotation handle.\n *\n * Two-step call form. The first step takes the `Payload` type argument\n * (TypeScript cannot infer `Payload` from anything in the options, so it\n * must be supplied explicitly); the second step takes the runtime options\n * and infers `Kinds` from the `applicableTo` array via a `const` type\n * parameter, so the operation kinds appear exactly once at the call site.\n *\n * @example\n * ```typescript\n * // Read-only annotation. Lane terminals like `db.User.first(...)` accept\n * // it; `db.User.create(...)` rejects it at the type level.\n * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * }); // Kinds inferred as 'read'\n *\n * // Write-only annotation. Mirror image.\n * const auditAnnotation = defineAnnotation<{ actor: string }>()({\n * namespace: 'audit',\n * applicableTo: ['write'],\n * }); // Kinds inferred as 'write'\n *\n * // Annotation applicable to both kinds (e.g. tracing).\n * const otelAnnotation = defineAnnotation<{ traceId: string }>()({\n * namespace: 'otel',\n * applicableTo: ['read', 'write'],\n * }); // Kinds inferred as 'read' | 'write'\n * ```\n *\n * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the\n * list of framework-internal namespaces (`codecs`, target-specific keys).\n * `defineAnnotation` does not structurally prevent a user from naming a\n * reserved namespace, but the framework makes no compatibility guarantee\n * about handles that do.\n */\nexport function defineAnnotation<Payload>(): <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n) => AnnotationHandle<Payload, Kinds> {\n return <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n ): AnnotationHandle<Payload, Kinds> => {\n const namespace = options.namespace;\n const applicableTo: ReadonlySet<Kinds> = Object.freeze(new Set(options.applicableTo));\n\n function handle(value: Payload): AnnotationValue<Payload, Kinds> {\n return Object.freeze({\n __annotation: true as const,\n namespace,\n value,\n applicableTo,\n });\n }\n\n function read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined {\n const stored = plan.meta.annotations?.[namespace];\n if (!isAnnotationValue(stored)) {\n return undefined;\n }\n if (stored.namespace !== namespace) {\n // Defensive: a different handle wrote under our namespace key.\n return undefined;\n }\n return stored.value as Payload;\n }\n\n return Object.freeze(\n Object.assign(handle, {\n namespace,\n applicableTo,\n read,\n }),\n );\n };\n}\n\n/**\n * Type-level applicability gate consumed by lane terminals.\n *\n * Maps a tuple of `AnnotationValue`s to a tuple where each element either\n * keeps its annotation type (when the annotation's declared `Kinds`\n * includes the terminal's operation kind `K`) or resolves to `never`\n * (when the kinds are incompatible). A `never` element makes the entire\n * tuple unassignable, surfacing the mismatch as a type error at the call\n * site of the terminal.\n *\n * The SQL DSL builders constrain their variadic `...annotations`\n * parameter via `As & ValidAnnotations<K, As>`. **The intersection is\n * load-bearing** — see the note below. The ORM terminals deliberately\n * sidestep this trick by taking one annotation per `meta.annotate(...)`\n * call (no variadic-tuple inference involved), so `ValidAnnotations` is\n * consumed only by the SQL DSL today.\n *\n * @example\n * ```typescript\n * class SelectQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'read', As>\n * ): SelectQuery<Row>;\n * }\n *\n * class InsertQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'write', As>\n * ): InsertQuery<Row>;\n * }\n *\n * db.users.select('id').annotate(cacheAnnotation({ ttl: 60 }));\n * // ✓ cacheAnnotation declares 'read'; SelectQuery.annotate requires 'read'.\n *\n * db.users.insert([{ name: 'Alice' }]).annotate(cacheAnnotation({ ttl: 60 }));\n * // ✗ cacheAnnotation declares 'read'; InsertQuery.annotate requires 'write'.\n * // Element resolves to `never` → tuple unassignable → type error.\n * ```\n *\n * **Why `As & ValidAnnotations<K, As>` and not `ValidAnnotations<K, As>`\n * alone.** TypeScript's variadic-tuple inference is too forgiving when\n * the parameter type refers to `As` only through `ValidAnnotations`: it\n * will pick an `As` that makes the call valid even when the gated tuple\n * would contain `never` for an inapplicable element. The intersection\n * pins `As` to the actual call-site tuple AND requires it to be\n * assignable to the gated form. A `never` element in the gated tuple\n * then collapses the corresponding intersection position to `never`,\n * and the inapplicable argument fails to assign — surfacing the mismatch\n * as a type error at the call site.\n *\n * The runtime helper `assertAnnotationsApplicable` covers the equivalent\n * check at runtime so casts and `any` cannot bypass this gate.\n */\nexport type ValidAnnotations<\n K extends OperationKind,\n As extends readonly AnnotationValue<unknown, OperationKind>[],\n> = {\n readonly [I in keyof As]: As[I] extends AnnotationValue<infer P, infer Kinds>\n ? K extends Kinds\n ? AnnotationValue<P, Kinds>\n : never\n : never;\n};\n\n/**\n * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if\n * any annotation in `annotations` declares an `applicableTo` set that does\n * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,\n * ORM `Collection` terminals) to fail closed when the type-level\n * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic\n * invocation.\n *\n * Passes silently on:\n * - empty arrays\n * - annotations whose `applicableTo` includes `kind`\n *\n * Throws on:\n * - any annotation whose `applicableTo` does not include `kind`. The\n * error names the offending annotation's `namespace` and the\n * `terminalName` so users can locate the misuse.\n *\n * @example\n * ```typescript\n * // Inside an ORM read terminal:\n * assertAnnotationsApplicable(annotations, 'read', 'first');\n * ```\n */\nexport function assertAnnotationsApplicable(\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n kind: OperationKind,\n terminalName: string,\n): void {\n for (const annotation of annotations) {\n if (!annotation.applicableTo.has(kind)) {\n throw runtimeError(\n 'RUNTIME.ANNOTATION_INAPPLICABLE',\n `Annotation '${annotation.namespace}' is not applicable to '${kind}' operations (terminal: '${terminalName}'). The annotation declares applicableTo = [${Array.from(\n annotation.applicableTo,\n )\n .map((k) => `'${k}'`)\n .join(', ')}].`,\n {\n namespace: annotation.namespace,\n terminalName,\n kind,\n applicableTo: Array.from(annotation.applicableTo),\n },\n );\n }\n }\n}\n\n/**\n * Type guard for branded annotation values stored in `plan.meta.annotations`.\n *\n * Internal — used by `AnnotationHandle.read` to distinguish user\n * annotations (created by calling a handle returned from\n * `defineAnnotation(...)`) from framework-internal metadata that may\n * happen to live under the same namespace key.\n */\nfunction isAnnotationValue(value: unknown): value is AnnotationValue<unknown, OperationKind> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { readonly __annotation?: unknown };\n return candidate.__annotation === true;\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * context is already aborted at the precheck site. Centralises the\n * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site (and the `beforeExecute` middleware phase)\n * repeats. Accepts both the framework `CodecCallContext` and the\n * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.\n */\nexport function checkAborted(\n ctx: { readonly signal?: AbortSignal },\n phase: RuntimeAbortedPhase,\n): void {\n if (ctx.signal?.aborted) {\n throw runtimeAborted(phase, ctx.signal.reason);\n }\n}\n\n/**\n * Race a per-cell `Promise.all` (or any other in-flight work promise) against\n * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly\n * even when codec bodies ignore the signal. In-flight bodies that ignore the\n * signal are abandoned and run to completion in the background — the\n * cooperative-cancellation contract documented in ADR 204.\n *\n * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with\n * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —\n * that path is the canonical \"aborted at entry\" surface and avoids\n * scheduling the work promise. As a defensive belt-and-braces, this helper\n * also handles the already-aborted case internally: `AbortSignal` does not\n * replay past abort events to listeners registered after the abort, so we\n * inspect `signal.aborted` synchronously and reject with the sentinel\n * before installing the listener. The rejection is still attributed to the\n * abort path via the sentinel-identity check.\n *\n * Distinguishing the rejection source is load-bearing for AC-ERR4\n * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).\n * The semantically equivalent `abortable(signal)` helper in\n * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,\n * which is not stably distinguishable from a codec-thrown error by identity\n * alone (a fresh fallback DOMException is allocated per call). We instead\n * track abort attribution with a unique sentinel: only the `onAbort` listener\n * installed here ever rejects with the sentinel, so an `error === sentinel`\n * identity check after the race is unambiguous.\n *\n * Lives in `framework-components` (rather than the SQL family, where it\n * originated in m2) so every family runtime that needs cooperative\n * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode\n * today, Mongo encode in m3) shares the same attribution logic.\n */\nexport async function raceAgainstAbort<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n phase: RuntimeAbortedPhase,\n): Promise<T> {\n if (signal === undefined) {\n return await work;\n }\n const sentinel: { reason: unknown } = { reason: undefined };\n let onAbort: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n if (signal.aborted) {\n sentinel.reason = signal.reason;\n reject(sentinel);\n return;\n }\n onAbort = () => {\n sentinel.reason = signal.reason;\n reject(sentinel);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n return await Promise.race([work, abortPromise]);\n } catch (error) {\n if (error === sentinel) {\n throw runtimeAborted(phase, sentinel.reason);\n }\n throw error;\n } finally {\n if (onAbort) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n}\n","import type { ExecutionPlan } from './query-plan';\nimport { checkAborted, raceAgainstAbort } from './race-against-abort';\nimport type {\n ParamRefMutator,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Runs every middleware's `beforeExecute` hook in registration order,\n * threading through the (optional) family-specific `paramsMutator`.\n *\n * Why this lives outside {@link runWithMiddleware}: middleware that\n * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK\n * round-trip) must run *before* the family runtime encodes those\n * parameters to driver wire format. Family runtimes call\n * `runBeforeExecuteChain` between the AST → plan lowering step and\n * the parameter encode step; the encode then observes the mutator's\n * `currentParams()` view. `runWithMiddleware` retains the rest of\n * the lifecycle (`intercept`, driver/row source loop, `onRow`,\n * `afterExecute`) but no longer fires `beforeExecute` itself.\n *\n * Lifecycle within this helper:\n *\n * 1. For each middleware in registration order, if `beforeExecute`\n * is implemented:\n * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the\n * caller already aborted at entry.\n * - The hook is invoked with `(plan, ctx, paramsMutator)`. A\n * middleware body that ignores the mutator stays compatible —\n * JavaScript allows extra positional arguments.\n * - If the hook returns a Promise, it is raced against\n * `ctx.signal` via {@link raceAgainstAbort} so cooperative\n * cancellation surfaces a `RUNTIME.ABORTED { phase:\n * 'beforeExecute' }` envelope even when the body itself\n * ignores the signal.\n *\n * Error propagation: any error thrown by a `beforeExecute` body\n * (or surfaced by the abort race) propagates out of this helper\n * unchanged. The family runtime is responsible for converting it\n * into the appropriate `afterExecute(completed: false)` notification\n * once `runWithMiddleware` runs.\n *\n * Relationship to {@link runWithMiddleware}: the framework's\n * `RuntimeCore.execute` template calls this helper between\n * `lower(plan)` and `runWithMiddleware(...)`. Family runtimes that\n * override `execute` (e.g. SQL, which inlines lower + encode for\n * direct mutator threading) call this helper themselves at the\n * equivalent point — between the family's AST → draft-plan\n * lowering and the parameter-encode step.\n *\n * Intercept ordering: this helper fires unconditionally before\n * `runWithMiddleware`. `intercept` (inside `runWithMiddleware`)\n * therefore observes the post-`beforeExecute` plan — mutator\n * mutations are visible in the params interceptors see. The\n * trade-off is documented on `RuntimeMiddleware.intercept`.\n */\nexport async function runBeforeExecuteChain<\n TExec extends ExecutionPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n>(\n plan: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>,\n ctx: RuntimeMiddlewareContext,\n paramsMutator?: TMutator,\n): Promise<void> {\n for (const mw of middleware) {\n if (!mw.beforeExecute) {\n continue;\n }\n checkAborted(ctx, 'beforeExecute');\n const work = mw.beforeExecute(plan, ctx, paramsMutator as TMutator);\n if (work !== undefined) {\n await raceAgainstAbort(Promise.resolve(work), ctx.signal, 'beforeExecute');\n }\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware\n * lifecycle's intercept + row-source + termination phases.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `intercept(exec, ctx)`. The\n * first non-`undefined` result wins; subsequent middleware's `intercept`\n * does not fire. On a hit, the runtime emits a `middleware.intercept`\n * debug event naming the winning middleware, switches the row source to\n * the intercepted rows, and proceeds with `source: 'middleware'`. On\n * all-passthrough (every `intercept` returns `undefined` or is omitted),\n * `source: 'driver'` is used and the row source is `runDriver()`.\n * 2. Iterate the row source. On the driver path, for each row, for each\n * middleware in registration order: `onRow(row, exec, ctx)`; then yield\n * the row. On the intercepted hit path, `onRow` is skipped — intercepted\n * rows did not originate from a driver row stream — but rows are still\n * yielded to the consumer in order.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },\n * ctx)`.\n * 4. On any error thrown during steps 1–2: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false, source }, ctx)`. Errors thrown by `afterExecute`\n * during the error path are swallowed so they do not mask the original\n * error. The original error is then rethrown.\n *\n * `beforeExecute` is **not** fired here — see\n * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family\n * runtimes call that helper between the AST → plan lowering step and\n * the parameter encode step so middleware that mutates ParamRef\n * values (e.g. cipherstash bulk-encrypt) can have its mutations\n * visible to encode. `runWithMiddleware` operates on the fully-\n * encoded plan; interceptors therefore observe a fully-mutated,\n * encoded plan.\n *\n * The `source` field on `AfterExecuteResult` lets observers (telemetry,\n * lints, budgets) distinguish driver-served from middleware-served\n * executions without needing their own out-of-band signal.\n *\n * This helper is the single canonical implementation of the\n * intercept-and-row-source loop; family runtimes should not\n * reimplement it.\n */\nexport function runWithMiddleware<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n let source: 'driver' | 'middleware' = 'driver';\n // Deferred so a winning interceptor can skip `runDriver()` entirely.\n // For factories that lazily produce async generators this is a no-op,\n // but factories that do eager work (e.g. acquiring a connection,\n // sending a query) must not run on the intercepted hit path.\n let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;\n\n try {\n for (const mw of middleware) {\n if (!mw.intercept) {\n continue;\n }\n // Mark the lifecycle as middleware-driven *before* awaiting the\n // hook. If `intercept` throws, the catch block reports the failure\n // as `source: 'middleware'` — the failure originated in the\n // intercept chain, not in the driver. If `intercept` returns\n // `undefined` (passthrough), we revert to `'driver'` and continue.\n source = 'middleware';\n const result = await mw.intercept(exec, ctx);\n if (result === undefined) {\n source = 'driver';\n continue;\n }\n ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });\n // The intercepted rows are typed as `Record<string, unknown>` at\n // the SPI level; the consumer's `Row` type parameter is enforced by\n // the caller (via the plan's phantom `_row`) the same way driver\n // rows are. Cast through unknown to bridge the SPI shape to the\n // caller-supplied Row.\n rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;\n break;\n }\n\n if (source === 'driver') {\n rowSource = runDriver();\n }\n\n // `rowSource` is always assigned by this point: either the intercepted\n // rows (on a hit) or `runDriver()` (on the driver path).\n for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import type { CodecCallContext } from '../shared/codec-types';\nimport { AsyncIterableResult } from './async-iterable-result';\nimport { runBeforeExecuteChain } from './before-execute-chain';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { checkAborted } from './race-against-abort';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecuteOptions,\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runBeforeExecuteChain(exec, this.middleware, this.ctx)` — concrete;\n * runs every middleware's `beforeExecute` hook after lowering but\n * before the row source is opened. Family runtimes that need a\n * params mutator visible to a downstream encode step (SQL) override\n * `execute` and call this helper themselves at the equivalent\n * pre-encode point.\n * 4. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; runs the intercept chain,\n * drives the row source, fires `onRow` / `afterExecute`. Does\n * **not** fire `beforeExecute` — see step 3.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n *\n * `ctx` carries per-query cancellation (and any future fields on\n * `CodecCallContext`); concrete subclasses forward it to the\n * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,\n * Mongo's `resolveValue` in m3). The runtime allocates one ctx per\n * `execute()` call and threads the same reference everywhere; the\n * `signal` field inside may be `undefined`, but the ctx object itself\n * is always present.\n */\n protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call. The ctx object is always allocated; the\n // `signal` field is only included when a signal was supplied (required\n // under exactOptionalPropertyTypes — `{ signal: undefined }` would not\n // satisfy `signal?: AbortSignal`).\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n\n // Per-execute middleware context. Spread the stored runtime-level\n // template and mint a fresh `planExecutionId` so every hook in this\n // call observes the same value, and two executions of the same plan\n // observe distinct values. ADR 220. The same reference is threaded\n // through `runBeforeExecuteChain` and `runWithMiddleware`; the plan\n // itself flows through unchanged.\n const execCtx: RuntimeMiddlewareContext = {\n ...self.ctx,\n planExecutionId: crypto.randomUUID(),\n };\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n // Pre-check the signal at entry so an already-aborted caller observes\n // RUNTIME.ABORTED on the first `next()` without any work being done.\n checkAborted(codecCtx, 'stream');\n\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n // Fire the framework-level `beforeExecute` chain on the lowered\n // plan before opening the row source. Families that need\n // pre-encode mutator visibility (SQL) override `execute` to\n // inject the same chain at the equivalent point.\n await runBeforeExecuteChain<TExec>(exec, self.middleware, execCtx);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n execCtx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\n/**\n * Per-execute context threaded through every middleware phase\n * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per\n * `runtime.execute()` call and shared by reference across all\n * middleware in the chain.\n *\n * - `signal` carries the per-query `AbortSignal` -- the same\n * reference that `runtime.execute(plan, { signal })` was invoked\n * with, and the same reference threaded into the per-call\n * `CodecCallContext` (ADR 207). Middleware that wraps a\n * network-backed SDK forwards `ctx.signal` into that SDK to\n * propagate caller cancellation; pure-CPU middleware ignores it.\n *\n * Symmetric plumbing across all middleware phases (rather than only\n * `beforeExecute`) is a deliberate choice: a middleware that wraps a\n * downstream observability hook or post-processor in `afterExecute` /\n * `onRow` needs the same cancellation reach as its `beforeExecute`\n * counterpart.\n */\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n /**\n * Returns a stable string identifying the (storage, statement, params)\n * tuple of an execution. Two semantically equivalent executions return\n * the same string. Used by middleware that need per-execution identity\n * (caching, request coalescing).\n *\n * The family runtime owns the implementation:\n * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`\n * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`\n *\n * The method is `async` because the underlying digest helper\n * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`\n * primitive is asynchronous by design.\n *\n * The returned string is intended to be consumed directly as a `Map` key\n * — it is not (and should not be) further hashed by callers.\n */\n contentHash(exec: ExecutionPlan): Promise<string>;\n /**\n * Per-execute cancellation signal threaded through every middleware\n * phase. Middleware that wraps async work or downstream cancellable\n * primitives should observe this and abort early when the consumer\n * cancels.\n */\n readonly signal?: AbortSignal;\n /**\n * Identifies the queryable scope this execution is running under.\n *\n * - `'runtime'` — top-level `runtime.execute(plan)`. The default scope\n * used by the standard read/write paths.\n * - `'connection'` — `connection.execute(plan)` after\n * `runtime.connection()` checked out a connection from the pool.\n * - `'transaction'` — `transaction.execute(plan)` inside an explicit\n * transaction, or a query routed through `withTransaction`.\n *\n * Middleware that should only act at the top level read this field to\n * bypass non-runtime scopes. The cache middleware uses it to skip\n * caching inside transactions (where read-after-write coherence is the\n * caller's expectation) and dedicated connections (where the user has\n * explicitly stepped outside the shared cache surface). Observers that\n * don't care about the scope can ignore the field.\n *\n * Family runtimes populate this at context-construction time per\n * scope. Existing middleware that ignore the field are unaffected.\n */\n readonly scope: 'runtime' | 'connection' | 'transaction';\n /**\n * Identity for one `execute()` call. The runtime mints a fresh value via\n * `crypto.randomUUID()` when it constructs the per-execute context, and\n * the same context reference is threaded through every middleware phase\n * (`beforeExecute`, `intercept`, `onRow`, `afterExecute`). Every hook in\n * one execute call therefore observes the same `planExecutionId`; two\n * executions of the same plan observe distinct values. Use this to\n * correlate observations across the lifecycle of a single execute call\n * (tracing, timing, audit). See ADR 220.\n */\n readonly planExecutionId: string;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n /**\n * Indicates where the rows observed during this execution came from.\n *\n * - `'driver'` — the default. Rows came from the underlying driver via\n * `runDriver` / `runWithMiddleware`'s normal path.\n * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited\n * execution and supplied the rows directly. The driver was not invoked.\n *\n * Observers (telemetry, lints, budgets) that need to distinguish between\n * driver-served and middleware-served executions read this field.\n * Observers that don't care can ignore it.\n */\n readonly source: 'driver' | 'middleware';\n}\n\n/**\n * Result of a successful `RuntimeMiddleware.intercept` hook.\n *\n * Carries the rows that the middleware wishes to return in place of\n * invoking the driver. The runtime iterates `rows` in order and yields\n * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are\n * all skipped on the hit path. `afterExecute` still fires with\n * `source: 'middleware'`.\n *\n * `rows` accepts both `Iterable` (arrays, sync generators) and\n * `AsyncIterable` (async generators). `for await` natively handles both\n * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the\n * orchestrator does not need to branch on the variant. Cached arrays in\n * the cache middleware are the common case; streaming variants support\n * future use cases like mock layers replaying recordings.\n *\n * Row shape is `Record<string, unknown>` — the same untyped shape\n * `onRow` receives. The SQL runtime decodes intercepted rows through its\n * normal codec pass, so interceptors cache and return raw (undecoded)\n * rows.\n */\nexport interface InterceptResult {\n readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;\n}\n\n/**\n * Marker interface for family-specific param-ref mutators threaded into\n * `beforeExecute` as the third argument. The framework treats the mutator\n * opaquely — it allocates and forwards the family's mutator instance so\n * `runWithMiddleware` can stay family-agnostic. SQL extends this with\n * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with\n * `MongoParamRefMutator` (over `MongoParamRef`).\n *\n * Extension authors target the family-specific mutator type, not this\n * marker.\n */\ndeclare const PARAM_REF_MUTATOR_BRAND: unique symbol;\nexport type ParamRefMutator = { readonly [PARAM_REF_MUTATOR_BRAND]?: never };\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n *\n * `TMutator` is the family-specific {@link ParamRefMutator} the runtime\n * threads into `beforeExecute(plan, ctx, params)` as a third argument.\n * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile\n * — TypeScript permits assigning a function with fewer parameters to a\n * function-typed slot that declares more. The third arg is additive.\n */\nexport interface RuntimeMiddleware<\n TPlan extends QueryPlan = QueryPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n /**\n * Optional short-circuit hook. Runs inside `runWithMiddleware`, after\n * the orchestrator receives the lowered plan and before any\n * `beforeExecute` hook fires. Middleware run in registration order; the\n * first to return a non-`undefined` `InterceptResult` wins, and\n * subsequent middleware's `intercept` does not fire.\n *\n * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.\n * `afterExecute` still fires with `source: 'middleware'`.\n *\n * Returning `undefined` (or omitting the hook entirely) signals\n * passthrough — execution proceeds through the normal driver path.\n *\n * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`\n * as the original `Error` — no envelope is guaranteed at this layer.\n * Before rethrowing, `afterExecute` fires with `completed: false` and\n * `source: 'middleware'`. Errors thrown by `afterExecute` during the\n * error path remain swallowed (existing semantics, unchanged).\n *\n * Used by middleware that need to short-circuit execution and supply\n * rows directly: caching, mocks, rate limiting, circuit breaking.\n */\n intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;\n /**\n * Fires after the family runtime has produced a draft execution\n * plan from the AST, but before the family encodes parameter values\n * to driver wire format. Mutations applied via the\n * family-specific `params` mutator are visible to the subsequent\n * encode step.\n *\n * Lifecycle position (SQL example):\n * `runBeforeCompile → lowerSqlPlan → beforeExecute → encodeParams → intercept → driver`.\n *\n * The `params` argument is a family-specific {@link ParamRefMutator}\n * scoped to the value slots of `ParamRef` nodes in the plan's AST.\n * Middleware that doesn't need to mutate params can ignore the\n * argument; existing `(plan)` / `(plan, ctx)` bodies stay compatible.\n *\n * `ctx.signal` carries the per-query `AbortSignal`; middleware that\n * wraps a network SDK forwards it. Cooperative cancellation\n * surfaces a `RUNTIME.ABORTED { phase: 'beforeExecute' }` envelope\n * promptly even when the body ignores the signal.\n *\n * Intercept ordering: `intercept` runs *after* this hook; an\n * interceptor that short-circuits the driver path still observes\n * the post-`beforeExecute`, fully-encoded plan. The trade-off is\n * that any `beforeExecute` SDK round-trips happen even when a\n * downstream interceptor would have skipped the driver entirely.\n */\n beforeExecute?(\n plan: TPlan,\n ctx: RuntimeMiddlewareContext,\n params?: TMutator,\n ): void | Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family middleware — one that doesn't constrain `familyId` or\n * `targetId` and is therefore compatible with any family runtime's\n * middleware array (`SqlMiddleware[]`, `MongoMiddleware[]`, etc.).\n *\n * The intersection `RuntimeMiddleware & { familyId?: undefined; targetId?: undefined }`\n * pins both optional properties to exactly `undefined` (intersecting\n * `string | undefined` with `undefined` collapses to `undefined`). Under\n * `exactOptionalPropertyTypes: true`, the plain `RuntimeMiddleware` shape\n * — with `familyId?: string` — is *not* assignable to `SqlMiddleware`\n * (which narrows `familyId?: 'sql'`) because `string` is wider than\n * `'sql'`. Pinning the property to `undefined` makes the value a subtype\n * of every narrowed variant: `undefined` extends both `'sql' | undefined`\n * and `'mongo' | undefined`, so a `CrossFamilyMiddleware` value drops\n * into a SQL or Mongo middleware slot without a cast.\n *\n * Cross-family middleware factories (`createCacheMiddleware`, future\n * `audit` / OTel middleware) declare this as their return type so the\n * cross-family typing is named once rather than re-spelled at every call\n * site.\n */\nexport type CrossFamilyMiddleware<TPlan extends QueryPlan = QueryPlan> =\n RuntimeMiddleware<TPlan> & {\n readonly familyId?: undefined;\n readonly targetId?: undefined;\n };\n\n/**\n * Optional per-`execute` options accepted by every family runtime.\n *\n * `signal` is the per-query cancellation signal. The runtime threads the\n * signal through to every codec call for the query and uses it to short-\n * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.\n * Omitting the option (or passing `undefined`) preserves today's behavior\n * bit-for-bit.\n */\nexport interface RuntimeExecuteOptions {\n readonly signal?: AbortSignal;\n readonly scope?: 'runtime' | 'connection' | 'transaction';\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n","import {\n type AnnotationValue,\n assertAnnotationsApplicable,\n type OperationKind,\n} from './annotations';\n\n/**\n * Per-terminal meta configurator handed to user callbacks. The terminal's\n * operation kind `K` is fixed by the terminal that constructed the builder;\n * `annotate(...)` accepts only annotations whose declared `Kinds` include\n * `K`.\n *\n * The conditional parameter type\n * `K extends Kinds ? AnnotationValue<P, Kinds> : never` collapses to `never`\n * for inapplicable annotations, surfacing the mismatch as a type error at\n * the call site of `meta.annotate(...)`. No variadic-tuple inference is\n * involved — TypeScript infers `Kinds` from the annotation argument and\n * checks the conditional directly.\n *\n * The runtime gate inside `annotate` (via\n * `assertAnnotationsApplicable`) catches cast / `any` / dynamic bypasses\n * and throws `RUNTIME.ANNOTATION_INAPPLICABLE`.\n *\n * `annotate` returns the builder for chaining; the return value of the\n * configurator callback is unused, so both block-body and expression-body\n * callbacks compile.\n *\n * @example\n * ```typescript\n * await db.User.find({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60 })));\n * await db.User.create(input, (meta) => {\n * meta.annotate(auditAnnotation({ actor: 'system' }));\n * meta.annotate(otelAnnotation({ traceId }));\n * });\n * ```\n */\nexport interface MetaBuilder<K extends OperationKind> {\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this;\n}\n\n/**\n * Lane-side view of a meta builder. Extends the public `MetaBuilder<K>`\n * surface with `annotations` so lane terminals can read the recorded map\n * after invoking the user configurator.\n *\n * Lane terminals construct one of these via `createMetaBuilder(kind, terminalName)`,\n * pass it to the user callback as `MetaBuilder<K>` (the narrower public\n * view), then read `meta.annotations` to thread the recorded values into\n * `plan.meta.annotations`.\n */\nexport interface LaneMetaBuilder<K extends OperationKind> extends MetaBuilder<K> {\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n}\n\nclass MetaBuilderImpl<K extends OperationKind> implements LaneMetaBuilder<K> {\n readonly #kind: K;\n readonly #terminalName: string;\n readonly #annotations = new Map<string, AnnotationValue<unknown, OperationKind>>();\n\n constructor(kind: K, terminalName: string) {\n this.#kind = kind;\n this.#terminalName = terminalName;\n }\n\n get annotations(): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n return this.#annotations;\n }\n\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this {\n // Inside the body, the conditional `K extends Kinds ? AnnotationValue<P, Kinds> : never`\n // is opaque to TypeScript — it can't pick a branch without a concrete\n // K. Widen to the structural shape so we can call into the runtime\n // gate. The runtime gate (assertAnnotationsApplicable) is what\n // catches cast bypasses where the conditional would have resolved to\n // `never` had the type checker been allowed to specialise.\n const value = annotation as AnnotationValue<unknown, OperationKind>;\n assertAnnotationsApplicable([value], this.#kind, this.#terminalName);\n this.#annotations.set(value.namespace, value);\n return this;\n }\n}\n\n/**\n * Construct a lane-side meta builder for a terminal of operation kind `K`.\n *\n * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a\n * `terminalName` for error messages, hand the resulting builder to the\n * user-supplied configurator callback (typed as `MetaBuilder<K>`, the\n * narrower public view), and read `meta.annotations` afterwards to thread\n * the recorded values into `plan.meta.annotations`.\n */\nexport function createMetaBuilder<K extends OperationKind>(\n kind: K,\n terminalName: string,\n): LaneMetaBuilder<K> {\n return new MetaBuilderImpl(kind, terminalName);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAa,kBAAkB;;;;;;;AAiB/B,SAAgB,eAAe,OAA+C;CAC5E,OACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC9C,cAAc,SACd,cAAc;AAElB;AAEA,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,OAAO;CAC/B,OAAO,eAAe,OAAO,QAAQ;EACnC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;CACd;CAEA,SACE,YACM;EAON,MAAM,QAAQ;EACd,4BAA4B,CAAC,KAAK,GAAG,KAAKF,OAAO,KAAKC,aAAa;EACnE,KAAKC,aAAa,IAAI,MAAM,WAAW,KAAK;EAC5C,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,kBACd,MACA,cACoB;CACpB,OAAO,IAAI,gBAAgB,MAAM,YAAY;AAC/C"}
1
+ {"version":3,"file":"runtime.mjs","names":["candidate","#kind","#terminalName","#annotations"],"sources":["../src/execution/runtime-error.ts","../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/race-against-abort.ts","../src/execution/before-execute-chain.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/execution/runtime-middleware.ts","../src/meta-builder.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Stable code emitted by the runtime when an in-flight `execute()`\n * is cancelled via the per-query `AbortSignal`. The envelope's\n * `details.phase` distinguishes where the abort was observed:\n *\n * - `'encode'` — abort fired during `encodeParams` (SQL) or\n * `resolveValue` (Mongo).\n * - `'decode'` — abort fired during `decodeRow` / `decodeField`.\n * - `'stream'` — abort fired between rows or before any codec call\n * (already-aborted at entry).\n * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired\n * on entry to or during the corresponding middleware phase\n * (cooperative cancellation per the param-transform seam).\n */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase =\n | 'encode'\n | 'decode'\n | 'stream'\n | 'beforeExecute'\n | 'afterExecute'\n | 'onRow';\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n\n/**\n * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the\n * abort was observed — codec call sites (`encode` / `decode` / `stream`)\n * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as\n * enumerated on {@link RuntimeAbortedPhase}. Cause carries\n * `signal.reason` verbatim from the platform — native abort produces a\n * `DOMException`, explicit `controller.abort(reason)` produces whatever\n * the caller passed. No synthesis happens here.\n */\nexport function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {\n const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });\n return Object.assign(envelope, { cause });\n}\n","import { runtimeError } from './execution/runtime-error';\n\n/**\n * The kinds of operations an annotation may apply to.\n *\n * - `'read'` — `SELECT` / `find` / `first` / `all` / `count` / aggregates.\n * - `'write'` — `INSERT` / `UPDATE` / `DELETE` / `create` / `update` / `delete` / `upsert`.\n *\n * Annotations declare which kinds they apply to via `defineAnnotation`'s\n * `applicableTo` option; lane terminals enforce the constraint at both the\n * type level (via `ValidAnnotations`) and at runtime (via\n * `assertAnnotationsApplicable`).\n *\n * Finer-grained kinds (`'select' | 'insert' | 'update' | 'delete' | 'upsert'`)\n * are deliberately deferred. The binary covers the common case (the cache\n * middleware applies to reads; an audit annotation would apply to writes;\n * tracing/OTel applies to both). When a real annotation surfaces that needs\n * a finer split, the union widens and existing handles remain typecheckable.\n */\nexport type OperationKind = 'read' | 'write';\n\n/**\n * An applied annotation. Carries the namespace, the typed payload, and the\n * `applicableTo` set the underlying handle declared. The `__annotation`\n * brand lets `read` distinguish branded user annotations from arbitrary\n * data that may happen to live under the same namespace key in\n * `plan.meta.annotations` (e.g. framework-internal metadata such as\n * `meta.annotations.codecs`).\n *\n * Constructed by calling an `AnnotationHandle` directly (e.g.\n * `cacheAnnotation({ ttl: 60 })`); never instantiated by hand.\n */\nexport interface AnnotationValue<Payload, Kinds extends OperationKind> {\n readonly __annotation: true;\n readonly namespace: string;\n readonly value: Payload;\n readonly applicableTo: ReadonlySet<Kinds>;\n}\n\n/**\n * Handle returned by `defineAnnotation`. The handle is **callable**: the\n * call signature wraps a `Payload` into an `AnnotationValue` ready to\n * pass to a lane terminal's variadic `annotations` argument. The handle\n * also carries static metadata as own properties:\n *\n * - `namespace` — the namespace string the handle was declared with.\n * - `applicableTo` — the frozen `ReadonlySet<Kinds>` consumed by both\n * the type-level `ValidAnnotations` gate and the runtime\n * `assertAnnotationsApplicable` gate.\n * - `read(plan)` — extract the `Payload` from a plan's `meta.annotations`\n * if a value was previously written under this handle's namespace.\n * Returns `undefined` when the annotation is absent or when the stored\n * value is not a branded `AnnotationValue` (e.g. framework-internal\n * metadata under the same namespace key).\n *\n * Handles are the only supported public entry point for reading and\n * writing annotations. Direct mutation of `plan.meta.annotations` is not\n * part of the public API.\n *\n * ```typescript\n * const cacheAnnotation = defineAnnotation<{ ttl: number }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * });\n *\n * // Call the handle to construct a value:\n * const applied = cacheAnnotation({ ttl: 60 });\n *\n * // Read a stored value off a plan:\n * const payload = cacheAnnotation.read(plan);\n * ```\n *\n * Note on the inherited `Function.prototype.apply`: because the handle is\n * a function, the property name `apply` resolves to JavaScript's built-in\n * `Function.prototype.apply` (which lets you invoke a function with an\n * array of arguments). This is **not** the construction entry point — to\n * build an `AnnotationValue`, call the handle directly. The\n * `AnnotationHandle` interface deliberately does not declare an `apply`\n * member of its own.\n */\nexport interface AnnotationHandle<Payload, Kinds extends OperationKind> {\n (value: Payload): AnnotationValue<Payload, Kinds>;\n readonly namespace: string;\n readonly applicableTo: ReadonlySet<Kinds>;\n read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined;\n}\n\n/**\n * Options accepted by `defineAnnotation`.\n *\n * `namespace` is the string key under which the annotation is stored in\n * `plan.meta.annotations`. **Reserved namespaces** include framework-\n * internal metadata keys; user handles must not use them:\n *\n * - `codecs` — used by the SQL emitter to record per-alias codec ids\n * (`meta.annotations.codecs[alias] = 'pg/text@1'`); the SQL runtime's\n * `decodeRow` reads from this key. A user `defineAnnotation('codecs')`\n * handle is not structurally prevented, but its behavior with the\n * emitter and the runtime is undefined and we make no compatibility\n * guarantees about it.\n * - Target-specific keys such as `pg` (and equivalents on other\n * targets) are similarly reserved for adapter / target use.\n *\n * `applicableTo` declares which operation kinds the annotation may attach\n * to. The lane terminals' type-level `ValidAnnotations<K, As>` gate rejects\n * annotations whose `Kinds` does not include the terminal's `K`; the\n * runtime helper `assertAnnotationsApplicable` does the equivalent at\n * runtime so casts and `any` cannot bypass the gate.\n */\nexport interface DefineAnnotationOptions<Kinds extends OperationKind> {\n readonly namespace: string;\n readonly applicableTo: readonly Kinds[];\n}\n\n/**\n * Defines a typed annotation handle.\n *\n * Two-step call form. The first step takes the `Payload` type argument\n * (TypeScript cannot infer `Payload` from anything in the options, so it\n * must be supplied explicitly); the second step takes the runtime options\n * and infers `Kinds` from the `applicableTo` array via a `const` type\n * parameter, so the operation kinds appear exactly once at the call site.\n *\n * @example\n * ```typescript\n * // Read-only annotation. Lane terminals like `db.User.first(...)` accept\n * // it; `db.User.create(...)` rejects it at the type level.\n * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * }); // Kinds inferred as 'read'\n *\n * // Write-only annotation. Mirror image.\n * const auditAnnotation = defineAnnotation<{ actor: string }>()({\n * namespace: 'audit',\n * applicableTo: ['write'],\n * }); // Kinds inferred as 'write'\n *\n * // Annotation applicable to both kinds (e.g. tracing).\n * const otelAnnotation = defineAnnotation<{ traceId: string }>()({\n * namespace: 'otel',\n * applicableTo: ['read', 'write'],\n * }); // Kinds inferred as 'read' | 'write'\n * ```\n *\n * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the\n * list of framework-internal namespaces (`codecs`, target-specific keys).\n * `defineAnnotation` does not structurally prevent a user from naming a\n * reserved namespace, but the framework makes no compatibility guarantee\n * about handles that do.\n */\nexport function defineAnnotation<Payload>(): <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n) => AnnotationHandle<Payload, Kinds> {\n return <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n ): AnnotationHandle<Payload, Kinds> => {\n const namespace = options.namespace;\n const applicableTo: ReadonlySet<Kinds> = Object.freeze(new Set(options.applicableTo));\n\n function handle(value: Payload): AnnotationValue<Payload, Kinds> {\n return Object.freeze({\n __annotation: true as const,\n namespace,\n value,\n applicableTo,\n });\n }\n\n function read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined {\n const stored = plan.meta.annotations?.[namespace];\n if (!isAnnotationValue(stored)) {\n return undefined;\n }\n if (stored.namespace !== namespace) {\n // Defensive: a different handle wrote under our namespace key.\n return undefined;\n }\n return stored.value as Payload;\n }\n\n return Object.freeze(\n Object.assign(handle, {\n namespace,\n applicableTo,\n read,\n }),\n );\n };\n}\n\n/**\n * Type-level applicability gate consumed by lane terminals.\n *\n * Maps a tuple of `AnnotationValue`s to a tuple where each element either\n * keeps its annotation type (when the annotation's declared `Kinds`\n * includes the terminal's operation kind `K`) or resolves to `never`\n * (when the kinds are incompatible). A `never` element makes the entire\n * tuple unassignable, surfacing the mismatch as a type error at the call\n * site of the terminal.\n *\n * The SQL DSL builders constrain their variadic `...annotations`\n * parameter via `As & ValidAnnotations<K, As>`. **The intersection is\n * load-bearing** — see the note below. The ORM terminals deliberately\n * sidestep this trick by taking one annotation per `meta.annotate(...)`\n * call (no variadic-tuple inference involved), so `ValidAnnotations` is\n * consumed only by the SQL DSL today.\n *\n * @example\n * ```typescript\n * class SelectQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'read', As>\n * ): SelectQuery<Row>;\n * }\n *\n * class InsertQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'write', As>\n * ): InsertQuery<Row>;\n * }\n *\n * db.users.select('id').annotate(cacheAnnotation({ ttl: 60 }));\n * // ✓ cacheAnnotation declares 'read'; SelectQuery.annotate requires 'read'.\n *\n * db.users.insert([{ name: 'Alice' }]).annotate(cacheAnnotation({ ttl: 60 }));\n * // ✗ cacheAnnotation declares 'read'; InsertQuery.annotate requires 'write'.\n * // Element resolves to `never` → tuple unassignable → type error.\n * ```\n *\n * **Why `As & ValidAnnotations<K, As>` and not `ValidAnnotations<K, As>`\n * alone.** TypeScript's variadic-tuple inference is too forgiving when\n * the parameter type refers to `As` only through `ValidAnnotations`: it\n * will pick an `As` that makes the call valid even when the gated tuple\n * would contain `never` for an inapplicable element. The intersection\n * pins `As` to the actual call-site tuple AND requires it to be\n * assignable to the gated form. A `never` element in the gated tuple\n * then collapses the corresponding intersection position to `never`,\n * and the inapplicable argument fails to assign — surfacing the mismatch\n * as a type error at the call site.\n *\n * The runtime helper `assertAnnotationsApplicable` covers the equivalent\n * check at runtime so casts and `any` cannot bypass this gate.\n */\nexport type ValidAnnotations<\n K extends OperationKind,\n As extends readonly AnnotationValue<unknown, OperationKind>[],\n> = {\n readonly [I in keyof As]: As[I] extends AnnotationValue<infer P, infer Kinds>\n ? K extends Kinds\n ? AnnotationValue<P, Kinds>\n : never\n : never;\n};\n\n/**\n * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if\n * any annotation in `annotations` declares an `applicableTo` set that does\n * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,\n * ORM `Collection` terminals) to fail closed when the type-level\n * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic\n * invocation.\n *\n * Passes silently on:\n * - empty arrays\n * - annotations whose `applicableTo` includes `kind`\n *\n * Throws on:\n * - any annotation whose `applicableTo` does not include `kind`. The\n * error names the offending annotation's `namespace` and the\n * `terminalName` so users can locate the misuse.\n *\n * @example\n * ```typescript\n * // Inside an ORM read terminal:\n * assertAnnotationsApplicable(annotations, 'read', 'first');\n * ```\n */\nexport function assertAnnotationsApplicable(\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n kind: OperationKind,\n terminalName: string,\n): void {\n for (const annotation of annotations) {\n if (!annotation.applicableTo.has(kind)) {\n throw runtimeError(\n 'RUNTIME.ANNOTATION_INAPPLICABLE',\n `Annotation '${annotation.namespace}' is not applicable to '${kind}' operations (terminal: '${terminalName}'). The annotation declares applicableTo = [${Array.from(\n annotation.applicableTo,\n )\n .map((k) => `'${k}'`)\n .join(', ')}].`,\n {\n namespace: annotation.namespace,\n terminalName,\n kind,\n applicableTo: Array.from(annotation.applicableTo),\n },\n );\n }\n }\n}\n\n/**\n * Type guard for branded annotation values stored in `plan.meta.annotations`.\n *\n * Internal — used by `AnnotationHandle.read` to distinguish user\n * annotations (created by calling a handle returned from\n * `defineAnnotation(...)`) from framework-internal metadata that may\n * happen to live under the same namespace key.\n */\nfunction isAnnotationValue(value: unknown): value is AnnotationValue<unknown, OperationKind> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { readonly __annotation?: unknown };\n return candidate.__annotation === true;\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * context is already aborted at the precheck site. Centralises the\n * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site (and the `beforeExecute` middleware phase)\n * repeats. Accepts both the framework `CodecCallContext` and the\n * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.\n */\nexport function checkAborted(\n ctx: { readonly signal?: AbortSignal },\n phase: RuntimeAbortedPhase,\n): void {\n if (ctx.signal?.aborted) {\n throw runtimeAborted(phase, ctx.signal.reason);\n }\n}\n\n/**\n * Race a per-cell `Promise.all` (or any other in-flight work promise) against\n * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly\n * even when codec bodies ignore the signal. In-flight bodies that ignore the\n * signal are abandoned and run to completion in the background — the\n * cooperative-cancellation contract documented in ADR 204.\n *\n * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with\n * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —\n * that path is the canonical \"aborted at entry\" surface and avoids\n * scheduling the work promise. As a defensive belt-and-braces, this helper\n * also handles the already-aborted case internally: `AbortSignal` does not\n * replay past abort events to listeners registered after the abort, so we\n * inspect `signal.aborted` synchronously and reject with the sentinel\n * before installing the listener. The rejection is still attributed to the\n * abort path via the sentinel-identity check.\n *\n * Distinguishing the rejection source is load-bearing for AC-ERR4\n * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).\n * The semantically equivalent `abortable(signal)` helper in\n * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,\n * which is not stably distinguishable from a codec-thrown error by identity\n * alone (a fresh fallback DOMException is allocated per call). We instead\n * track abort attribution with a unique sentinel: only the `onAbort` listener\n * installed here ever rejects with the sentinel, so an `error === sentinel`\n * identity check after the race is unambiguous.\n *\n * Lives in `framework-components` (rather than the SQL family, where it\n * originated in m2) so every family runtime that needs cooperative\n * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode\n * today, Mongo encode in m3) shares the same attribution logic.\n */\nexport async function raceAgainstAbort<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n phase: RuntimeAbortedPhase,\n): Promise<T> {\n if (signal === undefined) {\n return await work;\n }\n const sentinel: { reason: unknown } = { reason: undefined };\n let onAbort: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n if (signal.aborted) {\n sentinel.reason = signal.reason;\n reject(sentinel);\n return;\n }\n onAbort = () => {\n sentinel.reason = signal.reason;\n reject(sentinel);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n return await Promise.race([work, abortPromise]);\n } catch (error) {\n if (error === sentinel) {\n throw runtimeAborted(phase, sentinel.reason);\n }\n throw error;\n } finally {\n if (onAbort) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n}\n","import type { ExecutionPlan } from './query-plan';\nimport { checkAborted, raceAgainstAbort } from './race-against-abort';\nimport type {\n ParamRefMutator,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Runs every middleware's `beforeExecute` hook in registration order,\n * threading through the (optional) family-specific `paramsMutator`.\n *\n * Why this lives outside {@link runWithMiddleware}: middleware that\n * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK\n * round-trip) must run *before* the family runtime encodes those\n * parameters to driver wire format. Family runtimes call\n * `runBeforeExecuteChain` between the AST → plan lowering step and\n * the parameter encode step; the encode then observes the mutator's\n * `currentParams()` view. `runWithMiddleware` retains the rest of\n * the lifecycle (`intercept`, driver/row source loop, `onRow`,\n * `afterExecute`) but no longer fires `beforeExecute` itself.\n *\n * Lifecycle within this helper:\n *\n * 1. For each middleware in registration order, if `beforeExecute`\n * is implemented:\n * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the\n * caller already aborted at entry.\n * - The hook is invoked with `(plan, ctx, paramsMutator)`. A\n * middleware body that ignores the mutator stays compatible —\n * JavaScript allows extra positional arguments.\n * - If the hook returns a Promise, it is raced against\n * `ctx.signal` via {@link raceAgainstAbort} so cooperative\n * cancellation surfaces a `RUNTIME.ABORTED { phase:\n * 'beforeExecute' }` envelope even when the body itself\n * ignores the signal.\n *\n * Error propagation: any error thrown by a `beforeExecute` body\n * (or surfaced by the abort race) propagates out of this helper\n * unchanged. The family runtime is responsible for converting it\n * into the appropriate `afterExecute(completed: false)` notification\n * once `runWithMiddleware` runs.\n *\n * Relationship to {@link runWithMiddleware}: the framework's\n * `RuntimeCore.execute` template calls this helper between\n * `lower(plan)` and `runWithMiddleware(...)`. Family runtimes that\n * override `execute` (e.g. SQL, which inlines lower + encode for\n * direct mutator threading) call this helper themselves at the\n * equivalent point — between the family's AST → draft-plan\n * lowering and the parameter-encode step.\n *\n * Intercept ordering: this helper fires unconditionally before\n * `runWithMiddleware`. `intercept` (inside `runWithMiddleware`)\n * therefore observes the post-`beforeExecute` plan — mutator\n * mutations are visible in the params interceptors see. The\n * trade-off is documented on `RuntimeMiddleware.intercept`.\n */\nexport async function runBeforeExecuteChain<\n TExec extends ExecutionPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n>(\n plan: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>,\n ctx: RuntimeMiddlewareContext,\n paramsMutator?: TMutator,\n): Promise<void> {\n for (const mw of middleware) {\n if (!mw.beforeExecute) {\n continue;\n }\n checkAborted(ctx, 'beforeExecute');\n const work = mw.beforeExecute(plan, ctx, paramsMutator as TMutator);\n if (work !== undefined) {\n await raceAgainstAbort(Promise.resolve(work), ctx.signal, 'beforeExecute');\n }\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware\n * lifecycle's intercept + row-source + termination phases.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `intercept(exec, ctx)`. The\n * first non-`undefined` result wins; subsequent middleware's `intercept`\n * does not fire. On a hit, the runtime emits a `middleware.intercept`\n * debug event naming the winning middleware, switches the row source to\n * the intercepted rows, and proceeds with `source: 'middleware'`. On\n * all-passthrough (every `intercept` returns `undefined` or is omitted),\n * `source: 'driver'` is used and the row source is `runDriver()`.\n * 2. Iterate the row source. On the driver path, for each row, for each\n * middleware in registration order: `onRow(row, exec, ctx)`; then yield\n * the row. On the intercepted hit path, `onRow` is skipped — intercepted\n * rows did not originate from a driver row stream — but rows are still\n * yielded to the consumer in order.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },\n * ctx)`.\n * 4. On any error thrown during steps 1–2: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false, source }, ctx)`. Errors thrown by `afterExecute`\n * during the error path are swallowed so they do not mask the original\n * error. The original error is then rethrown.\n *\n * `beforeExecute` is **not** fired here — see\n * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family\n * runtimes call that helper between the AST → plan lowering step and\n * the parameter encode step so middleware that mutates ParamRef\n * values (e.g. cipherstash bulk-encrypt) can have its mutations\n * visible to encode. `runWithMiddleware` operates on the fully-\n * encoded plan; interceptors therefore observe a fully-mutated,\n * encoded plan.\n *\n * The `source` field on `AfterExecuteResult` lets observers (telemetry,\n * lints, budgets) distinguish driver-served from middleware-served\n * executions without needing their own out-of-band signal.\n *\n * This helper is the single canonical implementation of the\n * intercept-and-row-source loop; family runtimes should not\n * reimplement it.\n */\nexport function runWithMiddleware<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n let source: 'driver' | 'middleware' = 'driver';\n // Deferred so a winning interceptor can skip `runDriver()` entirely.\n // For factories that lazily produce async generators this is a no-op,\n // but factories that do eager work (e.g. acquiring a connection,\n // sending a query) must not run on the intercepted hit path.\n let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;\n\n try {\n for (const mw of middleware) {\n if (!mw.intercept) {\n continue;\n }\n // Mark the lifecycle as middleware-driven *before* awaiting the\n // hook. If `intercept` throws, the catch block reports the failure\n // as `source: 'middleware'` — the failure originated in the\n // intercept chain, not in the driver. If `intercept` returns\n // `undefined` (passthrough), we revert to `'driver'` and continue.\n source = 'middleware';\n const result = await mw.intercept(exec, ctx);\n if (result === undefined) {\n source = 'driver';\n continue;\n }\n ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });\n // The intercepted rows are typed as `Record<string, unknown>` at\n // the SPI level; the consumer's `Row` type parameter is enforced by\n // the caller (via the plan's phantom `_row`) the same way driver\n // rows are. Cast through unknown to bridge the SPI shape to the\n // caller-supplied Row.\n rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;\n break;\n }\n\n if (source === 'driver') {\n rowSource = runDriver();\n }\n\n // `rowSource` is always assigned by this point: either the intercepted\n // rows (on a hit) or `runDriver()` (on the driver path).\n for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import type { CodecCallContext } from '../shared/codec-types';\nimport { AsyncIterableResult } from './async-iterable-result';\nimport { runBeforeExecuteChain } from './before-execute-chain';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { checkAborted } from './race-against-abort';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecuteOptions,\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runBeforeExecuteChain(exec, this.middleware, this.ctx)` — concrete;\n * runs every middleware's `beforeExecute` hook after lowering but\n * before the row source is opened. Family runtimes that need a\n * params mutator visible to a downstream encode step (SQL) override\n * `execute` and call this helper themselves at the equivalent\n * pre-encode point.\n * 4. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; runs the intercept chain,\n * drives the row source, fires `onRow` / `afterExecute`. Does\n * **not** fire `beforeExecute` — see step 3.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n *\n * `ctx` carries per-query cancellation (and any future fields on\n * `CodecCallContext`); concrete subclasses forward it to the\n * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,\n * Mongo's `resolveValue` in m3). The runtime allocates one ctx per\n * `execute()` call and threads the same reference everywhere; the\n * `signal` field inside may be `undefined`, but the ctx object itself\n * is always present.\n */\n protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call. The ctx object is always allocated; the\n // `signal` field is only included when a signal was supplied (required\n // under exactOptionalPropertyTypes — `{ signal: undefined }` would not\n // satisfy `signal?: AbortSignal`).\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n\n // Per-execute middleware context. Spread the stored runtime-level\n // template and mint a fresh `planExecutionId` so every hook in this\n // call observes the same value, and two executions of the same plan\n // observe distinct values. ADR 220. The same reference is threaded\n // through `runBeforeExecuteChain` and `runWithMiddleware`; the plan\n // itself flows through unchanged.\n const execCtx: RuntimeMiddlewareContext = {\n ...self.ctx,\n planExecutionId: crypto.randomUUID(),\n };\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n // Pre-check the signal at entry so an already-aborted caller observes\n // RUNTIME.ABORTED on the first `next()` without any work being done.\n checkAborted(codecCtx, 'stream');\n\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n // Fire the framework-level `beforeExecute` chain on the lowered\n // plan before opening the row source. Families that need\n // pre-encode mutator visibility (SQL) override `execute` to\n // inject the same chain at the equivalent point.\n await runBeforeExecuteChain<TExec>(exec, self.middleware, execCtx);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n execCtx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\n/**\n * Per-execute context threaded through every middleware phase\n * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per\n * `runtime.execute()` call and shared by reference across all\n * middleware in the chain.\n *\n * - `signal` carries the per-query `AbortSignal` -- the same\n * reference that `runtime.execute(plan, { signal })` was invoked\n * with, and the same reference threaded into the per-call\n * `CodecCallContext` (ADR 207). Middleware that wraps a\n * network-backed SDK forwards `ctx.signal` into that SDK to\n * propagate caller cancellation; pure-CPU middleware ignores it.\n *\n * Symmetric plumbing across all middleware phases (rather than only\n * `beforeExecute`) is a deliberate choice: a middleware that wraps a\n * downstream observability hook or post-processor in `afterExecute` /\n * `onRow` needs the same cancellation reach as its `beforeExecute`\n * counterpart.\n */\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n /**\n * Returns a stable string identifying the (storage, statement, params)\n * tuple of an execution. Two semantically equivalent executions return\n * the same string. Used by middleware that need per-execution identity\n * (caching, request coalescing).\n *\n * The family runtime owns the implementation:\n * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`\n * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`\n *\n * The method is `async` because the underlying digest helper\n * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`\n * primitive is asynchronous by design.\n *\n * The returned string is intended to be consumed directly as a `Map` key\n * — it is not (and should not be) further hashed by callers.\n */\n contentHash(exec: ExecutionPlan): Promise<string>;\n /**\n * Per-execute cancellation signal threaded through every middleware\n * phase. Middleware that wraps async work or downstream cancellable\n * primitives should observe this and abort early when the consumer\n * cancels.\n */\n readonly signal?: AbortSignal;\n /**\n * Identifies the queryable scope this execution is running under.\n *\n * - `'runtime'` — top-level `runtime.execute(plan)`. The default scope\n * used by the standard read/write paths.\n * - `'connection'` — `connection.execute(plan)` after\n * `runtime.connection()` checked out a connection from the pool.\n * - `'transaction'` — `transaction.execute(plan)` inside an explicit\n * transaction, or a query routed through `withTransaction`.\n *\n * Middleware that should only act at the top level read this field to\n * bypass non-runtime scopes. The cache middleware uses it to skip\n * caching inside transactions (where read-after-write coherence is the\n * caller's expectation) and dedicated connections (where the user has\n * explicitly stepped outside the shared cache surface). Observers that\n * don't care about the scope can ignore the field.\n *\n * Family runtimes populate this at context-construction time per\n * scope. Existing middleware that ignore the field are unaffected.\n */\n readonly scope: 'runtime' | 'connection' | 'transaction';\n /**\n * Identity for one `execute()` call. The runtime mints a fresh value via\n * `crypto.randomUUID()` when it constructs the per-execute context, and\n * the same context reference is threaded through every middleware phase\n * (`beforeExecute`, `intercept`, `onRow`, `afterExecute`). Every hook in\n * one execute call therefore observes the same `planExecutionId`; two\n * executions of the same plan observe distinct values. Use this to\n * correlate observations across the lifecycle of a single execute call\n * (tracing, timing, audit). See ADR 220.\n */\n readonly planExecutionId: string;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n /**\n * Indicates where the rows observed during this execution came from.\n *\n * - `'driver'` — the default. Rows came from the underlying driver via\n * `runDriver` / `runWithMiddleware`'s normal path.\n * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited\n * execution and supplied the rows directly. The driver was not invoked.\n *\n * Observers (telemetry, lints, budgets) that need to distinguish between\n * driver-served and middleware-served executions read this field.\n * Observers that don't care can ignore it.\n */\n readonly source: 'driver' | 'middleware';\n}\n\n/**\n * Result of a successful `RuntimeMiddleware.intercept` hook.\n *\n * Carries the rows that the middleware wishes to return in place of\n * invoking the driver. The runtime iterates `rows` in order and yields\n * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are\n * all skipped on the hit path. `afterExecute` still fires with\n * `source: 'middleware'`.\n *\n * `rows` accepts both `Iterable` (arrays, sync generators) and\n * `AsyncIterable` (async generators). `for await` natively handles both\n * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the\n * orchestrator does not need to branch on the variant. Cached arrays in\n * the cache middleware are the common case; streaming variants support\n * future use cases like mock layers replaying recordings.\n *\n * Row shape is `Record<string, unknown>` — the same untyped shape\n * `onRow` receives. The SQL runtime decodes intercepted rows through its\n * normal codec pass, so interceptors cache and return raw (undecoded)\n * rows.\n */\nexport interface InterceptResult {\n readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;\n}\n\n/**\n * Marker interface for family-specific param-ref mutators threaded into\n * `beforeExecute` as the third argument. The framework treats the mutator\n * opaquely — it allocates and forwards the family's mutator instance so\n * `runWithMiddleware` can stay family-agnostic. SQL extends this with\n * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with\n * `MongoParamRefMutator` (over `MongoParamRef`).\n *\n * Extension authors target the family-specific mutator type, not this\n * marker.\n */\ndeclare const PARAM_REF_MUTATOR_BRAND: unique symbol;\nexport type ParamRefMutator = { readonly [PARAM_REF_MUTATOR_BRAND]?: never };\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n *\n * `TMutator` is the family-specific {@link ParamRefMutator} the runtime\n * threads into `beforeExecute(plan, ctx, params)` as a third argument.\n * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile\n * — TypeScript permits assigning a function with fewer parameters to a\n * function-typed slot that declares more. The third arg is additive.\n */\nexport interface RuntimeMiddleware<\n TPlan extends QueryPlan = QueryPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n /**\n * Optional short-circuit hook. Runs inside `runWithMiddleware`, after\n * the orchestrator receives the lowered plan and before any\n * `beforeExecute` hook fires. Middleware run in registration order; the\n * first to return a non-`undefined` `InterceptResult` wins, and\n * subsequent middleware's `intercept` does not fire.\n *\n * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.\n * `afterExecute` still fires with `source: 'middleware'`.\n *\n * Returning `undefined` (or omitting the hook entirely) signals\n * passthrough — execution proceeds through the normal driver path.\n *\n * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`\n * as the original `Error` — no envelope is guaranteed at this layer.\n * Before rethrowing, `afterExecute` fires with `completed: false` and\n * `source: 'middleware'`. Errors thrown by `afterExecute` during the\n * error path remain swallowed (existing semantics, unchanged).\n *\n * Used by middleware that need to short-circuit execution and supply\n * rows directly: caching, mocks, rate limiting, circuit breaking.\n */\n intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;\n /**\n * Fires after the family runtime has produced a draft execution\n * plan from the AST, but before the family encodes parameter values\n * to driver wire format. Mutations applied via the\n * family-specific `params` mutator are visible to the subsequent\n * encode step.\n *\n * Lifecycle position (SQL example):\n * `runBeforeCompile → lowerSqlPlan → beforeExecute → encodeParams → intercept → driver`.\n *\n * The `params` argument is a family-specific {@link ParamRefMutator}\n * scoped to the value slots of `ParamRef` nodes in the plan's AST.\n * Middleware that doesn't need to mutate params can ignore the\n * argument; existing `(plan)` / `(plan, ctx)` bodies stay compatible.\n *\n * `ctx.signal` carries the per-query `AbortSignal`; middleware that\n * wraps a network SDK forwards it. Cooperative cancellation\n * surfaces a `RUNTIME.ABORTED { phase: 'beforeExecute' }` envelope\n * promptly even when the body ignores the signal.\n *\n * Intercept ordering: `intercept` runs *after* this hook; an\n * interceptor that short-circuits the driver path still observes\n * the post-`beforeExecute`, fully-encoded plan. The trade-off is\n * that any `beforeExecute` SDK round-trips happen even when a\n * downstream interceptor would have skipped the driver entirely.\n */\n beforeExecute?(\n plan: TPlan,\n ctx: RuntimeMiddlewareContext,\n params?: TMutator,\n ): void | Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family middleware — one that doesn't constrain `familyId` or\n * `targetId` and is therefore compatible with any family runtime's\n * middleware array (`SqlMiddleware[]`, `MongoMiddleware[]`, etc.).\n *\n * The intersection `RuntimeMiddleware & { familyId?: undefined; targetId?: undefined }`\n * pins both optional properties to exactly `undefined` (intersecting\n * `string | undefined` with `undefined` collapses to `undefined`). Under\n * `exactOptionalPropertyTypes: true`, the plain `RuntimeMiddleware` shape\n * — with `familyId?: string` — is *not* assignable to `SqlMiddleware`\n * (which narrows `familyId?: 'sql'`) because `string` is wider than\n * `'sql'`. Pinning the property to `undefined` makes the value a subtype\n * of every narrowed variant: `undefined` extends both `'sql' | undefined`\n * and `'mongo' | undefined`, so a `CrossFamilyMiddleware` value drops\n * into a SQL or Mongo middleware slot without a cast.\n *\n * Cross-family middleware factories (`createCacheMiddleware`, future\n * `audit` / OTel middleware) declare this as their return type so the\n * cross-family typing is named once rather than re-spelled at every call\n * site.\n */\nexport type CrossFamilyMiddleware<TPlan extends QueryPlan = QueryPlan> =\n RuntimeMiddleware<TPlan> & {\n readonly familyId?: undefined;\n readonly targetId?: undefined;\n };\n\n/**\n * Optional per-`execute` options accepted by every family runtime.\n *\n * `signal` is the per-query cancellation signal. The runtime threads the\n * signal through to every codec call for the query and uses it to short-\n * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.\n * Omitting the option (or passing `undefined`) preserves today's behavior\n * bit-for-bit.\n */\nexport interface RuntimeExecuteOptions {\n readonly signal?: AbortSignal;\n readonly scope?: 'runtime' | 'connection' | 'transaction';\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n","import {\n type AnnotationValue,\n assertAnnotationsApplicable,\n type OperationKind,\n} from './annotations';\n\n/**\n * Per-terminal meta configurator handed to user callbacks. The terminal's\n * operation kind `K` is fixed by the terminal that constructed the builder;\n * `annotate(...)` accepts only annotations whose declared `Kinds` include\n * `K`.\n *\n * The conditional parameter type\n * `K extends Kinds ? AnnotationValue<P, Kinds> : never` collapses to `never`\n * for inapplicable annotations, surfacing the mismatch as a type error at\n * the call site of `meta.annotate(...)`. No variadic-tuple inference is\n * involved — TypeScript infers `Kinds` from the annotation argument and\n * checks the conditional directly.\n *\n * The runtime gate inside `annotate` (via\n * `assertAnnotationsApplicable`) catches cast / `any` / dynamic bypasses\n * and throws `RUNTIME.ANNOTATION_INAPPLICABLE`.\n *\n * `annotate` returns the builder for chaining; the return value of the\n * configurator callback is unused, so both block-body and expression-body\n * callbacks compile.\n *\n * @example\n * ```typescript\n * await db.User.find({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60 })));\n * await db.User.create(input, (meta) => {\n * meta.annotate(auditAnnotation({ actor: 'system' }));\n * meta.annotate(otelAnnotation({ traceId }));\n * });\n * ```\n */\nexport interface MetaBuilder<K extends OperationKind> {\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this;\n}\n\n/**\n * Lane-side view of a meta builder. Extends the public `MetaBuilder<K>`\n * surface with `annotations` so lane terminals can read the recorded map\n * after invoking the user configurator.\n *\n * Lane terminals construct one of these via `createMetaBuilder(kind, terminalName)`,\n * pass it to the user callback as `MetaBuilder<K>` (the narrower public\n * view), then read `meta.annotations` to thread the recorded values into\n * `plan.meta.annotations`.\n */\nexport interface LaneMetaBuilder<K extends OperationKind> extends MetaBuilder<K> {\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n}\n\nclass MetaBuilderImpl<K extends OperationKind> implements LaneMetaBuilder<K> {\n readonly #kind: K;\n readonly #terminalName: string;\n readonly #annotations = new Map<string, AnnotationValue<unknown, OperationKind>>();\n\n constructor(kind: K, terminalName: string) {\n this.#kind = kind;\n this.#terminalName = terminalName;\n }\n\n get annotations(): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n return this.#annotations;\n }\n\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this {\n // Inside the body, the conditional `K extends Kinds ? AnnotationValue<P, Kinds> : never`\n // is opaque to TypeScript — it can't pick a branch without a concrete\n // K. Widen to the structural shape so we can call into the runtime\n // gate. The runtime gate (assertAnnotationsApplicable) is what\n // catches cast bypasses where the conditional would have resolved to\n // `never` had the type checker been allowed to specialise.\n const value = annotation as AnnotationValue<unknown, OperationKind>;\n assertAnnotationsApplicable([value], this.#kind, this.#terminalName);\n this.#annotations.set(value.namespace, value);\n return this;\n }\n}\n\n/**\n * Construct a lane-side meta builder for a terminal of operation kind `K`.\n *\n * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a\n * `terminalName` for error messages, hand the resulting builder to the\n * user-supplied configurator callback (typed as `MetaBuilder<K>`, the\n * narrower public view), and read `meta.annotations` afterwards to thread\n * the recorded values into `plan.meta.annotations`.\n */\nexport function createMetaBuilder<K extends OperationKind>(\n kind: K,\n terminalName: string,\n): LaneMetaBuilder<K> {\n return new MetaBuilderImpl(kind, terminalName);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAa,kBAAkB;;;;;;;AAiB/B,SAAgB,eAAe,OAA+C;CAC5E,OACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC9C,cAAc,SACd,cAAc;AAElB;AAEA,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,OAAO;CAC/B,OAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;CAChB,CAAC;CAED,OAAO,OAAO,OAAO,OAAO;EAC1B;EACA,UAAU,gBAAgB,IAAI;EAC9B,UAAU;EACV;EACA;CACF,CAAC;AACH;AAEA,SAAS,gBAAgB,MAAgD;CACvE,MAAM,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM;CACrC,QAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,UACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;;;;AAWA,SAAgB,eAAe,OAA4B,OAAuC;CAChG,MAAM,WAAW,aAAa,iBAAiB,4BAA4B,S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cSQy.d.mts.map
13
+ //# sourceMappingURL=types-import-spec-DRKzrJ20.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types-import-spec-BxI5cSQy.d.mts","names":[],"sources":["../src/shared/types-import-spec.ts"],"mappings":";;AAIA;;;UAAiB,eAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA;EAAA,SACA,KAAA;AAAA"}
1
+ {"version":3,"file":"types-import-spec-DRKzrJ20.d.mts","names":[],"sources":["../src/shared/types-import-spec.ts"],"mappings":";;AAIA;;;UAAiB,eAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA;EAAA,SACA,KAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils/canonicalize-json.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * `JSON.stringify` with object keys sorted lexicographically at every level. Two structurally equal values produce the same string regardless of object key insertion order, so the result is a stable cache key for JSON-shaped values.\n *\n * Array order is preserved; primitives serialise as their JSON form. Inputs are expected to be JSON-safe (the typeParams shape on {@link CodecRef} is `JsonValue`-constrained for this reason); callers that need to canonicalise non-JSON-safe values (BigInt, Dates, typed arrays) should use `canonicalStringify` from `@prisma-next/utils/canonical-stringify` instead.\n */\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n"],"mappings":";AAAA,SAAS,SAAS,OAAyB;CACzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,QAAQ;CAE3B,MAAM,SAAkC,OAAO,OAAO,IAAI;CAC1D,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,EAAE,KAAK,GACxC,OAAO,OAAO,SAAU,MAAkC,IAAI;CAEhE,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,KAAK,UAAU,SAAS,KAAK,CAAC;AACvC"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils/canonicalize-json.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * `JSON.stringify` with object keys sorted lexicographically at every level. Two structurally equal values produce the same string regardless of object key insertion order, so the result is a stable cache key for JSON-shaped values.\n *\n * Array order is preserved; primitives serialise as their JSON form. Inputs are expected to be JSON-safe (the typeParams shape on {@link CodecRef} is `JsonValue`-constrained for this reason); callers that need to canonicalise non-JSON-safe values (BigInt, Dates, typed arrays) should use `canonicalStringify` from `@prisma-next/utils/canonical-stringify` instead.\n */\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n"],"mappings":";AAAA,SAAS,SAAS,OAAyB;CACzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,QAAQ;CAE3B,MAAM,SAAkC,OAAO,OAAO,IAAI;CAC1D,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,GACxC,OAAO,OAAO,SAAU,MAAkC,IAAI;CAEhE,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,KAAK,UAAU,SAAS,KAAK,CAAC;AACvC"}
package/package.json CHANGED
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "name": "@prisma-next/framework-components",
3
- "version": "0.12.0",
3
+ "version": "0.13.0-dev.10",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Framework component types, assembly logic, and stack creation for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.12.0",
10
- "@prisma-next/operations": "0.12.0",
11
- "@prisma-next/ts-render": "0.12.0",
12
- "@prisma-next/utils": "0.12.0",
9
+ "@prisma-next/contract": "0.13.0-dev.10",
10
+ "@prisma-next/operations": "0.13.0-dev.10",
11
+ "@prisma-next/ts-render": "0.13.0-dev.10",
12
+ "@prisma-next/utils": "0.13.0-dev.10",
13
13
  "@standard-schema/spec": "^1.1.0",
14
14
  "arktype": "^2.2.0"
15
15
  },
16
16
  "devDependencies": {
17
- "@prisma-next/tsconfig": "0.12.0",
18
- "@prisma-next/tsdown": "0.12.0",
19
- "tsdown": "0.22.0",
17
+ "@prisma-next/tsconfig": "0.13.0-dev.10",
18
+ "@prisma-next/tsdown": "0.13.0-dev.10",
19
+ "tsdown": "0.22.1",
20
20
  "typescript": "5.9.3",
21
- "vitest": "4.1.6"
21
+ "vitest": "4.1.8"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "typescript": ">=5.9"
@@ -1,4 +1,8 @@
1
- import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';
1
+ import type {
2
+ Contract,
3
+ ContractMarkerRecord,
4
+ LedgerEntryRecord,
5
+ } from '@prisma-next/contract/types';
2
6
  import type {
3
7
  AdapterInstance,
4
8
  DriverInstance,
@@ -91,6 +95,16 @@ export interface ControlFamilyInstance<TFamilyId extends string, TSchemaIR>
91
95
  readonly driver: ControlDriverInstance<TFamilyId, string>;
92
96
  }): Promise<ReadonlyMap<string, ContractMarkerRecord>>;
93
97
 
98
+ /**
99
+ * Reads the per-migration ledger journal in apply order. When `space` is
100
+ * omitted, returns rows for every space. Returns an empty array when the
101
+ * ledger store does not yet exist or has no matching rows.
102
+ */
103
+ readLedger(options: {
104
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
105
+ readonly space?: string;
106
+ }): Promise<readonly LedgerEntryRecord[]>;
107
+
94
108
  introspect(options: {
95
109
  readonly driver: ControlDriverInstance<TFamilyId, string>;
96
110
  readonly contract?: unknown;
@@ -105,10 +119,6 @@ export interface ControlAdapterInstance<TFamilyId extends string, TTargetId exte
105
119
 
106
120
  export interface ControlDriverInstance<TFamilyId extends string, TTargetId extends string>
107
121
  extends DriverInstance<TFamilyId, TTargetId> {
108
- query<Row = Record<string, unknown>>(
109
- sql: string,
110
- params?: readonly unknown[],
111
- ): Promise<{ readonly rows: Row[] }>;
112
122
  close(): Promise<void>;
113
123
  }
114
124