@prisma/orm-toolchain 8.0.0-rc.4-dev.15 → 8.0.0-rc.4-dev.17

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 (47) hide show
  1. package/dist/{aggregate-BOlLu7k7.mjs → aggregate-EMuVN6hq.mjs} +8 -8
  2. package/dist/{aggregate-BOlLu7k7.mjs.map → aggregate-EMuVN6hq.mjs.map} +1 -1
  3. package/dist/cli.mjs +60 -65
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/cli__control-api.mjs +1 -1
  6. package/dist/cli__migration-cli.mjs +3 -3
  7. package/dist/cli__migration-cli.mjs.map +1 -1
  8. package/dist/{contract-snapshot-store-BAmQkHe5-BJFpuIQQ.mjs → contract-snapshot-store-qGrwlGmt-Cf2NFzRL.mjs} +3 -3
  9. package/dist/{contract-snapshot-store-BAmQkHe5-BJFpuIQQ.mjs.map → contract-snapshot-store-qGrwlGmt-Cf2NFzRL.mjs.map} +1 -1
  10. package/dist/{errors-CcEpbfnE-CsSXrttT.mjs → errors-SoLLYLtw-DMxVbVs9.mjs} +9 -9
  11. package/dist/errors-SoLLYLtw-DMxVbVs9.mjs.map +1 -0
  12. package/dist/{graph-membership-BoITerZB-C2-x1Qp6.mjs → graph-membership-DY1Onbc3-CwBd6wuB.mjs} +3 -3
  13. package/dist/{graph-membership-BoITerZB-C2-x1Qp6.mjs.map → graph-membership-DY1Onbc3-CwBd6wuB.mjs.map} +1 -1
  14. package/dist/{invariants-DcFfhJMZ-BHDWZP9k.mjs → invariants-Cww4bv0v-BEiFxmbX.mjs} +3 -3
  15. package/dist/{invariants-DcFfhJMZ-BHDWZP9k.mjs.map → invariants-Cww4bv0v-BEiFxmbX.mjs.map} +1 -1
  16. package/dist/{io-DsViRB_O-Ci1kJGBg.mjs → io-BmWQNxRP-DQqbcPsS.mjs} +5 -5
  17. package/dist/{io-DsViRB_O-Ci1kJGBg.mjs.map → io-BmWQNxRP-DQqbcPsS.mjs.map} +1 -1
  18. package/dist/{migration-CWSj4pMr.mjs → migration-B9w-7dKe.mjs} +3 -3
  19. package/dist/{migration-CWSj4pMr.mjs.map → migration-B9w-7dKe.mjs.map} +1 -1
  20. package/dist/{migration-graph-DwXAHP6T-NgmP2DNz.mjs → migration-graph-CW4bMmTz-B5xFtFVB.mjs} +3 -3
  21. package/dist/{migration-graph-DwXAHP6T-NgmP2DNz.mjs.map → migration-graph-CW4bMmTz-B5xFtFVB.mjs.map} +1 -1
  22. package/dist/migration-tools.mjs +12 -12
  23. package/dist/migration-tools__aggregate.mjs +1 -1
  24. package/dist/migration-tools__contract-snapshot-store.mjs +1 -1
  25. package/dist/migration-tools__errors.mjs +1 -1
  26. package/dist/migration-tools__invariants.mjs +1 -1
  27. package/dist/migration-tools__io.mjs +1 -1
  28. package/dist/migration-tools__migration-graph.mjs +2 -2
  29. package/dist/migration-tools__migration.mjs +1 -1
  30. package/dist/migration-tools__ref-resolution.mjs +1 -1
  31. package/dist/migration-tools__refs.mjs +1 -1
  32. package/dist/migration-tools__spaces.mjs +2 -2
  33. package/dist/{ref-DJkSkzAt-DCYlpVrB.mjs → ref-XdaDN3GF-Io-mSVS6.mjs} +51 -51
  34. package/dist/ref-XdaDN3GF-Io-mSVS6.mjs.map +1 -0
  35. package/dist/{ref-resolution-Cbdejrwt.mjs → ref-resolution-D77jPigU.mjs} +2 -2
  36. package/dist/{ref-resolution-Cbdejrwt.mjs.map → ref-resolution-D77jPigU.mjs.map} +1 -1
  37. package/dist/{refs-KVVlm3lE-BcqdpdYD.mjs → refs-BpSpzdYB-BcDelHGt.mjs} +9 -9
  38. package/dist/refs-BpSpzdYB-BcDelHGt.mjs.map +1 -0
  39. package/dist/{spaces-CHrjWRoZ.mjs → spaces-BCZiAZQn.mjs} +6 -6
  40. package/dist/{spaces-CHrjWRoZ.mjs.map → spaces-BCZiAZQn.mjs.map} +1 -1
  41. package/dist/{verify-contract-spaces-DomK5uP5-CyI3hD3Q.mjs → verify-contract-spaces-CrxvgpwD-D5LLXGci.mjs} +7 -7
  42. package/dist/{verify-contract-spaces-DomK5uP5-CyI3hD3Q.mjs.map → verify-contract-spaces-CrxvgpwD-D5LLXGci.mjs.map} +1 -1
  43. package/dist/vite-plugin-contract-emit.mjs +1 -1
  44. package/package.json +12 -12
  45. package/dist/errors-CcEpbfnE-CsSXrttT.mjs.map +0 -1
  46. package/dist/ref-DJkSkzAt-DCYlpVrB.mjs.map +0 -1
  47. package/dist/refs-KVVlm3lE-BcqdpdYD.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import { $ as loadContractRawSafely, At as statusForMigrationHash, B as executeDbUpdate, Ct as resolveRefAdvancementFields, Dt as runMigrationCheck, Et as runContractSpaceSeedPhase, G as executeRefAdvancement, H as executeMigrateShowPlan, J as executeRefSetCommand, K as executeRefDeleteCommand, Ot as runMigrationList, Q as loadAggregateIntegrityViolations, R as executeContractEmit, St as resolveMigrationRef, U as executeMigrationNewCommand, V as executeDbVerify, W as executeMigrationPlanCommand, X as hasMigrationPath, Z as listRefsByContractHash, _ as enumerateCheckSpaces, a as buildContractSpaceAggregate, bt as resolveContractRefToSnapshot, c as buildRefAdvancementFields, dt as refuseContractSpaceIntegrity, et as loadContractSpaceAggregateForCli, f as computeRefAdvancementName, ft as refuseDeclaredExtensionTargetMismatch, g as enrichContract, gt as refuseUnknownInvariants, h as disposeEmitQueue, ht as refusePackageCorruptionOnAggregate, i as appliedHashesFromLedger, it as mapIntegrityViolations, l as checkSingleTarget, lt as readContractIR, m as deriveStatusEdgeAnnotations, mt as refuseMissingInvariantPath, n as advanceRefSafely, nt as mapCaughtMigrationError, o as buildMigrationSpaceGraphEntries, ot as migrationSpaceListEntriesFromAggregate, p as createControlClient, pt as refuseMarkerOutsideGraph, q as executeRefListCommand, r as appContractStandInFromIdentity, rt as mapContractAtError, s as buildReadAggregate, st as originHashForStatus, ut as readMigrationRefs, wt as resolveToForPlan, xt as resolveFromForPlan, yt as resolveContractRef$1, z as executeDbInit } from "./ref-DJkSkzAt-DCYlpVrB.mjs";
1
+ import { $ as loadContractRawSafely, At as statusForMigrationHash, B as executeDbUpdate, Ct as resolveRefAdvancementFields, Dt as runMigrationCheck, Et as runContractSpaceSeedPhase, G as executeRefAdvancement, H as executeMigrateShowPlan, J as executeRefSetCommand, K as executeRefDeleteCommand, Ot as runMigrationList, Q as loadAggregateIntegrityViolations, R as executeContractEmit, St as resolveMigrationRef, U as executeMigrationNewCommand, V as executeDbVerify, W as executeMigrationPlanCommand, X as hasMigrationPath, Z as listRefsByContractHash, _ as enumerateCheckSpaces, a as buildContractSpaceAggregate, bt as resolveContractRefToSnapshot, c as buildRefAdvancementFields, dt as refuseContractSpaceIntegrity, et as loadContractSpaceAggregateForCli, f as computeRefAdvancementName, ft as refuseDeclaredExtensionTargetMismatch, g as enrichContract, gt as refuseUnknownInvariants, h as disposeEmitQueue, ht as refusePackageCorruptionOnAggregate, i as appliedHashesFromLedger, it as mapIntegrityViolations, l as checkSingleTarget, lt as readContractIR, m as deriveStatusEdgeAnnotations, mt as refuseMissingInvariantPath, n as advanceRefSafely, nt as mapCaughtMigrationError, o as buildMigrationSpaceGraphEntries, ot as migrationSpaceListEntriesFromAggregate, p as createControlClient, pt as refuseMarkerOutsideGraph, q as executeRefListCommand, r as appContractStandInFromIdentity, rt as mapContractAtError, s as buildReadAggregate, st as originHashForStatus, ut as readMigrationRefs, wt as resolveToForPlan, xt as resolveFromForPlan, yt as resolveContractRef$1, z as executeDbInit } from "./ref-XdaDN3GF-Io-mSVS6.mjs";
2
2
  export { advanceRefSafely, appContractStandInFromIdentity, appliedHashesFromLedger, buildContractSpaceAggregate, buildMigrationSpaceGraphEntries, buildReadAggregate, buildRefAdvancementFields, checkSingleTarget, computeRefAdvancementName, createControlClient, deriveStatusEdgeAnnotations, disposeEmitQueue, enrichContract, enumerateCheckSpaces, executeContractEmit, executeDbInit, executeDbUpdate, executeDbVerify, executeMigrateShowPlan, executeMigrationNewCommand, executeMigrationPlanCommand, executeRefAdvancement, executeRefDeleteCommand, executeRefListCommand, executeRefSetCommand, hasMigrationPath, listRefsByContractHash, loadAggregateIntegrityViolations, loadContractRawSafely, loadContractSpaceAggregateForCli, mapCaughtMigrationError, mapContractAtError, mapIntegrityViolations, migrationSpaceListEntriesFromAggregate, originHashForStatus, readContractIR, readMigrationRefs, refuseContractSpaceIntegrity, refuseDeclaredExtensionTargetMismatch, refuseMarkerOutsideGraph, refuseMissingInvariantPath, refusePackageCorruptionOnAggregate, refuseUnknownInvariants, resolveContractRef$1 as resolveContractRef, resolveContractRefToSnapshot, resolveFromForPlan, resolveMigrationRef, resolveRefAdvancementFields, resolveToForPlan, runContractSpaceSeedPhase, runMigrationCheck, runMigrationList, statusForMigrationHash };
@@ -1,6 +1,6 @@
1
- import { g as errorInvalidJson } from "./errors-CcEpbfnE-CsSXrttT.mjs";
1
+ import { g as errorInvalidJson } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
2
  import { a as loadConfigForSections } from "./exports-Cv8nMmBT.mjs";
3
- import { r as buildMigrationArtifacts } from "./migration-CWSj4pMr.mjs";
3
+ import { r as buildMigrationArtifacts } from "./migration-B9w-7dKe.mjs";
4
4
  import { readFileSync, realpathSync, writeFileSync } from "node:fs";
5
5
  import { CliStructuredError, errorMigrationCliInvalidConfigArg, errorMigrationCliUnknownFlag } from "@prisma/orm-framework/errors/control";
6
6
  import { createControlStack } from "@prisma/orm-framework/components/control";
@@ -14,7 +14,7 @@ import { Cli, Command, Option, UsageError } from "clipanion";
14
14
  * `node migration.ts` directly.
15
15
  *
16
16
  * Naming: this is *not* a "migration runner" in the apply-time sense. The
17
- * apply-time runner is the thing `prisma migrate` uses to
17
+ * apply-time runner is the thing `prisma db migrate` uses to
18
18
  * execute migration JSON ops against a database. `MigrationCLI` is the
19
19
  * tiny CLI surface owned by an authored `migration.ts` file: parse the
20
20
  * file's argv, load the project's `prisma.config.ts`, assemble a
