@prisma-idb/client-idb 0.12.0 → 0.13.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 (35) hide show
  1. package/dist/client-auto.d.mts +2 -2
  2. package/dist/client-auto.d.mts.map +1 -1
  3. package/dist/client-auto.mjs +44 -3
  4. package/dist/client-auto.mjs.map +1 -1
  5. package/dist/client.d.mts +3 -2
  6. package/dist/client.mjs +3 -2
  7. package/dist/decimal-identity-D_1J9lPN.d.mts +21 -0
  8. package/dist/decimal-identity-D_1J9lPN.d.mts.map +1 -0
  9. package/dist/internal.d.mts +5 -4
  10. package/dist/internal.d.mts.map +1 -1
  11. package/dist/internal.mjs +2 -2
  12. package/dist/{managed-client-M3xMUk0n.mjs → managed-client-DMk8ERfX.mjs} +12 -5
  13. package/dist/managed-client-DMk8ERfX.mjs.map +1 -0
  14. package/dist/{managed-client-DQlsxc4Z.d.mts → managed-client-eksFK4UF.d.mts} +32 -3
  15. package/dist/managed-client-eksFK4UF.d.mts.map +1 -0
  16. package/dist/{mutation-executor-inLFb0TE.mjs → mutation-executor-IuJmyWEG.mjs} +486 -105
  17. package/dist/mutation-executor-IuJmyWEG.mjs.map +1 -0
  18. package/dist/{executor-CIEHpa1j.d.mts → mutation-scope-CE3GMR4X.d.mts} +66 -22
  19. package/dist/mutation-scope-CE3GMR4X.d.mts.map +1 -0
  20. package/dist/{idb-orm-B1Br1C0F.mjs → orm-transaction-BGx1eukw.mjs} +357 -61
  21. package/dist/orm-transaction-BGx1eukw.mjs.map +1 -0
  22. package/dist/{idb-orm-6OuwkeDM.d.mts → orm-transaction-B_ZJ92uY.d.mts} +40 -7
  23. package/dist/orm-transaction-B_ZJ92uY.d.mts.map +1 -0
  24. package/dist/orm.d.mts +13 -4
  25. package/dist/orm.d.mts.map +1 -1
  26. package/dist/orm.mjs +3 -3
  27. package/package.json +9 -9
  28. package/dist/executor-CIEHpa1j.d.mts.map +0 -1
  29. package/dist/idb-orm-6OuwkeDM.d.mts.map +0 -1
  30. package/dist/idb-orm-B1Br1C0F.mjs.map +0 -1
  31. package/dist/managed-client-DQlsxc4Z.d.mts.map +0 -1
  32. package/dist/managed-client-M3xMUk0n.mjs.map +0 -1
  33. package/dist/mutation-executor-inLFb0TE.mjs.map +0 -1
  34. package/dist/mutation-scope-DrxFhek3.d.mts +0 -33
  35. package/dist/mutation-scope-DrxFhek3.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orm-transaction-BGx1eukw.mjs","names":["#contract","#modelName","#executor","#storeName","#state","#newGroupingKey","#includeRefinementMode","#clone","#resolveIncludeEntry","#buildScanPlan","#applyIncludes","#projectRows","#combinedFilterExpr","#materialize","#planMeta","#countTerminal","#lowerRows","#scope","#storeNames","#meta","#ended","#autoCommitCause","#state","#assertNotEnded","#assertStoresListed","#recordFailure","#observeThen","#recordThrown"],"sources":["../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/aggregate-builder.ts","../src/core/grouped-accessor.ts","../src/core/unique-lookup.ts","../src/core/relation-loader.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts","../src/core/open-transaction.ts","../src/core/orm-transaction.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 /** Reuse the field accessor within one filter callback so repeated reads share its operator surface. */\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`: count the related rows. The `state.filters` still constrain\n * 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 { CatalogField } from \"./planner/catalog\";\nimport 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). Values must match the declared number codec.\n */\nfunction reduceAggregate(\n fn: AggregateFn,\n field: string | undefined,\n rows: readonly Record<string, unknown>[],\n codecId: string | undefined\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 if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n throw new TypeError(`${fn}(\"${field}\") requires finite number values`);\n }\n if (codecId === \"idb/int32@1\" && (!Number.isInteger(raw) || raw < -2147483648 || raw > 2147483647)) {\n throw new TypeError(`${fn}(\"${field}\") requires Int values in the signed 32-bit range`);\n }\n values.push(raw);\n }\n\n if (values.length === 0) return null;\n\n switch (fn) {\n case \"sum\":\n return sumValues(values, field, codecId === \"idb/int32@1\");\n case \"avg\":\n return sumValues(values, field, codecId === \"idb/int32@1\") / values.length;\n // Not `Math.min(...values)`: spreading a large array overflows the call stack.\n case \"min\":\n return values.reduce((acc, n) => Math.min(acc, n));\n case \"max\":\n return values.reduce((acc, n) => Math.max(acc, n));\n }\n}\n\n/** Reject overflow before a rounded or nonfinite intermediate total can reach the result. */\nfunction sumValues(values: readonly number[], field: string, integer: boolean): number {\n let total = 0;\n for (const value of values) {\n total += value;\n if (!Number.isFinite(total) || (integer && !Number.isSafeInteger(total))) {\n throw new RangeError(\n `Aggregate total for \"${field}\" exceeds the ${integer ? \"safe integer\" : \"finite number\"} range`\n );\n }\n }\n return total;\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 fields: Readonly<Record<string, CatalogField>> = {}\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, fields[selector.field ?? \"\"]?.codecId);\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 over a declared scalar number field (except\n * count, which has no field). 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 fields: Readonly<Record<string, CatalogField>>\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 if (selector.fn === \"count\") continue;\n const field = typeof selector.field === \"string\" ? fields[selector.field] : undefined;\n if (!field || field.collection || (field.codecId !== \"idb/int32@1\" && field.codecId !== \"idb/double@1\")) {\n throw new TypeError(`${context} selector \"${alias}\" requires a declared number field (Int or Float)`);\n }\n }\n}\n","import type { IdbFilterExpr, IdbGroupByAst, IdbQueryAst } from \"@prisma-idb/adapter-idb/runtime\";\nimport {\n assertValidAggregateSpec,\n computeAggregateSpec,\n createAggregateBuilder,\n toAggregateRequests,\n} from \"./aggregate-builder\";\nimport type { CatalogField } from \"./planner/catalog\";\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 /** Declared scalar types used to validate selectors and numeric reductions. */\n readonly fields: Readonly<Record<string, CatalogField>>;\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 /** Materialize matching rows, partition them by group key, and reduce each group. */\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()\", init.fields);\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, init.fields) }) as GroupedResultRow<\n TContract,\n ModelName,\n Fields,\n Spec\n >\n );\n },\n };\n}\n","import { isValidIdbKey } from \"@prisma-idb/target-idb/runtime\";\nimport type { QueryCatalog } from \"./planner/catalog\";\n\n/**\n * Copy the own enumerable properties of an upsert `where` once. Validation and\n * filter parsing then see the same values even when a property is a getter.\n * Non-object inputs pass through so `assertUniqueLookup` can reject them.\n */\nexport function snapshotLookup<Where>(where: Where): Where {\n const isRecord = typeof where === \"object\" && where !== null && !Array.isArray(where);\n return isRecord ? (Object.fromEntries(Object.entries(where)) as Where) : where;\n}\n\n/**\n * Require equality on a complete native unique key before upsert can mutate.\n * Null and other non-key values are absent from IndexedDB indexes, so even a\n * declared unique index cannot make those filters identify at most one row.\n */\nexport function assertUniqueLookup(catalog: QueryCatalog, where: Record<string, unknown>): void {\n const sources = [catalog.primaryKey, ...catalog.indexes];\n const validFilter = typeof where === \"object\" && where !== null && !Array.isArray(where);\n const unique =\n validFilter &&\n sources.some(\n (source) =>\n source.unique &&\n !source.multiEntry &&\n source.fields.length > 0 &&\n source.fields.every(\n (field) => Object.prototype.propertyIsEnumerable.call(where, field) && isValidIdbKey(where[field])\n )\n );\n if (!unique) {\n throw new Error(\n `Invalid upsert where for \"${catalog.storeName}\": provide a complete primary key or unique index with non-null IndexedDB key values`\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, type QueryCatalog } 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, relatedModelName);\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, catalog.fields);\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 fields: QueryCatalog[\"fields\"]\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, fields);\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 { absentAsNull, isValidIdbKey } from \"@prisma-idb/target-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 { assertValidRecord } from \"./record-validation\";\nimport { assertUniqueLookup, snapshotLookup } from \"./unique-lookup\";\nimport { applyUpdateDefaults, completeCreateRecord, 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 { resolveDecimalKey } from \"./decimal-identity\";\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 * `where` must contain a complete primary key or declared unique index,\n * with non-null IndexedDB key values for every member. A multi-entry index\n * cannot serve as the lookup. Additional equality predicates are allowed. Invalid lookups reject before any mutation.\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 /** Add a callback or shorthand predicate to a new accessor without mutating this one. */\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 /** Add a collection or count refinement while preserving this accessor state. */\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 /** Narrow scalar output fields while retaining included relations. */\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 /** Read matching rows, load includes, and project fields before yielding. */\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 /** Reduce all filtered rows; query pagination does not constrain aggregates. */\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 const { fields } = buildCatalog(this.#contract, this.#storeName, this.#modelName);\n assertValidAggregateSpec(spec, \"aggregate()\", fields);\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, fields) as IdbAggregateResult<Spec>;\n }\n\n /** Carry this filter into a grouped accessor whose materialization is owned here. */\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 fields: buildCatalog(this.#contract, this.#storeName, this.#modelName).fields,\n where: combined,\n materialize,\n });\n }\n\n /** Complete and validate one record, using a transaction when relations need checks. */\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 = completeCreateRecord(this.#contract, this.#modelName, record, createMutationDefaultsCache());\n assertEnumValues(this.#contract, this.#modelName, withDefaults);\n assertValidRecord(this.#contract, this.#modelName, \"create\", 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 // Read the result to its end so `activityEnded` reports `succeeded`.\n // Returning early would still call the hook, but with outcome `stopped`.\n const [row] = await this.#executor.query(plan).toArray();\n return (row ?? withDefaults) as DefaultModelRow<TContract, ModelName>;\n }\n\n /** Resolve a primary key numerically for Decimal fields while retaining its stored spelling. */\n async findUnique(key: KeyType<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null> {\n if (!isValidIdbKey(key)) return null;\n const meta = this.#planMeta(this.#newGroupingKey());\n const ast: IdbFindUniqueAst = { kind: \"findUnique\", modelName: this.#modelName, key };\n const row = await resolveDecimalKey(\n {\n execute: (body) =>\n this.#executor.query<Record<string, unknown>>({ meta, ast, idbPlan: { ...body, meta } }).toArray(),\n },\n this.#contract,\n this.#modelName,\n key\n );\n return row === undefined\n ? null\n : (absentAsNull(this.#contract, this.#modelName)(row) as DefaultModelRow<TContract, ModelName>);\n }\n\n /** Delete a keyed row with child actions when its relations require them. */\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 /** Update the first matching row with scalar or nested relation validation. */\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 /** Select and apply the create or update arm inside one transaction. */\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 where = snapshotLookup(args.where as Record<string, unknown>);\n assertUniqueLookup(buildCatalog(this.#contract, this.#storeName, this.#modelName), where);\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const whereExpr = shorthandToFilterExpr(where);\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 = completeCreateRecord(\n this.#contract,\n this.#modelName,\n createRecord,\n createMutationDefaultsCache()\n );\n assertEnumValues(this.#contract, this.#modelName, effectivePatch);\n assertEnumValues(this.#contract, this.#modelName, createWithDefaults);\n assertValidRecord(this.#contract, this.#modelName, \"update\", effectivePatch);\n assertValidRecord(this.#contract, this.#modelName, \"create\", 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 const updated = absentAsNull(this.#contract, this.#modelName)(rows[0] ?? existing);\n return updated as DefaultModelRow<TContract, ModelName>;\n });\n }\n\n /** Complete a batch with shared query defaults and insert it atomically. */\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 records = data.map((d) =>\n completeCreateRecord(this.#contract, this.#modelName, 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) {\n assertEnumValues(contract, modelName, record);\n assertValidRecord(contract, modelName, \"create\", record);\n }\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 /** Return an include-count descriptor during refinement, or execute a top-level count. */\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 /** Count this filtered page through the planner, without applying select or include. */\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, this.#modelName);\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 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, this.#modelName);\n return lowerRows(catalog, planQuery(catalog, request), meta, request);\n }\n\n /** Pair the query intent with its planned driver operation and result shaping. */\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 /** Batch-load each requested relation using the unprojected parent rows. */\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 /** Attach the contract hash and grouping key shared by this operation. */\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 /** Preserve shared runtime wiring while replacing only the accessor state. */\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 { withDecimalIdentityExecutor } from \"./decimal-identity\";\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 // Roots carry CrossReference values; each accessor targets the referenced model.\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, contract });\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 } = options;\n const executor = withDecimalIdentityExecutor(contract, options.executor);\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 client[rootKey] = new IdbStoreAccessorImpl(contract, ref.model, executor, undefined, newGroupingKey);\n }\n\n return client as unknown as IdbOrmClient<TContract>;\n}\n","/**\n * An executor bound to one already-open IDB transaction.\n *\n * `db.transaction()` hands its callback ORM accessors built on this executor.\n * Every query the accessors issue runs on the open transaction instead of\n * opening a new one. Operations that normally open their own mutation scope\n * (FK-checked writes, cascade deletes) get a view of the same transaction:\n * `commit()` on the view does nothing, so an inner operation cannot commit the\n * outer transaction, and `rollback()` aborts it.\n *\n * The executor also records how the transaction ended, so the runner can tell\n * a rolled-back transaction from one that IndexedDB auto-committed early\n * (ADR 005).\n */\nimport { AsyncIterableResult } from \"@prisma/orm-framework/components/runtime\";\nimport type { PlanMeta } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbQueryPlan } from \"@prisma-idb/adapter-idb/runtime\";\nimport { IdbExecuteError } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbAtomicPlan, IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbQueryExecutorWithTransaction } from \"./mutation-scope\";\nimport { executeMutationPlan } from \"./mutation-executor\";\n\n/** A record returned by an IDB operation. */\ntype Row = Record<string, unknown>;\n\n/** `open` until an operation fails (`aborted`) or finds the transaction already finished (`auto-committed`). */\ntype State = \"open\" | \"aborted\" | \"auto-committed\";\n\nfunction isTransactionInactive(error: unknown): boolean {\n return error instanceof IdbExecuteError && error.code === \"TRANSACTION_INACTIVE\";\n}\n\n/** Bind ORM operations to one scope and record aborts or early commits. */\nexport class OpenTransaction implements IdbQueryExecutorWithTransaction, IdbTransactionScope {\n readonly #scope: IdbTransactionScope;\n readonly #storeNames: ReadonlySet<string>;\n readonly #meta: PlanMeta;\n #state: State = \"open\";\n #autoCommitCause: unknown;\n #ended = false;\n\n constructor(scope: IdbTransactionScope, storeNames: readonly string[], meta: PlanMeta) {\n this.#scope = scope;\n this.#storeNames = new Set(storeNames);\n this.#meta = meta;\n }\n\n /** Stop accepting operations. Called once the callback has settled. */\n end(): void {\n this.#ended = true;\n }\n\n /** The error of the first operation that found the transaction already finished, if any. */\n get autoCommitCause(): unknown {\n return this.#autoCommitCause;\n }\n\n /**\n * Whether IndexedDB has already finished this transaction on its own, so a\n * rollback can no longer undo its writes. Probes the transaction when no\n * operation has failed yet, and records the probe error as the cause, so call\n * it before rolling back or committing.\n */\n async hasAutoCommitted(): Promise<boolean> {\n if (this.#state !== \"open\") return this.#state === \"auto-committed\";\n const [storeName] = this.#storeNames;\n try {\n await this.#scope.execute({ meta: this.#meta, kind: \"key-get\", storeName: storeName!, key: \"\" });\n return false;\n } catch (error) {\n if (!isTransactionInactive(error)) return false;\n this.#state = \"auto-committed\";\n this.#autoCommitCause = error;\n return true;\n }\n }\n\n /** Expose rows from the existing scope through the ORM query-result interface. */\n query<R>(plan: IdbQueryPlan<R>): AsyncIterableResult<R> {\n const run = executeMutationPlan.bind(null, this);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<R, void, unknown> {\n for (const row of await run(plan.idbPlan)) yield row as R;\n })()\n );\n }\n\n /** Reuse the outer scope after verifying that the requested stores were declared. */\n async transaction(storeNames: string[]): Promise<IdbTransactionScope> {\n this.#assertNotEnded();\n try {\n this.#assertStoresListed(storeNames);\n } catch (error) {\n this.#recordFailure(error);\n throw error;\n }\n return this;\n }\n\n /** Run one operation in the scope and abort the transaction when it fails. */\n async execute(plan: IdbAtomicPlan): Promise<Row[]> {\n this.#assertNotEnded();\n try {\n this.#assertStoresListed([plan.storeName]);\n return await this.#scope.execute(plan);\n } catch (error) {\n this.#recordFailure(error);\n throw error;\n }\n }\n\n async commit(): Promise<void> {\n // Only the runner commits, once the callback resolves.\n }\n\n rollback(): void {\n this.#recordFailure(undefined);\n }\n\n /**\n * Wrap an ORM accessor so that any call that fails aborts the transaction.\n *\n * Some failures, such as enum validation, happen before an operation reaches\n * this executor. Without this wrapper the callback could catch them and\n * commit the writes made before. The wrapper covers errors thrown\n * synchronously, rejected promises, and rejections of a result that is\n * awaited directly (`AsyncIterableResult`). Objects the accessor returns,\n * such as `where()` builders, are wrapped too.\n */\n abortOnFailure<T extends object>(target: T): T {\n return new Proxy(target, {\n get: (object, property) => {\n const value: unknown = Reflect.get(object, property, object);\n if (typeof value !== \"function\") return value;\n if (property === \"then\") return this.#observeThen(object, value as (...args: unknown[]) => unknown);\n return (...args: unknown[]): unknown => {\n const result: unknown = this.#recordThrown(() => value.apply(object, args));\n if (result instanceof Promise) {\n result.catch((error: unknown) => this.#recordFailure(error));\n return result;\n }\n return typeof result === \"object\" && result !== null ? this.abortOnFailure(result) : result;\n };\n },\n });\n }\n\n /**\n * `await result` passes its own rejection handler to `then()`, which turns the\n * rejection into a fulfilled promise. Record the failure before that handler runs.\n */\n #observeThen(object: object, then: (...args: unknown[]) => unknown): unknown {\n return (onFulfilled: unknown, onRejected: unknown): unknown =>\n then.call(object, onFulfilled, (error: unknown) => {\n this.#recordFailure(error);\n if (typeof onRejected !== \"function\") throw error;\n return onRejected(error);\n });\n }\n\n /** Record synchronous accessor failures before propagating them to the callback. */\n #recordThrown<R>(call: () => R): R {\n try {\n return call();\n } catch (error) {\n this.#recordFailure(error);\n throw error;\n }\n }\n\n #assertNotEnded(): void {\n if (this.#ended) {\n throw new Error(\"This transaction has ended. Do not use `tx` after the db.transaction() callback finishes.\");\n }\n }\n\n /** Reject undeclared stores before an operation can escape the transaction scope. */\n #assertStoresListed(storeNames: readonly string[]): void {\n const missing = storeNames.filter((name) => !this.#storeNames.has(name));\n if (missing.length > 0) {\n throw new Error(\n `Stores ${missing.map((name) => `\"${name}\"`).join(\", \")} are not part of this transaction. ` +\n \"List the models that own them in the first argument of db.transaction().\"\n );\n }\n }\n\n /** Any failed operation aborts the whole transaction, even if the callback catches the error. */\n #recordFailure(error: unknown): void {\n if (this.#state !== \"open\") return;\n if (isTransactionInactive(error)) {\n this.#state = \"auto-committed\";\n this.#autoCommitCause = error;\n return;\n }\n this.#state = \"aborted\";\n this.#scope.rollback();\n }\n}\n","/**\n * Typed ORM transactions: `db.transaction([\"users\", \"posts\"], async (tx) => ...)`.\n *\n * The callback gets ORM accessors for the listed models only. All of them run\n * in one IDB readwrite transaction that commits when the callback resolves and\n * rolls back when it throws. See ADR 007.\n */\nimport type { IdbContract } from \"./types\";\nimport { idbOrm } from \"./idb-orm\";\nimport type { IdbOrmClient } from \"./idb-orm\";\nimport {\n collectDeleteStoreNames,\n collectOnUpdateClosureStoreNames,\n collectRelatedStoreNames,\n makePlanMeta,\n} from \"./mutation-executor\";\nimport { OpenTransaction } from \"./open-transaction\";\nimport type { IdbQueryExecutorWithTransaction } from \"./mutation-scope\";\nimport type { IdbTransactionScope } from \"@prisma-idb/driver-idb/runtime\";\n\n/** The ORM accessors available inside `db.transaction()`: only the listed root keys. */\nexport type IdbOrmTransaction<TContract extends IdbContract, TRootKey extends string & keyof TContract[\"roots\"]> = Pick<\n IdbOrmClient<TContract>,\n TRootKey\n>;\n\n/**\n * Thrown when IndexedDB finished the transaction before the callback did, so\n * writes made before that point were committed and could not be rolled back.\n *\n * IndexedDB commits a transaction as soon as it has no pending request. That\n * happens when the callback awaits something other than a `tx` operation, such\n * as a timer or a network call (ADR 005). `cause` holds the original error.\n */\nexport class IdbTransactionCommittedEarlyError extends Error {\n constructor(cause: unknown) {\n super(\n \"The transaction was committed before the db.transaction() callback finished, \" +\n \"so writes made earlier in the callback were saved and not rolled back. \" +\n \"Await only `tx` operations inside the callback; do not await timers or network calls.\",\n { cause }\n );\n this.name = \"IdbTransactionCommittedEarlyError\";\n }\n}\n\n/**\n * Run `fn` inside one readwrite transaction over the models behind `rootKeys`.\n *\n * Besides the listed models, the transaction opens the stores their operations\n * need: parents for foreign-key checks, children for referential actions, and\n * related models for `include`. An operation that needs any other store fails\n * with an error that names it.\n */\nexport async function runOrmTransaction<\n TContract extends IdbContract,\n TRootKey extends string & keyof TContract[\"roots\"],\n T,\n>(\n options: { readonly contract: TContract; readonly executor: IdbQueryExecutorWithTransaction },\n rootKeys: readonly TRootKey[],\n fn: (tx: IdbOrmTransaction<TContract, TRootKey>) => PromiseLike<T>\n): Promise<T> {\n const { contract, executor } = options;\n if (rootKeys.length === 0) {\n throw new Error(\"db.transaction() needs at least one model to open the transaction on.\");\n }\n const modelNames = rootKeys.map((key) => {\n const root = contract.roots[key];\n if (root === undefined) throw new Error(`db.transaction(): \"${key}\" is not a root of the contract.`);\n return root.model;\n });\n\n const storeNames = [...new Set(modelNames.flatMap((model) => storeNamesNeededBy(contract, model)))];\n const scope = await executor.transaction(storeNames, \"readwrite\");\n const open = new OpenTransaction(scope, storeNames, makePlanMeta(contract));\n\n let result: T;\n try {\n result = await fn(pickRoots(idbOrm({ contract, executor: open }), rootKeys, open));\n } catch (error) {\n open.end();\n if (await open.hasAutoCommitted()) await failCommittedEarly(scope, error);\n scope.rollback();\n throw error;\n }\n open.end();\n if (await open.hasAutoCommitted()) await failCommittedEarly(scope, open.autoCommitCause);\n await scope.commit();\n return result;\n}\n\n/**\n * Reports a transaction that IndexedDB committed before the callback ended. The writes\n * persisted, so the scope is committed rather than rolled back: a tracked scope only\n * announces its writes (for example, sync outbox notifications) when it commits.\n */\nasync function failCommittedEarly(scope: IdbTransactionScope, cause: unknown): Promise<never> {\n await scope.commit().catch(() => {});\n throw new IdbTransactionCommittedEarlyError(cause);\n}\n\n/** Collect stores used by relation reads, child actions, and cascading updates. */\nfunction storeNamesNeededBy(contract: IdbContract, modelName: string): string[] {\n return [\n ...collectRelatedStoreNames(contract, modelName),\n ...collectDeleteStoreNames(contract, modelName),\n ...collectOnUpdateClosureStoreNames(contract, modelName),\n ];\n}\n\n/** Expose only the requested roots and abort the scope on any accessor failure. */\nfunction pickRoots<TContract extends IdbContract, TRootKey extends string & keyof TContract[\"roots\"]>(\n orm: IdbOrmClient<TContract>,\n rootKeys: readonly TRootKey[],\n open: OpenTransaction\n): IdbOrmTransaction<TContract, TRootKey> {\n const picked = {} as IdbOrmTransaction<TContract, TRootKey>;\n for (const key of rootKeys) picked[key] = open.abortOnFailure(orm[key]);\n return picked;\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,iBAAi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AQ,MAAM,SAAS,YAAY,YAAY,WAAW;CAChE,MAAM,OAAO,IAAI,gBAAgB,OAAO,YAAY,aAAa,QAAQ,CAAC;CAE1E,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,GAAG,UAAU,OAAO;GAAE;GAAU,UAAU;EAAK,CAAC,GAAG,UAAU,IAAI,CAAC;CACnF,SAAS,OAAO;EACd,KAAK,IAAI;EACT,IAAI,MAAM,KAAK,iBAAiB,GAAG,MAAM,mBAAmB,OAAO,KAAK;EACxE,MAAM,SAAS;EACf,MAAM;CACR;CACA,KAAK,IAAI;CACT,IAAI,MAAM,KAAK,iBAAiB,GAAG,MAAM,mBAAmB,OAAO,KAAK,eAAe;CACvF,MAAM,MAAM,OAAO;CACnB,OAAO;AACT;;;;;;AAOA,eAAe,mBAAmB,OAA4B,OAAgC;CAC5F,MAAM,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACnC,MAAM,IAAI,kCAAkC,KAAK;AACnD;;AAGA,SAAS,mBAAmB,UAAuB,WAA6B;CAC9E,OAAO;EACL,GAAG,yBAAyB,UAAU,SAAS;EAC/C,GAAG,wBAAwB,UAAU,SAAS;EAC9C,GAAG,iCAAiC,UAAU,SAAS;CACzD;AACF;;AAGA,SAAS,UACP,KACA,UACA,MACwC;CACxC,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,OAAO,UAAU,OAAO,OAAO,KAAK,eAAe,IAAI,IAAI;CACtE,OAAO;AACT"}
