infra-kit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{boot-BL4EQMZV.js → boot-XLDVLQEG.js} +2 -2
  2. package/dist/boot-XLDVLQEG.js.map +7 -0
  3. package/dist/chunk-2H6VQIGT.js +7 -0
  4. package/dist/chunk-2H6VQIGT.js.map +7 -0
  5. package/dist/chunk-6UJQB36N.js +2 -0
  6. package/dist/chunk-6UJQB36N.js.map +7 -0
  7. package/dist/chunk-AG7XWZNT.js +3 -0
  8. package/dist/chunk-AG7XWZNT.js.map +7 -0
  9. package/dist/{chunk-HHWP3YXW.js → chunk-AWFGP6GY.js} +1 -1
  10. package/dist/{chunk-HHWP3YXW.js.map → chunk-AWFGP6GY.js.map} +1 -1
  11. package/dist/chunk-F656FWV5.js +11 -0
  12. package/dist/chunk-F656FWV5.js.map +7 -0
  13. package/dist/{chunk-X2HFNQRU.js → chunk-OWX4O3IS.js} +2 -2
  14. package/dist/chunk-R2SZWOPC.js +3 -0
  15. package/dist/chunk-R2SZWOPC.js.map +7 -0
  16. package/dist/chunk-RZF36IGQ.js +4 -0
  17. package/dist/chunk-RZF36IGQ.js.map +7 -0
  18. package/dist/cli.js +424 -13
  19. package/dist/cli.js.map +4 -4
  20. package/dist/dev-server.js +2 -2
  21. package/dist/dev-server.js.map +2 -2
  22. package/dist/dev-wizard-run-J5WSWCZT.js +2 -0
  23. package/dist/dev-wizard-run-J5WSWCZT.js.map +7 -0
  24. package/dist/mcp-proxy.js +9 -9
  25. package/dist/mcp-proxy.js.map +2 -2
  26. package/dist/update-check.js +1 -1
  27. package/dist/update-check.js.map +2 -2
  28. package/package.json +3 -7
  29. package/readme.md +4 -4
  30. package/dist/boot-BL4EQMZV.js.map +0 -7
  31. package/dist/chunk-75BE6MSY.js +0 -7
  32. package/dist/chunk-75BE6MSY.js.map +0 -7
  33. package/dist/chunk-75URROMU.js +0 -4
  34. package/dist/chunk-75URROMU.js.map +0 -7
  35. package/dist/chunk-FWINBDB5.js +0 -444
  36. package/dist/chunk-FWINBDB5.js.map +0 -7
  37. package/dist/chunk-GRWUCPQL.js +0 -2
  38. package/dist/chunk-GRWUCPQL.js.map +0 -7
  39. package/dist/chunk-H5AAXCRJ.js +0 -9
  40. package/dist/chunk-H5AAXCRJ.js.map +0 -7
  41. package/dist/chunk-IXWQ7EQT.js +0 -3
  42. package/dist/chunk-IXWQ7EQT.js.map +0 -7
  43. package/dist/dev-wizard-run-643QKSR3.js +0 -2
  44. package/dist/dev-wizard-run-643QKSR3.js.map +0 -7
  45. package/dist/mcp.js +0 -3
  46. package/dist/mcp.js.map +0 -7
  47. /package/dist/{chunk-X2HFNQRU.js.map → chunk-OWX4O3IS.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts", "../src/dev/proxy/portless-node.ts"],
4
+ "sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\nimport { ensurePortlessNode, stableNodeCandidate } from './portless-node'\nimport type { EnsurePortlessNodeDeps, PortlessNodeResult } from './portless-node'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n /**\n * `~/.infra-kit/node` as a health verdict: a string is \"resolved and healthy \u2014 render through it\"\n * (doctor/setup after their node row), `null` is \"resolved and unhealthy or absent \u2014 render through\n * `execPath`, the node that provably runs\", `undefined` is \"not resolved\" and the inode-only candidate\n * is checked here instead (`dev`, which never spawns on its hot path).\n */\n stableNode?: string | null\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n // Resolved before the candidate check: `dev` passes `{ home }` only, and the candidate must never stat `undefined`.\n const execPath = seams.execPath ?? process.execPath\n // Written out rather than `??`-chained: a `null` verdict (\"resolved, unhealthy\") must reach `execPath`\n // directly and never fall through to a candidate check that would contradict doctor's spawn.\n const stableNode =\n seams.stableNode === undefined ? stableNodeCandidate({ home: seams.home, execPath }) : seams.stableNode\n\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: stableNode ?? execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n kind: 'link'\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { kind: 'link', outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { kind: 'link', outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { kind: 'link', outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { kind: 'link', outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { kind: 'link', outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { kind: 'link', outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { kind: 'link', outcome: 'failed', target, link }\n }\n}\n\n/**\n * `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. The two\n * boot results are a union on `kind`: a caller that reads `link`/`target` (the `ik-mcp` stderr line)\n * narrows first.\n */\nexport type PortlessLinkLog = (result: PortlessLinkResult | PortlessNodeResult, message: string) => void\n\n/** The link's seams and the node's, sharing ONE `isGlobal` \u2014 the two are converged together at every boot. */\nexport interface PortlessStableDeps {\n link: EnsurePortlessLinkDeps\n node: EnsurePortlessNodeDeps\n}\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULTS back to report its steps, so the writers\n * can never disagree about which install is \"global\" or where the files go. `isGlobal` is memoised\n * per deps object: it costs a `realpathSync` plus the `.git` walk, and both steps ask it.\n */\nexport const realPortlessStableDeps = (): PortlessStableDeps => {\n const home = homedir()\n let global: boolean | undefined\n\n const isGlobal = (): boolean => {\n global ??= isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n\n return global\n }\n\n return {\n link: { resolveBin: resolvePortlessBin, isGlobal, home },\n node: {\n isGlobal,\n home,\n execPath: process.execPath,\n version: process.version,\n arch: process.arch,\n platform: process.platform,\n },\n }\n}\n\nconst logStep = (log: PortlessLinkLog, message: string, run: () => PortlessLinkResult | PortlessNodeResult): void => {\n try {\n log(run(), message)\n } catch {\n // A file that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n\n/**\n * The process-boot entry for both bins: the link, then the node \u2014 independent state, so the node step\n * runs whatever the link reported. fs-only, no subprocess, never throws, never exits, never writes to\n * stdout; each outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'` is\n * logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: PortlessStableDeps): void => {\n const stable = deps ?? realPortlessStableDeps()\n\n logStep(log, 'portless link', () => {\n return ensurePortlessLink(stable.link)\n })\n logStep(log, 'portless node', () => {\n return ensurePortlessNode(stable.node)\n })\n}\n", "/**\n * @fileoverview\n *\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, an Orca pane, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\nimport { shellLine } from 'src/lib/shell-quote'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\n// This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n// `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\n//\n// This is not merely cosmetic. portless's `service install` writes the interpreter and script path it was\n// invoked with straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n// `process.argv[1]`), so the command printed here is the command that gets installed as a ROOT SYSTEM\n// DAEMON. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as\n// root.\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + shellLine(words)\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\n */\n// This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was UNSOUND: portless's\n// `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n// process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n// stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n// old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n// were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n//\n// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n", "/**\n * @fileoverview\n *\n * `~/.infra-kit/node` \u2014 a stable, regular-file name for the Node binary the global infra-kit runs, kept\n * current by every process boot beside `~/.infra-kit/portless` (see that module's header for the link).\n *\n * Why a HARDLINK: `portless service install` bakes `process.execPath` into the root plist, and Node\n * realpaths `execPath` (measured: a hardlink of node prints its own path from `-p process.execPath`;\n * a symlink prints the target), so no symlink in front of the binary survives into the plist. Under\n * pnpm 12 the binary lives in `global/v11/{pid}-{ts}/\u2026/node@runtime/\u2026`, a directory every `pnpm add -g`\n * re-mints \u2014 with no Node bump. A hardlink is a regular file, costs 0.3 ms and 0 bytes, and its inode\n * outlives the manager's directory, so the name cannot dangle across a re-mint + reboot the way a\n * symlink would. `copyFile(COPYFILE_FICLONE)` is a full 134 MB copy on APFS here, so it is the FALLBACK\n * only: root-owned `/usr/bin/node` under `protected_hardlinks`, a cross-volume home (macOS answers\n * `EPERM`, not `EXDEV`), exFAT/SMB/NFS (`ENOTSUP`), dataless iCloud (`EDEADLK`) \u2014 the failure set of\n * `link(2)` is not enumerable, so ANY throw takes the copy. The daemon never consults `execPath` again\n * after boot (`proxy start --foreground` spawns nothing), so that one plist word is the whole contract.\n *\n * T-1 \u2014 the hardlink SHARES an inode with the package manager's node, and macOS enforces no `ETXTBSY`:\n * a write through this name lands in the developer's real node and, on Apple Silicon, kills every\n * process mapping it by signature invalidation. Rename-only discipline is the ONLY guard: every byte\n * goes to a `node.tmp-<pid>` sibling and is published by `rename(2)`; the node path is never opened\n * for writing, never chmod'ed (that too mutates the shared inode) and never unlinked. `chmod` runs on\n * the copy branch's tmp alone \u2014 the source is executable already, this process executed it.\n *\n * Staleness is one inode compare against `process.execPath`, never a version or byte compare: after a\n * re-mint the source is a new inode with identical bytes and relinking is free. The sidecar keeps two\n * clocks \u2014 `refreshedAt` (the file) and `versionChangedAt` (the Node behind it, carried over on a\n * same-version relink) \u2014 because doctor's \"daemon predates Node \u2026\" advisory must not nag after every\n * global install. Neither is an fs timestamp: a hardlink's mtime is the source's install time.\n *\n * Same gate and contract as the link: `isGlobalInstall` is the only thing between a checkout and the\n * root daemon; nothing here spawns, writes stdout, or throws.\n */\nimport fs from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport process from 'node:process'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\n\n/** `<home>/.infra-kit/node` \u2014 the file the plist's first argv word names. */\nexport const portlessNodePath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'node')\n}\n\n/** `<node>.source.json` \u2014 what the file is (method, Node triple, source) and the two clocks. */\nexport const portlessNodeSidecar = (home: string): string => {\n return `${portlessNodePath(home)}.source.json`\n}\n\n// Hand-checked, not zod: this module is reached from the `ik-mcp` bundle, which must stay free of every\n// node_modules input (`dist-shebang.test.ts`). A sidecar is eight scalars \u2014 a validator is cheaper than\n// the dependency.\nexport interface PortlessNodeSidecar {\n method: 'hardlink' | 'copy'\n version: string\n arch: string\n platform: string\n source: string\n sourceSize?: number\n refreshedAt: string\n versionChangedAt: string\n}\n\nconst isSidecar = (value: unknown): value is PortlessNodeSidecar => {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n const strings = ['version', 'arch', 'platform', 'source', 'refreshedAt', 'versionChangedAt']\n\n return (\n (record.method === 'hardlink' || record.method === 'copy') &&\n strings.every((key) => {\n return typeof record[key] === 'string'\n }) &&\n (record.sourceSize === undefined || typeof record.sourceSize === 'number')\n )\n}\n\n/** The subset of `fs.Stats` the inode compare and the copy-path size witness need. */\nexport interface PortlessNodeStat {\n ino: number\n dev: number\n size: number\n isFile: () => boolean\n}\n\n/**\n * Every fs call the file needs, as an OBJECT seam: `vi.spyOn` cannot intercept named `node:fs` imports,\n * so tests hand in an in-memory fake and the call log \u2014 not the final state \u2014 carries the rename-only\n * contract (T-1). `copyFileSync` takes the mode so the FICLONE flag is visible in that log.\n */\nexport interface PortlessNodeFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n statSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n readFileSync: (target: string, encoding: 'utf8') => string\n writeFileSync: (target: string, data: string) => void\n readdirSync: (dir: string) => string[]\n linkSync: (existing: string, newPath: string) => void\n copyFileSync: (src: string, dest: string, mode: number) => void\n chmodSync: (target: string, mode: number) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport type PortlessNodeOutcome =\n 'created' | 'refreshed' | 'unchanged' | 'skipped-local' | 'skipped-platform' | 'failed'\n\nexport interface PortlessNodeResult {\n kind: 'node'\n outcome: PortlessNodeOutcome\n node: string\n /** The `execPath` the file was (or would have been) made from. */\n source: string\n version: string\n /** How the file relates to `source`; `null` when nothing was published and nothing converged was found. */\n method: 'hardlink' | 'copy' | null\n}\n\nexport interface EnsurePortlessNodeDeps {\n /** The SAME memoised closure the link uses \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n execPath: string\n version: string\n arch: string\n platform: NodeJS.Platform\n fs?: PortlessNodeFs\n now?: () => Date\n}\n\n// EXCL is load-bearing, not hygiene: a stale `node.tmp-<pid>` from a boot that died before its `rename`\n// can be a HARDLINK of the live node, and a reused pid would hand the copy branch that name \u2014 an\n// `O_TRUNC` open of it is the T-1 write-through. With EXCL the copy refuses (`EEXIST` \u2192 `'failed'`) and\n// the next boot's sweep clears the name.\nconst COPY_FLAGS = fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL\nconst COPY_MODE = 0o755\n\n/** `null` when the sidecar is absent, unreadable or does not parse \u2014 every one of those forces a refresh. */\nexport const readPortlessNodeSidecar = (home: string, nodeFs: PortlessNodeFs = fs): PortlessNodeSidecar | null => {\n try {\n const parsed: unknown = JSON.parse(nodeFs.readFileSync(portlessNodeSidecar(home), 'utf8'))\n\n return isSidecar(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nconst sameInode = (a: PortlessNodeStat, b: PortlessNodeStat): boolean => {\n return a.ino === b.ino && a.dev === b.dev\n}\n\n/**\n * `<home>/.infra-kit/node` when it is a regular file on the SAME inode as `execPath`, else `null`.\n * Inode equality is proof of runnability \u2014 the asking process IS that inode \u2014 so this needs no sidecar\n * and no spawn, which is what lets `dev` render the short `service install` line on its hot path. A\n * copy-path file is never a candidate: nothing short of running it proves it runs (doctor's job).\n */\nexport const stableNodeCandidate = (input: { home: string; execPath: string; fs?: PortlessNodeFs }): string | null => {\n const { home, execPath, fs: nodeFs = fs } = input\n const node = portlessNodePath(home)\n\n try {\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (current === undefined || exec === undefined || !current.isFile()) return null\n\n return sameInode(current, exec) ? node : null\n } catch {\n return null\n }\n}\n\ntype NodeTriple = Pick<EnsurePortlessNodeDeps, 'version' | 'arch' | 'platform'>\n\nconst describesProcess = (sidecar: PortlessNodeSidecar, deps: NodeTriple): boolean => {\n return sidecar.version === deps.version && sidecar.arch === deps.arch && sidecar.platform === deps.platform\n}\n\n/**\n * The fast path. Inode equality is the strongest signal for the FILE; the version clause is for the\n * SIDECAR: a crash between the two renames after a Node bump leaves the new inode described as the old\n * version with a pre-bump `versionChangedAt`, and without this clause that would be `'unchanged'` forever\n * (doctor printing the wrong version, the restart advisory keyed on a clock that is too old). On the copy\n * path the inode can never match, so the size is the second witness beside the version triple.\n */\nconst isConverged = (\n current: PortlessNodeStat,\n exec: PortlessNodeStat,\n sidecar: PortlessNodeSidecar,\n deps: NodeTriple,\n): boolean => {\n if (!describesProcess(sidecar, deps)) return false\n if (sameInode(current, exec)) return true\n\n return sidecar.method === 'copy' && sidecar.sourceSize === exec.size\n}\n\nconst discard = (tmp: string, nodeFs: PortlessNodeFs): void => {\n try {\n nodeFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failure that got us here is the one worth surfacing, not a leftover sibling.\n }\n}\n\n/**\n * A SIGKILL mid-copy leaves a 134 MB `node.tmp-<pid>` under a pid that may never recur; the sidecar\n * orphan is ~250 B, but one pass covers both. Only these two prefixes are ours to remove. A concurrent\n * boot's live tmp may go too \u2014 its `rename` then fails into `'failed'` and the next boot converges;\n * the published name always holds a complete file.\n */\nconst sweepOrphans = (dir: string, prefixes: string[], nodeFs: PortlessNodeFs): void => {\n let names: string[]\n\n try {\n names = nodeFs.readdirSync(dir)\n } catch {\n return\n }\n\n for (const name of names) {\n const orphan = prefixes.some((prefix) => {\n return name.startsWith(prefix)\n })\n\n if (orphan) discard(join(dir, name), nodeFs)\n }\n}\n\n/** Hardlink first; on ANY throw, the copy (see the header for why the error set is not filtered). */\nconst stageNode = (execPath: string, tmp: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n try {\n nodeFs.linkSync(execPath, tmp)\n\n return 'hardlink'\n } catch {\n nodeFs.copyFileSync(execPath, tmp, COPY_FLAGS)\n // The copy branch ONLY: on a hardlink this would chmod the manager's inode. 0755 is what the source\n // carries and what root needs to exec a file under a 0700 home \u2014 no secret lives in a node binary.\n // eslint-disable-next-line sonarjs/file-permissions -- an executable's mode, not a data file's\n nodeFs.chmodSync(tmp, COPY_MODE)\n\n return 'copy'\n }\n}\n\n/**\n * Stage under the pid-suffixed sibling, publish by ONE `rename` (T-1). The old inode stays mapped by a\n * running daemon; `rename` touches no byte of it. On any throw the sibling is removed and the old file\n * is exactly as it was.\n */\nconst publishNode = (execPath: string, node: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n const tmp = `${node}.tmp-${process.pid}`\n\n try {\n const method = stageNode(execPath, tmp, nodeFs)\n\n nodeFs.renameSync(tmp, node)\n\n return method\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\nconst publishSidecar = (sidecarPath: string, sidecar: PortlessNodeSidecar, nodeFs: PortlessNodeFs): void => {\n const tmp = `${sidecarPath}.tmp-${process.pid}`\n\n try {\n nodeFs.writeFileSync(tmp, `${JSON.stringify(sidecar, null, 2)}\\n`)\n nodeFs.renameSync(tmp, sidecarPath)\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\n/**\n * `versionChangedAt` is carried over only when the Node behind the file is the same one the previous\n * sidecar described: the triple, plus the size whenever the previous sidecar recorded one (a copy of a\n * same-version different build IS a different Node). A same-version relink after a re-mint must not\n * look like a Node bump to doctor's restart advisory. No parsable previous sidecar \u2192 `now`, which errs\n * towards one advisory too many, never too few.\n */\nconst nextSidecar = (\n previous: PortlessNodeSidecar | null,\n method: 'hardlink' | 'copy',\n exec: PortlessNodeStat,\n deps: EnsurePortlessNodeDeps,\n now: string,\n): PortlessNodeSidecar => {\n const sameNode =\n previous !== null &&\n describesProcess(previous, deps) &&\n (previous.sourceSize === undefined || previous.sourceSize === exec.size)\n\n return {\n method,\n version: deps.version,\n arch: deps.arch,\n platform: deps.platform,\n source: deps.execPath,\n ...(method === 'copy' ? { sourceSize: exec.size } : {}),\n refreshedAt: now,\n versionChangedAt: sameNode ? previous.versionChangedAt : now,\n }\n}\n\n/**\n * Converge `~/.infra-kit/node` on the Node running THIS install. Never throws; every outcome is a value.\n *\n * A symlink or directory at the path is `'failed'` and left exactly as found \u2014 this code owns a regular\n * file, and removing whatever someone else put there is the one destructive act a boot hook must never\n * take. A converged machine pays one `lstat`, one `stat` and a ~250-byte read: no write, no subprocess.\n *\n * @example\n * ensurePortlessNode({ isGlobal: () => true, home: '/Users/x', execPath: process.execPath, version: process.version, arch: process.arch, platform: process.platform })\n * // => { kind: 'node', outcome: 'created', node: '/Users/x/.infra-kit/node', source: process.execPath, version: process.version, method: 'hardlink' }\n */\nexport const ensurePortlessNode = (deps: EnsurePortlessNodeDeps): PortlessNodeResult => {\n const {\n home,\n execPath,\n version,\n fs: nodeFs = fs,\n now = () => {\n return new Date()\n },\n } = deps\n const node = portlessNodePath(home)\n const sidecarPath = portlessNodeSidecar(home)\n const result = (outcome: PortlessNodeOutcome, method: PortlessNodeResult['method']): PortlessNodeResult => {\n return { kind: 'node', outcome, node, source: execPath, version, method }\n }\n\n if (deps.platform !== 'darwin' && deps.platform !== 'linux') return result('skipped-platform', null)\n if (!deps.isGlobal()) return result('skipped-local', null)\n\n try {\n nodeFs.mkdirSync(dirname(node), { recursive: true })\n\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n\n if (current !== undefined && !current.isFile()) return result('failed', null)\n\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (exec === undefined) return result('failed', null)\n\n const previous = readPortlessNodeSidecar(home, nodeFs)\n\n if (current !== undefined && previous !== null && isConverged(current, exec, previous, deps)) {\n return result('unchanged', previous.method)\n }\n\n sweepOrphans(dirname(node), [`${basename(node)}.tmp-`, `${basename(sidecarPath)}.tmp-`], nodeFs)\n\n const method = publishNode(execPath, node, nodeFs)\n\n publishSidecar(sidecarPath, nextSidecar(previous, method, exec, deps, now().toISOString()), nodeFs)\n\n return result(current === undefined ? 'created' : 'refreshed', method)\n } catch {\n return result('failed', null)\n }\n}\n"],
5
+ "mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAS,iBAAAC,OAAqB,WCP9B,OAAS,YAAAC,OAAgB,qBACzB,OAAS,cAAAC,OAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,OAAU,YACjB,OAAOC,OAAW,aAClB,OAAOC,OAAS,WAChB,OAAS,WAAAC,OAAe,UACxB,OAAS,WA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AClB,QAASA,EAAQ,QACjB,KAAMA,EAAQ,KACd,SAAUA,EAAQ,QACpB,CACF,CACF,EAEM2B,EAAU,CAACC,EAAsBC,EAAiBC,IAA6D,CACnH,GAAI,CACFF,EAAIE,EAAI,EAAGD,CAAO,CACpB,MAAQ,CAER,CACF,EAQaE,GAAmB,CAACH,EAAsBb,IAAoC,CACzF,IAAMiB,EAASjB,GAAQK,GAAuB,EAE9CO,EAAQC,EAAK,gBAAiB,IACrBd,GAAmBkB,EAAO,IAAI,CACtC,EACDL,EAAQC,EAAK,gBAAiB,IACrBK,EAAmBD,EAAO,IAAI,CACtC,CACH",
6
+ "names": ["fs", "homedir", "dirname", "join", "process", "fileURLToPath", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name", "fs", "basename", "dirname", "join", "process", "portlessNodePath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessNodeSidecar", "isSidecar", "value", "record", "strings", "key", "COPY_FLAGS", "fs", "COPY_MODE", "readPortlessNodeSidecar", "nodeFs", "parsed", "sameInode", "a", "b", "stableNodeCandidate", "input", "execPath", "node", "current", "exec", "describesProcess", "sidecar", "deps", "isConverged", "discard", "tmp", "sweepOrphans", "dir", "prefixes", "names", "name", "prefix", "stageNode", "publishNode", "process", "method", "error", "publishSidecar", "sidecarPath", "nextSidecar", "previous", "now", "sameNode", "ensurePortlessNode", "version", "result", "outcome", "dirname", "basename", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "execPath", "process", "stableNode", "stableNodeCandidate", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessStableDeps", "homedir", "global", "isGlobalInstall", "fileURLToPath", "safeRealpath", "resolvePortlessBin", "logStep", "log", "message", "run", "bootPortlessLink", "stable", "ensurePortlessNode"]
7
+ }
@@ -1,2 +1,2 @@
1
1
  import a from"node:path";var i="infra-kit",l=`${i}@latest`,M=(n,t)=>t===void 0?n:n.map(e=>e===l?`${i}@${t}`:e),g=(n,t,e)=>{let r=a.relative(e(a.resolve(n)),a.resolve(t));return r!==""&&!r.startsWith("..")&&!a.isAbsolute(r)},s=(n,t)=>a.resolve(n).split(a.sep).includes(t),h=(n,t)=>{let e=a.resolve(n).split(a.sep),r=e.indexOf("Cellar");return r!==-1&&e[r+1]===t},b=(n,t)=>{let e=a.resolve(n).split(a.sep),r=e.lastIndexOf("node_modules");return r<2||e[r-1]!=="lib"||e[r+1]!==t?null:e.slice(0,r-1).join(a.sep)||a.sep},w=n=>b(n,i),C=n=>["npm","install","-g","--prefix",n,l],N=n=>n.map(t=>t.includes(" ")?`'${t}'`:t).join(" "),u=(n,t,e,r)=>{let o=n[t];return o!=null&&o!==""&&g(o,e,r)},R=[{manager:"volta",test:({selfRealPath:n,env:t,realpath:e})=>u(t,"VOLTA_HOME",n,e)||s(n,".volta")||s(n,"volta"),updateCommand:["volta","install",i],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:n})=>h(n,i),updateCommand:["brew","upgrade",i],canSelfSpawn:!1}],O=[{manager:"pnpm",test:({selfRealPath:n,env:t,realpath:e})=>u(t,"PNPM_HOME",n,e)||s(n,"pnpm")&&s(n,"global"),updateCommand:["pnpm","add","-g",l],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:n,env:t,realpath:e})=>u(t,"BUN_INSTALL",n,e)||s(n,".bun"),updateCommand:["bun","add","-g",l],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:n})=>s(n,".yarn")||s(n,"yarn")&&s(n,"global"),updateCommand:["yarn","global","add",l],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:n,env:t,realpath:e})=>u(t,"npm_config_prefix",n,e),updateCommand:["npm","install","-g",l],canSelfSpawn:!0}],f=["npm","install","-g",l],y=n=>M(f,n),v=n=>{let{selfRealPath:t,env:e,realpath:r,lazyNpmRoot:o,version:p}=n,c=A({selfRealPath:t,env:e,realpath:r,lazyNpmRoot:o});return{...c,updateCommand:M(c.updateCommand,p)}},A=n=>{let{selfRealPath:t,env:e,realpath:r,lazyNpmRoot:o}=n,p=m=>({manager:m.manager,updateCommand:m.updateCommand,canSelfSpawn:m.canSelfSpawn}),c=({test:m})=>m({selfRealPath:t,env:e,realpath:r}),I=R.find(c);if(I)return p(I);let S=w(t);if(S!==null)return{manager:"npm",updateCommand:C(S),canSelfSpawn:!0};let x=O.find(c);if(x)return p(x);let d=o?.();return d!=null&&d!==""&&g(d,t,r)?{manager:"npm",updateCommand:f,canSelfSpawn:!0}:{manager:"unknown",updateCommand:f,canSelfSpawn:!1}},E=(n,t,e)=>s(n,"node_modules")&&g(t,n,e),T=32,F=n=>{let t=a.resolve(n).split(a.sep),e=t.indexOf("node_modules");return e===-1?a.dirname(n):t.slice(0,e).join(a.sep)||a.sep},k=(n,t)=>{let e=[],r=n;for(;r!==t&&e.length<T;){e.push(r);let o=a.dirname(r);if(o===r)break;r=o}return e},G=(n,t,e)=>k(n,t).some(r=>e(a.join(r,".git"))),P=n=>{try{let{selfRealPath:t,env:e,realpath:r,home:o,exists:p}=n;return v({selfRealPath:t,env:e,realpath:r}).manager==="unknown"?!1:!G(F(t),r(a.resolve(o)),p)}catch{return!1}},L=n=>{let{selfRealPath:t,cwd:e,realpath:r}=n;return!P(n)&&E(t,e,r)};import{realpathSync as D}from"node:fs";import W from"node:path";var U=n=>{try{return D(n)}catch{return W.resolve(n)}};import{execFileSync as j}from"node:child_process";import J from"node:process";var H=3e3,z=()=>{try{let t=j("npm",["root","-g"],{encoding:"utf-8",timeout:H,stdio:["ignore","pipe","ignore"],shell:J.platform==="win32"}).trim();return t===""?void 0:t}catch{return}};var _=n=>Object.fromEntries(Object.entries(n).filter(([t])=>!t.startsWith("npm_")&&t!=="PNPM_SCRIPT_SRC_DIR")),K=/^npm_config_(?:prefix|registry)$/i,$=n=>{let t=_(n);for(let[e,r]of Object.entries(n))K.test(e)&&(t[e]=r);return t};export{i as a,g as b,s as c,h as d,b as e,N as f,y as g,v as h,E as i,P as j,L as k,z as l,U as m,_ as n,$ as o};
