@powerhousedao/ph-cli 6.2.3 → 6.3.0-dev.10

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 (193) hide show
  1. package/README.md +21 -0
  2. package/dist/build-CD_KQkCH.mjs +4 -0
  3. package/dist/build-DDG00Wbj.mjs +3067 -0
  4. package/dist/build-DDG00Wbj.mjs.map +1 -0
  5. package/dist/check-B8oqVMg7.mjs +65 -0
  6. package/dist/check-B8oqVMg7.mjs.map +1 -0
  7. package/dist/check-CpzjVXHj.mjs +4 -0
  8. package/dist/check-Weu9n8OQ.mjs +81 -0
  9. package/dist/check-Weu9n8OQ.mjs.map +1 -0
  10. package/dist/classic-args-mH_DVsgC.mjs +48 -0
  11. package/dist/classic-args-mH_DVsgC.mjs.map +1 -0
  12. package/dist/classic-warnings-BR0S6lr5.mjs +179 -0
  13. package/dist/classic-warnings-BR0S6lr5.mjs.map +1 -0
  14. package/dist/{cli-connect-override-b4kKqgOZ.mjs → cli-connect-override-D22yFWlC.mjs} +6 -29
  15. package/dist/cli-connect-override-D22yFWlC.mjs.map +1 -0
  16. package/dist/cli.mjs +46 -1341
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/compound-DKi56SSx-CXQHhS6t.mjs +2911 -0
  19. package/dist/compound-DKi56SSx-CXQHhS6t.mjs.map +1 -0
  20. package/dist/connect-build-Bd6sSVwp.mjs +322 -0
  21. package/dist/connect-build-Bd6sSVwp.mjs.map +1 -0
  22. package/dist/{connect-config-_kiSMsbG.mjs → connect-config-CVU4xhti.mjs} +5 -5
  23. package/dist/{connect-config-_kiSMsbG.mjs.map → connect-config-CVU4xhti.mjs.map} +1 -1
  24. package/dist/connect-preview-CdFvlANO.mjs +49 -0
  25. package/dist/connect-preview-CdFvlANO.mjs.map +1 -0
  26. package/dist/connect-studio-BnfhpIv8.mjs +97 -0
  27. package/dist/connect-studio-BnfhpIv8.mjs.map +1 -0
  28. package/dist/{connect-studio-f3K1qPWd.mjs → connect-studio-D58ByAAn.mjs} +3 -3
  29. package/dist/definitions-worker.d.mts +98 -0
  30. package/dist/definitions-worker.d.mts.map +1 -0
  31. package/dist/definitions-worker.mjs +28 -0
  32. package/dist/definitions-worker.mjs.map +1 -0
  33. package/dist/dist-DXcB8fAF.mjs +542 -0
  34. package/dist/dist-DXcB8fAF.mjs.map +1 -0
  35. package/dist/evidence-CavwC5YV.mjs +134 -0
  36. package/dist/evidence-CavwC5YV.mjs.map +1 -0
  37. package/dist/explain-8OEXF2Dy.mjs +230 -0
  38. package/dist/explain-8OEXF2Dy.mjs.map +1 -0
  39. package/dist/export-DqbcbFU5.mjs +42 -0
  40. package/dist/export-DqbcbFU5.mjs.map +1 -0
  41. package/dist/external-M25AgDIE.d.mts +4277 -0
  42. package/dist/external-M25AgDIE.d.mts.map +1 -0
  43. package/dist/files-D6_euBBn.mjs +457 -0
  44. package/dist/files-D6_euBBn.mjs.map +1 -0
  45. package/dist/{generate-all-CIwP-3aa.mjs → generate-all-0YOnlZM0.mjs} +10 -5
  46. package/dist/generate-all-0YOnlZM0.mjs.map +1 -0
  47. package/dist/generate-app-hm6CJ_4O.mjs +72 -0
  48. package/dist/generate-app-hm6CJ_4O.mjs.map +1 -0
  49. package/dist/generate-desktop-shell-BovoRsR6.mjs +372 -0
  50. package/dist/generate-desktop-shell-BovoRsR6.mjs.map +1 -0
  51. package/dist/generate-document-model-BiD6ovXc.mjs +118 -0
  52. package/dist/generate-document-model-BiD6ovXc.mjs.map +1 -0
  53. package/dist/generate-editor-DBj_Pxwa.mjs +64 -0
  54. package/dist/generate-editor-DBj_Pxwa.mjs.map +1 -0
  55. package/dist/generate-hosts-BFmPIW2X.mjs +18 -0
  56. package/dist/generate-hosts-BFmPIW2X.mjs.map +1 -0
  57. package/dist/generate-hosts-RWj7WPHZ.mjs +4 -0
  58. package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
  59. package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
  60. package/dist/{generate-piece-QTt-ddt2.mjs → generate-piece-5Nyr2UZj.mjs} +18 -10
  61. package/dist/generate-piece-5Nyr2UZj.mjs.map +1 -0
  62. package/dist/{generate-piece-action-C5WTHsqu.mjs → generate-piece-action-DqR8BcoO.mjs} +10 -7
  63. package/dist/generate-piece-action-DqR8BcoO.mjs.map +1 -0
  64. package/dist/{generate-piece-trigger-DR10CPOG.mjs → generate-piece-trigger-CZaDD-cc.mjs} +8 -7
  65. package/dist/generate-piece-trigger-CZaDD-cc.mjs.map +1 -0
  66. package/dist/{generate-processor-DBtTkgo5.mjs → generate-processor-BVjOsfjJ.mjs} +20 -9
  67. package/dist/generate-processor-BVjOsfjJ.mjs.map +1 -0
  68. package/dist/generate-subgraph-DJZCr0Tk.mjs +86 -0
  69. package/dist/generate-subgraph-DJZCr0Tk.mjs.map +1 -0
  70. package/dist/get-version-ByaMbjqz.mjs +11 -0
  71. package/dist/get-version-ByaMbjqz.mjs.map +1 -0
  72. package/dist/index-H3AYe65i.d.mts +193 -0
  73. package/dist/index-H3AYe65i.d.mts.map +1 -0
  74. package/dist/{init-CIEMyAug.mjs → init-Ltg4cJzm.mjs} +29 -17
  75. package/dist/init-Ltg4cJzm.mjs.map +1 -0
  76. package/dist/inspect-CulIpVsF.mjs +52 -0
  77. package/dist/inspect-CulIpVsF.mjs.map +1 -0
  78. package/dist/{inspect-BpCB0TPo.mjs → inspect-zWJnBDMJ.mjs} +4 -4
  79. package/dist/{inspect-BpCB0TPo.mjs.map → inspect-zWJnBDMJ.mjs.map} +1 -1
  80. package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
  81. package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
  82. package/dist/keyframes-bFo9iDhT.mjs +201 -0
  83. package/dist/keyframes-bFo9iDhT.mjs.map +1 -0
  84. package/dist/mcp-VRTEA0Ib.mjs +263 -0
  85. package/dist/mcp-VRTEA0Ib.mjs.map +1 -0
  86. package/dist/migrate-BGFxHRgP.mjs +209 -0
  87. package/dist/migrate-BGFxHRgP.mjs.map +1 -0
  88. package/dist/migrate-document-models-CFNqYAgo.mjs +489 -0
  89. package/dist/migrate-document-models-CFNqYAgo.mjs.map +1 -0
  90. package/dist/migrate-subgraphs-BG-4KEzt.mjs +4 -0
  91. package/dist/migrate-subgraphs-CIksXwT7.mjs +710 -0
  92. package/dist/migrate-subgraphs-CIksXwT7.mjs.map +1 -0
  93. package/dist/module-dir-1avCXsBi.mjs +17 -0
  94. package/dist/module-dir-1avCXsBi.mjs.map +1 -0
  95. package/dist/npm-args-g1Tgel4s.mjs +78 -0
  96. package/dist/npm-args-g1Tgel4s.mjs.map +1 -0
  97. package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
  98. package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
  99. package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
  100. package/dist/ph-cli-commands-CcMT6rdd.mjs +4 -0
  101. package/dist/ph-cli-commands-Dy4vWwUm.mjs +1821 -0
  102. package/dist/ph-cli-commands-Dy4vWwUm.mjs.map +1 -0
  103. package/dist/render-3M3DwFzO.mjs +4 -0
  104. package/dist/render-SVfj3m8A.mjs +77 -0
  105. package/dist/render-SVfj3m8A.mjs.map +1 -0
  106. package/dist/run--de_-WAz.mjs +112 -0
  107. package/dist/run--de_-WAz.mjs.map +1 -0
  108. package/dist/run-LRGy7zGo.mjs +4 -0
  109. package/dist/run-sugar-DpznOP1e.mjs +56 -0
  110. package/dist/run-sugar-DpznOP1e.mjs.map +1 -0
  111. package/dist/runners/connect.d.mts +17 -0
  112. package/dist/runners/connect.d.mts.map +1 -0
  113. package/dist/runners/connect.mjs +83 -0
  114. package/dist/runners/connect.mjs.map +1 -0
  115. package/dist/runners/switchboard.d.mts +24 -0
  116. package/dist/runners/switchboard.d.mts.map +1 -0
  117. package/dist/runners/switchboard.mjs +178 -0
  118. package/dist/runners/switchboard.mjs.map +1 -0
  119. package/dist/schemas-DzgKfQIx.mjs +6024 -0
  120. package/dist/schemas-DzgKfQIx.mjs.map +1 -0
  121. package/dist/scripts/emit-runner-schemas.ts +24 -0
  122. package/dist/scripts/generate-commands-docs.ts +19 -0
  123. package/dist/scripts/manage-environment +0 -0
  124. package/dist/scripts/setup.sh +0 -0
  125. package/dist/subgraph-gate-BJ2PWXVY.mjs +26 -0
  126. package/dist/subgraph-gate-BJ2PWXVY.mjs.map +1 -0
  127. package/dist/subgraph-gate-j9ywj6KA.mjs +4 -0
  128. package/dist/subgraphs-7OYWwP-C.mjs +134 -0
  129. package/dist/subgraphs-7OYWwP-C.mjs.map +1 -0
  130. package/dist/{switchboard-migrate-7JQZM7-5.mjs → switchboard-migrate-BqSdKJ7u.mjs} +4 -5
  131. package/dist/switchboard-migrate-BqSdKJ7u.mjs.map +1 -0
  132. package/dist/switchboard-proxy-CGfMtENM.mjs +37 -0
  133. package/dist/switchboard-proxy-CGfMtENM.mjs.map +1 -0
  134. package/dist/{switchboard-reset-Ctegiqdm.mjs → switchboard-reset-MtTB_GAI.mjs} +8 -6
  135. package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
  136. package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
  137. package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
  138. package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
  139. package/dist/{utils-CvmDmCVd.mjs → utils-9KyRM0mf.mjs} +6 -34
  140. package/dist/{utils-CvmDmCVd.mjs.map → utils-9KyRM0mf.mjs.map} +1 -1
  141. package/dist/utils-TO9lB8Xs.mjs +4 -0
  142. package/dist/verify-D4V5VLnG.mjs +71 -0
  143. package/dist/verify-D4V5VLnG.mjs.map +1 -0
  144. package/dist/vetra-CVNZ46pK.mjs +352 -0
  145. package/dist/vetra-CVNZ46pK.mjs.map +1 -0
  146. package/dist/vetra-host-ChTpJiBJ.mjs +79 -0
  147. package/dist/vetra-host-ChTpJiBJ.mjs.map +1 -0
  148. package/dist/vetra-instance-CzhYIjxL.mjs +201 -0
  149. package/dist/vetra-instance-CzhYIjxL.mjs.map +1 -0
  150. package/dist/vetra-launch-qi10Unax.mjs +237 -0
  151. package/dist/vetra-launch-qi10Unax.mjs.map +1 -0
  152. package/dist/vetra-switchboard-BrkozIm7.mjs +4 -0
  153. package/dist/vetra-switchboard-tzdc14KA.mjs +230 -0
  154. package/dist/vetra-switchboard-tzdc14KA.mjs.map +1 -0
  155. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +19 -0
  156. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
  157. package/package.json +41 -15
  158. package/dist/build-CTvPQFMi.mjs +0 -4
  159. package/dist/build-sO3PcZxl.mjs +0 -166
  160. package/dist/build-sO3PcZxl.mjs.map +0 -1
  161. package/dist/cli-connect-override-b4kKqgOZ.mjs.map +0 -1
  162. package/dist/connect-build-BMaR9w4G.mjs +0 -153
  163. package/dist/connect-build-BMaR9w4G.mjs.map +0 -1
  164. package/dist/connect-preview-CzDqR-JN.mjs +0 -32
  165. package/dist/connect-preview-CzDqR-JN.mjs.map +0 -1
  166. package/dist/connect-studio-_-O1-oef.mjs +0 -36
  167. package/dist/connect-studio-_-O1-oef.mjs.map +0 -1
  168. package/dist/generate-all-CIwP-3aa.mjs.map +0 -1
  169. package/dist/generate-app-BTs1u-9l.mjs +0 -50
  170. package/dist/generate-app-BTs1u-9l.mjs.map +0 -1
  171. package/dist/generate-document-model-DhDQ_06X.mjs +0 -44
  172. package/dist/generate-document-model-DhDQ_06X.mjs.map +0 -1
  173. package/dist/generate-editor-CW7Do69u.mjs +0 -50
  174. package/dist/generate-editor-CW7Do69u.mjs.map +0 -1
  175. package/dist/generate-piece-QTt-ddt2.mjs.map +0 -1
  176. package/dist/generate-piece-action-C5WTHsqu.mjs.map +0 -1
  177. package/dist/generate-piece-trigger-DR10CPOG.mjs.map +0 -1
  178. package/dist/generate-processor-DBtTkgo5.mjs.map +0 -1
  179. package/dist/generate-subgraph-Dm27O59o.mjs +0 -42
  180. package/dist/generate-subgraph-Dm27O59o.mjs.map +0 -1
  181. package/dist/init-CIEMyAug.mjs.map +0 -1
  182. package/dist/install-added-dependencies-DVSbzler.mjs +0 -33
  183. package/dist/install-added-dependencies-DVSbzler.mjs.map +0 -1
  184. package/dist/migrate-B6QBYDNX.mjs +0 -83
  185. package/dist/migrate-B6QBYDNX.mjs.map +0 -1
  186. package/dist/switchboard-CgVB4U76.mjs +0 -87
  187. package/dist/switchboard-CgVB4U76.mjs.map +0 -1
  188. package/dist/switchboard-migrate-7JQZM7-5.mjs.map +0 -1
  189. package/dist/switchboard-nHCI3pha.mjs +0 -4
  190. package/dist/switchboard-reset-Ctegiqdm.mjs.map +0 -1
  191. package/dist/utils-C3c5YG6v.mjs +0 -4
  192. package/dist/vetra-s8gWslse.mjs +0 -627
  193. package/dist/vetra-s8gWslse.mjs.map +0 -1