@@ -1,7 +1,9 @@
1
- import { C as NoIncludes, D as ReferenceRelKeys, E as PatchInput, M as SelectedRow, O as RelatedModelOf, P as WhereFilter, S as MutationUpdateInput, T as OrderBySpec, a as IdbAggregateBuilder, c as IdbAggregateSpec, g as IncludeSpec, i as DefaultModelRow, l as IdbContract, o as IdbAggregateResult, p as IdbStorage, r as CreateInput, t as IdbQueryExecutor, v as KeyType, x as MutationCreateInput } from "./executor-CIEHpa1j.mjs";
1
+ import { A as RelatedModelOf, C as MutationCreateInput, D as OrderBySpec, I as WhereFilter, O as PatchInput, P as SelectedRow, T as NoIncludes, a as CreateInput, b as KeyType, c as IdbAggregateResult, d as IdbContract, h as IdbStorage, k as ReferenceRelKeys, o as DefaultModelRow, r as IdbQueryExecutor, s as IdbAggregateBuilder, t as IdbQueryExecutorWithTransaction, u as IdbAggregateSpec, v as IncludeSpec, w as MutationUpdateInput } from "./mutation-scope-CE3GMR4X.mjs";
2
2
  import { AsyncIterableResult } from "@prisma/orm-framework/components/runtime";
