@prisma-idb/client-idb 0.11.0 → 0.12.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.
Files changed (26) hide show
  1. package/README.md +6 -0
  2. package/dist/client-auto.d.mts +2 -2
  3. package/dist/client-auto.mjs +1 -1
  4. package/dist/client.d.mts +1 -1
  5. package/dist/client.mjs +1 -1
  6. package/dist/{executor-Bp-hdRg2.d.mts → executor-CIEHpa1j.d.mts} +14 -7
  7. package/dist/{executor-Bp-hdRg2.d.mts.map → executor-CIEHpa1j.d.mts.map} +1 -1
  8. package/dist/{idb-orm-9XN3c9ly.d.mts → idb-orm-6OuwkeDM.d.mts} +2 -2
  9. package/dist/{idb-orm-9XN3c9ly.d.mts.map → idb-orm-6OuwkeDM.d.mts.map} +1 -1
  10. package/dist/{idb-orm-BitJ-EMq.mjs → idb-orm-B1Br1C0F.mjs} +18 -506
  11. package/dist/idb-orm-B1Br1C0F.mjs.map +1 -0
  12. package/dist/internal.d.mts +2 -2
  13. package/dist/internal.mjs +1 -1
  14. package/dist/{managed-client-CS78EjPu.d.mts → managed-client-DQlsxc4Z.d.mts} +3 -3
  15. package/dist/{managed-client-CS78EjPu.d.mts.map → managed-client-DQlsxc4Z.d.mts.map} +1 -1
  16. package/dist/{managed-client-CxlNmERd.mjs → managed-client-M3xMUk0n.mjs} +3 -3
  17. package/dist/{managed-client-CxlNmERd.mjs.map → managed-client-M3xMUk0n.mjs.map} +1 -1
  18. package/dist/{mutation-executor-SJqTuSbb.mjs → mutation-executor-inLFb0TE.mjs} +701 -146
  19. package/dist/mutation-executor-inLFb0TE.mjs.map +1 -0
  20. package/dist/{mutation-scope-1hS0ogGa.d.mts → mutation-scope-DrxFhek3.d.mts} +2 -2
  21. package/dist/{mutation-scope-1hS0ogGa.d.mts.map → mutation-scope-DrxFhek3.d.mts.map} +1 -1
  22. package/dist/orm.d.mts +3 -3
  23. package/dist/orm.mjs +2 -2
  24. package/package.json +6 -6
  25. package/dist/idb-orm-BitJ-EMq.mjs.map +0 -1
  26. package/dist/mutation-executor-SJqTuSbb.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idb-orm-B1Br1C0F.mjs","names":["#contract","#modelName","#executor","#storeName","#state","#newGroupingKey","#includeRefinementMode","#clone","#resolveIncludeEntry","#buildScanPlan","#applyIncludes","#projectRows","#combinedFilterExpr","#materialize","#planMeta","#lowerRows","#countTerminal"],"sources":["../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/aggregate-builder.ts","../src/core/grouped-accessor.ts","../src/core/relation-loader.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts"],"sourcesContent":["/**\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 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","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 { 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 an {@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}? */\nfunction 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 */\nfunction 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 { fieldValueToken } from \"./types\";\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. */\ninterface 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 a composite group key from type-tagged field tokens. Equal Date, binary,\n * array and JSON object values share a group; null and undefined also share a group.\n */\nfunction groupKeyOf(by: readonly string[], row: Record<string, unknown>): string {\n return JSON.stringify(by.map((field) => groupToken(row[field])));\n}\n\n/** Keep `1n`, `1` and `\"1\"` apart while preserving structural grouping for JSON objects. */\nfunction groupToken(value: unknown): readonly [string, unknown] {\n // Invalid Dates serialize as null, so give them a separate token.\n if (value instanceof Date && Number.isNaN(value.getTime())) return [\"date\", \"invalid\"];\n const token = fieldValueToken(value ?? null);\n return [typeof token, typeof token === \"object\" ? token : String(token)];\n}\n\n/** Build a grouped accessor that reduces materialized rows from the source accessor. */\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","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 { andExpr, fieldFilter } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { buildRowComparator, combineFilterExprs } from \"./query-shaping\";\nimport type { IncludeEntry } from \"./store-state\";\nimport { fieldValueToken, getStoreName } from \"./types\";\nimport type { IdbContract } from \"./types\";\nimport { buildCatalog } from \"./planner/catalog\";\nimport { planQuery } from \"./planner/plan\";\nimport { lowerRows } from \"./planner/lower\";\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 plans one batch lookup for all parents, then groups\n * the rows in memory, 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 = getStoreName(contract, 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 // Each field's IN is a superset of the local tuples. Keep the tuple check\n // to reject crossed compound keys, and shape collections per parent below.\n const joinWhere = andExpr(\n targetFields.map((field, i) =>\n fieldFilter(\n field,\n \"in\",\n [...localTuples.values()].map((tuple) => tuple[i])\n )\n )\n );\n const where = refinedWhere === undefined ? joinWhere : andExpr([joinWhere, refinedWhere]);\n const request = { ...(refinedWhere === undefined ? {} : { where: refinedWhere }) };\n const catalog = buildCatalog(contract, relatedStoreName);\n const lowered = lowerRows(catalog, planQuery(catalog, { where }), planMeta, request, (row) => {\n const token = tupleToken(row, targetFields);\n return token !== null && localTuples.has(token);\n });\n const plan: IdbQueryPlan<Record<string, unknown>> = { meta: planMeta, idbPlan: lowered.idbPlan };\n const relatedRows = lowered.finish(await executor.query(plan).toArray());\n\n return attachRelatedRows(relName, entry, rows, relatedRows, relation);\n}\n\n/** Attach related rows by their join tuple, shaping each parent's collection independently. */\nfunction attachRelatedRows(\n relName: string,\n entry: IncludeEntry,\n rows: Record<string, unknown>[],\n relatedRows: Record<string, unknown>[],\n relation: ContractReferenceRelation\n): Record<string, unknown>[] {\n const {\n cardinality,\n on: { localFields, targetFields },\n } = relation;\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 (entry.kind === \"scalar\") {\n // Counts include all filtered children, without collection pagination.\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","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 { 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 extractKeyFromRow,\n getKeyPath,\n getRelation,\n getStoreName,\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 { combineFilterExprs } 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 { assertEnumValues } from \"./enum-validation\";\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 readMutationRows,\n validateScalarFks,\n} from \"./mutation-executor\";\nimport { withMutationScope } from \"./mutation-scope\";\nimport { buildCatalog } from \"./planner/catalog\";\nimport { planQuery } from \"./planner/plan\";\nimport { lowerCount, lowerRows, type LoweredRows, type RowsRequest } from \"./planner/lower\";\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 lookup 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 planned row\n * read 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 executorQuery = this.#executor.query.bind(this.#executor);\n const applyIncludes = this.#applyIncludes.bind(this);\n const projectRows = this.#projectRows.bind(this);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<SelectedRow<TContract, ModelName, TIncludes, TSelected>, void, unknown> {\n const scan = buildScanPlan(groupingKey);\n const rows: Record<string, unknown>[] = [];\n for await (const row of executorQuery(scan.plan)) {\n rows.push(row);\n }\n\n // Batch-load any included relations (uses full rows — FK fields intact).\n const withIncludes = await applyIncludes(scan.finish(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 // Like SQL's aggregate, skip/take don't apply.\n const rows = await this.#materialize(this.#newGroupingKey(), 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 assertEnumValues(this.#contract, this.#modelName, withDefaults);\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 keyPath = getKeyPath(this.#contract, this.#modelName);\n const fields = typeof keyPath === \"string\" ? [keyPath] : keyPath;\n const values = typeof keyPath === \"string\" ? [key] : (key as readonly unknown[]);\n const where = combineFilterExprs(fields.map((field, i) => ({ kind: \"field\", field, op: \"eq\", value: values[i] })));\n const request: RowsRequest = { ...(where === undefined ? {} : { where }), take: 1 };\n const lowered = this.#lowerRows(meta, request);\n const rows = await this.#executor.query<Record<string, unknown>>({ meta, ast, idbPlan: lowered.idbPlan }).toArray();\n return (lowered.finish(rows)[0] as DefaultModelRow<TContract, ModelName> | undefined) ?? 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 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 assertEnumValues(this.#contract, this.#modelName, effectivePatch);\n assertEnumValues(this.#contract, this.#modelName, createWithDefaults);\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 readMutationRows(scope, this.#contract, this.#modelName, whereExpr, 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 const contract = this.#contract;\n const modelName = this.#modelName;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n // The foreign-key path above checks enums per row in `insertSingleRow`.\n for (const record of records) assertEnumValues(contract, modelName, record);\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 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 ...(combined === undefined ? {} : { where: combined }),\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 combined = this.#combinedFilterExpr();\n const { skip, take } = this.#state;\n // Ordering never changes how many rows match, so the request omits it.\n const request: RowsRequest = {\n ...(combined === undefined ? {} : { where: combined }),\n ...(skip === undefined ? {} : { skip }),\n ...(take === undefined ? {} : { take }),\n };\n const meta = this.#planMeta(this.#newGroupingKey());\n const catalog = buildCatalog(this.#contract, this.#storeName);\n const lowered = lowerCount(catalog, planQuery(catalog, request), meta, request);\n // Middleware sees a `count` AST, not the plan that answers it.\n const ast: IdbCountAst = {\n kind: \"count\",\n modelName: this.#modelName,\n ...(combined !== undefined ? { where: combined } : {}),\n };\n const rows = await this.#executor.query<Record<string, unknown>>({ meta, ast, idbPlan: lowered.idbPlan }).toArray();\n return lowered.finish(rows);\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 * Materialise all rows matching the accumulated filters with no pagination —\n * used by `aggregate()` / `groupBy()`. The supplied `ast` is attached to the\n * row 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 meta = this.#planMeta(groupingKey);\n const lowered = this.#lowerRows(meta, { ...(combined === undefined ? {} : { where: combined }) });\n const rows = await this.#executor.query<Record<string, unknown>>({ meta, ast, idbPlan: lowered.idbPlan }).toArray();\n return lowered.finish(rows);\n }\n\n #lowerRows(meta: PlanMeta, request: RowsRequest): LoweredRows {\n const catalog = buildCatalog(this.#contract, this.#storeName);\n return lowerRows(catalog, planQuery(catalog, request), meta, request);\n }\n\n #buildScanPlan(groupingKey: string): { plan: IdbQueryPlan<Record<string, unknown>>; finish: LoweredRows[\"finish\"] } {\n const combined = this.#combinedFilterExpr();\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 } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n };\n const lowered = this.#lowerRows(meta, ast);\n return { plan: { meta, ast, idbPlan: lowered.idbPlan }, finish: lowered.finish };\n }\n\n /**\n * Combine all accumulated filter expressions with AND.\n *\n * Returns `undefined` when no filter has been installed so the planner sees\n * an unfiltered request. 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":";;;;;;;;;;;;;;;;;;;;;AAgEA,SAAS,oBAAoB,OAA0C;CACrE,OAAO;EACL,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,KAAK,WAAW,YAAY,OAAO,MAAM,MAAM;EAC/C,QAAQ,WAAW,YAAY,OAAO,SAAS,MAAM;EACrD,WAAW,QAAQ,YAAY,OAAO,YAAY,GAAG;EACrD,aAAa,QAAQ,YAAY,OAAO,cAAc,GAAG;EACzD,WAAW,QAAQ,YAAY,OAAO,YAAY,GAAG;EACrD,cAAc,cAAc,OAAO,IAAI;EACvC,iBAAiB,cAAc,OAAO,KAAK;CAC7C;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,sBAGd;CACA,MAAM,wBAAQ,IAAI,IAAuC;CACzD,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAuB;EAClC,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;EACrC,IAAI,MAAM,MAAM,IAAI,IAAI;EACxB,IAAI,QAAQ,KAAA,GAAW;GACrB,MAAM,oBAAoB,IAAI;GAC9B,MAAM,IAAI,MAAM,GAAG;EACrB;EACA,OAAO;CACT,EACF,CACF;AACF;;;;AChFA,SAAgB,oBAAoB,OAA2C;CAC7E,OAAO;EAAE,MAAM;EAAiB,IAAI;EAAS;CAAM;AACrD;;AAGA,SAAgB,gBAAgB,OAA2C;CACzE,IAAI,OAAO,U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AAK,QAAQ;GACvB,MAAM,MAA+B,CAAC;GACtC,KAAK,MAAM,SAAS,MAClB,IAAI,SAAS,KAAK,IAAI,SAAS,IAAI;GAErC,OAAO;EACT,CAAC;CACH;CAEA,UAAU,aAA+B;EACvC,OAAO;GACL,QAAQ;GACR,aAAa,KAAKJ,UAAU,QAAQ;GACpC,MAAM;GACN,aAAa,EAAE,YAAY;EAC7B;CACF;CAEA,OAAO,WAAwG;EAC7G,OAAO,IAAI,qBACT,KAAKA,WACL,KAAKC,YACL,KAAKC,WACL,mBAAmB,KAAKE,QAAQ,SAAS,GACzC,KAAKC,iBACL,KAAKC,sBACP;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;ACh8BA,SAAgB,OAAsC,SAA4D;CAChH,MAAM,EAAE,UAAU,aAAa;CAI/B,IAAI,OAAO;CACX,MAAM,uBAAuB,UAAU,EAAE;CAEzC,MAAM,SAA8D,CAAC;CACrE,KAAK,MAAM,CAAC,SAAS,QAAQ,OAAO,QAAQ,SAAS,KAAK,GAExD,OAAO,WAAW,IAAI,qBAAqB,UAAU,IAAI,OAAO,UAAU,KAAA,GAAW,cAAc;CAGrG,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