@@ -0,0 +1,3067 @@
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]="e005b454-89ec-573f-8ea2-d302567bbd23")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-ByaMbjqz.mjs";
4
+ import { d as object, f as record, g as union, i as boolean, l as looseObject, m as string, r as array, s as json } from "./schemas-DzgKfQIx.mjs";
5
+ import { _ as pendingPrefix, a as writeReleaseApproval, c as PH_CLI_BINDING, d as listed, g as LOCK_FILE, h as BUILD_DIRECTORY, i as revisionFiles, l as RELEASE_APPROVAL_PATH, m as packageRevision, o as packRelease, p as changedPaths, s as packedDigests, t as packagePath, v as takeoverPrefix } from "./files-D6_euBBn.mjs";
6
+ import { n as OFFERED_ROUTES_MODULE, r as syncProjectConnectRoutes, t as HOST_ROUTES_DIR } from "./sync-connect-routes-t0Slg-P6.mjs";
7
+ import { r as noConnectImports } from "./offered-routes-imports-CalXK9dh.mjs";
8
+ import { createRequire } from "node:module";
9
+ import { accessSync, chmodSync, constants, cpSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
10
+ import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
+ import { execFileSync, execSync, fork, spawn } from "node:child_process";
12
+ import { SpawnError, spawnAsync } from "@powerhousedao/shared/clis";
13
+ import { createHash, randomBytes } from "node:crypto";
14
+ import { assertPiecesOutDir, buildPieces, createDetectionCache, expandEntryGlobs, externalDependencyVersions, externalDepsPlugin, pieceListPath, planPieces, projectPath, syncDistManifest, undeclaredExternalDependencies } from "@powerhousedao/shared/build-pieces";
15
+ import { detect, resolveCommand } from "package-manager-detector";
16
+ import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
17
+ import { hostname, tmpdir } from "node:os";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
+ import { satisfies } from "semver";
20
+ import { browserEntry, buildBrowserBuildConfig, buildNodeBuildConfig, findBundledSharedDeps } from "@powerhousedao/shared/build-config";
21
+ import { EXTERNALIZABLE_SHARED_SPECIFIERS, findSharedImports } from "@powerhousedao/shared/connect";
22
+ import { readPackage } from "read-pkg";
23
+ import { build, globalLogger } from "tsdown";
24
+ import { localPackageNames, packageStyleEntry, packageStylesheet } from "@powerhousedao/shared/clis/package-style";
25
+ import { nodeFileTrace } from "@vercel/nft";
26
+ //#region src/services/package-build/pipeline/steps.ts
27
+ /** A step's decision not to finish the build. The runner rolls back first. */
28
+ var BuildRefusal = class extends Error {
29
+ exitCode;
30
+ constructor(message, exitCode = 1) {
31
+ super(message);
32
+ this.name = "BuildRefusal";
33
+ this.exitCode = exitCode;
34
+ }
35
+ };
36
+ /** The process was told to stop while the build ran; it was rolled back. */
37
+ var BuildStopped = class extends Error {
38
+ signal;
39
+ constructor(signal) {
40
+ super(`The build was stopped by ${signal} before it finished.`);
41
+ this.name = "BuildStopped";
42
+ this.signal = signal;
43
+ }
44
+ };
45
+ function dependencies(steps) {
46
+ const ids = /* @__PURE__ */ new Set();
47
+ for (const { id } of steps) {
48
+ if (ids.has(id)) throw new Error(`Build step "${id}" is listed twice.`);
49
+ ids.add(id);
50
+ }
51
+ const committed = new Set(steps.filter(({ when }) => when === "committed").map(({ id }) => id));
52
+ const waits = /* @__PURE__ */ new Map();
53
+ steps.forEach((step, index) => {
54
+ const previous = steps.slice(0, index).findLast(({ when }) => when === step.when);
55
+ const after = step.after ?? (previous === void 0 ? [] : [previous.id]);
56
+ for (const id of after) {
57
+ if (!ids.has(id)) throw new Error(`Build step "${step.id}" runs after "${id}", which no step provides.`);
58
+ if (step.when !== "committed" && committed.has(id)) throw new Error(`Build step "${step.id}" runs before the output is replaced, so it cannot run after "${id}", which runs once it is.`);
59
+ }
60
+ waits.set(step.id, after);
61
+ });
62
+ return waits;
63
+ }
64
+ /**
65
+ * The order the steps run in: list order, with each step that names `after`
66
+ * placed right after the last step it waits for, and every `committed` step
67
+ * after every other. Throws on a duplicate id, an unknown `after` id, a step
68
+ * that waits on a later phase, or steps that wait on each other.
69
+ */
70
+ function orderBuildSteps(steps) {
71
+ const waits = dependencies(steps);
72
+ const placed = /* @__PURE__ */ new Set();
73
+ const ordered = [];
74
+ while (ordered.length < steps.length) {
75
+ const ready = steps.filter(({ id }) => !placed.has(id) && waits.get(id).every((wait) => placed.has(wait)));
76
+ if (ready.length === 0) {
77
+ const waiting = steps.filter(({ id }) => !placed.has(id)).map(({ id }) => `"${id}"`);
78
+ throw new Error(`Build steps ${waiting.join(", ")} wait on each other.`);
79
+ }
80
+ const phase = ready.some(({ when }) => when !== "committed") ? ready.filter(({ when }) => when !== "committed") : ready;
81
+ const next = phase.find((step) => step.after !== void 0) ?? phase[0];
82
+ placed.add(next.id);
83
+ ordered.push(next);
84
+ }
85
+ return ordered;
86
+ }
87
+ //#endregion
88
+ //#region src/services/package-build/pipeline/run-steps.ts
89
+ function throwIfStopped(session) {
90
+ const signal = session.stopped();
91
+ if (signal === void 0) return;
92
+ session.rollback();
93
+ throw new BuildStopped(signal);
94
+ }
95
+ /**
96
+ * Runs the steps in order, commits, then runs the `committed` steps. When a
97
+ * step before the commit throws, `rollback` runs before the error goes on to
98
+ * the caller, so nothing the build wrote outlives the failure. A committed
99
+ * step's throw goes to the caller with the new output in place. A stop is
100
+ * seen once the running step settles, and before each step and the commit:
101
+ * no step starts after it, and the rollback waits for the step it stopped.
102
+ */
103
+ async function runBuildSteps(steps, ctx, session) {
104
+ const ordered = orderBuildSteps(steps);
105
+ for (const step of ordered.filter(({ when }) => when !== "committed")) {
106
+ throwIfStopped(session);
107
+ try {
108
+ await step.run(ctx);
109
+ } catch (error) {
110
+ session.rollback();
111
+ throwIfStopped(session);
112
+ throw error;
113
+ }
114
+ }
115
+ throwIfStopped(session);
116
+ session.commit();
117
+ for (const step of ordered.filter(({ when }) => when === "committed")) {
118
+ throwIfStopped(session);
119
+ await step.run(ctx);
120
+ }
121
+ }
122
+ //#endregion
123
+ //#region src/services/package-build/staging/files.ts
124
+ function exists(path) {
125
+ return lstatSync(path, { throwIfNoEntry: false }) !== void 0;
126
+ }
127
+ /**
128
+ * Copies a file or a tree with its timestamps. A clone where the filesystem
129
+ * has them, a byte copy elsewhere; never a hard link, because later steps
130
+ * rewrite files in place.
131
+ */
132
+ function cloneTree(from, to, filter) {
133
+ cpSync(from, to, {
134
+ recursive: true,
135
+ mode: constants.COPYFILE_FICLONE,
136
+ preserveTimestamps: true,
137
+ verbatimSymlinks: true,
138
+ ...filter && { filter }
139
+ });
140
+ }
141
+ /**
142
+ * Mirrors a tree whose files the next step unlinks before it writes (tsdown
143
+ * cleans its output directory that way): each file is hard linked, so no
144
+ * byte is copied and nothing written later reaches `from`. A file that
145
+ * cannot be linked, and anything else, is copied.
146
+ */
147
+ function linkTree(from, to, filter) {
148
+ mkdirSync(to);
149
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
150
+ const source = join(from, entry.name);
151
+ if (!filter(source)) continue;
152
+ const target = join(to, entry.name);
153
+ if (entry.isDirectory()) {
154
+ linkTree(source, target, filter);
155
+ continue;
156
+ }
157
+ if (entry.isFile()) try {
158
+ linkSync(source, target);
159
+ continue;
160
+ } catch {}
161
+ cloneTree(source, target);
162
+ }
163
+ }
164
+ const OWNER_RWX = 448;
165
+ /**
166
+ * Gives every directory of the tree at `path` that lacks it owner read,
167
+ * write and search permission, which emptying it needs, and returns the
168
+ * modes it changed, parents first.
169
+ */
170
+ function openDirectories(path) {
171
+ const changed = [];
172
+ const visit = (dir, rel) => {
173
+ const stat = lstatSync(dir, { throwIfNoEntry: false });
174
+ if (!stat?.isDirectory()) return;
175
+ const mode = stat.mode & 4095;
176
+ if ((mode & OWNER_RWX) !== OWNER_RWX) {
177
+ chmodSync(dir, mode | OWNER_RWX);
178
+ changed.push([rel, mode]);
179
+ }
180
+ for (const entry of readdirSync(dir)) visit(join(dir, entry), rel === "" ? entry : `${rel}/${entry}`);
181
+ };
182
+ visit(path, "");
183
+ return changed;
184
+ }
185
+ /** Sets back the modes `openDirectories` changed, children first. */
186
+ function restoreDirectoryModes(path, modes) {
187
+ for (const [rel, mode] of [...modes].reverse()) chmodSync(rel === "" ? path : join(path, ...rel.split("/")), mode);
188
+ }
189
+ /**
190
+ * Removes a tree. A directory without owner write permission keeps its
191
+ * entries, so on failure each directory is opened and the removal tried
192
+ * once more.
193
+ */
194
+ function removeTree(path) {
195
+ const remove = () => rmSync(path, {
196
+ recursive: true,
197
+ force: true,
198
+ maxRetries: 10
199
+ });
200
+ try {
201
+ remove();
202
+ } catch (error) {
203
+ try {
204
+ openDirectories(path);
205
+ } catch {
206
+ throw error;
207
+ }
208
+ remove();
209
+ }
210
+ }
211
+ /**
212
+ * Makes `path` a copy of `from`. A directory that is there is emptied and
213
+ * refilled rather than removed, so a mount point or a directory another
214
+ * process holds stays where it is.
215
+ */
216
+ function replaceTree(from, path) {
217
+ if (!(lstatSync(path, { throwIfNoEntry: false })?.isDirectory() && lstatSync(from).isDirectory())) {
218
+ removeTree(path);
219
+ cloneTree(from, path);
220
+ return;
221
+ }
222
+ openDirectories(path);
223
+ for (const entry of readdirSync(path)) removeTree(join(path, entry));
224
+ cloneTree(from, path);
225
+ }
226
+ /**
227
+ * The tree by the bytes of its files and the targets of its links. Times
228
+ * and inodes are left out: a touch changes them, and a rewrite can keep them.
229
+ */
230
+ function treeFingerprint(root, skipped, unmarked = /* @__PURE__ */ new Set()) {
231
+ const hash = createHash("sha256");
232
+ const visit = (path, rel) => {
233
+ const stat = lstatSync(path);
234
+ if (stat.isFile()) {
235
+ const bytes = readFileSync(path);
236
+ hash.update(`f\0${rel}\0${bytes.length}\0`).update(bytes);
237
+ return;
238
+ }
239
+ if (stat.isSymbolicLink()) {
240
+ hash.update(`l\0${rel}\0${readlinkSync(path)}\0`);
241
+ return;
242
+ }
243
+ if (!stat.isDirectory()) {
244
+ hash.update(`o\0${rel}\0`);
245
+ return;
246
+ }
247
+ if (rel !== "" && !unmarked.has(rel)) hash.update(`d\0${rel}\0`);
248
+ for (const entry of readdirSync(path).sort()) {
249
+ const child = rel === "" ? entry : `${rel}/${entry}`;
250
+ if (!skipped.has(child)) visit(join(path, entry), child);
251
+ }
252
+ };
253
+ if (exists(root)) visit(root, "");
254
+ return hash.digest("hex");
255
+ }
256
+ /**
257
+ * The first entry of the tree at `path`, itself included, that the stage
258
+ * cannot copy as it is, and why: a FIFO, socket or device, which a copy
259
+ * cannot represent, or a file or directory this process cannot read. Only
260
+ * permissions are checked; no file is read. Entries `filter` rejects, and
261
+ * what they hold, are not looked at.
262
+ */
263
+ function unstageableEntryIn(path, filter = () => true) {
264
+ const visit = (path, stat) => {
265
+ if (stat.isSymbolicLink()) return;
266
+ if (!stat.isFile() && !stat.isDirectory()) return {
267
+ path,
268
+ reason: "is not a file, directory or symbolic link"
269
+ };
270
+ const mode = stat.isDirectory() ? constants.R_OK | constants.X_OK : constants.R_OK;
271
+ try {
272
+ accessSync(path, mode);
273
+ } catch {
274
+ return {
275
+ path,
276
+ reason: "cannot be read"
277
+ };
278
+ }
279
+ if (!stat.isDirectory()) return;
280
+ for (const entry of readdirSync(path)) {
281
+ const child = join(path, entry);
282
+ if (!filter(child)) continue;
283
+ const found = visit(child, lstatSync(child));
284
+ if (found) return found;
285
+ }
286
+ };
287
+ const stat = lstatSync(path, { throwIfNoEntry: false });
288
+ return stat && visit(path, stat);
289
+ }
290
+ function entriesOf(dir) {
291
+ return exists(dir) ? readdirSync(dir) : [];
292
+ }
293
+ const blocker = new Int32Array(new SharedArrayBuffer(4));
294
+ /** Waits without returning to the event loop, so no signal handler runs meanwhile. */
295
+ function sleepSync(ms) {
296
+ Atomics.wait(blocker, 0, 0, ms);
297
+ }
298
+ /** Windows refuses to rename a directory while another process holds a file in it. */
299
+ function isHeldOpen(error) {
300
+ const code = error?.code;
301
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
302
+ }
303
+ const RENAME_PATIENCE_MS = 2e3;
304
+ /** `rename`, retried with backoff for about two seconds while the path is held open. */
305
+ function renamePatiently(from, to, patienceMs = RENAME_PATIENCE_MS) {
306
+ const deadline = Date.now() + patienceMs;
307
+ for (let wait = 20;; wait = Math.min(wait * 2, 400)) try {
308
+ renameSync(from, to);
309
+ return;
310
+ } catch (error) {
311
+ if (!isHeldOpen(error) || Date.now() + wait > deadline) throw error;
312
+ sleepSync(wait);
313
+ }
314
+ }
315
+ /** Moves each entry of `from` into `to`, replacing what `to` holds under that name. */
316
+ function moveEntries(from, to) {
317
+ for (const entry of entriesOf(from)) {
318
+ const target = join(to, entry);
319
+ if (exists(target)) removeTree(target);
320
+ renamePatiently(join(from, entry), target);
321
+ }
322
+ }
323
+ /** Staging cannot run where the build would write; `message` says why. */
324
+ var CannotStage = class extends Error {};
325
+ const CANNOT_WRITE = /* @__PURE__ */ new Set([
326
+ "ENOTDIR",
327
+ "EACCES",
328
+ "EPERM",
329
+ "EROFS",
330
+ "ENOTSUP",
331
+ "EOPNOTSUPP"
332
+ ]);
333
+ /** Runs `create`, turning a refusal to write `where` into `CannotStage`. */
334
+ async function creating(where, create) {
335
+ try {
336
+ return await create();
337
+ } catch (error) {
338
+ const code = error?.code;
339
+ if (typeof code === "string" && CANNOT_WRITE.has(code)) throw new CannotStage(`${where} cannot be written (${code})`);
340
+ throw error;
341
+ }
342
+ }
343
+ //#endregion
344
+ //#region src/services/package-build/staging/journal.ts
345
+ const RUNS_DIRECTORY = join(BUILD_DIRECTORY, "runs");
346
+ const JOURNAL_FILE = "journal.json";
347
+ /**
348
+ * The steps of a rollback, in order, each safe to repeat:
349
+ * - install: the output loses what the stage put in it.
350
+ * - retire: the retired tree, or its entries, goes back into the output.
351
+ * - stage: the stage goes and the compiler outputs come back.
352
+ */
353
+ const UNDO_STEPS = [
354
+ "install",
355
+ "retire",
356
+ "stage"
357
+ ];
358
+ const STATES = [
359
+ "building",
360
+ "retiring",
361
+ "installing",
362
+ "rolling-back",
363
+ "committed"
364
+ ];
365
+ /**
366
+ * A path inside `from` is recorded relative, in POSIX form. Any other path
367
+ * is recorded absolute and comes back unchanged: a relative spelling of
368
+ * another drive or a UNC share does not resolve back to it on Windows.
369
+ */
370
+ function toJournalPath(from, to, paths = path) {
371
+ const rel = paths.relative(from, to);
372
+ if (paths.isAbsolute(rel) || rel === ".." || rel.startsWith(`..${paths.sep}`)) return paths.resolve(to);
373
+ return rel.split(paths.sep).join("/");
374
+ }
375
+ function fromJournalPath(from, recorded, paths = path) {
376
+ return paths.isAbsolute(recorded) ? recorded : paths.resolve(from, recorded);
377
+ }
378
+ function journalPath(runDir) {
379
+ return join(runDir, JOURNAL_FILE);
380
+ }
381
+ /**
382
+ * Replaces the journal in one rename, so a reader sees the old state or the
383
+ * new. Patiently: on Windows a scanner that still holds the journal it just
384
+ * saw written fails the rename with EPERM.
385
+ */
386
+ function writeJournal(runDir, journal) {
387
+ const file = journalPath(runDir);
388
+ const pending = `${file}.${process.pid}.tmp`;
389
+ writeFileSync(pending, `${JSON.stringify(journal, null, 2)}\n`);
390
+ renamePatiently(pending, file);
391
+ }
392
+ const isString = (value) => typeof value === "string" && value !== "";
393
+ function parseSnapshot(value) {
394
+ if (typeof value !== "object" || value === null) return void 0;
395
+ const { path, kind, copy, created } = value;
396
+ if (!isString(path) || kind !== "directory" && kind !== "build-info" && kind !== "file") return;
397
+ if (copy !== null && !isString(copy)) return void 0;
398
+ if (created !== null && !isString(created)) return void 0;
399
+ const { modes } = value;
400
+ if (modes === void 0) return {
401
+ path,
402
+ kind,
403
+ copy,
404
+ created
405
+ };
406
+ if (!Array.isArray(modes) || !modes.every(isDirectoryMode)) return void 0;
407
+ return {
408
+ path,
409
+ kind,
410
+ copy,
411
+ created,
412
+ modes
413
+ };
414
+ }
415
+ function parsePendingBuildInfo(value) {
416
+ if (value === void 0) return void 0;
417
+ if (typeof value !== "object" || value === null) return null;
418
+ const { path, target } = value;
419
+ return isString(path) && isString(target) ? {
420
+ path,
421
+ target
422
+ } : null;
423
+ }
424
+ const isDirectoryMode = (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && Number.isInteger(value[1]);
425
+ /** The journal of a run directory, or undefined when it is missing or unreadable. */
426
+ function readJournal(runDir) {
427
+ let value;
428
+ try {
429
+ value = JSON.parse(readFileSync(journalPath(runDir), "utf8"));
430
+ } catch {
431
+ return;
432
+ }
433
+ if (typeof value !== "object" || value === null) return void 0;
434
+ const record = value;
435
+ if (record.format !== 1 || !isString(record.runId) || typeof record.pid !== "number" || !STATES.includes(record.state) || !isString(record.output) || !isString(record.stage) || !isString(record.retired)) return;
436
+ const optional = (key) => record[key] === void 0 || isString(record[key]);
437
+ if (!optional("generatedConfig") || !optional("outputDigest")) return void 0;
438
+ const pending = parsePendingBuildInfo(record.pendingBuildInfo);
439
+ if (pending === null) return void 0;
440
+ const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;
441
+ if (record.state === "rolling-back" !== (undo !== null)) return void 0;
442
+ let compiler = null;
443
+ if (Array.isArray(record.compiler)) {
444
+ compiler = [];
445
+ for (const entry of record.compiler) {
446
+ const snapshot = parseSnapshot(entry);
447
+ if (snapshot === void 0) return void 0;
448
+ compiler.push(snapshot);
449
+ }
450
+ } else if (record.compiler !== null) return;
451
+ return {
452
+ format: 1,
453
+ runId: record.runId,
454
+ pid: record.pid,
455
+ state: record.state,
456
+ undo,
457
+ output: record.output,
458
+ stage: record.stage,
459
+ retired: record.retired,
460
+ compiler,
461
+ ...isString(record.generatedConfig) && { generatedConfig: record.generatedConfig },
462
+ ...pending !== void 0 && { pendingBuildInfo: pending },
463
+ ...isString(record.outputDigest) && { outputDigest: record.outputDigest }
464
+ };
465
+ }
466
+ //#endregion
467
+ //#region src/services/package-build/staging/boot-id.ts
468
+ function readBootId() {
469
+ try {
470
+ return (process.platform === "linux" ? readFileSync("/proc/sys/kernel/random/boot_id", "utf8") : process.platform === "darwin" ? execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
471
+ encoding: "utf8",
472
+ stdio: [
473
+ "ignore",
474
+ "pipe",
475
+ "ignore"
476
+ ]
477
+ }) : "").trim() || null;
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+ let memo;
483
+ /**
484
+ * This boot of the machine, as the OS names it, or null where it cannot be
485
+ * read. Unlike a boot time derived from the clock, it changes only with a
486
+ * reboot.
487
+ */
488
+ function currentBootId() {
489
+ if (memo === void 0) memo = readBootId();
490
+ return memo;
491
+ }
492
+ //#endregion
493
+ //#region src/services/package-build/staging/lock.ts
494
+ const POLL_MS = 100;
495
+ const TAKEOVER_RETRY_MS = 10;
496
+ const QUIET_TAKEOVER_WAIT_MS = 1e3;
497
+ function isOwner(value) {
498
+ const owner = value;
499
+ return typeof owner?.pid === "number" && typeof owner.runId === "string" && typeof owner.host === "string" && (typeof owner.bootId === "string" || owner.bootId === null);
500
+ }
501
+ /**
502
+ * The owner's process is gone: on this machine, it ran in another boot (so
503
+ * the reboot ended it), or no process is left at its pid. Another host, or a
504
+ * live pid in this boot or an unknown one, is not proof: such an owner may
505
+ * still be building. A pid reused by another process of this boot reads as
506
+ * live, so its lock waits until someone deletes it.
507
+ */
508
+ const provenDead = (owner) => {
509
+ if (owner.host !== hostname()) return false;
510
+ const boot = currentBootId();
511
+ if (owner.bootId !== null && boot !== null && owner.bootId !== boot) return true;
512
+ return !isProcessAlive(owner.pid);
513
+ };
514
+ const errorCode = (error) => error.code;
515
+ function isProcessAlive(pid) {
516
+ try {
517
+ process.kill(pid, 0);
518
+ return true;
519
+ } catch (error) {
520
+ return errorCode(error) === "EPERM";
521
+ }
522
+ }
523
+ /** What a waiting build says about who holds a lock or takeover file. */
524
+ function described(value) {
525
+ const fields = value;
526
+ const parts = [
527
+ ["host", fields?.host],
528
+ ["pid", fields?.pid],
529
+ ["run", fields?.runId]
530
+ ].flatMap(([name, field]) => typeof field === "string" || typeof field === "number" ? [`${name} ${field}`] : []);
531
+ return parts.length > 0 ? parts.join(", ") : "owner unknown";
532
+ }
533
+ function holderOf(file) {
534
+ let value;
535
+ try {
536
+ value = JSON.parse(readFileSync(file, "utf8"));
537
+ } catch (error) {
538
+ if (errorCode(error) === "ENOENT") return void 0;
539
+ }
540
+ if (isOwner(value)) return {
541
+ id: value.runId,
542
+ dead: provenDead(value),
543
+ owner: described(value)
544
+ };
545
+ const stat = lstatSync(file, { throwIfNoEntry: false });
546
+ return stat && {
547
+ id: `file ${stat.ino} ${stat.mtimeMs}`,
548
+ dead: false,
549
+ owner: described(value)
550
+ };
551
+ }
552
+ /**
553
+ * Creates `file` holding `owner`, or returns false when it exists. The file
554
+ * appears with its content in one link, so no reader sees it empty.
555
+ */
556
+ function createOwned(file, owner) {
557
+ const pending = join(dirname(file), `${pendingPrefix(basename(file))}${owner.runId}.pending`);
558
+ writeFileSync(pending, JSON.stringify(owner));
559
+ try {
560
+ linkSync(pending, file);
561
+ return true;
562
+ } catch (error) {
563
+ if (errorCode(error) === "EEXIST") return false;
564
+ throw error;
565
+ } finally {
566
+ rmSync(pending, { force: true });
567
+ }
568
+ }
569
+ const takeoverFile = (lockFile, staleId) => join(dirname(lockFile), `${takeoverPrefix(basename(lockFile))}${encodeURIComponent(staleId)}`);
570
+ /**
571
+ * Removes `file` while it still holds the dead holder `stale`. Only the
572
+ * creator of the takeover file keyed to `stale` may remove it, and `stale`
573
+ * cannot come back, so the owner read under that file is the one removed: a
574
+ * contender that judged it stale before someone else took over removes
575
+ * nothing. A takeover file is itself taken over only from a holder proven
576
+ * dead, never for its age, so a paused holder keeps it. Returns what blocks
577
+ * the takeover, or nothing when the caller should try again.
578
+ */
579
+ function takeOver(lockFile, file, stale, me) {
580
+ const guard = takeoverFile(lockFile, stale.id);
581
+ if (!createOwned(guard, me)) {
582
+ const holder = holderOf(guard);
583
+ if (holder === void 0) return void 0;
584
+ return holder.dead ? takeOver(lockFile, guard, holder, me) : {
585
+ file: guard,
586
+ holder
587
+ };
588
+ }
589
+ try {
590
+ if (holderOf(file)?.id === stale.id) removeTree(file);
591
+ return;
592
+ } finally {
593
+ if (holderOf(guard)?.id === me.runId) rmSync(guard, { force: true });
594
+ }
595
+ }
596
+ /**
597
+ * Takeover files left by contenders that died. Safe under the lock: one
598
+ * matters only while the lock holds its stale owner, and the lock is ours.
599
+ * A pending file goes only when its writer is proven dead: a live
600
+ * contender links it next.
601
+ */
602
+ function removeTakeoverFiles(lockFile) {
603
+ const takeover = takeoverPrefix(basename(lockFile));
604
+ const pending = pendingPrefix(basename(lockFile));
605
+ for (const entry of readdirSync(dirname(lockFile))) {
606
+ const file = join(dirname(lockFile), entry);
607
+ if (entry.startsWith(takeover) || entry.startsWith(pending) && entry.endsWith(".pending") && holderOf(file)?.dead === true) rmSync(file, { force: true });
608
+ }
609
+ }
610
+ /**
611
+ * Takes `.ph/build/lock`, a file created exclusively that names this run.
612
+ * A lock is taken over only from an owner proven dead (see `provenDead`);
613
+ * otherwise this waits, and says once per holder which file it waits for.
614
+ */
615
+ async function acquireBuildLock(lockFile, runId, onWait) {
616
+ mkdirSync(dirname(lockFile), { recursive: true });
617
+ const me = {
618
+ pid: process.pid,
619
+ runId,
620
+ host: hostname(),
621
+ bootId: currentBootId()
622
+ };
623
+ const told = /* @__PURE__ */ new Set();
624
+ const firstBlocked = /* @__PURE__ */ new Map();
625
+ for (;;) {
626
+ if (createOwned(lockFile, me)) {
627
+ removeTakeoverFiles(lockFile);
628
+ let held = true;
629
+ return { release: () => {
630
+ if (!held) return;
631
+ held = false;
632
+ if (holderOf(lockFile)?.id === runId) rmSync(lockFile);
633
+ } };
634
+ }
635
+ const holder = holderOf(lockFile);
636
+ if (holder === void 0) continue;
637
+ const blocked = holder.dead ? takeOver(lockFile, lockFile, holder, me) : {
638
+ file: lockFile,
639
+ holder
640
+ };
641
+ if (blocked === void 0) {
642
+ await setTimeout$1(TAKEOVER_RETRY_MS);
643
+ continue;
644
+ }
645
+ const key = `${blocked.file}\0${blocked.holder.id}`;
646
+ const since = firstBlocked.get(key) ?? Date.now();
647
+ firstBlocked.set(key, since);
648
+ if (!(blocked.file !== lockFile && Date.now() - since < QUIET_TAKEOVER_WAIT_MS) && !told.has(key)) {
649
+ told.add(key);
650
+ onWait({
651
+ file: blocked.file,
652
+ owner: blocked.holder.owner
653
+ });
654
+ }
655
+ await setTimeout$1(blocked.file === lockFile ? POLL_MS : TAKEOVER_RETRY_MS);
656
+ }
657
+ }
658
+ //#endregion
659
+ //#region src/services/definitions/paths.ts
660
+ function toPosixPath(path) {
661
+ return path.split(sep).join("/");
662
+ }
663
+ function canonicalConfigFile(configFile) {
664
+ const absolute = resolve(configFile);
665
+ return join(realPathThroughExistingParent(dirname(absolute)), basename(absolute));
666
+ }
667
+ //#endregion
668
+ //#region src/services/package-build/staging/recovery.ts
669
+ function runPaths(packageRoot, runDir, journal) {
670
+ return {
671
+ packageRoot,
672
+ runDir,
673
+ output: fromJournalPath(packageRoot, journal.output),
674
+ stage: fromJournalPath(packageRoot, journal.stage),
675
+ retired: fromJournalPath(packageRoot, journal.retired)
676
+ };
677
+ }
678
+ function outputDigest(packageRoot, output, compiler) {
679
+ const real = realPathThroughExistingParent(output);
680
+ const inOutput = (recorded) => {
681
+ const rel = pathWithin(real, fromJournalPath(packageRoot, recorded));
682
+ return rel === null ? null : toPosixPath(rel);
683
+ };
684
+ const skipped = /* @__PURE__ */ new Set();
685
+ const unmarked = /* @__PURE__ */ new Set();
686
+ for (const { path, created } of compiler) {
687
+ if (pathWithin(fromJournalPath(packageRoot, path), real) !== null) return;
688
+ const rel = inOutput(path);
689
+ if (rel === null) continue;
690
+ skipped.add(rel);
691
+ if (created !== null) {
692
+ const parts = rel.split("/");
693
+ const createdRel = inOutput(created);
694
+ const first = createdRel ? createdRel.split("/").length : 1;
695
+ for (let length = first; length < parts.length; length++) unmarked.add(parts.slice(0, length).join("/"));
696
+ }
697
+ }
698
+ return treeFingerprint(output, skipped, unmarked);
699
+ }
700
+ function removeScratch(packageRoot, journal) {
701
+ for (const recorded of [journal.generatedConfig, journal.pendingBuildInfo?.path]) if (recorded !== void 0) removeTree(fromJournalPath(packageRoot, recorded));
702
+ }
703
+ function installBuildInfo(packageRoot, pending) {
704
+ if (pending === void 0) return;
705
+ const path = fromJournalPath(packageRoot, pending.path);
706
+ if (exists(path)) renamePatiently(path, fromJournalPath(packageRoot, pending.target));
707
+ }
708
+ /** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */
709
+ function moveTree(from, to) {
710
+ try {
711
+ renamePatiently(from, to);
712
+ return "renamed";
713
+ } catch (error) {
714
+ if (!isHeldOpen(error)) throw error;
715
+ mkdirSync(to, { recursive: true });
716
+ moveEntries(from, to);
717
+ removeTree(from);
718
+ return "entries";
719
+ }
720
+ }
721
+ /** Build info first: if a later copy fails, tsc still sees its outputs as stale. */
722
+ function restoreCompilerOutputs(paths, snapshots) {
723
+ const ordered = [...snapshots ?? []].sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info"));
724
+ for (const snapshot of ordered) {
725
+ const path = fromJournalPath(paths.packageRoot, snapshot.path);
726
+ if (snapshot.copy !== null) {
727
+ replaceTree(fromJournalPath(paths.runDir, snapshot.copy), path);
728
+ restoreDirectoryModes(path, snapshot.modes ?? []);
729
+ continue;
730
+ }
731
+ removeTree(path);
732
+ if (snapshot.created !== null) removeEmptyDirectories(dirname(path), fromJournalPath(paths.packageRoot, snapshot.created));
733
+ }
734
+ }
735
+ /** Removes `from` and its parents up to `upTo` while each is an empty directory. */
736
+ function removeEmptyDirectories(from, upTo) {
737
+ for (let dir = from;; dir = dirname(dir)) {
738
+ if (!exists(dir) || entriesOf(dir).length > 0) return;
739
+ rmdirSync(dir);
740
+ if (dir === upTo || dirname(dir) === dir) return;
741
+ }
742
+ }
743
+ const FIRST_UNDO_STEP = {
744
+ building: "stage",
745
+ retiring: "retire",
746
+ installing: "install"
747
+ };
748
+ /**
749
+ * Undoes a run: the previous output goes back in place, the stage goes, and
750
+ * the compiler outputs are restored, unless a later build replaced the output
751
+ * since they were saved (`superseded`). The journal records each step before
752
+ * it starts, so a rollback cut short is finished by the next build, never
753
+ * rolled forward; the run directory, and the snapshot in it, stay until the
754
+ * caller removes them.
755
+ */
756
+ function rollBack(paths, journal) {
757
+ if (journal.state === "committed") return "restored";
758
+ const first = journal.state === "rolling-back" ? journal.undo ?? "stage" : FIRST_UNDO_STEP[journal.state];
759
+ const { output, retired } = paths;
760
+ for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {
761
+ writeJournal(paths.runDir, {
762
+ ...journal,
763
+ state: "rolling-back",
764
+ undo: step
765
+ });
766
+ if (step === "install") {
767
+ if (!exists(retired)) removeTree(output);
768
+ else for (const entry of entriesOf(output)) removeTree(join(output, entry));
769
+ } else if (step === "retire") {
770
+ if (exists(retired)) {
771
+ if (exists(output)) moveEntries(retired, output);
772
+ else moveTree(retired, output);
773
+ }
774
+ } else {
775
+ removeTree(paths.stage);
776
+ removeTree(retired);
777
+ removeScratch(paths.packageRoot, journal);
778
+ const digest = journal.outputDigest === void 0 ? void 0 : outputDigest(paths.packageRoot, output, journal.compiler ?? []);
779
+ if (digest !== void 0 && digest !== journal.outputDigest) return "superseded";
780
+ restoreCompilerOutputs(paths, journal.compiler);
781
+ }
782
+ }
783
+ return "restored";
784
+ }
785
+ /** Finishes a run that was installing its stage: the stage becomes the output. */
786
+ function rollForward(paths, journal) {
787
+ const { output, stage } = paths;
788
+ if (exists(stage)) {
789
+ if (exists(output)) moveEntries(stage, output);
790
+ else moveTree(stage, output);
791
+ }
792
+ installBuildInfo(paths.packageRoot, journal.pendingBuildInfo);
793
+ removeTree(stage);
794
+ removeTree(paths.retired);
795
+ removeScratch(paths.packageRoot, journal);
796
+ }
797
+ /**
798
+ * Brings the package back to a consistent state after a run that died, then
799
+ * removes its run directory. A run that had not started to install its stage,
800
+ * or had started to roll back, is undone; one installing its stage is
801
+ * finished.
802
+ */
803
+ function replayRun(packageRoot, runDir) {
804
+ const journal = readJournal(runDir);
805
+ let replayed = "discarded";
806
+ if (journal !== void 0) {
807
+ const paths = runPaths(packageRoot, runDir, journal);
808
+ if (journal.state !== "installing" && journal.state !== "committed") replayed = rollBack(paths, journal) === "superseded" ? "superseded" : "rolled-back";
809
+ else {
810
+ rollForward(paths, journal);
811
+ replayed = "completed";
812
+ }
813
+ }
814
+ removeTree(runDir);
815
+ return replayed;
816
+ }
817
+ /** A run's stage and retired tree beside the output named `output`. */
818
+ const isScratchOf = (output, entry) => entry.startsWith(`.${output}.ph-stage-`) || entry.startsWith(`.${output}.ph-old-`);
819
+ /**
820
+ * Undoes or finishes every run a dead build left behind, then removes any
821
+ * stage or retired tree beside `output` that no run claims any more: a
822
+ * bundler of a stopped build can go on writing after its rollback. Call
823
+ * under the lock, where no other run of this package is live.
824
+ */
825
+ function recoverStaleRuns(packageRoot, output) {
826
+ const runsDir = join(packageRoot, RUNS_DIRECTORY);
827
+ for (const runId of entriesOf(runsDir)) {
828
+ const replayed = replayRun(packageRoot, join(runsDir, runId));
829
+ if (replayed === "rolled-back") console.warn("⚠ An earlier build of this package stopped before it finished; its partial output was removed and the previous output restored.");
830
+ else if (replayed === "superseded") console.warn(`⚠ An earlier build of this package stopped before it finished, and a build that wrote ${toJournalPath(packageRoot, output) || "the package root"} in place ran after it; the earlier build's partial output was removed and the newer files were kept.`);
831
+ else if (replayed === "completed") console.warn("⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.");
832
+ }
833
+ const beside = dirname(output);
834
+ for (const entry of entriesOf(beside)) if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));
835
+ }
836
+ //#endregion
837
+ //#region src/services/compiler-output/emit.ts
838
+ const withoutExtension = (path) => path.replace(/\.[^./\\]+$/, "");
839
+ const declares = (options) => options.declaration === true || options.composite === true;
840
+ /**
841
+ * Where tsc keeps the build info of `configFile`, by TypeScript's rule:
842
+ * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the
843
+ * config's place relative to `rootDir` when that is set; else beside the
844
+ * config.
845
+ */
846
+ function buildInfoFile(options, configFile) {
847
+ const configDir = dirname(configFile);
848
+ const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;
849
+ if (options.tsBuildInfoFile !== void 0) return resolve(configDir, options.tsBuildInfoFile);
850
+ if (options.outFile !== void 0) return resolve(configDir, `${withoutExtension(options.outFile)}.tsbuildinfo`);
851
+ if (options.outDir === void 0) return resolve(configDir, name);
852
+ const fromRoot = options.rootDir === void 0 ? "" : relative(resolve(configDir, options.rootDir), configDir);
853
+ return resolve(configDir, options.outDir, fromRoot, name);
854
+ }
855
+ /**
856
+ * The files tsc writes for `outFile`: the bundle and its map unless it
857
+ * emits declarations only, then the declaration and its map when it
858
+ * declares. None without `outFile` or with `noEmit`.
859
+ */
860
+ function outFileOutputs(options, configFile) {
861
+ if (options.outFile === void 0 || options.noEmit) return [];
862
+ const output = resolve(dirname(configFile), options.outFile);
863
+ const files = [];
864
+ if (!options.emitDeclarationOnly) files.push(output, ...options.sourceMap ? [`${output}.map`] : []);
865
+ if (declares(options)) {
866
+ const declaration = `${withoutExtension(output)}.d.ts`;
867
+ files.push(declaration, ...options.declarationMap ? [`${declaration}.map`] : []);
868
+ }
869
+ return files;
870
+ }
871
+ /** The declaration and output directories the options name, resolved. */
872
+ function outputDirectories$1(options, configDir) {
873
+ return [options.declarationDir, options.outDir].filter((dir) => dir !== void 0).map((dir) => resolve(configDir, dir));
874
+ }
875
+ /** Where tsc writes declarations, when it writes them to a directory of their own. */
876
+ function declarationDirectory(options, configDir) {
877
+ const dir = options.declarationDir ?? options.outDir;
878
+ if (!dir || !declares(options)) return void 0;
879
+ return resolve(configDir, dir);
880
+ }
881
+ //#endregion
882
+ //#region src/services/definitions/config-inputs.ts
883
+ const configSchema$1 = object({
884
+ extends: union([string(), array(string())]).optional(),
885
+ compilerOptions: record(string(), json()).optional()
886
+ });
887
+ function readConfig(path) {
888
+ const text = readFileSync(path, "utf8").replace(/^\uFEFF/, "").replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, (token) => token.startsWith("\"") ? token : "").replace(/"(?:\\.|[^"\\])*"|,\s*(?=[}\]])/g, (token) => token.startsWith("\"") ? token : "");
889
+ return JSON.parse(text);
890
+ }
891
+ const manifestSchema = object({
892
+ tsconfig: string().optional(),
893
+ exports: json().optional(),
894
+ typesVersions: record(string(), record(string(), array(string()))).optional()
895
+ });
896
+ function configDirOptions(configFile, compilerVersion) {
897
+ const visiting = /* @__PURE__ */ new Set();
898
+ const options = (path) => {
899
+ if (visiting.has(path)) return {};
900
+ visiting.add(path);
901
+ const config = configSchema$1.parse(readConfig(path));
902
+ const bases = typeof config.extends === "string" ? [config.extends] : config.extends ?? [];
903
+ const inherited = {};
904
+ for (const base of bases) Object.assign(inherited, options(extendedConfig(path, base, compilerVersion)));
905
+ visiting.delete(path);
906
+ return {
907
+ ...inherited,
908
+ ...config.compilerOptions
909
+ };
910
+ };
911
+ const substitute = (value) => {
912
+ if (typeof value === "string") return value.replaceAll("${configDir}", dirname(configFile));
913
+ if (Array.isArray(value)) return value.map(substitute);
914
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitute(entry)]));
915
+ return value;
916
+ };
917
+ return Object.fromEntries(Object.entries(options(configFile)).filter(([, value]) => JSON.stringify(value).includes("${configDir}")).map(([key, value]) => [key, substitute(value)]));
918
+ }
919
+ function file(path) {
920
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
921
+ }
922
+ function jsonFile(path) {
923
+ if (path.endsWith(".json")) return file(path);
924
+ return file(`${path.replace(/\.(?:js|ts)$/, "")}.json`) ?? file(`${path}.json`);
925
+ }
926
+ function matchedPath(paths, name, exports = false) {
927
+ if (Object.hasOwn(paths, name)) return {
928
+ key: name,
929
+ match: ""
930
+ };
931
+ const keys = Object.keys(paths).filter((key) => key.includes("*") && key.indexOf("*") === key.lastIndexOf("*") || exports && key.endsWith("/"));
932
+ keys.sort((a, b) => {
933
+ const prefix = (key) => key.includes("*") ? key.indexOf("*") + 1 : key.length;
934
+ return prefix(b) - prefix(a) || (exports ? Number(!a.includes("*")) - Number(!b.includes("*")) || b.length - a.length : 0);
935
+ });
936
+ for (const key of keys) {
937
+ const star = key.indexOf("*");
938
+ if (star !== -1 && name.startsWith(key.slice(0, star)) && name.endsWith(key.slice(star + 1))) return {
939
+ key,
940
+ match: name.slice(star, name.length - (key.length - star - 1))
941
+ };
942
+ if (star === -1 && name.startsWith(key)) return {
943
+ key,
944
+ match: name.slice(key.length)
945
+ };
946
+ }
947
+ }
948
+ function exportedConfig(target, directory, compilerVersion, match, pattern) {
949
+ if (typeof target === "string") {
950
+ if (!target.startsWith("./") || !pattern && match !== "" && !target.endsWith("/")) return {};
951
+ const path = pattern ? target.replaceAll("*", match) : target + match;
952
+ if (path.slice(2).split("/").some((part) => part === "." || part === ".." || part === "node_modules")) return {};
953
+ const resolved = jsonFile(resolve(directory, path));
954
+ return resolved === void 0 ? {} : { path: resolved };
955
+ }
956
+ if (target === null) return {};
957
+ if (Array.isArray(target)) {
958
+ if (target.length === 0) return {};
959
+ for (const entry of target) {
960
+ const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
961
+ if (result !== void 0) return result;
962
+ }
963
+ } else if (typeof target === "object") {
964
+ for (const [condition, entry] of Object.entries(target)) if ([
965
+ "types",
966
+ "require",
967
+ "node",
968
+ "default"
969
+ ].includes(condition) || condition.startsWith("types@") && satisfies(compilerVersion, condition.slice(6))) {
970
+ const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
971
+ if (result !== void 0) return result;
972
+ }
973
+ } else return {};
974
+ }
975
+ function extendedConfig(configFile, input, compilerVersion) {
976
+ const specifier = input.replaceAll("\\", "/");
977
+ if (specifier.startsWith("./") || specifier.startsWith("../") || isAbsolute(specifier)) {
978
+ const path = resolve(dirname(configFile), specifier);
979
+ const found = file(path) ?? (!path.endsWith(".json") ? file(`${path}.json`) : void 0);
980
+ if (found !== void 0) return found;
981
+ } else {
982
+ const parts = specifier.split("/");
983
+ const nameLength = specifier.startsWith("@") ? 2 : 1;
984
+ const packageName = parts.slice(0, nameLength).join("/");
985
+ const subpath = parts.slice(nameLength).join("/");
986
+ const manifestAt = (directory) => {
987
+ const path = join(directory, "package.json");
988
+ if (!existsSync(path)) return void 0;
989
+ return manifestSchema.parse(readConfig(path));
990
+ };
991
+ const fromDirectory = (directory, pkg) => {
992
+ const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
993
+ const entry = pkg?.tsconfig ? resolve(directory, pkg.tsconfig) : join(directory, "tsconfig");
994
+ if (versionPaths !== void 0) {
995
+ const match = matchedPath(versionPaths, entry.slice(directory.length + 1));
996
+ if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
997
+ const found = jsonFile(resolve(directory, path.replace("*", match.match)));
998
+ if (found !== void 0) return found;
999
+ }
1000
+ }
1001
+ return (pkg?.tsconfig ? jsonFile(entry) : void 0) ?? jsonFile(join(directory, "tsconfig"));
1002
+ };
1003
+ for (const modules of createRequire(configFile).resolve.paths(specifier) ?? []) {
1004
+ const directory = join(modules, packageName);
1005
+ const candidate = join(modules, specifier);
1006
+ const nested = manifestAt(candidate);
1007
+ const pkg = subpath === "" ? nested : manifestAt(directory);
1008
+ if (subpath !== "" && nested !== void 0 && !pkg?.exports) {
1009
+ const found = jsonFile(candidate) ?? fromDirectory(candidate, nested);
1010
+ if (found !== void 0) return found;
1011
+ continue;
1012
+ }
1013
+ if (pkg?.exports) {
1014
+ const exports = pkg.exports;
1015
+ const key = subpath === "" ? "." : `./${subpath}`;
1016
+ let target;
1017
+ let match = "";
1018
+ let pattern = false;
1019
+ if (typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) {
1020
+ const matched = matchedPath(exports, key, true);
1021
+ if (matched !== void 0) {
1022
+ target = exports[matched.key];
1023
+ match = matched.match;
1024
+ pattern = matched.key.includes("*");
1025
+ }
1026
+ } else if (key === ".") target = exports;
1027
+ const found = target === void 0 ? void 0 : exportedConfig(target, directory, compilerVersion, match, pattern)?.path;
1028
+ if (found !== void 0) return found;
1029
+ continue;
1030
+ }
1031
+ const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
1032
+ if (subpath !== "" && versionPaths !== void 0) {
1033
+ const match = matchedPath(versionPaths, subpath);
1034
+ if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
1035
+ const found = jsonFile(resolve(directory, path.replace("*", match.match)));
1036
+ if (found !== void 0) return found;
1037
+ }
1038
+ }
1039
+ const found = jsonFile(candidate) ?? fromDirectory(candidate, pkg);
1040
+ if (found !== void 0) return found;
1041
+ }
1042
+ }
1043
+ throw new Error(`The extended TypeScript config ${JSON.stringify(specifier)} could not be resolved from ${JSON.stringify(configFile)}.`);
1044
+ }
1045
+ //#endregion
1046
+ //#region src/services/definitions/compiler-output.ts
1047
+ const lines = (stdout) => stdout.split(/\r?\n/);
1048
+ function listedFiles(stdout = "", directory = ".") {
1049
+ return lines(stdout).map((line) => line.trim()).map((line) => resolve(directory, line)).filter((line) => existsSync(line) && statSync(line).isFile());
1050
+ }
1051
+ function explainedRoots(stdout, directory) {
1052
+ const roots = [];
1053
+ let file;
1054
+ for (const line of lines(stdout)) if (line !== "" && line === line.trim() && /\.(?:[cm]?[jt]sx?|json)$/i.test(line)) {
1055
+ const path = resolve(directory, line);
1056
+ file = statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
1057
+ } else if (file !== void 0 && /Root file specified|Part of 'files' list|Matched by (default )?include pattern/.test(line)) roots.push(file);
1058
+ return roots;
1059
+ }
1060
+ //#endregion
1061
+ //#region src/services/definitions/compiler.ts
1062
+ async function runLocal(packageRoot, agent, argv) {
1063
+ const command = resolveCommand(agent, "execute-local", [...argv]);
1064
+ if (command === null) return {
1065
+ ok: false,
1066
+ output: `${argv[0]} is not installed in this package`
1067
+ };
1068
+ try {
1069
+ return {
1070
+ ok: true,
1071
+ output: await spawnAsync(command.command, command.args, {
1072
+ cwd: packageRoot,
1073
+ env: {
1074
+ ...process.env,
1075
+ PWD: packageRoot
1076
+ }
1077
+ })
1078
+ };
1079
+ } catch (error) {
1080
+ return {
1081
+ ok: false,
1082
+ output: error instanceof SpawnError && error.stdout.length !== 0 ? error.stdout : error instanceof Error ? error.message : `${argv[0]} failed`
1083
+ };
1084
+ }
1085
+ }
1086
+ const configSchema = object({
1087
+ compilerOptions: looseObject({
1088
+ declaration: boolean().optional(),
1089
+ composite: boolean().optional(),
1090
+ incremental: boolean().optional(),
1091
+ declarationDir: string().optional(),
1092
+ outDir: string().optional(),
1093
+ rootDir: string().optional(),
1094
+ noEmit: boolean().optional(),
1095
+ emitDeclarationOnly: boolean().optional(),
1096
+ sourceMap: boolean().optional(),
1097
+ declarationMap: boolean().optional(),
1098
+ jsx: string().optional(),
1099
+ outFile: string().optional(),
1100
+ tsBuildInfoFile: string().optional(),
1101
+ resolveJsonModule: boolean().optional()
1102
+ }),
1103
+ references: array(object({ path: string() })).optional()
1104
+ });
1105
+ var CompilerDiagnostic = class extends Error {
1106
+ configFile;
1107
+ noWrites;
1108
+ constructor(summary, configFile, noWrites) {
1109
+ super(summary);
1110
+ this.configFile = configFile;
1111
+ this.noWrites = noWrites;
1112
+ }
1113
+ };
1114
+ function projectConfigFile(path) {
1115
+ const entry = statSync(path, { throwIfNoEntry: false });
1116
+ return canonicalConfigFile(entry?.isDirectory() || entry === void 0 && !path.endsWith(".json") ? join(path, "tsconfig.json") : path);
1117
+ }
1118
+ function commonSourceDirectory(files, fallback) {
1119
+ let root = files.length === 0 ? fallback : dirname(files[0] ?? fallback);
1120
+ for (const file of files) while (pathWithin(root, file) === null) {
1121
+ const parent = dirname(root);
1122
+ if (parent === root) throw new Error("TypeScript sources on different drives have no common source directory.");
1123
+ root = parent;
1124
+ }
1125
+ return root;
1126
+ }
1127
+ function outputFiles(project, emitsBuildInfoInBuildMode) {
1128
+ const { options, sources, configFile } = project;
1129
+ const directory = dirname(configFile);
1130
+ const root = project.emitRoot;
1131
+ const files = emitsBuildInfoInBuildMode || options.composite || options.incremental || options.tsBuildInfoFile !== void 0 ? [buildInfoFile(options, configFile)] : [];
1132
+ if (options.noEmit) return files;
1133
+ if (options.outFile !== void 0) return [...files, ...outFileOutputs(options, configFile)];
1134
+ const declares = options.declaration === true || options.composite === true;
1135
+ for (const source of sources) {
1136
+ if (/\.json$/i.test(source)) {
1137
+ if (!options.emitDeclarationOnly) {
1138
+ const inside = pathWithin(root, source);
1139
+ files.push(options.outDir === void 0 || inside === null ? source : resolve(directory, options.outDir, inside));
1140
+ }
1141
+ continue;
1142
+ }
1143
+ const suffix = /\.[cm]?[jt]sx?$/i;
1144
+ const jsExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace("t", "j") : options.jsx === "preserve" && /[jt]sx$/i.test(source) ? ".jsx" : ".js";
1145
+ const declarationExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace(/j/, "t").replace(".", ".d.") : ".d.ts";
1146
+ const inRoot = pathWithin(root, source);
1147
+ const destination = (out, extension) => out === void 0 || inRoot === null ? source.replace(suffix, extension) : resolve(directory, out, inRoot.replace(suffix, extension));
1148
+ if (!options.emitDeclarationOnly) {
1149
+ const js = destination(options.outDir, jsExtension);
1150
+ files.push(js, ...options.sourceMap ? [js + ".map"] : []);
1151
+ }
1152
+ if (declares) {
1153
+ const declaration = destination(options.declarationDir ?? options.outDir, declarationExtension);
1154
+ files.push(declaration, ...options.declarationMap ? [declaration + ".map"] : []);
1155
+ }
1156
+ }
1157
+ return files;
1158
+ }
1159
+ /**
1160
+ * Reads the package's project graph through its own `tsc` and predicts what
1161
+ * `tsc --build` writes, without writing. Refuses a build that would write
1162
+ * outside the package.
1163
+ */
1164
+ async function prepareCompile(packageRoot, agent) {
1165
+ try {
1166
+ const version = await runLocal(packageRoot, agent, ["tsc", "--version"]);
1167
+ const match = /Version (\d+)\.(\d+)/.exec(version.output);
1168
+ if (match === null) throw new Error("The installed TypeScript version could not be resolved.");
1169
+ const major = Number(match[1]);
1170
+ const minor = Number(match[2]);
1171
+ const emitsBuildInfoInBuildMode = major > 5 || major === 5 && minor >= 6;
1172
+ const defaultsRootDirToConfig = major >= 6;
1173
+ return {
1174
+ ok: true,
1175
+ plan: checkedCompilePlan(packageRoot, await readProjectGraph(packageRoot, agent, join(packageRoot, "tsconfig.json"), defaultsRootDirToConfig, /Version (\S+)/.exec(version.output)?.[1] ?? `${major}.${minor}.0`), emitsBuildInfoInBuildMode)
1176
+ };
1177
+ } catch (error) {
1178
+ if (error instanceof CompilerDiagnostic && error.noWrites && error.configFile === projectConfigFile(join(packageRoot, "tsconfig.json"))) return {
1179
+ ok: true,
1180
+ plan: {
1181
+ ...checkedCompilePlan(packageRoot, [{
1182
+ configFile: error.configFile,
1183
+ options: { noEmit: true },
1184
+ sources: [],
1185
+ external: false,
1186
+ emitRoot: packageRoot,
1187
+ references: []
1188
+ }], false),
1189
+ preflightTypeError: error.message
1190
+ }
1191
+ };
1192
+ return {
1193
+ ok: false,
1194
+ summary: error instanceof Error ? error.message : "The TypeScript output layout could not be resolved."
1195
+ };
1196
+ }
1197
+ }
1198
+ async function readProjectGraph(packageRoot, agent, configPath, defaultsRootDirToConfig, compilerVersion) {
1199
+ const projects = [];
1200
+ const visited = /* @__PURE__ */ new Set();
1201
+ const rootConfig = projectConfigFile(join(packageRoot, "tsconfig.json"));
1202
+ const visit = async (path) => {
1203
+ const configFile = projectConfigFile(path);
1204
+ if (visited.has(configFile)) return;
1205
+ visited.add(configFile);
1206
+ let shown = await runLocal(packageRoot, agent, [
1207
+ "tsc",
1208
+ "-p",
1209
+ configFile,
1210
+ "--showConfig"
1211
+ ]);
1212
+ let diagnostic;
1213
+ if (!shown.ok && /TS18003/.test(shown.output) && pathWithin(packageRoot, configFile) !== null) {
1214
+ diagnostic = shown.output;
1215
+ shown = await showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion);
1216
+ }
1217
+ if (!shown.ok) throw new CompilerDiagnostic(shown.output, configFile, statSync(configFile, { throwIfNoEntry: false }) === void 0);
1218
+ const config = configSchema.parse(JSON.parse(shown.output));
1219
+ const project = await refreshProject(packageRoot, agent, {
1220
+ ...diagnostic !== void 0 && { diagnostic },
1221
+ configFile,
1222
+ options: config.compilerOptions,
1223
+ sources: [],
1224
+ references: (config.references ?? []).map((reference) => projectConfigFile(resolve(dirname(configFile), reference.path))),
1225
+ emitRoot: dirname(configFile),
1226
+ external: configFile !== rootConfig && pathWithin(packageRoot, configFile) === null
1227
+ }, defaultsRootDirToConfig);
1228
+ projects.push(project);
1229
+ for (const reference of project.references) await visit(reference);
1230
+ };
1231
+ await visit(configPath);
1232
+ return projects;
1233
+ }
1234
+ async function showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion) {
1235
+ const config = object({ references: configSchema.shape.references }).parse(readConfig(configFile));
1236
+ const directory = realPathThroughExistingParent(mkdtempSync(join(tmpdir(), ".ph-preflight-")));
1237
+ try {
1238
+ const probe = join(directory, "tsconfig.json");
1239
+ writeFileSync(probe, JSON.stringify({
1240
+ extends: configFile,
1241
+ compilerOptions: configDirOptions(configFile, compilerVersion),
1242
+ files: [configFile],
1243
+ include: [],
1244
+ references: config.references?.map(({ path }) => ({ path: resolve(dirname(configFile), path) }))
1245
+ }));
1246
+ const shown = await runLocal(packageRoot, agent, [
1247
+ "tsc",
1248
+ "-p",
1249
+ probe,
1250
+ "--showConfig"
1251
+ ]);
1252
+ if (!shown.ok) return shown;
1253
+ const resolved = configSchema.parse(JSON.parse(shown.output));
1254
+ const options = resolved.compilerOptions;
1255
+ const rebase = (path) => {
1256
+ const absolute = resolve(directory, path);
1257
+ const inProbe = pathWithin(directory, absolute);
1258
+ return inProbe === null ? absolute : resolve(dirname(configFile), inProbe);
1259
+ };
1260
+ for (const key of [
1261
+ "outDir",
1262
+ "declarationDir",
1263
+ "rootDir",
1264
+ "outFile",
1265
+ "tsBuildInfoFile"
1266
+ ]) {
1267
+ const path = options[key];
1268
+ if (path !== void 0) options[key] = rebase(path);
1269
+ }
1270
+ return {
1271
+ ...shown,
1272
+ output: JSON.stringify(resolved)
1273
+ };
1274
+ } finally {
1275
+ rmSync(directory, {
1276
+ recursive: true,
1277
+ force: true
1278
+ });
1279
+ }
1280
+ }
1281
+ async function listProjectFiles(packageRoot, agent, configFile, preserveSymlinks = false) {
1282
+ const listed = await runLocal(packageRoot, agent, [
1283
+ "tsc",
1284
+ "-p",
1285
+ configFile,
1286
+ "--listFilesOnly",
1287
+ "--explainFiles",
1288
+ "--pretty",
1289
+ "false",
1290
+ ...preserveSymlinks ? ["--preserveSymlinks", "true"] : []
1291
+ ]);
1292
+ return {
1293
+ ...listed,
1294
+ files: listedFiles(listed.output, packageRoot),
1295
+ rootFiles: explainedRoots(listed.output, packageRoot)
1296
+ };
1297
+ }
1298
+ async function refreshProject(packageRoot, agent, project, defaultsRootDirToConfig) {
1299
+ const listed = await listProjectFiles(packageRoot, agent, project.configFile);
1300
+ const { files, rootFiles } = listed;
1301
+ if (!listed.ok && files.length === 0 && !/TS18003/.test(listed.output)) throw new CompilerDiagnostic(listed.output, project.configFile, false);
1302
+ const roots = new Set(rootFiles.map((file) => realPathThroughExistingParent(file)));
1303
+ let sources = files.filter((file) => (/\.[cm]?[jt]sx?$/i.test(file) || project.options.resolveJsonModule === true && /\.json$/i.test(file)) && !/\.d\.[cm]?ts$/i.test(file) && (roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")));
1304
+ if (sources.some((file) => !roots.has(realPathThroughExistingParent(file)) && pathWithin(packageRoot, realPathThroughExistingParent(file)) === null)) {
1305
+ const spellings = (await listProjectFiles(packageRoot, agent, project.configFile, true)).files;
1306
+ if (spellings.length === 0) throw new Error("tsc could not classify external library inputs without writing them.");
1307
+ const local = new Set(spellings.filter((file) => roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
1308
+ const libraries = new Set(spellings.filter((file) => toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
1309
+ sources = sources.filter((file) => !libraries.has(realPathThroughExistingParent(file)) || local.has(realPathThroughExistingParent(file)));
1310
+ }
1311
+ return {
1312
+ ...project,
1313
+ .../TS18003/.test(listed.output) && { diagnostic: listed.output },
1314
+ sources,
1315
+ emitRoot: resolve(dirname(project.configFile), project.options.rootDir ?? (project.options.composite || defaultsRootDirToConfig ? "." : commonSourceDirectory(sources, dirname(project.configFile))))
1316
+ };
1317
+ }
1318
+ function checkedCompilePlan(packageRoot, projects, emitsBuildInfoInBuildMode) {
1319
+ const directories = /* @__PURE__ */ new Set();
1320
+ const files = /* @__PURE__ */ new Set();
1321
+ for (const project of projects) {
1322
+ if (project.external) continue;
1323
+ if (!project.options.noEmit) for (const path of outputDirectories$1(project.options, dirname(project.configFile))) {
1324
+ const target = realPathThroughExistingParent(path);
1325
+ if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
1326
+ if (!project.sources.some((file) => pathWithin(target, realPathThroughExistingParent(file)) !== null)) {
1327
+ if (pathWithin(packageRoot, path) !== null) directories.add(toPosixPath(relative(packageRoot, path)));
1328
+ directories.add(toPosixPath(relative(packageRoot, target)));
1329
+ }
1330
+ }
1331
+ for (const path of outputFiles(project, emitsBuildInfoInBuildMode)) {
1332
+ if (/\.json$/i.test(path) && project.sources.includes(path)) continue;
1333
+ const target = realPathThroughExistingParent(path);
1334
+ if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
1335
+ if (pathWithin(packageRoot, path) !== null) files.add(toPosixPath(relative(packageRoot, path)));
1336
+ files.add(toPosixPath(relative(packageRoot, target)));
1337
+ }
1338
+ }
1339
+ const root = projects.at(0);
1340
+ const references = projects.slice(1);
1341
+ if (root === void 0) throw new Error("The root TypeScript project could not be resolved.");
1342
+ return {
1343
+ ...root.diagnostic !== void 0 && { preflightTypeError: root.diagnostic },
1344
+ projects: [root, ...references],
1345
+ outputs: {
1346
+ directories: [...directories].sort(),
1347
+ files: [...files].sort()
1348
+ }
1349
+ };
1350
+ }
1351
+ //#endregion
1352
+ //#region src/services/package-build/staging/inventory.ts
1353
+ const optionalString = (value) => typeof value === "string" ? value : void 0;
1354
+ const optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
1355
+ const strings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : void 0;
1356
+ /** The config in `tsc --showConfig` output, or undefined when it is not JSON. */
1357
+ function parseShownConfig(text) {
1358
+ let shown;
1359
+ try {
1360
+ shown = JSON.parse(text);
1361
+ } catch {
1362
+ return;
1363
+ }
1364
+ if (typeof shown !== "object" || shown === null) return void 0;
1365
+ const { compilerOptions, exclude, references } = shown;
1366
+ return {
1367
+ options: emitOptions(compilerOptions),
1368
+ exclude: strings(exclude),
1369
+ references: Array.isArray(references) ? references.flatMap((reference) => {
1370
+ const path = reference?.path;
1371
+ return typeof path === "string" ? [path] : [];
1372
+ }) : []
1373
+ };
1374
+ }
1375
+ function emitOptions(options) {
1376
+ if (typeof options !== "object" || options === null) return {};
1377
+ const record = options;
1378
+ return {
1379
+ declaration: optionalBoolean(record.declaration),
1380
+ composite: optionalBoolean(record.composite),
1381
+ incremental: optionalBoolean(record.incremental),
1382
+ declarationDir: optionalString(record.declarationDir),
1383
+ outDir: optionalString(record.outDir),
1384
+ outFile: optionalString(record.outFile),
1385
+ rootDir: optionalString(record.rootDir),
1386
+ tsBuildInfoFile: optionalString(record.tsBuildInfoFile),
1387
+ noEmit: optionalBoolean(record.noEmit),
1388
+ emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),
1389
+ sourceMap: optionalBoolean(record.sourceMap),
1390
+ declarationMap: optionalBoolean(record.declarationMap)
1391
+ };
1392
+ }
1393
+ /**
1394
+ * What the root project's tsc writes inside the package, for the build to
1395
+ * snapshot and restore: its build info first, then the files `outFile`
1396
+ * writes, then its declaration and output directories, the build's own
1397
+ * output directory or one holding it included. A directory holding
1398
+ * `buildDirectory`, where the build keeps its runs and their snapshots, is
1399
+ * left out and unprotected, as without staging: a snapshot of it would copy
1400
+ * itself. This says what to protect, not what to carry into the stage.
1401
+ */
1402
+ function compilerOutputInventory(options, at) {
1403
+ const inPackage = (path) => Boolean(pathWithin(at.packageRoot, path));
1404
+ const directories = outputDirectories$1(options, dirname(at.configFile)).filter(inPackage).filter((dir) => pathWithin(dir, at.buildDirectory) === null);
1405
+ return [
1406
+ ...[buildInfoFile(options, at.configFile)].filter(inPackage).map((path) => ({
1407
+ path,
1408
+ kind: "build-info"
1409
+ })),
1410
+ ...outFileOutputs(options, at.configFile).filter(inPackage).map((path) => ({
1411
+ path,
1412
+ kind: "file"
1413
+ })),
1414
+ ...[...new Set(directories)].map((path) => ({
1415
+ path,
1416
+ kind: "directory"
1417
+ }))
1418
+ ];
1419
+ }
1420
+ //#endregion
1421
+ //#region src/services/package-build/staging/compiler.ts
1422
+ function writesBesideSources(options) {
1423
+ if (options.noEmit || options.outFile !== void 0) return false;
1424
+ if (options.outDir !== void 0) return false;
1425
+ const declares = options.declaration === true || options.composite === true;
1426
+ return !options.emitDeclarationOnly || declares && !options.declarationDir;
1427
+ }
1428
+ const redirectable = ({ references, options }) => references.length === 0 && Boolean(options.incremental || options.composite || options.tsBuildInfoFile);
1429
+ async function compilerOutputs(config, at) {
1430
+ const root = compilerOutputInventory(config.options, at);
1431
+ const real = (path) => realPathThroughExistingParent(path);
1432
+ const packageIdentity = real(at.packageRoot);
1433
+ const inPackage = (path) => pathWithin(packageIdentity, real(path)) !== null;
1434
+ const referencesInPackage = config.references.some((reference) => inPackage(resolve(dirname(at.configFile), reference)));
1435
+ const holdsOutput = (dir) => pathWithin(real(dir), at.output) !== null;
1436
+ const protectsOutput = root.some(({ kind, path }) => kind === "directory" && holdsOutput(path) && !(redirectable(config) && real(path) === at.output));
1437
+ if (!referencesInPackage && !writesBesideSources(config.options) && !protectsOutput) return root;
1438
+ const prepared = await prepareCompile(at.packageRoot, at.agent);
1439
+ if (!prepared.ok) return root;
1440
+ const { directories, files } = prepared.plan.outputs;
1441
+ const absolute = (path) => resolve(at.packageRoot, path);
1442
+ const owned = (path) => inPackage(path) && pathWithin(path, at.buildDirectory) === null;
1443
+ const dirs = directories.map(absolute).filter((dir) => owned(dir) && !holdsOutput(dir));
1444
+ return [...files.map(absolute).filter((file) => owned(file) && !dirs.some((dir) => pathWithin(dir, file) !== null)).map((path) => ({
1445
+ path,
1446
+ kind: path.endsWith(".tsbuildinfo") ? "build-info" : "file"
1447
+ })).sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info")), ...dirs.map((path) => ({
1448
+ path,
1449
+ kind: "directory"
1450
+ }))];
1451
+ }
1452
+ function redirectRootProject(config, at) {
1453
+ if (!redirectable(config)) return void 0;
1454
+ const { options } = config;
1455
+ const configDir = dirname(at.configFile);
1456
+ const real = (path) => realPathThroughExistingParent(path);
1457
+ const inOutput = (path) => pathWithin(at.output, real(path));
1458
+ const compilerOptions = {};
1459
+ const staged = [];
1460
+ for (const key of [
1461
+ "declarationDir",
1462
+ "outDir",
1463
+ "outFile"
1464
+ ]) {
1465
+ const value = options[key];
1466
+ if (value === void 0 || key === "outFile" && options.noEmit) continue;
1467
+ const rel = inOutput(resolve(configDir, value));
1468
+ if (rel === null) continue;
1469
+ compilerOptions[key] = join(at.stage, rel);
1470
+ staged.push(...(key === "outFile" ? outFileOutputs(options, at.configFile) : [resolve(configDir, value)]).map(real));
1471
+ }
1472
+ const target = buildInfoFile(options, at.configFile);
1473
+ const rel = inOutput(target);
1474
+ let pendingBuildInfo;
1475
+ if (rel !== null) {
1476
+ compilerOptions.tsBuildInfoFile = join(at.stage, rel);
1477
+ staged.push(real(target));
1478
+ } else if (pathWithin(at.packageRoot, target) !== null && !lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
1479
+ pendingBuildInfo = {
1480
+ path: at.pending(target),
1481
+ target
1482
+ };
1483
+ compilerOptions.tsBuildInfoFile = pendingBuildInfo.path;
1484
+ staged.push(real(target));
1485
+ } else compilerOptions.tsBuildInfoFile = target;
1486
+ return {
1487
+ compilerOptions,
1488
+ exclude: config.exclude,
1489
+ pendingBuildInfo,
1490
+ staged
1491
+ };
1492
+ }
1493
+ //#endregion
1494
+ //#region src/services/package-build/staging/session.ts
1495
+ const isUnreadable = (error) => {
1496
+ const code = error?.code;
1497
+ return code === "EACCES" || code === "EPERM";
1498
+ };
1499
+ /** `path` is `dir` or holds it. */
1500
+ const isOrHolds = (path, dir) => pathWithin(path, dir) !== null;
1501
+ /** The outermost directory of `path`, inside the package, that does not exist. */
1502
+ function outermostMissing(packageRoot, path) {
1503
+ let missing = path;
1504
+ for (let parent = dirname(path); pathWithin(packageRoot, parent) && !exists(parent); parent = dirname(parent)) missing = parent;
1505
+ return missing;
1506
+ }
1507
+ /** A path as messages name it: from the package root, which is named so. */
1508
+ const shownPath = (packageRoot, path) => toJournalPath(packageRoot, path) || "the package root";
1509
+ const scratchBeside = (path, kind, runId) => join(dirname(path), `.${basename(path)}.ph-${kind}-${runId}`);
1510
+ /**
1511
+ * One `ph build` of one package: the output is written to a stage beside the
1512
+ * output directory and replaces it only on commit. Until then the previous
1513
+ * output and the compiler outputs tsc rewrote can be put back, by `rollback`
1514
+ * in this process or, after a crash, by the next build.
1515
+ */
1516
+ var StagedBuildSession = class StagedBuildSession {
1517
+ runId;
1518
+ packageRoot;
1519
+ output;
1520
+ writesPackageDist;
1521
+ runDir;
1522
+ paths;
1523
+ lock;
1524
+ journal;
1525
+ status = "open";
1526
+ stoppedBy;
1527
+ seeded = false;
1528
+ compilerWritten = false;
1529
+ restored = false;
1530
+ redirected = [];
1531
+ cleanedEntries;
1532
+ linkCleanedEntries;
1533
+ constructor(fields) {
1534
+ this.runId = fields.runId;
1535
+ this.packageRoot = fields.packageRoot;
1536
+ this.output = fields.output;
1537
+ this.writesPackageDist = fields.writesPackageDist;
1538
+ this.cleanedEntries = fields.cleanedEntries;
1539
+ this.linkCleanedEntries = fields.linkCleanedEntries;
1540
+ this.runDir = fields.runDir;
1541
+ this.lock = fields.lock;
1542
+ this.journal = fields.journal;
1543
+ this.paths = runPaths(fields.packageRoot, fields.runDir, fields.journal);
1544
+ }
1545
+ /**
1546
+ * Starts a run under `lock`, which the caller took and recovered stale
1547
+ * runs under; the caller still releases it when this throws. The stage
1548
+ * sits beside `logical`, the output as given, so the paths the bundlers
1549
+ * record from it are the ones an unstaged build records.
1550
+ */
1551
+ static async open(options) {
1552
+ const { packageRoot, logical, runId } = options;
1553
+ const runDir = join(packageRoot, RUNS_DIRECTORY, runId);
1554
+ try {
1555
+ const beside = (kind) => scratchBeside(logical, kind, runId);
1556
+ const journal = {
1557
+ format: 1,
1558
+ runId,
1559
+ pid: process.pid,
1560
+ state: "building",
1561
+ undo: null,
1562
+ output: toJournalPath(packageRoot, logical),
1563
+ stage: toJournalPath(packageRoot, beside("stage")),
1564
+ retired: toJournalPath(packageRoot, beside("old")),
1565
+ compiler: null
1566
+ };
1567
+ await creating(BUILD_DIRECTORY, () => {
1568
+ mkdirSync(runDir, { recursive: true });
1569
+ writeJournal(runDir, journal);
1570
+ });
1571
+ await creating(shownPath(packageRoot, dirname(logical)), () => mkdirSync(beside("stage"), { recursive: true }));
1572
+ return new StagedBuildSession({
1573
+ ...options,
1574
+ runDir,
1575
+ journal
1576
+ });
1577
+ } catch (error) {
1578
+ removeTree(runDir);
1579
+ throw error;
1580
+ }
1581
+ }
1582
+ assertOpen() {
1583
+ if (this.status !== "open") throw new Error("The build was stopped before it finished.");
1584
+ }
1585
+ record(changes) {
1586
+ this.journal = {
1587
+ ...this.journal,
1588
+ ...changes
1589
+ };
1590
+ writeJournal(this.runDir, this.journal);
1591
+ }
1592
+ setState(state) {
1593
+ this.record({ state });
1594
+ }
1595
+ /**
1596
+ * Compiler outputs strictly inside the output directory, relative to it:
1597
+ * tsc rewrote them in the real output, so the stage leaves them out when
1598
+ * it is seeded and takes them fresh at commit. A protected directory that
1599
+ * is the output or holds it is not one: it holds the bundles too.
1600
+ */
1601
+ compilerOutputsInOutput() {
1602
+ return (this.journal.compiler ?? []).flatMap(({ path }) => {
1603
+ const rel = pathWithin(this.output, fromJournalPath(this.packageRoot, path));
1604
+ return rel ? [rel] : [];
1605
+ });
1606
+ }
1607
+ /**
1608
+ * The stage directory every output write targets. The first call seeds it
1609
+ * with the current output, minus what tsc writes afresh. With
1610
+ * `linkCleanedEntries`, the entries a step cleans are seeded by hard link,
1611
+ * since it unlinks their files before it writes and says so in the same
1612
+ * words as on the output; the rest, and otherwise everything, by clone.
1613
+ */
1614
+ stage() {
1615
+ this.assertOpen();
1616
+ const { stage, output } = this.paths;
1617
+ if (this.seeded) return stage;
1618
+ removeTree(stage);
1619
+ if (exists(output)) {
1620
+ const skipped = new Set(this.compilerWritten ? [] : this.compilerOutputsInOutput().map((rel) => join(output, rel)));
1621
+ const keep = (source) => !skipped.has(source);
1622
+ const linked = (this.linkCleanedEntries ? this.cleanedEntries : []).filter((entry) => {
1623
+ const real = join(this.output, entry);
1624
+ return !this.redirected.some((path) => isOrHolds(real, path) || isOrHolds(path, real));
1625
+ }).map((entry) => join(output, entry)).filter((dir) => keep(dir) && lstatSync(dir, { throwIfNoEntry: false })?.isDirectory());
1626
+ cloneTree(output, stage, (source) => keep(source) && !linked.includes(source));
1627
+ for (const dir of linked) linkTree(dir, join(stage, basename(dir)), keep);
1628
+ } else mkdirSync(stage);
1629
+ this.seeded = true;
1630
+ return stage;
1631
+ }
1632
+ async prepareCompiler(compiler) {
1633
+ this.assertOpen();
1634
+ const redirect = redirectRootProject(compiler.config, {
1635
+ configFile: compiler.configFile,
1636
+ packageRoot: this.packageRoot,
1637
+ output: this.output,
1638
+ stage: this.paths.stage,
1639
+ pending: (target) => scratchBeside(target, "stage", this.runId)
1640
+ });
1641
+ let config;
1642
+ let staged = [];
1643
+ if (redirect) {
1644
+ config = await this.writeCompilerConfig(compiler.configFile, redirect);
1645
+ if (config) staged = redirect.staged;
1646
+ }
1647
+ const real = (path) => realPathThroughExistingParent(path);
1648
+ this.protectCompilerOutputs(compiler.outputs.filter(({ path }) => !staged.some((dir) => isOrHolds(dir, real(path)))));
1649
+ if (!config) return void 0;
1650
+ this.redirected = staged;
1651
+ this.stage();
1652
+ return config;
1653
+ }
1654
+ /**
1655
+ * Writes the config that sends the root project's outputs into the stage,
1656
+ * beside the package's so `${configDir}` and its relative paths mean the
1657
+ * same, with the package config's modification time so tsc finds the
1658
+ * project up to date when it would. The pending build info starts as a
1659
+ * copy of the real one. Undefined when the package does not let the run
1660
+ * write them: tsc then writes in place.
1661
+ */
1662
+ async writeCompilerConfig(configFile, redirect) {
1663
+ const generated = join(dirname(configFile), `.${basename(configFile, extname(configFile))}.ph-stage-${this.runId}.json`);
1664
+ const pending = redirect.pendingBuildInfo;
1665
+ const recorded = (path) => toJournalPath(this.packageRoot, path);
1666
+ this.record({
1667
+ generatedConfig: recorded(generated),
1668
+ ...pending && { pendingBuildInfo: {
1669
+ path: recorded(pending.path),
1670
+ target: recorded(pending.target)
1671
+ } }
1672
+ });
1673
+ try {
1674
+ await creating(shownPath(this.packageRoot, dirname(configFile)), () => {
1675
+ writeFileSync(generated, `${JSON.stringify({
1676
+ extends: `./${basename(configFile)}`,
1677
+ compilerOptions: redirect.compilerOptions,
1678
+ ...redirect.exclude && { exclude: redirect.exclude }
1679
+ }, null, 2)}\n`);
1680
+ const { atime, mtime } = statSync(configFile);
1681
+ utimesSync(generated, atime, mtime);
1682
+ if (pending && exists(pending.target)) cloneTree(pending.target, pending.path);
1683
+ });
1684
+ return generated;
1685
+ } catch (error) {
1686
+ if (!(error instanceof CannotStage)) throw error;
1687
+ removeTree(generated);
1688
+ if (pending) removeTree(pending.path);
1689
+ this.record({
1690
+ generatedConfig: void 0,
1691
+ pendingBuildInfo: void 0
1692
+ });
1693
+ return;
1694
+ }
1695
+ }
1696
+ /**
1697
+ * Copies what tsc is about to rewrite into the run, or notes it absent, so
1698
+ * a build that does not finish puts it back. Call before tsc runs. An
1699
+ * output that is or holds `.ph/build` or this run, by real path, is left
1700
+ * unprotected, as without staging: a copy of it would copy itself. So is
1701
+ * one holding something a copy cannot take: a FIFO, socket or device, or
1702
+ * an entry this process cannot read. The copy's directories are made
1703
+ * owner-writable, so the run can always be removed; the journal keeps
1704
+ * their modes for a restore.
1705
+ */
1706
+ protectCompilerOutputs(outputs) {
1707
+ const real = (path) => realPathThroughExistingParent(path);
1708
+ const control = [real(join(this.packageRoot, BUILD_DIRECTORY)), real(this.runDir)];
1709
+ const snapshots = [...this.journal.compiler ?? []];
1710
+ for (const { path, kind } of outputs) {
1711
+ const target = real(path);
1712
+ if (control.some((dir) => isOrHolds(target, dir))) continue;
1713
+ const recorded = toJournalPath(this.packageRoot, target);
1714
+ if (snapshots.some((snapshot) => snapshot.path === recorded)) continue;
1715
+ if (exists(target)) {
1716
+ const copy = `compiler/${snapshots.length}`;
1717
+ const output = basename(this.paths.output);
1718
+ const snapshot = join(this.runDir, copy);
1719
+ const keep = (source) => !isScratchOf(output, basename(source));
1720
+ if (unstageableEntryIn(target, keep) !== void 0) continue;
1721
+ try {
1722
+ cloneTree(target, snapshot, keep);
1723
+ } catch (error) {
1724
+ if (!isUnreadable(error)) throw error;
1725
+ removeTree(snapshot);
1726
+ continue;
1727
+ }
1728
+ const modes = openDirectories(snapshot);
1729
+ snapshots.push({
1730
+ path: recorded,
1731
+ kind,
1732
+ copy,
1733
+ created: null,
1734
+ ...modes.length > 0 && { modes }
1735
+ });
1736
+ } else {
1737
+ const missing = outermostMissing(this.packageRoot, target);
1738
+ const created = missing === target ? null : toJournalPath(this.packageRoot, missing);
1739
+ snapshots.push({
1740
+ path: recorded,
1741
+ kind,
1742
+ copy: null,
1743
+ created
1744
+ });
1745
+ }
1746
+ }
1747
+ const digest = snapshots.length > 0 ? outputDigest(this.packageRoot, this.paths.output, snapshots) : void 0;
1748
+ this.record({
1749
+ compiler: snapshots,
1750
+ ...digest !== void 0 && { outputDigest: digest }
1751
+ });
1752
+ }
1753
+ /**
1754
+ * tsc wrote into the real output directory; the stage takes its fresh
1755
+ * files now, before any bundle step, so a step that cleans or rewrites an
1756
+ * entry treats them as it would in the output.
1757
+ */
1758
+ compilerOutputsWritten() {
1759
+ this.assertOpen();
1760
+ this.compilerWritten = true;
1761
+ const generated = this.journal.generatedConfig;
1762
+ if (generated) removeTree(fromJournalPath(this.packageRoot, generated));
1763
+ if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);
1764
+ }
1765
+ carryOverCompilerOutputs(stage) {
1766
+ for (const rel of this.compilerOutputsInOutput()) {
1767
+ const target = join(stage, rel);
1768
+ removeTree(target);
1769
+ const source = join(this.paths.output, rel);
1770
+ if (exists(source)) {
1771
+ mkdirSync(dirname(target), { recursive: true });
1772
+ cloneTree(source, target);
1773
+ }
1774
+ }
1775
+ }
1776
+ warnNotAtomic() {
1777
+ const shown = toJournalPath(this.packageRoot, this.paths.output);
1778
+ console.warn(`⚠ Another process holds files in ${shown}, so ${shown} was replaced entry by entry instead of in one rename; while that ran, it held parts of both builds.`);
1779
+ }
1780
+ /**
1781
+ * Replaces the output with the stage: the output moves aside, the stage
1782
+ * takes its place, the old tree goes. The journal records each move first.
1783
+ * Synchronous, so no signal handler runs in between. The lock stays held
1784
+ * until `close`.
1785
+ */
1786
+ commit() {
1787
+ const stage = this.stage();
1788
+ const { output, retired } = this.paths;
1789
+ try {
1790
+ this.setState("retiring");
1791
+ let entryByEntry = false;
1792
+ if (exists(output)) try {
1793
+ renamePatiently(output, retired);
1794
+ } catch (error) {
1795
+ if (!isHeldOpen(error)) throw error;
1796
+ entryByEntry = true;
1797
+ mkdirSync(retired);
1798
+ moveEntries(output, retired);
1799
+ }
1800
+ this.setState("installing");
1801
+ if (exists(output)) {
1802
+ moveEntries(stage, output);
1803
+ removeTree(stage);
1804
+ } else try {
1805
+ renamePatiently(stage, output);
1806
+ } catch (error) {
1807
+ if (!isHeldOpen(error)) throw error;
1808
+ entryByEntry = true;
1809
+ mkdirSync(output);
1810
+ moveEntries(stage, output);
1811
+ removeTree(stage);
1812
+ }
1813
+ installBuildInfo(this.packageRoot, this.journal.pendingBuildInfo);
1814
+ this.status = "committed";
1815
+ if (entryByEntry) this.warnNotAtomic();
1816
+ } catch (error) {
1817
+ this.rollback();
1818
+ throw error;
1819
+ }
1820
+ try {
1821
+ this.setState("committed");
1822
+ removeTree(retired);
1823
+ removeTree(this.runDir);
1824
+ } catch (error) {
1825
+ console.warn(`⚠ The build finished, but its scratch files were not all removed (${error instanceof Error ? error.message : String(error)}); the next build removes them.`);
1826
+ }
1827
+ }
1828
+ /**
1829
+ * Releases the lock a commit keeps, so steps that read the committed
1830
+ * output finish before another build replaces it, and drops the run a
1831
+ * rollback restored from. Idempotent.
1832
+ */
1833
+ close() {
1834
+ try {
1835
+ if (this.status === "rolled-back" && this.restored) removeTree(this.runDir);
1836
+ } finally {
1837
+ this.lock.release();
1838
+ }
1839
+ }
1840
+ releaseLock() {
1841
+ this.lock.release();
1842
+ }
1843
+ /**
1844
+ * Puts the previous output and compiler outputs back. Synchronous, so a
1845
+ * signal handler can call it; a no-op after commit. The run and its
1846
+ * snapshot stay until `close`, so a call after a step still running at
1847
+ * the first one settles restores again, undoing what that step wrote
1848
+ * since. A restore that failed is left to the next build. The lock stays
1849
+ * held until `close`.
1850
+ */
1851
+ rollback() {
1852
+ if (this.status === "committed") return;
1853
+ if (this.status === "rolled-back" && !this.restored) return;
1854
+ this.status = "rolled-back";
1855
+ try {
1856
+ rollBack(this.paths, this.journal);
1857
+ this.journal = {
1858
+ ...this.journal,
1859
+ state: "rolling-back",
1860
+ undo: "stage"
1861
+ };
1862
+ this.restored = true;
1863
+ } catch (error) {
1864
+ this.restored = false;
1865
+ console.error(`✘ The previous output could not be restored (${error instanceof Error ? error.message : String(error)}); the next build restores it.`);
1866
+ }
1867
+ }
1868
+ stops = /* @__PURE__ */ new Set();
1869
+ cancel(signal) {
1870
+ this.stoppedBy ??= signal;
1871
+ for (const stop of [...this.stops]) stop();
1872
+ }
1873
+ onCancel(stop) {
1874
+ this.stops.add(stop);
1875
+ return () => this.stops.delete(stop);
1876
+ }
1877
+ /** The signal `cancel` was called with, if it was. */
1878
+ stopped() {
1879
+ return this.stoppedBy;
1880
+ }
1881
+ };
1882
+ //#endregion
1883
+ //#region src/services/package-build/staging/open.ts
1884
+ /**
1885
+ * The first symlink among the output and its parents inside the package:
1886
+ * a stage beside its target would change the paths the bundlers record.
1887
+ */
1888
+ function symlinkOnPath(packageRoot, output) {
1889
+ const root = realPathThroughExistingParent(packageRoot);
1890
+ for (let dir = output;; dir = dirname(dir)) {
1891
+ if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) return dir;
1892
+ const parent = realPathThroughExistingParent(dirname(dir));
1893
+ if (parent === root || pathWithin(root, parent) === null) return;
1894
+ }
1895
+ }
1896
+ /**
1897
+ * The output is a mount point, or otherwise on another filesystem than the
1898
+ * directory beside it: the stage's rename cannot replace it.
1899
+ */
1900
+ function onAnotherFilesystem(output) {
1901
+ const dev = statSync(output, { throwIfNoEntry: false })?.dev;
1902
+ return dev !== void 0 && dev !== statSync(dirname(output)).dev;
1903
+ }
1904
+ function linkIntoOutput(logical, output, stage) {
1905
+ const visit = (dir) => {
1906
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1907
+ const path = join(dir, entry.name);
1908
+ if (entry.isDirectory()) {
1909
+ const found = visit(path);
1910
+ if (found) return found;
1911
+ continue;
1912
+ }
1913
+ if (!entry.isSymbolicLink()) continue;
1914
+ const target = readlinkSync(path);
1915
+ const copied = isAbsolute(target) ? target : resolve(stage, relative(logical, dirname(path)), target);
1916
+ if (pathWithin(logical, copied) !== null) return path;
1917
+ if (pathWithin(output, copied) !== null) return path;
1918
+ }
1919
+ };
1920
+ return lstatSync(logical, { throwIfNoEntry: false })?.isDirectory() ? visit(logical) : void 0;
1921
+ }
1922
+ /**
1923
+ * Writes the output in place, as builds did before staging: no stage or
1924
+ * snapshot, and nothing to commit or roll back. It holds the package's lock
1925
+ * until `close` when `.ph/build` can hold one. A stop signal does not stop
1926
+ * it, as it did not stop an unstaged build.
1927
+ */
1928
+ var InPlaceSession = class {
1929
+ output;
1930
+ logical;
1931
+ writesPackageDist;
1932
+ lock;
1933
+ constructor(output, logical, writesPackageDist, lock) {
1934
+ this.output = output;
1935
+ this.logical = logical;
1936
+ this.writesPackageDist = writesPackageDist;
1937
+ this.lock = lock;
1938
+ }
1939
+ stage() {
1940
+ return this.logical;
1941
+ }
1942
+ prepareCompiler() {
1943
+ return Promise.resolve(void 0);
1944
+ }
1945
+ compilerOutputsWritten() {}
1946
+ commit() {}
1947
+ close() {
1948
+ this.lock?.release();
1949
+ }
1950
+ releaseLock() {
1951
+ this.lock?.release();
1952
+ }
1953
+ rollback() {}
1954
+ stops = /* @__PURE__ */ new Set();
1955
+ cancel() {
1956
+ for (const stop of [...this.stops]) stop();
1957
+ }
1958
+ stopped() {}
1959
+ onCancel(stop) {
1960
+ this.stops.add(stop);
1961
+ return () => this.stops.delete(stop);
1962
+ }
1963
+ };
1964
+ function newRunId() {
1965
+ return `${Date.now().toString(36)}-${process.pid}-${randomBytes(3).toString("hex")}`;
1966
+ }
1967
+ /**
1968
+ * Takes the package's lock and finishes what dead builds left, then opens a
1969
+ * staged session, or an in-place one when staging cannot run as an unstaged
1970
+ * build would: the output or a directory on its path in the package is a
1971
+ * symlink, the output is on another filesystem than its parent, it holds an
1972
+ * entry a copy cannot take (a FIFO, socket or device, or one this process
1973
+ * cannot read) or a symlink into itself, it holds `.ph/build`, whose lock and
1974
+ * journal a swap would move away, or the stage beside it cannot be written.
1975
+ * Only when `.ph/build` cannot hold the lock does the build run without one,
1976
+ * as builds did before staging. One warning says why a build writes in place.
1977
+ */
1978
+ async function openBuildSession(options) {
1979
+ const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;
1980
+ const logical = resolve(packageRoot, outDir);
1981
+ const output = realPathThroughExistingParent(logical);
1982
+ const writesPackageDist = output === realPathThroughExistingParent(join(packageRoot, "dist"));
1983
+ const shown = (path) => shownPath(packageRoot, path);
1984
+ const inPlace = (reason, lock) => {
1985
+ console.warn(`⚠ ${reason}, so this build writes ${shown(logical)} in place: if it does not finish, ${shown(logical)} can be left part old, part new.`);
1986
+ return new InPlaceSession(output, logical, writesPackageDist, lock);
1987
+ };
1988
+ const runId = newRunId();
1989
+ let lock;
1990
+ try {
1991
+ lock = await creating(BUILD_DIRECTORY, () => acquireBuildLock(join(packageRoot, LOCK_FILE), runId, (wait) => console.log(`Another build of this package holds ${shown(wait.file)} (${wait.owner}); waiting for it to finish... If that build is gone, delete ${shown(wait.file)}.`)));
1992
+ } catch (error) {
1993
+ if (!(error instanceof CannotStage)) throw error;
1994
+ return inPlace(error.message, void 0);
1995
+ }
1996
+ try {
1997
+ recoverStaleRuns(packageRoot, logical);
1998
+ const link = symlinkOnPath(packageRoot, logical);
1999
+ if (link !== void 0) return inPlace(`${shown(link)} is a symbolic link`, lock);
2000
+ if (onAnotherFilesystem(logical)) return inPlace(`${shown(logical)} is on another filesystem than the directory that holds it`, lock);
2001
+ const unstageable = unstageableEntryIn(logical);
2002
+ if (unstageable !== void 0) return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);
2003
+ const intoOutput = linkIntoOutput(logical, output, scratchBeside(logical, "stage", runId));
2004
+ if (intoOutput !== void 0) return inPlace(`${shown(intoOutput)} is a symbolic link into ${shown(logical)}`, lock);
2005
+ const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find((dir) => pathWithin(output, realPathThroughExistingParent(join(packageRoot, dir))) !== null);
2006
+ if (control !== void 0) return inPlace(`${shown(logical)} holds ${control}`, lock);
2007
+ try {
2008
+ return await StagedBuildSession.open({
2009
+ packageRoot,
2010
+ logical,
2011
+ output,
2012
+ writesPackageDist,
2013
+ cleanedEntries,
2014
+ linkCleanedEntries,
2015
+ runId,
2016
+ lock
2017
+ });
2018
+ } catch (error) {
2019
+ if (!(error instanceof CannotStage)) throw error;
2020
+ return inPlace(error.message, lock);
2021
+ }
2022
+ } catch (error) {
2023
+ lock.release();
2024
+ throw error;
2025
+ }
2026
+ }
2027
+ //#endregion
2028
+ //#region src/utils/offered-routes-manifest.ts
2029
+ function withOfferedRoutes(json, offers) {
2030
+ const manifest = JSON.parse(json);
2031
+ if (offers ? manifest.connectRoutes === true : !("connectRoutes" in manifest)) return json;
2032
+ if (offers) manifest.connectRoutes = true;
2033
+ else delete manifest.connectRoutes;
2034
+ return `${JSON.stringify(manifest, null, 2)}\n`;
2035
+ }
2036
+ const slashes = (path) => path.replaceAll("\\", "/");
2037
+ /** Sets `connectRoutes` in the manifest the package's root module imports,
2038
+ * leaving the project's file as it is. */
2039
+ function offeredRoutesManifest(projectRoot, offers) {
2040
+ const manifestPath = slashes(join(projectRoot, "powerhouse.manifest.json"));
2041
+ return {
2042
+ name: "ph-offered-routes-manifest",
2043
+ transform(code, id) {
2044
+ if (slashes(id) !== manifestPath) return null;
2045
+ return {
2046
+ code: withOfferedRoutes(code, offers),
2047
+ map: null
2048
+ };
2049
+ }
2050
+ };
2051
+ }
2052
+ /** Sets `connectRoutes` in the dist copy of the manifest. */
2053
+ function markOfferedRoutes(dir, offers) {
2054
+ const manifestPath = join(dir, "powerhouse.manifest.json");
2055
+ if (!existsSync(manifestPath)) return;
2056
+ const json = readFileSync(manifestPath, "utf-8");
2057
+ writeFileSync(manifestPath, withOfferedRoutes(json, offers));
2058
+ }
2059
+ //#endregion
2060
+ //#region src/services/package-build/steps/stage-logger.ts
2061
+ /**
2062
+ * tsdown labels each file it writes with its directory, relative to the
2063
+ * package. Bundles written to the stage keep the labels of the output
2064
+ * directory they stand in for, so the log reads as without staging.
2065
+ */
2066
+ function stageLogger({ projectRoot, outDir, session }) {
2067
+ const shown = `${relative(projectRoot, resolve(projectRoot, outDir))}${sep}`;
2068
+ const written = `${relative(projectRoot, session.stage())}${sep}`;
2069
+ const label = (message) => typeof message === "string" ? message.replaceAll(written, shown) : message;
2070
+ const relabel = (log) => (...messages) => log(...messages.map(label));
2071
+ return {
2072
+ get level() {
2073
+ return globalLogger.level;
2074
+ },
2075
+ set level(level) {
2076
+ globalLogger.level = level;
2077
+ },
2078
+ info: relabel((...m) => globalLogger.info(...m)),
2079
+ warn: relabel((...m) => globalLogger.warn(...m)),
2080
+ warnOnce: relabel((...m) => globalLogger.warnOnce(...m)),
2081
+ error: relabel((...m) => globalLogger.error(...m)),
2082
+ success: relabel((...m) => globalLogger.success(...m)),
2083
+ clearScreen: (type) => globalLogger.clearScreen(type)
2084
+ };
2085
+ }
2086
+ //#endregion
2087
+ //#region src/services/package-build/steps/bundles.ts
2088
+ /**
2089
+ * Every shared specifier imported from the entry sources; the post-build
2090
+ * scan compares these against the built output.
2091
+ *
2092
+ * Scoped to the specifiers the build actually externalizes: a specifier the
2093
+ * vendor does not publish (the bare `@powerhousedao/shared` root, an
2094
+ * unvendored subpath) is deliberately bundled, so reporting it as "bundled
2095
+ * instead of externalized" would be a false alarm.
2096
+ */
2097
+ function findSharedImportsInSources(root, globs) {
2098
+ const found = /* @__PURE__ */ new Set();
2099
+ for (const file of expandEntryGlobs(root, globs)) {
2100
+ const src = readFileSync(file, "utf8");
2101
+ for (const spec of findSharedImports(src, EXTERNALIZABLE_SHARED_SPECIFIERS)) found.add(spec);
2102
+ }
2103
+ return [...found].sort();
2104
+ }
2105
+ /**
2106
+ * The built JS outputs of a browser build (entry files and chunks).
2107
+ */
2108
+ function readDistBrowserFiles(dir) {
2109
+ const out = [];
2110
+ if (!existsSync(dir)) return out;
2111
+ const walk = (d) => {
2112
+ for (const e of readdirSync(d, { withFileTypes: true })) {
2113
+ const p = join(d, e.name);
2114
+ if (e.isDirectory()) walk(p);
2115
+ else if (e.isFile() && e.name.endsWith(".js")) out.push({
2116
+ path: p,
2117
+ content: readFileSync(p, "utf8")
2118
+ });
2119
+ }
2120
+ };
2121
+ walk(dir);
2122
+ return out;
2123
+ }
2124
+ const browserBundleStep = {
2125
+ id: "browser-bundle",
2126
+ run: async (ctx) => {
2127
+ const { args, projectRoot, session, trace, detection, findings } = ctx;
2128
+ const stage = session.stage();
2129
+ const sharedDeps = !args.noSharedDeps;
2130
+ const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);
2131
+ const config = buildBrowserBuildConfig({
2132
+ sharedDeps,
2133
+ plugins: [
2134
+ externalDepsPlugin(trace, /* @__PURE__ */ new Map(), {
2135
+ root: projectRoot,
2136
+ browser: true,
2137
+ cache: detection
2138
+ }),
2139
+ offeredRoutesManifest(projectRoot, findings.offersRoutes),
2140
+ noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR))
2141
+ ]
2142
+ });
2143
+ await build({
2144
+ ...config,
2145
+ ...session.writesPackageDist && { copy: [{
2146
+ from: "powerhouse.manifest.json",
2147
+ to: stage
2148
+ }] },
2149
+ ...findings.offersRoutes ? { entry: [...browserEntry, { "connect-routes": routesEntry }] } : {},
2150
+ outDir: join(stage, "browser"),
2151
+ customLogger: stageLogger(ctx)
2152
+ });
2153
+ if (sharedDeps) {
2154
+ const imported = findSharedImportsInSources(projectRoot, browserEntry);
2155
+ const bundled = findBundledSharedDeps(imported, readDistBrowserFiles(join(stage, "browser")));
2156
+ if (bundled.length > 0) console.warn(`⚠ shared deps bundled instead of externalized: ${bundled.join(", ")} — check your neverBundle config`);
2157
+ }
2158
+ }
2159
+ };
2160
+ function assertExternalDependenciesDeclared(projectRoot, found, pkg) {
2161
+ for (const dep of found) console.log(`${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`);
2162
+ const undeclared = undeclaredExternalDependencies(found, pkg);
2163
+ if (undeclared.length === 0) return;
2164
+ const lines = undeclared.map((dep) => ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : ""}`);
2165
+ throw new Error(`Packages with native addons or WebAssembly modules must be listed in package.json "dependencies", "optionalDependencies" or "peerDependencies":\n${lines.join("\n")}\n\nThey stay external to the build, and installs of this package skip devDependencies.`);
2166
+ }
2167
+ const nodeBundleStep = {
2168
+ id: "node-bundle",
2169
+ run: async (ctx) => {
2170
+ const { args, projectRoot, session, trace, detection, findings } = ctx;
2171
+ await build({
2172
+ ...buildNodeBuildConfig({
2173
+ sharedDeps: !args.noSharedDeps,
2174
+ plugins: [externalDepsPlugin(trace, findings.external, {
2175
+ root: projectRoot,
2176
+ ignoreDirs: ["editors"],
2177
+ forbidDirs: ["document-models", "scalars"],
2178
+ cache: detection
2179
+ })]
2180
+ }),
2181
+ outDir: join(session.stage(), "node"),
2182
+ customLogger: stageLogger(ctx)
2183
+ });
2184
+ findings.pkg = await readPackage({ cwd: projectRoot });
2185
+ assertExternalDependenciesDeclared(projectRoot, [...findings.external.values()], findings.pkg);
2186
+ }
2187
+ };
2188
+ /** The output entry each bundle step writes, which tsdown empties first. */
2189
+ const CLEANED_BY_STEP = /* @__PURE__ */ new Map([[browserBundleStep.id, "browser"], [nodeBundleStep.id, "node"]]);
2190
+ /** The output entries `steps` empty before they write them, by step id. */
2191
+ const entriesCleanedBy = (steps) => steps.flatMap(({ id }) => CLEANED_BY_STEP.get(id) ?? []);
2192
+ //#endregion
2193
+ //#region src/services/package-build/steps/connect-routes.ts
2194
+ const connectRoutesStep = {
2195
+ id: "connect-routes",
2196
+ run: async ({ projectRoot, findings }) => {
2197
+ await syncProjectConnectRoutes(projectRoot);
2198
+ findings.offersRoutes = existsSync(join(projectRoot, OFFERED_ROUTES_MODULE));
2199
+ }
2200
+ };
2201
+ //#endregion
2202
+ //#region src/services/package-build/steps/definitions.ts
2203
+ /**
2204
+ * The built worker beside ph-cli's own code. Run from source (under vitest),
2205
+ * the TypeScript worker through tsx, so a test runs the current source.
2206
+ */
2207
+ function definitionsWorker() {
2208
+ const root = dirname(createRequire(import.meta.url).resolve("@powerhousedao/ph-cli/package.json"));
2209
+ if (!import.meta.url.endsWith(".ts")) return {
2210
+ path: join(root, "dist", "definitions-worker.mjs"),
2211
+ execArgv: []
2212
+ };
2213
+ return {
2214
+ path: join(root, "src", "services", "model", "definitions-worker.ts"),
2215
+ execArgv: ["--import", import.meta.resolve("tsx")]
2216
+ };
2217
+ }
2218
+ /**
2219
+ * Runs the definition check in a child process: the package's own modules
2220
+ * can exit, hang or start timers there without reaching the build. A child
2221
+ * that ends without a reply, outlives `timeoutMs` or outlives a stop of the
2222
+ * build is killed, and the reply says why the check could not run.
2223
+ */
2224
+ function checkInChild(projectRoot, profile, session, timeoutMs) {
2225
+ const worker = definitionsWorker();
2226
+ return new Promise((resolve) => {
2227
+ let reply;
2228
+ let killedFor;
2229
+ const child = fork(worker.path, [projectRoot, profile], {
2230
+ cwd: projectRoot,
2231
+ execArgv: worker.execArgv,
2232
+ stdio: [
2233
+ "ignore",
2234
+ 2,
2235
+ 2,
2236
+ "ipc"
2237
+ ]
2238
+ });
2239
+ const kill = (why) => {
2240
+ killedFor ??= why;
2241
+ child.kill("SIGKILL");
2242
+ };
2243
+ const timer = setTimeout(() => kill(`the check did not finish within ${timeoutMs / 1e3} seconds`), timeoutMs);
2244
+ const unwatch = session.onCancel(() => kill("the build was stopped"));
2245
+ if (session.stopped()) kill("the build was stopped");
2246
+ const settle = (settled) => {
2247
+ clearTimeout(timer);
2248
+ unwatch();
2249
+ resolve(settled);
2250
+ };
2251
+ child.on("message", (message) => {
2252
+ reply ??= message;
2253
+ });
2254
+ child.on("error", (error) => {
2255
+ kill(error.message);
2256
+ settle({
2257
+ ok: false,
2258
+ message: error.message
2259
+ });
2260
+ });
2261
+ child.on("exit", (code, signal) => {
2262
+ settle(reply ?? {
2263
+ ok: false,
2264
+ message: killedFor ?? `the check ${signal ? `was stopped by ${signal}` : `exited with code ${code}`} before it reported`
2265
+ });
2266
+ });
2267
+ });
2268
+ }
2269
+ /**
2270
+ * Checks the package's definitions after tsc and before any bundle, when
2271
+ * `ph build` asks or with `--release`. Without `--release` it checks the
2272
+ * package when discovery finds a code-first model directory or cannot read
2273
+ * the models directory, never stops the build, and skips without a word a
2274
+ * package with no code-first model. With `--release`
2275
+ * (experimental) it runs the release profile over every model, stored ones
2276
+ * included, and stops the build when the check is invalid or cannot run, a
2277
+ * configuration error included. The package's modules load only in the
2278
+ * definitions worker, which has `timeoutMs` to report.
2279
+ */
2280
+ function definitionsStepWithin(timeoutMs) {
2281
+ return {
2282
+ id: "definitions",
2283
+ after: ["typecheck"],
2284
+ run: async ({ args, checkDefinitions, projectRoot, session, findings }) => {
2285
+ if (!args.release && !checkDefinitions) return;
2286
+ if (!args.release) {
2287
+ const { resolveDefinitionSelection } = await import("document-model/tooling");
2288
+ if (resolveDefinitionSelection({
2289
+ configFile: join(projectRoot, "powerhouse.config.json"),
2290
+ allowMissingConfig: true
2291
+ }).status === "skipped") return;
2292
+ }
2293
+ const { renderCheckReport } = await import("./render-3M3DwFzO.mjs");
2294
+ const printReport = (report) => {
2295
+ const text = renderCheckReport(report);
2296
+ if (report.diagnostics.length > 0) console.warn(`⚠ The definition check reported problems; the build goes on:\n${text}`);
2297
+ else console.log(`✔ ${text}`);
2298
+ };
2299
+ console.log("\n▶ Checking document model definitions...");
2300
+ if (!args.release) {
2301
+ const edit = await checkInChild(projectRoot, "edit", session, timeoutMs);
2302
+ if (edit.ok) printReport(edit.result);
2303
+ else console.warn(`⚠ The definition check could not run: ${edit.message}`);
2304
+ return;
2305
+ }
2306
+ const release = await checkInChild(projectRoot, "release", session, timeoutMs);
2307
+ if (!release.ok) throw new BuildRefusal(`✘ The definition check could not run: ${release.message}`);
2308
+ const { status } = release.result.report;
2309
+ if (status === "invalid" || status === "failed") throw new BuildRefusal(`✘ The release definition check stopped the build:\n${renderCheckReport(release.result.report)}`);
2310
+ findings.release = release.result;
2311
+ printReport(release.result.report);
2312
+ }
2313
+ };
2314
+ }
2315
+ const definitionsStep = definitionsStepWithin(3e5);
2316
+ //#endregion
2317
+ //#region src/services/package-build/steps/package-checks.ts
2318
+ /**
2319
+ * A Powerhouse package's `powerhouse.manifest.json` "name" must match its
2320
+ * `package.json` "name" — Connect and the registry resolve installed versions
2321
+ * by treating the manifest name as the npm package name, so a mismatch silently
2322
+ * breaks resolution. Fail the build early if they diverge. No-op when the
2323
+ * project has no manifest (nothing to compare).
2324
+ */
2325
+ async function assertManifestNameMatchesPackage(projectPath) {
2326
+ const manifestPath = join(projectPath, "powerhouse.manifest.json");
2327
+ if (!existsSync(manifestPath)) return;
2328
+ const { name: packageName } = await readPackage({ cwd: projectPath });
2329
+ let manifestName;
2330
+ try {
2331
+ manifestName = JSON.parse(readFileSync(manifestPath, "utf-8")).name;
2332
+ } catch {
2333
+ throw new Error(`Failed to parse "powerhouse.manifest.json" at ${manifestPath}. Make sure it is valid JSON.`);
2334
+ }
2335
+ if (manifestName !== packageName) throw new Error(`Package name mismatch — "package.json" and "powerhouse.manifest.json" must have the same "name":\n package.json "name": ${JSON.stringify(packageName)}\n powerhouse.manifest.json "name": ${JSON.stringify(manifestName)}\n\nUpdate one so they match, then run the build again.`);
2336
+ }
2337
+ const manifestNameStep = {
2338
+ id: "manifest-name",
2339
+ run: ({ projectRoot }) => assertManifestNameMatchesPackage(projectRoot)
2340
+ };
2341
+ const piecesOutDirStep = {
2342
+ id: "pieces-out-dir",
2343
+ run: ({ outDir, pieces }) => {
2344
+ assertPiecesOutDir({
2345
+ outDir,
2346
+ pieces: [...pieces]
2347
+ });
2348
+ return Promise.resolve();
2349
+ }
2350
+ };
2351
+ //#endregion
2352
+ //#region src/services/package-build/steps/pieces.ts
2353
+ const piecesStep = {
2354
+ id: "pieces",
2355
+ run: async (ctx) => {
2356
+ const { projectRoot, outDir, pieces, session, trace, detection, findings } = ctx;
2357
+ const stage = session.stage();
2358
+ if (!existsSync(pieceListPath({
2359
+ projectRoot,
2360
+ outDir: stage
2361
+ }))) return;
2362
+ const pkg = findings.pkg ?? await readPackage({ cwd: projectRoot });
2363
+ const customLogger = stageLogger(ctx);
2364
+ findings.built = await buildPieces({
2365
+ projectRoot,
2366
+ outDir,
2367
+ writeTo: stage,
2368
+ pieces: [...pieces]
2369
+ }, {
2370
+ name: pkg.name,
2371
+ version: pkg.version,
2372
+ license: typeof pkg.license === "string" ? pkg.license : void 0
2373
+ }, {
2374
+ bundle: (config) => build({
2375
+ ...config,
2376
+ customLogger
2377
+ }),
2378
+ trace,
2379
+ cache: detection
2380
+ });
2381
+ }
2382
+ };
2383
+ const distManifestStep = {
2384
+ id: "dist-manifest",
2385
+ run: ({ projectRoot, pieces, session, findings }) => {
2386
+ syncDistManifest({
2387
+ projectRoot,
2388
+ outDir: session.stage(),
2389
+ pieces: [...pieces]
2390
+ }, findings.built, externalDependencyVersions(findings.external.values()));
2391
+ return Promise.resolve();
2392
+ }
2393
+ };
2394
+ const offeredRoutesStep = {
2395
+ id: "offered-routes",
2396
+ run: ({ session, findings }) => {
2397
+ markOfferedRoutes(session.stage(), findings.offersRoutes);
2398
+ return Promise.resolve();
2399
+ }
2400
+ };
2401
+ //#endregion
2402
+ //#region src/services/release/consumer.ts
2403
+ const CONDITIONS = {
2404
+ node: /* @__PURE__ */ new Set([
2405
+ "node",
2406
+ "import",
2407
+ "module-sync",
2408
+ "default"
2409
+ ]),
2410
+ browser: /* @__PURE__ */ new Set([
2411
+ "browser",
2412
+ "import",
2413
+ "module",
2414
+ "default"
2415
+ ])
2416
+ };
2417
+ const IMPORTABLE = /\.(m?js|cjs)$/;
2418
+ function resolveTarget(value, conditions) {
2419
+ if (typeof value === "string") return value;
2420
+ if (Array.isArray(value)) {
2421
+ for (const item of value) {
2422
+ const target = resolveTarget(item, conditions);
2423
+ if (target !== void 0) return target;
2424
+ }
2425
+ return;
2426
+ }
2427
+ if (value === null || typeof value !== "object") return void 0;
2428
+ for (const [key, nested] of Object.entries(value)) {
2429
+ if (!conditions.has(key)) continue;
2430
+ const target = resolveTarget(nested, conditions);
2431
+ if (target !== void 0) return target;
2432
+ }
2433
+ }
2434
+ function targetsOf(value) {
2435
+ if (typeof value === "string") return [value];
2436
+ if (Array.isArray(value)) return value.flatMap(targetsOf);
2437
+ if (value === null || typeof value !== "object") return [];
2438
+ return Object.values(value).flatMap(targetsOf);
2439
+ }
2440
+ function subpaths(manifest) {
2441
+ const { exports } = manifest;
2442
+ if (exports === void 0) return [];
2443
+ if (exports !== null && typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) return Object.entries(exports);
2444
+ return [[".", exports]];
2445
+ }
2446
+ const packedPath = (target) => target.replace(/^\.\//, "");
2447
+ function packedEntries(manifest, files, unbuilt) {
2448
+ const imports = {
2449
+ node: [],
2450
+ browser: []
2451
+ };
2452
+ const missing = [];
2453
+ const entries = subpaths(manifest);
2454
+ if (entries.length === 0) {
2455
+ imports.node.push(manifest.name);
2456
+ return {
2457
+ imports,
2458
+ missing
2459
+ };
2460
+ }
2461
+ for (const [subpath, value] of entries) {
2462
+ const targets = targetsOf(value).filter((target) => !target.includes("*"));
2463
+ const absent = targets.filter((target) => !files.has(packedPath(target)));
2464
+ if (unbuilt.has(subpath) && absent.length === targets.length) continue;
2465
+ missing.push(...absent.map((target) => `exports["${subpath}"] names ${target}`));
2466
+ if (subpath === "./package.json") continue;
2467
+ for (const consumer of ["node", "browser"]) {
2468
+ const target = resolveTarget(value, CONDITIONS[consumer]);
2469
+ if (target === void 0 || !IMPORTABLE.test(target)) continue;
2470
+ const specifier = `${manifest.name}${subpath.slice(1)}`;
2471
+ if (!subpath.includes("*")) {
2472
+ imports[consumer].push(specifier);
2473
+ continue;
2474
+ }
2475
+ const [before, after] = packedPath(target).split("*");
2476
+ const [subBefore, subAfter] = specifier.split("*");
2477
+ for (const file of [...files].sort()) {
2478
+ if (!file.startsWith(before) || !file.endsWith(after)) continue;
2479
+ const star = file.slice(before.length, file.length - after.length);
2480
+ if (star !== "") imports[consumer].push(`${subBefore}${star}${subAfter}`);
2481
+ }
2482
+ }
2483
+ }
2484
+ return {
2485
+ imports,
2486
+ missing
2487
+ };
2488
+ }
2489
+ function installed(projectRoot, name) {
2490
+ for (let directory = projectRoot;; directory = dirname(directory)) {
2491
+ const candidate = join(directory, "node_modules", ...name.split("/"));
2492
+ if (existsSync(join(candidate, "package.json"))) return realpathSync.native(candidate);
2493
+ if (dirname(directory) === directory) return void 0;
2494
+ }
2495
+ }
2496
+ const IMPORT_EACH = `import { writeFileSync } from "node:fs";
2497
+ import { registerHooks } from "node:module";
2498
+ const { specifiers, conditions, resultFile } = JSON.parse(process.argv[1]);
2499
+ if (conditions) {
2500
+ registerHooks({
2501
+ resolve: (specifier, context, next) => next(specifier, {
2502
+ ...context,
2503
+ conditions: context.conditions.includes("require")
2504
+ ? conditions.map((name) => (name === "import" ? "require" : name))
2505
+ : conditions,
2506
+ }),
2507
+ });
2508
+ }
2509
+ const failed = [];
2510
+ for (const specifier of specifiers) {
2511
+ try { await import(specifier); }
2512
+ catch (error) { failed.push(specifier + ": " + (error instanceof Error ? error.message : String(error)).split("\\n")[0]); }
2513
+ }
2514
+ writeFileSync(resultFile, JSON.stringify(failed));
2515
+ process.exit(0);
2516
+ `;
2517
+ const TIMEOUT_MS = 12e4;
2518
+ const STDERR_LIMIT = 65536;
2519
+ async function importAll(consumerRoot, consumer, specifiers, signal) {
2520
+ if (specifiers.length === 0) return [];
2521
+ const env = { ...process.env };
2522
+ delete env.NODE_OPTIONS;
2523
+ delete env.NODE_PATH;
2524
+ const resultFile = join(dirname(consumerRoot), `${consumer}-result.json`);
2525
+ const input = {
2526
+ specifiers,
2527
+ conditions: consumer === "browser" ? [...CONDITIONS.browser] : null,
2528
+ resultFile
2529
+ };
2530
+ const ended = await new Promise((done) => {
2531
+ const child = spawn(process.execPath, [
2532
+ "--input-type=module",
2533
+ "-e",
2534
+ IMPORT_EACH,
2535
+ JSON.stringify(input)
2536
+ ], {
2537
+ cwd: consumerRoot,
2538
+ env,
2539
+ signal,
2540
+ stdio: [
2541
+ "ignore",
2542
+ "ignore",
2543
+ "pipe"
2544
+ ]
2545
+ });
2546
+ let timedOut = false;
2547
+ const timer = setTimeout(() => {
2548
+ timedOut = true;
2549
+ child.kill();
2550
+ }, TIMEOUT_MS);
2551
+ let stderr = "";
2552
+ child.stderr.setEncoding("utf8");
2553
+ child.stderr.on("data", (chunk) => {
2554
+ if (stderr.length < STDERR_LIMIT) stderr += chunk;
2555
+ });
2556
+ child.on("error", (error) => done(error.message));
2557
+ child.on("close", (code, killedBy) => {
2558
+ clearTimeout(timer);
2559
+ if (timedOut) {
2560
+ done(`did not finish its imports within ${TIMEOUT_MS / 1e3} seconds`);
2561
+ return;
2562
+ }
2563
+ const how = killedBy === null ? `exited with ${code}` : `got ${killedBy}`;
2564
+ const why = stderr.trim().split("\n")[0];
2565
+ done(why ? `${how}: ${why}` : how);
2566
+ });
2567
+ });
2568
+ if (!existsSync(resultFile)) return [`${consumer} consumer did not finish: it ${ended}`];
2569
+ return JSON.parse(readFileSync(resultFile, "utf8")).map((failure) => `${consumer} consumer cannot import ${failure.replace(/ imported from \S*\[eval\d*\]$/, "")}`);
2570
+ }
2571
+ async function checkPackedConsumer(projectRoot, packed, unbuilt, signal) {
2572
+ const { manifest, files } = packed;
2573
+ const consumerRoot = join(packed.directory, "consumer");
2574
+ const modules = join(consumerRoot, "node_modules");
2575
+ const installRoot = join(modules, ...manifest.name.split("/"));
2576
+ for (const [path, bytes] of files) {
2577
+ const target = resolve(installRoot, path);
2578
+ if (!target.startsWith(`${installRoot}${sep}`)) return [`the tarball has an entry outside the package: ${path}`];
2579
+ mkdirSync(dirname(target), { recursive: true });
2580
+ writeFileSync(target, bytes);
2581
+ }
2582
+ writeFileSync(join(consumerRoot, "package.json"), `${JSON.stringify({
2583
+ name: "ph-packed-consumer",
2584
+ private: true,
2585
+ type: "module"
2586
+ })}\n`);
2587
+ const runtime = /* @__PURE__ */ new Set([
2588
+ ...Object.keys(manifest.dependencies ?? {}),
2589
+ ...Object.keys(manifest.optionalDependencies ?? {}),
2590
+ ...Object.keys(manifest.peerDependencies ?? {})
2591
+ ]);
2592
+ for (const name of runtime) {
2593
+ if (name === manifest.name) continue;
2594
+ const from = installed(projectRoot, name);
2595
+ if (from === void 0) continue;
2596
+ const link = join(modules, ...name.split("/"));
2597
+ mkdirSync(dirname(link), { recursive: true });
2598
+ symlinkSync(from, link, process.platform === "win32" ? "junction" : "dir");
2599
+ }
2600
+ const { imports, missing } = packedEntries(manifest, new Set(files.keys()), unbuilt);
2601
+ const failures = await Promise.all(["node", "browser"].map((consumer) => importAll(consumerRoot, consumer, imports[consumer], signal)));
2602
+ return [...missing.map((entry) => `${entry}, which the package does not contain`), ...failures.flat()].map((failure) => {
2603
+ const shown = failure.replaceAll(`${consumerRoot}${sep}`, "").replaceAll(consumerRoot, ".");
2604
+ return sep === "\\" ? shown.replaceAll("\\", "/") : shown;
2605
+ });
2606
+ }
2607
+ //#endregion
2608
+ //#region src/services/release/issuance.ts
2609
+ const under$1 = (path, directory) => path === directory || path.startsWith(`${directory}/`);
2610
+ /**
2611
+ * Whether a release build may write an approval, and what its revision
2612
+ * leaves out: the replaced directory, and what tsc writes outside the
2613
+ * output.
2614
+ */
2615
+ function planApproval(build) {
2616
+ const { release, startFiles, outputs } = build;
2617
+ if (!build.typesOk) return { refused: "the build went on despite tsc's type errors" };
2618
+ if (release === void 0 || startFiles === void 0) return { refused: "the release check did not run" };
2619
+ return {
2620
+ release,
2621
+ startFiles,
2622
+ excluded: [...outputs.slice(1), ...build.compilerOutputs.filter((path) => !outputs.some((directory) => under$1(path, directory)))]
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Why the approval may not be written because the package changed while it
2627
+ * was built, comparing its files at the start, minus what the revision
2628
+ * leaves out, with `endFiles`; undefined when nothing changed.
2629
+ */
2630
+ function changedWhileBuilt(plan, endFiles) {
2631
+ const leftOut = (path) => plan.excluded.some((exclusion) => under$1(path, exclusion));
2632
+ const changed = changedPaths(plan.startFiles.filter(({ path }) => !leftOut(path)), endFiles);
2633
+ return changed.length === 0 ? void 0 : `the package's files changed while it was built (${listed(changed)})`;
2634
+ }
2635
+ //#endregion
2636
+ //#region src/services/package-build/steps/release-approval.ts
2637
+ const under = (path, directory) => path === directory || path.startsWith(`${directory}/`);
2638
+ /**
2639
+ * The output directory as given, then the directory the build replaces when
2640
+ * that is a symlink to another place in the package: neither is a source.
2641
+ */
2642
+ function outputDirectories(projectRoot, outDir, target) {
2643
+ const output = packagePath(projectRoot, outDir);
2644
+ const real = packagePath(projectRoot, target);
2645
+ return real !== ".." && !real.startsWith("../") && !isAbsolute(real) && !under(real, output) ? [output, real] : [output];
2646
+ }
2647
+ /** With `--release`, records the package's files before anything is built. */
2648
+ const releaseStartStep = {
2649
+ id: "release-start",
2650
+ run: ({ args, projectRoot, outDir, session, findings }) => {
2651
+ if (args.release) findings.releaseStart = revisionFiles(projectRoot, outputDirectories(projectRoot, outDir, session.output));
2652
+ return Promise.resolve();
2653
+ }
2654
+ };
2655
+ /** Exports `ph init` declares whose entry the build skips when its source is absent. */
2656
+ const OPTIONAL_EXPORTS = {
2657
+ "./scalars": "scalars/index.ts",
2658
+ "./pieces": "pieces/index.ts"
2659
+ };
2660
+ const unbuiltExports = (projectRoot, findings) => /* @__PURE__ */ new Set([...Object.entries(OPTIONAL_EXPORTS).filter(([, source]) => !existsSync(join(projectRoot, source))).map(([subpath]) => subpath), ...findings.offersRoutes ? [] : ["./connect-routes"]]);
2661
+ const notWritten = (why) => new BuildRefusal(`✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`);
2662
+ /**
2663
+ * With `--release`, once the output is replaced: records what the release
2664
+ * check approved and what `npm pack` publishes from the new output, unless
2665
+ * tsc's errors were accepted, the package changed while it was built, or the
2666
+ * packed tarball fails to install and import in a scratch consumer.
2667
+ */
2668
+ const releaseApprovalStep = {
2669
+ id: "release-approval",
2670
+ when: "committed",
2671
+ run: async ({ args, projectRoot, outDir, session, findings }) => {
2672
+ if (args.release) await recordApproval(projectRoot, outputDirectories(projectRoot, outDir, session.output), findings, session);
2673
+ }
2674
+ };
2675
+ async function recordApproval(projectRoot, outputs, findings, session) {
2676
+ const plan = planApproval({
2677
+ typesOk: findings.typesOk,
2678
+ release: findings.release,
2679
+ startFiles: findings.releaseStart,
2680
+ outputs,
2681
+ compilerOutputs: findings.compilerOutputs.map((path) => packagePath(projectRoot, path))
2682
+ });
2683
+ if ("refused" in plan) throw notWritten(plan.refused);
2684
+ const { release, excluded } = plan;
2685
+ const [output] = outputs;
2686
+ const files = revisionFiles(projectRoot, [output, ...excluded]);
2687
+ const changed = changedWhileBuilt(plan, files);
2688
+ if (changed !== void 0) throw notWritten(changed);
2689
+ let packed;
2690
+ try {
2691
+ packed = packRelease(projectRoot);
2692
+ } catch (error) {
2693
+ throw notWritten(error instanceof Error ? error.message : String(error));
2694
+ }
2695
+ let published;
2696
+ const stop = new AbortController();
2697
+ const unwatch = session.onCancel(() => {
2698
+ stop.abort();
2699
+ packed.dispose();
2700
+ });
2701
+ try {
2702
+ const failures = await checkPackedConsumer(projectRoot, packed, unbuiltExports(projectRoot, findings), stop.signal);
2703
+ if (failures.length > 0) throw notWritten(`the packed package does not install and import in a scratch consumer: ${listed(failures)}`);
2704
+ published = packedDigests(packed);
2705
+ } finally {
2706
+ unwatch();
2707
+ packed.dispose();
2708
+ }
2709
+ const phCliVersion = getVersion();
2710
+ writeReleaseApproval(projectRoot, {
2711
+ kind: "powerhouse.release-approval",
2712
+ formatVersion: 1,
2713
+ phCliVersion,
2714
+ outDir: output,
2715
+ packageRevision: {
2716
+ digest: packageRevision(files, { [PH_CLI_BINDING]: phCliVersion }),
2717
+ excluded
2718
+ },
2719
+ publishedFiles: published,
2720
+ report: {
2721
+ profile: "release",
2722
+ status: release.report.status,
2723
+ definitions: release.report.definitions
2724
+ },
2725
+ scalars: release.scalars,
2726
+ hostValidation: release.host
2727
+ });
2728
+ console.log(`✔ Release approval written to ${RELEASE_APPROVAL_PATH}`);
2729
+ }
2730
+ //#endregion
2731
+ //#region src/services/package-build/steps/stylesheet.ts
2732
+ function sourcePath(projectRoot, path) {
2733
+ return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll("\\", "/")}`;
2734
+ }
2735
+ const stylesheetStep = {
2736
+ id: "stylesheet",
2737
+ run: ({ agent, projectRoot, session }) => {
2738
+ const stage = session.stage();
2739
+ const command = resolveCommand(agent, "execute-local", [
2740
+ "tailwindcss",
2741
+ "--input",
2742
+ "-",
2743
+ "--minify"
2744
+ ]);
2745
+ if (command === null) throw new BuildRefusal("You need to have tailwindcss installed to use the `build` command.");
2746
+ const stylePath = join(projectRoot, "style.css");
2747
+ const style = existsSync(stylePath) ? readFileSync(stylePath, "utf-8") : void 0;
2748
+ const compiled = execSync(`${command.command} ${command.args.join(" ")}`, {
2749
+ cwd: projectRoot,
2750
+ input: packageStyleEntry(style, {
2751
+ browserDir: sourcePath(projectRoot, join(stage, "browser")),
2752
+ localPackages: localPackageNames(projectRoot)
2753
+ }),
2754
+ encoding: "utf-8",
2755
+ stdio: [
2756
+ "pipe",
2757
+ "pipe",
2758
+ "inherit"
2759
+ ],
2760
+ maxBuffer: 67108864
2761
+ });
2762
+ const distDir = session.writesPackageDist ? stage : join(projectRoot, "dist");
2763
+ mkdirSync(distDir, { recursive: true });
2764
+ writeFileSync(join(distDir, "style.css"), packageStylesheet(compiled));
2765
+ return Promise.resolve();
2766
+ }
2767
+ };
2768
+ //#endregion
2769
+ //#region src/services/package-build/steps/typecheck.ts
2770
+ const TYPE_ERROR_RISK = "A package built with type errors can load and still fail at runtime.";
2771
+ const UNSAFE_BUILD_WARNING = "⚠ Built despite type errors. " + TYPE_ERROR_RISK + " Fix them before you publish or deploy it.";
2772
+ /** The root project's config, as `tsc --showConfig` prints it. */
2773
+ function showCompilerConfig(agent, projectRoot) {
2774
+ const showConfig = resolveCommand(agent, "execute-local", ["tsc", "--showConfig"]);
2775
+ if (showConfig === null) return void 0;
2776
+ try {
2777
+ return parseShownConfig(execSync(`${showConfig.command} ${showConfig.args.join(" ")}`, {
2778
+ cwd: projectRoot,
2779
+ encoding: "utf8",
2780
+ stdio: [
2781
+ "ignore",
2782
+ "pipe",
2783
+ "ignore"
2784
+ ]
2785
+ }));
2786
+ } catch {
2787
+ return;
2788
+ }
2789
+ }
2790
+ function declarationsMissing(options, projectRoot) {
2791
+ const path = declarationDirectory(options, projectRoot);
2792
+ if (path === void 0) return false;
2793
+ return !existsSync(path) || readdirSync(path).length === 0;
2794
+ }
2795
+ function isInteractive() {
2796
+ return Boolean(process.stdin.isTTY) && !process.env.CI;
2797
+ }
2798
+ async function confirmBuildDespiteTypeErrors() {
2799
+ const hint = "Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.";
2800
+ if (!isInteractive()) throw new BuildRefusal(`\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\n${hint}`);
2801
+ const enquirer = await import("enquirer");
2802
+ let confirmed;
2803
+ try {
2804
+ confirmed = (await enquirer.default.prompt({
2805
+ type: "confirm",
2806
+ name: "confirmed",
2807
+ message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,
2808
+ initial: false
2809
+ })).confirmed;
2810
+ } catch {
2811
+ confirmed = false;
2812
+ }
2813
+ if (!confirmed) throw new BuildRefusal(`Build cancelled. ${hint}`);
2814
+ }
2815
+ //#endregion
2816
+ //#region src/services/package-build/steps/standard.ts
2817
+ /**
2818
+ * `ph build`'s steps in the order they run. Another phase inserts its own
2819
+ * with `[...standardBuildSteps, ...more]` and `after` on the step it follows.
2820
+ */
2821
+ const standardBuildSteps = [
2822
+ releaseStartStep,
2823
+ manifestNameStep,
2824
+ piecesOutDirStep,
2825
+ connectRoutesStep,
2826
+ {
2827
+ id: "typecheck",
2828
+ run: async ({ agent, args, outDir, projectRoot, session, findings }) => {
2829
+ const config = showCompilerConfig(agent, projectRoot);
2830
+ const force = config !== void 0 && declarationsMissing(config.options, projectRoot);
2831
+ let generated;
2832
+ if (config !== void 0) {
2833
+ const configFile = join(projectRoot, "tsconfig.json");
2834
+ const outputs = await compilerOutputs(config, {
2835
+ configFile,
2836
+ packageRoot: projectRoot,
2837
+ buildDirectory: join(projectRoot, BUILD_DIRECTORY),
2838
+ agent,
2839
+ output: session.output
2840
+ });
2841
+ generated = await session.prepareCompiler({
2842
+ configFile,
2843
+ config,
2844
+ outputs
2845
+ });
2846
+ findings.compilerOutputs = outputs.map(({ path }) => path);
2847
+ }
2848
+ const tscCommand = resolveCommand(agent, "execute-local", [
2849
+ "tsc",
2850
+ "--build",
2851
+ ...force ? ["--force"] : [],
2852
+ ...generated ? [relative(projectRoot, generated)] : []
2853
+ ]);
2854
+ if (tscCommand === null) throw new BuildRefusal("You need to have typescript installed to use the `build` command.");
2855
+ console.log("\n▶ Type-checking and emitting types via tsc...");
2856
+ try {
2857
+ execSync(`${tscCommand.command} ${tscCommand.args.join(" ")}`, { stdio: "inherit" });
2858
+ console.log("✔ Types emitted to", join(outDir, "types"));
2859
+ findings.typesOk = true;
2860
+ } catch {
2861
+ findings.typesOk = false;
2862
+ }
2863
+ session.compilerOutputsWritten();
2864
+ if (!findings.typesOk && !args.ignoreTypeErrors) await confirmBuildDespiteTypeErrors();
2865
+ }
2866
+ },
2867
+ definitionsStep,
2868
+ browserBundleStep,
2869
+ nodeBundleStep,
2870
+ piecesStep,
2871
+ distManifestStep,
2872
+ offeredRoutesStep,
2873
+ stylesheetStep,
2874
+ releaseApprovalStep
2875
+ ];
2876
+ //#endregion
2877
+ //#region src/services/package-build/steps/trace.ts
2878
+ function createTraceFiles() {
2879
+ const cache = {};
2880
+ return (file) => traceFile(file, cache);
2881
+ }
2882
+ async function traceFile(file, cache) {
2883
+ const { fileList, reasons } = await nodeFileTrace([file], {
2884
+ base: "/",
2885
+ cache
2886
+ });
2887
+ const absolute = (p) => resolve("/", p);
2888
+ return {
2889
+ fileList: new Set([...fileList].map(absolute)),
2890
+ reasons: new Map([...reasons].map(([p, reason]) => [absolute(p), { parents: new Set([...reason.parents].map(absolute)) }]))
2891
+ };
2892
+ }
2893
+ //#endregion
2894
+ //#region src/services/package-build/run-build.ts
2895
+ const STOP_SIGNALS = [
2896
+ "SIGINT",
2897
+ "SIGTERM",
2898
+ "SIGHUP"
2899
+ ];
2900
+ /**
2901
+ * The signal listeners signal-exit installs: each ends the process when
2902
+ * only signal-exit listeners are left, so they are not an embedding
2903
+ * process that keeps running. Read from the counts its copies share.
2904
+ */
2905
+ function exitOnlyListeners() {
2906
+ const count = (emitter) => {
2907
+ const value = emitter?.count;
2908
+ return typeof value === "number" ? value : 0;
2909
+ };
2910
+ const shared = globalThis;
2911
+ const legacy = process;
2912
+ return count(shared[Symbol.for("signal-exit emitter")]) + count(legacy.__signal_exit_emitter__);
2913
+ }
2914
+ /**
2915
+ * Stops the build when the process is told to stop, for as long as it runs.
2916
+ * The handler runs first and removes itself, so the listeners already there
2917
+ * act as if it had never been added. When one of them keeps the process
2918
+ * running (an embedding process), the handler only cancels: the step runner
2919
+ * rolls back once the running step settles, and the lock is released after
2920
+ * that. Otherwise the process should end with the signal: the handler
2921
+ * restores the previous output at once, releases the lock and, with no
2922
+ * listener left, re-raises the signal. The run and its snapshot stay for
2923
+ * the next build to replay. The lock does not: a dead owner's lock is taken
2924
+ * over only from the same host, which a new container or a renamed machine
2925
+ * is not. A signal-exit callback can still keep the process running; then
2926
+ * the runner restores again from that snapshot once the running step
2927
+ * settles.
2928
+ */
2929
+ function stopOnSignal(session, ownsProcess) {
2930
+ const stop = (signal) => {
2931
+ session.cancel(signal);
2932
+ remove();
2933
+ if (process.listenerCount(signal) > exitOnlyListeners()) return;
2934
+ session.rollback();
2935
+ if (ownsProcess) session.releaseLock();
2936
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
2937
+ };
2938
+ const remove = () => {
2939
+ for (const signal of STOP_SIGNALS) process.removeListener(signal, stop);
2940
+ };
2941
+ for (const signal of STOP_SIGNALS) process.prependListener(signal, stop);
2942
+ return remove;
2943
+ }
2944
+ /**
2945
+ * Builds the package in the current directory: every step writes to a stage,
2946
+ * which replaces the output directory only when all of them succeed. A
2947
+ * failure, a refusal or a stop signal leaves the previous output and
2948
+ * compiler outputs as they were.
2949
+ */
2950
+ async function buildPackage(args, options = {}) {
2951
+ const { outDir } = args;
2952
+ const projectRoot = process.cwd();
2953
+ const steps = options.steps ?? standardBuildSteps;
2954
+ const session = await openBuildSession({
2955
+ packageRoot: projectRoot,
2956
+ outDir,
2957
+ cleanedEntries: entriesCleanedBy(steps),
2958
+ linkCleanedEntries: options.steps === void 0
2959
+ });
2960
+ const stopListening = stopOnSignal(session, options.ownsProcess ?? false);
2961
+ try {
2962
+ const ctx = {
2963
+ args,
2964
+ projectRoot,
2965
+ outDir,
2966
+ agent: (await detect())?.agent ?? "npm",
2967
+ session,
2968
+ checkDefinitions: options.checkDefinitions ?? false,
2969
+ pieces: planPieces(projectRoot, outDir),
2970
+ detection: createDetectionCache(),
2971
+ trace: createTraceFiles(),
2972
+ findings: {
2973
+ offersRoutes: false,
2974
+ typesOk: true,
2975
+ compilerOutputs: [],
2976
+ releaseStart: void 0,
2977
+ release: void 0,
2978
+ external: /* @__PURE__ */ new Map(),
2979
+ pkg: void 0,
2980
+ built: []
2981
+ }
2982
+ };
2983
+ await runBuildSteps(steps, ctx, session);
2984
+ if (!ctx.findings.typesOk) console.warn(`\n${UNSAFE_BUILD_WARNING}`);
2985
+ } finally {
2986
+ stopListening();
2987
+ session.rollback();
2988
+ session.close();
2989
+ }
2990
+ }
2991
+ //#endregion
2992
+ //#region src/services/subgraph-build-step.ts
2993
+ /** The definitions step checks the package, subgraphs included, unless
2994
+ * discovery skips it, as it does for a package with no document model. */
2995
+ async function definitionsStepCoversSubgraphs(projectRoot) {
2996
+ const { resolveDefinitionSelection } = await import("document-model/tooling");
2997
+ return resolveDefinitionSelection({
2998
+ configFile: join(projectRoot, "powerhouse.config.json"),
2999
+ allowMissingConfig: true
3000
+ }).status !== "skipped";
3001
+ }
3002
+ /**
3003
+ * Checks a package's code-first subgraphs in `ph build`'s edit profile when
3004
+ * the definitions step does not: a package where discovery skips it. Under `--release` the definitions
3005
+ * step runs the release profile, which carries the subgraph checks and
3006
+ * refuses on their errors.
3007
+ */
3008
+ function subgraphStepWithin(timeoutMs) {
3009
+ return {
3010
+ id: "subgraphs",
3011
+ after: ["definitions"],
3012
+ run: async ({ args, checkDefinitions, projectRoot, session }) => {
3013
+ if (args.release || !checkDefinitions) return;
3014
+ if (await definitionsStepCoversSubgraphs(projectRoot)) return;
3015
+ const { renderCheckReport } = await import("./render-3M3DwFzO.mjs");
3016
+ console.log("\n▶ Checking subgraph definitions...");
3017
+ const edit = await checkInChild(projectRoot, "edit", session, timeoutMs);
3018
+ if (!edit.ok) {
3019
+ console.warn(`⚠ The subgraph check could not run: ${edit.message}`);
3020
+ return;
3021
+ }
3022
+ const text = renderCheckReport(edit.result);
3023
+ if (edit.result.diagnostics.length > 0) console.warn(`⚠ The subgraph check reported problems; the build goes on:\n${text}`);
3024
+ else console.log(`✔ ${text}`);
3025
+ }
3026
+ };
3027
+ }
3028
+ const subgraphStep = subgraphStepWithin(3e5);
3029
+ //#endregion
3030
+ //#region src/services/build.ts
3031
+ /**
3032
+ * The gate loads codegen, so a build without `checkDefinitions` or without a
3033
+ * `subgraphs/` directory never imports it.
3034
+ */
3035
+ async function withSubgraphStep(options) {
3036
+ if (!options.checkDefinitions) return options;
3037
+ if (!existsSync(join(process.cwd(), "subgraphs"))) return options;
3038
+ const { hasCodeFirstSubgraph } = await import("./subgraph-gate-j9ywj6KA.mjs");
3039
+ if (!hasCodeFirstSubgraph(process.cwd())) return options;
3040
+ return {
3041
+ ...options,
3042
+ steps: [...options.steps ?? standardBuildSteps, subgraphStep]
3043
+ };
3044
+ }
3045
+ /**
3046
+ * `ph build`, and the package build `ph connect build` and the switchboard
3047
+ * runner start from. A refusal (missing tsc or tailwindcss, type errors not
3048
+ * accepted, a release check that fails) prints its message and exits 1 once
3049
+ * the previous output is back, as these callers have always seen it.
3050
+ * Only `ph build` passes `checkDefinitions`, so the other callers import
3051
+ * none of the package's modules. A command that adds steps passes
3052
+ * `[...standardBuildSteps, ...its own]` as `steps`.
3053
+ */
3054
+ async function runBuild(args, options = {}) {
3055
+ try {
3056
+ return await buildPackage(args, await withSubgraphStep(options));
3057
+ } catch (error) {
3058
+ if (!(error instanceof BuildRefusal)) throw error;
3059
+ console.error(error.message);
3060
+ process.exit(error.exitCode);
3061
+ }
3062
+ }
3063
+ //#endregion
3064
+ export { assertExternalDependenciesDeclared as i, createTraceFiles as n, assertManifestNameMatchesPackage as r, runBuild as t };
3065
+
3066
+ //# sourceMappingURL=build-DDG00Wbj.mjs.map
3067
+ //# debugId=e005b454-89ec-573f-8ea2-d302567bbd23