3
- import { IdbFieldFilter, IdbFilterExpr, IdbNullCheckExpr } from "@prisma-idb/adapter-idb/runtime";
4
3
  import { Contract } from "@prisma/orm-framework/contract/types";
4
+ import "@prisma-idb/target-idb/runtime";
5
+ import { IdbFieldFilter, IdbFilterExpr, IdbNullCheckExpr } from "@prisma-idb/adapter-idb/runtime";
6
+ import "@prisma-idb/target-idb/pack";
5
7
  //#region src/core/model-accessor.d.ts
6
8
  /**
7
9
  * Operator surface available on every field. All return frozen AST nodes
@@ -41,8 +43,8 @@ type IdbModelAccessor<TContract, ModelName extends string> = { readonly [K in ke
41
43
  * - `collection`: load the related rows, applying the refined `state`
42
44
  * (its `filters` / `orderBy` / `skip` / `take`) to the child scan.
43
45
  * `state` is `emptyAccessorState()` for an unrefined `.include(rel)`.
44
- * - `scalar`: reduce the related rows to a single number (Phase 6.5 supports
45
- * `count`). The `state.filters` still constrain which children are counted.
46
+ * - `scalar`: count the related rows. The `state.filters` still constrain
47
+ * which children are counted.
46
48
  *
47
49
  * Mirrors the `IncludeExpr` / `IncludeScalar` split from
48
50
  * Prisma ORM's SQL client, collapsed to the two shapes IDB
@@ -300,6 +302,10 @@ interface IdbStoreAccessor<TContract, ModelName extends string, TIncludes extend
300
302
  /**
301
303
  * Insert or update a single record.
302
304
  *
305
+ * `where` must contain a complete primary key or declared unique index,
306
+ * with non-null IndexedDB key values for every member. A multi-entry index
307
+ * cannot serve as the lookup. Additional equality predicates are allowed. Invalid lookups reject before any mutation.
308
+ *
303
309
  * - If a row matching `where` exists: shallow-merge `update` onto it and
304
310
  * return the merged row.
305
311
  * - If no matching row exists: insert `create` and return it.
@@ -385,7 +391,7 @@ interface IdbOrmOptions<TContract extends IdbContract> {
385
391
  * import { createIdbRuntime } from "@prisma-idb/runtime-idb/runtime";
386
392
  * import contract from "./prisma/idb-contract";
387
393
  *
388
- * const runtime = createIdbRuntime({ adapter, driver });
394
+ * const runtime = createIdbRuntime({ adapter, driver, contract });
389
395
  * const db = idbOrm({ contract, executor: runtime });
390
396
  *
391
397
  * // Typed query builder:
@@ -395,5 +401,32 @@ interface IdbOrmOptions<TContract extends IdbContract> {
395
401
  */