@@ -1 +1 @@
1
- {"version":3,"file":"cli__migration-cli.mjs","names":[],"sources":["../../../../1-framework/3-tooling/cli/dist/migration-cli.mjs"],"sourcesContent":["import { readFileSync, realpathSync, writeFileSync } from \"node:fs\";\nimport { CliStructuredError, errorMigrationCliInvalidConfigArg, errorMigrationCliUnknownFlag } from \"@internal/errors/control\";\nimport { createControlStack } from \"@internal/framework-components/control\";\nimport { errorMigrationTargetMismatch } from \"@internal/errors/migration\";\nimport { errorInvalidJson } from \"@internal/migration-tools/errors\";\nimport { dirname, join } from \"pathe\";\nimport { loadConfigForSections } from \"@internal/config-loader\";\nimport { fileURLToPath } from \"node:url\";\nimport { buildMigrationArtifacts } from \"@internal/migration-tools/migration\";\nimport { Cli, Command, Option, UsageError } from \"clipanion\";\n//#region src/migration-cli.ts\n/**\n* The migration-file CLI interface: the actor invoked when the author runs\n* `node migration.ts` directly.\n*\n* Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n* apply-time runner is the thing `prisma migrate` uses to\n* execute migration JSON ops against a database. `MigrationCLI` is the\n* tiny CLI surface owned by an authored `migration.ts` file: parse the\n* file's argv, load the project's `prisma.config.ts`, assemble a\n* `ControlStack`, instantiate the migration class, and serialize.\n*\n* The user authors a migration class, then calls\n* `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n* after the class definition. When the file is invoked as a node\n* entrypoint (`node migration.ts`), the CLI:\n*\n* 1. Detects whether the file is the direct entrypoint (no-op when imported).\n* 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via\n* [clipanion](https://github.com/arcanis/clipanion).\n* 3. Loads the project's `prisma.config.ts` via the same\n* `loadConfigForSections` the CLI commands use, walking up from the\n* migration file's directory.\n* 4. Probe-instantiates the migration class without a stack so it can read\n* `targetId` and verify it matches `config.target.targetId`\n* (`MIGRATION.TARGET_MISMATCH` on mismatch) before any stack-driven adapter\n* construction runs.\n* 5. Assembles a `ControlStack` from the loaded config descriptors and\n* constructs the migration with that stack.\n* 6. Reads any previously-scaffolded `migration.json`, then calls\n* `buildMigrationArtifacts` from `@internal/migration-tools` to\n* produce in-memory `ops.json` + `migration.json` content. Persists\n* the result to disk (or prints in dry-run mode).\n*\n* File I/O lives here, in `@internal/cli`: this is the only place\n* that legitimately combines config loading, stack assembly, and\n* on-disk persistence. `@internal/migration-tools` owns the pure\n* conversion from a `Migration` instance to artifact strings; `Migration`\n* stays a pure abstract class.\n*\n* Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`\n* for its in-process testability and runtime-agnostic execution surface; see\n* `docs/architecture docs/research/commander-friction-points.md` for the\n* evaluation rubric and the durable rationale that drove the choice).\n*/\n/**\n* Flags exposed by the migration-file CLI.\n*\n* Must stay in sync with the `Option` declarations on\n* `MigrationFileCommand` below. This list is rendered in the\n* `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,\n* so order matters for user-visible output (declaration order is the\n* order users see when they run `--help`).\n*/\nconst KNOWN_FLAGS = [\n\t\"--help\",\n\t\"--dry-run\",\n\t\"--config\"\n];\n/**\n* The clipanion command that owns the migration-file CLI's option\n* declarations. The class is internal — `MigrationCLI.run` is the\n* stable public surface. Adding a flag here automatically updates\n* `--help` rendering and the `KNOWN_FLAGS` list (the latter must be\n* updated in tandem).\n*/\nvar MigrationFileCommand = class extends Command {\n\tstatic paths = [Command.Default];\n\tstatic usage = Command.Usage({\n\t\tdescription: \"Self-emit ops.json and migration.json from a class-flow migration\",\n\t\tdetails: `\n Loads the project's prisma.config.ts, assembles a ControlStack\n from the configured target/adapter/extensions, and serializes the\n migration's operations + metadata next to this file.\n `,\n\t\texamples: [\n\t\t\t[\"Self-emit ops.json + migration.json next to migration.ts\", \"$0\"],\n\t\t\t[\"Preview without writing files\", \"$0 --dry-run\"],\n\t\t\t[\"Use a non-default config path\", \"$0 --config ./custom.config.ts\"]\n\t\t]\n\t});\n\tdryRun = Option.Boolean(\"--dry-run\", false, { description: \"Print operations to stdout without writing files\" });\n\tconfig = Option.String(\"--config\", { description: \"Path to prisma.config.ts\" });\n\t/**\n\t* Unused: orchestration runs inside `MigrationCLI.run` so error\n\t* routing stays under our control (clipanion's `cli.run` writes\n\t* error output to `context.stdout`, but our contract requires\n\t* structured errors on stderr). `cli.process` is used to parse\n\t* argv into a populated `MigrationFileCommand` instance whose\n\t* fields drive the orchestration directly.\n\t*/\n\tasync execute() {\n\t\treturn 0;\n\t}\n};\n/**\n* The CLI surface invoked by an authored `migration.ts` file. Exposed as\n* a class with a static `run` method (rather than a free function) to\n* give the concept a stable identity in the ubiquitous language: this is\n* the \"migration-file CLI\", distinct from the apply-time runner that\n* executes migration JSON ops.\n*\n* Currently a single static method. Future surface (e.g. a programmatic\n* `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n* land here without changing the import shape used by every authored\n* migration.\n*/\nvar MigrationCLI = class {\n\t/**\n\t* Orchestrates a class-flow `migration.ts` script run.\n\t*\n\t* The third argument is the in-process testability surface: callers\n\t* (and tests) may inject `argv`, `stdout`, and `stderr` instead of\n\t* relying on `process.argv` / `process.stdout` / `process.stderr`.\n\t* Each option defaults to its `process` global when omitted, so\n\t* existing two-argument call sites\n\t* (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to\n\t* compile and behave identically.\n\t*\n\t* Returns the exit code so the caller can branch on it. Also writes\n\t* the same code to `process.exitCode` so script-style callers that\n\t* don't await the return value still surface a non-zero exit when\n\t* something fails.\n\t*\n\t* Exit codes:\n\t* - 0 — success, or `--help`, or imported-not-entrypoint no-op.\n\t* - 1 — runtime/orchestration error (config not found, target\n\t* mismatch, etc.).\n\t* - 2 — usage error (unknown flag, malformed `--config`). Aligns\n\t* with `docs/CLI Style Guide.md` § Exit Codes.\n\t*/\n\tstatic async run(importMetaUrl, MigrationClass, options = {}) {\n\t\tif (!importMetaUrl) return 0;\n\t\tconst argv = options.argv ?? process.argv;\n\t\tconst stdout = options.stdout ?? process.stdout;\n\t\tconst stderr = options.stderr ?? process.stderr;\n\t\tif (!isDirectEntrypoint(importMetaUrl, argv)) return 0;\n\t\tconst exitCode = await orchestrate(importMetaUrl, MigrationClass, {\n\t\t\targv,\n\t\t\tstdout,\n\t\t\tstderr\n\t\t});\n\t\tif (exitCode !== 0 || !process.exitCode) process.exitCode = exitCode;\n\t\treturn exitCode;\n\t}\n};\n/**\n* Argv-aware variant of the entrypoint guard. The shared\n* `@internal/migration-tools` helper of the same name reads\n* `process.argv[1]` directly, which doesn't compose with the new\n* in-process testability surface (tests inject `argv` without mutating\n* the process global). Inlined here so the migration-file CLI's check\n* follows the injected `argv[1]` consistently.\n*/\nfunction isDirectEntrypoint(importMetaUrl, argv) {\n\tconst argv1 = argv[1];\n\tif (!argv1) return false;\n\ttry {\n\t\treturn realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Argv-and-stream-driven orchestration body. Pulled out of the static\n* method so the entrypoint guard / process-default plumbing stays\n* separate from the parse + load + serialize steps.\n*/\nasync function orchestrate(importMetaUrl, MigrationClass, ctx) {\n\tconst cli = Cli.from([MigrationFileCommand], {\n\t\tbinaryName: \"migration.ts\",\n\t\tbinaryLabel: \"Migration file CLI\"\n\t});\n\tconst input = ctx.argv.slice(2);\n\tconst configError = detectInvalidConfig(input);\n\tif (configError) {\n\t\twriteStructuredError(ctx.stderr, configError);\n\t\treturn 2;\n\t}\n\tlet parsed;\n\ttry {\n\t\tconst command = cli.process({\n\t\t\tinput: [...input],\n\t\t\tcontext: {\n\t\t\t\tstdout: ctx.stdout,\n\t\t\t\tstderr: ctx.stderr\n\t\t\t}\n\t\t});\n\t\tif (!(command instanceof MigrationFileCommand)) {\n\t\t\tctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n\t\t\treturn 0;\n\t\t}\n\t\tparsed = command;\n\t} catch (err) {\n\t\treturn renderParseError(err, input, ctx.stderr);\n\t}\n\tif (parsed.help) {\n\t\tctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n\t\treturn 0;\n\t}\n\ttry {\n\t\tawait runMigration(importMetaUrl, MigrationClass, parsed, ctx);\n\t\treturn 0;\n\t} catch (err) {\n\t\tif (CliStructuredError.is(err)) writeStructuredError(ctx.stderr, err);\n\t\telse ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n\t\treturn 1;\n\t}\n}\n/**\n* Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`\n* contains a malformed `--config`:\n*\n* - `--config` as the last token (no value follows).\n* - `--config <flag>` where `<flag>` starts with `-` (silently\n* consuming the next flag would either drop the flag or serialize\n* against the wrong project).\n* - `--config <empty>` where the value is the empty string. Shells\n* expand `--config \"\"` (or `--config \"$UNSET_VAR\"`) into a real\n* empty argv token; treating that as a usage error here surfaces\n* `CLI.CONFIG_ARG_MISSING_PATH` instead of a less actionable loader error on an\n* empty path.\n* - `--config=` (the equals form with an empty value). Same shape as\n* the empty-string case above; the user expressed intent to override\n* the config path but the override is empty.\n*\n* `--config=<value>` and `--config <value>` with a non-empty value are\n* both valid (and the equals form's value is allowed to start with\n* `-` — the `=` makes the binding explicit).\n*/\nfunction detectInvalidConfig(input) {\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst token = input[i];\n\t\tif (token === \"--config\") {\n\t\t\tconst next = input[i + 1];\n\t\t\tif (next === void 0 || next === \"\") return errorMigrationCliInvalidConfigArg();\n\t\t\tif (next.startsWith(\"-\")) return errorMigrationCliInvalidConfigArg({ nextToken: next });\n\t\t\tcontinue;\n\t\t}\n\t\tif (token === \"--config=\") return errorMigrationCliInvalidConfigArg();\n\t}\n\treturn null;\n}\n/**\n* Translate clipanion's parse-time errors into the project's structured\n* error envelopes.\n*\n* - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and\n* the bare-trailing `--config` case (where arity-1 needs a value but\n* none was supplied). Distinguished by inspecting the input array.\n* - `UsageError` covers schema/validator failures from typanion. None\n* of the migration-file CLI's options have validators today, but we\n* still translate it as a usage error (exit 2) for forward-compat.\n* - Anything else re-throws — caller's outer catch will surface it as\n* exit 1 (runtime error).\n*/\nfunction renderParseError(err, input, stderr) {\n\tif (isUnknownSyntaxError(err)) {\n\t\twriteStructuredError(stderr, errorMigrationCliUnknownFlag({\n\t\t\tflag: findOffendingFlag(input),\n\t\t\tknownFlags: KNOWN_FLAGS\n\t\t}));\n\t\treturn 2;\n\t}\n\tif (err instanceof UsageError) {\n\t\twriteStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));\n\t\treturn 2;\n\t}\n\tthrow err;\n}\n/**\n* Duck-type check for clipanion's `UnknownSyntaxError`: the class is\n* thrown by the parser but is not re-exported from the package's main\n* entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).\n* Identified by `name === 'UnknownSyntaxError'` and the\n* `clipanion.type === 'none'` discriminator that clipanion's\n* `ErrorWithMeta` interface guarantees.\n*/\nfunction isUnknownSyntaxError(err) {\n\tif (!(err instanceof Error) || err.name !== \"UnknownSyntaxError\") return false;\n\tconst meta = err.clipanion;\n\treturn typeof meta === \"object\" && meta !== null && meta.type === \"none\";\n}\n/**\n* Best-effort: pull the first input token that doesn't match a known\n* flag. Falls back to the first token when we can't pinpoint it. The\n* returned name is rendered into the user-visible CLI.UNKNOWN_FLAG envelope\n* (`Unknown flag \\`<name>\\``) and round-tripped via `meta.flag` so\n* agent consumers can render their own \"did you mean\" suggestions.\n*/\nfunction findOffendingFlag(input) {\n\tfor (const token of input) {\n\t\tif (!token.startsWith(\"-\")) continue;\n\t\tconst head = token.split(\"=\", 1)[0] ?? token;\n\t\tif (!KNOWN_FLAGS.includes(head) && head !== \"-h\") return head;\n\t}\n\treturn input[0] ?? \"\";\n}\n/**\n* Write a `CliStructuredError` envelope to the given stream. Format\n* matches the legacy hand-rolled writer (`message: why`) so the rest of\n* the project's error rendering stays consistent across surfaces. The\n* full PN code (`PN-<domain>-<code>`) is included so consumers can\n* grep for stable identifiers.\n*/\nfunction writeStructuredError(stream, err) {\n\tconst envelope = err.toEnvelope();\n\tconst why = envelope.why ?? envelope.summary;\n\tconst fix = envelope.fix ? `\\n${envelope.fix}` : \"\";\n\tstream.write(`${envelope.code}: ${envelope.summary}\\n${why}${fix}\\n`);\n}\n/**\n* Read a previously-scaffolded `migration.json` from disk, returning\n* `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`\n* when the file is present but cannot be parsed as JSON. The CLI feeds\n* this into `buildMigrationArtifacts` so the pure builder can preserve\n* fields owned by `migration plan` (contract bookends, `createdAt`) across\n* re-emits.\n*\n* Author-time path: this loader still does not verify the manifest hash\n* or schema — that is the apply-time loader's job. Hash mismatch is the\n* *expected* outcome of a re-author (the developer's source changes\n* invalidate the prior hash by construction), and verification here\n* would block legitimate regenerations. Syntactic JSON-parse failure,\n* however, is now surfaced rather than swallowed: a malformed\n* `migration.json` indicates either a hand-edit gone wrong or partial\n* write, and silently rebuilding from `describe()` would discard the\n* user's on-disk content (preserved bookends, `createdAt`) without any\n* indication something was wrong on disk.\n* Apply-time consumers always route through the verifying\n* `readMigrationPackage` in `@internal/migration-tools/io` instead.\n*/\nfunction readExistingMetadata(metadataPath) {\n\tlet raw;\n\ttry {\n\t\traw = readFileSync(metadataPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));\n\t}\n}\n/**\n* Persist a migration instance's artifacts to `migrationDir`. In\n* `dryRun` mode the artifacts are printed to stdout (with the same\n* `--- migration.json --- / --- ops.json ---` framing the legacy\n* `serializeMigration` helper used) and no files are written. Otherwise\n* `ops.json` and `migration.json` are written next to `migration.ts` and\n* a confirmation line is printed.\n*\n* File I/O lives in the CLI rather than `@internal/migration-tools`\n* so the migration-tools package stays focused on the pure\n* `Migration` → in-memory artifact conversion. The CLI is the only\n* legitimate site for combining config loading, stack assembly, and\n* filesystem persistence.\n*/\nasync function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {\n\tconst metadataPath = join(migrationDir, \"migration.json\");\n\tconst { opsJson, metadataJson } = await buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));\n\tif (dryRun) {\n\t\tstdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n\t\tstdout.write(\"--- ops.json ---\\n\");\n\t\tstdout.write(`${opsJson}\\n`);\n\t\treturn;\n\t}\n\twriteFileSync(join(migrationDir, \"ops.json\"), opsJson);\n\twriteFileSync(metadataPath, metadataJson);\n\tstdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`);\n}\n/**\n* Inner orchestration: load config, probe-construct the migration,\n* verify target, assemble the stack, construct with the stack, persist.\n*\n* Throws `CliStructuredError` for known failure modes (config not\n* found, target mismatch); the outer `orchestrate` translates those to\n* exit 1.\n*/\nasync function runMigration(importMetaUrl, MigrationClass, parsed, ctx) {\n\tconst migrationDir = dirname(fileURLToPath(importMetaUrl));\n\tconst configResult = await loadConfigForSections(parsed.config, [\n\t\t\"family\",\n\t\t\"target\",\n\t\t\"adapter\",\n\t\t\"driver\",\n\t\t\"extensions\"\n\t]);\n\tif (!configResult.ok) throw configResult.failure;\n\tconst config = configResult.value;\n\tconst probe = new MigrationClass();\n\tif (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({\n\t\tmigrationTargetId: probe.targetId,\n\t\tconfigTargetId: config.target.targetId\n\t});\n\tawait serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);\n\tctx.stderr;\n}\n//#endregion\nexport { MigrationCLI };\n\n//# sourceMappingURL=migration-cli.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,cAAc;CACnB;CACA;CACA;AACD;;;;;;;;AAQA,IAAI,uBAAuB,cAAc,QAAQ;CAChD,OAAO,QAAQ,CAAC,QAAQ,OAAO;CAC/B,OAAO,QAAQ,QAAQ,MAAM;EAC5B,aAAa;EACb,SAAS;;;;;EAKT,UAAU;GACT,CAAC,4DAA4D,IAA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,SAAS,iBAAiB,MAAM,wBAAwB,UAAU,qBAAqB,YAAY,CAAC;CAC5G,IAAI,QAAQ;EACX,OAAO,MAAM,2BAA2B,aAAa,GAAG;EACxD,OAAO,MAAM,oBAAoB;EACjC,OAAO,MAAM,GAAG,QAAQ,GAAG;EAC3B;CACD;CACA,cAAc,KAAK,cAAc,UAAU,GAAG,OAAO;CACrD,cAAc,cAAc,YAAY;CACxC,OAAO,MAAM,sCAAsC,aAAa,GAAG;AACpE;;;;;;;;;AASA,eAAe,aAAa,eAAe,gBAAgB,QAAQ,KAAK;CACvE,MAAM,eAAe,QAAQ,cAAc,aAAa,CAAC;CACzD,MAAM,eAAe,MAAM,sBAAsB,OAAO,QAAQ;EAC/D;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,IAAI,CAAC,aAAa,IAAI,MAAM,aAAa;CACzC,MAAM,SAAS,aAAa;CAC5B,MAAM,QAAQ,IAAI,eAAe;CACjC,IAAI,MAAM,aAAa,OAAO,OAAO,UAAU,MAAM,6BAA6B;EACjF,mBAAmB,MAAM;EACzB,gBAAgB,OAAO,OAAO;CAC/B,CAAC;CACD,MAAM,yBAAyB,IAAI,eAAe,mBAAmB,MAAM,CAAC,GAAG,cAAc,OAAO,QAAQ,IAAI,MAAM;CACtH,IAAI;AACL"}
1
+ {"version":3,"file":"cli__migration-cli.mjs","names":[],"sources":["../../../../1-framework/3-tooling/cli/dist/migration-cli.mjs"],"sourcesContent":["import { readFileSync, realpathSync, writeFileSync } from \"node:fs\";\nimport { CliStructuredError, errorMigrationCliInvalidConfigArg, errorMigrationCliUnknownFlag } from \"@internal/errors/control\";\nimport { createControlStack } from \"@internal/framework-components/control\";\nimport { errorMigrationTargetMismatch } from \"@internal/errors/migration\";\nimport { errorInvalidJson } from \"@internal/migration-tools/errors\";\nimport { dirname, join } from \"pathe\";\nimport { loadConfigForSections } from \"@internal/config-loader\";\nimport { fileURLToPath } from \"node:url\";\nimport { buildMigrationArtifacts } from \"@internal/migration-tools/migration\";\nimport { Cli, Command, Option, UsageError } from \"clipanion\";\n//#region src/migration-cli.ts\n/**\n* The migration-file CLI interface: the actor invoked when the author runs\n* `node migration.ts` directly.\n*\n* Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n* apply-time runner is the thing `prisma db migrate` uses to\n* execute migration JSON ops against a database. `MigrationCLI` is the\n* tiny CLI surface owned by an authored `migration.ts` file: parse the\n* file's argv, load the project's `prisma.config.ts`, assemble a\n* `ControlStack`, instantiate the migration class, and serialize.\n*\n* The user authors a migration class, then calls\n* `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n* after the class definition. When the file is invoked as a node\n* entrypoint (`node migration.ts`), the CLI:\n*\n* 1. Detects whether the file is the direct entrypoint (no-op when imported).\n* 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via\n* [clipanion](https://github.com/arcanis/clipanion).\n* 3. Loads the project's `prisma.config.ts` via the same\n* `loadConfigForSections` the CLI commands use, walking up from the\n* migration file's directory.\n* 4. Probe-instantiates the migration class without a stack so it can read\n* `targetId` and verify it matches `config.target.targetId`\n* (`MIGRATION.TARGET_MISMATCH` on mismatch) before any stack-driven adapter\n* construction runs.\n* 5. Assembles a `ControlStack` from the loaded config descriptors and\n* constructs the migration with that stack.\n* 6. Reads any previously-scaffolded `migration.json`, then calls\n* `buildMigrationArtifacts` from `@internal/migration-tools` to\n* produce in-memory `ops.json` + `migration.json` content. Persists\n* the result to disk (or prints in dry-run mode).\n*\n* File I/O lives here, in `@internal/cli`: this is the only place\n* that legitimately combines config loading, stack assembly, and\n* on-disk persistence. `@internal/migration-tools` owns the pure\n* conversion from a `Migration` instance to artifact strings; `Migration`\n* stays a pure abstract class.\n*\n* Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`\n* for its in-process testability and runtime-agnostic execution surface; see\n* `docs/architecture docs/research/commander-friction-points.md` for the\n* evaluation rubric and the durable rationale that drove the choice).\n*/\n/**\n* Flags exposed by the migration-file CLI.\n*\n* Must stay in sync with the `Option` declarations on\n* `MigrationFileCommand` below. This list is rendered in the\n* `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,\n* so order matters for user-visible output (declaration order is the\n* order users see when they run `--help`).\n*/\nconst KNOWN_FLAGS = [\n\t\"--help\",\n\t\"--dry-run\",\n\t\"--config\"\n];\n/**\n* The clipanion command that owns the migration-file CLI's option\n* declarations. The class is internal — `MigrationCLI.run` is the\n* stable public surface. Adding a flag here automatically updates\n* `--help` rendering and the `KNOWN_FLAGS` list (the latter must be\n* updated in tandem).\n*/\nvar MigrationFileCommand = class extends Command {\n\tstatic paths = [Command.Default];\n\tstatic usage = Command.Usage({\n\t\tdescription: \"Self-emit ops.json and migration.json from a class-flow migration\",\n\t\tdetails: `\n Loads the project's prisma.config.ts, assembles a ControlStack\n from the configured target/adapter/extensions, and serializes the\n migration's operations + metadata next to this file.\n `,\n\t\texamples: [\n\t\t\t[\"Self-emit ops.json + migration.json next to migration.ts\", \"$0\"],\n\t\t\t[\"Preview without writing files\", \"$0 --dry-run\"],\n\t\t\t[\"Use a non-default config path\", \"$0 --config ./custom.config.ts\"]\n\t\t]\n\t});\n\tdryRun = Option.Boolean(\"--dry-run\", false, { description: \"Print operations to stdout without writing files\" });\n\tconfig = Option.String(\"--config\", { description: \"Path to prisma.config.ts\" });\n\t/**\n\t* Unused: orchestration runs inside `MigrationCLI.run` so error\n\t* routing stays under our control (clipanion's `cli.run` writes\n\t* error output to `context.stdout`, but our contract requires\n\t* structured errors on stderr). `cli.process` is used to parse\n\t* argv into a populated `MigrationFileCommand` instance whose\n\t* fields drive the orchestration directly.\n\t*/\n\tasync execute() {\n\t\treturn 0;\n\t}\n};\n/**\n* The CLI surface invoked by an authored `migration.ts` file. Exposed as\n* a class with a static `run` method (rather than a free function) to\n* give the concept a stable identity in the ubiquitous language: this is\n* the \"migration-file CLI\", distinct from the apply-time runner that\n* executes migration JSON ops.\n*\n* Currently a single static method. Future surface (e.g. a programmatic\n* `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n* land here without changing the import shape used by every authored\n* migration.\n*/\nvar MigrationCLI = class {\n\t/**\n\t* Orchestrates a class-flow `migration.ts` script run.\n\t*\n\t* The third argument is the in-process testability surface: callers\n\t* (and tests) may inject `argv`, `stdout`, and `stderr` instead of\n\t* relying on `process.argv` / `process.stdout` / `process.stderr`.\n\t* Each option defaults to its `process` global when omitted, so\n\t* existing two-argument call sites\n\t* (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to\n\t* compile and behave identically.\n\t*\n\t* Returns the exit code so the caller can branch on it. Also writes\n\t* the same code to `process.exitCode` so script-style callers that\n\t* don't await the return value still surface a non-zero exit when\n\t* something fails.\n\t*\n\t* Exit codes:\n\t* - 0 — success, or `--help`, or imported-not-entrypoint no-op.\n\t* - 1 — runtime/orchestration error (config not found, target\n\t* mismatch, etc.).\n\t* - 2 — usage error (unknown flag, malformed `--config`). Aligns\n\t* with `docs/CLI Style Guide.md` § Exit Codes.\n\t*/\n\tstatic async run(importMetaUrl, MigrationClass, options = {}) {\n\t\tif (!importMetaUrl) return 0;\n\t\tconst argv = options.argv ?? process.argv;\n\t\tconst stdout = options.stdout ?? process.stdout;\n\t\tconst stderr = options.stderr ?? process.stderr;\n\t\tif (!isDirectEntrypoint(importMetaUrl, argv)) return 0;\n\t\tconst exitCode = await orchestrate(importMetaUrl, MigrationClass, {\n\t\t\targv,\n\t\t\tstdout,\n\t\t\tstderr\n\t\t});\n\t\tif (exitCode !== 0 || !process.exitCode) process.exitCode = exitCode;\n\t\treturn exitCode;\n\t}\n};\n/**\n* Argv-aware variant of the entrypoint guard. The shared\n* `@internal/migration-tools` helper of the same name reads\n* `process.argv[1]` directly, which doesn't compose with the new\n* in-process testability surface (tests inject `argv` without mutating\n* the process global). Inlined here so the migration-file CLI's check\n* follows the injected `argv[1]` consistently.\n*/\nfunction isDirectEntrypoint(importMetaUrl, argv) {\n\tconst argv1 = argv[1];\n\tif (!argv1) return false;\n\ttry {\n\t\treturn realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Argv-and-stream-driven orchestration body. Pulled out of the static\n* method so the entrypoint guard / process-default plumbing stays\n* separate from the parse + load + serialize steps.\n*/\nasync function orchestrate(importMetaUrl, MigrationClass, ctx) {\n\tconst cli = Cli.from([MigrationFileCommand], {\n\t\tbinaryName: \"migration.ts\",\n\t\tbinaryLabel: \"Migration file CLI\"\n\t});\n\tconst input = ctx.argv.slice(2);\n\tconst configError = detectInvalidConfig(input);\n\tif (configError) {\n\t\twriteStructuredError(ctx.stderr, configError);\n\t\treturn 2;\n\t}\n\tlet parsed;\n\ttry {\n\t\tconst command = cli.process({\n\t\t\tinput: [...input],\n\t\t\tcontext: {\n\t\t\t\tstdout: ctx.stdout,\n\t\t\t\tstderr: ctx.stderr\n\t\t\t}\n\t\t});\n\t\tif (!(command instanceof MigrationFileCommand)) {\n\t\t\tctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n\t\t\treturn 0;\n\t\t}\n\t\tparsed = command;\n\t} catch (err) {\n\t\treturn renderParseError(err, input, ctx.stderr);\n\t}\n\tif (parsed.help) {\n\t\tctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n\t\treturn 0;\n\t}\n\ttry {\n\t\tawait runMigration(importMetaUrl, MigrationClass, parsed, ctx);\n\t\treturn 0;\n\t} catch (err) {\n\t\tif (CliStructuredError.is(err)) writeStructuredError(ctx.stderr, err);\n\t\telse ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n\t\treturn 1;\n\t}\n}\n/**\n* Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`\n* contains a malformed `--config`:\n*\n* - `--config` as the last token (no value follows).\n* - `--config <flag>` where `<flag>` starts with `-` (silently\n* consuming the next flag would either drop the flag or serialize\n* against the wrong project).\n* - `--config <empty>` where the value is the empty string. Shells\n* expand `--config \"\"` (or `--config \"$UNSET_VAR\"`) into a real\n* empty argv token; treating that as a usage error here surfaces\n* `CLI.CONFIG_ARG_MISSING_PATH` instead of a less actionable loader error on an\n* empty path.\n* - `--config=` (the equals form with an empty value). Same shape as\n* the empty-string case above; the user expressed intent to override\n* the config path but the override is empty.\n*\n* `--config=<value>` and `--config <value>` with a non-empty value are\n* both valid (and the equals form's value is allowed to start with\n* `-` — the `=` makes the binding explicit).\n*/\nfunction detectInvalidConfig(input) {\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst token = input[i];\n\t\tif (token === \"--config\") {\n\t\t\tconst next = input[i + 1];\n\t\t\tif (next === void 0 || next === \"\") return errorMigrationCliInvalidConfigArg();\n\t\t\tif (next.startsWith(\"-\")) return errorMigrationCliInvalidConfigArg({ nextToken: next });\n\t\t\tcontinue;\n\t\t}\n\t\tif (token === \"--config=\") return errorMigrationCliInvalidConfigArg();\n\t}\n\treturn null;\n}\n/**\n* Translate clipanion's parse-time errors into the project's structured\n* error envelopes.\n*\n* - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and\n* the bare-trailing `--config` case (where arity-1 needs a value but\n* none was supplied). Distinguished by inspecting the input array.\n* - `UsageError` covers schema/validator failures from typanion. None\n* of the migration-file CLI's options have validators today, but we\n* still translate it as a usage error (exit 2) for forward-compat.\n* - Anything else re-throws — caller's outer catch will surface it as\n* exit 1 (runtime error).\n*/\nfunction renderParseError(err, input, stderr) {\n\tif (isUnknownSyntaxError(err)) {\n\t\twriteStructuredError(stderr, errorMigrationCliUnknownFlag({\n\t\t\tflag: findOffendingFlag(input),\n\t\t\tknownFlags: KNOWN_FLAGS\n\t\t}));\n\t\treturn 2;\n\t}\n\tif (err instanceof UsageError) {\n\t\twriteStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));\n\t\treturn 2;\n\t}\n\tthrow err;\n}\n/**\n* Duck-type check for clipanion's `UnknownSyntaxError`: the class is\n* thrown by the parser but is not re-exported from the package's main\n* entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).\n* Identified by `name === 'UnknownSyntaxError'` and the\n* `clipanion.type === 'none'` discriminator that clipanion's\n* `ErrorWithMeta` interface guarantees.\n*/\nfunction isUnknownSyntaxError(err) {\n\tif (!(err instanceof Error) || err.name !== \"UnknownSyntaxError\") return false;\n\tconst meta = err.clipanion;\n\treturn typeof meta === \"object\" && meta !== null && meta.type === \"none\";\n}\n/**\n* Best-effort: pull the first input token that doesn't match a known\n* flag. Falls back to the first token when we can't pinpoint it. The\n* returned name is rendered into the user-visible CLI.UNKNOWN_FLAG envelope\n* (`Unknown flag \\`<name>\\``) and round-tripped via `meta.flag` so\n* agent consumers can render their own \"did you mean\" suggestions.\n*/\nfunction findOffendingFlag(input) {\n\tfor (const token of input) {\n\t\tif (!token.startsWith(\"-\")) continue;\n\t\tconst head = token.split(\"=\", 1)[0] ?? token;\n\t\tif (!KNOWN_FLAGS.includes(head) && head !== \"-h\") return head;\n\t}\n\treturn input[0] ?? \"\";\n}\n/**\n* Write a `CliStructuredError` envelope to the given stream. Format\n* matches the legacy hand-rolled writer (`message: why`) so the rest of\n* the project's error rendering stays consistent across surfaces. The\n* full PN code (`PN-<domain>-<code>`) is included so consumers can\n* grep for stable identifiers.\n*/\nfunction writeStructuredError(stream, err) {\n\tconst envelope = err.toEnvelope();\n\tconst why = envelope.why ?? envelope.summary;\n\tconst fix = envelope.fix ? `\\n${envelope.fix}` : \"\";\n\tstream.write(`${envelope.code}: ${envelope.summary}\\n${why}${fix}\\n`);\n}\n/**\n* Read a previously-scaffolded `migration.json` from disk, returning\n* `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`\n* when the file is present but cannot be parsed as JSON. The CLI feeds\n* this into `buildMigrationArtifacts` so the pure builder can preserve\n* fields owned by `migration plan` (contract bookends, `createdAt`) across\n* re-emits.\n*\n* Author-time path: this loader still does not verify the manifest hash\n* or schema — that is the apply-time loader's job. Hash mismatch is the\n* *expected* outcome of a re-author (the developer's source changes\n* invalidate the prior hash by construction), and verification here\n* would block legitimate regenerations. Syntactic JSON-parse failure,\n* however, is now surfaced rather than swallowed: a malformed\n* `migration.json` indicates either a hand-edit gone wrong or partial\n* write, and silently rebuilding from `describe()` would discard the\n* user's on-disk content (preserved bookends, `createdAt`) without any\n* indication something was wrong on disk.\n* Apply-time consumers always route through the verifying\n* `readMigrationPackage` in `@internal/migration-tools/io` instead.\n*/\nfunction readExistingMetadata(metadataPath) {\n\tlet raw;\n\ttry {\n\t\traw = readFileSync(metadataPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));\n\t}\n}\n/**\n* Persist a migration instance's artifacts to `migrationDir`. In\n* `dryRun` mode the artifacts are printed to stdout (with the same\n* `--- migration.json --- / --- ops.json ---` framing the legacy\n* `serializeMigration` helper used) and no files are written. Otherwise\n* `ops.json` and `migration.json` are written next to `migration.ts` and\n* a confirmation line is printed.\n*\n* File I/O lives in the CLI rather than `@internal/migration-tools`\n* so the migration-tools package stays focused on the pure\n* `Migration` → in-memory artifact conversion. The CLI is the only\n* legitimate site for combining config loading, stack assembly, and\n* filesystem persistence.\n*/\nasync function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {\n\tconst metadataPath = join(migrationDir, \"migration.json\");\n\tconst { opsJson, metadataJson } = await buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));\n\tif (dryRun) {\n\t\tstdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n\t\tstdout.write(\"--- ops.json ---\\n\");\n\t\tstdout.write(`${opsJson}\\n`);\n\t\treturn;\n\t}\n\twriteFileSync(join(migrationDir, \"ops.json\"), opsJson);\n\twriteFileSync(metadataPath, metadataJson);\n\tstdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`);\n}\n/**\n* Inner orchestration: load config, probe-construct the migration,\n* verify target, assemble the stack, construct with the stack, persist.\n*\n* Throws `CliStructuredError` for known failure modes (config not\n* found, target mismatch); the outer `orchestrate` translates those to\n* exit 1.\n*/\nasync function runMigration(importMetaUrl, MigrationClass, parsed, ctx) {\n\tconst migrationDir = dirname(fileURLToPath(importMetaUrl));\n\tconst configResult = await loadConfigForSections(parsed.config, [\n\t\t\"family\",\n\t\t\"target\",\n\t\t\"adapter\",\n\t\t\"driver\",\n\t\t\"extensions\"\n\t]);\n\tif (!configResult.ok) throw configResult.failure;\n\tconst config = configResult.value;\n\tconst probe = new MigrationClass();\n\tif (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({\n\t\tmigrationTargetId: probe.targetId,\n\t\tconfigTargetId: config.target.targetId\n\t});\n\tawait serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);\n\tctx.stderr;\n}\n//#endregion\nexport { MigrationCLI };\n\n//# sourceMappingURL=migration-cli.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,cAAc;CACnB;CACA;CACA;AACD;;;;;;;;AAQA,IAAI,uBAAuB,cAAc,QAAQ;CAChD,OAAO,QAAQ,CAAC,QAAQ,OAAO;CAC/B,OAAO,QAAQ,QAAQ,MAAM;EAC5B,aAAa;EACb,SAAS;;;;;EAKT,UAAU;GACT,CAAC,4DAA4D,IAAI;GACjE,CAAC,iCAAiC,cAAc;GAChD,CAAC,iCAAiC,gCAAgC;EACnE;CACD,CAAC;CACD,SAAS,OAAO,QAAQ,aAAa,OAAO,EAAE,aAAa,mDAAmD,CAAC;CAC/G,SAAS,OAAO,OAAO,YAAY,EAAE,aAAa,2BAA2B,CAAC;;;;;;;;;CAS9E,MAAM,UAAU;EACf,OAAO;CACR;AACD;;;;;;;;;;;;;AAaA,IAAI,eAAe,MAAM;;;;;;;;;;;;;;;;;;;;;;;;CAwBxB,aAAa,IAAI,eAAe,gBAAgB,UAAU,CAAC,GAAG;EAC7D,IAAI,CAAC,eAAe,OAAO;EAC3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zD,MAAM,eAAe,MAAM,sBAAsB,OAAO,QAAQ;EAC/D;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,IAAI,CAAC,aAAa,IAAI,MAAM,aAAa;CACzC,MAAM,SAAS,aAAa;CAC5B,MAAM,QAAQ,IAAI,eAAe;CACjC,IAAI,MAAM,aAAa,OAAO,OAAO,UAAU,MAAM,6BAA6B;EACjF,mBAAmB,MAAM;EACzB,gBAAgB,OAAO,OAAO;CAC/B,CAAC;CACD,MAAM,yBAAyB,IAAI,eAAe,mBAAmB,MAAM,CAAC,GAAG,cAAc,OAAO,QAAQ,IAAI,MAAM;CACtH,IAAI;AACL"}
@@ -1,11 +1,11 @@
1
- import { a as errorContractSnapshotHashMismatch, g as errorInvalidJson, o as errorContractSnapshotMissing } from "./errors-CcEpbfnE-CsSXrttT.mjs";
1
+ import { a as errorContractSnapshotHashMismatch, g as errorInvalidJson, o as errorContractSnapshotMissing } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
2
  import { blindCast } from "@prisma/orm-framework/utils/casts";
3
3
  import { CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex } from "@prisma/orm-framework/components/control";
4
4
  import { join, relative } from "pathe";
5
5
  import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import { randomBytes } from "node:crypto";
7
7
  import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
8
- //#region ../../../1-framework/3-tooling/migration/dist/contract-snapshot-store-BAmQkHe5.mjs
8
+ //#region ../../../1-framework/3-tooling/migration/dist/contract-snapshot-store-qGrwlGmt.mjs
9
9
  const CONTRACT_JSON_FILE = "contract.json";
10
10
  const CONTRACT_DTS_FILE = "contract.d.ts";
11
11
  function hasErrnoCode(error, code) {
@@ -115,4 +115,4 @@ function snapshotsImportPathFrom(packageDir, migrationsDir) {
115
115
  //#endregion
116
116
  export { snapshotsImportPathFrom as a, readContractSnapshotJsonTolerant as i, readContractSnapshotDts as n, writeContractSnapshot as o, readContractSnapshotJson as r, contractSnapshotDir as t };
117
117
 
118
- //# sourceMappingURL=contract-snapshot-store-BAmQkHe5-BJFpuIQQ.mjs.map
118
+ //# sourceMappingURL=contract-snapshot-store-qGrwlGmt-Cf2NFzRL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract-snapshot-store-BAmQkHe5-BJFpuIQQ.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/contract-snapshot-store-BAmQkHe5.mjs"],"sourcesContent":["import { a as errorContractSnapshotHashMismatch, g as errorInvalidJson, o as errorContractSnapshotMissing } from \"./errors-CcEpbfnE.mjs\";\nimport { join, relative } from \"pathe\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { randomBytes } from \"node:crypto\";\nimport { CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex } from \"@internal/framework-components/control\";\nimport { canonicalizeJson } from \"@internal/framework-components/utils\";\nimport { blindCast } from \"@internal/utils/casts\";\n//#region src/contract-snapshot-store.ts\nconst CONTRACT_JSON_FILE = \"contract.json\";\nconst CONTRACT_DTS_FILE = \"contract.d.ts\";\nfunction hasErrnoCode(error, code) {\n\treturn error instanceof Error && blindCast(error).code === code;\n}\nasync function directoryExists(p) {\n\ttry {\n\t\treturn (await stat(p)).isDirectory();\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return false;\n\t\tthrow error;\n\t}\n}\nfunction contractSnapshotDir(migrationsDir, storageHash) {\n\treturn join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex(storageHash));\n}\nasync function writeContractSnapshot(migrationsDir, storageHash, input) {\n\tconst dir = contractSnapshotDir(migrationsDir, storageHash);\n\tconst actualStorageHash = blindCast(input.contractJson).storage?.storageHash;\n\tif (actualStorageHash !== storageHash) throw errorContractSnapshotHashMismatch(storageHash, typeof actualStorageHash === \"string\" ? actualStorageHash : String(actualStorageHash), dir);\n\tif (await directoryExists(dir)) return {\n\t\twritten: false,\n\t\tdir\n\t};\n\tconst tmpDir = join(join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME), `.tmp-${storageHashHex(storageHash)}-${Date.now()}-${randomBytes(4).toString(\"hex\")}`);\n\tawait mkdir(tmpDir, { recursive: true });\n\tconst jsonContent = `${canonicalizeJson(input.contractJson)}\\n`;\n\tconst dtsContent = input.contractDts.endsWith(\"\\n\") ? input.contractDts : `${input.contractDts}\\n`;\n\ttry {\n\t\tawait writeFile(join(tmpDir, CONTRACT_JSON_FILE), jsonContent);\n\t\tawait writeFile(join(tmpDir, CONTRACT_DTS_FILE), dtsContent);\n\t\tawait rename(tmpDir, dir);\n\t} catch (error) {\n\t\tawait rm(tmpDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tif (hasErrnoCode(error, \"EEXIST\") || hasErrnoCode(error, \"ENOTEMPTY\")) return {\n\t\t\twritten: false,\n\t\t\tdir\n\t\t};\n\t\tthrow error;\n\t}\n\treturn {\n\t\twritten: true,\n\t\tdir\n\t};\n}\nasync function readContractSnapshotJson(migrationsDir, storageHash) {\n\tconst jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n\tlet raw;\n\ttry {\n\t\traw = await readFile(jsonPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorContractSnapshotMissing(storageHash, jsonPath);\n\t\tthrow error;\n\t}\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(jsonPath, e instanceof Error ? e.message : String(e));\n\t}\n}\n/**\n* Tolerant read: a missing store entry (ENOENT), an unparseable\n* `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a\n* well-formed 64-hex value all resolve to `undefined` rather than\n* throwing — parity with the catch-all tolerance of the pre-store\n* `readEndContractJson` (`io.ts`), which never validated the hash it was\n* keyed by either. Any other fs error (e.g. `EACCES` on a present-but-\n* unreadable file) propagates rather than silently loading a contract-less\n* package.\n*/\nasync function readContractSnapshotJsonTolerant(migrationsDir, storageHash) {\n\tlet jsonPath;\n\ttry {\n\t\tjsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n\t} catch {\n\t\treturn;\n\t}\n\tlet raw;\n\ttry {\n\t\traw = await readFile(jsonPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return;\n\t\tthrow error;\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(raw);\n\t\treturn parsed === null ? void 0 : parsed;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function readContractSnapshotDts(migrationsDir, storageHash) {\n\tconst dtsPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_DTS_FILE);\n\ttry {\n\t\treturn await readFile(dtsPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorContractSnapshotMissing(storageHash, dtsPath);\n\t\tthrow error;\n\t}\n}\nfunction snapshotsImportPathFrom(packageDir, migrationsDir) {\n\treturn relative(packageDir, join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME)).split(\"\\\\\").join(\"/\");\n}\n//#endregion\nexport { snapshotsImportPathFrom as a, readContractSnapshotJsonTolerant as i, readContractSnapshotDts as n, writeContractSnapshot as o, readContractSnapshotJson as r, contractSnapshotDir as t };\n\n//# sourceMappingURL=contract-snapshot-store-BAmQkHe5.mjs.map"],"mappings":";;;;;;;;AAQA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,SAAS,aAAa,OAAO,MAAM;CAClC,OAAO,iBAAiB,SAAS,UAAU,KAAK,CAAC,CAAC,SAAS;AAC5D;AACA,eAAe,gBAAgB,GAAG;CACjC,IAAI;EACH,QAAQ,MAAM,KAAK,CAAC,EAAA,CAAG,YAAY;CACpC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,OAAO;EAC1C,MAAM;CACP;AACD;AACA,SAAS,oBAAoB,eAAe,aA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,aAAa,OAAO,QAAQ,GAAG,MAAM,6BAA6B,aAAa,QAAQ;EAC3F,MAAM;CACP;CACA,IAAI;EACH,OAAO,KAAK,MAAM,GAAG;CACtB,SAAS,GAAG;EACX,MAAM,iBAAiB,UAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CAC5E;AACD;;;;;;;;;;;AAWA,eAAe,iCAAiC,eAAe,aAAa;CAC3E,IAAI;CACJ,IAAI;EACH,WAAW,KAAK,oBAAoB,eAAe,WAAW,GAAG,kBAAkB;CACpF,QAAQ;EACP;CACD;CACA,IAAI;CACJ,IAAI;EACH,MAAM,MAAM,SAAS,UAAU,OAAO;CACvC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG;EACnC,MAAM;CACP;CACA,IAAI;EACH,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,WAAW,OAAO,KAAK,IAAI;CACnC,QAAQ;EACP;CACD;AACD;AACA,eAAe,wBAAwB,eAAe,aAAa;CAClE,MAAM,UAAU,KAAK,oBAAoB,eAAe,WAAW,GAAG,iBAAiB;CACvF,IAAI;EACH,OAAO,MAAM,SAAS,SAAS,OAAO;CACvC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,MAAM,6BAA6B,aAAa,OAAO;EAC1F,MAAM;CACP;AACD;AACA,SAAS,wBAAwB,YAAY,eAAe;CAC3D,OAAO,SAAS,YAAY,KAAK,eAAe,0BAA0B,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AAClG"}
1
+ {"version":3,"file":"contract-snapshot-store-qGrwlGmt-Cf2NFzRL.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/contract-snapshot-store-qGrwlGmt.mjs"],"sourcesContent":["import { a as errorContractSnapshotHashMismatch, g as errorInvalidJson, o as errorContractSnapshotMissing } from \"./errors-SoLLYLtw.mjs\";\nimport { join, relative } from \"pathe\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { randomBytes } from \"node:crypto\";\nimport { CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex } from \"@internal/framework-components/control\";\nimport { canonicalizeJson } from \"@internal/framework-components/utils\";\nimport { blindCast } from \"@internal/utils/casts\";\n//#region src/contract-snapshot-store.ts\nconst CONTRACT_JSON_FILE = \"contract.json\";\nconst CONTRACT_DTS_FILE = \"contract.d.ts\";\nfunction hasErrnoCode(error, code) {\n\treturn error instanceof Error && blindCast(error).code === code;\n}\nasync function directoryExists(p) {\n\ttry {\n\t\treturn (await stat(p)).isDirectory();\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return false;\n\t\tthrow error;\n\t}\n}\nfunction contractSnapshotDir(migrationsDir, storageHash) {\n\treturn join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex(storageHash));\n}\nasync function writeContractSnapshot(migrationsDir, storageHash, input) {\n\tconst dir = contractSnapshotDir(migrationsDir, storageHash);\n\tconst actualStorageHash = blindCast(input.contractJson).storage?.storageHash;\n\tif (actualStorageHash !== storageHash) throw errorContractSnapshotHashMismatch(storageHash, typeof actualStorageHash === \"string\" ? actualStorageHash : String(actualStorageHash), dir);\n\tif (await directoryExists(dir)) return {\n\t\twritten: false,\n\t\tdir\n\t};\n\tconst tmpDir = join(join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME), `.tmp-${storageHashHex(storageHash)}-${Date.now()}-${randomBytes(4).toString(\"hex\")}`);\n\tawait mkdir(tmpDir, { recursive: true });\n\tconst jsonContent = `${canonicalizeJson(input.contractJson)}\\n`;\n\tconst dtsContent = input.contractDts.endsWith(\"\\n\") ? input.contractDts : `${input.contractDts}\\n`;\n\ttry {\n\t\tawait writeFile(join(tmpDir, CONTRACT_JSON_FILE), jsonContent);\n\t\tawait writeFile(join(tmpDir, CONTRACT_DTS_FILE), dtsContent);\n\t\tawait rename(tmpDir, dir);\n\t} catch (error) {\n\t\tawait rm(tmpDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tif (hasErrnoCode(error, \"EEXIST\") || hasErrnoCode(error, \"ENOTEMPTY\")) return {\n\t\t\twritten: false,\n\t\t\tdir\n\t\t};\n\t\tthrow error;\n\t}\n\treturn {\n\t\twritten: true,\n\t\tdir\n\t};\n}\nasync function readContractSnapshotJson(migrationsDir, storageHash) {\n\tconst jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n\tlet raw;\n\ttry {\n\t\traw = await readFile(jsonPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorContractSnapshotMissing(storageHash, jsonPath);\n\t\tthrow error;\n\t}\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(jsonPath, e instanceof Error ? e.message : String(e));\n\t}\n}\n/**\n* Tolerant read: a missing store entry (ENOENT), an unparseable\n* `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a\n* well-formed 64-hex value all resolve to `undefined` rather than\n* throwing — parity with the catch-all tolerance of the pre-store\n* `readEndContractJson` (`io.ts`), which never validated the hash it was\n* keyed by either. Any other fs error (e.g. `EACCES` on a present-but-\n* unreadable file) propagates rather than silently loading a contract-less\n* package.\n*/\nasync function readContractSnapshotJsonTolerant(migrationsDir, storageHash) {\n\tlet jsonPath;\n\ttry {\n\t\tjsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n\t} catch {\n\t\treturn;\n\t}\n\tlet raw;\n\ttry {\n\t\traw = await readFile(jsonPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return;\n\t\tthrow error;\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(raw);\n\t\treturn parsed === null ? void 0 : parsed;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function readContractSnapshotDts(migrationsDir, storageHash) {\n\tconst dtsPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_DTS_FILE);\n\ttry {\n\t\treturn await readFile(dtsPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorContractSnapshotMissing(storageHash, dtsPath);\n\t\tthrow error;\n\t}\n}\nfunction snapshotsImportPathFrom(packageDir, migrationsDir) {\n\treturn relative(packageDir, join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME)).split(\"\\\\\").join(\"/\");\n}\n//#endregion\nexport { snapshotsImportPathFrom as a, readContractSnapshotJsonTolerant as i, readContractSnapshotDts as n, writeContractSnapshot as o, readContractSnapshotJson as r, contractSnapshotDir as t };\n\n//# sourceMappingURL=contract-snapshot-store-qGrwlGmt.mjs.map"],"mappings":";;;;;;;;AAQA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,SAAS,aAAa,OAAO,MAAM;CAClC,OAAO,iBAAiB,SAAS,UAAU,KAAK,CAAC,CAAC,SAAS;AAC5D;AACA,eAAe,gBAAgB,GAAG;CACjC,IAAI;EACH,QAAQ,MAAM,KAAK,CAAC,EAAA,CAAG,YAAY;CACpC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,OAAO;EAC1C,MAAM;CACP;AACD;AACA,SAAS,oBAAoB,eAAe,aAAa;CACxD,OAAO,KAAK,eAAe,4BAA4B,eAAe,WAAW,CAAC;AACnF;AACA,eAAe,sBAAsB,eAAe,aAAa,OAAO;CACvE,MAAM,MAAM,oBAAoB,eAAe,WAAW;CAC1D,MAAM,oBAAoB,UAAU,MAAM,YAAY,CAAC,CAAC,SAAS;CACjE,IAAI,sBAAsB,aAAa,MAAM,kCAAkC,aAAa,OAAO,sBAAsB,WAAW,oBAAoB,OAAO,iBAAiB,GAAG,GAAG;CACtL,IAAI,MAAM,gBAAgB,GAAG,GAAG,OAAO;EACtC,SAAS;EACT;CACD;CACA,MAAM,SAAS,KAAK,KAAK,eAAe,0BAA0B,GAAG,QAA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vC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG;EACnC,MAAM;CACP;CACA,IAAI;EACH,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,WAAW,OAAO,KAAK,IAAI;CACnC,QAAQ;EACP;CACD;AACD;AACA,eAAe,wBAAwB,eAAe,aAAa;CAClE,MAAM,UAAU,KAAK,oBAAoB,eAAe,WAAW,GAAG,iBAAiB;CACvF,IAAI;EACH,OAAO,MAAM,SAAS,SAAS,OAAO;CACvC,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,MAAM,6BAA6B,aAAa,OAAO;EAC1F,MAAM;CACP;AACD;AACA,SAAS,wBAAwB,YAAY,eAAe;CAC3D,OAAO,SAAS,YAAY,KAAK,eAAe,0BAA0B,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AAClG"}
@@ -1,7 +1,7 @@
1
1
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
2
2
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
3
3
  import { dirname, relative } from "pathe";
4
- //#region ../../../1-framework/3-tooling/migration/dist/errors-CcEpbfnE.mjs
4
+ //#region ../../../1-framework/3-tooling/migration/dist/errors-SoLLYLtw.mjs
5
5
  /**
6
6
  * Build the canonical "re-emit this package" remediation hint.
7
7
  *
@@ -164,7 +164,7 @@ function errorAmbiguousTarget(branchTips, context) {
164
164
  const divergenceInfo = context ? `\nDivergence point: ${context.divergencePoint}\nBranches:\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(" → ") || "direct"})`).join("\n")}` : "";
165
165
  return new MigrationToolsError("MIGRATION.AMBIGUOUS_TARGET", "Ambiguous migration target", {
166
166
  why: `The migration history has diverged into multiple branches: ${branchTips.join(", ")}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,
167
- fix: "Use `ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `migration plan`, or use --from <hash> to explicitly select a starting point.",
167
+ fix: "Use `{bin} migration ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `{bin} migration plan`, or use --from <hash> to explicitly select a starting point.",
168
168
  meta: {
169
169
  branchTips,
170
170
  ...context ? {
@@ -208,7 +208,7 @@ function errorNoTarget(reachableHashes) {
208
208
  function errorInvalidRefValue(value) {
209
209
  return new MigrationToolsError("MIGRATION.INVALID_REF_VALUE", "Invalid ref value", {
210
210
  why: `Ref value "${value}" is not a valid contract hash. Values must be a 64-character hex digest or "empty".`,
211
- fix: "Use a valid storage hash from `prisma contract emit` output or an existing migration.",
211
+ fix: "Use a valid storage hash from `{bin} contract emit` output or an existing migration.",
212
212
  nextActions: [{
213
213
  kind: "run-command",
214
214
  label: "Emit the contract to obtain a valid storage hash",
@@ -301,12 +301,12 @@ function errorMigrationHashMismatch(dir, storedHash, computedHash) {
301
301
  function errorRefNotResolvable(refName) {
302
302
  return new MigrationToolsError("MIGRATION.REF_NOT_RESOLVABLE", `Ref "${refName}" is not resolvable`, {
303
303
  why: `Ref "${refName}" has no pointer file, and the hash being resolved is not a node in the migration graph either — there is nothing to materialize a contract from.`,
304
- fix: `Create the ref with "prisma ref set ${refName} <hash>" (or advance it via "prisma db update --advance-ref ${refName}"), or pass a hash that is a node in the migration graph.`,
304
+ fix: `Create the ref with "{bin} migration ref set ${refName} <hash>" (or advance it via "{bin} db update --advance-ref ${refName}"), or pass a hash that is a node in the migration graph.`,
305
305
  nextActions: [
306
306
  {
307
307
  kind: "run-command",
308
308
  label: `Create the ref "${refName}"`,
309
- command: `{bin} ref set ${refName} <hash>`
309
+ command: `{bin} migration ref set ${refName} <hash>`
310
310
  },
311
311
  {
312
312
  kind: "run-command",
@@ -327,7 +327,7 @@ function errorRefNotResolvable(refName) {
327
327
  function errorBundleNotFoundForGraphNode(hash, explicitLabel) {
328
328
  return new MigrationToolsError("MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE", explicitLabel ? `No migration bundle found for reference "${explicitLabel}" (resolved hash: ${hash})` : `No migration bundle found for graph node ${hash}`, {
329
329
  why: `The hash ${hash} is a graph node but no on-disk migration package has a destination (\`to\`) hash matching it.`,
330
- fix: "Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.",
330
+ fix: "Provide a ref or hash that corresponds to an existing migration package, or run `{bin} migration list` to see available migrations.",
331
331
  meta: {
332
332
  hash,
333
333
  ...explicitLabel ? { explicitLabel } : {}
@@ -350,7 +350,7 @@ function errorHashNotInGraph(hash, graph) {
350
350
  const reachableList = reachableHashes.length > 0 ? reachableHashes.join(", ") : "(none)";
351
351
  return new MigrationToolsError("MIGRATION.HASH_NOT_IN_GRAPH", `Hash "${hash}" is not a node in the migration graph`, {
352
352
  why: `The migration graph contains nodes ${reachableList}; "${hash}" isn't one of them.`,
353
- fix: `Pass a hash that's the from-or-to of an on-disk migration bundle, use --from with a graph-node hash, or run "prisma migration plan" to introduce it.`,
353
+ fix: `Pass a hash that's the from-or-to of an on-disk migration bundle, use --from with a graph-node hash, or run "{bin} migration plan" to introduce it.`,
354
354
  nextActions: [{
355
355
  kind: "user-choice",
356
356
  label: "Pass a hash that is the from-or-to of an on-disk migration bundle, or use --from with a graph-node hash",
@@ -369,7 +369,7 @@ function errorHashNotInGraph(hash, graph) {
369
369
  function errorContractSnapshotMissing(storageHash, expectedPath) {
370
370
  return new MigrationToolsError("MIGRATION.CONTRACT_SNAPSHOT_MISSING", "Contract snapshot is missing", {
371
371
  why: `Expected a contract snapshot for ${storageHash} at "${expectedPath}" but the file does not exist.`,
372
- fix: "Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`prisma migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.",
372
+ fix: "Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`{bin} migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.",
373
373
  nextActions: [
374
374
  {
375
375
  kind: "run-command",
@@ -416,4 +416,4 @@ function errorMigrationContractViewMissing(className, accessor, jsonField) {
416
416
  //#endregion
417
417
  export { errorOperationsNotArray as A, errorInvalidSpaceId as C, errorNoInitialMigration as D, errorMissingFile as E, errorRefNotResolvable as M, errorSpaceHeadRefMissing as N, errorNoInvariantPath as O, errorUnknownInvariant as P, errorInvalidSlug as S, errorMigrationHashMismatch as T, errorInvalidManifest as _, errorContractSnapshotHashMismatch as a, errorInvalidRefName as b, errorDescribeMissingEndContract as c, errorDuplicateInvariantInEdge as d, errorDuplicateSpaceId as f, errorInvalidJson as g, errorInvalidInvariantId as h, errorContractDeserializationFailed as i, errorProvidedInvariantsMismatch as j, errorNoTarget as k, errorDescriptorHeadHashMismatch as l, errorInvalidDestName as m, errorAmbiguousTarget as n, errorContractSnapshotMissing as o, errorHashNotInGraph as p, errorBundleNotFoundForGraphNode as r, errorDescribeInvalidMetadata as s, MigrationToolsError as t, errorDirectoryExists as u, errorInvalidOperationEntry as v, errorMigrationContractViewMissing as w, errorInvalidRefValue as x, errorInvalidRefFile as y };
418
418
 
419
- //# sourceMappingURL=errors-CcEpbfnE-CsSXrttT.mjs.map
419
+ //# sourceMappingURL=errors-SoLLYLtw-DMxVbVs9.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-SoLLYLtw-DMxVbVs9.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/errors-SoLLYLtw.mjs"],"sourcesContent":["import { CliStructuredError } from \"@internal/errors/control\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { dirname, relative } from \"pathe\";\n//#region src/errors.ts\n/**\n* Build the canonical \"re-emit this package\" remediation hint.\n*\n* Every on-disk migration package ships its own `migration.ts` author-time\n* file. Running it regenerates `migration.json` and `ops.json` with the\n* correct hash + metadata, so it is the right primitive whenever a single\n* package's on-disk artifacts are missing, malformed, or otherwise corrupt.\n* Pointing users at `migration plan` would emit a *new* package rather than\n* heal the broken one.\n*/\nfunction reemitHint(dir, fallback) {\n\tconst reemit = `Re-emit the package by running \\`node \"${relative(process.cwd(), dir)}/migration.ts\"\\``;\n\treturn fallback ? `${reemit}, ${fallback}` : `${reemit}.`;\n}\n/**\n* Structured error for migration tooling operations.\n*\n* Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under\n* the MIGRATION namespace. These are tooling-time errors (file I/O, hash\n* verification, migration history reconstruction), distinct from the runtime\n* MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,\n* etc.).\n*\n* Fields:\n* - code: Stable machine-readable code (MIGRATION.SUBCODE)\n* - category: Always 'MIGRATION'\n* - why: Explains the cause in plain language\n* - fix: Actionable remediation step\n* - meta: Machine-readable structured data for agents\n*/\nvar MigrationToolsError = class extends CliStructuredError {\n\tcategory;\n\tconstructor(code, summary, options) {\n\t\tsuper(code, summary, options);\n\t\tthis.category = \"MIGRATION\";\n\t}\n\tstatic is(error) {\n\t\treturn CliStructuredError.is(error) && \"category\" in error && error.category === \"MIGRATION\" && error.code.startsWith(\"MIGRATION.\");\n\t}\n};\nfunction errorDirectoryExists(dir) {\n\treturn new MigrationToolsError(\"MIGRATION.DIR_EXISTS\", \"Migration directory already exists\", {\n\t\twhy: `The directory \"${dir}\" already exists. Each migration must have a unique directory.`,\n\t\tfix: \"Use --name to pick a different name, or delete the existing directory and re-run.\",\n\t\tmeta: { dir }\n\t});\n}\nfunction errorMissingFile(file, dir) {\n\treturn new MigrationToolsError(\"MIGRATION.FILE_MISSING\", `Missing ${file}`, {\n\t\twhy: `Expected \"${file}\" in \"${dir}\" but the file does not exist.`,\n\t\tfix: reemitHint(dir, \"or delete the directory if the migration is unwanted and the source TypeScript is gone.\"),\n\t\tmeta: {\n\t\t\tfile,\n\t\t\tdir\n\t\t}\n\t});\n}\nfunction errorInvalidJson(filePath, parseError) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_JSON\", \"Invalid JSON in migration file\", {\n\t\twhy: `Failed to parse \"${filePath}\": ${parseError}`,\n\t\tfix: reemitHint(dirname(filePath), \"or restore the directory from version control.\"),\n\t\tmeta: {\n\t\t\tfilePath,\n\t\t\tparseError\n\t\t}\n\t});\n}\nfunction errorInvalidManifest(filePath, reason) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_MANIFEST\", \"Invalid migration manifest\", {\n\t\twhy: `Migration manifest at \"${filePath}\" is invalid: ${reason}`,\n\t\tfix: reemitHint(dirname(filePath), \"or restore the directory from version control.\"),\n\t\tmeta: {\n\t\t\tfilePath,\n\t\t\treason\n\t\t}\n\t});\n}\nfunction errorDescribeMissingEndContract() {\n\treturn new MigrationToolsError(\"MIGRATION.DESCRIBE_INVALID\", \"Migration.describe(): provide endContractJson or override describe() — a migration needs a destination contract hash.\", {\n\t\twhy: \"Migration.describe() was called on a migration that carries no endContractJson and does not override describe(), so no destination contract hash can be derived.\",\n\t\tfix: \"Set endContractJson on the migration, or override describe() to return the { from, to } metadata explicitly.\",\n\t\tmeta: { reason: \"missing-end-contract\" }\n\t});\n}\nfunction errorDescribeInvalidMetadata(summary) {\n\treturn new MigrationToolsError(\"MIGRATION.DESCRIBE_INVALID\", `describe() returned invalid metadata: ${summary}`, {\n\t\twhy: `The migration's describe() returned metadata that failed schema validation: ${summary}.`,\n\t\tfix: \"Ensure describe() returns { from: string | null, to: string } with valid contract hashes.\",\n\t\tmeta: {\n\t\t\treason: \"invalid-metadata\",\n\t\t\tsummary\n\t\t}\n\t});\n}\nfunction errorOperationsNotArray() {\n\treturn new MigrationToolsError(\"MIGRATION.PLAN_NOT_ARRAY\", \"operations must be an array\", {\n\t\twhy: \"The migration instance's `operations` getter returned a non-array value.\",\n\t\tfix: \"Ensure the `operations` getter returns an array of migration operations.\",\n\t\tmeta: {}\n\t});\n}\nfunction errorSpaceHeadRefMissing(spaceId) {\n\treturn new MigrationToolsError(\"MIGRATION.CHECK_HEAD_REF_MISSING\", `Contract space \"${spaceId}\" has no head ref; its contract cannot be resolved from the snapshot store without one.`, {\n\t\twhy: `Contract space \"${spaceId}\" declares no refs/head.json, so there is no hash to resolve its contract against the snapshot store.`,\n\t\tfix: \"Re-emit the contract-space migrations and head-ref artifacts (the extension's contract-space build), or restore refs/head.json from version control.\",\n\t\tmeta: { spaceId }\n\t});\n}\nfunction errorInvalidOperationEntry(index, reason) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_OPERATION_ENTRY\", \"Migration operation entry is malformed\", {\n\t\twhy: `Operation at index ${index} returned by the migration class failed schema validation: ${reason}.`,\n\t\tfix: \"Update the migration class so each entry of `operations` carries `id` (string), `label` (string), and `operationClass` (one of 'additive' | 'widening' | 'destructive' | 'data').\",\n\t\tmeta: {\n\t\t\tindex,\n\t\t\treason\n\t\t}\n\t});\n}\nfunction errorInvalidSlug(slug) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_NAME\", \"Invalid migration name\", {\n\t\twhy: `The slug \"${slug}\" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,\n\t\tfix: \"Provide a name with at least one alphanumeric character, e.g. --name add_users.\",\n\t\tmeta: { slug }\n\t});\n}\nfunction errorInvalidDestName(destName) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_DEST_NAME\", \"Invalid copy destination name\", {\n\t\twhy: `The destination name \"${destName}\" must be a single path segment (no \"..\" or directory separators).`,\n\t\tfix: \"Use a simple file name such as \\\"contract.json\\\" for each destination in the copy list.\",\n\t\tmeta: { destName }\n\t});\n}\nfunction errorInvalidSpaceId(spaceId) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_SPACE_ID\", \"Invalid contract space identifier\", {\n\t\twhy: `The space id \"${spaceId}\" does not match the required pattern /^[a-z][a-z0-9_-]{0,63}$/. Space ids are used as filesystem directory names under \\`migrations/\\`, so the pattern is conservative on purpose.`,\n\t\tfix: \"Pick a lowercase identifier that begins with a letter and contains only lowercase letters, digits, hyphens, or underscores; max 64 characters total.\",\n\t\tmeta: { spaceId }\n\t});\n}\nfunction errorDescriptorHeadHashMismatch(args) {\n\tconst { extensionId, recomputedHash, headRefHash } = args;\n\treturn new MigrationToolsError(\"MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH\", \"Extension descriptor's headRef.hash does not match its contractJson\", {\n\t\twhy: `Extension \"${extensionId}\" publishes a \\`contractSpace\\` whose \\`headRef.hash\\` (${headRefHash}) does not match the canonical hash recomputed from \\`contractSpace.contractJson\\` (${recomputedHash}). This means the extension descriptor was published with stale \\`headRef.hash\\` — typically because the contract was bumped without rerunning the extension's emit pipeline.`,\n\t\tfix: \"Re-run the extension authoring pipeline so `contractJson.storage.storageHash` and `headRef.hash` agree, then republish the extension. If you are the extension author and you intentionally bumped `contractJson`, recompute and update `headRef.hash` (and refresh any on-disk migration metadata that derives from it).\",\n\t\tmeta: {\n\t\t\textensionId,\n\t\t\trecomputedHash,\n\t\t\theadRefHash\n\t\t}\n\t});\n}\nfunction errorDuplicateSpaceId(spaceId) {\n\treturn new MigrationToolsError(\"MIGRATION.DUPLICATE_SPACE_ID\", \"Duplicate contract space identifier\", {\n\t\twhy: `The space id \"${spaceId}\" appears more than once in the per-space planner input. Each space id must be unique across the inputs (the per-space planner emits one output entry per id).`,\n\t\tfix: \"Deduplicate the inputs before passing them to `planAllSpaces` — typically by checking your `extensions` declaration for repeated entries.\",\n\t\tmeta: { spaceId }\n\t});\n}\nfunction errorAmbiguousTarget(branchTips, context) {\n\tconst divergenceInfo = context ? `\\nDivergence point: ${context.divergencePoint}\\nBranches:\\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(\" → \") || \"direct\"})`).join(\"\\n\")}` : \"\";\n\treturn new MigrationToolsError(\"MIGRATION.AMBIGUOUS_TARGET\", \"Ambiguous migration target\", {\n\t\twhy: `The migration history has diverged into multiple branches: ${branchTips.join(\", \")}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,\n\t\tfix: \"Use `{bin} migration ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `{bin} migration plan`, or use --from <hash> to explicitly select a starting point.\",\n\t\tmeta: {\n\t\t\tbranchTips,\n\t\t\t...context ? {\n\t\t\t\tdivergencePoint: context.divergencePoint,\n\t\t\t\tbranches: context.branches\n\t\t\t} : {}\n\t\t}\n\t});\n}\nfunction errorNoInitialMigration(nodes) {\n\treturn new MigrationToolsError(\"MIGRATION.NO_INITIAL_MIGRATION\", \"No initial migration found\", {\n\t\twhy: `No migration starts from the empty contract state (known hashes: ${nodes.join(\", \")}). At least one migration must originate from the empty state.`,\n\t\tfix: \"Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.\",\n\t\tmeta: { nodes }\n\t});\n}\nfunction errorInvalidRefFile(filePath, reason) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_REF_FILE\", \"Invalid ref file\", {\n\t\twhy: `Ref file at \"${filePath}\" is invalid: ${reason}`,\n\t\tfix: \"Ensure the ref file contains valid JSON with { \\\"hash\\\": \\\"<64 hex chars>\\\", \\\"invariants\\\": [\\\"...\\\"] }.\",\n\t\tmeta: {\n\t\t\tpath: filePath,\n\t\t\treason\n\t\t}\n\t});\n}\nfunction errorInvalidRefName(refName) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_REF_NAME\", \"Invalid ref name\", {\n\t\twhy: `Ref name \"${refName}\" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no \".\" or \"..\" segments).`,\n\t\tfix: `Use a valid ref name (e.g., \"staging\", \"envs/production\").`,\n\t\tmeta: { refName }\n\t});\n}\nfunction errorNoTarget(reachableHashes) {\n\treturn new MigrationToolsError(\"MIGRATION.NO_TARGET\", \"No migration target could be resolved\", {\n\t\twhy: `The migration history contains cycles and no target can be resolved automatically (reachable hashes: ${reachableHashes.join(\", \")}). This typically happens after rollback migrations (e.g., C1→C2→C1).`,\n\t\tfix: \"Use --from <hash> to specify the planning origin explicitly.\",\n\t\tmeta: { reachableHashes }\n\t});\n}\nfunction errorInvalidRefValue(value) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_REF_VALUE\", \"Invalid ref value\", {\n\t\twhy: `Ref value \"${value}\" is not a valid contract hash. Values must be a 64-character hex digest or \"empty\".`,\n\t\tfix: \"Use a valid storage hash from `{bin} contract emit` output or an existing migration.\",\n\t\tnextActions: [{\n\t\t\tkind: \"run-command\",\n\t\t\tlabel: \"Emit the contract to obtain a valid storage hash\",\n\t\t\tcommand: \"{bin} contract emit\"\n\t\t}, {\n\t\t\tkind: \"run-command\",\n\t\t\tlabel: \"List existing migrations to reuse one of their hashes\",\n\t\t\tcommand: \"{bin} migration list\"\n\t\t}],\n\t\tmeta: { value }\n\t});\n}\nfunction errorInvalidInvariantId(invariantId) {\n\treturn new MigrationToolsError(\"MIGRATION.INVALID_INVARIANT_ID\", \"Invalid invariantId\", {\n\t\twhy: `invariantId ${JSON.stringify(invariantId)} is invalid. Ids must be non-empty and contain no whitespace or control characters (including Unicode whitespace like NBSP); other content (kebab-case, camelCase, namespaced, Unicode letters) is allowed.`,\n\t\tfix: \"Pick an invariantId without spaces, tabs, newlines, or control characters — e.g. \\\"backfill-user-phone\\\", \\\"users/backfill-phone\\\", or \\\"BackfillUserPhone\\\".\",\n\t\tmeta: { invariantId }\n\t});\n}\nfunction errorDuplicateInvariantInEdge(invariantId) {\n\treturn new MigrationToolsError(\"MIGRATION.DUPLICATE_INVARIANT_IN_EDGE\", \"Duplicate invariantId on a single migration\", {\n\t\twhy: `invariantId \"${invariantId}\" is declared by more than one dataTransform on the same migration. The marker stores invariants as a set and the routing layer treats them as edge-level, so two ops cannot share a routing identity.`,\n\t\tfix: \"Rename one of the conflicting dataTransform invariantIds, or drop invariantId on the op that does not need to be routing-visible.\",\n\t\tmeta: { invariantId }\n\t});\n}\nfunction errorProvidedInvariantsMismatch(filePath, stored, derived) {\n\tconst storedSet = new Set(stored);\n\tconst derivedSet = new Set(derived);\n\tconst missing = [...derivedSet].filter((id) => !storedSet.has(id));\n\tconst extra = [...storedSet].filter((id) => !derivedSet.has(id));\n\treturn new MigrationToolsError(\"MIGRATION.PROVIDED_INVARIANTS_MISMATCH\", \"providedInvariants on migration.json disagrees with ops.json\", {\n\t\twhy: missing.length === 0 && extra.length === 0 ? `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the canonical value derived from ops.json is ${JSON.stringify(derived)} — same ids, different order. Canonical providedInvariants is sorted ascending.` : `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the value derived from ops.json is ${JSON.stringify(derived)}. The manifest copy was likely hand-edited without re-emitting.`,\n\t\tfix: reemitHint(dirname(filePath), \"or restore the directory from version control.\"),\n\t\tmeta: {\n\t\t\tfilePath,\n\t\t\tstored,\n\t\t\tderived,\n\t\t\tdifference: {\n\t\t\t\tmissing,\n\t\t\t\textra\n\t\t\t}\n\t\t}\n\t});\n}\nfunction errorNoInvariantPath(args) {\n\tconst { refName, required, missing, structuralPath } = args;\n\tconst refClause = refName ? `Ref \"${refName}\"` : \"Target\";\n\tconst missingList = missing.map((id) => JSON.stringify(id)).join(\", \");\n\treturn new MigrationToolsError(\"MIGRATION.NO_INVARIANT_PATH\", \"No path covers the required invariants\", {\n\t\twhy: `${refClause} requires invariants the reachable path doesn't cover. required=[${required.map((id) => JSON.stringify(id)).join(\", \")}], missing=[${missingList}].`,\n\t\tfix: \"Add a migration on the path that runs `dataTransform({ invariantId: \\\"<id>\\\", … })` for each missing invariant, or retarget the ref to a hash whose path already provides them.\",\n\t\tmeta: {\n\t\t\trequired,\n\t\t\tmissing,\n\t\t\tstructuralPath,\n\t\t\t...ifDefined(\"refName\", refName)\n\t\t}\n\t});\n}\nfunction errorUnknownInvariant(args) {\n\tconst { refName, unknown, declared } = args;\n\treturn new MigrationToolsError(\"MIGRATION.UNKNOWN_INVARIANT\", \"Ref declares invariants no migration in the graph provides\", {\n\t\twhy: `${refName ? `Ref \"${refName}\" declares` : \"Declares\"} invariants no migration in the graph provides. unknown=[${unknown.map((id) => JSON.stringify(id)).join(\", \")}].`,\n\t\tfix: \"Either the ref has a typo, or the declaring migration has not been authored/attested yet. Re-check the ref file and the migrations directory.\",\n\t\tmeta: {\n\t\t\tunknown,\n\t\t\tdeclared,\n\t\t\t...ifDefined(\"refName\", refName)\n\t\t}\n\t});\n}\nfunction errorMigrationHashMismatch(dir, storedHash, computedHash) {\n\treturn new MigrationToolsError(\"MIGRATION.HASH_MISMATCH\", \"Migration package is corrupt\", {\n\t\twhy: `Stored migrationHash \"${storedHash}\" does not match the recomputed hash \"${computedHash}\" for \"${relative(process.cwd(), dir)}\". The migration.json or ops.json has been edited or partially written since emit.`,\n\t\tfix: reemitHint(dir, \"or restore the directory from version control.\"),\n\t\tmeta: {\n\t\t\tdir,\n\t\t\tstoredHash,\n\t\t\tcomputedHash\n\t\t}\n\t});\n}\n/**\n* A ref name that resolves to nothing: no pointer file named `refName`\n* exists, and the hash being resolved (the `contractAt` argument, used as a\n* fallback when the pointer is absent) is not a node in the migration graph\n* either. There is no contract to materialize.\n*/\nfunction errorRefNotResolvable(refName) {\n\treturn new MigrationToolsError(\"MIGRATION.REF_NOT_RESOLVABLE\", `Ref \"${refName}\" is not resolvable`, {\n\t\twhy: `Ref \"${refName}\" has no pointer file, and the hash being resolved is not a node in the migration graph either — there is nothing to materialize a contract from.`,\n\t\tfix: `Create the ref with \"{bin} migration ref set ${refName} <hash>\" (or advance it via \"{bin} db update --advance-ref ${refName}\"), or pass a hash that is a node in the migration graph.`,\n\t\tnextActions: [\n\t\t\t{\n\t\t\t\tkind: \"run-command\",\n\t\t\t\tlabel: `Create the ref \"${refName}\"`,\n\t\t\t\tcommand: `{bin} migration ref set ${refName} <hash>`\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: \"run-command\",\n\t\t\t\tlabel: `Advance the ref \"${refName}\" as part of an update`,\n\t\t\t\tcommand: `{bin} db update --advance-ref ${refName}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: \"user-choice\",\n\t\t\t\tlabel: \"Pass a hash that is already a node in the migration graph\"\n\t\t\t}\n\t\t],\n\t\tmeta: {\n\t\t\trefName,\n\t\t\tidentifier: refName\n\t\t}\n\t});\n}\nfunction errorBundleNotFoundForGraphNode(hash, explicitLabel) {\n\treturn new MigrationToolsError(\"MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE\", explicitLabel ? `No migration bundle found for reference \"${explicitLabel}\" (resolved hash: ${hash})` : `No migration bundle found for graph node ${hash}`, {\n\t\twhy: `The hash ${hash} is a graph node but no on-disk migration package has a destination (\\`to\\`) hash matching it.`,\n\t\tfix: \"Provide a ref or hash that corresponds to an existing migration package, or run `{bin} migration list` to see available migrations.\",\n\t\tmeta: {\n\t\t\thash,\n\t\t\t...explicitLabel ? { explicitLabel } : {}\n\t\t}\n\t});\n}\nfunction errorContractDeserializationFailed(filePath, message, options) {\n\treturn new MigrationToolsError(\"MIGRATION.CONTRACT_DESERIALIZATION_FAILED\", \"Contract failed to deserialize\", {\n\t\twhy: `Contract at \"${filePath}\" failed to deserialize: ${message}`,\n\t\tfix: reemitHint(dirname(filePath), \"or restore the directory from version control.\"),\n\t\tmeta: {\n\t\t\tfilePath,\n\t\t\tmessage\n\t\t},\n\t\t...ifDefined(\"cause\", options?.cause)\n\t});\n}\nfunction errorHashNotInGraph(hash, graph) {\n\tconst reachableHashes = [...graph.nodes].sort();\n\tconst reachableList = reachableHashes.length > 0 ? reachableHashes.join(\", \") : \"(none)\";\n\treturn new MigrationToolsError(\"MIGRATION.HASH_NOT_IN_GRAPH\", `Hash \"${hash}\" is not a node in the migration graph`, {\n\t\twhy: `The migration graph contains nodes ${reachableList}; \"${hash}\" isn't one of them.`,\n\t\tfix: `Pass a hash that's the from-or-to of an on-disk migration bundle, use --from with a graph-node hash, or run \"{bin} migration plan\" to introduce it.`,\n\t\tnextActions: [{\n\t\t\tkind: \"user-choice\",\n\t\t\tlabel: \"Pass a hash that is the from-or-to of an on-disk migration bundle, or use --from with a graph-node hash\",\n\t\t\treason: `Graph nodes: ${reachableList}.`\n\t\t}, {\n\t\t\tkind: \"run-command\",\n\t\t\tlabel: `Introduce \"${hash}\" by planning a migration for it`,\n\t\t\tcommand: \"{bin} migration plan\"\n\t\t}],\n\t\tmeta: {\n\t\t\thash,\n\t\t\treachableHashes\n\t\t}\n\t});\n}\nfunction errorContractSnapshotMissing(storageHash, expectedPath) {\n\treturn new MigrationToolsError(\"MIGRATION.CONTRACT_SNAPSHOT_MISSING\", \"Contract snapshot is missing\", {\n\t\twhy: `Expected a contract snapshot for ${storageHash} at \"${expectedPath}\" but the file does not exist.`,\n\t\tfix: \"Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`{bin} migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.\",\n\t\tnextActions: [\n\t\t\t{\n\t\t\t\tkind: \"run-command\",\n\t\t\t\tlabel: \"Re-emit the snapshot for an app-space migration\",\n\t\t\t\tcommand: \"{bin} migration plan\"\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: \"user-choice\",\n\t\t\t\tlabel: \"For an extension space, re-run that extension's contract-space build instead\"\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: \"user-choice\",\n\t\t\t\tlabel: \"Restore migrations/snapshots/ from version control\"\n\t\t\t}\n\t\t],\n\t\tmeta: {\n\t\t\tstorageHash,\n\t\t\texpectedPath\n\t\t}\n\t});\n}\nfunction errorContractSnapshotHashMismatch(storageHash, actualHash, dir) {\n\treturn new MigrationToolsError(\"MIGRATION.CONTRACT_SNAPSHOT_HASH_MISMATCH\", \"Contract snapshot hash mismatch\", {\n\t\twhy: `The contract JSON's inner storage.storageHash (\"${actualHash}\") does not match the requested storage hash (\"${storageHash}\") for snapshot directory \"${dir}\".`,\n\t\tfix: \"Pass a contractJson whose storage.storageHash equals the storageHash argument passed to writeContractSnapshot — the two must agree by construction.\",\n\t\tmeta: {\n\t\t\tstorageHash,\n\t\t\tactualHash,\n\t\t\tdir\n\t\t}\n\t});\n}\nfunction errorMigrationContractViewMissing(className, accessor, jsonField) {\n\treturn new MigrationToolsError(\"MIGRATION.CONTRACT_VIEW_MISSING\", `${className}.${accessor} requires ${jsonField}`, {\n\t\twhy: `${className}.${accessor} was read, but this instance has no ${jsonField} to build the view from.`,\n\t\tfix: `Set ${jsonField} to the migration's committed contract JSON, or avoid reading ${accessor} on a migration that overrides describe() and carries no contract.`,\n\t\tmeta: {\n\t\t\tclassName,\n\t\t\taccessor,\n\t\t\tjsonField\n\t\t}\n\t});\n}\n//#endregion\nexport { errorOperationsNotArray as A, errorInvalidSpaceId as C, errorNoInitialMigration as D, errorMissingFile as E, errorRefNotResolvable as M, errorSpaceHeadRefMissing as N, errorNoInvariantPath as O, errorUnknownInvariant as P, errorInvalidSlug as S, errorMigrationHashMismatch as T, errorInvalidManifest as _, errorContractSnapshotHashMismatch as a, errorInvalidRefName as b, errorDescribeMissingEndContract as c, errorDuplicateInvariantInEdge as d, errorDuplicateSpaceId as f, errorInvalidJson as g, errorInvalidInvariantId as h, errorContractDeserializationFailed as i, errorProvidedInvariantsMismatch as j, errorNoTarget as k, errorDescriptorHeadHashMismatch as l, errorInvalidDestName as m, errorAmbiguousTarget as n, errorContractSnapshotMissing as o, errorHashNotInGraph as p, errorBundleNotFoundForGraphNode as r, errorDescribeInvalidMetadata as s, MigrationToolsError as t, errorDirectoryExists as u, errorInvalidOperationEntry as v, errorMigrationContractViewMissing as w, errorInvalidRefValue as x, errorInvalidRefFile as y };\n\n//# sourceMappingURL=errors-SoLLYLtw.mjs.map"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,WAAW,KAAK,UAAU;CAClC,MAAM,SAAS,0CAA0C,SAAS,QAAQ,IAAI,GAAG,GAAG,EAAE;CACtF,OAAO,WAAW,GAAG,OAAO,IAAI,aAAa,GAAG,OAAO;AACxD;;;;;;;;;;;;;;;;;AAiBA,IAAI,sBAAsB,cAAc,mBAAmB;CAC1D;CACA,YAAY,MAAM,SAAS,SAAS;EACnC,MAAM,MAAM,SAAS,OAAO;E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OAAO;GACR;GACA;IACC,MAAM;IACN,OAAO;GACR;EACD;EACA,MAAM;GACL;GACA;EACD;CACD,CAAC;AACF;AACA,SAAS,kCAAkC,aAAa,YAAY,KAAK;CACxE,OAAO,IAAI,oBAAoB,6CAA6C,mCAAmC;EAC9G,KAAK,mDAAmD,WAAW,iDAAiD,YAAY,6BAA6B,IAAI;EACjK,KAAK;EACL,MAAM;GACL;GACA;GACA;EACD;CACD,CAAC;AACF;AACA,SAAS,kCAAkC,WAAW,UAAU,WAAW;CAC1E,OAAO,IAAI,oBAAoB,mCAAmC,GAAG,UAAU,GAAG,SAAS,YAAY,aAAa;EACnH,KAAK,GAAG,UAAU,GAAG,SAAS,sCAAsC,UAAU;EAC9E,KAAK,OAAO,UAAU,gEAAgE,SAAS;EAC/F,MAAM;GACL;GACA;GACA;EACD;CACD,CAAC;AACF"}
@@ -1,5 +1,5 @@
1
- import { p as errorHashNotInGraph } from "./errors-CcEpbfnE-CsSXrttT.mjs";
2
- //#region ../../../1-framework/3-tooling/migration/dist/graph-membership-BoITerZB.mjs
1
+ import { p as errorHashNotInGraph } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
+ //#region ../../../1-framework/3-tooling/migration/dist/graph-membership-DY1Onbc3.mjs
3
3
  function isGraphNode(hash, graph) {
4
4
  if (hash === "empty") return true;
5
5
  return graph.nodes.has(hash);
@@ -11,4 +11,4 @@ function assertHashIsGraphNode(hash, graph) {
11
11
  //#endregion
12
12
  export { isGraphNode as n, assertHashIsGraphNode as t };
13
13
 
14
- //# sourceMappingURL=graph-membership-BoITerZB-C2-x1Qp6.mjs.map
14
+ //# sourceMappingURL=graph-membership-DY1Onbc3-CwBd6wuB.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph-membership-BoITerZB-C2-x1Qp6.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/graph-membership-BoITerZB.mjs"],"sourcesContent":["import { p as errorHashNotInGraph } from \"./errors-CcEpbfnE.mjs\";\nimport \"./constants-CM-w38DQ.mjs\";\n//#region src/graph-membership.ts\nfunction isGraphNode(hash, graph) {\n\tif (hash === \"empty\") return true;\n\treturn graph.nodes.has(hash);\n}\nfunction assertHashIsGraphNode(hash, graph) {\n\tif (isGraphNode(hash, graph)) return;\n\tthrow errorHashNotInGraph(hash, graph);\n}\n//#endregion\nexport { isGraphNode as n, assertHashIsGraphNode as t };\n\n//# sourceMappingURL=graph-membership-BoITerZB.mjs.map"],"mappings":";;AAGA,SAAS,YAAY,MAAM,OAAO;CACjC,IAAI,SAAS,SAAS,OAAO;CAC7B,OAAO,MAAM,MAAM,IAAI,IAAI;AAC5B;AACA,SAAS,sBAAsB,MAAM,OAAO;CAC3C,IAAI,YAAY,MAAM,KAAK,GAAG;CAC9B,MAAM,oBAAoB,MAAM,KAAK;AACtC"}
1
+ {"version":3,"file":"graph-membership-DY1Onbc3-CwBd6wuB.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/graph-membership-DY1Onbc3.mjs"],"sourcesContent":["import { p as errorHashNotInGraph } from \"./errors-SoLLYLtw.mjs\";\nimport \"./constants-CM-w38DQ.mjs\";\n//#region src/graph-membership.ts\nfunction isGraphNode(hash, graph) {\n\tif (hash === \"empty\") return true;\n\treturn graph.nodes.has(hash);\n}\nfunction assertHashIsGraphNode(hash, graph) {\n\tif (isGraphNode(hash, graph)) return;\n\tthrow errorHashNotInGraph(hash, graph);\n}\n//#endregion\nexport { isGraphNode as n, assertHashIsGraphNode as t };\n\n//# sourceMappingURL=graph-membership-DY1Onbc3.mjs.map"],"mappings":";;AAGA,SAAS,YAAY,MAAM,OAAO;CACjC,IAAI,SAAS,SAAS,OAAO;CAC7B,OAAO,MAAM,MAAM,IAAI,IAAI;AAC5B;AACA,SAAS,sBAAsB,MAAM,OAAO;CAC3C,IAAI,YAAY,MAAM,KAAK,GAAG;CAC9B,MAAM,oBAAoB,MAAM,KAAK;AACtC"}
@@ -1,5 +1,5 @@
1
- import { d as errorDuplicateInvariantInEdge, h as errorInvalidInvariantId } from "./errors-CcEpbfnE-CsSXrttT.mjs";
2
- //#region ../../../1-framework/3-tooling/migration/dist/invariants-DcFfhJMZ.mjs
1
+ import { d as errorDuplicateInvariantInEdge, h as errorInvalidInvariantId } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
+ //#region ../../../1-framework/3-tooling/migration/dist/invariants-Cww4bv0v.mjs
3
3
  /**
4
4
  * Hygiene check for `invariantId`. Rejects empty values plus any
5
5
  * whitespace or control character (including Unicode whitespace like
@@ -54,4 +54,4 @@ function readInvariantId(op) {
54
54
  //#endregion
55
55
  export { validateInvariantId as n, deriveProvidedInvariants as t };
56
56
 
57
- //# sourceMappingURL=invariants-DcFfhJMZ-BHDWZP9k.mjs.map
57
+ //# sourceMappingURL=invariants-Cww4bv0v-BEiFxmbX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"invariants-DcFfhJMZ-BHDWZP9k.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/invariants-DcFfhJMZ.mjs"],"sourcesContent":["import { d as errorDuplicateInvariantInEdge, h as errorInvalidInvariantId } from \"./errors-CcEpbfnE.mjs\";\n//#region src/invariants.ts\n/**\n* Hygiene check for `invariantId`. Rejects empty values plus any\n* whitespace or control character (including Unicode whitespace like\n* NBSP and em space, which are visually identical to ASCII space and\n* routinely sneak in via paste).\n*/\nfunction validateInvariantId(invariantId) {\n\tif (invariantId.length === 0) return false;\n\treturn !/[\\p{Cc}\\p{White_Space}]/u.test(invariantId);\n}\n/**\n* Walk a migration's operations and produce its `providedInvariants`\n* aggregate: the sorted, deduplicated list of `invariantId`s declared\n* by ops in the migration. Ops without an `invariantId` are skipped.\n*\n* Both `data`-class ops (data-transforms, e.g. backfills) and\n* `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle\n* via `installEqlBundleOp`) may declare invariantIds: the\n* `operationClass` axis classifies *policy gating* (which kinds of ops\n* a `db init` / `db update` policy permits), while `invariantId`\n* classifies *marker bookkeeping* (which named bundles of work a\n* future regeneration knows to skip). The two concerns are\n* intentionally orthogonal — an extension can ship additive\n* non-IR-derivable DDL (the only way the planner can know the bundle\n* is already applied is via the invariantId on the marker) without\n* needing to mis-classify it as `data`-class.\n*\n* Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and\n* `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.\n*\n* @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md\n* — extension migrations carry `invariantId`s on additive ops; e.g.\n* cipherstash's `installEqlBundle` and structural `create-*` ops are\n* additive-class but carry `cipherstash:*` invariantIds.\n*/\nfunction deriveProvidedInvariants(ops) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const op of ops) {\n\t\tconst invariantId = readInvariantId(op);\n\t\tif (invariantId === void 0) continue;\n\t\tif (!validateInvariantId(invariantId)) throw errorInvalidInvariantId(invariantId);\n\t\tif (seen.has(invariantId)) throw errorDuplicateInvariantInEdge(invariantId);\n\t\tseen.add(invariantId);\n\t}\n\treturn [...seen].sort();\n}\nfunction readInvariantId(op) {\n\tif (!Object.hasOwn(op, \"invariantId\")) return void 0;\n\tconst candidate = op.invariantId;\n\treturn typeof candidate === \"string\" ? candidate : void 0;\n}\n//#endregion\nexport { validateInvariantId as n, deriveProvidedInvariants as t };\n\n//# sourceMappingURL=invariants-DcFfhJMZ.mjs.map"],"mappings":";;;;;;;;AAQA,SAAS,oBAAoB,aAAa;CACzC,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,OAAO,CAAC,2BAA2B,KAAK,WAAW;AACpD;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,yBAAyB,KAAK;CACtC,MAAM,uBAAuB,IAAI,IAAI;CACrC,KAAK,MAAM,MAAM,KAAK;EACrB,MAAM,cAAc,gBAAgB,EAAE;EACtC,IAAI,gBAAgB,KAAK,GAAG;EAC5B,IAAI,CAAC,oBAAoB,WAAW,GAAG,MAAM,wBAAwB,WAAW;EAChF,IAAI,KAAK,IAAI,WAAW,GAAG,MAAM,8BAA8B,WAAW;EAC1E,KAAK,IAAI,WAAW;CACrB;CACA,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;AACvB;AACA,SAAS,gBAAgB,IAAI;CAC5B,IAAI,CAAC,OAAO,OAAO,IAAI,aAAa,GAAG,OAAO,KAAK;CACnD,MAAM,YAAY,GAAG;CACrB,OAAO,OAAO,cAAc,WAAW,YAAY,KAAK;AACzD"}
1
+ {"version":3,"file":"invariants-Cww4bv0v-BEiFxmbX.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/invariants-Cww4bv0v.mjs"],"sourcesContent":["import { d as errorDuplicateInvariantInEdge, h as errorInvalidInvariantId } from \"./errors-SoLLYLtw.mjs\";\n//#region src/invariants.ts\n/**\n* Hygiene check for `invariantId`. Rejects empty values plus any\n* whitespace or control character (including Unicode whitespace like\n* NBSP and em space, which are visually identical to ASCII space and\n* routinely sneak in via paste).\n*/\nfunction validateInvariantId(invariantId) {\n\tif (invariantId.length === 0) return false;\n\treturn !/[\\p{Cc}\\p{White_Space}]/u.test(invariantId);\n}\n/**\n* Walk a migration's operations and produce its `providedInvariants`\n* aggregate: the sorted, deduplicated list of `invariantId`s declared\n* by ops in the migration. Ops without an `invariantId` are skipped.\n*\n* Both `data`-class ops (data-transforms, e.g. backfills) and\n* `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle\n* via `installEqlBundleOp`) may declare invariantIds: the\n* `operationClass` axis classifies *policy gating* (which kinds of ops\n* a `db init` / `db update` policy permits), while `invariantId`\n* classifies *marker bookkeeping* (which named bundles of work a\n* future regeneration knows to skip). The two concerns are\n* intentionally orthogonal — an extension can ship additive\n* non-IR-derivable DDL (the only way the planner can know the bundle\n* is already applied is via the invariantId on the marker) without\n* needing to mis-classify it as `data`-class.\n*\n* Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and\n* `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.\n*\n* @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md\n* — extension migrations carry `invariantId`s on additive ops; e.g.\n* cipherstash's `installEqlBundle` and structural `create-*` ops are\n* additive-class but carry `cipherstash:*` invariantIds.\n*/\nfunction deriveProvidedInvariants(ops) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const op of ops) {\n\t\tconst invariantId = readInvariantId(op);\n\t\tif (invariantId === void 0) continue;\n\t\tif (!validateInvariantId(invariantId)) throw errorInvalidInvariantId(invariantId);\n\t\tif (seen.has(invariantId)) throw errorDuplicateInvariantInEdge(invariantId);\n\t\tseen.add(invariantId);\n\t}\n\treturn [...seen].sort();\n}\nfunction readInvariantId(op) {\n\tif (!Object.hasOwn(op, \"invariantId\")) return void 0;\n\tconst candidate = op.invariantId;\n\treturn typeof candidate === \"string\" ? candidate : void 0;\n}\n//#endregion\nexport { validateInvariantId as n, deriveProvidedInvariants as t };\n\n//# sourceMappingURL=invariants-Cww4bv0v.mjs.map"],"mappings":";;;;;;;;AAQA,SAAS,oBAAoB,aAAa;CACzC,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,OAAO,CAAC,2BAA2B,KAAK,WAAW;AACpD;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,yBAAyB,KAAK;CACtC,MAAM,uBAAuB,IAAI,IAAI;CACrC,KAAK,MAAM,MAAM,KAAK;EACrB,MAAM,cAAc,gBAAgB,EAAE;EACtC,IAAI,gBAAgB,KAAK,GAAG;EAC5B,IAAI,CAAC,oBAAoB,WAAW,GAAG,MAAM,wBAAwB,WAAW;EAChF,IAAI,KAAK,IAAI,WAAW,GAAG,MAAM,8BAA8B,WAAW;EAC1E,KAAK,IAAI,WAAW;CACrB;CACA,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;AACvB;AACA,SAAS,gBAAgB,IAAI;CAC5B,IAAI,CAAC,OAAO,OAAO,IAAI,aAAa,GAAG,OAAO,KAAK;CACnD,MAAM,YAAY,GAAG;CACrB,OAAO,OAAO,cAAc,WAAW,YAAY,KAAK;AACzD"}
@@ -1,13 +1,13 @@
1
- import { E as errorMissingFile, S as errorInvalidSlug, T as errorMigrationHashMismatch, _ as errorInvalidManifest, g as errorInvalidJson, j as errorProvidedInvariantsMismatch, m as errorInvalidDestName, t as MigrationToolsError, u as errorDirectoryExists } from "./errors-CcEpbfnE-CsSXrttT.mjs";
2
- import { i as readContractSnapshotJsonTolerant } from "./contract-snapshot-store-BAmQkHe5-BJFpuIQQ.mjs";
1
+ import { E as errorMissingFile, S as errorInvalidSlug, T as errorMigrationHashMismatch, _ as errorInvalidManifest, g as errorInvalidJson, j as errorProvidedInvariantsMismatch, m as errorInvalidDestName, t as MigrationToolsError, u as errorDirectoryExists } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
+ import { i as readContractSnapshotJsonTolerant } from "./contract-snapshot-store-qGrwlGmt-Cf2NFzRL.mjs";
3
3
  import { n as verifyMigrationHash } from "./hash-DH8hl5Rq-BpM2t3Nu.mjs";
4
- import { t as deriveProvidedInvariants } from "./invariants-DcFfhJMZ-BHDWZP9k.mjs";
4
+ import { t as deriveProvidedInvariants } from "./invariants-Cww4bv0v-BEiFxmbX.mjs";
5
5
  import { n as MigrationOpsSchema } from "./op-schema-BSVHzEQN-DIWt28D8.mjs";
6
6
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
7
7
  import { basename, dirname, join, resolve } from "pathe";
8
8
  import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
9
  import { type } from "arktype";
10
- //#region ../../../1-framework/3-tooling/migration/dist/io-DsViRB_O.mjs
10
+ //#region ../../../1-framework/3-tooling/migration/dist/io-BmWQNxRP.mjs
11
11
  const MANIFEST_FILE = "migration.json";
12
12
  const OPS_FILE = "ops.json";
13
13
  const MAX_SLUG_LENGTH = 64;
@@ -310,4 +310,4 @@ function formatMigrationDirName(timestamp, slug) {
310
310
  //#endregion
311
311
  export { materialiseMigrationPackage as a, writeMigrationMetadata as c, materialiseExtensionMigrationPackageIfMissing as i, writeMigrationOps as l, copyFilesWithRename as n, readMigrationPackage as o, formatMigrationDirName as r, readMigrationsDir as s, MANIFEST_FILE as t, writeMigrationPackage as u };
312
312
 
313
- //# sourceMappingURL=io-DsViRB_O-Ci1kJGBg.mjs.map
313
+ //# sourceMappingURL=io-BmWQNxRP-DQqbcPsS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"io-DsViRB_O-Ci1kJGBg.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/io-DsViRB_O.mjs"],"sourcesContent":["import { E as errorMissingFile, S as errorInvalidSlug, T as errorMigrationHashMismatch, _ as errorInvalidManifest, g as errorInvalidJson, j as errorProvidedInvariantsMismatch, m as errorInvalidDestName, t as MigrationToolsError, u as errorDirectoryExists } from \"./errors-CcEpbfnE.mjs\";\nimport { i as readContractSnapshotJsonTolerant } from \"./contract-snapshot-store-BAmQkHe5.mjs\";\nimport { n as verifyMigrationHash } from \"./hash-DH8hl5Rq.mjs\";\nimport { t as deriveProvidedInvariants } from \"./invariants-DcFfhJMZ.mjs\";\nimport { n as MigrationOpsSchema } from \"./op-schema-BSVHzEQN.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { basename, dirname, join, resolve } from \"pathe\";\nimport { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport { type } from \"arktype\";\n//#region src/io.ts\nconst MANIFEST_FILE = \"migration.json\";\nconst OPS_FILE = \"ops.json\";\nconst MAX_SLUG_LENGTH = 64;\nfunction hasErrnoCode(error, code) {\n\treturn error instanceof Error && error.code === code;\n}\nconst MigrationMetadataSchema = type({\n\t\"+\": \"reject\",\n\tfrom: \"string > 0 | null\",\n\tto: \"string\",\n\tmigrationHash: \"string\",\n\tprovidedInvariants: \"string[]\",\n\tcreatedAt: \"string\"\n});\nasync function writeMigrationPackage(dir, metadata, ops) {\n\tawait mkdir(dirname(dir), { recursive: true });\n\ttry {\n\t\tawait mkdir(dir);\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"EEXIST\")) throw errorDirectoryExists(dir);\n\t\tthrow error;\n\t}\n\tawait writeFile(join(dir, MANIFEST_FILE), JSON.stringify(metadata, null, 2), { flag: \"wx\" });\n\tawait writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: \"wx\" });\n}\n/**\n* Materialise an in-memory {@link MigrationPackage} to a per-space\n* directory on disk.\n*\n* Writes two files under `<targetDir>/<pkg.dirName>/`:\n*\n* - `migration.json` — the manifest (pretty-printed, matches\n* {@link writeMigrationPackage}'s output for byte-for-byte parity with\n* app-space migrations).\n* - `ops.json` — the operation list (pretty-printed).\n*\n* Distinct verb from the lower-level {@link writeMigrationPackage}\n* (which takes constituent `(metadata, ops)`): callers reading\n* `materialise…` know they are persisting a struct-typed package.\n*\n* Overwrite-idempotent: the per-package directory is cleared before\n* each emit, so re-running against the same `targetDir` produces\n* byte-identical contents and never leaves stale files behind. The\n* lower-level {@link writeMigrationPackage} stays strict because the\n* CLI authoring path (`migration plan` / `migration new`) deliberately\n* refuses to clobber an existing authored migration; this helper is\n* the re-emit path that is supposed to converge on a single canonical\n* on-disk shape.\n*\n* The per-space head contract resolves through\n* `<projectMigrationsDir>/snapshots/<hex>/` (written by\n* {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),\n* not inside the per-package directory. The runner reads only\n* `migration.json` + `ops.json` from each package.\n*/\nasync function materialiseMigrationPackage(targetDir, pkg) {\n\tconst dir = join(targetDir, pkg.dirName);\n\tawait rm(dir, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n\tawait writeMigrationPackage(dir, pkg.metadata, pkg.ops);\n}\n/**\n* Idempotent variant of {@link materialiseMigrationPackage}: writes the\n* package only if `<targetDir>/<pkg.dirName>/` does not already exist on\n* disk as a directory; returns `{ written: false }` when the package\n* directory is present (no rewrite, no comparison — by-existence skip).\n*\n* Concretely:\n* - existing directory → skip silently, return `{ written: false }`.\n* - missing path → write three files via {@link materialiseMigrationPackage},\n* return `{ written: true }`.\n* - path exists but is not a directory (file/symlink) → treated as\n* missing; {@link materialiseMigrationPackage} will attempt creation\n* and fail with an appropriate OS error.\n* - any other I/O error from `stat` → propagated unchanged.\n*\n* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to\n* materialise extension migration packages into a project's\n* `migrations/<spaceId>/` directory, and by extension-package tests\n* that mirror the same idempotent-rematerialise property locally\n* without taking a CLI dependency.\n*/\nasync function materialiseExtensionMigrationPackageIfMissing(targetDir, pkg) {\n\tif (await directoryExists(join(targetDir, pkg.dirName))) return { written: false };\n\tawait materialiseMigrationPackage(targetDir, pkg);\n\treturn { written: true };\n}\nasync function directoryExists(p) {\n\ttry {\n\t\treturn (await stat(p)).isDirectory();\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return false;\n\t\tthrow error;\n\t}\n}\n/**\n* Copy a list of files into `destDir`, optionally renaming each one.\n*\n* The destination directory is created (with `recursive: true`) if it\n* does not already exist. Each source path is copied byte-for-byte into\n* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is\n* intentionally generic: callers own the list of files and the naming\n* convention for the copies.\n*/\nasync function copyFilesWithRename(destDir, files) {\n\tawait mkdir(destDir, { recursive: true });\n\tfor (const file of files) {\n\t\tif (basename(file.destName) !== file.destName) throw errorInvalidDestName(file.destName);\n\t\tawait copyFile(file.sourcePath, join(destDir, file.destName));\n\t}\n}\nasync function writeMigrationMetadata(dir, metadata) {\n\tawait writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(metadata, null, 2)}\\n`);\n}\nasync function writeMigrationOps(dir, ops) {\n\tawait writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\\n`);\n}\nasync function readMigrationPackage(dir, options) {\n\tconst absoluteDir = resolve(dir);\n\tconst manifestPath = join(absoluteDir, MANIFEST_FILE);\n\tconst opsPath = join(absoluteDir, OPS_FILE);\n\tlet manifestRaw;\n\ttry {\n\t\tmanifestRaw = await readFile(manifestPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorMissingFile(MANIFEST_FILE, absoluteDir);\n\t\tthrow error;\n\t}\n\tlet opsRaw;\n\ttry {\n\t\topsRaw = await readFile(opsPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorMissingFile(OPS_FILE, absoluteDir);\n\t\tthrow error;\n\t}\n\tlet metadata;\n\ttry {\n\t\tmetadata = JSON.parse(manifestRaw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));\n\t}\n\tlet ops;\n\ttry {\n\t\tops = JSON.parse(opsRaw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));\n\t}\n\tvalidateMetadata(metadata, manifestPath);\n\tvalidateOps(ops, opsPath);\n\tconst derivedInvariants = deriveProvidedInvariants(ops);\n\tif (!arraysEqual(metadata.providedInvariants, derivedInvariants)) throw errorProvidedInvariantsMismatch(manifestPath, metadata.providedInvariants, derivedInvariants);\n\tconst endContractJson = await readContractSnapshotJsonTolerant(options.migrationsDir, metadata.to);\n\tconst pkg = {\n\t\tdirName: basename(absoluteDir),\n\t\tdirPath: absoluteDir,\n\t\tmetadata,\n\t\tops,\n\t\t...ifDefined(\"endContractJson\", endContractJson)\n\t};\n\tconst verification = verifyMigrationHash(pkg);\n\tif (!verification.ok) throw errorMigrationHashMismatch(absoluteDir, verification.storedHash, verification.computedHash);\n\treturn pkg;\n}\n/**\n* Reads a migration package's manifest and ops without running hash or\n* invariants verification. Returns `null` when the files cannot be read or\n* parsed (i.e. when the package is genuinely unloadable).\n*\n* Used by {@link readMigrationsDir} to retain a package whose hash or\n* invariants diverge from what is stored on disk — the raw content is still\n* useful for display / querying; only integrity is in question.\n*/\nasync function readMigrationPackageRaw(dir) {\n\tconst absoluteDir = resolve(dir);\n\tconst manifestPath = join(absoluteDir, MANIFEST_FILE);\n\tconst opsPath = join(absoluteDir, OPS_FILE);\n\tlet manifestRaw;\n\ttry {\n\t\tmanifestRaw = await readFile(manifestPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet opsRaw;\n\ttry {\n\t\topsRaw = await readFile(opsPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet metadata;\n\ttry {\n\t\tmetadata = JSON.parse(manifestRaw);\n\t} catch {\n\t\treturn null;\n\t}\n\tlet ops;\n\ttry {\n\t\tops = JSON.parse(opsRaw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (MigrationMetadataSchema(metadata) instanceof type.errors) return null;\n\tif (MigrationOpsSchema(ops) instanceof type.errors) return null;\n\treturn {\n\t\tdirName: basename(absoluteDir),\n\t\tdirPath: absoluteDir,\n\t\tmetadata,\n\t\tops\n\t};\n}\nfunction arraysEqual(a, b) {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n\treturn true;\n}\nfunction validateMetadata(metadata, filePath) {\n\tconst result = MigrationMetadataSchema(metadata);\n\tif (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);\n}\nfunction validateOps(ops, filePath) {\n\tconst result = MigrationOpsSchema(ops);\n\tif (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);\n}\nfunction packageLoadProblemDetailFromError(error) {\n\tif (MigrationToolsError.is(error)) return error.why;\n\tif (error instanceof Error) return error.message;\n\treturn String(error);\n}\nasync function readMigrationsDir(migrationsRoot, options) {\n\tlet entries;\n\ttry {\n\t\tentries = await readdir(migrationsRoot);\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return {\n\t\t\tpackages: [],\n\t\t\tproblems: []\n\t\t};\n\t\tthrow error;\n\t}\n\tconst packages = [];\n\tconst problems = [];\n\tfor (const entry of entries.sort()) {\n\t\tconst entryPath = join(migrationsRoot, entry);\n\t\tif (!(await stat(entryPath)).isDirectory()) continue;\n\t\tconst manifestPath = join(entryPath, MANIFEST_FILE);\n\t\ttry {\n\t\t\tawait stat(manifestPath);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tlet pkg;\n\t\ttry {\n\t\t\tpkg = await readMigrationPackage(entryPath, options);\n\t\t} catch (error) {\n\t\t\tconst dirName = entry;\n\t\t\tif (MigrationToolsError.is(error)) {\n\t\t\t\tif (error.code === \"MIGRATION.HASH_MISMATCH\") {\n\t\t\t\t\tconst meta = error.meta;\n\t\t\t\t\tconst rawPkg = await readMigrationPackageRaw(entryPath);\n\t\t\t\t\tif (rawPkg !== null) packages.push(rawPkg);\n\t\t\t\t\tproblems.push({\n\t\t\t\t\t\tkind: \"hashMismatch\",\n\t\t\t\t\t\tdirName,\n\t\t\t\t\t\tstored: typeof meta?.[\"storedHash\"] === \"string\" ? meta[\"storedHash\"] : \"\",\n\t\t\t\t\t\tcomputed: typeof meta?.[\"computedHash\"] === \"string\" ? meta[\"computedHash\"] : \"\"\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error.code === \"MIGRATION.PROVIDED_INVARIANTS_MISMATCH\") {\n\t\t\t\t\tconst rawPkg = await readMigrationPackageRaw(entryPath);\n\t\t\t\t\tif (rawPkg !== null) packages.push(rawPkg);\n\t\t\t\t\tproblems.push({\n\t\t\t\t\t\tkind: \"providedInvariantsMismatch\",\n\t\t\t\t\t\tdirName\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tproblems.push({\n\t\t\t\tkind: \"packageUnloadable\",\n\t\t\t\tdirName,\n\t\t\t\tdetail: packageLoadProblemDetailFromError(error)\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tpackages.push(pkg);\n\t}\n\treturn {\n\t\tpackages,\n\t\tproblems\n\t};\n}\nfunction formatMigrationDirName(timestamp, slug) {\n\tconst sanitized = slug.toLowerCase().replace(/[^a-z0-9]/g, \"_\").replace(/_+/g, \"_\").replace(/^_|_$/g, \"\");\n\tif (sanitized.length === 0) throw errorInvalidSlug(slug);\n\tconst truncated = sanitized.slice(0, MAX_SLUG_LENGTH);\n\treturn `${timestamp.getUTCFullYear()}${String(timestamp.getUTCMonth() + 1).padStart(2, \"0\")}${String(timestamp.getUTCDate()).padStart(2, \"0\")}T${String(timestamp.getUTCHours()).padStart(2, \"0\")}${String(timestamp.getUTCMinutes()).padStart(2, \"0\")}_${truncated}`;\n}\n//#endregion\nexport { materialiseMigrationPackage as a, writeMigrationMetadata as c, materialiseExtensionMigrationPackageIfMissing as i, writeMigrationOps as l, copyFilesWithRename as n, readMigrationPackage as o, formatMigrationDirName as r, readMigrationsDir as s, MANIFEST_FILE as t, writeMigrationPackage as u };\n\n//# sourceMappingURL=io-DsViRB_O.mjs.map"],"mappings":";;;;;;;;;;AAUA,MAAM,gBAAgB;AACtB,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,SAAS,aAAa,OAAO,MAAM;CAClC,OAAO,iBAAiB,SAAS,MAAM,SAAS;AACjD;AACA,MAAM,0BAA0B,KAAK;CACpC,KAAK;CACL,MAAM;CACN,IAAI;CACJ,eAAe;CACf,oBAAoB;CACpB,WAAW;AACZ,CAAC;AACD,eAAe,sBAAsB,KAAK,UAAU,KAAK;CACxD,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAC7C,IAAI;EACH,MAAM,MAAM,GAAG;CAChB,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,MAAM,qBAAqB,GAAG;EACjE,MAAM;CACP;CACA,MAAM,UAAU,KAAK,KAAK,aAAa,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;CAC3F,MAAM,UAAU,KAAK,KAAK,QAAQ,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;AAClF;;;;;;;;;;;;;;;;;;;;;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,GAAG,CAAC,CAAC,QAAQ,UAAU,EAAE;CACxG,IAAI,UAAU,WAAW,GAAG,MAAM,iBAAiB,IAAI;CACvD,MAAM,YAAY,UAAU,MAAM,GAAG,eAAe;CACpD,OAAO,GAAG,UAAU,eAAe,IAAI,OAAO,UAAU,YAAY,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,IAAI,OAAO,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG,OAAO,UAAU,YAAY,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,IAAI,OAAO,UAAU,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG;AAC3P"}
1
+ {"version":3,"file":"io-BmWQNxRP-DQqbcPsS.mjs","names":[],"sources":["../../../../1-framework/3-tooling/migration/dist/io-BmWQNxRP.mjs"],"sourcesContent":["import { E as errorMissingFile, S as errorInvalidSlug, T as errorMigrationHashMismatch, _ as errorInvalidManifest, g as errorInvalidJson, j as errorProvidedInvariantsMismatch, m as errorInvalidDestName, t as MigrationToolsError, u as errorDirectoryExists } from \"./errors-SoLLYLtw.mjs\";\nimport { i as readContractSnapshotJsonTolerant } from \"./contract-snapshot-store-qGrwlGmt.mjs\";\nimport { n as verifyMigrationHash } from \"./hash-DH8hl5Rq.mjs\";\nimport { t as deriveProvidedInvariants } from \"./invariants-Cww4bv0v.mjs\";\nimport { n as MigrationOpsSchema } from \"./op-schema-BSVHzEQN.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { basename, dirname, join, resolve } from \"pathe\";\nimport { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport { type } from \"arktype\";\n//#region src/io.ts\nconst MANIFEST_FILE = \"migration.json\";\nconst OPS_FILE = \"ops.json\";\nconst MAX_SLUG_LENGTH = 64;\nfunction hasErrnoCode(error, code) {\n\treturn error instanceof Error && error.code === code;\n}\nconst MigrationMetadataSchema = type({\n\t\"+\": \"reject\",\n\tfrom: \"string > 0 | null\",\n\tto: \"string\",\n\tmigrationHash: \"string\",\n\tprovidedInvariants: \"string[]\",\n\tcreatedAt: \"string\"\n});\nasync function writeMigrationPackage(dir, metadata, ops) {\n\tawait mkdir(dirname(dir), { recursive: true });\n\ttry {\n\t\tawait mkdir(dir);\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"EEXIST\")) throw errorDirectoryExists(dir);\n\t\tthrow error;\n\t}\n\tawait writeFile(join(dir, MANIFEST_FILE), JSON.stringify(metadata, null, 2), { flag: \"wx\" });\n\tawait writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: \"wx\" });\n}\n/**\n* Materialise an in-memory {@link MigrationPackage} to a per-space\n* directory on disk.\n*\n* Writes two files under `<targetDir>/<pkg.dirName>/`:\n*\n* - `migration.json` — the manifest (pretty-printed, matches\n* {@link writeMigrationPackage}'s output for byte-for-byte parity with\n* app-space migrations).\n* - `ops.json` — the operation list (pretty-printed).\n*\n* Distinct verb from the lower-level {@link writeMigrationPackage}\n* (which takes constituent `(metadata, ops)`): callers reading\n* `materialise…` know they are persisting a struct-typed package.\n*\n* Overwrite-idempotent: the per-package directory is cleared before\n* each emit, so re-running against the same `targetDir` produces\n* byte-identical contents and never leaves stale files behind. The\n* lower-level {@link writeMigrationPackage} stays strict because the\n* CLI authoring path (`migration plan` / `migration new`) deliberately\n* refuses to clobber an existing authored migration; this helper is\n* the re-emit path that is supposed to converge on a single canonical\n* on-disk shape.\n*\n* The per-space head contract resolves through\n* `<projectMigrationsDir>/snapshots/<hex>/` (written by\n* {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),\n* not inside the per-package directory. The runner reads only\n* `migration.json` + `ops.json` from each package.\n*/\nasync function materialiseMigrationPackage(targetDir, pkg) {\n\tconst dir = join(targetDir, pkg.dirName);\n\tawait rm(dir, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n\tawait writeMigrationPackage(dir, pkg.metadata, pkg.ops);\n}\n/**\n* Idempotent variant of {@link materialiseMigrationPackage}: writes the\n* package only if `<targetDir>/<pkg.dirName>/` does not already exist on\n* disk as a directory; returns `{ written: false }` when the package\n* directory is present (no rewrite, no comparison — by-existence skip).\n*\n* Concretely:\n* - existing directory → skip silently, return `{ written: false }`.\n* - missing path → write three files via {@link materialiseMigrationPackage},\n* return `{ written: true }`.\n* - path exists but is not a directory (file/symlink) → treated as\n* missing; {@link materialiseMigrationPackage} will attempt creation\n* and fail with an appropriate OS error.\n* - any other I/O error from `stat` → propagated unchanged.\n*\n* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to\n* materialise extension migration packages into a project's\n* `migrations/<spaceId>/` directory, and by extension-package tests\n* that mirror the same idempotent-rematerialise property locally\n* without taking a CLI dependency.\n*/\nasync function materialiseExtensionMigrationPackageIfMissing(targetDir, pkg) {\n\tif (await directoryExists(join(targetDir, pkg.dirName))) return { written: false };\n\tawait materialiseMigrationPackage(targetDir, pkg);\n\treturn { written: true };\n}\nasync function directoryExists(p) {\n\ttry {\n\t\treturn (await stat(p)).isDirectory();\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return false;\n\t\tthrow error;\n\t}\n}\n/**\n* Copy a list of files into `destDir`, optionally renaming each one.\n*\n* The destination directory is created (with `recursive: true`) if it\n* does not already exist. Each source path is copied byte-for-byte into\n* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is\n* intentionally generic: callers own the list of files and the naming\n* convention for the copies.\n*/\nasync function copyFilesWithRename(destDir, files) {\n\tawait mkdir(destDir, { recursive: true });\n\tfor (const file of files) {\n\t\tif (basename(file.destName) !== file.destName) throw errorInvalidDestName(file.destName);\n\t\tawait copyFile(file.sourcePath, join(destDir, file.destName));\n\t}\n}\nasync function writeMigrationMetadata(dir, metadata) {\n\tawait writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(metadata, null, 2)}\\n`);\n}\nasync function writeMigrationOps(dir, ops) {\n\tawait writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\\n`);\n}\nasync function readMigrationPackage(dir, options) {\n\tconst absoluteDir = resolve(dir);\n\tconst manifestPath = join(absoluteDir, MANIFEST_FILE);\n\tconst opsPath = join(absoluteDir, OPS_FILE);\n\tlet manifestRaw;\n\ttry {\n\t\tmanifestRaw = await readFile(manifestPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorMissingFile(MANIFEST_FILE, absoluteDir);\n\t\tthrow error;\n\t}\n\tlet opsRaw;\n\ttry {\n\t\topsRaw = await readFile(opsPath, \"utf-8\");\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) throw errorMissingFile(OPS_FILE, absoluteDir);\n\t\tthrow error;\n\t}\n\tlet metadata;\n\ttry {\n\t\tmetadata = JSON.parse(manifestRaw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));\n\t}\n\tlet ops;\n\ttry {\n\t\tops = JSON.parse(opsRaw);\n\t} catch (e) {\n\t\tthrow errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));\n\t}\n\tvalidateMetadata(metadata, manifestPath);\n\tvalidateOps(ops, opsPath);\n\tconst derivedInvariants = deriveProvidedInvariants(ops);\n\tif (!arraysEqual(metadata.providedInvariants, derivedInvariants)) throw errorProvidedInvariantsMismatch(manifestPath, metadata.providedInvariants, derivedInvariants);\n\tconst endContractJson = await readContractSnapshotJsonTolerant(options.migrationsDir, metadata.to);\n\tconst pkg = {\n\t\tdirName: basename(absoluteDir),\n\t\tdirPath: absoluteDir,\n\t\tmetadata,\n\t\tops,\n\t\t...ifDefined(\"endContractJson\", endContractJson)\n\t};\n\tconst verification = verifyMigrationHash(pkg);\n\tif (!verification.ok) throw errorMigrationHashMismatch(absoluteDir, verification.storedHash, verification.computedHash);\n\treturn pkg;\n}\n/**\n* Reads a migration package's manifest and ops without running hash or\n* invariants verification. Returns `null` when the files cannot be read or\n* parsed (i.e. when the package is genuinely unloadable).\n*\n* Used by {@link readMigrationsDir} to retain a package whose hash or\n* invariants diverge from what is stored on disk — the raw content is still\n* useful for display / querying; only integrity is in question.\n*/\nasync function readMigrationPackageRaw(dir) {\n\tconst absoluteDir = resolve(dir);\n\tconst manifestPath = join(absoluteDir, MANIFEST_FILE);\n\tconst opsPath = join(absoluteDir, OPS_FILE);\n\tlet manifestRaw;\n\ttry {\n\t\tmanifestRaw = await readFile(manifestPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet opsRaw;\n\ttry {\n\t\topsRaw = await readFile(opsPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet metadata;\n\ttry {\n\t\tmetadata = JSON.parse(manifestRaw);\n\t} catch {\n\t\treturn null;\n\t}\n\tlet ops;\n\ttry {\n\t\tops = JSON.parse(opsRaw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (MigrationMetadataSchema(metadata) instanceof type.errors) return null;\n\tif (MigrationOpsSchema(ops) instanceof type.errors) return null;\n\treturn {\n\t\tdirName: basename(absoluteDir),\n\t\tdirPath: absoluteDir,\n\t\tmetadata,\n\t\tops\n\t};\n}\nfunction arraysEqual(a, b) {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n\treturn true;\n}\nfunction validateMetadata(metadata, filePath) {\n\tconst result = MigrationMetadataSchema(metadata);\n\tif (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);\n}\nfunction validateOps(ops, filePath) {\n\tconst result = MigrationOpsSchema(ops);\n\tif (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);\n}\nfunction packageLoadProblemDetailFromError(error) {\n\tif (MigrationToolsError.is(error)) return error.why;\n\tif (error instanceof Error) return error.message;\n\treturn String(error);\n}\nasync function readMigrationsDir(migrationsRoot, options) {\n\tlet entries;\n\ttry {\n\t\tentries = await readdir(migrationsRoot);\n\t} catch (error) {\n\t\tif (hasErrnoCode(error, \"ENOENT\")) return {\n\t\t\tpackages: [],\n\t\t\tproblems: []\n\t\t};\n\t\tthrow error;\n\t}\n\tconst packages = [];\n\tconst problems = [];\n\tfor (const entry of entries.sort()) {\n\t\tconst entryPath = join(migrationsRoot, entry);\n\t\tif (!(await stat(entryPath)).isDirectory()) continue;\n\t\tconst manifestPath = join(entryPath, MANIFEST_FILE);\n\t\ttry {\n\t\t\tawait stat(manifestPath);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tlet pkg;\n\t\ttry {\n\t\t\tpkg = await readMigrationPackage(entryPath, options);\n\t\t} catch (error) {\n\t\t\tconst dirName = entry;\n\t\t\tif (MigrationToolsError.is(error)) {\n\t\t\t\tif (error.code === \"MIGRATION.HASH_MISMATCH\") {\n\t\t\t\t\tconst meta = error.meta;\n\t\t\t\t\tconst rawPkg = await readMigrationPackageRaw(entryPath);\n\t\t\t\t\tif (rawPkg !== null) packages.push(rawPkg);\n\t\t\t\t\tproblems.push({\n\t\t\t\t\t\tkind: \"hashMismatch\",\n\t\t\t\t\t\tdirName,\n\t\t\t\t\t\tstored: typeof meta?.[\"storedHash\"] === \"string\" ? meta[\"storedHash\"] : \"\",\n\t\t\t\t\t\tcomputed: typeof meta?.[\"computedHash\"] === \"string\" ? meta[\"computedHash\"] : \"\"\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error.code === \"MIGRATION.PROVIDED_INVARIANTS_MISMATCH\") {\n\t\t\t\t\tconst rawPkg = await readMigrationPackageRaw(entryPath);\n\t\t\t\t\tif (rawPkg !== null) packages.push(rawPkg);\n\t\t\t\t\tproblems.push({\n\t\t\t\t\t\tkind: \"providedInvariantsMismatch\",\n\t\t\t\t\t\tdirName\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tproblems.push({\n\t\t\t\tkind: \"packageUnloadable\",\n\t\t\t\tdirName,\n\t\t\t\tdetail: packageLoadProblemDetailFromError(error)\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tpackages.push(pkg);\n\t}\n\treturn {\n\t\tpackages,\n\t\tproblems\n\t};\n}\nfunction formatMigrationDirName(timestamp, slug) {\n\tconst sanitized = slug.toLowerCase().replace(/[^a-z0-9]/g, \"_\").replace(/_+/g, \"_\").replace(/^_|_$/g, \"\");\n\tif (sanitized.length === 0) throw errorInvalidSlug(slug);\n\tconst truncated = sanitized.slice(0, MAX_SLUG_LENGTH);\n\treturn `${timestamp.getUTCFullYear()}${String(timestamp.getUTCMonth() + 1).padStart(2, \"0\")}${String(timestamp.getUTCDate()).padStart(2, \"0\")}T${String(timestamp.getUTCHours()).padStart(2, \"0\")}${String(timestamp.getUTCMinutes()).padStart(2, \"0\")}_${truncated}`;\n}\n//#endregion\nexport { materialiseMigrationPackage as a, writeMigrationMetadata as c, materialiseExtensionMigrationPackageIfMissing as i, writeMigrationOps as l, copyFilesWithRename as n, readMigrationPackage as o, formatMigrationDirName as r, readMigrationsDir as s, MANIFEST_FILE as t, writeMigrationPackage as u };\n\n//# sourceMappingURL=io-BmWQNxRP.mjs.map"],"mappings":";;;;;;;;;;AAUA,MAAM,gBAAgB;AACtB,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,SAAS,aAAa,OAAO,MAAM;CAClC,OAAO,iBAAiB,SAAS,MAAM,SAAS;AACjD;AACA,MAAM,0BAA0B,KAAK;CACpC,KAAK;CACL,MAAM;CACN,IAAI;CACJ,eAAe;CACf,oBAAoB;CACpB,WAAW;AACZ,CAAC;AACD,eAAe,sBAAsB,KAAK,UAAU,KAAK;CACxD,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAC7C,IAAI;EACH,MAAM,MAAM,GAAG;CAChB,SAAS,OAAO;EACf,IAAI,aAAa,OAAO,QAAQ,GAAG,MAAM,qBAAqB,GAAG;EACjE,MAAM;CACP;CACA,MAAM,UAAU,KAAK,KAAK,aAAa,GAAG,KAAK,UA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;GACD;EACD;EACA,SAAS,KAAK,GAAG;CAClB;CACA,OAAO;EACN;EACA;CACD;AACD;AACA,SAAS,uBAAuB,WAAW,MAAM;CAChD,MAAM,YAAY,KAAK,YAAY,CAAC,CAAC,QAAQ,cAAc,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,EAAE;CACxG,IAAI,UAAU,WAAW,GAAG,MAAM,iBAAiB,IAAI;CACvD,MAAM,YAAY,UAAU,MAAM,GAAG,eAAe;CACpD,OAAO,GAAG,UAAU,eAAe,IAAI,OAAO,UAAU,YAAY,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,IAAI,OAAO,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG,OAAO,UAAU,YAAY,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,IAAI,OAAO,UAAU,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG;AAC3P"}
@@ -1,6 +1,6 @@
1
- import { A as errorOperationsNotArray, c as errorDescribeMissingEndContract, s as errorDescribeInvalidMetadata, v as errorInvalidOperationEntry, w as errorMigrationContractViewMissing } from "./errors-CcEpbfnE-CsSXrttT.mjs";
1
+ import { A as errorOperationsNotArray, c as errorDescribeMissingEndContract, s as errorDescribeInvalidMetadata, v as errorInvalidOperationEntry, w as errorMigrationContractViewMissing } from "./errors-SoLLYLtw-DMxVbVs9.mjs";
2
2
  import { t as computeMigrationHash } from "./hash-DH8hl5Rq-BpM2t3Nu.mjs";
3
- import { t as deriveProvidedInvariants } from "./invariants-DcFfhJMZ-BHDWZP9k.mjs";
3
+ import { t as deriveProvidedInvariants } from "./invariants-Cww4bv0v-BEiFxmbX.mjs";
4
4
  import { t as MigrationOpSchema } from "./op-schema-BSVHzEQN-DIWt28D8.mjs";
5
5
  import { realpathSync } from "node:fs";
6
6
  import { type } from "arktype";
@@ -206,4 +206,4 @@ async function buildMigrationArtifacts(instance, existing) {
206
206
  //#endregion
207
207
  export { isDirectEntrypoint as i, MigrationContractViews as n, buildMigrationArtifacts as r, Migration as t };
208
208
 
209
- //# sourceMappingURL=migration-CWSj4pMr.mjs.map
209
+ //# sourceMappingURL=migration-B9w-7dKe.mjs.map