2
- //# sourceMappingURL=chunk-HHWP3YXW.js.map
2
+ //# sourceMappingURL=chunk-AWFGP6GY.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/install-manager/install-manager.ts", "../src/lib/install-manager/safe-realpath.ts", "../src/lib/install-manager/npm-root.ts", "../src/lib/pm-env/pm-env.ts"],
4
- "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so the background updater knows whether it may act at\n * all, and the advisory it prints can name the one command that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n /**\n * The exact version to install, when the caller has already resolved it. Omitted, the command targets\n * the `latest` dist-tag \u2014 fine to PRINT, unsafe to RUN: see {@link pinSpec}.\n */\n version?: string\n}\n\n/**\n * Swap the `@latest` token for `@<version>`.\n *\n * `pnpm add -g infra-kit@latest` resolves the tag from pnpm's on-disk metadata cache and does not\n * revalidate it when a cached version already satisfies the tag (pnpm 12.3.4, measured: two runs 90+\n * minutes after a publish both reinstalled the stale `latest` while `pnpm view` already reported the new\n * one). The updater had fetched the real latest itself moments earlier, ran the tag command, got exit 0\n * \u2014 nothing was reinstalled \u2014 and recorded `installed`, so the stale binary looked up to date until the\n * next cycle repeated the same no-op. A concrete version the cache has never seen forces the fetch.\n */\nconst pinSpec = (command: string[], version: string | undefined): string[] => {\n if (version === undefined) return command\n\n return command.map((token) => {\n return token === LATEST ? `${PACKAGE_NAME}@${version}` : token\n })\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nexport const isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nexport const hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nexport const isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/**\n * The npm global prefix that owns `binRealPath`, derived from the path ITSELF, or null when the\n * layout is not an npm global one.\n *\n * Matches `<prefix>/lib/node_modules/<packageName>` \u2014 npm's global layout and no other manager's\n * \u2014 requiring BOTH the `lib` parent and our package as the immediate child. Windows global npm has\n * no `lib` segment (`%APPDATA%\\npm\\node_modules`), so this returns null there and detection falls\n * through to `npm root -g`, which is correct on Windows, where there is normally one npm.\n */\n// This is the one signal that cannot point at the wrong tree. Everything else in this module\n// answers \"is this file somewhere inside tool X's directory?\", and containment is not ownership:\n// - `npm root -g` answers for whichever `npm` is first on PATH, which is routinely a DIFFERENT\n// node than the one that installed us (a pnpm/nvm/fnm-managed node, or a node that has since\n// been removed). It then reports a root that does not contain us, every matcher misses, and\n// detection degrades to `unknown` \u2014 a notice printed forever, on the single most common install\n// method. That is the bug this exists to close.\n// - `PNPM_HOME` containment is satisfied by `<PNPM_HOME>/nodejs/<v>/lib/node_modules/<pkg>` (a\n// plain `npm i -g` under a pnpm-managed node), yet `pnpm add -g` installs to\n// `<PNPM_HOME>/global/<v>/...` \u2014 a different directory. That one is worse than a missed update:\n// the install \"succeeds\" while the binary on PATH stays old, silently, with no notice to show\n// for it.\n//\n// Requiring both segments is what makes the match proof rather than a hint. The `lib` requirement\n// is also what keeps a project-local `<repo>/node_modules/<pkg>` out (it has no `lib`), and nesting\n// cannot spoof it: `.../node_modules/foo/node_modules/<pkg>` fails the `lib` test.\nexport const npmPrefixOfPackage = (binRealPath: string, packageName: string): string | null => {\n const segments = path.resolve(binRealPath).split(path.sep)\n const nodeModules = segments.lastIndexOf('node_modules')\n\n if (nodeModules < 2) return null\n if (segments[nodeModules - 1] !== 'lib') return null\n if (segments[nodeModules + 1] !== packageName) return null\n\n // Drop `lib/node_modules/...`; the empty result of a root-level prefix (`/lib/node_modules/...`) is `/`.\n return segments.slice(0, nodeModules - 1).join(path.sep) || path.sep\n}\n\n// The self-scoped reading, kept as the name every call site below already uses. `dependency-registry`\n// asks the same question about OTHER packages (`portless`), which is why the body moved up one level\n// rather than gaining a defaulted parameter \u2014 a default is how the wrong package silently gets probed.\nconst npmPrefixFromSelfPath = (selfRealPath: string): string | null => {\n return npmPrefixOfPackage(selfRealPath, PACKAGE_NAME)\n}\n\n/**\n * `--prefix` is passed EXPLICITLY rather than trusting the ambient one: the whole point of deriving it is\n * that the `npm` we are about to run may default to a different prefix than the one we are installed in.\n * A command-line flag outranks both `npm_config_prefix` and any `.npmrc`, so this targets the tree we\n * actually run from. With `-g`, npm writes `<prefix>/lib/node_modules` and links bins into `<prefix>/bin`.\n */\nconst npmPrefixInstallCommand = (prefix: string): string[] => {\n return ['npm', 'install', '-g', '--prefix', prefix, LATEST]\n}\n\n/**\n * Render argv as a line the user can paste into a shell.\n *\n * A plain `join(' ')` was fine while every token came from a static table; `--prefix <path>` puts a\n * filesystem path in argv, and `/Users/Ada Lovelace/.nvm/...` pasted unquoted is two arguments and a\n * failed install. Single quotes are sound here without escaping because the callers' validation rejects a\n * token containing a quote \u2014 see `SAFE_COMMAND_TOKEN` in src/lib/update-check/auto-update.ts.\n *\n * @example\n * formatUpdateCommand(['npm', 'install', '-g', '--prefix', '/opt/x y', 'infra-kit@latest'])\n * // => \"npm install -g --prefix '/opt/x y' infra-kit@latest\"\n */\nexport const formatUpdateCommand = (command: string[]): string => {\n return command\n .map((token) => {\n return token.includes(' ') ? `'${token}'` : token\n })\n .join(' ')\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Consulted FIRST, before {@link npmPrefixFromSelfPath}. Both of these legitimately wrap an npm-shaped\n * `lib/node_modules` tree \u2014 volta at `~/.volta/tools/image/node/<v>/lib/node_modules`, brew at\n * `Cellar/<pkg>/<v>/libexec/lib/node_modules` \u2014 so deriving an npm prefix from the path would hijack\n * installs that a wrapper owns and must keep owning.\n */\nconst WRAPPER_MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see `isBrewKegOf`. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n]\n\n/**\n * Consulted LAST, after {@link npmPrefixFromSelfPath} has had its say. Each of these proves only that we\n * live somewhere inside a tool's directory tree, which is weaker than knowing the layout npm itself\n * created \u2014 see the `PNPM_HOME`/`nodejs` case in that helper's doc for a containment hit whose install\n * command targets the wrong directory.\n */\nconst TREE_MATCHERS: Matcher[] = [\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * The command to print when nobody has identified this CLI's package manager \u2014 the same guess\n * `detectInstallManager` records for an unrecognised location, pinned to `version`. For a caller that\n * must name a command but has no worker verdict to read (no update cache on an opt-out machine).\n *\n * @example\n * fallbackUpdateCommand('0.8.0') // => ['npm', 'install', '-g', 'infra-kit@0.8.0']\n */\nexport const fallbackUpdateCommand = (version: string): string[] => {\n return pinSpec(NPM_UPDATE_COMMAND, version)\n}\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * Order, and why it is this one: wrappers that own an npm-shaped tree (volta, brew) first, then the npm\n * prefix DERIVED from our own path, then the env/path containment matchers, then the `npm root -g` probe.\n * The derived prefix sits above containment because it is the only signal that cannot name a directory we\n * do not live in \u2014 see {@link npmPrefixFromSelfPath}.\n *\n * `lazyNpmRoot` is the last resort and is invoked at most once, only after every matcher has missed \u2014 a\n * pnpm or volta install never pays for the subprocess, and neither does any npm global install in the\n * standard layout, which the derived prefix now settles for free. When nothing matches we report `unknown`\n * with an npm command that is a *suggestion only* (`canSelfSpawn: false`): running a guessed global\n * install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {}, version: '0.5.5' })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@0.5.5'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot, version } = input\n const detected = detectUnpinned({ selfRealPath, env, realpath, lazyNpmRoot })\n\n return { ...detected, updateCommand: pinSpec(detected.updateCommand, version) }\n}\n\nconst detectUnpinned = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const toInfo = (hit: Matcher): InstallManagerInfo => {\n return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n }\n const matches = ({ test }: Matcher): boolean => {\n return test({ selfRealPath, env, realpath })\n }\n\n const wrapper = WRAPPER_MATCHERS.find(matches)\n\n if (wrapper) return toInfo(wrapper)\n\n const derivedPrefix = npmPrefixFromSelfPath(selfRealPath)\n\n if (derivedPrefix !== null) {\n return { manager: 'npm', updateCommand: npmPrefixInstallCommand(derivedPrefix), canSelfSpawn: true }\n }\n\n const tree = TREE_MATCHERS.find(matches)\n\n if (tree) return toInfo(tree)\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n\n/** Does this path exist at all \u2014 directory, file, or symlink? Injected so the walk never touches the real disk in tests. */\nexport type ExistsFn = (p: string) => boolean\n\nexport interface IsGlobalInstallInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises `home` and every root {@link detectInstallManager} compares against. */\n realpath: RealpathFn\n /** The user's home directory (`os.homedir()`), raw \u2014 canonicalised here before the walk compares it. */\n home: string\n exists: ExistsFn\n}\n\n/** Upper bound on the `.git` walk: deeper than any real install layout, so it only ever guards against a pathological path. */\nconst GIT_WALK_MAX_HOPS = 32\n\n/**\n * Where the `.git` walk starts: the parent of the OUTERMOST `node_modules` segment (`indexOf`, not\n * `lastIndexOf` \u2014 pnpm's `.pnpm/<pkg>@<v>/node_modules/<pkg>` nests two, and the checkout that owns the\n * tree sits above the first). A self path with no `node_modules` at all (a plain brew keg's `bin/`) starts\n * at its own directory, so the walk still inspects every ancestor.\n */\nconst gitWalkStart = (selfRealPath: string): string => {\n const segments = path.resolve(selfRealPath).split(path.sep)\n const outermost = segments.indexOf('node_modules')\n\n if (outermost === -1) return path.dirname(selfRealPath)\n\n return segments.slice(0, outermost).join(path.sep) || path.sep\n}\n\n/** `start` and its ancestors up to but EXCLUDING `homeReal`, bounded \u2014 the directories the `.git` walk may inspect. */\nconst ancestorsBelowHome = (start: string, homeReal: string): string[] => {\n const dirs: string[] = []\n let dir = start\n\n while (dir !== homeReal && dirs.length < GIT_WALK_MAX_HOPS) {\n dirs.push(dir)\n\n const parent = path.dirname(dir)\n\n if (parent === dir) break\n\n dir = parent\n }\n\n return dirs\n}\n\nconst hasGitAncestor = (start: string, homeReal: string, exists: ExistsFn): boolean => {\n return ancestorsBelowHome(start, homeReal).some((dir) => {\n return exists(path.join(dir, '.git'))\n })\n}\n\n/**\n * Is this CLI the machine's *global* install \u2014 the one a root-owned daemon or a system-wide link may be\n * aimed at \u2014 as opposed to a checkout or a project-local dependency? Probe-free: fs + env only, never a\n * subprocess, because it runs on every boot.\n *\n * True iff {@link detectInstallManager} names a manager AND no `.git` entry (directory or file \u2014 a\n * worktree's is a file) exists above the outermost `node_modules`, walking up to but EXCLUDING\n * `realpath(home)`. Never throws: any seam failure reports false, the safe direction for every caller.\n *\n * @example\n * isGlobalInstall({\n * selfRealPath: '/Users/x/Library/pnpm/global/v11/8a83-1/node_modules/.pnpm/infra-kit@0.5.6/node_modules/infra-kit/dist/cli.js',\n * env: { PNPM_HOME: '/Users/x/Library/pnpm' },\n * realpath: (p) => p,\n * home: '/Users/x',\n * exists: (p) => p === '/Users/x/.git',\n * }) // => true \u2014 the only `.git` is $HOME's own, which the walk never inspects\n */\n// Why these two predicates and not the obvious candidates:\n// - Not `canSelfSpawn`: that flag encodes \"may I run an unattended `npm i -g`\", and homebrew is\n// `canSelfSpawn: false` while being unmistakably global \u2014 gating on it would leave a brew install\n// unconverged forever. A global install whose manager cannot be identified in a stripped env (no\n// `PNPM_HOME`, no derivable prefix) reports false: fail-safe, since a skipped write is never wrong and\n// the next shell-run command converges it.\n// - Not `isLocalNodeModulesInstall`: its cwd clause calls every global layout under `$HOME` \"local\" the\n// moment cwd is `$HOME` \u2014 which is exactly the cwd the background updater spawns with, and a plain\n// `cd ~ && infra-kit version` reproduces it. This predicate reads the tree, not the cwd.\n// - Why the `.git` walk at all: the cheap matchers are segment heuristics that also fire on\n// project-local shapes \u2014 a repo with a `volta` path segment, Yarn Berry's `.yarn/unplugged/\u2026`, a\n// checkout cloned under `$PNPM_HOME`, a workspace package literally named `lib` \u2014 and every one of\n// those is a checkout; every checkout has a `.git`, no global root does.\n// - Why `$HOME` is excluded: dotfiles users `git init ~`, and a `~/.git` would refuse the pnpm-global\n// install permanently. Every checkout under `$HOME` (`~/repo/.git`) is still strictly below it.\n// - Why `.git` ONLY, not `pnpm-workspace.yaml`: pnpm 12 writes one INSIDE the global install dir, so\n// that marker would refuse the very install this is for.\nexport const isGlobalInstall = (input: IsGlobalInstallInput): boolean => {\n try {\n const { selfRealPath, env, realpath, home, exists } = input\n\n if (detectInstallManager({ selfRealPath, env, realpath }).manager === 'unknown') return false\n\n return !hasGitAncestor(gitWalkStart(selfRealPath), realpath(path.resolve(home)), exists)\n } catch {\n return false\n }\n}\n\n/**\n * The advisory gate for `warnIfLocalInstall`, pulled out so it is testable without spawning the CLI.\n * Warn only when the install is provably NOT global AND looks project-local: the second clause alone\n * fires on a global pnpm root whenever cwd is `$HOME` (see {@link isGlobalInstall}).\n */\nexport const shouldWarnLocalInstall = (input: IsGlobalInstallInput & { cwd: string }): boolean => {\n const { selfRealPath, cwd, realpath } = input\n\n return !isGlobalInstall(input) && isLocalNodeModulesInstall(selfRealPath, cwd, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Read by the background update worker, and by the `doctor` advisory that names the command a human\n * would run by hand \u2014 one probe so the two can never disagree about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install:\n * the whole `npm_*` block plus `PNPM_SCRIPT_SRC_DIR`. The result makes the child look exactly like\n * a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\n// Any child we launch through `node <bin>` (the portless driver, the update worker, the mcp launcher)\n// inherits our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm\n// dlx` and refuse to work. portless is the motivating case; its guard (cli.js `main()`) is:\n//\n// isNpx = npm_command === 'exec' && !npm_lifecycle_event\n// isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n// if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) -> abort\n//\n// `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n// transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is\n// live. `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event, so `isNpx`\n// holds, every portless call exits 1, `isAvailable()` is false, and `ensureProxy` aborts the whole\n// dev boot with \"portless is not installed\", on a machine where it plainly is.\n//\n// `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n// `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n// `npm_*` removes that suppressor and creates an abort for the script-style invocation that\n// previously worked. Both markers go, or neither is safe.\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config\n * kept \u2014 specifically `npm_config_prefix` and `npm_config_registry`.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\n// `withoutPackageManagerEnv` is deliberately a blunt `npm_*` prefix filter, and it is the\n// right tool for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it\n// also drops the two variables that tell the package manager where, and from where, to install:\n//\n// - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and\n// we detect a global install rooted at prefix P, then run the install with P erased \u2014 so it\n// lands in the DEFAULT prefix instead. That is either a permanent EACCES, or a second global\n// copy that is not the one on PATH. Nothing notices: the install exits 0, we report\n// `installed`, the version on PATH never moves, and the whole cycle repeats every window\n// forever. `export npm_config_prefix=~/.npm-global` is npm's own documented EACCES workaround,\n// so this is a mainstream layout, not an exotic one.\n// - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it\n// here means we decide against a corporate mirror and then install from somewhere else.\n//\n// Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`,\n// `npm_lifecycle_event` and `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm config, and all of which\n// remain stripped.\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
4
+ "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so the background updater knows whether it may act at\n * all, and the advisory it prints can name the one command that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n /**\n * The exact version to install, when the caller has already resolved it. Omitted, the command targets\n * the `latest` dist-tag \u2014 fine to PRINT, unsafe to RUN: see {@link pinSpec}.\n */\n version?: string\n}\n\n/**\n * Swap the `@latest` token for `@<version>`.\n *\n * `pnpm add -g infra-kit@latest` resolves the tag from pnpm's on-disk metadata cache and does not\n * revalidate it when a cached version already satisfies the tag (pnpm 12.3.4, measured: two runs 90+\n * minutes after a publish both reinstalled the stale `latest` while `pnpm view` already reported the new\n * one). The updater had fetched the real latest itself moments earlier, ran the tag command, got exit 0\n * \u2014 nothing was reinstalled \u2014 and recorded `installed`, so the stale binary looked up to date until the\n * next cycle repeated the same no-op. A concrete version the cache has never seen forces the fetch.\n */\nconst pinSpec = (command: string[], version: string | undefined): string[] => {\n if (version === undefined) return command\n\n return command.map((token) => {\n return token === LATEST ? `${PACKAGE_NAME}@${version}` : token\n })\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nexport const isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nexport const hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nexport const isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/**\n * The npm global prefix that owns `binRealPath`, derived from the path ITSELF, or null when the\n * layout is not an npm global one.\n *\n * Matches `<prefix>/lib/node_modules/<packageName>` \u2014 npm's global layout and no other manager's\n * \u2014 requiring BOTH the `lib` parent and our package as the immediate child. Windows global npm has\n * no `lib` segment (`%APPDATA%\\npm\\node_modules`), so this returns null there and detection falls\n * through to `npm root -g`, which is correct on Windows, where there is normally one npm.\n */\n// This is the one signal that cannot point at the wrong tree. Everything else in this module\n// answers \"is this file somewhere inside tool X's directory?\", and containment is not ownership:\n// - `npm root -g` answers for whichever `npm` is first on PATH, which is routinely a DIFFERENT\n// node than the one that installed us (a pnpm/nvm/fnm-managed node, or a node that has since\n// been removed). It then reports a root that does not contain us, every matcher misses, and\n// detection degrades to `unknown` \u2014 a notice printed forever, on the single most common install\n// method. That is the bug this exists to close.\n// - `PNPM_HOME` containment is satisfied by `<PNPM_HOME>/nodejs/<v>/lib/node_modules/<pkg>` (a\n// plain `npm i -g` under a pnpm-managed node), yet `pnpm add -g` installs to\n// `<PNPM_HOME>/global/<v>/...` \u2014 a different directory. That one is worse than a missed update:\n// the install \"succeeds\" while the binary on PATH stays old, silently, with no notice to show\n// for it.\n//\n// Requiring both segments is what makes the match proof rather than a hint. The `lib` requirement\n// is also what keeps a project-local `<repo>/node_modules/<pkg>` out (it has no `lib`), and nesting\n// cannot spoof it: `.../node_modules/foo/node_modules/<pkg>` fails the `lib` test.\nexport const npmPrefixOfPackage = (binRealPath: string, packageName: string): string | null => {\n const segments = path.resolve(binRealPath).split(path.sep)\n const nodeModules = segments.lastIndexOf('node_modules')\n\n if (nodeModules < 2) return null\n if (segments[nodeModules - 1] !== 'lib') return null\n if (segments[nodeModules + 1] !== packageName) return null\n\n // Drop `lib/node_modules/...`; the empty result of a root-level prefix (`/lib/node_modules/...`) is `/`.\n return segments.slice(0, nodeModules - 1).join(path.sep) || path.sep\n}\n\n// The self-scoped reading, kept as the name every call site below already uses. `dependency-registry`\n// asks the same question about OTHER packages (`portless`), which is why the body moved up one level\n// rather than gaining a defaulted parameter \u2014 a default is how the wrong package silently gets probed.\nconst npmPrefixFromSelfPath = (selfRealPath: string): string | null => {\n return npmPrefixOfPackage(selfRealPath, PACKAGE_NAME)\n}\n\n/**\n * `--prefix` is passed EXPLICITLY rather than trusting the ambient one: the whole point of deriving it is\n * that the `npm` we are about to run may default to a different prefix than the one we are installed in.\n * A command-line flag outranks both `npm_config_prefix` and any `.npmrc`, so this targets the tree we\n * actually run from. With `-g`, npm writes `<prefix>/lib/node_modules` and links bins into `<prefix>/bin`.\n */\nconst npmPrefixInstallCommand = (prefix: string): string[] => {\n return ['npm', 'install', '-g', '--prefix', prefix, LATEST]\n}\n\n/**\n * Render argv as a line the user can paste into a shell.\n *\n * A plain `join(' ')` was fine while every token came from a static table; `--prefix <path>` puts a\n * filesystem path in argv, and `/Users/Ada Lovelace/.nvm/...` pasted unquoted is two arguments and a\n * failed install. Single quotes are sound here without escaping because the callers' validation rejects a\n * token containing a quote \u2014 see `SAFE_COMMAND_TOKEN` in src/lib/update-check/auto-update.ts.\n *\n * @example\n * formatUpdateCommand(['npm', 'install', '-g', '--prefix', '/opt/x y', 'infra-kit@latest'])\n * // => \"npm install -g --prefix '/opt/x y' infra-kit@latest\"\n */\nexport const formatUpdateCommand = (command: string[]): string => {\n return command\n .map((token) => {\n return token.includes(' ') ? `'${token}'` : token\n })\n .join(' ')\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Consulted FIRST, before {@link npmPrefixFromSelfPath}. Both of these legitimately wrap an npm-shaped\n * `lib/node_modules` tree \u2014 volta at `~/.volta/tools/image/node/<v>/lib/node_modules`, brew at\n * `Cellar/<pkg>/<v>/libexec/lib/node_modules` \u2014 so deriving an npm prefix from the path would hijack\n * installs that a wrapper owns and must keep owning.\n */\nconst WRAPPER_MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see `isBrewKegOf`. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n]\n\n/**\n * Consulted LAST, after {@link npmPrefixFromSelfPath} has had its say. Each of these proves only that we\n * live somewhere inside a tool's directory tree, which is weaker than knowing the layout npm itself\n * created \u2014 see the `PNPM_HOME`/`nodejs` case in that helper's doc for a containment hit whose install\n * command targets the wrong directory.\n */\nconst TREE_MATCHERS: Matcher[] = [\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * The command to print when nobody has identified this CLI's package manager \u2014 the same guess\n * `detectInstallManager` records for an unrecognised location, pinned to `version`. For a caller that\n * must name a command but has no worker verdict to read (no update cache on an opt-out machine).\n *\n * @example\n * fallbackUpdateCommand('0.8.0') // => ['npm', 'install', '-g', 'infra-kit@0.8.0']\n */\nexport const fallbackUpdateCommand = (version: string): string[] => {\n return pinSpec(NPM_UPDATE_COMMAND, version)\n}\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * Order, and why it is this one: wrappers that own an npm-shaped tree (volta, brew) first, then the npm\n * prefix DERIVED from our own path, then the env/path containment matchers, then the `npm root -g` probe.\n * The derived prefix sits above containment because it is the only signal that cannot name a directory we\n * do not live in \u2014 see {@link npmPrefixFromSelfPath}.\n *\n * `lazyNpmRoot` is the last resort and is invoked at most once, only after every matcher has missed \u2014 a\n * pnpm or volta install never pays for the subprocess, and neither does any npm global install in the\n * standard layout, which the derived prefix now settles for free. When nothing matches we report `unknown`\n * with an npm command that is a *suggestion only* (`canSelfSpawn: false`): running a guessed global\n * install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {}, version: '0.5.5' })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@0.5.5'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot, version } = input\n const detected = detectUnpinned({ selfRealPath, env, realpath, lazyNpmRoot })\n\n return { ...detected, updateCommand: pinSpec(detected.updateCommand, version) }\n}\n\nconst detectUnpinned = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const toInfo = (hit: Matcher): InstallManagerInfo => {\n return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n }\n const matches = ({ test }: Matcher): boolean => {\n return test({ selfRealPath, env, realpath })\n }\n\n const wrapper = WRAPPER_MATCHERS.find(matches)\n\n if (wrapper) return toInfo(wrapper)\n\n const derivedPrefix = npmPrefixFromSelfPath(selfRealPath)\n\n if (derivedPrefix !== null) {\n return { manager: 'npm', updateCommand: npmPrefixInstallCommand(derivedPrefix), canSelfSpawn: true }\n }\n\n const tree = TREE_MATCHERS.find(matches)\n\n if (tree) return toInfo(tree)\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n\n/** Does this path exist at all \u2014 directory, file, or symlink? Injected so the walk never touches the real disk in tests. */\nexport type ExistsFn = (p: string) => boolean\n\nexport interface IsGlobalInstallInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises `home` and every root {@link detectInstallManager} compares against. */\n realpath: RealpathFn\n /** The user's home directory (`os.homedir()`), raw \u2014 canonicalised here before the walk compares it. */\n home: string\n exists: ExistsFn\n}\n\n/** Upper bound on the `.git` walk: deeper than any real install layout, so it only ever guards against a pathological path. */\nconst GIT_WALK_MAX_HOPS = 32\n\n/**\n * Where the `.git` walk starts: the parent of the OUTERMOST `node_modules` segment (`indexOf`, not\n * `lastIndexOf` \u2014 pnpm's `.pnpm/<pkg>@<v>/node_modules/<pkg>` nests two, and the checkout that owns the\n * tree sits above the first). A self path with no `node_modules` at all (a plain brew keg's `bin/`) starts\n * at its own directory, so the walk still inspects every ancestor.\n */\nconst gitWalkStart = (selfRealPath: string): string => {\n const segments = path.resolve(selfRealPath).split(path.sep)\n const outermost = segments.indexOf('node_modules')\n\n if (outermost === -1) return path.dirname(selfRealPath)\n\n return segments.slice(0, outermost).join(path.sep) || path.sep\n}\n\n/** `start` and its ancestors up to but EXCLUDING `homeReal`, bounded \u2014 the directories the `.git` walk may inspect. */\nconst ancestorsBelowHome = (start: string, homeReal: string): string[] => {\n const dirs: string[] = []\n let dir = start\n\n while (dir !== homeReal && dirs.length < GIT_WALK_MAX_HOPS) {\n dirs.push(dir)\n\n const parent = path.dirname(dir)\n\n if (parent === dir) break\n\n dir = parent\n }\n\n return dirs\n}\n\nconst hasGitAncestor = (start: string, homeReal: string, exists: ExistsFn): boolean => {\n return ancestorsBelowHome(start, homeReal).some((dir) => {\n return exists(path.join(dir, '.git'))\n })\n}\n\n/**\n * Is this CLI the machine's *global* install \u2014 the one a root-owned daemon or a system-wide link may be\n * aimed at \u2014 as opposed to a checkout or a project-local dependency? Probe-free: fs + env only, never a\n * subprocess, because it runs on every boot.\n *\n * True iff {@link detectInstallManager} names a manager AND no `.git` entry (directory or file \u2014 a\n * worktree's is a file) exists above the outermost `node_modules`, walking up to but EXCLUDING\n * `realpath(home)`. Never throws: any seam failure reports false, the safe direction for every caller.\n *\n * @example\n * isGlobalInstall({\n * selfRealPath: '/Users/x/Library/pnpm/global/v11/8a83-1/node_modules/.pnpm/infra-kit@0.5.6/node_modules/infra-kit/dist/cli.js',\n * env: { PNPM_HOME: '/Users/x/Library/pnpm' },\n * realpath: (p) => p,\n * home: '/Users/x',\n * exists: (p) => p === '/Users/x/.git',\n * }) // => true \u2014 the only `.git` is $HOME's own, which the walk never inspects\n */\n// Why these two predicates and not the obvious candidates:\n// - Not `canSelfSpawn`: that flag encodes \"may I run an unattended `npm i -g`\", and homebrew is\n// `canSelfSpawn: false` while being unmistakably global \u2014 gating on it would leave a brew install\n// unconverged forever. A global install whose manager cannot be identified in a stripped env (no\n// `PNPM_HOME`, no derivable prefix) reports false: fail-safe, since a skipped write is never wrong and\n// the next shell-run command converges it.\n// - Not `isLocalNodeModulesInstall`: its cwd clause calls every global layout under `$HOME` \"local\" the\n// moment cwd is `$HOME` \u2014 which is exactly the cwd the background updater spawns with, and a plain\n// `cd ~ && infra-kit version` reproduces it. This predicate reads the tree, not the cwd.\n// - Why the `.git` walk at all: the cheap matchers are segment heuristics that also fire on\n// project-local shapes \u2014 a repo with a `volta` path segment, Yarn Berry's `.yarn/unplugged/\u2026`, a\n// checkout cloned under `$PNPM_HOME`, a workspace package literally named `lib` \u2014 and every one of\n// those is a checkout; every checkout has a `.git`, no global root does.\n// - Why `$HOME` is excluded: dotfiles users `git init ~`, and a `~/.git` would refuse the pnpm-global\n// install permanently. Every checkout under `$HOME` (`~/repo/.git`) is still strictly below it.\n// - Why `.git` ONLY, not `pnpm-workspace.yaml`: pnpm 12 writes one INSIDE the global install dir, so\n// that marker would refuse the very install this is for.\nexport const isGlobalInstall = (input: IsGlobalInstallInput): boolean => {\n try {\n const { selfRealPath, env, realpath, home, exists } = input\n\n if (detectInstallManager({ selfRealPath, env, realpath }).manager === 'unknown') return false\n\n return !hasGitAncestor(gitWalkStart(selfRealPath), realpath(path.resolve(home)), exists)\n } catch {\n return false\n }\n}\n\n/**\n * The advisory gate for `warnIfLocalInstall`, pulled out so it is testable without spawning the CLI.\n * Warn only when the install is provably NOT global AND looks project-local: the second clause alone\n * fires on a global pnpm root whenever cwd is `$HOME` (see {@link isGlobalInstall}).\n */\nexport const shouldWarnLocalInstall = (input: IsGlobalInstallInput & { cwd: string }): boolean => {\n const { selfRealPath, cwd, realpath } = input\n\n return !isGlobalInstall(input) && isLocalNodeModulesInstall(selfRealPath, cwd, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Read by the background update worker, and by the `doctor` advisory that names the command a human\n * would run by hand \u2014 one probe so the two can never disagree about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install:\n * the whole `npm_*` block plus `PNPM_SCRIPT_SRC_DIR`. The result makes the child look exactly like\n * a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\n// Any child we launch through `node <bin>` (the portless driver, the update worker, the dependency installer)\n// inherits our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm\n// dlx` and refuse to work. portless is the motivating case; its guard (cli.js `main()`) is:\n//\n// isNpx = npm_command === 'exec' && !npm_lifecycle_event\n// isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n// if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) -> abort\n//\n// `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n// transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is\n// live. `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event, so `isNpx`\n// holds, every portless call exits 1, `isAvailable()` is false, and `ensureProxy` aborts the whole\n// dev boot with \"portless is not installed\", on a machine where it plainly is.\n//\n// `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n// `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n// `npm_*` removes that suppressor and creates an abort for the script-style invocation that\n// previously worked. Both markers go, or neither is safe.\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config\n * kept \u2014 specifically `npm_config_prefix` and `npm_config_registry`.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\n// `withoutPackageManagerEnv` is deliberately a blunt `npm_*` prefix filter, and it is the\n// right tool for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it\n// also drops the two variables that tell the package manager where, and from where, to install:\n//\n// - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and\n// we detect a global install rooted at prefix P, then run the install with P erased \u2014 so it\n// lands in the DEFAULT prefix instead. That is either a permanent EACCES, or a second global\n// copy that is not the one on PATH. Nothing notices: the install exits 0, we report\n// `installed`, the version on PATH never moves, and the whole cycle repeats every window\n// forever. `export npm_config_prefix=~/.npm-global` is npm's own documented EACCES workaround,\n// so this is a mainstream layout, not an exotic one.\n// - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it\n// here means we decide against a corporate mirror and then install from somewhere else.\n//\n// Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`,\n// `npm_lifecycle_event` and `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm config, and all of which\n// remain stripped.\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
5
5
  "mappings": "AAQA,OAAOA,MAAU,YAGV,IAAMC,EAAe,YAEtBC,EAAS,GAAGD,CAAY,UA8CxBE,EAAU,CAACC,EAAmBC,IAC9BA,IAAY,OAAkBD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BzB,GAA2D,CAChG,GAAM,CAAE,aAAAb,EAAc,IAAA0B,EAAK,SAAAvC,CAAS,EAAI0B,EAExC,MAAO,CAACuB,EAAgBvB,CAAK,GAAKY,EAA0BzB,EAAc0B,EAAKvC,CAAQ,CACzF,ECreA,OAAS,gBAAAoD,MAAoB,UAC7B,OAAOC,MAAU,YAUV,IAAMC,EAAgBC,GAAwB,CACnD,GAAI,CACF,OAAOH,EAAaG,CAAG,CACzB,MAAQ,CACN,OAAOF,EAAK,QAAQE,CAAG,CACzB,CACF,ECLA,OAAS,gBAAAC,MAAoB,qBAC7B,OAAOC,MAAa,eAEpB,IAAMC,EAAsB,IAafC,EAAqB,IAA0B,CAC1D,GAAI,CAOF,IAAMC,EANMJ,EAAa,MAAO,CAAC,OAAQ,IAAI,EAAG,CAC9C,SAAU,QACV,QAASE,EACT,MAAO,CAAC,SAAU,OAAQ,QAAQ,EAClC,MAAOD,EAAQ,WAAa,OAC9B,CAAC,EACmB,KAAK,EAEzB,OAAOG,IAAY,GAAK,OAAYA,CACtC,MAAQ,CACN,MACF,CACF,ECnBO,IAAMC,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH,EASIC,EAAyB,oCA2BlBC,EAA4BH,GAA8C,CACrF,IAAMI,EAAYL,EAAyBC,CAAG,EAE9C,OAAW,CAACC,EAAKI,CAAK,IAAK,OAAO,QAAQL,CAAG,EACvCE,EAAuB,KAAKD,CAAG,IAAGG,EAAUH,CAAG,EAAII,GAGzD,OAAOD,CACT",