396
402
  declare function idbOrm<TContract extends IdbContract>(options: IdbOrmOptions<TContract>): IdbOrmClient<TContract>;
397
403
  //#endregion
398
- export { IdbStoreAccessor as a, IdbGroupedAccessor as c, IdbModelAccessor as d, IdbIncludeRefinementAccessor as i, IdbIncludeScalar as l, IdbOrmOptions as n, WhereCallback as o, idbOrm as r, GroupedResultRow as s, IdbOrmClient as t, IdbFieldAccessor as u };
399
- //# sourceMappingURL=idb-orm-6OuwkeDM.d.mts.map
404
+ //#region src/core/orm-transaction.d.ts
405
+ /** The ORM accessors available inside `db.transaction()`: only the listed root keys. */
406
+ type IdbOrmTransaction<TContract extends IdbContract, TRootKey extends string & keyof TContract["roots"]> = Pick<IdbOrmClient<TContract>, TRootKey>;
407
+ /**
408
+ * Thrown when IndexedDB finished the transaction before the callback did, so
409
+ * writes made before that point were committed and could not be rolled back.
410
+ *
411
+ * IndexedDB commits a transaction as soon as it has no pending request. That
412
+ * happens when the callback awaits something other than a `tx` operation, such
413
+ * as a timer or a network call (ADR 005). `cause` holds the original error.
414
+ */
415
+ declare class IdbTransactionCommittedEarlyError extends Error {
416
+ constructor(cause: unknown);
417
+ }
418
+ /**
419
+ * Run `fn` inside one readwrite transaction over the models behind `rootKeys`.
420
+ *
421
+ * Besides the listed models, the transaction opens the stores their operations
422
+ * need: parents for foreign-key checks, children for referential actions, and
423
+ * related models for `include`. An operation that needs any other store fails
424
+ * with an error that names it.
425
+ */
426
+ declare function runOrmTransaction<TContract extends IdbContract, TRootKey extends string & keyof TContract["roots"], T>(options: {
427
+ readonly contract: TContract;
428
+ readonly executor: IdbQueryExecutorWithTransaction;
429
+ }, rootKeys: readonly TRootKey[], fn: (tx: IdbOrmTransaction<TContract, TRootKey>) => PromiseLike<T>): Promise<T>;
430
+ //#endregion
431
+ export { IdbOrmOptions as a, IdbStoreAccessor as c, IdbGroupedAccessor as d, IdbIncludeScalar as f, IdbOrmClient as i, WhereCallback as l, IdbModelAccessor as m, IdbTransactionCommittedEarlyError as n, idbOrm as o, IdbFieldAccessor as p, runOrmTransaction as r, IdbIncludeRefinementAccessor as s, IdbOrmTransaction as t, GroupedResultRow as u };
432
+ //# sourceMappingURL=orm-transaction-B_ZJ92uY.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orm-transaction-B_ZJ92uY.d.mts","names":[],"sources":["../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/grouped-accessor.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts","../src/core/orm-transaction.ts"],"mappings":";;;;;;;;;;;;UA2BiB,iBAAiB;EAChC,GAAG,OAAO,IAAI;EACd,IAAI,OAAO,IAAI;EACf,GAAG,OAAO,IAAI;EACd,GAAG,OAAO,IAAI;EACd,IAAI,OAAO,IAAI;EACf,IAAI,OAAO,IAAI;EACf,GAAG,QAAQ,cAAc,KAAK;EAC9B,MAAM,QAAQ,cAAc,KAAK;EACjC,SAAS,cAAc;EACvB,WAAW,cAAc;EACzB,SAAS,cAAc;EACvB,UAAU;EACV,aAAa;;;;;;;;;;KAWH,iBAAiB,WAAW,wCAC5B,WAAW,gBAAgB,WAAW,eAAe,iBAC7D,gBAAgB,WAAW,WAAW;;;;;;;;;;;;;;;;;KCrC9B;WACG;WAA6B,OAAO;;WACpC;WAAyB;WAAsB,OAAO;;;;;;;;;;UAUpD;WACN;WACA;WACA,OAAO;;;;;;;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WAAW;;;;;EAM5D,eAAe;;;;;;;;;;;EAYf,SAAS;;;;;;;;;;;;;;;;KC9UC,aAAa,kBAAkB,SAAS,2BAExC,oBAAoB,qBAAqB,mBAAmB;EACpE,aAAa;IAEX,iBAAiB,WAAW;;;;UAOjB,cAAc,kBAAkB;;WAEtC,UAAU;;;;;;;WAOV,UAAU;;;;;;;;;;;;;;;;;;;;;;;iBA0BL,OAAO,kBAAkB,aAAa,SAAS,cAAc,aAAa,aAAa;;;;KC9C3F,kBAAkB,kBAAkB,aAAa,gCAAgC,sBAAsB,KACjH,aAAa,YACb;;;;;;;;;cAWW,0CAA0C;EACzC,YAAA;;;;;;;;;;iBAmBQ,kBACpB,kBAAkB,aAClB,gCAAgC,oBAChC,GAEA;WAAoB,UAAU;WAAoB,UAAU;GAC5D,mBAAmB,YACnB,KAAK,IAAI,kBAAkB,WAAW,cAAc,YAAY,KAC/D,QAAQ"}
package/dist/orm.d.mts CHANGED
@@ -1,7 +1,16 @@
1
- import { A as RelationMutationCreate, C as NoIncludes, D as ReferenceRelKeys, E as PatchInput, F as extractKeyFromRow, I as getKeyPath, L as getStoreName, M as SelectedRow, N as SortDirection, O as RelatedModelOf, P as WhereFilter, R as keyEquals, S as MutationUpdateInput, T as OrderBySpec, _ as IncludedRow, a as IdbAggregateBuilder, b as ModelKeyPathOrdered, c as IdbAggregateSpec, d as IdbRelationMutation, f as IdbRelationMutator, g as IncludeSpec, h as IncludeMarker, i as DefaultModelRow, j as RelationMutationDisconnect, k as RelationMutationConnect, l as IdbContract, m as IncludeFields, n as AggregateFn, o as IdbAggregateResult, r as CreateInput, s as IdbAggregateSelector, t as IdbQueryExecutor, u as IdbKeyPath, v as KeyType, w as NumericFieldNames, x as MutationCreateInput, y as ModelKeyPath, z as keyToken } from "./executor-CIEHpa1j.mjs";
2
- import { a as IdbStoreAccessor, c as IdbGroupedAccessor, d as IdbModelAccessor, i as IdbIncludeRefinementAccessor, l as IdbIncludeScalar, n as IdbOrmOptions, o as WhereCallback, r as idbOrm, s as GroupedResultRow, t as IdbOrmClient, u as IdbFieldAccessor } from "./idb-orm-6OuwkeDM.mjs";
3
- import { n as withMutationScope, t as IdbQueryExecutorWithTransaction } from "./mutation-scope-DrxFhek3.mjs";
1
+ import { A as RelatedModelOf, B as keyEquals, C as MutationCreateInput, D as OrderBySpec, E as NumericFieldNames, F as SortDirection, I as WhereFilter, L as extractKeyFromRow, M as RelationMutationCreate, N as RelationMutationDisconnect, O as PatchInput, P as SelectedRow, R as getKeyPath, S as ModelKeyPathOrdered, T as NoIncludes, V as keyToken, _ as IncludeMarker, a as CreateInput, b as KeyType, c as IdbAggregateResult, d as IdbContract, f as IdbKeyPath, g as IncludeFields, i as AggregateFn, j as RelationMutationConnect, k as ReferenceRelKeys, l as IdbAggregateSelector, m as IdbRelationMutator, n as withMutationScope, o as DefaultModelRow, p as IdbRelationMutation, r as IdbQueryExecutor, s as IdbAggregateBuilder, t as IdbQueryExecutorWithTransaction, u as IdbAggregateSpec, v as IncludeSpec, w as MutationUpdateInput, x as ModelKeyPath, y as IncludedRow, z as getStoreName } from "./mutation-scope-CE3GMR4X.mjs";
2
+ import { a as IdbOrmOptions, c as IdbStoreAccessor, d as IdbGroupedAccessor, f as IdbIncludeScalar, i as IdbOrmClient, l as WhereCallback, m as IdbModelAccessor, n as IdbTransactionCommittedEarlyError, o as idbOrm, p as IdbFieldAccessor, r as runOrmTransaction, s as IdbIncludeRefinementAccessor, t as IdbOrmTransaction, u as GroupedResultRow } from "./orm-transaction-B_ZJ92uY.mjs";
3
+ import { t as IdbDecimalIdentityConflictError } from "./decimal-identity-D_1J9lPN.mjs";
4
4
  import { IdbAndExpr, IdbAndExpr as IdbAndExpr$1, IdbFieldFilter, IdbFilterExpr, IdbFilterExpr as IdbFilterExpr$1, IdbFilterOp, IdbNotExpr, IdbNotExpr as IdbNotExpr$1, IdbNullCheckExpr, IdbOrExpr, IdbOrExpr as IdbOrExpr$1 } from "@prisma-idb/adapter-idb/runtime";
