|
| 1 | +import { Config, TypeScriptSerializer } from 'kysely-codegen'; |
| 2 | +import * as fs from 'fs'; |
| 3 | + |
| 4 | +const kyselyConfigData = fs.readFileSync('.kysely-codegenrc.json') |
| 5 | +const kyselyConfig = JSON.parse(kyselyConfigData) as Config; |
| 6 | + |
| 7 | +// From jlarmstrngiv, https://github.com/RobinBlomberg/kysely-codegen/issues/86#issuecomment-2545060194 |
| 8 | + |
| 9 | +import { generate as generateZod } from "ts-to-zod"; |
| 10 | +// import prettier, { Options as PrettierOptions } from "prettier"; |
| 11 | + |
| 12 | +const defaultBanner = `/** |
| 13 | + * This file was generated by kysely-codegen and ts-to-zod |
| 14 | + * Manual edits will be overwritten. |
| 15 | + */ |
| 16 | +
|
| 17 | +`; |
| 18 | + |
| 19 | +export type GenerateOptions = { |
| 20 | + banner?: string; |
| 21 | + footer?: string; |
| 22 | + // prettierOptions?: PrettierOptions; |
| 23 | +}; |
| 24 | + |
| 25 | +export const generateFromKysely = ( |
| 26 | + src: string, |
| 27 | + { |
| 28 | + banner = defaultBanner, |
| 29 | + footer = "", |
| 30 | + // prettierOptions = {}, |
| 31 | + }: GenerateOptions = {}, |
| 32 | +): string => { |
| 33 | + const hasPostgresInterval = src.includes("IPostgresInterval"); |
| 34 | + |
| 35 | + // multiline replacement regex https://stackoverflow.com/a/45981809 |
| 36 | + |
| 37 | + // remove comment |
| 38 | + src = src.replace( |
| 39 | + /\/\*\*.* This file was generated by kysely-codegen.*?\*\//s, |
| 40 | + "", |
| 41 | + ); |
| 42 | + // remove unneeded imports |
| 43 | + src = src.replaceAll(/import.*?;/gs, ""); |
| 44 | + if (hasPostgresInterval) { |
| 45 | + // ts-to-zod is unable to parse IPostgresInterval from import |
| 46 | + // reference node_modules/postgres-interval/index.d.ts |
| 47 | + src = |
| 48 | + `export interface IPostgresInterval { |
| 49 | + years: number; |
| 50 | + months: number; |
| 51 | + days: number; |
| 52 | + hours: number; |
| 53 | + minutes: number; |
| 54 | + seconds: number; |
| 55 | + milliseconds: number; |
| 56 | + // toPostgres(): string; |
| 57 | + // toISO(): string; |
| 58 | + // toISOString(): string; |
| 59 | + // toISOStringShort(): string; |
| 60 | +}` + |
| 61 | + "\n" + |
| 62 | + src; |
| 63 | + } |
| 64 | + // remove Generated type |
| 65 | + src = src.replace(/export type Generated.*?;/s, ""); |
| 66 | + src = src.replaceAll( |
| 67 | + /: Generated<(.*?)>/g, |
| 68 | + (match) => "?: " + match.slice(": Generated<".length, -">".length), |
| 69 | + ); |
| 70 | + // remove array types |
| 71 | + src = src.replace(/export type ArrayType<T>.*?;/s, ""); |
| 72 | + src = src.replace(/export type ArrayTypeImpl<T>.*?;/s, ""); |
| 73 | + src = src.replaceAll( |
| 74 | + /ArrayType<(.*?)>/g, |
| 75 | + (match) => match.slice("ArrayType<".length, -">".length) + "[]", |
| 76 | + ); |
| 77 | + // remove json column type |
| 78 | + src = src.replaceAll(/JSONColumnType<(.*?)>/g, (match) => |
| 79 | + match.slice("JSONColumnType<".length, -">".length), |
| 80 | + ); |
| 81 | + // remove DB export |
| 82 | + src = src.replace(/export interface DB {.*?}/s, ""); |
| 83 | + |
| 84 | + // remove and simplify ColumnType |
| 85 | + const columnTypeRegex = /export type (.*?) = ColumnType<(.*?)>;/g; |
| 86 | + const matches = [...(src.matchAll(columnTypeRegex) ?? [])]; |
| 87 | + for (const match of matches) { |
| 88 | + const original = match[0]; |
| 89 | + const typeName = match[1]; |
| 90 | + const types = match[2]; |
| 91 | + const reducedTypes = [...new Set((types||'').split(/ \| |, /))]; |
| 92 | + src = src.replace( |
| 93 | + original, |
| 94 | + `export type ${typeName} = ${reducedTypes.join(" | ")};`, |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + // zod programmatic api https://github.com/fabien0102/ts-to-zod/blob/main/src/core/generate.test.ts |
| 99 | + const { getZodSchemasFile, errors } = generateZod({ |
| 100 | + sourceText: src, |
| 101 | + skipParseJSDoc: true, |
| 102 | + }); |
| 103 | + |
| 104 | + // console log and throw errors, if any |
| 105 | + if (errors.length > 0) { |
| 106 | + for (const error of errors) { |
| 107 | + console.error(error); |
| 108 | + } |
| 109 | + throw new Error(`ts-to-zod generate failed`); |
| 110 | + } |
| 111 | + |
| 112 | + // generate zod types |
| 113 | + let schemas = getZodSchemasFile("./database-types.ts"); |
| 114 | + // find enums names |
| 115 | + const enumNames = [...schemas.matchAll(/\bz\.enum\(([^)]+)\)/gs)].map(([match, p1])=>p1) || []; |
| 116 | + const schemaNames = [...schemas.matchAll(/\bz\.ZodSchema\<([^>]+)\>/gs)].map(([match, p1])=>p1) || []; |
| 117 | + const srcImport = `import {${(enumNames.concat(schemaNames)).join(', ')}} from "./kyselyTypes";` |
| 118 | + // apply enums |
| 119 | + schemas = schemas.replaceAll(/\bz\.enum\b/gs, "z.nativeEnum"); |
| 120 | + // remove unneeded imports |
| 121 | + schemas = schemas.replaceAll(/import.*?;/gs, ""); |
| 122 | + // add back zod import |
| 123 | + schemas = `import { z } from "zod";\nimport { Insertable } from "kysely";\n${srcImport}\n\n${schemas}`; |
| 124 | + // Insertable |
| 125 | + schemas = schemas.replaceAll(/\bz\.ZodSchema\<([^>]+)\>/gs, (match, p1) => |
| 126 | + (p1.includes('Json'))?match:`z.ZodSchema<Insertable<${p1}>>` |
| 127 | + ); |
| 128 | + // remove comment |
| 129 | + schemas = schemas.replace("// Generated by ts-to-zod", ""); |
| 130 | + // concatenate types and schemas |
| 131 | + schemas = banner + schemas + footer; |
| 132 | + // format result |
| 133 | + // schemas = await prettier.format(schemas, { |
| 134 | + // ...prettierOptions, |
| 135 | + // parser: "typescript", |
| 136 | + // }); |
| 137 | + |
| 138 | + return schemas; |
| 139 | +} |
| 140 | + |
| 141 | + |
| 142 | +const config: Config = { |
| 143 | + ...kyselyConfig, |
| 144 | + outFile: "src/zodTypes.ts", |
| 145 | + serializer: { |
| 146 | + serializeFile: (metadata, dialect, options) => { |
| 147 | + const upstream = new TypeScriptSerializer({ |
| 148 | + runtimeEnums: kyselyConfig.runtimeEnums |
| 149 | + }); |
| 150 | + let input = upstream.serializeFile(metadata, dialect, options); |
| 151 | + return generateFromKysely(input); |
| 152 | + } |
| 153 | + } |
| 154 | +}; |
| 155 | + |
| 156 | +export default config; |
0 commit comments