prisma-next 0.5.0-dev.11 → 0.5.0-dev.13

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.
Files changed (81) hide show
  1. package/dist/cli.mjs +7 -14
  2. package/dist/cli.mjs.map +1 -1
  3. package/dist/{client-faKQqcix.mjs → client-enZIahga.mjs} +5 -5
  4. package/dist/{client-faKQqcix.mjs.map → client-enZIahga.mjs.map} +1 -1
  5. package/dist/commands/contract-emit.d.mts.map +1 -1
  6. package/dist/commands/contract-emit.mjs +2 -7
  7. package/dist/commands/contract-infer.mjs +2 -8
  8. package/dist/commands/db-init.mjs +7 -8
  9. package/dist/commands/db-init.mjs.map +1 -1
  10. package/dist/commands/db-schema.mjs +5 -8
  11. package/dist/commands/db-schema.mjs.map +1 -1
  12. package/dist/commands/db-sign.mjs +6 -7
  13. package/dist/commands/db-sign.mjs.map +1 -1
  14. package/dist/commands/db-update.mjs +7 -8
  15. package/dist/commands/db-update.mjs.map +1 -1
  16. package/dist/commands/db-verify.mjs +8 -9
  17. package/dist/commands/db-verify.mjs.map +1 -1
  18. package/dist/commands/migration-apply.mjs +6 -7
  19. package/dist/commands/migration-apply.mjs.map +1 -1
  20. package/dist/commands/migration-new.mjs +6 -6
  21. package/dist/commands/migration-plan.mjs +7 -7
  22. package/dist/commands/migration-ref.d.mts +1 -1
  23. package/dist/commands/migration-ref.mjs +3 -3
  24. package/dist/commands/migration-show.d.mts +1 -1
  25. package/dist/commands/migration-show.mjs +5 -5
  26. package/dist/commands/migration-status.mjs +2 -7
  27. package/dist/{config-loader-C25b63rJ.mjs → config-loader-ih8ViDb_.mjs} +2 -2
  28. package/dist/config-loader-ih8ViDb_.mjs.map +1 -0
  29. package/dist/config-loader.mjs +1 -1
  30. package/dist/contract-emit-DWtGQYCD.mjs +150 -0
  31. package/dist/contract-emit-DWtGQYCD.mjs.map +1 -0
  32. package/dist/contract-emit-LjzCoicC.mjs +4 -0
  33. package/dist/contract-emit-RZBWzkop.mjs +329 -0
  34. package/dist/contract-emit-RZBWzkop.mjs.map +1 -0
  35. package/dist/{contract-enrichment-CAOELa-H.mjs → contract-enrichment-4Ptgw3Pe.mjs} +1 -1
  36. package/dist/{contract-enrichment-CAOELa-H.mjs.map → contract-enrichment-4Ptgw3Pe.mjs.map} +1 -1
  37. package/dist/{contract-infer-BgnsSkGp.mjs → contract-infer-BjzkcwQt.mjs} +5 -5
  38. package/dist/{contract-infer-BgnsSkGp.mjs.map → contract-infer-BjzkcwQt.mjs.map} +1 -1
  39. package/dist/exports/control-api.d.mts +41 -16
  40. package/dist/exports/control-api.d.mts.map +1 -1
  41. package/dist/exports/control-api.mjs +5 -7
  42. package/dist/exports/index.mjs +3 -8
  43. package/dist/exports/index.mjs.map +1 -1
  44. package/dist/exports/init-output.mjs +1 -1
  45. package/dist/{extract-operation-statements-DsFfxXVZ.mjs → extract-operation-statements-CU-Pp4-N.mjs} +2 -2
  46. package/dist/{extract-operation-statements-DsFfxXVZ.mjs.map → extract-operation-statements-CU-Pp4-N.mjs.map} +1 -1
  47. package/dist/{extract-sql-ddl-D9UbZDyz.mjs → extract-sql-ddl-Bm0Mm0IT.mjs} +1 -1
  48. package/dist/{extract-sql-ddl-D9UbZDyz.mjs.map → extract-sql-ddl-Bm0Mm0IT.mjs.map} +1 -1
  49. package/dist/{framework-components-C6el-5x_.mjs → framework-components-Bgcre3Z6.mjs} +1 -1
  50. package/dist/{framework-components-C6el-5x_.mjs.map → framework-components-Bgcre3Z6.mjs.map} +1 -1
  51. package/dist/{init-jf33mNQ6.mjs → init-BKgjxw6r.mjs} +5 -5
  52. package/dist/{init-jf33mNQ6.mjs.map → init-BKgjxw6r.mjs.map} +1 -1
  53. package/dist/{inspect-live-schema-yCu0JT0I.mjs → inspect-live-schema-QklSDLt_.mjs} +5 -5
  54. package/dist/{inspect-live-schema-yCu0JT0I.mjs.map → inspect-live-schema-QklSDLt_.mjs.map} +1 -1
  55. package/dist/migration-cli.mjs +2 -2
  56. package/dist/{migration-command-scaffold-B8HAEGhQ.mjs → migration-command-scaffold-BfloSWPZ.mjs} +6 -6
  57. package/dist/{migration-command-scaffold-B8HAEGhQ.mjs.map → migration-command-scaffold-BfloSWPZ.mjs.map} +1 -1
  58. package/dist/{migration-status-8QUxCJHE.mjs → migration-status-C5VYA5r9.mjs} +7 -7
  59. package/dist/{migration-status-8QUxCJHE.mjs.map → migration-status-C5VYA5r9.mjs.map} +1 -1
  60. package/dist/{migrations-CKRMAKka.mjs → migrations-CSaDHNpB.mjs} +2 -2
  61. package/dist/{migrations-CKRMAKka.mjs.map → migrations-CSaDHNpB.mjs.map} +1 -1
  62. package/dist/{output-BpcQrnnq.mjs → output-BiO7kt87.mjs} +1 -1
  63. package/dist/{output-BpcQrnnq.mjs.map → output-BiO7kt87.mjs.map} +1 -1
  64. package/dist/{progress-adapter-DvQWB1nK.mjs → progress-adapter-DgRGldpT.mjs} +1 -1
  65. package/dist/{progress-adapter-DvQWB1nK.mjs.map → progress-adapter-DgRGldpT.mjs.map} +1 -1
  66. package/dist/{result-handler-CuhZ3kNu.mjs → result-handler-BmVh8AeV.mjs} +4 -4
  67. package/dist/{result-handler-CuhZ3kNu.mjs.map → result-handler-BmVh8AeV.mjs.map} +1 -1
  68. package/dist/{terminal-ui-C3ZLwQxK.mjs → terminal-ui-u2YgKghu.mjs} +1 -1
  69. package/dist/{terminal-ui-C3ZLwQxK.mjs.map → terminal-ui-u2YgKghu.mjs.map} +1 -1
  70. package/dist/{verify-Bkycc-Tf.mjs → verify-BumcH6Ry.mjs} +2 -2
  71. package/dist/{verify-Bkycc-Tf.mjs.map → verify-BumcH6Ry.mjs.map} +1 -1
  72. package/package.json +10 -10
  73. package/dist/config-loader-C25b63rJ.mjs.map +0 -1
  74. package/dist/contract-emit-B9wkchud.mjs +0 -6
  75. package/dist/contract-emit-Cf3fjDL6.mjs +0 -195
  76. package/dist/contract-emit-Cf3fjDL6.mjs.map +0 -1
  77. package/dist/contract-emit-PeB96eHy.mjs +0 -122
  78. package/dist/contract-emit-PeB96eHy.mjs.map +0 -1
  79. package/dist/validate-contract-deps-B_Cs29TL.mjs +0 -37
  80. package/dist/validate-contract-deps-B_Cs29TL.mjs.map +0 -1
  81. /package/dist/{cli-errors-D2NPMaxW.d.mts → cli-errors-BJLUczXT.d.mts} +0 -0
