@prisma-next/cli 0.3.0-pr.99.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +381 -128
- package/dist/agent-skill-mongo.md +106 -0
- package/dist/agent-skill-postgres.md +106 -0
- package/dist/cli-errors-BDCYR5ap.mjs +4 -0
- package/dist/cli-errors-DStABy9d.d.mts +3 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.js +1 -2910
- package/dist/cli.mjs +261 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-DiUkJAeN.mjs +987 -0
- package/dist/client-DiUkJAeN.mjs.map +1 -0
- package/dist/commands/contract-emit.d.mts +7 -0
- package/dist/commands/contract-emit.d.mts.map +1 -0
- package/dist/commands/contract-emit.mjs +9 -0
- package/dist/commands/contract-infer.d.mts +7 -0
- package/dist/commands/contract-infer.d.mts.map +1 -0
- package/dist/commands/contract-infer.mjs +10 -0
- package/dist/commands/db-init.d.mts +7 -0
- package/dist/commands/db-init.d.mts.map +1 -0
- package/dist/commands/db-init.mjs +126 -0
- package/dist/commands/db-init.mjs.map +1 -0
- package/dist/commands/db-schema.d.mts +7 -0
- package/dist/commands/db-schema.d.mts.map +1 -0
- package/dist/commands/db-schema.mjs +56 -0
- package/dist/commands/db-schema.mjs.map +1 -0
- package/dist/commands/db-sign.d.mts +7 -0
- package/dist/commands/db-sign.d.mts.map +1 -0
- package/dist/commands/db-sign.mjs +137 -0
- package/dist/commands/db-sign.mjs.map +1 -0
- package/dist/commands/db-update.d.mts +7 -0
- package/dist/commands/db-update.d.mts.map +1 -0
- package/dist/commands/db-update.mjs +123 -0
- package/dist/commands/db-update.mjs.map +1 -0
- package/dist/commands/db-verify.d.mts +7 -0
- package/dist/commands/db-verify.d.mts.map +1 -0
- package/dist/commands/db-verify.mjs +323 -0
- package/dist/commands/db-verify.mjs.map +1 -0
- package/dist/commands/migration-apply.d.mts +36 -0
- package/dist/commands/migration-apply.d.mts.map +1 -0
- package/dist/commands/migration-apply.mjs +245 -0
- package/dist/commands/migration-apply.mjs.map +1 -0
- package/dist/commands/migration-new.d.mts +8 -0
- package/dist/commands/migration-new.d.mts.map +1 -0
- package/dist/commands/migration-new.mjs +152 -0
- package/dist/commands/migration-new.mjs.map +1 -0
- package/dist/commands/migration-plan.d.mts +47 -0
- package/dist/commands/migration-plan.d.mts.map +1 -0
- package/dist/commands/migration-plan.mjs +313 -0
- package/dist/commands/migration-plan.mjs.map +1 -0
- package/dist/commands/migration-ref.d.mts +43 -0
- package/dist/commands/migration-ref.d.mts.map +1 -0
- package/dist/commands/migration-ref.mjs +195 -0
- package/dist/commands/migration-ref.mjs.map +1 -0
- package/dist/commands/migration-show.d.mts +28 -0
- package/dist/commands/migration-show.d.mts.map +1 -0
- package/dist/commands/migration-show.mjs +140 -0
- package/dist/commands/migration-show.mjs.map +1 -0
- package/dist/commands/migration-status.d.mts +86 -0
- package/dist/commands/migration-status.d.mts.map +1 -0
- package/dist/commands/migration-status.mjs +9 -0
- package/dist/commands/migration-verify.d.mts +16 -0
- package/dist/commands/migration-verify.d.mts.map +1 -0
- package/dist/commands/migration-verify.mjs +110 -0
- package/dist/commands/migration-verify.mjs.map +1 -0
- package/dist/config-loader-C4VXKl8f.mjs +43 -0
- package/dist/config-loader-C4VXKl8f.mjs.map +1 -0
- package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
- package/dist/config-loader.d.mts.map +1 -0
- package/dist/config-loader.mjs +3 -0
- package/dist/contract-emit-D2wDXfyo.mjs +191 -0
- package/dist/contract-emit-D2wDXfyo.mjs.map +1 -0
- package/dist/contract-emit-Zm_sd1wQ.mjs +112 -0
- package/dist/contract-emit-Zm_sd1wQ.mjs.map +1 -0
- package/dist/contract-emit-kN-IkKTE.mjs +6 -0
- package/dist/contract-enrichment-CGW6mm-E.mjs +79 -0
- package/dist/contract-enrichment-CGW6mm-E.mjs.map +1 -0
- package/dist/contract-infer-DozZT511.mjs +90 -0
- package/dist/contract-infer-DozZT511.mjs.map +1 -0
- package/dist/exports/config-types.d.mts +2 -0
- package/dist/exports/config-types.mjs +3 -0
- package/dist/exports/control-api.d.mts +624 -0
- package/dist/exports/control-api.d.mts.map +1 -0
- package/dist/exports/control-api.mjs +8 -0
- package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +12 -7
- package/dist/exports/index.d.mts.map +1 -0
- package/dist/exports/index.mjs +142 -0
- package/dist/exports/index.mjs.map +1 -0
- package/dist/extract-operation-statements-DZUJNmL3.mjs +13 -0
- package/dist/extract-operation-statements-DZUJNmL3.mjs.map +1 -0
- package/dist/extract-sql-ddl-DDMX-9mz.mjs +26 -0
- package/dist/extract-sql-ddl-DDMX-9mz.mjs.map +1 -0
- package/dist/framework-components-BAsliT4V.mjs +59 -0
- package/dist/framework-components-BAsliT4V.mjs.map +1 -0
- package/dist/init-6Pvm_esG.mjs +430 -0
- package/dist/init-6Pvm_esG.mjs.map +1 -0
- package/dist/inspect-live-schema-BYnhztxZ.mjs +91 -0
- package/dist/inspect-live-schema-BYnhztxZ.mjs.map +1 -0
- package/dist/migration-command-scaffold-CntCcntR.mjs +105 -0
- package/dist/migration-command-scaffold-CntCcntR.mjs.map +1 -0
- package/dist/migration-status-CJANY4yr.mjs +1583 -0
- package/dist/migration-status-CJANY4yr.mjs.map +1 -0
- package/dist/migrations-DTZBYXm1.mjs +173 -0
- package/dist/migrations-DTZBYXm1.mjs.map +1 -0
- package/dist/progress-adapter-B-YvmcDu.mjs +43 -0
- package/dist/progress-adapter-B-YvmcDu.mjs.map +1 -0
- package/dist/quick-reference-mongo.md +93 -0
- package/dist/quick-reference-postgres.md +91 -0
- package/dist/result-handler-oK_vA-Fn.mjs +697 -0
- package/dist/result-handler-oK_vA-Fn.mjs.map +1 -0
- package/dist/terminal-ui-C5k88MmW.mjs +274 -0
- package/dist/terminal-ui-C5k88MmW.mjs.map +1 -0
- package/dist/validate-contract-deps-esa-VQ0h.mjs +37 -0
- package/dist/validate-contract-deps-esa-VQ0h.mjs.map +1 -0
- package/dist/verify-DlFQ2FOw.mjs +385 -0
- package/dist/verify-DlFQ2FOw.mjs.map +1 -0
- package/package.json +87 -40
- package/src/cli.ts +118 -58
- package/src/commands/contract-emit.ts +101 -78
- package/src/commands/contract-infer-paths.ts +32 -0
- package/src/commands/contract-infer.ts +143 -0
- package/src/commands/db-init.ts +97 -219
- package/src/commands/db-schema.ts +77 -0
- package/src/commands/db-sign.ts +46 -73
- package/src/commands/db-update.ts +236 -0
- package/src/commands/db-verify.ts +409 -119
- package/src/commands/init/detect-package-manager.ts +47 -0
- package/src/commands/init/index.ts +21 -0
- package/src/commands/init/init.ts +203 -0
- package/src/commands/init/templates/agent-skill-mongo.md +106 -0
- package/src/commands/init/templates/agent-skill-postgres.md +106 -0
- package/src/commands/init/templates/agent-skill.ts +19 -0
- package/src/commands/init/templates/code-templates.ts +168 -0
- package/src/commands/init/templates/quick-reference-mongo.md +93 -0
- package/src/commands/init/templates/quick-reference-postgres.md +91 -0
- package/src/commands/init/templates/quick-reference.ts +19 -0
- package/src/commands/init/templates/render.ts +20 -0
- package/src/commands/init/templates/tsconfig.ts +35 -0
- package/src/commands/inspect-live-schema.ts +170 -0
- package/src/commands/migration-apply.ts +427 -0
- package/src/commands/migration-new.ts +260 -0
- package/src/commands/migration-plan.ts +519 -0
- package/src/commands/migration-ref.ts +305 -0
- package/src/commands/migration-show.ts +246 -0
- package/src/commands/migration-status.ts +864 -0
- package/src/commands/migration-verify.ts +180 -0
- package/src/config-loader.ts +13 -3
- package/src/control-api/client.ts +205 -183
- package/src/control-api/contract-enrichment.ts +119 -0
- package/src/control-api/errors.ts +9 -0
- package/src/control-api/operations/contract-emit.ts +181 -0
- package/src/control-api/operations/db-init.ts +53 -49
- package/src/control-api/operations/db-update.ts +220 -0
- package/src/control-api/operations/extract-operation-statements.ts +14 -0
- package/src/control-api/operations/extract-sql-ddl.ts +47 -0
- package/src/control-api/operations/migration-apply.ts +191 -0
- package/src/control-api/operations/migration-helpers.ts +49 -0
- package/src/control-api/types.ts +274 -52
- package/src/exports/config-types.ts +4 -3
- package/src/exports/control-api.ts +15 -5
- package/src/load-ts-contract.ts +30 -19
- package/src/utils/cli-errors.ts +14 -8
- package/src/utils/command-helpers.ts +302 -3
- package/src/utils/formatters/emit.ts +67 -0
- package/src/utils/formatters/errors.ts +82 -0
- package/src/utils/formatters/graph-migration-mapper.ts +240 -0
- package/src/utils/formatters/graph-render.ts +1323 -0
- package/src/utils/formatters/graph-types.ts +120 -0
- package/src/utils/formatters/help.ts +380 -0
- package/src/utils/formatters/helpers.ts +28 -0
- package/src/utils/formatters/migrations.ts +346 -0
- package/src/utils/formatters/styled.ts +212 -0
- package/src/utils/formatters/verify.ts +621 -0
- package/src/utils/framework-components.ts +13 -10
- package/src/utils/global-flags.ts +41 -23
- package/src/utils/migration-command-scaffold.ts +184 -0
- package/src/utils/migration-types.ts +12 -0
- package/src/utils/progress-adapter.ts +18 -29
- package/src/utils/result-handler.ts +12 -13
- package/src/utils/shutdown.ts +92 -0
- package/src/utils/suggest-command.ts +31 -0
- package/src/utils/terminal-ui.ts +276 -0
- package/src/utils/validate-contract-deps.ts +49 -0
- package/dist/chunk-AGOTG4L3.js +0 -965
- package/dist/chunk-AGOTG4L3.js.map +0 -1
- package/dist/chunk-HLLI4YL7.js +0 -180
- package/dist/chunk-HLLI4YL7.js.map +0 -1
- package/dist/chunk-HWYQOCAJ.js +0 -47
- package/dist/chunk-HWYQOCAJ.js.map +0 -1
- package/dist/chunk-VG2R7DGF.js +0 -735
- package/dist/chunk-VG2R7DGF.js.map +0 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/commands/contract-emit.d.ts +0 -3
- package/dist/commands/contract-emit.d.ts.map +0 -1
- package/dist/commands/contract-emit.js +0 -10
- package/dist/commands/contract-emit.js.map +0 -1
- package/dist/commands/db-init.d.ts +0 -3
- package/dist/commands/db-init.d.ts.map +0 -1
- package/dist/commands/db-init.js +0 -257
- package/dist/commands/db-init.js.map +0 -1
- package/dist/commands/db-introspect.d.ts +0 -3
- package/dist/commands/db-introspect.d.ts.map +0 -1
- package/dist/commands/db-introspect.js +0 -155
- package/dist/commands/db-introspect.js.map +0 -1
- package/dist/commands/db-schema-verify.d.ts +0 -3
- package/dist/commands/db-schema-verify.d.ts.map +0 -1
- package/dist/commands/db-schema-verify.js +0 -171
- package/dist/commands/db-schema-verify.js.map +0 -1
- package/dist/commands/db-sign.d.ts +0 -3
- package/dist/commands/db-sign.d.ts.map +0 -1
- package/dist/commands/db-sign.js +0 -195
- package/dist/commands/db-sign.js.map +0 -1
- package/dist/commands/db-verify.d.ts +0 -3
- package/dist/commands/db-verify.d.ts.map +0 -1
- package/dist/commands/db-verify.js +0 -193
- package/dist/commands/db-verify.js.map +0 -1
- package/dist/config-loader.d.ts.map +0 -1
- package/dist/config-loader.js +0 -7
- package/dist/config-loader.js.map +0 -1
- package/dist/control-api/client.d.ts +0 -13
- package/dist/control-api/client.d.ts.map +0 -1
- package/dist/control-api/operations/db-init.d.ts +0 -29
- package/dist/control-api/operations/db-init.d.ts.map +0 -1
- package/dist/control-api/types.d.ts +0 -387
- package/dist/control-api/types.d.ts.map +0 -1
- package/dist/exports/config-types.d.ts +0 -3
- package/dist/exports/config-types.d.ts.map +0 -1
- package/dist/exports/config-types.js +0 -6
- package/dist/exports/config-types.js.map +0 -1
- package/dist/exports/control-api.d.ts +0 -13
- package/dist/exports/control-api.d.ts.map +0 -1
- package/dist/exports/control-api.js +0 -7
- package/dist/exports/control-api.js.map +0 -1
- package/dist/exports/index.d.ts +0 -4
- package/dist/exports/index.d.ts.map +0 -1
- package/dist/exports/index.js +0 -176
- package/dist/exports/index.js.map +0 -1
- package/dist/load-ts-contract.d.ts.map +0 -1
- package/dist/utils/cli-errors.d.ts +0 -7
- package/dist/utils/cli-errors.d.ts.map +0 -1
- package/dist/utils/command-helpers.d.ts +0 -12
- package/dist/utils/command-helpers.d.ts.map +0 -1
- package/dist/utils/framework-components.d.ts +0 -70
- package/dist/utils/framework-components.d.ts.map +0 -1
- package/dist/utils/global-flags.d.ts +0 -25
- package/dist/utils/global-flags.d.ts.map +0 -1
- package/dist/utils/output.d.ts +0 -142
- package/dist/utils/output.d.ts.map +0 -1
- package/dist/utils/progress-adapter.d.ts +0 -26
- package/dist/utils/progress-adapter.d.ts.map +0 -1
- package/dist/utils/result-handler.d.ts +0 -15
- package/dist/utils/result-handler.d.ts.map +0 -1
- package/src/commands/db-introspect.ts +0 -227
- package/src/commands/db-schema-verify.ts +0 -238
- package/src/utils/output.ts +0 -1471
|
@@ -0,0 +1,1583 @@
|
|
|
1
|
+
import { t as loadConfig } from "./config-loader-C4VXKl8f.mjs";
|
|
2
|
+
import { _ as errorUnexpected, m as errorRuntime } from "./cli-errors-BDCYR5ap.mjs";
|
|
3
|
+
import { t as createControlClient } from "./client-DiUkJAeN.mjs";
|
|
4
|
+
import { _ as formatStyledHeader, a as maskConnectionUrl, c as resolveMigrationPaths, d as setCommandExamples, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, o as readContractEnvelope, p as toPathDecisionResult, t as handleResult, u as setCommandDescriptions } from "./result-handler-oK_vA-Fn.mjs";
|
|
5
|
+
import { t as TerminalUI } from "./terminal-ui-C5k88MmW.mjs";
|
|
6
|
+
import { Command } from "commander";
|
|
7
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
|
+
import { ifDefined } from "@prisma-next/utils/defined";
|
|
9
|
+
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
10
|
+
import { findPath, findPathWithDecision, findReachableLeaves } from "@prisma-next/migration-tools/dag";
|
|
11
|
+
import { MigrationToolsError } from "@prisma-next/migration-tools/types";
|
|
12
|
+
import { bold, cyan, dim, magenta, yellow } from "colorette";
|
|
13
|
+
import { readRefs, resolveRef } from "@prisma-next/migration-tools/refs";
|
|
14
|
+
import dagre from "@dagrejs/dagre";
|
|
15
|
+
|
|
16
|
+
//#region src/utils/formatters/graph-types.ts
|
|
17
|
+
/**
|
|
18
|
+
* Immutable directed graph with adjacency-list indexing.
|
|
19
|
+
*
|
|
20
|
+
* Built once from flat arrays of nodes and edges, then passed around as
|
|
21
|
+
* the primary graph representation for rendering, traversal, truncation,
|
|
22
|
+
* and subgraph extraction.
|
|
23
|
+
*/
|
|
24
|
+
var RenderGraph = class {
|
|
25
|
+
nodes;
|
|
26
|
+
edges;
|
|
27
|
+
/** Forward adjacency: node id → outgoing edges. */
|
|
28
|
+
forward;
|
|
29
|
+
/** Set of node ids that have at least one incoming edge. */
|
|
30
|
+
incomingNodes;
|
|
31
|
+
/** Node lookup by id. */
|
|
32
|
+
nodeById;
|
|
33
|
+
constructor(nodes, edges) {
|
|
34
|
+
this.nodes = nodes;
|
|
35
|
+
this.edges = edges;
|
|
36
|
+
const fwd = /* @__PURE__ */ new Map();
|
|
37
|
+
const inc = /* @__PURE__ */ new Set();
|
|
38
|
+
const byId = /* @__PURE__ */ new Map();
|
|
39
|
+
for (const n of nodes) byId.set(n.id, n);
|
|
40
|
+
for (const e of edges) {
|
|
41
|
+
const list = fwd.get(e.from);
|
|
42
|
+
if (list) list.push(e);
|
|
43
|
+
else fwd.set(e.from, [e]);
|
|
44
|
+
inc.add(e.to);
|
|
45
|
+
}
|
|
46
|
+
this.forward = fwd;
|
|
47
|
+
this.incomingNodes = inc;
|
|
48
|
+
this.nodeById = byId;
|
|
49
|
+
}
|
|
50
|
+
/** Outgoing edges from a node (empty array if none). */
|
|
51
|
+
outgoing(nodeId) {
|
|
52
|
+
return this.forward.get(nodeId) ?? [];
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/utils/formatters/graph-migration-mapper.ts
|
|
58
|
+
/**
|
|
59
|
+
* Maps MigrationGraph + status info to the generic graph renderer types.
|
|
60
|
+
*/
|
|
61
|
+
const STATUS_ICON = {
|
|
62
|
+
applied: " ✓",
|
|
63
|
+
pending: " ⧗",
|
|
64
|
+
unreachable: " ✗"
|
|
65
|
+
};
|
|
66
|
+
/** Shorten a contract hash for display: strip sha256: prefix, take 7 chars. */
|
|
67
|
+
function shortHash(hash) {
|
|
68
|
+
return (hash.startsWith("sha256:") ? hash.slice(7) : hash).slice(0, 7);
|
|
69
|
+
}
|
|
70
|
+
function toShortId(hash) {
|
|
71
|
+
return hash === EMPTY_CONTRACT_HASH ? "∅" : shortHash(hash);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Convert a MigrationGraph + status info into the generic graph renderer types.
|
|
75
|
+
*/
|
|
76
|
+
function migrationGraphToRenderInput(input) {
|
|
77
|
+
const { graph, mode, markerHash, contractHash, refs, activeRefHash, edgeStatuses } = input;
|
|
78
|
+
const statusByDirName = new Map(edgeStatuses?.map((e) => [e.dirName, e.status]));
|
|
79
|
+
const nodeList = [];
|
|
80
|
+
for (const nodeId of graph.nodes) {
|
|
81
|
+
const markers = [];
|
|
82
|
+
if (mode === "online" && markerHash === nodeId) markers.push({ kind: "db" });
|
|
83
|
+
if (refs) {
|
|
84
|
+
for (const ref of refs) if (ref.hash === nodeId) markers.push({
|
|
85
|
+
kind: "ref",
|
|
86
|
+
name: ref.name,
|
|
87
|
+
active: ref.active
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
if (contractHash === nodeId && contractHash !== EMPTY_CONTRACT_HASH) markers.push({
|
|
91
|
+
kind: "contract",
|
|
92
|
+
planned: true
|
|
93
|
+
});
|
|
94
|
+
nodeList.push({
|
|
95
|
+
id: toShortId(nodeId),
|
|
96
|
+
markers: markers.length > 0 ? markers : void 0
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const edgeList = [];
|
|
100
|
+
for (const [, entries] of graph.forwardChain) for (const entry of entries) {
|
|
101
|
+
const status = statusByDirName.get(entry.dirName);
|
|
102
|
+
const icon = status ? STATUS_ICON[status] : "";
|
|
103
|
+
const label = `${entry.dirName}${icon}`;
|
|
104
|
+
edgeList.push({
|
|
105
|
+
from: toShortId(entry.from),
|
|
106
|
+
to: toShortId(entry.to),
|
|
107
|
+
label,
|
|
108
|
+
...ifDefined("colorHint", status)
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const relevantPaths = [];
|
|
112
|
+
const rootId = EMPTY_CONTRACT_HASH;
|
|
113
|
+
function addPathFromRoot(targetHash) {
|
|
114
|
+
if (!graph.nodes.has(targetHash)) return;
|
|
115
|
+
const raw = findPath(graph, rootId, targetHash);
|
|
116
|
+
if (raw && raw.length > 0) relevantPaths.push([toShortId(rootId), ...raw.map((e) => toShortId(e.to))]);
|
|
117
|
+
}
|
|
118
|
+
function addPathBetween(fromHash, toHash) {
|
|
119
|
+
/* v8 ignore next -- @preserve */
|
|
120
|
+
if (!graph.nodes.has(fromHash) || !graph.nodes.has(toHash)) return;
|
|
121
|
+
const raw = findPath(graph, fromHash, toHash);
|
|
122
|
+
if (raw && raw.length > 0) relevantPaths.push([toShortId(fromHash), ...raw.map((e) => toShortId(e.to))]);
|
|
123
|
+
}
|
|
124
|
+
if (mode === "online" && markerHash) addPathFromRoot(markerHash);
|
|
125
|
+
if (activeRefHash && activeRefHash !== markerHash) addPathFromRoot(activeRefHash);
|
|
126
|
+
if (contractHash !== EMPTY_CONTRACT_HASH) {
|
|
127
|
+
let contractReached = false;
|
|
128
|
+
if (markerHash && markerHash !== contractHash) {
|
|
129
|
+
if (findPath(graph, markerHash, contractHash)) {
|
|
130
|
+
addPathBetween(markerHash, contractHash);
|
|
131
|
+
contractReached = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (activeRefHash && activeRefHash !== markerHash && activeRefHash !== contractHash) {
|
|
135
|
+
if (findPath(graph, activeRefHash, contractHash)) {
|
|
136
|
+
addPathBetween(activeRefHash, contractHash);
|
|
137
|
+
contractReached = true;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (!contractReached && contractHash !== (markerHash ?? activeRefHash)) addPathFromRoot(contractHash);
|
|
141
|
+
}
|
|
142
|
+
if (relevantPaths.length === 0) addPathFromRoot([...graph.forwardChain.values()].flat().pop()?.to ?? EMPTY_CONTRACT_HASH);
|
|
143
|
+
let spineTargetHash;
|
|
144
|
+
if (activeRefHash && graph.nodes.has(activeRefHash)) spineTargetHash = activeRefHash;
|
|
145
|
+
else if (contractHash !== EMPTY_CONTRACT_HASH && graph.nodes.has(contractHash)) spineTargetHash = contractHash;
|
|
146
|
+
else spineTargetHash = [...graph.forwardChain.values()].flat().pop()?.to ?? EMPTY_CONTRACT_HASH;
|
|
147
|
+
if (contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash)) {
|
|
148
|
+
const contractMarkers = [];
|
|
149
|
+
if (mode === "online" && markerHash === contractHash) contractMarkers.push({ kind: "db" });
|
|
150
|
+
contractMarkers.push({
|
|
151
|
+
kind: "contract",
|
|
152
|
+
planned: false
|
|
153
|
+
});
|
|
154
|
+
nodeList.push({
|
|
155
|
+
id: shortHash(contractHash),
|
|
156
|
+
markers: contractMarkers
|
|
157
|
+
});
|
|
158
|
+
const matchingDraft = input.draftEdges?.find((d) => d.to === contractHash);
|
|
159
|
+
const fromHash = matchingDraft?.from ?? spineTargetHash;
|
|
160
|
+
if (graph.nodes.has(fromHash) || fromHash === spineTargetHash) edgeList.push({
|
|
161
|
+
from: toShortId(fromHash),
|
|
162
|
+
to: shortHash(contractHash),
|
|
163
|
+
...ifDefined("label", matchingDraft ? `${matchingDraft.dirName} [draft]` : void 0),
|
|
164
|
+
style: "dashed"
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
graph: new RenderGraph(nodeList, edgeList),
|
|
169
|
+
options: {
|
|
170
|
+
spineTarget: toShortId(spineTargetHash),
|
|
171
|
+
rootId: "∅",
|
|
172
|
+
colorize: true
|
|
173
|
+
},
|
|
174
|
+
relevantPaths
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/utils/formatters/graph-render.ts
|
|
180
|
+
/**
|
|
181
|
+
* Terminal graph renderer.
|
|
182
|
+
*
|
|
183
|
+
* Renders directed graphs as ASCII/box-drawing art for terminal output. Uses
|
|
184
|
+
* dagre for automatic layout (rank assignment + coordinate placement), then
|
|
185
|
+
* stamps the result onto a {@link CharGrid} — a sparse character canvas that
|
|
186
|
+
* resolves box-drawing junctions, color priority, and label placement.
|
|
187
|
+
*
|
|
188
|
+
* ## Rendering pipeline
|
|
189
|
+
*
|
|
190
|
+
* 1. **Layout** — dagre assigns (x, y) coordinates to nodes and polyline
|
|
191
|
+
* control points to edges. We use `rankdir: 'TB'` (top-to-bottom).
|
|
192
|
+
* 2. **Orthogonalization** — dagre's polylines may contain diagonal segments.
|
|
193
|
+
* {@link selectBestVariant} resolves each diagonal into an L-shaped bend,
|
|
194
|
+
* enumerating all 2^N combinations and picking the variant with fewest
|
|
195
|
+
* corners and shortest total length.
|
|
196
|
+
* 3. **Edge stamping** — orthogonal segments are stamped onto the CharGrid as
|
|
197
|
+
* directional bitmasks. The grid resolves overlapping directions into the
|
|
198
|
+
* correct box-drawing character (│, ─, ┌, ┼, etc.).
|
|
199
|
+
* 4. **Label placement** — edge labels are placed adjacent to their polyline
|
|
200
|
+
* segments, preferring horizontal (branch-specific) segments over shared
|
|
201
|
+
* vertical trunks to avoid ambiguity.
|
|
202
|
+
* 5. **Arrowheads** — ▾ ▴ ◂ ▸ placed one cell before the terminal point.
|
|
203
|
+
* 6. **Node stamping** — `○ nodeId` with inline marker tags (db, contract,
|
|
204
|
+
* ref names).
|
|
205
|
+
* 7. **Elided indicator** — when truncation is active, `┊ (N earlier
|
|
206
|
+
* migrations)` is stamped above the visible root.
|
|
207
|
+
* 8. **Detached nodes** — rendered below the graph with `◇` and a dotted
|
|
208
|
+
* connector.
|
|
209
|
+
*
|
|
210
|
+
* ## Graph filtering
|
|
211
|
+
*
|
|
212
|
+
* The caller controls what graph is rendered: the full graph, or a subgraph
|
|
213
|
+
* extracted via {@link extractRelevantSubgraph} (union of relevant paths).
|
|
214
|
+
* The renderer itself is agnostic — it renders whatever graph it receives.
|
|
215
|
+
*
|
|
216
|
+
* Truncation is supported via `options.limit`.
|
|
217
|
+
*
|
|
218
|
+
* ## Color accessibility
|
|
219
|
+
*
|
|
220
|
+
* Uses a CVD-safe palette — no red/green contrast. Shape and icon always
|
|
221
|
+
* carry meaning; color only reinforces.
|
|
222
|
+
*/
|
|
223
|
+
function segment(from, to) {
|
|
224
|
+
return {
|
|
225
|
+
from,
|
|
226
|
+
to
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function isVertical(seg) {
|
|
230
|
+
return seg.from.x === seg.to.x;
|
|
231
|
+
}
|
|
232
|
+
function manhattanLength(seg) {
|
|
233
|
+
return Math.abs(seg.to.x - seg.from.x) + Math.abs(seg.to.y - seg.from.y);
|
|
234
|
+
}
|
|
235
|
+
/** Rotating palette for ref marker names, cycling through these for each ref. */
|
|
236
|
+
const REF_COLORS = [
|
|
237
|
+
yellow,
|
|
238
|
+
magenta,
|
|
239
|
+
bold,
|
|
240
|
+
cyan
|
|
241
|
+
];
|
|
242
|
+
/** Build the color palette, respecting the `colorize` flag. When false, all color functions become identity. */
|
|
243
|
+
function buildColors(colorize) {
|
|
244
|
+
const c = (fn) => colorize ? fn : (s) => s;
|
|
245
|
+
return {
|
|
246
|
+
spine: c(cyan),
|
|
247
|
+
branch: c(dim),
|
|
248
|
+
backward: c(magenta),
|
|
249
|
+
applied: c(cyan),
|
|
250
|
+
pending: c(yellow),
|
|
251
|
+
unreachable: c(magenta),
|
|
252
|
+
node: c(cyan),
|
|
253
|
+
label: c(dim),
|
|
254
|
+
marker: c(bold),
|
|
255
|
+
ref: (index) => c(REF_COLORS[index % REF_COLORS.length])
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/** Map a `colorHint` value to its color function, or `undefined` for no hint. */
|
|
259
|
+
function resolveHintColor(hint, colors) {
|
|
260
|
+
if (hint === "applied") return colors.applied;
|
|
261
|
+
if (hint === "pending") return colors.pending;
|
|
262
|
+
if (hint === "unreachable") return colors.unreachable;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Edge drawing priorities — higher priority wins when edges overlap on the
|
|
266
|
+
* same grid cell. Backward edges are drawn on top so rollback paths remain
|
|
267
|
+
* visible over spine and branch edges.
|
|
268
|
+
*/
|
|
269
|
+
const PRIORITY = {
|
|
270
|
+
branch: 1,
|
|
271
|
+
spine: 2,
|
|
272
|
+
backward: 3
|
|
273
|
+
};
|
|
274
|
+
const DIR = {
|
|
275
|
+
up: 1,
|
|
276
|
+
down: 2,
|
|
277
|
+
left: 4,
|
|
278
|
+
right: 8,
|
|
279
|
+
dashed: 16
|
|
280
|
+
};
|
|
281
|
+
/** Arrow characters for edge termination (one cell before the target node). */
|
|
282
|
+
const ARROW = {
|
|
283
|
+
up: "▴",
|
|
284
|
+
down: "▾",
|
|
285
|
+
left: "◂",
|
|
286
|
+
right: "▸"
|
|
287
|
+
};
|
|
288
|
+
/** Maps a direction bitmask to its box-drawing character. */
|
|
289
|
+
const BOX_CHAR = {
|
|
290
|
+
0: " ",
|
|
291
|
+
[DIR.up]: "│",
|
|
292
|
+
[DIR.down]: "│",
|
|
293
|
+
[DIR.up | DIR.down]: "│",
|
|
294
|
+
[DIR.left]: "─",
|
|
295
|
+
[DIR.right]: "─",
|
|
296
|
+
[DIR.left | DIR.right]: "─",
|
|
297
|
+
[DIR.down | DIR.right]: "┌",
|
|
298
|
+
[DIR.down | DIR.left]: "┐",
|
|
299
|
+
[DIR.up | DIR.right]: "└",
|
|
300
|
+
[DIR.up | DIR.left]: "┘",
|
|
301
|
+
[DIR.up | DIR.down | DIR.right]: "├",
|
|
302
|
+
[DIR.up | DIR.down | DIR.left]: "┤",
|
|
303
|
+
[DIR.left | DIR.right | DIR.down]: "┬",
|
|
304
|
+
[DIR.left | DIR.right | DIR.up]: "┴",
|
|
305
|
+
[DIR.up | DIR.down | DIR.left | DIR.right]: "┼",
|
|
306
|
+
[DIR.up | DIR.dashed]: "┊",
|
|
307
|
+
[DIR.down | DIR.dashed]: "┊",
|
|
308
|
+
[DIR.up | DIR.down | DIR.dashed]: "┊",
|
|
309
|
+
[DIR.left | DIR.dashed]: "┈",
|
|
310
|
+
[DIR.right | DIR.dashed]: "┈",
|
|
311
|
+
[DIR.left | DIR.right | DIR.dashed]: "┈"
|
|
312
|
+
};
|
|
313
|
+
/**
|
|
314
|
+
* Convert a node's markers into renderable inline tags.
|
|
315
|
+
*
|
|
316
|
+
* - `db` → `◆ db`
|
|
317
|
+
* - `contract` → `◆ contract` (applied) or `◇ contract` (planned)
|
|
318
|
+
* - `ref` → the ref name, colored from the rotating {@link REF_COLORS} palette
|
|
319
|
+
* - `custom` → the custom label
|
|
320
|
+
*/
|
|
321
|
+
function buildInlineTags(markers, colors) {
|
|
322
|
+
const tags = [];
|
|
323
|
+
const refNames = markers.filter((m) => m.kind === "ref").map((m) => m.name);
|
|
324
|
+
for (const m of markers) if (m.kind === "db") tags.push({
|
|
325
|
+
text: "◆ db",
|
|
326
|
+
color: colors.marker
|
|
327
|
+
});
|
|
328
|
+
else if (m.kind === "contract") tags.push({
|
|
329
|
+
text: m.planned ? "◆ contract" : "◇ contract",
|
|
330
|
+
color: colors.marker
|
|
331
|
+
});
|
|
332
|
+
else if (m.kind === "ref") tags.push({
|
|
333
|
+
text: m.name,
|
|
334
|
+
color: colors.ref(refNames.indexOf(m.name))
|
|
335
|
+
});
|
|
336
|
+
else if (m.kind === "custom") tags.push({
|
|
337
|
+
text: m.label,
|
|
338
|
+
color: colors.marker
|
|
339
|
+
});
|
|
340
|
+
return tags;
|
|
341
|
+
}
|
|
342
|
+
/** Total character width of inline tags including leading spaces (0 if no tags). */
|
|
343
|
+
function inlineTagsWidth(tags) {
|
|
344
|
+
if (tags.length === 0) return 0;
|
|
345
|
+
return tags.reduce((w, t) => w + 1 + t.text.length, 0);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Sparse character canvas for terminal graph rendering.
|
|
349
|
+
*
|
|
350
|
+
* Coordinates are unbounded integers — the grid auto-expands as content is
|
|
351
|
+
* added and trims to the bounding box on {@link render}.
|
|
352
|
+
*/
|
|
353
|
+
var CharGrid = class {
|
|
354
|
+
connections = /* @__PURE__ */ new Map();
|
|
355
|
+
cellColors = /* @__PURE__ */ new Map();
|
|
356
|
+
chars = /* @__PURE__ */ new Map();
|
|
357
|
+
reserved = /* @__PURE__ */ new Set();
|
|
358
|
+
minX = Number.POSITIVE_INFINITY;
|
|
359
|
+
maxX = Number.NEGATIVE_INFINITY;
|
|
360
|
+
minY = Number.POSITIVE_INFINITY;
|
|
361
|
+
maxY = Number.NEGATIVE_INFINITY;
|
|
362
|
+
key(x, y) {
|
|
363
|
+
return `${x},${y}`;
|
|
364
|
+
}
|
|
365
|
+
/** Expand the bounding box to include (x, y). */
|
|
366
|
+
touch(x, y) {
|
|
367
|
+
if (x < this.minX) this.minX = x;
|
|
368
|
+
if (x > this.maxX) this.maxX = x;
|
|
369
|
+
if (y < this.minY) this.minY = y;
|
|
370
|
+
if (y > this.maxY) this.maxY = y;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Add a directional connection at (x, y). Multiple calls at the same cell
|
|
374
|
+
* are OR'd together — e.g. `addConnection(x, y, UP)` then
|
|
375
|
+
* `addConnection(x, y, RIGHT)` produces a └ corner. Color follows
|
|
376
|
+
* priority: higher-priority edges win at shared cells.
|
|
377
|
+
*/
|
|
378
|
+
addConnection(x, y, dir, color, priority = PRIORITY.branch) {
|
|
379
|
+
this.touch(x, y);
|
|
380
|
+
const k = this.key(x, y);
|
|
381
|
+
this.connections.set(k, (this.connections.get(k) ?? 0) | dir);
|
|
382
|
+
const existing = this.cellColors.get(k);
|
|
383
|
+
if (!existing || priority >= existing.priority) this.cellColors.set(k, {
|
|
384
|
+
color,
|
|
385
|
+
priority
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
/** Stamp a horizontal edge segment from x1 to x2 at row y. */
|
|
389
|
+
markHorizontal(y, x1, x2, color, priority, extraBits = 0) {
|
|
390
|
+
const lo = Math.min(x1, x2);
|
|
391
|
+
const hi = Math.max(x1, x2);
|
|
392
|
+
/* v8 ignore next -- @preserve */
|
|
393
|
+
if (lo === hi) return;
|
|
394
|
+
this.addConnection(lo, y, DIR.right | extraBits, color, priority);
|
|
395
|
+
for (let x = lo + 1; x < hi; x++) this.addConnection(x, y, DIR.left | DIR.right | extraBits, color, priority);
|
|
396
|
+
this.addConnection(hi, y, DIR.left | extraBits, color, priority);
|
|
397
|
+
}
|
|
398
|
+
/** Stamp a vertical edge segment from y1 to y2 at column x. */
|
|
399
|
+
markVertical(x, y1, y2, color, priority, extraBits = 0) {
|
|
400
|
+
const lo = Math.min(y1, y2);
|
|
401
|
+
const hi = Math.max(y1, y2);
|
|
402
|
+
/* v8 ignore next -- @preserve */
|
|
403
|
+
if (lo === hi) return;
|
|
404
|
+
this.addConnection(x, lo, DIR.down | extraBits, color, priority);
|
|
405
|
+
for (let y = lo + 1; y < hi; y++) this.addConnection(x, y, DIR.up | DIR.down | extraBits, color, priority);
|
|
406
|
+
this.addConnection(x, hi, DIR.up | extraBits, color, priority);
|
|
407
|
+
}
|
|
408
|
+
/** Place literal text at (x, y). Each character occupies one cell. Text stamps override connections. */
|
|
409
|
+
stampText(x, y, text, color) {
|
|
410
|
+
for (let i = 0; i < text.length; i++) {
|
|
411
|
+
const cx = x + i;
|
|
412
|
+
this.touch(cx, y);
|
|
413
|
+
this.chars.set(this.key(cx, y), {
|
|
414
|
+
ch: text[i],
|
|
415
|
+
color
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/** True if (x, y) has stamped text or is in a reserved area (node labels). */
|
|
420
|
+
hasLabel(x, y) {
|
|
421
|
+
return this.chars.has(this.key(x, y)) || this.reserved.has(this.key(x, y));
|
|
422
|
+
}
|
|
423
|
+
/** True if (x, y) has any directional connection (an edge passes through). */
|
|
424
|
+
hasConnection(x, y) {
|
|
425
|
+
return (this.connections.get(this.key(x, y)) ?? 0) !== 0;
|
|
426
|
+
}
|
|
427
|
+
/** True if (x, y) has stamped text (not just a reserved area). */
|
|
428
|
+
hasText(x, y) {
|
|
429
|
+
return this.chars.has(this.key(x, y));
|
|
430
|
+
}
|
|
431
|
+
/** Reserve a horizontal span so label placement avoids it. Used for node id + marker regions. */
|
|
432
|
+
reserveArea(x, y, width) {
|
|
433
|
+
for (let i = 0; i < width; i++) this.reserved.add(this.key(x + i, y));
|
|
434
|
+
}
|
|
435
|
+
/** The largest y coordinate with content — used for positioning detached nodes below the graph. */
|
|
436
|
+
getMaxY() {
|
|
437
|
+
return this.maxY;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Render the grid to a multi-line string.
|
|
441
|
+
*
|
|
442
|
+
* Iterates row by row over the bounding box, resolving each cell to either
|
|
443
|
+
* its stamped text character or the box-drawing character for its
|
|
444
|
+
* connection bitmask. Consecutive characters with the same color are
|
|
445
|
+
* batched into a single ANSI-wrapped run for efficiency.
|
|
446
|
+
*/
|
|
447
|
+
render() {
|
|
448
|
+
/* v8 ignore next -- @preserve */
|
|
449
|
+
if (this.minX === Number.POSITIVE_INFINITY) return "(empty)";
|
|
450
|
+
const rows = [];
|
|
451
|
+
for (let y = this.minY; y <= this.maxY; y++) {
|
|
452
|
+
let row = "";
|
|
453
|
+
let runChars = "";
|
|
454
|
+
let runColor;
|
|
455
|
+
const flush = () => {
|
|
456
|
+
if (runChars.length === 0) return;
|
|
457
|
+
row += runColor ? runColor(runChars) : runChars;
|
|
458
|
+
runChars = "";
|
|
459
|
+
};
|
|
460
|
+
for (let x = this.minX; x <= this.maxX; x++) {
|
|
461
|
+
const k = this.key(x, y);
|
|
462
|
+
let ch;
|
|
463
|
+
let color;
|
|
464
|
+
const label = this.chars.get(k);
|
|
465
|
+
if (label) {
|
|
466
|
+
ch = label.ch;
|
|
467
|
+
color = label.color;
|
|
468
|
+
} else {
|
|
469
|
+
const conn = this.connections.get(k) ?? 0;
|
|
470
|
+
ch = BOX_CHAR[conn] ?? BOX_CHAR[conn & ~DIR.dashed] ?? " ";
|
|
471
|
+
color = conn === 0 ? void 0 : this.cellColors.get(k)?.color;
|
|
472
|
+
}
|
|
473
|
+
if (color !== runColor) {
|
|
474
|
+
flush();
|
|
475
|
+
runColor = color;
|
|
476
|
+
}
|
|
477
|
+
runChars += ch;
|
|
478
|
+
}
|
|
479
|
+
flush();
|
|
480
|
+
rows.push(row.trimEnd());
|
|
481
|
+
}
|
|
482
|
+
while (rows.length > 0 && rows[rows.length - 1] === "") rows.pop();
|
|
483
|
+
return rows.join("\n");
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
/**
|
|
487
|
+
* Find the set of edge keys (`"from→to"`) on the shortest path from
|
|
488
|
+
* `rootId` to `targetId`. Used to color spine edges distinctly from
|
|
489
|
+
* branch edges in the rendered output.
|
|
490
|
+
*
|
|
491
|
+
* Returns an empty set if no path exists.
|
|
492
|
+
*/
|
|
493
|
+
function findSpineEdges(graph, rootId, targetId) {
|
|
494
|
+
const visited = new Set([rootId]);
|
|
495
|
+
const parent = /* @__PURE__ */ new Map();
|
|
496
|
+
const queue = [rootId];
|
|
497
|
+
while (queue.length > 0) {
|
|
498
|
+
const current = queue.shift();
|
|
499
|
+
if (current === targetId) {
|
|
500
|
+
const spineEdges = /* @__PURE__ */ new Set();
|
|
501
|
+
let node = targetId;
|
|
502
|
+
while (parent.has(node)) {
|
|
503
|
+
const edge = parent.get(node);
|
|
504
|
+
spineEdges.add(`${edge.from}→${edge.to}`);
|
|
505
|
+
node = edge.from;
|
|
506
|
+
}
|
|
507
|
+
return spineEdges;
|
|
508
|
+
}
|
|
509
|
+
for (const edge of graph.outgoing(current)) if (!visited.has(edge.to)) {
|
|
510
|
+
visited.add(edge.to);
|
|
511
|
+
parent.set(edge.to, edge);
|
|
512
|
+
queue.push(edge.to);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return /* @__PURE__ */ new Set();
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Prepend `src` and append `tgt` to dagre's control points, round to
|
|
519
|
+
* integers, and deduplicate consecutive identical points.
|
|
520
|
+
*/
|
|
521
|
+
function prepareRawPoints(src, dagrePoints, tgt) {
|
|
522
|
+
const rounded = [
|
|
523
|
+
src,
|
|
524
|
+
...dagrePoints,
|
|
525
|
+
tgt
|
|
526
|
+
].map((p) => ({
|
|
527
|
+
x: Math.round(p.x),
|
|
528
|
+
y: Math.round(p.y)
|
|
529
|
+
}));
|
|
530
|
+
const deduped = [rounded[0]];
|
|
531
|
+
for (let i = 1; i < rounded.length; i++) {
|
|
532
|
+
const prev = deduped[deduped.length - 1];
|
|
533
|
+
const curr = rounded[i];
|
|
534
|
+
if (curr.x !== prev.x || curr.y !== prev.y) deduped.push(curr);
|
|
535
|
+
}
|
|
536
|
+
return deduped;
|
|
537
|
+
}
|
|
538
|
+
function countDiagonals(points) {
|
|
539
|
+
let count = 0;
|
|
540
|
+
for (let i = 1; i < points.length; i++) {
|
|
541
|
+
const prev = points[i - 1];
|
|
542
|
+
const curr = points[i];
|
|
543
|
+
if (prev.x !== curr.x && prev.y !== curr.y) count++;
|
|
544
|
+
}
|
|
545
|
+
return count;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Decode a bitmask into an array of bend directions.
|
|
549
|
+
*
|
|
550
|
+
* Each bit selects how one diagonal is converted to an orthogonal corner:
|
|
551
|
+
* 0 → horizontal-first, 1 → vertical-first. Used by {@link selectBestVariant}
|
|
552
|
+
* to enumerate all 2^N combinations.
|
|
553
|
+
*/
|
|
554
|
+
function bitsToBends(bits, count) {
|
|
555
|
+
const bends = [];
|
|
556
|
+
for (let k = 0; k < count; k++) bends.push(bits >> k & 1 ? "vertical-first" : "horizontal-first");
|
|
557
|
+
return bends;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Build one polyline variant by resolving each diagonal with the given bend direction.
|
|
561
|
+
*
|
|
562
|
+
* Diagonals are detected inline: when the last emitted point and the next
|
|
563
|
+
* input point differ in both x and y, the segment is diagonal and is
|
|
564
|
+
* resolved using the next value from `bends`. The result is deduplicated
|
|
565
|
+
* to remove zero-length segments created when a bend coincides with an
|
|
566
|
+
* adjacent point.
|
|
567
|
+
*/
|
|
568
|
+
function buildVariant(points, bends) {
|
|
569
|
+
/* v8 ignore next -- @preserve */
|
|
570
|
+
if (points.length < 2) return points;
|
|
571
|
+
let bendIdx = 0;
|
|
572
|
+
const result = [points[0]];
|
|
573
|
+
for (let i = 1; i < points.length; i++) {
|
|
574
|
+
const prev = result[result.length - 1];
|
|
575
|
+
const curr = points[i];
|
|
576
|
+
if (prev.x === curr.x || prev.y === curr.y) result.push(curr);
|
|
577
|
+
else {
|
|
578
|
+
if ((bends[bendIdx++] ?? "horizontal-first") === "horizontal-first") result.push({
|
|
579
|
+
x: curr.x,
|
|
580
|
+
y: prev.y
|
|
581
|
+
});
|
|
582
|
+
else result.push({
|
|
583
|
+
x: prev.x,
|
|
584
|
+
y: curr.y
|
|
585
|
+
});
|
|
586
|
+
result.push(curr);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const final = [result[0]];
|
|
590
|
+
for (let i = 1; i < result.length; i++) {
|
|
591
|
+
const prev = final[final.length - 1];
|
|
592
|
+
const curr = result[i];
|
|
593
|
+
if (curr.x !== prev.x || curr.y !== prev.y) final.push(curr);
|
|
594
|
+
}
|
|
595
|
+
return final;
|
|
596
|
+
}
|
|
597
|
+
/** Count the number of direction changes (corners) in an orthogonal polyline. */
|
|
598
|
+
function countCorners(poly) {
|
|
599
|
+
let corners = 0;
|
|
600
|
+
for (let i = 1; i < poly.length - 1; i++) {
|
|
601
|
+
const a = poly[i - 1];
|
|
602
|
+
const b = poly[i];
|
|
603
|
+
const c = poly[i + 1];
|
|
604
|
+
if (a.x === b.x !== (b.x === c.x)) corners++;
|
|
605
|
+
}
|
|
606
|
+
return corners;
|
|
607
|
+
}
|
|
608
|
+
/** Manhattan length of a polyline (sum of absolute x and y deltas). */
|
|
609
|
+
function polyLength(poly) {
|
|
610
|
+
let len = 0;
|
|
611
|
+
for (let i = 0; i < poly.length - 1; i++) len += Math.abs(poly[i + 1].x - poly[i].x) + Math.abs(poly[i + 1].y - poly[i].y);
|
|
612
|
+
return len;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Find the best (x, y) position to place an edge label adjacent to its
|
|
616
|
+
* polyline. Returns null if no collision-free position exists.
|
|
617
|
+
*
|
|
618
|
+
* @param poly - The orthogonalized polyline for the edge.
|
|
619
|
+
* @param label - The label text to place.
|
|
620
|
+
* @param grid - The character grid (used for collision checks).
|
|
621
|
+
* @param srcY - Y coordinate of the source node (for adjacency penalty).
|
|
622
|
+
*/
|
|
623
|
+
function findLabelPlacement(poly, label, grid, srcY) {
|
|
624
|
+
const segments = polyToSegments(poly);
|
|
625
|
+
let best;
|
|
626
|
+
for (const seg of segments) {
|
|
627
|
+
const candidates = segmentLabelCandidates(seg, label.length);
|
|
628
|
+
for (const pos of candidates) {
|
|
629
|
+
if (labelCollides(grid, pos.x, pos.y, label)) continue;
|
|
630
|
+
const score = scoreLabelCandidate(pos, seg, segments, label, grid, srcY);
|
|
631
|
+
if (!best || score > best.score) best = {
|
|
632
|
+
x: pos.x,
|
|
633
|
+
y: pos.y,
|
|
634
|
+
score
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return best;
|
|
639
|
+
}
|
|
640
|
+
/** Convert a polyline into non-zero-length segments. */
|
|
641
|
+
function polyToSegments(poly) {
|
|
642
|
+
const segments = [];
|
|
643
|
+
for (let i = 0; i < poly.length - 1; i++) {
|
|
644
|
+
const seg = segment(poly[i], poly[i + 1]);
|
|
645
|
+
if (manhattanLength(seg) > 0) segments.push(seg);
|
|
646
|
+
}
|
|
647
|
+
return segments;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Generate all candidate (x, y) positions for placing a label adjacent
|
|
651
|
+
* to a single segment. Positions are perpendicular to the segment:
|
|
652
|
+
*
|
|
653
|
+
* - Vertical segments: left and right, at every y along the segment.
|
|
654
|
+
* - Horizontal segments: above and below, at every x where the label fits.
|
|
655
|
+
*/
|
|
656
|
+
function segmentLabelCandidates(seg, labelLen) {
|
|
657
|
+
const candidates = [];
|
|
658
|
+
if (isVertical(seg)) {
|
|
659
|
+
const minY = Math.min(seg.from.y, seg.to.y);
|
|
660
|
+
const maxY = Math.max(seg.from.y, seg.to.y);
|
|
661
|
+
for (const x of [seg.from.x + 2, seg.from.x - labelLen - 1]) for (let y = minY; y <= maxY; y++) candidates.push({
|
|
662
|
+
x,
|
|
663
|
+
y
|
|
664
|
+
});
|
|
665
|
+
} else {
|
|
666
|
+
const minX = Math.min(seg.from.x, seg.to.x);
|
|
667
|
+
const maxX = Math.max(seg.from.x, seg.to.x);
|
|
668
|
+
for (const dy of [-1, 1]) {
|
|
669
|
+
const y = seg.from.y + dy;
|
|
670
|
+
for (let x = minX; x <= maxX - labelLen + 1; x++) candidates.push({
|
|
671
|
+
x,
|
|
672
|
+
y
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return candidates;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Score a candidate label position. Higher is better.
|
|
680
|
+
*
|
|
681
|
+
* Combines: segment length, surrounding whitespace, distance from
|
|
682
|
+
* segment midpoint, source-node proximity penalty, and segment-position
|
|
683
|
+
* bonus (horizontal/later segments preferred when the edge has bends).
|
|
684
|
+
*
|
|
685
|
+
* @param pos - Candidate position (top-left corner of the label text).
|
|
686
|
+
* @param seg - The segment this candidate is adjacent to.
|
|
687
|
+
* @param allSegments - All segments of the edge polyline (for segment-position bonus).
|
|
688
|
+
* @param label - The label text (used for width and whitespace probing).
|
|
689
|
+
* @param grid - The character grid (used for whitespace checks).
|
|
690
|
+
* @param srcY - Y coordinate of the edge's source node (penalizes labels
|
|
691
|
+
* that would appear to belong to the node rather than the edge).
|
|
692
|
+
*/
|
|
693
|
+
function scoreLabelCandidate(pos, seg, allSegments, label, grid, srcY) {
|
|
694
|
+
const len = manhattanLength(seg);
|
|
695
|
+
const midX = Math.round((seg.from.x + seg.to.x) / 2);
|
|
696
|
+
const midY = Math.round((seg.from.y + seg.to.y) / 2);
|
|
697
|
+
let score = len;
|
|
698
|
+
for (let dy = 1; dy <= 2; dy++) {
|
|
699
|
+
if (!rowHasContent(grid, pos.x, pos.y - dy, label.length)) score += 3;
|
|
700
|
+
if (!rowHasContent(grid, pos.x, pos.y + dy, label.length)) score += 3;
|
|
701
|
+
}
|
|
702
|
+
const labelCenterX = pos.x + Math.floor(label.length / 2);
|
|
703
|
+
score -= (Math.abs(labelCenterX - midX) + Math.abs(pos.y - midY)) * 2;
|
|
704
|
+
const labelCenterY = pos.y + Math.floor(label.length / 2);
|
|
705
|
+
score -= (Math.abs(labelCenterY - midY) + Math.abs(pos.x - midX)) * 2;
|
|
706
|
+
if (isVertical(seg) && pos.x > seg.from.x) score += 10;
|
|
707
|
+
if (srcY !== void 0 && Math.abs(pos.y - srcY) <= 1) score -= 20;
|
|
708
|
+
if (allSegments.some((s) => !isVertical(s))) {
|
|
709
|
+
if (!isVertical(seg)) score += 15;
|
|
710
|
+
const segIndex = allSegments.indexOf(seg);
|
|
711
|
+
score += segIndex / allSegments.length * 5;
|
|
712
|
+
}
|
|
713
|
+
return score;
|
|
714
|
+
}
|
|
715
|
+
/** True if any cell in the horizontal span [x, x+width) at row y has content. */
|
|
716
|
+
function rowHasContent(grid, x, y, width) {
|
|
717
|
+
for (let i = 0; i < width; i++) if (grid.hasLabel(x + i, y) || grid.hasConnection(x + i, y)) return true;
|
|
718
|
+
return false;
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Check if placing `text` at (x, y) would collide with existing content.
|
|
722
|
+
* Checks one cell of padding on each side to keep labels visually separated.
|
|
723
|
+
*/
|
|
724
|
+
function labelCollides(grid, x, y, text) {
|
|
725
|
+
for (let i = -1; i <= text.length; i++) {
|
|
726
|
+
const cx = x + i;
|
|
727
|
+
if (grid.hasLabel(cx, y)) return true;
|
|
728
|
+
if (i >= 0 && i < text.length && grid.hasConnection(cx, y)) return true;
|
|
729
|
+
}
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Resolve dagre's polyline into the best orthogonal variant and find the
|
|
734
|
+
* optimal label position in a single pass.
|
|
735
|
+
*
|
|
736
|
+
* Enumerates all 2^N diagonal resolutions, scores each by:
|
|
737
|
+
* - `corners * 10` — fewer corners preferred
|
|
738
|
+
* - `+ manhattan length` — shorter paths preferred
|
|
739
|
+
* - `+ 100` penalty if the label couldn't be placed
|
|
740
|
+
*
|
|
741
|
+
* For edges with no diagonals, the polyline is used as-is.
|
|
742
|
+
*/
|
|
743
|
+
function selectBestVariant(src, dagrePoints, tgt, label, grid) {
|
|
744
|
+
const rawPoints = prepareRawPoints(src, dagrePoints, tgt);
|
|
745
|
+
const diagCount = countDiagonals(rawPoints);
|
|
746
|
+
if (diagCount === 0) {
|
|
747
|
+
const poly = buildVariant(rawPoints, []);
|
|
748
|
+
return {
|
|
749
|
+
poly,
|
|
750
|
+
labelPos: label ? findLabelPlacement(poly, label, grid, src.y) : void 0
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
const numVariants = 1 << diagCount;
|
|
754
|
+
let bestPoly = null;
|
|
755
|
+
let bestLabel;
|
|
756
|
+
let bestScore = Number.POSITIVE_INFINITY;
|
|
757
|
+
for (let bits = 0; bits < numVariants; bits++) {
|
|
758
|
+
const poly = buildVariant(rawPoints, bitsToBends(bits, diagCount));
|
|
759
|
+
const corners = countCorners(poly);
|
|
760
|
+
const len = polyLength(poly);
|
|
761
|
+
const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : void 0;
|
|
762
|
+
const labelPenalty = label && !labelPos ? 100 : 0;
|
|
763
|
+
const score = corners * 10 + len + labelPenalty;
|
|
764
|
+
if (score < bestScore) {
|
|
765
|
+
bestScore = score;
|
|
766
|
+
bestPoly = poly;
|
|
767
|
+
bestLabel = labelPos;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return {
|
|
771
|
+
poly: bestPoly ?? buildVariant(rawPoints, bitsToBends(0, diagCount)),
|
|
772
|
+
labelPos: bestLabel
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Extract the subgraph covering the union of multiple paths.
|
|
777
|
+
*
|
|
778
|
+
* Each path is an ordered list of node ids (root → target). The result
|
|
779
|
+
* contains every node on any path plus every forward edge between
|
|
780
|
+
* consecutive nodes on any path. Detached nodes are always included.
|
|
781
|
+
*
|
|
782
|
+
* When all paths overlap (the common case), the result is identical to
|
|
783
|
+
* a single-path extract. When paths diverge (e.g. DB marker on a
|
|
784
|
+
* different branch than the contract), the result naturally includes the
|
|
785
|
+
* fork and both branches — exactly the minimal information needed.
|
|
786
|
+
*/
|
|
787
|
+
function extractRelevantSubgraph(graph, paths) {
|
|
788
|
+
const nodeSet = /* @__PURE__ */ new Set();
|
|
789
|
+
const edgePairs = /* @__PURE__ */ new Set();
|
|
790
|
+
for (const path of paths) for (let i = 0; i < path.length; i++) {
|
|
791
|
+
nodeSet.add(path[i]);
|
|
792
|
+
if (i > 0) edgePairs.add(`${path[i - 1]}\0${path[i]}`);
|
|
793
|
+
}
|
|
794
|
+
const dashedEdges = graph.edges.filter((e) => e.style === "dashed");
|
|
795
|
+
for (const e of dashedEdges) {
|
|
796
|
+
nodeSet.add(e.from);
|
|
797
|
+
nodeSet.add(e.to);
|
|
798
|
+
}
|
|
799
|
+
return new RenderGraph(graph.nodes.filter((n) => nodeSet.has(n.id)), graph.edges.filter((e) => edgePairs.has(`${e.from}\0${e.to}`) || e.style === "dashed"));
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Truncate a graph to the last `limit` spine edges from the spine target.
|
|
803
|
+
* The window expands to include any node carrying a db or contract marker
|
|
804
|
+
* so those are never truncated away.
|
|
805
|
+
*
|
|
806
|
+
* For the full graph: keeps all branches that fork from the visible spine window.
|
|
807
|
+
* For the spine view: caller should call extractSubgraph first, then truncate.
|
|
808
|
+
*/
|
|
809
|
+
function truncateGraph(graph, spine, limit) {
|
|
810
|
+
if (spine.length <= 1 || limit >= spine.length - 1) return {
|
|
811
|
+
graph,
|
|
812
|
+
elidedCount: 0,
|
|
813
|
+
spine
|
|
814
|
+
};
|
|
815
|
+
let earliestMarkerIdx = spine.length;
|
|
816
|
+
for (let i = 0; i < spine.length; i++) if (graph.nodeById.get(spine[i])?.markers?.some((m) => m.kind === "db" || m.kind === "contract")) {
|
|
817
|
+
earliestMarkerIdx = i;
|
|
818
|
+
break;
|
|
819
|
+
}
|
|
820
|
+
const markerDistance = spine.length - 1 - earliestMarkerIdx;
|
|
821
|
+
const effectiveEdges = Math.max(limit, markerDistance);
|
|
822
|
+
if (effectiveEdges >= spine.length - 1) return {
|
|
823
|
+
graph,
|
|
824
|
+
elidedCount: 0,
|
|
825
|
+
spine
|
|
826
|
+
};
|
|
827
|
+
const keepFromIdx = spine.length - 1 - effectiveEdges;
|
|
828
|
+
const truncatedSpine = spine.slice(keepFromIdx);
|
|
829
|
+
const visibleSpineSet = new Set(truncatedSpine);
|
|
830
|
+
const reachable = new Set(visibleSpineSet);
|
|
831
|
+
const queue = [...truncatedSpine];
|
|
832
|
+
while (queue.length > 0) {
|
|
833
|
+
const current = queue.shift();
|
|
834
|
+
for (const edge of graph.outgoing(current)) if (!reachable.has(edge.to)) {
|
|
835
|
+
reachable.add(edge.to);
|
|
836
|
+
queue.push(edge.to);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
const truncatedNodes = graph.nodes.filter((n) => reachable.has(n.id));
|
|
840
|
+
const truncatedEdges = graph.edges.filter((e) => reachable.has(e.from) && reachable.has(e.to));
|
|
841
|
+
const elidedCount = spine.length - 1 - effectiveEdges;
|
|
842
|
+
return {
|
|
843
|
+
graph: new RenderGraph(truncatedNodes, truncatedEdges),
|
|
844
|
+
elidedCount,
|
|
845
|
+
spine: truncatedSpine
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* After truncation the original root may not be in the visible graph.
|
|
850
|
+
* Find the first node with no incoming edges as a fallback root.
|
|
851
|
+
*/
|
|
852
|
+
function findVisibleRoot(graph, layoutNodes) {
|
|
853
|
+
return layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id ?? "∅";
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* The main rendering pipeline: dagre layout → edge stamping → label
|
|
857
|
+
* placement → arrowheads → nodes → elided indicator → detached nodes.
|
|
858
|
+
*
|
|
859
|
+
* Called by {@link render} after optional truncation. Receives nodes/edges
|
|
860
|
+
* and produces the final multi-line string.
|
|
861
|
+
*
|
|
862
|
+
* @param graph - The graph to render (may include detached nodes, which are
|
|
863
|
+
* rendered below the main graph rather than laid out by dagre).
|
|
864
|
+
* @param options - Render options (rootId, spineTarget, colorize).
|
|
865
|
+
* @param elidedCount - If > 0, a `┊ (N earlier migrations)` indicator
|
|
866
|
+
* is stamped above the visible root node.
|
|
867
|
+
*/
|
|
868
|
+
function layoutAndRender(graph, options, elidedCount = 0) {
|
|
869
|
+
const colors = buildColors(options.colorize ?? true);
|
|
870
|
+
const layoutNodes = graph.nodes;
|
|
871
|
+
const layoutNodeIds = new Set(layoutNodes.map((n) => n.id));
|
|
872
|
+
const requestedRoot = options.rootId ?? layoutNodes[0]?.id ?? "∅";
|
|
873
|
+
const spineEdgeKeys = findSpineEdges(graph, layoutNodeIds.has(requestedRoot) ? requestedRoot : findVisibleRoot(graph, layoutNodes), options.spineTarget);
|
|
874
|
+
const g = new dagre.graphlib.Graph({ multigraph: true });
|
|
875
|
+
g.setGraph({
|
|
876
|
+
rankdir: "TB",
|
|
877
|
+
ranksep: 4,
|
|
878
|
+
nodesep: 6,
|
|
879
|
+
marginx: 2,
|
|
880
|
+
marginy: 1,
|
|
881
|
+
...options.dagreOptions
|
|
882
|
+
});
|
|
883
|
+
g.setDefaultEdgeLabel(() => ({}));
|
|
884
|
+
for (const node of layoutNodes) {
|
|
885
|
+
const tagWidth = inlineTagsWidth(buildInlineTags(node.markers ?? [], colors));
|
|
886
|
+
g.setNode(node.id, {
|
|
887
|
+
width: node.id.length + 6 + tagWidth,
|
|
888
|
+
height: 1
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
const edgeNames = [];
|
|
892
|
+
for (let i = 0; i < graph.edges.length; i++) {
|
|
893
|
+
const edge = graph.edges[i];
|
|
894
|
+
const name = `e${i}`;
|
|
895
|
+
edgeNames.push(name);
|
|
896
|
+
g.setEdge(edge.from, edge.to, { label: edge.label ?? "" }, name);
|
|
897
|
+
}
|
|
898
|
+
dagre.layout(g);
|
|
899
|
+
const nodePos = /* @__PURE__ */ new Map();
|
|
900
|
+
for (const id of g.nodes()) {
|
|
901
|
+
const n = g.node(id);
|
|
902
|
+
nodePos.set(id, {
|
|
903
|
+
x: Math.round(n.x),
|
|
904
|
+
y: Math.round(n.y)
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
const grid = new CharGrid();
|
|
908
|
+
for (const node of layoutNodes) {
|
|
909
|
+
const pos = nodePos.get(node.id);
|
|
910
|
+
/* v8 ignore next -- @preserve */
|
|
911
|
+
if (!pos) continue;
|
|
912
|
+
const tagWidth = inlineTagsWidth(buildInlineTags(node.markers ?? [], colors));
|
|
913
|
+
grid.reserveArea(pos.x - 1, pos.y, node.id.length + 4 + tagWidth);
|
|
914
|
+
}
|
|
915
|
+
const edgeEntries = [];
|
|
916
|
+
for (let i = 0; i < graph.edges.length; i++) {
|
|
917
|
+
const edge = graph.edges[i];
|
|
918
|
+
const name = edgeNames[i];
|
|
919
|
+
if (!name || !nodePos.has(edge.from) || !nodePos.has(edge.to)) continue;
|
|
920
|
+
const src = nodePos.get(edge.from);
|
|
921
|
+
const tgt = nodePos.get(edge.to);
|
|
922
|
+
const dagrePoints = g.edge({
|
|
923
|
+
v: edge.from,
|
|
924
|
+
w: edge.to,
|
|
925
|
+
name
|
|
926
|
+
})?.points ?? [];
|
|
927
|
+
const isBackward = tgt.y < src.y;
|
|
928
|
+
const isSpine = spineEdgeKeys.has(`${edge.from}→${edge.to}`);
|
|
929
|
+
const role = isBackward ? "backward" : isSpine ? "spine" : "branch";
|
|
930
|
+
const edgeColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.branch);
|
|
931
|
+
const priority = role === "backward" ? PRIORITY.backward : role === "spine" ? PRIORITY.spine : PRIORITY.branch;
|
|
932
|
+
edgeEntries.push({
|
|
933
|
+
idx: i,
|
|
934
|
+
edge,
|
|
935
|
+
dagrePoints,
|
|
936
|
+
src,
|
|
937
|
+
tgt,
|
|
938
|
+
role,
|
|
939
|
+
edgeColor,
|
|
940
|
+
priority
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
const drawnEdges = [];
|
|
944
|
+
for (const entry of edgeEntries) {
|
|
945
|
+
const { edge, dagrePoints, src, tgt, edgeColor, priority } = entry;
|
|
946
|
+
const { poly } = selectBestVariant(src, dagrePoints, tgt, edge.label, grid);
|
|
947
|
+
const dashedBit = edge.style === "dashed" ? DIR.dashed : 0;
|
|
948
|
+
for (let j = 0; j < poly.length - 1; j++) {
|
|
949
|
+
const a = poly[j];
|
|
950
|
+
const b = poly[j + 1];
|
|
951
|
+
if (a.y === b.y) grid.markHorizontal(a.y, a.x, b.x, edgeColor, priority, dashedBit);
|
|
952
|
+
else if (a.x === b.x) grid.markVertical(a.x, a.y, b.y, edgeColor, priority, dashedBit);
|
|
953
|
+
}
|
|
954
|
+
drawnEdges.push({
|
|
955
|
+
edge,
|
|
956
|
+
poly,
|
|
957
|
+
role: entry.role,
|
|
958
|
+
srcY: src.y
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
const labelOrder = [...drawnEdges].map((de, i) => ({
|
|
962
|
+
...de,
|
|
963
|
+
i
|
|
964
|
+
})).filter((de) => de.edge.label).sort((a, b) => (b.edge.label?.length ?? 0) - (a.edge.label?.length ?? 0));
|
|
965
|
+
for (const { edge, poly, role, srcY } of labelOrder) {
|
|
966
|
+
/* v8 ignore next -- @preserve */
|
|
967
|
+
if (!edge.label) continue;
|
|
968
|
+
const labelPos = findLabelPlacement(poly, edge.label, grid, srcY);
|
|
969
|
+
if (labelPos) {
|
|
970
|
+
const labelColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.label);
|
|
971
|
+
grid.stampText(labelPos.x, labelPos.y, edge.label, labelColor);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
for (const { edge, poly, role } of drawnEdges) {
|
|
975
|
+
/* v8 ignore next -- @preserve */
|
|
976
|
+
if (poly.length < 2) continue;
|
|
977
|
+
const last = poly[poly.length - 1];
|
|
978
|
+
const prev = poly[poly.length - 2];
|
|
979
|
+
const edgeColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.branch);
|
|
980
|
+
let ax;
|
|
981
|
+
let ay;
|
|
982
|
+
let arrow;
|
|
983
|
+
if (prev.x === last.x) if (last.y > prev.y) {
|
|
984
|
+
ax = last.x;
|
|
985
|
+
ay = last.y - 1;
|
|
986
|
+
arrow = ARROW.down;
|
|
987
|
+
} else {
|
|
988
|
+
ax = last.x;
|
|
989
|
+
ay = last.y + 1;
|
|
990
|
+
arrow = ARROW.up;
|
|
991
|
+
}
|
|
992
|
+
else if (last.x > prev.x) {
|
|
993
|
+
ax = last.x - 1;
|
|
994
|
+
ay = last.y;
|
|
995
|
+
arrow = ARROW.right;
|
|
996
|
+
} else {
|
|
997
|
+
ax = last.x + 1;
|
|
998
|
+
ay = last.y;
|
|
999
|
+
arrow = ARROW.left;
|
|
1000
|
+
}
|
|
1001
|
+
if (ax !== void 0 && ay !== void 0 && arrow && !grid.hasText(ax, ay)) grid.stampText(ax, ay, arrow, edgeColor);
|
|
1002
|
+
}
|
|
1003
|
+
const spineNodeIds = /* @__PURE__ */ new Set();
|
|
1004
|
+
for (const key of spineEdgeKeys) {
|
|
1005
|
+
const [from, to] = key.split("→");
|
|
1006
|
+
if (from) spineNodeIds.add(from);
|
|
1007
|
+
if (to) spineNodeIds.add(to);
|
|
1008
|
+
}
|
|
1009
|
+
for (const node of layoutNodes) {
|
|
1010
|
+
const pos = nodePos.get(node.id);
|
|
1011
|
+
if (!pos) continue;
|
|
1012
|
+
const isSpineNode = spineNodeIds.has(node.id);
|
|
1013
|
+
const nodeColor = isSpineNode ? colors.spine : colors.branch;
|
|
1014
|
+
grid.stampText(pos.x, pos.y, "○", nodeColor);
|
|
1015
|
+
grid.stampText(pos.x + 1, pos.y, " ");
|
|
1016
|
+
const hasMarkers = node.markers && node.markers.length > 0;
|
|
1017
|
+
grid.stampText(pos.x + 2, pos.y, node.id, isSpineNode || hasMarkers ? bold : dim);
|
|
1018
|
+
const tags = buildInlineTags(node.markers ?? [], colors);
|
|
1019
|
+
if (tags.length > 0) {
|
|
1020
|
+
let bx = pos.x + 2 + node.id.length;
|
|
1021
|
+
for (const tag of tags) {
|
|
1022
|
+
grid.stampText(bx, pos.y, " ");
|
|
1023
|
+
bx++;
|
|
1024
|
+
grid.stampText(bx, pos.y, tag.text, tag.color);
|
|
1025
|
+
bx += tag.text.length;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (elidedCount > 0) {
|
|
1030
|
+
const topNodeId = layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id;
|
|
1031
|
+
const rootPos = topNodeId ? nodePos.get(topNodeId) : void 0;
|
|
1032
|
+
if (rootPos) {
|
|
1033
|
+
const label = elidedCount === 1 ? "1 earlier migration" : `${elidedCount} earlier migrations`;
|
|
1034
|
+
const topY = rootPos.y - 3;
|
|
1035
|
+
grid.stampText(rootPos.x, topY, "┊", colors.label);
|
|
1036
|
+
grid.stampText(rootPos.x, topY + 1, "┊", colors.label);
|
|
1037
|
+
grid.stampText(rootPos.x + 2, topY + 1, `(${label})`, colors.label);
|
|
1038
|
+
grid.stampText(rootPos.x, topY + 2, "┊", colors.label);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return grid.render();
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* BFS to find the ordered node path from `rootId` to `targetId`.
|
|
1045
|
+
* Used for truncation — the spine path determines which edges to keep.
|
|
1046
|
+
*
|
|
1047
|
+
* Returns `[rootId]` if no path exists.
|
|
1048
|
+
*/
|
|
1049
|
+
function findSpinePath(graph, rootId, targetId) {
|
|
1050
|
+
const visited = new Set([rootId]);
|
|
1051
|
+
const parent = /* @__PURE__ */ new Map();
|
|
1052
|
+
const queue = [rootId];
|
|
1053
|
+
while (queue.length > 0) {
|
|
1054
|
+
const current = queue.shift();
|
|
1055
|
+
if (current === targetId) {
|
|
1056
|
+
const path = [];
|
|
1057
|
+
let node = targetId;
|
|
1058
|
+
while (node !== rootId) {
|
|
1059
|
+
path.unshift(node);
|
|
1060
|
+
node = parent.get(node);
|
|
1061
|
+
}
|
|
1062
|
+
path.unshift(rootId);
|
|
1063
|
+
return path;
|
|
1064
|
+
}
|
|
1065
|
+
for (const edge of graph.outgoing(current)) if (!visited.has(edge.to)) {
|
|
1066
|
+
visited.add(edge.to);
|
|
1067
|
+
parent.set(edge.to, current);
|
|
1068
|
+
queue.push(edge.to);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return [rootId];
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Render a graph with optional truncation.
|
|
1075
|
+
*
|
|
1076
|
+
* The caller decides what to pass in: the full graph for `--graph`, or a
|
|
1077
|
+
* subgraph extracted via {@link extractRelevantSubgraph} for the default view.
|
|
1078
|
+
*/
|
|
1079
|
+
function render(graph, options) {
|
|
1080
|
+
if (options.limit !== void 0) {
|
|
1081
|
+
const { graph: truncated, elidedCount } = truncateGraph(graph, findSpinePath(graph, options.rootId ?? graph.nodes[0]?.id ?? "∅", options.spineTarget), options.limit);
|
|
1082
|
+
return layoutAndRender(truncated, options, elidedCount);
|
|
1083
|
+
}
|
|
1084
|
+
return layoutAndRender(graph, options);
|
|
1085
|
+
}
|
|
1086
|
+
const graphRenderer = { render };
|
|
1087
|
+
/** True if the graph is a single linear chain (no branching), ignoring dashed edges. */
|
|
1088
|
+
function isLinearGraph(graph) {
|
|
1089
|
+
for (const node of graph.nodes) if (graph.outgoing(node.id).filter((e) => e.style !== "dashed").length > 1) return false;
|
|
1090
|
+
return true;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region src/commands/migration-status.ts
|
|
1095
|
+
function summarizeOps(ops) {
|
|
1096
|
+
if (ops.length === 0) return {
|
|
1097
|
+
summary: "0 ops",
|
|
1098
|
+
hasDestructive: false
|
|
1099
|
+
};
|
|
1100
|
+
const classes = /* @__PURE__ */ new Map();
|
|
1101
|
+
for (const op of ops) classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);
|
|
1102
|
+
const hasDestructive = classes.has("destructive");
|
|
1103
|
+
const count = ops.length;
|
|
1104
|
+
const noun = count === 1 ? "op" : "ops";
|
|
1105
|
+
if (classes.size === 1) return {
|
|
1106
|
+
summary: `${count} ${noun} (all ${[...classes.keys()][0]})`,
|
|
1107
|
+
hasDestructive
|
|
1108
|
+
};
|
|
1109
|
+
const destructiveCount = classes.get("destructive");
|
|
1110
|
+
if (destructiveCount) return {
|
|
1111
|
+
summary: `${count} ${noun} (${destructiveCount} destructive)`,
|
|
1112
|
+
hasDestructive
|
|
1113
|
+
};
|
|
1114
|
+
return {
|
|
1115
|
+
summary: `${count} ${noun} (${[...classes.entries()].map(([cls, n]) => `${n} ${cls}`).join(", ")})`,
|
|
1116
|
+
hasDestructive
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Derive per-edge status across the full graph using path analysis.
|
|
1121
|
+
*
|
|
1122
|
+
* - **applied**: edge is on the path from root to the DB marker
|
|
1123
|
+
* - **pending**: edge is on the path from the DB marker to the target
|
|
1124
|
+
* (and the marker is reachable from root, i.e. it's on the same branch)
|
|
1125
|
+
* - **unreachable**: edge is on the path from root to the target but the DB
|
|
1126
|
+
* marker is on a different branch — `apply` can't reach these edges
|
|
1127
|
+
* without the DB first moving to this branch
|
|
1128
|
+
*
|
|
1129
|
+
* Returns statuses only for edges that have a known status (skips offline
|
|
1130
|
+
* and edges not on any relevant path).
|
|
1131
|
+
*
|
|
1132
|
+
* @internal Exported for testing only.
|
|
1133
|
+
*/
|
|
1134
|
+
function deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode) {
|
|
1135
|
+
if (mode === "offline") return [];
|
|
1136
|
+
const edgeKey = (e) => `${e.from}\0${e.to}`;
|
|
1137
|
+
const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;
|
|
1138
|
+
const appliedPath = markerHash !== void 0 ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;
|
|
1139
|
+
const pendingPath = findPath(graph, effectiveMarker, targetHash);
|
|
1140
|
+
const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
|
|
1141
|
+
const statuses = [];
|
|
1142
|
+
const assignedKeys = /* @__PURE__ */ new Set();
|
|
1143
|
+
if (appliedPath) for (const e of appliedPath) {
|
|
1144
|
+
assignedKeys.add(edgeKey(e));
|
|
1145
|
+
statuses.push({
|
|
1146
|
+
dirName: e.dirName,
|
|
1147
|
+
status: "applied"
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
if (pendingPath) for (const e of pendingPath) {
|
|
1151
|
+
assignedKeys.add(edgeKey(e));
|
|
1152
|
+
statuses.push({
|
|
1153
|
+
dirName: e.dirName,
|
|
1154
|
+
status: "pending"
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
if (contractHash !== EMPTY_CONTRACT_HASH && contractHash !== targetHash && graph.nodes.has(contractHash)) {
|
|
1158
|
+
const beyondTarget = findPath(graph, targetHash, contractHash);
|
|
1159
|
+
if (beyondTarget) {
|
|
1160
|
+
for (const e of beyondTarget) if (!assignedKeys.has(edgeKey(e))) {
|
|
1161
|
+
assignedKeys.add(edgeKey(e));
|
|
1162
|
+
statuses.push({
|
|
1163
|
+
dirName: e.dirName,
|
|
1164
|
+
status: "pending"
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
if (targetPath) {
|
|
1170
|
+
for (const e of targetPath) if (!assignedKeys.has(edgeKey(e))) statuses.push({
|
|
1171
|
+
dirName: e.dirName,
|
|
1172
|
+
status: "unreachable"
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
return statuses;
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* @param mode — 'online' if we connected to the database, 'offline' otherwise
|
|
1179
|
+
* @param markerHash — the marker hash from the database, or undefined if no marker row / offline
|
|
1180
|
+
*/
|
|
1181
|
+
function buildMigrationEntries(chain, packages, mode, markerHash, edgeStatuses) {
|
|
1182
|
+
const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));
|
|
1183
|
+
const statusByDirName = edgeStatuses ? new Map(edgeStatuses.map((e) => [e.dirName, e.status])) : void 0;
|
|
1184
|
+
const markerInChain = markerHash === void 0 || chain.some((e) => e.to === markerHash);
|
|
1185
|
+
const entries = [];
|
|
1186
|
+
let reachedMarker = mode === "online" && markerHash === void 0;
|
|
1187
|
+
for (const migration of chain) {
|
|
1188
|
+
const ops = pkgByDirName.get(migration.dirName)?.ops ?? [];
|
|
1189
|
+
const { summary, hasDestructive } = summarizeOps(ops);
|
|
1190
|
+
let status;
|
|
1191
|
+
const edgeStatus = statusByDirName?.get(migration.dirName);
|
|
1192
|
+
if (edgeStatus) status = edgeStatus;
|
|
1193
|
+
else if (mode === "offline" || !markerInChain) status = "unknown";
|
|
1194
|
+
else if (reachedMarker) status = "pending";
|
|
1195
|
+
else status = "applied";
|
|
1196
|
+
entries.push({
|
|
1197
|
+
dirName: migration.dirName,
|
|
1198
|
+
from: migration.from,
|
|
1199
|
+
to: migration.to,
|
|
1200
|
+
migrationId: migration.migrationId,
|
|
1201
|
+
operationCount: ops.length,
|
|
1202
|
+
operationSummary: summary,
|
|
1203
|
+
hasDestructive,
|
|
1204
|
+
status
|
|
1205
|
+
});
|
|
1206
|
+
if (!reachedMarker && migration.to === markerHash) reachedMarker = true;
|
|
1207
|
+
}
|
|
1208
|
+
return entries;
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Resolve the migration chain to display in status output.
|
|
1212
|
+
*
|
|
1213
|
+
* When offline or the marker is at EMPTY, the chain is simply the shortest
|
|
1214
|
+
* path from EMPTY to the target — all structural paths are equivalent per
|
|
1215
|
+
* the spec, so the deterministic shortest path is the canonical display.
|
|
1216
|
+
*
|
|
1217
|
+
* When online with a non-empty marker, the chain routes *through* the marker:
|
|
1218
|
+
* EMPTY→marker (applied history) + marker→target (pending edges). This ensures
|
|
1219
|
+
* the displayed chain includes the marker node so applied/pending status is
|
|
1220
|
+
* correct. Without this, BFS from EMPTY to target could pick a shortest path
|
|
1221
|
+
* that bypasses the marker entirely (e.g. in a diamond graph), causing the
|
|
1222
|
+
* marker to appear "diverged" when it isn't.
|
|
1223
|
+
*/
|
|
1224
|
+
function resolveDisplayChain(graph, targetHash, markerHash) {
|
|
1225
|
+
if (markerHash === void 0) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
|
|
1226
|
+
const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);
|
|
1227
|
+
if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
|
|
1228
|
+
if (markerHash === targetHash) return toMarker;
|
|
1229
|
+
const fromMarker = findPath(graph, markerHash, targetHash);
|
|
1230
|
+
if (fromMarker) return [...toMarker, ...fromMarker];
|
|
1231
|
+
const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
|
|
1232
|
+
if (!toTarget) return null;
|
|
1233
|
+
const targetToMarker = findPath(graph, targetHash, markerHash);
|
|
1234
|
+
if (targetToMarker) return [...toTarget, ...targetToMarker];
|
|
1235
|
+
return toTarget;
|
|
1236
|
+
}
|
|
1237
|
+
const DEFAULT_LIMIT = 10;
|
|
1238
|
+
function determineLimit(opts) {
|
|
1239
|
+
if (opts.all) return;
|
|
1240
|
+
if (!opts.limit) return DEFAULT_LIMIT;
|
|
1241
|
+
const parsed = Number.parseInt(opts.limit, 10);
|
|
1242
|
+
if (Number.isNaN(parsed)) return DEFAULT_LIMIT;
|
|
1243
|
+
return parsed;
|
|
1244
|
+
}
|
|
1245
|
+
async function executeMigrationStatusCommand(options, flags, ui) {
|
|
1246
|
+
const config = await loadConfig(options.config);
|
|
1247
|
+
const { configPath, migrationsDir, migrationsRelative, refsPath } = resolveMigrationPaths(options.config, config);
|
|
1248
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
1249
|
+
const hasDriver = !!config.driver;
|
|
1250
|
+
let activeRefName;
|
|
1251
|
+
let activeRefHash;
|
|
1252
|
+
let allRefs = {};
|
|
1253
|
+
try {
|
|
1254
|
+
allRefs = await readRefs(refsPath);
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
if (MigrationToolsError.is(error)) return notOk(errorRuntime(error.message, {
|
|
1257
|
+
why: error.why,
|
|
1258
|
+
fix: error.fix,
|
|
1259
|
+
meta: { code: error.code }
|
|
1260
|
+
}));
|
|
1261
|
+
throw error;
|
|
1262
|
+
}
|
|
1263
|
+
if (options.ref) {
|
|
1264
|
+
activeRefName = options.ref;
|
|
1265
|
+
const refHash = allRefs[activeRefName];
|
|
1266
|
+
if (refHash) activeRefHash = refHash;
|
|
1267
|
+
else try {
|
|
1268
|
+
activeRefHash = resolveRef(allRefs, activeRefName);
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
if (MigrationToolsError.is(error)) return notOk(errorRuntime(error.message, {
|
|
1271
|
+
why: error.why,
|
|
1272
|
+
fix: error.fix,
|
|
1273
|
+
meta: { code: error.code }
|
|
1274
|
+
}));
|
|
1275
|
+
throw error;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
const statusRefs = Object.entries(allRefs).map(([name, hash]) => ({
|
|
1279
|
+
name,
|
|
1280
|
+
hash,
|
|
1281
|
+
active: name === activeRefName
|
|
1282
|
+
}));
|
|
1283
|
+
if (!flags.json && !flags.quiet) {
|
|
1284
|
+
const details = [{
|
|
1285
|
+
label: "config",
|
|
1286
|
+
value: configPath
|
|
1287
|
+
}, {
|
|
1288
|
+
label: "migrations",
|
|
1289
|
+
value: migrationsRelative
|
|
1290
|
+
}];
|
|
1291
|
+
if (dbConnection && hasDriver) details.push({
|
|
1292
|
+
label: "database",
|
|
1293
|
+
value: maskConnectionUrl(String(dbConnection))
|
|
1294
|
+
});
|
|
1295
|
+
if (activeRefName) details.push({
|
|
1296
|
+
label: "ref",
|
|
1297
|
+
value: activeRefName
|
|
1298
|
+
});
|
|
1299
|
+
const header = formatStyledHeader({
|
|
1300
|
+
command: "migration status",
|
|
1301
|
+
description: "Show migration history and applied status",
|
|
1302
|
+
details,
|
|
1303
|
+
flags
|
|
1304
|
+
});
|
|
1305
|
+
ui.stderr(header);
|
|
1306
|
+
}
|
|
1307
|
+
const diagnostics = [];
|
|
1308
|
+
let contractHash = EMPTY_CONTRACT_HASH;
|
|
1309
|
+
try {
|
|
1310
|
+
contractHash = (await readContractEnvelope(config)).storageHash;
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
diagnostics.push({
|
|
1313
|
+
code: "CONTRACT.UNREADABLE",
|
|
1314
|
+
severity: "warn",
|
|
1315
|
+
message: `Could not read contract: ${error instanceof Error ? error.message : "unknown error"}`,
|
|
1316
|
+
hints: ["Run 'prisma-next contract emit' to generate a valid contract"]
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
let attested;
|
|
1320
|
+
let drafts;
|
|
1321
|
+
let graph;
|
|
1322
|
+
try {
|
|
1323
|
+
({attested, drafts, graph} = await loadAllBundles(migrationsDir));
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
if (MigrationToolsError.is(error)) return notOk(errorRuntime(error.message, {
|
|
1326
|
+
why: error.why,
|
|
1327
|
+
fix: error.fix,
|
|
1328
|
+
meta: { code: error.code }
|
|
1329
|
+
}));
|
|
1330
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}` }));
|
|
1331
|
+
}
|
|
1332
|
+
if (drafts.length > 0) diagnostics.push({
|
|
1333
|
+
code: "MIGRATION.DRAFTS",
|
|
1334
|
+
severity: "warn",
|
|
1335
|
+
message: `${drafts.length} draft migration(s) found: ${drafts.map((d) => d.dirName).join(", ")}`,
|
|
1336
|
+
hints: ["Run 'prisma-next migration verify --dir <path>' to attest draft migrations before applying"]
|
|
1337
|
+
});
|
|
1338
|
+
if (attested.length === 0) {
|
|
1339
|
+
if (contractHash !== EMPTY_CONTRACT_HASH) diagnostics.push({
|
|
1340
|
+
code: "CONTRACT.AHEAD",
|
|
1341
|
+
severity: "warn",
|
|
1342
|
+
message: "No migration exists for the current contract",
|
|
1343
|
+
hints: ["Run 'prisma-next migration plan' to generate a migration for the current contract"]
|
|
1344
|
+
});
|
|
1345
|
+
return ok({
|
|
1346
|
+
ok: true,
|
|
1347
|
+
mode: dbConnection && hasDriver ? "online" : "offline",
|
|
1348
|
+
migrations: [],
|
|
1349
|
+
targetHash: EMPTY_CONTRACT_HASH,
|
|
1350
|
+
contractHash,
|
|
1351
|
+
summary: "No migrations found",
|
|
1352
|
+
diagnostics
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
let targetHash;
|
|
1356
|
+
if (activeRefHash) targetHash = activeRefHash;
|
|
1357
|
+
else if (graph.nodes.has(contractHash)) targetHash = contractHash;
|
|
1358
|
+
else {
|
|
1359
|
+
const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);
|
|
1360
|
+
if (leaves.length === 1) targetHash = leaves[0];
|
|
1361
|
+
else diagnostics.push({
|
|
1362
|
+
code: "MIGRATION.DIVERGED",
|
|
1363
|
+
severity: "warn",
|
|
1364
|
+
message: "There are multiple valid migration paths — you must select a target",
|
|
1365
|
+
hints: ["Use '--ref <name>' to select a target", "Or 'prisma-next migration ref set <name> <hash>' to create one"]
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
let markerHash;
|
|
1369
|
+
let mode = "offline";
|
|
1370
|
+
if (dbConnection && hasDriver) {
|
|
1371
|
+
const client = createControlClient({
|
|
1372
|
+
family: config.family,
|
|
1373
|
+
target: config.target,
|
|
1374
|
+
adapter: config.adapter,
|
|
1375
|
+
driver: config.driver,
|
|
1376
|
+
extensionPacks: config.extensionPacks ?? []
|
|
1377
|
+
});
|
|
1378
|
+
try {
|
|
1379
|
+
await client.connect(dbConnection);
|
|
1380
|
+
markerHash = (await client.readMarker())?.storageHash;
|
|
1381
|
+
mode = "online";
|
|
1382
|
+
} catch {
|
|
1383
|
+
if (!flags.json && !flags.quiet) ui.warn("Could not connect to database — showing offline status");
|
|
1384
|
+
} finally {
|
|
1385
|
+
await client.close();
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (mode === "online" && markerHash !== void 0 && !graph.nodes.has(markerHash) && markerHash !== contractHash) {
|
|
1389
|
+
const hints = [];
|
|
1390
|
+
if (graph.nodes.has(contractHash)) hints.push("Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract", "Run 'prisma-next db update' to push the current contract to the database", "Run 'prisma-next contract infer' to make your contract match the database", "Run 'prisma-next db verify' to inspect the database state");
|
|
1391
|
+
else hints.push("Run 'prisma-next db update' to push the current contract to the database", "Run 'prisma-next contract infer' to make your contract match the database", "Run 'prisma-next db verify' to inspect the database state");
|
|
1392
|
+
diagnostics.push({
|
|
1393
|
+
code: "MIGRATION.MARKER_NOT_IN_HISTORY",
|
|
1394
|
+
severity: "warn",
|
|
1395
|
+
message: "Database was updated outside the migration system (marker does not match any migration)",
|
|
1396
|
+
hints
|
|
1397
|
+
});
|
|
1398
|
+
return ok({
|
|
1399
|
+
ok: true,
|
|
1400
|
+
mode,
|
|
1401
|
+
migrations: [],
|
|
1402
|
+
targetHash: EMPTY_CONTRACT_HASH,
|
|
1403
|
+
contractHash,
|
|
1404
|
+
summary: `${attested.length} migration(s) on disk`,
|
|
1405
|
+
diagnostics,
|
|
1406
|
+
markerHash,
|
|
1407
|
+
...statusRefs.length > 0 ? { refs: statusRefs } : {}
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
if (mode === "online" && markerHash === void 0) diagnostics.push({
|
|
1411
|
+
code: "MIGRATION.NO_MARKER",
|
|
1412
|
+
severity: "warn",
|
|
1413
|
+
message: "Database has not been initialized — no migration marker found",
|
|
1414
|
+
hints: ["Run 'prisma-next migration apply' to apply pending migrations"]
|
|
1415
|
+
});
|
|
1416
|
+
if (targetHash && contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash) && markerHash !== contractHash) diagnostics.push({
|
|
1417
|
+
code: "CONTRACT.AHEAD",
|
|
1418
|
+
severity: "warn",
|
|
1419
|
+
message: "Contract has changed since the last migration was planned",
|
|
1420
|
+
hints: ["Run 'prisma-next migration plan' to generate a migration for the current contract"]
|
|
1421
|
+
});
|
|
1422
|
+
if (!targetHash) return ok({
|
|
1423
|
+
ok: true,
|
|
1424
|
+
mode,
|
|
1425
|
+
migrations: [],
|
|
1426
|
+
targetHash: EMPTY_CONTRACT_HASH,
|
|
1427
|
+
contractHash,
|
|
1428
|
+
summary: `${attested.length} migration(s) on disk`,
|
|
1429
|
+
diagnostics,
|
|
1430
|
+
...ifDefined("markerHash", markerHash),
|
|
1431
|
+
...statusRefs.length > 0 ? { refs: statusRefs } : {},
|
|
1432
|
+
graph,
|
|
1433
|
+
bundles: attested,
|
|
1434
|
+
diverged: true
|
|
1435
|
+
});
|
|
1436
|
+
const chain = resolveDisplayChain(graph, targetHash, markerHash);
|
|
1437
|
+
if (!chain) return notOk(errorRuntime("Cannot reconstruct migration history", {
|
|
1438
|
+
why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,
|
|
1439
|
+
fix: "The migration history may have gaps. Check the migrations directory for missing or corrupted packages."
|
|
1440
|
+
}));
|
|
1441
|
+
const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);
|
|
1442
|
+
const entries = buildMigrationEntries(chain, attested, mode, markerHash, edgeStatuses);
|
|
1443
|
+
const pendingCount = edgeStatuses.filter((e) => e.status === "pending").length;
|
|
1444
|
+
const appliedCount = edgeStatuses.filter((e) => e.status === "applied").length;
|
|
1445
|
+
let summary;
|
|
1446
|
+
if (mode === "online") if (markerHash !== void 0 && !graph.nodes.has(markerHash) && markerHash === contractHash) summary = `${attested.length} migration(s) on disk`;
|
|
1447
|
+
else if (activeRefHash && markerHash !== void 0) summary = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName);
|
|
1448
|
+
else if (pendingCount === 0) summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? "s" : ""} applied)`;
|
|
1449
|
+
else if (markerHash === void 0) summary = `${pendingCount} pending migration(s) — database has no marker`;
|
|
1450
|
+
else summary = `${pendingCount} pending migration(s) — run 'prisma-next migration apply' to apply`;
|
|
1451
|
+
else summary = `${entries.length} migration(s) on disk`;
|
|
1452
|
+
if (mode === "online") if (markerHash !== void 0 && !graph.nodes.has(markerHash) && markerHash === contractHash) diagnostics.push({
|
|
1453
|
+
code: "MIGRATION.MARKER_NOT_IN_HISTORY",
|
|
1454
|
+
severity: "warn",
|
|
1455
|
+
message: "Database matches the current contract but was updated directly (not via migration apply)",
|
|
1456
|
+
hints: ["Run 'prisma-next migration plan' to plan a migration to your current contract"]
|
|
1457
|
+
});
|
|
1458
|
+
else if (pendingCount > 0) diagnostics.push({
|
|
1459
|
+
code: "MIGRATION.DATABASE_BEHIND",
|
|
1460
|
+
severity: "info",
|
|
1461
|
+
message: `${pendingCount} migration(s) pending`,
|
|
1462
|
+
hints: ["Run 'prisma-next migration apply' to apply pending migrations"]
|
|
1463
|
+
});
|
|
1464
|
+
else diagnostics.push({
|
|
1465
|
+
code: "MIGRATION.UP_TO_DATE",
|
|
1466
|
+
severity: "info",
|
|
1467
|
+
message: "Database is up to date",
|
|
1468
|
+
hints: []
|
|
1469
|
+
});
|
|
1470
|
+
let pathDecision;
|
|
1471
|
+
if (mode === "online" && markerHash !== void 0) {
|
|
1472
|
+
const decision = findPathWithDecision(graph, markerHash, targetHash, activeRefName);
|
|
1473
|
+
if (decision) pathDecision = toPathDecisionResult(decision);
|
|
1474
|
+
}
|
|
1475
|
+
return ok({
|
|
1476
|
+
ok: true,
|
|
1477
|
+
mode,
|
|
1478
|
+
migrations: entries,
|
|
1479
|
+
targetHash,
|
|
1480
|
+
contractHash,
|
|
1481
|
+
summary,
|
|
1482
|
+
diagnostics,
|
|
1483
|
+
...ifDefined("markerHash", markerHash),
|
|
1484
|
+
...statusRefs.length > 0 ? { refs: statusRefs } : {},
|
|
1485
|
+
...ifDefined("pathDecision", pathDecision),
|
|
1486
|
+
graph,
|
|
1487
|
+
bundles: attested,
|
|
1488
|
+
...drafts.length > 0 ? { drafts } : {},
|
|
1489
|
+
edgeStatuses,
|
|
1490
|
+
...ifDefined("activeRefHash", activeRefHash),
|
|
1491
|
+
...ifDefined("activeRefName", activeRefName)
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
function createMigrationStatusCommand() {
|
|
1495
|
+
const command = new Command("status");
|
|
1496
|
+
setCommandDescriptions(command, "Show migration history and applied status", "Displays the migration history in order. When a database connection\nis available, shows which migrations are applied and which are pending.\nWithout a database connection, shows the history from disk only.");
|
|
1497
|
+
setCommandExamples(command, ["prisma-next migration status", "prisma-next migration status --db $DATABASE_URL"]);
|
|
1498
|
+
addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--ref <name>", "Target ref name from migrations/refs/").option("--graph", "Show the full migration graph with all branches").option("--limit <n>", "Maximum number of migrations to display (default: 10)").option("--all", "Show full history (disables truncation)").action(async (options) => {
|
|
1499
|
+
const flags = parseGlobalFlags(options);
|
|
1500
|
+
const ui = new TerminalUI({
|
|
1501
|
+
color: flags.color,
|
|
1502
|
+
interactive: flags.interactive
|
|
1503
|
+
});
|
|
1504
|
+
const exitCode = handleResult(await executeMigrationStatusCommand(options, flags, ui), flags, ui, (statusResult) => {
|
|
1505
|
+
if (flags.json) {
|
|
1506
|
+
const { graph: _g, bundles: _b, edgeStatuses: _es, activeRefHash: _arh, activeRefName: _arn, diverged: _d, ...jsonResult } = statusResult;
|
|
1507
|
+
ui.output(JSON.stringify(jsonResult, null, 2));
|
|
1508
|
+
} else if (!flags.quiet) {
|
|
1509
|
+
const colorize = flags.color !== false;
|
|
1510
|
+
if (statusResult.graph) {
|
|
1511
|
+
const limit = determineLimit(options);
|
|
1512
|
+
const renderInput = migrationGraphToRenderInput({
|
|
1513
|
+
graph: statusResult.graph,
|
|
1514
|
+
mode: statusResult.mode,
|
|
1515
|
+
markerHash: statusResult.markerHash,
|
|
1516
|
+
contractHash: statusResult.contractHash,
|
|
1517
|
+
refs: statusResult.refs,
|
|
1518
|
+
activeRefHash: statusResult.activeRefHash,
|
|
1519
|
+
activeRefName: statusResult.activeRefName,
|
|
1520
|
+
edgeStatuses: statusResult.edgeStatuses,
|
|
1521
|
+
draftEdges: statusResult.drafts?.map((d) => ({
|
|
1522
|
+
from: d.manifest.from,
|
|
1523
|
+
to: d.manifest.to,
|
|
1524
|
+
dirName: d.dirName
|
|
1525
|
+
}))
|
|
1526
|
+
});
|
|
1527
|
+
const graphToRender = options.graph || statusResult.diverged ? renderInput.graph : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);
|
|
1528
|
+
const dagreOptions = !options.graph && isLinearGraph(graphToRender) ? { ranksep: 1 } : void 0;
|
|
1529
|
+
const renderOptions = {
|
|
1530
|
+
...renderInput.options,
|
|
1531
|
+
colorize,
|
|
1532
|
+
...ifDefined("limit", limit),
|
|
1533
|
+
...ifDefined("dagreOptions", dagreOptions)
|
|
1534
|
+
};
|
|
1535
|
+
const graphOutput = graphRenderer.render(graphToRender, renderOptions);
|
|
1536
|
+
ui.log(graphOutput);
|
|
1537
|
+
if (statusResult.mode === "online") ui.log(formatLegend(colorize));
|
|
1538
|
+
}
|
|
1539
|
+
ui.log("");
|
|
1540
|
+
ui.log(formatStatusSummary(statusResult, colorize));
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
process.exit(exitCode);
|
|
1544
|
+
});
|
|
1545
|
+
return command;
|
|
1546
|
+
}
|
|
1547
|
+
function formatLegend(colorize) {
|
|
1548
|
+
const c = (fn, s) => colorize ? fn(s) : s;
|
|
1549
|
+
return c(dim, [
|
|
1550
|
+
`${c(cyan, "✓")} applied`,
|
|
1551
|
+
`${c(yellow, "⧗")} pending`,
|
|
1552
|
+
`${c(magenta, "✗")} unreachable`
|
|
1553
|
+
].join(" "));
|
|
1554
|
+
}
|
|
1555
|
+
function formatStatusSummary(result, colorize) {
|
|
1556
|
+
const c = (fn, s) => colorize ? fn(s) : s;
|
|
1557
|
+
const lines = [];
|
|
1558
|
+
const hasUnknown = result.migrations.some((e) => e.status === "unknown");
|
|
1559
|
+
const pendingCount = result.migrations.filter((e) => e.status === "pending").length;
|
|
1560
|
+
const hasWarnings = result.diagnostics?.some((d) => d.severity === "warn") ?? false;
|
|
1561
|
+
if (result.mode === "online") if (hasUnknown || hasWarnings) lines.push(`${c(yellow, "⚠")} ${result.summary}`);
|
|
1562
|
+
else if (pendingCount === 0) lines.push(`${c(cyan, "✔")} ${result.summary}`);
|
|
1563
|
+
else lines.push(`${c(yellow, "⧗")} ${result.summary}`);
|
|
1564
|
+
else lines.push(result.summary);
|
|
1565
|
+
const warnings = result.diagnostics?.filter((d) => d.severity === "warn") ?? [];
|
|
1566
|
+
for (const diag of warnings) {
|
|
1567
|
+
lines.push(`${c(yellow, "⚠")} ${diag.message}`);
|
|
1568
|
+
for (const hint of diag.hints) lines.push(` ${c(dim, hint)}`);
|
|
1569
|
+
}
|
|
1570
|
+
return lines.join("\n");
|
|
1571
|
+
}
|
|
1572
|
+
function summarizeRefDistance(graph, markerHash, refHash, refName) {
|
|
1573
|
+
if (markerHash === refHash) return `At ref "${refName}" target`;
|
|
1574
|
+
const pathToRef = findPath(graph, markerHash, refHash);
|
|
1575
|
+
if (pathToRef) return `${pathToRef.length} migration(s) behind ref "${refName}"`;
|
|
1576
|
+
const pathFromRef = findPath(graph, refHash, markerHash);
|
|
1577
|
+
if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref "${refName}"`;
|
|
1578
|
+
return `No path between database marker and ref "${refName}" target`;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
//#endregion
|
|
1582
|
+
export { deriveEdgeStatuses as n, createMigrationStatusCommand as t };
|
|
1583
|
+
//# sourceMappingURL=migration-status-CJANY4yr.mjs.map
|