@prisma-next/cli 0.3.0-dev.17 → 0.3.0-dev.19
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/{chunk-ZG5T6OB5.js → chunk-AGOTG4L3.js} +43 -1
- package/dist/chunk-AGOTG4L3.js.map +1 -0
- package/dist/chunk-HLLI4YL7.js +180 -0
- package/dist/chunk-HLLI4YL7.js.map +1 -0
- package/dist/chunk-VG2R7DGF.js +735 -0
- package/dist/chunk-VG2R7DGF.js.map +1 -0
- package/dist/cli.js +1621 -1382
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.d.ts.map +1 -1
- package/dist/commands/contract-emit.js +3 -4
- package/dist/commands/db-init.js +4 -49
- package/dist/commands/db-init.js.map +1 -1
- package/dist/commands/db-introspect.d.ts.map +1 -1
- package/dist/commands/db-introspect.js +106 -136
- package/dist/commands/db-introspect.js.map +1 -1
- package/dist/commands/db-schema-verify.d.ts.map +1 -1
- package/dist/commands/db-schema-verify.js +118 -110
- package/dist/commands/db-schema-verify.js.map +1 -1
- package/dist/commands/db-sign.d.ts.map +1 -1
- package/dist/commands/db-sign.js +150 -153
- package/dist/commands/db-sign.js.map +1 -1
- package/dist/commands/db-verify.d.ts.map +1 -1
- package/dist/commands/db-verify.js +140 -119
- package/dist/commands/db-verify.js.map +1 -1
- package/dist/control-api/client.d.ts.map +1 -1
- package/dist/control-api/types.d.ts +132 -1
- package/dist/control-api/types.d.ts.map +1 -1
- package/dist/exports/control-api.d.ts +1 -1
- package/dist/exports/control-api.d.ts.map +1 -1
- package/dist/exports/control-api.js +1 -3
- package/dist/exports/index.js +3 -4
- package/dist/exports/index.js.map +1 -1
- package/package.json +10 -10
- package/src/commands/contract-emit.ts +179 -102
- package/src/commands/db-introspect.ts +151 -178
- package/src/commands/db-schema-verify.ts +150 -143
- package/src/commands/db-sign.ts +202 -196
- package/src/commands/db-verify.ts +179 -149
- package/src/control-api/client.ts +352 -22
- package/src/control-api/types.ts +149 -1
- package/src/exports/control-api.ts +9 -0
- package/dist/chunk-5MPKZYVI.js +0 -47
- package/dist/chunk-5MPKZYVI.js.map +0 -1
- package/dist/chunk-6EPKRATC.js +0 -91
- package/dist/chunk-6EPKRATC.js.map +0 -1
- package/dist/chunk-74IELXRA.js +0 -371
- package/dist/chunk-74IELXRA.js.map +0 -1
- package/dist/chunk-U6QI3AZ3.js +0 -133
- package/dist/chunk-U6QI3AZ3.js.map +0 -1
- package/dist/chunk-VI2YETW7.js +0 -38
- package/dist/chunk-VI2YETW7.js.map +0 -1
- package/dist/chunk-ZG5T6OB5.js.map +0 -1
- package/dist/utils/action.d.ts +0 -16
- package/dist/utils/action.d.ts.map +0 -1
- package/dist/utils/spinner.d.ts +0 -29
- package/dist/utils/spinner.d.ts.map +0 -1
- package/src/utils/action.ts +0 -43
- package/src/utils/spinner.ts +0 -67
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control-api.d.ts","sourceRoot":"","sources":["../../src/exports/control-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,YAAY,EACV,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAG5D,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,oBAAoB,EACpB,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,WAAW,EACX,aAAa,GACd,MAAM,sBAAsB,CAAC"}
|
|
1
|
+
{"version":3,"file":"control-api.d.ts","sourceRoot":"","sources":["../../src/exports/control-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,YAAY,EACV,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAG5D,YAAY,EACV,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,oBAAoB,EACpB,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,WAAW,EACX,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,WAAW,EACX,aAAa,GACd,MAAM,sBAAsB,CAAC"}
|
package/dist/exports/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createContractEmitCommand
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-ZG5T6OB5.js";
|
|
3
|
+
} from "../chunk-HLLI4YL7.js";
|
|
4
|
+
import "../chunk-AGOTG4L3.js";
|
|
6
5
|
import "../chunk-HWYQOCAJ.js";
|
|
7
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-VG2R7DGF.js";
|
|
8
7
|
|
|
9
8
|
// src/load-ts-contract.ts
|
|
10
9
|
import { existsSync, unlinkSync, writeFileSync } from "fs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const seen = new WeakSet();\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (seen.has(value)) {\n throw new Error('Contract export contains circular references');\n }\n seen.add(value);\n\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(`Contract export contains getter/setter at key \"${key}\"`);\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw new Error(`Contract export contains function at key \"${key}\"`);\n }\n check((value as Record<string, unknown>)[key]);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw new Error(`Contract export is not JSON-serializable: ${error.message}`);\n }\n throw new Error('Contract export is not JSON-serializable');\n }\n}\n\nfunction createImportAllowlistPlugin(allowlist: ReadonlyArray<string>, entryPath: string): Plugin {\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n const isFromEntryPoint = args.importer === entryPath || args.importer === '<stdin>';\n if (isFromEntryPoint && !isAllowedImport(args.path, allowlist)) {\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as ContractIR.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as ContractIR (should already be normalized)\n * @throws Error if the contract cannot be loaded or is not JSON-serializable\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<ContractIR> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new Error(`Contract file not found: ${entryPath}`);\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw new Error(`Failed to bundle contract file: ${errorMessages}`);\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new Error('No output files generated from bundling');\n }\n\n const disallowedImports: string[] = [];\n if (result.metafile) {\n const inputs = result.metafile.inputs;\n for (const [, inputData] of Object.entries(inputs)) {\n const imports =\n (inputData as { imports?: Array<{ path: string; external?: boolean }> }).imports || [];\n for (const imp of imports) {\n if (\n imp.external &&\n !imp.path.startsWith('.') &&\n !imp.path.startsWith('/') &&\n !isAllowedImport(imp.path, allowlist)\n ) {\n disallowedImports.push(imp.path);\n }\n }\n }\n }\n\n if (disallowedImports.length > 0) {\n throw new Error(\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${disallowedImports.join(', ')}\\n\\nOnly @prisma-next/* packages are allowed in contract files.`,\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new Error('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(`file://${tempFile}`)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new Error(\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw new Error(`Contract export must be an object, got ${typeof contract}`);\n }\n\n validatePurity(contract);\n\n return contract as ContractIR;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Failed to load contract from ${entryPath}: ${String(error)}`);\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,YAAY,YAAY,qBAAqB;AACtD,SAAS,cAAc;AACvB,SAAS,YAAY;AAGrB,SAAS,aAAa;AAMtB,IAAM,oBAAoB,CAAC,gBAAgB;AAE3C,SAAS,gBAAgB,YAAoB,WAA2C;AACtF,aAAW,WAAW,WAAW;AAC/B,QAAI,QAAQ,SAAS,IAAI,GAAG;AAC1B,YAAM,SAAS,QAAQ,MAAM,GAAG,EAAE;AAClC,UAAI,eAAe,UAAU,WAAW,WAAW,GAAG,MAAM,GAAG,GAAG;AAChE,eAAO;AAAA,MACT;AAAA,IACF,WAAW,eAAe,SAAS;AACjC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,OAAsB;AAC5C,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C;AAAA,EACF;AAEA,QAAM,OAAO,oBAAI,QAAQ;AACzB,WAAS,MAAMA,QAAsB;AACnC,QAAIA,WAAU,QAAQ,OAAOA,WAAU,UAAU;AAC/C;AAAA,IACF;AAEA,QAAI,KAAK,IAAIA,MAAK,GAAG;AACnB,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AACA,SAAK,IAAIA,MAAK;AAEd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AAkB,SAAS,GAAG;AAChC,YAAM,IAAI;AAAA,QACR;AAAA,eAAiG,UAAU,KAAK,IAAI,CAAC;AAAA,wBAA2B,kBAAkB,KAAK,IAAI,CAAC;AAAA;AAAA;AAAA,MAC9K;AAAA,IACF;AAEA,UAAM,gBAAgB,OAAO,YAAY,CAAC,GAAG;AAC7C,QAAI,kBAAkB,QAAW;AAC/B,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,kBAAc,UAAU,eAAe,OAAO;AAE9C,UAAM,SAAU,MAAM,OAAO,UAAU,QAAQ;AAI/C,eAAW,QAAQ;AAEnB,QAAI;AAEJ,QAAI,OAAO,YAAY,QAAW;AAChC,iBAAW,OAAO;AAAA,IACpB,WAAW,OAAO,aAAa,QAAW;AACxC,iBAAW,OAAO;AAAA,IACpB,OAAO;AACL,YAAM,IAAI;AAAA,QACR,qGAAqG,OAAO,KAAK,MAAiC,EAAE,KAAK,IAAI,KAAK,MAAM;AAAA,MAC1K;AAAA,IACF;AAEA,QAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AACrD,YAAM,IAAI,MAAM,0CAA0C,OAAO,QAAQ,EAAE;AAAA,IAC7E;AAEA,mBAAe,QAAQ;AAEvB,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI;AACF,UAAI,UAAU;AACZ,mBAAW,QAAQ;AAAA,MACrB;AAAA,IACF,QAAQ;AAAA,IAER;AAEA,QAAI,iBAAiB,OAAO;AAC1B,YAAM;AAAA,IACR;AACA,UAAM,IAAI,MAAM,gCAAgC,SAAS,KAAK,OAAO,KAAK,CAAC,EAAE;AAAA,EAC/E;AACF;","names":["value","build"]}
|
|
1
|
+
{"version":3,"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const seen = new WeakSet();\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (seen.has(value)) {\n throw new Error('Contract export contains circular references');\n }\n seen.add(value);\n\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(`Contract export contains getter/setter at key \"${key}\"`);\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw new Error(`Contract export contains function at key \"${key}\"`);\n }\n check((value as Record<string, unknown>)[key]);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw new Error(`Contract export is not JSON-serializable: ${error.message}`);\n }\n throw new Error('Contract export is not JSON-serializable');\n }\n}\n\nfunction createImportAllowlistPlugin(allowlist: ReadonlyArray<string>, entryPath: string): Plugin {\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n const isFromEntryPoint = args.importer === entryPath || args.importer === '<stdin>';\n if (isFromEntryPoint && !isAllowedImport(args.path, allowlist)) {\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as ContractIR.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as ContractIR (should already be normalized)\n * @throws Error if the contract cannot be loaded or is not JSON-serializable\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<ContractIR> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new Error(`Contract file not found: ${entryPath}`);\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw new Error(`Failed to bundle contract file: ${errorMessages}`);\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new Error('No output files generated from bundling');\n }\n\n const disallowedImports: string[] = [];\n if (result.metafile) {\n const inputs = result.metafile.inputs;\n for (const [, inputData] of Object.entries(inputs)) {\n const imports =\n (inputData as { imports?: Array<{ path: string; external?: boolean }> }).imports || [];\n for (const imp of imports) {\n if (\n imp.external &&\n !imp.path.startsWith('.') &&\n !imp.path.startsWith('/') &&\n !isAllowedImport(imp.path, allowlist)\n ) {\n disallowedImports.push(imp.path);\n }\n }\n }\n }\n\n if (disallowedImports.length > 0) {\n throw new Error(\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${disallowedImports.join(', ')}\\n\\nOnly @prisma-next/* packages are allowed in contract files.`,\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new Error('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(`file://${tempFile}`)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new Error(\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw new Error(`Contract export must be an object, got ${typeof contract}`);\n }\n\n validatePurity(contract);\n\n return contract as ContractIR;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Failed to load contract from ${entryPath}: ${String(error)}`);\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,YAAY,YAAY,qBAAqB;AACtD,SAAS,cAAc;AACvB,SAAS,YAAY;AAGrB,SAAS,aAAa;AAMtB,IAAM,oBAAoB,CAAC,gBAAgB;AAE3C,SAAS,gBAAgB,YAAoB,WAA2C;AACtF,aAAW,WAAW,WAAW;AAC/B,QAAI,QAAQ,SAAS,IAAI,GAAG;AAC1B,YAAM,SAAS,QAAQ,MAAM,GAAG,EAAE;AAClC,UAAI,eAAe,UAAU,WAAW,WAAW,GAAG,MAAM,GAAG,GAAG;AAChE,eAAO;AAAA,MACT;AAAA,IACF,WAAW,eAAe,SAAS;AACjC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,OAAsB;AAC5C,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C;AAAA,EACF;AAEA,QAAM,OAAO,oBAAI,QAAQ;AACzB,WAA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|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/cli",
|
|
3
|
-
"version": "0.3.0-dev.
|
|
3
|
+
"version": "0.3.0-dev.19",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"files": [
|
|
@@ -20,10 +20,10 @@
|
|
|
20
20
|
"string-width": "^7.2.0",
|
|
21
21
|
"strip-ansi": "^7.1.2",
|
|
22
22
|
"wrap-ansi": "^9.0.2",
|
|
23
|
-
"@prisma-next/contract": "0.3.0-dev.
|
|
24
|
-
"@prisma-next/core-control-plane": "0.3.0-dev.
|
|
25
|
-
"@prisma-next/
|
|
26
|
-
"@prisma-next/
|
|
23
|
+
"@prisma-next/contract": "0.3.0-dev.19",
|
|
24
|
+
"@prisma-next/core-control-plane": "0.3.0-dev.19",
|
|
25
|
+
"@prisma-next/utils": "0.3.0-dev.19",
|
|
26
|
+
"@prisma-next/emitter": "0.3.0-dev.19"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/node": "24.10.4",
|
|
@@ -31,11 +31,11 @@
|
|
|
31
31
|
"tsup": "8.5.1",
|
|
32
32
|
"typescript": "5.9.3",
|
|
33
33
|
"vitest": "4.0.16",
|
|
34
|
-
"@prisma-next/sql-contract": "0.3.0-dev.
|
|
35
|
-
"@prisma-next/sql-contract-
|
|
36
|
-
"@prisma-next/sql-contract-
|
|
37
|
-
"@prisma-next/sql-operations": "0.3.0-dev.
|
|
38
|
-
"@prisma-next/sql-runtime": "0.3.0-dev.
|
|
34
|
+
"@prisma-next/sql-contract": "0.3.0-dev.19",
|
|
35
|
+
"@prisma-next/sql-contract-ts": "0.3.0-dev.19",
|
|
36
|
+
"@prisma-next/sql-contract-emitter": "0.3.0-dev.19",
|
|
37
|
+
"@prisma-next/sql-operations": "0.3.0-dev.19",
|
|
38
|
+
"@prisma-next/sql-runtime": "0.3.0-dev.19",
|
|
39
39
|
"@prisma-next/test-utils": "0.0.1"
|
|
40
40
|
},
|
|
41
41
|
"exports": {
|
|
@@ -1,21 +1,24 @@
|
|
|
1
1
|
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, relative, resolve } from 'node:path';
|
|
3
3
|
import { errorContractConfigMissing } from '@prisma-next/core-control-plane/errors';
|
|
4
|
-
import {
|
|
4
|
+
import { notOk, ok, type Result } from '@prisma-next/utils/result';
|
|
5
5
|
import { Command } from 'commander';
|
|
6
6
|
import { loadConfig } from '../config-loader';
|
|
7
|
-
import {
|
|
7
|
+
import { createControlClient } from '../control-api/client';
|
|
8
|
+
import type { EmitContractSource, EmitFailure } from '../control-api/types';
|
|
9
|
+
import { CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';
|
|
8
10
|
import { setCommandDescriptions } from '../utils/command-helpers';
|
|
9
|
-
import { parseGlobalFlags } from '../utils/global-flags';
|
|
11
|
+
import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
|
|
10
12
|
import {
|
|
13
|
+
type EmitContractResult,
|
|
11
14
|
formatCommandHelp,
|
|
12
15
|
formatEmitJson,
|
|
13
16
|
formatEmitOutput,
|
|
14
17
|
formatStyledHeader,
|
|
15
18
|
formatSuccessMessage,
|
|
16
19
|
} from '../utils/output';
|
|
20
|
+
import { createProgressAdapter } from '../utils/progress-adapter';
|
|
17
21
|
import { handleResult } from '../utils/result-handler';
|
|
18
|
-
import { withSpinner } from '../utils/spinner';
|
|
19
22
|
|
|
20
23
|
interface ContractEmitOptions {
|
|
21
24
|
readonly config?: string;
|
|
@@ -31,6 +34,176 @@ interface ContractEmitOptions {
|
|
|
31
34
|
readonly 'no-color'?: boolean;
|
|
32
35
|
}
|
|
33
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Maps an EmitFailure to a CliStructuredError for consistent error handling.
|
|
39
|
+
*/
|
|
40
|
+
function mapEmitFailure(failure: EmitFailure): CliStructuredError {
|
|
41
|
+
if (failure.code === 'CONTRACT_SOURCE_INVALID') {
|
|
42
|
+
return errorRuntime(failure.summary, {
|
|
43
|
+
why: failure.why ?? 'Contract source is invalid',
|
|
44
|
+
fix: 'Check your contract source configuration in prisma-next.config.ts',
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (failure.code === 'EMIT_FAILED') {
|
|
49
|
+
return errorRuntime(failure.summary, {
|
|
50
|
+
why: failure.why ?? 'Failed to emit contract',
|
|
51
|
+
fix: 'Check your contract configuration and ensure the source is valid',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Exhaustive check - TypeScript will error if a new code is added but not handled
|
|
56
|
+
const exhaustive: never = failure.code;
|
|
57
|
+
throw new Error(`Unhandled EmitFailure code: ${exhaustive}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Executes the contract emit command and returns a structured Result.
|
|
62
|
+
*/
|
|
63
|
+
async function executeContractEmitCommand(
|
|
64
|
+
options: ContractEmitOptions,
|
|
65
|
+
flags: GlobalFlags,
|
|
66
|
+
startTime: number,
|
|
67
|
+
): Promise<Result<EmitContractResult, CliStructuredError>> {
|
|
68
|
+
// Load config
|
|
69
|
+
let config: Awaited<ReturnType<typeof loadConfig>>;
|
|
70
|
+
try {
|
|
71
|
+
config = await loadConfig(options.config);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
// Convert thrown CliStructuredError to Result
|
|
74
|
+
if (error instanceof CliStructuredError) {
|
|
75
|
+
return notOk(error);
|
|
76
|
+
}
|
|
77
|
+
return notOk(
|
|
78
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
79
|
+
why: 'Failed to load config',
|
|
80
|
+
}),
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Resolve contract from config
|
|
85
|
+
if (!config.contract) {
|
|
86
|
+
return notOk(
|
|
87
|
+
errorContractConfigMissing({
|
|
88
|
+
why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }',
|
|
89
|
+
}),
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Contract config is already normalized by defineConfig() with defaults applied
|
|
94
|
+
const contractConfig = config.contract;
|
|
95
|
+
|
|
96
|
+
// Resolve artifact paths from config (already normalized by defineConfig() with defaults)
|
|
97
|
+
if (!contractConfig.output || !contractConfig.types) {
|
|
98
|
+
return notOk(
|
|
99
|
+
errorContractConfigMissing({
|
|
100
|
+
why: 'Contract config must have output and types paths. This should not happen if defineConfig() was used.',
|
|
101
|
+
}),
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
const outputJsonPath = resolve(contractConfig.output);
|
|
105
|
+
const outputDtsPath = resolve(contractConfig.types);
|
|
106
|
+
|
|
107
|
+
// Output header (only for human-readable output)
|
|
108
|
+
if (flags.json !== 'object' && !flags.quiet) {
|
|
109
|
+
// Normalize config path for display (match contract path format - no ./ prefix)
|
|
110
|
+
const configPath = options.config
|
|
111
|
+
? relative(process.cwd(), resolve(options.config))
|
|
112
|
+
: 'prisma-next.config.ts';
|
|
113
|
+
// Convert absolute paths to relative paths for display
|
|
114
|
+
const contractPath = relative(process.cwd(), outputJsonPath);
|
|
115
|
+
const typesPath = relative(process.cwd(), outputDtsPath);
|
|
116
|
+
const header = formatStyledHeader({
|
|
117
|
+
command: 'contract emit',
|
|
118
|
+
description: 'Write your contract to JSON and sign it',
|
|
119
|
+
url: 'https://pris.ly/contract-emit',
|
|
120
|
+
details: [
|
|
121
|
+
{ label: 'config', value: configPath },
|
|
122
|
+
{ label: 'contract', value: contractPath },
|
|
123
|
+
{ label: 'types', value: typesPath },
|
|
124
|
+
],
|
|
125
|
+
flags,
|
|
126
|
+
});
|
|
127
|
+
console.log(header);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Create control client (no driver needed for emit)
|
|
131
|
+
const client = createControlClient({
|
|
132
|
+
family: config.family,
|
|
133
|
+
target: config.target,
|
|
134
|
+
adapter: config.adapter,
|
|
135
|
+
extensionPacks: config.extensionPacks ?? [],
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// Create progress adapter
|
|
139
|
+
const onProgress = createProgressAdapter({ flags });
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
// Convert user config source to discriminated union
|
|
143
|
+
// Type assertion is safe: we check typeof to determine if it's a function
|
|
144
|
+
const source: EmitContractSource =
|
|
145
|
+
typeof contractConfig.source === 'function'
|
|
146
|
+
? { kind: 'loader', load: contractConfig.source as () => unknown | Promise<unknown> }
|
|
147
|
+
: { kind: 'value', value: contractConfig.source };
|
|
148
|
+
|
|
149
|
+
// Call emit with progress callback
|
|
150
|
+
const result = await client.emit({
|
|
151
|
+
contractConfig: {
|
|
152
|
+
source,
|
|
153
|
+
output: outputJsonPath,
|
|
154
|
+
types: outputDtsPath,
|
|
155
|
+
},
|
|
156
|
+
onProgress,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Handle failures by mapping to CLI structured error
|
|
160
|
+
if (!result.ok) {
|
|
161
|
+
return notOk(mapEmitFailure(result.failure));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Create directories if needed
|
|
165
|
+
mkdirSync(dirname(outputJsonPath), { recursive: true });
|
|
166
|
+
mkdirSync(dirname(outputDtsPath), { recursive: true });
|
|
167
|
+
|
|
168
|
+
// Write the results to files
|
|
169
|
+
writeFileSync(outputJsonPath, result.value.contractJson, 'utf-8');
|
|
170
|
+
writeFileSync(outputDtsPath, result.value.contractDts, 'utf-8');
|
|
171
|
+
|
|
172
|
+
// Add blank line after all async operations if spinners were shown
|
|
173
|
+
if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
|
|
174
|
+
console.log('');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Convert success result to CLI output format
|
|
178
|
+
const emitResult: EmitContractResult = {
|
|
179
|
+
coreHash: result.value.coreHash,
|
|
180
|
+
profileHash: result.value.profileHash,
|
|
181
|
+
outDir: dirname(outputJsonPath),
|
|
182
|
+
files: {
|
|
183
|
+
json: outputJsonPath,
|
|
184
|
+
dts: outputDtsPath,
|
|
185
|
+
},
|
|
186
|
+
timings: { total: Date.now() - startTime },
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
return ok(emitResult);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
// Use static type guard to work across module boundaries
|
|
192
|
+
if (CliStructuredError.is(error)) {
|
|
193
|
+
return notOk(error);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Wrap unexpected errors
|
|
197
|
+
return notOk(
|
|
198
|
+
errorUnexpected('Unexpected error during contract emit', {
|
|
199
|
+
why: error instanceof Error ? error.message : String(error),
|
|
200
|
+
}),
|
|
201
|
+
);
|
|
202
|
+
} finally {
|
|
203
|
+
await client.close();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
34
207
|
export function createContractEmitCommand(): Command {
|
|
35
208
|
const command = new Command('emit');
|
|
36
209
|
setCommandDescriptions(
|
|
@@ -57,105 +230,9 @@ export function createContractEmitCommand(): Command {
|
|
|
57
230
|
.option('--no-color', 'Disable color output')
|
|
58
231
|
.action(async (options: ContractEmitOptions) => {
|
|
59
232
|
const flags = parseGlobalFlags(options);
|
|
233
|
+
const startTime = Date.now();
|
|
60
234
|
|
|
61
|
-
const result = await
|
|
62
|
-
// Load config
|
|
63
|
-
const config = await loadConfig(options.config);
|
|
64
|
-
|
|
65
|
-
// Resolve contract from config
|
|
66
|
-
if (!config.contract) {
|
|
67
|
-
throw errorContractConfigMissing({
|
|
68
|
-
why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }',
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// Contract config is already normalized by defineConfig() with defaults applied
|
|
73
|
-
const contractConfig = config.contract;
|
|
74
|
-
|
|
75
|
-
// Resolve artifact paths from config (already normalized by defineConfig() with defaults)
|
|
76
|
-
if (!contractConfig.output || !contractConfig.types) {
|
|
77
|
-
throw errorContractConfigMissing({
|
|
78
|
-
why: 'Contract config must have output and types paths. This should not happen if defineConfig() was used.',
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
const outputJsonPath = resolve(contractConfig.output);
|
|
82
|
-
const outputDtsPath = resolve(contractConfig.types);
|
|
83
|
-
|
|
84
|
-
// Output header (only for human-readable output)
|
|
85
|
-
if (flags.json !== 'object' && !flags.quiet) {
|
|
86
|
-
// Normalize config path for display (match contract path format - no ./ prefix)
|
|
87
|
-
const configPath = options.config
|
|
88
|
-
? relative(process.cwd(), resolve(options.config))
|
|
89
|
-
: 'prisma-next.config.ts';
|
|
90
|
-
// Convert absolute paths to relative paths for display
|
|
91
|
-
const contractPath = relative(process.cwd(), outputJsonPath);
|
|
92
|
-
const typesPath = relative(process.cwd(), outputDtsPath);
|
|
93
|
-
const header = formatStyledHeader({
|
|
94
|
-
command: 'contract emit',
|
|
95
|
-
description: 'Write your contract to JSON and sign it',
|
|
96
|
-
url: 'https://pris.ly/contract-emit',
|
|
97
|
-
details: [
|
|
98
|
-
{ label: 'config', value: configPath },
|
|
99
|
-
{ label: 'contract', value: contractPath },
|
|
100
|
-
{ label: 'types', value: typesPath },
|
|
101
|
-
],
|
|
102
|
-
flags,
|
|
103
|
-
});
|
|
104
|
-
console.log(header);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const stack = createControlPlaneStack({
|
|
108
|
-
target: config.target,
|
|
109
|
-
adapter: config.adapter,
|
|
110
|
-
driver: config.driver,
|
|
111
|
-
extensionPacks: config.extensionPacks,
|
|
112
|
-
});
|
|
113
|
-
const familyInstance = config.family.create(stack);
|
|
114
|
-
|
|
115
|
-
// Resolve contract source from config (user's config handles loading)
|
|
116
|
-
let contractRaw: unknown;
|
|
117
|
-
if (typeof contractConfig.source === 'function') {
|
|
118
|
-
contractRaw = await contractConfig.source();
|
|
119
|
-
} else {
|
|
120
|
-
contractRaw = contractConfig.source;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Call emitContract on family instance (handles stripping mappings and validation internally)
|
|
124
|
-
const emitResult = await withSpinner(
|
|
125
|
-
() => familyInstance.emitContract({ contractIR: contractRaw }),
|
|
126
|
-
{
|
|
127
|
-
message: 'Emitting contract...',
|
|
128
|
-
flags,
|
|
129
|
-
},
|
|
130
|
-
);
|
|
131
|
-
|
|
132
|
-
// Create directories if needed
|
|
133
|
-
mkdirSync(dirname(outputJsonPath), { recursive: true });
|
|
134
|
-
mkdirSync(dirname(outputDtsPath), { recursive: true });
|
|
135
|
-
|
|
136
|
-
// Write the results to files
|
|
137
|
-
writeFileSync(outputJsonPath, emitResult.contractJson, 'utf-8');
|
|
138
|
-
writeFileSync(outputDtsPath, emitResult.contractDts, 'utf-8');
|
|
139
|
-
|
|
140
|
-
// Add blank line after all async operations if spinners were shown
|
|
141
|
-
if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
|
|
142
|
-
console.log('');
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Return result with file paths for output formatting
|
|
146
|
-
return {
|
|
147
|
-
coreHash: emitResult.coreHash,
|
|
148
|
-
profileHash: emitResult.profileHash,
|
|
149
|
-
outDir: dirname(outputJsonPath),
|
|
150
|
-
files: {
|
|
151
|
-
json: outputJsonPath,
|
|
152
|
-
dts: outputDtsPath,
|
|
153
|
-
},
|
|
154
|
-
timings: {
|
|
155
|
-
total: 0, // Timing is handled by emitContract internally if needed
|
|
156
|
-
},
|
|
157
|
-
};
|
|
158
|
-
});
|
|
235
|
+
const result = await executeContractEmitCommand(options, flags, startTime);
|
|
159
236
|
|
|
160
237
|
// Handle result - formats output and returns exit code
|
|
161
238
|
const exitCode = handleResult(result, flags, (emitResult) => {
|