6
6
  "names": ["path", "PACKAGE_NAME", "LATEST", "pinSpec", "command", "version", "token", "isWithin", "parent", "child", "realpath", "rel", "hasSegment", "p", "name", "isBrewKegOf", "segments", "cellar", "npmPrefixOfPackage", "binRealPath", "packageName", "nodeModules", "npmPrefixFromSelfPath", "selfRealPath", "npmPrefixInstallCommand", "prefix", "formatUpdateCommand", "underEnvDir", "env", "key", "dir", "WRAPPER_MATCHERS", "TREE_MATCHERS", "NPM_UPDATE_COMMAND", "fallbackUpdateCommand", "detectInstallManager", "input", "lazyNpmRoot", "detected", "detectUnpinned", "toInfo", "hit", "matches", "test", "wrapper", "derivedPrefix", "tree", "npmRoot", "isLocalNodeModulesInstall", "cwd", "GIT_WALK_MAX_HOPS", "gitWalkStart", "outermost", "ancestorsBelowHome", "start", "homeReal", "dirs", "hasGitAncestor", "exists", "isGlobalInstall", "home", "shouldWarnLocalInstall", "realpathSync", "path", "safeRealpath", "dir", "execFileSync", "process", "NPM_ROOT_TIMEOUT_MS", "defaultLazyNpmRoot", "trimmed", "withoutPackageManagerEnv", "env", "key", "NPM_CONFIG_TO_PRESERVE", "packageManagerInstallEnv", "sanitised", "value"]
