infra-kit 0.5.6 → 0.7.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.
- package/dist/chunk-63VNUKUS.js +8 -0
- package/dist/chunk-63VNUKUS.js.map +7 -0
- package/dist/chunk-7YE5QKKB.js +444 -0
- package/dist/chunk-7YE5QKKB.js.map +7 -0
- package/dist/chunk-GYPVEWUV.js +2 -0
- package/dist/chunk-GYPVEWUV.js.map +7 -0
- package/dist/chunk-KXQQUBGV.js +10 -0
- package/dist/{chunk-744Y674Y.js.map → chunk-KXQQUBGV.js.map} +4 -4
- package/dist/chunk-MFLYORUJ.js +2 -0
- package/dist/chunk-MFLYORUJ.js.map +7 -0
- package/dist/chunk-NFIFWIO6.js +4 -0
- package/dist/chunk-NFIFWIO6.js.map +7 -0
- package/dist/chunk-QS4JZKF2.js +2 -0
- package/dist/{chunk-YYEUJYC7.js.map → chunk-QS4JZKF2.js.map} +1 -1
- package/dist/chunk-UI2MUEVR.js +2 -0
- package/dist/chunk-UI2MUEVR.js.map +7 -0
- package/dist/{chunk-QUXDC3A3.js → chunk-YKCY657C.js} +4 -4
- package/dist/cli.js +11 -10
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +22 -22
- package/dist/dev-server.js.map +3 -3
- package/dist/{dev-wizard-run-DWDA5R3A.js → dev-wizard-run-MCUYV6IN.js} +2 -2
- package/dist/mcp-proxy.js +9 -9
- package/dist/mcp-proxy.js.map +3 -3
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-744Y674Y.js +0 -10
- package/dist/chunk-LCNORKDV.js +0 -8
- package/dist/chunk-LCNORKDV.js.map +0 -7
- package/dist/chunk-PQG63EIV.js +0 -4
- package/dist/chunk-PQG63EIV.js.map +0 -7
- package/dist/chunk-XJOY7J3G.js +0 -2
- package/dist/chunk-XJOY7J3G.js.map +0 -7
- package/dist/chunk-XN7VHD7P.js +0 -445
- package/dist/chunk-XN7VHD7P.js.map +0 -7
- package/dist/chunk-Y5TLBGZT.js +0 -2
- package/dist/chunk-Y5TLBGZT.js.map +0 -7
- package/dist/chunk-YYEUJYC7.js +0 -2
- /package/dist/{chunk-QUXDC3A3.js.map → chunk-YKCY657C.js.map} +0 -0
- /package/dist/{dev-wizard-run-DWDA5R3A.js.map → dev-wizard-run-MCUYV6IN.js.map} +0 -0
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { PACKAGE_NAME, defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal throttle window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /**\n * The version the user now gets from the `infra-kit` on their PATH. Consulted once, after the install\n * command returns 0, because that exit code is not proof of anything \u2014 see {@link readInstalledVersion}.\n */\n installedVersion?: (env: NodeJS.ProcessEnv) => string | null\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Bounds the post-install probe; a hung shim must not pin this worker for the parent's 5-minute budget. */\nconst VERSION_PROBE_TIMEOUT_MS = 15_000\n\n/**\n * Ask the freshly installed CLI what it is, the way the user will: the `infra-kit` bin on PATH.\n *\n * Not `<selfRealPath>/../package.json`. pnpm keeps each version in its own directory\n * (`.pnpm/infra-kit@0.5.1/\u2026`, `global/v11/<hash>/\u2026`) and repoints the shim, so the path THIS worker was\n * launched from keeps reporting the old version forever, while the path the user gets has moved.\n *\n * `--json` doubles as the guard that stops the probe spawning a second updater from inside the first:\n * `autoUpdateSkipReason` returns `json` before anything else runs, and piped stdio fails the tty arm too.\n * Anything short of a parseable version is `null` \u2014 a shim that no longer resolves, a bin that crashes on\n * boot, output that is not JSON \u2014 and the caller treats every one of those as \"not verified\".\n */\nconst readInstalledVersion = (env: NodeJS.ProcessEnv): string | null => {\n const result = spawnSync(PACKAGE_NAME, ['version', '--json'], {\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n cwd: homedir(),\n env,\n timeout: VERSION_PROBE_TIMEOUT_MS,\n windowsHide: true,\n encoding: 'utf8',\n })\n\n if (result.error || result.signal || result.status !== 0) return null\n\n try {\n const parsed: unknown = JSON.parse(result.stdout)\n const version = (parsed as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n }\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n /** The install command returned 0, yet the `infra-kit` on PATH still does not report `latestVersion`. */\n | 'install-stale'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n try {\n return await runUpdateCheckLocked(currentVersion, deps)\n } finally {\n release()\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n const installedVersion = deps.installedVersion ?? readInstalledVersion\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (\n outcome: UpdateCheckOutcome,\n cache: Omit<UpdateCache, 'lastCheckMs' | 'outcome'>,\n ): UpdateCheckOutcome => {\n // `outcome` is recorded on EVERY write: it is what lets a reader (human or `isStale`) tell a settled\n // `installed`/`up-to-date` from a transient `fetch-failed`, all of which otherwise write an identical\n // `{latestVersion:null}`. See `UpdateCache.outcome`.\n writeCache({ lastCheckMs: nowMs, ...cache, outcome })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n // `version` pins the spec to what we just fetched: a `@latest` command is resolved by the package\n // manager from ITS cache, which pnpm does not revalidate \u2014 see `pinSpec` in install-manager.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n version: latestVersion,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n //\n // `outcome: 'installing'` marks a mid-install checkpoint: if the worker is killed here (machine sleeps,\n // SIGKILL) and never reaches `finish()`, this stamp is what the next run reads, and the cache says so\n // rather than looking like a settled result. It does not shorten the next window \u2014 see CHECK_INTERVAL_MS.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null, outcome: 'installing' })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // Exit 0 is the package manager saying it is content, not that anything changed. `pnpm add -g\n // infra-kit@latest` resolved the tag from its own stale metadata cache, reinstalled the version already\n // present, and returned 0 \u2014 and this function recorded `installed`, cleared `latestVersion`, and\n // repeated the same no-op every cycle. The spec is pinned now, but the check that would have SHOWN\n // that bug is this one: ask the binary the user actually runs. A mismatch keeps `latestVersion` and the\n // command in the cache, so the parent prints the manual line instead of staying silent.\n const nowInstalled = installedVersion(env)\n\n if (nowInstalled !== latestVersion) return finish('install-stale', { latestVersion, updateCommand })\n\n // Verified: clear `latestVersion` so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/**\n * Bounded so a hanging registry can never keep a detached child alive indefinitely. 5s, not a tighter\n * bound: the abbreviated `/pkg/latest` endpoint is usually ~20-900ms, but a cold TLS/DNS handshake in a\n * freshly-spawned worker can spike past a 2.5s cap \u2014 and a single trip used to cost a `fetch-failed` that\n * pushed the next check a full window out. A detached child that lingers a few extra seconds harms nothing.\n */\nexport const FETCH_TIMEOUT_MS = 5_000\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit setup` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/**\n * The ONE re-check window, whatever the last outcome was. A background check is cheap \u2014 one\n * detached child and a single registry fetch bounded by `FETCH_TIMEOUT_MS` \u2014 but not once per\n * shell command, which is the storm this throttle exists to stop.\n *\n * MUST stay above a full worker cycle: `runUpdateCheck` stamps `lastCheckMs` BEFORE waiting up to\n * `PARENT_WAIT_TIMEOUT_MS` (5min) for the parent to exit and THEN installing.\n */\n// There is deliberately no shorter \"retry after a transient failure\" window. One used to exist\n// because this interval was 24h, and burning a whole day on a single network blip locked out\n// exactly the publisher pushing a release mid-window. At 20 minutes that gap is gone: a blip costs\n// one window, so a second window buys nothing and cannot pay for what it costs.\n//\n// What it would cost: go below a full worker cycle and the cache reads stale while the first worker\n// is still legitimately working, so the next shell spawns a worker that dies on the live\n// single-flight lock and returns WITHOUT writing \u2014 leaving the cache stale for every command until\n// `LOCK_STALE_MS` (30min) reaps the lock. That is the per-command spawn storm this throttle exists\n// to prevent, and it is why a 5-minute retry window is not an option.\nexport const CHECK_INTERVAL_MS = 20 * 60 * 1000\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n /**\n * The last check's terminal outcome (`installed`, `fetch-failed`, `up-to-date`, \u2026), or absent on a\n * cache written before this field existed.\n *\n * Diagnostic ONLY \u2014 nothing branches on it, {@link isStale} included. It earns its keep by being the\n * one thing that makes this file legible: a successful `installed` and a failed `fetch-failed` both\n * write a byte-identical `{latestVersion:null, updateCommand:null}`, so without this the cache cannot\n * say which happened, and a silent auto-update leaves no other trace of what it did.\n */\n outcome?: string | null\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand, outcome } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand)) &&\n (outcome === undefined || outcome === null || typeof outcome === 'string')\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * The window does NOT depend on `outcome`: every last outcome, transient or settled, is re-checked\n * after {@link CHECK_INTERVAL_MS}. See that constant for why a shorter transient-failure window is not\n * worth its cost here.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null, updateCommand: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n if (elapsed < 0) return true\n\n return elapsed >= CHECK_INTERVAL_MS\n}\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": "8GAWA,OAAS,aAAAA,MAAiB,qBAC1B,OAAS,WAAAC,MAAe,UACxB,OAAOC,MAAa,eCFpB,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAIb,IAAMC,EAAiB,oBAiBjBC,EAAgB,KAAU,IAE1BC,EAAe,IACnBC,EAAK,KAAKC,EAAa,EAAGJ,CAAc,EAS3CK,EAAc,CAACC,EAAkBC,IAAwB,CAC7D,GAAI,CACEA,EAAQC,EAAG,SAAS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AAOiB,EAAO,aAAc,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAQpE,GAAM,CAAE,aAAAK,EAAc,cAAAC,CAAc,EAAIC,EAAqB,CAC3D,aAAc1B,EAAK,aACnB,IAAAd,EACA,SAAUyC,EACV,YAAAZ,EACA,QAASI,CACX,CAAC,EAID,GAAI,CAACK,EAAc,OAAOJ,EAAO,oBAAqB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAKtF,GAAIzB,EAAK,WAAa,KAAM,OAAOoB,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAqBlG,GALAT,EAAW,CAAE,YAAaH,EAAO,cAAAY,EAAe,cAAe,KAAM,QAAS,YAAa,CAAC,EAKxF,CAHe,MAAMrB,GAAkBE,EAAK,UAAW,CAAE,eAAAY,EAAgB,MAAAC,EAAO,MAAAC,CAAM,CAAC,EAG1E,OAAOM,EAAO,uBAAwB,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAgB7F,IAAMhC,EAAS8B,EAAMQ,EAAc,CAAC,EAAaA,EAAc,MAAM,CAAC,EAAG,CACvE,MAAO,SACP,MAAOnC,EAAQ,WAAa,QAC5B,IAAKC,EAAQ,EACb,IAAKqC,EAAyB1C,CAAG,EACjC,YAAa,EACf,CAAC,EAID,OAAIC,EAAO,OAASA,EAAO,QAAUA,EAAO,SAAW,EAC9CiC,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAS7CP,EAAiBhC,CAAG,IAEpBiC,EAAsBC,EAAO,gBAAiB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAG5FL,EAAO,YAAa,CAAE,cAAe,KAAM,cAAe,IAAK,CAAC,CACzE",
|
|
6
6
|
"names": ["spawnSync", "homedir", "process", "fs", "path", "process", "LOCK_FILE_NAME", "LOCK_STALE_MS", "lockFilePath", "path", "getCacheRoot", "reapIfStale", "lockPath", "nowMs", "fs", "acquireUpdateLock", "deps", "open", "fd", "process", "DEFAULT_REGISTRY", "FETCH_TIMEOUT_MS", "configuredRegistry", "env", "key", "value", "registryUrl", "configured", "base", "fetchLatestVersion", "fetchFn", "controller", "timer", "response", "PACKAGE_NAME", "version", "RELEASE_PATTERN", "parseSemver", "version", "withoutBuild", "core", "prereleaseParts", "match", "major", "minor", "patch", "NUMERIC_IDENTIFIER", "compareIdentifier", "left", "right", "leftNumeric", "rightNumeric", "comparePrerelease", "a", "b", "index", "isNewerVersion", "latest", "current", "parsedLatest", "parsedCurrent", "latestIsFinal", "currentIsFinal", "fs", "path", "CACHE_FILE_NAME", "CHECK_INTERVAL_MS", "cacheFilePath", "path", "getCacheRoot", "isStringArray", "value", "entry", "isUpdateCache", "lastCheckMs", "latestVersion", "updateCommand", "outcome", "readUpdateCache", "readFile", "p", "fs", "parsed", "writeUpdateCache", "cache", "root", "atomicWriteFileSync", "isStale", "nowMs", "elapsed", "PARENT_POLL_INTERVAL_MS", "PARENT_WAIT_TIMEOUT_MS", "VERSION_PROBE_TIMEOUT_MS", "readInstalledVersion", "env", "result", "spawnSync", "PACKAGE_NAME", "process", "homedir", "version", "defaultIsProcessAlive", "pid", "defaultSleep", "ms", "resolve", "waitForParentExit", "parentPid", "deps", "deadline", "runUpdateCheck", "currentVersion", "release", "acquireUpdateLock", "runUpdateCheckLocked", "nowMs", "fetchLatest", "fetchLatestVersion", "writeCache", "writeUpdateCache", "isProcessAlive", "sleep", "clock", "lazyNpmRoot", "defaultLazyNpmRoot", "spawn", "installedVersion", "latestVersion", "finish", "outcome", "cache", "isNewerVersion", "canSelfSpawn", "updateCommand", "detectInstallManager", "safeRealpath", "packageManagerInstallEnv"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{i as L,l as I,m as R}from"./chunk-GYPVEWUV.js";import{e as E}from"./chunk-NFIFWIO6.js";import g from"node:fs";import{homedir as ce}from"node:os";import{dirname as v,join as C}from"node:path";import O from"node:process";import{fileURLToPath as ue}from"node:url";import{execFile as j}from"node:child_process";import{createHash as H}from"node:crypto";import{existsSync as _,readFileSync as f}from"node:fs";import G from"node:http";import K from"node:https";import q from"node:net";import{homedir as z}from"node:os";import{dirname as y,join as u}from"node:path";import m from"node:process";import J from"node:tls";import{fileURLToPath as V}from"node:url";import{promisify as $}from"node:util";var U=/^[\w@%+=:,./-]+$/,F="'\\''",A=e=>U.test(e)?e:`'${e.replaceAll("'",F)}'`,P=e=>e.map(A).join(" ");var W=$(j),Q=e=>{let r=JSON.parse(f(e,"utf-8")),t=typeof r.bin=="string"?r.bin:r.bin?.portless;return t==null||t===""?null:t},x=()=>{try{let e=y(V(import.meta.url));for(;;){let r=u(e,"node_modules","portless","package.json");if(_(r)){let n=Q(r);return n==null?null:u(y(r),n)}let t=y(e);if(t===e)return null;e=t}}catch{return null}},h,w=()=>(h===void 0&&(h=x()),h),N=(e,r)=>{let t=[r.execPath??m.execPath,r.bin,...e];return(r.sudo===!0?"sudo ":"")+P(t)},X=1500,S=1500,Y="x-portless",b="127.0.0.1",Z="localhost",ee="sh.portless.proxy",te=`/Library/LaunchDaemons/${ee}.plist`,re="/etc/systemd/system/portless.service",Be="portless",ne=(e=_)=>{try{return m.platform==="darwin"?e(te)?"yes":"no":m.platform==="linux"?e(re)?"yes":"no":"unknown"}catch{return"unknown"}},oe=e=>new Promise(r=>{let t=q.connect({host:b,port:e}),n=o=>{t.destroy(),r(o)};t.setTimeout(S),t.once("connect",()=>{n(!0)}),t.once("timeout",()=>{n(!1)}),t.once("error",()=>{n(!1)})}),se=(e,r)=>new Promise(t=>{let o=(r?K.request:G.request)({host:b,port:e,method:"HEAD",path:"/",timeout:S,...r?{rejectUnauthorized:!1,servername:Z}:{}},s=>{s.resume(),t(s.headers[Y]==="1")});o.on("error",()=>{t(!1)}),o.on("timeout",()=>{o.destroy(),t(!1)}),o.end()}),ie=async(e,{timeoutMs:r})=>{let t=w();if(t==null)throw new Error("portless is not installed (not resolvable from node_modules)");await W(m.execPath,[t,...e],{signal:AbortSignal.timeout(r),encoding:"utf-8",env:R(m.env)})},k=()=>m.env.PORTLESS_STATE_DIR??u(z(),".portless"),ae="ca.pem",le="ca.trusted",T=()=>u(k(),ae),Ue=()=>{try{let e=f(u(k(),le),"utf-8").trim();return e===""?!1:H("sha256").update(f(T())).digest("hex")===e.toLowerCase()}catch{return!1}},Fe=(e,r)=>new Promise(t=>{let n;try{n=f(T())}catch{t({ok:!1,code:"ENOENT"});return}let o=J.connect({host:b,port:e,servername:r,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,c=o.authorized;o.destroy(),t(c?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(S),o.once("timeout",()=>{o.destroy(),t({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),t({ok:!1,code:s.code??"UNKNOWN"})})}),je=()=>{try{let e=JSON.parse(f(u(k(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(r=>{let{hostname:t,port:n}=r??{};return typeof t!="string"||t===""||typeof n!="number"?[]:[{name:t,port:n}]}):[]}catch{return[]}},He=(e={})=>{let r=e.bin===void 0?w():e.bin,t=e.run??ie,n=e.isListening??oe,o=e.isProxyServing??se,s=e.isServiceInstalled??ne,c=e.timeoutMs??X,a=null,l=async i=>{try{return await t(i,{timeoutMs:c}),!0}catch{return!1}},d=async()=>(a??=await l(["--version"]),a);return{binPath:()=>r,isAvailable:d,isProxyServing:async(i,p)=>!await d()||!await n(i)?!1:o(i,p),probeProxy:async(i,p)=>await n(i)?await o(i,p)?"serving":"not-portless":"daemon-down",isServiceInstalled:s,registerAlias:async(i,p)=>await d()?l(["alias",i,String(p)]):!1,removeAlias:async i=>{await d()&&await l(["alias","--remove",i])}}};var D=e=>C(e,E,"portless"),me=(e,r=g.existsSync)=>{let t=C(D(e),"dist","cli.js");return r(t)?t:null},Xe=(e,r)=>N(["service","install"],{sudo:!0,bin:me(r.home,r.exists)??e,execPath:r.execPath}),M=Symbol("absent"),B=Symbol("not-a-symlink"),pe=(e,r)=>{let t=r.lstatSync(e,{throwIfNoEntry:!1});return t===void 0?M:t.isSymbolicLink()?r.readlinkSync(e):B},fe=(e,r,t)=>{let n=`${r}.tmp-${O.pid}`;try{t.unlinkSync(n)}catch{}t.symlinkSync(e,n);try{t.renameSync(n,r)}catch(o){try{t.unlinkSync(n)}catch{}throw o}},de=e=>{let{resolveBin:r,isGlobal:t,home:n,fs:o=g}=e,s=D(n),c=r();if(c===null)return{outcome:"skipped-unresolved",target:null,link:s};let a=v(v(c));if(!t())return{outcome:"skipped-local",target:a,link:s};try{o.mkdirSync(v(s),{recursive:!0});let l=pe(s,o);return l===a?{outcome:"unchanged",target:a,link:s}:l===B?{outcome:"failed",target:a,link:s}:(fe(a,s,o),{outcome:l===M?"created":"repointed",target:a,link:s})}catch{return{outcome:"failed",target:a,link:s}}},ge=()=>{let e=ce();return{resolveBin:x,isGlobal:()=>L({selfRealPath:g.realpathSync(ue(import.meta.url)),env:O.env,realpath:I,home:e,exists:g.existsSync}),home:e}},Ye=(e,r)=>{try{e(de(r??ge()),"portless link")}catch{}};export{P as a,x as b,N as c,ee as d,te as e,re as f,Be as g,oe as h,se as i,k as j,T as k,Ue as l,Fe as m,je as n,He as o,D as p,me as q,Xe as r,de as s,ge as t,Ye as u};
|
|
2
|
+
//# sourceMappingURL=chunk-UI2MUEVR.js.map
|
|
@@ -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"],
|
|
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'\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\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 return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: seams.execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\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 * // => { 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 { outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { 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 { outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { outcome: 'failed', target, link }\n }\n}\n\n/** `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. */\ntype PortlessLinkLog = (result: PortlessLinkResult, message: string) => void\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULT back to report its step, so the two\n * writers can never disagree about which install is \"global\" or where the link goes.\n */\nexport const realPortlessLinkDeps = (): EnsurePortlessLinkDeps => {\n const home = homedir()\n\n return {\n resolveBin: resolvePortlessBin,\n isGlobal: () => {\n return 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 home,\n }\n}\n\n/**\n * The process-boot entry for both bins. fs-only, no subprocess, never throws, never exits, never\n * writes to stdout; the outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'`\n * is logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: EnsurePortlessLinkDeps): void => {\n try {\n log(ensurePortlessLink(deps ?? realPortlessLinkDeps()), 'portless link')\n } catch {\n // A link that could not be converged is `doctor`'s to report; it must never be a boot failure.\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, a cmux runner, 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"],
|
|
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,MAAgB,qBACzB,OAAS,cAAAC,MAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAOC,MAAW,aAClB,OAAOC,MAAS,WAChB,OAAS,WAAAC,MAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAOC,MAAS,WAChB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,aAAAC,MAAiB,YCrB1B,IAAMC,EAAa,mBAGbC,EAAsB,QAGf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AsBZ,IAAwC,CAC7F,GAAI,CACFY,EAAIb,GAAmBC,GAAQK,GAAqB,CAAC,EAAG,eAAe,CACzE,MAAQ,CAER,CACF",
|
|
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", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "process", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessLinkDeps", "homedir", "resolvePortlessBin", "isGlobalInstall", "fileURLToPath", "safeRealpath", "bootPortlessLink", "log"]
|
|
7
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{K as f,Q as k,b as y,d as T}from"./chunk-63VNUKUS.js";import{s as O}from"./chunk-NFIFWIO6.js";import{a as S,b as P}from"./chunk-QWVLAZ6N.js";import u from"node:fs/promises";import c from"node:path";import{z as s}from"zod";var i=class extends Error{env;constructor(t,o=null){super(t),this.name="EnvAuthError",this.env=o}},L=e=>e instanceof i;import N from"node:fs/promises";import I from"node:os";var j=async e=>{try{return await N.access(e),!0}catch{return!1}},d=e=>{let t=I.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};var _="tokens.json",h=1,b=384,C=448,A=s.object({version:s.literal(h).default(h),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),g=async()=>{let e=await k();return c.join(c.dirname(e.userProject),_)},v=async()=>{let e=await g(),t;try{t=await u.readFile(e,"utf-8")}catch{return null}let o;try{o=JSON.parse(t)}catch(n){throw new i(`Invalid JSON in the token store at ${d(e)}: ${n.message}
|
|
2
2
|
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let r=A.safeParse(o);if(!r.success)throw new i(`Invalid token store at ${d(e)}: ${s.prettifyError(r.error)}
|
|
3
|
-
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return r.data},x=async e=>{let t=await g(),o=c.dirname(t),r=c.dirname(o),n=c.dirname(r);for(let a of[n,r,o])await u.mkdir(a,{recursive:!0,mode:C}),await u.chmod(a,C);
|
|
3
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return r.data},x=async e=>{let t=await g(),o=c.dirname(t),r=c.dirname(o),n=c.dirname(r);for(let a of[n,r,o])await u.mkdir(a,{recursive:!0,mode:C}),await u.chmod(a,C);O(t,`${JSON.stringify(e,null,2)}
|
|
4
4
|
`,b),await u.chmod(t,b)},F=async(e,t)=>{let o=await v();await x({version:h,envs:{...o?.envs,[e]:t}})},H=async e=>{let t=await v();if(!t||!(e in t.envs))return;let o={...t.envs};delete o[e],await x({version:h,envs:o})};var M=()=>{let e="",t=[],o=!1;return{start(r){e=r,t=[],o=!1},setInteractive(){o=!0},addOption(r,n){t.push({flag:r,value:n})},formatOptions(){return t.map(r=>typeof r.value=="boolean"?r.value?r.flag:"":Array.isArray(r.value)?`${r.flag} "${r.value.join(", ")}"`:`${r.flag} "${r.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!o||t.length===0||!e||f.info(`\u{1F4DF} Equivalent command:
|
|
5
5
|
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
6
|
-
`)},reset(){e="",t=[],o=!1}}},w=M();import D from"node:process";var R=27,J=e=>{if(typeof e=="object")return e.value;throw new
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
`)},reset(){e="",t=[],o=!1}}},w=M();import D from"node:process";var R=27,J=e=>{if(typeof e=="object")return e.value;throw new y(void 0,{operation:"interactive prompt",remediation:e==="unreachable"?"this prompt is declared unreachable under MCP because a required field should block the path \u2014 reaching it means that field was relaxed without updating the call site":"pass the value explicitly instead of relying on the prompt \u2014 MCP runs have no human to answer it",stderrExcerpt:"an interactive prompt was reached under MCP, where stdin carries JSON-RPC"})},$=async(e,t)=>{let o=new AbortController,{whenHeadless:r="refuse",...n}=t??{},a={...n,signal:o.signal};if(T())return J(r);if(!D.stdin.isTTY)return e(a);let m=D.stdin,E=p=>{p.length===1&&p[0]===R&&o.abort()};S();try{let p=e(a);return m.isPaused()&&m.resume(),m.on("data",E),await p}finally{m.removeListener("data",E),P()}};import B from"@inquirer/confirm";import K from"node:process";var l=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},ue=e=>e instanceof l;var q=async(e,t,o={})=>{let r=e?!0:await $(n=>B({message:t},n),{whenHeadless:"refuse"});if(e||w.setInteractive(),!r){if(o.throwOnDecline)throw new l;f.info("Operation cancelled. Exiting..."),K.exit(0)}};export{i as a,L as b,j as c,d,g as e,v as f,F as g,H as h,w as i,ue as j,$ as k,q as l};
|
|
7
|
+
//# sourceMappingURL=chunk-YKCY657C.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as
|
|
2
|
+
import{$ as Jt,A as Pt,B as xt,C as Ct,D as ee,E as Et,F as D,G as m,H as bt,I as At,J as Dt,K as It,L as Lt,M as _t,N as Nt,O as Ot,P as Ft,Q as Mt,R as $t,S as jt,T as Ut,U as qt,V as te,W as Wt,X as Gt,Y as Vt,Z as Kt,_ as Ht,a as F,aa as Bt,b as ze,ba as Yt,c as Xe,ca as zt,da as Xt,e as Qe,ea as Qt,f as Ze,g as tt,ga as Zt,h as ot,ha as eo,i as M,ia as to,j as st,k as U,l as lt,m as dt,n as ut,o as mt,p as pt,q as ft,r as gt,s as ht,t as Z,u as vt,v as yt,w as wt,x as St,y as kt,z as Rt}from"./chunk-7YE5QKKB.js";import{b as et,c as b,d as h,e as $,f as rt,g as nt,h as it,i as P,k as j}from"./chunk-YKCY657C.js";import{p as oe}from"./chunk-KXQQUBGV.js";import{K as l,Q,R as Be,T as Ye,a as Ke,r as He}from"./chunk-63VNUKUS.js";import{u as Ve}from"./chunk-UI2MUEVR.js";import"./chunk-MFAFQVTW.js";import{a as re,b as ne,c as ie}from"./chunk-QS4JZKF2.js";import{a as Je}from"./chunk-MFLYORUJ.js";import{f as Ue,h as qe,j as We,l as O,m as Ge}from"./chunk-GYPVEWUV.js";import{a as N,b as Ne,d as Oe,g as Fe,h as Me,k as X,l as $e,p as w,s as je}from"./chunk-NFIFWIO6.js";import{a as Tt}from"./chunk-TVG47UHG.js";import{a as at,b as ct}from"./chunk-QWVLAZ6N.js";import Nn,{Separator as Ko}from"@inquirer/select";import{existsSync as On,realpathSync as Fn}from"node:fs";import{homedir as Mn}from"node:os";import g from"node:process";import{fileURLToPath as Jo}from"node:url";var Yo=(e,t)=>{let o=e,r;for(let n of t){if(r=o.find(s=>s.name()===n),!r)return;o=r.commands}return r},oo=e=>Xt.flatMap(({key:t,label:o})=>Zt(t).flatMap(r=>{let n=Yo(e,r.groupPath);return n?[{name:r.groupPath.join(" "),description:n.description(),group:o}]:[]}));import{Command as Cr}from"commander";import x from"node:process";import ro from"node:process";import{$ as zo}from"zx";var se=async()=>{let e=await Q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async a=>({...a,exists:await b(a.path)}))),o=t.at(-1)?.exists===!0,r=await wt(e.userProject,o),n=o?St(r):"";l.info(`Project name: ${e.projectName}
|
|
3
3
|
`),l.info(`Config merge chain (later overrides earlier):
|
|
4
|
-
`);for(let a of t){let i=a.exists?" [\u2713]":" [ ]",c=a.path===e.userProject&&n!==""?` ${n}`:"";l.info(`${i} ${a.label.padEnd(22)} ${h(a.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(a=>({label:a.label,path:a.path,exists:a.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},
|
|
5
|
-
`))},
|
|
6
|
-
`),
|
|
7
|
-
`;var B=(e,t=!0)=>({line:e,reproducible:t});import Y from"node:fs";import Sr from"node:os";import kr from"node:path";import go from"node:process";var z="INFRA_KIT_SESSION_REPORT",xe=null,mo=!1,po=[],ho=(e=go.env)=>{mo||(xe=e[z]??null,mo=!0,delete e[z])};var vo=(e,t)=>{if(!xe)return;let o=e.summary??(po.length>0?[...po]:void 0),r={...e,...o?{summary:o}:{}},n=t?.write??((s,a)=>{Y.writeFileSync(s,a)});try{n(xe,JSON.stringify(r))}catch{}},fo=0,yo=e=>{let t=e?.tmpdir?.()??Sr.tmpdir(),o=e?.pid??go.pid;return fo+=1,kr.join(t,`infra-kit-session-${o}-${fo}.json`)},wo=(e,t)=>{if(!(t?.exists??(a=>Y.existsSync(a)))(e))return null;let r=t?.read??(a=>Y.readFileSync(a,"utf-8")),n=t?.unlink??(a=>Y.unlinkSync(a)),s;try{s=r(e)}catch{return null}finally{try{n(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Ce=e=>{e.options.some(o=>o.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Ce)};var Pr=(e,t)=>[...t,e],So=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},xr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").action(async t=>{let o=await bt(()=>At({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));m(o),o.structuredContent.failedMerges>0&&(b.exitCode=1)}),Cr=e=>e.description("List all release branches").action(async()=>{m(await Ot())}),Er=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',Pr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(wt),n=r.length>0?r:void 0;m(await $t({releases:n,confirmedCommand:t.yes}))}),br=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await jt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),ko=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Dt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),Ar=e=>ko(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{m(await we({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Tr=e=>ko(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{m(await Se({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Dr=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Tt({version:t.version,confirmedCommand:t.yes}))}),Ir=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ut({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),Lr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Bt({confirmedCommand:t.yes}))}),_r=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=So(t.ide,"--ide")??So(t.cursor,"--cursor");m(await Kt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Nr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Ht())}),Or=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{m(await Jt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Mr=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{m(await qt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),Fr=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{m(await Pe({init:t.init}))}),$r=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Wt();m(t),t.structuredContent.ok||(b.exitCode=1)}),jr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await ae())}),Ur=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await ce())}),qr=new Set(["setup","doctor","version","dev","mcp"]),Gr=e=>e.startsWith("env-")||qr.has(e),Wr=new Set(["env-autoload","mcp","version"]),X=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Ee=()=>{let e=new Rr,t=e.command("release").description("Release management commands");xr(t.command("merge-dev")),Cr(t.command("list")),Er(t.command("create")),br(t.command("desc-edit")),Ar(t.command("deploy-all")),Tr(t.command("deploy-selected")),Dr(t.command("deliver")),Ir(t.command("remove"));let o=e.command("worktrees").description("Git worktree management commands");_r(o.command("add")),Nr(o.command("list")),Or(o.command("remove")),Lr(o.command("sync")),Mr(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");jr(r.command("path")),Ur(r.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{m(await qe())});let n=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=i=>i.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(n.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async i=>{m(await J({env:i.env,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"all"))}),s(n.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async i=>{m(await J({env:i.env,services:i.service,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async i=>{if(i.design&&!i.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),b.exitCode=1;return}let c=await Ue({all:i.all,root:i.root,fix:i.fix,design:i.design});m(c);let{allPassed:u,fixed:d}=c.structuredContent,p=(d??[]).some(y=>y.action==="failed");(!u||p)&&(b.exitCode=1)});let a=e.command("vendor").description("Verify the mirrored vendor/ tree");return $r(a.command("check")),Fr(a.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async i=>{let c=await St({fix:!!i.fix});D.enabled||Ve(c.structuredContent.checks,{ascii:!!i.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(b.exitCode=1),m(c)}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(i,c)=>{let{runDevServerCli:u}=await import("./dev-server.js"),d=!!(b.stdout.isTTY&&b.stdin.isTTY);await u({...c,preset:i},d,D.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{m(await We())}),e.command("setup").description("Set this machine up: shell integration, agent files, MCP server, then the external tools").option("--tools <ids...>","Limit to these tools (brew, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").action(async i=>{m(await Gt({tools:i.tools,update:i.update,skipTools:i.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Vt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Pt())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{m(await Rt())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async i=>{m(await at({config:i.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async i=>{m(await kt({purge:!!i.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(i,c)=>{m(await he({env:i,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async i=>{m(await xt({check:!!i.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async i=>{m(await fe({env:i}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async i=>{await pe({projectDir:i.projectDir})}),e.commands.forEach(Ct),Ce(e),e.hook("preAction",async(i,c)=>{P.start(X(c)),D.enabled=!!c.optsWithGlobals().json,D.enabled&&(l.level="warn"),Wr.has(X(c))||await pt(),W(),Gr(c.name())||await _({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(i,c)=>{let u=X(c);if(Qt(u))return;let p=P.snapshot()?.formattedOptions??"",y=p?` ${p}`:"",R=`infra-kit ${u}${y}`;vo({equivalent:B(R,!0)})}),e};var be=(e,t=" ")=>{let o=e.reduce((r,[n])=>Math.max(r,n.length),0);return e.map(([r,n])=>`${r.padEnd(o)}${t}${n}`)};import{chalkStderr as un}from"chalk";import{spawn as mn}from"node:child_process";import v from"node:process";import{Chalk as Vr}from"chalk";var A=new Vr({level:1}),k={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},Kr={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Ro={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Po={unicode:"\u2500",ascii:"-"},Hr=3,Ae=e=>e,Jr={ok:e=>A.green(e),findings:e=>A.yellow(e),failed:e=>A.red(e),cancelled:e=>A.gray(e)},De=e=>e?{dim:t=>A.dim(t),bold:t=>A.bold(t)}:{dim:Ae,bold:Ae},Br=(e,t)=>e?Jr[t]:Ae,Te=e=>[...e].length,Yr=(e,t)=>{if(t==null)return e;let o=Math.max(0,t-1);return Te(e)<=o?e:[...e].slice(0,o).join("")},xo=e=>{let t=De(e.color===!0).dim,o=Kr[e.canSuspend?"suspend":"plain"],r=e.ascii===!0?o.ascii:o.unicode;return t(Yr(r,e.width))},Co=(e,t={})=>{let o=De(t.color===!0);return`${o.dim(k.reproPrefix.trim())} ${o.bold(e)}`},zr=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Xr=(e,t)=>e==="findings"?t!=null?`${t} ${k.findingsSuffix}`:k.findingsPlain:{ok:k.ok,failed:k.failed,cancelled:k.cancelled}[e],Qr=(e,t,o,r)=>{if(t==null)return"";let n=t-2-e;return n<Hr?"":` ${r(o.repeat(n))}`},Eo=e=>{let t=e.color===!0,o=De(t),r=Br(t,e.outcome),n=e.ascii===!0,s=e.equivalent.reproducible?k.reproPrefix:k.nonReproPrefix,a=n?Ro[e.outcome].ascii:Ro[e.outcome].unicode,i=Xr(e.outcome,e.findingsCount),c=[zr(e.durationMs)],u=e.summary?.[0]?.split(`
|
|
8
|
-
`)[0];u!=null&&u.length>0&&c.push(u);let d=`${a} ${i}`,p=`${k.sep}${c.join(k.sep)}`,y=Te(d)+Te(p),R=Qr(y,e.width,n?Po.ascii:Po.unicode,o.dim),C=[`${r(d)}${o.dim(p)}${R}`];return e.showEquivalent!==!1&&C.unshift(`${o.dim(s.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&C.push(o.dim(k.envNotice)),C.join(`
|
|
9
|
-
`)
|
|
10
|
-
|
|
4
|
+
`);for(let a of t){let i=a.exists?" [\u2713]":" [ ]",c=a.path===e.userProject&&n!==""?` ${n}`:"";l.info(`${i} ${a.label.padEnd(22)} ${h(a.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(a=>({label:a.label,path:a.path,exists:a.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},ae=async()=>{let e=await Q(),t=ro.env.EDITOR||ro.env.VISUAL||"vi",o=await ft(e);o.createdConfig&&l.info(gt(o)),l.info(`Opening ${h(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await zo({stdio:"inherit"})`${t} ${e.userProject}`,Ye();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var ce=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},I=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import f from"node:fs";import S from"node:path";import L from"node:process";var Xo="autoload-warn-fail.flag",le="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",Qo=3e4,io=async(e=!0)=>{let t;try{t=await Be()}catch{return null}let o=t.envAutoLoad;if(!o)return null;let r={trigger:o.trigger,config:o.config,project:t.envManagement.config.name};try{if(await st(o.config))return r}catch{return r}return ao({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&q(I(o.config),le),null},so=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:n,env:s,force:a}=e;return t!==o||!s.session||s.cleared||s.currentConfig&&!s.autoLoadedMarker||!a&&s.autoLoadedMarker&&s.currentConfig===r&&s.currentProject===n?"skip":"load"},_=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=et})=>{let n=e==="cli-invocation";n&&W();let s=null;try{if(s=await io(n),!s||so({trigger:s.trigger,expectedTrigger:e,targetConfig:s.config,targetProject:s.project,env:tr(),force:o})==="skip"||no()||nr())return null;let i=or(),c=await lt({config:s.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!no()&&!rr(i)});return c?(sr(),er(),c.filePath):null}catch(a){let i=a.message,c=r(a);return ir(),c&&s&&ao({config:s.config,reason:i,at:Date.now()}),n&&c&&s?(q(I(s.config),le),l.debug(`env auto-load auth failure: ${i}`)):n?q(`infra-kit: env auto-load failed \u2014 ${i} (will retry later)`,Xo):l.debug(`env auto-load skipped: ${i}`),null}},W=()=>{let e=Zo();e&&(q(I(e.config),le),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Zo=()=>{try{let e=f.readFileSync(S.join(w(),ue),"utf-8");return ce(JSON.parse(e))}catch{return null}},ao=e=>{try{let t=w();f.mkdirSync(t,{recursive:!0,mode:448}),je(S.join(t,ue),JSON.stringify(e),384)}catch{}},er=()=>{try{f.rmSync(S.join(w(),ue),{force:!0})}catch{}},tr=()=>({session:L.env[Oe],cleared:L.env[$e],currentConfig:L.env[Fe],currentProject:L.env[Me],autoLoadedMarker:L.env[X]}),or=()=>{try{return f.statSync(S.join(w(),N)).mtimeMs}catch{return null}},rr=e=>{try{let t=S.join(w(),N);if(!f.existsSync(t))return!1;let o=f.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${X}$`,"m").test(f.readFileSync(t,"utf-8"))}catch{return!1}},no=()=>{try{let e=w(),t=S.join(e,Ne);if(!f.existsSync(t))return!1;let o=S.join(e,N);return f.existsSync(o)?f.statSync(t).mtimeMs>=f.statSync(o).mtimeMs:!0}catch{return!1}},nr=()=>{try{let e=S.join(w(),de);return f.existsSync(e)?Date.now()-f.statSync(e).mtimeMs<Qo:!1}catch{return!1}},ir=()=>{try{let e=w();f.mkdirSync(e,{recursive:!0,mode:448}),f.writeFileSync(S.join(e,de),"",{mode:384})}catch{}},sr=()=>{try{f.rmSync(S.join(w(),de),{force:!0})}catch{}},q=(e,t)=>{try{let o=w(),r=S.join(o,t);if(f.existsSync(r))return;f.mkdirSync(o,{recursive:!0,mode:448}),f.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var me=async({projectDir:e}={})=>{await _({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var co="https://dashboard.doppler.com/workplace/projects",ar=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${co}/${e}`],pe=async({env:e})=>{let o=!!(await rt())?.envs[e];await it(e);let r=await U(),n=await M(),s=await $();o?l.info(`Removed the "${e}" service token from ${h(s)}.`):l.info(`No "${e}" service token was stored in ${h(s)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let i of ar(n,e))l.warn(i);let a={env:e,removed:o,storePath:s,warmCachesPurged:r.length,revokeUrl:`${co}/${n}`};return{content:F(JSON.stringify(a,null,2)),structuredContent:a}};import cr from"@inquirer/password";import V from"node:process";import{$ as G}from"zx";var lr=async({stdin:e,fromEnv:t})=>{if(e)return{token:await dr(),source:"stdin"};if(t){let r=V.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return P.setInteractive(),{token:(await j(r=>cr({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:V.stderr})).trim(),source:"prompt"}},dr=async()=>{let e=[];V.stdin.setEncoding("utf8");for await(let t of V.stdin)e.push(t);return e.join("").trim()},fe="DOPPLER_CONFIG",ur=3e4,mr=async(e,t,o)=>{let r=G.quiet;G.quiet=!0;let n;try{n=(await G({env:ut(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(ur)).stdout}catch(s){throw pr(s,o)}finally{G.quiet=r}return pt(n)},pr=(e,t)=>{let o=Ke(e)??(e instanceof Error?e.message:String(e));if(tt(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=ot(o)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${r}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
|
|
5
|
+
`))},fr=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${fe}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
|
|
6
|
+
`),ge=async({env:e,stdin:t,fromEnv:o,force:r})=>{let n=await M(),{token:s,source:a}=await lr({stdin:t,fromEnv:o});if(!s)throw new Error("No token provided \u2014 nothing was written.");let i=await mr(s,n,e);mt(i,e);let c=i.some(([y])=>y===fe);if(!c&&!r)throw new Error(fr(e));await nt(e,s);let u=await U(),d=await $();l.info(`Stored the "${e}" service token (${ee(s)}) in ${h(d)} (mode 0600).`),c||l.warn(`Scope was NOT verified (no ${fe} in the payload) \u2014 written because --force was given.`),u.length>0&&l.info(`Purged ${u.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let p={env:e,source:a,redactedToken:ee(s),storePath:d,scopeVerified:c,warmCachesPurged:u.length};return P.print(),{content:F(JSON.stringify(p,null,2)),structuredContent:p}};import{spawn as gr}from"node:child_process";import K from"node:process";import{fileURLToPath as hr}from"node:url";var vr=["SIGINT","SIGTERM"],lo=()=>hr(new URL("./mcp.js",import.meta.url)),he=(e={})=>{let t=e.spawn??gr,o=e.exit??(a=>K.exit(a)),r=e.env??K.env,n=e.onError??(a=>l.error(a)),s=t(K.execPath,[lo()],{stdio:"inherit",env:Ge(r)});s.on("error",a=>{n(`failed to launch the MCP server: ${a.message}`),o(1)}),vr.forEach(a=>{K.on(a,()=>{s.kill(a)})}),s.on("exit",(a,i)=>{o(i?1:a??1)})};var ve=async(e,t,o=!0)=>{let{from:r,version:n,env:s,services:a,skipTerraform:i,yes:c,dryRun:u,printEnv:d}=e,p=await Nt(r);return o&&P.addOption("--from",p),_t(p,{"--version":n,"--skip-terraform":i,"--dry-run":u,"--print-env":d}),p==="local"?t==="all"?$t({env:s,confirmedCommand:c,dryRun:u,printEnv:d}):jt({env:s,service:a,confirmedCommand:c,dryRun:u,printEnv:d}):t==="all"?Ot({version:n,env:s,skipTerraform:i,confirmedCommand:c}):Ft({version:n,env:s,services:a,skipTerraform:i,confirmedCommand:c})},ye=async e=>ve(e,"all"),we=async e=>ve(e,"selected"),H=async(e,t)=>{let o=`release deploy-${t} --from local`;return l.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${o}\` instead.`),ve({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as mo}from"@slip-stream-kit/config/internal";import Se from"node:fs/promises";import ke from"node:path";import uo from"node:process";import{pathToFileURL as yr}from"node:url";var po="~/projects",Re=async(e={})=>{if(e.init){await Sr(e.cwd);return}await wr()},wr=async()=>{let e=Z(),t=await b(e);if(l.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),uo.exitCode=1;return}let{workspaceDir:o,targets:r}=await yt(),n=vt(o),s=await b(n);l.info(`workspaceDir: ${o} (resolved: ${n}) ${s?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let a=s;for(let i of r){let c=ke.join(n,i),u=await b(c);u||(a=!1);let d=u?"[\u2713]":"[ ]",p=u?"":" (not found \u2014 clone or remove)";l.info(` ${d} ${i} ${h(c)}${p}`)}a||(uo.exitCode=1)},Sr=async e=>{let t=Z();if(await b(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await He(),r=await kr(o);await Se.mkdir(ke.dirname(t),{recursive:!0}),await Se.writeFile(t,Rr(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${mo}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${po}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},kr=async e=>{try{let t=ke.join(e,mo),o=await Se.stat(t),s=(await import(`${yr(t).href}?mtime=${Number(o.mtimeMs)}`)).default,a=typeof s=="function"?await s():s;if(a&&typeof a=="object"&&"targets"in a){let i=a.targets;if(Array.isArray(i)&&i.every(c=>typeof c=="string"))return i}}catch{}return[]},Rr=e=>`${JSON.stringify({workspaceDir:po,targets:e},null,2)}
|
|
7
|
+
`;var J=(e,t=!0)=>({line:e,reproducible:t});import B from"node:fs";import Pr from"node:os";import xr from"node:path";import vo from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Pe=null,fo=!1,go=[],yo=(e=vo.env)=>{fo||(Pe=e[Y]??null,fo=!0,delete e[Y])};var wo=(e,t)=>{if(!Pe)return;let o=e.summary??(go.length>0?[...go]:void 0),r={...e,...o?{summary:o}:{}},n=t?.write??((s,a)=>{B.writeFileSync(s,a)});try{n(Pe,JSON.stringify(r))}catch{}},ho=0,So=e=>{let t=e?.tmpdir?.()??Pr.tmpdir(),o=e?.pid??vo.pid;return ho+=1,xr.join(t,`infra-kit-session-${o}-${ho}.json`)},ko=(e,t)=>{if(!(t?.exists??(a=>B.existsSync(a)))(e))return null;let r=t?.read??(a=>B.readFileSync(a,"utf-8")),n=t?.unlink??(a=>B.unlinkSync(a)),s;try{s=r(e)}catch{return null}finally{try{n(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var xe=e=>{e.options.some(o=>o.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(xe)};var Er=(e,t)=>[...t,e],Ro=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&te.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${te.join(", ")}.`)}},br=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").action(async t=>{let o=await At(()=>Dt({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));m(o),o.structuredContent.failedMerges>0&&(x.exitCode=1)}),Po=e=>(x.stdout.write(`${e.structuredContent.filePath}
|
|
8
|
+
`),m(e)),Tr=e=>e.description("List all release branches").action(async()=>{m(await Mt())}),Ar=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',Er,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),n=r.length>0?r:void 0;m(await Ut({releases:n,confirmedCommand:t.yes}))}),Dr=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await qt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),xo=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Lt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),Ir=e=>xo(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{m(await ye({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Lr=e=>xo(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{m(await we({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),_r=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await It({version:t.version,confirmedCommand:t.yes}))}),Nr=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Wt({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),Or=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await zt({confirmedCommand:t.yes}))}),Fr=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=Ro(t.ide,"--ide")??Ro(t.cursor,"--cursor");m(await Jt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Mr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Bt())}),$r=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{m(await Yt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),jr=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{m(await Gt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),Ur=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{m(await Re({init:t.init}))}),qr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Kt();m(t),t.structuredContent.ok||(x.exitCode=1)}),Wr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await se())}),Gr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await ae())}),Vr=new Set(["setup","doctor","version","dev","mcp"]),Kr=e=>e.startsWith("env-")||Vr.has(e),Hr=new Set(["env-autoload","mcp","version"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Ce=()=>{let e=new Cr,t=e.command("release").description("Release management commands");br(t.command("merge-dev")),Tr(t.command("list")),Ar(t.command("create")),Dr(t.command("desc-edit")),Ir(t.command("deploy-all")),Lr(t.command("deploy-selected")),_r(t.command("deliver")),Nr(t.command("remove"));let o=e.command("worktrees").description("Git worktree management commands");Fr(o.command("add")),Mr(o.command("list")),$r(o.command("remove")),Or(o.command("sync")),jr(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");Wr(r.command("path")),Gr(r.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{m(await Xe())});let n=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=i=>i.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(n.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async i=>{m(await H({env:i.env,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"all"))}),s(n.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async i=>{m(await H({env:i.env,services:i.service,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async i=>{if(i.design&&!i.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),x.exitCode=1;return}let c=await ze({all:i.all,root:i.root,fix:i.fix,design:i.design});m(c);let{allPassed:u,fixed:d}=c.structuredContent,p=(d??[]).some(y=>y.action==="failed");(!u||p)&&(x.exitCode=1)});let a=e.command("vendor").description("Verify the mirrored vendor/ tree");return qr(a.command("check")),Ur(a.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async i=>{let c=await Rt({fix:!!i.fix});D.enabled||Ze(c.structuredContent.checks,{ascii:!!i.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(x.exitCode=1),m(c)}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{he()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(i,c)=>{let{runDevServerCli:u}=await import("./dev-server.js"),d=!!(x.stdout.isTTY&&x.stdin.isTTY);await u({...c,preset:i},d,D.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{m(await Qe())}),e.command("setup").description("Set this machine up: shell integration, agent files, MCP server, then the external tools").option("--tools <ids...>","Limit to these tools (brew, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").action(async i=>{m(await Vt({tools:i.tools,update:i.update,skipTools:i.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Ht())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Ct())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{m(await xt())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async i=>{Po(await dt({config:i.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async i=>{Po(await Pt({purge:!!i.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(i,c)=>{m(await ge({env:i,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async i=>{m(await Et({check:!!i.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async i=>{m(await pe({env:i}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async i=>{await me({projectDir:i.projectDir})}),e.commands.forEach(bt),xe(e),e.hook("preAction",async(i,c)=>{P.start(z(c)),D.enabled=!!c.optsWithGlobals().json,D.enabled&&(l.level="warn"),Hr.has(z(c))||await ht(),W(),Kr(c.name())||await _({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(i,c)=>{let u=z(c);if(eo(u))return;let p=P.snapshot()?.formattedOptions??"",y=p?` ${p}`:"",R=`infra-kit ${u}${y}`;wo({equivalent:J(R,!0)})}),e};var Ee=(e,t=" ")=>{let o=e.reduce((r,[n])=>Math.max(r,n.length),0);return e.map(([r,n])=>`${r.padEnd(o)}${t}${n}`)};import{chalkStderr as fn}from"chalk";import{spawn as gn}from"node:child_process";import v from"node:process";import{Chalk as Jr}from"chalk";var T=new Jr({level:1}),k={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},Br={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Co={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Eo={unicode:"\u2500",ascii:"-"},Yr=3,be=e=>e,zr={ok:e=>T.green(e),findings:e=>T.yellow(e),failed:e=>T.red(e),cancelled:e=>T.gray(e)},Ae=e=>e?{dim:t=>T.dim(t),bold:t=>T.bold(t)}:{dim:be,bold:be},Xr=(e,t)=>e?zr[t]:be,Te=e=>[...e].length,Qr=(e,t)=>{if(t==null)return e;let o=Math.max(0,t-1);return Te(e)<=o?e:[...e].slice(0,o).join("")},bo=e=>{let t=Ae(e.color===!0).dim,o=Br[e.canSuspend?"suspend":"plain"],r=e.ascii===!0?o.ascii:o.unicode;return t(Qr(r,e.width))},To=(e,t={})=>{let o=Ae(t.color===!0);return`${o.dim(k.reproPrefix.trim())} ${o.bold(e)}`},Zr=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,en=(e,t)=>e==="findings"?t!=null?`${t} ${k.findingsSuffix}`:k.findingsPlain:{ok:k.ok,failed:k.failed,cancelled:k.cancelled}[e],tn=(e,t,o,r)=>{if(t==null)return"";let n=t-2-e;return n<Yr?"":` ${r(o.repeat(n))}`},Ao=e=>{let t=e.color===!0,o=Ae(t),r=Xr(t,e.outcome),n=e.ascii===!0,s=e.equivalent.reproducible?k.reproPrefix:k.nonReproPrefix,a=n?Co[e.outcome].ascii:Co[e.outcome].unicode,i=en(e.outcome,e.findingsCount),c=[Zr(e.durationMs)],u=e.summary?.[0]?.split(`
|
|
9
|
+
`)[0];u!=null&&u.length>0&&c.push(u);let d=`${a} ${i}`,p=`${k.sep}${c.join(k.sep)}`,y=Te(d)+Te(p),R=tn(y,e.width,n?Eo.ascii:Eo.unicode,o.dim),E=[`${r(d)}${o.dim(p)}${R}`];return e.showEquivalent!==!1&&E.unshift(`${o.dim(s.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&E.push(o.dim(k.envNotice)),E.join(`
|
|
10
|
+
`)};var on=new Set([130,143]),Do=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&on.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import rn from"node:process";var nn={3:"quit",4:"quit",26:"suspend",27:"quit"},sn=e=>{if(e.length!==1)return"continue";let t=typeof e=="string"?e.charCodeAt(0):e[0];return t===void 0||Number.isNaN(t)?"continue":nn[t]??"continue"},an=150,cn="\r\x1B[2K",ln=`\r
|
|
11
|
+
`,Io=(e,t)=>{Lo(e),e.stdin.on("data",t),e.listener=t},Lo=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},_o=(e,t)=>{at(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Io(e,t)},No=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(cn)),Lo(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),ct()},dn=e=>{e.settled||(e.settled=!0,No(e))},Oo=(e,t)=>{let o=bo({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(t+o),e.hintOnScreen=!0},un=async e=>{await new Promise(t=>{setTimeout(t,e)})},mn=(e,t,o)=>{No(e),t(),_o(e,o),Oo(e,ln)},pn=async e=>new Promise(t=>{let o=r=>{let n=sn(r),s=e.deps.suspend;if(n==="quit"){t("quit");return}if(n==="suspend"&&s!==void 0){mn(e,s,o);return}t("palette")};Io(e,o),Oo(e,"")}),Fo=async(e,t)=>{if(e.quitRequested())return"quit";let o=t.stdin??rn.stdin;if(o.isTTY!==!0)return"palette";let r={deps:t,stdin:o,listener:null,hintOnScreen:!1,settled:!1};try{return _o(r,()=>{}),e.armed(),await un(t.drainMs??an),await pn(r)}finally{dn(r)}};import Mo from"node:process";var C={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},$o=(e,t)=>{let o=t?.write??(s=>{Mo.stderr.write(s)}),r=t?.stdin??Mo.stdin,n=[C.saveCursor,C.scrollRegion,C.restoreCursor,C.column,C.sgr,C.cursor,C.wrap];e.entersAltScreen===!0&&n.push(C.primaryBuffer),o(n.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var jo=e=>`infra-kit ${e.groupPath.join(" ")}`,hn=()=>{vn();let e=v.stderr.columns;return e!=null&&e>0?e:void 0},vn=()=>{let e=v.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},yn=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),wn=async(e,t,o)=>{let r=So(),n={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),a={code:1,signal:null};o();try{let p=t.spawn(v.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:n});a=await yn(p)}catch{a={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let i=ko(r),c=Do(a.code,a.signal,i!=null,e.longRunning),u=jo(e),d=i?.equivalent??J(u,!0);return Ao({equivalent:d,outcome:c,durationMs:t.now()-s,summary:i?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===u)})},Sn=1e3,kn=(e,t)=>e!=null&&t-e<=Sn,De=e=>{e.resetTerminal(),e.exit(0)},Rn=(e,t)=>{let o=null,r=!1,n=()=>{let c=e();if(c==="child"){o=t.now();return}c!=="pause"&&De(t)},s=()=>{let c=e();if(c==="palette"){De(t);return}if(!kn(o,t.now())){if(c==="pause"){De(t);return}r=!0}},a=()=>{t.exit(129)},i=()=>{e()==="child"&&t.raise("SIGSTOP")};return t.register("SIGINT",n),t.register("SIGTERM",s),t.register("SIGHUP",a),t.register("SIGTSTP",i),{dispose:()=>{t.unregister("SIGINT",n),t.unregister("SIGTERM",s),t.unregister("SIGHUP",a),t.unregister("SIGTSTP",i)},childStarted:()=>{o=null},quitRequested:()=>r}},Uo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Pn=v.platform==="win32"?void 0:()=>{Tt()},xn=(e,t)=>o=>Fo(o,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:Pn}),qo=async(e,t)=>{let o={spawn:t.spawn??gn,now:t.now??(()=>Date.now()),env:t.env??v.env,cliPath:t.cliPath,ascii:t.ascii??!(v.stdout.isTTY&&v.env.TERM!=="dumb"),color:t.color??fn.level>0,columns:t.columns??hn,resetTerminal:t.resetTerminal??(d=>{$o(d)})},r=t.write??(d=>v.stderr.write(d)),n="palette",s=t.signals??{register:(d,p)=>{v.on(d,p)},unregister:(d,p)=>{v.off(d,p)},exit:d=>{v.exit(d)},raise:d=>{v.kill(v.pid,d)},now:()=>Date.now(),resetTerminal:()=>{n==="pause"&&r("\r\x1B[2K"),o.resetTerminal({entersAltScreen:!1})}},a={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},i=t.installSignals===!1?a:Rn(()=>n,s),c={armed:()=>{n="pause"},quitRequested:()=>i.quitRequested()},u=t.afterRun??xn(r,o);try{for(;;){if(i.quitRequested())return;n="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let y=To(jo(p),{color:o.color});r(`
|
|
11
12
|
${y}
|
|
12
|
-
`),i.childStarted();let R=await
|
|
13
|
+
`),i.childStarted();let R=await wn(p,o,()=>{n="child"});if(r(`
|
|
13
14
|
${R}
|
|
14
|
-
`),await u(c)==="quit")return}}finally{i.dispose()}};import{spawn as
|
|
15
|
+
`),await u(c)==="quit")return}}finally{i.dispose()}};import{spawn as bn}from"node:child_process";import Go from"node:fs";import A from"node:process";import{fileURLToPath as Vo}from"node:url";var Wo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Cn=new Set(["mcp"]),En=e=>e[2]!=null&&Cn.has(e[2]),Ie=e=>{let{argv:t,env:o,isTty:r,selfRealPath:n,cwd:s,realpath:a}=e;return Wo.some(c=>{let u=o[c];return u!=null&&u!==""})?"opt-out":t.includes("--json")?"json":En(t)?"own-command":r?qe(n,s,a)?"local-install":null:"not-a-tty"};var Tn=e=>{bn(A.execPath,[e,"--parent-pid",String(A.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},An=()=>Vo(new URL("./update-check.js",import.meta.url)),Dn=()=>Go.realpathSync(Vo(new URL("./cli.js",import.meta.url))),In=/^[\w@./+ -]+$/i,Ln=e=>In.test(e),_n=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||re(e.latestVersion,t)&&e.updateCommand.every(Ln)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ue(e.updateCommand)}`)},Le=(e,t={})=>{try{let o=t.argv??A.argv,r=t.env??A.env,n=t.isTty??!!A.stdout.isTTY,s=t.cwd??A.cwd(),a=t.nowMs??Date.now(),i=t.selfRealPath??Dn(),c=t.readCache??ne,u=t.spawnChild??Tn,d=t.fileExists??(E=>Go.existsSync(E)),p=t.notify??(E=>{l.info(E)});if(Ie({argv:o,env:r,isTty:n,selfRealPath:i,cwd:s,realpath:O})!==null)return;let y=c();if(_n(y,e,p),!ie(y,a))return;let R=t.childPath??An();if(!d(R))return;u(R)}catch{}};to();yo();var _e=Ce(),Ho=async e=>{try{e?await _e.parseAsync(e):await _e.parseAsync()}catch(t){oe(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},$n=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;We({selfRealPath:Fn(Jo(import.meta.url)),cwd:g.cwd(),env:g.env,realpath:O,home:Mn(),exists:On})&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};$n();Ve((e,t)=>{l.debug(e,t)});Le(Je.version);var Bo=()=>oo(_e.commands),jn=async()=>{let e=Bo(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-BL4EQMZV.js");t=await o(e)}else{let o=Ee(e.map(n=>[n.name,n.description])),r=e.flatMap((n,s)=>[...e[s-1]?.group===n.group?[]:[new Ko(" "),new Ko(`\u2014 ${n.group} \u2014`)],{name:o[s]??n.name,value:n.name}]);t=await j(n=>Nn({message:"Select a command to run",choices:r},n),{output:g.stderr})}}catch(o){if(!oe(o))throw o}return t},Un=async()=>{let{runCommandPalette:e}=await import("./boot-BL4EQMZV.js"),t=Jo(import.meta.url),o=new Map(Qt.map(r=>[r.groupPath.join(" "),r]));await qo(Bo(),{renderPalette:e,resolveCommand:r=>{let n=o.get(r);return n?{groupPath:n.groupPath,entersAltScreen:n.entersAltScreen,sessionEnvNotice:n.sessionEnvNotice,longRunning:n.longRunning}:void 0},cliPath:t})};if(g.argv.length<=2){let e={stdoutIsTTY:!!g.stdout.isTTY,stdinIsTTY:!!g.stdin.isTTY,stderrIsTTY:!!g.stderr.isTTY};if(Uo(g.env,e))await Un();else{let t=await jn();t&&await Ho(["node","infra-kit",...t.split(" ")])}}else await Ho();
|
|
15
16
|
//# sourceMappingURL=cli.js.map
|