- import { l as IdbContract } from "./executor-Bp-hdRg2.mjs";
2
- import "./mutation-scope-1hS0ogGa.mjs";
1
+ import { l as IdbContract } from "./executor-CIEHpa1j.mjs";
2
+ import "./mutation-scope-DrxFhek3.mjs";
3
3
  import { IdbFilterExpr } from "@prisma-idb/adapter-idb/runtime";
4
4
  import { IdbTransactionScope } from "@prisma-idb/driver-idb/runtime";
5
5
  //#region src/core/mutation-executor.d.ts
package/dist/internal.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { r as collectDeleteStoreNames, t as applyReferentialActionsForRow } from "./mutation-executor-SJqTuSbb.mjs";
1
+ import { r as collectDeleteStoreNames, t as applyReferentialActionsForRow } from "./mutation-executor-inLFb0TE.mjs";
2
2
  export { applyReferentialActionsForRow, collectDeleteStoreNames };
@@ -1,5 +1,5 @@
1
- import { l as IdbContract } from "./executor-Bp-hdRg2.mjs";
2
- import { t as IdbOrmClient } from "./idb-orm-9XN3c9ly.mjs";
1
+ import { l as IdbContract } from "./executor-CIEHpa1j.mjs";
2
+ import { t as IdbOrmClient } from "./idb-orm-6OuwkeDM.mjs";
3
3
  import { IdbTransactionScope } from "@prisma-idb/driver-idb/runtime";
