infra-kit 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/boot-EEEVHAMO.js +2 -0
  2. package/dist/boot-EEEVHAMO.js.map +7 -0
  3. package/dist/{chunk-V4XK2YEH.js → chunk-7F5YKMWK.js} +2 -2
  4. package/dist/chunk-7F5YKMWK.js.map +7 -0
  5. package/dist/chunk-AJW5M44V.js +231 -0
  6. package/dist/chunk-AJW5M44V.js.map +7 -0
  7. package/dist/{chunk-JPTSUMWI.js → chunk-FTCM2766.js} +2 -2
  8. package/dist/{chunk-JPTSUMWI.js.map → chunk-FTCM2766.js.map} +1 -1
  9. package/dist/chunk-IPF7ILCB.js +7 -0
  10. package/dist/{chunk-KAKTWDWJ.js.map → chunk-IPF7ILCB.js.map} +4 -4
  11. package/dist/{chunk-AVLZBOOA.js → chunk-KHEUED4B.js} +1 -1
  12. package/dist/chunk-KHEUED4B.js.map +7 -0
  13. package/dist/chunk-NLOLELZ5.js +6 -0
  14. package/dist/chunk-NLOLELZ5.js.map +7 -0
  15. package/dist/cli.js +9 -9
  16. package/dist/cli.js.map +3 -3
  17. package/dist/dev-server.js +39 -25
  18. package/dist/dev-server.js.map +4 -4
  19. package/dist/dev-wizard-run-5NOQIMR5.js +2 -0
  20. package/dist/dev-wizard-run-5NOQIMR5.js.map +7 -0
  21. package/dist/mcp.js +1 -1
  22. package/dist/mcp.js.map +3 -3
  23. package/dist/persistent-ink-dev-ui-TLUJJC2D.js +2 -0
  24. package/dist/persistent-ink-dev-ui-TLUJJC2D.js.map +7 -0
  25. package/dist/update-check.js +1 -1
  26. package/package.json +1 -1
  27. package/dist/boot-YQAPYAKT.js +0 -2
  28. package/dist/boot-YQAPYAKT.js.map +0 -7
  29. package/dist/chunk-AVLZBOOA.js.map +0 -7
  30. package/dist/chunk-KAKTWDWJ.js +0 -7
  31. package/dist/chunk-TI33V5G2.js +0 -6
  32. package/dist/chunk-TI33V5G2.js.map +0 -7
  33. package/dist/chunk-TL7LO2FF.js +0 -231
  34. package/dist/chunk-TL7LO2FF.js.map +0 -7
  35. package/dist/chunk-V4XK2YEH.js.map +0 -7
  36. package/dist/dev-wizard-run-2ISRQPGA.js +0 -2
  37. package/dist/dev-wizard-run-2ISRQPGA.js.map +0 -7
  38. package/dist/persistent-ink-dev-ui-KOI44ZVT.js +0 -2
  39. package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +0 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/render.ts"],