@@ -1,18 +1,18 @@
1
- import { t as loadConfig } from "../config-loader-C25b63rJ.mjs";
1
+ import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
2
  import { _ as errorUnexpected, a as errorContractValidationFailed, f as errorMigrationPlanningFailed, h as errorTargetMigrationNotSupported, l as errorFileNotFound, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as assertFrameworkComponentsCompatible } from "../framework-components-C6el-5x_.mjs";
4
- import { t as extractSqlDdl } from "../extract-sql-ddl-D9UbZDyz.mjs";
5
- import { t as TerminalUI } from "../terminal-ui-C3ZLwQxK.mjs";
6
- import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, i as loadMigrationPackages, m as parseGlobalFlags, n as addGlobalOptions, r as getTargetMigrations, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-CuhZ3kNu.mjs";
3
+ import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bgcre3Z6.mjs";
4
+ import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
5
+ import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, i as loadMigrationPackages, m as parseGlobalFlags, n as addGlobalOptions, r as getTargetMigrations, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-BmVh8AeV.mjs";
6
+ import { t as extractSqlDdl } from "../extract-sql-ddl-Bm0Mm0IT.mjs";
7
7
  import { Command } from "commander";
8
8
  import { getEmittedArtifactPaths } from "@prisma-next/emitter";
9
9
  import { notOk, ok } from "@prisma-next/utils/result";
10
10
  import { join, relative } from "pathe";
11
- import { createControlStack } from "@prisma-next/framework-components/control";
12
- import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
13
11
  import { readFile } from "node:fs/promises";
12
+ import { createControlStack } from "@prisma-next/framework-components/control";
14
13
  import { copyFilesWithRename, formatMigrationDirName, writeMigrationPackage } from "@prisma-next/migration-tools/io";
15
14
  import { findLatestMigration } from "@prisma-next/migration-tools/migration-graph";
15
+ import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
16
16
  import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
17
17
  import { computeMigrationHash } from "@prisma-next/migration-tools/hash";
18
18
  import { writeMigrationTs } from "@prisma-next/migration-tools/migration-ts";
@@ -1,4 +1,4 @@
1
- import { t as CliStructuredError } from "../cli-errors-D2NPMaxW.mjs";
1
+ import { t as CliStructuredError } from "../cli-errors-BJLUczXT.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { RefEntry } from "@prisma-next/migration-tools/refs";
@@ -1,7 +1,7 @@
1
- import { t as loadConfig } from "../config-loader-C25b63rJ.mjs";
1
+ import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
2
  import { _ as errorUnexpected, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as TerminalUI } from "../terminal-ui-C3ZLwQxK.mjs";