5
+ //#region src/core/record-validation.d.ts
6
+ /** A local ORM create or update failed the contract's native record validation. */
7
+ declare class IdbRecordValidationError extends Error {
8
+ readonly modelName: string;
9
+ readonly operation: "create" | "update";
10
+ readonly issues: readonly string[];
11
+ constructor(modelName: string, operation: "create" | "update", issues: readonly string[]);
12
+ }
13
+ //#endregion
5
14
  //#region src/core/filters.d.ts
6
15
  /** Variadic AND. `and()` (no args) is vacuously true. */
7
16
  declare function and(...exprs: ReadonlyArray<IdbFilterExpr$1>): IdbAndExpr$1;
@@ -10,5 +19,5 @@ declare function or(...exprs: ReadonlyArray<IdbFilterExpr$1>): IdbOrExpr$1;
10
19
  /** Logical NOT. */
11
20
  declare function not(expr: IdbFilterExpr$1): IdbNotExpr$1;
12
21
  //#endregion
13
- export { type AggregateFn, type CreateInput, type DefaultModelRow, type GroupedResultRow, type IdbAggregateBuilder, type IdbAggregateResult, type IdbAggregateSelector, type IdbAggregateSpec, type IdbAndExpr, type IdbContract, type IdbFieldAccessor, type IdbFieldFilter, type IdbFilterExpr, type IdbFilterOp, type IdbGroupedAccessor, type IdbIncludeRefinementAccessor, type IdbIncludeScalar, type IdbKeyPath, type IdbModelAccessor, type IdbNotExpr, type IdbNullCheckExpr, type IdbOrExpr, type IdbOrmClient, type IdbOrmOptions, type IdbQueryExecutor, type IdbQueryExecutorWithTransaction, type IdbRelationMutation, type IdbRelationMutator, type IdbStoreAccessor, type IncludeFields, type IncludeMarker, type IncludeSpec, type IncludedRow, type KeyType, type ModelKeyPath, type ModelKeyPathOrdered, type MutationCreateInput, type MutationUpdateInput, type NoIncludes, type NumericFieldNames, type OrderBySpec, type PatchInput, type ReferenceRelKeys, type RelatedModelOf, type RelationMutationConnect, type RelationMutationCreate, type RelationMutationDisconnect, type SelectedRow, type SortDirection, type WhereCallback, type WhereFilter, and, extractKeyFromRow, getKeyPath, getStoreName, idbOrm, keyEquals, keyToken, not, or, withMutationScope };
22
+ export { type AggregateFn, type CreateInput, type DefaultModelRow, type GroupedResultRow, type IdbAggregateBuilder, type IdbAggregateResult, type IdbAggregateSelector, type IdbAggregateSpec, type IdbAndExpr, type IdbContract, IdbDecimalIdentityConflictError, type IdbFieldAccessor, type IdbFieldFilter, type IdbFilterExpr, type IdbFilterOp, type IdbGroupedAccessor, type IdbIncludeRefinementAccessor, type IdbIncludeScalar, type IdbKeyPath, type IdbModelAccessor, type IdbNotExpr, type IdbNullCheckExpr, type IdbOrExpr, type IdbOrmClient, type IdbOrmOptions, type IdbOrmTransaction, type IdbQueryExecutor, type IdbQueryExecutorWithTransaction, IdbRecordValidationError, type IdbRelationMutation, type IdbRelationMutator, type IdbStoreAccessor, IdbTransactionCommittedEarlyError, type IncludeFields, type IncludeMarker, type IncludeSpec, type IncludedRow, type KeyType, type ModelKeyPath, type ModelKeyPathOrdered, type MutationCreateInput, type MutationUpdateInput, type NoIncludes, type NumericFieldNames, type OrderBySpec, type PatchInput, type ReferenceRelKeys, type RelatedModelOf, type RelationMutationConnect, type RelationMutationCreate, type RelationMutationDisconnect, type SelectedRow, type SortDirection, type WhereCallback, type WhereFilter, and, extractKeyFromRow, getKeyPath, getStoreName, idbOrm, keyEquals, keyToken, not, or, runOrmTransaction, withMutationScope };
14
23
  //# sourceMappingURL=orm.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"orm.d.mts","names":[],"sources":["../src/core/filters.ts"],"mappings":";;;;;;iBAqBgB,OAAO,OAAO,cAAc,mBAAiB;;iBAK7C,MAAM,OAAO,cAAc,mBAAiB;;iBAK5C,IAAI,MAAM,kBAAgB"}
