@cydm/pie 4.5.0 → 4.6.1

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  readProcessCommandLine
4
- } from "./chunk-X6LBWHK3.js";
4
+ } from "./chunk-7RJXKN7N.js";
5
5
  import {
6
6
  VERSION
7
7
  } from "./chunk-CBDQJMUI.js";
@@ -39,17 +39,35 @@ function versionDiffers(a, b) {
39
39
  const canon = (v) => v.trim().replace(/^v/, "").split("+")[0];
40
40
  return canon(a) !== canon(b);
41
41
  }
42
- function resolveNpm(nodePath) {
43
- const prefix = path.dirname(path.dirname(nodePath));
44
- for (const npmCli of [
42
+ function resolveNpm(nodePath, platform = process.platform, env = process.env) {
43
+ const nodeDir = path.dirname(nodePath);
44
+ const prefix = path.dirname(nodeDir);
45
+ const windows = platform === "win32";
46
+ const candidates = [
47
+ path.join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js"),
45
48
  path.join(prefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
46
49
  path.join(prefix, "node_modules", "npm", "bin", "npm-cli.js")
47
- ]) {
48
- if (fs.existsSync(npmCli)) return { command: nodePath, prefixArgs: [npmCli], reason: `node + ${npmCli}` };
50
+ ];
51
+ if (windows) {
52
+ const searchPath = Object.entries(env).find(([key]) => key.toUpperCase() === "PATH")?.[1] ?? "";
53
+ for (const dir of searchPath.split(";").filter(Boolean)) {
54
+ candidates.push(path.resolve(dir.replace(/^"(.*)"$/, "$1"), "node_modules", "npm", "bin", "npm-cli.js"));
55
+ }
56
+ }
57
+ const isFile = (file) => {
58
+ try {
59
+ return fs.statSync(file).isFile();
60
+ } catch {
61
+ return false;
62
+ }
63
+ };
64
+ for (const npmCli of candidates) {
65
+ if (isFile(npmCli)) return { command: nodePath, prefixArgs: [npmCli], reason: `node + ${npmCli}` };
49
66
  }
50
- const sibling = path.join(path.dirname(nodePath), "npm");
51
- if (fs.existsSync(sibling)) return { command: sibling, prefixArgs: [], reason: `sibling ${sibling}` };
52
- return { command: "npm", prefixArgs: [], reason: "PATH npm" };
67
+ const binary = windows ? "npm.exe" : "npm";
68
+ const sibling = path.join(nodeDir, binary);
69
+ if (isFile(sibling)) return { command: sibling, prefixArgs: [], reason: `sibling ${sibling}` };
70
+ return { command: binary, prefixArgs: [], reason: `PATH ${binary}` };
53
71
  }
54
72
  function runNpm(plan, args, timeoutMs) {
55
73
  const child = spawnSync(plan.command, [...plan.prefixArgs, ...args], {
@@ -61,7 +79,9 @@ function runNpm(plan, args, timeoutMs) {
61
79
  });
62
80
  const sanitize = (text) => text.replace(/[^\x20-\x7e\n\t]/g, "?").trim();
63
81
  const stdout = sanitize(child.stdout ?? "");
64
- const stderr = sanitize(child.stderr ?? "");
82
+ const error = child.error;
83
+ const spawnError = error ? [error.code, error.message].filter(Boolean).join(": ") : "";
84
+ const stderr = sanitize([child.stderr ?? "", spawnError].filter(Boolean).join("\n"));
65
85
  const lines = [stdout, stderr].join("\n").split("\n").filter(Boolean);
66
86
  return { code: child.status, stdout, stderr, tail: lines.slice(-8).join("\n").slice(0, 1200) };
67
87
  }
@@ -221,23 +241,35 @@ async function performUpgrade(paths, effects, options) {
221
241
  return finish(build("guard", `the recorded resident pid cannot be verified (${residency}); refusing to restart blindly. Check pie manager status, then retry.`));
222
242
  }
223
243
  effects.log(`repair run: version ${toVersion} already installed but the resident is ${residency}; restarting without reinstall`);
224
- return finish(await restartAndRecycle(effects, state, fromVersion, toVersion, (s) => {
244
+ return finish(await restartAndRecycle(effects, paths, state, fromVersion, toVersion, (s) => {
225
245
  stage = s;
226
246
  }, build));
227
247
  }
248
+ if (effects.preInstallStop) {
249
+ const stopped = effects.preInstallStop(state);
250
+ if (stopped === "refused") {
251
+ return finish(build("install", "refused: could not stop the resident/workers before install (Windows file locks); check pie manager status and retry"));
252
+ }
253
+ if (stopped === "stopped") effects.log("windows: resident/workers stopped before install (native-module file locks)");
254
+ }
228
255
  const install = effects.npmInstall(toVersion);
229
256
  if (install.code !== 0) {
230
257
  return finish(build("install", `npm install @cydm/pie@${toVersion} failed (exit ${install.code}):
231
258
  ${install.tail}`));
232
259
  }
233
- return finish(await restartAndRecycle(effects, state, fromVersion, toVersion, (s) => {
260
+ const target = effects.installTargetCheck();
261
+ if (!target.ok) {
262
+ return finish(build("install", `install target mismatch \u2014 restart skipped:
263
+ ${target.detail}`));
264
+ }
265
+ return finish(await restartAndRecycle(effects, paths, state, fromVersion, toVersion, (s) => {
234
266
  stage = s;
235
267
  }, build));
236
268
  } catch (error) {
237
269
  return finish(build(stage, `unexpected error: ${error instanceof Error ? error.message : String(error)}`));
238
270
  }
239
271
  }
240
- async function restartAndRecycle(effects, state, fromVersion, toVersion, setStage, build) {
272
+ async function restartAndRecycle(effects, paths, state, fromVersion, toVersion, setStage, build) {
241
273
  setStage("restart");
242
274
  let successorPid;
243
275
  if (state.service === true) {
@@ -262,6 +294,11 @@ async function restartAndRecycle(effects, state, fromVersion, toVersion, setStag
262
294
  }
263
295
  successorPid = started.pid;
264
296
  effects.log(`manual mode: successor resident verified (pid ${successorPid})`);
297
+ const successor = findManagerResident(paths.discoveryDir, state.sessionId);
298
+ if (successor && successor.version && successor.pid === started.pid && successor.version !== toVersion) {
299
+ return build("restart", `successor became ready on pid ${successor.pid} but reports version ${successor.version}, expected ${toVersion} \u2014 the restart launched OLD code. The install target check passed yet the entry differs; inspect the entry path and npm prefixes before retrying.`);
300
+ }
301
+ if (successor && !successor.version) effects.log(`manual mode: successor discovery entry carries no version \u2014 upgrade success verified by readiness marker only`);
265
302
  }
266
303
  setStage("workers");
267
304
  const { recycle, skip } = partitionWorkers(effects.scanWorkers());
@@ -369,6 +406,42 @@ function cliEffects(paths, log) {
369
406
  const npm = resolveNpm(process.execPath);
370
407
  const effects = {
371
408
  npmInstall: (target) => runNpm(npm, ["install", "-g", `@cydm/pie@${target}`], 5 * 6e4),
409
+ installTargetCheck: () => {
410
+ try {
411
+ const rootRaw = spawnSync(npm.command, [...npm.prefixArgs, "root", "-g"], { encoding: "utf8", timeout: 3e4, windowsHide: true });
412
+ const npmRoot = String(rootRaw.stdout ?? "").trim().split(/\r?\n/).filter(Boolean).pop() ?? "";
413
+ if (rootRaw.status !== 0 || !npmRoot) return { ok: false, detail: `npm root -g failed (exit ${rootRaw.status}): ${String(rootRaw.stderr ?? "").slice(-200)}` };
414
+ let entry;
415
+ try {
416
+ entry = fs.realpathSync(paths.entryPath);
417
+ } catch {
418
+ return { ok: false, detail: `entry ${paths.entryPath} is not resolvable` };
419
+ }
420
+ let dir = path.dirname(entry);
421
+ let pkgRoot;
422
+ for (let i = 0; i < 6 && dir; i += 1) {
423
+ if (fs.existsSync(path.join(dir, "package.json"))) {
424
+ pkgRoot = dir;
425
+ break;
426
+ }
427
+ const parent = path.dirname(dir);
428
+ if (parent === dir) break;
429
+ dir = parent;
430
+ }
431
+ let installedPkg;
432
+ try {
433
+ installedPkg = fs.realpathSync(path.join(npmRoot, "@cydm", "pie"));
434
+ } catch {
435
+ return { ok: false, detail: `npm root ${npmRoot} has no @cydm/pie installed (realpath failed) \u2014 the install did not land in this npm's global tree.` };
436
+ }
437
+ if (pkgRoot === void 0 || installedPkg !== pkgRoot) {
438
+ return { ok: false, detail: `npm installed ${installedPkg} but the running entry resolves to ${pkgRoot ?? path.dirname(entry)} \u2014 a different prefix owns this Pie (multi-Node or custom npm prefix); the restart would keep the OLD code. Install with the npm that owns ${pkgRoot ?? entry} or fix the entry resolution.` };
439
+ }
440
+ return { ok: true, detail: `install target verified: ${pkgRoot}` };
441
+ } catch (error) {
442
+ return { ok: false, detail: `install-target check errored: ${error instanceof Error ? error.message : String(error)}` };
443
+ }
444
+ },
372
445
  npmViewLatest: () => {
373
446
  const out = runNpm(npm, ["view", "@cydm/pie", "version", "--json"], 3e4);
374
447
  if (out.code !== 0) return { tail: out.tail || `npm view exited ${out.code}` };
@@ -491,8 +564,8 @@ function cliEffects(paths, log) {
491
564
  restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
492
565
  restartFailed = r.status !== 0;
493
566
  } else if (process.platform === "win32") {
494
- spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
495
- const r = spawnSync("schtasks", ["/Run", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
567
+ spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
568
+ const r = spawnSync("schtasks", ["/Run", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
496
569
  restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
497
570
  restartFailed = r.status !== 0;
498
571
  } else {
@@ -534,6 +607,36 @@ function cliEffects(paths, log) {
534
607
  writeResult: (result) => writeResultAtomic(paths.resultFile, result, log),
535
608
  tryLock: () => tryLockWithReclamation(paths.lockFile),
536
609
  unlock: () => unlockOwned(paths.lockFile),
610
+ ...process.platform === "win32" ? { preInstallStop: (state) => {
611
+ let touched = false;
612
+ for (const peer of partitionWorkers(effects.scanWorkers()).recycle) {
613
+ if (effects.retireWorkerIfStillIdle(peer) === "retired") {
614
+ touched = true;
615
+ effects.log(`windows pre-install: retired idle worker pid ${peer.pid} (${peer.name})`);
616
+ }
617
+ }
618
+ if (state.service === true) {
619
+ try {
620
+ spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
621
+ touched = true;
622
+ } catch (error) {
623
+ log(`windows pre-install: schtasks /End failed: ${error instanceof Error ? error.message : String(error)}`);
624
+ return "refused";
625
+ }
626
+ } else {
627
+ const status = effects.residentStatus(state);
628
+ if (status === "foreign" || status === "unknown") return "refused";
629
+ if (status === "alive") {
630
+ const stopped = effects.terminateResident(state);
631
+ if (stopped !== "terminated" && stopped !== "dead") return "refused";
632
+ if (stopped === "terminated" && typeof state.pid === "number") {
633
+ if (!effects.waitExit(state.pid, 2e4)) log(`windows pre-install: resident pid ${state.pid} did not exit within 20s; npm may still hit file locks`);
634
+ }
635
+ touched = true;
636
+ }
637
+ }
638
+ return touched ? "stopped" : "unnecessary";
639
+ } } : {},
537
640
  log
538
641
  };
539
642
  return effects;
@@ -0,0 +1,14 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ understandReadFile
4
+ } from "./chunk-4PR34UZF.js";
5
+ import "./chunk-BLDI2GRF.js";
6
+ import "./chunk-Y3I2UV5Y.js";
7
+ import "./chunk-5KI4Y4LA.js";
8
+ import "./chunk-3W3SXVPB.js";
9
+ import "./chunk-XXGYUYXI.js";
10
+ import "./chunk-F7EBZTZO.js";
11
+ import "./chunk-LZQXQOPJ.js";
12
+ export {
13
+ understandReadFile
14
+ };