4
+ "sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI).\n *\n * The boot collapses into a single transient spinner; the final screen is a STATUS PANEL, one row per\n * server, carrying health, uptime, requests/min, restarts and an error count. There is no log tail:\n * every line \u2014 framework output, request logs, a handler's own `console.log` \u2014 is written to that\n * service's file under `<cacheRoot>/<session>/dev/<pid>/` and never printed. What still appears above\n * the panel is only what the RUNNER says: a restart, an unhealthy app, a dead engine.\n *\n * The panel's live fields are the reason it is a status surface and not a screenshot. With nothing\n * scrolling beside it, a panel whose numbers never move cannot be told apart from a hung process.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable and\n * the spinner is deterministically disabled in tests (`isTTY: false`).\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/**\n * Per-call options for {@link DevRenderer.log}.\n *\n * `tee: false` exists for exactly one caller: `DevServerRunner.reportFault`, which files the fault into the\n * sink ITSELF (at `error` level \u2014 that is what turns the panel row red) and then prints it. Without this\n * opt-out the print tees a SECOND copy into the same `runner.log`, so every fault is filed twice \u2014 a\n * literal 2\u00D7 amplifier sitting at the centre of the loop that wrote 455 GB.\n */\nexport interface LogOptions {\n /** Also append the line to the log file. Default `true`; `false` prints without filing. */\n tee?: boolean\n}\n\n/**\n * A row's liveness, as the runner's probe state machine resolved it.\n *\n * Five arms, not a boolean, because a probe has three outcomes and a row has a history. The two that\n * are neither `ok` nor `down` are the honest ones: a UI that has never answered yet is `starting`\n * (vite is spawned after the ready frame, so red would be a lie for the first seconds), and a port that\n * answers something OTHER than vite's ping is `unverified` \u2014 a squatter, a shadowing proxy, or a future\n * vite that dropped the endpoint are all consistent with that, and only one of them is broken. Red must\n * stay a PROOF of failure, so `unverified` renders a question mark and never a red dot.\n */\nexport type HealthState = 'ok' | 'down' | 'starting' | 'unverified' | 'unknown'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/**\n * One server's row on the status panel.\n *\n * The live fields below are what make the panel a STATUS surface rather than a screenshot. The terminal\n * no longer carries a log tail, so a static row would leave \"quiet\" indistinguishable from \"hung\" \u2014 the\n * moving numbers are the liveness tell, and they are not decoration.\n */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness, as {@link HealthState} defines it; `unknown` renders no dot at all (nothing to probe). */\n health: HealthState\n /** Milliseconds since this server last (re)started. Omitted on the boot frame. */\n uptimeMs?: number\n /** Watch-triggered restarts so far this session. */\n restarts?: number\n /** Requests served in the last 60s. */\n rpm?: number\n /**\n * Errors this service has declared since boot \u2014 a 5xx, a `console.error`, a framework failure line.\n * This is the ONLY error signal the user gets now that nothing prints, so a row that cannot count is\n * a row that lies. A COUNT, never a classification: it is incremented from the level the emitter\n * declared, never from anything read out of the line's text.\n */\n errors?: number\n}\n\n/**\n * A UI app whose URL the runner does not own, so it streams its own below \u2014 referenced, never given a\n * (fabricated) endpoint row. The fallback case only: a UI whose port the runner pre-assigned is an\n * {@link EndpointRow}, proxy or no proxy.\n */\nexport interface UiRef {\n /** Stream tag, e.g. `client/ui`. */\n tag: string\n /**\n * Errors this UI has declared since boot. Present for the same reason an {@link EndpointRow} has one:\n * with nothing printing, a row that cannot count is a row that lies \u2014 and this row belongs to the app\n * whose vite config never wired `infraKitDev()`, i.e. the one most likely to be misconfigured.\n */\n errors?: number\n}\n\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/**\n * A route that wanted a local backend and is falling back to cloud because that backend failed to start.\n *\n * It gets a row of its own \u2014 not a footnote on the failed backend's row \u2014 because the two facts land on\n * different people. `client/api \u25CF failed` says a server is down, which reads as \"that half is broken\".\n * It does NOT say the frontend beside it came up healthy and is now sending every `/api` request to the\n * shared cloud backend. That second fact is the one that gets you writing to the cloud dev database\n * while you believe you are on localhost, and it is invisible everywhere else on the screen: the vite\n * proxy resolved cleanly, so nothing else has anything to complain about.\n *\n * Only rendered under `--watch` \u2014 without it the run is refused outright (see `local-pairing.ts`).\n */\nexport interface DegradedRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Stream tag of the frontend serving it, e.g. `client/ui`. */\n tag: string\n /**\n * Where the route ACTUALLY resolves now. Not always `cloud`: the helper falls back to\n * `route.default ?? route.from[0]`, so a single-source `from: ['local']` route with no `default` falls\n * back to `local` \u2014 at an alias nothing registered, i.e. a 502 on every request. The row must name the\n * real destination, or it is doing the same lying-by-omission it exists to prevent.\n */\n fallback: 'local' | 'cloud'\n /** The cloud origin it now resolves to. Only ever set when `fallback` is `cloud` and it is knowable. */\n target?: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /**\n * Routes silently demoted from local to cloud by a backend that failed to start. Recomputed on every\n * repaint, so a route CLEARS from the panel the moment `--watch` gets its backend up (see\n * {@link DegradedRow}).\n */\n degraded?: DegradedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /**\n * Compact, human-readable log path shown as the `logs \u2192 \u2026` label. A DIRECTORY, not a file\n * (e.g. `~/.cache/infra-kit/<session>/dev/<pid>`): there is one log per service, so a single path\n * would have to pick a favourite.\n */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\n /**\n * Milliseconds since the session became ready \u2014 the panel's HEARTBEAT.\n *\n * Every other live field belongs to a backend: uptime, req/min, restarts. A UI-only session has no\n * backend, so its rows have nothing that moves \u2014 and Ink does not repaint an identical frame, so the\n * screen would sit perfectly still while the session ran. With no log tail left to prove otherwise,\n * a motionless panel is indistinguishable from a hung process. This is the one field that ticks for\n * EVERY session shape. Omitted on the boot frame, where nothing has elapsed yet.\n */\n sessionUptimeMs?: number\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n\nconst ANSI = {\n reset: '\\x1B[0m',\n dim: '\\x1B[2m',\n bold: '\\x1B[1m',\n teal: '\\x1B[36m',\n green: '\\x1B[32m',\n blue: '\\x1B[34m',\n red: '\\x1B[31m',\n} as const\n\n/** Erase the current line and return the cursor to column 0 (used to clear the spinner). */\nconst CLEAR_LINE = '\\r\\x1B[2K'\n\n/**\n * SGR color codes (`ESC [ \u2026 m`) and OSC-8 hyperlink wrappers (`ESC ] 8 ; ; \u2026 ESC \\`), non-greedy.\n * Matching the ESC control character is the whole point here \u2014 this pattern exists to remove it.\n */\n// eslint-disable-next-line sonarjs/no-control-regex, no-control-regex\nconst ANSI_PATTERN = /\\x1B\\[[0-9;]*m|\\x1B\\]8;;.*?\\x1B\\\\/g\n\n/**\n * Strip SGR colors + OSC-8 hyperlink escapes, keeping the hyperlink's visible label. Applied at the\n * file-tee seam so `logs.txt` stays greppable plain text even though the terminal frames it renders\n * from are colored + hyperlinked (both renderers format once, for a TTY, and tee the same string).\n */\nexport const stripAnsi = (s: string): string => {\n return s.replace(ANSI_PATTERN, '')\n}\n\n/** Zero-pad to 2 digits for `HH:MM:SS`. */\nconst pad2 = (n: number): string => {\n return String(n).padStart(2, '0')\n}\n\n/** `HH:MM:SS` for a tail timestamp. */\nexport const formatClock = (d: Date): string => {\n return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`\n}\n\n/** `2.4s` for the `ready in \u2026` header. */\nexport const formatElapsed = (ms: number): string => {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * `47s` / `4m12s` / `2h03m` \u2014 the panel's liveness tell.\n *\n * With no log tail on screen, a panel whose numbers never move is indistinguishable from a hung\n * process. This is the field that proves the session is alive even when nothing is happening, so it is\n * always rendered and always advancing.\n */\nexport const formatUptime = (ms: number): string => {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor((total % 3600) / 60)\n const seconds = total % 60\n\n if (hours > 0) return `${hours}h${pad2(minutes)}m`\n if (minutes > 0) return `${minutes}m${pad2(seconds)}s`\n\n return `${seconds}s`\n}\n\n/**\n * Resolve the endpoint URL for an app: `https://<alias><prefix>`, where `alias` is the portless hostname\n * the runner registered (e.g. `feat-x.backend-api.localhost`). The runner refuses to start an app it could\n * not alias, so there is no port-form to fall back to.\n *\n * There is no port and no scheme choice, by construction. The proxy serves TLS on 443 \u2014 the implicit HTTPS\n * port \u2014 so the URL is byte-identical to the `dev.proxy` local template that `infra-kit/vite` proxies to,\n * and what the table prints cannot drift from what the frontend calls. Any port suffix here would mean the\n * proxy is not on 443, which `ensureProxy` has already refused to start.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string }): string => {\n return `https://${input.alias}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info', options: LogOptions = {}): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n if (options.tee !== false) {\n this.tee(message, level)\n }\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /**\n * The error counter, shared by endpoint rows and UI reference rows.\n *\n * Zero is rendered, not omitted: with nothing else printing, this is the only failure signal on the\n * screen, so a dim `\u26A0 0` is a claim worth making.\n *\n * Non-zero is BOLD red, and that is not decoration. A frontend that fails to compile still serves and\n * still answers vite's ping, so its dot stays green \u2014 the dot is liveness, and the app IS alive. This\n * counter is the only thing on the screen that says the app is nevertheless broken, so it has to win a\n * glance against a green dot sitting two columns away.\n */\n private errorCount(errors: number): string {\n const text = `\u26A0 ${errors}`\n\n return errors > 0 ? this.color(`${ANSI.bold}${ANSI.red}`, text) : this.color(ANSI.dim, text)\n }\n\n /**\n * The padded tag gutter for a PANEL row \u2014 red once the row has declared an error, teal otherwise.\n *\n * Footer only, never {@link formatHeaderLines}. The header is committed once through Ink's `<Static>`,\n * so a tag reddened there would be a photograph of the boot: it could never turn red later, and \u2014 far\n * worse \u2014 could never turn back. The panel repaints, so the color tracks the fact.\n */\n private tagCell(tag: string, tagWidth: number, errors: number | undefined): string {\n return this.color((errors ?? 0) > 0 ? ANSI.red : ANSI.teal, tag.padEnd(tagWidth))\n }\n\n /** Format the health dot for an endpoint row \u2014 one arm per {@link HealthState}; `unknown` prints nothing. */\n private healthDot(health: HealthState): string {\n switch (health) {\n case 'ok':\n return this.color(ANSI.green, '\u25CF ok')\n case 'down':\n return this.color(ANSI.red, '\u25CF down')\n case 'starting':\n return this.color(ANSI.dim, '\u25CC starting')\n // Answering, but not with vite's ping. Dim, never red: a non-204 is equally consistent with a\n // broken squatter and a perfectly healthy vite behind something that shadows the ping, and a red\n // dot on a coin-flip is how a dot stops being read at all.\n case 'unverified':\n return this.color(ANSI.dim, '\u25CD ?')\n default:\n return ''\n }\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n // A degraded row's gutter is `<tag> <route>`, which is wider than any bare tag \u2014 measure the label\n // it actually prints or its `\u25CF cloud \u2026` cell would sit out of column with every row above it.\n ...(summary.degraded ?? []).map((d) => {\n return `${d.tag} ${d.route}`\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /**\n * A UI reference row \u2014 used when infra-kit could not claim the UI's port, so it has no URL to print.\n *\n * It STILL carries an error count. That is the whole point: this row is exactly the misconfigured app\n * (its vite config never wired `infraKitDev()`), which is the app most likely to be broken \u2014 and with\n * no log tail on screen, a row with no error field is a row that cannot report the breakage. It used\n * to be a bare reference line, so its errors were counted into a file nobody had a reason to open.\n */\n private uiRefLine(ref: UiRef, tagWidth: number, errors: number | undefined): string {\n const errText = errors == null ? '' : ` ${this.errorCount(errors)}`\n\n return ` ${this.color(ANSI.teal, ref.tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n 'no managed port (vite prints its own URL)',\n )}${errText}`\n }\n\n /**\n * The live half of an endpoint row: `up 4m12s 18/min \u21BA2 \u26A0 3`.\n *\n * Empty on the boot frame (no field is set yet). Each field is omitted individually when absent \u2014 a\n * server with no restarts should not have to say so.\n */\n private statusFields(endpoint: ReadySummary['endpoints'][number]): string {\n const parts: string[] = []\n\n if (endpoint.uptimeMs != null) parts.push(this.color(ANSI.dim, `up ${formatUptime(endpoint.uptimeMs)}`))\n if (endpoint.rpm != null && endpoint.rpm > 0) parts.push(this.color(ANSI.dim, `${endpoint.rpm}/min`))\n if (endpoint.restarts != null && endpoint.restarts > 0) parts.push(this.color(ANSI.dim, `\u21BA${endpoint.restarts}`))\n // Errors are the exception to \"omit when zero\" \u2014 see {@link errorCount}.\n if (endpoint.errors != null) {\n parts.push(this.errorCount(endpoint.errors))\n }\n\n return parts.join(' ')\n }\n\n /** One endpoint row (`client/api https://\u2026 \u25CF ok up 4m12s 18/min \u26A0 0`). */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.health) : ''\n const status = this.statusFields(endpoint)\n const suffix = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${\n suffix ? ` ${suffix}` : ''\n }`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * One degraded-route row (`\u26A0 /api \u25CF cloud (local backend failed) https://dev.hulyo.co.il`).\n *\n * Tagged by ROUTE, not by app, and deliberately so: the app rows above already say what is up and what\n * is down, and neither of them can say \"the frontend that came up healthy is talking to cloud\". The\n * route is the thing that got redirected, so the route is what the row is about.\n */\n private degradedLine(row: DegradedRow, tagWidth: number): string {\n const label = `${row.tag} ${row.route}`\n // A `local` fallback is not a cloud proxy \u2014 it is a dead alias that 502s. Saying \"cloud\" there would\n // name a destination the traffic never reaches.\n const state = row.fallback === 'cloud' ? '\u25CF cloud (local backend down)' : '\u25CF dead alias (local backend down)'\n const target = row.target ? ` ${this.color(ANSI.dim, row.target)}` : ''\n\n return ` ${this.color(ANSI.red, '\u26A0')} ${this.color(ANSI.teal, label.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n state,\n )}${target}`\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u, tagWidth, u.errors))\n }\n // Below the app rows, because it is a consequence of one of them \u2014 a `\u25CF failed` backend is WHY a\n // route went to cloud, and the two read as cause and effect only in that order.\n for (const d of summary.degraded ?? []) {\n lines.push(this.degradedLine(d, tagWidth))\n }\n\n lines.push('', ...this.legendLines(summary))\n\n return lines\n }\n\n /**\n * Static reference lines for the persistent Ink header, committed ONCE via `<Static>`: title,\n * endpoint URLs WITHOUT the health dot (health is live \u2192 the footer owns it), UI reference rows,\n * watch line, clickable log path, separator. Pure; colors follow `isTTY`.\n */\n formatHeaderLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: false })\n }\n\n /**\n * The live status rows \u2014 THE PANEL. Re-rendered in place on every tick; never committed to `<Static>`.\n *\n * This is the only part of the screen that can change after `ready`, and that makes it the only place\n * live fields can live. The header is committed once through `<Static>`, so anything painted there is\n * a photograph: an uptime or an error count rendered into the header would be frozen at its boot value\n * for the whole session, looking live and being a lie. (It was: the live fields went into the shared\n * endpoint line first, the header picked them up, the footer kept printing a bare health dot, and a\n * real run showed a panel with no uptime, no req/min and no error count at all. No unit test saw it \u2014\n * only the rendered terminal did.)\n *\n * Every row is rendered, including an endpoint that was never probed and a UI with no backend at all:\n * with no log tail on screen this panel is the entire signal, and a row that is absent cannot report\n * that its service is broken.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n const rows = summary.endpoints.map((e) => {\n const dot = this.healthDot(e.health)\n const status = this.statusFields(e)\n const cells = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.tagCell(e.tag, tagWidth, e.errors)} ${cells}`\n })\n\n // A UI whose port infra-kit could not claim has no endpoint row \u2014 but its errors still have to land\n // somewhere the user can see, and it is precisely the app most likely to be misconfigured.\n for (const ref of summary.uiRefs) {\n if (ref.errors == null) continue\n rows.push(` ${this.tagCell(ref.tag, tagWidth, ref.errors)} ${this.errorCount(ref.errors)}`)\n }\n\n // Degraded routes live in the PANEL, not only in the header. The header is committed once through\n // `<Static>` \u2014 a photograph \u2014 so a degraded row painted only there would still be on screen after\n // `--watch` brought the backend back and the route went local again: a permanent warning about a\n // condition that has been fixed, which trains the user to ignore it. The caller re-derives this list\n // from the running set on every tick, so the row survives exactly as long as the problem does.\n for (const d of summary.degraded ?? []) {\n rows.push(this.degradedLine(d, tagWidth))\n }\n\n // The heartbeat. Without it a UI-only session \u2014 whose rows carry no backend uptime and no req/min \u2014\n // would render an identical frame every tick, and Ink does not repaint an identical frame. The panel\n // would be genuinely, verifiably alive and look exactly like a hung process.\n if (summary.sessionUptimeMs != null) {\n const beat = `up ${formatUptime(summary.sessionUptimeMs)}`\n\n rows.push(` ${this.color(ANSI.dim, beat)}`)\n }\n\n return rows\n }\n\n /**\n * Build the ready-header lines with NO side effects (no terminal write, no tee), so both\n * {@link ready} (which writes + tees them) and the Ink boot UI (which commits them via `<Static>`\n * and tee-only's them) share one layout. Colors follow `isTTY` exactly like every other line.\n */\n formatReadyLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: true })\n }\n\n // ---- the live tail ------------------------------------------------------\n\n /**\n * One tagged, timestamped tail line: `14:02:11 client/api GET /api/v1/ping 200 12ms`. Arrives\n * strictly after {@link ready} (a request implies a running server), so it never interleaves the\n * header. Timestamp comes from the injected clock.\n */\n event(input: { tag: string; text: string }): void {\n const ts = formatClock(this.deps.now())\n const line = ` ${this.color(ANSI.dim, ts)} ${this.color(ANSI.teal, input.tag)} ${input.text}`\n\n this.emit(line)\n this.tee(`${input.tag} ${input.text}`, 'info')\n }\n}\n"],
5
+ "mappings": "AAeA,OAAOA,MAAa,eAgLpB,IAAMC,EAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClEC,EAAsB,GAEtBC,EAAO,CACX,MAAO,UACP,IAAK,UACL,KAAM,UACN,KAAM,WACN,MAAO,WACP,KAAM,WACN,IAAK,UACP,EAGMC,EAAa,YAObC,EAAe,qCAORC,EAAaC,GACjBA,EAAE,QAAQF,EAAc,EAAE,EAI7BG,EAAQC,GACL,OAAOA,CAAC,EAAE,SAAS,EAAG,GAAG,EAIrBC,EAAeC,GACnB,GAAGH,EAAKG,EAAE,SAAS,CAAC,CAAC,IAAIH,EAAKG,EAAE,WAAW,CAAC,CAAC,IAAIH,EAAKG,EAAE,WAAW,CAAC,CAAC,GAIjEC,EAAiBC,GACrB,IAAIA,EAAK,KAAM,QAAQ,CAAC,CAAC,IAUrBC,EAAgBD,GAAuB,CAClD,IAAME,EAAQ,KAAK,IAAI,EAAG,KAAK,MAAMF,EAAK,GAAI,CAAC,EACzCG,EAAQ,KAAK,MAAMD,EAAQ,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QAAU,MAClBW,EAAK,KAAK,KAAK,KAAK,QAAQX,EAAI,IAAKjB,EAAUiB,EAAI,MAAM,CAAC,KAAK,KAAK,WAAWA,EAAI,MAAM,CAAC,EAAE,EAQ9F,QAAW1C,KAAK2B,EAAQ,UAAY,CAAC,EACnC0B,EAAK,KAAK,KAAK,aAAarD,EAAGyB,CAAQ,CAAC,EAM1C,GAAIE,EAAQ,iBAAmB,KAAM,CACnC,IAAM4B,EAAO,MAAMpD,EAAawB,EAAQ,eAAe,CAAC,GAExD0B,EAAK,KAAK,KAAK,KAAK,MAAM7D,EAAK,IAAK+D,CAAI,CAAC,EAAE,CAC7C,CAEA,OAAOF,CACT,CAOA,iBAAiB1B,EAAiC,CAChD,OAAO,KAAK,YAAYA,EAAS,CAAE,cAAe,EAAK,CAAC,CAC1D,CASA,MAAMlB,EAA4C,CAChD,IAAM+C,EAAKzD,EAAY,KAAK,KAAK,IAAI,CAAC,EAChCoB,EAAO,KAAK,KAAK,MAAM3B,EAAK,IAAKgE,CAAE,CAAC,KAAK,KAAK,MAAMhE,EAAK,KAAMiB,EAAM,GAAG,CAAC,KAAKA,EAAM,IAAI,GAE9F,KAAK,KAAKU,CAAI,EACd,KAAK,IAAI,GAAGV,EAAM,GAAG,IAAIA,EAAM,IAAI,GAAI,MAAM,CAC/C,CACF",
6
+ "names": ["process", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "s", "pad2", "n", "formatClock", "d", "formatElapsed", "ms", "formatUptime", "total", "hours", "minutes", "seconds", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "href", "label", "c", "message", "level", "line", "options", "frame", "phase", "errors", "tag", "tagWidth", "health", "summary", "lines", "e", "u", "f", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "ref", "errText", "endpoint", "parts", "withHealthDot", "dot", "suffix", "failed", "row", "state", "target", "rows", "cells", "beat", "ts"]
7
+ }
package/dist/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{$ as Ot,A as ee,B as pt,C as j,D as d,E as ft,F as gt,G as ht,H as vt,I as yt,J as wt,K as St,L as kt,M as Rt,N as Et,O as xt,P as Ct,Q as Tt,R as At,S as te,T as bt,U as Pt,V as It,W as Lt,X as Nt,Y as Dt,Z as _t,a as _,aa as $t,b as De,ba as jt,c as Oe,d as $e,e as Fe,f as O,g as Ke,h as M,i as Ye,j as He,k as ze,l as Xe,m as Qe,n as et,o as tt,p as ot,q as Q,r as rt,s as nt,t as Z,u as at,v as ct,w as lt,x as mt,y as dt,z as ut}from"./chunk-TL7LO2FF.js";import{r as oe}from"./chunk-V4XK2YEH.js";import{a as Ft,b as U,c as Mt,d as A,e as re,f as ne,g as ie}from"./chunk-UO3FYLPX.js";import{a as Ze}from"./chunk-JPTSUMWI.js";import{a as it,b as st}from"./chunk-A7FAXZGI.js";import{b as _e,c as C,d as h,e as F,f as Je,g as We,h as Be,i as T}from"./chunk-KAKTWDWJ.js";import{P as z,Q as Le,S as Ne,m as Ie,v as l}from"./chunk-AVLZBOOA.js";import{a as $,b as Me,d as je,f as Ue,g as Ge,j as X,k as qe,n as v,q as Ve}from"./chunk-CHETBZ6M.js";import Zr,{Separator as Ro}from"@inquirer/select";import{realpathSync as en}from"node:fs";import g from"node:process";import{fileURLToPath as xo}from"node:url";var To=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},Ut=e=>Dt.flatMap(({key:t,label:o})=>Ot(t).flatMap(r=>{let s=To(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as cr}from"commander";import D from"node:process";import Gt from"node:process";import{$ as Ao}from"zx";var se=async()=>{let e=await z(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await C(i.path)}))),o=t.at(-1)?.exists===!0,r=await at(e.userProject,o),s=o?ct(r):"";l.info(`Project name: ${e.projectName}
2
+ import{$ as $t,A as te,B as ft,C as U,D as d,E as gt,F as ht,G as vt,H as yt,I as wt,J as St,K as kt,L as Rt,M as Et,N as xt,O as Tt,P as At,Q as Ct,R as bt,S as oe,T as Pt,U as It,V as Nt,W as Lt,X as _t,Y as Dt,Z as Ot,a as D,aa as Ft,b as De,ba as Ut,c as $e,d as Fe,e as Me,f as O,g as He,h as j,i as Ye,j as ze,k as Xe,l as Qe,m as Ze,n as tt,o as ot,p as rt,q as Z,r as nt,s as it,t as ee,u as ct,v as lt,w as mt,x as dt,y as ut,z as pt}from"./chunk-AJW5M44V.js";import{r as re}from"./chunk-7F5YKMWK.js";import{a as Mt,b as G,c as jt,d as C,e as ne,f as ie,g as se}from"./chunk-UO3FYLPX.js";import{a as et}from"./chunk-FTCM2766.js";import{a as st,b as at}from"./chunk-A7FAXZGI.js";import{b as Oe,c as T,d as h,e as F,f as We,g as Ke,h as Be,i as A,l as M}from"./chunk-IPF7ILCB.js";import{P as X,Q as Le,S as _e,m as Ne,v as l}from"./chunk-KHEUED4B.js";import{a as $,b as je,d as Ue,f as Ge,g as qe,j as Q,k as Ve,n as v,q as Je}from"./chunk-CHETBZ6M.js";import en,{Separator as Eo}from"@inquirer/select";import{realpathSync as tn}from"node:fs";import g from"node:process";import{fileURLToPath as To}from"node:url";var Co=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},Gt=e=>Dt.flatMap(({key:t,label:o})=>$t(t).flatMap(r=>{let s=Co(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as lr}from"commander";import _ from"node:process";import qt from"node:process";import{$ as bo}from"zx";var ae=async()=>{let e=await X(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await T(i.path)}))),o=t.at(-1)?.exists===!0,r=await ct(e.userProject,o),s=o?lt(r):"";l.info(`Project name: ${e.projectName}
3
3
  `),l.info(`Config merge chain (later overrides earlier):
4
- `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ae=async()=>{let e=await z(),t=Gt.env.EDITOR||Gt.env.VISUAL||"vi",o=await et(e);o.createdConfig&&l.info(tt(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await Ao({stdio:"inherit"})`${t} ${e.userProject}`,Ne();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 p from"node:fs";import y from"node:path";import L from"node:process";var bo="autoload-warn-fail.flag",le="autoload-warn-auth-fail.flag",me="autoload-fail.flag",de="autoload-auth-fail.json",Po=3e4,Vt=async(e=!0)=>{let t;try{t=await Le()}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 Ke(o.config))return r}catch{return r}return Wt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&G(I(o.config),le),null},Jt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},N=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=_e})=>{let s=e==="cli-invocation";s&&q();let n=null;try{if(n=await Vt(s),!n||Jt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:No(),force:o})==="skip"||qt()||Oo())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!qt()&&!_o(c)});return a?(Fo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return $o(),a&&n&&Wt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(G(I(n.config),le),l.debug(`env auto-load auth failure: ${c}`)):s?G(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,bo):l.debug(`env auto-load skipped: ${c}`),null}},q=()=>{let e=Io();e&&(G(I(e.config),le),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Io=()=>{try{let e=p.readFileSync(y.join(v(),de),"utf-8");return ce(JSON.parse(e))}catch{return null}},Wt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Ve(y.join(t,de),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},No=()=>({session:L.env[je],cleared:L.env[qe],currentConfig:L.env[Ue],currentProject:L.env[Ge],autoLoadedMarker:L.env[X]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},_o=e=>{try{let t=y.join(v(),$);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${X}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},qt=()=>{try{let e=v(),t=y.join(e,Me);if(!p.existsSync(t))return!1;let o=y.join(e,$);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},Oo=()=>{try{let e=y.join(v(),me);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Po:!1}catch{return!1}},$o=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,me),"",{mode:384})}catch{}},Fo=()=>{try{p.rmSync(y.join(v(),me),{force:!0})}catch{}},G=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var ue=async({projectDir:e}={})=>{await N({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",Mo=(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}"): ${Bt}/${e}`],pe=async({env:e})=>{let o=!!(await Je())?.envs[e];await Be(e);let r=await M(),s=await O(),n=await F();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of Mo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:_(JSON.stringify(i,null,2)),structuredContent:i}};import jo from"@inquirer/password";import J from"node:process";import{$ as V}from"zx";var Uo=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Go(),source:"stdin"};if(t){let r=J.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return T.setInteractive(),{token:(await jo({message:"Paste the Doppler service token (input is hidden)",mask:!0},{output:J.stderr})).trim(),source:"prompt"}},Go=async()=>{let e=[];J.stdin.setEncoding("utf8");for await(let t of J.stdin)e.push(t);return e.join("").trim()},fe="DOPPLER_CONFIG",qo=3e4,Vo=async(e,t,o)=>{let r=V.quiet;V.quiet=!0;let s;try{s=(await V({env:ze(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(qo)).stdout}catch(n){throw Jo(n,o)}finally{V.quiet=r}return Qe(s)},Jo=(e,t)=>{let o=Fe(e)??(e instanceof Error?e.message:String(e));if(Oe(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=$e(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
- `))},Wo=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 s=await O(),{token:n,source:i}=await Uo({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Vo(n,s,e);Xe(c,e);let a=c.some(([k])=>k===fe);if(!a&&!r)throw new Error(Wo(e));await We(e,n);let m=await M(),u=await F();l.info(`Stored the "${e}" service token (${ee(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${fe} in the payload) \u2014 written because --force was given.`),m.length>0&&l.info(`Purged ${m.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let f={env:e,source:i,redactedToken:ee(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return T.print(),{content:_(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Bo}from"node:child_process";import W from"node:process";import{fileURLToPath as Ko}from"node:url";var Yo=["SIGINT","SIGTERM"],Kt=()=>Ko(new URL("./mcp.js",import.meta.url)),he=(e={})=>{let t=e.spawn??Bo,o=e.exit??(i=>W.exit(i)),r=e.env??W.env,s=e.onError??(i=>l.error(i)),n=t(W.execPath,[Kt()],{stdio:"inherit",env:it(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),Yo.forEach(i=>{W.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as Ho}from"node:child_process";import{realpathSync as zo}from"node:fs";import{homedir as Xo}from"node:os";import ve from"node:process";import{fileURLToPath as Qo}from"node:url";var Zo=()=>zo(Qo(import.meta.url)),er=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),ye=({dryRun:e},t={})=>{let o=t.spawnSync??Ho,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ve.exit(R)),n=t.env??ve.env,i=t.selfRealPath??Zo(),c=t.lazyNpmRoot??Mt,{manager:a,updateCommand:m,canSelfSpawn:u}=Ft({selfRealPath:i,env:n,realpath:A,lazyNpmRoot:c}),f=m.join(" ");if(e){r(`Detected install manager: ${a}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${a}`),r(`Run this yourself: ${f}`),r(a==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let k=o(m[0],m.slice(1),{stdio:"inherit",shell:ve.platform==="win32",cwd:Xo(),env:st(n)});er(k,a,r,s)};import{VENDOR_CONFIG_FILE as Ht}from"@slip-stream-kit/config/internal";import we from"node:fs/promises";import Se from"node:path";import Yt from"node:process";import{pathToFileURL as tr}from"node:url";var zt="~/projects",ke=async(e={})=>{if(e.init){await rr(e.cwd);return}await or()},or=async()=>{let e=Q(),t=await C(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."),Yt.exitCode=1;return}let{workspaceDir:o,targets:r}=await nt(),s=rt(o),n=await C(s);l.info(`workspaceDir: ${o} (resolved: ${s}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let a=Se.join(s,c),m=await C(a);m||(i=!1);let u=m?"[\u2713]":"[ ]",f=m?"":" (not found \u2014 clone or remove)";l.info(` ${u} ${c} ${h(a)}${f}`)}i||(Yt.exitCode=1)},rr=async e=>{let t=Q();if(await C(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ie(),r=await nr(o);await we.mkdir(Se.dirname(t),{recursive:!0}),await we.writeFile(t,ir(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${Ht}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${zt}) 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.")},nr=async e=>{try{let t=Se.join(e,Ht),o=await we.stat(t),n=(await import(`${tr(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(a=>typeof a=="string"))return c}}catch{}return[]},ir=e=>`${JSON.stringify({workspaceDir:zt,targets:e},null,2)}
7
- `;var B=(e,t=!0)=>({line:e,reproducible:t});import K from"node:fs";import sr from"node:os";import ar from"node:path";import eo from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Re=null,Xt=!1,Qt=[],to=(e=eo.env)=>{Xt||(Re=e[Y]??null,Xt=!0,delete e[Y])};var oo=(e,t)=>{if(!Re)return;let o=e.summary??(Qt.length>0?[...Qt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{K.writeFileSync(n,i)});try{s(Re,JSON.stringify(r))}catch{}},Zt=0,ro=e=>{let t=e?.tmpdir?.()??sr.tmpdir(),o=e?.pid??eo.pid;return Zt+=1,ar.join(t,`infra-kit-session-${o}-${Zt}.json`)},no=(e,t)=>{if(!(t?.exists??(i=>K.existsSync(i)))(e))return null;let r=t?.read??(i=>K.readFileSync(i,"utf-8")),s=t?.unlink??(i=>K.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var lr=(e,t)=>[...t,e],Ee=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,io=(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(", ")}.`)}},mr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await gt({all:t.all,confirmedCommand:t.yes}))}),dr=e=>e.description("List all release branches").action(async()=>{d(await wt())}),ur=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".',lr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(St),s=r.length>0?r:void 0;d(await kt({releases:s,confirmedCommand:t.yes}))}),pr=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=>{d(await Rt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),fr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await vt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),gr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=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=>{d(await ht({version:t.version,confirmedCommand:t.yes}))}),vr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await Nt({confirmedCommand:t.yes}))}),yr=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=io(t.ide,"--ide")??io(t.cursor,"--cursor");d(await bt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),wr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await Pt())}),Sr=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=>{d(await Lt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),kr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{d(await It())}),Rr=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=>{d(await ke({init:t.init}))}),Er=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Et();d(t),t.structuredContent.ok||(D.exitCode=1)}),xr=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await xt({repos:Ee(t.repos)});d(o),o.structuredContent.ok||(D.exitCode=1)}),Cr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await se())}),Tr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ae())}),Ar=new Set(["init","doctor","version","dev","self-update","mcp"]),br=e=>e.startsWith("env-")||Ar.has(e),Pr=new Set(["env-autoload","mcp","version","self-update"]),H=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},xe=()=>{let e=new cr,t=e.command("release").description("Release management commands");mr(t.command("merge-dev")),dr(t.command("list")),ur(t.command("create")),pr(t.command("desc-edit")),fr(t.command("deploy-all")),gr(t.command("deploy-selected")),hr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");yr(o.command("add")),wr(o.command("list")),Sr(o.command("remove")),vr(o.command("sync")),kr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");Cr(r.command("path")),Tr(r.command("edit")),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)").action(async n=>{let i=await De({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(D.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Er(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Tt({confirmedCommand:n.yes,repos:Ee(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Ct({confirmedCommand:!0,repos:Ee(n.repos)}))}),xr(s.command("diff")),Rr(s.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.").action(async n=>{d(await lt({fix:!!n.fix}))}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{ye({dryRun:!!n.dryRun})}),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)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(D.stdout.isTTY&&D.stdin.isTTY);await c({...i,preset:n},a,j.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await At())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await ut())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{d(await dt())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await Z())}),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 n=>{d(await He({config:n.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 n=>{d(await mt({purge:!!n.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(n,i)=>{d(await ge({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.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 n=>{d(await pt({check:!!n.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 n=>{d(await pe({env:n}))}),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 n=>{await ue({projectDir:n.projectDir})}),e.commands.forEach(ft),e.hook("preAction",async(n,i)=>{T.start(H(i)),j.enabled=!!i.optsWithGlobals().json,j.enabled&&(l.level="warn"),Pr.has(H(i))||await ot(),q(),br(i.name())||await N({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=H(i);if($t(c))return;let m=T.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;oo({equivalent:B(f,!0)})}),e};var Ce=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as Mr}from"chalk";import{spawn as jr}from"node:child_process";import S from"node:process";import{Chalk as Ir}from"chalk";var b=new Ir({level:1}),w={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."},so={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},ao={unicode:"\u2500",ascii:"-"},Lr=3,Te=e=>e,Nr={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},lo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Te,bold:Te},Dr=(e,t)=>e?Nr[t]:Te,co=e=>[...e].length,mo=(e,t={})=>{let o=lo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},_r=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Or=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],$r=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},uo=e=>{let t=e.color===!0,o=lo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?so[e.outcome].ascii:so[e.outcome].unicode,c=Or(e.outcome,e.findingsCount),a=[_r(e.durationMs)],m=e.summary?.[0]?.split(`
8
- `)[0];m!=null&&m.length>0&&a.push(m);let u=`${i} ${c}`,f=`${w.sep}${a.join(w.sep)}`,k=co(u)+co(f),R=$r(k,e.width,s?ao.ascii:ao.unicode,o.dim),x=[`${r(u)}${o.dim(f)}${R}`];return e.showEquivalent!==!1&&x.unshift(`${o.dim(n.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&x.push(o.dim(w.envNotice)),x.join(`
9
- `)};var Fr=new Set([130,143]),po=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Fr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import fo from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},go=(e,t)=>{let o=t?.write??(n=>{fo.stderr.write(n)}),r=t?.stdin??fo.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var ho=e=>`infra-kit ${e.groupPath.join(" ")}`,Ur=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},Gr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),qr=async(e,t,o)=>{let r=ro(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await Gr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=no(r),a=po(i.code,i.signal,c!=null,e.longRunning),m=ho(e),u=c?.equivalent??B(m,!0);return uo({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Vr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},vo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),yo=async(e,t)=>{let o={spawn:t.spawn??jr,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??Mr.level>0,columns:t.columns??Ur,resetTerminal:t.resetTerminal??(a=>{go(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Vr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=mo(ho(m),{color:o.color});r(`
4
+ `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ce=async()=>{let e=await X(),t=qt.env.EDITOR||qt.env.VISUAL||"vi",o=await tt(e);o.createdConfig&&l.info(ot(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await bo({stdio:"inherit"})`${t} ${e.userProject}`,_e();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=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 p from"node:fs";import y from"node:path";import N from"node:process";var Po="autoload-warn-fail.flag",me="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",Io=3e4,Jt=async(e=!0)=>{let t;try{t=await Le()}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 He(o.config))return r}catch{return r}return Kt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&q(I(o.config),me),null},Wt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},L=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Oe})=>{let s=e==="cli-invocation";s&&V();let n=null;try{if(n=await Jt(s),!n||Wt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:_o(),force:o})==="skip"||Vt()||$o())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!Vt()&&!Oo(c)});return a?(Mo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return Fo(),a&&n&&Kt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(q(I(n.config),me),l.debug(`env auto-load auth failure: ${c}`)):s?q(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,Po):l.debug(`env auto-load skipped: ${c}`),null}},V=()=>{let e=No();e&&(q(I(e.config),me),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},No=()=>{try{let e=p.readFileSync(y.join(v(),ue),"utf-8");return le(JSON.parse(e))}catch{return null}},Kt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Je(y.join(t,ue),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),ue),{force:!0})}catch{}},_o=()=>({session:N.env[Ue],cleared:N.env[Ve],currentConfig:N.env[Ge],currentProject:N.env[qe],autoLoadedMarker:N.env[Q]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},Oo=e=>{try{let t=y.join(v(),$);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},Vt=()=>{try{let e=v(),t=y.join(e,je);if(!p.existsSync(t))return!1;let o=y.join(e,$);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},$o=()=>{try{let e=y.join(v(),de);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Io:!1}catch{return!1}},Fo=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,de),"",{mode:384})}catch{}},Mo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},q=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await L({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",jo=(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}"): ${Bt}/${e}`],fe=async({env:e})=>{let o=!!(await We())?.envs[e];await Be(e);let r=await j(),s=await O(),n=await F();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of jo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:D(JSON.stringify(i,null,2)),structuredContent:i}};import Uo from"@inquirer/password";import W from"node:process";import{$ as J}from"zx";var Go=async({stdin:e,fromEnv:t})=>{if(e)return{token:await qo(),source:"stdin"};if(t){let r=W.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return A.setInteractive(),{token:(await M(r=>Uo({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:W.stderr})).trim(),source:"prompt"}},qo=async()=>{let e=[];W.stdin.setEncoding("utf8");for await(let t of W.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",Vo=3e4,Jo=async(e,t,o)=>{let r=J.quiet;J.quiet=!0;let s;try{s=(await J({env:Xe(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Vo)).stdout}catch(n){throw Wo(n,o)}finally{J.quiet=r}return Ze(s)},Wo=(e,t)=>{let o=Me(e)??(e instanceof Error?e.message:String(e));if($e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Fe(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
+ `))},Ko=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${ge}.`,"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
+ `),he=async({env:e,stdin:t,fromEnv:o,force:r})=>{let s=await O(),{token:n,source:i}=await Go({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Jo(n,s,e);Qe(c,e);let a=c.some(([k])=>k===ge);if(!a&&!r)throw new Error(Ko(e));await Ke(e,n);let m=await j(),u=await F();l.info(`Stored the "${e}" service token (${te(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${ge} in the payload) \u2014 written because --force was given.`),m.length>0&&l.info(`Purged ${m.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let f={env:e,source:i,redactedToken:te(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return A.print(),{content:D(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Bo}from"node:child_process";import K from"node:process";import{fileURLToPath as Ho}from"node:url";var Yo=["SIGINT","SIGTERM"],Ht=()=>Ho(new URL("./mcp.js",import.meta.url)),ve=(e={})=>{let t=e.spawn??Bo,o=e.exit??(i=>K.exit(i)),r=e.env??K.env,s=e.onError??(i=>l.error(i)),n=t(K.execPath,[Ht()],{stdio:"inherit",env:st(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),Yo.forEach(i=>{K.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as zo}from"node:child_process";import{realpathSync as Xo}from"node:fs";import{homedir as Qo}from"node:os";import ye from"node:process";import{fileURLToPath as Zo}from"node:url";var er=()=>Xo(Zo(import.meta.url)),tr=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),we=({dryRun:e},t={})=>{let o=t.spawnSync??zo,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ye.exit(R)),n=t.env??ye.env,i=t.selfRealPath??er(),c=t.lazyNpmRoot??jt,{manager:a,updateCommand:m,canSelfSpawn:u}=Mt({selfRealPath:i,env:n,realpath:C,lazyNpmRoot:c}),f=m.join(" ");if(e){r(`Detected install manager: ${a}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${a}`),r(`Run this yourself: ${f}`),r(a==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let k=o(m[0],m.slice(1),{stdio:"inherit",shell:ye.platform==="win32",cwd:Qo(),env:at(n)});tr(k,a,r,s)};import{VENDOR_CONFIG_FILE as zt}from"@slip-stream-kit/config/internal";import Se from"node:fs/promises";import ke from"node:path";import Yt from"node:process";import{pathToFileURL as or}from"node:url";var Xt="~/projects",Re=async(e={})=>{if(e.init){await nr(e.cwd);return}await rr()},rr=async()=>{let e=Z(),t=await T(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."),Yt.exitCode=1;return}let{workspaceDir:o,targets:r}=await it(),s=nt(o),n=await T(s);l.info(`workspaceDir: ${o} (resolved: ${s}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let a=ke.join(s,c),m=await T(a);m||(i=!1);let u=m?"[\u2713]":"[ ]",f=m?"":" (not found \u2014 clone or remove)";l.info(` ${u} ${c} ${h(a)}${f}`)}i||(Yt.exitCode=1)},nr=async e=>{let t=Z();if(await T(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ne(),r=await ir(o);await Se.mkdir(ke.dirname(t),{recursive:!0}),await Se.writeFile(t,sr(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${zt}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${Xt}) 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.")},ir=async e=>{try{let t=ke.join(e,zt),o=await Se.stat(t),n=(await import(`${or(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(a=>typeof a=="string"))return c}}catch{}return[]},sr=e=>`${JSON.stringify({workspaceDir:Xt,targets:e},null,2)}
7
+ `;var B=(e,t=!0)=>({line:e,reproducible:t});import H from"node:fs";import ar from"node:os";import cr from"node:path";import to from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Ee=null,Qt=!1,Zt=[],oo=(e=to.env)=>{Qt||(Ee=e[Y]??null,Qt=!0,delete e[Y])};var ro=(e,t)=>{if(!Ee)return;let o=e.summary??(Zt.length>0?[...Zt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{H.writeFileSync(n,i)});try{s(Ee,JSON.stringify(r))}catch{}},eo=0,no=e=>{let t=e?.tmpdir?.()??ar.tmpdir(),o=e?.pid??to.pid;return eo+=1,cr.join(t,`infra-kit-session-${o}-${eo}.json`)},io=(e,t)=>{if(!(t?.exists??(i=>H.existsSync(i)))(e))return null;let r=t?.read??(i=>H.readFileSync(i,"utf-8")),s=t?.unlink??(i=>H.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var mr=(e,t)=>[...t,e],xe=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,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(", ")}.`)}},dr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await ht({all:t.all,confirmedCommand:t.yes}))}),ur=e=>e.description("List all release branches").action(async()=>{d(await St())}),pr=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".',mr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),s=r.length>0?r:void 0;d(await Rt({releases:s,confirmedCommand:t.yes}))}),fr=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=>{d(await Et({version:t.version,description:t.description,confirmedCommand:t.yes}))}),gr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await wt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),vr=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=>{d(await vt({version:t.version,confirmedCommand:t.yes}))}),yr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await _t({confirmedCommand:t.yes}))}),wr=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");d(await Pt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Sr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await It())}),kr=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=>{d(await Lt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Rr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{d(await Nt())}),Er=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=>{d(await Re({init:t.init}))}),xr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await xt();d(t),t.structuredContent.ok||(_.exitCode=1)}),Tr=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Tt({repos:xe(t.repos)});d(o),o.structuredContent.ok||(_.exitCode=1)}),Ar=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await ae())}),Cr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ce())}),br=new Set(["init","doctor","version","dev","self-update","mcp"]),Pr=e=>e.startsWith("env-")||br.has(e),Ir=new Set(["env-autoload","mcp","version","self-update"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new lr,t=e.command("release").description("Release management commands");dr(t.command("merge-dev")),ur(t.command("list")),pr(t.command("create")),fr(t.command("desc-edit")),gr(t.command("deploy-all")),hr(t.command("deploy-selected")),vr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");wr(o.command("add")),Sr(o.command("list")),kr(o.command("remove")),yr(o.command("sync")),Rr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");Ar(r.command("path")),Cr(r.command("edit")),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)").action(async n=>{let i=await De({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(_.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return xr(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Ct({confirmedCommand:n.yes,repos:xe(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await At({confirmedCommand:!0,repos:xe(n.repos)}))}),Tr(s.command("diff")),Er(s.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.").action(async n=>{d(await mt({fix:!!n.fix}))}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{we({dryRun:!!n.dryRun})}),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(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(_.stdout.isTTY&&_.stdin.isTTY);await c({...i,preset:n},a,U.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await bt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(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()=>{d(await ut())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await ee())}),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 n=>{d(await ze({config:n.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 n=>{d(await dt({purge:!!n.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(n,i)=>{d(await he({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.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 n=>{d(await ft({check:!!n.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 n=>{d(await fe({env:n}))}),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 n=>{await pe({projectDir:n.projectDir})}),e.commands.forEach(gt),e.hook("preAction",async(n,i)=>{A.start(z(i)),U.enabled=!!i.optsWithGlobals().json,U.enabled&&(l.level="warn"),Ir.has(z(i))||await rt(),V(),Pr(i.name())||await L({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=z(i);if(Ft(c))return;let m=A.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;ro({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as jr}from"chalk";import{spawn as Ur}from"node:child_process";import S from"node:process";import{Chalk as Nr}from"chalk";var b=new Nr({level:1}),w={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."},ao={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},co={unicode:"\u2500",ascii:"-"},Lr=3,Ce=e=>e,_r={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},mo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Ce,bold:Ce},Dr=(e,t)=>e?_r[t]:Ce,lo=e=>[...e].length,uo=(e,t={})=>{let o=mo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},Or=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$r=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],Fr=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},po=e=>{let t=e.color===!0,o=mo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?ao[e.outcome].ascii:ao[e.outcome].unicode,c=$r(e.outcome,e.findingsCount),a=[Or(e.durationMs)],m=e.summary?.[0]?.split(`
8
+ `)[0];m!=null&&m.length>0&&a.push(m);let u=`${i} ${c}`,f=`${w.sep}${a.join(w.sep)}`,k=lo(u)+lo(f),R=Fr(k,e.width,s?co.ascii:co.unicode,o.dim),x=[`${r(u)}${o.dim(f)}${R}`];return e.showEquivalent!==!1&&x.unshift(`${o.dim(n.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&x.push(o.dim(w.envNotice)),x.join(`
9
+ `)};var Mr=new Set([130,143]),fo=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Mr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import go from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ho=(e,t)=>{let o=t?.write??(n=>{go.stderr.write(n)}),r=t?.stdin??go.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var vo=e=>`infra-kit ${e.groupPath.join(" ")}`,Gr=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},qr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Vr=async(e,t,o)=>{let r=no(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await qr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=io(r),a=fo(i.code,i.signal,c!=null,e.longRunning),m=vo(e),u=c?.equivalent??B(m,!0);return po({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Jr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},yo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wo=async(e,t)=>{let o={spawn:t.spawn??Ur,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??jr.level>0,columns:t.columns??Gr,resetTerminal:t.resetTerminal??(a=>{ho(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Jr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=uo(vo(m),{color:o.color});r(`
10
10
  ${u}
11
- `),c.childStarted();let f=await qr(m,o,()=>{n=!0});r(`
11
+ `),c.childStarted();let f=await Vr(m,o,()=>{n=!0});r(`
12
12
  ${f}
13
- `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import So from"node:fs";import P from"node:process";import{fileURLToPath as ko}from"node:url";var wo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Jr=new Set(["mcp","self-update"]),Wr=e=>e[2]!=null&&Jr.has(e[2]),Ae=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return wo.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Wr(t)?"own-command":r?U(s,n,i)?"local-install":null:"not-a-tty"};var Kr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>ko(new URL("./update-check.js",import.meta.url)),Hr=()=>So.realpathSync(ko(new URL("./cli.js",import.meta.url))),zr=/^[\w@./+-]+$/i,Xr=e=>zr.test(e),Qr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||re(e.latestVersion,t)&&e.updateCommand.every(Xr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},be=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??Hr(),a=t.readCache??ne,m=t.spawnChild??Kr,u=t.fileExists??(x=>So.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(Ae({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:A})!==null)return;let k=a();if(Qr(k,e,f),!ie(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};jt();to();var Pe=xe(),Eo=async e=>{try{e?await Pe.parseAsync(e):await Pe.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)}},tn=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;U(en(xo(import.meta.url)),g.cwd(),A)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};tn();be(Ze.version);var Co=()=>Ut(Pe.commands),on=async()=>{let e=Co(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-YQAPYAKT.js");t=await o(e)}else{let o=Ce(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Ro(" "),new Ro(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await Zr({message:"Select a command to run",choices:r},{output:g.stderr})}}catch(o){if(!oe(o))throw o}return t},rn=async()=>{let{runCommandPalette:e}=await import("./boot-YQAPYAKT.js"),t=xo(import.meta.url),o=new Map(_t.map(r=>[r.groupPath.join(" "),r]));await yo(Co(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.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(vo(g.env,e))await rn();else{let t=await on();t&&await Eo(["node","infra-kit",...t.split(" ")])}}else await Eo();
13
+ `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import ko from"node:fs";import P from"node:process";import{fileURLToPath as Ro}from"node:url";var So=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Wr=new Set(["mcp","self-update"]),Kr=e=>e[2]!=null&&Wr.has(e[2]),be=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return So.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Kr(t)?"own-command":r?G(s,n,i)?"local-install":null:"not-a-tty"};var Hr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>Ro(new URL("./update-check.js",import.meta.url)),zr=()=>ko.realpathSync(Ro(new URL("./cli.js",import.meta.url))),Xr=/^[\w@./+-]+$/i,Qr=e=>Xr.test(e),Zr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Qr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Pe=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??zr(),a=t.readCache??ie,m=t.spawnChild??Hr,u=t.fileExists??(x=>ko.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(be({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:C})!==null)return;let k=a();if(Zr(k,e,f),!se(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};Ut();oo();var Ie=Te(),xo=async e=>{try{e?await Ie.parseAsync(e):await Ie.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},on=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;G(tn(To(import.meta.url)),g.cwd(),C)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};on();Pe(et.version);var Ao=()=>Gt(Ie.commands),rn=async()=>{let e=Ao(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-EEEVHAMO.js");t=await o(e)}else{let o=Ae(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Eo(" "),new Eo(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await M(s=>en({message:"Select a command to run",choices:r},s),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},nn=async()=>{let{runCommandPalette:e}=await import("./boot-EEEVHAMO.js"),t=To(import.meta.url),o=new Map(Ot.map(r=>[r.groupPath.join(" "),r]));await wo(Ao(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.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(yo(g.env,e))await nn();else{let t=await rn();t&&await xo(["node","infra-kit",...t.split(" ")])}}else await xo();
14
14
  //# sourceMappingURL=cli.js.map