@kurotako/parser-prisma 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/index.cjs +638 -79
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -2
- package/dist/index.d.ts +52 -2
- package/dist/index.js +633 -79
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/options.ts","../src/parser.ts","../src/detect.ts","../src/dmmf/load.ts","../src/dmmf/read.ts","../src/map/build.ts","../src/map/defaults.ts","../src/map/scalars.ts","../src/map/relations.ts"],"sourcesContent":["/**\n * `@kurotako/parser-prisma` — the Prisma parser driver.\n *\n * Reads a Prisma schema (single file or `prismaSchemaFolder`) through\n * `@prisma/internals`' `getDMMF` and produces a `SourceIR` for `@kurotako/core`.\n * Single entry point: the driver object, its options schema/type, and the error\n * classes.\n */\n\nexport {\n PrismaInputError,\n PrismaPeerMissingError,\n PrismaSchemaError,\n} from './errors.js';\nexport { PrismaParserOptions } from './options.js';\nexport { prismaParser } from './parser.js';\n","/**\n * Prisma-parser error classes. Each extends `TakoError` from `@kurotako/core`\n * so the CLI's single `instanceof TakoError` catch covers them; `@kurotako/core`\n * additionally wraps any throw from `parse()` as a `DriverError`.\n *\n * Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema`.\n */\nimport { TakoError } from '@kurotako/core';\n\n/** Schema path missing, an empty folder, or a folder with no `.prisma` file. */\nexport class PrismaInputError extends TakoError {\n readonly namespace: string;\n readonly resolvedPath: string;\n\n constructor(namespace: string, resolvedPath: string, detail: string) {\n super(\n 'prisma_input',\n `prisma parser (namespace '${namespace}'): ${detail} (resolved path: ${resolvedPath})`,\n );\n this.namespace = namespace;\n this.resolvedPath = resolvedPath;\n }\n}\n\n/** `@prisma/internals` cannot be resolved from the project. */\nexport class PrismaPeerMissingError extends TakoError {\n readonly namespace: string;\n\n constructor(namespace: string, options?: { cause?: unknown }) {\n super(\n 'prisma_peer_missing',\n `prisma parser (namespace '${namespace}'): '@prisma/internals' could not be resolved. ` +\n 'Add it as a devDependency (`bun add -d @prisma/internals`, matching your Prisma major). ' +\n 'In a monorepo it is resolved from the directory holding the schema, so it may ' +\n 'be installed in the sub-project that owns the schema rather than at the repo root. ' +\n 'Note: installing it pulls @prisma/engines, whose postinstall downloads a schema-engine binary.',\n options,\n );\n this.namespace = namespace;\n }\n}\n\n/** `getDMMF` threw — an invalid schema. Carries the Prisma message and `cause`. */\nexport class PrismaSchemaError extends TakoError {\n readonly namespace: string;\n readonly prismaMessage: string;\n\n constructor(\n namespace: string,\n prismaMessage: string,\n options?: { cause?: unknown },\n ) {\n super(\n 'prisma_schema',\n `prisma parser (namespace '${namespace}'): the Prisma schema is invalid:\\n${prismaMessage}`,\n options,\n );\n this.namespace = namespace;\n this.prismaMessage = prismaMessage;\n }\n}\n","/**\n * Valibot schema for `@kurotako/parser-prisma`'s `options`, plus the inferred\n * type. `@kurotako/config` validates a config entry's `options` against this\n * schema and curries it away before `@kurotako/core` sees the parser.\n *\n * `schema` is resolved against `ParseContext.cwd`. `version` forces the\n * version-mode (see `detect.ts`); omitted, the mode is inferred from the input.\n */\nimport * as v from 'valibot';\n\n// `strictObject`: an unknown key (a typo like `schemaPath`) is a hard error\n// rather than being silently dropped.\nexport const PrismaParserOptions = v.strictObject({\n schema: v.optional(v.string(), './prisma/schema.prisma'),\n version: v.optional(v.picklist([7, 8])),\n});\n\nexport type PrismaParserOptions = v.InferOutput<typeof PrismaParserOptions>;\n","/**\n * `prismaParser` — the `@kurotako/parser-prisma` driver.\n *\n * `@kurotako/config` validates `options` against `optionsSchema` and curries it\n * away; `@kurotako/core` then calls `parse(ctx)` once per namespace and runs\n * `validateSourceIR` on the result.\n *\n * Flow: `resolveInput` (detect.ts) → `readDmmf` (dmmf/, Prisma <= 7) →\n * `buildSourceIR` (map/). The Prisma 8 `contract.json` mode is detected but not\n * implemented in v1.\n */\nimport { dirname, resolve } from 'node:path';\nimport { defineParser } from '@kurotako/config';\nimport type { ParseContext } from '@kurotako/core';\nimport type { SourceIR } from '@kurotako/ir';\nimport { resolveInput } from './detect.js';\nimport { readDmmf } from './dmmf/load.js';\nimport { PrismaInputError } from './errors.js';\nimport { buildSourceIR } from './map/build.js';\nimport { PrismaParserOptions } from './options.js';\n\nexport const prismaParser = defineParser({\n name: 'prisma',\n optionsSchema: PrismaParserOptions,\n\n async parse(ctx: ParseContext, options): Promise<SourceIR> {\n const input = await resolveInput(ctx.cwd, options, ctx.namespace);\n\n if (input.mode === 8) {\n throw new PrismaInputError(\n ctx.namespace,\n input.contractPath,\n 'the Prisma 8 contract.json mode is not implemented in kurotako v1',\n );\n }\n\n const { model, prismaVersion } = await readDmmf(input, ctx);\n return buildSourceIR(\n ctx.namespace,\n model,\n `prisma@${prismaVersion}`,\n ctx.logger,\n );\n },\n\n async watchPaths(ctx: ParseContext, options): Promise<string[]> {\n // The resolved schema path — a `.prisma` file, a schema folder, or the\n // deferred contract.json. A folder watch covers every `*.prisma` inside it.\n return [resolve(ctx.cwd, options.schema)];\n },\n\n anchor(rootDir, options) {\n // The directory the schema lives in. `dirname` is correct for a `.prisma`\n // file and for a `contract.json`; for a schema *folder* it yields the\n // parent, which is still a valid walk-up base for `node_modules`\n // resolution. No `stat` — the hook stays cheap.\n return dirname(resolve(rootDir, options.schema));\n },\n});\n","/**\n * Input resolution and version-mode detection.\n *\n * `resolveInput` turns `options.schema` (a `.prisma` file, a\n * `prismaSchemaFolder`, or — deferred — a `contract.json`) into a\n * `ResolvedInput`: the concrete file tuples for the Prisma <= 7 DMMF path, or\n * the `contract.json` path for the deferred Prisma 8 path.\n *\n * `options.version` forces the mode; otherwise it is inferred from what is on\n * disk. Multi-file Prisma schemas are read transparently.\n */\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport { PrismaInputError } from './errors.js';\nimport type { PrismaParserOptions } from './options.js';\n\nexport type ResolvedInput =\n | { mode: 7; kind: 'file' | 'folder'; files: Array<[string, string]> }\n | { mode: 8; kind: 'contract'; contractPath: string };\n\nconst PRISMA_EXT = '.prisma';\nconst CONTRACT_FILE = 'contract.json';\n\nfunction toPosix(p: string): string {\n return sep === '/' ? p : p.split(sep).join('/');\n}\n\nasync function pathKind(p: string): Promise<'file' | 'dir' | 'missing'> {\n try {\n const s = await stat(p);\n return s.isDirectory() ? 'dir' : 'file';\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return 'missing';\n }\n throw err;\n }\n}\n\n/** `*.prisma` directly in `dir`, then one level down (prismaSchemaFolder layout). */\nasync function collectPrismaFiles(dir: string): Promise<string[]> {\n const found: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isFile() && entry.name.endsWith(PRISMA_EXT)) {\n found.push(full);\n } else if (entry.isDirectory()) {\n const nested = await readdir(full, { withFileTypes: true });\n for (const child of nested) {\n if (child.isFile() && child.name.endsWith(PRISMA_EXT)) {\n found.push(join(full, child.name));\n }\n }\n }\n }\n return found;\n}\n\nasync function dirHasContract(dir: string): Promise<boolean> {\n return (await pathKind(join(dir, CONTRACT_FILE))) === 'file';\n}\n\nasync function readTuples(\n root: string,\n files: string[],\n): Promise<Array<[string, string]>> {\n const tuples = await Promise.all(\n files.map(\n async (file): Promise<[string, string]> => [\n toPosix(relative(root, file)),\n await readFile(file, 'utf8'),\n ],\n ),\n );\n return tuples.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nasync function resolveMode7(\n namespace: string,\n resolved: string,\n kind: 'file' | 'dir',\n): Promise<ResolvedInput> {\n if (kind === 'file') {\n return {\n mode: 7,\n kind: 'file',\n files: await readTuples(dirname(resolved), [resolved]),\n };\n }\n const files = await collectPrismaFiles(resolved);\n if (files.length === 0) {\n throw new PrismaInputError(\n namespace,\n resolved,\n 'the schema folder contains no .prisma file',\n );\n }\n return { mode: 7, kind: 'folder', files: await readTuples(resolved, files) };\n}\n\nasync function resolveMode8(\n namespace: string,\n resolved: string,\n kind: 'file' | 'dir',\n): Promise<ResolvedInput> {\n if (kind === 'dir') {\n const contractPath = join(resolved, CONTRACT_FILE);\n if ((await pathKind(contractPath)) !== 'file') {\n throw new PrismaInputError(\n namespace,\n resolved,\n `version 8 mode expects a ${CONTRACT_FILE} in the folder`,\n );\n }\n return { mode: 8, kind: 'contract', contractPath };\n }\n return { mode: 8, kind: 'contract', contractPath: resolved };\n}\n\nexport async function resolveInput(\n cwd: string,\n o: PrismaParserOptions,\n namespace = '<unknown>',\n): Promise<ResolvedInput> {\n const resolved = resolve(cwd, o.schema);\n const kind = await pathKind(resolved);\n if (kind === 'missing') {\n throw new PrismaInputError(\n namespace,\n resolved,\n 'the schema path does not exist',\n );\n }\n\n if (o.version === 8) {\n return resolveMode8(namespace, resolved, kind);\n }\n if (o.version === 7) {\n return resolveMode7(namespace, resolved, kind);\n }\n\n // Infer.\n if (kind === 'file') {\n if (basename(resolved) === CONTRACT_FILE) {\n return { mode: 8, kind: 'contract', contractPath: resolved };\n }\n if (resolved.endsWith(PRISMA_EXT)) {\n return resolveMode7(namespace, resolved, 'file');\n }\n throw new PrismaInputError(\n namespace,\n resolved,\n `not a .prisma file or a ${CONTRACT_FILE}`,\n );\n }\n\n if (await dirHasContract(resolved)) {\n return resolveMode8(namespace, resolved, 'dir');\n }\n return resolveMode7(namespace, resolved, 'dir');\n}\n","/**\n * Prisma <= 7 DMMF acquisition.\n *\n * `@prisma/internals` is an optional peer: it is resolved dynamically from the\n * consumer's project (`ctx.cwd`), not bundled. A resolution failure is a\n * `PrismaPeerMissingError` with an install hint; a `getDMMF` throw (invalid\n * schema) is a `PrismaSchemaError` keeping the Prisma P1012 text and `cause`.\n *\n * The package is CJS-only and its ESM-interop is unreliable, so the `getDMMF`\n * function is looked up on both the namespace and its `default`.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { ParseContext } from '@kurotako/core';\nimport type { ResolvedInput } from '../detect.js';\nimport { PrismaPeerMissingError, PrismaSchemaError } from '../errors.js';\nimport type { PrismaModel } from './model.js';\nimport { toPrismaModel } from './read.js';\n\ntype SchemaFileInput = string | Array<[string, string]>;\ntype GetDmmf = (options: {\n datamodel: SchemaFileInput;\n}) => Promise<import('@prisma/dmmf').Document>;\n\ninterface InternalsModule {\n getDMMF?: GetDmmf;\n default?: { getDMMF?: GetDmmf };\n}\n\nasync function resolveInternals(\n ctx: ParseContext,\n): Promise<{ getDMMF: GetDmmf; prismaVersion: string }> {\n // Resolve `@prisma/internals` from the source's anchor directory (where its\n // schema lives) so it can be a devDependency of the sub-project holding the\n // schema, not only of the repo root. Node still walks up `node_modules` from\n // there to `ctx.cwd` and beyond. Absent ⇒ anchor on `ctx.cwd`.\n const base = ctx.anchorDir ?? ctx.cwd;\n const require = createRequire(join(base, 'noop.js'));\n\n let entry: string;\n try {\n entry = require.resolve('@prisma/internals');\n } catch (err) {\n throw new PrismaPeerMissingError(ctx.namespace, { cause: err });\n }\n\n let mod: InternalsModule;\n try {\n mod = (await import(pathToFileURL(entry).href)) as InternalsModule;\n } catch (err) {\n throw new PrismaPeerMissingError(ctx.namespace, { cause: err });\n }\n\n const getDMMF = mod.default?.getDMMF ?? mod.getDMMF;\n if (typeof getDMMF !== 'function') {\n throw new PrismaPeerMissingError(ctx.namespace);\n }\n\n let prismaVersion = 'unknown';\n try {\n const pkg = JSON.parse(\n await readFile(require.resolve('@prisma/internals/package.json'), 'utf8'),\n ) as { version?: string };\n if (typeof pkg.version === 'string') {\n prismaVersion = pkg.version;\n }\n } catch {\n ctx.logger.debug(\n 'prisma parser: could not read @prisma/internals version',\n { namespace: ctx.namespace },\n );\n }\n\n return { getDMMF, prismaVersion };\n}\n\nexport async function readDmmf(\n input: Extract<ResolvedInput, { mode: 7 }>,\n ctx: ParseContext,\n): Promise<{ model: PrismaModel; prismaVersion: string }> {\n const { getDMMF, prismaVersion } = await resolveInternals(ctx);\n\n const datamodel: SchemaFileInput =\n input.kind === 'file'\n ? (input.files[0]?.[1] ?? '')\n : input.files.map(([path, content]) => [path, content]);\n\n let doc: Awaited<ReturnType<GetDmmf>>;\n try {\n doc = await getDMMF({ datamodel });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new PrismaSchemaError(ctx.namespace, message, { cause: err });\n }\n\n return { model: toPrismaModel(doc), prismaVersion };\n}\n","/**\n * `DMMF.Document` → the mode-neutral `PrismaModel`.\n *\n * Pure and total: it never touches disk or Prisma. Object fields become\n * `relationEdges`; scalar / enum / unsupported fields become `fields`. Model and\n * enum `documentation` / `dbName` are carried verbatim. Non-unique `@@index`\n * entries come from `datamodel.indexes` when the resolved `@prisma/internals`\n * exposes them (6.x does), otherwise `indexes` stays empty.\n */\nimport type * as DMMF from '@prisma/dmmf';\nimport type {\n PrismaDefault,\n PrismaEntity,\n PrismaEnum,\n PrismaField,\n PrismaIndex,\n PrismaModel,\n PrismaRelationEdge,\n PrismaUnique,\n} from './model.js';\n\nfunction readField(f: DMMF.Field): PrismaField {\n const field: PrismaField = {\n name: f.name,\n type: f.type,\n kind:\n f.kind === 'enum'\n ? 'enum'\n : f.kind === 'unsupported'\n ? 'unsupported'\n : 'scalar',\n isList: f.isList,\n isRequired: f.isRequired,\n isUnique: f.isUnique,\n isUpdatedAt: f.isUpdatedAt ?? false,\n hasDefaultValue: f.hasDefaultValue,\n nativeType: f.nativeType ? [f.nativeType[0], [...f.nativeType[1]]] : null,\n };\n if (f.default !== undefined) {\n field.default = f.default as PrismaDefault;\n }\n if (f.documentation !== undefined) {\n field.doc = f.documentation;\n }\n return field;\n}\n\nfunction readEdge(f: DMMF.Field): PrismaRelationEdge {\n const edge: PrismaRelationEdge = {\n fieldName: f.name,\n relationName: f.relationName ?? '',\n targetEntity: f.type,\n isList: f.isList,\n isRequired: f.isRequired,\n fromFields: [...(f.relationFromFields ?? [])],\n toFields: [...(f.relationToFields ?? [])],\n };\n if (f.relationOnDelete !== undefined) {\n edge.onDelete = f.relationOnDelete;\n }\n if (f.relationOnUpdate !== undefined) {\n edge.onUpdate = f.relationOnUpdate;\n }\n return edge;\n}\n\nfunction readPrimaryKey(model: DMMF.Model): string[] {\n if (model.primaryKey && model.primaryKey.fields.length > 0) {\n return [...model.primaryKey.fields];\n }\n const id = model.fields.find((f) => f.isId);\n return id ? [id.name] : [];\n}\n\nfunction readUniques(model: DMMF.Model): PrismaUnique[] {\n if (model.uniqueIndexes.length > 0) {\n return model.uniqueIndexes.map((u) => {\n const entry: PrismaUnique = { fields: [...u.fields] };\n if (u.name) {\n entry.name = u.name;\n }\n return entry;\n });\n }\n return model.uniqueFields.map((fields) => ({ fields: [...fields] }));\n}\n\nfunction readIndexes(\n modelName: string,\n all: readonly DMMF.Index[] | undefined,\n): PrismaIndex[] {\n if (!all) {\n return [];\n }\n return all\n .filter((idx) => idx.model === modelName && idx.type === 'normal')\n .map((idx) => {\n const entry: PrismaIndex = { fields: idx.fields.map((f) => f.name) };\n if (idx.name) {\n entry.name = idx.name;\n }\n if (idx.algorithm) {\n entry.type = idx.algorithm.toLowerCase();\n }\n return entry;\n });\n}\n\nfunction readEntity(model: DMMF.Model, doc: DMMF.Document): PrismaEntity {\n const fields: PrismaField[] = [];\n const relationEdges: PrismaRelationEdge[] = [];\n for (const f of model.fields) {\n if (f.kind === 'object') {\n relationEdges.push(readEdge(f));\n } else {\n fields.push(readField(f));\n }\n }\n const entity: PrismaEntity = {\n name: model.name,\n fields,\n relationEdges,\n primaryKey: readPrimaryKey(model),\n uniques: readUniques(model),\n indexes: readIndexes(model.name, doc.datamodel.indexes),\n };\n if (model.dbName) {\n entity.dbName = model.dbName;\n }\n if (model.documentation !== undefined) {\n entity.doc = model.documentation;\n }\n return entity;\n}\n\nfunction readEnum(e: DMMF.DatamodelEnum): PrismaEnum {\n const def: PrismaEnum = {\n name: e.name,\n values: e.values.map((value) => {\n const entry = { name: value.name } as PrismaEnum['values'][number];\n if (value.dbName) {\n entry.dbName = value.dbName;\n }\n return entry;\n }),\n };\n if (e.dbName) {\n def.dbName = e.dbName;\n }\n if (e.documentation !== undefined) {\n def.doc = e.documentation;\n }\n return def;\n}\n\nexport function toPrismaModel(doc: DMMF.Document): PrismaModel {\n return {\n entities: doc.datamodel.models.map((m) => readEntity(m, doc)),\n enums: doc.datamodel.enums.map(readEnum),\n };\n}\n","/**\n * `PrismaModel` → `SourceIR`, driven entirely by the `createSourceIR` fluent\n * builder (the parser never hand-assembles IR).\n *\n * Field rules: `list ← isList`, `nullable ← !isRequired`,\n * `optional ← hasDefaultValue || isUpdatedAt`, `unique ← isUnique`. Scalars and\n * native-type refinement come from `map/scalars.ts`, defaults / id `format` from\n * `map/defaults.ts`, relations and implicit-m2m materialisation from\n * `map/relations.ts` (this module injects the namespace into every relation\n * target). Enums are emitted at source level, matching Prisma.\n */\nimport type { Logger } from '@kurotako/core';\nimport type { IndexType } from '@kurotako/ir';\nimport {\n createSourceIR,\n type EntityBuilder,\n type EnumBuilder,\n type FieldBuilder,\n type Relation,\n type SourceIR,\n} from '@kurotako/ir';\nimport type { PrismaEnum, PrismaModel } from '../dmmf/model.js';\nimport { mapDefault } from './defaults.js';\nimport { buildRelations } from './relations.js';\nimport { mapFieldType } from './scalars.js';\n\nconst INDEX_TYPES = new Set<IndexType>([\n 'btree',\n 'hash',\n 'gin',\n 'gist',\n 'brin',\n 'spgist',\n]);\n\nfunction asIndexType(raw: string | undefined): IndexType | undefined {\n return raw !== undefined && INDEX_TYPES.has(raw as IndexType)\n ? (raw as IndexType)\n : undefined;\n}\n\nfunction fillEnum(eb: EnumBuilder, e: PrismaEnum): void {\n for (const value of e.values) {\n const opts: { dbName?: string; doc?: string } = {};\n if (value.dbName !== undefined) {\n opts.dbName = value.dbName;\n }\n if (value.doc !== undefined) {\n opts.doc = value.doc;\n }\n eb.value(value.name, opts);\n }\n if (e.doc !== undefined) {\n eb.doc(e.doc);\n }\n if (e.dbName !== undefined) {\n eb.dbName(e.dbName);\n }\n}\n\nfunction addRelation(\n eb: EntityBuilder,\n rel: Relation,\n namespace: string,\n): void {\n eb.relation(rel.name, (rb) => {\n rb.to(namespace, rel.target.entity);\n if (rel.cardinality === 'many') {\n rb.many();\n } else {\n rb.one();\n }\n if (rel.optional) {\n rb.optional();\n }\n if (rel.owning) {\n rb.owning();\n }\n if (rel.backRelation !== undefined) {\n rb.backRelation(rel.backRelation);\n }\n if (rel.fkFields) {\n rb.fkFields(...rel.fkFields);\n }\n if (rel.references) {\n rb.references(...rel.references);\n }\n if (rel.onDelete) {\n rb.onDelete(rel.onDelete);\n }\n if (rel.onUpdate) {\n rb.onUpdate(rel.onUpdate);\n }\n });\n}\n\nexport function buildSourceIR(\n namespace: string,\n model: PrismaModel,\n parserVersion: string,\n logger?: Logger,\n): SourceIR {\n const b = createSourceIR({ namespace, parser: 'prisma', parserVersion });\n\n for (const e of model.enums) {\n b.addEnum(e.name, (eb) => fillEnum(eb, e));\n }\n\n const { relations, syntheticEntities } = buildRelations(model, logger);\n\n for (const entity of model.entities) {\n b.addEntity(entity.name, (eb) => {\n for (const field of entity.fields) {\n eb.field(field.name, (fb: FieldBuilder) => {\n const mapped = mapFieldType(field, logger);\n const scalar =\n mapped.scalarOverride ??\n (mapped.type.kind === 'scalar' ? mapped.type.scalar : undefined);\n\n if (scalar !== undefined) {\n fb.scalar(scalar);\n } else if (mapped.type.kind === 'enum') {\n fb.enum(mapped.type.ref);\n } else {\n fb.unknown(\n mapped.type.kind === 'unknown' ? mapped.type.hint : undefined,\n );\n }\n\n const isString = scalar === 'string';\n const { maxLength, format: nativeFormat } = mapped.constraints;\n if (maxLength !== undefined) {\n fb.maxLength(maxLength);\n }\n\n const mappedDefault = mapDefault(field.default);\n if (mappedDefault.default) {\n fb.default(mappedDefault.default);\n }\n const format = mappedDefault.format ?? nativeFormat;\n if (format !== undefined) {\n if (isString) {\n fb.format(format);\n } else {\n logger?.debug(\n `prisma parser: dropping format '${format}' on non-string field '${entity.name}.${field.name}'`,\n );\n }\n }\n\n if (field.isList) {\n fb.list();\n }\n if (!field.isRequired) {\n fb.nullable();\n }\n if (field.hasDefaultValue || field.isUpdatedAt) {\n fb.optional();\n }\n if (field.isUnique) {\n fb.unique();\n }\n if (field.doc !== undefined) {\n fb.doc(field.doc);\n }\n });\n }\n\n if (entity.primaryKey.length > 0) {\n eb.primaryKey(...entity.primaryKey);\n }\n for (const unique of entity.uniques) {\n eb.unique(\n unique.fields,\n unique.name ? { name: unique.name } : undefined,\n );\n }\n for (const index of entity.indexes) {\n const opts: { name?: string; type?: IndexType } = {};\n if (index.name) {\n opts.name = index.name;\n }\n const type = asIndexType(index.type);\n if (type) {\n opts.type = type;\n }\n eb.index(index.fields, opts);\n }\n if (entity.doc !== undefined) {\n eb.doc(entity.doc);\n }\n if (entity.dbName !== undefined) {\n eb.dbName(entity.dbName);\n }\n for (const rel of relations.get(entity.name) ?? []) {\n addRelation(eb, rel, namespace);\n }\n });\n }\n\n for (const synthetic of syntheticEntities) {\n b.addEntity(synthetic.name, (eb) => {\n for (const field of synthetic.fields) {\n eb.field(field.name, (fb) => fb.scalar(field.scalar));\n }\n eb.primaryKey(...synthetic.primaryKey);\n for (const rel of synthetic.relations) {\n addRelation(eb, rel, namespace);\n }\n });\n }\n\n return b.build();\n}\n","/**\n * Prisma `@default(...)` → IR `DefaultValue`, plus the `StringFormat` a\n * generator-side id default implies.\n *\n * Literals (and enum values, which the DMMF encodes as bare strings) become\n * `{ kind: 'value' }`. Function calls become `{ kind: 'expr' }`; `uuid()` /\n * `cuid()` / `cuid(2)` / `ulid()` additionally carry a `format` (the scalar is\n * left as `string`). `nanoid()` has no matching closed `StringFormat` → expr\n * only.\n */\nimport type { DefaultValue, StringFormat } from '@kurotako/ir';\nimport type { PrismaDefault } from '../dmmf/model.js';\n\nexport interface MappedDefault {\n default?: DefaultValue;\n format?: StringFormat;\n}\n\nconst ID_FORMATS: Record<string, StringFormat> = {\n uuid: 'uuid',\n cuid: 'cuid',\n ulid: 'ulid',\n};\n\nfunction isCall(\n raw: PrismaDefault,\n): raw is { name: string; args: Array<string | number> } {\n return typeof raw === 'object' && !Array.isArray(raw) && raw !== null;\n}\n\nexport function mapDefault(raw: PrismaDefault | undefined): MappedDefault {\n if (raw === undefined) {\n return {};\n }\n\n if (!isCall(raw)) {\n // literal, literal array, or enum value (bare string)\n return { default: { kind: 'value', value: raw } };\n }\n\n const { name, args } = raw;\n\n if (name === 'dbgenerated') {\n return { default: { kind: 'expr', expr: 'dbgenerated', args: [...args] } };\n }\n\n const idFormat = ID_FORMATS[name];\n if (idFormat !== undefined) {\n const format: StringFormat =\n name === 'cuid' && args[0] === 2 ? 'cuid2' : idFormat;\n return { default: { kind: 'expr', expr: `${name}()` }, format };\n }\n\n // now(), autoincrement(), nanoid(), and any other bare call\n return { default: { kind: 'expr', expr: `${name}()` } };\n}\n","/**\n * Prisma field type + native `@db.*` type → IR `FieldType` and `Constraints`.\n *\n * Base scalar mapping is a closed table. Native types refine it: a length\n * argument becomes `maxLength`, `@db.Uuid` / `@db.ObjectId` promote the scalar to\n * `uuid`, `@db.Date` to `date`, `@db.Time` keeps `datetime` but sets\n * `format: 'time'`. Unknown native types are ignored (logged at `debug`).\n */\nimport type { Logger } from '@kurotako/core';\nimport type { Constraints, FieldType, ScalarType } from '@kurotako/ir';\nimport type { PrismaField } from '../dmmf/model.js';\n\nconst SCALAR_TABLE: Record<string, ScalarType> = {\n String: 'string',\n Boolean: 'boolean',\n Int: 'int',\n BigInt: 'bigint',\n Float: 'float',\n Decimal: 'decimal',\n DateTime: 'datetime',\n Json: 'json',\n Bytes: 'bytes',\n};\n\nconst LENGTH_NATIVE = new Set(['VarChar', 'Char', 'NVarChar', 'String']);\nconst UUID_NATIVE = new Set(['Uuid', 'ObjectId']);\n/** Native types that are known and deliberately have no effect in v1. */\nconst NOOP_NATIVE = new Set([\n 'Text',\n 'Citext',\n 'Xml',\n 'Bit',\n 'VarBit',\n 'Inet',\n 'Line',\n 'LongText',\n 'MediumText',\n 'TinyText',\n 'SmallInt',\n 'MediumInt',\n 'UnsignedInt',\n 'UnsignedBigInt',\n 'Money',\n 'Real',\n 'DoublePrecision',\n 'Decimal',\n 'Numeric',\n 'SmallMoney',\n 'Timestamp',\n 'Timestamptz',\n 'DateTime2',\n 'DateTimeOffset',\n]);\n\nexport interface MappedFieldType {\n type: FieldType;\n constraints: Constraints;\n scalarOverride?: ScalarType;\n}\n\nfunction refineNative(\n native: [string, string[]],\n constraints: Constraints,\n result: MappedFieldType,\n field: PrismaField,\n logger: Logger | undefined,\n): void {\n const [name, args] = native;\n if (LENGTH_NATIVE.has(name)) {\n const n = Number(args[0]);\n if (Number.isFinite(n)) {\n constraints.maxLength = n;\n }\n return;\n }\n if (UUID_NATIVE.has(name)) {\n result.scalarOverride = 'uuid';\n return;\n }\n if (name === 'Date') {\n result.scalarOverride = 'date';\n return;\n }\n if (name === 'Time' || name === 'Timetz') {\n constraints.format = 'time';\n return;\n }\n if (NOOP_NATIVE.has(name)) {\n return;\n }\n logger?.debug(`prisma parser: ignoring unmapped native type @db.${name}`, {\n field: field.name,\n });\n}\n\nexport function mapFieldType(\n field: PrismaField,\n logger?: Logger,\n): MappedFieldType {\n const constraints: Constraints = {};\n\n if (field.kind === 'unsupported') {\n return { type: { kind: 'unknown', hint: field.type }, constraints };\n }\n if (field.kind === 'enum') {\n return { type: { kind: 'enum', ref: field.type }, constraints };\n }\n\n const scalar = SCALAR_TABLE[field.type];\n if (scalar === undefined) {\n return { type: { kind: 'unknown', hint: field.type }, constraints };\n }\n\n const result: MappedFieldType = {\n type: { kind: 'scalar', scalar },\n constraints,\n };\n if (field.nativeType) {\n refineNative(field.nativeType, constraints, result, field, logger);\n }\n return result;\n}\n","/**\n * Relation pairing and implicit-many-to-many materialisation.\n *\n * DMMF relation edges are grouped by `relationName`. A normal pair yields one\n * `Relation` per side (owning side = the one carrying `fromFields`). An implicit\n * m2m (both sides list, neither side carries fields) is materialised as a\n * synthetic join entity so downstream generators only ever see explicit m2m:\n * the two originals are rewritten to `many` relations pointing at the synthetic\n * entity, which gets `<model>Id` FK fields, a composite PK and two owning `one`\n * relations back to the originals.\n *\n * Every produced `Relation` has `target.namespace === ''`; `build.ts` injects\n * the real namespace (relations are always same-namespace for one Prisma\n * schema).\n */\nimport type { Logger } from '@kurotako/core';\nimport type { ReferentialAction, Relation, ScalarType } from '@kurotako/ir';\nimport type {\n PrismaEntity,\n PrismaModel,\n PrismaRelationEdge,\n} from '../dmmf/model.js';\nimport { mapFieldType } from './scalars.js';\n\nexport interface SyntheticField {\n name: string;\n scalar: ScalarType;\n}\n\nexport interface SyntheticEntity {\n name: string;\n fields: SyntheticField[];\n primaryKey: string[];\n relations: Relation[];\n}\n\nexport interface BuiltRelations {\n relations: Map<string, Relation[]>;\n syntheticEntities: SyntheticEntity[];\n}\n\nconst ACTION_MAP: Record<string, ReferentialAction> = {\n Cascade: 'cascade',\n Restrict: 'restrict',\n SetNull: 'setNull',\n SetDefault: 'setDefault',\n NoAction: 'noAction',\n};\n\nfunction mapAction(raw: string | undefined): ReferentialAction | undefined {\n return raw === undefined ? undefined : ACTION_MAP[raw];\n}\n\nfunction lcfirst(s: string): string {\n return s.length === 0 ? s : s.charAt(0).toLowerCase() + s.slice(1);\n}\n\ninterface OwnedEdge {\n owner: string;\n edge: PrismaRelationEdge;\n}\n\nfunction isImplicitM2M(edges: OwnedEdge[]): boolean {\n return (\n edges.length === 2 &&\n edges.every(\n ({ edge }) =>\n edge.isList &&\n edge.fromFields.length === 0 &&\n edge.toFields.length === 0,\n )\n );\n}\n\nfunction pkScalar(\n entities: Map<string, PrismaEntity>,\n entityName: string,\n logger: Logger | undefined,\n): ScalarType {\n const entity = entities.get(entityName);\n if (entity && entity.primaryKey.length === 1) {\n const pkName = entity.primaryKey[0];\n const field = entity.fields.find((f) => f.name === pkName);\n if (field) {\n const mapped = mapFieldType(field);\n if (mapped.scalarOverride) {\n return mapped.scalarOverride;\n }\n if (mapped.type.kind === 'scalar') {\n return mapped.type.scalar;\n }\n }\n }\n logger?.debug(\n `prisma parser: could not resolve primary-key scalar of '${entityName}', defaulting to string`,\n );\n return 'string';\n}\n\nfunction normalRelation(\n edge: PrismaRelationEdge,\n back: PrismaRelationEdge | undefined,\n): Relation {\n const owning = edge.fromFields.length > 0;\n const relation: Relation = {\n name: edge.fieldName,\n target: { namespace: '', entity: edge.targetEntity },\n cardinality: edge.isList ? 'many' : 'one',\n optional: !edge.isRequired,\n owning,\n };\n if (owning) {\n relation.fkFields = [...edge.fromFields];\n relation.references = [...edge.toFields];\n }\n if (back) {\n relation.backRelation = back.fieldName;\n }\n const onDelete = mapAction(edge.onDelete);\n if (onDelete) {\n relation.onDelete = onDelete;\n }\n const onUpdate = mapAction(edge.onUpdate);\n if (onUpdate) {\n relation.onUpdate = onUpdate;\n }\n return relation;\n}\n\nfunction materialiseM2M(\n a: OwnedEdge,\n b: OwnedEdge,\n relationName: string,\n entities: Map<string, PrismaEntity>,\n logger: Logger | undefined,\n): {\n synthetic: SyntheticEntity;\n rewrites: Array<{ owner: string; relation: Relation }>;\n} {\n const sorted = [a.owner, b.owner].sort((l, r) =>\n l < r ? -1 : l > r ? 1 : 0,\n );\n const x = sorted[0] ?? a.owner;\n const y = sorted[1] ?? b.owner;\n const defaultName = `${x}To${y}`;\n const name =\n relationName !== '' && relationName !== defaultName\n ? relationName\n : `${x}${y}`;\n\n const fkX = `${lcfirst(x)}Id`;\n const fkY = `${lcfirst(y)}Id`;\n const relX = lcfirst(x);\n const relY = lcfirst(y);\n const pkX = entities.get(x)?.primaryKey[0] ?? 'id';\n const pkY = entities.get(y)?.primaryKey[0] ?? 'id';\n\n const synthetic: SyntheticEntity = {\n name,\n fields: [\n { name: fkX, scalar: pkScalar(entities, x, logger) },\n { name: fkY, scalar: pkScalar(entities, y, logger) },\n ],\n primaryKey: [fkX, fkY],\n relations: [\n {\n name: relX,\n target: { namespace: '', entity: x },\n cardinality: 'one',\n optional: false,\n owning: true,\n fkFields: [fkX],\n references: [pkX],\n onDelete: 'cascade',\n },\n {\n name: relY,\n target: { namespace: '', entity: y },\n cardinality: 'one',\n optional: false,\n owning: true,\n fkFields: [fkY],\n references: [pkY],\n onDelete: 'cascade',\n },\n ],\n };\n\n const mkRewrite = (\n edge: OwnedEdge,\n backName: string,\n ): { owner: string; relation: Relation } => ({\n owner: edge.owner,\n relation: {\n name: edge.edge.fieldName,\n target: { namespace: '', entity: name },\n cardinality: 'many',\n optional: false,\n owning: false,\n backRelation: backName,\n },\n });\n\n return {\n synthetic,\n rewrites: [\n mkRewrite(a, a.owner === x ? relX : relY),\n mkRewrite(b, b.owner === x ? relX : relY),\n ],\n };\n}\n\nexport function buildRelations(\n model: PrismaModel,\n logger?: Logger,\n): BuiltRelations {\n const entities = new Map(model.entities.map((e) => [e.name, e]));\n const relations = new Map<string, Relation[]>();\n const syntheticEntities: SyntheticEntity[] = [];\n\n const push = (owner: string, relation: Relation): void => {\n const list = relations.get(owner) ?? [];\n list.push(relation);\n relations.set(owner, list);\n };\n\n const groups = new Map<string, OwnedEdge[]>();\n for (const entity of model.entities) {\n for (const edge of entity.relationEdges) {\n const list = groups.get(edge.relationName) ?? [];\n list.push({ owner: entity.name, edge });\n groups.set(edge.relationName, list);\n }\n }\n\n for (const [relationName, edges] of groups) {\n if (isImplicitM2M(edges)) {\n const [a, b] = edges as [OwnedEdge, OwnedEdge];\n const { synthetic, rewrites } = materialiseM2M(\n a,\n b,\n relationName,\n entities,\n logger,\n );\n syntheticEntities.push(synthetic);\n for (const { owner, relation } of rewrites) {\n push(owner, relation);\n }\n continue;\n }\n\n for (const { owner, edge } of edges) {\n const back = edges.find((e) => e.edge !== edge)?.edge;\n push(owner, normalRelation(edge, back));\n }\n }\n\n return { relations, syntheticEntities };\n}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O,EAAE,MAAM;AACjB;;;AJhMO,IAAM,mBAAe,4BAAa;AAAA,EACvC,MAAM;AAAA,EACN,eAAe;AAAA,EAEf,MAAM,MAAM,KAAmB,SAA4B;AACzD,UAAM,QAAQ,MAAM,aAAa,IAAI,KAAK,SAAS,IAAI,SAAS;AAEhE,QAAI,MAAM,SAAS,GAAG;AACpB,YAAM,IAAI;AAAA,QACR,IAAI;AAAA,QACJ,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAEA,UAAM,EAAE,OAAO,cAAc,IAAI,MAAM,SAAS,OAAO,GAAG;AAC1D,WAAO;AAAA,MACL,IAAI;AAAA,MACJ;AAAA,MACA,UAAU,aAAa;AAAA,MACvB,IAAI;AAAA,IACN;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,KAAmB,SAA4B;AAG9D,WAAO,KAAC,2BAAQ,IAAI,KAAK,QAAQ,MAAM,CAAC;AAAA,EAC1C;AAAA,EAEA,OAAO,SAAS,SAAS;AAKvB,eAAO,+BAAQ,2BAAQ,SAAS,QAAQ,MAAM,CAAC;AAAA,EACjD;AACF,CAAC;","names":["import_node_path","import_promises","import_node_path","require"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/options.ts","../src/parser.ts","../src/contract/codecs.ts","../src/contract/naming.ts","../src/contract/schema.ts","../src/contract/version.ts","../src/contract/read.ts","../src/detect.ts","../src/dmmf/load.ts","../src/dmmf/read.ts","../src/map/build.ts","../src/map/defaults.ts","../src/map/scalars.ts","../src/map/relations.ts"],"sourcesContent":["/**\n * `@kurotako/parser-prisma` — the Prisma parser driver.\n *\n * Reads a Prisma schema (single file or `prismaSchemaFolder`) through\n * `@prisma/internals`' `getDMMF` and produces a `SourceIR` for `@kurotako/core`.\n * Single entry point: the driver object, its options schema/type, and the error\n * classes.\n */\n\nexport {\n PrismaAmbiguousRelationError,\n PrismaContractError,\n PrismaContractVersionError,\n PrismaDialectError,\n PrismaEntityCollisionError,\n PrismaInputError,\n PrismaPeerMissingError,\n PrismaSchemaError,\n} from './errors.js';\nexport { PrismaParserOptions } from './options.js';\nexport { prismaParser } from './parser.js';\n","/**\n * Prisma-parser error classes. Each extends `TakoError` from `@kurotako/core`\n * so the CLI's single `instanceof TakoError` catch covers them; `@kurotako/core`\n * additionally wraps any throw from `parse()` as a `DriverError`.\n *\n * Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema`,\n * `prisma_contract`, `prisma_contract_version`, `prisma_dialect`, and\n * `prisma_entity_collision`.\n */\nimport { TakoError } from '@kurotako/core';\n\n/** Schema path missing, an empty folder, or a folder with no `.prisma` file. */\nexport class PrismaInputError extends TakoError {\n readonly namespace: string;\n readonly resolvedPath: string;\n\n constructor(namespace: string, resolvedPath: string, detail: string) {\n super(\n 'prisma_input',\n `prisma parser (namespace '${namespace}'): ${detail} (resolved path: ${resolvedPath})`,\n );\n this.namespace = namespace;\n this.resolvedPath = resolvedPath;\n }\n}\n\n/** `@prisma/internals` cannot be resolved from the project. */\nexport class PrismaPeerMissingError extends TakoError {\n readonly namespace: string;\n\n constructor(namespace: string, options?: { cause?: unknown }) {\n super(\n 'prisma_peer_missing',\n `prisma parser (namespace '${namespace}'): '@prisma/internals' could not be resolved. ` +\n 'Add it as a devDependency (`bun add -d @prisma/internals`, matching your Prisma major). ' +\n 'In a monorepo it is resolved from the directory holding the schema, so it may ' +\n 'be installed in the sub-project that owns the schema rather than at the repo root. ' +\n 'Note: installing it pulls @prisma/engines, whose postinstall downloads a schema-engine binary.',\n options,\n );\n this.namespace = namespace;\n }\n}\n\n/** `getDMMF` threw — an invalid schema. Carries the Prisma message and `cause`. */\nexport class PrismaSchemaError extends TakoError {\n readonly namespace: string;\n readonly prismaMessage: string;\n\n constructor(\n namespace: string,\n prismaMessage: string,\n options?: { cause?: unknown },\n ) {\n super(\n 'prisma_schema',\n `prisma parser (namespace '${namespace}'): the Prisma schema is invalid:\\n${prismaMessage}`,\n options,\n );\n this.namespace = namespace;\n this.prismaMessage = prismaMessage;\n }\n}\n\n/** A Prisma 8 contract is invalid JSON or does not have the expected shape. */\nexport class PrismaContractError extends TakoError {\n constructor(detail: string, options?: { cause?: unknown }) {\n super(\n 'prisma_contract',\n `invalid Prisma 8 contract.json: ${detail}`,\n options,\n );\n }\n}\n\n/** The contract schema version is not one this parser understands. */\nexport class PrismaContractVersionError extends TakoError {\n readonly found: string;\n\n constructor(found: string, expected: readonly string[]) {\n super(\n 'prisma_contract_version',\n `unsupported Prisma contract schemaVersion '${found}' (expected one of: ${expected.join(', ')})`,\n );\n this.found = found;\n }\n}\n\n/** A contract codec belongs to a database dialect kurotako does not support. */\nexport class PrismaDialectError extends TakoError {\n readonly codecId: string;\n\n constructor(codecId: string) {\n const dialect = codecId.split('/')[0] ?? codecId;\n super(\n 'prisma_dialect',\n `unsupported Prisma contract dialect '${dialect}' in codec '${codecId}'; only PostgreSQL contracts are supported currently`,\n );\n this.codecId = codecId;\n }\n}\n\n/** Multiple namespace-qualified models resolve to the same IR entity name. */\nexport class PrismaEntityCollisionError extends TakoError {\n readonly entityName: string;\n readonly models: readonly string[];\n\n constructor(entityName: string, models: readonly string[]) {\n super(\n 'prisma_entity_collision',\n `Prisma contract models ${models.join(', ')} resolve to the same entity name '${entityName}'`,\n );\n this.entityName = entityName;\n this.models = models;\n }\n}\n\n/** Prisma emitted a relation to a homonym model whose namespace is unreliable. */\nexport class PrismaAmbiguousRelationError extends TakoError {\n constructor(modelName: string) {\n super(\n 'prisma_ambiguous_relation',\n `Prisma contract relation targets '${modelName}', which exists in multiple namespaces; Prisma 8 RC does not resolve this reliably`,\n );\n }\n}\n","/**\n * Valibot schema for `@kurotako/parser-prisma`'s `options`, plus the inferred\n * type. `@kurotako/config` validates a config entry's `options` against this\n * schema and curries it away before `@kurotako/core` sees the parser.\n *\n * `schema` is resolved against `ParseContext.cwd`. `version` forces the\n * version-mode (see `detect.ts`); omitted, the mode is inferred from the input.\n */\nimport * as v from 'valibot';\n\n// `strictObject`: an unknown key (a typo like `schemaPath`) is a hard error\n// rather than being silently dropped.\nexport const PrismaParserOptions = v.strictObject({\n schema: v.optional(v.string(), './prisma/schema.prisma'),\n version: v.optional(v.picklist([7, 8])),\n namespacePrefix: v.optional(v.record(v.string(), v.string())),\n rename: v.optional(v.record(v.string(), v.string())),\n});\n\nexport type PrismaParserOptions = v.InferOutput<typeof PrismaParserOptions>;\n","/**\n * `prismaParser` — the `@kurotako/parser-prisma` driver.\n *\n * `@kurotako/config` validates `options` against `optionsSchema` and curries it\n * away; `@kurotako/core` then calls `parse(ctx)` once per namespace and runs\n * `validateSourceIR` on the result.\n *\n * Flow: `resolveInput` (detect.ts) → `readDmmf` (dmmf/, Prisma <= 7) →\n * `buildSourceIR` (map/). The Prisma 8 `contract.json` mode is detected but not\n * implemented in v1.\n */\nimport { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { defineParser } from '@kurotako/config';\nimport type { ParseContext } from '@kurotako/core';\nimport type { SourceIR } from '@kurotako/ir';\nimport { readContract } from './contract/read.js';\nimport { resolveInput } from './detect.js';\nimport { readDmmf } from './dmmf/load.js';\nimport { buildSourceIR } from './map/build.js';\nimport { PrismaParserOptions } from './options.js';\n\nexport const prismaParser = defineParser({\n name: 'prisma',\n optionsSchema: PrismaParserOptions,\n\n async parse(ctx: ParseContext, options): Promise<SourceIR> {\n const input = await resolveInput(ctx.cwd, options, ctx.namespace);\n\n if (input.mode === 8) {\n const raw = await readFile(input.contractPath, 'utf8');\n const { model, generatorVersion } = readContract(raw, ctx, options);\n return buildSourceIR(\n ctx.namespace,\n model,\n `prisma-contract@${generatorVersion}`,\n ctx.logger,\n );\n }\n\n if (options.namespacePrefix) {\n ctx.logger.warn(\n 'prisma parser: namespacePrefix is ignored in Prisma 7 mode',\n );\n }\n const { model, prismaVersion } = await readDmmf(input, ctx, options);\n return buildSourceIR(\n ctx.namespace,\n model,\n `prisma@${prismaVersion}`,\n ctx.logger,\n );\n },\n\n async watchPaths(ctx: ParseContext, options): Promise<string[]> {\n // The resolved schema path — a `.prisma` file, a schema folder, or the\n // deferred contract.json. A folder watch covers every `*.prisma` inside it.\n return [resolve(ctx.cwd, options.schema)];\n },\n\n anchor(rootDir, options) {\n // The directory the schema lives in. `dirname` is correct for a `.prisma`\n // file and for a `contract.json`; for a schema *folder* it yields the\n // parent, which is still a valid walk-up base for `node_modules`\n // resolution. No `stat` — the hook stays cheap.\n return dirname(resolve(rootDir, options.schema));\n },\n});\n","import type { Logger } from '@kurotako/core';\nimport type { FieldType, ScalarType, StringFormat } from '@kurotako/ir';\nimport { PrismaDialectError } from '../errors.js';\n\nexport interface MappedCodec {\n type: FieldType;\n scalarOverride?: ScalarType;\n format?: StringFormat;\n needsLength?: boolean;\n}\n\ninterface CodecEntry {\n scalar: ScalarType;\n format?: StringFormat;\n needsLength?: boolean;\n}\n\nconst CODECS: Record<string, CodecEntry> = {\n 'pg/text': { scalar: 'string' },\n 'pg/text-array': { scalar: 'string' },\n 'pg/varchar': { scalar: 'string', needsLength: true },\n 'sql/varchar': { scalar: 'string', needsLength: true },\n 'pg/char': { scalar: 'string' },\n 'pg/bpchar': { scalar: 'string' },\n 'pg/bool': { scalar: 'boolean' },\n 'pg/int': { scalar: 'int' },\n 'pg/int2': { scalar: 'int' },\n 'pg/int4': { scalar: 'int' },\n 'pg/int8': { scalar: 'bigint' },\n 'pg/int8number': { scalar: 'int' },\n 'pg/unboundedint': { scalar: 'bigint' },\n 'pg/float': { scalar: 'float' },\n 'pg/float4': { scalar: 'float' },\n 'pg/float8': { scalar: 'float' },\n 'pg/numeric': { scalar: 'decimal' },\n 'pg/uuid': { scalar: 'uuid' },\n 'pg/timestamp-string': { scalar: 'datetime' },\n 'pg/timestamp-temporal': { scalar: 'datetime' },\n 'pg/timestamptz-string': { scalar: 'datetime' },\n 'pg/timestamptz-temporal': { scalar: 'datetime' },\n 'pg/date-string': { scalar: 'date' },\n 'pg/date-temporal': { scalar: 'date' },\n 'pg/time-string': { scalar: 'datetime', format: 'time' },\n 'pg/time-temporal': { scalar: 'datetime', format: 'time' },\n 'pg/timetz': { scalar: 'datetime', format: 'time' },\n 'pg/json': { scalar: 'json' },\n 'pg/jsonb': { scalar: 'json' },\n 'pg/bytea': { scalar: 'bytes' },\n};\n\nfunction splitCodec(codecId: string): { name: string; version?: string } {\n const at = codecId.lastIndexOf('@');\n return at === -1\n ? { name: codecId }\n : { name: codecId.slice(0, at), version: codecId.slice(at + 1) };\n}\n\nexport function mapCodec(codecId: string, logger?: Logger): MappedCodec {\n const { name, version } = splitCodec(codecId);\n if (version !== undefined) {\n logger?.debug(`prisma parser: contract codec '${name}' version ${version}`);\n }\n const entry = CODECS[name];\n if (entry) {\n return {\n type: { kind: 'scalar', scalar: entry.scalar },\n ...(entry.format !== undefined ? { format: entry.format } : {}),\n ...(entry.needsLength ? { needsLength: true } : {}),\n };\n }\n // `sql/varchar` is a target-family codec emitted by the PostgreSQL contract.\n if (!name.startsWith('pg/') && !name.startsWith('sql/')) {\n throw new PrismaDialectError(codecId);\n }\n logger?.debug(`prisma parser: unknown contract codec '${codecId}'`);\n return { type: { kind: 'unknown', hint: codecId } };\n}\n","import { PrismaEntityCollisionError } from '../errors.js';\nimport type { PrismaParserOptions } from '../options.js';\n\nexport interface ContractModelName {\n namespace: string;\n name: string;\n}\n\nexport function resolveNames(\n models: readonly ContractModelName[],\n options: Pick<PrismaParserOptions, 'namespacePrefix' | 'rename'>,\n): Map<string, string> {\n const names = new Map<string, string>();\n const collisions = new Map<string, string[]>();\n for (const { namespace, name } of models) {\n const key = `${namespace}.${name}`;\n const target =\n options.rename?.[key] ??\n `${options.namespacePrefix?.[namespace] ?? ''}${name}`;\n names.set(key, target);\n const entries = collisions.get(target) ?? [];\n entries.push(key);\n collisions.set(target, entries);\n }\n for (const [target, modelsForTarget] of collisions) {\n if (modelsForTarget.length > 1) {\n throw new PrismaEntityCollisionError(target, modelsForTarget);\n }\n }\n return names;\n}\n","import * as v from 'valibot';\nimport { PrismaContractError } from '../errors.js';\n\nconst scalarType = v.looseObject({\n kind: v.literal('scalar'),\n codecId: v.string(),\n typeParams: v.optional(v.looseObject({ length: v.optional(v.number()) })),\n});\n\nconst valueObjectType = v.looseObject({\n kind: v.literal('valueObject'),\n name: v.string(),\n});\n\nconst field = v.looseObject({\n nullable: v.boolean(),\n many: v.optional(v.boolean()),\n type: v.union([scalarType, valueObjectType]),\n valueSet: v.optional(v.looseObject({ entityName: v.string() })),\n});\n\nconst relation = v.looseObject({\n cardinality: v.picklist(['1:1', '1:N', 'N:1', 'N:M']),\n to: v.looseObject({ namespace: v.string(), model: v.string() }),\n on: v.looseObject({\n localFields: v.array(v.string()),\n targetFields: v.array(v.string()),\n }),\n});\n\nconst model = v.looseObject({\n fields: v.record(v.string(), field),\n relations: v.optional(v.record(v.string(), relation)),\n storage: v.looseObject({\n table: v.string(),\n namespaceId: v.string(),\n fields: v.record(v.string(), v.looseObject({ column: v.string() })),\n }),\n});\n\nconst enumDef = v.looseObject({\n members: v.array(v.looseObject({ name: v.string(), value: v.string() })),\n});\n\nconst column = v.looseObject({\n codecId: v.string(),\n nullable: v.boolean(),\n many: v.optional(v.boolean()),\n default: v.optional(\n v.looseObject({\n kind: v.picklist(['function', 'literal']),\n expression: v.optional(v.string()),\n value: v.optional(\n v.union([\n v.string(),\n v.number(),\n v.boolean(),\n v.array(v.union([v.string(), v.number(), v.boolean()])),\n ]),\n ),\n }),\n ),\n});\n\nconst table = v.looseObject({\n columns: v.record(v.string(), column),\n primaryKey: v.optional(v.looseObject({ columns: v.array(v.string()) })),\n uniques: v.optional(\n v.array(\n v.looseObject({\n columns: v.array(v.string()),\n name: v.optional(v.string()),\n }),\n ),\n ),\n indexes: v.optional(\n v.array(\n v.looseObject({\n columns: v.array(v.string()),\n name: v.optional(v.string()),\n type: v.optional(v.string()),\n }),\n ),\n ),\n foreignKeys: v.optional(\n v.array(\n v.looseObject({\n source: v.looseObject({ columns: v.array(v.string()) }),\n onDelete: v.optional(v.string()),\n onUpdate: v.optional(v.string()),\n }),\n ),\n ),\n});\n\nexport const ContractSchema = v.looseObject({\n schemaVersion: v.string(),\n target: v.string(),\n targetFamily: v.string(),\n domain: v.looseObject({\n namespaces: v.record(\n v.string(),\n v.looseObject({\n models: v.record(v.string(), model),\n enum: v.optional(v.record(v.string(), enumDef)),\n }),\n ),\n }),\n storage: v.looseObject({\n namespaces: v.record(\n v.string(),\n v.looseObject({\n entries: v.looseObject({\n table: v.optional(v.record(v.string(), table)),\n valueSet: v.optional(\n v.record(\n v.string(),\n v.looseObject({ values: v.array(v.string()) }),\n ),\n ),\n }),\n }),\n ),\n }),\n execution: v.optional(\n v.looseObject({\n mutations: v.optional(\n v.looseObject({\n defaults: v.optional(\n v.array(\n v.looseObject({\n ref: v.looseObject({\n namespace: v.string(),\n table: v.string(),\n column: v.string(),\n }),\n onCreate: v.optional(\n v.looseObject({ kind: v.string(), id: v.string() }),\n ),\n onUpdate: v.optional(\n v.looseObject({ kind: v.string(), id: v.string() }),\n ),\n }),\n ),\n ),\n }),\n ),\n }),\n ),\n});\n\nexport type Contract = v.InferOutput<typeof ContractSchema>;\n\nfunction issuePath(err: unknown): string {\n if (err instanceof v.ValiError) {\n return err.issues\n .map(\n (issue) =>\n issue.path\n ?.map((part: { key: unknown }) => String(part.key))\n .join('.') ?? '<root>',\n )\n .join(', ');\n }\n return '<root>';\n}\n\nexport function parseContract(raw: string): Contract {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (err) {\n throw new PrismaContractError('invalid JSON', { cause: err });\n }\n try {\n return v.parse(ContractSchema, value);\n } catch (err) {\n throw new PrismaContractError(`invalid structure at ${issuePath(err)}`, {\n cause: err,\n });\n }\n}\n","import { PrismaContractVersionError } from '../errors.js';\n\nexport const SUPPORTED_SCHEMA_VERSIONS = new Set(['1']);\n\nexport function assertSupportedVersion(found: string): void {\n if (!SUPPORTED_SCHEMA_VERSIONS.has(found)) {\n throw new PrismaContractVersionError(found, [...SUPPORTED_SCHEMA_VERSIONS]);\n }\n}\n","import type { ParseContext } from '@kurotako/core';\nimport type {\n PrismaDefault,\n PrismaEntity,\n PrismaEnum,\n PrismaField,\n PrismaModel,\n PrismaRelationEdge,\n} from '../dmmf/model.js';\nimport { PrismaAmbiguousRelationError } from '../errors.js';\nimport type { PrismaParserOptions } from '../options.js';\nimport { mapCodec } from './codecs.js';\nimport { resolveNames } from './naming.js';\nimport { parseContract } from './schema.js';\nimport { assertSupportedVersion } from './version.js';\n\ntype RawRecord = Record<string, unknown>;\n\nfunction record(value: unknown): RawRecord {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as RawRecord)\n : {};\n}\n\nfunction strings(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction storageTable(\n contract: RawRecord,\n namespace: string,\n tableName: string,\n): RawRecord {\n const namespaces = record(record(contract.storage).namespaces);\n const entries = record(record(namespaces[namespace]).entries);\n return record(record(entries.table)[tableName]);\n}\n\nfunction defaultValue(value: unknown): PrismaDefault | undefined {\n const raw = record(value);\n if (raw.kind === 'literal') {\n return raw.value as PrismaDefault;\n }\n if (raw.kind === 'function' && typeof raw.expression === 'string') {\n const expression = raw.expression;\n const match = /^(\\\\w+)\\\\((.*)\\\\)$/.exec(expression);\n return match\n ? { name: match[1] ?? expression, args: [] }\n : { name: expression, args: [] };\n }\n return undefined;\n}\n\nfunction generatorDefault(\n contract: RawRecord,\n namespace: string,\n table: string,\n column: string,\n): RawRecord | undefined {\n const defaults = record(\n record(record(contract.execution).mutations).defaults,\n );\n if (!Array.isArray(defaults)) return undefined;\n return defaults.map(record).find((entry) => {\n const ref = record(entry.ref);\n return (\n ref.namespace === namespace &&\n ref.table === table &&\n ref.column === column\n );\n });\n}\n\nfunction readField(\n name: string,\n raw: RawRecord,\n storageColumn: RawRecord,\n generator: RawRecord | undefined,\n logger: ParseContext['logger'],\n): PrismaField {\n const type = record(raw.type);\n if (type.kind === 'valueObject') {\n return {\n name,\n type: typeof type.name === 'string' ? type.name : 'valueObject',\n kind: 'unsupported',\n isList: raw.many === true,\n isRequired: raw.nullable !== true,\n isUnique: false,\n isUpdatedAt: false,\n hasDefaultValue:\n generator !== undefined || storageColumn.default !== undefined,\n nativeType: null,\n };\n }\n const codecId = String(type.codecId);\n const mapped = mapCodec(codecId, logger);\n const valueSet = record(raw.valueSet);\n const isEnum = typeof valueSet.entityName === 'string';\n const typeParams = record(type.typeParams);\n const maxLength =\n mapped.needsLength && typeof typeParams.length === 'number'\n ? typeParams.length\n : undefined;\n const field: PrismaField = {\n name,\n type: isEnum ? String(valueSet.entityName) : codecId,\n kind: isEnum ? 'enum' : 'scalar',\n isList: raw.many === true,\n isRequired: raw.nullable !== true,\n isUnique: false,\n isUpdatedAt: record(generator?.onUpdate).id === 'instantNow',\n hasDefaultValue:\n generator !== undefined || storageColumn.default !== undefined,\n nativeType: null,\n };\n if (isEnum) return field;\n field.mappedType = mapped.type;\n field.scalarOverride = mapped.scalarOverride;\n field.format = mapped.format;\n field.maxLength = maxLength;\n const parsedDefault = defaultValue(storageColumn.default);\n if (parsedDefault !== undefined) field.default = parsedDefault;\n return field;\n}\n\nfunction readRelationEdges(\n relations: RawRecord,\n names: Map<string, string>,\n sourceName: string,\n table: RawRecord,\n): PrismaRelationEdge[] {\n const foreignKeys = Array.isArray(table.foreignKeys)\n ? table.foreignKeys.map(record)\n : [];\n return Object.entries(relations).map(([fieldName, relation]) => {\n const raw = record(relation);\n const to = record(raw.to);\n const on = record(raw.on);\n const localFields = strings(on.localFields);\n const targetFields = strings(on.targetFields);\n const fk = foreignKeys.find((candidate) => {\n const source = record(candidate.source);\n return (\n JSON.stringify(strings(source.columns)) === JSON.stringify(localFields)\n );\n });\n const targetKey = `${String(to.namespace)}.${String(to.model)}`;\n const cardinality = raw.cardinality;\n const edge: PrismaRelationEdge = {\n fieldName,\n relationName:\n [sourceName, String(to.model)].sort().join(':') +\n `:${[...localFields, ...targetFields].sort().join(',')}`,\n targetEntity: names.get(targetKey) ?? String(to.model),\n isList: cardinality === '1:N' || cardinality === 'N:M',\n isRequired: cardinality !== '1:N' && cardinality !== 'N:M',\n fromFields: fk ? localFields : [],\n toFields: fk ? targetFields : [],\n };\n if (typeof fk?.onDelete === 'string') edge.onDelete = fk.onDelete;\n if (typeof fk?.onUpdate === 'string') edge.onUpdate = fk.onUpdate;\n return edge;\n });\n}\n\nexport function readContract(\n raw: string,\n ctx: ParseContext,\n options: Pick<PrismaParserOptions, 'namespacePrefix' | 'rename'>,\n): { model: PrismaModel; generatorVersion: string } {\n const parsed = parseContract(raw);\n assertSupportedVersion(parsed.schemaVersion);\n const contract = parsed as unknown as RawRecord;\n const namespaces = record(record(contract.domain).namespaces);\n const models = Object.entries(namespaces).flatMap(\n ([namespace, rawNamespace]) =>\n Object.keys(record(record(rawNamespace).models)).map((name) => ({\n namespace,\n name,\n })),\n );\n const modelCounts = new Map<string, number>();\n for (const model of models) {\n modelCounts.set(model.name, (modelCounts.get(model.name) ?? 0) + 1);\n }\n for (const rawNamespace of Object.values(namespaces)) {\n for (const rawModel of Object.values(record(record(rawNamespace).models))) {\n for (const relation of Object.values(\n record(record(rawModel).relations),\n )) {\n const target = record(record(relation).to);\n if (\n typeof target.model === 'string' &&\n (modelCounts.get(target.model) ?? 0) > 1\n ) {\n throw new PrismaAmbiguousRelationError(target.model);\n }\n }\n }\n }\n const names = resolveNames(models, options);\n const entities: PrismaEntity[] = [];\n const enums: PrismaEnum[] = [];\n for (const [namespace, rawNamespace] of Object.entries(namespaces)) {\n const namespaceData = record(rawNamespace);\n const modelDefs = record(namespaceData.models);\n for (const [sourceName, rawModel] of Object.entries(modelDefs)) {\n const model = record(rawModel);\n const bridge = record(model.storage);\n const tableName = String(bridge.table);\n const table = storageTable(\n contract,\n String(bridge.namespaceId),\n tableName,\n );\n const columns = record(table.columns);\n const bridgeFields = record(bridge.fields);\n const fields = Object.entries(record(model.fields)).map(\n ([name, rawField]) => {\n const column = String(record(bridgeFields[name]).column);\n return readField(\n name,\n record(rawField),\n record(columns[column]),\n generatorDefault(\n contract,\n String(bridge.namespaceId),\n tableName,\n column,\n ),\n ctx.logger,\n );\n },\n );\n const uniqueColumns = new Set(\n (Array.isArray(table.uniques) ? table.uniques : []).flatMap((entry) =>\n strings(record(entry).columns),\n ),\n );\n for (const field of fields)\n field.isUnique = uniqueColumns.has(field.name);\n const entity: PrismaEntity = {\n name: names.get(`${namespace}.${sourceName}`) ?? sourceName,\n dbName: tableName === sourceName ? undefined : tableName,\n fields,\n relationEdges: readRelationEdges(\n record(model.relations),\n names,\n sourceName,\n table,\n ),\n primaryKey: strings(record(table.primaryKey).columns),\n uniques: (Array.isArray(table.uniques) ? table.uniques : []).map(\n (entry) => ({\n fields: strings(record(entry).columns),\n ...(typeof record(entry).name === 'string'\n ? { name: String(record(entry).name) }\n : {}),\n }),\n ),\n indexes: (Array.isArray(table.indexes) ? table.indexes : []).map(\n (entry) => ({\n fields: strings(record(entry).columns),\n ...(typeof record(entry).name === 'string'\n ? { name: String(record(entry).name) }\n : {}),\n ...(typeof record(entry).type === 'string'\n ? { type: String(record(entry).type) }\n : {}),\n }),\n ),\n };\n entities.push(entity);\n }\n for (const [name, rawEnum] of Object.entries(record(namespaceData.enum))) {\n const members: unknown[] = Array.isArray(record(rawEnum).members)\n ? (record(rawEnum).members as unknown[])\n : [];\n enums.push({\n name,\n values: members.map((member) => {\n const value = record(member);\n return {\n name: String(value.name),\n ...(String(value.value) !== String(value.name)\n ? { dbName: String(value.value) }\n : {}),\n };\n }),\n });\n }\n }\n return { model: { entities, enums }, generatorVersion: parsed.schemaVersion };\n}\n","/**\n * Input resolution and version-mode detection.\n *\n * `resolveInput` turns `options.schema` (a `.prisma` file, a\n * `prismaSchemaFolder`, or — deferred — a `contract.json`) into a\n * `ResolvedInput`: the concrete file tuples for the Prisma <= 7 DMMF path, or\n * the `contract.json` path for the deferred Prisma 8 path.\n *\n * `options.version` forces the mode; otherwise it is inferred from what is on\n * disk. Multi-file Prisma schemas are read transparently.\n */\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport { PrismaInputError } from './errors.js';\nimport type { PrismaParserOptions } from './options.js';\n\nexport type ResolvedInput =\n | { mode: 7; kind: 'file' | 'folder'; files: Array<[string, string]> }\n | { mode: 8; kind: 'contract'; contractPath: string };\n\nconst PRISMA_EXT = '.prisma';\nconst CONTRACT_FILE = 'contract.json';\n\nfunction toPosix(p: string): string {\n return sep === '/' ? p : p.split(sep).join('/');\n}\n\nasync function pathKind(p: string): Promise<'file' | 'dir' | 'missing'> {\n try {\n const s = await stat(p);\n return s.isDirectory() ? 'dir' : 'file';\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return 'missing';\n }\n throw err;\n }\n}\n\n/** `*.prisma` directly in `dir`, then one level down (prismaSchemaFolder layout). */\nasync function collectPrismaFiles(dir: string): Promise<string[]> {\n const found: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isFile() && entry.name.endsWith(PRISMA_EXT)) {\n found.push(full);\n } else if (entry.isDirectory()) {\n const nested = await readdir(full, { withFileTypes: true });\n for (const child of nested) {\n if (child.isFile() && child.name.endsWith(PRISMA_EXT)) {\n found.push(join(full, child.name));\n }\n }\n }\n }\n return found;\n}\n\nasync function dirHasContract(dir: string): Promise<boolean> {\n return (await pathKind(join(dir, CONTRACT_FILE))) === 'file';\n}\n\nasync function readTuples(\n root: string,\n files: string[],\n): Promise<Array<[string, string]>> {\n const tuples = await Promise.all(\n files.map(\n async (file): Promise<[string, string]> => [\n toPosix(relative(root, file)),\n await readFile(file, 'utf8'),\n ],\n ),\n );\n return tuples.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nasync function resolveMode7(\n namespace: string,\n resolved: string,\n kind: 'file' | 'dir',\n): Promise<ResolvedInput> {\n if (kind === 'file') {\n return {\n mode: 7,\n kind: 'file',\n files: await readTuples(dirname(resolved), [resolved]),\n };\n }\n const files = await collectPrismaFiles(resolved);\n if (files.length === 0) {\n throw new PrismaInputError(\n namespace,\n resolved,\n 'the schema folder contains no .prisma file',\n );\n }\n return { mode: 7, kind: 'folder', files: await readTuples(resolved, files) };\n}\n\nasync function resolveMode8(\n namespace: string,\n resolved: string,\n kind: 'file' | 'dir',\n): Promise<ResolvedInput> {\n if (kind === 'dir') {\n const contractPath = join(resolved, CONTRACT_FILE);\n if ((await pathKind(contractPath)) !== 'file') {\n throw new PrismaInputError(\n namespace,\n resolved,\n `version 8 mode expects a ${CONTRACT_FILE} in the folder`,\n );\n }\n return { mode: 8, kind: 'contract', contractPath };\n }\n return { mode: 8, kind: 'contract', contractPath: resolved };\n}\n\nexport async function resolveInput(\n cwd: string,\n o: PrismaParserOptions,\n namespace = '<unknown>',\n): Promise<ResolvedInput> {\n const resolved = resolve(cwd, o.schema);\n const kind = await pathKind(resolved);\n if (kind === 'missing') {\n throw new PrismaInputError(\n namespace,\n resolved,\n 'the schema path does not exist',\n );\n }\n\n if (o.version === 8) {\n return resolveMode8(namespace, resolved, kind);\n }\n if (o.version === 7) {\n return resolveMode7(namespace, resolved, kind);\n }\n\n // Infer.\n if (kind === 'file') {\n if (basename(resolved) === CONTRACT_FILE) {\n return { mode: 8, kind: 'contract', contractPath: resolved };\n }\n if (resolved.endsWith(PRISMA_EXT)) {\n return resolveMode7(namespace, resolved, 'file');\n }\n throw new PrismaInputError(\n namespace,\n resolved,\n `not a .prisma file or a ${CONTRACT_FILE}`,\n );\n }\n\n if (await dirHasContract(resolved)) {\n return resolveMode8(namespace, resolved, 'dir');\n }\n return resolveMode7(namespace, resolved, 'dir');\n}\n","/**\n * Prisma <= 7 DMMF acquisition.\n *\n * `@prisma/internals` is an optional peer: it is resolved dynamically from the\n * consumer's project (`ctx.cwd`), not bundled. A resolution failure is a\n * `PrismaPeerMissingError` with an install hint; a `getDMMF` throw (invalid\n * schema) is a `PrismaSchemaError` keeping the Prisma P1012 text and `cause`.\n *\n * The package is CJS-only and its ESM-interop is unreliable, so the `getDMMF`\n * function is looked up on both the namespace and its `default`.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { ParseContext } from '@kurotako/core';\nimport type { ResolvedInput } from '../detect.js';\nimport { PrismaPeerMissingError, PrismaSchemaError } from '../errors.js';\nimport type { PrismaParserOptions } from '../options.js';\nimport type { PrismaModel } from './model.js';\nimport { toPrismaModel } from './read.js';\n\ntype SchemaFileInput = string | Array<[string, string]>;\ntype GetDmmf = (options: {\n datamodel: SchemaFileInput;\n}) => Promise<import('@prisma/dmmf').Document>;\n\ninterface InternalsModule {\n getDMMF?: GetDmmf;\n default?: { getDMMF?: GetDmmf };\n}\n\nasync function resolveInternals(\n ctx: ParseContext,\n): Promise<{ getDMMF: GetDmmf; prismaVersion: string }> {\n // Resolve `@prisma/internals` from the source's anchor directory (where its\n // schema lives) so it can be a devDependency of the sub-project holding the\n // schema, not only of the repo root. Node still walks up `node_modules` from\n // there to `ctx.cwd` and beyond. Absent ⇒ anchor on `ctx.cwd`.\n const base = ctx.anchorDir ?? ctx.cwd;\n const require = createRequire(join(base, 'noop.js'));\n\n let entry: string;\n try {\n entry = require.resolve('@prisma/internals');\n } catch (err) {\n throw new PrismaPeerMissingError(ctx.namespace, { cause: err });\n }\n\n let mod: InternalsModule;\n try {\n mod = (await import(pathToFileURL(entry).href)) as InternalsModule;\n } catch (err) {\n throw new PrismaPeerMissingError(ctx.namespace, { cause: err });\n }\n\n const getDMMF = mod.default?.getDMMF ?? mod.getDMMF;\n if (typeof getDMMF !== 'function') {\n throw new PrismaPeerMissingError(ctx.namespace);\n }\n\n let prismaVersion = 'unknown';\n try {\n const pkg = JSON.parse(\n await readFile(require.resolve('@prisma/internals/package.json'), 'utf8'),\n ) as { version?: string };\n if (typeof pkg.version === 'string') {\n prismaVersion = pkg.version;\n }\n } catch {\n ctx.logger.debug(\n 'prisma parser: could not read @prisma/internals version',\n { namespace: ctx.namespace },\n );\n }\n\n return { getDMMF, prismaVersion };\n}\n\nexport async function readDmmf(\n input: Extract<ResolvedInput, { mode: 7 }>,\n ctx: ParseContext,\n options?: Pick<PrismaParserOptions, 'rename'>,\n): Promise<{ model: PrismaModel; prismaVersion: string }> {\n const { getDMMF, prismaVersion } = await resolveInternals(ctx);\n\n const datamodel: SchemaFileInput =\n input.kind === 'file'\n ? (input.files[0]?.[1] ?? '')\n : input.files.map(([path, content]) => [path, content]);\n\n let doc: Awaited<ReturnType<GetDmmf>>;\n try {\n doc = await getDMMF({ datamodel });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new PrismaSchemaError(ctx.namespace, message, { cause: err });\n }\n\n return { model: toPrismaModel(doc, options), prismaVersion };\n}\n","/**\n * `DMMF.Document` → the mode-neutral `PrismaModel`.\n *\n * Pure and total: it never touches disk or Prisma. Object fields become\n * `relationEdges`; scalar / enum / unsupported fields become `fields`. Model and\n * enum `documentation` / `dbName` are carried verbatim. Non-unique `@@index`\n * entries come from `datamodel.indexes` when the resolved `@prisma/internals`\n * exposes them (6.x does), otherwise `indexes` stays empty.\n */\nimport type * as DMMF from '@prisma/dmmf';\nimport type { PrismaParserOptions } from '../options.js';\nimport type {\n PrismaDefault,\n PrismaEntity,\n PrismaEnum,\n PrismaField,\n PrismaIndex,\n PrismaModel,\n PrismaRelationEdge,\n PrismaUnique,\n} from './model.js';\n\nfunction readField(f: DMMF.Field): PrismaField {\n const field: PrismaField = {\n name: f.name,\n type: f.type,\n kind:\n f.kind === 'enum'\n ? 'enum'\n : f.kind === 'unsupported'\n ? 'unsupported'\n : 'scalar',\n isList: f.isList,\n isRequired: f.isRequired,\n isUnique: f.isUnique,\n isUpdatedAt: f.isUpdatedAt ?? false,\n hasDefaultValue: f.hasDefaultValue,\n nativeType: f.nativeType ? [f.nativeType[0], [...f.nativeType[1]]] : null,\n };\n if (f.default !== undefined) {\n field.default = f.default as PrismaDefault;\n }\n if (f.documentation !== undefined) {\n field.doc = f.documentation;\n }\n return field;\n}\n\nfunction readEdge(f: DMMF.Field): PrismaRelationEdge {\n const edge: PrismaRelationEdge = {\n fieldName: f.name,\n relationName: f.relationName ?? '',\n targetEntity: f.type,\n isList: f.isList,\n isRequired: f.isRequired,\n fromFields: [...(f.relationFromFields ?? [])],\n toFields: [...(f.relationToFields ?? [])],\n };\n if (f.relationOnDelete !== undefined) {\n edge.onDelete = f.relationOnDelete;\n }\n if (f.relationOnUpdate !== undefined) {\n edge.onUpdate = f.relationOnUpdate;\n }\n return edge;\n}\n\nfunction readPrimaryKey(model: DMMF.Model): string[] {\n if (model.primaryKey && model.primaryKey.fields.length > 0) {\n return [...model.primaryKey.fields];\n }\n const id = model.fields.find((f) => f.isId);\n return id ? [id.name] : [];\n}\n\nfunction readUniques(model: DMMF.Model): PrismaUnique[] {\n if (model.uniqueIndexes.length > 0) {\n return model.uniqueIndexes.map((u) => {\n const entry: PrismaUnique = { fields: [...u.fields] };\n if (u.name) {\n entry.name = u.name;\n }\n return entry;\n });\n }\n return model.uniqueFields.map((fields) => ({ fields: [...fields] }));\n}\n\nfunction readIndexes(\n modelName: string,\n all: readonly DMMF.Index[] | undefined,\n): PrismaIndex[] {\n if (!all) {\n return [];\n }\n return all\n .filter((idx) => idx.model === modelName && idx.type === 'normal')\n .map((idx) => {\n const entry: PrismaIndex = { fields: idx.fields.map((f) => f.name) };\n if (idx.name) {\n entry.name = idx.name;\n }\n if (idx.algorithm) {\n entry.type = idx.algorithm.toLowerCase();\n }\n return entry;\n });\n}\n\nfunction readEntity(model: DMMF.Model, doc: DMMF.Document): PrismaEntity {\n const fields: PrismaField[] = [];\n const relationEdges: PrismaRelationEdge[] = [];\n for (const f of model.fields) {\n if (f.kind === 'object') {\n relationEdges.push(readEdge(f));\n } else {\n fields.push(readField(f));\n }\n }\n const entity: PrismaEntity = {\n name: model.name,\n fields,\n relationEdges,\n primaryKey: readPrimaryKey(model),\n uniques: readUniques(model),\n indexes: readIndexes(model.name, doc.datamodel.indexes),\n };\n if (model.dbName) {\n entity.dbName = model.dbName;\n }\n if (model.documentation !== undefined) {\n entity.doc = model.documentation;\n }\n return entity;\n}\n\nfunction readEnum(e: DMMF.DatamodelEnum): PrismaEnum {\n const def: PrismaEnum = {\n name: e.name,\n values: e.values.map((value) => {\n const entry = { name: value.name } as PrismaEnum['values'][number];\n if (value.dbName) {\n entry.dbName = value.dbName;\n }\n return entry;\n }),\n };\n if (e.dbName) {\n def.dbName = e.dbName;\n }\n if (e.documentation !== undefined) {\n def.doc = e.documentation;\n }\n return def;\n}\n\nexport function toPrismaModel(\n doc: DMMF.Document,\n options?: Pick<PrismaParserOptions, 'rename'>,\n): PrismaModel {\n const result: PrismaModel = {\n entities: doc.datamodel.models.map((m) => readEntity(m, doc)),\n enums: doc.datamodel.enums.map(readEnum),\n };\n if (!options?.rename) {\n return result;\n }\n const names = new Map(\n result.entities.map((entity) => [\n entity.name,\n options.rename?.[entity.name] ?? entity.name,\n ]),\n );\n for (const entity of result.entities) {\n entity.name = names.get(entity.name) ?? entity.name;\n for (const edge of entity.relationEdges) {\n edge.targetEntity = names.get(edge.targetEntity) ?? edge.targetEntity;\n }\n }\n return result;\n}\n","/**\n * `PrismaModel` → `SourceIR`, driven entirely by the `createSourceIR` fluent\n * builder (the parser never hand-assembles IR).\n *\n * Field rules: `list ← isList`, `nullable ← !isRequired`,\n * `optional ← hasDefaultValue || isUpdatedAt`, `unique ← isUnique`. Scalars and\n * native-type refinement come from `map/scalars.ts`, defaults / id `format` from\n * `map/defaults.ts`, relations and implicit-m2m materialisation from\n * `map/relations.ts` (this module injects the namespace into every relation\n * target). Enums are emitted at source level, matching Prisma.\n */\nimport type { Logger } from '@kurotako/core';\nimport type { IndexType } from '@kurotako/ir';\nimport {\n createSourceIR,\n type EntityBuilder,\n type EnumBuilder,\n type FieldBuilder,\n type Relation,\n type SourceIR,\n} from '@kurotako/ir';\nimport type { PrismaEnum, PrismaModel } from '../dmmf/model.js';\nimport { mapDefault } from './defaults.js';\nimport { buildRelations } from './relations.js';\nimport { mapFieldType } from './scalars.js';\n\nconst INDEX_TYPES = new Set<IndexType>([\n 'btree',\n 'hash',\n 'gin',\n 'gist',\n 'brin',\n 'spgist',\n]);\n\nfunction asIndexType(raw: string | undefined): IndexType | undefined {\n return raw !== undefined && INDEX_TYPES.has(raw as IndexType)\n ? (raw as IndexType)\n : undefined;\n}\n\nfunction fillEnum(eb: EnumBuilder, e: PrismaEnum): void {\n for (const value of e.values) {\n const opts: { dbName?: string; doc?: string } = {};\n if (value.dbName !== undefined) {\n opts.dbName = value.dbName;\n }\n if (value.doc !== undefined) {\n opts.doc = value.doc;\n }\n eb.value(value.name, opts);\n }\n if (e.doc !== undefined) {\n eb.doc(e.doc);\n }\n if (e.dbName !== undefined) {\n eb.dbName(e.dbName);\n }\n}\n\nfunction addRelation(\n eb: EntityBuilder,\n rel: Relation,\n namespace: string,\n): void {\n eb.relation(rel.name, (rb) => {\n rb.to(namespace, rel.target.entity);\n if (rel.cardinality === 'many') {\n rb.many();\n } else {\n rb.one();\n }\n if (rel.optional) {\n rb.optional();\n }\n if (rel.owning) {\n rb.owning();\n }\n if (rel.backRelation !== undefined) {\n rb.backRelation(rel.backRelation);\n }\n if (rel.fkFields) {\n rb.fkFields(...rel.fkFields);\n }\n if (rel.references) {\n rb.references(...rel.references);\n }\n if (rel.onDelete) {\n rb.onDelete(rel.onDelete);\n }\n if (rel.onUpdate) {\n rb.onUpdate(rel.onUpdate);\n }\n });\n}\n\nexport function buildSourceIR(\n namespace: string,\n model: PrismaModel,\n parserVersion: string,\n logger?: Logger,\n): SourceIR {\n const b = createSourceIR({ namespace, parser: 'prisma', parserVersion });\n\n for (const e of model.enums) {\n b.addEnum(e.name, (eb) => fillEnum(eb, e));\n }\n\n const { relations, syntheticEntities } = buildRelations(model, logger);\n\n for (const entity of model.entities) {\n b.addEntity(entity.name, (eb) => {\n for (const field of entity.fields) {\n eb.field(field.name, (fb: FieldBuilder) => {\n const mapped = field.mappedType\n ? {\n type: field.mappedType,\n constraints: {\n ...(field.maxLength !== undefined\n ? { maxLength: field.maxLength }\n : {}),\n ...(field.format !== undefined\n ? { format: field.format }\n : {}),\n },\n scalarOverride: field.scalarOverride,\n }\n : mapFieldType(field, logger);\n const scalar =\n mapped.scalarOverride ??\n (mapped.type.kind === 'scalar' ? mapped.type.scalar : undefined);\n\n if (scalar !== undefined) {\n fb.scalar(scalar);\n } else if (mapped.type.kind === 'enum') {\n fb.enum(mapped.type.ref);\n } else {\n fb.unknown(\n mapped.type.kind === 'unknown' ? mapped.type.hint : undefined,\n );\n }\n\n const isString = scalar === 'string';\n const { maxLength, format: nativeFormat } = mapped.constraints;\n if (maxLength !== undefined) {\n fb.maxLength(maxLength);\n }\n\n const mappedDefault = mapDefault(field.default);\n if (mappedDefault.default) {\n fb.default(mappedDefault.default);\n }\n const format = mappedDefault.format ?? nativeFormat;\n if (format !== undefined) {\n if (isString) {\n fb.format(format);\n } else {\n logger?.debug(\n `prisma parser: dropping format '${format}' on non-string field '${entity.name}.${field.name}'`,\n );\n }\n }\n\n if (field.isList) {\n fb.list();\n }\n if (!field.isRequired) {\n fb.nullable();\n }\n if (field.hasDefaultValue || field.isUpdatedAt) {\n fb.optional();\n }\n if (field.isUnique) {\n fb.unique();\n }\n if (field.doc !== undefined) {\n fb.doc(field.doc);\n }\n });\n }\n\n if (entity.primaryKey.length > 0) {\n eb.primaryKey(...entity.primaryKey);\n }\n for (const unique of entity.uniques) {\n eb.unique(\n unique.fields,\n unique.name ? { name: unique.name } : undefined,\n );\n }\n for (const index of entity.indexes) {\n const opts: { name?: string; type?: IndexType } = {};\n if (index.name) {\n opts.name = index.name;\n }\n const type = asIndexType(index.type);\n if (type) {\n opts.type = type;\n }\n eb.index(index.fields, opts);\n }\n if (entity.doc !== undefined) {\n eb.doc(entity.doc);\n }\n if (entity.dbName !== undefined) {\n eb.dbName(entity.dbName);\n }\n for (const rel of relations.get(entity.name) ?? []) {\n addRelation(eb, rel, namespace);\n }\n });\n }\n\n for (const synthetic of syntheticEntities) {\n b.addEntity(synthetic.name, (eb) => {\n for (const field of synthetic.fields) {\n eb.field(field.name, (fb) => fb.scalar(field.scalar));\n }\n eb.primaryKey(...synthetic.primaryKey);\n for (const rel of synthetic.relations) {\n addRelation(eb, rel, namespace);\n }\n });\n }\n\n return b.build();\n}\n","/**\n * Prisma `@default(...)` → IR `DefaultValue`, plus the `StringFormat` a\n * generator-side id default implies.\n *\n * Literals (and enum values, which the DMMF encodes as bare strings) become\n * `{ kind: 'value' }`. Function calls become `{ kind: 'expr' }`; `uuid()` /\n * `cuid()` / `cuid(2)` / `ulid()` additionally carry a `format` (the scalar is\n * left as `string`). `nanoid()` has no matching closed `StringFormat` → expr\n * only.\n */\nimport type { DefaultValue, StringFormat } from '@kurotako/ir';\nimport type { PrismaDefault } from '../dmmf/model.js';\n\nexport interface MappedDefault {\n default?: DefaultValue;\n format?: StringFormat;\n}\n\nconst ID_FORMATS: Record<string, StringFormat> = {\n uuid: 'uuid',\n cuid: 'cuid',\n ulid: 'ulid',\n};\n\nfunction isCall(\n raw: PrismaDefault,\n): raw is { name: string; args: Array<string | number> } {\n return typeof raw === 'object' && !Array.isArray(raw) && raw !== null;\n}\n\nexport function mapDefault(raw: PrismaDefault | undefined): MappedDefault {\n if (raw === undefined) {\n return {};\n }\n\n if (!isCall(raw)) {\n // literal, literal array, or enum value (bare string)\n return { default: { kind: 'value', value: raw } };\n }\n\n const { name, args } = raw;\n\n if (name === 'dbgenerated') {\n return { default: { kind: 'expr', expr: 'dbgenerated', args: [...args] } };\n }\n\n const idFormat = ID_FORMATS[name];\n if (idFormat !== undefined) {\n const format: StringFormat =\n name === 'cuid' && args[0] === 2 ? 'cuid2' : idFormat;\n return { default: { kind: 'expr', expr: `${name}()` }, format };\n }\n\n // now(), autoincrement(), nanoid(), and any other bare call\n return { default: { kind: 'expr', expr: `${name}()` } };\n}\n","/**\n * Prisma field type + native `@db.*` type → IR `FieldType` and `Constraints`.\n *\n * Base scalar mapping is a closed table. Native types refine it: a length\n * argument becomes `maxLength`, `@db.Uuid` / `@db.ObjectId` promote the scalar to\n * `uuid`, `@db.Date` to `date`, `@db.Time` keeps `datetime` but sets\n * `format: 'time'`. Unknown native types are ignored (logged at `debug`).\n */\nimport type { Logger } from '@kurotako/core';\nimport type { Constraints, FieldType, ScalarType } from '@kurotako/ir';\nimport type { PrismaField } from '../dmmf/model.js';\n\nconst SCALAR_TABLE: Record<string, ScalarType> = {\n String: 'string',\n Boolean: 'boolean',\n Int: 'int',\n BigInt: 'bigint',\n Float: 'float',\n Decimal: 'decimal',\n DateTime: 'datetime',\n Json: 'json',\n Bytes: 'bytes',\n};\n\nconst LENGTH_NATIVE = new Set(['VarChar', 'Char', 'NVarChar', 'String']);\nconst UUID_NATIVE = new Set(['Uuid', 'ObjectId']);\n/** Native types that are known and deliberately have no effect in v1. */\nconst NOOP_NATIVE = new Set([\n 'Text',\n 'Citext',\n 'Xml',\n 'Bit',\n 'VarBit',\n 'Inet',\n 'Line',\n 'LongText',\n 'MediumText',\n 'TinyText',\n 'SmallInt',\n 'MediumInt',\n 'UnsignedInt',\n 'UnsignedBigInt',\n 'Money',\n 'Real',\n 'DoublePrecision',\n 'Decimal',\n 'Numeric',\n 'SmallMoney',\n 'Timestamp',\n 'Timestamptz',\n 'DateTime2',\n 'DateTimeOffset',\n]);\n\nexport interface MappedFieldType {\n type: FieldType;\n constraints: Constraints;\n scalarOverride?: ScalarType;\n}\n\nfunction refineNative(\n native: [string, string[]],\n constraints: Constraints,\n result: MappedFieldType,\n field: PrismaField,\n logger: Logger | undefined,\n): void {\n const [name, args] = native;\n if (LENGTH_NATIVE.has(name)) {\n const n = Number(args[0]);\n if (Number.isFinite(n)) {\n constraints.maxLength = n;\n }\n return;\n }\n if (UUID_NATIVE.has(name)) {\n result.scalarOverride = 'uuid';\n return;\n }\n if (name === 'Date') {\n result.scalarOverride = 'date';\n return;\n }\n if (name === 'Time' || name === 'Timetz') {\n constraints.format = 'time';\n return;\n }\n if (NOOP_NATIVE.has(name)) {\n return;\n }\n logger?.debug(`prisma parser: ignoring unmapped native type @db.${name}`, {\n field: field.name,\n });\n}\n\nexport function mapFieldType(\n field: PrismaField,\n logger?: Logger,\n): MappedFieldType {\n const constraints: Constraints = {};\n\n if (field.kind === 'unsupported') {\n return { type: { kind: 'unknown', hint: field.type }, constraints };\n }\n if (field.kind === 'enum') {\n return { type: { kind: 'enum', ref: field.type }, constraints };\n }\n\n const scalar = SCALAR_TABLE[field.type];\n if (scalar === undefined) {\n return { type: { kind: 'unknown', hint: field.type }, constraints };\n }\n\n const result: MappedFieldType = {\n type: { kind: 'scalar', scalar },\n constraints,\n };\n if (field.nativeType) {\n refineNative(field.nativeType, constraints, result, field, logger);\n }\n return result;\n}\n","/**\n * Relation pairing and implicit-many-to-many materialisation.\n *\n * DMMF relation edges are grouped by `relationName`. A normal pair yields one\n * `Relation` per side (owning side = the one carrying `fromFields`). An implicit\n * m2m (both sides list, neither side carries fields) is materialised as a\n * synthetic join entity so downstream generators only ever see explicit m2m:\n * the two originals are rewritten to `many` relations pointing at the synthetic\n * entity, which gets `<model>Id` FK fields, a composite PK and two owning `one`\n * relations back to the originals.\n *\n * Every produced `Relation` has `target.namespace === ''`; `build.ts` injects\n * the real namespace (relations are always same-namespace for one Prisma\n * schema).\n */\nimport type { Logger } from '@kurotako/core';\nimport type { ReferentialAction, Relation, ScalarType } from '@kurotako/ir';\nimport type {\n PrismaEntity,\n PrismaModel,\n PrismaRelationEdge,\n} from '../dmmf/model.js';\nimport { mapFieldType } from './scalars.js';\n\nexport interface SyntheticField {\n name: string;\n scalar: ScalarType;\n}\n\nexport interface SyntheticEntity {\n name: string;\n fields: SyntheticField[];\n primaryKey: string[];\n relations: Relation[];\n}\n\nexport interface BuiltRelations {\n relations: Map<string, Relation[]>;\n syntheticEntities: SyntheticEntity[];\n}\n\nconst ACTION_MAP: Record<string, ReferentialAction> = {\n Cascade: 'cascade',\n Restrict: 'restrict',\n SetNull: 'setNull',\n SetDefault: 'setDefault',\n NoAction: 'noAction',\n};\n\nfunction mapAction(raw: string | undefined): ReferentialAction | undefined {\n return raw === undefined ? undefined : ACTION_MAP[raw];\n}\n\nfunction lcfirst(s: string): string {\n return s.length === 0 ? s : s.charAt(0).toLowerCase() + s.slice(1);\n}\n\ninterface OwnedEdge {\n owner: string;\n edge: PrismaRelationEdge;\n}\n\nfunction isImplicitM2M(edges: OwnedEdge[]): boolean {\n return (\n edges.length === 2 &&\n edges.every(\n ({ edge }) =>\n edge.isList &&\n edge.fromFields.length === 0 &&\n edge.toFields.length === 0,\n )\n );\n}\n\nfunction pkScalar(\n entities: Map<string, PrismaEntity>,\n entityName: string,\n logger: Logger | undefined,\n): ScalarType {\n const entity = entities.get(entityName);\n if (entity && entity.primaryKey.length === 1) {\n const pkName = entity.primaryKey[0];\n const field = entity.fields.find((f) => f.name === pkName);\n if (field) {\n const mapped = mapFieldType(field);\n if (mapped.scalarOverride) {\n return mapped.scalarOverride;\n }\n if (mapped.type.kind === 'scalar') {\n return mapped.type.scalar;\n }\n }\n }\n logger?.debug(\n `prisma parser: could not resolve primary-key scalar of '${entityName}', defaulting to string`,\n );\n return 'string';\n}\n\nfunction normalRelation(\n edge: PrismaRelationEdge,\n back: PrismaRelationEdge | undefined,\n): Relation {\n const owning = edge.fromFields.length > 0;\n const relation: Relation = {\n name: edge.fieldName,\n target: { namespace: '', entity: edge.targetEntity },\n cardinality: edge.isList ? 'many' : 'one',\n optional: !edge.isRequired,\n owning,\n };\n if (owning) {\n relation.fkFields = [...edge.fromFields];\n relation.references = [...edge.toFields];\n }\n if (back) {\n relation.backRelation = back.fieldName;\n }\n const onDelete = mapAction(edge.onDelete);\n if (onDelete) {\n relation.onDelete = onDelete;\n }\n const onUpdate = mapAction(edge.onUpdate);\n if (onUpdate) {\n relation.onUpdate = onUpdate;\n }\n return relation;\n}\n\nfunction materialiseM2M(\n a: OwnedEdge,\n b: OwnedEdge,\n relationName: string,\n entities: Map<string, PrismaEntity>,\n logger: Logger | undefined,\n): {\n synthetic: SyntheticEntity;\n rewrites: Array<{ owner: string; relation: Relation }>;\n} {\n const sorted = [a.owner, b.owner].sort((l, r) =>\n l < r ? -1 : l > r ? 1 : 0,\n );\n const x = sorted[0] ?? a.owner;\n const y = sorted[1] ?? b.owner;\n const defaultName = `${x}To${y}`;\n const name =\n relationName !== '' && relationName !== defaultName\n ? relationName\n : `${x}${y}`;\n\n const fkX = `${lcfirst(x)}Id`;\n const fkY = `${lcfirst(y)}Id`;\n const relX = lcfirst(x);\n const relY = lcfirst(y);\n const pkX = entities.get(x)?.primaryKey[0] ?? 'id';\n const pkY = entities.get(y)?.primaryKey[0] ?? 'id';\n\n const synthetic: SyntheticEntity = {\n name,\n fields: [\n { name: fkX, scalar: pkScalar(entities, x, logger) },\n { name: fkY, scalar: pkScalar(entities, y, logger) },\n ],\n primaryKey: [fkX, fkY],\n relations: [\n {\n name: relX,\n target: { namespace: '', entity: x },\n cardinality: 'one',\n optional: false,\n owning: true,\n fkFields: [fkX],\n references: [pkX],\n onDelete: 'cascade',\n },\n {\n name: relY,\n target: { namespace: '', entity: y },\n cardinality: 'one',\n optional: false,\n owning: true,\n fkFields: [fkY],\n references: [pkY],\n onDelete: 'cascade',\n },\n ],\n };\n\n const mkRewrite = (\n edge: OwnedEdge,\n backName: string,\n ): { owner: string; relation: Relation } => ({\n owner: edge.owner,\n relation: {\n name: edge.edge.fieldName,\n target: { namespace: '', entity: name },\n cardinality: 'many',\n optional: false,\n owning: false,\n backRelation: backName,\n },\n });\n\n return {\n synthetic,\n rewrites: [\n mkRewrite(a, a.owner === x ? relX : relY),\n mkRewrite(b, b.owner === x ? relX : relY),\n ],\n };\n}\n\nexport function buildRelations(\n model: PrismaModel,\n logger?: Logger,\n): BuiltRelations {\n const entities = new Map(model.entities.map((e) => [e.name, e]));\n const relations = new Map<string, Relation[]>();\n const syntheticEntities: SyntheticEntity[] = [];\n\n const push = (owner: string, relation: Relation): void => {\n const list = relations.get(owner) ?? [];\n list.push(relation);\n relations.set(owner, list);\n };\n\n const groups = new Map<string, OwnedEdge[]>();\n for (const entity of model.entities) {\n for (const edge of entity.relationEdges) {\n const list = groups.get(edge.relationName) ?? [];\n list.push({ owner: entity.name, edge });\n groups.set(edge.relationName, list);\n }\n }\n\n for (const [relationName, edges] of groups) {\n if (isImplicitM2M(edges)) {\n const [a, b] = edges as [OwnedEdge, OwnedEdge];\n const { synthetic, rewrites } = materialiseM2M(\n a,\n b,\n relationName,\n entities,\n logger,\n );\n syntheticEntities.push(synthetic);\n for (const { owner, relation } of rewrites) {\n push(owner, relation);\n }\n continue;\n }\n\n for (const { owner, edge } of edges) {\n const back = edges.find((e) => e.edge !== edge)?.edge;\n push(owner, normalRelation(edge, back));\n }\n }\n\n return { relations, syntheticEntities };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,kBAA0B;AAGnB,IAAM,mBAAN,cAA+B,sBAAU;AAAA,EACrC;AAAA,EACA;AAAA,EAET,YAAY,WAAmB,cAAsB,QAAgB;AACnE;AAAA,MACE;AAAA,MACA,6BAA6B,SAAS,OAAO,MAAM,oBAAoB,YAAY;AAAA,IACrF;AACA,SAAK,YAAY;AACjB,SAAK,eAAe;AAAA,EACtB;AACF;AAGO,IAAM,yBAAN,cAAqC,sBAAU;AAAA,EAC3C;AAAA,EAET,YAAY,WAAmB,SAA+B;AAC5D;AAAA,MACE;AAAA,MACA,6BAA6B,SAAS;AAAA,MAKtC;AAAA,IACF;AACA,SAAK,YAAY;AAAA,EACnB;AACF;AAGO,IAAM,oBAAN,cAAgC,sBAAU;AAAA,EACtC;AAAA,EACA;AAAA,EAET,YACE,WACA,eACA,SACA;AACA;AAAA,MACE;AAAA,MACA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AM,cAAc,MAAM;AACrD,YAAM,EAAE,OAAAC,QAAO,iBAAiB,IAAI,aAAa,KAAK,KAAK,OAAO;AAClE,aAAO;AAAA,QACL,IAAI;AAAA,QACJA;AAAA,QACA,mBAAmB,gBAAgB;AAAA,QACnC,IAAI;AAAA,MACN;AAAA,IACF;AAEA,QAAI,QAAQ,iBAAiB;AAC3B,UAAI,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AACA,UAAM,EAAE,OAAAA,QAAO,cAAc,IAAI,MAAM,SAAS,OAAO,KAAK,OAAO;AACnE,WAAO;AAAA,MACL,IAAI;AAAA,MACJA;AAAA,MACA,UAAU,aAAa;AAAA,MACvB,IAAI;AAAA,IACN;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,KAAmB,SAA4B;AAG9D,WAAO,KAAC,2BAAQ,IAAI,KAAK,QAAQ,MAAM,CAAC;AAAA,EAC1C;AAAA,EAEA,OAAO,SAAS,SAAS;AAKvB,eAAO,+BAAQ,2BAAQ,SAAS,QAAQ,MAAM,CAAC;AAAA,EACjD;AACF,CAAC;","names":["import_promises","import_node_path","v","record","table","column","field","relation","model","import_promises","import_node_path","readField","field","model","require","field","field","relation","model","model","field","model"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -7,7 +7,9 @@ import { SourceIR } from '@kurotako/ir';
|
|
|
7
7
|
* so the CLI's single `instanceof TakoError` catch covers them; `@kurotako/core`
|
|
8
8
|
* additionally wraps any throw from `parse()` as a `DriverError`.
|
|
9
9
|
*
|
|
10
|
-
* Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema
|
|
10
|
+
* Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema`,
|
|
11
|
+
* `prisma_contract`, `prisma_contract_version`, `prisma_dialect`, and
|
|
12
|
+
* `prisma_entity_collision`.
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
15
|
/** Schema path missing, an empty folder, or a folder with no `.prisma` file. */
|
|
@@ -31,6 +33,32 @@ declare class PrismaSchemaError extends TakoError {
|
|
|
31
33
|
cause?: unknown;
|
|
32
34
|
});
|
|
33
35
|
}
|
|
36
|
+
/** A Prisma 8 contract is invalid JSON or does not have the expected shape. */
|
|
37
|
+
declare class PrismaContractError extends TakoError {
|
|
38
|
+
constructor(detail: string, options?: {
|
|
39
|
+
cause?: unknown;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** The contract schema version is not one this parser understands. */
|
|
43
|
+
declare class PrismaContractVersionError extends TakoError {
|
|
44
|
+
readonly found: string;
|
|
45
|
+
constructor(found: string, expected: readonly string[]);
|
|
46
|
+
}
|
|
47
|
+
/** A contract codec belongs to a database dialect kurotako does not support. */
|
|
48
|
+
declare class PrismaDialectError extends TakoError {
|
|
49
|
+
readonly codecId: string;
|
|
50
|
+
constructor(codecId: string);
|
|
51
|
+
}
|
|
52
|
+
/** Multiple namespace-qualified models resolve to the same IR entity name. */
|
|
53
|
+
declare class PrismaEntityCollisionError extends TakoError {
|
|
54
|
+
readonly entityName: string;
|
|
55
|
+
readonly models: readonly string[];
|
|
56
|
+
constructor(entityName: string, models: readonly string[]);
|
|
57
|
+
}
|
|
58
|
+
/** Prisma emitted a relation to a homonym model whose namespace is unreliable. */
|
|
59
|
+
declare class PrismaAmbiguousRelationError extends TakoError {
|
|
60
|
+
constructor(modelName: string);
|
|
61
|
+
}
|
|
34
62
|
|
|
35
63
|
/**
|
|
36
64
|
* Valibot schema for `@kurotako/parser-prisma`'s `options`, plus the inferred
|
|
@@ -44,6 +72,8 @@ declare class PrismaSchemaError extends TakoError {
|
|
|
44
72
|
declare const PrismaParserOptions: v.StrictObjectSchema<{
|
|
45
73
|
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, "./prisma/schema.prisma">;
|
|
46
74
|
readonly version: v.OptionalSchema<v.PicklistSchema<[7, 8], undefined>, undefined>;
|
|
75
|
+
readonly namespacePrefix: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
76
|
+
readonly rename: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
47
77
|
}, undefined>;
|
|
48
78
|
type PrismaParserOptions = v.InferOutput<typeof PrismaParserOptions>;
|
|
49
79
|
|
|
@@ -52,19 +82,39 @@ declare const prismaParser: {
|
|
|
52
82
|
optionsSchema?: v.StrictObjectSchema<{
|
|
53
83
|
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, "./prisma/schema.prisma">;
|
|
54
84
|
readonly version: v.OptionalSchema<v.PicklistSchema<[7, 8], undefined>, undefined>;
|
|
85
|
+
readonly namespacePrefix: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
86
|
+
readonly rename: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
55
87
|
}, undefined> | undefined;
|
|
56
88
|
parse(ctx: ParseContext, options: {
|
|
57
89
|
schema: string;
|
|
58
90
|
version?: 7 | 8 | undefined;
|
|
91
|
+
namespacePrefix?: {
|
|
92
|
+
[x: string]: string;
|
|
93
|
+
} | undefined;
|
|
94
|
+
rename?: {
|
|
95
|
+
[x: string]: string;
|
|
96
|
+
} | undefined;
|
|
59
97
|
}): SourceIR | Promise<SourceIR>;
|
|
60
98
|
watchPaths?(ctx: ParseContext, options: {
|
|
61
99
|
schema: string;
|
|
62
100
|
version?: 7 | 8 | undefined;
|
|
101
|
+
namespacePrefix?: {
|
|
102
|
+
[x: string]: string;
|
|
103
|
+
} | undefined;
|
|
104
|
+
rename?: {
|
|
105
|
+
[x: string]: string;
|
|
106
|
+
} | undefined;
|
|
63
107
|
}): string[] | Promise<string[]>;
|
|
64
108
|
anchor?(rootDir: string, options: {
|
|
65
109
|
schema: string;
|
|
66
110
|
version?: 7 | 8 | undefined;
|
|
111
|
+
namespacePrefix?: {
|
|
112
|
+
[x: string]: string;
|
|
113
|
+
} | undefined;
|
|
114
|
+
rename?: {
|
|
115
|
+
[x: string]: string;
|
|
116
|
+
} | undefined;
|
|
67
117
|
}): string | undefined | Promise<string | undefined>;
|
|
68
118
|
};
|
|
69
119
|
|
|
70
|
-
export { PrismaInputError, PrismaParserOptions, PrismaPeerMissingError, PrismaSchemaError, prismaParser };
|
|
120
|
+
export { PrismaAmbiguousRelationError, PrismaContractError, PrismaContractVersionError, PrismaDialectError, PrismaEntityCollisionError, PrismaInputError, PrismaParserOptions, PrismaPeerMissingError, PrismaSchemaError, prismaParser };
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,9 @@ import { SourceIR } from '@kurotako/ir';
|
|
|
7
7
|
* so the CLI's single `instanceof TakoError` catch covers them; `@kurotako/core`
|
|
8
8
|
* additionally wraps any throw from `parse()` as a `DriverError`.
|
|
9
9
|
*
|
|
10
|
-
* Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema
|
|
10
|
+
* Codes: `prisma_input`, `prisma_peer_missing`, `prisma_schema`,
|
|
11
|
+
* `prisma_contract`, `prisma_contract_version`, `prisma_dialect`, and
|
|
12
|
+
* `prisma_entity_collision`.
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
15
|
/** Schema path missing, an empty folder, or a folder with no `.prisma` file. */
|
|
@@ -31,6 +33,32 @@ declare class PrismaSchemaError extends TakoError {
|
|
|
31
33
|
cause?: unknown;
|
|
32
34
|
});
|
|
33
35
|
}
|
|
36
|
+
/** A Prisma 8 contract is invalid JSON or does not have the expected shape. */
|
|
37
|
+
declare class PrismaContractError extends TakoError {
|
|
38
|
+
constructor(detail: string, options?: {
|
|
39
|
+
cause?: unknown;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** The contract schema version is not one this parser understands. */
|
|
43
|
+
declare class PrismaContractVersionError extends TakoError {
|
|
44
|
+
readonly found: string;
|
|
45
|
+
constructor(found: string, expected: readonly string[]);
|
|
46
|
+
}
|
|
47
|
+
/** A contract codec belongs to a database dialect kurotako does not support. */
|
|
48
|
+
declare class PrismaDialectError extends TakoError {
|
|
49
|
+
readonly codecId: string;
|
|
50
|
+
constructor(codecId: string);
|
|
51
|
+
}
|
|
52
|
+
/** Multiple namespace-qualified models resolve to the same IR entity name. */
|
|
53
|
+
declare class PrismaEntityCollisionError extends TakoError {
|
|
54
|
+
readonly entityName: string;
|
|
55
|
+
readonly models: readonly string[];
|
|
56
|
+
constructor(entityName: string, models: readonly string[]);
|
|
57
|
+
}
|
|
58
|
+
/** Prisma emitted a relation to a homonym model whose namespace is unreliable. */
|
|
59
|
+
declare class PrismaAmbiguousRelationError extends TakoError {
|
|
60
|
+
constructor(modelName: string);
|
|
61
|
+
}
|
|
34
62
|
|
|
35
63
|
/**
|
|
36
64
|
* Valibot schema for `@kurotako/parser-prisma`'s `options`, plus the inferred
|
|
@@ -44,6 +72,8 @@ declare class PrismaSchemaError extends TakoError {
|
|
|
44
72
|
declare const PrismaParserOptions: v.StrictObjectSchema<{
|
|
45
73
|
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, "./prisma/schema.prisma">;
|
|
46
74
|
readonly version: v.OptionalSchema<v.PicklistSchema<[7, 8], undefined>, undefined>;
|
|
75
|
+
readonly namespacePrefix: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
76
|
+
readonly rename: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
47
77
|
}, undefined>;
|
|
48
78
|
type PrismaParserOptions = v.InferOutput<typeof PrismaParserOptions>;
|
|
49
79
|
|
|
@@ -52,19 +82,39 @@ declare const prismaParser: {
|
|
|
52
82
|
optionsSchema?: v.StrictObjectSchema<{
|
|
53
83
|
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, "./prisma/schema.prisma">;
|
|
54
84
|
readonly version: v.OptionalSchema<v.PicklistSchema<[7, 8], undefined>, undefined>;
|
|
85
|
+
readonly namespacePrefix: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
86
|
+
readonly rename: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
55
87
|
}, undefined> | undefined;
|
|
56
88
|
parse(ctx: ParseContext, options: {
|
|
57
89
|
schema: string;
|
|
58
90
|
version?: 7 | 8 | undefined;
|
|
91
|
+
namespacePrefix?: {
|
|
92
|
+
[x: string]: string;
|
|
93
|
+
} | undefined;
|
|
94
|
+
rename?: {
|
|
95
|
+
[x: string]: string;
|
|
96
|
+
} | undefined;
|
|
59
97
|
}): SourceIR | Promise<SourceIR>;
|
|
60
98
|
watchPaths?(ctx: ParseContext, options: {
|
|
61
99
|
schema: string;
|
|
62
100
|
version?: 7 | 8 | undefined;
|
|
101
|
+
namespacePrefix?: {
|
|
102
|
+
[x: string]: string;
|
|
103
|
+
} | undefined;
|
|
104
|
+
rename?: {
|
|
105
|
+
[x: string]: string;
|
|
106
|
+
} | undefined;
|
|
63
107
|
}): string[] | Promise<string[]>;
|
|
64
108
|
anchor?(rootDir: string, options: {
|
|
65
109
|
schema: string;
|
|
66
110
|
version?: 7 | 8 | undefined;
|
|
111
|
+
namespacePrefix?: {
|
|
112
|
+
[x: string]: string;
|
|
113
|
+
} | undefined;
|
|
114
|
+
rename?: {
|
|
115
|
+
[x: string]: string;
|
|
116
|
+
} | undefined;
|
|
67
117
|
}): string | undefined | Promise<string | undefined>;
|
|
68
118
|
};
|
|
69
119
|
|
|
70
|
-
export { PrismaInputError, PrismaParserOptions, PrismaPeerMissingError, PrismaSchemaError, prismaParser };
|
|
120
|
+
export { PrismaAmbiguousRelationError, PrismaContractError, PrismaContractVersionError, PrismaDialectError, PrismaEntityCollisionError, PrismaInputError, PrismaParserOptions, PrismaPeerMissingError, PrismaSchemaError, prismaParser };
|