-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.js.map
1 lines (1 loc) · 15 KB
/
main.js.map
1
{"version":3,"file":"main.js","names":["updateTypes","db","options","overrides","output","fs","createWriteStream","encoding","forEach","line","write","schema","split","map","x","trim","includeSchemas","excludeSchemas","reduce","acc","s","startsWith","push","exclude","prefix","enums","table","join","orderBy","select","i","key","enumName","value","replace","enumsMap","Map","columns","withSchema","whereIn","whereNotIn","raw","tableSet","Set","Array","from","tableName","schemaName","type","getType","udt","substring","default","nullable","sanitize","column","suffix","end","destroy","customTypes","defaultValue","get","name","test","JSON","stringify"],"sources":["main.ts"],"sourcesContent":["/* SPDX-FileCopyrightText: 2016-present Kriasoft <[email protected]> */\n/* SPDX-License-Identifier: MIT */\n\nimport fs from \"fs\";\nimport { Knex } from \"knex\";\nimport { camelCase, upperFirst } from \"lodash\";\nimport type { Writable } from \"stream\";\n\nexport type Options = {\n /**\n * Filename or output stream where the type definitions needs to be written.\n */\n output: Writable | string;\n\n /**\n * Name overrides for enums, classes, and fields.\n *\n * @example\n * overrides: {\n * \"identity_provider.linkedin\": \"LinkedIn\"\n * }\n */\n overrides?: Record<string, string>;\n\n prefix?: string;\n suffix?: string;\n\n /**\n * Schemas that should be included/excluded when generating types.\n *\n * By default if this is null/not specified, \"public\" will be the only schema added, but if this property\n * is specified, public will be excluded by default and has to be included in the list to be added to the output.\n * If a schema is added by its name, i.e. 'log' all tables from that schema will be added.\n * If a schema name is added with an exclamation mark it will be ignored, i.e. \"!log\".\n *\n * The table-type will be prefixed by its schema name, the table log.message will become LogMessage.\n *\n * @example\n * // This will include \"public\" and \"log\", but exclude the \"auth\" schema.\n * schema: [\"public\", \"log\", \"!auth\"]\n * @default\n * \"public\"\n */\n schema?: string[] | string;\n\n /**\n * A comma separated list or an array of tables that should be excluded when\n * generating types.\n *\n * @example\n * exclude: [\"migration\", \"migration_lock\"]\n */\n exclude?: string[] | string;\n};\n\n/**\n * Generates TypeScript definitions (types) from a PostgreSQL database schema.\n */\nexport async function updateTypes(db: Knex, options: Options): Promise<void> {\n const overrides: Record<string, string> = options.overrides ?? {};\n const output: Writable =\n typeof options.output === \"string\"\n ? fs.createWriteStream(options.output, { encoding: \"utf-8\" })\n : options.output;\n\n [\n \"// The TypeScript definitions below are automatically generated.\\n\",\n \"// Do not touch them, or risk, your modifications being lost.\\n\\n\",\n ].forEach((line) => output.write(line));\n\n const schema = (typeof options.schema === \"string\"\n ? options.schema.split(\",\").map((x) => x.trim())\n : options.schema) ?? [\"public\"];\n\n // Schemas to include or exclude\n const [includeSchemas, excludeSchemas] = schema.reduce(\n (acc, s) =>\n (acc[+s.startsWith(\"!\")].push(s) && acc) as [string[], string[]],\n [[] as string[], [] as string[]]\n );\n\n // Tables to exclude\n const exclude =\n (typeof options.exclude === \"string\"\n ? options.exclude.split(\",\").map((x) => x.trim())\n : options.exclude) ?? [];\n\n if (options.prefix) {\n output.write(options.prefix);\n output.write(\"\\n\\n\");\n }\n\n try {\n // Fetch the list of custom enum types\n const enums = await db\n .table(\"pg_type\")\n .join(\"pg_enum\", \"pg_enum.enumtypid\", \"pg_type.oid\")\n .orderBy(\"pg_type.typname\")\n .orderBy(\"pg_enum.enumsortorder\")\n .select<Enum[]>(\"pg_type.typname as key\", \"pg_enum.enumlabel as value\");\n\n // Construct TypeScript enum types\n enums.forEach((x, i) => {\n // The first line of enum declaration\n if (!(enums[i - 1] && enums[i - 1].key === x.key)) {\n const enumName = overrides[x.key] ?? upperFirst(camelCase(x.key));\n output.write(`export enum ${enumName} {\\n`);\n }\n\n // Enum body\n const key =\n overrides[`${x.key}.${x.value}`] ??\n upperFirst(camelCase(x.value.replace(/[.-]/g, \"_\")));\n output.write(` ${key} = \"${x.value}\",\\n`);\n\n // The closing line\n if (!(enums[i + 1] && enums[i + 1].key === x.key)) {\n output.write(\"}\\n\\n\");\n }\n });\n\n const enumsMap = new Map(\n enums.map((x) => [\n x.key,\n overrides[x.key] ?? upperFirst(camelCase(x.key)),\n ])\n );\n\n // Fetch the list of tables/columns\n const columns = await db\n .withSchema(\"information_schema\")\n .table(\"columns\")\n .whereIn(\"table_schema\", includeSchemas)\n .whereNotIn(\"table_schema\", excludeSchemas)\n .whereNotIn(\"table_name\", exclude)\n .orderBy(\"table_schema\")\n .orderBy(\"table_name\")\n .orderBy(\"ordinal_position\")\n .select<Column[]>(\n \"table_schema as schema\",\n \"table_name as table\",\n \"column_name as column\",\n db.raw(\"(is_nullable = 'YES') as nullable\"),\n \"column_default as default\",\n \"data_type as type\",\n \"udt_name as udt\"\n );\n\n // The list of database tables as enum\n output.write(\"export enum Table {\\n\");\n const tableSet = new Set(\n columns.map((x) => {\n const schema = x.schema !== \"public\" ? `${x.schema}.` : \"\";\n return `${schema}${x.table}`;\n })\n );\n Array.from(tableSet).forEach((value) => {\n const key = overrides[value] ?? upperFirst(camelCase(value));\n output.write(` ${key} = \"${value}\",\\n`);\n });\n output.write(\"}\\n\\n\");\n // The list of tables as type\n output.write(\"export type Tables = {\\n\");\n Array.from(tableSet).forEach((key) => {\n const value = overrides[key] ?? upperFirst(camelCase(key));\n output.write(` \"${key}\": ${value},\\n`);\n });\n output.write(\"};\\n\\n\");\n\n // Construct TypeScript db record types\n columns.forEach((x, i) => {\n if (!(columns[i - 1] && columns[i - 1].table === x.table)) {\n const tableName = overrides[x.table] ?? upperFirst(camelCase(x.table));\n const schemaName =\n x.schema !== \"public\" ? upperFirst(camelCase(x.schema)) : \"\";\n output.write(`export type ${schemaName}${tableName} = {\\n`);\n }\n\n let type =\n x.type === \"ARRAY\"\n ? `${getType(x.udt.substring(1), enumsMap, x.default)}[]`\n : getType(x.udt, enumsMap, x.default);\n\n if (x.nullable) {\n type += \" | null\";\n }\n\n output.write(` ${sanitize(x.column)}: ${type};\\n`);\n\n if (!(columns[i + 1] && columns[i + 1].table === x.table)) {\n output.write(\"};\\n\\n\");\n }\n });\n\n if (options.suffix) {\n output.write(options.suffix);\n output.write(\"\\n\");\n }\n } finally {\n output.end();\n db.destroy();\n }\n}\n\ntype Enum = {\n key: string;\n value: string;\n};\n\ntype Column = {\n table: string;\n column: string;\n schema: string;\n nullable: boolean;\n default: string | null;\n type: string;\n udt: string;\n};\n\nexport function getType(\n udt: string,\n customTypes: Map<string, string>,\n defaultValue: string | null\n): string {\n switch (udt) {\n case \"bool\":\n return \"boolean\";\n case \"text\":\n case \"citext\":\n case \"money\":\n case \"numeric\":\n case \"int8\":\n case \"char\":\n case \"character\":\n case \"bpchar\":\n case \"varchar\":\n case \"time\":\n case \"tsquery\":\n case \"tsvector\":\n case \"uuid\":\n case \"xml\":\n case \"cidr\":\n case \"inet\":\n case \"macaddr\":\n return \"string\";\n case \"smallint\":\n case \"integer\":\n case \"int\":\n case \"int2\":\n case \"int4\":\n case \"real\":\n case \"float\":\n case \"float4\":\n case \"float8\":\n return \"number\";\n case \"date\":\n case \"timestamp\":\n case \"timestamptz\":\n return \"Date\";\n case \"json\":\n case \"jsonb\":\n if (defaultValue) {\n if (defaultValue.startsWith(\"'{\")) {\n return \"Record<string, unknown>\";\n }\n if (defaultValue.startsWith(\"'[\")) {\n return \"unknown[]\";\n }\n }\n return \"unknown\";\n case \"bytea\":\n return \"Buffer\";\n case \"interval\":\n return \"PostgresInterval\";\n default:\n return customTypes.get(udt) ?? \"unknown\";\n }\n}\n\n/**\n * Wraps the target property identifier into quotes in case it contains any\n * invalid characters.\n *\n * @see https://developer.mozilla.org/docs/Glossary/Identifier\n */\nfunction sanitize(name: string): string {\n return /^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(name) ? name : JSON.stringify(name);\n}\n"],"mappings":";;;;;;;;;AAGA;AAAoB;AAHpB;AACA;;AAsDA;AACA;AACA;AACO,eAAeA,WAAW,CAACC,EAAQ,EAAEC,OAAgB,EAAiB;EAAA;EAC3E,MAAMC,SAAiC,yBAAGD,OAAO,CAACC,SAAS,mEAAI,CAAC,CAAC;EACjE,MAAMC,MAAgB,GACpB,OAAOF,OAAO,CAACE,MAAM,KAAK,QAAQ,GAC9B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