@powerhousedao/ph-cli 6.2.3-dev.94 → 6.2.3-dev.95

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 (85) hide show
  1. package/dist/build-BYl_Uu3s.mjs +4 -0
  2. package/dist/build-Dfrq_MIX.mjs +2036 -0
  3. package/dist/build-Dfrq_MIX.mjs.map +1 -0
  4. package/dist/check-XulH7-hn.mjs +4 -0
  5. package/dist/check-bEVuToRY.mjs +60 -0
  6. package/dist/check-bEVuToRY.mjs.map +1 -0
  7. package/dist/{check-Dmx8U75w.mjs → check-d-VEsSZX.mjs} +4 -4
  8. package/dist/{check-Dmx8U75w.mjs.map → check-d-VEsSZX.mjs.map} +1 -1
  9. package/dist/{cli-connect-override-CLHLCeF5.mjs → cli-connect-override-BQr3yjC_.mjs} +4 -4
  10. package/dist/{cli-connect-override-CLHLCeF5.mjs.map → cli-connect-override-BQr3yjC_.mjs.map} +1 -1
  11. package/dist/cli.mjs +4 -4
  12. package/dist/{compound-Cv5yxdLC-DAYAbASE.mjs → compound-DO_mvh0O-D254asEo.mjs} +36 -19
  13. package/dist/{compound-Cv5yxdLC-DAYAbASE.mjs.map → compound-DO_mvh0O-D254asEo.mjs.map} +1 -1
  14. package/dist/{connect-build-D20s-YzT.mjs → connect-build-DrKrCMPR.mjs} +8 -7
  15. package/dist/connect-build-DrKrCMPR.mjs.map +1 -0
  16. package/dist/{connect-config-CoB5ejxj.mjs → connect-config-DWJf22Ro.mjs} +4 -4
  17. package/dist/{connect-config-CoB5ejxj.mjs.map → connect-config-DWJf22Ro.mjs.map} +1 -1
  18. package/dist/{connect-studio-CCjF7Fo2.mjs → connect-studio-DTZEwZ4C.mjs} +3 -3
  19. package/dist/{connect-studio-DWKRk0Zc.mjs → connect-studio-DWty6fZd.mjs} +4 -4
  20. package/dist/{connect-studio-DWKRk0Zc.mjs.map → connect-studio-DWty6fZd.mjs.map} +1 -1
  21. package/dist/definitions-worker.d.mts +96 -0
  22. package/dist/definitions-worker.d.mts.map +1 -0
  23. package/dist/definitions-worker.mjs +28 -0
  24. package/dist/definitions-worker.mjs.map +1 -0
  25. package/dist/{dist-CF0RfguD.mjs → dist-BOjmQhjX.mjs} +5 -5
  26. package/dist/dist-BOjmQhjX.mjs.map +1 -0
  27. package/dist/evidence-BiMKzRLV.mjs +120 -0
  28. package/dist/evidence-BiMKzRLV.mjs.map +1 -0
  29. package/dist/{explain-BD6bemOK.mjs → explain-DKS-t7dS.mjs} +5 -5
  30. package/dist/{explain-BD6bemOK.mjs.map → explain-DKS-t7dS.mjs.map} +1 -1
  31. package/dist/{export-BiIRQJ7L.mjs → export-DRw3XVfG.mjs} +4 -4
  32. package/dist/{export-BiIRQJ7L.mjs.map → export-DRw3XVfG.mjs.map} +1 -1
  33. package/dist/{index-CuWHsoBB.d.mts → external-M25AgDIE.d.mts} +2 -186
  34. package/dist/external-M25AgDIE.d.mts.map +1 -0
  35. package/dist/files-D05VjxVj.mjs +350 -0
  36. package/dist/files-D05VjxVj.mjs.map +1 -0
  37. package/dist/{generate-all-BWpiTcED.mjs → generate-all-CMpNPpD8.mjs} +4 -4
  38. package/dist/{generate-all-BWpiTcED.mjs.map → generate-all-CMpNPpD8.mjs.map} +1 -1
  39. package/dist/{generate-desktop-shell-NeH89X6S.mjs → generate-desktop-shell-B-Rf7ds8.mjs} +4 -4
  40. package/dist/{generate-desktop-shell-NeH89X6S.mjs.map → generate-desktop-shell-B-Rf7ds8.mjs.map} +1 -1
  41. package/dist/{generate-document-model-vzFHWp4O.mjs → generate-document-model-DCjzz3Sa.mjs} +4 -4
  42. package/dist/{generate-document-model-vzFHWp4O.mjs.map → generate-document-model-DCjzz3Sa.mjs.map} +1 -1
  43. package/dist/{generate-piece-DpFUr1ON.mjs → generate-piece-5Nyr2UZj.mjs} +4 -4
  44. package/dist/{generate-piece-DpFUr1ON.mjs.map → generate-piece-5Nyr2UZj.mjs.map} +1 -1
  45. package/dist/{get-version-Cou2oS93.mjs → get-version-qXfoI8qS.mjs} +4 -4
  46. package/dist/{get-version-Cou2oS93.mjs.map → get-version-qXfoI8qS.mjs.map} +1 -1
  47. package/dist/index-BdxG1c0H.d.mts +188 -0
  48. package/dist/index-BdxG1c0H.d.mts.map +1 -0
  49. package/dist/{inspect-CzjDr590.mjs → inspect-DlRPzee1.mjs} +4 -4
  50. package/dist/{inspect-CzjDr590.mjs.map → inspect-DlRPzee1.mjs.map} +1 -1
  51. package/dist/{mcp-v8q-w6FP.mjs → mcp-BSigu-6U.mjs} +4 -4
  52. package/dist/{mcp-v8q-w6FP.mjs.map → mcp-BSigu-6U.mjs.map} +1 -1
  53. package/dist/npm-args-g1Tgel4s.mjs +78 -0
  54. package/dist/npm-args-g1Tgel4s.mjs.map +1 -0
  55. package/dist/ph-cli-commands-DAqHeYm7.mjs +4 -0
  56. package/dist/{ph-cli-commands-SGDvwQud.mjs → ph-cli-commands-XNEhuXzO.mjs} +64 -19
  57. package/dist/ph-cli-commands-XNEhuXzO.mjs.map +1 -0
  58. package/dist/render-CTQG4359.mjs +4 -0
  59. package/dist/{run-C7ExLhAm.mjs → run-DEKE4MJY.mjs} +34 -20
  60. package/dist/run-DEKE4MJY.mjs.map +1 -0
  61. package/dist/{run-BiS1kA5W.mjs → run-DP3fNgPv.mjs} +3 -3
  62. package/dist/{run-sugar-DZjQhZb1.mjs → run-sugar-yf2ggYJ9.mjs} +4 -4
  63. package/dist/{run-sugar-DZjQhZb1.mjs.map → run-sugar-yf2ggYJ9.mjs.map} +1 -1
  64. package/dist/runners/connect.d.mts +1 -1
  65. package/dist/runners/connect.mjs +2 -2
  66. package/dist/runners/switchboard.d.mts +1 -1
  67. package/dist/runners/switchboard.mjs +1 -1
  68. package/dist/{schemas-ByfuhvAb.mjs → schemas-ZQiV98u4.mjs} +186 -4
  69. package/dist/{schemas-ByfuhvAb.mjs.map → schemas-ZQiV98u4.mjs.map} +1 -1
  70. package/dist/verify-D16BN0dO.mjs +64 -0
  71. package/dist/verify-D16BN0dO.mjs.map +1 -0
  72. package/dist/{vetra-s0oeZqMz.mjs → vetra-CdYsxlvS.mjs} +6 -6
  73. package/dist/{vetra-s0oeZqMz.mjs.map → vetra-CdYsxlvS.mjs.map} +1 -1
  74. package/package.json +16 -15
  75. package/dist/build-t5pFQx0f.mjs +0 -304
  76. package/dist/build-t5pFQx0f.mjs.map +0 -1
  77. package/dist/build-wvc_NiGr.mjs +0 -4
  78. package/dist/check-B_uGHUz3.mjs +0 -20
  79. package/dist/check-B_uGHUz3.mjs.map +0 -1
  80. package/dist/connect-build-D20s-YzT.mjs.map +0 -1
  81. package/dist/dist-CF0RfguD.mjs.map +0 -1
  82. package/dist/index-CuWHsoBB.d.mts.map +0 -1
  83. package/dist/ph-cli-commands-CLbK9iC7.mjs +0 -4
  84. package/dist/ph-cli-commands-SGDvwQud.mjs.map +0 -1
  85. package/dist/run-C7ExLhAm.mjs.map +0 -1
