@powerhousedao/ph-cli 6.3.0-dev.2 → 6.3.0-dev.4

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 (78) hide show
  1. package/dist/{build-DEARgWyg.mjs → build-BzYMwDBA.mjs} +4 -4
  2. package/dist/{build-DEARgWyg.mjs.map → build-BzYMwDBA.mjs.map} +1 -1
  3. package/dist/build-DKS03LRl.mjs +4 -0
  4. package/dist/{check-C4kc91Oy.mjs → check-B-L_Fi2h.mjs} +4 -4
  5. package/dist/{check-C4kc91Oy.mjs.map → check-B-L_Fi2h.mjs.map} +1 -1
  6. package/dist/{check-D0b-uWwK.mjs → check-B8oqVMg7.mjs} +4 -4
  7. package/dist/{check-D0b-uWwK.mjs.map → check-B8oqVMg7.mjs.map} +1 -1
  8. package/dist/{check-CklNk7AL.mjs → check-CwvNG1y5.mjs} +3 -3
  9. package/dist/{classic-warnings-kQsFGSeA.mjs → classic-warnings-BR0S6lr5.mjs} +4 -4
  10. package/dist/{classic-warnings-kQsFGSeA.mjs.map → classic-warnings-BR0S6lr5.mjs.map} +1 -1
  11. package/dist/{cli-connect-override-31gBnNxd.mjs → cli-connect-override-D22yFWlC.mjs} +4 -4
  12. package/dist/{cli-connect-override-31gBnNxd.mjs.map → cli-connect-override-D22yFWlC.mjs.map} +1 -1
  13. package/dist/cli.mjs +5 -5
  14. package/dist/{compound-CDrU3CLt-gW8JNJQK.mjs → compound-DKi56SSx-CXQHhS6t.mjs} +5 -4
  15. package/dist/{compound-CDrU3CLt-gW8JNJQK.mjs.map → compound-DKi56SSx-CXQHhS6t.mjs.map} +1 -1
  16. package/dist/{connect-build-8Y-QmOJ5.mjs → connect-build-Bwz5FCLl.mjs} +5 -5
  17. package/dist/{connect-build-8Y-QmOJ5.mjs.map → connect-build-Bwz5FCLl.mjs.map} +1 -1
  18. package/dist/{connect-config-Dj3E8CaW.mjs → connect-config-CVU4xhti.mjs} +4 -4
  19. package/dist/{connect-config-Dj3E8CaW.mjs.map → connect-config-CVU4xhti.mjs.map} +1 -1
  20. package/dist/{connect-studio-CBtduPet.mjs → connect-studio-BnfhpIv8.mjs} +10 -7
  21. package/dist/connect-studio-BnfhpIv8.mjs.map +1 -0
  22. package/dist/{connect-studio-BNSe_8PI.mjs → connect-studio-D58ByAAn.mjs} +3 -3
  23. package/dist/definitions-worker.mjs +1 -1
  24. package/dist/{dist-seTzvoSw.mjs → dist-DXcB8fAF.mjs} +67 -5
  25. package/dist/dist-DXcB8fAF.mjs.map +1 -0
  26. package/dist/{explain-DTa32gEY.mjs → explain-8OEXF2Dy.mjs} +5 -5
  27. package/dist/{explain-DTa32gEY.mjs.map → explain-8OEXF2Dy.mjs.map} +1 -1
  28. package/dist/{export-YEBE-Gvl.mjs → export-DqbcbFU5.mjs} +4 -4
  29. package/dist/{export-YEBE-Gvl.mjs.map → export-DqbcbFU5.mjs.map} +1 -1
  30. package/dist/{generate-all-DKuaLgz1.mjs → generate-all-0YOnlZM0.mjs} +4 -4
  31. package/dist/{generate-all-DKuaLgz1.mjs.map → generate-all-0YOnlZM0.mjs.map} +1 -1
  32. package/dist/{generate-document-model-OQPfeHs-.mjs → generate-document-model-BiD6ovXc.mjs} +4 -4
  33. package/dist/generate-document-model-BiD6ovXc.mjs.map +1 -0
  34. package/dist/{get-version-DATiLAmB.mjs → get-version-DrPnQWsE.mjs} +4 -4
  35. package/dist/{get-version-DATiLAmB.mjs.map → get-version-DrPnQWsE.mjs.map} +1 -1
  36. package/dist/{index-Dy3U1WqW.d.mts → index-H3AYe65i.d.mts} +2 -1
  37. package/dist/index-H3AYe65i.d.mts.map +1 -0
  38. package/dist/{mcp-BV_EZ15p.mjs → mcp-CxF7arQA.mjs} +6 -6
  39. package/dist/{mcp-BV_EZ15p.mjs.map → mcp-CxF7arQA.mjs.map} +1 -1
  40. package/dist/{migrate-Bg-HBsYa.mjs → migrate-BWfVrOD7.mjs} +4 -4
  41. package/dist/{migrate-Bg-HBsYa.mjs.map → migrate-BWfVrOD7.mjs.map} +1 -1
  42. package/dist/migrate-document-models-GPxMBuO3.mjs +489 -0
  43. package/dist/migrate-document-models-GPxMBuO3.mjs.map +1 -0
  44. package/dist/migrate-subgraphs-CWlZxwiL.mjs +4 -0
  45. package/dist/migrate-subgraphs-p6K0q-6V.mjs +710 -0
  46. package/dist/migrate-subgraphs-p6K0q-6V.mjs.map +1 -0
  47. package/dist/{ph-cli-commands--2HdnZaA.mjs → ph-cli-commands-CGcyoFMZ.mjs} +61 -27
  48. package/dist/ph-cli-commands-CGcyoFMZ.mjs.map +1 -0
  49. package/dist/ph-cli-commands-u7JueqJc.mjs +4 -0
  50. package/dist/{run-sugar-ByAIbE2x.mjs → run-sugar-DpznOP1e.mjs} +4 -4
  51. package/dist/{run-sugar-ByAIbE2x.mjs.map → run-sugar-DpznOP1e.mjs.map} +1 -1
  52. package/dist/runners/connect.d.mts +1 -1
  53. package/dist/runners/connect.mjs +2 -2
  54. package/dist/runners/switchboard.d.mts +1 -1
  55. package/dist/runners/switchboard.mjs +3 -3
  56. package/dist/{verify-Go5DrPvf.mjs → verify-fPOZMFVM.mjs} +4 -4
  57. package/dist/{verify-Go5DrPvf.mjs.map → verify-fPOZMFVM.mjs.map} +1 -1
  58. package/dist/{vetra-CmTg8Lja.mjs → vetra-CVNZ46pK.mjs} +9 -8
  59. package/dist/vetra-CVNZ46pK.mjs.map +1 -0
  60. package/dist/{vetra-host-C0Q0oMUW.mjs → vetra-host-ChTpJiBJ.mjs} +5 -5
  61. package/dist/{vetra-host-C0Q0oMUW.mjs.map → vetra-host-ChTpJiBJ.mjs.map} +1 -1
  62. package/dist/{vetra-instance-B0bXPj7g.mjs → vetra-instance-CzhYIjxL.mjs} +4 -4
  63. package/dist/{vetra-instance-B0bXPj7g.mjs.map → vetra-instance-CzhYIjxL.mjs.map} +1 -1
  64. package/dist/{vetra-launch-T_uLKaR3.mjs → vetra-launch-qi10Unax.mjs} +7 -6
  65. package/dist/vetra-launch-qi10Unax.mjs.map +1 -0
  66. package/package.json +17 -17
  67. package/dist/build-rj6WVkRW.mjs +0 -4
  68. package/dist/connect-studio-CBtduPet.mjs.map +0 -1
  69. package/dist/dist-seTzvoSw.mjs.map +0 -1
  70. package/dist/generate-document-model-OQPfeHs-.mjs.map +0 -1
  71. package/dist/index-Dy3U1WqW.d.mts.map +0 -1
  72. package/dist/migrate-subgraphs-Bm3zpsO9.mjs +0 -214
  73. package/dist/migrate-subgraphs-Bm3zpsO9.mjs.map +0 -1
  74. package/dist/migrate-subgraphs-De_rX4Hv.mjs +0 -4
  75. package/dist/ph-cli-commands--2HdnZaA.mjs.map +0 -1
  76. package/dist/ph-cli-commands-BdA9sXDE.mjs +0 -4
  77. package/dist/vetra-CmTg8Lja.mjs.map +0 -1
  78. package/dist/vetra-launch-T_uLKaR3.mjs.map +0 -1
