@drzl/cli 4.17.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../generator-trpc/dist/index.js","../../generator-json-schema/dist/index.js","../src/cli.ts","../src/validation-options.ts","../src/json-schema-options.ts","../src/config.ts","../src/trpc-options.ts","../src/drift.ts","../src/generator-loader.ts","../src/sponsor.ts","../src/version.ts"],"sourcesContent":["// src/index.ts\nimport {\n formatCode,\n importSpecifier,\n resolveAffix,\n resolveConfiguredImport,\n schemaName\n} from \"@drzl/validation-core\";\nvar TRPC_MAJOR = 11;\nvar q = (v) => JSON.stringify(v);\nvar LIB_IMPORTS = {\n zod: \"import { z } from 'zod';\",\n valibot: \"import * as v from 'valibot';\",\n arktype: \"import { type } from 'arktype';\"\n};\nvar LIB_USAGE = {\n zod: /\\bz\\./,\n valibot: /\\bv\\./,\n arktype: /\\btype\\(/\n};\nvar LIBS = {\n zod: {\n number: \"z.number()\",\n string: \"z.string()\",\n boolean: \"z.boolean()\",\n date: \"z.date()\",\n unknown: \"z.unknown()\",\n tuple: (n) => `z.tuple([${Array.from({ length: n }, () => \"z.number()\").join(\", \")}])`,\n numberObject: (fields) => `z.object({ ${fields.map((f) => `${f}: z.number()`).join(\", \")} })`,\n enum: (vals) => `z.enum([${vals.map(q).join(\", \")}] as const)`,\n nullable: (b) => `${b}.nullable()`,\n optional: (b) => `${b}.optional()`,\n object: (body) => `z.object({\n${body}\n})`,\n objectInline: (body) => `z.object({ ${body} })`,\n partialUpdate: (s) => `${s}.partial()`,\n arrayOf: (s) => `z.array(${s})`,\n nullableOf: (s) => `${s}.nullable()`,\n booleanSchema: \"z.boolean()\"\n },\n valibot: {\n number: \"v.number()\",\n string: \"v.string()\",\n boolean: \"v.boolean()\",\n date: \"v.date()\",\n unknown: \"v.unknown()\",\n tuple: (n) => `v.tuple([${Array.from({ length: n }, () => \"v.number()\").join(\", \")}])`,\n numberObject: (fields) => `v.object({ ${fields.map((f) => `${f}: v.number()`).join(\", \")} })`,\n enum: (vals) => `v.picklist([${vals.map(q).join(\", \")}] as const)`,\n nullable: (b) => `v.nullable(${b})`,\n optional: (b) => `v.optional(${b})`,\n object: (body) => `v.object({\n${body}\n})`,\n objectInline: (body) => `v.object({ ${body} })`,\n arrayOf: (s) => `v.array(${s})`,\n nullableOf: (s) => `v.nullable(${s})`,\n booleanSchema: \"v.boolean()\"\n },\n arktype: {\n number: \"number\",\n string: \"string\",\n boolean: \"boolean\",\n date: \"Date\",\n unknown: \"unknown\",\n // The surrounding encode adds the quotes, so the union is built with the inner quoting\n // ArkType expects. Emitting `'${...}'` here produces `''admin' | 'user''`, which does not parse.\n enum: (vals) => vals.map((x) => `'${x.replace(/'/g, \"\\\\'\")}'`).join(\" | \"),\n nullable: (b) => `(${b} | null)`,\n optional: (b) => `${b}?`,\n object: (body) => `type({\n${body}\n})`,\n objectInline: (body) => `type({ ${body} })`,\n fieldIsString: true,\n arrayOf: (s) => `${s}.array()`,\n nullableOf: (s) => `${s}.or('null')`,\n booleanSchema: `type('boolean')`\n }\n};\nfunction isWide(column) {\n if (column.enumValues && column.enumValues.length) return false;\n if (column.shape?.kind === \"tuple\" || column.shape?.kind === \"numberObject\") return false;\n return ![\"number\", \"string\", \"boolean\", \"Date\"].includes(column.tsType);\n}\nfunction mapExpr(column, lib, mode) {\n const d = LIBS[lib];\n let base = (() => {\n if (column.enumValues && column.enumValues.length) return d.enum(column.enumValues);\n if (column.shape?.kind === \"tuple\" && d.tuple) return d.tuple(column.shape.length);\n if (column.shape?.kind === \"numberObject\" && d.numberObject) {\n return d.numberObject(column.shape.fields);\n }\n switch (column.tsType) {\n case \"number\":\n return d.number;\n case \"string\":\n return d.string;\n case \"boolean\":\n return d.boolean;\n case \"Date\":\n return d.date;\n default:\n return d.unknown;\n }\n })();\n if (column.nullable) base = d.nullable(base);\n if (mode !== \"select\") {\n const optional = mode === \"update\" || column.nullable || column.hasDefault;\n if (optional) base = d.optional(base);\n }\n return base;\n}\nfunction field(column, lib, mode) {\n const d = LIBS[lib];\n const expr = mapExpr(column, lib, mode);\n return `${objectKey(column.name)}: ${d.fieldIsString ? JSON.stringify(expr) : expr}`;\n}\nfunction objectKey(name) {\n return isIdent(name) ? name : JSON.stringify(name);\n}\nfunction renderSchema(table, lib, mode) {\n const d = LIBS[lib];\n const cols = table.columns.filter((c) => mode === \"select\" ? true : !c.isGenerated);\n const body = cols.map((c) => ` ${field(c, lib, mode)},`).join(\"\\n\");\n const schema = d.object(body);\n return mode === \"update\" && d.partialUpdate ? d.partialUpdate(schema) : schema;\n}\nfunction toCase(s, c) {\n if (!c) return s;\n const parts = s.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/[_-]/g, \" \").split(/\\s+/);\n if (c === \"camel\") {\n return parts.map(\n (p, i) => i === 0 ? p.toLowerCase() : p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()\n ).join(\"\");\n }\n if (c === \"kebab\") return parts.map((p) => p.toLowerCase()).join(\"-\");\n if (c === \"snake\") return parts.map((p) => p.toLowerCase()).join(\"_\");\n return s;\n}\nvar cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);\nvar singularize = (s) => s.endsWith(\"ies\") ? s.slice(0, -3) + \"y\" : s.endsWith(\"s\") ? s.slice(0, -1) : s;\nvar isIdent = (s) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s);\nvar BASE_MODULE = \"trpc\";\nfunction keyColumns(table) {\n const names = table.primaryKey?.columns ?? [];\n if (!names.length) return null;\n const cols = names.map((n) => table.columns.find((c) => c.name === n));\n if (cols.some((c) => !c)) return null;\n return cols;\n}\nvar TRPCGenerator = class {\n constructor(analysis) {\n this.analysis = analysis;\n }\n async generate(opts) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const out = path.resolve(process.cwd(), opts.outputDir);\n const ctx = {\n out,\n services: path.resolve(process.cwd(), opts.servicesDir ?? \"src/services\")\n };\n await fs.mkdir(out, { recursive: true });\n const files = [];\n const write = async (filePath, content) => {\n const formatted = await formatCode(\n buildHeader(opts.outputHeader) + content,\n filePath,\n opts.format\n );\n await fs.writeFile(filePath, formatted, \"utf8\");\n files.push(filePath);\n };\n const basePath = path.join(out, `${BASE_MODULE}.ts`);\n await write(basePath, renderBase(opts));\n const routers = [];\n const total = this.analysis.tables.length;\n let index = 0;\n for (const table of this.analysis.tables) {\n const base = `${table.tsName}${opts.naming?.routerSuffix ?? \"\"}`;\n const filePath = path.join(out, `${toCase(base, opts.naming?.procedureCase)}.ts`);\n if (filePath === basePath) {\n throw new Error(\n `@drzl/generator-trpc: the router for table \"${table.name}\" would be written to ${filePath}, which is the shared tRPC base module this generator also writes. Set naming.routerSuffix to move it out of the way.`\n );\n }\n await write(filePath, renderRouter(table, opts, ctx));\n routers.push({ table, filePath, exportName: routerExportName(table, opts.naming) });\n index++;\n opts.onProgress?.({ index, total, table: table.name, filePath });\n }\n await write(path.join(out, \"index.ts\"), renderBarrel(routers, ctx, path, opts));\n return { files };\n }\n};\nvar index_default = TRPCGenerator;\nfunction renderBase(opts) {\n const injection = opts.databaseInjection?.enabled === true;\n const dbType = opts.databaseInjection?.databaseType ?? \"unknown\";\n const typeImport = opts.databaseInjection?.databaseTypeImport ? `import type { ${opts.databaseInjection.databaseTypeImport.name} } from '${opts.databaseInjection.databaseTypeImport.from}';\n` : \"\";\n const trpcImport = injection ? `import { initTRPC, TRPCError } from '@trpc/server';` : `import { initTRPC } from '@trpc/server';`;\n const context = injection ? `/**\n * What your \\`createContext\\` hands every procedure.\n *\n * \\`db\\` is optional here and required by \\`dbProcedure\\` below. That split is what lets an adapter\n * build a context without a handle, for a health check or a public route, while every generated\n * procedure still sees one that is present.\n */\nexport interface Context {\n db?: ${dbType};\n}` : `/**\n * What your \\`createContext\\` hands every procedure. Nothing generated reads it, so it is left\n * open; narrow it to the shape your own context really has.\n */\nexport type Context = Record<string, unknown>;`;\n const middleware = injection ? `\n/**\n * The builder every generated procedure is built from: it refuses to run without a database\n * handle, and narrows \\`ctx.db\\` from optional to present for everything downstream.\n */\nexport const dbProcedure = t.procedure.use(async ({ ctx, next }) => {\n if (!ctx.db) {\n throw new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'No database handle on the tRPC context. Provide one from createContext.',\n });\n }\n return next({ ctx: { db: ctx.db } });\n});\n` : \"\";\n return `// Generated by @drzl/generator-trpc\n// The shared tRPC base. Every generated router imports from here.\n${trpcImport}\n${typeImport}\n${context}\n\nconst t = initTRPC.context<Context>().create();\n\nexport const router = t.router;\nexport const mergeRouters = t.mergeRouters;\nexport const middleware = t.middleware;\n/** Needed to call this router in-process, from a test or from SSR. */\nexport const createCallerFactory = t.createCallerFactory;\nexport const publicProcedure = t.procedure;\n${middleware}`;\n}\nfunction renderRouter(table, opts, ctx) {\n const lib = opts.validation?.library ?? \"zod\";\n const d = LIBS[lib];\n const service = opts.template === \"service\";\n const injection = opts.databaseInjection?.enabled === true;\n const builder = injection ? \"dbProcedure\" : \"publicProcedure\";\n const insertName = `Insert${table.tsName}Schema`;\n const updateName = `Update${table.tsName}Schema`;\n const selectName = `Select${table.tsName}Schema`;\n const writable = !table.readOnly;\n const key = keyColumns(table);\n const Service = `${cap(singularize(table.tsName))}Service`;\n const serviceKeyable = !!key && key.length === 1 && key[0].tsType === \"number\";\n const keyArg = key && key.length === 1 ? `input.${key[0].name}` : \"\";\n const dbArg = injection ? \"ctx.db, \" : \"\";\n const wiredParams = injection ? \"{ ctx, input }\" : \"{ input }\";\n const procedures = [];\n const notImplemented = (what) => `throw new Error('Not implemented: ${what} ${table.tsName}.');`;\n procedures.push({\n name: \"list\",\n kind: \"query\",\n output: d.arrayOf(selectName),\n params: service && injection ? \"{ ctx }\" : \"\",\n body: service ? [`return await ${Service}.getAll(${injection ? \"ctx.db\" : \"\"});`] : [\"return [];\"]\n });\n const keyInput = key ? d.objectInline(key.map((c) => field(c, lib, \"select\")).join(\", \")) : void 0;\n if (key && keyInput) {\n const wired = service && serviceKeyable;\n procedures.push({\n name: \"byId\",\n kind: \"query\",\n input: keyInput,\n output: d.nullableOf(selectName),\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.getById(${dbArg}${keyArg});`] : service ? [serviceKeyNote(table), notImplemented(\"byId\")] : [\"return null;\"]\n });\n if (writable) {\n const updateInput = d.objectInline(\n [...key.map((c) => field(c, lib, \"select\")), `data: ${updateName}`].join(\", \")\n );\n procedures.push({\n name: \"update\",\n kind: \"mutation\",\n input: updateInput,\n output: selectName,\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.update(${dbArg}${keyArg}, input.data);`] : service ? [serviceKeyNote(table), notImplemented(\"update\")] : [notImplemented(\"update\")]\n });\n procedures.push({\n name: \"delete\",\n kind: \"mutation\",\n input: keyInput,\n output: d.booleanSchema,\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.delete(${dbArg}${keyArg});`] : service ? [serviceKeyNote(table), notImplemented(\"delete\")] : [\"return true;\"]\n });\n }\n }\n if (writable) {\n procedures.push({\n name: \"create\",\n kind: \"mutation\",\n input: insertName,\n output: selectName,\n params: service ? wiredParams : \"{ input: _input }\",\n body: service ? [`return await ${Service}.create(${dbArg}input);`] : [notImplemented(\"create\")]\n });\n }\n if (opts.includeRelations) {\n const taken = new Set(procedures.map((p) => p.name));\n procedures.push(...relationProcedures(table, lib, selectName, taken, service));\n }\n const order = [\"list\", \"byId\", \"create\", \"update\", \"delete\"];\n const rank = (n) => order.indexOf(n) === -1 ? order.length : order.indexOf(n);\n procedures.sort((a, b) => rank(a.name) - rank(b.name));\n const routerName = routerExportName(table, opts.naming);\n const entries = procedures.map((p) => {\n const rawKey = toCase(p.name, opts.naming?.procedureCase);\n const propKey = isIdent(rawKey) ? rawKey : JSON.stringify(rawKey);\n return [\n ` ${propKey}: ${builder}`,\n ...p.input ? [` .input(${p.input})`] : [],\n ` .output(${p.output})`,\n ` .${p.kind}(async (${p.params}) => {`,\n ...p.body.map((line) => ` ${line}`),\n ` }),`\n ].join(\"\\n\");\n }).join(\"\\n\");\n const body = `export const ${routerName} = router({\n${entries}\n});\n`;\n const useShared = !!opts.validation?.useShared && !!opts.validation?.importPath;\n const declared = [];\n if (!useShared) {\n if (writable) {\n declared.push(`export const ${insertName} = ${renderSchema(table, lib, \"insert\")};`);\n declared.push(`export const ${updateName} = ${renderSchema(table, lib, \"update\")};`);\n }\n declared.push(`export const ${selectName} = ${renderSchema(table, lib, \"select\")};`);\n }\n const decided = [...declared, body].join(\"\\n\\n\");\n const imports = [];\n if (useShared) {\n const sharedAffix = resolveAffix({\n affix: opts.validation?.affix,\n schemaSuffix: opts.validation?.schemaSuffix\n });\n const wanted = [\n [\"insert\", insertName],\n [\"update\", updateName],\n [\"select\", selectName]\n ].filter(([, local]) => decided.includes(local));\n if (wanted.length) {\n const spec = resolveConfiguredImport(\n opts.validation.importPath,\n ctx.out,\n process.cwd(),\n opts.importExtension\n );\n const names = wanted.map(([mode, local]) => {\n const exported = schemaName(mode, table.tsName, sharedAffix);\n return exported === local ? local : `${exported} as ${local}`;\n }).join(\", \");\n imports.push(`import { ${names} } from '${spec}';`);\n }\n }\n imports.push(\n `import { ${[builder, \"router\"].sort().join(\", \")} } from '${importSpecifier(\n `./${BASE_MODULE}.ts`,\n opts.importExtension\n )}';`\n );\n if (service) {\n imports.push(`import { ${Service} } from '${serviceImportSpecifier(table, ctx, opts)}';`);\n }\n if (LIB_USAGE[lib].test(decided)) imports.unshift(LIB_IMPORTS[lib]);\n const wide = table.columns.filter(isWide).map((c) => c.name);\n const wideNote = wide.length ? `// No validated type for ${wide.length === 1 ? \"this column\" : \"these columns\"}: ${wide.join(\", \")}.\n// DRZL could not derive one from the schema, so the router accepts any value there.\n` : \"\";\n return `// Generated by @drzl/generator-trpc\n// Router for table: ${table.name}\n${wideNote}${imports.join(\"\\n\")}\n\n${decided}`;\n}\nfunction relationProcedures(table, lib, selectSchemaName, taken, service) {\n const d = LIBS[lib];\n const out = [];\n for (const fk of table.foreignKeys ?? []) {\n if (fk.columns.length !== 1) continue;\n const colName = fk.columns[0];\n const column = table.columns.find((c) => c.name === colName);\n if (!column) continue;\n const name = `listBy${cap(colName)}`;\n if (taken.has(name)) continue;\n taken.add(name);\n out.push({\n name,\n kind: \"query\",\n input: d.objectInline(field(column, lib, \"select\")),\n output: d.arrayOf(selectSchemaName),\n params: \"{ input: _input }\",\n body: [\n `// Rows of ${table.name} whose ${JSON.stringify(colName)} matches _input.${colName}.`,\n // In `service` mode every other procedure really does reach the database, so a lookup\n // quietly answering with an empty array would read as \"no matching rows\". There is no\n // generated service method for it, so it says so instead. In `standard` mode everything\n // is a stub and `[]` is consistent with `list`.\n service ? `throw new Error('Not implemented: ${name} ${table.tsName}.');` : \"return [];\"\n ]\n });\n }\n return out;\n}\nfunction renderBarrel(routers, ctx, path, opts) {\n const baseSpec = importSpecifier(`./${BASE_MODULE}.ts`, opts.importExtension);\n const reExports = `export { createCallerFactory, publicProcedure, router } from '${baseSpec}';\n` + (opts.databaseInjection?.enabled === true ? `export { dbProcedure } from '${baseSpec}';\n` : \"\") + `export type { Context } from '${baseSpec}';\n`;\n if (!routers.length) {\n return `// Generated by @drzl/generator-trpc\n// No tables detected in analysis. Add tables to your schema and regenerate.\nimport { router } from '${baseSpec}';\n\nexport const appRouter = router({});\n\n/** The type a tRPC client is parameterised by: \\`createTRPCClient<AppRouter>()\\`. */\nexport type AppRouter = typeof appRouter;\n\n${reExports}`;\n }\n const entries = routers.map(({ filePath, exportName, table }) => ({\n rel: importSpecifier(\n \"./\" + path.relative(ctx.out, filePath).replace(/\\\\/g, \"/\"),\n opts.importExtension\n ),\n exportName,\n // The namespace a client reaches this table's procedures through: `trpc.userProfiles.list`.\n // `tsName` verbatim, because it is already a valid identifier and it is the name the user\n // wrote in their schema. The oRPC barrel lowercases this key, turning `userProfiles` into\n // `userprofiles`: harmless in an object literal nobody reads, and not harmless when the key\n // is the public API of a typed client.\n key: table.tsName\n }));\n const importLines = entries.map(({ rel, exportName }) => `import { ${exportName} } from '${rel}';`).join(\"\\n\");\n const bodyLines = entries.map(({ key, exportName }) => ` ${isIdent(key) ? key : JSON.stringify(key)}: ${exportName},`).join(\"\\n\");\n return `// Generated by @drzl/generator-trpc\nimport { router } from '${baseSpec}';\n${importLines}\n\nexport const appRouter = router({\n${bodyLines}\n});\n\n/** The type a tRPC client is parameterised by: \\`createTRPCClient<AppRouter>()\\`. */\nexport type AppRouter = typeof appRouter;\n\n${reExports}`;\n}\nfunction serviceKeyNote(table) {\n const cols = table.primaryKey?.columns ?? [];\n const shape = cols.length > 1 ? `has a composite primary key (${cols.join(\", \")})` : `has a non-numeric primary key (${cols[0]})`;\n return `// ${table.name} ${shape}, and @drzl/generator-service types its key parameter as one number.\n// Wire this to your own lookup.`;\n}\nfunction routerExportName(table, naming) {\n const base = `${table.tsName}${naming?.routerSuffix ?? \"Router\"}`;\n const c = naming?.procedureCase;\n return toCase(base, c === \"kebab\" ? \"camel\" : c);\n}\nfunction serviceImportSpecifier(table, ctx, opts) {\n const rel = relativePosix(ctx.out, ctx.services);\n const dir = !rel ? \".\" : rel.startsWith(\".\") ? rel : `./${rel}`;\n return importSpecifier(`${dir}/${singularize(table.tsName)}Service.ts`, opts.importExtension);\n}\nfunction relativePosix(from, to) {\n const norm = (p) => p.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const a = norm(from).split(\"/\");\n const b = norm(to).split(\"/\");\n let i = 0;\n while (i < a.length && i < b.length && a[i] === b[i]) i++;\n return [...Array.from({ length: a.length - i }, () => \"..\"), ...b.slice(i)].join(\"/\");\n}\nfunction buildHeader(h) {\n if (h && h.enabled === false) return \"\";\n const text = h?.text?.trim();\n const lines = text ? text.split(/\\r?\\n/).map((l) => `// ${l}`) : [\n \"// Generated by DRZL (@drzl/*)\",\n \"// Generated output is granted to you under your project's license.\",\n \"// You may use, copy, modify, and distribute without attribution.\"\n ];\n return lines.join(\"\\n\") + \"\\n\\n\";\n}\nexport {\n BASE_MODULE,\n TRPCGenerator,\n TRPC_MAJOR,\n index_default as default\n};\n","// src/index.ts\nimport {\n formatCode,\n moduleFileName,\n moduleSpecifier,\n resolveAffix,\n schemaName,\n typeName\n} from \"@drzl/validation-core\";\n\n// src/schemas.ts\nimport {\n COLUMN_FORMATS,\n insertColumns,\n isIntegerColumn,\n parseCheck,\n selectColumns,\n updateColumns\n} from \"@drzl/validation-core\";\nvar DRAFT = \"https://json-schema.org/draft/2020-12/schema\";\nvar UUID_FORMAT = \"uuid\";\nvar base64 = (target) => target === \"openapi-3.0\" ? { type: \"string\", format: \"byte\" } : { type: \"string\", contentEncoding: \"base64\" };\nfunction baseSchema(c, mode, target, checks, sets, lengths) {\n const s = c.shape;\n if (s) {\n switch (s.kind) {\n case \"json\":\n return {};\n case \"custom\":\n return {};\n case \"buffer\":\n return base64(target);\n case \"tuple\":\n return target === \"openapi-3.0\" ? { type: \"array\", items: { type: \"number\" }, minItems: s.length, maxItems: s.length } : {\n type: \"array\",\n prefixItems: Array.from({ length: s.length }, () => ({ type: \"number\" })),\n minItems: s.length,\n maxItems: s.length\n };\n case \"numberObject\":\n return {\n type: \"object\",\n properties: Object.fromEntries(s.fields.map((f) => [f, { type: \"number\" }])),\n required: [...s.fields]\n };\n case \"numberVector\":\n return {\n type: \"array\",\n items: { type: \"number\" },\n ...s.length ? { minItems: s.length, maxItems: s.length } : {}\n };\n case \"bitstring\":\n return {\n type: \"string\",\n pattern: \"^[01]*$\",\n ...s.length ? s.exact ? { minLength: s.length, maxLength: s.length } : { maxLength: s.length } : {}\n };\n case \"byteString\":\n return { type: \"string\", ...s.length ? { maxLength: s.length } : {} };\n }\n }\n const set = sets.find((x) => x.column === c.name);\n if (set) return { enum: set.values.map((v) => set.kind === \"string\" ? v : Number(v)) };\n if (c.enumValues && c.enumValues.length) return { enum: [...c.enumValues] };\n const mine = c.arrayDimensions ? [] : checks.filter((k) => k.column === c.name);\n const eq = mine.find((k) => k.operator === \"=\");\n if (eq) {\n const only = eq.kind === \"string\" ? eq.value : Number(eq.value);\n return target === \"openapi-3.0\" ? { enum: [only] } : { const: only };\n }\n switch (c.tsType) {\n case \"string\": {\n const out = { type: \"string\" };\n if (c.format === \"uuid\") out.format = UUID_FORMAT;\n else if (c.format && COLUMN_FORMATS[c.format]) out.pattern = COLUMN_FORMATS[c.format];\n if (c.maxLength !== void 0) out.maxLength = c.maxLength;\n applyByteCap(out, c);\n applyLengths(out, c, lengths);\n return out;\n }\n case \"number\": {\n const out = { type: isIntegerColumn(c) ? \"integer\" : \"number\" };\n if (!c.arrayDimensions) applyNumericBounds(out, c, checks, target);\n return out;\n }\n case \"bigint\":\n return { type: \"string\", pattern: \"^-?\\\\d+$\" };\n case \"boolean\":\n return { type: \"boolean\" };\n case \"Date\":\n return { type: \"string\", format: \"date-time\" };\n case \"Uint8Array\":\n return base64(target);\n default:\n return {};\n }\n}\nfunction applyByteCap(out, c) {\n if (!c.maxBytes) return;\n out.maxLength = Math.min(Number(out.maxLength ?? Infinity), c.maxBytes);\n out.description = `At most ${c.maxBytes} bytes of UTF-8, which JSON Schema has no keyword for. maxLength counts characters: it refuses nothing the column accepts, and a string of multi-byte characters can satisfy it and still be too long for the column.`;\n}\nfunction applyLengths(out, c, lengths) {\n for (const k of lengths.filter((x) => x.column === c.name)) {\n const n = Number(k.value);\n if (k.operator === \">=\") out.minLength = Math.max(Number(out.minLength ?? 0), n);\n else if (k.operator === \">\") out.minLength = Math.max(Number(out.minLength ?? 0), n + 1);\n else if (k.operator === \"<=\") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n);\n else if (k.operator === \"<\") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n - 1);\n else if (k.operator === \"=\") {\n out.minLength = n;\n out.maxLength = n;\n }\n }\n}\nfunction applyNumericBounds(out, c, checks, target) {\n let min = c.min !== void 0 ? { value: Number(c.min), exclusive: false } : void 0;\n let max = c.max !== void 0 ? { value: Number(c.max), exclusive: false } : void 0;\n for (const k of checks.filter((x) => x.column === c.name && x.kind === \"number\")) {\n if (k.operator === \">=\") min = { value: Number(k.value), exclusive: false };\n else if (k.operator === \">\") min = { value: Number(k.value), exclusive: true };\n else if (k.operator === \"<=\") max = { value: Number(k.value), exclusive: false };\n else if (k.operator === \"<\") max = { value: Number(k.value), exclusive: true };\n }\n const old = target === \"openapi-3.0\";\n if (min) {\n if (min.exclusive && !old) out.exclusiveMinimum = min.value;\n else {\n out.minimum = min.value;\n if (min.exclusive) out.exclusiveMinimum = true;\n }\n }\n if (max) {\n if (max.exclusive && !old) out.exclusiveMaximum = max.value;\n else {\n out.maximum = max.value;\n if (max.exclusive) out.exclusiveMaximum = true;\n }\n }\n}\nfunction cardinalityBounds(c, cardinalities) {\n if (!c.arrayDimensions) return {};\n const out = {};\n for (const k of cardinalities.filter((x) => x.column === c.name)) {\n const n = Number(k.value);\n if (k.operator === \">=\") out.minItems = n;\n else if (k.operator === \">\") out.minItems = n + 1;\n else if (k.operator === \"<=\") out.maxItems = n;\n else if (k.operator === \"<\") out.maxItems = n - 1;\n else if (k.operator === \"=\") {\n out.minItems = n;\n out.maxItems = n;\n }\n }\n return out;\n}\nfunction makeNullable(s, target) {\n if (target === \"openapi-3.0\") return { ...s, nullable: true };\n if (s.type === void 0) {\n if (Array.isArray(s.enum)) return { ...s, enum: [...s.enum, null] };\n if (\"const\" in s) {\n const { const: k, ...rest } = s;\n return { ...rest, enum: [k, null] };\n }\n return s;\n }\n return { ...s, type: [s.type, \"null\"] };\n}\nfunction columnSchema(c, mode, target, checks, sets, lengths, cardinalities, applyDefault) {\n let s = baseSchema(c, mode, target, checks, sets, lengths);\n const dims = c.arrayDimensions ?? 0;\n for (let i = 0; i < dims; i++) {\n s = { type: \"array\", items: s, ...i === dims - 1 ? cardinalityBounds(c, cardinalities) : {} };\n }\n if (c.nullable) s = makeNullable(s, target);\n if (mode === \"insert\" && applyDefault && c.defaultValue !== void 0) {\n s = { ...s, default: c.defaultValue };\n }\n return s;\n}\nfunction rowDescription(rows, cols) {\n const present = new Set(cols.map((c) => c.name));\n const applicable = rows.filter((r) => present.has(r.left) && present.has(r.right));\n if (!applicable.length) return void 0;\n const list = applicable.map((r) => `${r.name ? `${r.name}: ` : \"\"}${r.left} ${r.operator} ${r.right}`).join(\"; \");\n return `Row constraints not expressible in JSON Schema: ${list}`;\n}\nfunction tableSchema(table, cols, mode, target, applyDefaults, parsed) {\n const properties = {};\n const required = [];\n for (const c of cols) {\n properties[c.name] = columnSchema(\n c,\n mode,\n target,\n parsed.checks,\n parsed.sets,\n parsed.lengths,\n parsed.cardinalities,\n applyDefaults\n );\n const suppliedOnInsert = c.hasDefault || applyDefaults && c.defaultValue !== void 0 || c.isGenerated;\n const optional = mode === \"update\" || mode === \"insert\" && suppliedOnInsert;\n if (!optional) required.push(c.name);\n }\n const desc = rowDescription(parsed.rows, cols);\n return {\n ...target === \"draft-2020-12\" ? { $schema: DRAFT } : {},\n $id: `${table.tsName}.${mode}`,\n title: `${mode} ${table.tsName}`,\n ...desc ? { description: desc } : {},\n type: \"object\",\n properties,\n ...required.length ? { required } : {},\n additionalProperties: false\n };\n}\nfunction collect(table) {\n const parsed = (table.checks ?? []).map((k) => parseCheck(k.expression, k.name));\n return {\n checks: parsed.flatMap((p) => p.ok ? p.checks : []),\n sets: parsed.flatMap((p) => p.ok ? p.sets ?? [] : []),\n rows: parsed.flatMap((p) => p.ok ? p.rows ?? [] : []),\n lengths: parsed.flatMap((p) => p.ok ? p.lengths ?? [] : []),\n cardinalities: parsed.flatMap((p) => p.ok ? p.cardinalities ?? [] : [])\n };\n}\nfunction tableSchemas(table, opts = {}) {\n const target = opts.target ?? \"draft-2020-12\";\n const parsed = collect(table);\n const build2 = (cols, mode) => tableSchema(table, cols, mode, target, !!opts.applyDefaults, parsed);\n return {\n insert: build2(insertColumns(table), \"insert\"),\n update: build2(updateColumns(table), \"update\"),\n select: build2(selectColumns(table), \"select\")\n };\n}\nfunction componentsDocument(tables, opts = {}) {\n const schemas = {};\n for (const table of tables) {\n const built = tableSchemas(table, opts);\n for (const mode of [\"insert\", \"update\", \"select\"]) {\n const name = `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;\n const { $schema: _dialect, $id: _id, ...rest } = built[mode];\n schemas[name] = rest;\n }\n }\n return { schemas };\n}\n\n// src/openapi.ts\nvar ERROR_SCHEMA = \"Error\";\nvar componentName = (table, mode) => `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;\nvar ref = (name) => ({ $ref: `#/components/schemas/${name}` });\nvar pascal = (s) => s.charAt(0).toUpperCase() + s.slice(1);\nfunction keyColumns(table) {\n const names = table.primaryKey?.columns ?? [];\n if (!names.length) return null;\n const cols = names.map((n) => table.columns.find((c) => c.name === n));\n if (cols.some((c) => !c)) return null;\n return cols;\n}\nvar modesFor = (table, key) => [\n ...table.readOnly ? [] : [\"insert\"],\n ...table.readOnly || !key ? [] : [\"update\"],\n \"select\"\n];\nvar resourceSegment = (table) => encodeURIComponent(table.name);\nfunction foreignKeysOf(table) {\n if (table.foreignKeys?.length) return table.foreignKeys;\n return table.columns.filter((c) => c.references).map((c) => ({\n columns: [c.name],\n foreignTable: c.references.table,\n foreignColumns: [c.references.column]\n }));\n}\nvar jsonBody = (schema) => ({ content: { \"application/json\": { schema } } });\nfunction build(tables, opts) {\n const target = opts.target ?? \"draft-2020-12\";\n const schemaTarget = target === \"openapi-3.0\" ? \"openapi-3.0\" : \"openapi-3.1\";\n const failure = String(opts.validationStatus ?? 400);\n const paths = {};\n const schemas = {};\n const tags = [];\n const operationIds = /* @__PURE__ */ new Map();\n const owner = /* @__PURE__ */ new Map();\n const claim = (path, by, label) => {\n const taken = owner.get(path);\n if (taken !== void 0 && taken.by !== by) {\n throw new Error(\n `@drzl/generator-json-schema: the OpenAPI path \"${path}\" is claimed twice: by table \"${taken.label}\" (exported as ${taken.by}) and by table \"${label}\" (exported as ${by}). A path names one resource, so one of the two has to be left out of this generator with the config's \"exclude\" list.`\n );\n }\n owner.set(path, { by, label });\n };\n const operation = (id, table, rest) => {\n const clash = operationIds.get(id);\n if (clash !== void 0) {\n throw new Error(\n `@drzl/generator-json-schema: the operationId \"${id}\" would be emitted for both \"${clash}\" and \"${table.name}\". An operationId is the method name a client generator derives, and the specification requires it to be unique across the document.`\n );\n }\n operationIds.set(id, table.name);\n return { operationId: id, tags: [table.name], ...rest };\n };\n const built = tables.map((table) => ({\n table,\n key: keyColumns(table),\n segment: resourceSegment(table),\n schemas: tableSchemas(table, { target: schemaTarget, applyDefaults: opts.applyDefaults })\n }));\n for (const { table, key, segment, schemas: built3 } of built) {\n for (const mode of modesFor(table, key)) {\n const { $schema: _dialect, $id: _id, ...rest } = built3[mode];\n schemas[componentName(table, mode)] = rest;\n }\n const notes = [];\n if (!key) notes.push(\"It has no primary key, so no path addresses a single row.\");\n if (table.readOnly) {\n notes.push(\"It refuses every write, so only reads are described.\");\n }\n tags.push({ name: table.name, description: [`Table \"${table.name}\".`, ...notes].join(\" \") });\n const T = pascal(table.tsName);\n const select = ref(componentName(table, \"select\"));\n const validationFailed = {\n description: \"The request does not match the schema for this operation.\",\n ...jsonBody(ref(ERROR_SCHEMA))\n };\n const collidable = [\n ...table.primaryKey ? [`primary key (${table.primaryKey.columns.join(\", \")})`] : [],\n ...table.unique.map((u) => `${u.name ? `${u.name} ` : \"\"}(${u.columns.join(\", \")})`)\n ];\n const conflict = (constraints) => ({\n description: `The row collides with an existing one on ${constraints.join(\"; \")}.`,\n ...jsonBody(ref(ERROR_SCHEMA))\n });\n const collection = `/${segment}`;\n claim(collection, table.tsName, table.name);\n const item = {\n get: operation(`list${T}`, table, {\n summary: `List every ${table.name} row.`,\n // No pagination parameters. Whether the server implements a limit, an offset or a cursor is\n // not something a Drizzle schema states, and a declared parameter nothing honours is worse\n // than an undeclared one.\n responses: {\n \"200\": {\n description: `Every ${table.name} row.`,\n ...jsonBody({ type: \"array\", items: select })\n }\n }\n })\n };\n if (!table.readOnly) {\n item.post = operation(`create${T}`, table, {\n summary: `Create a ${table.name} row.`,\n requestBody: { required: true, ...jsonBody(ref(componentName(table, \"insert\"))) },\n responses: {\n \"201\": { description: `The ${table.name} row that was created.`, ...jsonBody(select) },\n [failure]: validationFailed,\n ...collidable.length ? { \"409\": conflict(collidable) } : {}\n }\n });\n }\n paths[collection] = item;\n if (!key) continue;\n const itemPath = `${collection}/${key.map((c) => `{${c.name}}`).join(\"/\")}`;\n claim(itemPath, table.tsName, table.name);\n const parameters = key.map((c) => ({\n name: c.name,\n in: \"path\",\n required: true,\n description: `${c.name}, from the primary key of ${table.name}.`,\n // The column's own schema rather than a string, so an integer key is declared as one and a\n // uuid key carries its format. This is the whole point of reading the real key.\n schema: built3.select.properties[c.name] ?? {}\n }));\n const missing = {\n description: `No ${table.name} row has that ${key.map((c) => c.name).join(\" and \")}.`,\n ...jsonBody(ref(ERROR_SCHEMA))\n };\n const byId = {\n parameters,\n get: operation(`get${T}`, table, {\n summary: `Read one ${table.name} row.`,\n responses: {\n \"200\": { description: `The requested ${table.name} row.`, ...jsonBody(select) },\n [failure]: validationFailed,\n \"404\": missing\n }\n })\n };\n if (!table.readOnly) {\n byId.patch = operation(`update${T}`, table, {\n summary: `Patch one ${table.name} row.`,\n requestBody: { required: true, ...jsonBody(ref(componentName(table, \"update\"))) },\n responses: {\n \"200\": { description: `The ${table.name} row after the patch.`, ...jsonBody(select) },\n [failure]: validationFailed,\n \"404\": missing,\n // The primary key is not in the update schema, so a patch cannot collide on it. Only a\n // unique constraint over other columns can.\n ...table.unique.length ? {\n \"409\": conflict(\n table.unique.map((u) => `${u.name ? `${u.name} ` : \"\"}(${u.columns.join(\", \")})`)\n )\n } : {}\n }\n });\n byId.delete = operation(`delete${T}`, table, {\n summary: `Delete one ${table.name} row.`,\n responses: {\n // No body. Handing back the deleted row is the alternative and it is not a true statement\n // on every dialect DRZL supports: RETURNING is Postgres and SQLite, and MySQL has no such\n // clause, so an implementation there has nothing to send.\n \"204\": { description: `The ${table.name} row was deleted. No content is returned.` },\n [failure]: validationFailed,\n \"404\": missing\n }\n });\n }\n paths[itemPath] = byId;\n if (!opts.includeRelations) continue;\n for (const child of built) {\n if (child.table === table) continue;\n const matching = foreignKeysOf(child.table).filter(\n (fk) => fk.foreignTable === table.name && fk.foreignColumns.length === key.length && fk.foreignColumns.every((c, i) => c === key[i].name)\n );\n if (matching.length !== 1) continue;\n const subPath = `${itemPath}/${child.segment}`;\n claim(\n subPath,\n `${table.tsName} -> ${child.table.tsName}`,\n `${table.name} -> ${child.table.name}`\n );\n paths[subPath] = {\n parameters,\n get: operation(`list${T}${pascal(child.table.tsName)}`, child.table, {\n summary: `List the ${child.table.name} rows belonging to one ${table.name} row.`,\n responses: {\n \"200\": {\n description: `The ${child.table.name} rows whose ${matching[0].columns.join(\", \")} names this ${table.name} row.`,\n ...jsonBody({ type: \"array\", items: ref(componentName(child.table, \"select\")) })\n },\n [failure]: validationFailed,\n \"404\": missing\n }\n })\n };\n }\n }\n return { paths, schemas, tags };\n}\nvar errorSchema = () => ({\n title: \"error\",\n description: \"What an operation returns when it does not return the row.\",\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n code: { type: \"string\" }\n },\n required: [\"message\"],\n additionalProperties: true\n});\nfunction openApiDocument(tables, opts = {}) {\n const target = opts.target ?? \"draft-2020-12\";\n const { paths, schemas, tags } = build(tables, opts);\n if (ERROR_SCHEMA in schemas) {\n throw new Error(\n `@drzl/generator-json-schema: a table produced the component schema name \"${ERROR_SCHEMA}\", which the document already uses for its error responses.`\n );\n }\n return {\n openapi: target === \"openapi-3.0\" ? \"3.0.3\" : \"3.1.1\",\n info: {\n title: opts.info?.title ?? \"API\",\n version: opts.info?.version ?? \"0.0.0\",\n description: opts.info?.description ?? \"Generated by DRZL from a Drizzle schema. Paths, request bodies and response bodies are derived from the schema alone; nothing here has been checked against a running server.\"\n },\n ...opts.servers?.length ? { servers: opts.servers } : {},\n paths,\n components: { schemas: { ...schemas, [ERROR_SCHEMA]: errorSchema() } },\n tags\n };\n}\n\n// src/index.ts\nvar DEFAULT_FILE_SUFFIX = \".schema.ts\";\nfunction renderTableModule(table, affix, target, applyDefaults) {\n const T = table.tsName;\n const schemas = tableSchemas(table, { target, applyDefaults });\n const decl = (mode) => `export const ${schemaName(mode, T, affix)} = ${JSON.stringify(schemas[mode], null, 2)} as const;\n\nexport type ${typeName(mode, T, affix)} = typeof ${schemaName(mode, T, affix)};`;\n return [decl(\"insert\"), decl(\"update\"), decl(\"select\")].join(\"\\n\\n\") + \"\\n\";\n}\nfunction resolveDocument(opt) {\n if (!opt) return null;\n const o = opt === true ? {} : opt;\n if (o.enabled === false) return null;\n return { ...o, format: o.format ?? \"ts\" };\n}\nvar JsonSchemaGenerator = class {\n constructor(analysis) {\n this.analysis = analysis;\n this.library = \"json-schema\";\n }\n async generate(opts) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const out = path.resolve(process.cwd(), opts.outDir);\n const files = [];\n await fs.mkdir(out, { recursive: true });\n const affix = resolveAffix(opts);\n const fileSuffix = opts.fileSuffix ?? DEFAULT_FILE_SUFFIX;\n const target = opts.target ?? \"draft-2020-12\";\n const document = resolveDocument(opts.document);\n for (const table of this.analysis.tables) {\n const filePath = path.join(out, moduleFileName(table.tsName, fileSuffix));\n const code = renderTableModule(table, affix, target, !!opts.applyDefaults);\n const formatted = await formatCode(\n buildHeader(opts.outputHeader) + code,\n filePath,\n opts.format\n );\n await fs.writeFile(filePath, formatted, \"utf8\");\n files.push(filePath);\n }\n if (opts.components) {\n const doc = componentsDocument(this.analysis.tables, {\n target,\n applyDefaults: !!opts.applyDefaults\n });\n const componentsPath = path.join(out, \"components.ts\");\n const code = `export const components = ${JSON.stringify(doc, null, 2)} as const;\n`;\n await fs.writeFile(\n componentsPath,\n await formatCode(buildHeader(opts.outputHeader) + code, componentsPath, opts.format),\n \"utf8\"\n );\n files.push(componentsPath);\n }\n if (document) {\n const built = openApiDocument(this.analysis.tables, {\n target,\n applyDefaults: !!opts.applyDefaults,\n includeRelations: !!opts.includeRelations,\n info: document.info,\n servers: document.servers,\n validationStatus: document.validationStatus\n });\n const body = JSON.stringify(built, null, 2);\n if (document.format !== \"json\") {\n const tsPath = path.join(out, \"openapi.ts\");\n const code = `export const openapi = ${body} as const;\n`;\n await fs.writeFile(\n tsPath,\n await formatCode(buildHeader(opts.outputHeader) + code, tsPath, opts.format),\n \"utf8\"\n );\n files.push(tsPath);\n }\n if (document.format !== \"ts\") {\n const jsonPath = path.join(out, \"openapi.json\");\n await fs.writeFile(jsonPath, body + \"\\n\", \"utf8\");\n files.push(jsonPath);\n }\n }\n const ext = opts.importExtension === \"none\" ? \"\" : \".js\";\n const indexPath = path.join(out, \"index.ts\");\n const index = this.analysis.tables.map(\n (t) => `export * from '${moduleSpecifier(t.tsName, fileSuffix, opts.importExtension)}';`\n ).concat(opts.components ? [`export * from './components${ext}';`] : []).concat(document && document.format !== \"json\" ? [`export * from './openapi${ext}';`] : []).join(\"\\n\") + \"\\n\";\n const indexFormatted = await formatCode(\n buildHeader(opts.outputHeader) + index,\n indexPath,\n opts.format\n );\n await fs.writeFile(indexPath, indexFormatted, \"utf8\");\n files.push(indexPath);\n return files;\n }\n renderTable(table, opts) {\n return renderTableModule(\n table,\n resolveAffix(opts),\n opts?.target ?? \"draft-2020-12\",\n !!opts?.applyDefaults\n );\n }\n};\nvar index_default = JsonSchemaGenerator;\nfunction buildHeader(h) {\n if (h?.enabled === false) return \"\";\n const text = h?.text ?? \"// Generated by DRZL. Do not edit by hand.\";\n return `${text}\n\n`;\n}\nexport {\n DRAFT,\n JsonSchemaGenerator,\n componentsDocument,\n index_default as default,\n openApiDocument,\n tableSchemas\n};\n","#!/usr/bin/env node\nimport { SchemaAnalyzer } from '@drzl/analyzer';\nimport { ORPCGenerator } from '@drzl/generator-orpc';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport cliProgress from 'cli-progress';\nimport { Command } from 'commander';\nimport * as path from 'node:path';\nimport ora from 'ora';\nimport { jsonSchemaOptions } from './json-schema-options.js';\nimport { trpcOptions } from './trpc-options.js';\nimport { validationOptions } from './validation-options';\nimport {\n computeGeneratorOutputDirs,\n computeWatchTargets,\n DrzlConfig,\n filterTables,\n loadConfig,\n} from './config.js';\nimport { diffSnapshots, restoreSnapshot, snapshotAll } from './drift.js';\nimport { GeneratorNotInstalledError, loadGenerator } from './generator-loader.js';\nimport { maybeShowSponsorMessage } from './sponsor.js';\nimport { CLI_VERSION } from './version.js';\n\n/**\n * Say what went wrong with a generator, distinguishing the two things that can.\n *\n * Every branch below used to print \"<name> generator missing. Install with: npm install\n * @drzl/generator-<name>\" for anything at all that threw, with the real reason on a trailing\n * \"Error details\" line. A generator that was installed and merely failed therefore sent its user\n * to reinstall a package they already had, and the sentence that would have told them what\n * actually happened was the one written as a footnote.\n *\n * `loadGenerator` marks the one case that is an install problem, so the package name comes off the\n * error rather than being repeated here beside the `import()` that already spells it.\n */\nfunction reportGeneratorFailure(kind: string, e: unknown): void {\n if (e instanceof GeneratorNotInstalledError) {\n console.error(\n chalk.red(`The ${kind} generator is not installed.`),\n chalk.yellow(`\\nInstall with: npm install ${e.specifier}`)\n );\n return;\n }\n console.error(chalk.red(`The ${kind} generator failed:`), (e as any)?.message ?? e);\n}\n\nconst program = new Command();\nprogram.name('drzl').description('DRZL - Drizzle Developer Toolkit').version(CLI_VERSION);\nprogram.addHelpText(\n 'afterAll',\n `\\nNeed a template, adapter, or generator DRZL doesn't ship yet?\\n→ DM @omardulaimidev on X: https://x.com/omardulaimidev\\n`\n);\n\nprogram\n .command('analyze')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('--relations', 'include relations', true)\n .option('--validate', 'validate constraints', true)\n .option('--out <file>', 'write analysis JSON to file')\n .option('--json', 'print JSON to stdout (overrides --out)', false)\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const spinner = !opts.json ? ora('Analyzing schema...').start() : null;\n const start = Date.now();\n const res = await analyzer.analyze({\n includeRelations: !!opts.relations,\n validateConstraints: !!opts.validate,\n });\n const ms = Date.now() - start;\n const json = JSON.stringify(res, null, 2);\n if (opts.json) {\n console.log(json);\n } else if (opts.out) {\n const fs = await import('node:fs/promises');\n await fs.writeFile(opts.out, json, 'utf8');\n spinner?.succeed(chalk.green(`Analysis written to ${opts.out} in ${ms}ms`));\n } else {\n spinner?.succeed(chalk.green(`Analyzed in ${ms}ms`));\n console.log(json);\n }\n process.exit(res.issues.some((i) => i.level === 'error') ? 2 : 0);\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n if (opts.json)\n console.log(JSON.stringify({ event: 'error', code: 'DRZL_CLI_ANALYZE', message: msg }));\n else\n console.error(\n chalk.red('Analyze failed (DRZL_CLI_ANALYZE):'),\n msg,\n '\\nTip: run with --json for structured output.'\n );\n process.exit(1);\n }\n });\n\nprogram\n .command('generate')\n .description('Run configured generators (drzl.config.*)')\n .option('-c, --config <path>', 'path to drzl.config')\n .option(\n '--check',\n 'regenerate and fail if the result differs from what is on disk, without changing it'\n )\n .action(async (opts: any) => {\n try {\n const cfg = await loadConfig(opts.config);\n if (!cfg) {\n console.error(\n chalk.red('No config found (DRZL_CFG_001). Create drzl.config.ts or pass --config.')\n );\n process.exit(2);\n return;\n }\n const analyzer = new SchemaAnalyzer(cfg.schema);\n const spinner = ora('Analyzing...').start();\n const t0 = Date.now();\n const analysis = await analyzer.analyze({\n includeRelations: cfg.analyzer.includeRelations,\n validateConstraints: cfg.analyzer.validateConstraints,\n includeHeuristicRelations: cfg.analyzer.includeHeuristicRelations,\n });\n // Applied before any generator sees the analysis, so every one of them honours it without\n // needing to know the option exists.\n analysis.tables = filterTables(analysis.tables, cfg);\n spinner.succeed(`Analysis complete in ${Date.now() - t0}ms`);\n reportWideColumns(analysis.issues);\n // Under --check the existing output is captured before anything overwrites it, so the\n // regenerated result can be compared against it and the tree put back either way.\n const driftDirs = computeGeneratorOutputDirs(cfg);\n const driftBefore = opts.check ? await snapshotAll(driftDirs) : null;\n const progress = new cliProgress.SingleBar(\n { hideCursor: true },\n cliProgress.Presets.shades_classic\n );\n const total = analysis.tables.length || 1;\n progress.start(total, 0);\n // Where the service generator is actually writing, so a router template that imports\n // services spells a path that exists. Templates default this to 'src/services', and with\n // nothing passed that default was used no matter where the services really went, emitting\n // an import of a module that was never created. Must match the `g.path ?? 'src/services'`\n // used by the service branch below.\n const servicesDir =\n cfg.generators.find((x: { kind: string }) => x.kind === 'service')?.path ?? 'src/services';\n for (const g of cfg.generators) {\n if (g.kind === 'orpc') {\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: cfg.outDir,\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n templateOptions: g.templateOptions,\n importExtension: g.importExtension,\n validation: g.validation,\n // Documented on this generator since it was added and never reachable from a config\n // file, because the config schema had no such key and zod stripped it in silence.\n databaseInjection: g.databaseInjection,\n servicesDir,\n onProgress: ({ index }) => progress.update(index),\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (${g.kind}): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } else if (g.kind === 'trpc') {\n try {\n // An optional dependency, like the json-schema generator and unlike oRPC. A package\n // that has never been published cannot publish through npm's trusted-publisher OIDC\n // flow, so its first version has to go out by hand; naming it as a hard dependency of\n // the CLI in the same release breaks `npm i @drzl/cli` for everyone until it exists.\n // A missing optional dependency is skipped by the installer rather than failing it,\n // which is why this one really can be absent on an ordinary install.\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n const { files } = await gen.generate({\n ...trpcOptions(g, cfg, servicesDir),\n onProgress: ({ index }: { index: number }) => progress.update(index),\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (trpc): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'service') {\n try {\n const { ServiceGenerator } = await loadGenerator(\n '@drzl/generator-service',\n () => import('@drzl/generator-service')\n );\n const gen = new ServiceGenerator(analysis);\n const target = g.path ?? 'src/services';\n const files = await gen.generate({\n outDir: target,\n outputHeader: g.outputHeader,\n format: g.format,\n dataAccess: g.dataAccess,\n dbImportPath: g.dbImportPath,\n schemaImportPath: g.schemaImportPath,\n importExtension: g.importExtension,\n // The other half of `databaseInjection`. A router generator in injection mode\n // emits `Service.getById(ctx.db, id)`, and only a service generated in the same\n // mode has a `db` parameter to receive it. This branch never passed the option, so\n // the two halves of one generated project disagreed about the signature.\n databaseInjection: g.databaseInjection,\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (service): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'zod') {\n try {\n const { ZodGenerator } = await loadGenerator(\n '@drzl/generator-zod',\n () => import('@drzl/generator-zod')\n );\n const gen = new ZodGenerator(analysis);\n const target = g.path ?? 'src/validators/zod';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (zod): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'valibot') {\n try {\n const { ValibotGenerator } = await loadGenerator(\n '@drzl/generator-valibot',\n () => import('@drzl/generator-valibot')\n );\n const gen = new ValibotGenerator(analysis);\n const target = g.path ?? 'src/validators/valibot';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (valibot): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'arktype') {\n try {\n const { ArkTypeGenerator } = await loadGenerator(\n '@drzl/generator-arktype',\n () => import('@drzl/generator-arktype')\n );\n const gen = new ArkTypeGenerator(analysis);\n const target = g.path ?? 'src/validators/arktype';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: false }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (arktype): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'json-schema') {\n try {\n // An optional dependency, unlike the other generators, until its npm trusted publisher\n // exists. A missing optional dependency is skipped rather than failing the install,\n // which is what keeps `npm i @drzl/cli` working meanwhile, and is why this one really\n // can be absent on a normal install.\n const { JsonSchemaGenerator } = await loadGenerator(\n '@drzl/generator-json-schema',\n () => import('@drzl/generator-json-schema')\n );\n const gen = new JsonSchemaGenerator(analysis);\n const target = g.path ?? 'src/validators/json-schema';\n const files = await gen.generate(jsonSchemaOptions(g, cfg, target) as never);\n progress.stop();\n ora().succeed(chalk.green(`Generated (json-schema): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'typebox') {\n try {\n const { TypeBoxGenerator } = await loadGenerator(\n '@drzl/generator-typebox',\n () => import('@drzl/generator-typebox')\n );\n const gen = new TypeBoxGenerator(analysis);\n const target = g.path ?? 'src/validators/typebox';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (typebox): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n }\n }\n if (driftBefore) {\n const after = await snapshotAll(driftDirs);\n const drift = diffSnapshots(driftBefore, after);\n // Restored whether or not anything drifted, so `--check` never leaves the tree altered.\n await restoreSnapshot(driftBefore, after);\n\n if (drift.length) {\n console.error(chalk.red(`\\nGenerated output is out of date (${drift.length} file(s)):`));\n for (const d of drift) {\n const mark = d.status === 'added' ? '+' : d.status === 'removed' ? '-' : '~';\n console.error(\n ` ${mark} ${chalk.yellow(d.status.padEnd(8))} ${path.relative(process.cwd(), d.file)}`\n );\n }\n console.error(\n chalk.dim(\n '\\nRun `drzl generate` and commit the result. Nothing was written by this check.'\n )\n );\n process.exit(1);\n }\n console.log(chalk.green('Generated output is up to date.'));\n return;\n }\n\n if (cfg.generators.length) {\n maybeShowSponsorMessage({ reason: 'generate' });\n }\n } catch (e: any) {\n console.error(\n chalk.red('Generate failed (DRZL_GEN_001):'),\n e?.message ?? e,\n '\\nTip: check your drzl.config.ts and template path.'\n );\n process.exit(1);\n }\n });\n\nprogram\n .command('generate:orpc')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('-o, --outDir <dir>', 'output directory', 'src/api')\n .option('--template <name>', 'template name', 'standard')\n .option('--includeRelations', 'include relation endpoints')\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const analysis = await analyzer.analyze({\n includeRelations: !!opts.includeRelations,\n validateConstraints: true,\n });\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: opts.outDir,\n template: opts.template,\n includeRelations: !!opts.includeRelations,\n });\n console.log(chalk.green(`Generated:`), files.map((f) => chalk.cyan(f)).join(', '));\n maybeShowSponsorMessage({ reason: 'generate:orpc' });\n } catch (e: any) {\n console.error(chalk.red('Generate orpc failed:'), e?.message ?? e);\n process.exit(1);\n }\n });\n\nprogram\n .command('generate:trpc')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('-o, --outDir <dir>', 'output directory', 'src/api')\n .option('--template <name>', 'standard | service', 'standard')\n .option('--includeRelations', 'include relation endpoints')\n .option('--servicesDir <dir>', 'where the service generator writes', 'src/services')\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const analysis = await analyzer.analyze({\n includeRelations: !!opts.includeRelations,\n validateConstraints: true,\n });\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: opts.outDir,\n template: opts.template,\n includeRelations: !!opts.includeRelations,\n // Only consulted by `--template service`, and passed unconditionally so this command\n // cannot become the branch that forgets it.\n servicesDir: opts.servicesDir,\n });\n console.log(chalk.green(`Generated:`), files.map((f: string) => chalk.cyan(f)).join(', '));\n maybeShowSponsorMessage({ reason: 'generate:trpc' });\n } catch (e: any) {\n reportGeneratorFailure('trpc', e);\n process.exit(1);\n }\n });\n\nprogram\n .command('watch')\n .description('Watch schema and regenerate on changes')\n .option('-c, --config <path>', 'path to drzl.config')\n .option('--pipeline <name>', 'all | analyze | generate-orpc | generate-trpc', 'all')\n .option('--debounce <ms>', 'debounce ms', '200')\n .option('--json', 'emit JSON logs', false)\n .option('--poll', 'force polling (helps WSL/Docker/remote FS)', false)\n .action(async (opts: any) => {\n let cfg = await loadConfig(opts.config);\n if (!cfg) {\n console.error(chalk.red('No config found. Create drzl.config.ts or pass --config.'));\n process.exit(2);\n return;\n }\n\n const abs = (p: string) => path.resolve(process.cwd(), p);\n const isInside = (child: string, parent: string) => {\n const rel = path.relative(parent, child);\n return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);\n };\n\n const ignoredOutDirs = new Set<string>(computeGeneratorOutputDirs(cfg).map(abs));\n const currentTargets = new Set<string>(computeWatchTargets(cfg).map(abs));\n\n const syncWatcherTargets = (watcher: import('chokidar').FSWatcher, next: Set<string>) => {\n const add: string[] = [];\n const del: string[] = [];\n for (const p of next) if (!currentTargets.has(p)) add.push(p);\n for (const p of currentTargets) if (!next.has(p)) del.push(p);\n if (add.length) watcher.add(add);\n if (del.length) watcher.unwatch(del);\n currentTargets.clear();\n next.forEach((p) => currentTargets.add(p));\n };\n\n const rebuildIgnoreDirsFrom = (cfgNow: DrzlConfig) => {\n ignoredOutDirs.clear();\n for (const d of computeGeneratorOutputDirs(cfgNow)) ignoredOutDirs.add(abs(d));\n };\n\n // Watch targets are directories now, because chokidar v4 dropped glob support. The\n // extensions the old `**/*.{ts,tsx,js}` glob selected therefore have to be filtered here\n // instead, or every unrelated file in the schema's directory would trigger a rebuild.\n const WATCHED_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs', '.cjs']);\n\n const ignoredFn = (p: string, stats?: { isDirectory(): boolean }) => {\n const full = abs(p);\n for (const dir of ignoredOutDirs) {\n if (full === dir || isInside(full, dir)) return true;\n }\n // A directory is never ignored: chokidar has to descend into it to reach the files.\n if (stats?.isDirectory()) return false;\n const ext = path.extname(full);\n // Without stats chokidar is asking about a path it has not resolved yet. An extensionless\n // one is almost certainly a directory, so let it through and decide once it is known.\n if (!ext) return false;\n return !WATCHED_EXTENSIONS.has(ext);\n };\n\n const watcher = chokidar.watch(Array.from(currentTargets), {\n ignoreInitial: true,\n awaitWriteFinish: { stabilityThreshold: 400, pollInterval: 50 },\n usePolling: !!opts.poll,\n ignored: ignoredFn,\n });\n\n const logTrigger = (type: 'add' | 'change' | 'unlink', file: string) => {\n if (opts.json) console.log(JSON.stringify({ event: 'trigger', type, file }));\n };\n\n watcher\n .on('add', (p) => {\n logTrigger('add', p);\n trigger(p);\n })\n .on('change', (p) => {\n logTrigger('change', p);\n trigger(p);\n })\n .on('unlink', (p) => {\n logTrigger('unlink', p);\n trigger(p);\n });\n\n let lastFiles: string[] = [];\n\n const run = async () => {\n try {\n const reloaded = await loadConfig(opts.config);\n if (!reloaded) throw new Error('Config disappeared during watch.');\n cfg = reloaded;\n\n rebuildIgnoreDirsFrom(cfg);\n const nextTargets = new Set<string>(computeWatchTargets(cfg).map(abs));\n syncWatcherTargets(watcher, nextTargets);\n\n if (!opts.json) console.clear();\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'watch_config_applied',\n targets: Array.from(currentTargets),\n ignored: Array.from(ignoredOutDirs),\n })\n );\n }\n\n const analyzer = new SchemaAnalyzer(cfg.schema);\n const analysis = await analyzer.analyze({\n includeRelations: cfg.analyzer.includeRelations,\n validateConstraints: cfg.analyzer.validateConstraints,\n includeHeuristicRelations: cfg.analyzer.includeHeuristicRelations,\n });\n analysis.tables = filterTables(analysis.tables, cfg);\n if (!opts.json) reportWideColumns(analysis.issues);\n\n if (opts.pipeline === 'analyze') {\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'analyze_complete',\n issues: analysis.issues,\n tables: analysis.tables.length,\n })\n );\n } else {\n console.log(chalk.green('Analyze complete.'));\n }\n return;\n }\n\n const newFiles: string[] = [];\n\n // Must match the `g.path ?? 'src/services'` the service branch below uses, or a router\n // template that imports services spells a path nothing ever wrote. `generate` has always\n // computed this; `watch` did not, so a rebuild silently emitted the default.\n const servicesDir =\n cfg.generators.find((x: { kind: string }) => x.kind === 'service')?.path ??\n 'src/services';\n\n const PIPELINE_KINDS: Record<string, string> = {\n 'generate-orpc': 'orpc',\n 'generate-trpc': 'trpc',\n };\n\n for (const g of cfg.generators) {\n if (opts.pipeline !== 'all' && PIPELINE_KINDS[opts.pipeline] !== g.kind) {\n continue;\n }\n\n if (g.kind === 'orpc') {\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: cfg.outDir,\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n templateOptions: g.templateOptions,\n importExtension: g.importExtension,\n validation: g.validation,\n databaseInjection: g.databaseInjection,\n servicesDir,\n });\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (${g.kind}):`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } else if (g.kind === 'trpc') {\n try {\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n // The same builder `generate` uses, so the two dispatch loops cannot disagree\n // about what this generator is given.\n const { files } = await gen.generate(trpcOptions(g, cfg, servicesDir));\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (trpc): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'service') {\n try {\n const { ServiceGenerator } = await loadGenerator(\n '@drzl/generator-service',\n () => import('@drzl/generator-service')\n );\n const gen = new ServiceGenerator(analysis);\n const target = g.path ?? 'src/services';\n const files = await gen.generate({\n outDir: target,\n outputHeader: g.outputHeader,\n format: g.format,\n dataAccess: g.dataAccess,\n dbImportPath: g.dbImportPath,\n schemaImportPath: g.schemaImportPath,\n importExtension: g.importExtension,\n databaseInjection: g.databaseInjection,\n });\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (service): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'zod') {\n try {\n const { ZodGenerator } = await loadGenerator(\n '@drzl/generator-zod',\n () => import('@drzl/generator-zod')\n );\n const gen = new ZodGenerator(analysis);\n const target = g.path ?? 'src/validators/zod';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (zod): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'valibot') {\n try {\n const { ValibotGenerator } = await loadGenerator(\n '@drzl/generator-valibot',\n () => import('@drzl/generator-valibot')\n );\n const gen = new ValibotGenerator(analysis);\n const target = g.path ?? 'src/validators/valibot';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (valibot): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'arktype') {\n try {\n const { ArkTypeGenerator } = await loadGenerator(\n '@drzl/generator-arktype',\n () => import('@drzl/generator-arktype')\n );\n const gen = new ArkTypeGenerator(analysis);\n const target = g.path ?? 'src/validators/arktype';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: false }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (arktype): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'typebox') {\n try {\n const { TypeBoxGenerator } = await loadGenerator(\n '@drzl/generator-typebox',\n () => import('@drzl/generator-typebox')\n );\n const gen = new TypeBoxGenerator(analysis);\n const target = g.path ?? 'src/validators/typebox';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (typebox): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'json-schema') {\n try {\n const { JsonSchemaGenerator } = await loadGenerator(\n '@drzl/generator-json-schema',\n () => import('@drzl/generator-json-schema')\n );\n const gen = new JsonSchemaGenerator(analysis);\n const target = g.path ?? 'src/validators/json-schema';\n // The same builder `generate` uses, so the two dispatch loops cannot disagree about\n // what this generator is given.\n const files = await gen.generate(jsonSchemaOptions(g, cfg, target) as never);\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (json-schema): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n }\n }\n\n const added = newFiles.filter((f) => !lastFiles.includes(f));\n const removed = lastFiles.filter((f) => !newFiles.includes(f));\n opts.json\n ? console.log(JSON.stringify({ event: 'diff', added, removed }))\n : (() => {\n if (added.length) console.log(chalk.blue(`Added: ${added.join(', ')}`));\n if (removed.length) console.log(chalk.yellow(`Removed: ${removed.join(', ')}`));\n })();\n if (newFiles.length && !opts.json) {\n const reason =\n opts.pipeline && opts.pipeline !== 'all' ? `watch:${opts.pipeline}` : 'watch';\n maybeShowSponsorMessage({ reason });\n }\n lastFiles = newFiles;\n } catch (e: any) {\n opts.json\n ? console.log(JSON.stringify({ event: 'error', message: String(e?.message ?? e) }))\n : console.error(chalk.red('Watch pipeline failed:'), e?.message ?? e);\n }\n };\n\n const debounced = Number(opts.debounce) || 200;\n let timer: NodeJS.Timeout | null = null;\n const trigger = (file?: string) => {\n if (file) {\n const full = abs(file);\n for (const dir of ignoredOutDirs) {\n if (full === dir || isInside(full, dir)) return;\n }\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(run, debounced);\n };\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'watching',\n targets: Array.from(currentTargets),\n ignored: Array.from(ignoredOutDirs),\n })\n );\n } else {\n console.log(\n chalk.gray(\n 'Watching:\\n ' +\n Array.from(currentTargets)\n .map((p) => path.relative(process.cwd(), p))\n .join('\\n ')\n )\n );\n }\n\n watcher\n .on('add', (p) => trigger(p))\n .on('change', (p) => trigger(p))\n .on('unlink', (p) => trigger(p))\n .on('error', (err) => console.error(chalk.red('Watcher error:'), err));\n\n await run();\n });\n\nprogram\n .command('init')\n .description('Scaffold a drzl.config.ts')\n .option('-y, --yes', 'accept defaults')\n .action(async (_opts: any) => {\n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n const target = path.resolve(process.cwd(), 'drzl.config.ts');\n // One router generator, not both: they default to the same `outDir` and would each write an\n // `index.ts` there, so a scaffold naming both would emit a config whose second generator\n // silently overwrote the first. Swapping the kind is a one-word edit; running both needs a\n // `path` on one of them, which is what the comment says.\n const template = `export default {\n schema: 'src/db/schema.ts',\n outDir: 'src/api',\n analyzer: { includeRelations: true, validateConstraints: true },\n generators: [\n // For tRPC instead: { kind: 'trpc', template: 'standard', includeRelations: true }\n // To run both, give one of them its own \\`path\\`; they share \\`outDir\\` otherwise.\n { kind: 'orpc', template: 'standard', includeRelations: true }\n ]\n} as const\\n`;\n try {\n await fs.writeFile(target, template, { flag: 'wx' });\n console.log(chalk.green(`Created ${target}`));\n } catch (e: any) {\n console.error(chalk.red('Init failed:'), e?.message ?? e);\n process.exit(1);\n }\n });\n\n/**\n * Tell the user which columns got a validator that accepts anything.\n *\n * This is the user-facing half of a check `verify-packed.sh` runs on this repository. Two real\n * bugs took exactly this shape, `.array()` and `pgEnum` columns coming back untyped on\n * drizzle-orm 0.4x, and the only way anyone noticed was reading the generated file. A user whose\n * schema uses a type nobody here has modelled gets the same silence, and no gate of ours helps\n * them.\n *\n * Printed once with a count rather than a line per column, so a schema with fifty custom types\n * stays readable.\n */\nfunction reportWideColumns(issues: Array<{ code?: string; message?: string; hint?: string }>) {\n const wide = issues.filter((i) => i.code === 'DRZL_ANL_UNKNOWN_COLUMN');\n if (!wide.length) return;\n console.warn(\n chalk.yellow(`\\n${wide.length} column${wide.length === 1 ? '' : 's'} could not be typed:`)\n );\n for (const i of wide.slice(0, 10)) console.warn(chalk.gray(` - ${i.message}`));\n if (wide.length > 10) console.warn(chalk.gray(` ... and ${wide.length - 10} more`));\n // One hint for the set, since they are almost always the same two.\n const hints = [...new Set(wide.map((i) => i.hint).filter(Boolean))];\n for (const h of hints) console.warn(chalk.gray(` ${h}`));\n}\n\nprogram.parseAsync(process.argv);\n","/**\n * The options every validation generator receives, built in one place.\n *\n * Each of the four branches used to assemble this by hand, and three documented options were\n * found silently dead as a result: `typedJson` never reached typebox, and `coerceDates` and\n * `applyDefaults` never reached anything but zod. The config parsed them, the CLI dropped them,\n * and the feature simply did nothing while nothing said so. Building it once removes the class\n * rather than fixing each instance.\n *\n * What stays per-generator is a real capability rather than an oversight, which is why it is\n * named as one.\n */\n\n/**\n * A generator entry from the config, loosely typed because the config schema owns its shape.\n *\n * Exported so a builder that wraps this one names the same keys rather than restating them: every\n * key listed in two places is a key the two can drift on, which is the failure this file exists to\n * remove.\n */\nexport type ValidationGeneratorConfig = {\n outputHeader?: unknown;\n format?: unknown;\n schemaSuffix?: unknown;\n fileSuffix?: unknown;\n importExtension?: unknown;\n affix?: unknown;\n coerceDates?: unknown;\n applyDefaults?: unknown;\n typedJson?: unknown;\n typedColumns?: unknown;\n duplicateFinder?: unknown;\n nestedSchemas?: unknown;\n nestedDepth?: unknown;\n};\n\nexport interface GeneratorCapabilities {\n /**\n * Whether the generator can reference a type from the schema module.\n *\n * `typedJson` and `typedColumns` both work by importing the table back and reading\n * `typeof table.$inferSelect['col']`, so a generator that cannot embed a TypeScript type in its\n * output cannot use either. ArkType is the case: it emits one string per field, and a type\n * reference has nowhere to live inside a string DSL.\n */\n schemaTypes?: boolean;\n}\n\nexport function validationOptions(\n g: ValidationGeneratorConfig,\n cfg: { schema?: unknown },\n outDir: string,\n caps: GeneratorCapabilities = {}\n): Record<string, unknown> {\n return {\n outDir,\n outputHeader: g.outputHeader,\n format: g.format,\n schemaSuffix: g.schemaSuffix,\n fileSuffix: g.fileSuffix,\n importExtension: g.importExtension,\n affix: g.affix,\n coerceDates: g.coerceDates,\n applyDefaults: g.applyDefaults,\n duplicateFinder: g.duplicateFinder,\n nestedSchemas: g.nestedSchemas,\n nestedDepth: g.nestedDepth,\n // Only where the generator can act on them, so an unsupported option is absent rather than\n // present and ignored.\n ...(caps.schemaTypes\n ? {\n // Needed by both: the reference is resolved relative to the emitted file.\n schemaPath: cfg.schema,\n typedJson: g.typedJson,\n typedColumns: g.typedColumns,\n }\n : {}),\n };\n}\n","/**\n * The options `@drzl/generator-json-schema` receives, built in one place.\n *\n * `generate` and `watch` each dispatch over `cfg.generators` in their own loop, and the json-schema\n * branch was assembled by hand in both. That arrangement has already dropped options silently more\n * than once here: five validation options never reached a watch rebuild, and `watch` had no\n * json-schema branch at all for a while, so that directory went stale from the first save onward.\n * None of it is visible in the wiring, because the option parses, the generator defaults it, and\n * the feature simply does nothing.\n *\n * One builder makes the two call sites the same object by construction rather than by review, and\n * `packages/cli/test/openapi-branch-parity.e2e.spec.ts` runs both commands and compares the bytes.\n */\nimport { validationOptions, type ValidationGeneratorConfig } from './validation-options.js';\n\n/** A generator entry from the config, loosely typed because the config schema owns its shape. */\ntype GeneratorConfig = ValidationGeneratorConfig & {\n path?: string;\n target?: unknown;\n components?: unknown;\n document?: unknown;\n includeRelations?: unknown;\n};\n\nexport function jsonSchemaOptions(\n g: GeneratorConfig,\n cfg: { schema?: unknown },\n outDir: string\n): Record<string, unknown> {\n return {\n // JSON Schema is data, so nothing it emits references a type from the schema module.\n ...validationOptions(g, cfg, outDir, { schemaTypes: false }),\n target: g.target,\n components: g.components,\n document: g.document,\n // Read only while emitting a document, where it adds `/users/{id}/posts`. The per-table\n // schemas are flat whatever it says.\n includeRelations: g.includeRelations,\n };\n}\n","import type { AffixOptions } from '@drzl/validation-core';\nimport {\n AFFIX_PROBE_TABLE,\n DEFAULT_IMPORT_EXTENSION,\n IMPORT_EXTENSIONS,\n NAME_MODES,\n resolveAffix,\n schemaName,\n validateAffix,\n} from '@drzl/validation-core';\nimport * as fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport { z } from 'zod';\n\nexport const NamingSchema = z\n .object({\n routerSuffix: z.string().default('Router'),\n procedureCase: z.enum(['camel', 'kebab', 'snake']).default('camel'),\n })\n .partial();\n\n/** One affix for every mode, or a per-mode map. Keys match drzl's internal mode names. */\nconst AffixValueSchema = z.union(\n [\n z.string(),\n z\n .object({\n insert: z.string().optional(),\n update: z.string().optional(),\n select: z.string().optional(),\n })\n .strict(),\n ],\n {\n error:\n 'Expected a string to use for every mode, or an object with any of the keys \"insert\", ' +\n '\"update\" and \"select\". Those keys are lowercase, matching the mode names drzl uses ' +\n 'everywhere else.',\n }\n);\n\nconst AffixPartSchema = z\n .object({\n prefix: AffixValueSchema.optional(),\n suffix: AffixValueSchema.optional(),\n })\n .strict();\n\nexport const AffixSchema = z\n .object({\n /**\n * `preserve` (default) keeps today's output: the Drizzle export name goes into the\n * identifier verbatim, so `export const users` yields `InsertusersSchema`. `pascal`\n * upper-camels it first, yielding `InsertUsersSchema`.\n */\n tableCase: z.enum(['preserve', 'pascal']).optional(),\n schema: AffixPartSchema.optional(),\n type: AffixPartSchema.optional(),\n })\n .strict();\n\n/**\n * How every relative specifier drzl invents spells its extension.\n *\n * The generated files land in the consumer's own source tree, so the consumer's\n * `moduleResolution` decides which forms resolve. `js` is the only one that resolves under\n * all of `bundler`, `node10`, `node16` and `nodenext` with no compiler flag, so it is the\n * default. See the `ImportExtension` docs in `@drzl/validation-core` for the measured grid.\n */\nexport const ImportExtensionSchema = z.enum(IMPORT_EXTENSIONS);\n\nexport const GeneratorSchema = z.object({\n kind: z.enum(['orpc', 'trpc', 'service', 'zod', 'valibot', 'arktype', 'typebox', 'json-schema']),\n /**\n * Overrides the top-level `importExtension` for this generator alone, for a project whose\n * generated directories are compiled by different tsconfigs.\n */\n importExtension: ImportExtensionSchema.optional(),\n template: z.string().optional(),\n includeRelations: z.boolean().optional(),\n /**\n * Type `json` and `jsonb` columns from the schema rather than leaving them wide.\n *\n * `.$type<T>()` is a compile-time cast, so no runtime-derived validator can see it and\n * `drizzle-orm/zod` types every json column as its generic `Json`. A generator can reference\n * `typeof <table>.$inferSelect['<column>']` instead, which is the declared type resolved by\n * TypeScript itself, so generics, unions and imported interfaces all work.\n *\n * Off by default because it makes the generated file import your schema module, as a\n * type-only import that disappears at build time.\n */\n // What a date column accepts. Documented on the zod generator and, until now, accepted by the\n // config parser and then dropped on the floor: the generators default it to 'input' themselves,\n // so setting it here changed nothing.\n coerceDates: z.enum(['input', 'all', 'none']).optional(),\n typedJson: z.boolean().optional(),\n // The wider form: every column's static type comes from Drizzle, not just the untyped ones.\n typedColumns: z.boolean().optional(),\n // Reproduce literal column defaults in the insert schema, so parsing fills them in.\n applyDefaults: z.boolean().optional(),\n /**\n * Emit `findDuplicate<Table>` beside the schemas: the rows in a batch that collide with an\n * earlier row on a unique constraint.\n *\n * Uniqueness is the one constraint a per-row validator structurally cannot see, since it is a\n * fact about the table rather than the row. This checks the half that needs no database.\n */\n duplicateFinder: z.boolean().optional(),\n /**\n * Emit `NestedInsert<Table>` and `NestedSelect<Table>` beside the flat schemas: the table plus\n * one key per relation, so `{ ...user, posts: [...] }` can be validated whole.\n *\n * Nothing in the Drizzle validator ecosystem describes that payload, and `db.insert` drops the\n * relation key silently rather than refusing it, so the children are never written and nothing\n * says so.\n */\n nestedSchemas: z.boolean().optional(),\n /**\n * How many levels of children a nested schema describes. Defaults to 1, capped at 3.\n *\n * Nesting is expanded inline rather than by reference, so this multiplies the emitted size, and\n * it is also what terminates a cycle: `users -> posts -> users` stops here.\n */\n nestedDepth: z.number().int().optional(),\n naming: NamingSchema.optional(),\n outputHeader: z\n .object({\n enabled: z.boolean().default(true).optional(),\n text: z.string().optional(),\n })\n .optional(),\n format: z\n .object({\n enabled: z.boolean().default(true).optional(),\n engine: z.enum(['auto', 'prettier', 'biome']).default('auto').optional(),\n configPath: z.string().optional(),\n })\n .optional(),\n /**\n * Which spelling of JSON Schema the `json-schema` generator emits.\n *\n * OpenAPI 3.0 is not an older superset of the 2020-12 draft, it is a different dialect: a\n * nullable type is `nullable: true` rather than a type array, and an exclusive bound is a\n * boolean flag beside the bound rather than its own keyword. An unknown keyword is not an error\n * in JSON Schema, it is ignored, so emitting the wrong dialect produces a document that\n * validates and then accepts the values the constraints exist to reject.\n */\n target: z.enum(['draft-2020-12', 'openapi-3.1', 'openapi-3.0']).optional(),\n /** Also emit `components.ts` for the `json-schema` generator, ready for an OpenAPI document. */\n components: z.boolean().optional(),\n /**\n * Also emit the whole OpenAPI document for the `json-schema` generator: paths, verbs, request and\n * response bodies per table, with `components.schemas` embedded so the file stands alone.\n *\n * `true` is the short form. The object form carries the three things a Drizzle schema genuinely\n * cannot say: what the API is called, where it is served, and which status code that particular\n * server answers a request that fails its schema with.\n */\n document: z\n .union([\n z.boolean(),\n z\n .object({\n enabled: z.boolean().optional(),\n /** `ts` (default) writes a module, `json` the file OpenAPI tooling reads directly. */\n format: z.enum(['ts', 'json', 'both']).optional(),\n info: z\n .object({\n title: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n })\n .strict()\n .optional(),\n /**\n * Omitted by default, which the specification reads as a single server at `/`: the\n * document describes whatever is serving it. A placeholder host would be a fabrication\n * that tooling then follows.\n */\n servers: z\n .array(z.object({ url: z.string(), description: z.string().optional() }).strict())\n .optional(),\n /** 400 by default. 422 is the other defensible reading; exactly one is emitted. */\n validationStatus: z.union([z.literal(400), z.literal(422)]).optional(),\n })\n .strict(),\n ])\n .optional(),\n // service generator specific options\n path: z.string().optional(),\n dataAccess: z.enum(['stub', 'drizzle']).default('stub').optional(),\n dbImportPath: z.string().optional(),\n schemaImportPath: z.string().optional(),\n // zod/valibot/arktype generator specific options\n schemaSuffix: z.string().optional(),\n fileSuffix: z.string().optional(),\n /**\n * Prefixes, suffixes and table casing for generated identifiers (zod/valibot/arktype).\n * Omitting it reproduces the output of every previous release exactly.\n */\n affix: AffixSchema.optional(),\n /**\n * How the router generators reach a database handle: through the request context, rather than\n * through a module-level import in the service layer.\n *\n * Documented on the oRPC generator since it was added and, until now, absent from this schema\n * entirely. `GeneratorSchema` is not strict, so zod stripped the key without a word and the\n * option did nothing at all when set from a config file. It was only ever reachable by calling\n * the generator's API directly.\n */\n databaseInjection: z\n .object({\n enabled: z.boolean().optional(),\n /** The type annotation for the injected handle, e.g. `DrizzleD1Database`. */\n databaseType: z.string().optional(),\n databaseTypeImport: z.object({ name: z.string(), from: z.string() }).optional(),\n })\n .optional(),\n // router validation sharing (orpc, trpc)\n validation: z\n .object({\n useShared: z.boolean().default(false).optional(),\n library: z.enum(['zod', 'valibot', 'arktype']).default('zod').optional(),\n importPath: z.string().optional(),\n schemaSuffix: z.string().optional(),\n /**\n * How the validation generator named its exports. Usually left unset: the CLI copies\n * it from the sibling generator whose `kind` matches `library`.\n */\n affix: AffixSchema.optional(),\n })\n .optional(),\n // template options\n templateOptions: z.record(z.string(), z.any()).optional(),\n});\n\nexport const AnalyzerSchema = z.object({\n includeRelations: z.boolean().default(true),\n validateConstraints: z.boolean().default(true),\n includeHeuristicRelations: z.boolean().default(false),\n});\n\nexport const ConfigSchema = z\n .object({\n schema: z.string(),\n outDir: z.string().default('src/api'),\n /**\n * Which tables to generate for, matched against the database table name.\n *\n * There was no way to say this, and every generator loops over every table it finds, so\n * DRZL emitted unauthenticated CRUD over whatever shared the schema file. That is noise for\n * a migrations table and a genuine leak for an auth one: Better Auth puts `user`, `session`,\n * `account` and `verification` alongside your own tables, and `account` holds\n * `accessToken`, `refreshToken`, `idToken` and `password`.\n *\n * Deliberately name-based and explicit rather than detecting any particular library. Auth\n * table names are all renameable, so a built-in list would miss renamed tables and, worse,\n * silently skip an ordinary table that happened to be called `user`, which is usually the\n * application's main entity.\n *\n * `exclude` wins over `include`. Patterns support `*`, matching within a name.\n */\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n /**\n * How every relative specifier drzl invents spells its extension, for every generator.\n * A generator may override it. Defaults to `js`, which is the only form that resolves\n * under every `moduleResolution` without a compiler flag.\n */\n importExtension: ImportExtensionSchema.default(DEFAULT_IMPORT_EXTENSION),\n analyzer: AnalyzerSchema.default({\n includeRelations: true,\n validateConstraints: true,\n includeHeuristicRelations: false,\n }),\n generators: z\n .array(GeneratorSchema)\n .min(1)\n .default([{ kind: 'orpc' } as any]),\n })\n // Reject an affix before anything is written, rather than emitting a file that cannot\n // compile. Only `affix` is inspected; the legacy flat `schemaSuffix` is left alone so\n // configs that parse today keep parsing.\n .superRefine((cfg, ctx) => {\n cfg.generators.forEach((g, i) => {\n const report = (base: (string | number)[], affix?: AffixOptions, schemaSuffix?: string) => {\n for (const issue of validateAffix(affix, schemaSuffix)) {\n ctx.addIssue({\n code: 'custom',\n path: ['generators', i, ...base, ...issue.path],\n message: issue.message,\n });\n }\n };\n report(['affix'], g.affix as AffixOptions | undefined, g.schemaSuffix);\n report(\n ['validation', 'affix'],\n g.validation?.affix as AffixOptions | undefined,\n g.validation?.schemaSuffix\n );\n });\n });\n\n// ✨ Separate input vs output types\nexport type DrzlConfigInput = z.input<typeof ConfigSchema>;\nexport type DrzlConfig = z.output<typeof ConfigSchema>;\n\nexport function defineConfig<T extends DrzlConfigInput>(cfg: T): T {\n return cfg;\n}\n\ntype GeneratorConfig = DrzlConfig['generators'][number];\n\n/** The generators that emit an RPC router, and so share `outDir` and `validation`. */\nconst ROUTER_KINDS = new Set(['orpc', 'trpc']);\n\n/**\n * Where the tRPC generator writes.\n *\n * `outDir` by default, exactly like oRPC, so a config that names one router generator puts its\n * output where the top-level setting says. `path` is the escape hatch, and a config that runs\n * *both* router generators needs it: they would otherwise write two different `index.ts` files to\n * the same directory and the second would win.\n *\n * Exported because `computeGeneratorOutputDirs` has to agree with the dispatch in cli.ts about\n * this, and the watcher ignoring the wrong directory is an infinite regeneration loop.\n */\nexport function trpcOutDir(g: { path?: string }, cfg: { outDir: string }): string {\n return g.path ?? cfg.outDir;\n}\n\nfunction sharedSchemaNames(opts: { affix?: AffixOptions; schemaSuffix?: string }): string[] {\n const resolved = resolveAffix(opts);\n return NAME_MODES.map((mode) => schemaName(mode, AFFIX_PROBE_TABLE, resolved));\n}\n\n/**\n * Fill in cross-generator defaults and refuse configs whose generators would disagree.\n *\n * An oRPC router that imports shared schemas has to spell the exact names the validation\n * generator exported. Both sides used to be configured independently, so they could silently\n * drift into a router that does not compile. When an oRPC generator uses shared validation\n * and exactly one sibling generator produces that library, its `affix` is copied across.\n *\n * Deliberately conservative about the pre-existing flat `schemaSuffix`: a disagreement there\n * is only reported, never repaired, because repairing it would change the bytes an existing\n * config emits.\n *\n * `importExtension` is pushed down here too. A consumer compiles the whole generated tree\n * with one tsconfig, so the setting that has to hold is the same for every generator, and\n * every call site downstream can then read it off the generator without knowing about the\n * top-level default.\n */\nexport function resolveConfig(cfg: DrzlConfig): { config: DrzlConfig; warnings: string[] } {\n const warnings: string[] = [];\n const generators: GeneratorConfig[] = cfg.generators.map((g) => ({\n ...g,\n importExtension: g.importExtension ?? cfg.importExtension,\n }));\n\n for (const g of generators) {\n // Both router generators import the validation generators' exports by name, so both have to\n // spell them the way the sibling generator wrote them.\n if (!ROUTER_KINDS.has(g.kind)) continue;\n\n /**\n * `databaseInjection` describes a contract between two generators, not a setting of one.\n *\n * A router in injection mode emits `Service.getById(ctx.db, id)`, and only a service\n * generated in the same mode has a `db` parameter to receive it. Declared once on the router\n * and pushed onto the service generator here, exactly as `validation.affix` is pulled the\n * other way, because the alternative is writing the same block twice and a project that\n * compiles in halves and not as a whole.\n *\n * `@drzl/generator-service` honours the flag only while emitting real Drizzle queries: its\n * stub bodies take no database whatever they are told. That combination cannot be repaired\n * from here without changing what an existing config emits, so it is reported instead.\n */\n if (g.databaseInjection?.enabled) {\n for (const s of generators.filter((x) => x.kind === 'service')) {\n if (!s.databaseInjection) {\n s.databaseInjection = g.databaseInjection;\n } else if (!s.databaseInjection.enabled) {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator sets databaseInjection.enabled while the ` +\n `\"service\" generator sets it to false. The router will call ` +\n `Service.method(ctx.db, ...) against services that take no database parameter, so ` +\n `the generated project will not compile. Set both, or neither.`\n );\n }\n if ((s.dataAccess ?? 'stub') === 'stub') {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator sets databaseInjection.enabled, so its ` +\n `handlers call Service.method(ctx.db, ...). The \"service\" generator emits stub ` +\n `bodies, which take no database parameter whatever this option says, so those ` +\n `calls will not compile. Set dataAccess: 'drizzle' on the \"service\" generator, or ` +\n `drop databaseInjection.`\n );\n }\n }\n }\n\n const v = g.validation;\n if (!v?.useShared) continue;\n\n const library = v.library ?? 'zod';\n const siblings = generators.filter((s) => s.kind === library);\n // Zero siblings means the user points at a barrel drzl does not generate; more than one\n // means there is no single source of truth. Either way, leave the config alone.\n if (siblings.length !== 1) continue;\n const sibling = siblings[0];\n\n const theirs = sharedSchemaNames({\n affix: sibling.affix as AffixOptions | undefined,\n schemaSuffix: sibling.schemaSuffix,\n });\n\n if (!v.affix) {\n if (sibling.affix) {\n // Bake the sibling's fully resolved naming in, so its own schemaSuffix fallback\n // travels with it and cannot be re-interpreted on the oRPC side.\n g.validation = {\n ...v,\n affix: resolveAffix({\n affix: sibling.affix as AffixOptions,\n schemaSuffix: sibling.schemaSuffix,\n }),\n };\n continue;\n }\n const mine = sharedSchemaNames({ schemaSuffix: v.schemaSuffix });\n if (mine.join(',') !== theirs.join(',')) {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator's validation.schemaSuffix ` +\n `(${JSON.stringify(v.schemaSuffix ?? 'Schema')}) does not match the \"${library}\" ` +\n `generator's schemaSuffix (${JSON.stringify(sibling.schemaSuffix ?? 'Schema')}). ` +\n `The router will import ${mine.join(', ')} but the \"${library}\" generator exports ` +\n `${theirs.join(', ')}, so the generated router will not compile. Set both to the ` +\n `same value, or move to \"affix\", which is inherited automatically.`\n );\n }\n continue;\n }\n\n const mine = sharedSchemaNames({\n affix: v.affix as AffixOptions,\n schemaSuffix: v.schemaSuffix,\n });\n if (mine.join(',') !== theirs.join(',')) {\n throw new Error(\n `drzl config: the \"${g.kind}\" generator imports shared ${library} schemas, but its ` +\n `validation.affix disagrees with the \"${library}\" generator's own naming. The router ` +\n `would import ${mine.join(', ')} while the \"${library}\" generator exports ` +\n `${theirs.join(', ')}. Make them match, or drop validation.affix and let it be ` +\n `inherited from the \"${library}\" generator.`\n );\n }\n }\n\n return { config: { ...cfg, generators }, warnings };\n}\n\n/**\n * Parse, then resolve cross-generator defaults. Both `generate` and `watch` go through\n * loadConfig, so putting the resolution here is what keeps the two duplicated generator\n * dispatch blocks in cli.ts from needing the logic twice.\n */\nfunction finalize(raw: unknown): DrzlConfig {\n const { config, warnings } = resolveConfig(ConfigSchema.parse(raw));\n for (const w of warnings) console.warn(w);\n return config;\n}\n\nexport async function loadConfig(customPath?: string): Promise<DrzlConfig | null> {\n const fsp = await import('node:fs/promises');\n\n const candidates = customPath\n ? [customPath]\n : [\n 'drzl.config.ts',\n 'drzl.config.mjs',\n 'drzl.config.js',\n 'drzl.config.cjs',\n 'drzl.config.json',\n ];\n\n for (const c of candidates) {\n const p = path.resolve(process.cwd(), c);\n try {\n await fsp.access(p);\n } catch {\n continue;\n }\n\n const ext = path.extname(p).toLowerCase();\n\n // JSON: read directly\n if (ext === '.json') {\n const raw = JSON.parse(await fsp.readFile(p, 'utf8'));\n return finalize(raw);\n }\n\n // Everything else (TS/JS/MJS/CJS) -> Jiti with cache-busting\n const { createJiti } = await import('jiti');\n const stat = await fsp.stat(p);\n\n // Passing __filename is safe in CJS; fallback to cwd if not defined.\n const base =\n typeof __filename !== 'undefined' ? __filename : path.join(process.cwd(), 'index.js');\n\n const jiti = createJiti(base, {\n moduleCache: false, // re-evaluate each time\n fsCache: true, // keep transform cache\n cacheVersion: String(stat.mtimeMs), // bump on edit\n interopDefault: true,\n tryNative: false, // <-- prevent native import of .ts\n // debug: true,\n }) as any;\n\n const mod = await jiti.import(p);\n const raw = mod?.default ?? mod;\n return finalize(raw);\n }\n\n return null;\n}\n\n/** Absolute output dirs for all generators (to ignore in watcher). */\nexport function computeGeneratorOutputDirs(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const abs = (p: string) => path.resolve(cwd, p);\n const dirs = new Set<string>();\n dirs.add(abs(cfg.outDir)); // orpc\n for (const g of cfg.generators) {\n if (g.kind === 'trpc') dirs.add(abs(trpcOutDir(g, cfg)));\n if (g.kind === 'service') dirs.add(abs(g.path ?? 'src/services'));\n if (g.kind === 'zod') dirs.add(abs(g.path ?? 'src/validators/zod'));\n if (g.kind === 'valibot') dirs.add(abs(g.path ?? 'src/validators/valibot'));\n if (g.kind === 'arktype') dirs.add(abs(g.path ?? 'src/validators/arktype'));\n if (g.kind === 'typebox') dirs.add(abs(g.path ?? 'src/validators/typebox'));\n if (g.kind === 'json-schema') dirs.add(abs(g.path ?? 'src/validators/json-schema'));\n }\n return [...dirs];\n}\n\n/** Resolve custom template directories (local path or installed package). */\nexport function resolveTemplateDirsSync(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const results: string[] = [];\n const req = createRequire(\n typeof __filename !== 'undefined' ? __filename : path.join(process.cwd(), 'index.js')\n );\n\n for (const g of cfg.generators) {\n const t = g.template;\n // Built-in template names, not packages. `service` is the tRPC generator's, and without it\n // here every run would try to resolve a package called \"service\" and then watch a directory\n // of that name, neither of which exists.\n if (!t || t === 'standard' || t === 'minimal' || t === 'service') continue;\n\n // Try package resolution relative to cwd\n let pkgDir: string | null = null;\n try {\n const pkg = req.resolve(`${t}/package.json`, { paths: [cwd] as any });\n pkgDir = path.dirname(pkg);\n } catch {}\n\n if (pkgDir) {\n results.push(pkgDir);\n continue;\n }\n\n // Local path-like template\n if (/[./\\\\]/.test(t)) {\n const abs = path.resolve(cwd, t);\n if (fs.existsSync(abs)) results.push(abs);\n }\n }\n\n return Array.from(new Set(results));\n}\n\n/** Build watch targets (exclude output dirs; watcher will ignore those). */\n/**\n * Narrow an analysis's tables to the ones the config asked for.\n *\n * Matching is on the database table name, anchored, with `*` as the only metacharacter. Anchored\n * matters: `user` must not also drop `users`, and a substring match would. `exclude` is applied\n * after `include`, so the safer direction wins when both name the same table.\n */\nexport function filterTables<T extends { name: string }>(\n tables: T[],\n opts: { include?: string[]; exclude?: string[] }\n): T[] {\n const toRegExp = (pattern: string) =>\n new RegExp(\n '^' +\n pattern\n .split('*')\n .map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('.*') +\n '$'\n );\n\n const matches = (patterns: string[], name: string) =>\n patterns.some((p) => toRegExp(p).test(name));\n\n let out = tables;\n if (opts.include?.length) out = out.filter((t) => matches(opts.include!, t.name));\n if (opts.exclude?.length) out = out.filter((t) => !matches(opts.exclude!, t.name));\n return out;\n}\n\nexport function computeWatchTargets(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const abs = (p: string) => path.resolve(cwd, p);\n const schemaAbs = abs(cfg.schema);\n // The schema's directory, not a glob under it. Chokidar removed glob support in v4 and treats\n // `<dir>/**/*.{ts,tsx,js}` as a literal path, so it watched a directory named `**` that does\n // not exist: no event ever fired and `drzl watch` did its initial build and then sat inert.\n // A directory is watched recursively by chokidar itself, and the extension filtering that the\n // glob was doing now happens on the event instead.\n const targets = new Set<string>([\n path.dirname(schemaAbs),\n abs('drzl.config.ts'),\n abs('drzl.config.js'),\n abs('drzl.config.mjs'),\n abs('drzl.config.cjs'),\n ]);\n for (const t of resolveTemplateDirsSync(cfg, cwd)) targets.add(t);\n return [...targets];\n}\n","/**\n * The options `@drzl/generator-trpc` receives, built in one place.\n *\n * `generate` and `watch` each dispatch over `cfg.generators` in their own loop, and every branch\n * in both assembles its own options object by hand. Three documented options have already been\n * found dead that way: `typedJson` never reached typebox, `coerceDates` and `applyDefaults`\n * reached nothing but zod, and `servicesDir` is passed by `generate`'s oRPC branch and not by\n * `watch`'s, so a watch rebuild emits a service import pointing at the default directory whatever\n * the config says. None of those is visible in the wiring: the option parses, the generator\n * defaults it, and the feature simply does nothing.\n *\n * One builder means the two call sites are the same object by construction rather than by review.\n * It also gives the drift something to be asserted against, which is what\n * `packages/cli/test/trpc-branch-parity.spec.ts` does by running both commands and comparing the\n * bytes they wrote.\n */\nimport { trpcOutDir } from './config.js';\n\n/** A generator entry from the config, loosely typed because the config schema owns its shape. */\ntype GeneratorConfig = {\n path?: string;\n template?: unknown;\n includeRelations?: unknown;\n naming?: unknown;\n outputHeader?: unknown;\n format?: unknown;\n importExtension?: unknown;\n validation?: unknown;\n databaseInjection?: unknown;\n};\n\nexport function trpcOptions(\n g: GeneratorConfig,\n cfg: { outDir: string },\n servicesDir: string\n): Record<string, unknown> {\n return {\n outputDir: trpcOutDir(g, cfg),\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n importExtension: g.importExtension,\n validation: g.validation,\n databaseInjection: g.databaseInjection,\n // Where the service generator is actually writing, so `template: 'service'` emits an import\n // of a module that exists. The generator defaults this to `src/services`, which is right only\n // by coincidence for a config that puts them elsewhere.\n servicesDir,\n };\n}\n","/**\n * Drift detection for generated output.\n *\n * No runtime validator can offer this. `drizzle-orm/zod` and friends derive schemas in memory at\n * import time, so there is nothing on disk to have drifted and nothing for CI to compare. It is\n * only available to a code generator, which makes it one of the few things DRZL can do that the\n * first-party modules structurally cannot.\n *\n * The check is: regenerate, and require the result to equal what is committed. That catches the\n * two failures that actually happen, someone editing generated files by hand and someone\n * changing the schema without regenerating, and it catches them in CI rather than in review.\n *\n * Content-neutral by construction. Redirecting output to a temporary directory would not work:\n * generated files contain paths computed relative to their own location, so a different output\n * directory produces legitimately different bytes and every file would report as drifted. So the\n * real directories are snapshotted first, regeneration is allowed to overwrite them, and the\n * snapshot is put back if anything changed. Either way the tree ends as it began.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface DriftEntry {\n file: string;\n status: 'changed' | 'added' | 'removed';\n}\n\n/** Every file under `dir`, keyed by its path relative to `dir`. Missing directory means empty. */\nexport async function snapshotDir(dir: string): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n async function walk(current: string) {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return; // Nothing generated there yet, which a first run should report as additions.\n }\n for (const e of entries) {\n const full = path.join(current, e.name);\n if (e.isDirectory()) await walk(full);\n else out.set(path.relative(dir, full), await fs.readFile(full, 'utf8'));\n }\n }\n await walk(dir);\n return out;\n}\n\n/** Snapshot several directories at once, keys prefixed by directory so they cannot collide. */\nexport async function snapshotAll(dirs: string[]): Promise<Map<string, string>> {\n const all = new Map<string, string>();\n for (const dir of dirs) {\n for (const [rel, content] of await snapshotDir(dir)) {\n all.set(path.join(dir, rel), content);\n }\n }\n return all;\n}\n\n/** What changed between two snapshots. */\nexport function diffSnapshots(\n before: Map<string, string>,\n after: Map<string, string>\n): DriftEntry[] {\n const out: DriftEntry[] = [];\n for (const [file, content] of after) {\n if (!before.has(file)) out.push({ file, status: 'added' });\n else if (before.get(file) !== content) out.push({ file, status: 'changed' });\n }\n for (const file of before.keys()) {\n if (!after.has(file)) out.push({ file, status: 'removed' });\n }\n return out.sort((a, b) => a.file.localeCompare(b.file));\n}\n\n/**\n * Put a snapshot back, so a failed check leaves the tree exactly as it found it.\n *\n * A file that regeneration created and the snapshot does not know about is deleted, since it was\n * not there before the check ran.\n */\nexport async function restoreSnapshot(\n before: Map<string, string>,\n after: Map<string, string>\n): Promise<void> {\n for (const [file, content] of before) {\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.writeFile(file, content, 'utf8');\n }\n for (const file of after.keys()) {\n if (!before.has(file)) await fs.rm(file, { force: true });\n }\n}\n","/**\n * Loading an optional generator package, and telling absence apart from failure.\n *\n * Every validation generator is loaded on demand, because a project that only wants zod should not\n * have to install five. That makes \"the package is not installed\" a real, expected outcome worth a\n * helpful message. It does not make it the only outcome: a generator that is installed and running\n * can throw for any reason a program can throw, and the CLI reported all of those as a missing npm\n * package too, with the true reason printed underneath as a detail.\n *\n * Node reports an unresolvable import as `ERR_MODULE_NOT_FOUND`, and reports the same code when\n * the module resolved and something *it* imported did not. The code alone therefore does not\n * separate the two; the message does, because it names the specifier that failed to resolve.\n */\n\n/** A generator package that is not installed. Everything else is somebody's real error. */\nexport class GeneratorNotInstalledError extends Error {\n constructor(\n readonly specifier: string,\n /** What Node threw, kept so nothing is discarded on the way to the message. */\n readonly reason: unknown\n ) {\n super(`${specifier} is not installed`);\n this.name = 'GeneratorNotInstalledError';\n }\n}\n\n/**\n * Whether `err` is Node refusing to resolve `specifier` itself.\n *\n * Measured on Node 22, from an ESM entry and from a CJS one, since the CLI ships both builds and\n * the bundler leaves `import()` as `import()` in each:\n *\n * absent package ERR_MODULE_NOT_FOUND, `Cannot find package '<specifier>' imported…`\n * present, inner dep absent ERR_MODULE_NOT_FOUND, naming the *inner* specifier instead\n * present, main file gone ERR_MODULE_NOT_FOUND, naming the resolved file path\n * throws while evaluating no `code` at all, and whatever message the generator threw\n *\n * Only the first is an install problem, and only the first quotes the specifier that was asked\n * for, which is what this matches on.\n */\nexport function isPackageMissing(err: unknown, specifier: string): boolean {\n const code = (err as { code?: unknown } | null | undefined)?.code;\n if (code !== 'ERR_MODULE_NOT_FOUND') return false;\n const message = (err as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message.includes(`'${specifier}'`);\n}\n\n/**\n * Run `load` and re-throw a missing package as `GeneratorNotInstalledError`.\n *\n * `load` is a thunk rather than a specifier so the caller keeps a literal `import('@drzl/…')` in\n * its own source, which is what lets the bundler see the dependency. Anything it throws that is\n * not this package's own absence comes out unchanged.\n */\nexport async function loadGenerator<T>(specifier: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isPackageMissing(e, specifier)) throw new GeneratorNotInstalledError(specifier, e);\n throw e;\n }\n}\n","import chalk from 'chalk';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\nexport interface SponsorMessageOptions {\n reason?: string;\n minIntervalMs?: number;\n force?: boolean;\n}\n\ninterface SponsorCachePayload {\n runs: number;\n lastShownAt?: number;\n lastReason?: string;\n}\n\nconst CACHE_DIR = path.join(process.cwd(), 'node_modules', '.cache', '@drzl');\nconst CACHE_FILE = path.join(CACHE_DIR, 'sponsor-message.json');\nconst DEFAULT_INTERVAL_MS = 1000 * 60 * 15; // 15 minutes\nlet shownThisProcess = false;\n\nconst tips = [\n 'Pair DRZL watch mode with drizzle-kit to keep schema & API synced.',\n 'Templatize your ORPC routers to roll out new endpoints safely.',\n 'Need typed validators? Enable the zod, valibot, arktype, or typebox generators.',\n 'Need JSON Schema or OpenAPI? The json-schema generator emits both, with no runtime dependency.',\n 'Use output headers to track generated files and trim noisy diffs.',\n];\n\nconst green = (msg: string) => chalk.hex('#6ee7b7')(msg);\nconst cyan = (msg: string) => chalk.cyan(msg);\nconst gray = (msg: string) => chalk.gray(msg);\n\nexport function maybeShowSponsorMessage({\n reason = 'generate',\n minIntervalMs = DEFAULT_INTERVAL_MS,\n force = false,\n}: SponsorMessageOptions = {}) {\n const hideViaEnv = process.env.DRZL_HIDE_SPONSOR?.toLowerCase();\n const hideRequested = hideViaEnv === '1' || hideViaEnv === 'true';\n if (hideRequested || (process.env.CI && !force) || (shownThisProcess && !force)) return;\n\n try {\n mkdirSync(CACHE_DIR, { recursive: true });\n const payload = readCache();\n payload.runs += 1;\n\n const now = Date.now();\n const shouldShow = force || now - (payload.lastShownAt ?? 0) >= minIntervalMs;\n\n if (shouldShow) {\n payload.lastShownAt = now;\n payload.lastReason = reason;\n }\n\n writeCache(payload);\n\n if (!shouldShow) return;\n\n shownThisProcess = true;\n const tip = tips[payload.runs % tips.length];\n\n console.log(\n `\\n${cyan(`🚀 DRZL finished a ${reason} run (#${payload.runs.toLocaleString()}).`)}\\n\\n` +\n `${green('✨ Sponsors keep DRZL shipping. Consider supporting ongoing dev:')}\\n` +\n ` ${green('GitHub Sponsors')} ${gray('→ https://github.com/sponsors/omar-dulaimi')}\\n\\n` +\n `${green('Pro tip:')} ${tip}\\n`\n );\n } catch {\n // Swallow to avoid impacting generator success paths\n }\n}\n\nfunction readCache(): SponsorCachePayload {\n if (!existsSync(CACHE_FILE)) {\n return { runs: 0 };\n }\n try {\n const data = JSON.parse(readFileSync(CACHE_FILE, 'utf8')) as SponsorCachePayload;\n if (typeof data.runs !== 'number') return { runs: 0 };\n return data;\n } catch {\n return { runs: 0 };\n }\n}\n\nfunction writeCache(payload: SponsorCachePayload) {\n writeFileSync(CACHE_FILE, JSON.stringify(payload, null, 2), 'utf8');\n}\n","/**\n * The version `drzl --version` prints, read from the manifest that ships beside the build.\n *\n * It used to be the literal `'0.0.1'`, passed to `program.version()` when the CLI was scaffolded\n * and never touched again. That was true of exactly one release, the first: the registry lists 29\n * versions of `@drzl/cli`, and the other 28 printed `0.0.1` as well. Reading the manifest is the\n * only form that cannot drift, because it is the same file the registry took the version from.\n *\n * Nothing here falls back. A build that cannot find its own manifest, or finds someone else's, has\n * resolved somewhere it did not intend to, and a placeholder standing in for that is how the\n * original defect stayed invisible for 28 releases.\n */\nimport { readFileSync } from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/** The name the manifest beside this build must carry, which is what makes it ours. */\nconst PACKAGE_NAME = '@drzl/cli';\n\n/**\n * The directory holding the file this code ends up in, in every form it is reached.\n *\n * Three of them: `dist/cli.js`, `dist/cli.cjs`, and this file unbundled under ts-node, all three\n * run and checked. Only the CommonJS bundle has no `import.meta`; `tsup.config.ts` gives that\n * build a real value for `import.meta.url` rather than esbuild's empty one, so this needs no\n * branch. If that config is ever dropped, `fileURLToPath(undefined)` throws on load, so the\n * CommonJS bundle stops working loudly instead of reporting the wrong directory.\n */\nfunction moduleDir(): string {\n return path.dirname(fileURLToPath(import.meta.url));\n}\n\n/**\n * The `version` a named manifest declares, or a throw naming what was wrong with it.\n *\n * Split out from the caller below only so the three ways it refuses can be exercised without a\n * build. Nothing in the CLI passes a path.\n */\nexport function readVersionFrom(manifestPath: string): string {\n let raw: string;\n try {\n raw = readFileSync(manifestPath, 'utf8');\n } catch (e: any) {\n throw new Error(\n `${PACKAGE_NAME} cannot read its own version: no manifest at ${manifestPath} ` +\n `(${e?.message ?? String(e)}).`\n );\n }\n\n const manifest = JSON.parse(raw) as { name?: unknown; version?: unknown };\n\n if (manifest.name !== PACKAGE_NAME) {\n throw new Error(\n `${PACKAGE_NAME} looked for its own version in ${manifestPath} and found ` +\n `${JSON.stringify(manifest.name)}, so this build is not sitting where it thinks it is.`\n );\n }\n\n if (typeof manifest.version !== 'string' || manifest.version.length === 0) {\n throw new Error(`${manifestPath} declares no version, so there is nothing to report.`);\n }\n\n return manifest.version;\n}\n\n/**\n * The `version` field of this package's own manifest.\n *\n * Both bundles sit one level below it, in `dist/`, and so does `src/` when this file is run\n * unbundled, so one `..` covers every way it is reached. All three were run.\n */\nexport function readCliVersion(): string {\n return readVersionFrom(path.join(moduleDir(), '..', 'package.json'));\n}\n\nexport const CLI_VERSION = readCliVersion();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiFA,SAAS,OAAO,QAAQ;AACtB,MAAI,OAAO,cAAc,OAAO,WAAW,OAAQ,QAAO;AAC1D,MAAI,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO,SAAS,eAAgB,QAAO;AACpF,SAAO,CAAC,CAAC,UAAU,UAAU,WAAW,MAAM,EAAE,SAAS,OAAO,MAAM;AACxE;AACA,SAAS,QAAQ,QAAQ,KAAK,MAAM;AAClC,QAAM,IAAI,KAAK,GAAG;AAClB,MAAI,QAAQ,MAAM;AAChB,QAAI,OAAO,cAAc,OAAO,WAAW,OAAQ,QAAO,EAAE,KAAK,OAAO,UAAU;AAClF,QAAI,OAAO,OAAO,SAAS,WAAW,EAAE,MAAO,QAAO,EAAE,MAAM,OAAO,MAAM,MAAM;AACjF,QAAI,OAAO,OAAO,SAAS,kBAAkB,EAAE,cAAc;AAC3D,aAAO,EAAE,aAAa,OAAO,MAAM,MAAM;AAAA,IAC3C;AACA,YAAQ,OAAO,QAAQ;AAAA,MACrB,KAAK;AACH,eAAO,EAAE;AAAA,MACX,KAAK;AACH,eAAO,EAAE;AAAA,MACX,KAAK;AACH,eAAO,EAAE;AAAA,MACX,KAAK;AACH,eAAO,EAAE;AAAA,MACX;AACE,eAAO,EAAE;AAAA,IACb;AAAA,EACF,GAAG;AACH,MAAI,OAAO,SAAU,QAAO,EAAE,SAAS,IAAI;AAC3C,MAAI,SAAS,UAAU;AACrB,UAAM,WAAW,SAAS,YAAY,OAAO,YAAY,OAAO;AAChE,QAAI,SAAU,QAAO,EAAE,SAAS,IAAI;AAAA,EACtC;AACA,SAAO;AACT;AACA,SAAS,MAAM,QAAQ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AK,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,OAAO,CAAC,CAAC;AAClE,aAAW,KAAK,MAAO,SAAQ,KAAK,cAAAA,QAAM,KAAK,KAAK,CAAC,EAAE,CAAC;AAC1D;AAEA,QAAQ,WAAW,QAAQ,IAAI;","names":["path","import_validation_core","fs","dist_exports","index_default","keyColumns","path","buildHeader","import_validation_core","init_dist","fs","import_chalk","path","mine","raw","fs","path","import_node_fs","import_node_path","path","chalk","import_node_fs","path","chalk","ora","fs","cliProgress","TRPCGenerator","JsonSchemaGenerator","watcher","chokidar","path"]}
1
+ {"version":3,"sources":["../../generator-trpc/dist/index.js","../../generator-json-schema/dist/index.js","../src/cli.ts","../src/validation-options.ts","../src/json-schema-options.ts","../src/config.ts","../src/trpc-options.ts","../src/doctor.ts","../src/drift.ts","../src/generator-loader.ts","../src/sponsor.ts","../src/version.ts"],"sourcesContent":["// src/index.ts\nimport {\n formatCode,\n importSpecifier,\n resolveAffix,\n resolveConfiguredImport,\n schemaName\n} from \"@drzl/validation-core\";\nvar TRPC_MAJOR = 11;\nvar q = (v) => JSON.stringify(v);\nvar LIB_IMPORTS = {\n zod: \"import { z } from 'zod';\",\n valibot: \"import * as v from 'valibot';\",\n arktype: \"import { type } from 'arktype';\"\n};\nvar LIB_USAGE = {\n zod: /\\bz\\./,\n valibot: /\\bv\\./,\n arktype: /\\btype\\(/\n};\nvar LIBS = {\n zod: {\n number: \"z.number()\",\n string: \"z.string()\",\n boolean: \"z.boolean()\",\n date: \"z.date()\",\n unknown: \"z.unknown()\",\n tuple: (n) => `z.tuple([${Array.from({ length: n }, () => \"z.number()\").join(\", \")}])`,\n numberObject: (fields) => `z.object({ ${fields.map((f) => `${f}: z.number()`).join(\", \")} })`,\n enum: (vals) => `z.enum([${vals.map(q).join(\", \")}] as const)`,\n nullable: (b) => `${b}.nullable()`,\n optional: (b) => `${b}.optional()`,\n object: (body) => `z.object({\n${body}\n})`,\n objectInline: (body) => `z.object({ ${body} })`,\n partialUpdate: (s) => `${s}.partial()`,\n arrayOf: (s) => `z.array(${s})`,\n nullableOf: (s) => `${s}.nullable()`,\n booleanSchema: \"z.boolean()\"\n },\n valibot: {\n number: \"v.number()\",\n string: \"v.string()\",\n boolean: \"v.boolean()\",\n date: \"v.date()\",\n unknown: \"v.unknown()\",\n tuple: (n) => `v.tuple([${Array.from({ length: n }, () => \"v.number()\").join(\", \")}])`,\n numberObject: (fields) => `v.object({ ${fields.map((f) => `${f}: v.number()`).join(\", \")} })`,\n enum: (vals) => `v.picklist([${vals.map(q).join(\", \")}] as const)`,\n nullable: (b) => `v.nullable(${b})`,\n optional: (b) => `v.optional(${b})`,\n object: (body) => `v.object({\n${body}\n})`,\n objectInline: (body) => `v.object({ ${body} })`,\n arrayOf: (s) => `v.array(${s})`,\n nullableOf: (s) => `v.nullable(${s})`,\n booleanSchema: \"v.boolean()\"\n },\n arktype: {\n number: \"number\",\n string: \"string\",\n boolean: \"boolean\",\n date: \"Date\",\n unknown: \"unknown\",\n // The surrounding encode adds the quotes, so the union is built with the inner quoting\n // ArkType expects. Emitting `'${...}'` here produces `''admin' | 'user''`, which does not parse.\n enum: (vals) => vals.map((x) => `'${x.replace(/'/g, \"\\\\'\")}'`).join(\" | \"),\n nullable: (b) => `(${b} | null)`,\n optional: (b) => `${b}?`,\n object: (body) => `type({\n${body}\n})`,\n objectInline: (body) => `type({ ${body} })`,\n fieldIsString: true,\n arrayOf: (s) => `${s}.array()`,\n nullableOf: (s) => `${s}.or('null')`,\n booleanSchema: `type('boolean')`\n }\n};\nfunction isWide(column) {\n if (column.enumValues && column.enumValues.length) return false;\n if (column.shape?.kind === \"tuple\" || column.shape?.kind === \"numberObject\") return false;\n return ![\"number\", \"string\", \"boolean\", \"Date\"].includes(column.tsType);\n}\nfunction mapExpr(column, lib, mode) {\n const d = LIBS[lib];\n let base = (() => {\n if (column.enumValues && column.enumValues.length) return d.enum(column.enumValues);\n if (column.shape?.kind === \"tuple\" && d.tuple) return d.tuple(column.shape.length);\n if (column.shape?.kind === \"numberObject\" && d.numberObject) {\n return d.numberObject(column.shape.fields);\n }\n switch (column.tsType) {\n case \"number\":\n return d.number;\n case \"string\":\n return d.string;\n case \"boolean\":\n return d.boolean;\n case \"Date\":\n return d.date;\n default:\n return d.unknown;\n }\n })();\n if (column.nullable) base = d.nullable(base);\n if (mode !== \"select\") {\n const optional = mode === \"update\" || column.nullable || column.hasDefault;\n if (optional) base = d.optional(base);\n }\n return base;\n}\nfunction field(column, lib, mode) {\n const d = LIBS[lib];\n const expr = mapExpr(column, lib, mode);\n return `${objectKey(column.name)}: ${d.fieldIsString ? JSON.stringify(expr) : expr}`;\n}\nfunction objectKey(name) {\n return isIdent(name) ? name : JSON.stringify(name);\n}\nfunction renderSchema(table, lib, mode) {\n const d = LIBS[lib];\n const cols = table.columns.filter((c) => mode === \"select\" ? true : !c.isGenerated);\n const body = cols.map((c) => ` ${field(c, lib, mode)},`).join(\"\\n\");\n const schema = d.object(body);\n return mode === \"update\" && d.partialUpdate ? d.partialUpdate(schema) : schema;\n}\nfunction toCase(s, c) {\n if (!c) return s;\n const parts = s.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/[_-]/g, \" \").split(/\\s+/);\n if (c === \"camel\") {\n return parts.map(\n (p, i) => i === 0 ? p.toLowerCase() : p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()\n ).join(\"\");\n }\n if (c === \"kebab\") return parts.map((p) => p.toLowerCase()).join(\"-\");\n if (c === \"snake\") return parts.map((p) => p.toLowerCase()).join(\"_\");\n return s;\n}\nvar cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);\nvar singularize = (s) => s.endsWith(\"ies\") ? s.slice(0, -3) + \"y\" : s.endsWith(\"s\") ? s.slice(0, -1) : s;\nvar isIdent = (s) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s);\nvar BASE_MODULE = \"trpc\";\nfunction keyColumns(table) {\n const names = table.primaryKey?.columns ?? [];\n if (!names.length) return null;\n const cols = names.map((n) => table.columns.find((c) => c.name === n));\n if (cols.some((c) => !c)) return null;\n return cols;\n}\nvar TRPCGenerator = class {\n constructor(analysis) {\n this.analysis = analysis;\n }\n async generate(opts) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const out = path.resolve(process.cwd(), opts.outputDir);\n const ctx = {\n out,\n services: path.resolve(process.cwd(), opts.servicesDir ?? \"src/services\")\n };\n await fs.mkdir(out, { recursive: true });\n const files = [];\n const write = async (filePath, content) => {\n const formatted = await formatCode(\n buildHeader(opts.outputHeader) + content,\n filePath,\n opts.format\n );\n await fs.writeFile(filePath, formatted, \"utf8\");\n files.push(filePath);\n };\n const basePath = path.join(out, `${BASE_MODULE}.ts`);\n await write(basePath, renderBase(opts));\n const routers = [];\n const total = this.analysis.tables.length;\n let index = 0;\n for (const table of this.analysis.tables) {\n const base = `${table.tsName}${opts.naming?.routerSuffix ?? \"\"}`;\n const filePath = path.join(out, `${toCase(base, opts.naming?.procedureCase)}.ts`);\n if (filePath === basePath) {\n throw new Error(\n `@drzl/generator-trpc: the router for table \"${table.name}\" would be written to ${filePath}, which is the shared tRPC base module this generator also writes. Set naming.routerSuffix to move it out of the way.`\n );\n }\n await write(filePath, renderRouter(table, opts, ctx));\n routers.push({ table, filePath, exportName: routerExportName(table, opts.naming) });\n index++;\n opts.onProgress?.({ index, total, table: table.name, filePath });\n }\n await write(path.join(out, \"index.ts\"), renderBarrel(routers, ctx, path, opts));\n return { files };\n }\n};\nvar index_default = TRPCGenerator;\nfunction renderBase(opts) {\n const injection = opts.databaseInjection?.enabled === true;\n const dbType = opts.databaseInjection?.databaseType ?? \"unknown\";\n const typeImport = opts.databaseInjection?.databaseTypeImport ? `import type { ${opts.databaseInjection.databaseTypeImport.name} } from '${opts.databaseInjection.databaseTypeImport.from}';\n` : \"\";\n const trpcImport = injection ? `import { initTRPC, TRPCError } from '@trpc/server';` : `import { initTRPC } from '@trpc/server';`;\n const context = injection ? `/**\n * What your \\`createContext\\` hands every procedure.\n *\n * \\`db\\` is optional here and required by \\`dbProcedure\\` below. That split is what lets an adapter\n * build a context without a handle, for a health check or a public route, while every generated\n * procedure still sees one that is present.\n */\nexport interface Context {\n db?: ${dbType};\n}` : `/**\n * What your \\`createContext\\` hands every procedure. Nothing generated reads it, so it is left\n * open; narrow it to the shape your own context really has.\n */\nexport type Context = Record<string, unknown>;`;\n const middleware = injection ? `\n/**\n * The builder every generated procedure is built from: it refuses to run without a database\n * handle, and narrows \\`ctx.db\\` from optional to present for everything downstream.\n */\nexport const dbProcedure = t.procedure.use(async ({ ctx, next }) => {\n if (!ctx.db) {\n throw new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'No database handle on the tRPC context. Provide one from createContext.',\n });\n }\n return next({ ctx: { db: ctx.db } });\n});\n` : \"\";\n return `// Generated by @drzl/generator-trpc\n// The shared tRPC base. Every generated router imports from here.\n${trpcImport}\n${typeImport}\n${context}\n\nconst t = initTRPC.context<Context>().create();\n\nexport const router = t.router;\nexport const mergeRouters = t.mergeRouters;\nexport const middleware = t.middleware;\n/** Needed to call this router in-process, from a test or from SSR. */\nexport const createCallerFactory = t.createCallerFactory;\nexport const publicProcedure = t.procedure;\n${middleware}`;\n}\nfunction renderRouter(table, opts, ctx) {\n const lib = opts.validation?.library ?? \"zod\";\n const d = LIBS[lib];\n const service = opts.template === \"service\";\n const injection = opts.databaseInjection?.enabled === true;\n const builder = injection ? \"dbProcedure\" : \"publicProcedure\";\n const insertName = `Insert${table.tsName}Schema`;\n const updateName = `Update${table.tsName}Schema`;\n const selectName = `Select${table.tsName}Schema`;\n const writable = !table.readOnly;\n const key = keyColumns(table);\n const Service = `${cap(singularize(table.tsName))}Service`;\n const serviceKeyable = !!key && key.length === 1 && key[0].tsType === \"number\";\n const keyArg = key && key.length === 1 ? `input.${key[0].name}` : \"\";\n const dbArg = injection ? \"ctx.db, \" : \"\";\n const wiredParams = injection ? \"{ ctx, input }\" : \"{ input }\";\n const procedures = [];\n const notImplemented = (what) => `throw new Error('Not implemented: ${what} ${table.tsName}.');`;\n procedures.push({\n name: \"list\",\n kind: \"query\",\n output: d.arrayOf(selectName),\n params: service && injection ? \"{ ctx }\" : \"\",\n body: service ? [`return await ${Service}.getAll(${injection ? \"ctx.db\" : \"\"});`] : [\"return [];\"]\n });\n const keyInput = key ? d.objectInline(key.map((c) => field(c, lib, \"select\")).join(\", \")) : void 0;\n if (key && keyInput) {\n const wired = service && serviceKeyable;\n procedures.push({\n name: \"byId\",\n kind: \"query\",\n input: keyInput,\n output: d.nullableOf(selectName),\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.getById(${dbArg}${keyArg});`] : service ? [serviceKeyNote(table), notImplemented(\"byId\")] : [\"return null;\"]\n });\n if (writable) {\n const updateInput = d.objectInline(\n [...key.map((c) => field(c, lib, \"select\")), `data: ${updateName}`].join(\", \")\n );\n procedures.push({\n name: \"update\",\n kind: \"mutation\",\n input: updateInput,\n output: selectName,\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.update(${dbArg}${keyArg}, input.data);`] : service ? [serviceKeyNote(table), notImplemented(\"update\")] : [notImplemented(\"update\")]\n });\n procedures.push({\n name: \"delete\",\n kind: \"mutation\",\n input: keyInput,\n output: d.booleanSchema,\n params: wired ? wiredParams : \"{ input: _input }\",\n body: wired ? [`return await ${Service}.delete(${dbArg}${keyArg});`] : service ? [serviceKeyNote(table), notImplemented(\"delete\")] : [\"return true;\"]\n });\n }\n }\n if (writable) {\n procedures.push({\n name: \"create\",\n kind: \"mutation\",\n input: insertName,\n output: selectName,\n params: service ? wiredParams : \"{ input: _input }\",\n body: service ? [`return await ${Service}.create(${dbArg}input);`] : [notImplemented(\"create\")]\n });\n }\n if (opts.includeRelations) {\n const taken = new Set(procedures.map((p) => p.name));\n procedures.push(...relationProcedures(table, lib, selectName, taken, service));\n }\n const order = [\"list\", \"byId\", \"create\", \"update\", \"delete\"];\n const rank = (n) => order.indexOf(n) === -1 ? order.length : order.indexOf(n);\n procedures.sort((a, b) => rank(a.name) - rank(b.name));\n const routerName = routerExportName(table, opts.naming);\n const entries = procedures.map((p) => {\n const rawKey = toCase(p.name, opts.naming?.procedureCase);\n const propKey = isIdent(rawKey) ? rawKey : JSON.stringify(rawKey);\n return [\n ` ${propKey}: ${builder}`,\n ...p.input ? [` .input(${p.input})`] : [],\n ` .output(${p.output})`,\n ` .${p.kind}(async (${p.params}) => {`,\n ...p.body.map((line) => ` ${line}`),\n ` }),`\n ].join(\"\\n\");\n }).join(\"\\n\");\n const body = `export const ${routerName} = router({\n${entries}\n});\n`;\n const useShared = !!opts.validation?.useShared && !!opts.validation?.importPath;\n const declared = [];\n if (!useShared) {\n if (writable) {\n declared.push(`export const ${insertName} = ${renderSchema(table, lib, \"insert\")};`);\n declared.push(`export const ${updateName} = ${renderSchema(table, lib, \"update\")};`);\n }\n declared.push(`export const ${selectName} = ${renderSchema(table, lib, \"select\")};`);\n }\n const decided = [...declared, body].join(\"\\n\\n\");\n const imports = [];\n if (useShared) {\n const sharedAffix = resolveAffix({\n affix: opts.validation?.affix,\n schemaSuffix: opts.validation?.schemaSuffix\n });\n const wanted = [\n [\"insert\", insertName],\n [\"update\", updateName],\n [\"select\", selectName]\n ].filter(([, local]) => decided.includes(local));\n if (wanted.length) {\n const spec = resolveConfiguredImport(\n opts.validation.importPath,\n ctx.out,\n process.cwd(),\n opts.importExtension\n );\n const names = wanted.map(([mode, local]) => {\n const exported = schemaName(mode, table.tsName, sharedAffix);\n return exported === local ? local : `${exported} as ${local}`;\n }).join(\", \");\n imports.push(`import { ${names} } from '${spec}';`);\n }\n }\n imports.push(\n `import { ${[builder, \"router\"].sort().join(\", \")} } from '${importSpecifier(\n `./${BASE_MODULE}.ts`,\n opts.importExtension\n )}';`\n );\n if (service) {\n imports.push(`import { ${Service} } from '${serviceImportSpecifier(table, ctx, opts)}';`);\n }\n if (LIB_USAGE[lib].test(decided)) imports.unshift(LIB_IMPORTS[lib]);\n const wide = table.columns.filter(isWide).map((c) => c.name);\n const wideNote = wide.length ? `// No validated type for ${wide.length === 1 ? \"this column\" : \"these columns\"}: ${wide.join(\", \")}.\n// DRZL could not derive one from the schema, so the router accepts any value there.\n` : \"\";\n return `// Generated by @drzl/generator-trpc\n// Router for table: ${table.name}\n${wideNote}${imports.join(\"\\n\")}\n\n${decided}`;\n}\nfunction relationProcedures(table, lib, selectSchemaName, taken, service) {\n const d = LIBS[lib];\n const out = [];\n for (const fk of table.foreignKeys ?? []) {\n if (fk.columns.length !== 1) continue;\n const colName = fk.columns[0];\n const column = table.columns.find((c) => c.name === colName);\n if (!column) continue;\n const name = `listBy${cap(colName)}`;\n if (taken.has(name)) continue;\n taken.add(name);\n out.push({\n name,\n kind: \"query\",\n input: d.objectInline(field(column, lib, \"select\")),\n output: d.arrayOf(selectSchemaName),\n params: \"{ input: _input }\",\n body: [\n `// Rows of ${table.name} whose ${JSON.stringify(colName)} matches _input.${colName}.`,\n // In `service` mode every other procedure really does reach the database, so a lookup\n // quietly answering with an empty array would read as \"no matching rows\". There is no\n // generated service method for it, so it says so instead. In `standard` mode everything\n // is a stub and `[]` is consistent with `list`.\n service ? `throw new Error('Not implemented: ${name} ${table.tsName}.');` : \"return [];\"\n ]\n });\n }\n return out;\n}\nfunction renderBarrel(routers, ctx, path, opts) {\n const baseSpec = importSpecifier(`./${BASE_MODULE}.ts`, opts.importExtension);\n const reExports = `export { createCallerFactory, publicProcedure, router } from '${baseSpec}';\n` + (opts.databaseInjection?.enabled === true ? `export { dbProcedure } from '${baseSpec}';\n` : \"\") + `export type { Context } from '${baseSpec}';\n`;\n if (!routers.length) {\n return `// Generated by @drzl/generator-trpc\n// No tables detected in analysis. Add tables to your schema and regenerate.\nimport { router } from '${baseSpec}';\n\nexport const appRouter = router({});\n\n/** The type a tRPC client is parameterised by: \\`createTRPCClient<AppRouter>()\\`. */\nexport type AppRouter = typeof appRouter;\n\n${reExports}`;\n }\n const entries = routers.map(({ filePath, exportName, table }) => ({\n rel: importSpecifier(\n \"./\" + path.relative(ctx.out, filePath).replace(/\\\\/g, \"/\"),\n opts.importExtension\n ),\n exportName,\n // The namespace a client reaches this table's procedures through: `trpc.userProfiles.list`.\n // `tsName` verbatim, because it is already a valid identifier and it is the name the user\n // wrote in their schema. The oRPC barrel lowercases this key, turning `userProfiles` into\n // `userprofiles`: harmless in an object literal nobody reads, and not harmless when the key\n // is the public API of a typed client.\n key: table.tsName\n }));\n const importLines = entries.map(({ rel, exportName }) => `import { ${exportName} } from '${rel}';`).join(\"\\n\");\n const bodyLines = entries.map(({ key, exportName }) => ` ${isIdent(key) ? key : JSON.stringify(key)}: ${exportName},`).join(\"\\n\");\n return `// Generated by @drzl/generator-trpc\nimport { router } from '${baseSpec}';\n${importLines}\n\nexport const appRouter = router({\n${bodyLines}\n});\n\n/** The type a tRPC client is parameterised by: \\`createTRPCClient<AppRouter>()\\`. */\nexport type AppRouter = typeof appRouter;\n\n${reExports}`;\n}\nfunction serviceKeyNote(table) {\n const cols = table.primaryKey?.columns ?? [];\n const shape = cols.length > 1 ? `has a composite primary key (${cols.join(\", \")})` : `has a non-numeric primary key (${cols[0]})`;\n return `// ${table.name} ${shape}, and @drzl/generator-service types its key parameter as one number.\n// Wire this to your own lookup.`;\n}\nfunction routerExportName(table, naming) {\n const base = `${table.tsName}${naming?.routerSuffix ?? \"Router\"}`;\n const c = naming?.procedureCase;\n return toCase(base, c === \"kebab\" ? \"camel\" : c);\n}\nfunction serviceImportSpecifier(table, ctx, opts) {\n const rel = relativePosix(ctx.out, ctx.services);\n const dir = !rel ? \".\" : rel.startsWith(\".\") ? rel : `./${rel}`;\n return importSpecifier(`${dir}/${singularize(table.tsName)}Service.ts`, opts.importExtension);\n}\nfunction relativePosix(from, to) {\n const norm = (p) => p.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const a = norm(from).split(\"/\");\n const b = norm(to).split(\"/\");\n let i = 0;\n while (i < a.length && i < b.length && a[i] === b[i]) i++;\n return [...Array.from({ length: a.length - i }, () => \"..\"), ...b.slice(i)].join(\"/\");\n}\nfunction buildHeader(h) {\n if (h && h.enabled === false) return \"\";\n const text = h?.text?.trim();\n const lines = text ? text.split(/\\r?\\n/).map((l) => `// ${l}`) : [\n \"// Generated by DRZL (@drzl/*)\",\n \"// Generated output is granted to you under your project's license.\",\n \"// You may use, copy, modify, and distribute without attribution.\"\n ];\n return lines.join(\"\\n\") + \"\\n\\n\";\n}\nexport {\n BASE_MODULE,\n TRPCGenerator,\n TRPC_MAJOR,\n index_default as default\n};\n","// src/index.ts\nimport {\n formatCode,\n moduleFileName,\n moduleSpecifier,\n resolveAffix,\n schemaName,\n typeName\n} from \"@drzl/validation-core\";\n\n// src/schemas.ts\nimport {\n COLUMN_FORMATS,\n insertColumns,\n isIntegerColumn,\n parseCheck,\n selectColumns,\n updateColumns\n} from \"@drzl/validation-core\";\nvar DRAFT = \"https://json-schema.org/draft/2020-12/schema\";\nvar UUID_FORMAT = \"uuid\";\nvar base64 = (target) => target === \"openapi-3.0\" ? { type: \"string\", format: \"byte\" } : { type: \"string\", contentEncoding: \"base64\" };\nfunction baseSchema(c, mode, target, checks, sets, lengths) {\n const s = c.shape;\n if (s) {\n switch (s.kind) {\n case \"json\":\n return {};\n case \"custom\":\n return {};\n case \"buffer\":\n return base64(target);\n case \"tuple\":\n return target === \"openapi-3.0\" ? { type: \"array\", items: { type: \"number\" }, minItems: s.length, maxItems: s.length } : {\n type: \"array\",\n prefixItems: Array.from({ length: s.length }, () => ({ type: \"number\" })),\n minItems: s.length,\n maxItems: s.length\n };\n case \"numberObject\":\n return {\n type: \"object\",\n properties: Object.fromEntries(s.fields.map((f) => [f, { type: \"number\" }])),\n required: [...s.fields]\n };\n case \"numberVector\":\n return {\n type: \"array\",\n items: { type: \"number\" },\n ...s.length ? { minItems: s.length, maxItems: s.length } : {}\n };\n case \"bitstring\":\n return {\n type: \"string\",\n pattern: \"^[01]*$\",\n ...s.length ? s.exact ? { minLength: s.length, maxLength: s.length } : { maxLength: s.length } : {}\n };\n case \"byteString\":\n return { type: \"string\", ...s.length ? { maxLength: s.length } : {} };\n }\n }\n const set = sets.find((x) => x.column === c.name);\n if (set) return { enum: set.values.map((v) => set.kind === \"string\" ? v : Number(v)) };\n if (c.enumValues && c.enumValues.length) return { enum: [...c.enumValues] };\n const mine = c.arrayDimensions ? [] : checks.filter((k) => k.column === c.name);\n const eq = mine.find((k) => k.operator === \"=\");\n if (eq) {\n const only = eq.kind === \"string\" ? eq.value : Number(eq.value);\n return target === \"openapi-3.0\" ? { enum: [only] } : { const: only };\n }\n switch (c.tsType) {\n case \"string\": {\n const out = { type: \"string\" };\n if (c.format === \"uuid\") out.format = UUID_FORMAT;\n else if (c.format && COLUMN_FORMATS[c.format]) out.pattern = COLUMN_FORMATS[c.format];\n if (c.maxLength !== void 0) out.maxLength = c.maxLength;\n applyByteCap(out, c);\n applyLengths(out, c, lengths);\n return out;\n }\n case \"number\": {\n const out = { type: isIntegerColumn(c) ? \"integer\" : \"number\" };\n if (!c.arrayDimensions) applyNumericBounds(out, c, checks, target);\n return out;\n }\n case \"bigint\":\n return { type: \"string\", pattern: \"^-?\\\\d+$\" };\n case \"boolean\":\n return { type: \"boolean\" };\n case \"Date\":\n return { type: \"string\", format: \"date-time\" };\n case \"Uint8Array\":\n return base64(target);\n default:\n return {};\n }\n}\nfunction applyByteCap(out, c) {\n if (!c.maxBytes) return;\n out.maxLength = Math.min(Number(out.maxLength ?? Infinity), c.maxBytes);\n out.description = `At most ${c.maxBytes} bytes of UTF-8, which JSON Schema has no keyword for. maxLength counts characters: it refuses nothing the column accepts, and a string of multi-byte characters can satisfy it and still be too long for the column.`;\n}\nfunction applyLengths(out, c, lengths) {\n for (const k of lengths.filter((x) => x.column === c.name)) {\n const n = Number(k.value);\n if (k.operator === \">=\") out.minLength = Math.max(Number(out.minLength ?? 0), n);\n else if (k.operator === \">\") out.minLength = Math.max(Number(out.minLength ?? 0), n + 1);\n else if (k.operator === \"<=\") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n);\n else if (k.operator === \"<\") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n - 1);\n else if (k.operator === \"=\") {\n out.minLength = n;\n out.maxLength = n;\n }\n }\n}\nfunction applyNumericBounds(out, c, checks, target) {\n let min = c.min !== void 0 ? { value: Number(c.min), exclusive: false } : void 0;\n let max = c.max !== void 0 ? { value: Number(c.max), exclusive: false } : void 0;\n for (const k of checks.filter((x) => x.column === c.name && x.kind === \"number\")) {\n if (k.operator === \">=\") min = { value: Number(k.value), exclusive: false };\n else if (k.operator === \">\") min = { value: Number(k.value), exclusive: true };\n else if (k.operator === \"<=\") max = { value: Number(k.value), exclusive: false };\n else if (k.operator === \"<\") max = { value: Number(k.value), exclusive: true };\n }\n const old = target === \"openapi-3.0\";\n if (min) {\n if (min.exclusive && !old) out.exclusiveMinimum = min.value;\n else {\n out.minimum = min.value;\n if (min.exclusive) out.exclusiveMinimum = true;\n }\n }\n if (max) {\n if (max.exclusive && !old) out.exclusiveMaximum = max.value;\n else {\n out.maximum = max.value;\n if (max.exclusive) out.exclusiveMaximum = true;\n }\n }\n}\nfunction cardinalityBounds(c, cardinalities) {\n if (!c.arrayDimensions) return {};\n const out = {};\n for (const k of cardinalities.filter((x) => x.column === c.name)) {\n const n = Number(k.value);\n if (k.operator === \">=\") out.minItems = n;\n else if (k.operator === \">\") out.minItems = n + 1;\n else if (k.operator === \"<=\") out.maxItems = n;\n else if (k.operator === \"<\") out.maxItems = n - 1;\n else if (k.operator === \"=\") {\n out.minItems = n;\n out.maxItems = n;\n }\n }\n return out;\n}\nfunction makeNullable(s, target) {\n if (target === \"openapi-3.0\") return { ...s, nullable: true };\n if (s.type === void 0) {\n if (Array.isArray(s.enum)) return { ...s, enum: [...s.enum, null] };\n if (\"const\" in s) {\n const { const: k, ...rest } = s;\n return { ...rest, enum: [k, null] };\n }\n return s;\n }\n return { ...s, type: [s.type, \"null\"] };\n}\nfunction columnSchema(c, mode, target, checks, sets, lengths, cardinalities, applyDefault) {\n let s = baseSchema(c, mode, target, checks, sets, lengths);\n const dims = c.arrayDimensions ?? 0;\n for (let i = 0; i < dims; i++) {\n s = { type: \"array\", items: s, ...i === dims - 1 ? cardinalityBounds(c, cardinalities) : {} };\n }\n if (c.nullable) s = makeNullable(s, target);\n if (mode === \"insert\" && applyDefault && c.defaultValue !== void 0) {\n s = { ...s, default: c.defaultValue };\n }\n return s;\n}\nfunction rowDescription(rows, cols) {\n const present = new Set(cols.map((c) => c.name));\n const applicable = rows.filter((r) => present.has(r.left) && present.has(r.right));\n if (!applicable.length) return void 0;\n const list = applicable.map((r) => `${r.name ? `${r.name}: ` : \"\"}${r.left} ${r.operator} ${r.right}`).join(\"; \");\n return `Row constraints not expressible in JSON Schema: ${list}`;\n}\nfunction tableSchema(table, cols, mode, target, applyDefaults, parsed) {\n const properties = {};\n const required = [];\n for (const c of cols) {\n properties[c.name] = columnSchema(\n c,\n mode,\n target,\n parsed.checks,\n parsed.sets,\n parsed.lengths,\n parsed.cardinalities,\n applyDefaults\n );\n const suppliedOnInsert = c.hasDefault || applyDefaults && c.defaultValue !== void 0 || c.isGenerated;\n const optional = mode === \"update\" || mode === \"insert\" && suppliedOnInsert;\n if (!optional) required.push(c.name);\n }\n const desc = rowDescription(parsed.rows, cols);\n return {\n ...target === \"draft-2020-12\" ? { $schema: DRAFT } : {},\n $id: `${table.tsName}.${mode}`,\n title: `${mode} ${table.tsName}`,\n ...desc ? { description: desc } : {},\n type: \"object\",\n properties,\n ...required.length ? { required } : {},\n additionalProperties: false\n };\n}\nfunction collect(table) {\n const parsed = (table.checks ?? []).map((k) => parseCheck(k.expression, k.name));\n return {\n checks: parsed.flatMap((p) => p.ok ? p.checks : []),\n sets: parsed.flatMap((p) => p.ok ? p.sets ?? [] : []),\n rows: parsed.flatMap((p) => p.ok ? p.rows ?? [] : []),\n lengths: parsed.flatMap((p) => p.ok ? p.lengths ?? [] : []),\n cardinalities: parsed.flatMap((p) => p.ok ? p.cardinalities ?? [] : [])\n };\n}\nfunction tableSchemas(table, opts = {}) {\n const target = opts.target ?? \"draft-2020-12\";\n const parsed = collect(table);\n const build2 = (cols, mode) => tableSchema(table, cols, mode, target, !!opts.applyDefaults, parsed);\n return {\n insert: build2(insertColumns(table), \"insert\"),\n update: build2(updateColumns(table), \"update\"),\n select: build2(selectColumns(table), \"select\")\n };\n}\nfunction componentsDocument(tables, opts = {}) {\n const schemas = {};\n for (const table of tables) {\n const built = tableSchemas(table, opts);\n for (const mode of [\"insert\", \"update\", \"select\"]) {\n const name = `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;\n const { $schema: _dialect, $id: _id, ...rest } = built[mode];\n schemas[name] = rest;\n }\n }\n return { schemas };\n}\n\n// src/openapi.ts\nvar ERROR_SCHEMA = \"Error\";\nvar componentName = (table, mode) => `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;\nvar ref = (name) => ({ $ref: `#/components/schemas/${name}` });\nvar pascal = (s) => s.charAt(0).toUpperCase() + s.slice(1);\nfunction keyColumns(table) {\n const names = table.primaryKey?.columns ?? [];\n if (!names.length) return null;\n const cols = names.map((n) => table.columns.find((c) => c.name === n));\n if (cols.some((c) => !c)) return null;\n return cols;\n}\nvar modesFor = (table, key) => [\n ...table.readOnly ? [] : [\"insert\"],\n ...table.readOnly || !key ? [] : [\"update\"],\n \"select\"\n];\nvar resourceSegment = (table) => encodeURIComponent(table.name);\nfunction foreignKeysOf(table) {\n if (table.foreignKeys?.length) return table.foreignKeys;\n return table.columns.filter((c) => c.references).map((c) => ({\n columns: [c.name],\n foreignTable: c.references.table,\n foreignColumns: [c.references.column]\n }));\n}\nvar jsonBody = (schema) => ({ content: { \"application/json\": { schema } } });\nfunction build(tables, opts) {\n const target = opts.target ?? \"draft-2020-12\";\n const schemaTarget = target === \"openapi-3.0\" ? \"openapi-3.0\" : \"openapi-3.1\";\n const failure = String(opts.validationStatus ?? 400);\n const paths = {};\n const schemas = {};\n const tags = [];\n const operationIds = /* @__PURE__ */ new Map();\n const owner = /* @__PURE__ */ new Map();\n const claim = (path, by, label) => {\n const taken = owner.get(path);\n if (taken !== void 0 && taken.by !== by) {\n throw new Error(\n `@drzl/generator-json-schema: the OpenAPI path \"${path}\" is claimed twice: by table \"${taken.label}\" (exported as ${taken.by}) and by table \"${label}\" (exported as ${by}). A path names one resource, so one of the two has to be left out of this generator with the config's \"exclude\" list.`\n );\n }\n owner.set(path, { by, label });\n };\n const operation = (id, table, rest) => {\n const clash = operationIds.get(id);\n if (clash !== void 0) {\n throw new Error(\n `@drzl/generator-json-schema: the operationId \"${id}\" would be emitted for both \"${clash}\" and \"${table.name}\". An operationId is the method name a client generator derives, and the specification requires it to be unique across the document.`\n );\n }\n operationIds.set(id, table.name);\n return { operationId: id, tags: [table.name], ...rest };\n };\n const built = tables.map((table) => ({\n table,\n key: keyColumns(table),\n segment: resourceSegment(table),\n schemas: tableSchemas(table, { target: schemaTarget, applyDefaults: opts.applyDefaults })\n }));\n for (const { table, key, segment, schemas: built3 } of built) {\n for (const mode of modesFor(table, key)) {\n const { $schema: _dialect, $id: _id, ...rest } = built3[mode];\n schemas[componentName(table, mode)] = rest;\n }\n const notes = [];\n if (!key) notes.push(\"It has no primary key, so no path addresses a single row.\");\n if (table.readOnly) {\n notes.push(\"It refuses every write, so only reads are described.\");\n }\n tags.push({ name: table.name, description: [`Table \"${table.name}\".`, ...notes].join(\" \") });\n const T = pascal(table.tsName);\n const select = ref(componentName(table, \"select\"));\n const validationFailed = {\n description: \"The request does not match the schema for this operation.\",\n ...jsonBody(ref(ERROR_SCHEMA))\n };\n const collidable = [\n ...table.primaryKey ? [`primary key (${table.primaryKey.columns.join(\", \")})`] : [],\n ...table.unique.map((u) => `${u.name ? `${u.name} ` : \"\"}(${u.columns.join(\", \")})`)\n ];\n const conflict = (constraints) => ({\n description: `The row collides with an existing one on ${constraints.join(\"; \")}.`,\n ...jsonBody(ref(ERROR_SCHEMA))\n });\n const collection = `/${segment}`;\n claim(collection, table.tsName, table.name);\n const item = {\n get: operation(`list${T}`, table, {\n summary: `List every ${table.name} row.`,\n // No pagination parameters. Whether the server implements a limit, an offset or a cursor is\n // not something a Drizzle schema states, and a declared parameter nothing honours is worse\n // than an undeclared one.\n responses: {\n \"200\": {\n description: `Every ${table.name} row.`,\n ...jsonBody({ type: \"array\", items: select })\n }\n }\n })\n };\n if (!table.readOnly) {\n item.post = operation(`create${T}`, table, {\n summary: `Create a ${table.name} row.`,\n requestBody: { required: true, ...jsonBody(ref(componentName(table, \"insert\"))) },\n responses: {\n \"201\": { description: `The ${table.name} row that was created.`, ...jsonBody(select) },\n [failure]: validationFailed,\n ...collidable.length ? { \"409\": conflict(collidable) } : {}\n }\n });\n }\n paths[collection] = item;\n if (!key) continue;\n const itemPath = `${collection}/${key.map((c) => `{${c.name}}`).join(\"/\")}`;\n claim(itemPath, table.tsName, table.name);\n const parameters = key.map((c) => ({\n name: c.name,\n in: \"path\",\n required: true,\n description: `${c.name}, from the primary key of ${table.name}.`,\n // The column's own schema rather than a string, so an integer key is declared as one and a\n // uuid key carries its format. This is the whole point of reading the real key.\n schema: built3.select.properties[c.name] ?? {}\n }));\n const missing = {\n description: `No ${table.name} row has that ${key.map((c) => c.name).join(\" and \")}.`,\n ...jsonBody(ref(ERROR_SCHEMA))\n };\n const byId = {\n parameters,\n get: operation(`get${T}`, table, {\n summary: `Read one ${table.name} row.`,\n responses: {\n \"200\": { description: `The requested ${table.name} row.`, ...jsonBody(select) },\n [failure]: validationFailed,\n \"404\": missing\n }\n })\n };\n if (!table.readOnly) {\n byId.patch = operation(`update${T}`, table, {\n summary: `Patch one ${table.name} row.`,\n requestBody: { required: true, ...jsonBody(ref(componentName(table, \"update\"))) },\n responses: {\n \"200\": { description: `The ${table.name} row after the patch.`, ...jsonBody(select) },\n [failure]: validationFailed,\n \"404\": missing,\n // The primary key is not in the update schema, so a patch cannot collide on it. Only a\n // unique constraint over other columns can.\n ...table.unique.length ? {\n \"409\": conflict(\n table.unique.map((u) => `${u.name ? `${u.name} ` : \"\"}(${u.columns.join(\", \")})`)\n )\n } : {}\n }\n });\n byId.delete = operation(`delete${T}`, table, {\n summary: `Delete one ${table.name} row.`,\n responses: {\n // No body. Handing back the deleted row is the alternative and it is not a true statement\n // on every dialect DRZL supports: RETURNING is Postgres and SQLite, and MySQL has no such\n // clause, so an implementation there has nothing to send.\n \"204\": { description: `The ${table.name} row was deleted. No content is returned.` },\n [failure]: validationFailed,\n \"404\": missing\n }\n });\n }\n paths[itemPath] = byId;\n if (!opts.includeRelations) continue;\n for (const child of built) {\n if (child.table === table) continue;\n const matching = foreignKeysOf(child.table).filter(\n (fk) => fk.foreignTable === table.name && fk.foreignColumns.length === key.length && fk.foreignColumns.every((c, i) => c === key[i].name)\n );\n if (matching.length !== 1) continue;\n const subPath = `${itemPath}/${child.segment}`;\n claim(\n subPath,\n `${table.tsName} -> ${child.table.tsName}`,\n `${table.name} -> ${child.table.name}`\n );\n paths[subPath] = {\n parameters,\n get: operation(`list${T}${pascal(child.table.tsName)}`, child.table, {\n summary: `List the ${child.table.name} rows belonging to one ${table.name} row.`,\n responses: {\n \"200\": {\n description: `The ${child.table.name} rows whose ${matching[0].columns.join(\", \")} names this ${table.name} row.`,\n ...jsonBody({ type: \"array\", items: ref(componentName(child.table, \"select\")) })\n },\n [failure]: validationFailed,\n \"404\": missing\n }\n })\n };\n }\n }\n return { paths, schemas, tags };\n}\nvar errorSchema = () => ({\n title: \"error\",\n description: \"What an operation returns when it does not return the row.\",\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n code: { type: \"string\" }\n },\n required: [\"message\"],\n additionalProperties: true\n});\nfunction openApiDocument(tables, opts = {}) {\n const target = opts.target ?? \"draft-2020-12\";\n const { paths, schemas, tags } = build(tables, opts);\n if (ERROR_SCHEMA in schemas) {\n throw new Error(\n `@drzl/generator-json-schema: a table produced the component schema name \"${ERROR_SCHEMA}\", which the document already uses for its error responses.`\n );\n }\n return {\n openapi: target === \"openapi-3.0\" ? \"3.0.3\" : \"3.1.1\",\n info: {\n title: opts.info?.title ?? \"API\",\n version: opts.info?.version ?? \"0.0.0\",\n description: opts.info?.description ?? \"Generated by DRZL from a Drizzle schema. Paths, request bodies and response bodies are derived from the schema alone; nothing here has been checked against a running server.\"\n },\n ...opts.servers?.length ? { servers: opts.servers } : {},\n paths,\n components: { schemas: { ...schemas, [ERROR_SCHEMA]: errorSchema() } },\n tags\n };\n}\n\n// src/index.ts\nvar DEFAULT_FILE_SUFFIX = \".schema.ts\";\nfunction renderTableModule(table, affix, target, applyDefaults) {\n const T = table.tsName;\n const schemas = tableSchemas(table, { target, applyDefaults });\n const decl = (mode) => `export const ${schemaName(mode, T, affix)} = ${JSON.stringify(schemas[mode], null, 2)} as const;\n\nexport type ${typeName(mode, T, affix)} = typeof ${schemaName(mode, T, affix)};`;\n return [decl(\"insert\"), decl(\"update\"), decl(\"select\")].join(\"\\n\\n\") + \"\\n\";\n}\nfunction resolveDocument(opt) {\n if (!opt) return null;\n const o = opt === true ? {} : opt;\n if (o.enabled === false) return null;\n return { ...o, format: o.format ?? \"ts\" };\n}\nvar JsonSchemaGenerator = class {\n constructor(analysis) {\n this.analysis = analysis;\n this.library = \"json-schema\";\n }\n async generate(opts) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const out = path.resolve(process.cwd(), opts.outDir);\n const files = [];\n await fs.mkdir(out, { recursive: true });\n const affix = resolveAffix(opts);\n const fileSuffix = opts.fileSuffix ?? DEFAULT_FILE_SUFFIX;\n const target = opts.target ?? \"draft-2020-12\";\n const document = resolveDocument(opts.document);\n for (const table of this.analysis.tables) {\n const filePath = path.join(out, moduleFileName(table.tsName, fileSuffix));\n const code = renderTableModule(table, affix, target, !!opts.applyDefaults);\n const formatted = await formatCode(\n buildHeader(opts.outputHeader) + code,\n filePath,\n opts.format\n );\n await fs.writeFile(filePath, formatted, \"utf8\");\n files.push(filePath);\n }\n if (opts.components) {\n const doc = componentsDocument(this.analysis.tables, {\n target,\n applyDefaults: !!opts.applyDefaults\n });\n const componentsPath = path.join(out, \"components.ts\");\n const code = `export const components = ${JSON.stringify(doc, null, 2)} as const;\n`;\n await fs.writeFile(\n componentsPath,\n await formatCode(buildHeader(opts.outputHeader) + code, componentsPath, opts.format),\n \"utf8\"\n );\n files.push(componentsPath);\n }\n if (document) {\n const built = openApiDocument(this.analysis.tables, {\n target,\n applyDefaults: !!opts.applyDefaults,\n includeRelations: !!opts.includeRelations,\n info: document.info,\n servers: document.servers,\n validationStatus: document.validationStatus\n });\n const body = JSON.stringify(built, null, 2);\n if (document.format !== \"json\") {\n const tsPath = path.join(out, \"openapi.ts\");\n const code = `export const openapi = ${body} as const;\n`;\n await fs.writeFile(\n tsPath,\n await formatCode(buildHeader(opts.outputHeader) + code, tsPath, opts.format),\n \"utf8\"\n );\n files.push(tsPath);\n }\n if (document.format !== \"ts\") {\n const jsonPath = path.join(out, \"openapi.json\");\n await fs.writeFile(jsonPath, body + \"\\n\", \"utf8\");\n files.push(jsonPath);\n }\n }\n const ext = opts.importExtension === \"none\" ? \"\" : \".js\";\n const indexPath = path.join(out, \"index.ts\");\n const index = this.analysis.tables.map(\n (t) => `export * from '${moduleSpecifier(t.tsName, fileSuffix, opts.importExtension)}';`\n ).concat(opts.components ? [`export * from './components${ext}';`] : []).concat(document && document.format !== \"json\" ? [`export * from './openapi${ext}';`] : []).join(\"\\n\") + \"\\n\";\n const indexFormatted = await formatCode(\n buildHeader(opts.outputHeader) + index,\n indexPath,\n opts.format\n );\n await fs.writeFile(indexPath, indexFormatted, \"utf8\");\n files.push(indexPath);\n return files;\n }\n renderTable(table, opts) {\n return renderTableModule(\n table,\n resolveAffix(opts),\n opts?.target ?? \"draft-2020-12\",\n !!opts?.applyDefaults\n );\n }\n};\nvar index_default = JsonSchemaGenerator;\nfunction buildHeader(h) {\n if (h?.enabled === false) return \"\";\n const text = h?.text ?? \"// Generated by DRZL. Do not edit by hand.\";\n return `${text}\n\n`;\n}\nexport {\n DRAFT,\n JsonSchemaGenerator,\n componentsDocument,\n index_default as default,\n openApiDocument,\n tableSchemas\n};\n","#!/usr/bin/env node\nimport { SchemaAnalyzer } from '@drzl/analyzer';\nimport { ORPCGenerator } from '@drzl/generator-orpc';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport cliProgress from 'cli-progress';\nimport { Command } from 'commander';\nimport * as path from 'node:path';\nimport ora from 'ora';\nimport { jsonSchemaOptions } from './json-schema-options.js';\nimport { trpcOptions } from './trpc-options.js';\nimport { validationOptions } from './validation-options';\nimport {\n computeGeneratorOutputDirs,\n computeWatchTargets,\n DrzlConfig,\n filterTables,\n loadConfig,\n} from './config.js';\nimport { buildDoctorReport, renderDoctorReport } from './doctor.js';\nimport { diffSnapshots, restoreSnapshot, snapshotAll } from './drift.js';\nimport { GeneratorNotInstalledError, loadGenerator } from './generator-loader.js';\nimport { maybeShowSponsorMessage } from './sponsor.js';\nimport { CLI_VERSION } from './version.js';\n\n/**\n * Say what went wrong with a generator, distinguishing the two things that can.\n *\n * Every branch below used to print \"<name> generator missing. Install with: npm install\n * @drzl/generator-<name>\" for anything at all that threw, with the real reason on a trailing\n * \"Error details\" line. A generator that was installed and merely failed therefore sent its user\n * to reinstall a package they already had, and the sentence that would have told them what\n * actually happened was the one written as a footnote.\n *\n * `loadGenerator` marks the one case that is an install problem, so the package name comes off the\n * error rather than being repeated here beside the `import()` that already spells it.\n */\nfunction reportGeneratorFailure(kind: string, e: unknown): void {\n if (e instanceof GeneratorNotInstalledError) {\n console.error(\n chalk.red(`The ${kind} generator is not installed.`),\n chalk.yellow(`\\nInstall with: npm install ${e.specifier}`)\n );\n return;\n }\n console.error(chalk.red(`The ${kind} generator failed:`), (e as any)?.message ?? e);\n}\n\nconst program = new Command();\nprogram.name('drzl').description('DRZL - Drizzle Developer Toolkit').version(CLI_VERSION);\nprogram.addHelpText(\n 'afterAll',\n `\\nNeed a template, adapter, or generator DRZL doesn't ship yet?\\n→ DM @omardulaimidev on X: https://x.com/omardulaimidev\\n`\n);\n\nprogram\n .command('analyze')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('--relations', 'include relations', true)\n .option('--validate', 'validate constraints', true)\n .option('--out <file>', 'write analysis JSON to file')\n .option('--json', 'print JSON to stdout (overrides --out)', false)\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const spinner = !opts.json ? ora('Analyzing schema...').start() : null;\n const start = Date.now();\n const res = await analyzer.analyze({\n includeRelations: !!opts.relations,\n validateConstraints: !!opts.validate,\n });\n const ms = Date.now() - start;\n const json = JSON.stringify(res, null, 2);\n if (opts.json) {\n console.log(json);\n } else if (opts.out) {\n const fs = await import('node:fs/promises');\n await fs.writeFile(opts.out, json, 'utf8');\n spinner?.succeed(chalk.green(`Analysis written to ${opts.out} in ${ms}ms`));\n } else {\n spinner?.succeed(chalk.green(`Analyzed in ${ms}ms`));\n console.log(json);\n }\n process.exit(res.issues.some((i) => i.level === 'error') ? 2 : 0);\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n if (opts.json)\n console.log(JSON.stringify({ event: 'error', code: 'DRZL_CLI_ANALYZE', message: msg }));\n else\n console.error(\n chalk.red('Analyze failed (DRZL_CLI_ANALYZE):'),\n msg,\n '\\nTip: run with --json for structured output.'\n );\n process.exit(1);\n }\n });\n\nprogram\n .command('doctor')\n .description('Report what DRZL cannot type or enforce in your schema, and why')\n .argument('[schema]', 'path to drizzle schema (TS); defaults to the schema in drzl.config')\n .option('-c, --config <path>', 'path to drzl.config, read when no schema argument is given')\n .option('--json', 'print the report as JSON instead of prose', false)\n .option('--strict', 'exit 2 when anything is reported', false)\n .action(async (schema: string | undefined, opts: any) => {\n try {\n // A schema path argument, like `analyze`, or the one already named in the config, since a\n // user who has a config should not have to retype the path they put in it.\n let target = schema;\n if (!target) {\n const cfg = await loadConfig(opts.config);\n target = cfg?.schema;\n }\n if (!target) {\n const msg = 'No schema given. Pass a path, or run from a directory with a drzl.config.';\n if (opts.json)\n console.log(JSON.stringify({ event: 'error', code: 'DRZL_CLI_DOCTOR', message: msg }));\n else console.error(chalk.red('Doctor failed (DRZL_CLI_DOCTOR):'), msg);\n process.exit(1);\n return;\n }\n\n const analyzer = new SchemaAnalyzer(target);\n // Both on, unconditionally. Doctor's job is to look at everything, and a warning that only\n // appears when relations are read would be hidden by a flag turning them off.\n const analysis = await analyzer.analyze({\n includeRelations: true,\n validateConstraints: true,\n });\n const report = buildDoctorReport(analysis, target);\n\n if (opts.json) console.log(JSON.stringify(report, null, 2));\n else console.log(renderDoctorReport(report));\n\n // An error-level issue means the schema was never read: the file is missing, or importing it\n // threw. There is no report to act on, so this exits like `analyze`'s failure path rather\n // than pretending the empty analysis was a clean bill of health.\n if (report.findings.some((f) => f.level === 'error')) {\n process.exit(1);\n return;\n }\n // Zero by default, and that is the whole point. A schema carrying a customType or a CHECK\n // this parser will not guess at is normal and usable, and a doctor that failed every\n // pipeline reading one would be switched off within a week. `--strict` is the opt-in.\n process.exit(opts.strict && report.findings.length ? 2 : 0);\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n if (opts.json)\n console.log(JSON.stringify({ event: 'error', code: 'DRZL_CLI_DOCTOR', message: msg }));\n else\n console.error(\n chalk.red('Doctor failed (DRZL_CLI_DOCTOR):'),\n msg,\n '\\nTip: run with --json for structured output.'\n );\n process.exit(1);\n }\n });\n\nprogram\n .command('generate')\n .description('Run configured generators (drzl.config.*)')\n .option('-c, --config <path>', 'path to drzl.config')\n .option(\n '--check',\n 'regenerate and fail if the result differs from what is on disk, without changing it'\n )\n .action(async (opts: any) => {\n try {\n const cfg = await loadConfig(opts.config);\n if (!cfg) {\n console.error(\n chalk.red('No config found (DRZL_CFG_001). Create drzl.config.ts or pass --config.')\n );\n process.exit(2);\n return;\n }\n const analyzer = new SchemaAnalyzer(cfg.schema);\n const spinner = ora('Analyzing...').start();\n const t0 = Date.now();\n const analysis = await analyzer.analyze({\n includeRelations: cfg.analyzer.includeRelations,\n validateConstraints: cfg.analyzer.validateConstraints,\n includeHeuristicRelations: cfg.analyzer.includeHeuristicRelations,\n });\n // Applied before any generator sees the analysis, so every one of them honours it without\n // needing to know the option exists.\n analysis.tables = filterTables(analysis.tables, cfg);\n spinner.succeed(`Analysis complete in ${Date.now() - t0}ms`);\n reportWideColumns(analysis.issues);\n // Under --check the existing output is captured before anything overwrites it, so the\n // regenerated result can be compared against it and the tree put back either way.\n const driftDirs = computeGeneratorOutputDirs(cfg);\n const driftBefore = opts.check ? await snapshotAll(driftDirs) : null;\n const progress = new cliProgress.SingleBar(\n { hideCursor: true },\n cliProgress.Presets.shades_classic\n );\n const total = analysis.tables.length || 1;\n progress.start(total, 0);\n // Where the service generator is actually writing, so a router template that imports\n // services spells a path that exists. Templates default this to 'src/services', and with\n // nothing passed that default was used no matter where the services really went, emitting\n // an import of a module that was never created. Must match the `g.path ?? 'src/services'`\n // used by the service branch below.\n const servicesDir =\n cfg.generators.find((x: { kind: string }) => x.kind === 'service')?.path ?? 'src/services';\n for (const g of cfg.generators) {\n if (g.kind === 'orpc') {\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: cfg.outDir,\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n templateOptions: g.templateOptions,\n importExtension: g.importExtension,\n validation: g.validation,\n // Documented on this generator since it was added and never reachable from a config\n // file, because the config schema had no such key and zod stripped it in silence.\n databaseInjection: g.databaseInjection,\n servicesDir,\n onProgress: ({ index }) => progress.update(index),\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (${g.kind}): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } else if (g.kind === 'trpc') {\n try {\n // An optional dependency, like the json-schema generator and unlike oRPC. A package\n // that has never been published cannot publish through npm's trusted-publisher OIDC\n // flow, so its first version has to go out by hand; naming it as a hard dependency of\n // the CLI in the same release breaks `npm i @drzl/cli` for everyone until it exists.\n // A missing optional dependency is skipped by the installer rather than failing it,\n // which is why this one really can be absent on an ordinary install.\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n const { files } = await gen.generate({\n ...trpcOptions(g, cfg, servicesDir),\n onProgress: ({ index }: { index: number }) => progress.update(index),\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (trpc): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'service') {\n try {\n const { ServiceGenerator } = await loadGenerator(\n '@drzl/generator-service',\n () => import('@drzl/generator-service')\n );\n const gen = new ServiceGenerator(analysis);\n const target = g.path ?? 'src/services';\n const files = await gen.generate({\n outDir: target,\n outputHeader: g.outputHeader,\n format: g.format,\n dataAccess: g.dataAccess,\n dbImportPath: g.dbImportPath,\n schemaImportPath: g.schemaImportPath,\n importExtension: g.importExtension,\n // The other half of `databaseInjection`. A router generator in injection mode\n // emits `Service.getById(ctx.db, id)`, and only a service generated in the same\n // mode has a `db` parameter to receive it. This branch never passed the option, so\n // the two halves of one generated project disagreed about the signature.\n databaseInjection: g.databaseInjection,\n });\n progress.stop();\n ora().succeed(chalk.green(`Generated (service): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'zod') {\n try {\n const { ZodGenerator } = await loadGenerator(\n '@drzl/generator-zod',\n () => import('@drzl/generator-zod')\n );\n const gen = new ZodGenerator(analysis);\n const target = g.path ?? 'src/validators/zod';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (zod): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'valibot') {\n try {\n const { ValibotGenerator } = await loadGenerator(\n '@drzl/generator-valibot',\n () => import('@drzl/generator-valibot')\n );\n const gen = new ValibotGenerator(analysis);\n const target = g.path ?? 'src/validators/valibot';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (valibot): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'arktype') {\n try {\n const { ArkTypeGenerator } = await loadGenerator(\n '@drzl/generator-arktype',\n () => import('@drzl/generator-arktype')\n );\n const gen = new ArkTypeGenerator(analysis);\n const target = g.path ?? 'src/validators/arktype';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: false }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (arktype): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'json-schema') {\n try {\n // An optional dependency, unlike the other generators, until its npm trusted publisher\n // exists. A missing optional dependency is skipped rather than failing the install,\n // which is what keeps `npm i @drzl/cli` working meanwhile, and is why this one really\n // can be absent on a normal install.\n const { JsonSchemaGenerator } = await loadGenerator(\n '@drzl/generator-json-schema',\n () => import('@drzl/generator-json-schema')\n );\n const gen = new JsonSchemaGenerator(analysis);\n const target = g.path ?? 'src/validators/json-schema';\n const files = await gen.generate(jsonSchemaOptions(g, cfg, target) as never);\n progress.stop();\n ora().succeed(chalk.green(`Generated (json-schema): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n } else if (g.kind === 'typebox') {\n try {\n const { TypeBoxGenerator } = await loadGenerator(\n '@drzl/generator-typebox',\n () => import('@drzl/generator-typebox')\n );\n const gen = new TypeBoxGenerator(analysis);\n const target = g.path ?? 'src/validators/typebox';\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n progress.stop();\n ora().succeed(chalk.green(`Generated (typebox): ${files.length} files`));\n files.forEach((f: string) => console.log(' -', chalk.cyan(f)));\n } catch (e: any) {\n progress.stop();\n reportGeneratorFailure(g.kind, e);\n process.exit(1);\n }\n }\n }\n if (driftBefore) {\n const after = await snapshotAll(driftDirs);\n const drift = diffSnapshots(driftBefore, after);\n // Restored whether or not anything drifted, so `--check` never leaves the tree altered.\n await restoreSnapshot(driftBefore, after);\n\n if (drift.length) {\n console.error(chalk.red(`\\nGenerated output is out of date (${drift.length} file(s)):`));\n for (const d of drift) {\n const mark = d.status === 'added' ? '+' : d.status === 'removed' ? '-' : '~';\n console.error(\n ` ${mark} ${chalk.yellow(d.status.padEnd(8))} ${path.relative(process.cwd(), d.file)}`\n );\n }\n console.error(\n chalk.dim(\n '\\nRun `drzl generate` and commit the result. Nothing was written by this check.'\n )\n );\n process.exit(1);\n }\n console.log(chalk.green('Generated output is up to date.'));\n return;\n }\n\n if (cfg.generators.length) {\n maybeShowSponsorMessage({ reason: 'generate' });\n }\n } catch (e: any) {\n console.error(\n chalk.red('Generate failed (DRZL_GEN_001):'),\n e?.message ?? e,\n '\\nTip: check your drzl.config.ts and template path.'\n );\n process.exit(1);\n }\n });\n\nprogram\n .command('generate:orpc')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('-o, --outDir <dir>', 'output directory', 'src/api')\n .option('--template <name>', 'template name', 'standard')\n .option('--includeRelations', 'include relation endpoints')\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const analysis = await analyzer.analyze({\n includeRelations: !!opts.includeRelations,\n validateConstraints: true,\n });\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: opts.outDir,\n template: opts.template,\n includeRelations: !!opts.includeRelations,\n });\n console.log(chalk.green(`Generated:`), files.map((f) => chalk.cyan(f)).join(', '));\n maybeShowSponsorMessage({ reason: 'generate:orpc' });\n } catch (e: any) {\n console.error(chalk.red('Generate orpc failed:'), e?.message ?? e);\n process.exit(1);\n }\n });\n\nprogram\n .command('generate:trpc')\n .argument('<schema>', 'path to drizzle schema (TS)')\n .option('-o, --outDir <dir>', 'output directory', 'src/api')\n .option('--template <name>', 'standard | service', 'standard')\n .option('--includeRelations', 'include relation endpoints')\n .option('--servicesDir <dir>', 'where the service generator writes', 'src/services')\n .action(async (schema: string, opts: any) => {\n try {\n const analyzer = new SchemaAnalyzer(schema);\n const analysis = await analyzer.analyze({\n includeRelations: !!opts.includeRelations,\n validateConstraints: true,\n });\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: opts.outDir,\n template: opts.template,\n includeRelations: !!opts.includeRelations,\n // Only consulted by `--template service`, and passed unconditionally so this command\n // cannot become the branch that forgets it.\n servicesDir: opts.servicesDir,\n });\n console.log(chalk.green(`Generated:`), files.map((f: string) => chalk.cyan(f)).join(', '));\n maybeShowSponsorMessage({ reason: 'generate:trpc' });\n } catch (e: any) {\n reportGeneratorFailure('trpc', e);\n process.exit(1);\n }\n });\n\nprogram\n .command('watch')\n .description('Watch schema and regenerate on changes')\n .option('-c, --config <path>', 'path to drzl.config')\n .option('--pipeline <name>', 'all | analyze | generate-orpc | generate-trpc', 'all')\n .option('--debounce <ms>', 'debounce ms', '200')\n .option('--json', 'emit JSON logs', false)\n .option('--poll', 'force polling (helps WSL/Docker/remote FS)', false)\n .action(async (opts: any) => {\n let cfg = await loadConfig(opts.config);\n if (!cfg) {\n console.error(chalk.red('No config found. Create drzl.config.ts or pass --config.'));\n process.exit(2);\n return;\n }\n\n const abs = (p: string) => path.resolve(process.cwd(), p);\n const isInside = (child: string, parent: string) => {\n const rel = path.relative(parent, child);\n return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);\n };\n\n const ignoredOutDirs = new Set<string>(computeGeneratorOutputDirs(cfg).map(abs));\n const currentTargets = new Set<string>(computeWatchTargets(cfg).map(abs));\n\n const syncWatcherTargets = (watcher: import('chokidar').FSWatcher, next: Set<string>) => {\n const add: string[] = [];\n const del: string[] = [];\n for (const p of next) if (!currentTargets.has(p)) add.push(p);\n for (const p of currentTargets) if (!next.has(p)) del.push(p);\n if (add.length) watcher.add(add);\n if (del.length) watcher.unwatch(del);\n currentTargets.clear();\n next.forEach((p) => currentTargets.add(p));\n };\n\n const rebuildIgnoreDirsFrom = (cfgNow: DrzlConfig) => {\n ignoredOutDirs.clear();\n for (const d of computeGeneratorOutputDirs(cfgNow)) ignoredOutDirs.add(abs(d));\n };\n\n // Watch targets are directories now, because chokidar v4 dropped glob support. The\n // extensions the old `**/*.{ts,tsx,js}` glob selected therefore have to be filtered here\n // instead, or every unrelated file in the schema's directory would trigger a rebuild.\n const WATCHED_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs', '.cjs']);\n\n const ignoredFn = (p: string, stats?: { isDirectory(): boolean }) => {\n const full = abs(p);\n for (const dir of ignoredOutDirs) {\n if (full === dir || isInside(full, dir)) return true;\n }\n // A directory is never ignored: chokidar has to descend into it to reach the files.\n if (stats?.isDirectory()) return false;\n const ext = path.extname(full);\n // Without stats chokidar is asking about a path it has not resolved yet. An extensionless\n // one is almost certainly a directory, so let it through and decide once it is known.\n if (!ext) return false;\n return !WATCHED_EXTENSIONS.has(ext);\n };\n\n const watcher = chokidar.watch(Array.from(currentTargets), {\n ignoreInitial: true,\n awaitWriteFinish: { stabilityThreshold: 400, pollInterval: 50 },\n usePolling: !!opts.poll,\n ignored: ignoredFn,\n });\n\n const logTrigger = (type: 'add' | 'change' | 'unlink', file: string) => {\n if (opts.json) console.log(JSON.stringify({ event: 'trigger', type, file }));\n };\n\n watcher\n .on('add', (p) => {\n logTrigger('add', p);\n trigger(p);\n })\n .on('change', (p) => {\n logTrigger('change', p);\n trigger(p);\n })\n .on('unlink', (p) => {\n logTrigger('unlink', p);\n trigger(p);\n });\n\n let lastFiles: string[] = [];\n\n const run = async () => {\n try {\n const reloaded = await loadConfig(opts.config);\n if (!reloaded) throw new Error('Config disappeared during watch.');\n cfg = reloaded;\n\n rebuildIgnoreDirsFrom(cfg);\n const nextTargets = new Set<string>(computeWatchTargets(cfg).map(abs));\n syncWatcherTargets(watcher, nextTargets);\n\n if (!opts.json) console.clear();\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'watch_config_applied',\n targets: Array.from(currentTargets),\n ignored: Array.from(ignoredOutDirs),\n })\n );\n }\n\n const analyzer = new SchemaAnalyzer(cfg.schema);\n const analysis = await analyzer.analyze({\n includeRelations: cfg.analyzer.includeRelations,\n validateConstraints: cfg.analyzer.validateConstraints,\n includeHeuristicRelations: cfg.analyzer.includeHeuristicRelations,\n });\n analysis.tables = filterTables(analysis.tables, cfg);\n if (!opts.json) reportWideColumns(analysis.issues);\n\n if (opts.pipeline === 'analyze') {\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'analyze_complete',\n issues: analysis.issues,\n tables: analysis.tables.length,\n })\n );\n } else {\n console.log(chalk.green('Analyze complete.'));\n }\n return;\n }\n\n const newFiles: string[] = [];\n\n // Must match the `g.path ?? 'src/services'` the service branch below uses, or a router\n // template that imports services spells a path nothing ever wrote. `generate` has always\n // computed this; `watch` did not, so a rebuild silently emitted the default.\n const servicesDir =\n cfg.generators.find((x: { kind: string }) => x.kind === 'service')?.path ??\n 'src/services';\n\n const PIPELINE_KINDS: Record<string, string> = {\n 'generate-orpc': 'orpc',\n 'generate-trpc': 'trpc',\n };\n\n for (const g of cfg.generators) {\n if (opts.pipeline !== 'all' && PIPELINE_KINDS[opts.pipeline] !== g.kind) {\n continue;\n }\n\n if (g.kind === 'orpc') {\n const gen = new ORPCGenerator(analysis);\n const { files } = await gen.generate({\n outputDir: cfg.outDir,\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n templateOptions: g.templateOptions,\n importExtension: g.importExtension,\n validation: g.validation,\n databaseInjection: g.databaseInjection,\n servicesDir,\n });\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (${g.kind}):`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } else if (g.kind === 'trpc') {\n try {\n const { TRPCGenerator } = await loadGenerator(\n '@drzl/generator-trpc',\n () => import('@drzl/generator-trpc')\n );\n const gen = new TRPCGenerator(analysis);\n // The same builder `generate` uses, so the two dispatch loops cannot disagree\n // about what this generator is given.\n const { files } = await gen.generate(trpcOptions(g, cfg, servicesDir));\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (trpc): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'service') {\n try {\n const { ServiceGenerator } = await loadGenerator(\n '@drzl/generator-service',\n () => import('@drzl/generator-service')\n );\n const gen = new ServiceGenerator(analysis);\n const target = g.path ?? 'src/services';\n const files = await gen.generate({\n outDir: target,\n outputHeader: g.outputHeader,\n format: g.format,\n dataAccess: g.dataAccess,\n dbImportPath: g.dbImportPath,\n schemaImportPath: g.schemaImportPath,\n importExtension: g.importExtension,\n databaseInjection: g.databaseInjection,\n });\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (service): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'zod') {\n try {\n const { ZodGenerator } = await loadGenerator(\n '@drzl/generator-zod',\n () => import('@drzl/generator-zod')\n );\n const gen = new ZodGenerator(analysis);\n const target = g.path ?? 'src/validators/zod';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (zod): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'valibot') {\n try {\n const { ValibotGenerator } = await loadGenerator(\n '@drzl/generator-valibot',\n () => import('@drzl/generator-valibot')\n );\n const gen = new ValibotGenerator(analysis);\n const target = g.path ?? 'src/validators/valibot';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (valibot): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'arktype') {\n try {\n const { ArkTypeGenerator } = await loadGenerator(\n '@drzl/generator-arktype',\n () => import('@drzl/generator-arktype')\n );\n const gen = new ArkTypeGenerator(analysis);\n const target = g.path ?? 'src/validators/arktype';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: false }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (arktype): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'typebox') {\n try {\n const { TypeBoxGenerator } = await loadGenerator(\n '@drzl/generator-typebox',\n () => import('@drzl/generator-typebox')\n );\n const gen = new TypeBoxGenerator(analysis);\n const target = g.path ?? 'src/validators/typebox';\n // The same builder `generate` uses. Assembled by hand here until now, and every\n // option added since the builder existed was therefore absent from a watch rebuild:\n // `coerceDates`, `applyDefaults`, `typedJson`, `typedColumns` and `duplicateFinder`\n // were all dropped, so the first save after starting `drzl watch` silently replaced\n // correct output with output generated from defaults.\n const files = await gen.generate(\n validationOptions(g, cfg, target, { schemaTypes: true }) as never\n );\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (typebox): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n } else if (g.kind === 'json-schema') {\n try {\n const { JsonSchemaGenerator } = await loadGenerator(\n '@drzl/generator-json-schema',\n () => import('@drzl/generator-json-schema')\n );\n const gen = new JsonSchemaGenerator(analysis);\n const target = g.path ?? 'src/validators/json-schema';\n // The same builder `generate` uses, so the two dispatch loops cannot disagree about\n // what this generator is given.\n const files = await gen.generate(jsonSchemaOptions(g, cfg, target) as never);\n opts.json\n ? console.log(JSON.stringify({ event: 'generate_complete', kind: g.kind, files }))\n : console.log(\n chalk.green(`Generated (json-schema): ${files.length} files`),\n files.map((f: string) => chalk.cyan(f)).join(', ')\n );\n newFiles.push(...files);\n } catch (e: any) {\n reportGeneratorFailure(g.kind, e);\n return;\n }\n }\n }\n\n const added = newFiles.filter((f) => !lastFiles.includes(f));\n const removed = lastFiles.filter((f) => !newFiles.includes(f));\n opts.json\n ? console.log(JSON.stringify({ event: 'diff', added, removed }))\n : (() => {\n if (added.length) console.log(chalk.blue(`Added: ${added.join(', ')}`));\n if (removed.length) console.log(chalk.yellow(`Removed: ${removed.join(', ')}`));\n })();\n if (newFiles.length && !opts.json) {\n const reason =\n opts.pipeline && opts.pipeline !== 'all' ? `watch:${opts.pipeline}` : 'watch';\n maybeShowSponsorMessage({ reason });\n }\n lastFiles = newFiles;\n } catch (e: any) {\n opts.json\n ? console.log(JSON.stringify({ event: 'error', message: String(e?.message ?? e) }))\n : console.error(chalk.red('Watch pipeline failed:'), e?.message ?? e);\n }\n };\n\n const debounced = Number(opts.debounce) || 200;\n let timer: NodeJS.Timeout | null = null;\n const trigger = (file?: string) => {\n if (file) {\n const full = abs(file);\n for (const dir of ignoredOutDirs) {\n if (full === dir || isInside(full, dir)) return;\n }\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(run, debounced);\n };\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n event: 'watching',\n targets: Array.from(currentTargets),\n ignored: Array.from(ignoredOutDirs),\n })\n );\n } else {\n console.log(\n chalk.gray(\n 'Watching:\\n ' +\n Array.from(currentTargets)\n .map((p) => path.relative(process.cwd(), p))\n .join('\\n ')\n )\n );\n }\n\n watcher\n .on('add', (p) => trigger(p))\n .on('change', (p) => trigger(p))\n .on('unlink', (p) => trigger(p))\n .on('error', (err) => console.error(chalk.red('Watcher error:'), err));\n\n await run();\n });\n\nprogram\n .command('init')\n .description('Scaffold a drzl.config.ts')\n .option('-y, --yes', 'accept defaults')\n .action(async (_opts: any) => {\n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n const target = path.resolve(process.cwd(), 'drzl.config.ts');\n // One router generator, not both: they default to the same `outDir` and would each write an\n // `index.ts` there, so a scaffold naming both would emit a config whose second generator\n // silently overwrote the first. Swapping the kind is a one-word edit; running both needs a\n // `path` on one of them, which is what the comment says.\n const template = `export default {\n schema: 'src/db/schema.ts',\n outDir: 'src/api',\n analyzer: { includeRelations: true, validateConstraints: true },\n generators: [\n // For tRPC instead: { kind: 'trpc', template: 'standard', includeRelations: true }\n // To run both, give one of them its own \\`path\\`; they share \\`outDir\\` otherwise.\n { kind: 'orpc', template: 'standard', includeRelations: true }\n ]\n} as const\\n`;\n try {\n await fs.writeFile(target, template, { flag: 'wx' });\n console.log(chalk.green(`Created ${target}`));\n } catch (e: any) {\n console.error(chalk.red('Init failed:'), e?.message ?? e);\n process.exit(1);\n }\n });\n\n/**\n * Tell the user which columns got a validator that accepts anything.\n *\n * This is the user-facing half of a check `verify-packed.sh` runs on this repository. Two real\n * bugs took exactly this shape, `.array()` and `pgEnum` columns coming back untyped on\n * drizzle-orm 0.4x, and the only way anyone noticed was reading the generated file. A user whose\n * schema uses a type nobody here has modelled gets the same silence, and no gate of ours helps\n * them.\n *\n * Printed once with a count rather than a line per column, so a schema with fifty custom types\n * stays readable.\n */\nfunction reportWideColumns(issues: Array<{ code?: string; message?: string; hint?: string }>) {\n const wide = issues.filter((i) => i.code === 'DRZL_ANL_UNKNOWN_COLUMN');\n if (!wide.length) return;\n console.warn(\n chalk.yellow(`\\n${wide.length} column${wide.length === 1 ? '' : 's'} could not be typed:`)\n );\n for (const i of wide.slice(0, 10)) console.warn(chalk.gray(` - ${i.message}`));\n if (wide.length > 10) console.warn(chalk.gray(` ... and ${wide.length - 10} more`));\n // One hint for the set, since they are almost always the same two.\n const hints = [...new Set(wide.map((i) => i.hint).filter(Boolean))];\n for (const h of hints) console.warn(chalk.gray(` ${h}`));\n // Untypeable columns are the only thing this line can see. A CHECK constraint the generators\n // decline produces no output at all and so cannot be counted here without parsing every one of\n // them on the generate path, which is what `doctor` is for.\n console.warn(chalk.gray(' Run `drzl doctor` for the full report.'));\n}\n\nprogram.parseAsync(process.argv);\n","/**\n * The options every validation generator receives, built in one place.\n *\n * Each of the four branches used to assemble this by hand, and three documented options were\n * found silently dead as a result: `typedJson` never reached typebox, and `coerceDates` and\n * `applyDefaults` never reached anything but zod. The config parsed them, the CLI dropped them,\n * and the feature simply did nothing while nothing said so. Building it once removes the class\n * rather than fixing each instance.\n *\n * What stays per-generator is a real capability rather than an oversight, which is why it is\n * named as one.\n */\n\n/**\n * A generator entry from the config, loosely typed because the config schema owns its shape.\n *\n * Exported so a builder that wraps this one names the same keys rather than restating them: every\n * key listed in two places is a key the two can drift on, which is the failure this file exists to\n * remove.\n */\nexport type ValidationGeneratorConfig = {\n outputHeader?: unknown;\n format?: unknown;\n schemaSuffix?: unknown;\n fileSuffix?: unknown;\n importExtension?: unknown;\n affix?: unknown;\n coerceDates?: unknown;\n applyDefaults?: unknown;\n typedJson?: unknown;\n typedColumns?: unknown;\n duplicateFinder?: unknown;\n nestedSchemas?: unknown;\n nestedDepth?: unknown;\n};\n\nexport interface GeneratorCapabilities {\n /**\n * Whether the generator can reference a type from the schema module.\n *\n * `typedJson` and `typedColumns` both work by importing the table back and reading\n * `typeof table.$inferSelect['col']`, so a generator that cannot embed a TypeScript type in its\n * output cannot use either. ArkType is the case: it emits one string per field, and a type\n * reference has nowhere to live inside a string DSL.\n */\n schemaTypes?: boolean;\n}\n\nexport function validationOptions(\n g: ValidationGeneratorConfig,\n cfg: { schema?: unknown },\n outDir: string,\n caps: GeneratorCapabilities = {}\n): Record<string, unknown> {\n return {\n outDir,\n outputHeader: g.outputHeader,\n format: g.format,\n schemaSuffix: g.schemaSuffix,\n fileSuffix: g.fileSuffix,\n importExtension: g.importExtension,\n affix: g.affix,\n coerceDates: g.coerceDates,\n applyDefaults: g.applyDefaults,\n duplicateFinder: g.duplicateFinder,\n nestedSchemas: g.nestedSchemas,\n nestedDepth: g.nestedDepth,\n // Only where the generator can act on them, so an unsupported option is absent rather than\n // present and ignored.\n ...(caps.schemaTypes\n ? {\n // Needed by both: the reference is resolved relative to the emitted file.\n schemaPath: cfg.schema,\n typedJson: g.typedJson,\n typedColumns: g.typedColumns,\n }\n : {}),\n };\n}\n","/**\n * The options `@drzl/generator-json-schema` receives, built in one place.\n *\n * `generate` and `watch` each dispatch over `cfg.generators` in their own loop, and the json-schema\n * branch was assembled by hand in both. That arrangement has already dropped options silently more\n * than once here: five validation options never reached a watch rebuild, and `watch` had no\n * json-schema branch at all for a while, so that directory went stale from the first save onward.\n * None of it is visible in the wiring, because the option parses, the generator defaults it, and\n * the feature simply does nothing.\n *\n * One builder makes the two call sites the same object by construction rather than by review, and\n * `packages/cli/test/openapi-branch-parity.e2e.spec.ts` runs both commands and compares the bytes.\n */\nimport { validationOptions, type ValidationGeneratorConfig } from './validation-options.js';\n\n/** A generator entry from the config, loosely typed because the config schema owns its shape. */\ntype GeneratorConfig = ValidationGeneratorConfig & {\n path?: string;\n target?: unknown;\n components?: unknown;\n document?: unknown;\n includeRelations?: unknown;\n};\n\nexport function jsonSchemaOptions(\n g: GeneratorConfig,\n cfg: { schema?: unknown },\n outDir: string\n): Record<string, unknown> {\n return {\n // JSON Schema is data, so nothing it emits references a type from the schema module.\n ...validationOptions(g, cfg, outDir, { schemaTypes: false }),\n target: g.target,\n components: g.components,\n document: g.document,\n // Read only while emitting a document, where it adds `/users/{id}/posts`. The per-table\n // schemas are flat whatever it says.\n includeRelations: g.includeRelations,\n };\n}\n","import type { AffixOptions } from '@drzl/validation-core';\nimport {\n AFFIX_PROBE_TABLE,\n DEFAULT_IMPORT_EXTENSION,\n IMPORT_EXTENSIONS,\n NAME_MODES,\n resolveAffix,\n schemaName,\n validateAffix,\n} from '@drzl/validation-core';\nimport * as fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport { z } from 'zod';\n\nexport const NamingSchema = z\n .object({\n routerSuffix: z.string().default('Router'),\n procedureCase: z.enum(['camel', 'kebab', 'snake']).default('camel'),\n })\n .partial();\n\n/** One affix for every mode, or a per-mode map. Keys match drzl's internal mode names. */\nconst AffixValueSchema = z.union(\n [\n z.string(),\n z\n .object({\n insert: z.string().optional(),\n update: z.string().optional(),\n select: z.string().optional(),\n })\n .strict(),\n ],\n {\n error:\n 'Expected a string to use for every mode, or an object with any of the keys \"insert\", ' +\n '\"update\" and \"select\". Those keys are lowercase, matching the mode names drzl uses ' +\n 'everywhere else.',\n }\n);\n\nconst AffixPartSchema = z\n .object({\n prefix: AffixValueSchema.optional(),\n suffix: AffixValueSchema.optional(),\n })\n .strict();\n\nexport const AffixSchema = z\n .object({\n /**\n * `preserve` (default) keeps today's output: the Drizzle export name goes into the\n * identifier verbatim, so `export const users` yields `InsertusersSchema`. `pascal`\n * upper-camels it first, yielding `InsertUsersSchema`.\n */\n tableCase: z.enum(['preserve', 'pascal']).optional(),\n schema: AffixPartSchema.optional(),\n type: AffixPartSchema.optional(),\n })\n .strict();\n\n/**\n * How every relative specifier drzl invents spells its extension.\n *\n * The generated files land in the consumer's own source tree, so the consumer's\n * `moduleResolution` decides which forms resolve. `js` is the only one that resolves under\n * all of `bundler`, `node10`, `node16` and `nodenext` with no compiler flag, so it is the\n * default. See the `ImportExtension` docs in `@drzl/validation-core` for the measured grid.\n */\nexport const ImportExtensionSchema = z.enum(IMPORT_EXTENSIONS);\n\nexport const GeneratorSchema = z.object({\n kind: z.enum(['orpc', 'trpc', 'service', 'zod', 'valibot', 'arktype', 'typebox', 'json-schema']),\n /**\n * Overrides the top-level `importExtension` for this generator alone, for a project whose\n * generated directories are compiled by different tsconfigs.\n */\n importExtension: ImportExtensionSchema.optional(),\n template: z.string().optional(),\n includeRelations: z.boolean().optional(),\n /**\n * Type `json` and `jsonb` columns from the schema rather than leaving them wide.\n *\n * `.$type<T>()` is a compile-time cast, so no runtime-derived validator can see it and\n * `drizzle-orm/zod` types every json column as its generic `Json`. A generator can reference\n * `typeof <table>.$inferSelect['<column>']` instead, which is the declared type resolved by\n * TypeScript itself, so generics, unions and imported interfaces all work.\n *\n * Off by default because it makes the generated file import your schema module, as a\n * type-only import that disappears at build time.\n */\n // What a date column accepts. Documented on the zod generator and, until now, accepted by the\n // config parser and then dropped on the floor: the generators default it to 'input' themselves,\n // so setting it here changed nothing.\n coerceDates: z.enum(['input', 'all', 'none']).optional(),\n typedJson: z.boolean().optional(),\n // The wider form: every column's static type comes from Drizzle, not just the untyped ones.\n typedColumns: z.boolean().optional(),\n // Reproduce literal column defaults in the insert schema, so parsing fills them in.\n applyDefaults: z.boolean().optional(),\n /**\n * Emit `findDuplicate<Table>` beside the schemas: the rows in a batch that collide with an\n * earlier row on a unique constraint.\n *\n * Uniqueness is the one constraint a per-row validator structurally cannot see, since it is a\n * fact about the table rather than the row. This checks the half that needs no database.\n */\n duplicateFinder: z.boolean().optional(),\n /**\n * Emit `NestedInsert<Table>` and `NestedSelect<Table>` beside the flat schemas: the table plus\n * one key per relation, so `{ ...user, posts: [...] }` can be validated whole.\n *\n * Nothing in the Drizzle validator ecosystem describes that payload, and `db.insert` drops the\n * relation key silently rather than refusing it, so the children are never written and nothing\n * says so.\n */\n nestedSchemas: z.boolean().optional(),\n /**\n * How many levels of children a nested schema describes. Defaults to 1, capped at 3.\n *\n * Nesting is expanded inline rather than by reference, so this multiplies the emitted size, and\n * it is also what terminates a cycle: `users -> posts -> users` stops here.\n */\n nestedDepth: z.number().int().optional(),\n naming: NamingSchema.optional(),\n outputHeader: z\n .object({\n enabled: z.boolean().default(true).optional(),\n text: z.string().optional(),\n })\n .optional(),\n format: z\n .object({\n enabled: z.boolean().default(true).optional(),\n engine: z.enum(['auto', 'prettier', 'biome']).default('auto').optional(),\n configPath: z.string().optional(),\n })\n .optional(),\n /**\n * Which spelling of JSON Schema the `json-schema` generator emits.\n *\n * OpenAPI 3.0 is not an older superset of the 2020-12 draft, it is a different dialect: a\n * nullable type is `nullable: true` rather than a type array, and an exclusive bound is a\n * boolean flag beside the bound rather than its own keyword. An unknown keyword is not an error\n * in JSON Schema, it is ignored, so emitting the wrong dialect produces a document that\n * validates and then accepts the values the constraints exist to reject.\n */\n target: z.enum(['draft-2020-12', 'openapi-3.1', 'openapi-3.0']).optional(),\n /** Also emit `components.ts` for the `json-schema` generator, ready for an OpenAPI document. */\n components: z.boolean().optional(),\n /**\n * Also emit the whole OpenAPI document for the `json-schema` generator: paths, verbs, request and\n * response bodies per table, with `components.schemas` embedded so the file stands alone.\n *\n * `true` is the short form. The object form carries the three things a Drizzle schema genuinely\n * cannot say: what the API is called, where it is served, and which status code that particular\n * server answers a request that fails its schema with.\n */\n document: z\n .union([\n z.boolean(),\n z\n .object({\n enabled: z.boolean().optional(),\n /** `ts` (default) writes a module, `json` the file OpenAPI tooling reads directly. */\n format: z.enum(['ts', 'json', 'both']).optional(),\n info: z\n .object({\n title: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n })\n .strict()\n .optional(),\n /**\n * Omitted by default, which the specification reads as a single server at `/`: the\n * document describes whatever is serving it. A placeholder host would be a fabrication\n * that tooling then follows.\n */\n servers: z\n .array(z.object({ url: z.string(), description: z.string().optional() }).strict())\n .optional(),\n /** 400 by default. 422 is the other defensible reading; exactly one is emitted. */\n validationStatus: z.union([z.literal(400), z.literal(422)]).optional(),\n })\n .strict(),\n ])\n .optional(),\n // service generator specific options\n path: z.string().optional(),\n dataAccess: z.enum(['stub', 'drizzle']).default('stub').optional(),\n dbImportPath: z.string().optional(),\n schemaImportPath: z.string().optional(),\n // zod/valibot/arktype generator specific options\n schemaSuffix: z.string().optional(),\n fileSuffix: z.string().optional(),\n /**\n * Prefixes, suffixes and table casing for generated identifiers (zod/valibot/arktype).\n * Omitting it reproduces the output of every previous release exactly.\n */\n affix: AffixSchema.optional(),\n /**\n * How the router generators reach a database handle: through the request context, rather than\n * through a module-level import in the service layer.\n *\n * Documented on the oRPC generator since it was added and, until now, absent from this schema\n * entirely. `GeneratorSchema` is not strict, so zod stripped the key without a word and the\n * option did nothing at all when set from a config file. It was only ever reachable by calling\n * the generator's API directly.\n */\n databaseInjection: z\n .object({\n enabled: z.boolean().optional(),\n /** The type annotation for the injected handle, e.g. `DrizzleD1Database`. */\n databaseType: z.string().optional(),\n databaseTypeImport: z.object({ name: z.string(), from: z.string() }).optional(),\n })\n .optional(),\n // router validation sharing (orpc, trpc)\n validation: z\n .object({\n useShared: z.boolean().default(false).optional(),\n library: z.enum(['zod', 'valibot', 'arktype']).default('zod').optional(),\n importPath: z.string().optional(),\n schemaSuffix: z.string().optional(),\n /**\n * How the validation generator named its exports. Usually left unset: the CLI copies\n * it from the sibling generator whose `kind` matches `library`.\n */\n affix: AffixSchema.optional(),\n })\n .optional(),\n // template options\n templateOptions: z.record(z.string(), z.any()).optional(),\n});\n\nexport const AnalyzerSchema = z.object({\n includeRelations: z.boolean().default(true),\n validateConstraints: z.boolean().default(true),\n includeHeuristicRelations: z.boolean().default(false),\n});\n\nexport const ConfigSchema = z\n .object({\n schema: z.string(),\n outDir: z.string().default('src/api'),\n /**\n * Which tables to generate for, matched against the database table name.\n *\n * There was no way to say this, and every generator loops over every table it finds, so\n * DRZL emitted unauthenticated CRUD over whatever shared the schema file. That is noise for\n * a migrations table and a genuine leak for an auth one: Better Auth puts `user`, `session`,\n * `account` and `verification` alongside your own tables, and `account` holds\n * `accessToken`, `refreshToken`, `idToken` and `password`.\n *\n * Deliberately name-based and explicit rather than detecting any particular library. Auth\n * table names are all renameable, so a built-in list would miss renamed tables and, worse,\n * silently skip an ordinary table that happened to be called `user`, which is usually the\n * application's main entity.\n *\n * `exclude` wins over `include`. Patterns support `*`, matching within a name.\n */\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n /**\n * How every relative specifier drzl invents spells its extension, for every generator.\n * A generator may override it. Defaults to `js`, which is the only form that resolves\n * under every `moduleResolution` without a compiler flag.\n */\n importExtension: ImportExtensionSchema.default(DEFAULT_IMPORT_EXTENSION),\n analyzer: AnalyzerSchema.default({\n includeRelations: true,\n validateConstraints: true,\n includeHeuristicRelations: false,\n }),\n generators: z\n .array(GeneratorSchema)\n .min(1)\n .default([{ kind: 'orpc' } as any]),\n })\n // Reject an affix before anything is written, rather than emitting a file that cannot\n // compile. Only `affix` is inspected; the legacy flat `schemaSuffix` is left alone so\n // configs that parse today keep parsing.\n .superRefine((cfg, ctx) => {\n cfg.generators.forEach((g, i) => {\n const report = (base: (string | number)[], affix?: AffixOptions, schemaSuffix?: string) => {\n for (const issue of validateAffix(affix, schemaSuffix)) {\n ctx.addIssue({\n code: 'custom',\n path: ['generators', i, ...base, ...issue.path],\n message: issue.message,\n });\n }\n };\n report(['affix'], g.affix as AffixOptions | undefined, g.schemaSuffix);\n report(\n ['validation', 'affix'],\n g.validation?.affix as AffixOptions | undefined,\n g.validation?.schemaSuffix\n );\n });\n });\n\n// ✨ Separate input vs output types\nexport type DrzlConfigInput = z.input<typeof ConfigSchema>;\nexport type DrzlConfig = z.output<typeof ConfigSchema>;\n\nexport function defineConfig<T extends DrzlConfigInput>(cfg: T): T {\n return cfg;\n}\n\ntype GeneratorConfig = DrzlConfig['generators'][number];\n\n/** The generators that emit an RPC router, and so share `outDir` and `validation`. */\nconst ROUTER_KINDS = new Set(['orpc', 'trpc']);\n\n/**\n * Where the tRPC generator writes.\n *\n * `outDir` by default, exactly like oRPC, so a config that names one router generator puts its\n * output where the top-level setting says. `path` is the escape hatch, and a config that runs\n * *both* router generators needs it: they would otherwise write two different `index.ts` files to\n * the same directory and the second would win.\n *\n * Exported because `computeGeneratorOutputDirs` has to agree with the dispatch in cli.ts about\n * this, and the watcher ignoring the wrong directory is an infinite regeneration loop.\n */\nexport function trpcOutDir(g: { path?: string }, cfg: { outDir: string }): string {\n return g.path ?? cfg.outDir;\n}\n\nfunction sharedSchemaNames(opts: { affix?: AffixOptions; schemaSuffix?: string }): string[] {\n const resolved = resolveAffix(opts);\n return NAME_MODES.map((mode) => schemaName(mode, AFFIX_PROBE_TABLE, resolved));\n}\n\n/**\n * Fill in cross-generator defaults and refuse configs whose generators would disagree.\n *\n * An oRPC router that imports shared schemas has to spell the exact names the validation\n * generator exported. Both sides used to be configured independently, so they could silently\n * drift into a router that does not compile. When an oRPC generator uses shared validation\n * and exactly one sibling generator produces that library, its `affix` is copied across.\n *\n * Deliberately conservative about the pre-existing flat `schemaSuffix`: a disagreement there\n * is only reported, never repaired, because repairing it would change the bytes an existing\n * config emits.\n *\n * `importExtension` is pushed down here too. A consumer compiles the whole generated tree\n * with one tsconfig, so the setting that has to hold is the same for every generator, and\n * every call site downstream can then read it off the generator without knowing about the\n * top-level default.\n */\nexport function resolveConfig(cfg: DrzlConfig): { config: DrzlConfig; warnings: string[] } {\n const warnings: string[] = [];\n const generators: GeneratorConfig[] = cfg.generators.map((g) => ({\n ...g,\n importExtension: g.importExtension ?? cfg.importExtension,\n }));\n\n for (const g of generators) {\n // Both router generators import the validation generators' exports by name, so both have to\n // spell them the way the sibling generator wrote them.\n if (!ROUTER_KINDS.has(g.kind)) continue;\n\n /**\n * `databaseInjection` describes a contract between two generators, not a setting of one.\n *\n * A router in injection mode emits `Service.getById(ctx.db, id)`, and only a service\n * generated in the same mode has a `db` parameter to receive it. Declared once on the router\n * and pushed onto the service generator here, exactly as `validation.affix` is pulled the\n * other way, because the alternative is writing the same block twice and a project that\n * compiles in halves and not as a whole.\n *\n * `@drzl/generator-service` honours the flag only while emitting real Drizzle queries: its\n * stub bodies take no database whatever they are told. That combination cannot be repaired\n * from here without changing what an existing config emits, so it is reported instead.\n */\n if (g.databaseInjection?.enabled) {\n for (const s of generators.filter((x) => x.kind === 'service')) {\n if (!s.databaseInjection) {\n s.databaseInjection = g.databaseInjection;\n } else if (!s.databaseInjection.enabled) {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator sets databaseInjection.enabled while the ` +\n `\"service\" generator sets it to false. The router will call ` +\n `Service.method(ctx.db, ...) against services that take no database parameter, so ` +\n `the generated project will not compile. Set both, or neither.`\n );\n }\n if ((s.dataAccess ?? 'stub') === 'stub') {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator sets databaseInjection.enabled, so its ` +\n `handlers call Service.method(ctx.db, ...). The \"service\" generator emits stub ` +\n `bodies, which take no database parameter whatever this option says, so those ` +\n `calls will not compile. Set dataAccess: 'drizzle' on the \"service\" generator, or ` +\n `drop databaseInjection.`\n );\n }\n }\n }\n\n const v = g.validation;\n if (!v?.useShared) continue;\n\n const library = v.library ?? 'zod';\n const siblings = generators.filter((s) => s.kind === library);\n // Zero siblings means the user points at a barrel drzl does not generate; more than one\n // means there is no single source of truth. Either way, leave the config alone.\n if (siblings.length !== 1) continue;\n const sibling = siblings[0];\n\n const theirs = sharedSchemaNames({\n affix: sibling.affix as AffixOptions | undefined,\n schemaSuffix: sibling.schemaSuffix,\n });\n\n if (!v.affix) {\n if (sibling.affix) {\n // Bake the sibling's fully resolved naming in, so its own schemaSuffix fallback\n // travels with it and cannot be re-interpreted on the oRPC side.\n g.validation = {\n ...v,\n affix: resolveAffix({\n affix: sibling.affix as AffixOptions,\n schemaSuffix: sibling.schemaSuffix,\n }),\n };\n continue;\n }\n const mine = sharedSchemaNames({ schemaSuffix: v.schemaSuffix });\n if (mine.join(',') !== theirs.join(',')) {\n warnings.push(\n `drzl config: the \"${g.kind}\" generator's validation.schemaSuffix ` +\n `(${JSON.stringify(v.schemaSuffix ?? 'Schema')}) does not match the \"${library}\" ` +\n `generator's schemaSuffix (${JSON.stringify(sibling.schemaSuffix ?? 'Schema')}). ` +\n `The router will import ${mine.join(', ')} but the \"${library}\" generator exports ` +\n `${theirs.join(', ')}, so the generated router will not compile. Set both to the ` +\n `same value, or move to \"affix\", which is inherited automatically.`\n );\n }\n continue;\n }\n\n const mine = sharedSchemaNames({\n affix: v.affix as AffixOptions,\n schemaSuffix: v.schemaSuffix,\n });\n if (mine.join(',') !== theirs.join(',')) {\n throw new Error(\n `drzl config: the \"${g.kind}\" generator imports shared ${library} schemas, but its ` +\n `validation.affix disagrees with the \"${library}\" generator's own naming. The router ` +\n `would import ${mine.join(', ')} while the \"${library}\" generator exports ` +\n `${theirs.join(', ')}. Make them match, or drop validation.affix and let it be ` +\n `inherited from the \"${library}\" generator.`\n );\n }\n }\n\n return { config: { ...cfg, generators }, warnings };\n}\n\n/**\n * Parse, then resolve cross-generator defaults. Both `generate` and `watch` go through\n * loadConfig, so putting the resolution here is what keeps the two duplicated generator\n * dispatch blocks in cli.ts from needing the logic twice.\n */\nfunction finalize(raw: unknown): DrzlConfig {\n const { config, warnings } = resolveConfig(ConfigSchema.parse(raw));\n for (const w of warnings) console.warn(w);\n return config;\n}\n\nexport async function loadConfig(customPath?: string): Promise<DrzlConfig | null> {\n const fsp = await import('node:fs/promises');\n\n const candidates = customPath\n ? [customPath]\n : [\n 'drzl.config.ts',\n 'drzl.config.mjs',\n 'drzl.config.js',\n 'drzl.config.cjs',\n 'drzl.config.json',\n ];\n\n for (const c of candidates) {\n const p = path.resolve(process.cwd(), c);\n try {\n await fsp.access(p);\n } catch {\n continue;\n }\n\n const ext = path.extname(p).toLowerCase();\n\n // JSON: read directly\n if (ext === '.json') {\n const raw = JSON.parse(await fsp.readFile(p, 'utf8'));\n return finalize(raw);\n }\n\n // Everything else (TS/JS/MJS/CJS) -> Jiti with cache-busting\n const { createJiti } = await import('jiti');\n const stat = await fsp.stat(p);\n\n // Passing __filename is safe in CJS; fallback to cwd if not defined.\n const base =\n typeof __filename !== 'undefined' ? __filename : path.join(process.cwd(), 'index.js');\n\n const jiti = createJiti(base, {\n moduleCache: false, // re-evaluate each time\n fsCache: true, // keep transform cache\n cacheVersion: String(stat.mtimeMs), // bump on edit\n interopDefault: true,\n tryNative: false, // <-- prevent native import of .ts\n // debug: true,\n }) as any;\n\n const mod = await jiti.import(p);\n const raw = mod?.default ?? mod;\n return finalize(raw);\n }\n\n return null;\n}\n\n/** Absolute output dirs for all generators (to ignore in watcher). */\nexport function computeGeneratorOutputDirs(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const abs = (p: string) => path.resolve(cwd, p);\n const dirs = new Set<string>();\n dirs.add(abs(cfg.outDir)); // orpc\n for (const g of cfg.generators) {\n if (g.kind === 'trpc') dirs.add(abs(trpcOutDir(g, cfg)));\n if (g.kind === 'service') dirs.add(abs(g.path ?? 'src/services'));\n if (g.kind === 'zod') dirs.add(abs(g.path ?? 'src/validators/zod'));\n if (g.kind === 'valibot') dirs.add(abs(g.path ?? 'src/validators/valibot'));\n if (g.kind === 'arktype') dirs.add(abs(g.path ?? 'src/validators/arktype'));\n if (g.kind === 'typebox') dirs.add(abs(g.path ?? 'src/validators/typebox'));\n if (g.kind === 'json-schema') dirs.add(abs(g.path ?? 'src/validators/json-schema'));\n }\n return [...dirs];\n}\n\n/** Resolve custom template directories (local path or installed package). */\nexport function resolveTemplateDirsSync(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const results: string[] = [];\n const req = createRequire(\n typeof __filename !== 'undefined' ? __filename : path.join(process.cwd(), 'index.js')\n );\n\n for (const g of cfg.generators) {\n const t = g.template;\n // Built-in template names, not packages. `service` is the tRPC generator's, and without it\n // here every run would try to resolve a package called \"service\" and then watch a directory\n // of that name, neither of which exists.\n if (!t || t === 'standard' || t === 'minimal' || t === 'service') continue;\n\n // Try package resolution relative to cwd\n let pkgDir: string | null = null;\n try {\n const pkg = req.resolve(`${t}/package.json`, { paths: [cwd] as any });\n pkgDir = path.dirname(pkg);\n } catch {}\n\n if (pkgDir) {\n results.push(pkgDir);\n continue;\n }\n\n // Local path-like template\n if (/[./\\\\]/.test(t)) {\n const abs = path.resolve(cwd, t);\n if (fs.existsSync(abs)) results.push(abs);\n }\n }\n\n return Array.from(new Set(results));\n}\n\n/** Build watch targets (exclude output dirs; watcher will ignore those). */\n/**\n * Narrow an analysis's tables to the ones the config asked for.\n *\n * Matching is on the database table name, anchored, with `*` as the only metacharacter. Anchored\n * matters: `user` must not also drop `users`, and a substring match would. `exclude` is applied\n * after `include`, so the safer direction wins when both name the same table.\n */\nexport function filterTables<T extends { name: string }>(\n tables: T[],\n opts: { include?: string[]; exclude?: string[] }\n): T[] {\n const toRegExp = (pattern: string) =>\n new RegExp(\n '^' +\n pattern\n .split('*')\n .map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('.*') +\n '$'\n );\n\n const matches = (patterns: string[], name: string) =>\n patterns.some((p) => toRegExp(p).test(name));\n\n let out = tables;\n if (opts.include?.length) out = out.filter((t) => matches(opts.include!, t.name));\n if (opts.exclude?.length) out = out.filter((t) => !matches(opts.exclude!, t.name));\n return out;\n}\n\nexport function computeWatchTargets(cfg: DrzlConfig, cwd = process.cwd()): string[] {\n const abs = (p: string) => path.resolve(cwd, p);\n const schemaAbs = abs(cfg.schema);\n // The schema's directory, not a glob under it. Chokidar removed glob support in v4 and treats\n // `<dir>/**/*.{ts,tsx,js}` as a literal path, so it watched a directory named `**` that does\n // not exist: no event ever fired and `drzl watch` did its initial build and then sat inert.\n // A directory is watched recursively by chokidar itself, and the extension filtering that the\n // glob was doing now happens on the event instead.\n const targets = new Set<string>([\n path.dirname(schemaAbs),\n abs('drzl.config.ts'),\n abs('drzl.config.js'),\n abs('drzl.config.mjs'),\n abs('drzl.config.cjs'),\n ]);\n for (const t of resolveTemplateDirsSync(cfg, cwd)) targets.add(t);\n return [...targets];\n}\n","/**\n * The options `@drzl/generator-trpc` receives, built in one place.\n *\n * `generate` and `watch` each dispatch over `cfg.generators` in their own loop, and every branch\n * in both assembles its own options object by hand. Three documented options have already been\n * found dead that way: `typedJson` never reached typebox, `coerceDates` and `applyDefaults`\n * reached nothing but zod, and `servicesDir` is passed by `generate`'s oRPC branch and not by\n * `watch`'s, so a watch rebuild emits a service import pointing at the default directory whatever\n * the config says. None of those is visible in the wiring: the option parses, the generator\n * defaults it, and the feature simply does nothing.\n *\n * One builder means the two call sites are the same object by construction rather than by review.\n * It also gives the drift something to be asserted against, which is what\n * `packages/cli/test/trpc-branch-parity.spec.ts` does by running both commands and comparing the\n * bytes they wrote.\n */\nimport { trpcOutDir } from './config.js';\n\n/** A generator entry from the config, loosely typed because the config schema owns its shape. */\ntype GeneratorConfig = {\n path?: string;\n template?: unknown;\n includeRelations?: unknown;\n naming?: unknown;\n outputHeader?: unknown;\n format?: unknown;\n importExtension?: unknown;\n validation?: unknown;\n databaseInjection?: unknown;\n};\n\nexport function trpcOptions(\n g: GeneratorConfig,\n cfg: { outDir: string },\n servicesDir: string\n): Record<string, unknown> {\n return {\n outputDir: trpcOutDir(g, cfg),\n template: g.template,\n includeRelations: g.includeRelations,\n naming: g.naming,\n outputHeader: g.outputHeader,\n format: g.format,\n importExtension: g.importExtension,\n validation: g.validation,\n databaseInjection: g.databaseInjection,\n // Where the service generator is actually writing, so `template: 'service'` emits an import\n // of a module that exists. The generator defaults this to `src/services`, which is right only\n // by coincidence for a config that puts them elsewhere.\n servicesDir,\n };\n}\n","/**\n * The report behind `drzl doctor`: what DRZL will not check for you, and why.\n *\n * `drzl analyze` already prints the whole `Analysis` as JSON. This is not that. The analysis is a\n * description of the schema and the reader has to know which fields mean trouble; this is the list\n * of things that will silently not work, each with the sentence that says what to do about it.\n *\n * The point of the command is the *silent* half. A generator that cannot type a column emits a\n * validator accepting any value, and a CHECK the parser declines is simply absent from the output:\n * both produce a file that looks finished. `drzl generate` prints a one-line count for the first\n * and says nothing at all about the second.\n *\n * Two of the sections here read something the analyzer does not know:\n *\n * - **CHECK constraints.** `parseCheck` lives in `@drzl/validation-core` and every validation\n * generator calls it; the analyzer never does. It carries the raw expression through and has no\n * opinion on whether anything can be made of it. So the only way to say \"this constraint is in\n * your schema and nothing DRZL emits enforces it\" is to run the generators' own parser, which is\n * what this file does.\n * - **Primary keys.** The service generator keys `getById`, `update` and `delete` on\n * `table.primaryKey?.columns[0] ?? 'id'`, and the router templates take an `id` input to match.\n * A table with no primary key therefore gets a service referencing a column that may not exist,\n * and a composite key gets one keyed on half of it. The analysis states the key correctly; the\n * consequence is the generator's.\n *\n * Deliberately *not* reported, and each for a measured reason:\n *\n * - A CHECK that DRZL does translate. `age >= 18` folds into `.gte(18)` and `start < end` becomes\n * an object-level refinement; listing them as findings would drown the ones that matter.\n * - `length(col)` and `cardinality(col)` landing on a column that cannot take them. Two of the four\n * validation generators drop those and two emit something for them, so no single sentence here is\n * true of all four. It is also unreachable from a working schema: Postgres has no\n * `length(anyarray)` and no `cardinality(integer)`, so the DDL is refused before DRZL sees it.\n */\nimport type { Analysis, Column, Issue, Table } from '@drzl/analyzer';\nimport { parseCheck } from '@drzl/validation-core';\nimport chalk from 'chalk';\n\nexport type DoctorFindingKind =\n /** A column whose validator will accept any value. */\n | 'unknown-column'\n /** A CHECK the shared parser refused to translate. */\n | 'check-declined'\n /** A CHECK naming a column the table does not have. */\n | 'check-unknown-column'\n /** A CHECK comparing an array or structured column against a scalar literal. */\n | 'check-not-scalar'\n /** A table the generators cannot key. */\n | 'no-primary-key'\n /** A table keyed on more columns than the generators use. */\n | 'partial-primary-key'\n /** Anything else the analyzer said, passed through rather than dropped. */\n | 'analyzer';\n\nexport interface DoctorFinding {\n kind: DoctorFindingKind;\n level: 'warn' | 'error';\n /** Table this is about, as the analysis names it. Absent for a finding about the whole schema. */\n table?: string;\n column?: string;\n /** Constraint name, where the finding is about a CHECK. */\n constraint?: string;\n message: string;\n hint?: string;\n}\n\nexport interface DoctorReport {\n /** The schema path as the user spelled it, so the report names the file they asked about. */\n schema: string;\n dialect: string;\n /** True only when there is nothing at all to say. */\n ok: boolean;\n counts: { tables: number; columns: number; checks: number; findings: number };\n findings: DoctorFinding[];\n}\n\n/** Issue codes with a section of their own, so the catch-all does not print them twice. */\nconst HANDLED_CODES = new Set(['DRZL_ANL_UNKNOWN_COLUMN']);\n\n/**\n * Split an issue `path` into its table and column halves.\n *\n * The analyzer writes `table.column` for a column issue and a bare table name otherwise. Table\n * names are JavaScript identifiers, so the last dot is the separator and there is no ambiguity.\n */\nfunction splitPath(path: string | undefined): { table?: string; column?: string } {\n if (!path) return {};\n const dot = path.lastIndexOf('.');\n if (dot <= 0) return { table: path };\n return { table: path.slice(0, dot), column: path.slice(dot + 1) };\n}\n\n/** Every column name a parsed CHECK talks about, paired with the kind of constraint it came from. */\nfunction namedColumns(parsed: Extract<ReturnType<typeof parseCheck>, { ok: true }>) {\n const out: Array<{ column: string; scalar: boolean }> = [];\n // A comparison against a literal and an `IN` list are both statements about a scalar value, so\n // neither describes an array or a structured column. The other three kinds are not: a length or\n // a cardinality is a statement about a count, and a row check is a comparison of two columns.\n for (const c of parsed.checks) out.push({ column: c.column, scalar: true });\n for (const s of parsed.sets ?? []) out.push({ column: s.column, scalar: true });\n for (const l of parsed.lengths ?? []) out.push({ column: l.column, scalar: false });\n for (const c of parsed.cardinalities ?? []) out.push({ column: c.column, scalar: false });\n for (const r of parsed.rows ?? []) {\n out.push({ column: r.left, scalar: false });\n out.push({ column: r.right, scalar: false });\n }\n return out;\n}\n\n/**\n * What a column is, for a sentence about a constraint that does not fit it.\n *\n * Every `ColumnShape` kind has an arm, so a shape added later reads as \"a structured column\" rather\n * than as a wrong noun. `arrayDimensions` is checked first because an array carries its element's\n * shape and it is the array the constraint failed to describe.\n */\nfunction describeShape(c: Column): string {\n if (c.arrayDimensions) return 'an array';\n switch (c.shape?.kind) {\n case 'json':\n return 'a JSON';\n case 'buffer':\n return 'a binary';\n case 'tuple':\n case 'numberObject':\n return 'a structured';\n case 'numberVector':\n return 'a vector';\n case 'bitstring':\n return 'a bit-string';\n case 'byteString':\n return 'a byte-string';\n case 'custom':\n return 'a customType';\n default:\n return 'a structured';\n }\n}\n\nfunction checkFindings(table: Table): DoctorFinding[] {\n const out: DoctorFinding[] = [];\n const byName = new Map(table.columns.map((c) => [c.name, c]));\n for (const k of table.checks ?? []) {\n const label = k.name ? `\"${k.name}\"` : 'an unnamed constraint';\n const raw = k.expression ?? '';\n // A constraint whose expression the analyzer could not render at all is the one case where\n // printing the expression verbatim says nothing, and a line ending in \"Expression:\" reads\n // like the report itself is broken.\n const expr = raw.trim() ? raw : '(empty)';\n const parsed = parseCheck(raw, k.name);\n if (!parsed.ok) {\n out.push({\n kind: 'check-declined',\n level: 'warn',\n table: table.tsName,\n constraint: k.name,\n message: `CHECK ${label} on \"${table.tsName}\" is not translated: ${parsed.reason}. Expression: ${expr}`,\n hint:\n 'Only constraints whose meaning is unambiguous are translated, because a validator ' +\n 'enforcing a guess rejects rows the database accepts. Your database still enforces ' +\n 'this one; nothing DRZL emits does.',\n });\n continue;\n }\n\n // Reported once per column rather than once per clause, so `a >= 1 AND a <= 9` on a missing\n // column is one line and not two.\n const seen = new Set<string>();\n for (const { column, scalar } of namedColumns(parsed)) {\n if (seen.has(column)) continue;\n seen.add(column);\n const col = byName.get(column);\n if (!col) {\n out.push({\n kind: 'check-unknown-column',\n level: 'warn',\n table: table.tsName,\n column,\n constraint: k.name,\n message: `CHECK ${label} on \"${table.tsName}\" names \"${column}\", which is not a column of that table, so nothing enforces it. Expression: ${expr}`,\n hint:\n 'A constraint is attached to the field it names. Check the spelling, or move a ' +\n 'constraint spanning two tables out of the schema.',\n });\n continue;\n }\n if (scalar && (col.arrayDimensions || col.shape)) {\n out.push({\n kind: 'check-not-scalar',\n level: 'warn',\n table: table.tsName,\n column,\n constraint: k.name,\n message: `CHECK ${label} on \"${table.tsName}\" compares ${describeShape(col)} column \"${column}\" against a scalar literal, which does not describe it, so it is not translated. Expression: ${expr}`,\n hint:\n 'On an array column only cardinality(col) is read, since it is the one comparison ' +\n 'that is about the array rather than about an element.',\n });\n }\n }\n }\n return out;\n}\n\nfunction primaryKeyFindings(table: Table): DoctorFinding[] {\n // A read-only relation takes no writes and gets no keyed route, so it needs no key.\n if (table.readOnly) return [];\n const pk = table.primaryKey?.columns ?? [];\n if (!pk.length) {\n const hasId = table.columns.some((c) => c.name === 'id');\n return [\n {\n kind: 'no-primary-key',\n level: 'warn',\n table: table.tsName,\n message: hasId\n ? `Table \"${table.tsName}\" declares no primary key. The service and router generators fall back to a column named \"id\", which this table happens to have, so they work by coincidence.`\n : `Table \"${table.tsName}\" declares no primary key. The service and router generators fall back to a column named \"id\", which this table does not have, so the generated service will not compile.`,\n hint: 'Declare a primary key, or leave this table out with the config table filter.',\n },\n ];\n }\n if (pk.length > 1) {\n return [\n {\n kind: 'partial-primary-key',\n level: 'warn',\n table: table.tsName,\n message: `Table \"${table.tsName}\" has a composite primary key (${pk.join(', ')}). The service and router generators key getById, update and delete on \"${pk[0]}\" alone, so those operations match on part of the key.`,\n hint: 'Treat the generated service as a starting point for this table and widen the key by hand.',\n },\n ];\n }\n return [];\n}\n\n/**\n * Everything worth saying about one analysis, in the order it should be read.\n *\n * Ordered worst-first, and within that silent-first. A schema that could not be analyzed comes\n * first because nothing after it is trustworthy. Untypeable columns and dropped constraints come\n * next because they are invisible: the generated file exists, compiles and validates nothing. The\n * primary-key findings come after because one half of that pair announces itself as a compile\n * error. The catch-all is last.\n */\nexport function buildDoctorReport(analysis: Analysis, schemaPath: string): DoctorReport {\n const findings: DoctorFinding[] = [];\n\n const errors = analysis.issues.filter((i: Issue) => i.level === 'error');\n for (const i of errors) {\n findings.push({\n kind: 'analyzer',\n level: 'error',\n ...splitPath(i.path),\n message: i.message,\n hint: i.hint,\n });\n }\n\n for (const i of analysis.issues) {\n if (i.code !== 'DRZL_ANL_UNKNOWN_COLUMN') continue;\n findings.push({\n kind: 'unknown-column',\n level: 'warn',\n ...splitPath(i.path),\n message: i.message,\n hint: i.hint,\n });\n }\n\n for (const t of analysis.tables) findings.push(...checkFindings(t));\n for (const t of analysis.tables) findings.push(...primaryKeyFindings(t));\n\n for (const i of analysis.issues) {\n if (i.level === 'error' || HANDLED_CODES.has(i.code)) continue;\n findings.push({\n kind: 'analyzer',\n level: 'warn',\n ...splitPath(i.path),\n message: i.message,\n hint: i.hint,\n });\n }\n\n const columns = analysis.tables.reduce((n, t) => n + t.columns.length, 0);\n const checks = analysis.tables.reduce((n, t) => n + (t.checks?.length ?? 0), 0);\n return {\n schema: schemaPath,\n dialect: analysis.dialect,\n ok: findings.length === 0,\n counts: { tables: analysis.tables.length, columns, checks, findings: findings.length },\n findings,\n };\n}\n\n/** Sections, in report order, each with the sentence that says why its contents matter. */\nconst SECTIONS: Array<{ kinds: DoctorFindingKind[]; title: string; why: string }> = [\n {\n kinds: ['unknown-column'],\n title: 'Columns DRZL cannot type',\n why: 'These get a validator that accepts any value.',\n },\n {\n kinds: ['check-declined', 'check-unknown-column', 'check-not-scalar'],\n title: 'CHECK constraints DRZL does not enforce',\n why: 'Your database still enforces these. Nothing DRZL generates does.',\n },\n {\n kinds: ['no-primary-key', 'partial-primary-key'],\n title: 'Primary keys the generators cannot use',\n why: 'The generated getById, update and delete are keyed on one column.',\n },\n {\n kinds: ['analyzer'],\n title: 'Other findings',\n why: 'Reported by the analyzer while reading the schema.',\n },\n];\n\n/**\n * Wrap a sentence under a fixed indent, so it does not run off a narrow terminal.\n *\n * `first` is the prefix the opening line carries instead of the indent, which is what gives a\n * finding its bullet and its continuation lines a hanging indent under the text rather than under\n * the bullet.\n */\nfunction wrap(text: string, indent: string, first = indent, width = 96): string {\n const lines: string[] = [];\n let line = '';\n for (const word of text.split(/\\s+/)) {\n if (line && `${line} ${word}`.length + indent.length > width) {\n lines.push(line);\n line = word;\n } else {\n line = line ? `${line} ${word}` : word;\n }\n }\n if (line) lines.push(line);\n return lines.map((l, i) => (i === 0 ? first : indent) + l).join('\\n');\n}\n\n/**\n * The human-readable report.\n *\n * A clean schema prints what was looked at rather than nothing, because an empty page cannot be\n * told apart from a command that failed to run.\n */\nexport function renderDoctorReport(report: DoctorReport): string {\n const out: string[] = [];\n const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`;\n\n out.push(chalk.bold(`DRZL doctor ${report.schema}`));\n out.push(\n chalk.dim(\n `${report.dialect}, ${plural(report.counts.tables, 'table')}, ` +\n `${plural(report.counts.columns, 'column')}, ${plural(report.counts.checks, 'CHECK constraint')}`\n )\n );\n out.push('');\n\n if (report.ok) {\n out.push(chalk.green('Nothing to report.'));\n out.push(chalk.dim(' Every column has a type DRZL can describe.'));\n out.push(chalk.dim(' Every CHECK constraint is translated into the generated validators.'));\n out.push(chalk.dim(' Every table has a primary key the generators can use.'));\n return out.join('\\n');\n }\n\n // Ahead of the sections rather than inside one. An error means the schema was never read, so\n // every count above is zero and every section below is empty, and printing that under \"Other\n // findings\" at the foot of the page buries the only sentence that matters.\n const fatal = report.findings.filter((f) => f.level === 'error');\n if (fatal.length) {\n out.push(chalk.red('DRZL could not read this schema'));\n out.push(chalk.dim(' Nothing else could be checked.'));\n out.push('');\n for (const f of fatal) {\n out.push(wrap(f.message, ' ', ` ${chalk.dim('-')} `));\n if (f.hint) out.push(chalk.dim(wrap(f.hint, ' ')));\n }\n out.push('');\n }\n\n for (const section of SECTIONS) {\n const mine = report.findings.filter(\n (f) => f.level !== 'error' && section.kinds.includes(f.kind)\n );\n if (!mine.length) continue;\n out.push(chalk.yellow(`${section.title} (${mine.length})`));\n out.push(chalk.dim(` ${section.why}`));\n out.push('');\n // One hint per distinct sentence, under the findings that share it: the same advice repeated\n // under twenty columns is the thing that makes a report unreadable.\n const groups = new Map<string, DoctorFinding[]>();\n for (const f of mine) {\n const key = f.hint ?? '';\n groups.set(key, [...(groups.get(key) ?? []), f]);\n }\n for (const [hint, items] of groups) {\n for (const f of items) out.push(wrap(f.message, ' ', ` ${chalk.dim('-')} `));\n if (hint) out.push(chalk.dim(wrap(hint, ' ')));\n out.push('');\n }\n }\n\n out.push(\n chalk.bold(`${plural(report.counts.findings, 'finding')} in ${report.schema}.`) +\n chalk.dim(\n fatal.length\n ? ' Fix the error above and run this again.'\n : ' None of these stop DRZL generating; they are what it will not check for you.'\n )\n );\n return out.join('\\n');\n}\n","/**\n * Drift detection for generated output.\n *\n * No runtime validator can offer this. `drizzle-orm/zod` and friends derive schemas in memory at\n * import time, so there is nothing on disk to have drifted and nothing for CI to compare. It is\n * only available to a code generator, which makes it one of the few things DRZL can do that the\n * first-party modules structurally cannot.\n *\n * The check is: regenerate, and require the result to equal what is committed. That catches the\n * two failures that actually happen, someone editing generated files by hand and someone\n * changing the schema without regenerating, and it catches them in CI rather than in review.\n *\n * Content-neutral by construction. Redirecting output to a temporary directory would not work:\n * generated files contain paths computed relative to their own location, so a different output\n * directory produces legitimately different bytes and every file would report as drifted. So the\n * real directories are snapshotted first, regeneration is allowed to overwrite them, and the\n * snapshot is put back if anything changed. Either way the tree ends as it began.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface DriftEntry {\n file: string;\n status: 'changed' | 'added' | 'removed';\n}\n\n/** Every file under `dir`, keyed by its path relative to `dir`. Missing directory means empty. */\nexport async function snapshotDir(dir: string): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n async function walk(current: string) {\n let entries;\n try {\n entries = await fs.readdir(current, { withFileTypes: true });\n } catch {\n return; // Nothing generated there yet, which a first run should report as additions.\n }\n for (const e of entries) {\n const full = path.join(current, e.name);\n if (e.isDirectory()) await walk(full);\n else out.set(path.relative(dir, full), await fs.readFile(full, 'utf8'));\n }\n }\n await walk(dir);\n return out;\n}\n\n/** Snapshot several directories at once, keys prefixed by directory so they cannot collide. */\nexport async function snapshotAll(dirs: string[]): Promise<Map<string, string>> {\n const all = new Map<string, string>();\n for (const dir of dirs) {\n for (const [rel, content] of await snapshotDir(dir)) {\n all.set(path.join(dir, rel), content);\n }\n }\n return all;\n}\n\n/** What changed between two snapshots. */\nexport function diffSnapshots(\n before: Map<string, string>,\n after: Map<string, string>\n): DriftEntry[] {\n const out: DriftEntry[] = [];\n for (const [file, content] of after) {\n if (!before.has(file)) out.push({ file, status: 'added' });\n else if (before.get(file) !== content) out.push({ file, status: 'changed' });\n }\n for (const file of before.keys()) {\n if (!after.has(file)) out.push({ file, status: 'removed' });\n }\n return out.sort((a, b) => a.file.localeCompare(b.file));\n}\n\n/**\n * Put a snapshot back, so a failed check leaves the tree exactly as it found it.\n *\n * A file that regeneration created and the snapshot does not know about is deleted, since it was\n * not there before the check ran.\n */\nexport async function restoreSnapshot(\n before: Map<string, string>,\n after: Map<string, string>\n): Promise<void> {\n for (const [file, content] of before) {\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.writeFile(file, content, 'utf8');\n }\n for (const file of after.keys()) {\n if (!before.has(file)) await fs.rm(file, { force: true });\n }\n}\n","/**\n * Loading an optional generator package, and telling absence apart from failure.\n *\n * Every validation generator is loaded on demand, because a project that only wants zod should not\n * have to install five. That makes \"the package is not installed\" a real, expected outcome worth a\n * helpful message. It does not make it the only outcome: a generator that is installed and running\n * can throw for any reason a program can throw, and the CLI reported all of those as a missing npm\n * package too, with the true reason printed underneath as a detail.\n *\n * Node reports an unresolvable import as `ERR_MODULE_NOT_FOUND`, and reports the same code when\n * the module resolved and something *it* imported did not. The code alone therefore does not\n * separate the two; the message does, because it names the specifier that failed to resolve.\n */\n\n/** A generator package that is not installed. Everything else is somebody's real error. */\nexport class GeneratorNotInstalledError extends Error {\n constructor(\n readonly specifier: string,\n /** What Node threw, kept so nothing is discarded on the way to the message. */\n readonly reason: unknown\n ) {\n super(`${specifier} is not installed`);\n this.name = 'GeneratorNotInstalledError';\n }\n}\n\n/**\n * Whether `err` is Node refusing to resolve `specifier` itself.\n *\n * Measured on Node 22, from an ESM entry and from a CJS one, since the CLI ships both builds and\n * the bundler leaves `import()` as `import()` in each:\n *\n * absent package ERR_MODULE_NOT_FOUND, `Cannot find package '<specifier>' imported…`\n * present, inner dep absent ERR_MODULE_NOT_FOUND, naming the *inner* specifier instead\n * present, main file gone ERR_MODULE_NOT_FOUND, naming the resolved file path\n * throws while evaluating no `code` at all, and whatever message the generator threw\n *\n * Only the first is an install problem, and only the first quotes the specifier that was asked\n * for, which is what this matches on.\n */\nexport function isPackageMissing(err: unknown, specifier: string): boolean {\n const code = (err as { code?: unknown } | null | undefined)?.code;\n if (code !== 'ERR_MODULE_NOT_FOUND') return false;\n const message = (err as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message.includes(`'${specifier}'`);\n}\n\n/**\n * Run `load` and re-throw a missing package as `GeneratorNotInstalledError`.\n *\n * `load` is a thunk rather than a specifier so the caller keeps a literal `import('@drzl/…')` in\n * its own source, which is what lets the bundler see the dependency. Anything it throws that is\n * not this package's own absence comes out unchanged.\n */\nexport async function loadGenerator<T>(specifier: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isPackageMissing(e, specifier)) throw new GeneratorNotInstalledError(specifier, e);\n throw e;\n }\n}\n","import chalk from 'chalk';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\nexport interface SponsorMessageOptions {\n reason?: string;\n minIntervalMs?: number;\n force?: boolean;\n}\n\ninterface SponsorCachePayload {\n runs: number;\n lastShownAt?: number;\n lastReason?: string;\n}\n\nconst CACHE_DIR = path.join(process.cwd(), 'node_modules', '.cache', '@drzl');\nconst CACHE_FILE = path.join(CACHE_DIR, 'sponsor-message.json');\nconst DEFAULT_INTERVAL_MS = 1000 * 60 * 15; // 15 minutes\nlet shownThisProcess = false;\n\nconst tips = [\n 'Pair DRZL watch mode with drizzle-kit to keep schema & API synced.',\n 'Templatize your ORPC routers to roll out new endpoints safely.',\n 'Need typed validators? Enable the zod, valibot, arktype, or typebox generators.',\n 'Need JSON Schema or OpenAPI? The json-schema generator emits both, with no runtime dependency.',\n 'Use output headers to track generated files and trim noisy diffs.',\n];\n\nconst green = (msg: string) => chalk.hex('#6ee7b7')(msg);\nconst cyan = (msg: string) => chalk.cyan(msg);\nconst gray = (msg: string) => chalk.gray(msg);\n\nexport function maybeShowSponsorMessage({\n reason = 'generate',\n minIntervalMs = DEFAULT_INTERVAL_MS,\n force = false,\n}: SponsorMessageOptions = {}) {\n const hideViaEnv = process.env.DRZL_HIDE_SPONSOR?.toLowerCase();\n const hideRequested = hideViaEnv === '1' || hideViaEnv === 'true';\n if (hideRequested || (process.env.CI && !force) || (shownThisProcess && !force)) return;\n\n try {\n mkdirSync(CACHE_DIR, { recursive: true });\n const payload = readCache();\n payload.runs += 1;\n\n const now = Date.now();\n const shouldShow = force || now - (payload.lastShownAt ?? 0) >= minIntervalMs;\n\n if (shouldShow) {\n payload.lastShownAt = now;\n payload.lastReason = reason;\n }\n\n writeCache(payload);\n\n if (!shouldShow) return;\n\n shownThisProcess = true;\n const tip = tips[payload.runs % tips.length];\n\n console.log(\n `\\n${cyan(`🚀 DRZL finished a ${reason} run (#${payload.runs.toLocaleString()}).`)}\\n\\n` +\n `${green('✨ Sponsors keep DRZL shipping. Consider supporting ongoing dev:')}\\n` +\n ` ${green('GitHub Sponsors')} ${gray('→ https://github.com/sponsors/omar-dulaimi')}\\n\\n` +\n `${green('Pro tip:')} ${tip}\\n`\n );\n } catch {\n // Swallow to avoid impacting generator success paths\n }\n}\n\nfunction readCache(): SponsorCachePayload {\n if (!existsSync(CACHE_FILE)) {\n return { runs: 0 };\n }\n try {\n const data = JSON.parse(readFileSync(CACHE_FILE, 'utf8')) as SponsorCachePayload;\n if (typeof data.runs !== 'number') return { runs: 0 };\n return data;\n } catch {\n return { runs: 0 };\n }\n}\n\nfunction writeCache(payload: SponsorCachePayload) {\n writeFileSync(CACHE_FILE, JSON.stringify(payload, null, 2), 'utf8');\n}\n","/**\n * The version `drzl --version` prints, read from the manifest that ships beside the build.\n *\n * It used to be the literal `'0.0.1'`, passed to `program.version()` when the CLI was scaffolded\n * and never touched again. That was true of exactly one release, the first: the registry lists 29\n * versions of `@drzl/cli`, and the other 28 printed `0.0.1` as well. Reading the manifest is the\n * only form that cannot drift, because it is the same file the registry took the version from.\n *\n * Nothing here falls back. A build that cannot find its own manifest, or finds someone else's, has\n * resolved somewhere it did not intend to, and a placeholder standing in for that is how the\n * original defect stayed invisible for 28 releases.\n */\nimport { readFileSync } from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/** The name the manifest beside this build must carry, which is what makes it ours. */\nconst PACKAGE_NAME = '@drzl/cli';\n\n/**\n * The directory holding the file this code ends up in, in every form it is reached.\n *\n * Three of them: `dist/cli.js`, `dist/cli.cjs`, and this file unbundled under ts-node, all three\n * run and checked. Only the CommonJS bundle has no `import.meta`; `tsup.config.ts` gives that\n * build a real value for `import.meta.url` rather than esbuild's empty one, so this needs no\n * branch. If that config is ever dropped, `fileURLToPath(undefined)` throws on load, so the\n * CommonJS bundle stops working loudly instead of reporting the wrong directory.\n */\nfunction moduleDir(): string {\n return path.dirname(fileURLToPath(import.meta.url));\n}\n\n/**\n * The `version` a named manifest declares, or a throw naming what was wrong with it.\n *\n * Split out from the caller below only so the three ways it refuses can be exercised without a\n * build. Nothing in the CLI passes a path.\n */\nexport function readVersionFrom(manifestPath: string): string {\n let raw: string;\n try {\n raw = readFileSync(manifestPath, 'utf8');\n } catch (e: any) {\n throw new Error(\n `${PACKAGE_NAME} cannot read its own version: no manifest at ${manifestPath} ` +\n `(${e?.message ?? String(e)}).`\n );\n }\n\n const manifest = JSON.parse(raw) as { name?: unknown; version?: unknown };\n\n if (manifest.name !== PACKAGE_NAME) {\n throw new Error(\n `${PACKAGE_NAME} looked for its own version in ${manifestPath} and found ` +\n `${JSON.stringify(manifest.name)}, so this build is not sitting where it thinks it is.`\n );\n }\n\n if (typeof manifest.version !== 'string' || manifest.version.length === 0) {\n throw new Error(`${manifestPath} declares no version, so there is nothing to report.`);\n }\n\n return manifest.version;\n}\n\n/**\n * The `version` field of this package's own manifest.\n *\n * Both bundles sit one level below it, in `dist/`, and so does `src/` when this file is run\n * unbundled, so one `..` covers every way it is reached. All three were run.\n */\nexport function readCliVersion(): string {\n return readVersionFrom(path.join(moduleDir(), '..', 'package.json'));\n}\n\nexport const CLI_VERSION = readCliVersion();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiFA,SAAS,OAAO,QAAQ;AACtB,MAAI,OAAO,cAAc,OAAO,WAAW,OAAQ,QA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,sBAAsB;AAAA,EAC3F;AACA,aAAW,KAAK,KAAK,MAAM,GAAG,EAAE,EAAG,SAAQ,KAAK,cAAAA,QAAM,KAAK,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9E,MAAI,KAAK,SAAS,GAAI,SAAQ,KAAK,cAAAA,QAAM,KAAK,aAAa,KAAK,SAAS,EAAE,OAAO,CAAC;AAEnF,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,OAAO,CAAC,CAAC;AAClE,aAAW,KAAK,MAAO,SAAQ,KAAK,cAAAA,QAAM,KAAK,KAAK,CAAC,EAAE,CAAC;AAIxD,UAAQ,KAAK,cAAAA,QAAM,KAAK,0CAA0C,CAAC;AACrE;AAEA,QAAQ,WAAW,QAAQ,IAAI;","names":["path","import_validation_core","fs","dist_exports","index_default","keyColumns","path","buildHeader","import_validation_core","init_dist","fs","import_chalk","path","mine","raw","import_validation_core","path","chalk","fs","path","import_chalk","import_node_fs","import_node_path","path","chalk","import_node_fs","path","chalk","ora","fs","cliProgress","TRPCGenerator","JsonSchemaGenerator","watcher","chokidar","path"]}