7
7
  }
@@ -0,0 +1,11 @@
1
+ import{a as ie}from"./chunk-MFAFQVTW.js";import{a as oe}from"./chunk-6UJQB36N.js";import{d as _}from"./chunk-RZF36IGQ.js";import We from"node:process";import Ge from"pino";import ze from"pino-pretty";var Be=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],Ve=()=>{let e=We.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),Ge({level:e,redact:Be},ze({destination:2,ignore:t.join(","),colorize:!0}))},L=Ve();import te from"node:fs/promises";import Ie from"node:os";import j from"node:path";import _t from"node:process";import{z as s}from"zod";import He from"node:process";import qe from"node:process";var $={enabled:!1},Ue=(e,t=r=>{qe.stdout.write(r)})=>($.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
2
+ `),e),se=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(se)};var ae={source:null},P=()=>ae.source!==null,Je=()=>P()||$.enabled,K=()=>!!He.env.CI,Xe=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let n=e.INFRA_KIT_AGENT;return n==="1"||e.CLAUDECODE!==void 0&&!t&&n!=="0"?"env":null};var F=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var w=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r])=>r!==t));var E=({key:e,id:t,note:r})=>({id:t,note:r,apply:n=>e in n?{changed:!0,result:w(n,e)}:{changed:!1,result:n}});var ce=E({key:"devProxy",id:"drop-dev-proxy-key",note:'the retired "devProxy" key (dev URLs are port-free https://<release>.<package>.localhost)'});var pe=E({key:"envAutoLoad",id:"drop-env-auto-load-key",note:'the retired "envAutoLoad" key (env auto-load is gone \u2014 run `env-load -c <config>` in the terminal)'});var ue=E({key:"environments",id:"drop-environments-key",note:`the retired "environments" key (deploy targets now come from each workflow's workflow_dispatch options, auth from the token store)`});var Ye=e=>{let t=e.ide;if(t===null||typeof t!="object")return{changed:!1,result:e};let r=!1,n=i=>{if(i===null||typeof i!="object"||!("config"in i))return i;let a=i.config;return a===null||typeof a!="object"||!("mode"in a)?i:(r=!0,{...i,config:w(a,"mode")})},o=Array.isArray(t)?t.map(n):n(t);return r?{changed:!0,result:{...e,ide:o}}:{changed:!1,result:e}},le={id:"strip-legacy-ide-mode",note:'legacy "mode"',apply:Ye};var Ze="zed",de=e=>e!==null&&typeof e=="object"&&e.provider===Ze,Qe=e=>{let t=e.ide;if(Array.isArray(t)){let r=t.filter(n=>!de(n));return r.length===t.length?{changed:!1,result:e}:{changed:!0,result:r.length>0?{...e,ide:r}:w(e,"ide")}}return de(t)?{changed:!0,result:w(e,"ide")}:{changed:!1,result:e}},fe={id:"strip-retired-zed-ide",note:'the retired "zed" provider',apply:Qe};var W=[le,fe,ue,ce,pe];var S=e=>W.reduce((t,r)=>{let n=r.apply(t.result);return n.changed?{changed:!0,result:n.result,notes:[...t.notes,r.note]}:t},{changed:!1,result:e,notes:[]});import et from"node:fs/promises";import tt from"node:os";var rt=async e=>{try{return await et.access(e),!0}catch{return!1}},G=e=>{let t=tt.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};import{randomBytes as nt}from"node:crypto";import v from"node:fs/promises";import z from"node:path";import ot from"node:process";var D=class extends Error{constructor(t){super(`${t} changed on disk since it was read`),this.name="ConfigFileChangedError"}},it=2,st=e=>/^([ \t]+)\S/m.exec(e)?.[1]??it,at=4095,T=async({path:e,raw:t,migrated:r,expectedMtimeMs:n})=>{let o=await v.realpath(e),i=z.dirname(o),a=z.basename(o),p=z.join(i,`.${a}.${ot.pid}.${nt(4).toString("hex")}.tmp`),l=`${JSON.stringify(r,null,st(t))}
3
+ `;try{await v.writeFile(p,l,"utf8");let d=await v.stat(o);if(d.mtimeMs!==n)throw new D(e);await v.chmod(p,d.mode&at),await v.rename(p,o)}catch(d){throw await v.rm(p,{force:!0}),d}},ct=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),pt=async e=>{let t=await v.stat(e),r=await v.readFile(e,"utf8");if(r.trim()==="")return{changed:!1,result:{},notes:[],path:e};let n=JSON.parse(r);if(!ct(n))return{changed:!1,result:{},notes:[],path:e};let o=S(n);return o.changed&&await T({path:e,raw:r,migrated:o.result,expectedMtimeMs:t.mtimeMs}),{...o,path:e}};var B=async(e,t,r,{schema:n})=>{if(e.autoMigrate==="off")return{kind:"not-applicable"};let o=S(t);if(!o.changed)return{kind:"not-applicable"};let i=n.safeParse(o.result);if(!i.success)return{kind:"not-applicable"};if(e.required&&K())return{kind:"ci-gated"};try{await T({path:e.path,raw:r,migrated:o.result,expectedMtimeMs:e.mtimeMs})}catch(a){return L.debug(a,`auto-migration could not rewrite ${e.path}`),{kind:"not-applicable"}}return L.warn(`Migrated ${G(e.path)}: removed ${o.notes.join(" and ")} (retired by infra-kit ${oe.version})`),{kind:"migrated",data:i.data}};import C from"node:path";import ke from"node:process";import{$ as f}from"zx";var I=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:n,stderrExcerpt:o}=r;if(typeof n=="string"&&n.length>0)return n;if(typeof o=="string"&&o.length>0)return o;r=r.cause}},ut=(e,t)=>{let r=t.stderrExcerpt??I(e),n=[`failed to ${t.operation}`];return r&&n.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&n.push(`try: ${t.remediation}`),n.join(" \u2014 ")},g=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(ut(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??I(t)}};var lt=/^v?(\d+)\.(\d+)\.(\d+)$/,dt=/^(\d+)\.(\d+)\.(\d+)$/,ft=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,N="release/",V="release/v",ge="refs/heads/",gt="next";var me=new Set(["dev","main","next","hotfix","regular","release"]),x=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},b=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},ye=e=>e.startsWith(ge)?e.slice(ge.length):e,ve=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),q=e=>{if(e.length===0)throw new x('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new x(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!ft.test(e))throw new x(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(me.has(e))throw new x(`Release name "${e}" is reserved. Reserved names: ${[...me].join(", ")}.`)},U=e=>{let t=ye(e.trim());if(!t.startsWith(N))return null;if(t.startsWith(V)){let n=t.slice(V.length),o=dt.exec(n);if(o)return ve(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(N.length);try{q(r)}catch{return null}return{kind:"name",name:r,raw:r}},mt=e=>{let t=e.trim();if(ye(t).startsWith(N)){let o=U(t);if(!o)throw new b(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=lt.exec(t);if(n)return ve(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===gt)throw new b('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');if(t.includes("@"))throw new b(`Cannot parse "${e}" as a release ref: the \`@date\` suffix belongs to \`release create\`; pass the version alone here and use \`--release-date\` on \`release edit\``);try{q(t)}catch(o){let i=o instanceof Error?o.message:String(o);throw new b(`Cannot parse "${e}" as a release ref: ${i}`)}return{kind:"name",name:t,raw:t}},ht=e=>e.kind==="version"?`${V}${e.raw}`:`${N}${e.name}`,yt=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},vt=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,kt=e=>e.kind==="version"?`v${e.raw}`:e.name,wt=e=>e.raw,H=e=>e==null?!1:U(e)!==null,he=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},xt=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=he(r?.a),o=he(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var we=async e=>{let t=await f({cwd:e})`git worktree list --porcelain`,r=[],n=null;for(let o of t.stdout.split(`
4
+ `)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},bt=async e=>{let t=await we(ke.cwd()),r=n=>e==="release"?H(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},Rt=e=>{let t=I(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},Pt=({hasStderr:e})=>{if(P())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},A=async()=>{try{return(await f({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=Rt(e)??I(e);throw new g(e,{operation:`resolve the project root from ${ke.cwd()}`,stderrExcerpt:t,remediation:Pt({hasStderr:t!==void 0})})}},J=async e=>{let t=e??await A(),r=(await f({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=C.resolve(t,r);return n.includes(`${C.sep}.git${C.sep}modules${C.sep}`)?t:C.dirname(n)},xe=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),be=async()=>(await f`git status --porcelain`).stdout.split(`
5
+ `).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),Et=async()=>(await be()).length===0,Ct=async()=>{let e=await A(),[t,r]=await Promise.all([f({cwd:e})`git rev-parse --absolute-git-dir`,f({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),o=C.resolve(e,r.stdout.trim());return n!==o};var St=async e=>(await f`git branch --list ${e}`).stdout.trim().length>0,It=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await xe()!==e&&await f`git branch -D ${e}`},At=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};import{$ as O}from"zx";var Mt=async(e,t)=>{let r=`${t}^{commit}`;try{return(await O({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},jt=async(e,t,r)=>{try{return await O({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(n){if(n.exitCode===1)return!1;throw new g(n,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},$t=async(e,t)=>{let n=(await O({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
6
+ `)[0];return n?n.split(/\s+/)[0]??null:null},Dt=async(e,t)=>{let r=t.map(n=>`${n.sha}:refs/heads/${n.branch}`);if(r.length===0)return{refspecs:r,pushed:!1};try{return await O({cwd:e,quiet:!0})`git push --atomic origin ${r}`,{refspecs:r,pushed:!0}}catch(n){return{refspecs:r,pushed:!1,stderr:n.stderr}}};import Re from"node:path";import X from"node:process";import{$ as h}from"zx";var Pe=async e=>{let t=e??X.cwd(),r=(await h({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=X.env.INFRA_KIT_SESSION||String(X.pid);return Re.join(Re.resolve(t,r),"infra-kit",`merge-dev-${n}`)},Y=async e=>{try{return await h({cwd:e,quiet:!0})`git rev-parse -q --verify MERGE_HEAD`,!0}catch{return!1}},Tt=async e=>{if(await Y(e))throw new g(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:"a merge is still in progress in the scratch worktree",remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"});let t=(await h({cwd:e,quiet:!0})`git status --porcelain`).stdout.trim();if(t.length>0)throw new g(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:`scratch worktree is dirty: ${t.split(`
7
+ `)[0]}`,remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"})},Nt=async e=>{let t=async r=>{try{await r()}catch{}};await Y(e)&&await t(()=>h({cwd:e,quiet:!0})`git merge --abort`),await t(()=>h({cwd:e,quiet:!0})`git reset --hard`),await t(()=>h({cwd:e,quiet:!0})`git clean -fd`)},Ot=async(e,t)=>{let{cwd:r,anchor:n="origin/dev"}=e,o=await Pe(r),i=async()=>{await h({cwd:r,quiet:!0})`git worktree add --detach ${o} ${n}`};try{await i()}catch(p){try{await h({cwd:r,quiet:!0})`git worktree prune`,await i()}catch{throw new g(p,{operation:"create the scratch worktree for the merge",remediation:`remove any stale checkout at ${o}, then retry`})}}let a={path:o,remove:async()=>{try{await h({cwd:r,quiet:!0})`git worktree remove --force ${o}`}catch{}}};try{return await t(a)}finally{await a.remove()}};var Ee="infra-kit.json";var Lt="infra-kit.json",Kt="projects",Ft=s.object({provider:s.literal("doppler"),config:s.object({name:s.string().min(1)})}),Wt=s.discriminatedUnion("provider",[Ft]),Gt=s.object({workspaceConfigPath:s.string().min(1)}).strict(),zt=s.object({provider:s.literal("cursor"),config:Gt}).strict(),Ce=s.discriminatedUnion("provider",[zt]),Bt=s.union([Ce,s.array(Ce).min(1)]),Vt=s.object({provider:s.literal("jira"),config:s.object({baseUrl:s.string().url(),projectId:s.number().int().positive()})}),qt=s.discriminatedUnion("provider",[Vt]),Ut=["two-columns","three-pane"],Ht=s.object({layout:s.enum(Ut).optional()}).strict(),Jt=s.object({openInGithubDesktop:s.boolean().optional(),openInOrca:s.boolean().optional(),orca:Ht.optional()}).strict(),Xt=s.object({port:s.number().int().positive().optional(),prefixUrl:s.string().min(1).optional()}).strict(),Yt=s.record(s.string().min(1),Xt),Zt=s.enum(["local","cloud"]),Qt=s.object({watchDeps:s.boolean().optional(),proxy:s.record(s.string().min(1),Zt).optional()}).strict(),er=s.object({apps:s.record(s.string().min(1),Qt).optional(),orca:s.boolean().optional()}).strict(),tr=s.record(s.string().min(1),er),rr=s.enum(["disallow","allow","cli-only"]),Se=s.string().regex(/^[A-Z_]\w*$/i,"must be a POSIX environment-variable name"),nr=s.object({command:s.string().min(1),args:s.array(s.string()).default([]),env:s.array(Se).min(1),unset:s.array(Se).default([])}).strict().superRefine((e,t)=>{for(let r of e.env)ie.has(r)&&t.addIssue({code:"custom",path:["env"],message:`"${r}" is process plumbing the proxy never strips or injects \u2014 it cannot be a credential name`})}),or=s.record(s.string().regex(/^[a-z][a-z0-9-]*$/,"must be lowercase letters, digits and hyphens, starting with a letter").refine(e=>!e.includes("infra-kit"),{message:'"infra-kit" is reserved: it is the .mcp.json key of the retired infra-kit MCP server \u2014 pick another name'}),nr),re=s.object({envManagement:Wt,ide:Bt.optional(),taskManager:qt.optional(),worktrees:Jt.optional(),dev:Yt.optional(),devServersPresets:tr.optional(),protectedEnvs:rr.optional(),mcp:or.optional()}).strict(),ir=443,Ae=re.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),ee=re.partial(),sr=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},Me="two-columns",ar=e=>e.worktrees?.orca?.layout??Me,k=null,M=null,je=()=>`${_t.cwd()} ${Ie.homedir()}`,$e=()=>j.join(Ie.homedir(),_),De=()=>j.join($e(),Lt),Te=async()=>{let e=je();if(M&&M.key===e)return M.value;let t=await A(),r=await J(t),n=j.basename(r),o={main:j.join(t,Ee),userGlobal:De(),userProject:j.join($e(),Kt,n,Ee),projectName:n};return M={key:e,value:o},o},cr=async(e={})=>{let t=e.autoMigrate??"write",r=je(),n=await Te(),o;try{o=await te.stat(n.main)}catch{k=null;let y=n.main.replace(/\.json$/,".yml");throw await Z(y)?new Error(`infra-kit.json not found at ${n.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit setup --skip-tools\` to convert it.`):new Error(P()?`infra-kit.json not found at ${n.main} \u2014 the working directory is not an infra-kit project. Run infra-kit from inside an infra-kit project repo, or pass \`-C <dir>\` naming one.`:`infra-kit.json not found at ${n.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit setup --skip-tools\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[i,a]=await Promise.all([Z(n.userGlobal),Z(n.userProject)]),p={main:Number(o.mtimeMs),userGlobal:i?Number(i.mtimeMs):null,userProject:a?Number(a.mtimeMs):null};if(k&&k.key===r&&dr(k.mtimes,p))return k.value;let l=[{label:"infra-kit.json",path:n.main,required:!0,autoMigrate:t,mtimeMs:p.main},{label:"~/.infra-kit/infra-kit.json",path:n.userGlobal,required:!1,autoMigrate:t,mtimeMs:p.userGlobal},{label:`~/.infra-kit/projects/${n.projectName}/infra-kit.json`,path:n.userProject,required:!1,autoMigrate:t,mtimeMs:p.userProject}],d={};for(let y of l){let R=await fr(y);R!==null&&(d={...d,...R})}let m=Ae.safeParse(d);if(!m.success)throw new Error(`Invalid merged infra-kit config: ${s.prettifyError(m.error)}`);return k={key:r,mtimes:p,value:m.data},m.data},pr=()=>{k=null},ur=()=>{k=null,M=null},Z=async e=>{try{return await te.stat(e)}catch{return null}},lr=async e=>{try{return await te.readFile(e,"utf-8")}catch{return null}},dr=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},Ne=e=>new Error(`${e.message}
8
+ A retired key on this branch \u2014 run \`infra-kit setup --skip-tools\` in this checkout and commit infra-kit.json.`),fr=async e=>{let t=await lr(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(a){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${a.message}`)}if(Q(r)&&"envTokens"in r)throw new Error(mr(e));if(!e.required&&Q(r)&&"mcp"in r)throw new Error(gr(e));let n=ee.safeParse(r);if(n.success)return n.data;let o=new Error(`Invalid ${e.label} at ${e.path}: ${s.prettifyError(n.error)}`);if(!Q(r)||e.mtimeMs===null)throw o;let i=await B({...e,mtimeMs:e.mtimeMs},r,t,{schema:ee});switch(i.kind){case"migrated":return i.data;case"ci-gated":throw Ne(o);case"not-applicable":throw o;default:return F(i)}},gr=e=>[`"mcp" is not allowed in ${e.label} (${e.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,"Move the block to the project infra-kit.json and run `infra-kit setup`.","For a machine-only override of one server (e.g. a local fork), use Claude Code directly:"," claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>","(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected)."].join(`
9
+ `),Q=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mr=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
10
+ `);import*as u from"node:fs";import*as c from"node:path";function hr(e){let t=e;for(let r=0;r<10;r++){let n=c.join(t,"pnpm-workspace.yaml");if(u.existsSync(n))return t;t=c.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function _e(e,t){let r=c.join(e,"package.json");if(!u.existsSync(r))return t;try{let n=JSON.parse(u.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function Ro(e){let t=c.join(e,"apps"),r=[];if(!u.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=u.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=c.join(t,o,"api"),a=c.join(i,"serverless.yml");u.existsSync(a)&&r.push({name:o,packageName:_e(i,o),path:i})}return r}var Le=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],yr=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function vr(e){for(let t of Le){let r=c.join(e,t);if(u.existsSync(r))try{let n=u.readFileSync(r,"utf-8");return yr.some(o=>n.includes(o))}catch{return!1}}return!1}function Po(e){for(let t of Le){let r=c.join(e,t);if(u.existsSync(r))try{return u.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function kr(e){let t=c.join(e,"package.json");if(!u.existsSync(t))return!1;try{let r=JSON.parse(u.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function Eo(e){let t=c.join(e,"apps"),r=[];if(!u.existsSync(t))return r;let n=u.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=c.join(t,o,"ui");u.existsSync(i)&&kr(i)&&r.push({name:o,packageName:_e(i,o),path:i,managedPort:vr(i)})}return r}function Co(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function So(e){let t=hr(e),r=c.relative(c.join(t,"apps"),e),n=r.split(c.sep)[0];if(r===""||r.startsWith("..")||c.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var wr=new Set(["api","ui"]),Oe=e=>{let t=c.join(e,"dist");return u.existsSync(t)&&u.statSync(t).isDirectory()?t:void 0},ne=e=>u.existsSync(e)?u.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function Io(e){let t=[];for(let n of ne(c.join(e,"packages"))){let o=Oe(c.join(e,"packages",n));o!==void 0&&t.push(o)}let r=c.join(e,"apps");for(let n of ne(r))for(let o of ne(c.join(r,n))){if(wr.has(o))continue;let i=c.join(r,n,o);if(!u.existsSync(c.join(i,"package.json")))continue;let a=Oe(i);a!==void 0&&t.push(a)}return t}function Ao(e){return e.map(t=>c.join(t.path,"dist")).filter(t=>u.existsSync(t))}function Mo(e,t,r){let n=c.normalize(e),o=r.find(a=>n.startsWith(c.normalize(a)));return o?{kind:"package",packageDir:o}:{kind:"app",app:t.find(a=>n.startsWith(c.normalize(a)))}}var xr={"*/api":{},"*/ui":{}},Fe=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},br=e=>{let t=Fe(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},$o=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let i=Fe(o);i&&t.push({preset:r,key:o,message:`preset "${r}": ${i}`})}return t},Rr=(e,t)=>t==="api"?e.api:e.ui,Pr=e=>[...new Set([...e.api,...e.ui])].sort(),Ke=(e,t)=>`${e}/${t}`,Er=e=>e?0:1,Cr=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,Sr=(e,t,r)=>{let{app:n,part:o,watchDeps:i,isGlob:a}=r;if(!Rr(t,o).includes(n)){a||e.unmatched.push(Ke(n,o));return}let p=Ke(n,o),l=Cr(e.targets.get(p),{watchDeps:i,rank:Er(a)});e.targets.set(p,{app:n,part:o,...l})},Ir=(e,t)=>{let r=Object.entries(e.apps??xr),n={targets:new Map,proxy:{},unmatched:[]};for(let[a,p]of r){let{appGlob:l,part:d}=br(a),m=l==="*",y=m?Pr(t):[l];for(let R of y)Sr(n,t,{app:R,part:d,watchDeps:p.watchDeps,isGlob:m}),p.proxy&&(n.proxy[R]={...n.proxy[R]??{},...p.proxy})}let o=[...n.targets.values()].map(({app:a,part:p,watchDeps:l})=>({app:a,part:p,watchDeps:l})),i=[...new Set(o.filter(a=>a.part==="api").map(a=>a.app))];return{targets:o,orca:e.orca??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},Do=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},Ar=(e,t)=>Object.keys(e).find(r=>e[r]===t),Mr=({preset:e,app:t,route:r,launchedPkgs:n,ctx:o})=>{let i=o.routePkg(t,r);if(i===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let a=Ar(o.apiPkgByApp,i),p=a?`add "${a}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:e,app:t,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${p}, or set "${r}" to "cloud"`}},To=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let i=Ir(o,t.discovered),a=new Set(i.localApps.map(p=>t.apiPkgByApp[p]).filter(p=>p!==void 0));for(let[p,l]of Object.entries(i.proxy))for(let[d,m]of Object.entries(l)){if(m!=="local")continue;let y=Mr({preset:n,app:p,route:d,launchedPkgs:a,ctx:t});y&&r.push(y)}}return r};export{$ as a,Ue as b,se as c,ae as d,P as e,Je as f,Xe as g,I as h,g as i,x as j,q as k,U as l,mt as m,ht as n,yt as o,vt as p,kt as q,wt as r,H as s,xt as t,we as u,bt as v,A as w,J as x,xe as y,be as z,Et as A,Ct as B,St as C,It as D,At as E,Mt as F,jt as G,$t as H,Dt as I,Y as J,Tt as K,Nt as L,Ot as M,L as N,F as O,rt as P,G as Q,D as R,pt as S,ir as T,Ae as U,ee as V,sr as W,ar as X,De as Y,Te as Z,cr as _,pr as $,ur as aa,hr as ba,Ro as ca,Po as da,Eo as ea,Co as fa,So as ga,Io as ha,Ao as ia,Mo as ja,Fe as ka,$o as la,Ir as ma,Do as na,To as oa};
11
+ //# sourceMappingURL=chunk-F656FWV5.js.map