{"version":3,"file":"prisma.mjs","names":[],"sources":["../src/adapters/prisma.ts"],"sourcesContent":["import type { ModelQueryOptionsCb, ModelQueryOptionsCbArgs } from \"@prisma/client/runtime/client\";\nimport {\n  readIdColumn,\n  readIdColumnNullable,\n  writeIdColumn,\n  writeIdColumnNullable,\n  type IdColumnCodec,\n  type IdGeneratingCodec,\n} from \"./adapter-types.js\";\nimport type { Id } from \"../types.js\";\n\n/** {@link IdsError} class, {@link isIdsError} type guard, and {@link IdsErrorCode} union — re-exported from `\"@smonn/ids\"` for convenience. */\nexport { IdsError, isIdsError, type IdsErrorCode } from \"../error.js\";\n\nexport type { IdColumnCodec, IdGeneratingCodec };\n\n/**\n * The per-model object returned by {@link IdTransform.defaultQuery}, suitable for\n * the model-level value inside a Prisma `$extends({ query: { modelName: … } })` block.\n * Structurally identical to `{ [operation: string]: ModelQueryOptionsCb }` from\n * `@prisma/client/runtime/client`.\n */\nexport type IdQueryField = { [operation: string]: ModelQueryOptionsCb };\n\n/**\n * Typed `$extends` result-component field definition produced by\n * {@link IdTransform.computeField} — a `{ needs, compute }` pair whose `compute`\n * return type is statically `Id<Brand>`, so the extended-client model field is\n * typed correctly without a per-call-site cast.\n */\nexport type IdComputeField<Brand extends string> = {\n  needs: Record<string, boolean>;\n  compute: (model: Record<string, unknown>) => Id<Brand>;\n};\n\n/**\n * Typed `$extends` result-component field definition produced by\n * {@link IdTransform.computeNullableField} — like {@link IdComputeField} but\n * `compute` returns `Id<Brand> | null` for nullable columns.\n */\nexport type NullableIdComputeField<Brand extends string> = {\n  needs: Record<string, boolean>;\n  compute: (model: Record<string, unknown>) => Id<Brand> | null;\n};\n\n/**\n * Read/write transform pair and `$extends` result-component factory for\n * integrating `Id<Brand>` with Prisma extensions.\n */\nexport type IdTransform<Brand extends string> = {\n  /**\n   * Read transform: validates the raw database value via `safeParse` and returns\n   * `Id<Brand>`. Throws if the value is missing, malformed, or belongs to a\n   * different brand.\n   */\n  read(value: unknown): Id<Brand>;\n  /**\n   * Nullable read transform: returns `null` when `value` is `null` or `undefined`;\n   * otherwise delegates to {@link read}. Use for optional foreign keys.\n   */\n  readNullable(value: unknown): Id<Brand> | null;\n  /**\n   * Write transform: validates `value` via `codec.safeParse` and returns the\n   * canonical string form. Throws `IdsError(\"invalid_id\")` if the value is\n   * invalid, belongs to a different brand, or is `null`/`undefined`.\n   *\n   * Use in a Prisma `$extends` query component or explicit `data` mapping.\n   */\n  write(value: Id<Brand>): string;\n  /**\n   * Creates a typed `$extends` result-component field definition that carries\n   * `Id<Brand>` through Prisma's type machinery without a per-call-site cast.\n   *\n   * @param fieldName - The model field to read from (e.g. `\"id\"`).\n   * @returns An {@link IdComputeField} whose `compute` return type is statically\n   * `Id<Brand>`, so the extended-client model field is typed correctly.\n   *\n   * @example\n   * ```ts\n   * const xprisma = prisma.$extends({\n   *   result: {\n   *     user: { id: userIdField.computeField(\"id\") },\n   *   },\n   * });\n   * // xprisma.user.findUnique(…).id is typed as Id<\"usr\"> — no cast required\n   * ```\n   */\n  computeField(fieldName: string): IdComputeField<Brand>;\n  /**\n   * Creates a `$extends` query-component model slice that auto-generates\n   * `Id<Brand>` values for `create`, `createMany`, `createManyAndReturn`, and\n   * `upsert` operations when the field is absent, `undefined`, or `null` in\n   * `args.data` (or `args.create` for upsert). When the field is absent,\n   * `undefined`, or `null`, a fresh `Id<Brand>` is injected; when present, the\n   * value is validated via `codec.safeParse` and `IdsError(\"invalid_id\")` is\n   * thrown if invalid.\n   *\n   * @param fieldName - The model field to auto-generate (e.g. `\"id\"`).\n   * @returns An {@link IdQueryField} suitable for the model-level value inside\n   * a Prisma `$extends({ query: { modelName: … } })` block.\n   *\n   * @remarks\n   * **Nested-relation-write limitation:** ID fields inside nested relation writes\n   * (`data: { posts: { create: { … } } }`, `connectOrCreate.create`, etc.) are\n   * **not** reached by any model-level `defaultQuery` hook. Callers must validate\n   * or generate nested IDs explicitly at the service layer.\n   *\n   * @example\n   * ```ts\n   * const xprisma = prisma.$extends({\n   *   query: { user: userIdField.defaultQuery(\"id\") },\n   *   result: { user: { id: userIdField.computeField(\"id\") } },\n   * });\n   * // id is auto-filled on create, and typed as Id<\"usr\"> on read\n   * await xprisma.user.create({ data: { name: \"Alice\" } });\n   * ```\n   */\n  defaultQuery(fieldName: string): IdQueryField;\n  /**\n   * Like {@link computeField} but for nullable columns — `compute` returns\n   * `Id<Brand> | null` instead of `Id<Brand>`.\n   *\n   * @param fieldName - The nullable model field to read from.\n   * @returns A {@link NullableIdComputeField} whose `compute` returns `Id<Brand> | null`.\n   */\n  computeNullableField(fieldName: string): NullableIdComputeField<Brand>;\n};\n\n/**\n * The read/nullable-read/write surface returned by {@link nullableIdField} —\n * mirrors the nullable methods of {@link IdTransform} but omits `defaultQuery`,\n * `read`, and `computeField` since nullable FK columns neither auto-generate IDs\n * nor require a non-null read path at the top level.\n */\nexport type NullableIdTransform<Brand extends string> = {\n  readNullable(value: unknown): Id<Brand> | null;\n  write(value: Id<Brand> | null | undefined): string | null;\n  computeNullableField(fieldName: string): NullableIdComputeField<Brand>;\n};\n\n/**\n * Creates a read/write transform pair for use with Prisma's `$extends` extension model.\n *\n * Requires a codec variant that exposes a synchronous `generate()` in addition to `safeParse` — see {@link IdGeneratingCodec}. Only the **Timestamp codec** and **Reverse Timestamp codec** qualify; Opaque, Signed, Wrapped, and Digest codecs cannot be passed to `idField()`.\n *\n * Use `computeField(fieldName)` to produce a typed `$extends` result-component\n * field definition — the brand is carried through Prisma's type machinery\n * automatically and no per-call-site cast is required.\n *\n * For codecs that do not expose a synchronous `generate()` (Opaque Timestamp,\n * Signed Timestamp, Wrapped key, Digest), use {@link idFieldNonGenerating} instead —\n * it accepts any {@link IdColumnCodec} and omits `defaultQuery`.\n *\n * @example\n * ```ts\n * import { idField } from \"@smonn/ids/prisma\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n * const userIdField = idField(usr);\n *\n * const xprisma = prisma.$extends({\n *   result: {\n *     user: { id: userIdField.computeField(\"id\") },\n *   },\n * });\n * // xprisma.user.findUnique(…).id is typed as Id<\"usr\"> — no cast required\n * ```\n */\nexport function idField<Brand extends string>(codec: IdGeneratingCodec<Brand>): IdTransform<Brand> {\n  const { generate } = codec;\n  return {\n    read(value: unknown): Id<Brand> {\n      return readIdColumn(codec, value);\n    },\n    readNullable(value: unknown): Id<Brand> | null {\n      return readIdColumnNullable(codec, value);\n    },\n    write(value: Id<Brand>): string {\n      return writeIdColumn(codec, value);\n    },\n    computeField(fieldName: string) {\n      return {\n        needs: { [fieldName]: true },\n        // Prisma's $extends types `compute` as returning `any` in its constraint\n        // type (DynamicResultExtensionArgs). Returning a pre-built object with an\n        // explicit Id<Brand> return type on `compute` causes TypeScript to infer\n        // the brand through the `& R` intersection in $extends — encapsulating\n        // the single necessary cast here rather than pushing it to every call site.\n        compute: (model: Record<string, unknown>): Id<Brand> =>\n          readIdColumn(codec, model[fieldName]),\n      };\n    },\n    defaultQuery(fieldName: string): IdQueryField {\n      function injectOrValidate(data: Record<string, unknown>): Record<string, unknown> {\n        if (data[fieldName] == null) {\n          return { ...data, [fieldName]: generate() };\n        }\n        return { ...data, [fieldName]: writeIdColumn(codec, data[fieldName] as Id<Brand>) };\n      }\n\n      type QueryArg = Parameters<ModelQueryOptionsCbArgs[\"query\"]>[0];\n\n      async function applyInjectOrValidate({\n        args,\n        query,\n      }: ModelQueryOptionsCbArgs): Promise<unknown> {\n        const data = args.data as\n          | Array<Record<string, unknown>>\n          | Record<string, unknown>\n          | null\n          | undefined;\n        let nextArgs: QueryArg;\n        if (Array.isArray(data)) {\n          nextArgs = {\n            ...args,\n            data: data.map((item) => injectOrValidate(item)),\n          } as unknown as QueryArg;\n        } else if (data != null) {\n          nextArgs = { ...args, data: injectOrValidate(data) } as unknown as QueryArg;\n        } else {\n          nextArgs = args;\n        }\n        return query(nextArgs);\n      }\n\n      return {\n        async create({ args, query }) {\n          const data = args.data as Record<string, unknown> | null | undefined;\n          const nextArgs =\n            data != null\n              ? ({ ...args, data: injectOrValidate(data) } as unknown as QueryArg)\n              : args;\n          return query(nextArgs);\n        },\n        createMany: applyInjectOrValidate,\n        createManyAndReturn: applyInjectOrValidate,\n        async upsert({ args, query }) {\n          const createData = args.create as Record<string, unknown> | null | undefined;\n          const nextArgs =\n            createData != null\n              ? ({ ...args, create: injectOrValidate(createData) } as unknown as QueryArg)\n              : args;\n          return query(nextArgs);\n        },\n      };\n    },\n    computeNullableField(fieldName: string) {\n      return {\n        needs: { [fieldName]: true },\n        compute: (model: Record<string, unknown>): Id<Brand> | null =>\n          readIdColumnNullable(codec, model[fieldName]),\n      };\n    },\n  };\n}\n\n/**\n * Standalone nullable counterpart of {@link idField} for Prisma adapter symmetry\n * with the other ORM adapters ({@link nullableIdColumn} in Drizzle/Kysely,\n * `nullableIdType` in MikroORM, `nullableIdTransformer` in TypeORM).\n *\n * Accepts any {@link IdColumnCodec} — no synchronous `generate()` required,\n * because nullable FK columns do not auto-generate IDs.\n *\n * @example\n * ```ts\n * import { nullableIdField } from \"@smonn/ids/prisma\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n * const authorIdField = nullableIdField(usr);\n *\n * const xprisma = prisma.$extends({\n *   result: {\n *     post: { authorId: authorIdField.computeNullableField(\"authorId\") },\n *   },\n * });\n * // xprisma.post.findUnique(…).authorId is typed as Id<\"usr\"> | null\n * ```\n */\nexport function nullableIdField<Brand extends string>(\n  codec: IdColumnCodec<Brand>,\n): NullableIdTransform<Brand> {\n  return {\n    readNullable(value: unknown): Id<Brand> | null {\n      return readIdColumnNullable(codec, value);\n    },\n    write(value: Id<Brand> | null | undefined): string | null {\n      return writeIdColumnNullable(codec, value);\n    },\n    computeNullableField(fieldName: string) {\n      return {\n        needs: { [fieldName]: true },\n        compute: (model: Record<string, unknown>): Id<Brand> | null =>\n          readIdColumnNullable(codec, model[fieldName]),\n      };\n    },\n  };\n}\n\n/**\n * Non-generating sibling of {@link idField} for codec variants that do not expose a\n * synchronous `generate()` — Opaque Timestamp, Signed Timestamp, Wrapped key,\n * and Digest codecs all qualify.\n *\n * Accepts any {@link IdColumnCodec} (the wider constraint that only requires\n * `safeParse`) and returns the full read/transform surface of {@link IdTransform}\n * **minus `defaultQuery`**. Because `defaultQuery` is the only method that calls\n * `generate()`, callers who only need the read path are not forced to provide a\n * synchronous generator.\n *\n * The name reflects the provenance axis — this mapper does not generate IDs; it\n * parses and serialises a caller-supplied value. It is **not** read-only: the\n * return value includes a `write` method.\n *\n * @example\n * ```ts\n * import { idFieldNonGenerating } from \"@smonn/ids/prisma\";\n * import { createOpaqueTimestampId } from \"@smonn/ids/opaque\";\n *\n * const inv = createOpaqueTimestampId(\"inv\", { key });\n * const invoiceIdField = idFieldNonGenerating(inv);\n *\n * const xprisma = prisma.$extends({\n *   result: {\n *     invoice: { id: invoiceIdField.computeField(\"id\") },\n *   },\n * });\n * // xprisma.invoice.findUnique(…).id is typed as Id<\"inv\"> — no cast required\n * ```\n */\nexport function idFieldNonGenerating<Brand extends string>(\n  codec: IdColumnCodec<Brand>,\n): Omit<IdTransform<Brand>, \"defaultQuery\"> {\n  return {\n    read(value: unknown): Id<Brand> {\n      return readIdColumn(codec, value);\n    },\n    readNullable(value: unknown): Id<Brand> | null {\n      return readIdColumnNullable(codec, value);\n    },\n    write(value: Id<Brand>): string {\n      return writeIdColumn(codec, value);\n    },\n    computeField(fieldName: string) {\n      return {\n        needs: { [fieldName]: true },\n        compute: (model: Record<string, unknown>): Id<Brand> =>\n          readIdColumn(codec, model[fieldName]),\n      };\n    },\n    computeNullableField(fieldName: string) {\n      return {\n        needs: { [fieldName]: true },\n        compute: (model: Record<string, unknown>): Id<Brand> | null =>\n          readIdColumnNullable(codec, model[fieldName]),\n      };\n    },\n  };\n}\n\n/**\n * @deprecated Renamed to {@link idFieldNonGenerating}. Alias retained until 2.0.\n * Use `idFieldNonGenerating` for new code.\n */\nexport function idFieldReadOnly<Brand extends string>(\n  codec: IdColumnCodec<Br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