infra-kit 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-BL4EQMZV.js → boot-XLDVLQEG.js} +2 -2
- package/dist/boot-XLDVLQEG.js.map +7 -0
- package/dist/chunk-2H6VQIGT.js +7 -0
- package/dist/chunk-2H6VQIGT.js.map +7 -0
- package/dist/chunk-6UJQB36N.js +2 -0
- package/dist/chunk-6UJQB36N.js.map +7 -0
- package/dist/chunk-AG7XWZNT.js +3 -0
- package/dist/chunk-AG7XWZNT.js.map +7 -0
- package/dist/{chunk-HHWP3YXW.js → chunk-AWFGP6GY.js} +1 -1
- package/dist/{chunk-HHWP3YXW.js.map → chunk-AWFGP6GY.js.map} +1 -1
- package/dist/chunk-F656FWV5.js +11 -0
- package/dist/chunk-F656FWV5.js.map +7 -0
- package/dist/{chunk-X2HFNQRU.js → chunk-OWX4O3IS.js} +2 -2
- package/dist/chunk-R2SZWOPC.js +3 -0
- package/dist/chunk-R2SZWOPC.js.map +7 -0
- package/dist/chunk-RZF36IGQ.js +4 -0
- package/dist/chunk-RZF36IGQ.js.map +7 -0
- package/dist/cli.js +424 -13
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/dev-server.js.map +2 -2
- package/dist/dev-wizard-run-J5WSWCZT.js +2 -0
- package/dist/dev-wizard-run-J5WSWCZT.js.map +7 -0
- package/dist/mcp-proxy.js +9 -9
- package/dist/mcp-proxy.js.map +2 -2
- package/dist/update-check.js +1 -1
- package/dist/update-check.js.map +2 -2
- package/package.json +3 -7
- package/readme.md +4 -4
- package/dist/boot-BL4EQMZV.js.map +0 -7
- package/dist/chunk-75BE6MSY.js +0 -7
- package/dist/chunk-75BE6MSY.js.map +0 -7
- package/dist/chunk-75URROMU.js +0 -4
- package/dist/chunk-75URROMU.js.map +0 -7
- package/dist/chunk-FWINBDB5.js +0 -444
- package/dist/chunk-FWINBDB5.js.map +0 -7
- package/dist/chunk-GRWUCPQL.js +0 -2
- package/dist/chunk-GRWUCPQL.js.map +0 -7
- package/dist/chunk-H5AAXCRJ.js +0 -9
- package/dist/chunk-H5AAXCRJ.js.map +0 -7
- package/dist/chunk-IXWQ7EQT.js +0 -3
- package/dist/chunk-IXWQ7EQT.js.map +0 -7
- package/dist/dev-wizard-run-643QKSR3.js +0 -2
- package/dist/dev-wizard-run-643QKSR3.js.map +0 -7
- package/dist/mcp.js +0 -3
- package/dist/mcp.js.map +0 -7
- /package/dist/{chunk-X2HFNQRU.js.map → chunk-OWX4O3IS.js.map} +0 -0
package/dist/chunk-GRWUCPQL.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{j as L,m as I,n as R}from"./chunk-HHWP3YXW.js";import{e as E}from"./chunk-75URROMU.js";import g from"node:fs";import{homedir as ce}from"node:os";import{dirname as v,join as C}from"node:path";import O from"node:process";import{fileURLToPath as ue}from"node:url";import{execFile as j}from"node:child_process";import{createHash as H}from"node:crypto";import{existsSync as _,readFileSync as f}from"node:fs";import G from"node:http";import K from"node:https";import q from"node:net";import{homedir as z}from"node:os";import{dirname as y,join as u}from"node:path";import m from"node:process";import J from"node:tls";import{fileURLToPath as V}from"node:url";import{promisify as $}from"node:util";var U=/^[\w@%+=:,./-]+$/,F="'\\''",A=e=>U.test(e)?e:`'${e.replaceAll("'",F)}'`,P=e=>e.map(A).join(" ");var W=$(j),Q=e=>{let r=JSON.parse(f(e,"utf-8")),t=typeof r.bin=="string"?r.bin:r.bin?.portless;return t==null||t===""?null:t},x=()=>{try{let e=y(V(import.meta.url));for(;;){let r=u(e,"node_modules","portless","package.json");if(_(r)){let n=Q(r);return n==null?null:u(y(r),n)}let t=y(e);if(t===e)return null;e=t}}catch{return null}},h,w=()=>(h===void 0&&(h=x()),h),N=(e,r)=>{let t=[r.execPath??m.execPath,r.bin,...e];return(r.sudo===!0?"sudo ":"")+P(t)},X=1500,S=1500,Y="x-portless",b="127.0.0.1",Z="localhost",ee="sh.portless.proxy",te=`/Library/LaunchDaemons/${ee}.plist`,re="/etc/systemd/system/portless.service",Be="portless",ne=(e=_)=>{try{return m.platform==="darwin"?e(te)?"yes":"no":m.platform==="linux"?e(re)?"yes":"no":"unknown"}catch{return"unknown"}},oe=e=>new Promise(r=>{let t=q.connect({host:b,port:e}),n=o=>{t.destroy(),r(o)};t.setTimeout(S),t.once("connect",()=>{n(!0)}),t.once("timeout",()=>{n(!1)}),t.once("error",()=>{n(!1)})}),se=(e,r)=>new Promise(t=>{let o=(r?K.request:G.request)({host:b,port:e,method:"HEAD",path:"/",timeout:S,...r?{rejectUnauthorized:!1,servername:Z}:{}},s=>{s.resume(),t(s.headers[Y]==="1")});o.on("error",()=>{t(!1)}),o.on("timeout",()=>{o.destroy(),t(!1)}),o.end()}),ie=async(e,{timeoutMs:r})=>{let t=w();if(t==null)throw new Error("portless is not installed (not resolvable from node_modules)");await W(m.execPath,[t,...e],{signal:AbortSignal.timeout(r),encoding:"utf-8",env:R(m.env)})},k=()=>m.env.PORTLESS_STATE_DIR??u(z(),".portless"),ae="ca.pem",le="ca.trusted",T=()=>u(k(),ae),Ue=()=>{try{let e=f(u(k(),le),"utf-8").trim();return e===""?!1:H("sha256").update(f(T())).digest("hex")===e.toLowerCase()}catch{return!1}},Fe=(e,r)=>new Promise(t=>{let n;try{n=f(T())}catch{t({ok:!1,code:"ENOENT"});return}let o=J.connect({host:b,port:e,servername:r,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,c=o.authorized;o.destroy(),t(c?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(S),o.once("timeout",()=>{o.destroy(),t({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),t({ok:!1,code:s.code??"UNKNOWN"})})}),je=()=>{try{let e=JSON.parse(f(u(k(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(r=>{let{hostname:t,port:n}=r??{};return typeof t!="string"||t===""||typeof n!="number"?[]:[{name:t,port:n}]}):[]}catch{return[]}},He=(e={})=>{let r=e.bin===void 0?w():e.bin,t=e.run??ie,n=e.isListening??oe,o=e.isProxyServing??se,s=e.isServiceInstalled??ne,c=e.timeoutMs??X,a=null,l=async i=>{try{return await t(i,{timeoutMs:c}),!0}catch{return!1}},d=async()=>(a??=await l(["--version"]),a);return{binPath:()=>r,isAvailable:d,isProxyServing:async(i,p)=>!await d()||!await n(i)?!1:o(i,p),probeProxy:async(i,p)=>await n(i)?await o(i,p)?"serving":"not-portless":"daemon-down",isServiceInstalled:s,registerAlias:async(i,p)=>await d()?l(["alias",i,String(p)]):!1,removeAlias:async i=>{await d()&&await l(["alias","--remove",i])}}};var D=e=>C(e,E,"portless"),me=(e,r=g.existsSync)=>{let t=C(D(e),"dist","cli.js");return r(t)?t:null},Xe=(e,r)=>N(["service","install"],{sudo:!0,bin:me(r.home,r.exists)??e,execPath:r.execPath}),M=Symbol("absent"),B=Symbol("not-a-symlink"),pe=(e,r)=>{let t=r.lstatSync(e,{throwIfNoEntry:!1});return t===void 0?M:t.isSymbolicLink()?r.readlinkSync(e):B},fe=(e,r,t)=>{let n=`${r}.tmp-${O.pid}`;try{t.unlinkSync(n)}catch{}t.symlinkSync(e,n);try{t.renameSync(n,r)}catch(o){try{t.unlinkSync(n)}catch{}throw o}},de=e=>{let{resolveBin:r,isGlobal:t,home:n,fs:o=g}=e,s=D(n),c=r();if(c===null)return{outcome:"skipped-unresolved",target:null,link:s};let a=v(v(c));if(!t())return{outcome:"skipped-local",target:a,link:s};try{o.mkdirSync(v(s),{recursive:!0});let l=pe(s,o);return l===a?{outcome:"unchanged",target:a,link:s}:l===B?{outcome:"failed",target:a,link:s}:(fe(a,s,o),{outcome:l===M?"created":"repointed",target:a,link:s})}catch{return{outcome:"failed",target:a,link:s}}},ge=()=>{let e=ce();return{resolveBin:x,isGlobal:()=>L({selfRealPath:g.realpathSync(ue(import.meta.url)),env:O.env,realpath:I,home:e,exists:g.existsSync}),home:e}},Ye=(e,r)=>{try{e(de(r??ge()),"portless link")}catch{}};export{P as a,x as b,N as c,ee as d,te as e,re as f,Be as g,oe as h,se as i,k as j,T as k,Ue as l,Fe as m,je as n,He as o,D as p,me as q,Xe as r,de as s,ge as t,Ye as u};
|
|
2
|
-
//# sourceMappingURL=chunk-GRWUCPQL.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: seams.execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { outcome: 'failed', target, link }\n }\n}\n\n/** `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. */\ntype PortlessLinkLog = (result: PortlessLinkResult, message: string) => void\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULT back to report its step, so the two\n * writers can never disagree about which install is \"global\" or where the link goes.\n */\nexport const realPortlessLinkDeps = (): EnsurePortlessLinkDeps => {\n const home = homedir()\n\n return {\n resolveBin: resolvePortlessBin,\n isGlobal: () => {\n return isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n },\n home,\n }\n}\n\n/**\n * The process-boot entry for both bins. fs-only, no subprocess, never throws, never exits, never\n * writes to stdout; the outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'`\n * is logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: EnsurePortlessLinkDeps): void => {\n try {\n log(ensurePortlessLink(deps ?? realPortlessLinkDeps()), 'portless link')\n } catch {\n // A link that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n", "/**\n * @fileoverview\n *\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, an Orca pane, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\nimport { shellLine } from 'src/lib/shell-quote'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\n// This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n// `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\n//\n// This is not merely cosmetic. portless's `service install` writes the interpreter and script path it was\n// invoked with straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n// `process.argv[1]`), so the command printed here is the command that gets installed as a ROOT SYSTEM\n// DAEMON. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as\n// root.\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + shellLine(words)\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\n */\n// This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was UNSOUND: portless's\n// `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n// process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n// stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n// old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n// were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n//\n// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n"],
|
|
5
|
-
"mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAS,iBAAAC,OAAqB,WCP9B,OAAS,YAAAC,MAAgB,qBACzB,OAAS,cAAAC,MAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAOC,MAAW,aAClB,OAAOC,MAAS,WAChB,OAAS,WAAAC,MAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAOC,MAAS,WAChB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,aAAAC,MAAiB,YCrB1B,IAAMC,EAAa,mBAGbC,EAAsB,QAGfC,EAAcC,GAClBH,EAAW,KAAKG,CAAK,EAAIA,EAAQ,IAAIA,EAAM,WAAW,IAAKF,CAAmB,CAAC,IAI3EG,EAAaC,GACjBA,EAAK,IAAIH,CAAU,EAAE,KAAK,GAAG,EDctC,IAAMI,EAAgBC,EAAUC,CAAQ,EAGlCC,EAAcC,GAAuC,CACzD,IAAMC,EAAM,KAAK,MAAMC,EAAaF,EAAa,OAAO,CAAC,EACnDG,EAAM,OAAOF,EAAI,KAAQ,SAAWA,EAAI,IAAMA,EAAI,KAAK,SAE7D,OAAOE,GAAO,MAAQA,IAAQ,GAAK,KAAOA,CAC5C,EAYaC,EAAqB,IAAqB,CACrD,GAAI,CACF,IAAIC,EAAMC,EAAQC,EAAc,YAAY,GAAG,CAAC,EAEhD,OAAS,CACP,IAAMP,EAAcQ,EAAKH,EAAK,eAAgB,WAAY,cAAc,EAExE,GAAII,EAAWT,CAAW,EAAG,CAC3B,IAAMG,EAAMJ,EAAWC,CAAW,EAElC,OAAOG,GAAO,KAAO,KAAOK,EAAKF,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,CAAE,QAAS,YAAa,OAAAA,EAAQ,KAAAJ,CAAK,EAChEa,IAAYf,EAAsB,CAAE,QAAS,SAAU,OAAAM,EAAQ,KAAAJ,CAAK,GAExEG,GAAUC,EAAQJ,EAAMC,CAAM,EAEvB,CAAE,QAASY,IAAYhB,EAAS,UAAY,YAAa,OAAAO,EAAQ,KAAAJ,CAAK,EAC/E,MAAQ,CACN,MAAO,CAAE,QAAS,SAAU,OAAAI,EAAQ,KAAAJ,CAAK,CAC3C,CACF,EASac,GAAuB,IAA8B,CAChE,IAAM5B,EAAO6B,GAAQ,EAErB,MAAO,CACL,WAAYC,EACZ,SAAU,IACDC,EAAgB,CACrB,aAAc1B,EAAG,aAAa2B,GAAc,YAAY,GAAG,CAAC,EAC5D,IAAKZ,EAAQ,IACb,SAAUa,EACV,KAAAjC,EACA,OAAQK,EAAG,UACb,CAAC,EAEH,KAAAL,CACF,CACF,EAOakC,GAAmB,CAACC,EAAsBZ,IAAwC,CAC7F,GAAI,CACFY,EAAIb,GAAmBC,GAAQK,GAAqB,CAAC,EAAG,eAAe,CACzE,MAAQ,CAER,CACF",
|
|
6
|
-
"names": ["fs", "homedir", "dirname", "join", "process", "fileURLToPath", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "process", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessLinkDeps", "homedir", "resolvePortlessBin", "isGlobalInstall", "fileURLToPath", "safeRealpath", "bootPortlessLink", "log"]
|
|
7
|
-
}
|
package/dist/chunk-H5AAXCRJ.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{a as X}from"./chunk-MFAFQVTW.js";import{e as T}from"./chunk-75URROMU.js";import Y from"node:process";import N from"pino";import Ne from"pino-pretty";var J="/tmp/mcp-infra-kit.log",Z=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],kr=()=>{let e=Y.argv.includes("--debug")?"debug":"info",t=N({level:e,redact:Z},N.destination({dest:J}));return t.info(`Logger initialized with level: ${e}. Logging to: ${J}`),t},_e=()=>{let e=Y.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),N({level:e,redact:Z},Ne({destination:2,ignore:t.join(","),colorize:!0}))},Q=_e();import q from"node:fs/promises";import we from"node:os";import C from"node:path";import vt from"node:process";import{z as i}from"zod";import Oe from"node:process";var A={enabled:!1},Le=(e,t=r=>{Oe.stdout.write(r)})=>(A.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
|
-
`),e),ee=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(ee)};var te={source:null},x=()=>te.source!==null,Me=()=>x()||A.enabled,Ke=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let n=e.INFRA_KIT_AGENT;return n==="1"||e.CLAUDECODE!==void 0&&!t&&n!=="0"?"env":null};import P from"node:path";import ae from"node:process";import{$ as f}from"zx";var R=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:n,stderrExcerpt:o}=r;if(typeof n=="string"&&n.length>0)return n;if(typeof o=="string"&&o.length>0)return o;r=r.cause}},We=(e,t)=>{let r=t.stderrExcerpt??R(e),n=[`failed to ${t.operation}`];return r&&n.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&n.push(`try: ${t.remediation}`),n.join(" \u2014 ")},d=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(We(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??R(t)}};var Fe=/^v?(\d+)\.(\d+)\.(\d+)$/,Ge=/^(\d+)\.(\d+)\.(\d+)$/,ze=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I="release/",_="release/v",re="refs/heads/",Ve="next";var ne=new Set(["dev","main","next","hotfix","regular","release"]),k=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},w=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},se=e=>e.startsWith(re)?e.slice(re.length):e,ie=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),O=e=>{if(e.length===0)throw new k('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new k(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!ze.test(e))throw new k(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(ne.has(e))throw new k(`Release name "${e}" is reserved. Reserved names: ${[...ne].join(", ")}.`)},L=e=>{let t=se(e.trim());if(!t.startsWith(I))return null;if(t.startsWith(_)){let n=t.slice(_.length),o=Ge.exec(n);if(o)return ie(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(I.length);try{O(r)}catch{return null}return{kind:"name",name:r,raw:r}},Ue=e=>{let t=e.trim();if(se(t).startsWith(I)){let o=L(t);if(!o)throw new w(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=Fe.exec(t);if(n)return ie(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===Ve)throw new w('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{O(t)}catch(o){let s=o instanceof Error?o.message:String(o);throw new w(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:t,raw:t}},qe=e=>e.kind==="version"?`${_}${e.raw}`:`${I}${e.name}`,Be=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},He=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Xe=e=>e.kind==="version"?`v${e.raw}`:e.name,Je=e=>e.raw,M=e=>e==null?!1:L(e)!==null,oe=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},Ye=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=oe(r?.a),o=oe(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var ce=async e=>{let t=await f({cwd:e})`git worktree list --porcelain`,r=[],n=null;for(let o of t.stdout.split(`
|
|
3
|
-
`)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},Ze=async e=>{let t=await ce(ae.cwd()),r=n=>e==="release"?M(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},Qe=e=>{let t=R(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},et=({hasStderr:e})=>{if(x())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},E=async()=>{try{return(await f({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=Qe(e)??R(e);throw new d(e,{operation:`resolve the project root from ${ae.cwd()}`,stderrExcerpt:t,remediation:et({hasStderr:t!==void 0})})}},K=async e=>{let t=e??await E(),r=(await f({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=P.resolve(t,r);return n.includes(`${P.sep}.git${P.sep}modules${P.sep}`)?t:P.dirname(n)},pe=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),ue=async()=>(await f`git status --porcelain`).stdout.split(`
|
|
4
|
-
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),tt=async()=>(await ue()).length===0,rt=async()=>{let e=await E(),[t,r]=await Promise.all([f({cwd:e})`git rev-parse --absolute-git-dir`,f({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),o=P.resolve(e,r.stdout.trim());return n!==o};var nt=async e=>(await f`git branch --list ${e}`).stdout.trim().length>0,ot=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await pe()!==e&&await f`git branch -D ${e}`},st=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};import{$}from"zx";var it=async(e,t)=>{let r=`${t}^{commit}`;try{return(await $({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},at=async(e,t,r)=>{try{return await $({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(n){if(n.exitCode===1)return!1;throw new d(n,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},ct=async(e,t)=>{let n=(await $({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
5
|
-
`)[0];return n?n.split(/\s+/)[0]??null:null},pt=async(e,t)=>{let r=t.map(n=>`${n.sha}:refs/heads/${n.branch}`);if(r.length===0)return{refspecs:r,pushed:!1};try{return await $({cwd:e,quiet:!0})`git push --atomic origin ${r}`,{refspecs:r,pushed:!0}}catch(n){return{refspecs:r,pushed:!1,stderr:n.stderr}}};import le from"node:path";import W from"node:process";import{$ as g}from"zx";var fe=async e=>{let t=e??W.cwd(),r=(await g({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=W.env.INFRA_KIT_SESSION||String(W.pid);return le.join(le.resolve(t,r),"infra-kit",`merge-dev-${n}`)},F=async e=>{try{return await g({cwd:e,quiet:!0})`git rev-parse -q --verify MERGE_HEAD`,!0}catch{return!1}},ut=async e=>{if(await F(e))throw new d(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:"a merge is still in progress in the scratch worktree",remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"});let t=(await g({cwd:e,quiet:!0})`git status --porcelain`).stdout.trim();if(t.length>0)throw new d(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:`scratch worktree is dirty: ${t.split(`
|
|
6
|
-
`)[0]}`,remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"})},lt=async e=>{let t=async r=>{try{await r()}catch{}};await F(e)&&await t(()=>g({cwd:e,quiet:!0})`git merge --abort`),await t(()=>g({cwd:e,quiet:!0})`git reset --hard`),await t(()=>g({cwd:e,quiet:!0})`git clean -fd`)},ft=async(e,t)=>{let{cwd:r,anchor:n="origin/dev"}=e,o=await fe(r),s=async()=>{await g({cwd:r,quiet:!0})`git worktree add --detach ${o} ${n}`};try{await s()}catch(p){try{await g({cwd:r,quiet:!0})`git worktree prune`,await s()}catch{throw new d(p,{operation:"create the scratch worktree for the merge",remediation:`remove any stale checkout at ${o}, then retry`})}}let a={path:o,remove:async()=>{try{await g({cwd:r,quiet:!0})`git worktree remove --force ${o}`}catch{}}};try{return await t(a)}finally{await a.remove()}};import dt from"node:fs/promises";import gt from"node:os";var mt=async e=>{try{return await dt.access(e),!0}catch{return!1}},G=e=>{let t=gt.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};var me="openInCmux",b="cmux",ht="openInOrca",de="orca",m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ge=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r])=>!t.includes(r))),V=e=>{if(!m(e))return{stripped:[],result:e};let t=[],r=e,n=e.worktrees;if(m(n)){let s=[me,b].filter(a=>a in n);s.length>0&&(t.push(...s.map(a=>`worktrees.${a}`)),r={...r,worktrees:ge(n,s)})}let o=e.devServersPresets;if(m(o)){let s=o;for(let[a,p]of Object.entries(o))!m(p)||!(b in p)||(t.push(`devServersPresets.${a}.${b}`),s={...s,[a]:ge(p,[b])});s!==o&&(r={...r,devServersPresets:s})}return{stripped:t,result:r}},z=(e,t,r)=>{if(!(t in e))return{changed:!1,result:e};let n=r in e;return{changed:!0,result:Object.fromEntries(Object.entries(e).flatMap(([s,a])=>s!==t?[[s,a]]:n?[]:[[r,a]]))}},yt=e=>{if(!m(e))return{changed:!1,result:e};let t=!1,r=e,n=e.worktrees;if(m(n)){let s=z(n,me,ht),a=z(s.result,b,de);(s.changed||a.changed)&&(t=!0,r={...r,worktrees:a.result})}let o=e.devServersPresets;if(m(o)){let s=o;for(let[a,p]of Object.entries(o)){if(!m(p))continue;let l=z(p,b,de);l.changed&&(s={...s,[a]:l.result})}s!==o&&(t=!0,r={...r,devServersPresets:s})}return{changed:t,result:r}};var he="infra-kit.json";var kt="infra-kit.json",xt="projects",wt=i.object({provider:i.literal("doppler"),config:i.object({name:i.string().min(1)})}),Pt=i.discriminatedUnion("provider",[wt]),bt=i.object({workspaceConfigPath:i.string().min(1)}),Rt=i.object({provider:i.literal("cursor"),config:bt}),Et=i.object({}),St=i.object({provider:i.literal("zed"),config:Et}),ye=i.discriminatedUnion("provider",[Rt,St]),Ct=i.union([ye,i.array(ye).min(1)]),jt=i.object({provider:i.literal("jira"),config:i.object({baseUrl:i.string().url(),projectId:i.number().int().positive()})}),At=i.discriminatedUnion("provider",[jt]),It=["two-columns","three-pane"],$t=i.object({layout:i.enum(It).optional()}).strict(),Dt=i.object({openInGithubDesktop:i.boolean().optional(),openInOrca:i.boolean().optional(),orca:$t.optional()}).strict(),Tt=i.object({port:i.number().int().positive().optional(),prefixUrl:i.string().min(1).optional()}).strict(),Nt=i.record(i.string().min(1),Tt),_t=i.enum(["local","cloud"]),Ot=i.object({watchDeps:i.boolean().optional(),proxy:i.record(i.string().min(1),_t).optional()}).strict(),Lt=i.object({apps:i.record(i.string().min(1),Ot).optional(),orca:i.boolean().optional()}).strict(),Mt=i.record(i.string().min(1),Lt),Kt=i.object({port:i.number().int().positive().optional()}).strict(),Wt=i.object({trigger:i.enum(["shell-startup","cli-invocation"]),config:i.string().min(1)}).strict(),Ft=i.enum(["disallow","allow","cli-only"]),ve=i.string().regex(/^[A-Z_]\w*$/i,"must be a POSIX environment-variable name"),Gt=i.object({command:i.string().min(1),args:i.array(i.string()).default([]),env:i.array(ve).min(1),unset:i.array(ve).default([])}).strict().superRefine((e,t)=>{for(let r of e.env)X.has(r)&&t.addIssue({code:"custom",path:["env"],message:`"${r}" is process plumbing the proxy never strips or injects \u2014 it cannot be a credential name`})}),zt=i.record(i.string().regex(/^[a-z][a-z0-9-]*$/,"must be lowercase letters, digits and hyphens, starting with a letter").refine(e=>!e.includes("infra-kit"),{message:'"infra-kit" is reserved for the infra-kit MCP server itself'}),Gt),B=i.object({envManagement:Pt,ide:Ct.optional(),taskManager:At.optional(),worktrees:Dt.optional(),envAutoLoad:Wt.optional(),dev:Nt.optional(),devServersPresets:Mt.optional(),devProxy:Kt.optional(),protectedEnvs:Ft.optional(),mcp:zt.optional()}).strict(),Vt=443,Pe=B.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),be=B.partial(),Ut=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},Re="two-columns",qt=e=>e.worktrees?.orca?.layout??Re,h=null,S=null,Ee=()=>`${vt.cwd()} ${we.homedir()}`,Se=()=>C.join(we.homedir(),T),Ce=()=>C.join(Se(),kt),je=async()=>{let e=Ee();if(S&&S.key===e)return S.value;let t=await E(),r=await K(t),n=C.basename(r),o={main:C.join(t,he),userGlobal:Ce(),userProject:C.join(Se(),xt,n,he),projectName:n};return S={key:e,value:o},o},Bt=async()=>{let e=Ee(),t=await je(),r;try{r=await q.stat(t.main)}catch{h=null;let y=t.main.replace(/\.json$/,".yml");throw await U(y)?new Error(`infra-kit.json not found at ${t.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit setup --skip-tools\` to convert it.`):new Error(x()?`infra-kit.json not found at ${t.main} \u2014 the working directory is not an infra-kit project. Run infra-kit from inside an infra-kit project repo, or pass \`-C <dir>\` naming one.`:`infra-kit.json not found at ${t.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit setup --skip-tools\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[n,o]=await Promise.all([U(t.userGlobal),U(t.userProject)]),s={main:Number(r.mtimeMs),userGlobal:n?Number(n.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(h&&h.key===e&&Yt(h.mtimes,s))return h.value;let a=[{label:"infra-kit.json",path:t.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:t.userGlobal,required:!1},{label:`~/.infra-kit/projects/${t.projectName}/infra-kit.json`,path:t.userProject,required:!1}],p={};for(let y of a){let v=await Zt(y);v!==null&&(p={...p,...v})}let l=Pe.safeParse(p);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${i.prettifyError(l.error)}`);return h={key:e,mtimes:s,value:l.data},l.data},Ht=()=>{h=null},Xt=()=>{h=null,S=null},U=async e=>{try{return await q.stat(e)}catch{return null}},Jt=async e=>{try{return await q.readFile(e,"utf-8")}catch{return null}},Yt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},ke=new Set,Zt=async e=>{let t=await Jt(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(a){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${a.message}`)}if(xe(r)&&"envTokens"in r)throw new Error(er(e));if(!e.required&&xe(r)&&"mcp"in r)throw new Error(Qt(e));let{stripped:n,result:o}=V(r);n.length>0&&!ke.has(e.path)&&(ke.add(e.path),Q.warn(`legacy cmux keys (${n.join(", ")}) in ${G(e.path)} are ignored \u2014 run \`infra-kit setup\` to migrate them to orca`));let s=be.safeParse(o);if(!s.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${i.prettifyError(s.error)}`);return s.data},Qt=e=>[`"mcp" is not allowed in ${e.label} (${e.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,"Move the block to the project infra-kit.json and run `infra-kit setup`.","For a machine-only override of one server (e.g. a local fork), use Claude Code directly:"," claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>","(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected)."].join(`
|
|
7
|
-
`),xe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),er=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
8
|
-
`);import*as u from"node:fs";import*as c from"node:path";function tr(e){let t=e;for(let r=0;r<10;r++){let n=c.join(t,"pnpm-workspace.yaml");if(u.existsSync(n))return t;t=c.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function Ie(e,t){let r=c.join(e,"package.json");if(!u.existsSync(r))return t;try{let n=JSON.parse(u.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function Pn(e){let t=c.join(e,"apps"),r=[];if(!u.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=u.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let s=c.join(t,o,"api"),a=c.join(s,"serverless.yml");u.existsSync(a)&&r.push({name:o,packageName:Ie(s,o),path:s})}return r}var $e=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],rr=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function nr(e){for(let t of $e){let r=c.join(e,t);if(u.existsSync(r))try{let n=u.readFileSync(r,"utf-8");return rr.some(o=>n.includes(o))}catch{return!1}}return!1}function bn(e){for(let t of $e){let r=c.join(e,t);if(u.existsSync(r))try{return u.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function or(e){let t=c.join(e,"package.json");if(!u.existsSync(t))return!1;try{let r=JSON.parse(u.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function Rn(e){let t=c.join(e,"apps"),r=[];if(!u.existsSync(t))return r;let n=u.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let s=c.join(t,o,"ui");u.existsSync(s)&&or(s)&&r.push({name:o,packageName:Ie(s,o),path:s,managedPort:nr(s)})}return r}function En(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function Sn(e){let t=tr(e),r=c.relative(c.join(t,"apps"),e),n=r.split(c.sep)[0];if(r===""||r.startsWith("..")||c.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var sr=new Set(["api","ui"]),Ae=e=>{let t=c.join(e,"dist");return u.existsSync(t)&&u.statSync(t).isDirectory()?t:void 0},H=e=>u.existsSync(e)?u.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function Cn(e){let t=[];for(let n of H(c.join(e,"packages"))){let o=Ae(c.join(e,"packages",n));o!==void 0&&t.push(o)}let r=c.join(e,"apps");for(let n of H(r))for(let o of H(c.join(r,n))){if(sr.has(o))continue;let s=c.join(r,n,o);if(!u.existsSync(c.join(s,"package.json")))continue;let a=Ae(s);a!==void 0&&t.push(a)}return t}function jn(e){return e.map(t=>c.join(t.path,"dist")).filter(t=>u.existsSync(t))}function An(e,t,r){let n=c.normalize(e),o=r.find(a=>n.startsWith(c.normalize(a)));return o?{kind:"package",packageDir:o}:{kind:"app",app:t.find(a=>n.startsWith(c.normalize(a)))}}var ir={"*/api":{},"*/ui":{}},Te=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},ar=e=>{let t=Te(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},$n=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let s=Te(o);s&&t.push({preset:r,key:o,message:`preset "${r}": ${s}`})}return t},cr=(e,t)=>t==="api"?e.api:e.ui,pr=e=>[...new Set([...e.api,...e.ui])].sort(),De=(e,t)=>`${e}/${t}`,ur=e=>e?0:1,lr=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,fr=(e,t,r)=>{let{app:n,part:o,watchDeps:s,isGlob:a}=r;if(!cr(t,o).includes(n)){a||e.unmatched.push(De(n,o));return}let p=De(n,o),l=lr(e.targets.get(p),{watchDeps:s,rank:ur(a)});e.targets.set(p,{app:n,part:o,...l})},dr=(e,t)=>{let r=Object.entries(e.apps??ir),n={targets:new Map,proxy:{},unmatched:[]};for(let[a,p]of r){let{appGlob:l,part:y}=ar(a),v=l==="*",j=v?pr(t):[l];for(let D of j)fr(n,t,{app:D,part:y,watchDeps:p.watchDeps,isGlob:v}),p.proxy&&(n.proxy[D]={...n.proxy[D]??{},...p.proxy})}let o=[...n.targets.values()].map(({app:a,part:p,watchDeps:l})=>({app:a,part:p,watchDeps:l})),s=[...new Set(o.filter(a=>a.part==="api").map(a=>a.app))];return{targets:o,orca:e.orca??!1,proxy:n.proxy,localApps:s,unmatched:n.unmatched}},Dn=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},gr=(e,t)=>Object.keys(e).find(r=>e[r]===t),mr=({preset:e,app:t,route:r,launchedPkgs:n,ctx:o})=>{let s=o.routePkg(t,r);if(s===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(s))return null;let a=gr(o.apiPkgByApp,s),p=a?`add "${a}/api" to the preset`:`launch the api whose package is "${s}"`;return{preset:e,app:t,route:r,pkg:s,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${s}" to run locally, but the preset does not launch it \u2014 ${p}, or set "${r}" to "cloud"`}},Tn=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let s=dr(o,t.discovered),a=new Set(s.localApps.map(p=>t.apiPkgByApp[p]).filter(p=>p!==void 0));for(let[p,l]of Object.entries(s.proxy))for(let[y,v]of Object.entries(l)){if(v!=="local")continue;let j=mr({preset:n,app:p,route:y,launchedPkgs:a,ctx:t});j&&r.push(j)}}return r};export{A as a,Le as b,ee as c,te as d,x as e,Me as f,Ke as g,R as h,d as i,k as j,O as k,L as l,Ue as m,qe as n,Be as o,He as p,Xe as q,Je as r,M as s,Ye as t,ce as u,Ze as v,E as w,K as x,pe as y,ue as z,tt as A,rt as B,nt as C,ot as D,st as E,it as F,at as G,ct as H,pt as I,F as J,ut as K,lt as L,ft as M,J as N,kr as O,Q as P,mt as Q,G as R,V as S,yt as T,Vt as U,Pe as V,be as W,Ut as X,qt as Y,Ce as Z,je as _,Bt as $,Ht as aa,Xt as ba,tr as ca,Pn as da,bn as ea,Rn as fa,En as ga,Sn as ha,Cn as ia,jn as ja,An as ka,Te as la,$n as ma,dr as na,Dn as oa,Tn as pa};
|
|
9
|
-
//# sourceMappingURL=chunk-H5AAXCRJ.js.map
|