4
4
  import { IdbMiddleware } from "@prisma-idb/runtime-idb/runtime";
5
5
  //#region src/core/idb-client.d.ts
@@ -113,4 +113,4 @@ declare function createManagedIdbClient<TClient extends {
113
113
  }>(open: () => Promise<TClient>, options: ManagedIdbClientOptions): ManagedIdbClient<TClient>;
114
114
  //#endregion
115
115
  export { IdbClientOptions as a, IdbClient as i, ManagedIdbClientOptions as n, createIdbClient as o, createManagedIdbClient as r, ManagedIdbClient as t };
116
- //# sourceMappingURL=managed-client-CS78EjPu.d.mts.map
116
+ //# sourceMappingURL=managed-client-DQlsxc4Z.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"managed-client-CS78EjPu.d.mts","names":[],"sources":["../src/core/idb-client.ts","../src/core/managed-client.ts"],"mappings":";;;;;UAWiB,iBAAiB,kBAAkB;WACzC,UAAU;WACV;;WAGA,UAAU;WACV,sBAAsB;;UAGhB,UAAU,kBAAkB;WAClC,KAAK,aAAa;;;;;;;;;;;EAW3B,gBAAgB,GAAG,sBAAsB,KAAK,OAAO,wBAAwB,QAAQ,KAAK,QAAQ;EAClG,gBAAgB;EAChB,SAAS;GACR,OAAO,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;iBAwBX,gBAAgB,kBAAkB,aAChD,SAAS,iBAAiB,aACzB,UAAU;;;;;;;;;;;;;;;;;UC9CI;;WAEN;;WAEA,aAAa;;UAGP,iBAAiB;;EAEhC,OAAO,QAAQ;;EAEf,SAAS;;;;;;;;;;;;EAYT,SAAS;;;;;;;;;;;;;;;;;;;;;iBAsBK,uBAAuB;EAAkB,SAAS;GAChE,YAAY,QAAQ,UACpB,SAAS,0BACR,iBAAiB"}
1
+ {"version":3,"file":"managed-client-DQlsxc4Z.d.mts","names":[],"sources":["../src/core/idb-client.ts","../src/core/managed-client.ts"],"mappings":";;;;;UAWiB,iBAAiB,kBAAkB;WACzC,UAAU;WACV;;WAGA,UAAU;WACV,sBAAsB;;UAGhB,UAAU,kBAAkB;WAClC,KAAK,aAAa;;;;;;;;;;;EAW3B,gBAAgB,GAAG,sBAAsB,KAAK,OAAO,wBAAwB,QAAQ,KAAK,QAAQ;EAClG,gBAAgB;EAChB,SAAS;GACR,OAAO,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;iBAwBX,gBAAgB,kBAAkB,aAChD,SAAS,iBAAiB,aACzB,UAAU;;;;;;;;;;;;;;;;;UC9CI;;WAEN;;WAEA,aAAa;;UAGP,iBAAiB;;EAEhC,OAAO,QAAQ;;EAEf,SAAS;;;;;;;;;;;;EAYT,SAAS;;;;;;;;;;;;;;;;;;;;;iBAsBK,uBAAuB;EAAkB,SAAS;GAChE,YAAY,QAAQ,UACpB,SAAS,0BACR,iBAAiB"}
@@ -1,5 +1,5 @@
1
- import { y as withMutationScope } from "./mutation-executor-SJqTuSbb.mjs";
2
- import { t as idbOrm } from "./idb-orm-BitJ-EMq.mjs";
1
+ import { b as withMutationScope } from "./mutation-executor-inLFb0TE.mjs";
2
+ import { t as idbOrm } from "./idb-orm-B1Br1C0F.mjs";
3
3
  import { IdbAdapter } from "@prisma-idb/adapter-idb/runtime";