1
+ {"version":3,"file":"orm.d.mts","names":[],"sources":["../src/core/record-validation.ts","../src/core/filters.ts"],"mappings":";;;;;;cAIa,iCAAiC;WAEjC;WACA;WACA;EAFA,YAAA,mBACA,gCACA;;;;;iBCaG,OAAO,OAAO,cAAc,mBAAiB;;iBAK7C,MAAM,OAAO,cAAc,mBAAiB;;iBAK5C,IAAI,MAAM,kBAAgB"}
package/dist/orm.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { F as getStoreName, I as keyEquals, L as keyToken, N as getKeyPath, b as withMutationScope, j as extractKeyFromRow } from "./mutation-executor-inLFb0TE.mjs";
2
- import { t as idbOrm } from "./idb-orm-B1Br1C0F.mjs";
1
+ import { I as IdbDecimalIdentityConflictError, J as getStoreName, K as getKeyPath, W as extractKeyFromRow, X as keyToken, Y as keyEquals, j as IdbRecordValidationError, w as withMutationScope } from "./mutation-executor-IuJmyWEG.mjs";
2
+ import { n as runOrmTransaction, r as idbOrm, t as IdbTransactionCommittedEarlyError } from "./orm-transaction-BGx1eukw.mjs";
3
3
  import { andExpr, notExpr, orExpr } from "@prisma-idb/adapter-idb/runtime";
