@prisma-idb/client-idb 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client-auto.mjs +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{idb-orm-JBg6si7u.mjs → idb-orm-C8yXJp6R.mjs} +74 -1
- package/dist/idb-orm-C8yXJp6R.mjs.map +1 -0
- package/dist/idb-orm-MOH1S3ES.d.mts.map +1 -1
- package/dist/{managed-client-BLdCyxUi.mjs → managed-client-DofL09P8.mjs} +2 -2
- package/dist/{managed-client-BLdCyxUi.mjs.map → managed-client-DofL09P8.mjs.map} +1 -1
- package/dist/orm.d.mts.map +1 -1
- package/dist/orm.mjs +1 -1
- package/package.json +9 -9
- package/dist/idb-orm-JBg6si7u.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"idb-orm-JBg6si7u.mjs","names":["_exhaustive","#contract","#modelName","#executor","#storeName","#state","#newGroupingKey","#includeRefinementMode","#clone","#resolveIncludeEntry","#buildScanPlan","#executeOrRows","#applyIncludes","#projectRows","#combinedFilterExpr","#executeNativeCount","#materialize","#planMeta","#countTerminal"],"sources":["../src/core/types.ts","../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/query-shaping.ts","../src/core/aggregate-builder.ts","../src/core/grouped-accessor.ts","../src/core/mutation-defaults.ts","../src/core/relation-loader.ts","../src/core/mutation-scope.ts","../src/core/relation-mutator.ts","../src/core/mutation-executor.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts"],"sourcesContent":["import type { Contract, ContractModelBase, ContractReferenceRelation } from \"@prisma/orm-framework/contract/types\";\nimport { domainModelsAtDefaultNamespace } from \"@prisma/orm-framework/contract/types\";\nimport type {\n ExtractIdbFieldInputTypes,\n ExtractIdbFieldOutputTypes,\n IdbKeyPath,\n IdbModelStorage,\n IdbStorage,\n} from \"@prisma-idb/target-idb/pack\";\n\n// Key comparison lives in target-idb so adapter-idb's filter evaluator can\n// share it. Re-exported here for the modules and public exports that already\n// import it from this file.\nexport { fieldValueToken, fieldValuesEqual, isValidIdbKey, keyEquals, keyToken } from \"@prisma-idb/target-idb/runtime\";\n\n// Re-export so consumers that only import from client-idb don't need a\n// separate target-idb dependency.\nexport type { IdbKeyPath };\n\n// Re-export for consumers who only import from client-idb\nexport type { IdbStorage };\n\n// ── Model-map extraction (v0.12.0 domain plane) ───────────────────────────────\n\n/**\n * Extract the model map from a contract by traversing the domain namespace.\n *\n * 0.14.0: `Contract` dropped the 2nd `TModels` type parameter; models are now\n * accessed via `domain.namespaces[ns].models`. For a single-namespace contract\n * (the only IDB case) this resolves to the typed model map; falls back to\n * `Record<string, ContractModelBase>` for un-typed/multi-namespace inputs.\n */\ntype ModelsOf<TContract> = TContract extends { readonly domain: { readonly namespaces: infer NS } }\n ? NS[keyof NS] extends { readonly models: infer M }\n ? M extends Record<string, ContractModelBase>\n ? M\n : Record<string, ContractModelBase>\n : Record<string, ContractModelBase>\n : Record<string, ContractModelBase>;\n\n// ── IdbContract convenience alias ─────────────────────────────────────────────\n\n/**\n * A `Contract` narrowed to the IDB storage shape. Accepts any contract whose\n * `storage` block includes an `stores` record, regardless of the model set or\n * whether type maps are attached.\n */\nexport type IdbContract = Contract<IdbStorage>;\n\n// ── Row type resolution (full type-maps path) ─────────────────────────────────\n\n/**\n * Resolve the output row type for a model from the contract's type maps.\n *\n * When `fieldOutputTypes` is parameterised (the emitted contract carries\n * `IdbContractWithTypeMaps<Base, IdbTypeMaps<Codecs, FieldOutputTypes, ...>>`),\n * each field gets the exact TypeScript type emitted by the family (e.g. `Date`\n * for `idb/date@1`).\n *\n * Falls back to `Record<string, unknown>` when type maps are absent (plain\n * `IdbContract` or when the model name is not in the type maps).\n */\n// FieldOutputTypes = { __unbound__: { User: {...} } } — union over namespace values\n// to get the flat model map, then look up ModelName.\ntype NsFieldOutputTypes<TContract> = ExtractIdbFieldOutputTypes<TContract>[keyof ExtractIdbFieldOutputTypes<TContract>];\n\ntype ResolvedOutputRow<TContract, ModelName extends string> = string extends keyof ExtractIdbFieldOutputTypes<TContract>\n ? Record<string, unknown>\n : NsFieldOutputTypes<TContract> extends Record<string, unknown>\n ? ModelName extends keyof NsFieldOutputTypes<TContract>\n ? { -readonly [K in keyof NsFieldOutputTypes<TContract>[ModelName]]: NsFieldOutputTypes<TContract>[ModelName][K] }\n : Record<string, unknown>\n : Record<string, unknown>;\n\n/**\n * Resolve the input row type for a model from the contract's type maps.\n *\n * Mirrors `ResolvedOutputRow` but uses `fieldInputTypes` — the input types\n * used for `create()`, `where()`, and mutation payloads.\n */\ntype NsFieldInputTypes<TContract> = ExtractIdbFieldInputTypes<TContract>[keyof ExtractIdbFieldInputTypes<TContract>];\n\ntype ResolvedInputRow<TContract, ModelName extends string> = string extends keyof ExtractIdbFieldInputTypes<TContract>\n ? Record<string, unknown>\n : NsFieldInputTypes<TContract> extends Record<string, unknown>\n ? ModelName extends keyof NsFieldInputTypes<TContract>\n ? { -readonly [K in keyof NsFieldInputTypes<TContract>[ModelName]]: NsFieldInputTypes<TContract>[ModelName][K] }\n : Record<string, unknown>\n : Record<string, unknown>;\n\n// ── Public row types ──────────────────────────────────────────────────────────\n\n/** The full TypeScript row shape returned by `all()`, `first()`, and `create()`. */\nexport type DefaultModelRow<TContract, ModelName extends string> = ResolvedOutputRow<TContract, ModelName>;\n\n// ── Where filter ──────────────────────────────────────────────────────────────\n\n/**\n * Partial equality filter applied as an in-memory predicate during cursor scans.\n *\n * All fields are optional — only provided fields are checked. Values use the\n * output types (from `fieldOutputTypes`) since the values are compared against\n * decoded row data.\n */\nexport type WhereFilter<TContract, ModelName extends string> = {\n readonly [K in keyof DefaultModelRow<TContract, ModelName>]?: DefaultModelRow<TContract, ModelName>[K];\n};\n\n// ── KeyPath / KeyType ─────────────────────────────────────────────────────────\n\n/**\n * The union of a model's `keyPath` field name(s), extracted from\n * `contract.models[ModelName].storage.keyPath`. For a single-field key this\n * is just that field name; for a compound key it's the union of every member\n * field name (NOT an ordered tuple — see {@link ModelKeyPathOrdered} for the\n * order-preserving form `KeyType` needs).\n *\n * A plain union is what `Omit`/`Pick` need, where order doesn't matter.\n */\nexport type ModelKeyPath<TContract, ModelName extends string> = ModelName extends keyof ModelsOf<TContract>\n ? ModelsOf<TContract>[ModelName] extends { storage: { keyPath: infer P } }\n ? P extends string\n ? P\n : P extends readonly string[]\n ? P[number]\n : never\n : never\n : never;\n\n/**\n * Like {@link ModelKeyPath}, but preserves declaration order as a tuple\n * (`readonly [\"a\", \"b\"]`, not the unioned `\"a\" | \"b\"`). A single-field key is\n * normalized to a 1-tuple (`readonly [\"id\"]`) so `KeyType` below can branch\n * on tuple shape uniformly. Needed because `findUnique`/`delete` accept the\n * key as a positional array for compound-key models (mirroring the\n * `IDBValidKey` array form IDB itself expects — see ADR-tracked decision in\n * Phase 9.1), which requires order, unlike `ModelKeyPath`'s Omit/Pick usage.\n */\nexport type ModelKeyPathOrdered<TContract, ModelName extends string> = ModelName extends keyof ModelsOf<TContract>\n ? ModelsOf<TContract>[ModelName] extends { storage: { keyPath: infer P } }\n ? P extends string\n ? readonly [P]\n : P extends readonly string[]\n ? P\n : never\n : never\n : never;\n\n/** Maps an ordered tuple of key field names to their resolved output types, preserving position. */\ntype KeyTupleType<TContract, ModelName extends string, Fields extends readonly string[]> = {\n [I in keyof Fields]: Fields[I] extends keyof ResolvedOutputRow<TContract, ModelName>\n ? ResolvedOutputRow<TContract, ModelName>[Fields[I] & keyof ResolvedOutputRow<TContract, ModelName>]\n : IDBValidKey;\n};\n\n/**\n * `true` only when `T` is exactly `never` — the tuple-wrap defeats\n * conditional-type distributivity (without it, `never extends never ? A : B`\n * called with a naked, union-distributing `T` short-circuits to `never`\n * itself rather than evaluating `A`/`B`). Needed because `never` is also a\n * structural subtype of every other concrete type (including a 2+-element\n * tuple type), so a plain `ModelKeyPathOrdered<...> extends readonly\n * [string, string, ...string[]]` check would incorrectly match `never`\n * (the loosely-typed/no-type-maps contract case) as if it were a real\n * compound key.\n */\ntype IsNever<T> = [T] extends [never] ? true : false;\n\n/**\n * TypeScript type of the primary key parameter for `findUnique()`/`delete()`.\n *\n * Single-field-key models keep today's scalar shape (e.g. `string`) — no\n * change for the common case, and untyped/loosely-typed contracts (no\n * emitted type maps — `ModelKeyPathOrdered` resolves to `never`) fall\n * through to the exact same `IDBValidKey` fallback `KeyType` always used\n * before compound keys existed. Compound-key models get an ordered tuple\n * type (e.g. `[string, Date]` for `@@id([orgId, effectiveFrom])`), matching\n * the `IDBValidKey` array IDB itself expects for a compound key-get — the\n * same value passes straight through to the driver with zero runtime\n * conversion.\n */\nexport type KeyType<TContract, ModelName extends string> =\n IsNever<ModelKeyPathOrdered<TContract, ModelName>> extends true\n ? ModelKeyPath<TContract, ModelName> extends keyof ResolvedOutputRow<TContract, ModelName>\n ? ResolvedOutputRow<TContract, ModelName>[ModelKeyPath<TContract, ModelName>]\n : IDBValidKey\n : ModelKeyPathOrdered<TContract, ModelName> extends readonly [infer Single extends string]\n ? Single extends keyof ResolvedOutputRow<TContract, ModelName>\n ? ResolvedOutputRow<TContract, ModelName>[Single]\n : IDBValidKey\n : KeyTupleType<TContract, ModelName, ModelKeyPathOrdered<TContract, ModelName>>;\n\n// ── Create input ──────────────────────────────────────────────────────────────\n\n/** The object store name for a model, extracted from `contract.domain...storage.storeName` (used to match `execution.mutations.defaults[].ref.table`). */\ntype ModelStoreName<TContract, ModelName extends string> = ModelName extends keyof ModelsOf<TContract>\n ? ModelsOf<TContract>[ModelName] extends { readonly storage: { readonly storeName: infer S } }\n ? S extends string\n ? S\n : never\n : never\n : never;\n\n/** Whether the model's object store has `autoIncrement: true` in `contract.storage.stores` (set by `@default(autoincrement())`). */\ntype IsAutoIncrementStore<TContract, ModelName extends string> = TContract extends {\n readonly storage: { readonly stores: infer Stores };\n}\n ? ModelStoreName<TContract, ModelName> extends keyof Stores\n ? Stores[ModelStoreName<TContract, ModelName>] extends { readonly autoIncrement: true }\n ? true\n : false\n : false\n : false;\n\n/**\n * The primary key field `create()` may omit because IDB generates it: the\n * key of a *single-field*-key model whose store has `autoIncrement: true`.\n * IDB's key generator is numeric-only and never runs without\n * `autoIncrement` — an absent key then makes `add()` throw `DataError` —\n * and it can't fill a compound key (`autoIncrement` + array `keyPath` is\n * rejected). App-generated keys (`uuid()`/`cuid()`) are covered separately\n * by {@link FieldsWithCreateDefault}; any other key must be supplied.\n */\ntype OptionalKeyPathField<TContract, ModelName extends string> =\n IsAutoIncrementStore<TContract, ModelName> extends true\n ? ModelKeyPathOrdered<TContract, ModelName> extends readonly [infer Single extends string]\n ? Single\n : never\n : never;\n\n/** {@link OptionalKeyPathField}, narrowed to a key that actually exists on the resolved input row (may be absent for models with no typed maps). */\ntype KeyPathField<TContract, ModelName extends string> = OptionalKeyPathField<TContract, ModelName> &\n keyof ResolvedInputRow<TContract, ModelName>;\n\n/** The flattened `execution.mutations.defaults` array type, or `never` for a contract with no execution section. */\ntype ExecutionDefaultsOf<TContract> = TContract extends {\n readonly execution: { readonly mutations: { readonly defaults: infer D } };\n}\n ? D extends readonly unknown[]\n ? D[number]\n : never\n : never;\n\n/**\n * Column names with an `onCreate` execution default for this model's store —\n * e.g. `temporal.updatedAt()`/bare `@updatedAt` fields, or any\n * `@default(...)` field (literal, `now()`, `uuid()`, `cuid()`). These are\n * omittable in `create()` even though the field itself isn't nullable,\n * since the runtime fills them in (`client-idb/src/core/mutation-defaults.ts`).\n */\ntype FieldsWithCreateDefault<TContract, ModelName extends string> = Extract<\n ExecutionDefaultsOf<TContract>,\n { readonly ref: { readonly table: ModelStoreName<TContract, ModelName> }; readonly onCreate: unknown }\n>[\"ref\"][\"column\"];\n\n/** {@link FieldsWithCreateDefault}, narrowed to keys that actually exist on the resolved input row (may be absent for models with no typed maps). */\ntype DefaultedInputField<TContract, ModelName extends string> = FieldsWithCreateDefault<TContract, ModelName> &\n keyof ResolvedInputRow<TContract, ModelName>;\n\n/**\n * Input shape for `create()`: the full input row with an `autoIncrement`\n * primary key made optional (see {@link OptionalKeyPathField}), and every\n * field with an `onCreate` execution default — including a `uuid()`/`cuid()`\n * key — also made optional. Any other key field stays required.\n */\nexport type CreateInput<TContract, ModelName extends string> = Omit<\n ResolvedInputRow<TContract, ModelName>,\n OptionalKeyPathField<TContract, ModelName> | FieldsWithCreateDefault<TContract, ModelName>\n> &\n Partial<\n Pick<\n ResolvedInputRow<TContract, ModelName>,\n KeyPathField<TContract, ModelName> | DefaultedInputField<TContract, ModelName>\n >\n >;\n\n// ── Relations ─────────────────────────────────────────────────────────────────\n\n/** Extract the relations record for a model. */\ntype ModelRelations<TContract, ModelName extends string> = ModelName extends keyof ModelsOf<TContract>\n ? ModelsOf<TContract>[ModelName] extends { relations: infer R }\n ? R extends Record<string, unknown>\n ? R\n : Record<string, never>\n : Record<string, never>\n : Record<string, never>;\n\n/**\n * Union of relation keys on a model that are `ContractReferenceRelation`s\n * (i.e. cross-store joins, not embedded documents).\n *\n * Used to constrain the `include()` method's `relation` parameter to only\n * valid reference relation names.\n */\nexport type ReferenceRelKeys<TContract, ModelName extends string> = {\n [K in keyof ModelRelations<TContract, ModelName>]: ModelRelations<\n TContract,\n ModelName\n >[K] extends ContractReferenceRelation\n ? K\n : never;\n}[keyof ModelRelations<TContract, ModelName>] &\n string;\n\n/**\n * TypeScript row type for an included relation.\n *\n * - `1:N` cardinality → `RelatedRow[]`\n * - `N:1` or `1:1` cardinality → `RelatedRow | null`\n */\ntype RelationRowType<TContract, ModelName extends string, RelKey extends string> = RelKey extends keyof ModelRelations<\n TContract,\n ModelName\n>\n ? ModelRelations<TContract, ModelName>[RelKey] extends ContractReferenceRelation\n ? ModelRelations<TContract, ModelName>[RelKey] extends {\n to: { model: infer To extends string };\n cardinality: infer C;\n }\n ? C extends \"1:N\"\n ? DefaultModelRow<TContract, To>[]\n : DefaultModelRow<TContract, To> | null\n : never\n : never\n : never;\n\n/**\n * Per-relation include marker tracked at the type level.\n *\n * - `true` — the relation is loaded as rows (array for `1:N`, single/null\n * otherwise), optionally refined by a `where`/`orderBy`/`take` callback.\n * - `\"scalar\"` — the relation is reduced to a `count()` (Phase 6.5), so the\n * row field becomes a `number` instead of related rows.\n */\nexport type IncludeMarker = true | \"scalar\";\n\n/** Which relations are included in the current accessor chain. */\nexport type IncludeSpec<TContract, ModelName extends string> = Partial<\n Record<ReferenceRelKeys<TContract, ModelName>, IncludeMarker>\n>;\n\n/** Empty include spec — no relations included. */\nexport type NoIncludes = Record<never, never>;\n\n/**\n * The relation fields contributed by a set of `.include()` calls.\n *\n * A key is added only when its `TIncludes` marker is set; the field type is\n * `number` for a scalar `count()` include and the cardinality-shaped related\n * row(s) otherwise. Split out from {@link IncludedRow} so {@link SelectedRow}\n * can re-use it on top of a projected (picked) scalar base.\n */\nexport type IncludeFields<TContract, ModelName extends string, TIncludes extends IncludeSpec<TContract, ModelName>> = {\n -readonly [\n K in keyof TIncludes & string as TIncludes[K] extends IncludeMarker ? K : never\n ]: TIncludes[K] extends \"scalar\" ? number : RelationRowType<TContract, ModelName, K>;\n};\n\n/**\n * A row type that merges the base model row with any included relation fields.\n *\n * The extra fields are only added when the corresponding key in `TIncludes` is\n * set, so the type stays narrow until `.include()` is called.\n */\nexport type IncludedRow<\n TContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName>,\n> = DefaultModelRow<TContract, ModelName> & IncludeFields<TContract, ModelName, TIncludes>;\n\n/**\n * The row type after an optional `.select()` projection.\n *\n * When `TSelected` is `never` (no `.select()` call) the full {@link IncludedRow}\n * is returned. Otherwise the scalar base is narrowed to the picked fields, with\n * any included relation fields preserved (mirrors the vendor `select()` which\n * keeps relations and narrows only scalar columns).\n */\nexport type SelectedRow<\n TContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName>,\n TSelected extends string,\n> = [TSelected] extends [never]\n ? IncludedRow<TContract, ModelName, TIncludes>\n : Pick<DefaultModelRow<TContract, ModelName>, TSelected & keyof DefaultModelRow<TContract, ModelName>> &\n IncludeFields<TContract, ModelName, TIncludes>;\n\n// ── Patch input ───────────────────────────────────────────────────────────────\n\n/**\n * Partial update shape for `update()`, `updateAll()`, `updateCount()`, and the\n * `update` arm of `upsert()`. All fields are optional — only provided fields\n * are shallow-merged onto the existing record.\n */\nexport type PatchInput<TContract, ModelName extends string> = Partial<DefaultModelRow<TContract, ModelName>>;\n\n// ── Relation mutation types ───────────────────────────────────────────────────\n\n/** Extracts the `to` model name for a named relation on a model. */\nexport type RelatedModelOf<\n TContract,\n ModelName extends string,\n RelName extends string,\n> = ModelName extends keyof ModelsOf<TContract>\n ? ModelsOf<TContract>[ModelName] extends {\n relations: Record<RelName, { to: { model: infer To extends string } }>;\n }\n ? To\n : string\n : string;\n\n/** Nested-create descriptor: insert one or more related records. */\nexport interface RelationMutationCreate<TContract, ModelName extends string> {\n readonly kind: \"create\";\n readonly data: readonly CreateInput<TContract, ModelName>[];\n}\n\n/** Nested-connect descriptor: link existing records to the parent via FK update. */\nexport interface RelationMutationConnect {\n readonly kind: \"connect\";\n readonly criteria: readonly Record<string, unknown>[];\n}\n\n/**\n * Nested-disconnect descriptor: unlink related records by setting FK to null.\n * With no criteria, disconnects all child records from this parent.\n */\nexport interface RelationMutationDisconnect {\n readonly kind: \"disconnect\";\n readonly criteria?: readonly Record<string, unknown>[];\n}\n\n/** Discriminated union of all nested relation mutation descriptors. */\nexport type IdbRelationMutation<TContract, ModelName extends string> =\n RelationMutationCreate<TContract, ModelName> | RelationMutationConnect | RelationMutationDisconnect;\n\n/** Relation mutator object passed to the user's relation callback. */\nexport interface IdbRelationMutator<TContract, ModelName extends string> {\n create(\n data: CreateInput<TContract, ModelName> | readonly CreateInput<TContract, ModelName>[]\n ): RelationMutationCreate<TContract, ModelName>;\n connect(criteria: Record<string, unknown> | readonly Record<string, unknown>[]): RelationMutationConnect;\n disconnect(criteria?: readonly Record<string, unknown>[]): RelationMutationDisconnect;\n}\n\n/**\n * Maps each reference relation key to an optional mutation callback.\n *\n * When `ReferenceRelKeys` widens to `string` (a loosely-typed `IdbContract`\n * with no emitted type maps), a naive mapped type would become an index\n * signature `{ [k: string]: callback }` that incorrectly forces *every* field —\n * scalars included — to be a relation callback, so even `create({ name: \"x\" })`\n * would fail to type-check. The `string extends …` guard detects that case and\n * contributes no constraint (`& unknown` is identity), leaving plain scalar\n * payloads valid. Precisely-typed contracts (the emitted `contract.d.ts`)\n * resolve `ReferenceRelKeys` to a finite union and get the full callback typing.\n */\ntype RelationMutationFields<TContract, ModelName extends string> =\n string extends ReferenceRelKeys<TContract, ModelName>\n ? unknown\n : Partial<{\n [K in ReferenceRelKeys<TContract, ModelName>]: (\n mutator: IdbRelationMutator<TContract, RelatedModelOf<TContract, ModelName, K>>\n ) => IdbRelationMutation<TContract, RelatedModelOf<TContract, ModelName, K>>;\n }>;\n\n/**\n * The `localFields` of all N:1 relations on a model — the FK fields that are\n * owned by this model and can be supplied via a relation callback instead of\n * as a scalar value. Resolves to `never` for loosely-typed contracts where\n * cardinality is not preserved as a literal (e.g. `defineContract` in tests).\n *\n * Mirrors `ChildForeignKeyFieldNames` from `sql-orm-client`, simplified: instead\n * of crawling all models for relations pointing *to* this one, we look at this\n * model's own N:1 relations directly — same field set, one model.\n */\ntype N1LocalFieldNames<TContract, ModelName extends string> = {\n [K in keyof ModelRelations<TContract, ModelName>]: ModelRelations<TContract, ModelName>[K] extends {\n readonly cardinality: \"N:1\";\n readonly on: { readonly localFields: infer Fields extends readonly string[] };\n }\n ? Fields[number]\n : never;\n}[keyof ModelRelations<TContract, ModelName>] &\n string;\n\n/**\n * Like `CreateInput` but with N:1 FK fields made optional.\n *\n * An N:1 FK field (e.g. `authorId` on `Post`) can be supplied either as a\n * scalar value or via a relation callback (`author: (rel) => rel.connect({id})`).\n * Making it optional here lets callers omit it when using the callback form —\n * the executor populates it from the related record before inserting.\n *\n * Mirrors `NestedCreateInput` from `sql-orm-client`.\n */\ntype NestedCreateInput<TContract, ModelName extends string> = Omit<\n CreateInput<TContract, ModelName>,\n N1LocalFieldNames<TContract, ModelName>\n> &\n Partial<\n Pick<\n CreateInput<TContract, ModelName>,\n N1LocalFieldNames<TContract, ModelName> & keyof CreateInput<TContract, ModelName>\n >\n >;\n\n/**\n * Input shape for `create()` with optional relation callbacks.\n * N:1 FK fields (e.g. `authorId`) are optional when using a relation callback.\n * Relation fields accept a callback `(rel) => rel.create([...])` / `rel.connect(...)`.\n */\nexport type MutationCreateInput<TContract, ModelName extends string> = NestedCreateInput<TContract, ModelName> &\n RelationMutationFields<TContract, ModelName>;\n\n/**\n * Input shape for `update()` with optional relation callbacks.\n * All scalar fields are optional (shallow merge); relation fields accept\n * `connect` or `disconnect` callbacks.\n */\nexport type MutationUpdateInput<TContract, ModelName extends string> = PatchInput<TContract, ModelName> &\n RelationMutationFields<TContract, ModelName>;\n\n// ── OrderBy spec ─────────────────────────────────────────────────────────────\n\n/** Sort direction for `orderBy()`. */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/** Partial sort spec: field name → direction. */\nexport type OrderBySpec<TContract, ModelName extends string> = Partial<\n Record<string & keyof DefaultModelRow<TContract, ModelName>, SortDirection>\n>;\n\n// ── Aggregate / groupBy ───────────────────────────────────────────────────────\n\n/** The five aggregation functions, matching the vendor `AggregateFn`. */\nexport type AggregateFn = \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\n/**\n * Fields eligible for numeric aggregation (`sum`/`avg`/`min`/`max`).\n *\n * For an emitted (precisely-typed) contract this narrows to the fields whose\n * output type is assignable to `number`. For a loosely-typed `IdbContract`\n * (no type maps — `DefaultModelRow` is `Record<string, unknown>`) the row key\n * set widens to `string`, so we allow any field name rather than collapsing to\n * `never`. Mirrors `NumericFieldNames` from `sql-orm-client`, trait-free.\n */\nexport type NumericFieldNames<TContract, ModelName extends string> = string extends keyof DefaultModelRow<\n TContract,\n ModelName\n>\n ? string\n : {\n [K in keyof DefaultModelRow<TContract, ModelName> & string]: NonNullable<\n DefaultModelRow<TContract, ModelName>[K]\n > extends number\n ? K\n : never;\n }[keyof DefaultModelRow<TContract, ModelName> & string];\n\ndeclare const idbAggregateResultBrand: unique symbol;\n\n/**\n * A single aggregation selector produced by the {@link IdbAggregateBuilder}.\n *\n * The phantom `Result` brand carries the per-selector result type so\n * {@link IdbAggregateResult} can map each alias back to its value type.\n * Mirrors the vendor `AggregateSelector`.\n */\nexport interface IdbAggregateSelector<Result> {\n readonly kind: \"aggregate\";\n readonly fn: AggregateFn;\n readonly field?: string;\n readonly [idbAggregateResultBrand]?: Result;\n}\n\n/** A map of result aliases → aggregation selectors (the `aggregate()` spec). */\nexport type IdbAggregateSpec = Record<string, IdbAggregateSelector<unknown>>;\n\n/** The result row shape for an {@link IdbAggregateSpec}: alias → value type. */\nexport type IdbAggregateResult<Spec extends IdbAggregateSpec> = {\n [K in keyof Spec]: Spec[K] extends IdbAggregateSelector<infer Result> ? Result : never;\n};\n\n/**\n * The builder handed to an `.aggregate(agg => …)` callback. `count()` is always\n * available; the field reducers are constrained to {@link NumericFieldNames}.\n * Mirrors the vendor `AggregateBuilder`, minus the SQL column mapping.\n */\nexport interface IdbAggregateBuilder<TContract, ModelName extends string> {\n count(): IdbAggregateSelector<number>;\n sum<F extends NumericFieldNames<TContract, ModelName>>(field: F): IdbAggregateSelector<number | null>;\n avg<F extends NumericFieldNames<TContract, ModelName>>(field: F): IdbAggregateSelector<number | null>;\n min<F extends NumericFieldNames<TContract, ModelName>>(field: F): IdbAggregateSelector<number | null>;\n max<F extends NumericFieldNames<TContract, ModelName>>(field: F): IdbAggregateSelector<number | null>;\n}\n\n// ── Model storage helpers ─────────────────────────────────────────────────────\n\n/**\n * Extract the `storeName` from a model's storage metadata at runtime.\n * Falls back to the model name if `storeName` is absent.\n */\nexport function getStoreName(contract: IdbContract, modelName: string): string {\n const model = domainModelsAtDefaultNamespace(contract.domain)[modelName];\n return (model?.storage as IdbModelStorage | undefined)?.storeName ?? modelName;\n}\n\n/**\n * Extract the `keyPath` from a model's storage metadata at runtime.\n * A single field name for the common case; an ordered array of field names\n * for a compound primary key.\n *\n * @throws if the model is unknown or its storage has no `keyPath` — a\n * validated contract always has one, so this only fires on a malformed or\n * hand-built contract, where guessing a key name would silently read/write\n * the wrong key.\n */\nexport function getKeyPath(contract: IdbContract, modelName: string): IdbKeyPath {\n const model = domainModelsAtDefaultNamespace(contract.domain)[modelName];\n const keyPath = (model?.storage as IdbModelStorage | undefined)?.keyPath;\n if (keyPath === undefined) {\n throw new Error(`Model \"${modelName}\" has no storage.keyPath in the contract.`);\n }\n return keyPath;\n}\n\n/**\n * Extracts a row's primary key as an {@link IDBValidKey} — the scalar value\n * at `row[keyPath]` for a single-field key, or an ordered array of the\n * compound key's member field values (matching the array form IDB itself\n * expects for a compound `keyPath`). The one construction site every\n * key-get/put/delete/update call should route through, so compound-key field\n * order stays consistent everywhere.\n */\nexport function extractKeyFromRow(row: Record<string, unknown>, keyPath: IdbKeyPath): IDBValidKey {\n if (typeof keyPath === \"string\") return row[keyPath] as IDBValidKey;\n return keyPath.map((field) => row[field]) as IDBValidKey;\n}\n\n/**\n * Find the IDB index name for `fieldName` on the given object store, searching\n * `contract.storage.stores[storeName].indexes` by `keyPath` equality.\n *\n * Returns the index name (e.g. `\"byEmail\"`) when a single-field index whose\n * `keyPath` equals `fieldName` exists, or `undefined` otherwise.\n * Compound (array-`keyPath`) and multi-entry indexes are skipped — the\n * equality-acceleration path this map feeds (`query-shaping.ts`) only peels\n * off a single-field `eq` condition, so a compound index can't be point-range\n * queried from a single field alone. Whether/how to accelerate a compound\n * index (matching *all* its member fields against an AND'd filter) is a\n * cost-based planner decision, deferred to Phase 10.\n */\nexport function getIndexForField(contract: IdbContract, storeName: string, fieldName: string): string | undefined {\n return buildFieldToIndexMap(contract, storeName)[fieldName];\n}\n\n/**\n * Build a field → indexName lookup for every single-field, non-multi-entry\n * index on `storeName`. Shared by {@link getIndexForField} (relation loader,\n * single-field lookups) and {@link IdbStoreAccessorImpl} (top-level scans,\n * which need the whole map to probe combined filter expressions).\n */\nexport function buildFieldToIndexMap(contract: IdbContract, storeName: string): Record<string, string> {\n const storeDef = contract.storage.stores[storeName];\n const result: Record<string, string> = {};\n if (storeDef?.indexes === undefined) return result;\n for (const [indexName, indexDef] of Object.entries(storeDef.indexes)) {\n if (typeof indexDef.keyPath === \"string\" && indexDef.multiEntry !== true) {\n result[indexDef.keyPath] = indexName;\n }\n }\n return result;\n}\n\n/**\n * Resolve a model's named relation to a {@link ContractReferenceRelation} at\n * runtime, or `undefined` when the relation is absent or an embedded relation\n * (no `on` join block). Used by `include()` to find the related model name and\n * cardinality before building the child-accessor refinement.\n */\nexport function getRelation(\n contract: IdbContract,\n modelName: string,\n relName: string\n): ContractReferenceRelation | undefined {\n const relation = domainModelsAtDefaultNamespace(contract.domain)[modelName]?.relations?.[relName];\n if (relation === undefined || !(\"on\" in relation)) return undefined;\n return relation as ContractReferenceRelation;\n}\n","/**\n * Proxy-based typed accessor handed to `where(fn)` callbacks.\n *\n * Mirrors `createModelAccessor()` from\n * Prisma ORM's SQL client, but without\n * the codec-trait gating — IDB stores native JS values, so every operator\n * is available on every field. The runtime accessor object is a Proxy\n * that materialises an `IdbFieldAccessor` on demand for whichever field\n * name is read; the type-level surface narrows that to the model's\n * actual field set so callbacks get autocomplete.\n */\n\nimport {\n type IdbFieldFilter,\n type IdbFilterExpr,\n type IdbNullCheckExpr,\n fieldFilter,\n nullCheckExpr,\n} from \"@prisma-idb/adapter-idb/runtime\";\nimport type { DefaultModelRow, IdbContract } from \"./types\";\n\n// ── Typed surface ─────────────────────────────────────────────────────────────\n\n/**\n * Operator surface available on every field. All return frozen AST nodes\n * — they are values, not statements, so chaining and logical combinators\n * compose naturally.\n */\nexport interface IdbFieldAccessor<T> {\n eq(value: T): IdbFieldFilter;\n neq(value: T): IdbFieldFilter;\n gt(value: T): IdbFieldFilter;\n lt(value: T): IdbFieldFilter;\n gte(value: T): IdbFieldFilter;\n lte(value: T): IdbFieldFilter;\n in(values: ReadonlyArray<T>): IdbFieldFilter;\n notIn(values: ReadonlyArray<T>): IdbFieldFilter;\n contains(sub: string): IdbFieldFilter;\n startsWith(sub: string): IdbFieldFilter;\n endsWith(sub: string): IdbFieldFilter;\n isNull(): IdbNullCheckExpr;\n isNotNull(): IdbNullCheckExpr;\n}\n\n/**\n * The accessor object handed to a `where(fn)` callback. Each key resolves\n * to an {@link IdbFieldAccessor} typed against the field's output type.\n *\n * The Proxy makes every string key resolve to an accessor at runtime; the\n * type narrows the visible surface to the model's declared fields so the\n * developer gets autocomplete.\n */\nexport type IdbModelAccessor<TContract, ModelName extends string> = {\n readonly [K in keyof DefaultModelRow<TContract, ModelName>]-?: IdbFieldAccessor<\n DefaultModelRow<TContract, ModelName>[K]\n >;\n};\n\n// ── Runtime construction ──────────────────────────────────────────────────────\n\n/**\n * Build an {@link IdbFieldAccessor} for a single field. The accessor is\n * shared via the proxy below, but each accessor instance is bound to its\n * own field name so the produced AST nodes carry the right field.\n */\nfunction createFieldAccessor(field: string): IdbFieldAccessor<unknown> {\n return {\n eq: (value) => fieldFilter(field, \"eq\", value),\n neq: (value) => fieldFilter(field, \"neq\", value),\n gt: (value) => fieldFilter(field, \"gt\", value),\n lt: (value) => fieldFilter(field, \"lt\", value),\n gte: (value) => fieldFilter(field, \"gte\", value),\n lte: (value) => fieldFilter(field, \"lte\", value),\n in: (values) => fieldFilter(field, \"in\", values),\n notIn: (values) => fieldFilter(field, \"notIn\", values),\n contains: (sub) => fieldFilter(field, \"contains\", sub),\n startsWith: (sub) => fieldFilter(field, \"startsWith\", sub),\n endsWith: (sub) => fieldFilter(field, \"endsWith\", sub),\n isNull: () => nullCheckExpr(field, true),\n isNotNull: () => nullCheckExpr(field, false),\n };\n}\n\n/**\n * Create the typed model accessor used by `where(fn)` callbacks.\n *\n * Implemented as a Proxy keyed on field names — every read returns an\n * {@link IdbFieldAccessor} bound to that field. The accessor cache means\n * `m.name.eq(...)` and `m.name.startsWith(...)` reuse the same per-field\n * accessor object across the same `where()` invocation.\n *\n * The type parameter is structural — no contract is consulted at\n * runtime, because TS already gates the visible field set at compile\n * time. (Misspelled fields surface as accessor calls on names that\n * don't exist in stored rows, which is consistent with how the\n * shorthand form behaves today.)\n */\nexport function createModelAccessor<TContract extends IdbContract, ModelName extends string>(): IdbModelAccessor<\n TContract,\n ModelName\n> {\n const cache = new Map<string, IdbFieldAccessor<unknown>>();\n return new Proxy(\n {},\n {\n get(_target, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n let acc = cache.get(prop);\n if (acc === undefined) {\n acc = createFieldAccessor(prop);\n cache.set(prop, acc);\n }\n return acc;\n },\n }\n ) as IdbModelAccessor<TContract, ModelName>;\n}\n\n// ── Re-export the AST type the callback returns ───────────────────────────────\n\nexport type { IdbFilterExpr };\n","import type { IdbFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\n\n/**\n * One entry in {@link IdbAccessorState.includes} — describes how a single\n * `.include()`d relation should be materialised.\n *\n * - `collection`: load the related rows, applying the refined `state`\n * (its `filters` / `orderBy` / `skip` / `take`) to the child scan.\n * `state` is `emptyAccessorState()` for an unrefined `.include(rel)`.\n * - `scalar`: reduce the related rows to a single number (Phase 6.5 supports\n * `count`). The `state.filters` still constrain which children are counted.\n *\n * Mirrors the `IncludeExpr` / `IncludeScalar` split from\n * Prisma ORM's SQL client, collapsed to the two shapes IDB\n * needs (no SQL column mapping, no `combine()` branches).\n */\nexport type IncludeEntry =\n | { readonly kind: \"collection\"; readonly state: IdbAccessorState }\n | { readonly kind: \"scalar\"; readonly fn: \"count\"; readonly state: IdbAccessorState };\n\n/**\n * Marker returned by the child accessor's `.count()` terminal when it is\n * called inside an `include()` refinement callback. Carries the refined\n * child `state` so the relation loader counts only the matching children.\n *\n * Detected by {@link isIncludeScalar}; mirrors `IncludeScalar` from the\n * vendor `sql-orm-client/include-descriptors.ts`.\n */\nexport interface IdbIncludeScalar {\n readonly kind: \"includeScalar\";\n readonly fn: \"count\";\n readonly state: IdbAccessorState;\n}\n\n/** Build an {@link IdbIncludeScalar} marker for a `count()` reducer. */\nexport function createIncludeScalar(state: IdbAccessorState): IdbIncludeScalar {\n return { kind: \"includeScalar\", fn: \"count\", state };\n}\n\n/** Type guard: is `value` an {@link IdbIncludeScalar} marker? */\nexport function isIncludeScalar(value: unknown): value is IdbIncludeScalar {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { kind?: unknown; fn?: unknown };\n return candidate.kind === \"includeScalar\" && candidate.fn === \"count\";\n}\n\n/**\n * Immutable state carried by each {@link IdbStoreAccessorImpl} node in the\n * builder chain.\n *\n * Every mutating method (`.where()`, `.take()`, etc.) returns a cloned\n * instance with an updated state rather than mutating in place, making the\n * accessor safe to reuse across multiple query branches.\n */\nexport interface IdbAccessorState {\n /**\n * Accumulated filter expressions. Multiple `.where()` calls compose\n * with AND semantics — the planner wraps them in an `andExpr` when\n * lowering. Each entry is already either an `IdbFieldFilter`, a\n * combinator, or a `null-check` node — never raw shorthand records.\n */\n readonly filters: ReadonlyArray<IdbFilterExpr>;\n /** Sort spec: field → direction. Applied as an in-memory comparator. */\n readonly orderBy?: Record<string, \"asc\" | \"desc\">;\n /** OFFSET (number of rows to skip). */\n readonly skip?: number;\n /** LIMIT (maximum number of rows to return). */\n readonly take?: number;\n /**\n * Relations that have been `.include()`d — keys are relation names, values\n * describe how to materialise each (collection vs scalar count, plus any\n * refinement state). See {@link IncludeEntry}.\n */\n readonly includes: Record<string, IncludeEntry>;\n /**\n * Fields kept by `.select()`. `undefined` means \"all fields\". When set,\n * the materialised rows are projected down to these fields (plus any\n * included relation keys) after the scan and relation loads complete.\n */\n readonly selectedFields?: ReadonlyArray<string>;\n}\n\n/** Create a fresh, empty accessor state (no filters, no ordering, no includes). */\nexport function emptyAccessorState(): IdbAccessorState {\n return {\n filters: [],\n includes: {},\n };\n}\n\n/** Return a shallow-merged copy of `state` with the given overrides applied. */\nexport function mergeAccessorState(state: IdbAccessorState, overrides: Partial<IdbAccessorState>): IdbAccessorState {\n return { ...state, ...overrides };\n}\n","import type { IdbFilterExpr, IdbOrExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport { andExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbCountPlan, IdbCursorScanPlan, IdbRowComparator } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbKeyPath } from \"@prisma-idb/target-idb/pack\";\nimport { compareFieldValues } from \"@prisma-idb/target-idb/runtime\";\nimport { isValidIdbKey } from \"./types\";\n\n/** Describes an extractable indexed equality that can narrow a cursor scan. */\nexport interface IndexEqualityHint {\n /**\n * The IDB index name (e.g. `\"byEmail\"`), or `undefined` when the condition\n * is on the store's own primary key — a store's keyPath is always\n * point-range-queryable directly (`IDBObjectStore.openCursor(range)`),\n * without a named `IDBIndex`.\n */\n readonly indexName: string | undefined;\n /** The equality value to pass to `IDBKeyRange.only()`. */\n readonly value: unknown;\n /** The remainder of the filter after the indexed condition is peeled off. */\n readonly remainingFilter: IdbFilterExpr | undefined;\n}\n\n/**\n * Describes an OR filter where every branch can be satisfied by an indexed\n * equality lookup. Each branch maps to one `IDBKeyRange.only()` cursor scan;\n * the caller unions the results and deduplicates before applying\n * `remainingFilter`.\n */\nexport interface IndexOrHint {\n /** `indexName` is `undefined` for a branch on the store's own primary key — see {@link IndexEqualityHint}. */\n readonly branches: ReadonlyArray<{ readonly indexName: string | undefined; readonly value: unknown }>;\n /** AND conditions that wrapped the OR — applied in-memory after the union. */\n readonly remainingFilter: IdbFilterExpr | undefined;\n}\n\n/**\n * Combine accumulated filter expressions with AND.\n *\n * Returns `undefined` when no filter is present so callers can skip building a\n * row-filter closure. Shared by {@link IdbStoreAccessorImpl} (top-level scans)\n * and the relation loader (refined `include()` child scans).\n */\nexport function combineFilterExprs(filters: ReadonlyArray<IdbFilterExpr>): IdbFilterExpr | undefined {\n if (filters.length === 0) return undefined;\n if (filters.length === 1) return filters[0];\n return andExpr(filters);\n}\n\n/** Recursively flatten nested AND nodes into a single array of children. */\nfunction flattenAnd(filter: IdbFilterExpr): IdbFilterExpr[] {\n if (filter.kind !== \"and\") return [filter];\n return filter.exprs.flatMap(flattenAnd);\n}\n\n/** Fold the leftover AND children (after peeling an indexed condition) back into a single filter, or `undefined` if none remain. */\nfunction foldRemainder(rest: IdbFilterExpr[]): IdbFilterExpr | undefined {\n if (rest.length === 0) return undefined;\n if (rest.length === 1) return rest[0]!;\n return andExpr(rest);\n}\n\n/**\n * `IDBKeyRange.only()` throws `DataError` for values that aren't valid\n * IndexedDB keys (`null`/`undefined`, booleans, `NaN`, `BigInt`, plain\n * objects, or arrays containing any of those) — an `eq` condition on such a\n * value can't be served by an index point-range scan and must fall back to\n * a full scan. Delegates to the shared {@link isValidIdbKey} check.\n */\nfunction isIndexableEqValue(value: unknown): boolean {\n return isValidIdbKey(value);\n}\n\n/**\n * `true` when `field` is a *single-field* primary key that a lone `eq`\n * condition can directly point-range-query (`store.get`/`openCursor(range)`\n * against the store's own keyPath, no named index required).\n *\n * Deliberately `false` for a compound (array) `keyPath`, even if `field`\n * happens to be one of its member fields — a single `eq` condition can only\n * pin one member, not the whole compound key, so it can't drive a PK\n * point-range scan on its own. Accelerating that case needs *all* member\n * fields ANDed together, which is a cost-based multi-field planner decision\n * (Phase 10 §3.2), not this peephole optimizer's job.\n */\nfunction isPrimaryKeyField(field: string, keyPath: IdbKeyPath): boolean {\n return typeof keyPath === \"string\" && field === keyPath;\n}\n\n/**\n * Scan the combined filter expression for the first `eq` field condition whose\n * field either has a matching IDB index (`fieldToIndexName[field]` is set) or\n * *is* the store's own primary key (`keyPath`) — a store's keyPath is always\n * point-range-queryable directly, no named index required.\n *\n * When found, the indexed condition is peeled off and returned as an\n * {@link IndexEqualityHint}; any remaining conditions are preserved in\n * `remainingFilter`. Returns `null` when no usable index can be found.\n *\n * Nested AND nodes are flattened before scanning, so deeply-composed filters\n * are handled correctly. Only `eq` conditions are considered — range operators\n * (`gt`, `lt`, etc.) could also use an index range but that optimization is\n * not yet implemented.\n */\nexport function extractIndexEqualityHint(\n filter: IdbFilterExpr | undefined,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath\n): IndexEqualityHint | null {\n if (filter === undefined) return null;\n\n if (filter.kind === \"field\" && filter.op === \"eq\") {\n const indexName = fieldToIndexName[filter.field];\n if ((indexName !== undefined || isPrimaryKeyField(filter.field, keyPath)) && isIndexableEqValue(filter.value)) {\n return { indexName, value: filter.value, remainingFilter: undefined };\n }\n return null;\n }\n\n if (filter.kind === \"and\") {\n const flat = flattenAnd(filter);\n for (let i = 0; i < flat.length; i++) {\n const expr = flat[i]!;\n if (expr.kind === \"field\" && expr.op === \"eq\") {\n const indexName = fieldToIndexName[expr.field];\n if ((indexName !== undefined || isPrimaryKeyField(expr.field, keyPath)) && isIndexableEqValue(expr.value)) {\n const rest = flat.filter((_, j) => j !== i);\n return { indexName, value: expr.value, remainingFilter: foldRemainder(rest) };\n }\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check whether every branch of an OR node is a single `field eq value`\n * condition whose field has a matching index. Returns an {@link IndexOrHint}\n * when the whole OR can be satisfied by N point-range cursor scans, `null`\n * otherwise.\n */\nfunction tryExtractOrBranches(\n orNode: IdbOrExpr,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath,\n remainingFilter: IdbFilterExpr | undefined\n): IndexOrHint | null {\n if (orNode.exprs.length === 0) return null;\n const branches: { indexName: string | undefined; value: unknown }[] = [];\n for (const expr of orNode.exprs) {\n if (expr.kind !== \"field\" || expr.op !== \"eq\") return null;\n const indexName = fieldToIndexName[expr.field];\n if ((indexName === undefined && !isPrimaryKeyField(expr.field, keyPath)) || !isIndexableEqValue(expr.value))\n return null;\n branches.push({ indexName, value: expr.value });\n }\n return { branches, remainingFilter };\n}\n\n/**\n * Attempt to extract an {@link IndexOrHint} from `filter`.\n *\n * Handles two shapes:\n * - Top-level `or` where every branch is `field eq value` on an indexed field.\n * - Top-level `and` (with nested ANDs flattened) that contains exactly one `or`\n * child fitting the above pattern; the remaining AND children become\n * `remainingFilter` applied in-memory after the union.\n *\n * Returns `null` when the filter cannot be accelerated via OR index scans.\n */\nexport function extractIndexOrHint(\n filter: IdbFilterExpr | undefined,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath\n): IndexOrHint | null {\n if (filter === undefined) return null;\n\n if (filter.kind === \"or\") {\n return tryExtractOrBranches(filter, fieldToIndexName, keyPath, undefined);\n }\n\n if (filter.kind === \"and\") {\n const flat = flattenAnd(filter);\n const orIndices: number[] = [];\n for (let i = 0; i < flat.length; i++) {\n if (flat[i]!.kind === \"or\") orIndices.push(i);\n }\n if (orIndices.length !== 1) return null;\n const orIdx = orIndices[0]!;\n const orNode = flat[orIdx]! as IdbOrExpr;\n const rest = flat.filter((_, j) => j !== orIdx);\n return tryExtractOrBranches(orNode, fieldToIndexName, keyPath, foldRemainder(rest));\n }\n\n return null;\n}\n\n/**\n * Build an in-memory comparator from an `orderBy` spec (field → direction).\n *\n * Returns `undefined` when there is nothing to sort by. Compares fields in\n * declaration order, with {@link compareFieldValues}: the same order an\n * IndexedDB index uses, so equal `Date`s tie and fall through to the next\n * field, and `null`s sort last (first when descending).\n */\nexport function buildRowComparator(orderBy: Record<string, \"asc\" | \"desc\"> | undefined): IdbRowComparator | undefined {\n if (orderBy === undefined) return undefined;\n return (a: Record<string, unknown>, b: Record<string, unknown>): number => {\n for (const [field, dir] of Object.entries(orderBy)) {\n const cmp = compareFieldValues(a[field], b[field]);\n if (cmp === 0) continue;\n return dir === \"desc\" ? -cmp : cmp;\n }\n return 0;\n };\n}\n\n// ── Native count ──────────────────────────────────────────────────────────────\n\n/**\n * `true` when a `cursor-scan` plan's result *cardinality* is fully determined\n * by its store/index + key range — i.e. there is no in-memory `filter` that\n * would need each row's value. Only then can `count()` be answered natively\n * (`store.count(range)` / `index.count(range)`) without deserializing rows.\n *\n * `comparator` (ORDER BY), `direction`, `skip` and `take` don't change *which*\n * rows match, so they don't disqualify a plan — `skip`/`take` are applied to\n * the native total afterwards via {@link clampCount}.\n *\n * Safe for index scans because the equality hint that builds `range` never\n * selects a `multiEntry` (or compound) index — `buildFieldToIndexMap` excludes\n * them — so one record maps to at most one index entry and entries == rows.\n */\nexport function isNativelyCountable(plan: IdbCursorScanPlan): boolean {\n return plan.filter === undefined;\n}\n\n/** Rewrites a natively-countable `cursor-scan` as the equivalent native `count` plan. */\nexport function toCountPlan(plan: IdbCursorScanPlan): IdbCountPlan {\n return {\n meta: plan.meta,\n kind: \"count\",\n storeName: plan.storeName,\n ...(plan.indexName !== undefined ? { indexName: plan.indexName } : {}),\n ...(plan.range !== undefined ? { range: plan.range } : {}),\n };\n}\n\n/**\n * Applies `skip`/`take` to an *unpaginated* total. A paginated count is pure\n * arithmetic on the unpaginated count — `max(0, total - skip)`, capped at\n * `take` — so this is exact, not an approximation.\n */\nexport function clampCount(total: number, skip: number | undefined, take: number | undefined): number {\n let n = total;\n if (skip !== undefined) n = Math.max(0, n - skip);\n if (take !== undefined) n = Math.min(take, n);\n return n;\n}\n","import type { AggregateFn, IdbAggregateBuilder, IdbAggregateSelector } from \"./types\";\n\n/**\n * Build the aggregate selector factory handed to `.aggregate(agg => …)` and\n * `groupBy(...).aggregate(agg => …)`.\n *\n * Each method returns a frozen {@link IdbAggregateSelector} marker; the actual\n * reduction happens in {@link reduceAggregate} once the matching rows are\n * materialised in memory. Mirrors `createAggregateBuilder` from the vendor\n * `sql-orm-client/aggregate-builder.ts`, minus the field→column mapping (IDB\n * stores native field names).\n */\nexport function createAggregateBuilder<TContract, ModelName extends string>(): IdbAggregateBuilder<\n TContract,\n ModelName\n> {\n return {\n count: () => ({ kind: \"aggregate\", fn: \"count\" }),\n sum: (field) => ({ kind: \"aggregate\", fn: \"sum\", field: field as string }),\n avg: (field) => ({ kind: \"aggregate\", fn: \"avg\", field: field as string }),\n min: (field) => ({ kind: \"aggregate\", fn: \"min\", field: field as string }),\n max: (field) => ({ kind: \"aggregate\", fn: \"max\", field: field as string }),\n };\n}\n\n/** Type guard: is `value` an {@link IdbAggregateSelector}? */\nexport function isAggregateSelector(value: unknown): value is IdbAggregateSelector<unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { kind?: unknown; fn?: unknown };\n return (\n candidate.kind === \"aggregate\" &&\n (candidate.fn === \"count\" ||\n candidate.fn === \"sum\" ||\n candidate.fn === \"avg\" ||\n candidate.fn === \"min\" ||\n candidate.fn === \"max\")\n );\n}\n\n/**\n * Reduce a set of materialised rows to a single aggregate value.\n *\n * - `count` → the number of rows (always a number, never null).\n * - `sum`/`avg`/`min`/`max` → computed over the non-null numeric values of\n * `field`; `null` when no row has a non-null value (matching Prisma's\n * \"aggregate of an empty set is null\" and the vendor `coerceAggregateValue`\n * null handling). String-encoded numbers are coerced via `Number()`.\n */\nexport function reduceAggregate(\n fn: AggregateFn,\n field: string | undefined,\n rows: readonly Record<string, unknown>[]\n): number | null {\n if (fn === \"count\") return rows.length;\n if (field === undefined) return null;\n\n const values: number[] = [];\n for (const row of rows) {\n const raw = row[field];\n if (raw === null || raw === undefined) continue;\n const n = typeof raw === \"bigint\" ? Number(raw) : Number(raw as number);\n if (!Number.isNaN(n)) values.push(n);\n }\n\n if (values.length === 0) return null;\n\n switch (fn) {\n case \"sum\":\n return values.reduce((acc, n) => acc + n, 0);\n case \"avg\":\n return values.reduce((acc, n) => acc + n, 0) / values.length;\n case \"min\":\n return Math.min(...values);\n case \"max\":\n return Math.max(...values);\n }\n}\n\n/**\n * Run every selector in an aggregate spec against `rows`, producing the\n * result object keyed by the spec's aliases.\n */\nexport function computeAggregateSpec(\n spec: Record<string, IdbAggregateSelector<unknown>>,\n rows: readonly Record<string, unknown>[]\n): Record<string, number | null> {\n const result: Record<string, number | null> = {};\n for (const [alias, selector] of Object.entries(spec)) {\n result[alias] = reduceAggregate(selector.fn, selector.field, rows);\n }\n return result;\n}\n\n/**\n * Project an aggregate spec down to the plain `{ fn, field? }` shape carried by\n * the query AST (`IdbAggregateAst.aggregates` / `IdbGroupByAst.aggregates`), so\n * middleware can observe the requested aggregations.\n */\nexport function toAggregateRequests(\n spec: Record<string, IdbAggregateSelector<unknown>>\n): Record<string, { readonly fn: string; readonly field?: string }> {\n const out: Record<string, { fn: string; field?: string }> = {};\n for (const [alias, selector] of Object.entries(spec)) {\n out[alias] = selector.field !== undefined ? { fn: selector.fn, field: selector.field } : { fn: selector.fn };\n }\n return out;\n}\n\n/**\n * Validate a user-supplied aggregate spec: it must be non-empty and every\n * value must be a real selector. Throws a descriptive error otherwise, so a\n * typo (e.g. returning a plain object) fails loudly rather than silently\n * producing `NaN`/`undefined` results.\n */\nexport function assertValidAggregateSpec(\n spec: Record<string, unknown>,\n context: \"aggregate()\" | \"groupBy().aggregate()\"\n): void {\n const entries = Object.entries(spec);\n if (entries.length === 0) {\n throw new Error(`${context} requires at least one aggregation selector`);\n }\n for (const [alias, selector] of entries) {\n if (!isAggregateSelector(selector)) {\n throw new Error(`${context} selector \"${alias}\" is invalid`);\n }\n }\n}\n","import type { IdbFilterExpr, IdbGroupByAst, IdbQueryAst } from \"@prisma-idb/adapter-idb/runtime\";\nimport {\n assertValidAggregateSpec,\n computeAggregateSpec,\n createAggregateBuilder,\n toAggregateRequests,\n} from \"./aggregate-builder\";\nimport type { DefaultModelRow, IdbAggregateBuilder, IdbAggregateResult, IdbAggregateSpec } from \"./types\";\n\n/**\n * One grouped-aggregate result row: the group-key fields picked from the model\n * row, intersected with the aggregate aliases.\n */\nexport type GroupedResultRow<\n TContract,\n ModelName extends string,\n Fields extends readonly string[],\n Spec extends IdbAggregateSpec,\n> = Pick<DefaultModelRow<TContract, ModelName>, Fields[number] & keyof DefaultModelRow<TContract, ModelName>> &\n IdbAggregateResult<Spec>;\n\n/**\n * Grouped-aggregate builder returned by `accessor.groupBy(...)`.\n *\n * Port of the vendor `GroupedCollection` (`sql-orm-client/grouped-collection.ts`),\n * but purely in-memory: there is no SQL compilation, so `aggregate()`\n * materialises the matching rows, partitions them by the group-key fields, and\n * reduces each partition with the requested selectors.\n */\nexport interface IdbGroupedAccessor<TContract, ModelName extends string, Fields extends readonly string[]> {\n /**\n * Reduce each group to one row of `{ ...groupKeyFields, ...aggregates }`.\n *\n * @example\n * ```ts\n * const byUser = await db.posts\n * .where({ published: true })\n * .groupBy(\"authorId\")\n * .aggregate((agg) => ({ count: agg.count(), totalViews: agg.sum(\"views\") }));\n * // [{ authorId: \"u1\", count: 3, totalViews: 120 }, ...]\n * ```\n */\n aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<Array<GroupedResultRow<TContract, ModelName, Fields, Spec>>>;\n}\n\n/** Runtime wiring handed to {@link createGroupedAccessor} by the store accessor. */\nexport interface GroupedAccessorInit {\n readonly modelName: string;\n /** Group-key fields, in declaration order. */\n readonly by: readonly string[];\n /** Combined `where` expression carried over from the source accessor, if any. */\n readonly where: IdbFilterExpr | undefined;\n /**\n * Materialise all rows matching the source filters. The store accessor owns\n * plan-building; the grouped accessor only supplies the AST it wants attached\n * (for middleware visibility) and does the in-memory grouping.\n */\n readonly materialize: (ast: IdbQueryAst) => Promise<Record<string, unknown>[]>;\n}\n\n/**\n * Build the composite group key for a row. Uses a JSON encoding of the ordered\n * key-field values so multi-field groups and primitive value types (string,\n * number, boolean, null) partition correctly.\n */\nfunction groupKeyOf(by: readonly string[], row: Record<string, unknown>): string {\n return JSON.stringify(by.map((field) => row[field] ?? null));\n}\n\nexport function createGroupedAccessor<TContract, ModelName extends string, Fields extends readonly string[]>(\n init: GroupedAccessorInit\n): IdbGroupedAccessor<TContract, ModelName, Fields> {\n return {\n async aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<Array<GroupedResultRow<TContract, ModelName, Fields, Spec>>> {\n const spec = fn(createAggregateBuilder<TContract, ModelName>());\n assertValidAggregateSpec(spec, \"groupBy().aggregate()\");\n\n const ast: IdbGroupByAst = {\n kind: \"groupBy\",\n modelName: init.modelName,\n by: init.by,\n aggregates: toAggregateRequests(spec),\n ...(init.where !== undefined ? { where: init.where } : {}),\n };\n\n const rows = await init.materialize(ast);\n\n // Partition rows by their composite group key, preserving first-seen order.\n const groups = new Map<string, { key: Record<string, unknown>; rows: Record<string, unknown>[] }>();\n for (const row of rows) {\n const gk = groupKeyOf(init.by, row);\n let group = groups.get(gk);\n if (group === undefined) {\n const key: Record<string, unknown> = {};\n for (const field of init.by) key[field] = row[field];\n group = { key, rows: [] };\n groups.set(gk, group);\n }\n group.rows.push(row);\n }\n\n return Array.from(groups.values()).map(\n (group) =>\n ({ ...group.key, ...computeAggregateSpec(spec, group.rows) }) as GroupedResultRow<\n TContract,\n ModelName,\n Fields,\n Spec\n >\n );\n },\n };\n}\n","/**\n * Applies `contract.execution.mutations.defaults` (ADR 158) during a\n * create/update — IDB's equivalent of the SQL family's\n * `ExecutionContext.applyMutationDefaults`.\n *\n * Semantics mirror the SQL reference implementation:\n * - a caller-provided value always wins over a default;\n * - an empty update patch skips every `onUpdate` default (no write ⇒ no\n * `@updatedAt` advance);\n * - `timestampNow`'s value is cached per call so a whole top-level mutation\n * call (e.g. a `createAll()` batch) shares one generated value across\n * every row it backs, matching its `'query'`-stability in SQL. Every other\n * generator (`literal`, `uuidv4`, `uuidv7`, `cuid2`) is deliberately *not*\n * cached — an id generator must produce a fresh, unique value per\n * resolution (both across rows in a batch and across distinct defaulted\n * fields on the same row), and a cache keyed only by generator id would\n * otherwise leak one field's/row's value onto the next.\n */\nimport type { ExecutionMutationDefault, ExecutionMutationDefaultValue } from \"@prisma/orm-framework/contract/types\";\nimport { generateId } from \"@prisma/orm-framework/ids/runtime\";\nimport type { IdbMutationDefaultGeneratorId } from \"@prisma-idb/target-idb/pack\";\n\n/** Per-top-level-mutation-call cache, keyed by generator id. Create one with {@link createMutationDefaultsCache}. */\nexport type MutationDefaultsCache = Map<string, unknown>;\n\nexport function createMutationDefaultsCache(): MutationDefaultsCache {\n return new Map();\n}\n\n/** Generator ids whose value is shared across an entire top-level call. Every other id always regenerates. */\nconst CACHEABLE_GENERATOR_IDS: ReadonlySet<IdbMutationDefaultGeneratorId> = new Set([\"timestampNow\"]);\n\nfunction computeGeneratedValue(spec: ExecutionMutationDefaultValue): unknown {\n const id = spec.id as IdbMutationDefaultGeneratorId;\n switch (id) {\n case \"timestampNow\":\n return new Date();\n case \"literal\":\n return spec.params?.[\"value\"];\n case \"uuidv4\":\n case \"uuidv7\":\n case \"cuid2\":\n return generateId(spec.params !== undefined ? { id, params: spec.params } : { id });\n default: {\n const _exhaustive: never = id;\n throw new Error(`Unknown mutation-default generator id \"${String(_exhaustive)}\"`);\n }\n }\n}\n\nfunction resolveGeneratedValue(spec: ExecutionMutationDefaultValue, cache: MutationDefaultsCache): unknown {\n const id = spec.id as IdbMutationDefaultGeneratorId;\n if (!CACHEABLE_GENERATOR_IDS.has(id)) return computeGeneratedValue(spec);\n const cached = cache.get(id);\n if (cached !== undefined) return cached;\n const value = computeGeneratedValue(spec);\n cache.set(id, value);\n return value;\n}\n\n/**\n * Fills in every column with an `onCreate` default that `data` doesn't\n * already set. Returns `data` unchanged (same reference) if there's nothing\n * to apply.\n */\nexport function applyCreateDefaults(\n defaults: readonly ExecutionMutationDefault[] | undefined,\n storeName: string,\n data: Record<string, unknown>,\n cache: MutationDefaultsCache\n): Record<string, unknown> {\n if (!defaults || defaults.length === 0) return data;\n let result = data;\n for (const d of defaults) {\n if (d.ref.table !== storeName || !d.onCreate) continue;\n if (result[d.ref.column] !== undefined) continue;\n if (result === data) result = { ...data };\n result[d.ref.column] = resolveGeneratedValue(d.onCreate, cache);\n }\n return result;\n}\n\n/**\n * Fills in every column with an `onUpdate` default that `patch` doesn't\n * already set. A patch with no defined values (empty, or every field\n * explicitly `undefined`) is returned unchanged — no write means no default\n * should fire either (matches SQL's \"empty update payloads skip onUpdate\n * defaults\" rule).\n */\nexport function applyUpdateDefaults(\n defaults: readonly ExecutionMutationDefault[] | undefined,\n storeName: string,\n patch: Record<string, unknown>,\n cache: MutationDefaultsCache\n): Record<string, unknown> {\n if (Object.values(patch).every((v) => v === undefined)) return patch;\n if (!defaults || defaults.length === 0) return patch;\n let result = patch;\n for (const d of defaults) {\n if (d.ref.table !== storeName || !d.onUpdate) continue;\n if (result[d.ref.column] !== undefined) continue;\n if (result === patch) result = { ...patch };\n result[d.ref.column] = resolveGeneratedValue(d.onUpdate, cache);\n }\n return result;\n}\n","import type { ContractReferenceRelation } from \"@prisma/orm-framework/contract/types\";\nimport { domainModelsAtDefaultNamespace } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbQueryPlan } from \"@prisma-idb/adapter-idb/runtime\";\nimport { evaluateFilter } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbRowFilter } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { buildRowComparator, combineFilterExprs } from \"./query-shaping\";\nimport type { IncludeEntry } from \"./store-state\";\nimport { keyPathFields, type IdbKeyPath } from \"@prisma-idb/target-idb/pack\";\nimport { fieldValueToken, getKeyPath, isValidIdbKey } from \"./types\";\nimport type { IdbContract } from \"./types\";\n\n/**\n * Batch-load a single named relation for all rows in `rows` and attach the\n * result to each row under the `relName` key.\n *\n * The join matches every field of the relation, so compound foreign keys join\n * on the whole tuple. It uses one key-range scan per distinct tuple when an\n * index or the related primary key covers the target fields, and otherwise\n * one full scan with an in-memory filter. Rows are then grouped in memory,\n * which avoids N+1 queries.\n *\n * The `entry` carries any `include()` refinement:\n *\n * - `collection` — the refined `where` further filters the child scan;\n * `orderBy` / `skip` / `take` are applied **per parent group** for `1:N`\n * relations (each parent's children are independently sorted and paginated).\n * - `scalar` — the relation field becomes the `count` of matching children\n * (to-many only; `include()` rejects scalar refinements on to-one relations).\n *\n * @param relName - The relation key to load (e.g. `\"posts\"`, `\"author\"`).\n * @param entry - How to materialise the relation (collection vs scalar + refinement state).\n * @param rows - The parent rows to attach related data to.\n * @param contract - The resolved IDB contract.\n * @param modelName - The source model name (owner of the relation).\n * @param executor - The query executor used to run the related-store scan.\n */\nexport async function loadRelation(\n relName: string,\n entry: IncludeEntry,\n rows: Record<string, unknown>[],\n contract: IdbContract,\n modelName: string,\n executor: IdbQueryExecutor,\n groupingKey: string\n): Promise<Record<string, unknown>[]> {\n if (rows.length === 0) return rows;\n\n const models = domainModelsAtDefaultNamespace(contract.domain);\n const model = models[modelName];\n if (model === undefined) return rows;\n\n const rawRelation = model.relations[relName];\n if (rawRelation === undefined) return rows;\n\n // Only handle reference relations (cross-store joins). Embed relations don't\n // have an `on` block and are stored inline — nothing to load.\n if (!(\"on\" in rawRelation)) return rows;\n\n const relation = rawRelation as ContractReferenceRelation;\n const { cardinality, on } = relation;\n // `relation.to` is a CrossReference `{ namespace, model }`.\n const relatedModelName = relation.to.model;\n\n const localFields = on.localFields;\n const targetFields = on.targetFields;\n if (localFields.length === 0 || localFields.length !== targetFields.length) return rows;\n\n const relatedModel = models[relatedModelName];\n if (relatedModel === undefined) return rows;\n\n // Resolve the related object store name from the model's storage metadata.\n const relatedStoreName =\n typeof relatedModel.storage === \"object\" && relatedModel.storage !== null && \"storeName\" in relatedModel.storage\n ? String((relatedModel.storage as { storeName: unknown })[\"storeName\"])\n : relatedModelName;\n\n const isScalar = entry.kind === \"scalar\";\n\n // Collect the distinct local tuples to drive the related-store lookup. A\n // tuple is keyed by `tupleToken`, so equal Date/binary values collapse and\n // match the related rows' freshly-deserialized values below. A row with a\n // null in any local field has no related rows.\n const localTuples = new Map<string, unknown[]>();\n for (const row of rows) {\n const token = tupleToken(row, localFields);\n if (token !== null)\n localTuples.set(\n token,\n localFields.map((f) => row[f])\n );\n }\n\n // Short-circuit: if every local tuple has a null, attach empties.\n // (Scalar counts are 0; to-many is [], to-one is null.)\n if (localTuples.size === 0) {\n return rows.map((row) => ({\n ...row,\n [relName]: isScalar ? 0 : cardinality === \"1:N\" ? [] : null,\n }));\n }\n\n const refinedWhere = combineFilterExprs(entry.state.filters);\n\n const storageHash = contract.storage.storageHash;\n const planMeta = { target: \"idb\", storageHash, lane: \"idb-orm\", annotations: { groupingKey } } as const;\n\n // When an index or the related store's own primary key covers exactly the\n // target fields, run one IDBKeyRange.only() point-range scan per distinct\n // tuple. Each scan visits only matching records, so only the refined\n // `where` is applied as a row filter. Otherwise, scan the whole store.\n const rangeSource = findRangeSource(contract, relatedStoreName, relatedModelName, targetFields);\n\n let relatedRows: Record<string, unknown>[];\n if (rangeSource !== undefined) {\n const refinedFilter: IdbRowFilter | undefined =\n refinedWhere !== undefined ? (row: Record<string, unknown>) => evaluateFilter(refinedWhere, row) : undefined;\n\n // IDBKeyRange.only() throws DataError for invalid keys (boolean, NaN,\n // plain objects, etc.). Such values cannot be stored as IndexedDB keys,\n // so no related rows can match — skip them before building plans.\n const ranges: IDBKeyRange[] = [];\n for (const values of localTuples.values()) {\n const ordered = keyPathFields(rangeSource.keyPath).map((f) => values[targetFields.indexOf(f)]);\n if (!ordered.every((v) => isValidIdbKey(v))) continue;\n ranges.push(\n IDBKeyRange.only(\n typeof rangeSource.keyPath === \"string\" ? (ordered[0] as IDBValidKey) : (ordered as IDBValidKey[])\n )\n );\n }\n\n // One scan per distinct tuple — independent, so run concurrently.\n const rangeResults = await Promise.all(\n ranges.map(async (range) => {\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta: planMeta,\n idbPlan: {\n meta: planMeta,\n kind: \"cursor-scan\",\n storeName: relatedStoreName,\n ...(rangeSource.indexName !== undefined ? { indexName: rangeSource.indexName } : {}),\n range,\n ...(refinedFilter !== undefined ? { filter: refinedFilter } : {}),\n },\n };\n const rows: Record<string, unknown>[] = [];\n for await (const row of executor.query(plan)) {\n rows.push(row);\n }\n return rows;\n })\n );\n relatedRows = rangeResults.flat();\n } else {\n relatedRows = [];\n // Full store scan with an in-memory FK membership + refined-where filter.\n const filter: IdbRowFilter = (row: Record<string, unknown>): boolean => {\n const token = tupleToken(row, targetFields);\n return (\n token !== null && localTuples.has(token) && (refinedWhere === undefined || evaluateFilter(refinedWhere, row))\n );\n };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta: planMeta,\n idbPlan: { meta: planMeta, kind: \"cursor-scan\", storeName: relatedStoreName, filter },\n };\n for await (const row of executor.query(plan)) {\n relatedRows.push(row);\n }\n }\n\n // ── Merge ──────────────────────────────────────────────────────────────────\n\n if (cardinality === \"1:N\") {\n // Group related rows by their target tuple.\n const grouped = new Map<string, Record<string, unknown>[]>();\n for (const rrow of relatedRows) {\n const gk = tupleToken(rrow, targetFields);\n if (gk === null) continue;\n const group = grouped.get(gk) ?? [];\n group.push(rrow);\n grouped.set(gk, group);\n }\n const groupFor = (row: Record<string, unknown>): Record<string, unknown>[] => {\n const token = tupleToken(row, localFields);\n return token === null ? [] : (grouped.get(token) ?? []);\n };\n\n if (isScalar) {\n // Scalar reducer (Phase 6.5: count) — attach the per-parent child count.\n return rows.map((row) => ({\n ...row,\n [relName]: groupFor(row).length,\n }));\n }\n\n // Collection: apply refined orderBy / skip / take per parent group.\n const comparator = buildRowComparator(entry.state.orderBy);\n const skip = entry.state.skip ?? 0;\n const take = entry.state.take;\n return rows.map((row) => {\n let group = groupFor(row);\n if (comparator !== undefined) group = [...group].sort(comparator);\n if (skip > 0 || take !== undefined) {\n group = group.slice(skip, take !== undefined ? skip + take : undefined);\n }\n return { ...row, [relName]: group };\n });\n }\n\n // N:1 / 1:1: index related rows by their target tuple, attach singles.\n // A refined `where` that excludes the related row yields `null` here.\n const indexed = new Map<string, Record<string, unknown>>();\n for (const rrow of relatedRows) {\n const token = tupleToken(rrow, targetFields);\n if (token !== null) indexed.set(token, rrow);\n }\n return rows.map((row) => {\n const token = tupleToken(row, localFields);\n return { ...row, [relName]: (token === null ? undefined : indexed.get(token)) ?? null };\n });\n}\n\n/**\n * A `Map` key for the values of `fields` in `row`, or `null` when any of them\n * is null or undefined. Equal `Date`s and binary values give equal tokens.\n */\nfunction tupleToken(row: Record<string, unknown>, fields: readonly string[]): string | null {\n const parts: unknown[] = [];\n for (const field of fields) {\n const value = row[field];\n if (value === null || value === undefined) return null;\n const token = fieldValueToken(value);\n parts.push([typeof token, String(token)]);\n }\n return JSON.stringify(parts);\n}\n\n/**\n * Finds an index, or else the store's primary key, whose key path has exactly\n * `fields` (in any order), so a lookup on those fields can use a key range.\n * Returns `undefined` when there is none, or when `IDBKeyRange` isn't available.\n */\nfunction findRangeSource(\n contract: IdbContract,\n storeName: string,\n modelName: string,\n fields: readonly string[]\n): { readonly indexName?: string; readonly keyPath: IdbKeyPath } | undefined {\n if (typeof IDBKeyRange === \"undefined\") return undefined;\n const coversFields = (keyPath: IdbKeyPath): boolean => {\n const keyFields = keyPathFields(keyPath);\n return keyFields.length === fields.length && keyFields.every((f) => fields.includes(f));\n };\n const indexes = contract.storage.stores[storeName]?.indexes ?? {};\n for (const [indexName, indexDef] of Object.entries(indexes)) {\n if (indexDef.multiEntry !== true && coversFields(indexDef.keyPath)) return { indexName, keyPath: indexDef.keyPath };\n }\n const primaryKey = getKeyPath(contract, modelName);\n return coversFields(primaryKey) ? { keyPath: primaryKey } : undefined;\n}\n","/**\n * Multi-store mutation scope for the IDB ORM.\n *\n * `withMutationScope` opens one IDB transaction spanning the named stores,\n * runs the callback with an `IdbTransactionScope` (raw driver-level execute),\n * then commits or rolls back depending on whether the callback throws.\n *\n * Pattern is a direct port of `withMutationScope` from\n * `sql-orm-client/mutation-executor.ts`, adapted for IDB's explicit\n * transaction scope API.\n *\n * @example\n * ```ts\n * await withMutationScope(runtime, [\"users\", \"posts\"], async (scope) => {\n * const userRow = await scope.execute({ kind: \"put\", storeName: \"users\", ... });\n * await scope.execute({ kind: \"put\", storeName: \"posts\", ... });\n * });\n * ```\n */\nimport type { IdbQueryExecutor } from \"./executor\";\nimport type { IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\n\n// ── Interface ─────────────────────────────────────────────────────────────────\n\n/**\n * Extends the basic {@link IdbQueryExecutor} with multi-store transaction\n * support. `IdbRuntime` satisfies this interface — `runtime.transaction()`\n * delegates to `driver.transaction()` which opens the IDB transaction.\n */\nexport interface IdbQueryExecutorWithTransaction extends IdbQueryExecutor {\n /**\n * Open a multi-store IDB transaction and return a scope object.\n *\n * The returned scope's `execute()` runs `IdbAtomicPlan`s directly inside\n * the transaction — no new transaction is opened per call, and the\n * middleware chain is bypassed. `commit()` resolves when `tx.oncomplete`\n * fires; `rollback()` calls `tx.abort()`.\n */\n transaction(storeNames: string[], mode?: IDBTransactionMode): Promise<IdbTransactionScope>;\n}\n\n// ── withMutationScope ─────────────────────────────────────────────────────────\n\n/**\n * Run a callback inside a single multi-store IDB readwrite transaction.\n *\n * Opens the transaction, passes the `IdbTransactionScope` to `run`, then:\n * - On success: awaits `scope.commit()` (waits for `tx.oncomplete`).\n * - On error: calls `scope.rollback()` and rethrows.\n *\n * The callback receives the low-level scope, not the ORM accessor.\n * Use this for multi-store atomic writes that span several object stores.\n */\nexport async function withMutationScope<T>(\n executor: IdbQueryExecutorWithTransaction,\n storeNames: string[],\n run: (scope: IdbTransactionScope) => Promise<T>\n): Promise<T> {\n const tx = await executor.transaction(storeNames, \"readwrite\");\n try {\n const result = await run(tx);\n await tx.commit();\n return result;\n } catch (err) {\n tx.rollback();\n throw err;\n }\n}\n","/**\n * IDB relation mutator factory and type guards.\n *\n * Port of `sql-orm-client/relation-mutator.ts` — same pattern, IDB types only.\n * The mutator object is passed to user-supplied relation callbacks so they can\n * express nested writes in a type-safe, intent-revealing way.\n *\n * @example\n * ```ts\n * orm.users.create({\n * id: \"u1\",\n * name: \"Alice\",\n * posts: (rel) => rel.create([{ id: \"p1\", title: \"Hello\" }]),\n * });\n * ```\n */\nimport type {\n CreateInput,\n IdbContract,\n IdbRelationMutation,\n IdbRelationMutator,\n RelationMutationConnect,\n RelationMutationCreate,\n RelationMutationDisconnect,\n} from \"./types\";\n\nexport function createRelationMutator<TContract extends IdbContract, ModelName extends string>(): IdbRelationMutator<\n TContract,\n ModelName\n> {\n return {\n create(\n data: CreateInput<TContract, ModelName> | readonly CreateInput<TContract, ModelName>[]\n ): RelationMutationCreate<TContract, ModelName> {\n const rows = Array.isArray(data) ? [...data] : [data];\n return { kind: \"create\", data: rows as readonly CreateInput<TContract, ModelName>[] };\n },\n\n connect(criteria: Record<string, unknown> | readonly Record<string, unknown>[]): RelationMutationConnect {\n const values = Array.isArray(criteria) ? [...criteria] : [criteria];\n return { kind: \"connect\", criteria: values };\n },\n\n disconnect(criteria?: readonly Record<string, unknown>[]): RelationMutationDisconnect {\n if (!criteria) return { kind: \"disconnect\" };\n return { kind: \"disconnect\", criteria: [...criteria] };\n },\n };\n}\n\nexport function isRelationMutationDescriptor(value: unknown): value is IdbRelationMutation<IdbContract, string> {\n if (!value || typeof value !== \"object\") return false;\n const candidate = value as { kind?: unknown };\n return candidate.kind === \"create\" || candidate.kind === \"connect\" || candidate.kind === \"disconnect\";\n}\n\nexport function isRelationMutationCallback(\n value: unknown\n): value is (mutator: IdbRelationMutator<IdbContract, string>) => IdbRelationMutation<IdbContract, string> {\n return typeof value === \"function\";\n}\n","/**\n * IDB nested-write executor.\n *\n * IDB adaptation of `sql-orm-client/mutation-executor.ts`. Key differences\n * from the SQL vendor:\n *\n * - No column/field mapping — IDB field names ARE the storage keys.\n * - `applyCreateDefaults`/`applyUpdateDefaults` (`mutation-defaults.ts`) fill\n * in every generator id `contract.execution.mutations.defaults` declares\n * (see `IdbMutationDefaultGeneratorId`) — IDB has no server-rendered\n * defaults, so this always runs client-side, unlike SQL's storage-plane\n * `ColumnDefault`.\n * - `insertSingleRow` → `scope.execute({ kind: \"add\", ... })`.\n * - `findRowByCriterion` / `findFirstByFilters` → `scope.execute({ kind: \"cursor-scan\", ... })`.\n * IDB allows reads inside a readwrite transaction; the transaction scope accepts\n * all `IdbAtomicPlan` types including `cursor-scan`.\n * - Child-owned `connect` → `scope.execute({ kind: \"scan-write\", write: \"put-merged\", ... })`.\n * IDB has no UPDATE SET WHERE, so we use the scan-write plan with a filter closure.\n * - `connect()` for parent-owned (N:1) relations throws if the referenced row is not\n * found — this is Phase 6.4's implicit FK validation for the connect case.\n * - Recursive nesting (nested writes inside nested writes) is not supported and throws.\n *\n * All multi-store writes are wrapped in a single `withMutationScope` call that opens\n * one IDB transaction spanning all required stores, per ADR 007.\n */\n\nimport type { PlanMeta } from \"@prisma/orm-framework/contract/types\";\nimport type { ContractReferenceRelation } from \"@prisma/orm-framework/contract/types\";\nimport { domainModelsAtDefaultNamespace } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbAtomicPlan, IdbCursorScanPlan } from \"@prisma-idb/driver-idb/runtime\";\nimport { evaluateFilter, shorthandToFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbReferentialAction } from \"@prisma-idb/target-idb/pack\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport {\n applyCreateDefaults,\n applyUpdateDefaults,\n createMutationDefaultsCache,\n type MutationDefaultsCache,\n} from \"./mutation-defaults\";\nimport { withMutationScope, type IdbQueryExecutorWithTransaction } from \"./mutation-scope\";\nimport { createRelationMutator, isRelationMutationCallback, isRelationMutationDescriptor } from \"./relation-mutator\";\nimport {\n type IdbContract,\n type IdbRelationMutation,\n type IdbRelationMutator,\n type MutationCreateInput,\n type MutationUpdateInput,\n extractKeyFromRow,\n fieldValuesEqual,\n getKeyPath,\n getStoreName,\n isValidIdbKey,\n keyEquals,\n keyToken,\n} from \"./types\";\nimport { keyPathFields, type IdbKeyPath } from \"@prisma-idb/target-idb/pack\";\nimport type { IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\n\n// ── Internal types ─────────────────────────────────────────────────────────────\n\ninterface RelationDefinition {\n readonly relationName: string;\n readonly relatedModelName: string;\n readonly relatedStoreName: string;\n readonly cardinality: string | undefined;\n readonly localFields: readonly string[];\n readonly targetFields: readonly string[];\n}\n\ninterface ParsedRelationMutation {\n readonly relation: RelationDefinition;\n readonly mutation: IdbRelationMutation<IdbContract, string>;\n}\n\ninterface ParsedMutationInput {\n readonly scalarData: Record<string, unknown>;\n readonly relationMutations: readonly ParsedRelationMutation[];\n}\n\n// ── Plan meta helpers ─────────────────────────────────────────────────────────\n\nfunction makePlanMeta(contract: IdbContract): PlanMeta {\n return {\n target: \"idb\",\n storageHash: contract.storage.storageHash,\n lane: \"idb-mutation-executor\",\n annotations: { groupingKey: \"nested\" },\n };\n}\n\n// ── Relation definition resolution (cached) ──────────────────────────────────\n\nconst relationDefsCache = new WeakMap<object, Map<string, RelationDefinition[]>>();\n\nfunction getRelationDefinitions(contract: IdbContract, modelName: string): RelationDefinition[] {\n let perContract = relationDefsCache.get(contract);\n if (!perContract) {\n perContract = new Map();\n relationDefsCache.set(contract, perContract);\n }\n\n const cached = perContract.get(modelName);\n if (cached) return cached;\n\n const model = domainModelsAtDefaultNamespace(contract.domain)[modelName];\n if (!model) {\n perContract.set(modelName, []);\n return [];\n }\n\n const defs: RelationDefinition[] = [];\n for (const [relationName, rawRelation] of Object.entries(model.relations)) {\n if (!rawRelation || typeof rawRelation !== \"object\" || !(\"on\" in rawRelation)) continue;\n\n const relation = rawRelation as ContractReferenceRelation;\n // `relation.to` is a CrossReference `{ namespace, model }`.\n const relatedModelName = relation.to.model;\n const relatedStoreName = getStoreName(contract, relatedModelName);\n defs.push({\n relationName,\n relatedModelName,\n relatedStoreName,\n cardinality: relation.cardinality,\n localFields: relation.on.localFields,\n targetFields: relation.on.targetFields,\n });\n }\n\n perContract.set(modelName, defs);\n return defs;\n}\n\n// ── Public helpers ────────────────────────────────────────────────────────────\n\n/**\n * Returns true if `data` contains at least one field that is both a known\n * relation name for `modelName` and a function (a mutation callback).\n */\nexport function hasNestedMutationCallbacks(\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>\n): boolean {\n const relationNames = new Set(getRelationDefinitions(contract, modelName).map((r) => r.relationName));\n for (const [fieldName, value] of Object.entries(data)) {\n if (relationNames.has(fieldName) && isRelationMutationCallback(value)) return true;\n }\n return false;\n}\n\n/**\n * Guards that the executor supports multi-store transactions.\n * Throws a clear error if `transaction()` is not available — the user must\n * use IdbRuntime (createIdbRuntime / createAutoMigratingIdbClient) rather than\n * a plain IdbQueryExecutor stub.\n */\nexport function requireTransactionExecutor(executor: IdbQueryExecutor): IdbQueryExecutorWithTransaction {\n if (typeof (executor as IdbQueryExecutorWithTransaction).transaction !== \"function\") {\n throw new Error(\n \"This operation requires an executor with transaction support (nested relation writes, \" +\n \"FK-validated create/update, and referential-action delete all need it). \" +\n \"Use IdbRuntime (createIdbRuntime or createAutoMigratingIdbClient) instead of a plain IdbQueryExecutor.\"\n );\n }\n return executor as IdbQueryExecutorWithTransaction;\n}\n\n// ── Entry points ──────────────────────────────────────────────────────────────\n\nexport async function executeNestedCreateMutation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n data: MutationCreateInput<IdbContract, string>;\n}): Promise<Record<string, unknown>> {\n const { executor, contract, modelName, data } = options;\n const record = data as Record<string, unknown>;\n const storeNames = collectStoreNames(contract, modelName, record, \"create\");\n const defaultsCache = createMutationDefaultsCache();\n return withMutationScope(executor, storeNames, (scope) =>\n createGraph(scope, contract, modelName, record, defaultsCache)\n );\n}\n\nexport async function executeNestedUpdateMutation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n filters: readonly IdbFilterExpr[];\n data: MutationUpdateInput<IdbContract, string>;\n}): Promise<Record<string, unknown> | null> {\n const { executor, contract, modelName, filters, data } = options;\n const record = data as Record<string, unknown>;\n const storeNames = collectStoreNames(contract, modelName, record, \"update\");\n const defaultsCache = createMutationDefaultsCache();\n return withMutationScope(executor, storeNames, (scope) =>\n updateFirstGraph(scope, contract, modelName, filters, record, defaultsCache)\n );\n}\n\n// ── Store name collection ─────────────────────────────────────────────────────\n\n/**\n * Every store a nested write may touch: the model's own store, each related\n * store a relation callback writes to, and the parent stores that foreign-key\n * checks read, for the model and for each related model. An update also\n * declares the stores its `onUpdate` referential actions may touch.\n *\n * Parent stores are declared for every foreign key, not only the ones `data`\n * sets, because a nested write can set foreign keys through `connect()` or\n * through a default.\n */\nfunction collectStoreNames(\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>,\n kind: \"create\" | \"update\"\n): string[] {\n const stores = new Set([getStoreName(contract, modelName), ...fkParentStoreNames(contract, modelName)]);\n const scalarData: Record<string, unknown> = {};\n const relationNames = new Set<string>();\n for (const def of getRelationDefinitions(contract, modelName)) {\n relationNames.add(def.relationName);\n if (def.relationName in data && isRelationMutationCallback(data[def.relationName])) {\n stores.add(def.relatedStoreName);\n for (const store of fkParentStoreNames(contract, def.relatedModelName)) stores.add(store);\n }\n }\n if (kind === \"update\") {\n for (const [field, value] of Object.entries(data)) {\n if (!relationNames.has(field)) scalarData[field] = value;\n }\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n getStoreName(contract, modelName),\n scalarData,\n createMutationDefaultsCache()\n );\n for (const store of collectOnUpdateEnforcementStoreNames(contract, modelName, patch).storeNames) stores.add(store);\n }\n return [...stores];\n}\n\n/** The stores of every parent `modelName` has a foreign key to. */\nfunction fkParentStoreNames(contract: IdbContract, modelName: string): string[] {\n return getRelationDefinitions(contract, modelName)\n .filter((def) => def.cardinality === \"N:1\")\n .map((def) => def.relatedStoreName);\n}\n\n// ── Graph operations ──────────────────────────────────────────────────────────\n\nasync function createGraph(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n input: Record<string, unknown>,\n defaultsCache: MutationDefaultsCache\n): Promise<Record<string, unknown>> {\n const parsed = parseMutationInput(contract, modelName, input);\n const { parentOwned, childOwned } = partitionByOwnership(parsed.relationMutations);\n\n const scalarData = { ...parsed.scalarData };\n\n for (const item of parentOwned) {\n if (item.mutation.kind === \"disconnect\") {\n throw new Error(\"disconnect() is only supported in update() nested mutations\");\n }\n await applyParentOwnedMutation(scope, contract, modelName, scalarData, item.relation, item.mutation, defaultsCache);\n }\n\n const parentRow = await insertSingleRow(scope, contract, modelName, scalarData, defaultsCache);\n\n for (const item of childOwned) {\n if (item.mutation.kind === \"disconnect\") {\n throw new Error(\"disconnect() is only supported in update() nested mutations\");\n }\n await applyChildOwnedMutation(scope, contract, modelName, parentRow, item.relation, item.mutation, defaultsCache);\n }\n\n return parentRow;\n}\n\nasync function updateFirstGraph(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n filters: readonly IdbFilterExpr[],\n input: Record<string, unknown>,\n defaultsCache: MutationDefaultsCache\n): Promise<Record<string, unknown> | null> {\n const existingRow = await findFirstByFilters(scope, contract, modelName, filters);\n if (!existingRow) return null;\n\n const parsed = parseMutationInput(contract, modelName, input);\n const { parentOwned, childOwned } = partitionByOwnership(parsed.relationMutations);\n\n const scalarData = { ...parsed.scalarData };\n\n for (const item of parentOwned) {\n await applyParentOwnedMutation(scope, contract, modelName, scalarData, item.relation, item.mutation, defaultsCache);\n }\n\n let parentRow = existingRow;\n\n if (Object.keys(scalarData).length > 0) {\n const storeName = getStoreName(contract, modelName);\n const keyPath = getKeyPath(contract, modelName);\n const key = extractKeyFromRow(existingRow, keyPath);\n const meta = makePlanMeta(contract);\n const patch = applyUpdateDefaults(contract.execution?.mutations.defaults, storeName, scalarData, defaultsCache);\n await validateScalarFks(scope, contract, modelName, patch, existingRow);\n await applyReferentialActionsForRowOnUpdate(scope, contract, modelName, existingRow, patch);\n const rows = await scope.execute({ meta, kind: \"update\", storeName, key, patch });\n const updated = rows[0];\n if (updated) parentRow = updated;\n }\n\n for (const item of childOwned) {\n await applyChildOwnedMutation(scope, contract, modelName, parentRow, item.relation, item.mutation, defaultsCache);\n }\n\n return parentRow;\n}\n\n// ── Input parsing ─────────────────────────────────────────────────────────────\n\nfunction parseMutationInput(\n contract: IdbContract,\n modelName: string,\n input: Record<string, unknown>\n): ParsedMutationInput {\n const scalarData: Record<string, unknown> = {};\n const relationDefs = new Map(getRelationDefinitions(contract, modelName).map((r) => [r.relationName, r]));\n const relationMutations: ParsedRelationMutation[] = [];\n\n for (const [fieldName, value] of Object.entries(input)) {\n const relation = relationDefs.get(fieldName);\n if (!relation) {\n scalarData[fieldName] = value;\n continue;\n }\n\n if (!isRelationMutationCallback(value)) {\n throw new Error(`Relation field \"${fieldName}\" on model \"${modelName}\" expects a mutator callback`);\n }\n\n const mutator = createRelationMutator<IdbContract, string>();\n const mutation = value(mutator as IdbRelationMutator<IdbContract, string>);\n if (!isRelationMutationDescriptor(mutation)) {\n throw new Error(`Relation field \"${fieldName}\" on model \"${modelName}\" returned an invalid mutation descriptor`);\n }\n\n relationMutations.push({ relation, mutation });\n }\n\n return { scalarData, relationMutations };\n}\n\n// ── Ownership partitioning ────────────────────────────────────────────────────\n\nfunction partitionByOwnership(mutations: readonly ParsedRelationMutation[]): {\n parentOwned: ParsedRelationMutation[];\n childOwned: ParsedRelationMutation[];\n} {\n const parentOwned: ParsedRelationMutation[] = [];\n const childOwned: ParsedRelationMutation[] = [];\n\n for (const item of mutations) {\n if (item.relation.cardinality === \"N:1\") {\n parentOwned.push(item);\n continue;\n }\n if (item.relation.cardinality === \"M:N\") {\n throw new Error(\"M:N nested mutations are not supported\");\n }\n childOwned.push(item);\n }\n\n return { parentOwned, childOwned };\n}\n\n// ── Parent-owned (N:1) mutations ──────────────────────────────────────────────\n\nasync function applyParentOwnedMutation(\n scope: IdbTransactionScope,\n contract: IdbContract,\n parentModelName: string,\n scalarData: Record<string, unknown>,\n relation: RelationDefinition,\n mutation: IdbRelationMutation<IdbContract, string>,\n defaultsCache: MutationDefaultsCache\n): Promise<void> {\n if (mutation.kind === \"disconnect\") {\n for (const localField of relation.localFields) {\n scalarData[localField] = null;\n }\n return;\n }\n\n if (mutation.kind === \"create\") {\n const row = mutation.data[0] as Record<string, unknown> | undefined;\n if (!row) {\n throw new Error(`create() nested mutation for relation \"${relation.relationName}\" requires data`);\n }\n // Recursive nesting is not supported in Phase 6.4 — the nested record must\n // be a plain scalar create, not itself a nested mutation.\n const relatedRow = await insertSingleRow(scope, contract, relation.relatedModelName, row, defaultsCache);\n copyRelatedValuesToParent(relation, scalarData, relatedRow, parentModelName, contract);\n return;\n }\n\n // connect()\n const criterion = mutation.criteria[0] as Record<string, unknown> | undefined;\n if (!criterion) {\n throw new Error(`connect() nested mutation for relation \"${relation.relationName}\" requires a criterion`);\n }\n const relatedRow = await findRowByCriterion(scope, contract, relation.relatedModelName, criterion);\n if (!relatedRow) {\n throw new Error(`connect() nested mutation for relation \"${relation.relationName}\" did not find a matching row`);\n }\n copyRelatedValuesToParent(relation, scalarData, relatedRow, parentModelName, contract);\n}\n\nfunction copyRelatedValuesToParent(\n relation: RelationDefinition,\n scalarData: Record<string, unknown>,\n relatedRow: Record<string, unknown>,\n _parentModelName: string,\n _contract: IdbContract\n): void {\n // localFields = parent's FK fields; targetFields = related model's PK/unique fields\n for (let i = 0; i < relation.localFields.length; i++) {\n const localField = relation.localFields[i];\n const targetField = relation.targetFields[i];\n if (!localField || !targetField) continue;\n scalarData[localField] = relatedRow[targetField];\n }\n}\n\n// ── Child-owned (1:N / 1:1) mutations ────────────────────────────────────────\n\nasync function applyChildOwnedMutation(\n scope: IdbTransactionScope,\n contract: IdbContract,\n parentModelName: string,\n parentRow: Record<string, unknown>,\n relation: RelationDefinition,\n mutation: IdbRelationMutation<IdbContract, string>,\n defaultsCache: MutationDefaultsCache\n): Promise<void> {\n // parentValues: childFkField → parentPkValue (e.g. \"authorId\" → \"u1\")\n const parentValues = readParentColumnValues(parentModelName, relation, parentRow);\n\n if (mutation.kind === \"create\") {\n for (const childInput of mutation.data) {\n const payload: Record<string, unknown> = { ...(childInput as Record<string, unknown>) };\n for (const [childField, parentValue] of parentValues.entries()) {\n payload[childField] = parentValue;\n }\n await insertSingleRow(scope, contract, relation.relatedModelName, payload, defaultsCache);\n }\n return;\n }\n\n if (mutation.kind === \"connect\") {\n for (const criterion of mutation.criteria) {\n const setValues: Record<string, unknown> = {};\n for (const [childField, parentValue] of parentValues.entries()) {\n setValues[childField] = parentValue;\n }\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n relation.relatedStoreName,\n setValues,\n defaultsCache\n );\n const filter = buildCriterionFilter(criterion as Record<string, unknown>);\n const meta = makePlanMeta(contract);\n // scan-write + put-merged: set the FK fields on every child row matching\n // the criterion. No `take` cap — the vendor's relational connect\n // (`executeUpdateCount`) connects all matching rows; for the normal\n // unique-key criterion that is exactly one row anyway. (PLAN Issue #24.)\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: relation.relatedStoreName,\n write: \"put-merged\",\n patch,\n filter,\n });\n }\n return;\n }\n\n // disconnect()\n const setValues: Record<string, unknown> = {};\n for (const childField of parentValues.keys()) {\n setValues[childField] = null;\n }\n const meta = makePlanMeta(contract);\n\n if (!mutation.criteria || mutation.criteria.length === 0) {\n // Disconnect all children of this parent.\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n relation.relatedStoreName,\n setValues,\n defaultsCache\n );\n const parentJoinFilter = buildParentJoinFilter(parentValues);\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: relation.relatedStoreName,\n write: \"put-merged\",\n patch,\n filter: parentJoinFilter,\n });\n return;\n }\n\n // Disconnect specific children matching each criterion AND the parent join.\n for (const criterion of mutation.criteria) {\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n relation.relatedStoreName,\n setValues,\n defaultsCache\n );\n const criterionFilter = buildCriterionFilter(criterion as Record<string, unknown>);\n const parentJoinFilter = buildParentJoinFilter(parentValues);\n const combinedFilter = (row: Record<string, unknown>): boolean => parentJoinFilter(row) && criterionFilter(row);\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: relation.relatedStoreName,\n write: \"put-merged\",\n patch,\n filter: combinedFilter,\n });\n }\n}\n\nfunction readParentColumnValues(\n parentModelName: string,\n relation: RelationDefinition,\n parentRow: Record<string, unknown>\n): Map<string, unknown> {\n const values = new Map<string, unknown>();\n // For 1:N: localFields = parent PK fields; targetFields = child FK fields\n for (let i = 0; i < relation.localFields.length; i++) {\n const localField = relation.localFields[i];\n const targetField = relation.targetFields[i];\n if (!localField || !targetField) continue;\n const parentValue = parentRow[localField];\n if (parentValue === undefined) {\n throw new Error(\n `Nested mutation requires parent field \"${localField}\" to be present in \"${parentModelName}\" row`\n );\n }\n // targetField is the child's FK column name; map it to the parent's value.\n values.set(targetField, parentValue);\n }\n return values;\n}\n\n// ── Row operations ────────────────────────────────────────────────────────────\n\nasync function insertSingleRow(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>,\n defaultsCache: MutationDefaultsCache\n): Promise<Record<string, unknown>> {\n assertNoNestedCallbacks(modelName, data);\n const storeName = getStoreName(contract, modelName);\n const meta = makePlanMeta(contract);\n const record = applyCreateDefaults(contract.execution?.mutations.defaults, storeName, data, defaultsCache);\n await validateScalarFks(scope, contract, modelName, record);\n const rows = await scope.execute({ meta, kind: \"add\", storeName, record });\n return rows[0] ?? record;\n}\n\n/**\n * Recursive nesting (a relation callback inside an already-nested create) is\n * not supported in Phase 6.4. Without this guard the callback function would be\n * handed to `store.put(...)`, where IDB's structured-clone throws an opaque\n * `DataCloneError` (\"could not be cloned\") that gives the developer no hint\n * about the real cause. Surface a precise error instead. (PLAN Issue #22.)\n */\nfunction assertNoNestedCallbacks(modelName: string, data: Record<string, unknown>): void {\n for (const [field, value] of Object.entries(data)) {\n if (typeof value === \"function\") {\n throw new Error(\n `Recursive nested writes are not supported: field \"${field}\" on a nested \"${modelName}\" ` +\n \"record is a relation callback. Only one level of relation nesting is supported — \" +\n \"flatten the inner relation into a separate create/connect call.\"\n );\n }\n }\n}\n\nasync function findRowByCriterion(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n criterion: Record<string, unknown>\n): Promise<Record<string, unknown> | null> {\n const expr = shorthandToFilterExpr(criterion);\n if (!expr) {\n throw new Error(`Nested connect for model \"${modelName}\" requires a non-empty criterion`);\n }\n const filter = (row: Record<string, unknown>): boolean => evaluateFilter(expr, row);\n return scanOneRow(scope, contract, modelName, filter);\n}\n\nasync function findFirstByFilters(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n filters: readonly IdbFilterExpr[]\n): Promise<Record<string, unknown> | null> {\n if (filters.length === 0) return null;\n const combined = filters.length === 1 ? filters[0]! : { kind: \"and\" as const, exprs: filters };\n const filter = (row: Record<string, unknown>): boolean => evaluateFilter(combined, row);\n return scanOneRow(scope, contract, modelName, filter);\n}\n\nasync function scanOneRow(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n filter: (row: Record<string, unknown>) => boolean\n): Promise<Record<string, unknown> | null> {\n const storeName = getStoreName(contract, modelName);\n const meta = makePlanMeta(contract);\n const plan: IdbCursorScanPlan = { meta, kind: \"cursor-scan\", storeName, filter, take: 1 };\n const rows = await scope.execute(plan as IdbAtomicPlan);\n return rows[0] ?? null;\n}\n\n// ── Filter helpers ────────────────────────────────────────────────────────────\n\nfunction buildCriterionFilter(criterion: Record<string, unknown>): (row: Record<string, unknown>) => boolean {\n const expr = shorthandToFilterExpr(criterion);\n if (!expr) return () => true;\n return (row) => evaluateFilter(expr, row);\n}\n\nfunction buildParentJoinFilter(parentValues: Map<string, unknown>): (row: Record<string, unknown>) => boolean {\n const pairs = [...parentValues.entries()];\n return (row: Record<string, unknown>): boolean =>\n pairs.every(([childField, parentValue]) => fieldValuesEqual(row[childField], parentValue));\n}\n\n// ── Referential action helpers ────────────────────────────────────────────────\n\n/**\n * Which referential-action slot to read from `IdbRelationStorage`. Shared by\n * `onDelete` enforcement (delete/deleteAll/deleteCount) and `onUpdate`\n * enforcement (update/updateAll/updateCount/upsert) — both actions are\n * declared and resolved identically, just stored under a different key.\n */\ntype ReferentialActionKind = \"onDelete\" | \"onUpdate\";\n\nfunction getStoredAction(\n contract: IdbContract,\n modelName: string,\n relationName: string,\n kind: ReferentialActionKind\n): IdbReferentialAction | undefined {\n const model = domainModelsAtDefaultNamespace(contract.domain)[modelName];\n const storage = model?.storage as\n { relations?: Record<string, { onDelete?: string; onUpdate?: string }> } | undefined;\n return storage?.relations?.[relationName]?.[kind] as IdbReferentialAction | undefined;\n}\n\nfunction sameFields(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((field, index) => field === b[index]);\n}\n\n/**\n * Resolves the referential action for a child-enforcement relation: prefers\n * the action stored directly on this side, falls back to the same action\n * stored on the inverse (FK-owning) side of the relation, and finally to\n * `defaultAction` when neither side declares one.\n *\n * Both branches are live, for different authoring paths. PSL only ever\n * stores the action on the `N:1` (FK-owning) side — enforcement always walks\n * from the parent (`1:N`/non-owning-`1:1`) side, which PSL leaves bare, so\n * the fallback is what actually finds it. TS-DSL relation entries are\n * self-contained (no PSL-style pairing requirement) and typically declare\n * the action directly on the side this function is called for, so the direct\n * check is what fires there — see `contract-builder.ts`'s\n * `validateNoConflictingRelationActions`, which rejects declaring the same\n * action kind on both sides so this fallback never has to arbitrate a real\n * conflict.\n */\nfunction getReferentialActionForRelation(\n contract: IdbContract,\n modelName: string,\n def: RelationDefinition,\n kind: ReferentialActionKind\n): EnforcedReferentialAction {\n return enforcedAction(findDeclaredAction(contract, modelName, def, kind));\n}\n\nfunction findDeclaredAction(\n contract: IdbContract,\n modelName: string,\n def: RelationDefinition,\n kind: ReferentialActionKind\n): IdbReferentialAction | undefined {\n const direct = getStoredAction(contract, modelName, def.relationName, kind);\n if (direct !== undefined) return direct;\n\n for (const inverse of getRelationDefinitions(contract, def.relatedModelName)) {\n if (inverse.relatedModelName !== modelName) continue;\n if (!sameFields(inverse.localFields, def.targetFields)) continue;\n if (!sameFields(inverse.targetFields, def.localFields)) continue;\n\n const inverseAction = getStoredAction(contract, def.relatedModelName, inverse.relationName, kind);\n if (inverseAction !== undefined) return inverseAction;\n }\n\n return undefined;\n}\n\n/** A referential action after defaults are applied and `noAction` is resolved. */\ntype EnforcedReferentialAction = Exclude<IdbReferentialAction, \"noAction\">;\n\n/**\n * Applies the default and resolves `noAction`, matching what Postgres does\n * with the same schema, so a synced app behaves the same on both sides:\n *\n * - An undeclared action defaults to `restrict`, for `onDelete` and\n * `onUpdate` alike. Prisma 8 emits no `ON DELETE`/`ON UPDATE` clause for an\n * undeclared action, and the database default is `NO ACTION`.\n * - `noAction` behaves like `restrict`. In SQL, `NO ACTION` also rejects the\n * change; it only defers the check to the end of the statement, which makes\n * no difference here.\n */\nfunction enforcedAction(declared: IdbReferentialAction | undefined): EnforcedReferentialAction {\n return declared === undefined || declared === \"noAction\" ? \"restrict\" : declared;\n}\n\nfunction getOnDeleteForDeleteRelation(\n contract: IdbContract,\n modelName: string,\n def: RelationDefinition\n): EnforcedReferentialAction {\n return getReferentialActionForRelation(contract, modelName, def, \"onDelete\");\n}\n\nfunction getOnUpdateForRelation(\n contract: IdbContract,\n modelName: string,\n def: RelationDefinition\n): EnforcedReferentialAction {\n return getReferentialActionForRelation(contract, modelName, def, \"onUpdate\");\n}\n\nfunction isDeleteEnforcementRelation(contract: IdbContract, modelName: string, def: RelationDefinition): boolean {\n if (def.cardinality === \"1:N\") return true;\n if (def.cardinality === \"1:1\") {\n // Shared-PK 1:1: the non-owning side is the one whose *own* primary key\n // IS the FK (localFields === the model's own keyPath, field-for-field,\n // in order — a compound key must match the whole ordered field list, not\n // just its first member).\n const keyPath = getKeyPath(contract, modelName);\n return sameFields(def.localFields, keyPathFields(keyPath));\n }\n return false;\n}\n\n// ── Key-only existence lookups ────────────────────────────────────────────────\n\n/**\n * An `IDBKeyRange` for the lookup \"does `modelName` have a row whose `field`\n * equals `value`?\" — but ONLY when `field` is that model's own single-field\n * primary key (so the answer is a pure key lookup that needs no row value)\n * and `value` is a legal IDB key. `null` otherwise, and the caller keeps its\n * value-materializing `cursor-scan`.\n *\n * Deliberately `null` for a compound primary key even if `field` is one of its\n * members (one member can't pin the whole key), and for any non-key field\n * (that needs an index-resolution step — Phase 10.5's shared primitive, not\n * this helper's job). `IDBKeyRange.only` throws `DataError` on invalid keys\n * (`null`, `NaN`, booleans, …), hence the guard.\n */\nfunction pkEqualityRange(contract: IdbContract, modelName: string, field: string, value: unknown): IDBKeyRange | null {\n if (typeof IDBKeyRange === \"undefined\") return null;\n const keyPath = getKeyPath(contract, modelName);\n if (typeof keyPath !== \"string\" || keyPath !== field) return null;\n if (!isValidIdbKey(value)) return null;\n return IDBKeyRange.only(value);\n}\n\n/**\n * Resolves to the first primary key in `storeName` within `range`, or\n * `undefined` — one `getKey` request, no row deserialized.\n */\nasync function firstKeyInRange(\n scope: IdbTransactionScope,\n meta: PlanMeta,\n storeName: string,\n range: IDBKeyRange\n): Promise<IDBValidKey | undefined> {\n const rows = await scope.execute({ meta, kind: \"keys\", storeName, range, take: 1 } as IdbAtomicPlan);\n return rows[0]?.[\"key\"] as IDBValidKey | undefined;\n}\n\n/**\n * `true` if any child row matches the relation against `parentRow`'s values —\n * the existence check behind `restrict`. Key-only when the relation's single\n * child field is the child model's own primary key (a shared-PK 1:1); a\n * value-materializing `cursor-scan` (`take: 1`) otherwise.\n */\nasync function childExists(\n scope: IdbTransactionScope,\n contract: IdbContract,\n meta: PlanMeta,\n def: RelationDefinition,\n parentRow: Record<string, unknown>\n): Promise<boolean> {\n if (def.targetFields.length === 1) {\n const range = pkEqualityRange(contract, def.relatedModelName, def.targetFields[0]!, parentRow[def.localFields[0]!]);\n if (range !== null) return (await firstKeyInRange(scope, meta, def.relatedStoreName, range)) !== undefined;\n }\n const found = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName: def.relatedStoreName,\n filter: buildChildFilterFromRow(def, parentRow),\n take: 1,\n } as IdbAtomicPlan);\n return found.length > 0;\n}\n\n/**\n * Builds a filter matching a relation's children against one specific parent\n * row's values. Shared by `onDelete` cascade (`applyReferentialActionsForRow`)\n * and `onUpdate` cascade (`applyReferentialActionsForRowOnUpdate`).\n */\nfunction buildChildFilterFromRow(\n def: RelationDefinition,\n row: Record<string, unknown>\n): (child: Record<string, unknown>) => boolean {\n const pairs = def.localFields.map((lf, i) => ({ childField: def.targetFields[i]!, parentValue: row[lf] }));\n return (child: Record<string, unknown>): boolean =>\n pairs.every(({ childField, parentValue }) => fieldValuesEqual(child[childField], parentValue));\n}\n\n/** Reads a field's literal `@default(...)` value from `IdbModelStorage.fieldDefaults`, if declared. */\nfunction getFieldDefault(contract: IdbContract, modelName: string, fieldName: string): unknown {\n const model = domainModelsAtDefaultNamespace(contract.domain)[modelName];\n const storage = model?.storage as { fieldDefaults?: Record<string, unknown> } | undefined;\n return storage?.fieldDefaults?.[fieldName];\n}\n\n/**\n * Builds the patch for a `setDefault` referential action: each of the\n * relation's `targetFields` (the child's FK fields) reset to its own\n * declared literal default — not the parent's. Throws when any target field\n * has no declared default; `setDefault` is only meaningful when every FK\n * field it resets has somewhere to reset to.\n */\nfunction buildSetDefaultPatch(contract: IdbContract, def: RelationDefinition): Record<string, unknown> {\n const patch: Record<string, unknown> = {};\n for (const targetField of def.targetFields) {\n const value = getFieldDefault(contract, def.relatedModelName, targetField);\n if (value === undefined) {\n throw new Error(\n `setDefault referential action on relation '${def.relationName}' requires field ` +\n `'${def.relatedModelName}.${targetField}' to declare a literal @default(...) value — ` +\n \"no default is registered for that field.\"\n );\n }\n patch[targetField] = value;\n }\n return patch;\n}\n\n/**\n * Validates that a `setDefault` patch actually references a real row before\n * it's written — without this, `setDefault` would silently reintroduce the\n * exact dangling-FK problem the rest of this file exists to prevent. A real\n * SQL database only makes `SET DEFAULT` safe because its FK constraint\n * re-checks the new value transactionally at write time; IDB has no such\n * engine to delegate to, so this check is IDB's equivalent.\n *\n * Checks against `modelName`'s own store (the parent being deleted/updated)\n * using `def.localFields` — the relation's own semantics (\"child.targetField\n * references parent.localField\") mean that's exactly what a default value\n * written to the child's FK field must match. That store is always already\n * part of the transaction (it's the model literally being written), so no\n * store-list changes are needed to call this.\n *\n * A compound relation is checked as one tuple: a single parent row must\n * match every field's default.\n *\n * `excludeKey`, when given, excludes the parent row currently being\n * deleted/updated from the existence scan. That row is still physically\n * present in the store at this point (its own write/delete hasn't happened\n * yet — this check runs first, before the enforcement loop's caller applies\n * it), so without the exclusion, a default value equal to that row's *old*\n * `localField` value would false-positive: the scan would find the row about\n * to disappear (or change away from that value) and wrongly conclude the\n * default references a real row, when after the transaction nothing will.\n */\nasync function validateSetDefaultPatch(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n def: RelationDefinition,\n patch: Record<string, unknown>,\n excludeKey?: IDBValidKey\n): Promise<void> {\n const values = def.targetFields.map((f) => patch[f]);\n // A default of null leaves no reference to check.\n if (values.some((v) => v === null || v === undefined)) return;\n\n const meta = makePlanMeta(contract);\n const exists = await parentExists(scope, contract, meta, modelName, def.localFields, values, excludeKey);\n if (!exists) {\n throw new Error(\n `setDefault referential action on relation '${def.relationName}' would set ` +\n `${def.relatedModelName} to ${describeTuple(def.targetFields, values)}, but no ${modelName} with ` +\n `${describeTuple(def.localFields, values)} exists — the declared default does not reference a real row.`\n );\n }\n}\n\n// ── Update referential action enforcement ─────────────────────────────────────\n\n/**\n * Collects every store an `onUpdate`-enforced write to `modelName` might\n * touch: the model's own store, plus the related store of any 1:N/1:1-\n * parent-side relation whose `localFields` appear in the raw patch —\n * pessimistic (checks field *presence*, not whether the resolved value will\n * actually change, since the current row isn't read yet when this runs).\n * Once a `cascade` edge is entered, the walk continues transitively (mirrors\n * `collectDeleteStoreNames`'s cascade-only recursion), since a propagated\n * value change may itself need to cascade further.\n *\n * Returns `enforces: false` when no `onUpdate` enforcement can apply to this\n * write — callers use that to keep the existing fast blind-write path\n * instead of paying for a read-before-write. This is tracked as an explicit\n * flag rather than inferred from `storeNames.length > 1`: for a\n * self-referential relation, `def.relatedStoreName` equals `modelName`'s own\n * store (already the seed of the `Set`), so the store count alone can't tell\n * \"no enforcement\" apart from \"enforces, but only against this same store\".\n */\nexport function collectOnUpdateEnforcementStoreNames(\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>\n): { storeNames: string[]; enforces: boolean } {\n const stores = new Set([getStoreName(contract, modelName)]);\n const visitedModels = new Set<string>();\n let enforces = false;\n\n function walkCascadeChain(mName: string): void {\n if (visitedModels.has(mName)) return;\n visitedModels.add(mName);\n for (const def of getRelationDefinitions(contract, mName)) {\n if (!isDeleteEnforcementRelation(contract, mName, def)) continue;\n const action = getOnUpdateForRelation(contract, mName, def);\n stores.add(def.relatedStoreName);\n if (action === \"cascade\") walkCascadeChain(def.relatedModelName);\n }\n }\n\n visitedModels.add(modelName);\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (!isDeleteEnforcementRelation(contract, modelName, def)) continue;\n if (!def.localFields.some((f) => f in data)) continue;\n const action = getOnUpdateForRelation(contract, modelName, def);\n enforces = true;\n stores.add(def.relatedStoreName);\n if (action === \"cascade\") walkCascadeChain(def.relatedModelName);\n }\n\n return { storeNames: [...stores], enforces };\n}\n\n/**\n * Enforces every `onUpdate` action declared on `modelName`'s child relations\n * against one specific `oldRow` about to be patched with `patch`. Only\n * relations whose `localFields` are both present in `patch` and differ from\n * `oldRow`'s current value are enforced — a patch that sets a field to its\n * existing value, or never touches a locally-referenced field, is a no-op\n * here. Children are matched against `oldRow`'s pre-change values.\n *\n * `cascade` propagates the new value(s) onto the matched children's FK\n * fields and recurses into each child's own `onUpdate` relations before\n * writing (the propagated change may itself need to cascade further) —\n * mirrors `applyReferentialActionsForRow`'s recursive shape, including the\n * `visited` row-level cycle guard (see that function's doc comment for the\n * fresh-per-top-level-row / shared-across-one-row's-descent contract).\n * `setNull`/`setDefault` are leaf actions: the child's FK field changes but\n * its own key doesn't, so nothing below it needs re-enforcement.\n *\n * Unlike `validateScalarFks`'s compound-FK restriction, a compound (multi-\n * field) relation is safe to cascade here: both `localFields` values come\n * from the same `oldRow`/`patch`, so there's no risk of assembling a value\n * from two unrelated rows the way independently-validated FK-existence\n * checks could.\n */\nexport async function applyReferentialActionsForRowOnUpdate(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n oldRow: Record<string, unknown>,\n patch: Record<string, unknown>,\n visited: Set<string> = new Set()\n): Promise<void> {\n const keyPath = getKeyPath(contract, modelName);\n const rowKey = `${getStoreName(contract, modelName)}::${keyToken(extractKeyFromRow(oldRow, keyPath))}`;\n if (visited.has(rowKey)) return;\n visited.add(rowKey);\n\n const meta = makePlanMeta(contract);\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (!isDeleteEnforcementRelation(contract, modelName, def)) continue;\n const changedFields = def.localFields.filter((f) => f in patch && !fieldValuesEqual(patch[f], oldRow[f]));\n if (changedFields.length === 0) continue;\n\n const action = getOnUpdateForRelation(contract, modelName, def);\n\n const childFilter = buildChildFilterFromRow(def, oldRow);\n\n if (action === \"restrict\") {\n if (await childExists(scope, contract, meta, def, oldRow)) {\n throw new Error(\n `Cannot update ${modelName} '${keyToken(extractKeyFromRow(oldRow, keyPath))}': changing field(s) ${changedFields.join(\", \")} ` +\n `would orphan child records on relation '${def.relationName}'. ` +\n \"Update or remove those children first, or declare onUpdate: Cascade, SetNull or SetDefault on the relation.\"\n );\n }\n continue;\n }\n\n if (action === \"cascade\") {\n const childPatch: Record<string, unknown> = {};\n for (let i = 0; i < def.localFields.length; i++) {\n const lf = def.localFields[i]!;\n const tf = def.targetFields[i]!;\n if (changedFields.includes(lf)) childPatch[tf] = patch[lf];\n }\n const children = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName: def.relatedStoreName,\n filter: childFilter,\n } as IdbAtomicPlan);\n for (const child of children) {\n await applyReferentialActionsForRowOnUpdate(scope, contract, def.relatedModelName, child, childPatch, visited);\n }\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: def.relatedStoreName,\n write: \"put-merged\",\n patch: childPatch,\n filter: childFilter,\n } as IdbAtomicPlan);\n continue;\n }\n\n if (action === \"setNull\") {\n const childPatch: Record<string, unknown> = {};\n for (const targetField of def.targetFields) childPatch[targetField] = null;\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: def.relatedStoreName,\n write: \"put-merged\",\n patch: childPatch,\n filter: childFilter,\n } as IdbAtomicPlan);\n continue;\n }\n\n if (action === \"setDefault\") {\n const childPatch = buildSetDefaultPatch(contract, def);\n await validateSetDefaultPatch(scope, contract, modelName, def, childPatch, extractKeyFromRow(oldRow, keyPath));\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: def.relatedStoreName,\n write: \"put-merged\",\n patch: childPatch,\n filter: childFilter,\n } as IdbAtomicPlan);\n continue;\n }\n }\n}\n\n// ── Scalar FK validation ──────────────────────────────────────────────────────\n\n/**\n * Returns true if `data` contains at least one non-null value for a localField\n * of a N:1 relation — indicating scalar FK fields that need existence validation.\n */\nexport function hasScalarFkFields(contract: IdbContract, modelName: string, data: Record<string, unknown>): boolean {\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (def.cardinality !== \"N:1\") continue;\n for (const localField of def.localFields) {\n if (localField in data && data[localField] !== null && data[localField] !== undefined) return true;\n }\n }\n return false;\n}\n\nexport function collectScalarFkStoreNames(\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>\n): string[] {\n const stores = new Set([getStoreName(contract, modelName)]);\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (def.cardinality !== \"N:1\") continue;\n const hasFkField = def.localFields.some((f) => f in data && data[f] !== null && data[f] !== undefined);\n if (hasFkField) stores.add(def.relatedStoreName);\n }\n return [...stores];\n}\n\n/**\n * Checks that every foreign key `data` sets points at an existing parent row,\n * inside the write's transaction.\n *\n * A compound foreign key is checked as one tuple: a single parent row must\n * match every field. Checking the fields one at a time could pass with each\n * value taken from a different parent. When `data` sets only some fields of a\n * compound key, the rest come from `existingRow`, the row being updated.\n * Callers must pass it in that case; see {@link fkCheckNeedsExistingRow}.\n *\n * A key with any `null` field isn't checked, like SQL's default `MATCH SIMPLE`.\n */\nexport async function validateScalarFks(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>,\n existingRow?: Record<string, unknown>\n): Promise<void> {\n const meta = makePlanMeta(contract);\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (def.cardinality !== \"N:1\") continue;\n if (!def.localFields.some((f) => f in data)) continue;\n const values = def.localFields.map((f) => (f in data ? data[f] : existingRow?.[f]));\n if (values.some((v) => v === null || v === undefined)) continue;\n\n const exists = await parentExists(scope, contract, meta, def.relatedModelName, def.targetFields, values);\n if (!exists) {\n throw new Error(\n `FK violation on relation '${def.relationName}': no ${def.relatedModelName} with ${describeTuple(def.targetFields, values)}`\n );\n }\n }\n}\n\n/**\n * `true` when `data` sets some, but not all, fields of a compound foreign\n * key. Checking it then needs the rest of the key from the row being\n * updated, so the update has to read each row before writing it.\n */\nfunction fkCheckNeedsExistingRow(contract: IdbContract, modelName: string, data: Record<string, unknown>): boolean {\n return getRelationDefinitions(contract, modelName).some((def) => {\n if (def.cardinality !== \"N:1\") return false;\n const set = def.localFields.filter((f) => f in data).length;\n return set > 0 && set < def.localFields.length;\n });\n}\n\n/**\n * Does `parentModel` have a row whose `fields` equal `values`, pairwise?\n *\n * When `fields` are exactly the parent's primary key (in any order), this is\n * one key-only lookup. Otherwise it scans the parent store, comparing values\n * the way IndexedDB compares keys. `excludeKey` leaves out one parent row,\n * for checks that run while that row is being deleted or changed.\n */\nasync function parentExists(\n scope: IdbTransactionScope,\n contract: IdbContract,\n meta: PlanMeta,\n parentModel: string,\n fields: readonly string[],\n values: readonly unknown[],\n excludeKey?: IDBValidKey\n): Promise<boolean> {\n const storeName = getStoreName(contract, parentModel);\n const keyPath = getKeyPath(contract, parentModel);\n const range = primaryKeyRange(keyPath, fields, values);\n if (range !== null) {\n // A primary key matches at most one row.\n const foundKey = await firstKeyInRange(scope, meta, storeName, range);\n return foundKey !== undefined && (excludeKey === undefined || !keyEquals(foundKey, excludeKey));\n }\n const filter = (row: Record<string, unknown>): boolean =>\n fields.every((f, i) => fieldValuesEqual(row[f], values[i])) &&\n (excludeKey === undefined || !keyEquals(extractKeyFromRow(row, keyPath), excludeKey));\n const found = await scope.execute({ meta, kind: \"cursor-scan\", storeName, filter, take: 1 } as IdbAtomicPlan);\n return found.length > 0;\n}\n\n/**\n * An `IDBKeyRange` for \"the row whose primary key is `values`\", when `fields`\n * are exactly the key's fields (in any order) and every value is a valid\n * IndexedDB key. `null` otherwise, and the caller scans instead.\n */\nfunction primaryKeyRange(\n keyPath: IdbKeyPath,\n fields: readonly string[],\n values: readonly unknown[]\n): IDBKeyRange | null {\n if (typeof IDBKeyRange === \"undefined\") return null;\n const keyFields = keyPathFields(keyPath);\n if (keyFields.length !== fields.length || !keyFields.every((f) => fields.includes(f))) return null;\n const ordered = keyFields.map((f) => values[fields.indexOf(f)]);\n if (!ordered.every((v) => isValidIdbKey(v))) return null;\n return IDBKeyRange.only(typeof keyPath === \"string\" ? (ordered[0] as IDBValidKey) : (ordered as IDBValidKey[]));\n}\n\n/** `id='u1'`, or `orgId='a', id='u1'` for a compound key. */\nfunction describeTuple(fields: readonly string[], values: readonly unknown[]): string {\n return fields.map((f, i) => `${f}='${String(values[i])}'`).join(\", \");\n}\n\nexport async function executeScalarCreateWithFkValidation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n data: Record<string, unknown>;\n}): Promise<Record<string, unknown>> {\n const { executor, contract, modelName, data } = options;\n // Apply defaults first, so the transaction declares the parent store of a\n // foreign key that a default fills in. `insertSingleRow` checks the result.\n const defaultsCache = createMutationDefaultsCache();\n const record = applyCreateDefaults(\n contract.execution?.mutations.defaults,\n getStoreName(contract, modelName),\n data,\n defaultsCache\n );\n const storeNames = collectScalarFkStoreNames(contract, modelName, record);\n return withMutationScope(executor, storeNames, (scope) =>\n insertSingleRow(scope, contract, modelName, record, defaultsCache)\n );\n}\n\n/**\n * `createAll()` for rows that set foreign keys: checks every row's foreign\n * keys and inserts it, all in one transaction, so one bad row writes nothing.\n * The batch shares one defaults cache, like the plain `createAll()` path.\n */\nexport async function executeScalarCreateAllWithFkValidation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n data: readonly Record<string, unknown>[];\n}): Promise<Record<string, unknown>[]> {\n const { executor, contract, modelName, data } = options;\n const defaultsCache = createMutationDefaultsCache();\n const storeName = getStoreName(contract, modelName);\n const records = data.map((row) =>\n applyCreateDefaults(contract.execution?.mutations.defaults, storeName, row, defaultsCache)\n );\n const storeNames = [...new Set(records.flatMap((row) => collectScalarFkStoreNames(contract, modelName, row)))];\n return withMutationScope(executor, storeNames, async (scope) => {\n const inserted: Record<string, unknown>[] = [];\n for (const record of records) {\n inserted.push(await insertSingleRow(scope, contract, modelName, record, defaultsCache));\n }\n return inserted;\n });\n}\n\n/**\n * Combines FK-existence store scope (this model's own N:1 relations) with\n * `onUpdate` enforcement store scope (this model's child relations) for a\n * single write. Returns the union alongside whether `onUpdate` enforcement\n * actually applies (i.e. the `onUpdate` collector found more than just the\n * model's own store) — callers use that flag to choose between the existing\n * fast blind-write path and the read-before-write enforcement path.\n */\nfunction collectUpdateStoreNames(\n contract: IdbContract,\n modelName: string,\n data: Record<string, unknown>\n): { storeNames: string[]; enforcesOnUpdate: boolean } {\n const fkStoreNames = collectScalarFkStoreNames(contract, modelName, data);\n const { storeNames: onUpdateStoreNames, enforces } = collectOnUpdateEnforcementStoreNames(contract, modelName, data);\n return {\n storeNames: [...new Set([...fkStoreNames, ...onUpdateStoreNames])],\n enforcesOnUpdate: enforces,\n };\n}\n\nexport async function executeScalarUpdateWithFkValidation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n filters: readonly IdbFilterExpr[];\n data: Record<string, unknown>;\n}): Promise<Record<string, unknown> | null> {\n const { executor, contract, modelName, filters, data } = options;\n const storeName = getStoreName(contract, modelName);\n // Apply defaults first, so the checks and the store list see every field\n // the write sets, including one an `onUpdate` default fills in.\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n storeName,\n data,\n createMutationDefaultsCache()\n );\n const { storeNames, enforcesOnUpdate } = collectUpdateStoreNames(contract, modelName, patch);\n const needsRowForFks = fkCheckNeedsExistingRow(contract, modelName, patch);\n return withMutationScope(executor, storeNames, async (scope) => {\n if (!needsRowForFks) await validateScalarFks(scope, contract, modelName, patch);\n const meta = makePlanMeta(contract);\n const combined =\n filters.length === 0 ? undefined : filters.length === 1 ? filters[0]! : { kind: \"and\" as const, exprs: filters };\n const filter =\n combined !== undefined ? (row: Record<string, unknown>): boolean => evaluateFilter(combined, row) : undefined;\n\n if (!enforcesOnUpdate && !needsRowForFks) {\n const rows = await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName,\n write: \"put-merged\",\n patch,\n take: 1,\n ...(filter !== undefined ? { filter } : {}),\n } as IdbAtomicPlan);\n return rows[0] ?? null;\n }\n\n // Read-before-write: onUpdate enforcement needs the pre-image to know\n // whether a locally-referenced field's value is actually changing, and a\n // partly-set compound foreign key needs the row's other key fields.\n const oldRows = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName,\n take: 1,\n ...(filter !== undefined ? { filter } : {}),\n } as IdbAtomicPlan);\n const oldRow = oldRows[0];\n if (!oldRow) return null;\n if (needsRowForFks) await validateScalarFks(scope, contract, modelName, patch, oldRow);\n if (enforcesOnUpdate) await applyReferentialActionsForRowOnUpdate(scope, contract, modelName, oldRow, patch);\n const keyPath = getKeyPath(contract, modelName);\n const key = extractKeyFromRow(oldRow, keyPath);\n const rows = await scope.execute({ meta, kind: \"update\", storeName, key, patch } as IdbAtomicPlan);\n return rows[0] ?? null;\n });\n}\n\n/**\n * Bulk counterpart to {@link executeScalarUpdateWithFkValidation}: same FK\n * validation and `onUpdate` enforcement, but applies the patch to every row\n * the filter matches (no `take: 1`) and returns all of them.\n *\n * Always goes through the transaction scope — unlike single-row `update()`,\n * which only needs one when there's a scalar FK field or `onUpdate`\n * enforcement to apply. A bulk scan-write's affected row SET isn't knowable\n * until it actually runs, and observing that result INSIDE the same\n * transaction is exactly what the sync interceptor needs to track the write\n * correctly: its transaction-scope hook (`SyncInterceptingTransactionScope#maybeTrack`'s\n * `scan-write`/`update` cases) writes one outbox event per row it's handed,\n * atomically with the write itself. The plan-level path `update()` falls\n * back to for a non-enforced single row has no equivalent hook — a plan is\n * extended with outbox ops BEFORE it runs, which only works when the\n * affected key is knowable up front.\n */\nexport async function executeBulkUpdateWithFkValidation(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n filters: readonly IdbFilterExpr[];\n data: Record<string, unknown>;\n}): Promise<Record<string, unknown>[]> {\n const { executor, contract, modelName, filters, data } = options;\n const storeName = getStoreName(contract, modelName);\n // Apply defaults first, so the checks and the store list see every field\n // the write sets, including one an `onUpdate` default fills in.\n const patch = applyUpdateDefaults(\n contract.execution?.mutations.defaults,\n storeName,\n data,\n createMutationDefaultsCache()\n );\n const { storeNames, enforcesOnUpdate } = collectUpdateStoreNames(contract, modelName, patch);\n const needsRowForFks = fkCheckNeedsExistingRow(contract, modelName, patch);\n return withMutationScope(executor, storeNames, async (scope) => {\n if (!needsRowForFks) await validateScalarFks(scope, contract, modelName, patch);\n const meta = makePlanMeta(contract);\n const combined =\n filters.length === 0 ? undefined : filters.length === 1 ? filters[0]! : { kind: \"and\" as const, exprs: filters };\n const filter =\n combined !== undefined ? (row: Record<string, unknown>): boolean => evaluateFilter(combined, row) : undefined;\n\n if (!enforcesOnUpdate && !needsRowForFks) {\n return scope.execute({\n meta,\n kind: \"scan-write\",\n storeName,\n write: \"put-merged\",\n patch,\n ...(filter !== undefined ? { filter } : {}),\n } as IdbAtomicPlan);\n }\n\n const oldRows = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName,\n ...(filter !== undefined ? { filter } : {}),\n } as IdbAtomicPlan);\n const keyPath = getKeyPath(contract, modelName);\n const results: Record<string, unknown>[] = [];\n for (const oldRow of oldRows) {\n if (needsRowForFks) await validateScalarFks(scope, contract, modelName, patch, oldRow);\n if (enforcesOnUpdate) await applyReferentialActionsForRowOnUpdate(scope, contract, modelName, oldRow, patch);\n const key = extractKeyFromRow(oldRow, keyPath);\n const rows = await scope.execute({ meta, kind: \"update\", storeName, key, patch } as IdbAtomicPlan);\n const updated = rows[0];\n if (updated) results.push(updated);\n }\n return results;\n });\n}\n\n// ── Delete referential action enforcement ─────────────────────────────────────\n\n/**\n * Returns true if the model has at least one child relation (1:N or parent-side\n * 1:1). Every such relation has an `onDelete` action to enforce: `noAction`\n * behaves like `restrict`, which is also the default.\n */\nexport function hasEnforceableChildRelations(contract: IdbContract, modelName: string): boolean {\n return getRelationDefinitions(contract, modelName).some((def) =>\n isDeleteEnforcementRelation(contract, modelName, def)\n );\n}\n\n/**\n * Transitively walks the `onDelete` cascade graph from `modelName`, collecting\n * every store a recursive delete might touch. `cascade` edges are walked\n * further (a cascaded child's own children may themselves cascade);\n * `restrict`/`setNull`/`setDefault` edges still need their store added (each\n * is read or written once) but don't recurse further, since none of them\n * delete the child row. Guarded by a model-level visited set — required\n * because IDB must declare every store a transaction might touch before it\n * opens, so this static walk must terminate even on a self-referential model\n * or a cycle of mutually-cascading models.\n */\nexport function collectDeleteStoreNames(contract: IdbContract, modelName: string): string[] {\n const stores = new Set<string>();\n const visitedModels = new Set<string>();\n\n function walk(mName: string): void {\n if (visitedModels.has(mName)) return;\n visitedModels.add(mName);\n stores.add(getStoreName(contract, mName));\n for (const def of getRelationDefinitions(contract, mName)) {\n if (!isDeleteEnforcementRelation(contract, mName, def)) continue;\n const action = getOnDeleteForDeleteRelation(contract, mName, def);\n stores.add(def.relatedStoreName);\n if (action === \"cascade\") walk(def.relatedModelName);\n }\n }\n\n walk(modelName);\n return [...stores];\n}\n\n/**\n * Enforces every `onDelete` action declared on `modelName`'s child relations\n * against one specific `row` about to be deleted. `cascade` recurses into\n * each matched child's own `onDelete` relations *before* deleting it — so a\n * multi-hop chain (`User --cascade--> Post --cascade--> Comment`) is fully\n * torn down, and a `restrict` several hops deep still aborts the whole\n * transaction (recursing before deleting means the delete never happens if a\n * deeper hop throws). `setNull`/`setDefault` are leaf actions: the child row\n * survives, so recursion never continues past them.\n *\n * `visited` (keyed by `storeName::key`) guards against row-level cycles — two\n * specific rows whose FKs point at each other through a self-referential or\n * mutually-cascading relation graph. Callers should leave it at its default\n * (a fresh `Set` per top-level call) so independent rows deleted in the same\n * `deleteAll()` batch don't cross-suppress each other's cascades; it's only\n * ever passed explicitly by this function's own recursive calls, to keep one\n * shared guard across a single row's full recursive descent.\n */\nexport async function applyReferentialActionsForRow(\n scope: IdbTransactionScope,\n contract: IdbContract,\n modelName: string,\n row: Record<string, unknown>,\n visited: Set<string> = new Set()\n): Promise<void> {\n const keyPath = getKeyPath(contract, modelName);\n const rowKey = `${getStoreName(contract, modelName)}::${keyToken(extractKeyFromRow(row, keyPath))}`;\n if (visited.has(rowKey)) return;\n visited.add(rowKey);\n\n const meta = makePlanMeta(contract);\n for (const def of getRelationDefinitions(contract, modelName)) {\n if (!isDeleteEnforcementRelation(contract, modelName, def)) continue;\n const action = getOnDeleteForDeleteRelation(contract, modelName, def);\n\n const childFilter = buildChildFilterFromRow(def, row);\n\n if (action === \"restrict\") {\n if (await childExists(scope, contract, meta, def, row)) {\n throw new Error(\n `Cannot delete ${modelName} '${keyToken(extractKeyFromRow(row, keyPath))}': child records exist on relation '${def.relationName}'. ` +\n \"Delete those children first, or declare onDelete: Cascade, SetNull or SetDefault on the relation.\"\n );\n }\n continue;\n }\n\n if (action === \"cascade\") {\n const childKeyPath = getKeyPath(contract, def.relatedModelName);\n const children = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName: def.relatedStoreName,\n filter: childFilter,\n } as IdbAtomicPlan);\n for (const child of children) {\n await applyReferentialActionsForRow(scope, contract, def.relatedModelName, child, visited);\n await scope.execute({\n meta,\n kind: \"delete\",\n storeName: def.relatedStoreName,\n key: extractKeyFromRow(child, childKeyPath),\n } as IdbAtomicPlan);\n }\n continue;\n }\n\n if (action === \"setNull\") {\n const patch: Record<string, unknown> = {};\n for (const targetField of def.targetFields) patch[targetField] = null;\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: def.relatedStoreName,\n write: \"put-merged\",\n patch,\n filter: childFilter,\n } as IdbAtomicPlan);\n continue;\n }\n\n if (action === \"setDefault\") {\n const patch = buildSetDefaultPatch(contract, def);\n await validateSetDefaultPatch(scope, contract, modelName, def, patch, extractKeyFromRow(row, keyPath));\n await scope.execute({\n meta,\n kind: \"scan-write\",\n storeName: def.relatedStoreName,\n write: \"put-merged\",\n patch,\n filter: childFilter,\n } as IdbAtomicPlan);\n continue;\n }\n }\n}\n\nexport async function executeDeleteWithReferentialActions(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n key: IDBValidKey;\n}): Promise<void> {\n const { executor, contract, modelName, key } = options;\n const storeNames = collectDeleteStoreNames(contract, modelName);\n await withMutationScope(executor, storeNames, async (scope) => {\n const storeName = getStoreName(contract, modelName);\n const meta = makePlanMeta(contract);\n const rows = await scope.execute({ meta, kind: \"key-get\", storeName, key } as IdbAtomicPlan);\n const row = rows[0];\n if (!row) return [];\n await applyReferentialActionsForRow(scope, contract, modelName, row);\n await scope.execute({ meta, kind: \"delete\", storeName, key } as IdbAtomicPlan);\n return [];\n });\n}\n\nexport async function executeDeleteAllWithReferentialActions(options: {\n executor: IdbQueryExecutorWithTransaction;\n contract: IdbContract;\n modelName: string;\n filter?: (row: Record<string, unknown>) => boolean;\n}): Promise<Record<string, unknown>[]> {\n const { executor, contract, modelName, filter } = options;\n const storeNames = collectDeleteStoreNames(contract, modelName);\n return withMutationScope(executor, storeNames, async (scope) => {\n const storeName = getStoreName(contract, modelName);\n const meta = makePlanMeta(contract);\n const keyPath = getKeyPath(contract, modelName);\n const rows = await scope.execute({\n meta,\n kind: \"cursor-scan\",\n storeName,\n ...(filter !== undefined ? { filter } : {}),\n } as IdbAtomicPlan);\n for (const row of rows) {\n await applyReferentialActionsForRow(scope, contract, modelName, row);\n const key = extractKeyFromRow(row, keyPath);\n await scope.execute({ meta, kind: \"delete\", storeName, key } as IdbAtomicPlan);\n }\n return rows;\n });\n}\n","import { AsyncIterableResult } from \"@prisma/orm-framework/components/runtime\";\nimport type { PlanMeta } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbFilterExpr, IdbQueryPlan } from \"@prisma-idb/adapter-idb/runtime\";\nimport type {\n IdbAggregateAst,\n IdbCountAst,\n IdbCreateAst,\n IdbCreateAllAst,\n IdbDeleteAst,\n IdbFindManyAst,\n IdbFindUniqueAst,\n IdbQueryAst,\n} from \"@prisma-idb/adapter-idb/runtime\";\nimport { evaluateFilter, shorthandToFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport {\n type CreateInput,\n type DefaultModelRow,\n type IdbAggregateBuilder,\n type IdbAggregateResult,\n type IdbAggregateSpec,\n type IdbContract,\n type IncludeSpec,\n type KeyType,\n type MutationCreateInput,\n type MutationUpdateInput,\n type NoIncludes,\n type OrderBySpec,\n type PatchInput,\n type ReferenceRelKeys,\n type RelatedModelOf,\n type SelectedRow,\n type WhereFilter,\n buildFieldToIndexMap,\n extractKeyFromRow,\n getKeyPath,\n getRelation,\n getStoreName,\n keyToken,\n} from \"./types\";\nimport { createModelAccessor, type IdbModelAccessor } from \"./model-accessor\";\nimport {\n type IdbAccessorState,\n type IdbIncludeScalar,\n type IncludeEntry,\n createIncludeScalar,\n emptyAccessorState,\n isIncludeScalar,\n mergeAccessorState,\n} from \"./store-state\";\nimport {\n buildRowComparator,\n combineFilterExprs,\n clampCount,\n extractIndexEqualityHint,\n extractIndexOrHint,\n isNativelyCountable,\n toCountPlan,\n type IndexOrHint,\n} from \"./query-shaping\";\nimport {\n assertValidAggregateSpec,\n computeAggregateSpec,\n createAggregateBuilder,\n toAggregateRequests,\n} from \"./aggregate-builder\";\nimport { type IdbGroupedAccessor, createGroupedAccessor } from \"./grouped-accessor\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { applyCreateDefaults, applyUpdateDefaults, createMutationDefaultsCache } from \"./mutation-defaults\";\nimport { loadRelation } from \"./relation-loader\";\nimport {\n applyReferentialActionsForRowOnUpdate,\n collectOnUpdateEnforcementStoreNames,\n collectScalarFkStoreNames,\n executeBulkUpdateWithFkValidation,\n executeDeleteAllWithReferentialActions,\n executeDeleteWithReferentialActions,\n executeNestedCreateMutation,\n executeNestedUpdateMutation,\n executeScalarCreateAllWithFkValidation,\n executeScalarCreateWithFkValidation,\n executeScalarUpdateWithFkValidation,\n hasEnforceableChildRelations,\n hasNestedMutationCallbacks,\n hasScalarFkFields,\n requireTransactionExecutor,\n validateScalarFks,\n} from \"./mutation-executor\";\nimport { withMutationScope } from \"./mutation-scope\";\n\n/** Callback form of `.where(fn)` — receives the typed model accessor proxy. */\nexport type WhereCallback<TContract, ModelName extends string> = (\n m: IdbModelAccessor<TContract, ModelName>\n) => IdbFilterExpr;\n\n/** Tuple of one-or-more field names of a model (for `select()` / `groupBy()`). */\ntype FieldTuple<TContract, ModelName extends string> = readonly [\n keyof DefaultModelRow<TContract, ModelName> & string,\n ...(keyof DefaultModelRow<TContract, ModelName> & string)[],\n];\n\n/**\n * The child accessor handed to an `include()` refinement callback.\n *\n * Exposes the chainable narrowing methods (`where` / `orderBy` / `take` /\n * `skip`) plus the scalar `count()` reducer. Mirrors the vendor\n * `IncludeRefinementCollection`: chainable methods return the same refinement\n * surface so `count()` stays reachable after a `where()`, and `count()` returns\n * an {@link IdbIncludeScalar} marker rather than the async terminal `count()`\n * found on the top-level accessor.\n */\nexport interface IdbIncludeRefinementAccessor<TContract, ModelName extends string> {\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbIncludeRefinementAccessor<TContract, ModelName>;\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbIncludeRefinementAccessor<TContract, ModelName>;\n take(n: number): IdbIncludeRefinementAccessor<TContract, ModelName>;\n skip(n: number): IdbIncludeRefinementAccessor<TContract, ModelName>;\n count(): IdbIncludeScalar;\n}\n\n/** Refinement callback type for a given relation key `K`. */\ntype IncludeRefineFn<TContract, ModelName extends string, K extends string, R> = (\n collection: IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n) => R;\n\n// ── Interface ─────────────────────────────────────────────────────────────────\n\n/**\n * Immutable query-builder for a single IDB object store.\n *\n * Each method that narrows the query (`.where()`, `.take()`, etc.) returns a\n * new, independent accessor instance — the original is never mutated. This\n * mirrors the `MongoCollection` pattern from Prisma ORM's Mongo family.\n *\n * @template TContract - The full IDB contract (with or without type maps).\n * @template ModelName - The model (store) this accessor targets.\n * @template TIncludes - Tracks which relations have been included via\n * `.include()` calls, so the return type widens progressively.\n * @template TSelected - Field names kept by `.select()`. `never` (the\n * default) means \"all fields\"; otherwise the row narrows to these fields\n * (plus any included relations).\n */\nexport interface IdbStoreAccessor<\n TContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName> = NoIncludes,\n TSelected extends string = never,\n> {\n /**\n * Add a filter (ANDed with any previous `.where()` calls).\n *\n * Two forms:\n *\n * - **Shorthand**: `where({ field: value })` — multi-key shorthand\n * objects compose as AND. `null` values become null-checks rather\n * than literal-null equalities so absent fields match.\n * - **Callback**: `where((m) => m.field.op(value))` — receives the\n * typed model accessor proxy and returns an `IdbFilterExpr` built\n * via the operator surface. Combinators (`and`, `or`, `not` from\n * `@prisma-idb/client-idb/orm`) compose nodes.\n */\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Set the sort order. Replaces any previous `.orderBy()` call. */\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Limit the number of rows returned. */\n take(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Skip the first `n` rows (OFFSET). */\n skip(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /**\n * Include a reference relation in the returned rows.\n *\n * The relation is loaded via a single batch cursor scan after the main\n * query — O(1) round trips to IDB per included relation regardless of\n * the number of parent rows. The return type gains the relation field\n * automatically.\n *\n * An optional refinement callback narrows the loaded relation:\n *\n * - return the (chained) collection to apply `where` / `orderBy` /\n * `take` / `skip` to the related rows (per-parent for `1:N`);\n * - return `collection.count()` to reduce a to-many relation to the\n * number of matching children (the field becomes a `number`).\n *\n * @example\n * ```ts\n * db.users.include(\"posts\", (posts) => posts.where({ published: true }).take(5))\n * db.users.include(\"posts\", (posts) => posts.count())\n * ```\n */\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n >\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, true>, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn: IncludeRefineFn<TContract, ModelName, K, IdbIncludeScalar>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, \"scalar\">, TSelected>;\n\n /**\n * Project the row down to a subset of scalar fields. Any previously\n * `.include()`d relations are preserved on the result; only the scalar\n * fields are narrowed.\n *\n * @example\n * ```ts\n * const summaries = await db.users.select(\"id\", \"email\").all();\n * // typeof summaries[number] === { id: string; email: string }\n * ```\n */\n select<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, Fields[number]>;\n\n /** Return all matching rows as an async iterable (also awaitable as `Row[]`). */\n all(): AsyncIterableResult<SelectedRow<TContract, ModelName, TIncludes, TSelected>>;\n\n /** Return the first matching row, or `null` if none match. */\n first(): Promise<SelectedRow<TContract, ModelName, TIncludes, TSelected> | null>;\n\n /**\n * Run an in-memory aggregate (count/sum/avg/min/max) over the rows matching\n * the accumulated `.where()` filter. Returns one result object keyed by the\n * aliases supplied in the spec.\n *\n * @example\n * ```ts\n * const stats = await db.posts.where({ published: true }).aggregate((agg) => ({\n * total: agg.count(),\n * avgViews: agg.avg(\"views\"),\n * }));\n * ```\n */\n aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<IdbAggregateResult<Spec>>;\n\n /**\n * Switch to grouped-aggregate mode. The returned {@link IdbGroupedAccessor}'s\n * `.aggregate(...)` terminal produces one row per group with the chosen key\n * fields plus the requested aggregates.\n *\n * @example\n * ```ts\n * const byUser = await db.posts\n * .where({ published: true })\n * .groupBy(\"authorId\")\n * .aggregate((agg) => ({ count: agg.count(), totalViews: agg.sum(\"views\") }));\n * ```\n */\n groupBy<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbGroupedAccessor<TContract, ModelName, Fields>;\n\n /**\n * Insert a record into the store and return the stored row.\n *\n * The primary key field is optional in `data` — pass it to use a\n * client-generated ID (`cuid`, `uuid`) or omit it for auto-increment stores.\n *\n * Relation fields accept a mutation callback:\n * `posts: (rel) => rel.create([...])` or `author: (rel) => rel.connect({ id })`.\n * When any relation callback is present, all writes are wrapped in a single\n * multi-store IDB transaction (requires IdbRuntime, not a plain executor).\n */\n create(data: MutationCreateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName>>;\n\n /** Look up a single row by primary key. Returns `null` if not found. */\n findUnique(key: KeyType<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null>;\n\n /** Delete the row with the given primary key. */\n delete(key: KeyType<TContract, ModelName>): Promise<void>;\n\n /**\n * Update the first row matching the accumulated `.where()` filter.\n * Returns the merged row, or `null` if no row matches.\n *\n * Relation fields accept `connect` or `disconnect` callbacks. When any\n * relation callback is present, all writes run in a single multi-store\n * IDB transaction (requires IdbRuntime).\n */\n update(patch: MutationUpdateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null>;\n\n /**\n * Update all rows matching the accumulated `.where()` filter and return\n * them as an `AsyncIterableResult` (also awaitable as `Row[]`).\n */\n updateAll(patch: PatchInput<TContract, ModelName>): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Update all rows matching the accumulated `.where()` filter.\n * Returns the count of updated rows.\n */\n updateCount(patch: PatchInput<TContract, ModelName>): Promise<number>;\n\n /**\n * Insert or update a single record.\n *\n * - If a row matching `where` exists: shallow-merge `update` onto it and\n * return the merged row.\n * - If no matching row exists: insert `create` and return it.\n */\n upsert(args: {\n create: CreateInput<TContract, ModelName>;\n update: PatchInput<TContract, ModelName>;\n where: WhereFilter<TContract, ModelName>;\n }): Promise<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Insert multiple records in a single atomic transaction.\n * Returns all inserted rows as an `AsyncIterableResult`.\n */\n createAll(data: CreateInput<TContract, ModelName>[]): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Insert multiple records in a single atomic transaction.\n * Returns the count of inserted rows.\n */\n createCount(data: CreateInput<TContract, ModelName>[]): Promise<number>;\n\n /**\n * Delete all rows matching the accumulated `.where()` filter.\n * Returns the deleted rows as an `AsyncIterableResult`.\n */\n deleteAll(): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Delete all rows matching the accumulated `.where()` filter.\n * Returns the count of deleted rows.\n */\n deleteCount(): Promise<number>;\n\n /**\n * Count all rows matching the accumulated `.where()` filter.\n * With no filter, counts all rows in the store.\n *\n * **Note — `skip`/`take` are respected**: unlike Prisma's SQL `count()`,\n * which ignores pagination, this implementation reuses the same cursor-scan\n * plan as `all()`. That means `where(...).take(5).count()` returns at most 5,\n * not the total number of matching rows. Use `where(...).count()` without\n * `take`/`skip` when you need an unbounded total.\n */\n count(): Promise<number>;\n}\n\n// ── Implementation ────────────────────────────────────────────────────────────\n\n/**\n * Concrete immutable query builder.\n *\n * Internal details:\n * - All state is in `#state` (filters, orderBy, skip, take, includes, selectedFields).\n * - Builder methods clone via `#clone()` — O(1) copies since state is\n * structurally shared.\n * - `all()` materialises the main rows first, then batch-loads each included\n * relation, then applies any `.select()` projection before yielding.\n * - `#includeRefinementMode` flips `count()` from an async terminal to an\n * {@link IdbIncludeScalar} marker so it can be used inside `include()`.\n */\nexport class IdbStoreAccessorImpl<\n TContract extends IdbContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName> = NoIncludes,\n TSelected extends string = never,\n> implements IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n readonly #contract: TContract;\n readonly #modelName: ModelName;\n readonly #executor: IdbQueryExecutor;\n readonly #storeName: string;\n readonly #state: IdbAccessorState;\n readonly #newGroupingKey: () => string;\n readonly #includeRefinementMode: boolean;\n\n constructor(\n contract: TContract,\n modelName: ModelName,\n executor: IdbQueryExecutor,\n state?: IdbAccessorState,\n newGroupingKey?: () => string,\n includeRefinementMode = false\n ) {\n this.#contract = contract;\n this.#modelName = modelName;\n this.#executor = executor;\n this.#storeName = getStoreName(contract, modelName);\n this.#state = state ?? emptyAccessorState();\n // Default: per-instance counter (single client; avoids module-level interleaving).\n let _key = 0;\n this.#newGroupingKey = newGroupingKey ?? (() => `idb-op-${++_key}`);\n this.#includeRefinementMode = includeRefinementMode;\n }\n\n // ── Builder methods ───────────────────────────────────────────────────────\n\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n const expr =\n typeof filter === \"function\"\n ? filter(createModelAccessor<TContract, ModelName>())\n : shorthandToFilterExpr(filter as Record<string, unknown>);\n // An empty shorthand object (or one with only undefined values) lifts\n // to `undefined` — keep the existing filter list untouched so chained\n // `.where({})` calls don't produce noisy AND nodes.\n if (expr === undefined) return this.#clone({});\n return this.#clone({ filters: [...this.#state.filters, expr] });\n }\n\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ orderBy: spec as Record<string, \"asc\" | \"desc\"> });\n }\n\n take(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ take: n });\n }\n\n skip(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ skip: n });\n }\n\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n >\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, true>, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn: IncludeRefineFn<TContract, ModelName, K, IdbIncludeScalar>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, \"scalar\">, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>> | IdbIncludeScalar\n >\n ): IdbStoreAccessor<TContract, ModelName, IncludeSpec<TContract, ModelName>, TSelected> {\n const entry = this.#resolveIncludeEntry(relation, refineFn);\n const newState = mergeAccessorState(this.#state, {\n includes: { ...this.#state.includes, [relation]: entry },\n });\n // The new instance is identical at runtime; the narrowed TIncludes type is\n // only a compile-time distinction — so an `as unknown as` cast is safe.\n return new IdbStoreAccessorImpl(\n this.#contract,\n this.#modelName,\n this.#executor,\n newState,\n this.#newGroupingKey,\n this.#includeRefinementMode\n ) as unknown as IdbStoreAccessor<TContract, ModelName, IncludeSpec<TContract, ModelName>, TSelected>;\n }\n\n select<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, Fields[number]> {\n // Runtime is identical; only TSelected narrows. Cast bridges the type-level\n // projection (the clone preserves TIncludes / contract / executor).\n return this.#clone({ selectedFields: fields as readonly string[] }) as unknown as IdbStoreAccessor<\n TContract,\n ModelName,\n TIncludes,\n Fields[number]\n >;\n }\n\n // ── Execution methods ─────────────────────────────────────────────────────\n\n all(): AsyncIterableResult<SelectedRow<TContract, ModelName, TIncludes, TSelected>> {\n const groupingKey = this.#newGroupingKey();\n // Capture the private fields needed inside the generator. Private names\n // must be accessed on `this`, so we bind the methods to keep them callable\n // without aliasing `this` (no-this-alias).\n const buildScanPlan = this.#buildScanPlan.bind(this);\n const executeOrRows = this.#executeOrRows.bind(this);\n const executorQuery = this.#executor.query.bind(this.#executor);\n const applyIncludes = this.#applyIncludes.bind(this);\n const projectRows = this.#projectRows.bind(this);\n const combined = this.#combinedFilterExpr();\n const fieldToIndexMap =\n typeof IDBKeyRange !== \"undefined\" ? buildFieldToIndexMap(this.#contract, this.#storeName) : undefined;\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const comparator = buildRowComparator(this.#state.orderBy);\n const skip = this.#state.skip;\n const take = this.#state.take;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<SelectedRow<TContract, ModelName, TIncludes, TSelected>, void, unknown> {\n let rows: Record<string, unknown>[];\n\n // OR multi-scan path: union N index point-range scans, deduplicate,\n // re-apply orderBy (the union has no overall ordering), then apply\n // skip/take in-memory (pagination must happen after the union).\n const orHint = fieldToIndexMap !== undefined ? extractIndexOrHint(combined, fieldToIndexMap, keyPath) : null;\n if (orHint !== null) {\n rows = await executeOrRows(orHint, groupingKey, combined);\n if (comparator !== undefined) rows.sort(comparator);\n if (skip !== undefined) rows = rows.slice(skip);\n if (take !== undefined) rows = rows.slice(0, take);\n } else {\n // AND single-index path (or full scan — decided inside buildScanPlan).\n const scanPlan = buildScanPlan<Record<string, unknown>>(groupingKey, fieldToIndexMap);\n rows = [];\n for await (const row of executorQuery(scanPlan)) {\n rows.push(row);\n }\n }\n\n // Batch-load any included relations (uses full rows — FK fields intact).\n const withIncludes = await applyIncludes(rows, groupingKey);\n\n // Apply any `.select()` projection, then yield.\n for (const row of projectRows(withIncludes)) {\n yield row as SelectedRow<TContract, ModelName, TIncludes, TSelected>;\n }\n })()\n );\n }\n\n async first(): Promise<SelectedRow<TContract, ModelName, TIncludes, TSelected> | null> {\n return this.take(1).all().first();\n }\n\n async aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<IdbAggregateResult<Spec>> {\n const spec = fn(createAggregateBuilder<TContract, ModelName>());\n assertValidAggregateSpec(spec, \"aggregate()\");\n const combined = this.#combinedFilterExpr();\n const ast: IdbAggregateAst = {\n kind: \"aggregate\",\n modelName: this.#modelName,\n aggregates: toAggregateRequests(spec),\n ...(combined !== undefined ? { where: combined } : {}),\n };\n const groupingKey = this.#newGroupingKey();\n\n // When `count` is the ONLY selector no row value is ever read, so the\n // total can come from a native count. A mixed spec (count alongside\n // sum/avg/min/max) needs the rows regardless, so it materializes. Like\n // the materialized path, aggregate() ignores skip/take.\n if (Object.values(spec).every((selector) => selector.fn === \"count\")) {\n const scanPlan = this.#buildScanPlan<Record<string, unknown>>(groupingKey);\n const total = await this.#executeNativeCount(scanPlan, ast);\n if (total !== null) {\n const result: Record<string, number | null> = {};\n for (const alias of Object.keys(spec)) result[alias] = total;\n return result as IdbAggregateResult<Spec>;\n }\n }\n\n const rows = await this.#materialize(groupingKey, ast);\n return computeAggregateSpec(spec, rows) as IdbAggregateResult<Spec>;\n }\n\n groupBy<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbGroupedAccessor<TContract, ModelName, Fields> {\n const combined = this.#combinedFilterExpr();\n const materialize = (ast: IdbQueryAst): Promise<Record<string, unknown>[]> =>\n this.#materialize(this.#newGroupingKey(), ast);\n return createGroupedAccessor<TContract, ModelName, Fields>({\n modelName: this.#modelName,\n by: fields as readonly string[],\n where: combined,\n materialize,\n });\n }\n\n async create(data: MutationCreateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName>> {\n const record = data as Record<string, unknown>;\n\n if (hasNestedMutationCallbacks(this.#contract, this.#modelName, record)) {\n const row = await executeNestedCreateMutation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n data: record,\n });\n return row as DefaultModelRow<TContract, ModelName>;\n }\n\n // Apply defaults before deciding whether foreign keys need checking: a\n // default can fill in a foreign key the caller left out.\n const withDefaults = applyCreateDefaults(\n this.#contract.execution?.mutations.defaults,\n this.#storeName,\n record,\n createMutationDefaultsCache()\n );\n if (hasScalarFkFields(this.#contract, this.#modelName, withDefaults)) {\n const row = await executeScalarCreateWithFkValidation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n data: withDefaults,\n });\n return row as DefaultModelRow<TContract, ModelName>;\n }\n\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbCreateAst = { kind: \"create\", modelName: this.#modelName, data: withDefaults };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"add\", storeName: this.#storeName, record: withDefaults },\n };\n // The IDB driver echoes the stored record back as the single result row.\n for await (const row of this.#executor.query(plan)) {\n return row as DefaultModelRow<TContract, ModelName>;\n }\n return withDefaults as DefaultModelRow<TContract, ModelName>;\n }\n\n async findUnique(key: KeyType<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null> {\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbFindUniqueAst = { kind: \"findUnique\", modelName: this.#modelName, key };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"key-get\", storeName: this.#storeName, key: key as IDBValidKey },\n };\n for await (const row of this.#executor.query(plan)) {\n return row as DefaultModelRow<TContract, ModelName>;\n }\n return null;\n }\n\n async delete(key: KeyType<TContract, ModelName>): Promise<void> {\n if (hasEnforceableChildRelations(this.#contract, this.#modelName)) {\n await executeDeleteWithReferentialActions({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n key: key as IDBValidKey,\n });\n return;\n }\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbDeleteAst = { kind: \"delete\", modelName: this.#modelName, key };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"delete\", storeName: this.#storeName, key: key as IDBValidKey },\n };\n // The driver echoes the deleted row, but this API returns void — drain\n // via toArray() just to execute the plan and discard the result.\n await this.#executor.query(plan).toArray();\n }\n\n async update(\n patch: MutationUpdateInput<TContract, ModelName>\n ): Promise<DefaultModelRow<TContract, ModelName> | null> {\n const patchRecord = patch as Record<string, unknown>;\n\n if (hasNestedMutationCallbacks(this.#contract, this.#modelName, patchRecord)) {\n const row = await executeNestedUpdateMutation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n filters: this.#state.filters,\n data: patchRecord,\n });\n return row as DefaultModelRow<TContract, ModelName> | null;\n }\n\n // Always routes through the transaction scope, whether or not the patch\n // touches a scalar FK field — same reasoning as `updateAll()` below: the\n // matched row isn't known until the scan-write actually runs (`.where()`\n // filters on ANY field, not just the primary key), and only the\n // transaction-scope path lets the sync interceptor observe that REAL row\n // and key it correctly (`SyncInterceptingTransactionScope#maybeTrack`'s\n // `update`/`scan-write` cases), atomically with the write itself.\n //\n // The previous plan-level fallback here (for patches with no FK field)\n // tried to recover the key by statically inspecting the filter AST\n // instead — which only worked for the narrow case of an equality filter\n // directly on the primary key (`.where({ id })`). Any other filter\n // (`.where({ name: \"...\" })`, a range, an OR) left the key unresolved,\n // and the outbox event synced with a raw filter tree the server\n // couldn't apply — or, after an earlier fix, was rejected outright with\n // `Unsupported update: filter does not pin \"id\" by equality`. Routing\n // through the transaction scope unconditionally removes the whole\n // category: the row (and therefore its key) comes from what actually\n // matched, not from re-deriving it from the filter that found it.\n const row = await executeScalarUpdateWithFkValidation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n filters: this.#state.filters,\n data: patchRecord,\n });\n return row as DefaultModelRow<TContract, ModelName> | null;\n }\n\n /**\n * Always routes through the transaction scope (`executeBulkUpdateWithFkValidation`),\n * unlike single-row `update()`'s plan-level fallback for the no-FK-field\n * case. A bulk scan-write's affected row set isn't knowable until it\n * actually runs — going through the transaction scope is what lets the\n * sync interceptor observe the real affected rows and write one outbox\n * event per row (see `SyncInterceptingTransactionScope#maybeTrack`'s\n * `scan-write` case), atomically with the write itself, instead of one\n * event for the whole batch with no way to recover which rows it covered.\n */\n updateAll(patch: PatchInput<TContract, ModelName>): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n const contract = this.#contract;\n const modelName = this.#modelName;\n const filters = this.#state.filters;\n const patchRecord = patch as Record<string, unknown>;\n const executor = requireTransactionExecutor(this.#executor);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeBulkUpdateWithFkValidation({\n executor,\n contract,\n modelName,\n filters,\n data: patchRecord,\n });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n\n async updateCount(patch: PatchInput<TContract, ModelName>): Promise<number> {\n return (await this.updateAll(patch).toArray()).length;\n }\n\n async upsert(args: {\n create: CreateInput<TContract, ModelName>;\n update: PatchInput<TContract, ModelName>;\n where: WhereFilter<TContract, ModelName>;\n }): Promise<DefaultModelRow<TContract, ModelName>> {\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const whereExpr = shorthandToFilterExpr(args.where as Record<string, unknown>);\n const matches = (row: Record<string, unknown>): boolean =>\n whereExpr === undefined || evaluateFilter(whereExpr, row);\n const meta = this.#planMeta(this.#newGroupingKey());\n const createRecord = args.create as Record<string, unknown>;\n const patchRecord = args.update as Record<string, unknown>;\n const storeName = this.#storeName;\n const executionDefaults = this.#contract.execution?.mutations.defaults;\n\n // Runs the find-then-write in a single readwrite transaction so there is\n // no check-then-act race window — atomicity is needed both for that and\n // for `onUpdate` referential-action enforcement (a multi-store read +\n // write) on the update branch. Mirrors the vendor's single-statement\n // upsert.\n const exec = requireTransactionExecutor(this.#executor);\n // Defaults are applied here, before store-name collection, rather than\n // inside the transaction: a default can add a field that isn't in the\n // caller's raw data, and if that field is a foreign key or a field that\n // children reference, collecting stores from the raw data would\n // under-declare the transaction's store list. Applying defaults first (a\n // pure function of the data + static contract config, no row read needed)\n // and reusing the result throughout keeps FK checks, enforcement, store\n // collection and the actual write looking at the same values.\n const effectivePatch = applyUpdateDefaults(\n executionDefaults,\n storeName,\n patchRecord,\n createMutationDefaultsCache()\n );\n const createWithDefaults = applyCreateDefaults(\n executionDefaults,\n storeName,\n createRecord,\n createMutationDefaultsCache()\n );\n const { storeNames: onUpdateStoreNames } = collectOnUpdateEnforcementStoreNames(\n this.#contract,\n this.#modelName,\n effectivePatch\n );\n // Either branch may set foreign keys, and which one runs isn't known until\n // the row is looked up, so declare the parent stores both would read.\n const storeNames = [\n ...new Set([\n storeName,\n ...onUpdateStoreNames,\n ...collectScalarFkStoreNames(this.#contract, this.#modelName, createWithDefaults),\n ...collectScalarFkStoreNames(this.#contract, this.#modelName, effectivePatch),\n ]),\n ];\n return withMutationScope(exec, storeNames, async (scope) => {\n const found = await scope.execute({ meta, kind: \"cursor-scan\", storeName, filter: matches, take: 1 });\n const existing = found[0];\n if (existing === undefined) {\n await validateScalarFks(scope, this.#contract, this.#modelName, createWithDefaults);\n const rows = await scope.execute({ meta, kind: \"add\", storeName, record: createWithDefaults });\n return (rows[0] ?? createWithDefaults) as DefaultModelRow<TContract, ModelName>;\n }\n await validateScalarFks(scope, this.#contract, this.#modelName, effectivePatch, existing);\n const key = extractKeyFromRow(existing, keyPath);\n await applyReferentialActionsForRowOnUpdate(scope, this.#contract, this.#modelName, existing, effectivePatch);\n const rows = await scope.execute({ meta, kind: \"update\", storeName, key, patch: effectivePatch });\n return (rows[0] ?? existing) as DefaultModelRow<TContract, ModelName>;\n });\n }\n\n createAll(data: CreateInput<TContract, ModelName>[]): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n // One shared cache for the whole batch — every row in a single createAll()\n // call gets the same generated `temporal.updatedAt()` timestamp, matching\n // SQL's 'query'-stability semantics for the same generator. Defaults are\n // applied before deciding whether foreign keys need checking, because a\n // default can fill in a foreign key.\n const defaultsCache = createMutationDefaultsCache();\n const executionDefaults = this.#contract.execution?.mutations.defaults;\n const records = data.map((d) =>\n applyCreateDefaults(executionDefaults, this.#storeName, d as Record<string, unknown>, defaultsCache)\n );\n if (records.some((row) => hasScalarFkFields(this.#contract, this.#modelName, row))) {\n const executor = requireTransactionExecutor(this.#executor);\n const contract = this.#contract;\n const modelName = this.#modelName;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeScalarCreateAllWithFkValidation({ executor, contract, modelName, data: records });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbCreateAllAst = { kind: \"createAll\", modelName: this.#modelName, data: records };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"batch\",\n storeNames: [this.#storeName],\n ops: records.map((record) => ({ meta, kind: \"add\" as const, storeName: this.#storeName, record })),\n },\n };\n const executorQuery = this.#executor.query.bind(this.#executor);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n for await (const row of executorQuery(plan)) {\n yield row as DefaultModelRow<TContract, ModelName>;\n }\n })()\n );\n }\n\n async createCount(data: CreateInput<TContract, ModelName>[]): Promise<number> {\n return (await this.createAll(data).toArray()).length;\n }\n\n /**\n * Always routes through the transaction scope (`executeDeleteAllWithReferentialActions`),\n * not just when there are enforceable child relations to cascade — that\n * function already handles the no-relations case correctly (an empty\n * relation list is a no-op loop), and going through it unconditionally is\n * what lets the sync interceptor's transaction-scope tracking write one\n * outbox event per actually-deleted row instead of one lump event for\n * the whole batch with no way to know which rows it covered. See\n * `updateAll()`'s doc comment for the same reasoning.\n */\n deleteAll(): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n const combined = this.#combinedFilterExpr();\n const filter = combined !== undefined ? (row: Record<string, unknown>) => evaluateFilter(combined, row) : undefined;\n const contract = this.#contract;\n const modelName = this.#modelName;\n const executor = requireTransactionExecutor(this.#executor);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeDeleteAllWithReferentialActions({\n executor,\n contract,\n modelName,\n ...(filter !== undefined ? { filter } : {}),\n });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n\n async deleteCount(): Promise<number> {\n return (await this.deleteAll().toArray()).length;\n }\n\n count(): Promise<number> {\n if (this.#includeRefinementMode) {\n // Inside an include() refinement, count() is a scalar-include marker that\n // include() consumes synchronously — not the async terminal below. The\n // IdbIncludeRefinementAccessor type surfaces the IdbIncludeScalar return;\n // this cast bridges count()'s dual runtime role.\n return createIncludeScalar(this.#state) as unknown as Promise<number>;\n }\n return this.#countTerminal();\n }\n\n // ── Private helpers ───────────────────────────────────────────────────────\n\n async #countTerminal(): Promise<number> {\n const groupingKey = this.#newGroupingKey();\n const combined = this.#combinedFilterExpr();\n const fieldToIndexMap =\n typeof IDBKeyRange !== \"undefined\" ? buildFieldToIndexMap(this.#contract, this.#storeName) : undefined;\n\n // OR multi-scan path: count the deduped+filtered union, applying\n // skip/take pagination so count() is consistent with the non-OR path.\n // Never native: a per-branch count() double-counts a row that matches two\n // branches, and deduplication needs the actual primary keys.\n if (fieldToIndexMap !== undefined) {\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const orHint = extractIndexOrHint(combined, fieldToIndexMap, keyPath);\n if (orHint !== null) {\n const rows = await this.#executeOrRows(orHint, groupingKey, combined);\n return clampCount(rows.length, this.#state.skip, this.#state.take);\n }\n }\n\n const scanPlan = this.#buildScanPlan<Record<string, unknown>>(groupingKey, fieldToIndexMap);\n // Middleware sees a `count` AST regardless of which physical plan runs.\n const scanAst = scanPlan.ast;\n const ast: IdbCountAst = {\n kind: \"count\",\n modelName: this.#modelName,\n ...(scanAst?.kind === \"findMany\" && scanAst.where !== undefined ? { where: scanAst.where } : {}),\n };\n\n // Native path: when the whole `where` is captured by a key range (or\n // there is none), ask IndexedDB to count directly — no row is\n // deserialized. skip/take are applied to the native (unpaginated) total.\n const nativeTotal = await this.#executeNativeCount(scanPlan, ast);\n if (nativeTotal !== null) return clampCount(nativeTotal, this.#state.skip, this.#state.take);\n\n // Fallback: a residual in-memory filter needs each row's value, so the\n // rows must be materialized and counted.\n const plan: IdbQueryPlan<Record<string, unknown>> = { ...scanPlan, ast };\n let n = 0;\n for await (const _ of this.#executor.query(plan)) {\n n++;\n }\n return n;\n }\n\n /**\n * Resolve an `include()` argument pair into an {@link IncludeEntry}: run the\n * optional refinement against a fresh refinement-mode child accessor, then\n * classify the result as a scalar count or a refined collection.\n */\n #resolveIncludeEntry(relation: string, refineFn: ((collection: never) => unknown) | undefined): IncludeEntry {\n if (refineFn === undefined) {\n return { kind: \"collection\", state: emptyAccessorState() };\n }\n\n const rel = getRelation(this.#contract, this.#modelName, relation);\n // v0.12.0: `relation.to` is a CrossReference `{ namespace, model }`.\n const relatedModelName = rel?.to.model ?? relation;\n const child = new IdbStoreAccessorImpl(\n this.#contract,\n relatedModelName,\n this.#executor,\n emptyAccessorState(),\n this.#newGroupingKey,\n /* includeRefinementMode */ true\n );\n\n const refined = (refineFn as (c: unknown) => unknown)(child);\n\n if (isIncludeScalar(refined)) {\n if (rel !== undefined && rel.cardinality !== \"1:N\") {\n throw new Error(`include('${relation}'): count() is only supported for to-many (1:N) relations`);\n }\n return { kind: \"scalar\", fn: refined.fn, state: refined.state };\n }\n\n // Cross-instance private access is allowed within the class body.\n if (refined instanceof IdbStoreAccessorImpl) {\n return { kind: \"collection\", state: refined.#state };\n }\n\n throw new Error(\n `include('${relation}') refinement must return the collection (for where/orderBy/take/skip) or a count() selector`\n );\n }\n\n /**\n * Runs `scanPlan` as a native `count` plan when its cardinality is fully\n * determined by a key range (no in-memory filter) — returning the\n * *unpaginated* total — or `null` when it can't (the caller then falls back\n * to materializing). `ast` is attached so middleware sees the caller's\n * intent (`count` / `aggregate`) regardless of the physical plan.\n */\n async #executeNativeCount(scanPlan: IdbQueryPlan<Record<string, unknown>>, ast: IdbQueryAst): Promise<number | null> {\n const body = scanPlan.idbPlan;\n if (body.kind !== \"cursor-scan\" || !isNativelyCountable(body)) return null;\n const nativePlan: IdbQueryPlan<Record<string, unknown>> = { ...scanPlan, ast, idbPlan: toCountPlan(body) };\n let total = 0;\n for await (const row of this.#executor.query(nativePlan)) {\n total = (row as unknown as { count: number }).count;\n }\n return total;\n }\n\n /**\n * Materialise all rows matching the accumulated filters with no pagination —\n * used by `aggregate()` / `groupBy()`. The supplied `ast` is attached to the\n * scan plan so middleware can observe the aggregate intent.\n */\n async #materialize(groupingKey: string, ast: IdbQueryAst): Promise<Record<string, unknown>[]> {\n const combined = this.#combinedFilterExpr();\n const filter = combined !== undefined ? (row: Record<string, unknown>) => evaluateFilter(combined, row) : undefined;\n const meta = this.#planMeta(groupingKey);\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\",\n storeName: this.#storeName,\n ...(filter !== undefined ? { filter } : {}),\n },\n };\n const rows: Record<string, unknown>[] = [];\n for await (const row of this.#executor.query(plan)) {\n rows.push(row);\n }\n return rows;\n }\n\n #buildScanPlan<Row>(groupingKey: string, fieldToIndexMap?: Record<string, string>): IdbQueryPlan<Row> {\n const combined = this.#combinedFilterExpr();\n const comparator = buildRowComparator(this.#state.orderBy);\n const meta = this.#planMeta(groupingKey);\n const ast: IdbFindManyAst = {\n kind: \"findMany\",\n modelName: this.#modelName,\n ...(combined !== undefined ? { where: combined } : {}),\n ...(this.#state.orderBy !== undefined ? { orderBy: this.#state.orderBy as Record<string, \"asc\" | \"desc\"> } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n };\n\n // Attempt to peel an indexed equality condition from the combined filter\n // and use a cursor-scan over the index with a point range. This avoids\n // a full store scan when IDBKeyRange is available (browser / fake-indexeddb).\n if (typeof IDBKeyRange !== \"undefined\") {\n const fieldToIndexName = fieldToIndexMap ?? buildFieldToIndexMap(this.#contract, this.#storeName);\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const hint = extractIndexEqualityHint(combined, fieldToIndexName, keyPath);\n if (hint !== null) {\n const { indexName, value, remainingFilter } = hint;\n const filter =\n remainingFilter !== undefined\n ? (row: Record<string, unknown>) => evaluateFilter(remainingFilter, row)\n : undefined;\n return {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\" as const,\n storeName: this.#storeName,\n ...(indexName !== undefined ? { indexName } : {}),\n range: IDBKeyRange.only(value as IDBValidKey),\n ...(filter !== undefined ? { filter } : {}),\n ...(comparator !== undefined ? { comparator } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n },\n } as IdbQueryPlan<Row>;\n }\n }\n\n // Fallback: full cursor scan.\n const filter = combined !== undefined ? (row: Record<string, unknown>) => evaluateFilter(combined, row) : undefined;\n // exactOptionalPropertyTypes: spread conditionally to avoid `undefined`\n // values in optional fields.\n return {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\" as const,\n storeName: this.#storeName,\n ...(filter !== undefined ? { filter } : {}),\n ...(comparator !== undefined ? { comparator } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n },\n } as IdbQueryPlan<Row>;\n }\n\n /**\n * Execute one cursor-scan per OR branch, union the results, deduplicate by\n * primary key, and apply `hint.remainingFilter` in-memory. Skip/take are\n * NOT applied here — the caller slices the array after union so pagination\n * is correct across branches.\n */\n async #executeOrRows(\n hint: IndexOrHint,\n groupingKey: string,\n combined: IdbFilterExpr | undefined\n ): Promise<Record<string, unknown>[]> {\n const meta = this.#planMeta(groupingKey);\n const storeName = this.#storeName;\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const seen = new Set<unknown>();\n const rows: Record<string, unknown>[] = [];\n const ast: IdbFindManyAst = {\n kind: \"findMany\",\n modelName: this.#modelName,\n ...(combined !== undefined ? { where: combined } : {}),\n };\n\n // Branches are independent index scans — run them concurrently, then\n // merge/dedupe sequentially (first-branch-wins) so results stay\n // deterministic regardless of completion order.\n const branchResults = await Promise.all(\n hint.branches.map(async (branch) => {\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\" as const,\n storeName,\n ...(branch.indexName !== undefined ? { indexName: branch.indexName } : {}),\n range: IDBKeyRange.only(branch.value as IDBValidKey),\n },\n };\n const branchRows: Record<string, unknown>[] = [];\n for await (const row of this.#executor.query(plan)) {\n branchRows.push(row);\n }\n return branchRows;\n })\n );\n for (const branchRows of branchResults) {\n for (const row of branchRows) {\n const pk = keyToken(extractKeyFromRow(row, keyPath));\n if (!seen.has(pk)) {\n seen.add(pk);\n rows.push(row);\n }\n }\n }\n\n if (hint.remainingFilter === undefined) return rows;\n const { remainingFilter } = hint;\n return rows.filter((row) => evaluateFilter(remainingFilter, row));\n }\n\n /**\n * Combine all accumulated filter expressions with AND.\n *\n * Returns `undefined` when no filter has been installed so the driver can\n * skip building a row filter closure (a small perf and readability win on\n * `.all()` paths). Delegates to the shared {@link combineFilterExprs}.\n */\n #combinedFilterExpr(): IdbFilterExpr | undefined {\n return combineFilterExprs(this.#state.filters);\n }\n\n async #applyIncludes(rows: Record<string, unknown>[], groupingKey: string): Promise<Record<string, unknown>[]> {\n const relNames = Object.keys(this.#state.includes);\n if (relNames.length === 0) return rows;\n let result = rows;\n for (const relName of relNames) {\n const entry = this.#state.includes[relName]!;\n result = await loadRelation(relName, entry, result, this.#contract, this.#modelName, this.#executor, groupingKey);\n }\n return result;\n }\n\n /**\n * Apply a `.select()` projection (if any) to materialised rows. Keeps the\n * selected scalar fields plus every included relation key (which `include()`\n * attached during {@link #applyIncludes}); a no-op when nothing is selected.\n */\n #projectRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {\n const selected = this.#state.selectedFields;\n if (selected === undefined) return rows;\n const keep = [...selected, ...Object.keys(this.#state.includes)];\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const field of keep) {\n if (field in row) out[field] = row[field];\n }\n return out;\n });\n }\n\n #planMeta(groupingKey: string): PlanMeta {\n return {\n target: \"idb\",\n storageHash: this.#contract.storage.storageHash,\n lane: \"idb-orm\",\n annotations: { groupingKey },\n };\n }\n\n #clone(overrides: Partial<IdbAccessorState>): IdbStoreAccessorImpl<TContract, ModelName, TIncludes, TSelected> {\n return new IdbStoreAccessorImpl(\n this.#contract,\n this.#modelName,\n this.#executor,\n mergeAccessorState(this.#state, overrides),\n this.#newGroupingKey,\n this.#includeRefinementMode\n );\n }\n}\n","import type { Contract } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbContract, IdbStorage } from \"./types\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { type IdbStoreAccessor, IdbStoreAccessorImpl } from \"./store-accessor\";\n\n// ── Public types ──────────────────────────────────────────────────────────────\n\n/**\n * The ORM client object returned by {@link idbOrm}.\n *\n * Keys are the root keys from `contract.roots` (e.g. `\"users\"`, `\"posts\"`).\n * Each value is an {@link IdbStoreAccessor} targeting the corresponding model.\n *\n * @example\n * ```ts\n * const db = idbOrm({ contract, executor: runtime });\n * const users = await db.users.all(); // IdbStoreAccessor<..., \"User\">\n * ```\n */\nexport type IdbOrmClient<TContract extends Contract<IdbStorage>> = {\n // v0.12.0: `roots` values are CrossReference `{ namespace, model }`, so the\n // target model name is `roots[K].model` (was a bare model-name string).\n readonly [K in string & keyof TContract[\"roots\"]]: TContract[\"roots\"][K] extends {\n model: infer ModelName extends string;\n }\n ? IdbStoreAccessor<TContract, ModelName>\n : never;\n};\n\n/**\n * Options for {@link idbOrm}.\n */\nexport interface IdbOrmOptions<TContract extends IdbContract> {\n /** The resolved IDB contract (with or without attached type maps). */\n readonly contract: TContract;\n /**\n * The query executor.\n *\n * Any object with a compatible `query()` signature satisfies this —\n * most commonly an `IdbRuntime` created via `createIdbRuntime()`.\n */\n readonly executor: IdbQueryExecutor;\n}\n\n// ── Factory function ──────────────────────────────────────────────────────────\n\n/**\n * Create a typed IDB ORM client from a contract and executor.\n *\n * The client exposes one `IdbStoreAccessor` per entry in `contract.roots`.\n * Only roots-declared stores are accessible at the top level — other stores\n * can be reached via `.include()` on any accessor.\n *\n * @example\n * ```ts\n * import { idbOrm } from \"@prisma-idb/client-idb/orm\";\n * import { createIdbRuntime } from \"@prisma-idb/runtime-idb/runtime\";\n * import contract from \"./prisma/idb-contract\";\n *\n * const runtime = createIdbRuntime({ adapter, driver });\n * const db = idbOrm({ contract, executor: runtime });\n *\n * // Typed query builder:\n * const alice = await db.users.where({ email: \"alice@example.com\" }).first();\n * const postsWithAuthor = await db.posts.include(\"author\").all();\n * ```\n */\nexport function idbOrm<TContract extends IdbContract>(options: IdbOrmOptions<TContract>): IdbOrmClient<TContract> {\n const { contract, executor } = options;\n\n // One counter per idbOrm() call — two clients in the same realm get\n // independent key sequences and can't interleave (ADR 160).\n let _key = 0;\n const newGroupingKey = () => `idb-op-${++_key}`;\n\n const client: Record<string, IdbStoreAccessor<TContract, string>> = {};\n for (const [rootKey, ref] of Object.entries(contract.roots)) {\n // v0.12.0: `roots` values are CrossReference `{ namespace, model }`.\n client[rootKey] = new IdbStoreAccessorImpl(contract, ref.model, executor, undefined, newGroupingKey);\n }\n\n return client as unknown as IdbOrmClient<TContract>;\n}\n"],"mappings":";;;;;;;;;;;AA4lBA,SAAgB,aAAa,UAAuB,WAA2B;CAE7E,QADc,+BAA+B,SAAS,MAAM,CAAC,CAAC,UACjD,EAAE,QAAA,EAAyC,aAAa;AACvE;;;;;;;;;;;AAYA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