4
4
  import { idbCodecLookup } from "@prisma-idb/target-idb/runtime";
5
5
  import { createIDBRuntimeDriver } from "@prisma-idb/driver-idb/runtime";
@@ -120,4 +120,4 @@ function createManagedIdbClient(open, options) {
120
120
  //#endregion
121
121
  export { createIdbClient as n, createManagedIdbClient as t };
122
122
 
123
- //# sourceMappingURL=managed-client-CxlNmERd.mjs.map
123
+ //# sourceMappingURL=managed-client-M3xMUk0n.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"managed-client-CxlNmERd.mjs","names":[],"sources":["../src/core/idb-client.ts","../src/core/managed-client.ts"],"sourcesContent":["import { IdbAdapter } from \"@prisma-idb/adapter-idb/runtime\";\nimport { createIDBRuntimeDriver } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbMiddleware } from \"@prisma-idb/runtime-idb/runtime\";\nimport { createIdbRuntime } from \"@prisma-idb/runtime-idb/runtime\";\nimport { idbCodecLookup } from \"@prisma-idb/target-idb/runtime\";\nimport { withMutationScope } from \"./mutation-scope\";\nimport { idbOrm } from \"./idb-orm\";\nimport type { IdbOrmClient } from \"./idb-orm\";\nimport type { IdbContract } from \"./types\";\n\nexport interface IdbClientOptions<TContract extends IdbContract> {\n readonly contract: TContract;\n readonly dbName: string;\n // No version — the migration runner owns the IDB version integer (ADR 001).\n /** IDB factory override — primarily for tests and custom browser realms. */\n readonly factory?: IDBFactory;\n readonly middleware?: readonly IdbMiddleware[];\n}\n\nexport interface IdbClient<TContract extends IdbContract> {\n readonly orm: IdbOrmClient<TContract>;\n /**\n * Run `fn` inside a single multi-store readwrite IDB transaction.\n *\n * Opens the transaction, passes an `IdbTransactionScope` to `fn`, then\n * commits on success or rolls back on error. Equivalent to calling\n * `withMutationScope(runtime, storeNames, fn)`.\n *\n * Useful from test harnesses and from any caller that has an `IdbClient`\n * but not the raw runtime reference.\n */\n withTransaction<T>(storeNames: string[], fn: (scope: IdbTransactionScope) => Promise<T>): Promise<T>;\n verifyMarker(): Promise<boolean>;\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/**\n * Creates a typed IDB client from a contract and a database name.\n *\n * Assembles the full runtime stack (driver → adapter → runtime → ORM) internally.\n * Equivalent to `postgres({ contract, url })` in `@prisma/orm-postgres/runtime`.\n *\n * The IDB database version is not exposed — it is managed by the migration runner\n * per ADR 001. The driver opens at the current database version, which is correct\n * for a runtime that only reads/writes (no DDL).\n *\n * @example\n * ```ts\n * import { createIdbClient } from '@prisma-idb/client-idb/client';\n * import contract from './contract';\n *\n * export const db = createIdbClient({ contract, dbName: 'my-app' });\n *\n * // Later:\n * const users = await db.orm.users.all().toArray();\n * ```\n */\nexport function createIdbClient<TContract extends IdbContract>(\n options: IdbClientOptions<TContract>\n): IdbClient<TContract> {\n const driver = createIDBRuntimeDriver(\n options.dbName,\n undefined,\n options.factory !== undefined ? { factory: options.factory } : undefined\n ).create();\n const adapter = new IdbAdapter(idbCodecLookup);\n const runtime = createIdbRuntime({\n adapter,\n driver,\n contract: options.contract as Record<string, unknown>,\n ...(options.middleware !== undefined && options.middleware.length > 0 ? { middleware: options.middleware } : {}),\n });\n const orm = idbOrm({ contract: options.contract, executor: runtime });\n\n return {\n orm,\n withTransaction: <T>(storeNames: string[], fn: (scope: IdbTransactionScope) => Promise<T>) =>\n withMutationScope(runtime, storeNames, fn),\n verifyMarker: () => runtime.verifyMarker(),\n async close() {\n await runtime.close();\n },\n [Symbol.asyncDispose]() {\n return this.close();\n },\n };\n}\n","/**\n * `createManagedIdbClient` — a singleton, race-safe wrapper around any IDB\n * client factory (`createIdbClient`, `createAutoMigratingIdbClient`, or a\n * sync-extension factory like `createAutoMigratingSyncIdbClient` — anything\n * returning a `close(): Promise<void>`-shaped client).\n *\n * Every consumer of this package that wants a module-level singleton client\n * plus a \"wipe local data\" reset (e.g. on logout) needs the same race-safety:\n * `reset()` must never call `indexedDB.deleteDatabase` while a `get()` open\n * is still in flight, since a still-opening connection would block (or worse,\n * leave a stale handle once that open resolves after the delete). This was\n * previously hand-rolled per app with diverging correctness; see ADR-less\n * discussion in the kanban example's `db.ts` history.\n */\n\nexport interface ManagedIdbClientOptions {\n /** IDB database name — passed to `indexedDB.deleteDatabase` on `reset()`. */\n readonly dbName: string;\n /** IDB factory override — primarily for tests. Defaults to `indexedDB`. */\n readonly idbFactory?: IDBFactory;\n}\n\nexport interface ManagedIdbClient<TClient> {\n /** Opens the client on first call and caches it; concurrent calls share one open. */\n get(): Promise<TClient>;\n /** Closes the cached client, if any. Safe to call when nothing is open. */\n close(): Promise<void>;\n /**\n * Closes and deletes the database — waits out any `get()` open already in\n * flight first. `onblocked` (another tab still has the DB open) is NOT\n * terminal — per spec, the delete request stays pending, and still fires\n * `onsuccess` once every blocking connection closes — so this promise\n * stays pending through it too, settling only once `deleteDatabase`\n * actually reaches `onsuccess` or `onerror`. Neither resolving early\n * (claims success before the old data is actually gone) nor rejecting\n * early (reports failure on a delete that may still succeed) would be\n * accurate.\n */\n reset(): Promise<void>;\n}\n\n/**\n * Wraps `open` (a client factory, e.g. `() => createAutoMigratingIdbClient({...})`)\n * with a module-scoped singleton: `get()` opens once and caches the result,\n * `close()` releases it, `reset()` closes and wipes the underlying database.\n *\n * @example\n * ```ts\n * import { createManagedIdbClient } from '@prisma-idb/client-idb/client';\n *\n * const db = createManagedIdbClient(\n * () => createAutoMigratingIdbClient({ contractSpace, dbName: 'my-app' }),\n * { dbName: 'my-app' }\n * );\n *\n * const client = await db.get();\n * // ... on logout:\n * await db.reset();\n * ```\n */\nexport function createManagedIdbClient<TClient extends { close(): Promise<void> }>(\n open: () => Promise<TClient>,\n options: ManagedIdbClientOptions\n): ManagedIdbClient<TClient> {\n const { dbName, idbFactory = indexedDB } = options;\n\n let client: TClient | null = null;\n let clientPromise: Promise<TClient> | null = null;\n // Gate between get() and reset() — set synchronously (no `await` before\n // either reads/writes it) so the two never interleave: see module doc comment.\n let resetPromise: Promise<void> | null = null;\n\n async function get(): Promise<TClient> {\n if (resetPromise) await resetPromise;\n if (client) return client;\n clientPromise ??= open().catch((err: unknown) => {\n // Clear on rejection so a later get() call retries instead of\n // re-awaiting the same rejected promise forever.\n clientPromise = null;\n throw err;\n });\n\n const fresh = await clientPromise;\n client = fresh;\n return fresh;\n }\n\n async function close(): Promise<void> {\n if (!client) return;\n await client.close();\n client = null;\n clientPromise = null;\n }\n\n async function reset(): Promise<void> {\n if (resetPromise) return resetPromise;\n resetPromise = (async () => {\n if (clientPromise) await clientPromise.catch(() => {});\n await close();\n await new Promise<void>((resolve, reject) => {\n const req = idbFactory.deleteDatabase(dbName);\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error as Error);\n // Deliberately no-op: `onblocked` only means the request is waiting\n // on another open connection, not that it failed — `onsuccess` (or\n // `onerror`) still fires later once that connection closes. Settling\n // here either way would misreport the outcome; see the `reset()`\n // doc comment above.\n req.onblocked = () => {};\n });\n })();\n try {\n await resetPromise;\n } finally {\n resetPromise = null;\n }\n }\n\n return { get, close, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,gBACd,SACsB;CACtB,MAAM,SAAS,uBACb,QAAQ,QACR,KAAA,GACA,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,KAAA,CACjE,CAAC,CAAC,OAAO;CACT,MAAM,UAAU,IAAI,WAAW,cAAc;CAC7C,MAAM,UAAU,iBAAiB;EAC/B;EACA;EACA,UAAU,QAAQ;EAClB,GAAI,QAAQ,eAAe,KAAA,KAAa,QAAQ,WAAW,SAAS,IAAI,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;CAChH,CAAC;CAGD,OAAO;EACL,KAHU,OAAO;GAAE,UAAU,QAAQ;GAAU,UAAU;EAAQ,CAG/D;EACF,kBAAqB,YAAsB,OACzC,kBAAkB,SAAS,YAAY,EAAE;EAC3C,oBAAoB,QAAQ,aAAa;EACzC,MAAM,QAAQ;GACZ,MAAM,QAAQ,MAAM;EACtB;EACA,CAAC,OAAO,gBAAgB;GACtB,OAAO,KAAK,MAAM;EACpB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;AC5BA,SAAgB,uBACd,MACA,SAC2B;CAC3B,MAAM,EAAE,QAAQ,aAAa,cAAc;CAE3C,IAAI,SAAyB;CAC7B,IAAI,gBAAyC;CAG7C,IAAI,eAAqC;CAEzC,eAAe,MAAwB;EACrC,IAAI,cAAc,MAAM;EACxB,IAAI,QAAQ,OAAO;EACnB,kBAAkB,KAAK,CAAC,CAAC,OAAO,QAAiB;GAG/C,gBAAgB;GAChB,MAAM;EACR,CAAC;EAED,MAAM,QAAQ,MAAM;EACpB,SAAS;EACT,OAAO;CACT;CAEA,eAAe,QAAuB;EACpC,IAAI,CAAC,QAAQ;EACb,MAAM,OAAO,MAAM;EACnB,SAAS;EACT,gBAAgB;CAClB;CAEA,eAAe,QAAuB;EACpC,IAAI,cAAc,OAAO;EACzB,gBAAgB,YAAY;GAC1B,IAAI,eAAe,MAAM,cAAc,YAAY,CAAC,CAAC;GACrD,MAAM,MAAM;GACZ,MAAM,IAAI,SAAe,SAAS,WAAW;IAC3C,MAAM,MAAM,WAAW,eAAe,MAAM;IAC5C,IAAI,kBAAkB,QAAQ;IAC9B,IAAI,gBAAgB,OAAO,IAAI,KAAc;IAM7C,IAAI,kBAAkB,CAAC;GACzB,CAAC;EACH,EAAA,CAAG;EACH,IAAI;GACF,MAAM;EACR,UAAU;GACR,eAAe;EACjB;CACF;CAEA,OAAO;EAAE;EAAK;EAAO;CAAM;AAC7B"}
1
+ {"version":3,"file":"managed-client-M3xMUk0n.mjs","names":[],"sources":["../src/core/idb-client.ts","../src/core/managed-client.ts"],"sourcesContent":["import { IdbAdapter } from \"@prisma-idb/adapter-idb/runtime\";\nimport { createIDBRuntimeDriver } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbMiddleware } from \"@prisma-idb/runtime-idb/runtime\";\nimport { createIdbRuntime } from \"@prisma-idb/runtime-idb/runtime\";\nimport { idbCodecLookup } from \"@prisma-idb/target-idb/runtime\";\nimport { withMutationScope } from \"./mutation-scope\";\nimport { idbOrm } from \"./idb-orm\";\nimport type { IdbOrmClient } from \"./idb-orm\";\nimport type { IdbContract } from \"./types\";\n\nexport interface IdbClientOptions<TContract extends IdbContract> {\n readonly contract: TContract;\n readonly dbName: string;\n // No version — the migration runner owns the IDB version integer (ADR 001).\n /** IDB factory override — primarily for tests and custom browser realms. */\n readonly factory?: IDBFactory;\n readonly middleware?: readonly IdbMiddleware[];\n}\n\nexport interface IdbClient<TContract extends IdbContract> {\n readonly orm: IdbOrmClient<TContract>;\n /**\n * Run `fn` inside a single multi-store readwrite IDB transaction.\n *\n * Opens the transaction, passes an `IdbTransactionScope` to `fn`, then\n * commits on success or rolls back on error. Equivalent to calling\n * `withMutationScope(runtime, storeNames, fn)`.\n *\n * Useful from test harnesses and from any caller that has an `IdbClient`\n * but not the raw runtime reference.\n */\n withTransaction<T>(storeNames: string[], fn: (scope: IdbTransactionScope) => Promise<T>): Promise<T>;\n verifyMarker(): Promise<boolean>;\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/**\n * Creates a typed IDB client from a contract and a database name.\n *\n * Assembles the full runtime stack (driver → adapter → runtime → ORM) internally.\n * Equivalent to `postgres({ contract, url })` in `@prisma/orm-postgres/runtime`.\n *\n * The IDB database version is not exposed — it is managed by the migration runner\n * per ADR 001. The driver opens at the current database version, which is correct\n * for a runtime that only reads/writes (no DDL).\n *\n * @example\n * ```ts\n * import { createIdbClient } from '@prisma-idb/client-idb/client';\n * import contract from './contract';\n *\n * export const db = createIdbClient({ contract, dbName: 'my-app' });\n *\n * // Later:\n * const users = await db.orm.users.all().toArray();\n * ```\n */\nexport function createIdbClient<TContract extends IdbContract>(\n options: IdbClientOptions<TContract>\n): IdbClient<TContract> {\n const driver = createIDBRuntimeDriver(\n options.dbName,\n undefined,\n options.factory !== undefined ? { factory: options.factory } : undefined\n ).create();\n const adapter = new IdbAdapter(idbCodecLookup);\n const runtime = createIdbRuntime({\n adapter,\n driver,\n contract: options.contract as Record<string, unknown>,\n ...(options.middleware !== undefined && options.middleware.length > 0 ? { middleware: options.middleware } : {}),\n });\n const orm = idbOrm({ contract: options.contract, executor: runtime });\n\n return {\n orm,\n withTransaction: <T>(storeNames: string[], fn: (scope: IdbTransactionScope) => Promise<T>) =>\n withMutationScope(runtime, storeNames, fn),\n verifyMarker: () => runtime.verifyMarker(),\n async close() {\n await runtime.close();\n },\n [Symbol.asyncDispose]() {\n return this.close();\n },\n };\n}\n","/**\n * `createManagedIdbClient` — a singleton, race-safe wrapper around any IDB\n * client factory (`createIdbClient`, `createAutoMigratingIdbClient`, or a\n * sync-extension factory like `createAutoMigratingSyncIdbClient` — anything\n * returning a `close(): Promise<void>`-shaped client).\n *\n * Every consumer of this package that wants a module-level singleton client\n * plus a \"wipe local data\" reset (e.g. on logout) needs the same race-safety:\n * `reset()` must never call `indexedDB.deleteDatabase` while a `get()` open\n * is still in flight, since a still-opening connection would block (or worse,\n * leave a stale handle once that open resolves after the delete). This was\n * previously hand-rolled per app with diverging correctness; see ADR-less\n * discussion in the kanban example's `db.ts` history.\n */\n\nexport interface ManagedIdbClientOptions {\n /** IDB database name — passed to `indexedDB.deleteDatabase` on `reset()`. */\n readonly dbName: string;\n /** IDB factory override — primarily for tests. Defaults to `indexedDB`. */\n readonly idbFactory?: IDBFactory;\n}\n\nexport interface ManagedIdbClient<TClient> {\n /** Opens the client on first call and caches it; concurrent calls share one open. */\n get(): Promise<TClient>;\n /** Closes the cached client, if any. Safe to call when nothing is open. */\n close(): Promise<void>;\n /**\n * Closes and deletes the database — waits out any `get()` open already in\n * flight first. `onblocked` (another tab still has the DB open) is NOT\n * terminal — per spec, the delete request stays pending, and still fires\n * `onsuccess` once every blocking connection closes — so this promise\n * stays pending through it too, settling only once `deleteDatabase`\n * actually reaches `onsuccess` or `onerror`. Neither resolving early\n * (claims success before the old data is actually gone) nor rejecting\n * early (reports failure on a delete that may still succeed) would be\n * accurate.\n */\n reset(): Promise<void>;\n}\n\n/**\n * Wraps `open` (a client factory, e.g. `() => createAutoMigratingIdbClient({...})`)\n * with a module-scoped singleton: `get()` opens once and caches the result,\n * `close()` releases it, `reset()` closes and wipes the underlying database.\n *\n * @example\n * ```ts\n * import { createManagedIdbClient } from '@prisma-idb/client-idb/client';\n *\n * const db = createManagedIdbClient(\n * () => createAutoMigratingIdbClient({ contractSpace, dbName: 'my-app' }),\n * { dbName: 'my-app' }\n * );\n *\n * const client = await db.get();\n * // ... on logout:\n * await db.reset();\n * ```\n */\nexport function createManagedIdbClient<TClient extends { close(): Promise<void> }>(\n open: () => Promise<TClient>,\n options: ManagedIdbClientOptions\n): ManagedIdbClient<TClient> {\n const { dbName, idbFactory = indexedDB } = options;\n\n let client: TClient | null = null;\n let clientPromise: Promise<TClient> | null = null;\n // Gate between get() and reset() — set synchronously (no `await` before\n // either reads/writes it) so the two never interleave: see module doc comment.\n let resetPromise: Promise<void> | null = null;\n\n async function get(): Promise<TClient> {\n if (resetPromise) await resetPromise;\n if (client) return client;\n clientPromise ??= open().catch((err: unknown) => {\n // Clear on rejection so a later get() call retries instead of\n // re-awaiting the same rejected promise forever.\n clientPromise = null;\n throw err;\n });\n\n const fresh = await clientPromise;\n client = fresh;\n return fresh;\n }\n\n async function close(): Promise<void> {\n if (!client) return;\n await client.close();\n client = null;\n clientPromise = null;\n }\n\n async function reset(): Promise<void> {\n if (resetPromise) return resetPromise;\n resetPromise = (async () => {\n if (clientPromise) await clientPromise.catch(() => {});\n await close();\n await new Promise<void>((resolve, reject) => {\n const req = idbFactory.deleteDatabase(dbName);\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error as Error);\n // Deliberately no-op: `onblocked` only means the request is waiting\n // on another open connection, not that it failed — `onsuccess` (or\n // `onerror`) still fires later once that connection closes. Settling\n // here either way would misreport the outcome; see the `reset()`\n // doc comment above.\n req.onblocked = () => {};\n });\n })();\n try {\n await resetPromise;\n } finally {\n resetPromise = null;\n }\n }\n\n return { get, close, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,gBACd,SACsB;CACtB,MAAM,SAAS,uBACb,QAAQ,QACR,KAAA,GACA,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,KAAA,CACjE,CAAC,CAAC,OAAO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