@@ -0,0 +1,2036 @@
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]="e01699e0-0f44-5641-9609-791314473794")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-qXfoI8qS.mjs";
4
+ import { n as OFFERED_ROUTES_MODULE, r as syncProjectConnectRoutes, t as HOST_ROUTES_DIR } from "./sync-connect-routes-t0Slg-P6.mjs";
5
+ import { r as noConnectImports } from "./offered-routes-imports-CalXK9dh.mjs";
6
+ import { a as writeReleaseApproval, d as changedPaths, f as packageRevision, i as revisionFiles, l as listed, n as publishedFiles, o as PH_CLI_BINDING, s as RELEASE_APPROVAL_PATH, t as packagePath } from "./files-D05VjxVj.mjs";
7
+ import { createRequire } from "node:module";
8
+ import { accessSync, chmodSync, constants, cpSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
9
+ import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { execFileSync, execSync, fork } from "node:child_process";
11
+ import { assertPiecesOutDir, buildPieces, createDetectionCache, expandEntryGlobs, externalDependencyVersions, externalDepsPlugin, pieceListPath, planPieces, projectPath, syncDistManifest, undeclaredExternalDependencies } from "@powerhousedao/shared/build-pieces";
12
+ import { detect, resolveCommand } from "package-manager-detector";
13
+ import { randomBytes } from "node:crypto";
14
+ import { hostname } from "node:os";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
+ import { browserEntry, buildBrowserBuildConfig, buildNodeBuildConfig, findBundledSharedDeps } from "@powerhousedao/shared/build-config";
17
+ import { EXTERNALIZABLE_SHARED_SPECIFIERS, findSharedImports } from "@powerhousedao/shared/connect";
18
+ import { readPackage } from "read-pkg";
19
+ import { build, globalLogger } from "tsdown";
20
+ import { localPackageNames, packageStyleEntry, packageStylesheet } from "@powerhousedao/shared/clis/package-style";
21
+ import { nodeFileTrace } from "@vercel/nft";
22
+ //#region src/services/package-build/pipeline/steps.ts
23
+ /** A step's decision not to finish the build. The runner rolls back first. */
24
+ var BuildRefusal = class extends Error {
25
+ exitCode;
26
+ constructor(message, exitCode = 1) {
27
+ super(message);
28
+ this.name = "BuildRefusal";
29
+ this.exitCode = exitCode;
30
+ }
31
+ };
32
+ /** The process was told to stop while the build ran; it was rolled back. */
33
+ var BuildStopped = class extends Error {
34
+ signal;
35
+ constructor(signal) {
36
+ super(`The build was stopped by ${signal} before it finished.`);
37
+ this.name = "BuildStopped";
38
+ this.signal = signal;
39
+ }
40
+ };
41
+ function dependencies(steps) {
42
+ const ids = /* @__PURE__ */ new Set();
43
+ for (const { id } of steps) {
44
+ if (ids.has(id)) throw new Error(`Build step "${id}" is listed twice.`);
45
+ ids.add(id);
46
+ }
47
+ const committed = new Set(steps.filter(({ when }) => when === "committed").map(({ id }) => id));
48
+ const waits = /* @__PURE__ */ new Map();
49
+ steps.forEach((step, index) => {
50
+ const previous = steps.slice(0, index).findLast(({ when }) => when === step.when);
51
+ const after = step.after ?? (previous === void 0 ? [] : [previous.id]);
52
+ for (const id of after) {
53
+ if (!ids.has(id)) throw new Error(`Build step "${step.id}" runs after "${id}", which no step provides.`);
54
+ 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.`);
55
+ }
56
+ waits.set(step.id, after);
57
+ });
58
+ return waits;
59
+ }
60
+ /**
61
+ * The order the steps run in: list order, with each step that names `after`
62
+ * placed right after the last step it waits for, and every `committed` step
63
+ * after every other. Throws on a duplicate id, an unknown `after` id, a step
64
+ * that waits on a later phase, or steps that wait on each other.
65
+ */
66
+ function orderBuildSteps(steps) {
67
+ const waits = dependencies(steps);
68
+ const placed = /* @__PURE__ */ new Set();
69
+ const ordered = [];
70
+ while (ordered.length < steps.length) {
71
+ const ready = steps.filter(({ id }) => !placed.has(id) && waits.get(id).every((wait) => placed.has(wait)));
72
+ if (ready.length === 0) {
73
+ const waiting = steps.filter(({ id }) => !placed.has(id)).map(({ id }) => `"${id}"`);
74
+ throw new Error(`Build steps ${waiting.join(", ")} wait on each other.`);
75
+ }
76
+ const phase = ready.some(({ when }) => when !== "committed") ? ready.filter(({ when }) => when !== "committed") : ready;
77
+ const next = phase.find((step) => step.after !== void 0) ?? phase[0];
78
+ placed.add(next.id);
79
+ ordered.push(next);
80
+ }
81
+ return ordered;
82
+ }
83
+ //#endregion
84
+ //#region src/services/package-build/pipeline/run-steps.ts
85
+ function throwIfStopped(session) {
86
+ const signal = session.stopped();
87
+ if (signal === void 0) return;
88
+ session.rollback();
89
+ throw new BuildStopped(signal);
90
+ }
91
+ /**
92
+ * Runs the steps in order, commits, then runs the `committed` steps. When a
93
+ * step before the commit throws, `rollback` runs before the error goes on to
94
+ * the caller, so nothing the build wrote outlives the failure. A committed
95
+ * step's throw goes to the caller with the new output in place. A stop is
96
+ * seen once the running step settles, and before each step and the commit:
97
+ * no step starts after it, and the rollback waits for the step it stopped.
98
+ */
99
+ async function runBuildSteps(steps, ctx, session) {
100
+ const ordered = orderBuildSteps(steps);
101
+ for (const step of ordered.filter(({ when }) => when !== "committed")) {
102
+ throwIfStopped(session);
103
+ try {
104
+ await step.run(ctx);
105
+ } catch (error) {
106
+ session.rollback();
107
+ throwIfStopped(session);
108
+ throw error;
109
+ }
110
+ }
111
+ throwIfStopped(session);
112
+ session.commit();
113
+ for (const step of ordered.filter(({ when }) => when === "committed")) {
114
+ throwIfStopped(session);
115
+ await step.run(ctx);
116
+ }
117
+ }
118
+ //#endregion
119
+ //#region src/services/definitions/paths.ts
120
+ function canonicalPath(path, options = {}) {
121
+ const absolute = resolve(path);
122
+ let ancestor = absolute;
123
+ while (lstatSync(ancestor, { throwIfNoEntry: false }) === void 0) {
124
+ const parent = dirname(ancestor);
125
+ if (parent === ancestor) break;
126
+ ancestor = parent;
127
+ }
128
+ let canonical;
129
+ try {
130
+ canonical = realpathSync.native(ancestor);
131
+ } catch (error) {
132
+ if (options.resolveMissingLinks !== true || !(error instanceof Error && "code" in error && error.code === "ENOENT") || !lstatSync(ancestor, { throwIfNoEntry: false })?.isSymbolicLink()) throw error;
133
+ canonical = canonicalPath(resolve(dirname(ancestor), readlinkSync(ancestor)), options);
134
+ }
135
+ return resolve(canonical, relative(ancestor, absolute));
136
+ }
137
+ function pathWithin(root, path) {
138
+ const inside = relative(root, path);
139
+ return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside) ? null : inside;
140
+ }
141
+ //#endregion
142
+ //#region src/services/package-build/staging/files.ts
143
+ function exists(path) {
144
+ return lstatSync(path, { throwIfNoEntry: false }) !== void 0;
145
+ }
146
+ /**
147
+ * Copies a file or a tree with its timestamps. A clone where the filesystem
148
+ * has them, a byte copy elsewhere; never a hard link, because later steps
149
+ * rewrite files in place.
150
+ */
151
+ function cloneTree(from, to, filter) {
152
+ cpSync(from, to, {
153
+ recursive: true,
154
+ mode: constants.COPYFILE_FICLONE,
155
+ preserveTimestamps: true,
156
+ verbatimSymlinks: true,
157
+ ...filter && { filter }
158
+ });
159
+ }
160
+ /**
161
+ * Mirrors a tree whose files the next step unlinks before it writes (tsdown
162
+ * cleans its output directory that way): each file is hard linked, so no
163
+ * byte is copied and nothing written later reaches `from`. A file that
164
+ * cannot be linked, and anything else, is copied.
165
+ */
166
+ function linkTree(from, to, filter) {
167
+ mkdirSync(to);
168
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
169
+ const source = join(from, entry.name);
170
+ if (!filter(source)) continue;
171
+ const target = join(to, entry.name);
172
+ if (entry.isDirectory()) {
173
+ linkTree(source, target, filter);
174
+ continue;
175
+ }
176
+ if (entry.isFile()) try {
177
+ linkSync(source, target);
178
+ continue;
179
+ } catch {}
180
+ cloneTree(source, target);
181
+ }
182
+ }
183
+ const OWNER_RWX = 448;
184
+ /**
185
+ * Gives every directory of the tree at `path` that lacks it owner read,
186
+ * write and search permission, which emptying it needs, and returns the
187
+ * modes it changed, parents first.
188
+ */
189
+ function openDirectories(path) {
190
+ const changed = [];
191
+ const visit = (dir, rel) => {
192
+ const stat = lstatSync(dir, { throwIfNoEntry: false });
193
+ if (!stat?.isDirectory()) return;
194
+ const mode = stat.mode & 4095;
195
+ if ((mode & OWNER_RWX) !== OWNER_RWX) {
196
+ chmodSync(dir, mode | OWNER_RWX);
197
+ changed.push([rel, mode]);
198
+ }
199
+ for (const entry of readdirSync(dir)) visit(join(dir, entry), rel === "" ? entry : `${rel}/${entry}`);
200
+ };
201
+ visit(path, "");
202
+ return changed;
203
+ }
204
+ /** Sets back the modes `openDirectories` changed, children first. */
205
+ function restoreDirectoryModes(path, modes) {
206
+ for (const [rel, mode] of [...modes].reverse()) chmodSync(rel === "" ? path : join(path, ...rel.split("/")), mode);
207
+ }
208
+ /**
209
+ * Removes a tree. A directory without owner write permission keeps its
210
+ * entries, so on failure each directory is opened and the removal tried
211
+ * once more.
212
+ */
213
+ function removeTree(path) {
214
+ const remove = () => rmSync(path, {
215
+ recursive: true,
216
+ force: true,
217
+ maxRetries: 10
218
+ });
219
+ try {
220
+ remove();
221
+ } catch (error) {
222
+ try {
223
+ openDirectories(path);
224
+ } catch {
225
+ throw error;
226
+ }
227
+ remove();
228
+ }
229
+ }
230
+ /**
231
+ * The first entry of the tree at `path`, itself included, that the stage
232
+ * cannot copy as it is, and why: a FIFO, socket or device, which a copy
233
+ * cannot represent, or a file or directory this process cannot read. Only
234
+ * permissions are checked; no file is read. Entries `filter` rejects, and
235
+ * what they hold, are not looked at.
236
+ */
237
+ function unstageableEntryIn(path, filter = () => true) {
238
+ const visit = (path, stat) => {
239
+ if (stat.isSymbolicLink()) return;
240
+ if (!stat.isFile() && !stat.isDirectory()) return {
241
+ path,
242
+ reason: "is not a file, directory or symbolic link"
243
+ };
244
+ const mode = stat.isDirectory() ? constants.R_OK | constants.X_OK : constants.R_OK;
245
+ try {
246
+ accessSync(path, mode);
247
+ } catch {
248
+ return {
249
+ path,
250
+ reason: "cannot be read"
251
+ };
252
+ }
253
+ if (!stat.isDirectory()) return;
254
+ for (const entry of readdirSync(path)) {
255
+ const child = join(path, entry);
256
+ if (!filter(child)) continue;
257
+ const found = visit(child, lstatSync(child));
258
+ if (found) return found;
259
+ }
260
+ };
261
+ const stat = lstatSync(path, { throwIfNoEntry: false });
262
+ return stat && visit(path, stat);
263
+ }
264
+ function entriesOf(dir) {
265
+ return exists(dir) ? readdirSync(dir) : [];
266
+ }
267
+ const blocker = new Int32Array(new SharedArrayBuffer(4));
268
+ /** Waits without returning to the event loop, so no signal handler runs meanwhile. */
269
+ function sleepSync(ms) {
270
+ Atomics.wait(blocker, 0, 0, ms);
271
+ }
272
+ /** Windows refuses to rename a directory while another process holds a file in it. */
273
+ function isHeldOpen(error) {
274
+ const code = error?.code;
275
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
276
+ }
277
+ const RENAME_PATIENCE_MS = 2e3;
278
+ /** `rename`, retried with backoff for about two seconds while the path is held open. */
279
+ function renamePatiently(from, to, patienceMs = RENAME_PATIENCE_MS) {
280
+ const deadline = Date.now() + patienceMs;
281
+ for (let wait = 20;; wait = Math.min(wait * 2, 400)) try {
282
+ renameSync(from, to);
283
+ return;
284
+ } catch (error) {
285
+ if (!isHeldOpen(error) || Date.now() + wait > deadline) throw error;
286
+ sleepSync(wait);
287
+ }
288
+ }
289
+ /** Moves each entry of `from` into `to`, replacing what `to` holds under that name. */
290
+ function moveEntries(from, to) {
291
+ for (const entry of entriesOf(from)) {
292
+ const target = join(to, entry);
293
+ if (exists(target)) removeTree(target);
294
+ renamePatiently(join(from, entry), target);
295
+ }
296
+ }
297
+ /** Staging cannot run where the build would write; `message` says why. */
298
+ var CannotStage = class extends Error {};
299
+ const CANNOT_WRITE = /* @__PURE__ */ new Set([
300
+ "ENOTDIR",
301
+ "EACCES",
302
+ "EPERM",
303
+ "EROFS",
304
+ "ENOTSUP",
305
+ "EOPNOTSUPP"
306
+ ]);
307
+ /** Runs `create`, turning a refusal to write `where` into `CannotStage`. */
308
+ async function creating(where, create) {
309
+ try {
310
+ return await create();
311
+ } catch (error) {
312
+ const code = error?.code;
313
+ if (typeof code === "string" && CANNOT_WRITE.has(code)) throw new CannotStage(`${where} cannot be written (${code})`);
314
+ throw error;
315
+ }
316
+ }
317
+ //#endregion
318
+ //#region src/services/package-build/staging/journal.ts
319
+ /** Scratch space of `ph build`, per package. */
320
+ const BUILD_DIRECTORY = join(".ph", "build");
321
+ const RUNS_DIRECTORY = join(BUILD_DIRECTORY, "runs");
322
+ const LOCK_FILE = join(BUILD_DIRECTORY, "lock");
323
+ const JOURNAL_FILE = "journal.json";
324
+ /**
325
+ * The steps of a rollback, in order, each safe to repeat:
326
+ * - install: the output loses what the stage put in it.
327
+ * - retire: the retired tree, or its entries, goes back into the output.
328
+ * - stage: the stage goes and the compiler outputs come back.
329
+ */
330
+ const UNDO_STEPS = [
331
+ "install",
332
+ "retire",
333
+ "stage"
334
+ ];
335
+ const STATES = [
336
+ "building",
337
+ "retiring",
338
+ "installing",
339
+ "rolling-back",
340
+ "committed"
341
+ ];
342
+ /**
343
+ * A path inside `from` is recorded relative, in POSIX form. Any other path
344
+ * is recorded absolute and comes back unchanged: a relative spelling of
345
+ * another drive or a UNC share does not resolve back to it on Windows.
346
+ */
347
+ function toJournalPath(from, to, paths = path) {
348
+ const rel = paths.relative(from, to);
349
+ if (paths.isAbsolute(rel) || rel === ".." || rel.startsWith(`..${paths.sep}`)) return paths.resolve(to);
350
+ return rel.split(paths.sep).join("/");
351
+ }
352
+ function fromJournalPath(from, recorded, paths = path) {
353
+ return paths.isAbsolute(recorded) ? recorded : paths.resolve(from, recorded);
354
+ }
355
+ function journalPath(runDir) {
356
+ return join(runDir, JOURNAL_FILE);
357
+ }
358
+ /** Replaces the journal in one rename, so a reader sees the old state or the new. */
359
+ function writeJournal(runDir, journal) {
360
+ const file = journalPath(runDir);
361
+ const pending = `${file}.${process.pid}.tmp`;
362
+ writeFileSync(pending, `${JSON.stringify(journal, null, 2)}\n`);
363
+ renameSync(pending, file);
364
+ }
365
+ const isString = (value) => typeof value === "string" && value !== "";
366
+ function parseSnapshot(value) {
367
+ if (typeof value !== "object" || value === null) return void 0;
368
+ const { path, kind, copy, created } = value;
369
+ if (!isString(path) || kind !== "directory" && kind !== "build-info" && kind !== "file") return;
370
+ if (copy !== null && !isString(copy)) return void 0;
371
+ if (created !== null && !isString(created)) return void 0;
372
+ const { modes } = value;
373
+ if (modes === void 0) return {
374
+ path,
375
+ kind,
376
+ copy,
377
+ created
378
+ };
379
+ if (!Array.isArray(modes) || !modes.every(isDirectoryMode)) return void 0;
380
+ return {
381
+ path,
382
+ kind,
383
+ copy,
384
+ created,
385
+ modes
386
+ };
387
+ }
388
+ const isDirectoryMode = (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && Number.isInteger(value[1]);
389
+ /** The journal of a run directory, or undefined when it is missing or unreadable. */
390
+ function readJournal(runDir) {
391
+ let value;
392
+ try {
393
+ value = JSON.parse(readFileSync(journalPath(runDir), "utf8"));
394
+ } catch {
395
+ return;
396
+ }
397
+ if (typeof value !== "object" || value === null) return void 0;
398
+ const record = value;
399
+ 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;
400
+ const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;
401
+ if (record.state === "rolling-back" !== (undo !== null)) return void 0;
402
+ let compiler = null;
403
+ if (Array.isArray(record.compiler)) {
404
+ compiler = [];
405
+ for (const entry of record.compiler) {
406
+ const snapshot = parseSnapshot(entry);
407
+ if (snapshot === void 0) return void 0;
408
+ compiler.push(snapshot);
409
+ }
410
+ } else if (record.compiler !== null) return;
411
+ return {
412
+ format: 1,
413
+ runId: record.runId,
414
+ pid: record.pid,
415
+ state: record.state,
416
+ undo,
417
+ output: record.output,
418
+ stage: record.stage,
419
+ retired: record.retired,
420
+ compiler
421
+ };
422
+ }
423
+ //#endregion
424
+ //#region src/services/package-build/staging/boot-id.ts
425
+ function readBootId() {
426
+ try {
427
+ return (process.platform === "linux" ? readFileSync("/proc/sys/kernel/random/boot_id", "utf8") : process.platform === "darwin" ? execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
428
+ encoding: "utf8",
429
+ stdio: [
430
+ "ignore",
431
+ "pipe",
432
+ "ignore"
433
+ ]
434
+ }) : "").trim() || null;
435
+ } catch {
436
+ return null;
437
+ }
438
+ }
439
+ let memo;
440
+ /**
441
+ * This boot of the machine, as the OS names it, or null where it cannot be
442
+ * read. Unlike a boot time derived from the clock, it changes only with a
443
+ * reboot.
444
+ */
445
+ function currentBootId() {
446
+ if (memo === void 0) memo = readBootId();
447
+ return memo;
448
+ }
449
+ //#endregion
450
+ //#region src/services/package-build/staging/lock.ts
451
+ const POLL_MS = 100;
452
+ const TAKEOVER_RETRY_MS = 10;
453
+ const QUIET_TAKEOVER_WAIT_MS = 1e3;
454
+ function isOwner(value) {
455
+ const owner = value;
456
+ return typeof owner?.pid === "number" && typeof owner.runId === "string" && typeof owner.host === "string" && (typeof owner.bootId === "string" || owner.bootId === null);
457
+ }
458
+ /**
459
+ * The owner's process is gone: on this machine, it ran in another boot (so
460
+ * the reboot ended it), or no process is left at its pid. Another host, or a
461
+ * live pid in this boot or an unknown one, is not proof: such an owner may
462
+ * still be building. A pid reused by another process of this boot reads as
463
+ * live, so its lock waits until someone deletes it.
464
+ */
465
+ const provenDead = (owner) => {
466
+ if (owner.host !== hostname()) return false;
467
+ const boot = currentBootId();
468
+ if (owner.bootId !== null && boot !== null && owner.bootId !== boot) return true;
469
+ return !isProcessAlive(owner.pid);
470
+ };
471
+ const errorCode = (error) => error.code;
472
+ function isProcessAlive(pid) {
473
+ try {
474
+ process.kill(pid, 0);
475
+ return true;
476
+ } catch (error) {
477
+ return errorCode(error) === "EPERM";
478
+ }
479
+ }
480
+ /** What a waiting build says about who holds a lock or takeover file. */
481
+ function described(value) {
482
+ const fields = value;
483
+ const parts = [
484
+ ["host", fields?.host],
485
+ ["pid", fields?.pid],
486
+ ["run", fields?.runId]
487
+ ].flatMap(([name, field]) => typeof field === "string" || typeof field === "number" ? [`${name} ${field}`] : []);
488
+ return parts.length > 0 ? parts.join(", ") : "owner unknown";
489
+ }
490
+ function holderOf(file) {
491
+ let value;
492
+ try {
493
+ value = JSON.parse(readFileSync(file, "utf8"));
494
+ } catch (error) {
495
+ if (errorCode(error) === "ENOENT") return void 0;
496
+ }
497
+ if (isOwner(value)) return {
498
+ id: value.runId,
499
+ dead: provenDead(value),
500
+ owner: described(value)
501
+ };
502
+ const stat = lstatSync(file, { throwIfNoEntry: false });
503
+ return stat && {
504
+ id: `file ${stat.ino} ${stat.mtimeMs}`,
505
+ dead: false,
506
+ owner: described(value)
507
+ };
508
+ }
509
+ /**
510
+ * Creates `file` holding `owner`, or returns false when it exists. The file
511
+ * appears with its content in one link, so no reader sees it empty.
512
+ */
513
+ function createOwned(file, owner) {
514
+ const pending = join(dirname(file), `.${basename(file)}.${owner.runId}.pending`);
515
+ writeFileSync(pending, JSON.stringify(owner));
516
+ try {
517
+ linkSync(pending, file);
518
+ return true;
519
+ } catch (error) {
520
+ if (errorCode(error) === "EEXIST") return false;
521
+ throw error;
522
+ } finally {
523
+ rmSync(pending, { force: true });
524
+ }
525
+ }
526
+ const takeoverFile = (lockFile, staleId) => `${lockFile}.takeover-${encodeURIComponent(staleId)}`;
527
+ /**
528
+ * Removes `file` while it still holds the dead holder `stale`. Only the
529
+ * creator of the takeover file keyed to `stale` may remove it, and `stale`
530
+ * cannot come back, so the owner read under that file is the one removed: a
531
+ * contender that judged it stale before someone else took over removes
532
+ * nothing. A takeover file is itself taken over only from a holder proven
533
+ * dead, never for its age, so a paused holder keeps it. Returns what blocks
534
+ * the takeover, or nothing when the caller should try again.
535
+ */
536
+ function takeOver(lockFile, file, stale, me) {
537
+ const guard = takeoverFile(lockFile, stale.id);
538
+ if (!createOwned(guard, me)) {
539
+ const holder = holderOf(guard);
540
+ if (holder === void 0) return void 0;
541
+ return holder.dead ? takeOver(lockFile, guard, holder, me) : {
542
+ file: guard,
543
+ holder
544
+ };
545
+ }
546
+ try {
547
+ if (holderOf(file)?.id === stale.id) removeTree(file);
548
+ return;
549
+ } finally {
550
+ if (holderOf(guard)?.id === me.runId) rmSync(guard, { force: true });
551
+ }
552
+ }
553
+ /**
554
+ * Takeover files left by contenders that died. Safe under the lock: one
555
+ * matters only while the lock holds its stale owner, and the lock is ours.
556
+ * A pending file goes only when its writer is proven dead: a live
557
+ * contender links it next.
558
+ */
559
+ function removeTakeoverFiles(lockFile) {
560
+ const takeover = `${basename(lockFile)}.takeover-`;
561
+ const pending = `.${basename(lockFile)}.`;
562
+ for (const entry of readdirSync(dirname(lockFile))) {
563
+ const file = join(dirname(lockFile), entry);
564
+ if (entry.startsWith(takeover) || entry.startsWith(pending) && entry.endsWith(".pending") && holderOf(file)?.dead === true) rmSync(file, { force: true });
565
+ }
566
+ }
567
+ /**
568
+ * Takes `.ph/build/lock`, a file created exclusively that names this run.
569
+ * A lock is taken over only from an owner proven dead (see `provenDead`);
570
+ * otherwise this waits, and says once per holder which file it waits for.
571
+ */
572
+ async function acquireBuildLock(lockFile, runId, onWait) {
573
+ mkdirSync(dirname(lockFile), { recursive: true });
574
+ const me = {
575
+ pid: process.pid,
576
+ runId,
577
+ host: hostname(),
578
+ bootId: currentBootId()
579
+ };
580
+ const told = /* @__PURE__ */ new Set();
581
+ const firstBlocked = /* @__PURE__ */ new Map();
582
+ for (;;) {
583
+ if (createOwned(lockFile, me)) {
584
+ removeTakeoverFiles(lockFile);
585
+ let held = true;
586
+ return { release: () => {
587
+ if (!held) return;
588
+ held = false;
589
+ if (holderOf(lockFile)?.id === runId) rmSync(lockFile);
590
+ } };
591
+ }
592
+ const holder = holderOf(lockFile);
593
+ if (holder === void 0) continue;
594
+ const blocked = holder.dead ? takeOver(lockFile, lockFile, holder, me) : {
595
+ file: lockFile,
596
+ holder
597
+ };
598
+ if (blocked === void 0) {
599
+ await setTimeout$1(TAKEOVER_RETRY_MS);
600
+ continue;
601
+ }
602
+ const key = `${blocked.file}\0${blocked.holder.id}`;
603
+ const since = firstBlocked.get(key) ?? Date.now();
604
+ firstBlocked.set(key, since);
605
+ if (!(blocked.file !== lockFile && Date.now() - since < QUIET_TAKEOVER_WAIT_MS) && !told.has(key)) {
606
+ told.add(key);
607
+ onWait({
608
+ file: blocked.file,
609
+ owner: blocked.holder.owner
610
+ });
611
+ }
612
+ await setTimeout$1(blocked.file === lockFile ? POLL_MS : TAKEOVER_RETRY_MS);
613
+ }
614
+ }
615
+ //#endregion
616
+ //#region src/services/package-build/staging/recovery.ts
617
+ function runPaths(packageRoot, runDir, journal) {
618
+ return {
619
+ packageRoot,
620
+ runDir,
621
+ output: fromJournalPath(packageRoot, journal.output),
622
+ stage: fromJournalPath(packageRoot, journal.stage),
623
+ retired: fromJournalPath(packageRoot, journal.retired)
624
+ };
625
+ }
626
+ /** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */
627
+ function moveTree(from, to) {
628
+ try {
629
+ renamePatiently(from, to);
630
+ return "renamed";
631
+ } catch (error) {
632
+ if (!isHeldOpen(error)) throw error;
633
+ mkdirSync(to, { recursive: true });
634
+ moveEntries(from, to);
635
+ removeTree(from);
636
+ return "entries";
637
+ }
638
+ }
639
+ /** Build info first: if a later copy fails, tsc still sees its outputs as stale. */
640
+ function restoreCompilerOutputs(paths, snapshots) {
641
+ const ordered = [...snapshots ?? []].sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info"));
642
+ for (const snapshot of ordered) {
643
+ const path = fromJournalPath(paths.packageRoot, snapshot.path);
644
+ removeTree(path);
645
+ if (snapshot.copy !== null) {
646
+ cloneTree(fromJournalPath(paths.runDir, snapshot.copy), path);
647
+ restoreDirectoryModes(path, snapshot.modes ?? []);
648
+ } else if (snapshot.created !== null) removeEmptyDirectories(dirname(path), fromJournalPath(paths.packageRoot, snapshot.created));
649
+ }
650
+ }
651
+ /** Removes `from` and its parents up to `upTo` while each is an empty directory. */
652
+ function removeEmptyDirectories(from, upTo) {
653
+ for (let dir = from;; dir = dirname(dir)) {
654
+ if (!exists(dir) || entriesOf(dir).length > 0) return;
655
+ rmdirSync(dir);
656
+ if (dir === upTo || dirname(dir) === dir) return;
657
+ }
658
+ }
659
+ const FIRST_UNDO_STEP = {
660
+ building: "stage",
661
+ retiring: "retire",
662
+ installing: "install"
663
+ };
664
+ /**
665
+ * Undoes a run: the previous output goes back in place, the stage goes, and
666
+ * the compiler outputs are restored. The journal records each step before
667
+ * it starts, so a rollback cut short is finished by the next build, never
668
+ * rolled forward; the run directory, and the snapshot in it, stay until
669
+ * the caller removes them.
670
+ */
671
+ function rollBack(paths, journal) {
672
+ if (journal.state === "committed") return;
673
+ const first = journal.state === "rolling-back" ? journal.undo ?? "stage" : FIRST_UNDO_STEP[journal.state];
674
+ const { output, retired } = paths;
675
+ for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {
676
+ writeJournal(paths.runDir, {
677
+ ...journal,
678
+ state: "rolling-back",
679
+ undo: step
680
+ });
681
+ if (step === "install") {
682
+ if (!exists(retired)) removeTree(output);
683
+ else for (const entry of entriesOf(output)) removeTree(join(output, entry));
684
+ } else if (step === "retire") {
685
+ if (exists(retired)) {
686
+ if (exists(output)) moveEntries(retired, output);
687
+ else moveTree(retired, output);
688
+ }
689
+ } else {
690
+ removeTree(paths.stage);
691
+ removeTree(retired);
692
+ restoreCompilerOutputs(paths, journal.compiler);
693
+ }
694
+ }
695
+ }
696
+ /** Finishes a run that was installing its stage: the stage becomes the output. */
697
+ function rollForward(paths) {
698
+ const { output, stage } = paths;
699
+ if (exists(stage)) {
700
+ if (exists(output)) moveEntries(stage, output);
701
+ else moveTree(stage, output);
702
+ }
703
+ removeTree(stage);
704
+ removeTree(paths.retired);
705
+ }
706
+ /**
707
+ * Brings the package back to a consistent state after a run that died, then
708
+ * removes its run directory. A run that had not started to install its stage,
709
+ * or had started to roll back, is undone; one installing its stage is
710
+ * finished.
711
+ */
712
+ function replayRun(packageRoot, runDir) {
713
+ const journal = readJournal(runDir);
714
+ let replayed = "discarded";
715
+ if (journal !== void 0) {
716
+ const paths = runPaths(packageRoot, runDir, journal);
717
+ if (journal.state !== "installing" && journal.state !== "committed") {
718
+ rollBack(paths, journal);
719
+ replayed = "rolled-back";
720
+ } else {
721
+ rollForward(paths);
722
+ replayed = "completed";
723
+ }
724
+ }
725
+ removeTree(runDir);
726
+ return replayed;
727
+ }
728
+ /** A run's stage and retired tree beside the output named `output`. */
729
+ const isScratchOf = (output, entry) => entry.startsWith(`.${output}.ph-stage-`) || entry.startsWith(`.${output}.ph-old-`);
730
+ /**
731
+ * Undoes or finishes every run a dead build left behind, then removes any
732
+ * stage or retired tree beside `output` that no run claims any more: a
733
+ * bundler of a stopped build can go on writing after its rollback. Call
734
+ * under the lock, where no other run of this package is live.
735
+ */
736
+ function recoverStaleRuns(packageRoot, output) {
737
+ const runsDir = join(packageRoot, RUNS_DIRECTORY);
738
+ for (const runId of entriesOf(runsDir)) {
739
+ const replayed = replayRun(packageRoot, join(runsDir, runId));
740
+ 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.");
741
+ else if (replayed === "completed") console.warn("⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.");
742
+ }
743
+ const beside = dirname(output);
744
+ for (const entry of entriesOf(beside)) if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));
745
+ }
746
+ //#endregion
747
+ //#region src/services/package-build/staging/session.ts
748
+ function within(root, path) {
749
+ const rel = relative(root, path);
750
+ return rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) ? void 0 : rel;
751
+ }
752
+ const isUnreadable = (error) => {
753
+ const code = error?.code;
754
+ return code === "EACCES" || code === "EPERM";
755
+ };
756
+ /** `path` is `dir` or holds it. */
757
+ const isOrHolds = (path, dir) => path === dir || within(path, dir) !== void 0;
758
+ /** The outermost directory of `path`, inside the package, that does not exist. */
759
+ function outermostMissing(packageRoot, path) {
760
+ let missing = path;
761
+ for (let parent = dirname(path); within(packageRoot, parent) !== void 0 && !exists(parent); parent = dirname(parent)) missing = parent;
762
+ return missing;
763
+ }
764
+ /** A path as messages name it: from the package root, which is named so. */
765
+ const shownPath = (packageRoot, path) => toJournalPath(packageRoot, path) || "the package root";
766
+ /**
767
+ * One `ph build` of one package: the output is written to a stage beside the
768
+ * output directory and replaces it only on commit. Until then the previous
769
+ * output and the compiler outputs tsc rewrote can be put back, by `rollback`
770
+ * in this process or, after a crash, by the next build.
771
+ */
772
+ var StagedBuildSession = class StagedBuildSession {
773
+ runId;
774
+ packageRoot;
775
+ output;
776
+ writesPackageDist;
777
+ runDir;
778
+ paths;
779
+ lock;
780
+ journal;
781
+ status = "open";
782
+ stoppedBy;
783
+ seeded = false;
784
+ compilerWritten = false;
785
+ restored = false;
786
+ cleanedEntries;
787
+ linkCleanedEntries;
788
+ constructor(fields) {
789
+ this.runId = fields.runId;
790
+ this.packageRoot = fields.packageRoot;
791
+ this.output = fields.output;
792
+ this.writesPackageDist = fields.writesPackageDist;
793
+ this.cleanedEntries = fields.cleanedEntries;
794
+ this.linkCleanedEntries = fields.linkCleanedEntries;
795
+ this.runDir = fields.runDir;
796
+ this.lock = fields.lock;
797
+ this.journal = fields.journal;
798
+ this.paths = runPaths(fields.packageRoot, fields.runDir, fields.journal);
799
+ }
800
+ /**
801
+ * Starts a run under `lock`, which the caller took and recovered stale
802
+ * runs under; the caller still releases it when this throws. The stage
803
+ * sits beside `logical`, the output as given, so the paths the bundlers
804
+ * record from it are the ones an unstaged build records.
805
+ */
806
+ static async open(options) {
807
+ const { packageRoot, logical, runId } = options;
808
+ const runDir = join(packageRoot, RUNS_DIRECTORY, runId);
809
+ try {
810
+ const beside = (kind) => join(dirname(logical), `.${basename(logical)}.ph-${kind}-${runId}`);
811
+ const journal = {
812
+ format: 1,
813
+ runId,
814
+ pid: process.pid,
815
+ state: "building",
816
+ undo: null,
817
+ output: toJournalPath(packageRoot, logical),
818
+ stage: toJournalPath(packageRoot, beside("stage")),
819
+ retired: toJournalPath(packageRoot, beside("old")),
820
+ compiler: null
821
+ };
822
+ await creating(BUILD_DIRECTORY, () => {
823
+ mkdirSync(runDir, { recursive: true });
824
+ writeJournal(runDir, journal);
825
+ });
826
+ await creating(shownPath(packageRoot, dirname(logical)), () => mkdirSync(beside("stage"), { recursive: true }));
827
+ return new StagedBuildSession({
828
+ ...options,
829
+ runDir,
830
+ journal
831
+ });
832
+ } catch (error) {
833
+ removeTree(runDir);
834
+ throw error;
835
+ }
836
+ }
837
+ assertOpen() {
838
+ if (this.status !== "open") throw new Error("The build was stopped before it finished.");
839
+ }
840
+ record(changes) {
841
+ this.journal = {
842
+ ...this.journal,
843
+ ...changes
844
+ };
845
+ writeJournal(this.runDir, this.journal);
846
+ }
847
+ setState(state) {
848
+ this.record({ state });
849
+ }
850
+ /**
851
+ * Compiler outputs strictly inside the output directory, relative to it:
852
+ * tsc rewrote them in the real output, so the stage leaves them out when
853
+ * it is seeded and takes them fresh at commit. A protected directory that
854
+ * is the output or holds it is not one: it holds the bundles too.
855
+ */
856
+ compilerOutputsInOutput() {
857
+ return (this.journal.compiler ?? []).flatMap(({ path }) => {
858
+ const rel = within(this.output, fromJournalPath(this.packageRoot, path));
859
+ return rel === void 0 ? [] : [rel];
860
+ });
861
+ }
862
+ /**
863
+ * The stage directory every output write targets. The first call seeds it
864
+ * with the current output, minus what tsc writes afresh. With
865
+ * `linkCleanedEntries`, the entries a step cleans are seeded by hard link,
866
+ * since it unlinks their files before it writes and says so in the same
867
+ * words as on the output; the rest, and otherwise everything, by clone.
868
+ */
869
+ stage() {
870
+ this.assertOpen();
871
+ const { stage, output } = this.paths;
872
+ if (this.seeded) return stage;
873
+ removeTree(stage);
874
+ if (exists(output)) {
875
+ const skipped = new Set(this.compilerWritten ? [] : this.compilerOutputsInOutput().map((rel) => join(output, rel)));
876
+ const keep = (source) => !skipped.has(source);
877
+ const linked = (this.linkCleanedEntries ? this.cleanedEntries : []).map((dir) => join(output, dir)).filter((dir) => keep(dir) && lstatSync(dir, { throwIfNoEntry: false })?.isDirectory());
878
+ cloneTree(output, stage, (source) => keep(source) && !linked.includes(source));
879
+ for (const dir of linked) linkTree(dir, join(stage, basename(dir)), keep);
880
+ } else mkdirSync(stage);
881
+ this.seeded = true;
882
+ return stage;
883
+ }
884
+ /**
885
+ * Copies what tsc is about to rewrite into the run, or notes it absent, so
886
+ * a build that does not finish puts it back. Call before tsc runs. An
887
+ * output that is or holds `.ph/build` or this run, by real path, is left
888
+ * unprotected, as without staging: a copy of it would copy itself. So is
889
+ * one holding something a copy cannot take: a FIFO, socket or device, or
890
+ * an entry this process cannot read. The copy's directories are made
891
+ * owner-writable, so the run can always be removed; the journal keeps
892
+ * their modes for a restore.
893
+ */
894
+ protectCompilerOutputs(outputs) {
895
+ this.assertOpen();
896
+ const real = (path) => canonicalPath(path, { resolveMissingLinks: true });
897
+ const control = [real(join(this.packageRoot, BUILD_DIRECTORY)), real(this.runDir)];
898
+ const snapshots = [...this.journal.compiler ?? []];
899
+ for (const { path, kind } of outputs) {
900
+ const target = real(path);
901
+ if (control.some((dir) => isOrHolds(target, dir))) continue;
902
+ const recorded = toJournalPath(this.packageRoot, target);
903
+ if (snapshots.some((snapshot) => snapshot.path === recorded)) continue;
904
+ if (exists(target)) {
905
+ const copy = `compiler/${snapshots.length}`;
906
+ const output = basename(this.paths.output);
907
+ const snapshot = join(this.runDir, copy);
908
+ const keep = (source) => !isScratchOf(output, basename(source));
909
+ if (unstageableEntryIn(target, keep) !== void 0) continue;
910
+ try {
911
+ cloneTree(target, snapshot, keep);
912
+ } catch (error) {
913
+ if (!isUnreadable(error)) throw error;
914
+ removeTree(snapshot);
915
+ continue;
916
+ }
917
+ const modes = openDirectories(snapshot);
918
+ snapshots.push({
919
+ path: recorded,
920
+ kind,
921
+ copy,
922
+ created: null,
923
+ ...modes.length > 0 && { modes }
924
+ });
925
+ } else {
926
+ const missing = outermostMissing(this.packageRoot, target);
927
+ const created = missing === target ? null : toJournalPath(this.packageRoot, missing);
928
+ snapshots.push({
929
+ path: recorded,
930
+ kind,
931
+ copy: null,
932
+ created
933
+ });
934
+ }
935
+ }
936
+ this.record({ compiler: snapshots });
937
+ }
938
+ /**
939
+ * tsc wrote into the real output directory; the stage takes its fresh
940
+ * files now, before any bundle step, so a step that cleans or rewrites an
941
+ * entry treats them as it would in the output.
942
+ */
943
+ compilerOutputsWritten() {
944
+ this.assertOpen();
945
+ this.compilerWritten = true;
946
+ if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);
947
+ }
948
+ carryOverCompilerOutputs(stage) {
949
+ for (const rel of this.compilerOutputsInOutput()) {
950
+ const target = join(stage, rel);
951
+ removeTree(target);
952
+ const source = join(this.paths.output, rel);
953
+ if (exists(source)) {
954
+ mkdirSync(dirname(target), { recursive: true });
955
+ cloneTree(source, target);
956
+ }
957
+ }
958
+ }
959
+ warnNotAtomic() {
960
+ const shown = toJournalPath(this.packageRoot, this.paths.output);
961
+ 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.`);
962
+ }
963
+ /**
964
+ * Replaces the output with the stage: the output moves aside, the stage
965
+ * takes its place, the old tree goes. The journal records each move first.
966
+ * Synchronous, so no signal handler runs in between. The lock stays held
967
+ * until `close`.
968
+ */
969
+ commit() {
970
+ const stage = this.stage();
971
+ const { output, retired } = this.paths;
972
+ try {
973
+ this.setState("retiring");
974
+ let entryByEntry = false;
975
+ if (exists(output)) try {
976
+ renamePatiently(output, retired);
977
+ } catch (error) {
978
+ if (!isHeldOpen(error)) throw error;
979
+ entryByEntry = true;
980
+ mkdirSync(retired);
981
+ moveEntries(output, retired);
982
+ }
983
+ this.setState("installing");
984
+ if (exists(output)) {
985
+ moveEntries(stage, output);
986
+ removeTree(stage);
987
+ } else try {
988
+ renamePatiently(stage, output);
989
+ } catch (error) {
990
+ if (!isHeldOpen(error)) throw error;
991
+ entryByEntry = true;
992
+ mkdirSync(output);
993
+ moveEntries(stage, output);
994
+ removeTree(stage);
995
+ }
996
+ this.status = "committed";
997
+ if (entryByEntry) this.warnNotAtomic();
998
+ } catch (error) {
999
+ this.rollback();
1000
+ throw error;
1001
+ }
1002
+ try {
1003
+ this.setState("committed");
1004
+ removeTree(retired);
1005
+ removeTree(this.runDir);
1006
+ } catch (error) {
1007
+ 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.`);
1008
+ }
1009
+ }
1010
+ /**
1011
+ * Releases the lock a commit keeps, so steps that read the committed
1012
+ * output finish before another build replaces it, and drops the run a
1013
+ * rollback restored from. Idempotent.
1014
+ */
1015
+ close() {
1016
+ try {
1017
+ if (this.status === "rolled-back" && this.restored) removeTree(this.runDir);
1018
+ } finally {
1019
+ this.lock.release();
1020
+ }
1021
+ }
1022
+ releaseLock() {
1023
+ this.lock.release();
1024
+ }
1025
+ /**
1026
+ * Puts the previous output and compiler outputs back. Synchronous, so a
1027
+ * signal handler can call it; a no-op after commit. The run and its
1028
+ * snapshot stay until `close`, so a call after a step still running at
1029
+ * the first one settles restores again, undoing what that step wrote
1030
+ * since. A restore that failed is left to the next build. The lock stays
1031
+ * held until `close`.
1032
+ */
1033
+ rollback() {
1034
+ if (this.status === "committed") return;
1035
+ if (this.status === "rolled-back" && !this.restored) return;
1036
+ this.status = "rolled-back";
1037
+ try {
1038
+ rollBack(this.paths, this.journal);
1039
+ this.journal = {
1040
+ ...this.journal,
1041
+ state: "rolling-back",
1042
+ undo: "stage"
1043
+ };
1044
+ this.restored = true;
1045
+ } catch (error) {
1046
+ this.restored = false;
1047
+ console.error(`✘ The previous output could not be restored (${error instanceof Error ? error.message : String(error)}); the next build restores it.`);
1048
+ }
1049
+ }
1050
+ stops = /* @__PURE__ */ new Set();
1051
+ cancel(signal) {
1052
+ this.stoppedBy ??= signal;
1053
+ for (const stop of [...this.stops]) stop();
1054
+ }
1055
+ onCancel(stop) {
1056
+ this.stops.add(stop);
1057
+ return () => this.stops.delete(stop);
1058
+ }
1059
+ /** The signal `cancel` was called with, if it was. */
1060
+ stopped() {
1061
+ return this.stoppedBy;
1062
+ }
1063
+ };
1064
+ //#endregion
1065
+ //#region src/services/package-build/staging/open.ts
1066
+ /**
1067
+ * The first symlink among the output and its parents inside the package:
1068
+ * a stage beside its target would change the paths the bundlers record.
1069
+ */
1070
+ function symlinkOnPath(packageRoot, output) {
1071
+ const root = canonicalPath(packageRoot);
1072
+ for (let dir = output;; dir = dirname(dir)) {
1073
+ if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) return dir;
1074
+ const parent = canonicalPath(dirname(dir), { resolveMissingLinks: true });
1075
+ if (parent === root || pathWithin(root, parent) === null) return;
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Writes the output in place, as builds did before staging: no stage or
1080
+ * snapshot, and nothing to commit or roll back. It holds the package's lock
1081
+ * until `close` when `.ph/build` can hold one. A stop signal does not stop
1082
+ * it, as it did not stop an unstaged build.
1083
+ */
1084
+ var InPlaceSession = class {
1085
+ output;
1086
+ logical;
1087
+ writesPackageDist;
1088
+ lock;
1089
+ constructor(output, logical, writesPackageDist, lock) {
1090
+ this.output = output;
1091
+ this.logical = logical;
1092
+ this.writesPackageDist = writesPackageDist;
1093
+ this.lock = lock;
1094
+ }
1095
+ stage() {
1096
+ return this.logical;
1097
+ }
1098
+ protectCompilerOutputs() {}
1099
+ compilerOutputsWritten() {}
1100
+ commit() {}
1101
+ close() {
1102
+ this.lock?.release();
1103
+ }
1104
+ releaseLock() {
1105
+ this.lock?.release();
1106
+ }
1107
+ rollback() {}
1108
+ stops = /* @__PURE__ */ new Set();
1109
+ cancel() {
1110
+ for (const stop of [...this.stops]) stop();
1111
+ }
1112
+ stopped() {}
1113
+ onCancel(stop) {
1114
+ this.stops.add(stop);
1115
+ return () => this.stops.delete(stop);
1116
+ }
1117
+ };
1118
+ function newRunId() {
1119
+ return `${Date.now().toString(36)}-${process.pid}-${randomBytes(3).toString("hex")}`;
1120
+ }
1121
+ /**
1122
+ * Takes the package's lock and finishes what dead builds left, then opens a
1123
+ * staged session, or an in-place one when staging cannot run as an unstaged
1124
+ * build would: the output or a directory on its path in the package is a
1125
+ * symlink, the output holds an entry a copy cannot take (a FIFO, socket or
1126
+ * device, or one this process cannot read), the output holds `.ph/build`,
1127
+ * whose lock and journal a swap would move away, or the stage beside the
1128
+ * output cannot be written. Only when `.ph/build` cannot hold the lock does the
1129
+ * build run without one, as builds did before staging. One warning says why
1130
+ * a build writes in place.
1131
+ */
1132
+ async function openBuildSession(options) {
1133
+ const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;
1134
+ const logical = resolve(packageRoot, outDir);
1135
+ const output = canonicalPath(logical, { resolveMissingLinks: true });
1136
+ const writesPackageDist = output === canonicalPath(join(packageRoot, "dist"), { resolveMissingLinks: true });
1137
+ const shown = (path) => shownPath(packageRoot, path);
1138
+ const inPlace = (reason, lock) => {
1139
+ 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.`);
1140
+ return new InPlaceSession(output, logical, writesPackageDist, lock);
1141
+ };
1142
+ const runId = newRunId();
1143
+ let lock;
1144
+ try {
1145
+ 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)}.`)));
1146
+ } catch (error) {
1147
+ if (!(error instanceof CannotStage)) throw error;
1148
+ return inPlace(error.message, void 0);
1149
+ }
1150
+ try {
1151
+ recoverStaleRuns(packageRoot, logical);
1152
+ const link = symlinkOnPath(packageRoot, logical);
1153
+ if (link !== void 0) return inPlace(`${shown(link)} is a symbolic link`, lock);
1154
+ const unstageable = unstageableEntryIn(logical);
1155
+ if (unstageable !== void 0) return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);
1156
+ const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find((dir) => pathWithin(output, canonicalPath(join(packageRoot, dir), { resolveMissingLinks: true })) !== null);
1157
+ if (control !== void 0) return inPlace(`${shown(logical)} holds ${control}`, lock);
1158
+ try {
1159
+ return await StagedBuildSession.open({
1160
+ packageRoot,
1161
+ logical,
1162
+ output,
1163
+ writesPackageDist,
1164
+ cleanedEntries,
1165
+ linkCleanedEntries,
1166
+ runId,
1167
+ lock
1168
+ });
1169
+ } catch (error) {
1170
+ if (!(error instanceof CannotStage)) throw error;
1171
+ return inPlace(error.message, lock);
1172
+ }
1173
+ } catch (error) {
1174
+ lock.release();
1175
+ throw error;
1176
+ }
1177
+ }
1178
+ //#endregion
1179
+ //#region src/utils/offered-routes-manifest.ts
1180
+ function withOfferedRoutes(json, offers) {
1181
+ const manifest = JSON.parse(json);
1182
+ if (offers ? manifest.connectRoutes === true : !("connectRoutes" in manifest)) return json;
1183
+ if (offers) manifest.connectRoutes = true;
1184
+ else delete manifest.connectRoutes;
1185
+ return `${JSON.stringify(manifest, null, 2)}\n`;
1186
+ }
1187
+ const slashes = (path) => path.replaceAll("\\", "/");
1188
+ /** Sets `connectRoutes` in the manifest the package's root module imports,
1189
+ * leaving the project's file as it is. */
1190
+ function offeredRoutesManifest(projectRoot, offers) {
1191
+ const manifestPath = slashes(join(projectRoot, "powerhouse.manifest.json"));
1192
+ return {
1193
+ name: "ph-offered-routes-manifest",
1194
+ transform(code, id) {
1195
+ if (slashes(id) !== manifestPath) return null;
1196
+ return {
1197
+ code: withOfferedRoutes(code, offers),
1198
+ map: null
1199
+ };
1200
+ }
1201
+ };
1202
+ }
1203
+ /** Sets `connectRoutes` in the dist copy of the manifest. */
1204
+ function markOfferedRoutes(dir, offers) {
1205
+ const manifestPath = join(dir, "powerhouse.manifest.json");
1206
+ if (!existsSync(manifestPath)) return;
1207
+ const json = readFileSync(manifestPath, "utf-8");
1208
+ writeFileSync(manifestPath, withOfferedRoutes(json, offers));
1209
+ }
1210
+ //#endregion
1211
+ //#region src/services/package-build/steps/stage-logger.ts
1212
+ /**
1213
+ * tsdown labels each file it writes with its directory, relative to the
1214
+ * package. Bundles written to the stage keep the labels of the output
1215
+ * directory they stand in for, so the log reads as without staging.
1216
+ */
1217
+ function stageLogger({ projectRoot, outDir, session }) {
1218
+ const shown = `${relative(projectRoot, resolve(projectRoot, outDir))}${sep}`;
1219
+ const written = `${relative(projectRoot, session.stage())}${sep}`;
1220
+ const label = (message) => typeof message === "string" ? message.replaceAll(written, shown) : message;
1221
+ const relabel = (log) => (...messages) => log(...messages.map(label));
1222
+ return {
1223
+ get level() {
1224
+ return globalLogger.level;
1225
+ },
1226
+ set level(level) {
1227
+ globalLogger.level = level;
1228
+ },
1229
+ info: relabel((...m) => globalLogger.info(...m)),
1230
+ warn: relabel((...m) => globalLogger.warn(...m)),
1231
+ warnOnce: relabel((...m) => globalLogger.warnOnce(...m)),
1232
+ error: relabel((...m) => globalLogger.error(...m)),
1233
+ success: relabel((...m) => globalLogger.success(...m)),
1234
+ clearScreen: (type) => globalLogger.clearScreen(type)
1235
+ };
1236
+ }
1237
+ //#endregion
1238
+ //#region src/services/package-build/steps/bundles.ts
1239
+ /**
1240
+ * Every shared specifier imported from the entry sources; the post-build
1241
+ * scan compares these against the built output.
1242
+ *
1243
+ * Scoped to the specifiers the build actually externalizes: a specifier the
1244
+ * vendor does not publish (the bare `@powerhousedao/shared` root, an
1245
+ * unvendored subpath) is deliberately bundled, so reporting it as "bundled
1246
+ * instead of externalized" would be a false alarm.
1247
+ */
1248
+ function findSharedImportsInSources(root, globs) {
1249
+ const found = /* @__PURE__ */ new Set();
1250
+ for (const file of expandEntryGlobs(root, globs)) {
1251
+ const src = readFileSync(file, "utf8");
1252
+ for (const spec of findSharedImports(src, EXTERNALIZABLE_SHARED_SPECIFIERS)) found.add(spec);
1253
+ }
1254
+ return [...found].sort();
1255
+ }
1256
+ /**
1257
+ * The built JS outputs of a browser build (entry files and chunks).
1258
+ */
1259
+ function readDistBrowserFiles(dir) {
1260
+ const out = [];
1261
+ if (!existsSync(dir)) return out;
1262
+ const walk = (d) => {
1263
+ for (const e of readdirSync(d, { withFileTypes: true })) {
1264
+ const p = join(d, e.name);
1265
+ if (e.isDirectory()) walk(p);
1266
+ else if (e.isFile() && e.name.endsWith(".js")) out.push({
1267
+ path: p,
1268
+ content: readFileSync(p, "utf8")
1269
+ });
1270
+ }
1271
+ };
1272
+ walk(dir);
1273
+ return out;
1274
+ }
1275
+ const browserBundleStep = {
1276
+ id: "browser-bundle",
1277
+ run: async (ctx) => {
1278
+ const { args, projectRoot, session, trace, detection, findings } = ctx;
1279
+ const stage = session.stage();
1280
+ const sharedDeps = !args.noSharedDeps;
1281
+ const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);
1282
+ const config = buildBrowserBuildConfig({
1283
+ sharedDeps,
1284
+ plugins: [
1285
+ externalDepsPlugin(trace, /* @__PURE__ */ new Map(), {
1286
+ root: projectRoot,
1287
+ browser: true,
1288
+ cache: detection
1289
+ }),
1290
+ offeredRoutesManifest(projectRoot, findings.offersRoutes),
1291
+ noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR))
1292
+ ]
1293
+ });
1294
+ await build({
1295
+ ...config,
1296
+ ...session.writesPackageDist && { copy: [{
1297
+ from: "powerhouse.manifest.json",
1298
+ to: stage
1299
+ }] },
1300
+ ...findings.offersRoutes ? { entry: [...browserEntry, { "connect-routes": routesEntry }] } : {},
1301
+ outDir: join(stage, "browser"),
1302
+ customLogger: stageLogger(ctx)
1303
+ });
1304
+ if (sharedDeps) {
1305
+ const imported = findSharedImportsInSources(projectRoot, browserEntry);
1306
+ const bundled = findBundledSharedDeps(imported, readDistBrowserFiles(join(stage, "browser")));
1307
+ if (bundled.length > 0) console.warn(`⚠ shared deps bundled instead of externalized: ${bundled.join(", ")} — check your neverBundle config`);
1308
+ }
1309
+ }
1310
+ };
1311
+ function assertExternalDependenciesDeclared(projectRoot, found, pkg) {
1312
+ for (const dep of found) console.log(`${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`);
1313
+ const undeclared = undeclaredExternalDependencies(found, pkg);
1314
+ if (undeclared.length === 0) return;
1315
+ const lines = undeclared.map((dep) => ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : ""}`);
1316
+ 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.`);
1317
+ }
1318
+ const nodeBundleStep = {
1319
+ id: "node-bundle",
1320
+ run: async (ctx) => {
1321
+ const { args, projectRoot, session, trace, detection, findings } = ctx;
1322
+ await build({
1323
+ ...buildNodeBuildConfig({
1324
+ sharedDeps: !args.noSharedDeps,
1325
+ plugins: [externalDepsPlugin(trace, findings.external, {
1326
+ root: projectRoot,
1327
+ ignoreDirs: ["editors"],
1328
+ forbidDirs: ["document-models", "scalars"],
1329
+ cache: detection
1330
+ })]
1331
+ }),
1332
+ outDir: join(session.stage(), "node"),
1333
+ customLogger: stageLogger(ctx)
1334
+ });
1335
+ findings.pkg = await readPackage({ cwd: projectRoot });
1336
+ assertExternalDependenciesDeclared(projectRoot, [...findings.external.values()], findings.pkg);
1337
+ }
1338
+ };
1339
+ /** The output entry each bundle step writes, which tsdown empties first. */
1340
+ const CLEANED_BY_STEP = /* @__PURE__ */ new Map([[browserBundleStep.id, "browser"], [nodeBundleStep.id, "node"]]);
1341
+ /** The output entries `steps` empty before they write them, by step id. */
1342
+ const entriesCleanedBy = (steps) => steps.flatMap(({ id }) => CLEANED_BY_STEP.get(id) ?? []);
1343
+ //#endregion
1344
+ //#region src/services/package-build/steps/connect-routes.ts
1345
+ const connectRoutesStep = {
1346
+ id: "connect-routes",
1347
+ run: async ({ projectRoot, findings }) => {
1348
+ await syncProjectConnectRoutes(projectRoot);
1349
+ findings.offersRoutes = existsSync(join(projectRoot, OFFERED_ROUTES_MODULE));
1350
+ }
1351
+ };
1352
+ //#endregion
1353
+ //#region src/services/package-build/steps/definitions.ts
1354
+ /**
1355
+ * The built worker beside ph-cli's own code. Run from source (under vitest),
1356
+ * the TypeScript worker through tsx, so a test runs the current source.
1357
+ */
1358
+ function definitionsWorker() {
1359
+ const root = dirname(createRequire(import.meta.url).resolve("@powerhousedao/ph-cli/package.json"));
1360
+ if (!import.meta.url.endsWith(".ts")) return {
1361
+ path: join(root, "dist", "definitions-worker.mjs"),
1362
+ execArgv: []
1363
+ };
1364
+ return {
1365
+ path: join(root, "src", "services", "model", "definitions-worker.ts"),
1366
+ execArgv: ["--import", import.meta.resolve("tsx")]
1367
+ };
1368
+ }
1369
+ /**
1370
+ * Runs the definition check in a child process: the package's own modules
1371
+ * can exit, hang or start timers there without reaching the build. A child
1372
+ * that ends without a reply, outlives `timeoutMs` or outlives a stop of the
1373
+ * build is killed, and the reply says why the check could not run.
1374
+ */
1375
+ function checkInChild(projectRoot, profile, session, timeoutMs) {
1376
+ const worker = definitionsWorker();
1377
+ return new Promise((resolve) => {
1378
+ let reply;
1379
+ let killedFor;
1380
+ const child = fork(worker.path, [projectRoot, profile], {
1381
+ cwd: projectRoot,
1382
+ execArgv: worker.execArgv,
1383
+ stdio: [
1384
+ "ignore",
1385
+ 2,
1386
+ 2,
1387
+ "ipc"
1388
+ ]
1389
+ });
1390
+ const kill = (why) => {
1391
+ killedFor ??= why;
1392
+ child.kill("SIGKILL");
1393
+ };
1394
+ const timer = setTimeout(() => kill(`the check did not finish within ${timeoutMs / 1e3} seconds`), timeoutMs);
1395
+ const unwatch = session.onCancel(() => kill("the build was stopped"));
1396
+ if (session.stopped()) kill("the build was stopped");
1397
+ const settle = (settled) => {
1398
+ clearTimeout(timer);
1399
+ unwatch();
1400
+ resolve(settled);
1401
+ };
1402
+ child.on("message", (message) => {
1403
+ reply ??= message;
1404
+ });
1405
+ child.on("error", (error) => {
1406
+ kill(error.message);
1407
+ settle({
1408
+ ok: false,
1409
+ message: error.message
1410
+ });
1411
+ });
1412
+ child.on("exit", (code, signal) => {
1413
+ settle(reply ?? {
1414
+ ok: false,
1415
+ message: killedFor ?? `the check ${signal ? `was stopped by ${signal}` : `exited with code ${code}`} before it reported`
1416
+ });
1417
+ });
1418
+ });
1419
+ }
1420
+ /**
1421
+ * Checks the package's definitions after tsc and before any bundle, when
1422
+ * `ph build` asks or with `--release`. Without `--release` it checks the
1423
+ * code-first sources the package selects, never stops the build, and skips
1424
+ * without a word a package that selects none. With `--release`
1425
+ * (experimental) it runs the release profile over every model, stored ones
1426
+ * included, and stops the build when the check is invalid or cannot run, a
1427
+ * configuration error included. The package's modules load only in the
1428
+ * definitions worker, which has `timeoutMs` to report.
1429
+ */
1430
+ function definitionsStepWithin(timeoutMs) {
1431
+ return {
1432
+ id: "definitions",
1433
+ after: ["typecheck"],
1434
+ run: async ({ args, checkDefinitions, projectRoot, session, findings }) => {
1435
+ if (!args.release && !checkDefinitions) return;
1436
+ if (!args.release) {
1437
+ const { resolveDefinitionSelection } = await import("document-model/tooling");
1438
+ const selection = resolveDefinitionSelection({
1439
+ configFile: join(projectRoot, "powerhouse.config.json"),
1440
+ allowMissingConfig: true
1441
+ });
1442
+ if (selection.status !== "ready" || selection.sourceSet.sources.length === 0) return;
1443
+ }
1444
+ const { renderCheckReport } = await import("./render-CTQG4359.mjs");
1445
+ const printReport = (report) => {
1446
+ const text = renderCheckReport(report);
1447
+ if (report.diagnostics.length > 0) console.warn(`⚠ The definition check reported problems; the build goes on:\n${text}`);
1448
+ else console.log(`✔ ${text}`);
1449
+ };
1450
+ console.log("\n▶ Checking document model definitions...");
1451
+ if (!args.release) {
1452
+ const edit = await checkInChild(projectRoot, "edit", session, timeoutMs);
1453
+ if (edit.ok) printReport(edit.result);
1454
+ else console.warn(`⚠ The definition check could not run: ${edit.message}`);
1455
+ return;
1456
+ }
1457
+ const release = await checkInChild(projectRoot, "release", session, timeoutMs);
1458
+ if (!release.ok) throw new BuildRefusal(`✘ The definition check could not run: ${release.message}`);
1459
+ const { status } = release.result.report;
1460
+ if (status === "invalid" || status === "failed") throw new BuildRefusal(`✘ The release definition check stopped the build:\n${renderCheckReport(release.result.report)}`);
1461
+ findings.release = release.result;
1462
+ printReport(release.result.report);
1463
+ }
1464
+ };
1465
+ }
1466
+ const definitionsStep = definitionsStepWithin(3e5);
1467
+ //#endregion
1468
+ //#region src/services/package-build/steps/package-checks.ts
1469
+ /**
1470
+ * A Powerhouse package's `powerhouse.manifest.json` "name" must match its
1471
+ * `package.json` "name" — Connect and the registry resolve installed versions
1472
+ * by treating the manifest name as the npm package name, so a mismatch silently
1473
+ * breaks resolution. Fail the build early if they diverge. No-op when the
1474
+ * project has no manifest (nothing to compare).
1475
+ */
1476
+ async function assertManifestNameMatchesPackage(projectPath) {
1477
+ const manifestPath = join(projectPath, "powerhouse.manifest.json");
1478
+ if (!existsSync(manifestPath)) return;
1479
+ const { name: packageName } = await readPackage({ cwd: projectPath });
1480
+ let manifestName;
1481
+ try {
1482
+ manifestName = JSON.parse(readFileSync(manifestPath, "utf-8")).name;
1483
+ } catch {
1484
+ throw new Error(`Failed to parse "powerhouse.manifest.json" at ${manifestPath}. Make sure it is valid JSON.`);
1485
+ }
1486
+ 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.`);
1487
+ }
1488
+ const manifestNameStep = {
1489
+ id: "manifest-name",
1490
+ run: ({ projectRoot }) => assertManifestNameMatchesPackage(projectRoot)
1491
+ };
1492
+ const piecesOutDirStep = {
1493
+ id: "pieces-out-dir",
1494
+ run: ({ outDir, pieces }) => {
1495
+ assertPiecesOutDir({
1496
+ outDir,
1497
+ pieces: [...pieces]
1498
+ });
1499
+ return Promise.resolve();
1500
+ }
1501
+ };
1502
+ //#endregion
1503
+ //#region src/services/package-build/steps/pieces.ts
1504
+ const piecesStep = {
1505
+ id: "pieces",
1506
+ run: async (ctx) => {
1507
+ const { projectRoot, outDir, pieces, session, trace, detection, findings } = ctx;
1508
+ const stage = session.stage();
1509
+ if (!existsSync(pieceListPath({
1510
+ projectRoot,
1511
+ outDir: stage
1512
+ }))) return;
1513
+ const pkg = findings.pkg ?? await readPackage({ cwd: projectRoot });
1514
+ const customLogger = stageLogger(ctx);
1515
+ findings.built = await buildPieces({
1516
+ projectRoot,
1517
+ outDir,
1518
+ writeTo: stage,
1519
+ pieces: [...pieces]
1520
+ }, {
1521
+ name: pkg.name,
1522
+ version: pkg.version,
1523
+ license: typeof pkg.license === "string" ? pkg.license : void 0
1524
+ }, {
1525
+ bundle: (config) => build({
1526
+ ...config,
1527
+ customLogger
1528
+ }),
1529
+ trace,
1530
+ cache: detection
1531
+ });
1532
+ }
1533
+ };
1534
+ const distManifestStep = {
1535
+ id: "dist-manifest",
1536
+ run: ({ projectRoot, pieces, session, findings }) => {
1537
+ syncDistManifest({
1538
+ projectRoot,
1539
+ outDir: session.stage(),
1540
+ pieces: [...pieces]
1541
+ }, findings.built, externalDependencyVersions(findings.external.values()));
1542
+ return Promise.resolve();
1543
+ }
1544
+ };
1545
+ const offeredRoutesStep = {
1546
+ id: "offered-routes",
1547
+ run: ({ session, findings }) => {
1548
+ markOfferedRoutes(session.stage(), findings.offersRoutes);
1549
+ return Promise.resolve();
1550
+ }
1551
+ };
1552
+ //#endregion
1553
+ //#region src/services/release/issuance.ts
1554
+ const under$1 = (path, directory) => path === directory || path.startsWith(`${directory}/`);
1555
+ /**
1556
+ * Whether a release build may write an approval, and what its revision
1557
+ * leaves out: the replaced directory, and what tsc writes outside the
1558
+ * output.
1559
+ */
1560
+ function planApproval(build) {
1561
+ const { release, startFiles, outputs } = build;
1562
+ if (!build.typesOk) return { refused: "the build went on despite tsc's type errors" };
1563
+ if (release === void 0 || startFiles === void 0) return { refused: "the release check did not run" };
1564
+ return {
1565
+ release,
1566
+ startFiles,
1567
+ excluded: [...outputs.slice(1), ...build.compilerOutputs.filter((path) => !outputs.some((directory) => under$1(path, directory)))]
1568
+ };
1569
+ }
1570
+ /**
1571
+ * Why the approval may not be written because the package changed while it
1572
+ * was built, comparing its files at the start, minus what the revision
1573
+ * leaves out, with `endFiles`; undefined when nothing changed.
1574
+ */
1575
+ function changedWhileBuilt(plan, endFiles) {
1576
+ const leftOut = (path) => plan.excluded.some((exclusion) => under$1(path, exclusion));
1577
+ const changed = changedPaths(plan.startFiles.filter(({ path }) => !leftOut(path)), endFiles);
1578
+ return changed.length === 0 ? void 0 : `the package's files changed while it was built (${listed(changed)})`;
1579
+ }
1580
+ //#endregion
1581
+ //#region src/services/package-build/steps/release-approval.ts
1582
+ const under = (path, directory) => path === directory || path.startsWith(`${directory}/`);
1583
+ /**
1584
+ * The output directory as given, then the directory the build replaces when
1585
+ * that is a symlink to another place in the package: neither is a source.
1586
+ */
1587
+ function outputDirectories$1(projectRoot, outDir, target) {
1588
+ const output = packagePath(projectRoot, outDir);
1589
+ const real = packagePath(projectRoot, target);
1590
+ return real !== ".." && !real.startsWith("../") && !isAbsolute(real) && !under(real, output) ? [output, real] : [output];
1591
+ }
1592
+ /** With `--release`, records the package's files before anything is built. */
1593
+ const releaseStartStep = {
1594
+ id: "release-start",
1595
+ run: ({ args, projectRoot, outDir, session, findings }) => {
1596
+ if (args.release) findings.releaseStart = revisionFiles(projectRoot, outputDirectories$1(projectRoot, outDir, session.output));
1597
+ return Promise.resolve();
1598
+ }
1599
+ };
1600
+ const notWritten = (why) => new BuildRefusal(`✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`);
1601
+ /**
1602
+ * With `--release`, once the output is replaced: records what the release
1603
+ * check approved and what `npm pack` publishes from the new output, unless
1604
+ * tsc's errors were accepted or the package changed while it was built.
1605
+ */
1606
+ const releaseApprovalStep = {
1607
+ id: "release-approval",
1608
+ when: "committed",
1609
+ run: ({ args, projectRoot, outDir, session, findings }) => {
1610
+ if (args.release) recordApproval(projectRoot, outputDirectories$1(projectRoot, outDir, session.output), findings);
1611
+ return Promise.resolve();
1612
+ }
1613
+ };
1614
+ function recordApproval(projectRoot, outputs, findings) {
1615
+ const plan = planApproval({
1616
+ typesOk: findings.typesOk,
1617
+ release: findings.release,
1618
+ startFiles: findings.releaseStart,
1619
+ outputs,
1620
+ compilerOutputs: findings.compilerOutputs.map((path) => packagePath(projectRoot, path))
1621
+ });
1622
+ if ("refused" in plan) throw notWritten(plan.refused);
1623
+ const { release, excluded } = plan;
1624
+ const [output] = outputs;
1625
+ const files = revisionFiles(projectRoot, [output, ...excluded]);
1626
+ const changed = changedWhileBuilt(plan, files);
1627
+ if (changed !== void 0) throw notWritten(changed);
1628
+ let published;
1629
+ try {
1630
+ published = publishedFiles(projectRoot);
1631
+ } catch (error) {
1632
+ throw notWritten(error instanceof Error ? error.message : String(error));
1633
+ }
1634
+ const phCliVersion = getVersion();
1635
+ writeReleaseApproval(projectRoot, {
1636
+ kind: "powerhouse.release-approval",
1637
+ formatVersion: 1,
1638
+ phCliVersion,
1639
+ outDir: output,
1640
+ packageRevision: {
1641
+ digest: packageRevision(files, { [PH_CLI_BINDING]: phCliVersion }),
1642
+ excluded
1643
+ },
1644
+ publishedFiles: published,
1645
+ report: {
1646
+ profile: "release",
1647
+ status: release.report.status,
1648
+ definitions: release.report.definitions
1649
+ },
1650
+ scalars: release.scalars,
1651
+ hostValidation: release.host
1652
+ });
1653
+ console.log(`✔ Release approval written to ${RELEASE_APPROVAL_PATH}`);
1654
+ }
1655
+ //#endregion
1656
+ //#region src/services/package-build/steps/stylesheet.ts
1657
+ function sourcePath(projectRoot, path) {
1658
+ return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll("\\", "/")}`;
1659
+ }
1660
+ const stylesheetStep = {
1661
+ id: "stylesheet",
1662
+ run: ({ agent, projectRoot, session }) => {
1663
+ const stage = session.stage();
1664
+ const command = resolveCommand(agent, "execute-local", [
1665
+ "tailwindcss",
1666
+ "--input",
1667
+ "-",
1668
+ "--minify"
1669
+ ]);
1670
+ if (command === null) throw new BuildRefusal("You need to have tailwindcss installed to use the `build` command.");
1671
+ const stylePath = join(projectRoot, "style.css");
1672
+ const style = existsSync(stylePath) ? readFileSync(stylePath, "utf-8") : void 0;
1673
+ const compiled = execSync(`${command.command} ${command.args.join(" ")}`, {
1674
+ cwd: projectRoot,
1675
+ input: packageStyleEntry(style, {
1676
+ browserDir: sourcePath(projectRoot, join(stage, "browser")),
1677
+ localPackages: localPackageNames(projectRoot)
1678
+ }),
1679
+ encoding: "utf-8",
1680
+ stdio: [
1681
+ "pipe",
1682
+ "pipe",
1683
+ "inherit"
1684
+ ],
1685
+ maxBuffer: 67108864
1686
+ });
1687
+ const distDir = session.writesPackageDist ? stage : join(projectRoot, "dist");
1688
+ mkdirSync(distDir, { recursive: true });
1689
+ writeFileSync(join(distDir, "style.css"), packageStylesheet(compiled));
1690
+ return Promise.resolve();
1691
+ }
1692
+ };
1693
+ //#endregion
1694
+ //#region src/services/compiler-output/emit.ts
1695
+ const withoutExtension = (path) => path.replace(/\.[^./\\]+$/, "");
1696
+ const declares = (options) => options.declaration === true || options.composite === true;
1697
+ /**
1698
+ * Where tsc keeps the build info of `configFile`, by TypeScript's rule:
1699
+ * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the
1700
+ * config's place relative to `rootDir` when that is set; else beside the
1701
+ * config.
1702
+ */
1703
+ function buildInfoFile(options, configFile) {
1704
+ const configDir = dirname(configFile);
1705
+ const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;
1706
+ if (options.tsBuildInfoFile !== void 0) return resolve(configDir, options.tsBuildInfoFile);
1707
+ if (options.outFile !== void 0) return resolve(configDir, `${withoutExtension(options.outFile)}.tsbuildinfo`);
1708
+ if (options.outDir === void 0) return resolve(configDir, name);
1709
+ const fromRoot = options.rootDir === void 0 ? "" : relative(resolve(configDir, options.rootDir), configDir);
1710
+ return resolve(configDir, options.outDir, fromRoot, name);
1711
+ }
1712
+ /**
1713
+ * The files tsc writes for `outFile`: the bundle and its map unless it
1714
+ * emits declarations only, then the declaration and its map when it
1715
+ * declares. None without `outFile` or with `noEmit`.
1716
+ */
1717
+ function outFileOutputs(options, configFile) {
1718
+ if (options.outFile === void 0 || options.noEmit) return [];
1719
+ const output = resolve(dirname(configFile), options.outFile);
1720
+ const files = [];
1721
+ if (!options.emitDeclarationOnly) files.push(output, ...options.sourceMap ? [`${output}.map`] : []);
1722
+ if (declares(options)) {
1723
+ const declaration = `${withoutExtension(output)}.d.ts`;
1724
+ files.push(declaration, ...options.declarationMap ? [`${declaration}.map`] : []);
1725
+ }
1726
+ return files;
1727
+ }
1728
+ /** The declaration and output directories the options name, resolved. */
1729
+ function outputDirectories(options, configDir) {
1730
+ return [options.declarationDir, options.outDir].filter((dir) => dir !== void 0).map((dir) => resolve(configDir, dir));
1731
+ }
1732
+ /** Where tsc writes declarations, when it writes them to a directory of their own. */
1733
+ function declarationDirectory(options, configDir) {
1734
+ const dir = options.declarationDir ?? options.outDir;
1735
+ if (!dir || !declares(options)) return void 0;
1736
+ return resolve(configDir, dir);
1737
+ }
1738
+ //#endregion
1739
+ //#region src/services/package-build/staging/inventory.ts
1740
+ const optionalString = (value) => typeof value === "string" ? value : void 0;
1741
+ const optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
1742
+ /** The options in `tsc --showConfig` output, or undefined when it is not JSON. */
1743
+ function parseShownConfig(text) {
1744
+ let shown;
1745
+ try {
1746
+ shown = JSON.parse(text);
1747
+ } catch {
1748
+ return;
1749
+ }
1750
+ if (typeof shown !== "object" || shown === null) return void 0;
1751
+ const options = shown.compilerOptions;
1752
+ if (typeof options !== "object" || options === null) return {};
1753
+ const record = options;
1754
+ return {
1755
+ declaration: optionalBoolean(record.declaration),
1756
+ composite: optionalBoolean(record.composite),
1757
+ declarationDir: optionalString(record.declarationDir),
1758
+ outDir: optionalString(record.outDir),
1759
+ outFile: optionalString(record.outFile),
1760
+ rootDir: optionalString(record.rootDir),
1761
+ tsBuildInfoFile: optionalString(record.tsBuildInfoFile),
1762
+ noEmit: optionalBoolean(record.noEmit),
1763
+ emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),
1764
+ sourceMap: optionalBoolean(record.sourceMap),
1765
+ declarationMap: optionalBoolean(record.declarationMap)
1766
+ };
1767
+ }
1768
+ function inside(root, path) {
1769
+ const rel = relative(root, path);
1770
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
1771
+ }
1772
+ /**
1773
+ * What the root project's tsc writes inside the package, for the build to
1774
+ * snapshot and restore: its build info first, then the files `outFile`
1775
+ * writes, then its declaration and output directories, the build's own
1776
+ * output directory or one holding it included. A directory holding
1777
+ * `buildDirectory`, where the build keeps its runs and their snapshots, is
1778
+ * left out and unprotected, as without staging: a snapshot of it would copy
1779
+ * itself. This says what to protect, not what to carry into the stage.
1780
+ */
1781
+ function compilerOutputInventory(options, at) {
1782
+ const inPackage = (path) => inside(at.packageRoot, path);
1783
+ const directories = outputDirectories(options, dirname(at.configFile)).filter(inPackage).filter((dir) => dir !== at.buildDirectory && !inside(dir, at.buildDirectory));
1784
+ return [
1785
+ ...[buildInfoFile(options, at.configFile)].filter(inPackage).map((path) => ({
1786
+ path,
1787
+ kind: "build-info"
1788
+ })),
1789
+ ...outFileOutputs(options, at.configFile).filter(inPackage).map((path) => ({
1790
+ path,
1791
+ kind: "file"
1792
+ })),
1793
+ ...[...new Set(directories)].map((path) => ({
1794
+ path,
1795
+ kind: "directory"
1796
+ }))
1797
+ ];
1798
+ }
1799
+ //#endregion
1800
+ //#region src/services/package-build/steps/typecheck.ts
1801
+ const TYPE_ERROR_RISK = "A package built with type errors can load and still fail at runtime.";
1802
+ const UNSAFE_BUILD_WARNING = "⚠ Built despite type errors. " + TYPE_ERROR_RISK + " Fix them before you publish or deploy it.";
1803
+ function showCompilerOptions(agent, projectRoot) {
1804
+ const showConfig = resolveCommand(agent, "execute-local", ["tsc", "--showConfig"]);
1805
+ if (showConfig === null) return void 0;
1806
+ try {
1807
+ return parseShownConfig(execSync(`${showConfig.command} ${showConfig.args.join(" ")}`, {
1808
+ cwd: projectRoot,
1809
+ encoding: "utf8",
1810
+ stdio: [
1811
+ "ignore",
1812
+ "pipe",
1813
+ "ignore"
1814
+ ]
1815
+ }));
1816
+ } catch {
1817
+ return;
1818
+ }
1819
+ }
1820
+ function declarationsMissing(options, projectRoot) {
1821
+ const path = declarationDirectory(options, projectRoot);
1822
+ if (path === void 0) return false;
1823
+ return !existsSync(path) || readdirSync(path).length === 0;
1824
+ }
1825
+ function isInteractive() {
1826
+ return Boolean(process.stdin.isTTY) && !process.env.CI;
1827
+ }
1828
+ async function confirmBuildDespiteTypeErrors() {
1829
+ const hint = "Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.";
1830
+ if (!isInteractive()) throw new BuildRefusal(`\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\n${hint}`);
1831
+ const enquirer = await import("enquirer");
1832
+ let confirmed;
1833
+ try {
1834
+ confirmed = (await enquirer.default.prompt({
1835
+ type: "confirm",
1836
+ name: "confirmed",
1837
+ message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,
1838
+ initial: false
1839
+ })).confirmed;
1840
+ } catch {
1841
+ confirmed = false;
1842
+ }
1843
+ if (!confirmed) throw new BuildRefusal(`Build cancelled. ${hint}`);
1844
+ }
1845
+ //#endregion
1846
+ //#region src/services/package-build/steps/standard.ts
1847
+ /**
1848
+ * `ph build`'s steps in the order they run. Another phase inserts its own
1849
+ * with `[...standardBuildSteps, ...more]` and `after` on the step it follows.
1850
+ */
1851
+ const standardBuildSteps = [
1852
+ releaseStartStep,
1853
+ manifestNameStep,
1854
+ piecesOutDirStep,
1855
+ connectRoutesStep,
1856
+ {
1857
+ id: "typecheck",
1858
+ run: async ({ agent, args, outDir, projectRoot, session, findings }) => {
1859
+ const options = showCompilerOptions(agent, projectRoot);
1860
+ const force = options !== void 0 && declarationsMissing(options, projectRoot);
1861
+ const tscCommand = resolveCommand(agent, "execute-local", [
1862
+ "tsc",
1863
+ "--build",
1864
+ ...force ? ["--force"] : []
1865
+ ]);
1866
+ if (tscCommand === null) throw new BuildRefusal("You need to have typescript installed to use the `build` command.");
1867
+ if (options !== void 0) {
1868
+ const outputs = compilerOutputInventory(options, {
1869
+ configFile: join(projectRoot, "tsconfig.json"),
1870
+ packageRoot: projectRoot,
1871
+ buildDirectory: join(projectRoot, BUILD_DIRECTORY)
1872
+ });
1873
+ session.protectCompilerOutputs(outputs);
1874
+ findings.compilerOutputs = outputs.map(({ path }) => path);
1875
+ }
1876
+ console.log("\n▶ Type-checking and emitting types via tsc...");
1877
+ try {
1878
+ execSync(`${tscCommand.command} ${tscCommand.args.join(" ")}`, { stdio: "inherit" });
1879
+ console.log("✔ Types emitted to", join(outDir, "types"));
1880
+ findings.typesOk = true;
1881
+ } catch {
1882
+ findings.typesOk = false;
1883
+ }
1884
+ session.compilerOutputsWritten();
1885
+ if (!findings.typesOk && !args.ignoreTypeErrors) await confirmBuildDespiteTypeErrors();
1886
+ }
1887
+ },
1888
+ definitionsStep,
1889
+ browserBundleStep,
1890
+ nodeBundleStep,
1891
+ piecesStep,
1892
+ distManifestStep,
1893
+ offeredRoutesStep,
1894
+ stylesheetStep,
1895
+ releaseApprovalStep
1896
+ ];
1897
+ //#endregion
1898
+ //#region src/services/package-build/steps/trace.ts
1899
+ function createTraceFiles() {
1900
+ const cache = {};
1901
+ return (file) => traceFile(file, cache);
1902
+ }
1903
+ async function traceFile(file, cache) {
1904
+ const { fileList, reasons } = await nodeFileTrace([file], {
1905
+ base: "/",
1906
+ cache
1907
+ });
1908
+ const absolute = (p) => resolve("/", p);
1909
+ return {
1910
+ fileList: new Set([...fileList].map(absolute)),
1911
+ reasons: new Map([...reasons].map(([p, reason]) => [absolute(p), { parents: new Set([...reason.parents].map(absolute)) }]))
1912
+ };
1913
+ }
1914
+ //#endregion
1915
+ //#region src/services/package-build/run-build.ts
1916
+ const STOP_SIGNALS = [
1917
+ "SIGINT",
1918
+ "SIGTERM",
1919
+ "SIGHUP"
1920
+ ];
1921
+ /**
1922
+ * The signal listeners signal-exit installs: each ends the process when
1923
+ * only signal-exit listeners are left, so they are not an embedding
1924
+ * process that keeps running. Read from the counts its copies share.
1925
+ */
1926
+ function exitOnlyListeners() {
1927
+ const count = (emitter) => {
1928
+ const value = emitter?.count;
1929
+ return typeof value === "number" ? value : 0;
1930
+ };
1931
+ const shared = globalThis;
1932
+ const legacy = process;
1933
+ return count(shared[Symbol.for("signal-exit emitter")]) + count(legacy.__signal_exit_emitter__);
1934
+ }
1935
+ /**
1936
+ * Stops the build when the process is told to stop, for as long as it runs.
1937
+ * The handler runs first and removes itself, so the listeners already there
1938
+ * act as if it had never been added. When one of them keeps the process
1939
+ * running (an embedding process), the handler only cancels: the step runner
1940
+ * rolls back once the running step settles, and the lock is released after
1941
+ * that. Otherwise the process should end with the signal: the handler
1942
+ * restores the previous output at once, releases the lock and, with no
1943
+ * listener left, re-raises the signal. The run and its snapshot stay for
1944
+ * the next build to replay. The lock does not: a dead owner's lock is taken
1945
+ * over only from the same host, which a new container or a renamed machine
1946
+ * is not. A signal-exit callback can still keep the process running; then
1947
+ * the runner restores again from that snapshot once the running step
1948
+ * settles.
1949
+ */
1950
+ function stopOnSignal(session, ownsProcess) {
1951
+ const stop = (signal) => {
1952
+ session.cancel(signal);
1953
+ remove();
1954
+ if (process.listenerCount(signal) > exitOnlyListeners()) return;
1955
+ session.rollback();
1956
+ if (ownsProcess) session.releaseLock();
1957
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
1958
+ };
1959
+ const remove = () => {
1960
+ for (const signal of STOP_SIGNALS) process.removeListener(signal, stop);
1961
+ };
1962
+ for (const signal of STOP_SIGNALS) process.prependListener(signal, stop);
1963
+ return remove;
1964
+ }
1965
+ /**
1966
+ * Builds the package in the current directory: every step writes to a stage,
1967
+ * which replaces the output directory only when all of them succeed. A
1968
+ * failure, a refusal or a stop signal leaves the previous output and
1969
+ * compiler outputs as they were.
1970
+ */
1971
+ async function buildPackage(args, options = {}) {
1972
+ const { outDir } = args;
1973
+ const projectRoot = process.cwd();
1974
+ const steps = options.steps ?? standardBuildSteps;
1975
+ const session = await openBuildSession({
1976
+ packageRoot: projectRoot,
1977
+ outDir,
1978
+ cleanedEntries: entriesCleanedBy(steps),
1979
+ linkCleanedEntries: options.steps === void 0
1980
+ });
1981
+ const stopListening = stopOnSignal(session, options.ownsProcess ?? false);
1982
+ try {
1983
+ const ctx = {
1984
+ args,
1985
+ projectRoot,
1986
+ outDir,
1987
+ agent: (await detect())?.agent ?? "npm",
1988
+ session,
1989
+ checkDefinitions: options.checkDefinitions ?? false,
1990
+ pieces: planPieces(projectRoot, outDir),
1991
+ detection: createDetectionCache(),
1992
+ trace: createTraceFiles(),
1993
+ findings: {
1994
+ offersRoutes: false,
1995
+ typesOk: true,
1996
+ compilerOutputs: [],
1997
+ releaseStart: void 0,
1998
+ release: void 0,
1999
+ external: /* @__PURE__ */ new Map(),
2000
+ pkg: void 0,
2001
+ built: []
2002
+ }
2003
+ };
2004
+ await runBuildSteps(steps, ctx, session);
2005
+ if (!ctx.findings.typesOk) console.warn(`\n${UNSAFE_BUILD_WARNING}`);
2006
+ } finally {
2007
+ stopListening();
2008
+ session.rollback();
2009
+ session.close();
2010
+ }
2011
+ }
2012
+ //#endregion
2013
+ //#region src/services/build.ts
2014
+ /**
2015
+ * `ph build`, and the package build `ph connect build` and the switchboard
2016
+ * runner start from. A refusal (missing tsc or tailwindcss, type errors not
2017
+ * accepted, a release check that fails) prints its message and exits 1 once
2018
+ * the previous output is back, as these callers have always seen it.
2019
+ * Only `ph build` passes `checkDefinitions`, so the other callers import
2020
+ * none of the package's modules. A command that adds steps passes
2021
+ * `[...standardBuildSteps, ...its own]` as `steps`.
2022
+ */
2023
+ async function runBuild(args, options = {}) {
2024
+ try {
2025
+ return await buildPackage(args, options);
2026
+ } catch (error) {
2027
+ if (!(error instanceof BuildRefusal)) throw error;
2028
+ console.error(error.message);
2029
+ process.exit(error.exitCode);
2030
+ }
2031
+ }
2032
+ //#endregion
2033
+ export { assertExternalDependenciesDeclared as i, createTraceFiles as n, assertManifestNameMatchesPackage as r, runBuild as t };
2034
+
2035
+ //# sourceMappingURL=build-Dfrq_MIX.mjs.map
2036
+ //# debugId=e01699e0-0f44-5641-9609-791314473794