4
4
  //#region src/core/filters.ts
5
5
  /**
@@ -24,6 +24,6 @@ function not(expr) {
24
24
  return notExpr(expr);
25
25
  }
26
26
  //#endregion
27
- export { and, extractKeyFromRow, getKeyPath, getStoreName, idbOrm, keyEquals, keyToken, not, or, withMutationScope };
27
+ export { IdbDecimalIdentityConflictError, IdbRecordValidationError, IdbTransactionCommittedEarlyError, and, extractKeyFromRow, getKeyPath, getStoreName, idbOrm, keyEquals, keyToken, not, or, runOrmTransaction, withMutationScope };
28
28
 
29
29
  //# sourceMappingURL=orm.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma-idb/client-idb",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Prisma 8 IDB family — ORM client (idbOrm typed query builder)",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -32,16 +32,16 @@
32
32
  "./package.json": "./package.json"
33
33
  },
34
34
  "dependencies": {
35
- "@prisma-idb/adapter-idb": "0.12.0",
36
- "@prisma-idb/driver-idb": "0.12.0",
37
- "@prisma-idb/runtime-idb": "0.12.0",
38
- "@prisma-idb/target-idb": "0.12.0",
39
- "@prisma/orm-framework": "8.0.0-rc.12"
35
+ "@prisma-idb/adapter-idb": "0.13.0",
36
+ "@prisma-idb/driver-idb": "0.13.0",
37
+ "@prisma-idb/runtime-idb": "0.13.0",
38
+ "@prisma-idb/target-idb": "0.13.0",
39
+ "@prisma/orm-framework": "8.0.0-rc.18"
40
40
  },
41
41
  "devDependencies": {
42
- "@prisma-idb/family-idb": "0.12.0",
43
- "@prisma/cli-engine": "0.6.1",
44
- "@prisma/orm-toolchain": "8.0.0-rc.12",
42
+ "@prisma-idb/family-idb": "0.13.0",
43
+ "@prisma/cli-engine": "0.7.0",
44
+ "@prisma/orm-toolchain": "8.0.0-rc.18",
45
45
  "fake-indexeddb": "^6.2.5",
46
46
  "fast-check": "^4.10.2",
47
47
  "tsdown": "^0.22.14",
@@ -1 +0,0 @@
1
- {"version":3,"file":"executor-CIEHpa1j.d.mts","names":[],"sources":["../src/core/types.ts","../src/core/executor.ts"],"mappings":";;;;;;;;;;;;;;KAgCK,SAAS,aAAa;WAA6B;aAAmB,kBAAkB;;IACzF,SAAS;WAAuB,cAAc;IAC5C,UAAU,eAAe,qBACvB,IACA,eAAe,qBACjB,eAAe,qBACjB,eAAe;;;;;;KASP,cAAc,SAAS;;;;;;;;;;;;KAiB9B,mBAAmB,aAAa,2BAA2B,iBAAiB,2BAA2B;KAEvG,kBAAkB,WAAW,iDAAiD,2BAA2B,aAC1G,0BACA,mBAAmB,mBAAmB,0BACpC,wBAAwB,mBAAmB,0BAC5B,WAAW,mBAAmB,WAAW,aAAa,mBAAmB,WAAW,WAAW,QAC5G,0BACF;;;;;;;KAQD,kBAAkB,aAAa,0BAA0B,iBAAiB,0BAA0B;KAEpG,iBAAiB,WAAW,iDAAiD,0BAA0B,aACxG,0BACA,kBAAkB,mBAAmB,0BACnC,wBAAwB,kBAAkB,0BAC3B,WAAW,kBAAkB,WAAW,aAAa,kBAAkB,WAAW,WAAW,QAC1G,0BACF;;KAKM,gBAAgB,WAAW,4BAA4B,kBAAkB,WAAW;;;;;;;;KAWpF,YAAY,WAAW,wCACvB,WAAW,gBAAgB,WAAW,cAAc,gBAAgB,WAAW,WAAW;;;;;;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,WAAW,aAAa,uBAAuB,WAAW;;KAMnF;;KAGA,YAAY,WAAW,4BAA4B,QAC7D,sBAAsB,gBAAgB,WAAW,YAAY;;KAMnD;;;;;;;;;;KAWA,kBAAkB,WAAW,iDAAiD,gBACxF,WACA,yBAIK,WAAW,gBAAgB,WAAW,sBAAsB,YAC3D,gBAAgB,WAAW,WAAW,qBAEpC,mBAEE,gBAAgB,WAAW;cAEzB;;;;;;;;UASG,qBAAqB;WAC3B;WACA,IAAI;WACJ;YACC,2BAA2B;;;KAI3B,mBAAmB,eAAe;;KAGlC,mBAAmB,aAAa,uBACzC,WAAW,OAAO,KAAK,WAAW,2BAA2B,UAAU;;;;;;UAQzD,oBAAoB,WAAW;EAC9C,SAAS;EACT,IAAI,UAAU,kBAAkB,WAAW,YAAY,OAAO,IAAI;EAClE,IAAI,UAAU,kBAAkB,WAAW,YAAY,OAAO,IAAI;EAClE,IAAI,UAAU,kBAAkB,WAAW,YAAY,OAAO,IAAI;EAClE,IAAI,UAAU,kBAAkB,WAAW,YAAY,OAAO,IAAI;;;;;;iBASpD,aAAa,UAAU,aAAa;;;;;;;;;;;iBAepC,WAAW,UAAU,aAAa,oBAAoB;;;;;;;;;iBAiBtD,kBAAkB,KAAK,yBAAyB,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;;;UC/nBrE;EACf,MAAM,KAAK,MAAM,aAAa,OAAO,oBAAoB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"idb-orm-6OuwkeDM.d.mts","names":[],"sources":["../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/grouped-accessor.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts"],"mappings":";;;;;;;;;;UA2BiB,iBAAiB;EAChC,GAAG,OAAO,IAAI;EACd,IAAI,OAAO,IAAI;EACf,GAAG,OAAO,IAAI;EACd,GAAG,OAAO,IAAI;EACd,IAAI,OAAO,IAAI;EACf,IAAI,OAAO,IAAI;EACf,GAAG,QAAQ,cAAc,KAAK;EAC9B,M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