4
- import { c as resolveMigrationPaths, h as formatCommandHelp, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-CuhZ3kNu.mjs";
3
+ import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
4
+ import { c as resolveMigrationPaths, h as formatCommandHelp, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-BmVh8AeV.mjs";
5
5
  import { Command } from "commander";
6
6
  import { notOk, ok } from "@prisma-next/utils/result";
7
7
  import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
@@ -1,4 +1,4 @@
1
- import { t as CliStructuredError } from "../cli-errors-D2NPMaxW.mjs";
1
+ import { t as CliStructuredError } from "../cli-errors-BJLUczXT.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { MigrationPackage } from "@prisma-next/migration-tools/package";
@@ -1,9 +1,9 @@
1
- import { t as loadConfig } from "../config-loader-C25b63rJ.mjs";
1
+ import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
2
  import { _ as errorUnexpected, m as errorRuntime, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as extractOperationStatements } from "../extract-operation-statements-DsFfxXVZ.mjs";
4
- import { t as TerminalUI } from "../terminal-ui-C3ZLwQxK.mjs";
5
- import { _ as formatStyledHeader, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-CuhZ3kNu.mjs";
6
- import { a as formatMigrationShowOutput } from "../migrations-CKRMAKka.mjs";
3
+ import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
4
+ import { _ as formatStyledHeader, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-BmVh8AeV.mjs";
5
+ import { t as extractOperationStatements } from "../extract-operation-statements-CU-Pp4-N.mjs";
6
+ import { a as formatMigrationShowOutput } from "../migrations-CSaDHNpB.mjs";
7
7
  import { Command } from "commander";
8
8
  import { notOk, ok } from "@prisma-next/utils/result";
9
9
  import { relative, resolve } from "pathe";
@@ -1,9 +1,4 @@
1
- import "../config-loader-C25b63rJ.mjs";
2
- import "../cli-errors-By1iVE3z.mjs";
3
- import "../framework-components-C6el-5x_.mjs";
4
- import "../client-faKQqcix.mjs";
5
- import "../terminal-ui-C3ZLwQxK.mjs";
6
- import "../result-handler-CuhZ3kNu.mjs";
7
- import { n as deriveEdgeStatuses, t as createMigrationStatusCommand } from "../migration-status-8QUxCJHE.mjs";
1
+ import "../config-loader-ih8ViDb_.mjs";
2
+ import { n as deriveEdgeStatuses, t as createMigrationStatusCommand } from "../migration-status-C5VYA5r9.mjs";
8
3
 
9
4
  export { createMigrationStatusCommand, deriveEdgeStatuses };
@@ -1,8 +1,8 @@
1
1
  import { getEmittedArtifactPaths } from "@prisma-next/emitter";
2
2
  import { errorConfigFileNotFound, errorConfigValidation, errorUnexpected } from "@prisma-next/errors/control";
3
+ import { ifDefined } from "@prisma-next/utils/defined";
3
4
  import { dirname, resolve } from "pathe";
4
5
  import { ConfigValidationError, validateConfig } from "@prisma-next/config/config-validation";
5
- import { ifDefined } from "@prisma-next/utils/defined";
6
6
  import { loadConfig } from "c12";
7
7
  import { normalizeContractConfig } from "@prisma-next/config/config-types";
8
8
 
@@ -87,4 +87,4 @@ async function loadConfig$1(configPath) {
87
87
 
88
88
  //#endregion
89
89
  export { loadConfig$1 as t };
90
- //# sourceMappingURL=config-loader-C25b63rJ.mjs.map
90
+ //# sourceMappingURL=config-loader-ih8ViDb_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-loader-ih8ViDb_.mjs","names":["emittedArtifactPaths: ReturnType<typeof getEmittedArtifactPaths>","loadConfigC12","loadConfig"],"sources":["../src/config-path-validation.ts","../src/config-loader.ts"],"sourcesContent":["import {\n type ContractSourceProvider,\n normalizeContractConfig,\n type PrismaNextConfig,\n} from '@prisma-next/config/config-types';\nimport { ConfigValidationError } from '@prisma-next/config/config-validation';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { resolve } from 'pathe';\n\nfunction throwValidation(field: string, why: string): never {\n throw new ConfigValidationError(field, why);\n}\n\nfunction finalizeContractSource(\n source: ContractSourceProvider,\n configDir: string,\n): ContractSourceProvider {\n const resolvedInputs = source.inputs?.map((input) => resolve(configDir, input));\n if (resolvedInputs === undefined) {\n return source;\n }\n\n return {\n ...source,\n inputs: resolvedInputs,\n };\n}\n\nfunction validateNoOutputsAreInputs(\n inputs: readonly string[] | undefined,\n output: string | undefined,\n): void {\n if (inputs === undefined || output === undefined) {\n return;\n }\n\n let emittedArtifactPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n emittedArtifactPaths = getEmittedArtifactPaths(output);\n } catch (error) {\n throwValidation('contract.output', error instanceof Error ? error.message : String(error));\n }\n\n const emittedPaths = new Set([emittedArtifactPaths.jsonPath, emittedArtifactPaths.dtsPath]);\n\n for (const input of inputs) {\n if (emittedPaths.has(input)) {\n throwValidation(\n 'contract.source.inputs[]',\n 'Config.contract.source.inputs must not include emitted artifact paths derived from contract.output',\n );\n }\n }\n}\n\nexport function finalizeConfig(config: PrismaNextConfig, configDir: string): PrismaNextConfig {\n if (!config.contract) {\n return config;\n }\n const contract = normalizeContractConfig(config.contract);\n const source = finalizeContractSource(contract.source, configDir);\n const output = resolve(configDir, contract.output);\n\n validateNoOutputsAreInputs(source.inputs, output);\n\n return {\n ...config,\n contract: {\n ...contract,\n source,\n output,\n },\n };\n}\n","import type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport { ConfigValidationError, validateConfig } from '@prisma-next/config/config-validation';\nimport {\n errorConfigFileNotFound,\n errorConfigValidation,\n errorUnexpected,\n} from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { loadConfig as loadConfigC12 } from 'c12';\nimport { dirname, resolve } from 'pathe';\nimport { finalizeConfig } from './config-path-validation';\n\nasync function loadValidatedConfig(configPath?: string): Promise<PrismaNextConfig> {\n const cwd = process.cwd();\n const resolvedConfigPath = configPath ? resolve(cwd, configPath) : undefined;\n const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;\n\n const result = await loadConfigC12<PrismaNextConfig>({\n name: 'prisma-next',\n ...ifDefined('configFile', resolvedConfigPath),\n cwd: configCwd,\n });\n\n // When a specific config file was requested, verify it was actually loaded\n // (c12 falls back to searching by name if the specified file doesn't exist)\n if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {\n throw errorConfigFileNotFound(resolvedConfigPath);\n }\n\n // Check if config is missing or empty (c12 may return empty object when file doesn't exist)\n if (!result.config || Object.keys(result.config).length === 0) {\n // Use c12's configFile if available, otherwise use explicit configPath, otherwise omit path\n const displayPath = result.configFile || resolvedConfigPath || configPath;\n throw errorConfigFileNotFound(displayPath);\n }\n\n // Validate config structure\n validateConfig(result.config);\n\n const loadedConfigDir = result.configFile ? dirname(result.configFile) : configCwd;\n return finalizeConfig(result.config, loadedConfigDir);\n}\n\n/**\n * Loads the Prisma Next config from a TypeScript file.\n * Supports both default export and named export.\n * Uses c12 to automatically handle TypeScript compilation and config file discovery.\n *\n * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.\n * @returns The loaded config object.\n * @throws Error if config file doesn't exist or is invalid.\n */\nexport async function loadConfig(configPath?: string): Promise<PrismaNextConfig> {\n try {\n return await loadValidatedConfig(configPath);\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw errorConfigValidation(error.field, {\n why: error.why,\n });\n }\n\n // Re-throw structured errors as-is\n if (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code: string }).code === 'string'\n ) {\n throw error;\n }\n\n if (error instanceof Error) {\n // Check for file not found errors\n if (\n error.message.includes('not found') ||\n error.message.includes('Cannot find') ||\n error.message.includes('ENOENT')\n ) {\n // Use resolved path if available, otherwise use original configPath\n const displayPath = configPath ? resolve(process.cwd(), configPath) : undefined;\n throw errorConfigFileNotFound(displayPath, {\n why: error.message,\n });\n }\n // For other errors, wrap in unexpected error\n throw errorUnexpected(error.message, {\n why: `Failed to load config: ${error.message}`,\n });\n }\n throw errorUnexpected(String(error));\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,gBAAgB,OAAe,KAAoB;AAC1D,OAAM,IAAI,sBAAsB,OAAO,IAAI;;AAG7C,SAAS,uBACP,QACA,WACwB;CACxB,MAAM,iBAAiB,OAAO,QAAQ,KAAK,UAAU,QAAQ,WAAW,MAAM,CAAC;AAC/E,KAAI,mBAAmB,OACrB,Q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Ae,OAAO,QAAQ,gBAAgB;;;;;;;;;;;AAYvD,eAAsBC,aAAW,YAAgD;AAC/E,KAAI;AACF,SAAO,MAAM,oBAAoB,WAAW;UACrC,OAAO;AACd,MAAI,iBAAiB,sBACnB,OAAM,sBAAsB,MAAM,OAAO,EACvC,KAAK,MAAM,KACZ,CAAC;AAIJ,MACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA2B,SAAS,SAE5C,OAAM;AAGR,MAAI,iBAAiB,OAAO;AAE1B,OACE,MAAM,QAAQ,SAAS,YAAY,IACnC,MAAM,QAAQ,SAAS,cAAc,IACrC,MAAM,QAAQ,SAAS,SAAS,CAIhC,OAAM,wBADc,aAAa,QAAQ,QAAQ,KAAK,EAAE,WAAW,GAAG,QAC3B,EACzC,KAAK,MAAM,SACZ,CAAC;AAGJ,SAAM,gBAAgB,MAAM,SAAS,EACnC,KAAK,0BAA0B,MAAM,WACtC,CAAC;;AAEJ,QAAM,gBAAgB,OAAO,MAAM,CAAC"}
@@ -1,3 +1,3 @@
1
- import { t as loadConfig } from "./config-loader-C25b63rJ.mjs";
1
+ import { t as loadConfig } from "./config-loader-ih8ViDb_.mjs";
2
2
 
3
3
  export { loadConfig };
@@ -0,0 +1,150 @@
1
+ import { t as loadConfig } from "./config-loader-ih8ViDb_.mjs";
2
+ import { _ as errorUnexpected$1, t as CliStructuredError$1 } from "./cli-errors-By1iVE3z.mjs";
3
+ import { t as executeContractEmit } from "./contract-emit-RZBWzkop.mjs";
4
+ import { s as isVerbose, t as TerminalUI } from "./terminal-ui-u2YgKghu.mjs";
5
+ import { _ as formatStyledHeader, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions, v as formatSuccessMessage } from "./result-handler-BmVh8AeV.mjs";
6
+ import { t as createProgressAdapter } from "./progress-adapter-DgRGldpT.mjs";
7
+ import { Command } from "commander";
8
+ import { getEmittedArtifactPaths } from "@prisma-next/emitter";
9
+ import { errorContractConfigMissing } from "@prisma-next/errors/control";
10
+ import { ifDefined } from "@prisma-next/utils/defined";
11
+ import { notOk, ok } from "@prisma-next/utils/result";
12
+ import { dirname, relative, resolve } from "pathe";
13
+
14
+ //#region src/utils/formatters/emit.ts
15
+ /**
16
+ * Formats human-readable output for contract emit.
17
+ */
18
+ function formatEmitOutput(result, flags) {
19
+ if (flags.quiet) return "";
20
+ const lines = [];
21
+ const jsonPath = relative(process.cwd(), result.files.json);
22
+ const dtsPath = relative(process.cwd(), result.files.dts);
23
+ lines.push(`✔ Emitted contract.json → ${jsonPath}`);
24
+ lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);
25
+ lines.push(` storageHash: ${result.storageHash}`);
26
+ if (result.executionHash) lines.push(` executionHash: ${result.executionHash}`);
27
+ if (result.profileHash) lines.push(` profileHash: ${result.profileHash}`);
28
+ if (isVerbose(flags, 1)) lines.push(` Total time: ${result.timings.total}ms`);
29
+ return lines.join("\n");
30
+ }
31
+ /**
32
+ * Formats JSON output for contract emit.
33
+ */
34
+ function formatEmitJson(result) {
35
+ const output = {
36
+ ok: true,
37
+ storageHash: result.storageHash,
38
+ ...ifDefined("executionHash", result.executionHash),
39
+ ...result.profileHash ? { profileHash: result.profileHash } : {},
40
+ outDir: result.outDir,
41
+ files: result.files,
42
+ timings: result.timings
43
+ };
44
+ return JSON.stringify(output, null, 2);
45
+ }
46
+
47
+ //#endregion
48
+ //#region src/commands/contract-emit.ts
49
+ /**
50
+ * Pre-load the config just to compute display paths for the styled header. The
51
+ * actual emit work goes through `executeContractEmit`, which loads the config
52
+ * itself; the redundant load here is bounded and lets the header render before
53
+ * the emit spans start.
54
+ */
55
+ async function resolveHeaderPaths(configOption) {
56
+ const displayConfigPath = configOption ? relative(process.cwd(), resolve(configOption)) : "prisma-next.config.ts";
57
+ let config;
58
+ try {
59
+ config = await loadConfig(configOption);
60
+ } catch (error) {
61
+ if (error instanceof CliStructuredError$1) return notOk(error);
62
+ return notOk(errorUnexpected$1(error instanceof Error ? error.message : String(error), { why: "Failed to load config" }));
63
+ }
64
+ if (!config.contract?.output) return notOk(errorContractConfigMissing({ why: "Config.contract.output is required for emit. Define it in your config: contract: { source: ..., output: ... }" }));
65
+ try {
66
+ const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = getEmittedArtifactPaths(config.contract.output);
67
+ return ok({
68
+ displayConfigPath,
69
+ outputJsonPath,
70
+ outputDtsPath
71
+ });
72
+ } catch (error) {
73
+ return notOk(errorContractConfigMissing({ why: error instanceof Error ? error.message : String(error) }));
74
+ }
75
+ }
76
+ async function executeContractEmitCommand(options, flags, ui, startTime) {
77
+ const headerPathsResult = await resolveHeaderPaths(options.config);
78
+ if (!headerPathsResult.ok) return headerPathsResult;
79
+ const { displayConfigPath, outputJsonPath, outputDtsPath } = headerPathsResult.value;
80
+ if (!flags.json && !flags.quiet) ui.stderr(formatStyledHeader({
81
+ command: "contract emit",
82
+ description: "Emit your contract artifacts",
83
+ url: "https://pris.ly/contract-emit",
84
+ details: [
85
+ {
86
+ label: "config",
87
+ value: displayConfigPath
88
+ },
89
+ {
90
+ label: "contract",
91
+ value: relative(process.cwd(), outputJsonPath)
92
+ },
93
+ {
94
+ label: "types",
95
+ value: relative(process.cwd(), outputDtsPath)
96
+ }
97
+ ],
98
+ flags
99
+ }));
100
+ const onProgress = createProgressAdapter({
101
+ ui,
102
+ flags
103
+ });
104
+ const configPath = options.config ? resolve(options.config) : "prisma-next.config.ts";
105
+ let result;
106
+ try {
107
+ result = await executeContractEmit({
108
+ configPath,
109
+ onProgress
110
+ });
111
+ } catch (error) {
112
+ if (CliStructuredError$1.is(error)) return notOk(error);
113
+ return notOk(errorUnexpected$1("Unexpected error during contract emit", { why: error instanceof Error ? error.message : String(error) }));
114
+ }
115
+ if (result.validationWarning) ui.warn(result.validationWarning);
116
+ return ok({
117
+ storageHash: result.storageHash,
118
+ ...ifDefined("executionHash", result.executionHash),
119
+ profileHash: result.profileHash,
120
+ outDir: dirname(result.files.json),
121
+ files: result.files,
122
+ timings: { total: Date.now() - startTime }
123
+ });
124
+ }
125
+ function createContractEmitCommand() {
126
+ const command = new Command("emit");
127
+ setCommandDescriptions(command, "Emit your contract artifacts", "Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\ncontract.d.ts. The contract.json contains the canonical contract structure, and\ncontract.d.ts provides TypeScript types for type-safe query building.");
128
+ setCommandExamples(command, ["prisma-next contract emit", "prisma-next contract emit --config ./custom-config.ts"]);
129
+ addGlobalOptions(command).option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
130
+ const flags = parseGlobalFlags(options);
131
+ const ui = new TerminalUI({
132
+ color: flags.color,
133
+ interactive: flags.interactive
134
+ });
135
+ const exitCode = handleResult(await executeContractEmitCommand(options, flags, ui, Date.now()), flags, ui, (emitResult) => {
136
+ if (flags.json) ui.output(formatEmitJson(emitResult));
137
+ else {
138
+ const output = formatEmitOutput(emitResult, flags);
139
+ if (output) ui.log(output);
140
+ if (!flags.quiet) ui.success(formatSuccessMessage(flags));
141
+ }
142
+ });
143
+ process.exit(exitCode);
144
+ });
145
+ return command;
146
+ }
147
+
148
+ //#endregion
149
+ export { createContractEmitCommand as t };
150
+ //# sourceMappingURL=contract-emit-DWtGQYCD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-emit-DWtGQYCD.mjs","names":["lines: string[]","config: Awaited<ReturnType<typeof loadConfig>>","CliStructuredError","errorUnexpected","result: ContractEmitResult"],"sources":["../src/utils/formatters/emit.ts","../src/commands/contract-emit.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { relative } from 'pathe';\n\nimport type { GlobalFlags } from '../global-flags';\nimport { isVerbose } from './helpers';\n\n// EmitContractResult type for CLI output formatting (includes file paths)\nexport interface EmitContractResult {\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n readonly outDir: string;\n readonly files: {\n readonly json: string;\n readonly dts: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for contract emit.\n */\nexport function formatEmitOutput(result: EmitContractResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n // Convert absolute paths to relative paths from cwd\n const jsonPath = relative(process.cwd(), result.files.json);\n const dtsPath = relative(process.cwd(), result.files.dts);\n\n lines.push(`✔ Emitted contract.json → ${jsonPath}`);\n lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);\n lines.push(` storageHash: ${result.storageHash}`);\n if (result.executionHash) {\n lines.push(` executionHash: ${result.executionHash}`);\n }\n if (result.profileHash) {\n lines.push(` profileHash: ${result.profileHash}`);\n }\n if (isVerbose(flags, 1)) {\n lines.push(` Total time: ${result.timings.total}ms`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for contract emit.\n */\nexport function formatEmitJson(result: EmitContractResult): string {\n const output = {\n ok: true,\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n ...(result.profileHash ? { profileHash: result.profileHash } : {}),\n outDir: result.outDir,\n files: result.files,\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { errorContractConfigMissing } from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { executeContractEmit } from '../control-api/operations/contract-emit';\nimport type { ContractEmitResult } from '../control-api/types';\nimport { CliStructuredError, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n type EmitContractResult,\n formatEmitJson,\n formatEmitOutput,\n} from '../utils/formatters/emit';\nimport { formatStyledHeader, formatSuccessMessage } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface ContractEmitOptions extends CommonCommandOptions {\n readonly config?: string;\n}\n\ninterface HeaderPaths {\n readonly displayConfigPath: string;\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n}\n\n/**\n * Pre-load the config just to compute display paths for the styled header. The\n * actual emit work goes through `executeContractEmit`, which loads the config\n * itself; the redundant load here is bounded and lets the header render before\n * the emit spans start.\n */\nasync function resolveHeaderPaths(\n configOption: string | undefined,\n): Promise<Result<HeaderPaths, CliStructuredError>> {\n const displayConfigPath = configOption\n ? relative(process.cwd(), resolve(configOption))\n : 'prisma-next.config.ts';\n\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(configOption);\n } catch (error) {\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to load config',\n }),\n );\n }\n\n if (!config.contract?.output) {\n return notOk(\n errorContractConfigMissing({\n why: 'Config.contract.output is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n }),\n );\n }\n\n try {\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = getEmittedArtifactPaths(\n config.contract.output,\n );\n return ok({ displayConfigPath, outputJsonPath, outputDtsPath });\n } catch (error) {\n return notOk(\n errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n}\n\nasync function executeContractEmitCommand(\n options: ContractEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<EmitContractResult, CliStructuredError>> {\n const headerPathsResult = await resolveHeaderPaths(options.config);\n if (!headerPathsResult.ok) {\n return headerPathsResult;\n }\n const { displayConfigPath, outputJsonPath, outputDtsPath } = headerPathsResult.value;\n\n if (!flags.json && !flags.quiet) {\n ui.stderr(\n formatStyledHeader({\n command: 'contract emit',\n description: 'Emit your contract artifacts',\n url: 'https://pris.ly/contract-emit',\n details: [\n { label: 'config', value: displayConfigPath },\n { label: 'contract', value: relative(process.cwd(), outputJsonPath) },\n { label: 'types', value: relative(process.cwd(), outputDtsPath) },\n ],\n flags,\n }),\n );\n }\n\n const onProgress = createProgressAdapter({ ui, flags });\n const configPath = options.config ? resolve(options.config) : 'prisma-next.config.ts';\n\n let result: ContractEmitResult;\n try {\n result = await executeContractEmit({ configPath, onProgress });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected('Unexpected error during contract emit', {\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n\n if (result.validationWarning) {\n ui.warn(result.validationWarning);\n }\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n outDir: dirname(result.files.json),\n files: result.files,\n timings: { total: Date.now() - startTime },\n });\n}\n\nexport function createContractEmitCommand(): Command {\n const command = new Command('emit');\n setCommandDescriptions(\n command,\n 'Emit your contract artifacts',\n 'Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\\n' +\n 'contract.d.ts. The contract.json contains the canonical contract structure, and\\n' +\n 'contract.d.ts provides TypeScript types for type-safe query building.',\n );\n setCommandExamples(command, [\n 'prisma-next contract emit',\n 'prisma-next contract emit --config ./custom-config.ts',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: ContractEmitOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const startTime = Date.now();\n\n const result = await executeContractEmitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (emitResult) => {\n if (flags.json) {\n ui.output(formatEmitJson(emitResult));\n } else {\n const output = formatEmitOutput(emitResult, flags);\n if (output) {\n ui.log(output);\n }\n if (!flags.quiet) {\n ui.success(formatSuccessMessage(flags));\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command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GAAG,UAAU,iBAAiB,OAAO,cAAc;EACnD,aAAa,OAAO;EACpB,QAAQ,QAAQ,OAAO,MAAM,KAAK;EAClC,OAAO,OAAO;EACd,SAAS,EAAE,OAAO,KAAK,KAAK,GAAG,WAAW;EAC3C,CAAC;;AAGJ,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,OAAO;AACnC,wBACE,SACA,gCACA,+OAGD;AACD,oBAAmB,SAAS,CAC1B,6BACA,wDACD,CAAC;AACF,kBAAiB,QAAQ,CACtB,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;EAKjF,MAAM,WAAW,aAFF,MAAM,2BAA2B,SAAS,OAAO,IAF9C,KAAK,KAAK,CAEkD,EAExC,OAAO,KAAK,eAAe;AAC/D,OAAI,MAAM,KACR,IAAG,OAAO,eAAe,WAAW,CAAC;QAChC;IACL,MAAM,SAAS,iBAAiB,YAAY,MAAM;AAClD,QAAI,OACF,IAAG,IAAI,OAAO;AAEhB,QAAI,CAAC,MAAM,MACT,IAAG,QAAQ,qBAAqB,MAAM,CAAC;;IAG3C;AACF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
@@ -0,0 +1,4 @@
1
+ import "./config-loader-ih8ViDb_.mjs";
2
+ import { t as executeContractEmit } from "./contract-emit-RZBWzkop.mjs";
3
+
4
+ export { executeContractEmit };
@@ -0,0 +1,329 @@
1
+ import { t as loadConfig } from "./config-loader-ih8ViDb_.mjs";
2
+ import { i as errorContractConfigMissing, m as errorRuntime } from "./cli-errors-By1iVE3z.mjs";
3
+ import { t as assertFrameworkComponentsCompatible } from "./framework-components-Bgcre3Z6.mjs";
4
+ import { t as enrichContract } from "./contract-enrichment-4Ptgw3Pe.mjs";
5
+ import { createRequire } from "node:module";
6
+ import { emit, getEmittedArtifactPaths } from "@prisma-next/emitter";
7
+ import { ifDefined } from "@prisma-next/utils/defined";
8
+ import { basename, dirname, join } from "pathe";
9
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
10
+ import { createControlStack } from "@prisma-next/framework-components/control";
11
+ import { abortable } from "@prisma-next/utils/abortable";
12
+
13
+ //#region src/utils/emit-queue.ts
14
+ /**
15
+ * Per-output FIFO queue for `executeContractEmit`.
16
+ *
17
+ * Ensures that at most one emit (load → resolve source → emit bytes → publish)
18
+ * runs per output JSON path at a time. Concurrent calls for the same path
19
+ * line up behind the in-flight one and run in submission order; the user-visible
20
+ * outcome is "last submission wins on disk" without any supersession bookkeeping.
21
+ *
22
+ * Long-lived hosts (Vite dev server, watch CLIs) must call `disposeEmitQueue`
23
+ * when they stop publishing to a path, otherwise the module-global `Map`
24
+ * accumulates one entry per unique output path for the lifetime of the process.
25
+ */
26
+ const emitQueues = /* @__PURE__ */ new Map();
27
+ function queueEmitByOutput(outputJsonPath, action) {
28
+ const next = (emitQueues.get(outputJsonPath) ?? Promise.resolve()).then(action, action);
29
+ emitQueues.set(outputJsonPath, next);
30
+ return next;
31
+ }
32
+ function disposeEmitQueue(outputJsonPath) {
33
+ emitQueues.delete(outputJsonPath);
34
+ }
35
+
36
+ //#endregion
37
+ //#region src/utils/publish-contract-artifact-pair.ts
38
+ function isRecord$1(value) {
39
+ return typeof value === "object" && value !== null;
40
+ }
41
+ function createTempArtifactPath(path, publicationToken, phase) {
42
+ return join(dirname(path), `.${basename(path)}.${process.pid}.${publicationToken}.${phase}.tmp`);
43
+ }
44
+ async function readExistingArtifact(path) {
45
+ try {
46
+ return { content: await readFile(path, "utf-8") };
47
+ } catch (error) {
48
+ if (isRecord$1(error) && error["code"] === "ENOENT") return "remove";
49
+ throw error;
50
+ }
51
+ }
52
+ async function restoreArtifact(path, previous, publicationToken) {
53
+ if (previous === "remove") {
54
+ await rm(path, { force: true });
55
+ return;
56
+ }
57
+ const restorePath = createTempArtifactPath(path, publicationToken, "rollback");
58
+ await writeFile(restorePath, previous.content, "utf-8");
59
+ try {
60
+ await rename(restorePath, path);
61
+ } finally {
62
+ await rm(restorePath, { force: true });
63
+ }
64
+ }
65
+ function withRollbackFailureCause(error, rollbackFailures) {
66
+ const rollbackCause = new AggregateError(rollbackFailures, "Failed to restore published artifacts");
67
+ if (error instanceof Error) {
68
+ Object.defineProperty(error, "cause", {
69
+ value: rollbackCause,
70
+ configurable: true,
71
+ writable: true
72
+ });
73
+ return error;
74
+ }
75
+ return new Error(String(error), { cause: rollbackCause });
76
+ }
77
+ async function publishPairWithRollback(entries, publicationToken) {
78
+ const replaced = [];
79
+ try {
80
+ for (const entry of entries) {
81
+ await rename(entry.tempPath, entry.outputPath);
82
+ replaced.push(entry);
83
+ }
84
+ } catch (error) {
85
+ const rollbackFailures = (await Promise.allSettled(replaced.map((entry) => restoreArtifact(entry.outputPath, entry.previous, publicationToken)))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
86
+ if (rollbackFailures.length > 0) throw withRollbackFailureCause(error, rollbackFailures);
87
+ throw error;
88
+ }
89
+ }
90
+ async function publishContractArtifactPair({ outputJsonPath, outputDtsPath, contractJson, contractDts, publicationToken, beforePublish }) {
91
+ const tempJsonPath = createTempArtifactPath(outputJsonPath, publicationToken, "next");
92
+ const tempDtsPath = createTempArtifactPath(outputDtsPath, publicationToken, "next");
93
+ try {
94
+ await writeFile(tempJsonPath, contractJson, "utf-8");
95
+ await writeFile(tempDtsPath, contractDts, "utf-8");
96
+ if (await beforePublish?.() === false) return false;
97
+ const previousJson = await readExistingArtifact(outputJsonPath);
98
+ await publishPairWithRollback([{
99
+ tempPath: tempDtsPath,
100
+ outputPath: outputDtsPath,
101
+ previous: await readExistingArtifact(outputDtsPath)
102
+ }, {
103
+ tempPath: tempJsonPath,
104
+ outputPath: outputJsonPath,
105
+ previous: previousJson
106
+ }], publicationToken);
107
+ return true;
108
+ } finally {
109
+ await Promise.allSettled([rm(tempJsonPath, { force: true }), rm(tempDtsPath, { force: true })]);
110
+ }
111
+ }
112
+
113
+ //#endregion
114
+ //#region src/utils/validate-contract-deps.ts
115
+ const IMPORT_PATTERN = /import\s+type\s+.*?\s+from\s+['"](@[^/]+\/[^/'"]+)/g;
116
+ function extractPackageSpecifiers(dtsContent) {
117
+ const packages = /* @__PURE__ */ new Set();
118
+ for (const match of dtsContent.matchAll(IMPORT_PATTERN)) {
119
+ const pkg = match[1];
120
+ if (pkg) packages.add(pkg);
121
+ }
122
+ return [...packages];
123
+ }
124
+ function validateContractDeps(dtsContent, projectRoot) {
125
+ const packages = extractPackageSpecifiers(dtsContent);
126
+ const resolve$1 = createRequire(`${projectRoot}/package.json`);
127
+ const missing = [];
128
+ for (const pkg of packages) try {
129
+ resolve$1.resolve(`${pkg}/package.json`);
130
+ } catch {
131
+ missing.push(pkg);
132
+ }
133
+ if (missing.length === 0) return { missing };
134
+ return {
135
+ missing,
136
+ warning: [
137
+ "contract.d.ts imports types from packages that are not installed:",
138
+ missing.map((p) => ` - ${p}`).join("\n"),
139
+ "",
140
+ "Install them with your package manager:",
141
+ ...missing.map((p) => ` ${p}`)
142
+ ].join("\n")
143
+ };
144
+ }
145
+
146
+ //#endregion
147
+ //#region src/control-api/operations/contract-emit.ts
148
+ const EMIT_ACTION = "emit";
149
+ function isRecord(value) {
150
+ return typeof value === "object" && value !== null;
151
+ }
152
+ function startSpan(onProgress, spanId, label) {
153
+ onProgress?.({
154
+ action: EMIT_ACTION,
155
+ kind: "spanStart",
156
+ spanId,
157
+ label
158
+ });
159
+ }
160
+ function endSpan(onProgress, spanId, outcome) {
161
+ onProgress?.({
162
+ action: EMIT_ACTION,
163
+ kind: "spanEnd",
164
+ spanId,
165
+ outcome
166
+ });
167
+ }
168
+ function failedToResolveContractSource(why, fix, meta) {
169
+ return errorRuntime("Failed to resolve contract source", {
170
+ why,
171
+ fix,
172
+ ...ifDefined("meta", meta)
173
+ });
174
+ }
175
+ function diagnosticLocationSuffix(diagnostic) {
176
+ const sourceId = typeof diagnostic["sourceId"] === "string" ? diagnostic["sourceId"] : void 0;
177
+ const span = isRecord(diagnostic["span"]) ? diagnostic["span"] : void 0;
178
+ const start = span && isRecord(span["start"]) ? span["start"] : void 0;
179
+ const line = start && typeof start["line"] === "number" ? start["line"] : void 0;
180
+ const column = start && typeof start["column"] === "number" ? start["column"] : void 0;
181
+ if (sourceId && line !== void 0 && column !== void 0) return ` (${sourceId}:${line}:${column})`;
182
+ if (sourceId) return ` (${sourceId})`;
183
+ return "";
184
+ }
185
+ function mapDiagnosticsToIssues(diagnostics) {
186
+ const issues = [];
187
+ for (const raw of diagnostics) {
188
+ if (!isRecord(raw)) continue;
189
+ const code = typeof raw["code"] === "string" ? raw["code"] : "diagnostic";
190
+ const message = typeof raw["message"] === "string" ? raw["message"] : "";
191
+ issues.push({
192
+ kind: code,
193
+ message: `${message}${diagnosticLocationSuffix(raw)}`
194
+ });
195
+ }
196
+ return issues;
197
+ }
198
+ function validateProviderResult(providerResult) {
199
+ if (!isRecord(providerResult) || typeof providerResult["ok"] !== "boolean") return {
200
+ ok: false,
201
+ error: failedToResolveContractSource("Contract source provider returned malformed result shape.", "Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).")
202
+ };
203
+ if (providerResult["ok"]) {
204
+ if (!("value" in providerResult)) return {
205
+ ok: false,
206
+ error: failedToResolveContractSource("Contract source provider returned malformed success result: missing value.", "Ensure contract.source.load success payload is ok(Contract).")
207
+ };
208
+ return {
209
+ ok: true,
210
+ value: providerResult["value"]
211
+ };
212
+ }
213
+ const failure = providerResult["failure"];
214
+ if (!isRecord(failure) || typeof failure["summary"] !== "string" || !Array.isArray(failure["diagnostics"])) return {
215
+ ok: false,
216
+ error: failedToResolveContractSource("Contract source provider returned malformed failure result: expected summary and diagnostics.", "Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).")
217
+ };
218
+ return {
219
+ ok: false,
220
+ error: failedToResolveContractSource(String(failure["summary"]), "Fix contract source diagnostics and return ok(Contract).", {
221
+ diagnostics: failure["diagnostics"],
222
+ issues: mapDiagnosticsToIssues(failure["diagnostics"]),
223
+ ...ifDefined("providerMeta", failure["meta"])
224
+ })
225
+ };
226
+ }
227
+ /**
228
+ * Canonical contract emit operation.
229
+ *
230
+ * This is the SINGLE publication path used by both the CLI command
231
+ * (`prisma-next contract emit`) and the Vite plugin
232
+ * (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this
233
+ * function rather than re-implementing load → emit → publish.
234
+ *
235
+ * The whole flow (load config → resolve source → emit bytes → atomic publish)
236
+ * is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls
237
+ * for the same output line up FIFO; the user-visible outcome is "last
238
+ * submission wins on disk" without any supersession bookkeeping. Within a
239
+ * single emit, `publishContractArtifactPair` stages temp files, renames
240
+ * `contract.d.ts` before `contract.json`, and attempts to restore the previous
241
+ * pair if either rename fails — so type-only consumers never observe a
242
+ * mismatched pair.
243
+ *
244
+ * @throws {CliStructuredError} on config/source/validation problems
245
+ * @throws {DOMException} `AbortError` if cancelled via `signal`
246
+ */
247
+ async function executeContractEmit(options) {
248
+ const { configPath, signal = new AbortController().signal, onProgress } = options;
249
+ const unlessAborted = abortable(signal);
250
+ const config = await unlessAborted(loadConfig(configPath));
251
+ if (!config.contract) throw errorContractConfigMissing({ why: "Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }" });
252
+ const contractConfig = config.contract;
253
+ if (!contractConfig.output) throw errorContractConfigMissing({ why: "Contract config must have output path. This should not happen if defineConfig() was used." });
254
+ if (typeof contractConfig.source?.load !== "function") throw errorContractConfigMissing({ why: "Contract config must include a valid source provider object" });
255
+ let outputPaths;
256
+ try {
257
+ outputPaths = getEmittedArtifactPaths(contractConfig.output);
258
+ } catch (error) {
259
+ throw errorContractConfigMissing({ why: error instanceof Error ? error.message : String(error) });
260
+ }
261
+ const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;
262
+ return queueEmitByOutput(outputJsonPath, async () => {
263
+ const stack = createControlStack(config);
264
+ const sourceContext = {
265
+ composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
266
+ scalarTypeDescriptors: stack.scalarTypeDescriptors,
267
+ authoringContributions: stack.authoringContributions,
268
+ codecLookup: stack.codecLookup,
269
+ controlMutationDefaults: stack.controlMutationDefaults,
270
+ resolvedInputs: contractConfig.source.inputs ?? []
271
+ };
272
+ startSpan(onProgress, "resolveSource", "Resolving contract source...");
273
+ let providerResult;
274
+ try {
275
+ providerResult = await unlessAborted(contractConfig.source.load(sourceContext));
276
+ } catch (error) {
277
+ endSpan(onProgress, "resolveSource", "error");
278
+ if (signal.aborted || isRecord(error) && error["name"] === "AbortError") throw error;
279
+ throw failedToResolveContractSource(error instanceof Error ? error.message : String(error), "Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.");
280
+ }
281
+ const validatedContract = validateProviderResult(providerResult);
282
+ if (!validatedContract.ok) {
283
+ endSpan(onProgress, "resolveSource", "error");
284
+ throw validatedContract.error;
285
+ }
286
+ endSpan(onProgress, "resolveSource", "ok");
287
+ startSpan(onProgress, "emit", "Emitting contract...");
288
+ let emitResult;
289
+ try {
290
+ const familyInstance = config.family.create(stack);
291
+ const rawComponents = [
292
+ config.target,
293
+ config.adapter,
294
+ ...config.extensionPacks ?? []
295
+ ];
296
+ const frameworkComponents = assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, rawComponents);
297
+ const enrichedIR = enrichContract(validatedContract.value, frameworkComponents);
298
+ familyInstance.validateContract(enrichedIR);
299
+ emitResult = await unlessAborted(emit(enrichedIR, stack, config.family.emission, { outputJsonPath }));
300
+ } catch (error) {
301
+ endSpan(onProgress, "emit", "error");
302
+ throw error;
303
+ }
304
+ endSpan(onProgress, "emit", "ok");
305
+ await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));
306
+ await publishContractArtifactPair({
307
+ outputJsonPath,
308
+ outputDtsPath,
309
+ contractJson: emitResult.contractJson,
310
+ contractDts: emitResult.contractDts,
311
+ publicationToken: String(process.hrtime.bigint())
312
+ });
313
+ const validationWarning = validateContractDeps(emitResult.contractDts, dirname(outputDtsPath)).warning;
314
+ return {
315
+ storageHash: emitResult.storageHash,
316
+ ...ifDefined("executionHash", emitResult.executionHash),
317
+ profileHash: emitResult.profileHash,
318
+ files: {
319
+ json: outputJsonPath,
320
+ dts: outputDtsPath
321
+ },
322
+ ...ifDefined("validationWarning", validationWarning)
323
+ };
324
+ });
325
+ }
326
+
327
+ //#endregion
328
+ export { disposeEmitQueue as n, executeContractEmit as t };
329
+ //# sourceMappingURL=contract-emit-RZBWzkop.mjs.map