@@ -0,0 +1,710 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af25f6b5-cf66-5636-a974-84411242a6b6")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-DrPnQWsE.mjs";
4
+ import { i as readProjectDefinitions } from "./run--de_-WAz.mjs";
5
+ import { t as definitionChecks } from "./check-B-L_Fi2h.mjs";
6
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
8
+ import { castResolverTypeErrors, migrateSubgraph, projectTypeErrors, resolverCallErrors, sortedSchemaText, typeErrorMessage } from "@powerhousedao/codegen";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { readSubgraphDefinitions } from "document-model/tooling";
11
+ import { projectSubgraphGraphQL } from "document-model";
12
+ import { ViteTypeScriptSourceImportAdapter, subgraphDirStyles, uncachedDefinitionSourceRevision } from "@powerhousedao/codegen/utils";
13
+ import { lt, valid } from "semver";
14
+ import { readPackageSync } from "read-pkg";
15
+ import { ts } from "ts-morph";
16
+ //#region src/services/installed-version.ts
17
+ /** The version of `packageName` that Node resolves from `projectDir`. */
18
+ function installedVersion(projectDir, packageName) {
19
+ for (let dir = projectDir;; dir = dirname(dir)) {
20
+ const manifest = join(dir, "node_modules", packageName, "package.json");
21
+ if (existsSync(manifest)) {
22
+ const { version } = JSON.parse(readFileSync(manifest, "utf8"));
23
+ return typeof version === "string" ? version : void 0;
24
+ }
25
+ if (dirname(dir) === dir) return void 0;
26
+ }
27
+ }
28
+ /**
29
+ * Why the code `ph migrate` writes cannot run against the project's
30
+ * `packageName`, or undefined when it can: the project must have the package
31
+ * at this ph-cli's version or later. Unknown versions are not checked.
32
+ */
33
+ function outdatedDependency(projectDir, packageName) {
34
+ const required = getVersion();
35
+ if (valid(required) === null) return void 0;
36
+ const installed = installedVersion(projectDir, packageName);
37
+ if (installed === void 0) return `${packageName} is not installed in this project. Install the project's dependencies, then migrate again.`;
38
+ if (valid(installed) === null || !lt(installed, required)) return void 0;
39
+ return `This project has ${packageName} ${installed}, and what this ph migrate converts to code-first needs ${required} or later. Run ph migrate ${required} to upgrade the Powerhouse packages, then convert again.`;
40
+ }
41
+ //#endregion
42
+ //#region src/services/project-files.ts
43
+ /** Directories that never hold the package's own sources. */
44
+ const SKIPPED_DIRS = /* @__PURE__ */ new Set([
45
+ "node_modules",
46
+ "dist",
47
+ "build",
48
+ ".ph",
49
+ ".git",
50
+ ".turbo",
51
+ ".vite",
52
+ ".tsbuild",
53
+ "coverage"
54
+ ]);
55
+ const toPosix = (path) => path.split(sep).join("/");
56
+ const errorText = (error) => error instanceof Error ? error.message : String(error);
57
+ /** The package's files whose names match `pattern`, by project-relative POSIX path. */
58
+ function readProjectFiles(projectDir, pattern) {
59
+ const files = /* @__PURE__ */ new Map();
60
+ const visit = (dir) => {
61
+ for (const entry of readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) {
62
+ if (!SKIPPED_DIRS.has(entry.name)) visit(join(dir, entry.name));
63
+ } else if (entry.isFile() && pattern.test(entry.name)) {
64
+ const path = join(dir, entry.name);
65
+ files.set(toPosix(relative(projectDir, path)), readFileSync(path));
66
+ }
67
+ };
68
+ visit(projectDir);
69
+ return files;
70
+ }
71
+ /** Refuses links the source inventory cannot represent without following them. */
72
+ function assertChangesWritable(projectDir, changes) {
73
+ const root = resolve(projectDir);
74
+ for (const { path } of changes) {
75
+ let current = resolve(root, path);
76
+ const local = relative(root, current);
77
+ if (local === "" || local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local)) throw new Error(`${path} is not a file inside this project.`);
78
+ while (current !== root) {
79
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`${toPosix(relative(root, current))} is a symbolic link. Replace it with a regular project file or directory before migrating; its target was not changed.`);
80
+ current = dirname(current);
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * Writes `changes` and returns the bytes they replaced. When a write fails,
86
+ * everything already written is restored before the error is rethrown.
87
+ */
88
+ function writeChanges(projectDir, changes) {
89
+ assertChangesWritable(projectDir, changes);
90
+ const backup = /* @__PURE__ */ new Map();
91
+ for (const { path } of changes) {
92
+ const absolute = join(projectDir, path);
93
+ backup.set(path, existsSync(absolute) ? {
94
+ bytes: readFileSync(absolute),
95
+ mode: lstatSync(absolute).mode & 4095
96
+ } : null);
97
+ }
98
+ try {
99
+ for (const change of changes) put(projectDir, change.path, change.after);
100
+ } catch (error) {
101
+ restoreChanges(projectDir, backup);
102
+ throw error;
103
+ }
104
+ return backup;
105
+ }
106
+ /** Restores the contents and permissions `writeChanges` replaced. */
107
+ function restoreChanges(projectDir, backup) {
108
+ for (const [path, file] of backup) {
109
+ put(projectDir, path, file?.bytes ?? null);
110
+ if (file !== null) chmodSync(join(projectDir, path), file.mode);
111
+ }
112
+ }
113
+ function put(projectDir, path, bytes) {
114
+ const absolute = join(projectDir, path);
115
+ if (bytes === null) {
116
+ rmSync(absolute, { force: true });
117
+ removeEmptyParents(projectDir, dirname(absolute));
118
+ } else {
119
+ mkdirSync(dirname(absolute), { recursive: true });
120
+ writeFileSync(absolute, bytes);
121
+ }
122
+ }
123
+ /** Removes `dir` and its parents while they are empty, up to the project. */
124
+ function removeEmptyParents(projectDir, dir) {
125
+ let current = dir;
126
+ while (current.startsWith(projectDir) && current !== projectDir) {
127
+ if (!existsSync(current) || readdirSync(current).length > 0) return;
128
+ rmdirSync(current);
129
+ current = dirname(current);
130
+ }
131
+ }
132
+ //#endregion
133
+ //#region src/services/package-module-targets.ts
134
+ /** Every static alternative, without assuming which runtime conditions apply. */
135
+ function alternatives(value) {
136
+ if (typeof value === "string") return [value];
137
+ if (value === null || typeof value !== "object") return [];
138
+ return Object.values(value).flatMap(alternatives);
139
+ }
140
+ /** Extra matching patterns are safe here: targets are protected, never rewritten. */
141
+ function matchingTargets(mapping, specifier) {
142
+ if (mapping === null || typeof mapping !== "object") return [];
143
+ return Object.entries(mapping).flatMap(([pattern, value]) => {
144
+ if (pattern === specifier) return [{
145
+ pattern,
146
+ targets: alternatives(value)
147
+ }];
148
+ const star = pattern.indexOf("*");
149
+ if (star === -1) return [];
150
+ const prefix = pattern.slice(0, star);
151
+ const suffix = pattern.slice(star + 1);
152
+ if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix) || specifier.length < prefix.length + suffix.length) return [];
153
+ const matched = specifier.slice(prefix.length, specifier.length - suffix.length);
154
+ return [{
155
+ pattern,
156
+ targets: alternatives(value).map((target) => target.replaceAll("*", matched))
157
+ }];
158
+ });
159
+ }
160
+ /** Static local targets of observed imports/self-exports in each file's package scope. */
161
+ function packageModuleTargets(projectDir) {
162
+ const root = resolve(projectDir);
163
+ const packages = /* @__PURE__ */ new Map();
164
+ const imports = (from, specifier) => {
165
+ const redirects = [];
166
+ let dir = dirname(join(root, from));
167
+ for (;;) {
168
+ if (!packages.has(dir)) packages.set(dir, existsSync(join(dir, "package.json")) ? readPackageSync({
169
+ cwd: dir,
170
+ normalize: false
171
+ }) : void 0);
172
+ const metadata = packages.get(dir);
173
+ if (metadata !== void 0) {
174
+ const visit = (name, active) => {
175
+ let matches = [];
176
+ if (name.startsWith("#")) matches = matchingTargets(metadata.imports, name);
177
+ else if (typeof metadata.name === "string" && (name === metadata.name || name.startsWith(`${metadata.name}/`))) {
178
+ const subpath = `.${name.slice(metadata.name.length)}`;
179
+ const exports = metadata.exports;
180
+ const subpaths = exports !== null && typeof exports === "object" && Object.keys(exports).some((key) => key.startsWith("."));
181
+ matches = subpath === "." && !subpaths ? [{
182
+ pattern: ".",
183
+ targets: alternatives(exports)
184
+ }] : matchingTargets(exports, subpath);
185
+ }
186
+ return matches.flatMap(({ pattern, targets }) => {
187
+ const key = `${name.startsWith("#") ? "imports" : "exports"}:${pattern}`;
188
+ if (active.has(key)) throw new Error(`Package mapping ${pattern} redirects recursively. Remove that redirect before migrating subgraphs.`);
189
+ const next = new Set(active).add(key);
190
+ return targets.flatMap((target) => {
191
+ if (!target.startsWith("./")) {
192
+ if (target.startsWith("#") || typeof metadata.name === "string" && (target === metadata.name || target.startsWith(`${metadata.name}/`))) return visit(target, next);
193
+ redirects.push({
194
+ from: toPosix(relative(root, join(dir, "package.json"))),
195
+ specifier: target
196
+ });
197
+ return [];
198
+ }
199
+ const file = fileURLToPath(new URL(target, pathToFileURL(dir + sep)));
200
+ return [toPosix(relative(root, file))];
201
+ });
202
+ });
203
+ };
204
+ return {
205
+ targets: visit(specifier, /* @__PURE__ */ new Set()),
206
+ redirects
207
+ };
208
+ }
209
+ if (dir === root) return {
210
+ targets: [],
211
+ redirects
212
+ };
213
+ dir = dirname(dir);
214
+ }
215
+ };
216
+ const entries = (file, specifier) => {
217
+ const targets = /* @__PURE__ */ new Set();
218
+ for (const dir of /* @__PURE__ */ new Set([dirname(file), dirname(realpathSync(file))])) {
219
+ if (!packages.has(dir)) packages.set(dir, readPackageSync({
220
+ cwd: dir,
221
+ normalize: false
222
+ }));
223
+ const metadata = packages.get(dir);
224
+ if (metadata === void 0) continue;
225
+ const paths = [
226
+ "./index.js",
227
+ ...alternatives(metadata.main),
228
+ ...alternatives(metadata["module"]),
229
+ ...alternatives(metadata["browser"]),
230
+ ...alternatives(metadata["jsnext:main"]),
231
+ ...alternatives(metadata["jsnext"])
232
+ ];
233
+ const exports = metadata.exports;
234
+ if (!(exports !== null && typeof exports === "object" && Object.keys(exports).some((key) => key.startsWith(".")))) paths.push(...alternatives(exports));
235
+ else {
236
+ const subpath = specifier.split("/").slice(specifier.startsWith("@") ? 2 : 1).join("/");
237
+ for (const key of /* @__PURE__ */ new Set([".", ...subpath ? [`./${subpath}`] : []])) paths.push(...matchingTargets(exports, key).flatMap(({ targets }) => targets));
238
+ }
239
+ for (const target of paths) {
240
+ targets.add(toPosix(relative(root, resolve(dir, target))));
241
+ try {
242
+ const url = new URL(target, pathToFileURL(dir + sep));
243
+ if (url.protocol === "file:") targets.add(toPosix(relative(root, fileURLToPath(url))));
244
+ } catch {}
245
+ }
246
+ }
247
+ return [...targets];
248
+ };
249
+ return {
250
+ imports,
251
+ entries
252
+ };
253
+ }
254
+ //#endregion
255
+ //#region src/services/project-module-references.ts
256
+ const CODE_FILE = /\.[cm]?[jt]sx?$/;
257
+ /** Static module targets, including every package condition and redirected subpath. */
258
+ function projectModuleReferences(projectDir) {
259
+ const root = realpathSync(projectDir);
260
+ const configPath = ts.findConfigFile(root, (file) => ts.sys.fileExists(file));
261
+ const options = {
262
+ ...(configPath === void 0 ? void 0 : ts.getParsedCommandLineOfConfigFile(configPath, {}, {
263
+ ...ts.sys,
264
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
265
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
266
+ }
267
+ }))?.options,
268
+ module: ts.ModuleKind.ESNext,
269
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
270
+ resolvePackageJsonImports: true,
271
+ resolvePackageJsonExports: true
272
+ };
273
+ const resolutions = /* @__PURE__ */ new Map();
274
+ const contents = /* @__PURE__ */ new Map();
275
+ const packageTargets = packageModuleTargets(root);
276
+ const references = [];
277
+ for (const [sourcePath, bytes] of readProjectFiles(root, CODE_FILE)) {
278
+ const source = ts.createSourceFile(sourcePath, bytes.toString("utf8"), ts.ScriptTarget.Latest, true);
279
+ /** Each literal, and whether some use of it reads the module whole. */
280
+ const literals = /* @__PURE__ */ new Map();
281
+ const visit = (node) => {
282
+ if (ts.isStringLiteralLike(node)) literals.set(node.text, (literals.get(node.text) ?? false) || readsWhole(node));
283
+ ts.forEachChild(node, visit);
284
+ };
285
+ visit(source);
286
+ for (const [literal, whole] of literals) {
287
+ const targets = /* @__PURE__ */ new Map();
288
+ const requests = /* @__PURE__ */ new Map();
289
+ const enqueue = (from, literal) => {
290
+ const unqualified = literal.slice(0, 1) + literal.slice(1).split(/[?#]/, 1)[0];
291
+ for (const named of /* @__PURE__ */ new Set([literal, unqualified])) {
292
+ requests.set(JSON.stringify([from, named]), {
293
+ from,
294
+ named
295
+ });
296
+ try {
297
+ const decoded = decodeURIComponent(named);
298
+ requests.set(JSON.stringify([from, decoded]), {
299
+ from,
300
+ named: decoded
301
+ });
302
+ } catch {}
303
+ }
304
+ };
305
+ enqueue(sourcePath, literal);
306
+ for (const { from, named } of requests.values()) {
307
+ const isRelative = /^\.{1,2}\//.test(named);
308
+ const protect = (target, throughPackage = false) => {
309
+ targets.set(target, throughPackage || targets.get(target) === true);
310
+ };
311
+ const protectPackageTarget = (target) => {
312
+ protect(target, true);
313
+ const stem = target.replace(CODE_FILE, "");
314
+ for (const extension of [
315
+ "ts",
316
+ "tsx",
317
+ "mts",
318
+ "cts",
319
+ "js",
320
+ "jsx",
321
+ "mjs",
322
+ "cjs"
323
+ ]) {
324
+ protect(`${stem}.${extension}`, true);
325
+ protect(`${stem}/index.${extension}`, true);
326
+ }
327
+ };
328
+ const mapping = packageTargets.imports(from, named);
329
+ for (const redirect of mapping.redirects) enqueue(redirect.from, redirect.specifier);
330
+ for (const target of mapping.targets) protectPackageTarget(target);
331
+ for (const mode of [ts.ModuleKind.ESNext, ts.ModuleKind.CommonJS]) {
332
+ const key = JSON.stringify([
333
+ posix.dirname(from),
334
+ named,
335
+ mode
336
+ ]);
337
+ let resolution = resolutions.get(key);
338
+ if (resolution === void 0) {
339
+ const consulted = /* @__PURE__ */ new Set();
340
+ resolution = {
341
+ file: ts.resolveModuleName(named, join(root, from), options, {
342
+ ...ts.sys,
343
+ readFile: (file) => {
344
+ if (!contents.has(file)) contents.set(file, ts.sys.readFile(file));
345
+ const text = contents.get(file);
346
+ if (text !== void 0 && basename(file) === "package.json") consulted.add(file);
347
+ return text;
348
+ }
349
+ }, void 0, void 0, mode).resolvedModule?.resolvedFileName,
350
+ packages: [...consulted]
351
+ };
352
+ resolutions.set(key, resolution);
353
+ }
354
+ if (resolution.file !== void 0) protect(toPosix(relative(root, resolution.file)));
355
+ for (const file of resolution.packages) for (const target of packageTargets.entries(file, named)) protectPackageTarget(target);
356
+ }
357
+ const paths = isRelative ? [posix.join(posix.dirname(from), named)] : [...named.matchAll(/subgraphs\//g)].map((match) => named.slice(match.index));
358
+ for (const path of paths) {
359
+ const target = path.replace(CODE_FILE, "");
360
+ protect(`${target}.ts`);
361
+ protect(`${target}/index.ts`);
362
+ }
363
+ }
364
+ if (targets.size > 0) references.push({
365
+ file: sourcePath,
366
+ specifier: literal,
367
+ whole,
368
+ targets: [...targets].map(([path, throughPackage]) => ({
369
+ path,
370
+ throughPackage
371
+ }))
372
+ });
373
+ }
374
+ }
375
+ return references;
376
+ }
377
+ /** Whether `literal` reads its module whole, rather than by named bindings. */
378
+ function readsWhole(literal) {
379
+ const parent = literal.parent;
380
+ if (ts.isImportDeclaration(parent)) {
381
+ const bindings = parent.importClause?.namedBindings;
382
+ return bindings !== void 0 && ts.isNamespaceImport(bindings);
383
+ }
384
+ if (ts.isExportDeclaration(parent)) return parent.exportClause === void 0 || ts.isNamespaceExport(parent.exportClause);
385
+ return true;
386
+ }
387
+ //#endregion
388
+ //#region src/services/subgraph-readers.ts
389
+ /** Readers outside the relative import graph that codegen can rewrite. */
390
+ function subgraphReaders(projectDir) {
391
+ const found = /* @__PURE__ */ new Set();
392
+ const whole = /* @__PURE__ */ new Set();
393
+ for (const reference of projectModuleReferences(projectDir)) {
394
+ const isRelative = /^\.{1,2}\//.test(reference.specifier);
395
+ for (const target of reference.targets) {
396
+ const parts = target.path.split("/");
397
+ const [top, name] = parts;
398
+ if (top !== "subgraphs" || parts.length < 2) continue;
399
+ if (!target.throughPackage && isRelative && reference.file.startsWith(`subgraphs/${name}/`)) continue;
400
+ found.add(target.path);
401
+ if (reference.whole) whole.add(target.path);
402
+ }
403
+ }
404
+ return {
405
+ imported: found,
406
+ readWhole: whole
407
+ };
408
+ }
409
+ //#endregion
410
+ //#region src/services/migrate-subgraphs.ts
411
+ /** A module that hangs on a top-level await must not hang `ph migrate`. */
412
+ const IMPORT_TIMEOUT_MS = 6e4;
413
+ const SCALARS_ENTRY = "scalars/index.ts";
414
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|graphql)$/;
415
+ /**
416
+ * `ph migrate --subgraphs`: converts schema-first subgraphs into code-first
417
+ * ones. Each written directory is loaded as `ph model check` loads it and
418
+ * must serve the schema it served before; otherwise its files are restored.
419
+ * Without named directories, a directory whose `index.ts` holds no class is
420
+ * skipped. Returns the exit code: 0 when every requested subgraph converted
421
+ * or was already code-first, 1 otherwise.
422
+ */
423
+ async function migrateSubgraphs(options) {
424
+ const out = options.out ?? ((text) => void process.stdout.write(text));
425
+ const { projectDir, dryRun } = options;
426
+ let outdated = outdatedDependency(projectDir, "@powerhousedao/reactor-api");
427
+ /** The composition errors `ph model check` reported before this run converted anything. */
428
+ let composition;
429
+ /** What the project's tsc reported in the subgraphs before this run wrote anything. */
430
+ let typeBaseline;
431
+ const outsideReaders = subgraphReaders(projectDir);
432
+ const styles = new Map(subgraphDirStyles(join(projectDir, "subgraphs")).map(({ dirName, style }) => [dirName, style]));
433
+ let failed = false;
434
+ let schemaFirst = 0;
435
+ const named = options.dirs.length > 0;
436
+ const requested = named ? options.dirs : [...styles.keys()];
437
+ const converted = [];
438
+ const importer = new ViteTypeScriptSourceImportAdapter();
439
+ const revision = uncachedDefinitionSourceRevision();
440
+ try {
441
+ for (const dirName of requested) {
442
+ const label = `subgraphs/${dirName}`;
443
+ const style = styles.get(dirName);
444
+ if (style === void 0) {
445
+ out(`${label}: not found. Name a directory of subgraphs/ that has an index.ts.\n`);
446
+ failed = true;
447
+ continue;
448
+ }
449
+ if (style === "code-first") {
450
+ out(`${label}: already code-first\n`);
451
+ continue;
452
+ }
453
+ const originals = readDirectory(projectDir, dirName);
454
+ let written;
455
+ try {
456
+ const migration = await migrateSubgraph({
457
+ dirName,
458
+ files: new Map([...originals].map(([path, bytes]) => [path, bytes.toString("utf8")])),
459
+ importedFromOutside: outsideReaders.imported,
460
+ readWholeFromOutside: outsideReaders.readWhole
461
+ });
462
+ if (migration.kind === "no-subgraph-class" && !named) {
463
+ out(`${label}: no subgraph class, skipped\n`);
464
+ continue;
465
+ }
466
+ schemaFirst++;
467
+ if (migration.kind !== "converted") {
468
+ out(refusalText(label, migration));
469
+ failed = true;
470
+ continue;
471
+ }
472
+ if (dryRun) {
473
+ assertChangesWritable(projectDir, migration.files);
474
+ out(`${label}: would convert ${migration.className} to code-first\n`);
475
+ for (const file of migration.files) out(unifiedDiff(file));
476
+ continue;
477
+ }
478
+ if (outdated !== void 0) {
479
+ out(`${label}: not converted. ${outdated}\n`);
480
+ outdated = "@powerhousedao/reactor-api is too old, as above.";
481
+ failed = true;
482
+ continue;
483
+ }
484
+ composition ??= await compositionErrors(projectDir, /* @__PURE__ */ new Set());
485
+ typeBaseline ??= projectTypeErrors(projectDir, requested.map((name) => `subgraphs/${name}`), []);
486
+ try {
487
+ written = writeChanges(projectDir, migration.files);
488
+ } catch (error) {
489
+ out(`${label}: not converted; its files are restored. Writing them failed: ${errorText(error)}\n`);
490
+ failed = true;
491
+ continue;
492
+ }
493
+ let verification = await verify(projectDir, migration, importer, revision);
494
+ if (verification.ok) {
495
+ const added = await compositionErrors(projectDir, composition);
496
+ if (added.size > 0) verification = {
497
+ ok: false,
498
+ reason: `The host would not serve the package's code-first subgraphs together:\n${[...added].map((error) => ` ${error}`).join("\n")}\nRename the conflicting types in one of the subgraphs, then migrate again.`
499
+ };
500
+ }
501
+ if (!verification.ok) {
502
+ restoreChanges(projectDir, written);
503
+ out(`${label}: not converted; its files are restored. ${verification.reason}\n`);
504
+ failed = true;
505
+ continue;
506
+ }
507
+ converted.push(dirName);
508
+ out(`${label}: converted ${migration.className} to code-first; it serves the same schema\n`);
509
+ for (const note of migration.notes) out(`Note: ${note}\n`);
510
+ if (migration.sdlFile.endsWith("/schema.graphql")) out(`${migration.sdlFile} is no longer used; the schema is now in ${label}/schema.ts. It was kept, and you can delete it.\n`);
511
+ } catch (error) {
512
+ if (written !== void 0) restoreChanges(projectDir, written);
513
+ out(`${label}: not converted; its files are ${written === void 0 ? "unchanged" : "restored"}. The conversion failed unexpectedly: ${errorText(error)}\n`);
514
+ failed = true;
515
+ }
516
+ }
517
+ } finally {
518
+ await importer.disposeRevision();
519
+ }
520
+ if (converted.length > 0) out(await typeReport(projectDir, converted, options.strictResolvers ?? false, typeBaseline));
521
+ if (!named && schemaFirst === 0) out("No schema-first subgraphs to convert.\n");
522
+ return failed ? 1 : 0;
523
+ }
524
+ /**
525
+ * The converted resolvers TypeScript rejects. The schema-first resolver map
526
+ * never checked a resolver's types against the schema; each converted entry
527
+ * calls its resolver with the schema's types, so a disagreement is now a
528
+ * type error. Unless `strict`, each rejected call is cast where it fails, so
529
+ * it runs as before and the project compiles. Any other error the
530
+ * conversion added to the subgraphs, against `baseline`, is reported too.
531
+ */
532
+ async function typeReport(projectDir, converted, strict, baseline) {
533
+ const dirs = converted.map((dirName) => `subgraphs/${dirName}`);
534
+ const indexPaths = dirs.map((dir) => `${dir}/index.ts`);
535
+ const check = () => projectTypeErrors(projectDir, dirs, indexPaths);
536
+ const first = check();
537
+ if (first.kind === "untyped") return "";
538
+ if (first.kind === "skipped") return `Note: the converted resolvers were not type-checked: ${first.reason}.\n`;
539
+ const list = (shown) => shown.map(({ file, line, coordinate, message }) => ` ${file}:${line} ${coordinate}: ${message}\n`).join("");
540
+ const calls = resolverCallErrors(projectDir, indexPaths, first.errors);
541
+ let report = "";
542
+ let final = first;
543
+ if (calls.length > 0) {
544
+ const count = `${calls.length === 1 ? "1 resolver call disagrees" : `${calls.length} resolver calls disagree`} with the schema the subgraph serves`;
545
+ if (strict) report += `Note: ${count}, so TypeScript rejects ${calls.length === 1 ? "it" : "them"}. The schema-first map never checked them; fix each resolver's types:\n${list(calls)}`;
546
+ else {
547
+ writeChanges(projectDir, await castResolverTypeErrors(projectDir, calls));
548
+ let after = check();
549
+ if (after.kind === "checked" && calls.some(({ message }) => /^Expected (?:\d+-)?\d+ arguments?, but got \d+\./.test(message))) {
550
+ const exposed = resolverCallErrors(projectDir, indexPaths, after.errors);
551
+ if (exposed.length > 0) {
552
+ writeChanges(projectDir, await castResolverTypeErrors(projectDir, exposed));
553
+ calls.push(...exposed);
554
+ after = check();
555
+ }
556
+ }
557
+ if (after.kind === "checked") final = after;
558
+ const left = resolverCallErrors(projectDir, indexPaths, final.errors);
559
+ report += `Note: ${count}. The schema-first map never checked them; each call is cast where TypeScript rejects it, under a "ph migrate:" comment, so it runs as before and the project compiles. Fix each resolver's types, then remove its cast:\n${list(calls)}`;
560
+ if (left.length > 0) report += `Note: ${left.length === 1 ? "1 resolver call is" : `${left.length} resolver calls are`} still rejected after the casts; fix ${left.length === 1 ? "it" : "them"} by hand:\n${list(left)}`;
561
+ }
562
+ }
563
+ if (baseline?.kind === "checked") {
564
+ const key = (error) => `${error.file.split("/").slice(0, 2).join("/")}|${error.lines.join("|")}`;
565
+ const before = /* @__PURE__ */ new Map();
566
+ for (const error of baseline.errors) before.set(key(error), (before.get(key(error)) ?? 0) + 1);
567
+ const inSchema = new Set(resolverCallErrors(projectDir, indexPaths, final.errors).map(({ file, line, column }) => `${file}:${line}:${column}`));
568
+ const introduced = final.errors.filter((error) => {
569
+ if (inSchema.has(`${error.file}:${error.line}:${error.column}`)) return false;
570
+ const remaining = before.get(key(error)) ?? 0;
571
+ if (remaining > 0) {
572
+ before.set(key(error), remaining - 1);
573
+ return false;
574
+ }
575
+ return true;
576
+ });
577
+ if (introduced.length > 0) report += `Note: the conversion added ${introduced.length === 1 ? "1 type error" : `${introduced.length} type errors`} besides the resolver calls. That is a bug in ph migrate; please report it, and fix ${introduced.length === 1 ? "it" : "them"} by hand:\n${introduced.map((error) => ` ${error.file}:${error.line}: ${typeErrorMessage(error)}\n`).join("")}`;
578
+ }
579
+ return report;
580
+ }
581
+ /** The directory's files and `scalars/index.ts`, by project-relative path. */
582
+ function readDirectory(projectDir, dirName) {
583
+ const files = /* @__PURE__ */ new Map();
584
+ const dir = join(projectDir, "subgraphs", dirName);
585
+ for (const entry of readdirSync(dir, {
586
+ recursive: true,
587
+ withFileTypes: true
588
+ })) {
589
+ if (!entry.isFile() || !SOURCE_FILE.test(entry.name)) continue;
590
+ const path = join(entry.parentPath, entry.name);
591
+ files.set(path.slice(projectDir.length + 1).replaceAll("\\", "/"), readFileSync(path));
592
+ }
593
+ const scalars = join(projectDir, SCALARS_ENTRY);
594
+ if (existsSync(scalars)) files.set(SCALARS_ENTRY, readFileSync(scalars));
595
+ return files;
596
+ }
597
+ async function withTimeout(work, timeoutMs) {
598
+ let timer;
599
+ const timeout = new Promise((_, reject) => {
600
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`it did not finish loading within ${timeoutMs / 1e3} seconds`)), timeoutMs);
601
+ timer.unref();
602
+ });
603
+ try {
604
+ return await Promise.race([work, timeout]);
605
+ } finally {
606
+ clearTimeout(timer);
607
+ }
608
+ }
609
+ /**
610
+ * The subgraph composition errors `ph model check` reports for the project,
611
+ * leaving out those in `known`. Converted subgraphs are composed with each
612
+ * other: a type two of them declare differently keeps one out of the host.
613
+ */
614
+ async function compositionErrors(projectDir, known) {
615
+ const report = await readProjectDefinitions(projectDir, (project, modules) => definitionChecks.edit(project, modules));
616
+ return new Set(report.diagnostics.filter(({ severity, phase }) => severity === "error" && phase === "composition").map(({ message }) => message).filter((message) => !known.has(message)));
617
+ }
618
+ /** Loads the written class without constructing it and compares the schema it serves. */
619
+ async function verify(projectDir, migration, importer, revision) {
620
+ const specifier = `./subgraphs/${migration.dirName}/index.ts`;
621
+ let namespace;
622
+ try {
623
+ namespace = await withTimeout(importer.importModule({
624
+ packageRoot: projectDir,
625
+ specifier,
626
+ packageRevision: revision
627
+ }), IMPORT_TIMEOUT_MS);
628
+ } catch (error) {
629
+ return {
630
+ ok: false,
631
+ reason: `The converted module does not load: ${(error instanceof Error ? error.message : String(error)).replaceAll(projectDir, ".")}`
632
+ };
633
+ }
634
+ const { subgraphs, diagnostics } = readSubgraphDefinitions(namespace, { specifier });
635
+ const errors = diagnostics.filter(({ severity }) => severity === "error");
636
+ if (errors.length > 0) return {
637
+ ok: false,
638
+ reason: `The converted subgraph does not compile:\n${errors.map(({ message, repair }) => ` ${message} ${repair}`).join("\n")}`
639
+ };
640
+ const subgraph = subgraphs.find(({ name }) => name === migration.subgraphName);
641
+ if (subgraph === void 0) return {
642
+ ok: false,
643
+ reason: `${specifier} exports no code-first subgraph named ${migration.subgraphName}.`
644
+ };
645
+ const served = sortedSchemaText(projectSubgraphGraphQL(subgraph.definition));
646
+ if (served === migration.sdl) return { ok: true };
647
+ return {
648
+ ok: false,
649
+ reason: `The converted subgraph serves a different schema:\n${unifiedDiff({
650
+ path: "schema",
651
+ before: migration.sdl,
652
+ after: served
653
+ })}`
654
+ };
655
+ }
656
+ function refusalText(label, migration) {
657
+ return `${label}: not converted\n${migration.refusals.map(({ file, line, reason, repair }) => ` ${file}:${line}: ${reason}\n ${repair}\n`).join("")}`;
658
+ }
659
+ /** The line edits from `before` to `after`, by longest common subsequence. */
660
+ function lineEdits(before, after) {
661
+ const common = Array.from({ length: before.length + 1 }, () => new Array(after.length + 1).fill(0));
662
+ for (let i = before.length - 1; i >= 0; i--) for (let j = after.length - 1; j >= 0; j--) common[i][j] = before[i] === after[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
663
+ const lines = [];
664
+ let i = 0;
665
+ let j = 0;
666
+ while (i < before.length || j < after.length) if (i < before.length && j < after.length && before[i] === after[j]) {
667
+ lines.push({
668
+ kind: " ",
669
+ text: before[i++]
670
+ });
671
+ j++;
672
+ } else if (i < before.length && (j === after.length || common[i + 1][j] >= common[i][j + 1])) lines.push({
673
+ kind: "-",
674
+ text: before[i++]
675
+ });
676
+ else lines.push({
677
+ kind: "+",
678
+ text: after[j++]
679
+ });
680
+ return lines;
681
+ }
682
+ const CONTEXT = 3;
683
+ /** A unified diff of one file; a new file diffs against /dev/null. */
684
+ function unifiedDiff(file) {
685
+ const split = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
686
+ const lines = lineEdits(split(file.before ?? ""), split(file.after ?? ""));
687
+ const changed = lines.flatMap((line, index) => line.kind === " " ? [] : [index]);
688
+ if (changed.length === 0) return "";
689
+ const hunks = [];
690
+ for (const index of changed) {
691
+ const start = Math.max(0, index - CONTEXT);
692
+ const end = Math.min(lines.length, index + CONTEXT + 1);
693
+ const last = hunks.at(-1);
694
+ if (last !== void 0 && start <= last[1]) last[1] = end;
695
+ else hunks.push([start, end]);
696
+ }
697
+ return `--- ${file.before === null ? "/dev/null" : `a/${file.path}`}\n+++ ${file.after === null ? "/dev/null" : `b/${file.path}`}\n` + hunks.map(([start, end]) => {
698
+ const lineBefore = (kind) => lines.slice(0, start).filter((line) => line.kind !== kind).length;
699
+ const slice = lines.slice(start, end);
700
+ const count = (kind) => slice.filter((line) => line.kind !== kind).length;
701
+ const oldCount = count("+");
702
+ const newCount = count("-");
703
+ return `@@ -${oldCount === 0 ? lineBefore("+") : lineBefore("+") + 1},${oldCount} +${newCount === 0 ? lineBefore("-") : lineBefore("-") + 1},${newCount} @@\n${slice.map((line) => `${line.kind}${line.text}`).join("\n")}\n`;
704
+ }).join("");
705
+ }
706
+ //#endregion
707
+ export { errorText as a, toPosix as c, assertChangesWritable as i, writeChanges as l, unifiedDiff as n, readProjectFiles as o, projectModuleReferences as r, restoreChanges as s, migrateSubgraphs as t, outdatedDependency as u };
708
+
709
+ //# sourceMappingURL=migrate-subgraphs-p6K0q-6V.mjs.map
710
+ //# debugId=af25f6b5-cf66-5636-a974-84411242a6b6