infra-kit 0.34.0 → 0.36.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-LC2ESPY6.js → boot-ST2534PA.js} +2 -2
- package/dist/boot-ST2534PA.js.map +7 -0
- package/dist/{chunk-5ZBDB3U7.js → chunk-3JFITLZG.js} +2 -2
- package/dist/chunk-3JFITLZG.js.map +7 -0
- package/dist/{chunk-SAHE3MZJ.js → chunk-55F372Z7.js} +1 -1
- package/dist/{chunk-SAHE3MZJ.js.map → chunk-55F372Z7.js.map} +2 -2
- package/dist/chunk-BPOPODWW.js +15 -0
- package/dist/chunk-BPOPODWW.js.map +7 -0
- package/dist/{chunk-I23MDR4X.js → chunk-GCOYOWGH.js} +1 -1
- package/dist/{chunk-I23MDR4X.js.map → chunk-GCOYOWGH.js.map} +2 -2
- package/dist/{chunk-XES5EOEE.js → chunk-PP44RGIU.js} +2 -2
- package/dist/chunk-PP44RGIU.js.map +7 -0
- package/dist/{chunk-7A4LVTRJ.js → chunk-QS7RKE5P.js} +2 -2
- package/dist/chunk-QS7RKE5P.js.map +7 -0
- package/dist/{chunk-AWFGP6GY.js → chunk-REDCBY4O.js} +1 -1
- package/dist/{chunk-AWFGP6GY.js.map → chunk-REDCBY4O.js.map} +2 -2
- package/dist/{chunk-QCTAEXMN.js → chunk-SBG3HRSC.js} +6 -6
- package/dist/{chunk-QCTAEXMN.js.map → chunk-SBG3HRSC.js.map} +2 -2
- package/dist/{chunk-U7VGROH3.js → chunk-TCQXTDVZ.js} +2 -2
- package/dist/{chunk-U7VGROH3.js.map → chunk-TCQXTDVZ.js.map} +1 -1
- package/dist/{chunk-MWGE43QS.js → chunk-TGEAIKD6.js} +2 -2
- package/dist/{chunk-MWGE43QS.js.map → chunk-TGEAIKD6.js.map} +2 -2
- package/dist/{chunk-DVXTZPQ5.js → chunk-UTQ4KTO6.js} +1 -1
- package/dist/{chunk-DVXTZPQ5.js.map → chunk-UTQ4KTO6.js.map} +2 -2
- package/dist/{chunk-TVG47UHG.js → chunk-V2ZLQPLI.js} +1 -1
- package/dist/{chunk-TVG47UHG.js.map → chunk-V2ZLQPLI.js.map} +2 -2
- package/dist/cli.js +145 -127
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +5 -5
- package/dist/dev-server.js.map +2 -2
- package/dist/{dev-wizard-run-452R76HN.js → dev-wizard-run-PAHX7EMH.js} +2 -2
- package/dist/dev-wizard-run-PAHX7EMH.js.map +7 -0
- package/dist/{env-load-IXDGWGPV.js → env-load-XBKASGXP.js} +2 -2
- package/dist/mcp-proxy.js +1 -1
- package/dist/mcp-proxy.js.map +2 -2
- package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js → persistent-ink-dev-ui-D6ALK2P3.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/dist/boot-LC2ESPY6.js.map +0 -7
- package/dist/chunk-467ZSXYU.js +0 -15
- package/dist/chunk-467ZSXYU.js.map +0 -7
- package/dist/chunk-5ZBDB3U7.js.map +0 -7
- package/dist/chunk-7A4LVTRJ.js.map +0 -7
- package/dist/chunk-XES5EOEE.js.map +0 -7
- package/dist/dev-wizard-run-452R76HN.js.map +0 -7
- /package/dist/{env-load-IXDGWGPV.js.map → env-load-XBKASGXP.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js.map → persistent-ink-dev-ui-D6ALK2P3.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/dev/discovery.ts", "../src/dev/presets.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the helper import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * Every module specifier that binds a UI to infra-kit's dev wiring \u2014 whether through the raw\n * `infraKitDev` helper or through the `@slip-stream-kit/vite` plugin that wraps it.\n *\n * Matched as a SUBSTRING of a config's import specifiers. This is what makes `managedPort` true, so a\n * MISSING entry is not cosmetic: the runner would stop claiming the port for every UI on that specifier,\n * and with it the hero URL. Drop the legacy entry once every consumer repo is migrated.\n */\n// A LIST, not a single literal, because the wiring moved packages twice: it used to ship from the\n// `infra-kit` CLI itself, then from `@slip-stream-kit/config` (the split that let the CLI become a global\n// install \u2014 a local `node_modules/.bin/infra-kit` would otherwise shadow the global bin, see that\n// package's readme), and the plugin form now ships from `@slip-stream-kit/vite`. Consumers migrate one\n// repo at a time, so all three specifiers are live.\n//\n// The substring match is why the config package could not be called `@infra-kit/vite`: that name\n// *contains* `infra-kit/vite`, so the legacy entry would have matched it by accident and hidden the very\n// coupling the split makes explicit. Neither `@slip-stream-kit/config/vite` nor `@slip-stream-kit/vite`\n// contains any other entry, so no entry here shadows another.\nexport const INFRA_KIT_VITE_SPECIFIERS = [\n '@slip-stream-kit/vite',\n '@slip-stream-kit/config/vite',\n 'infra-kit/vite',\n] as const\n\n/**\n * True when `<dir>`'s vite config references the `infraKitDev` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n const source = fs.readFileSync(configPath, 'utf-8')\n\n return INFRA_KIT_VITE_SPECIFIERS.some((specifier) => {\n return source.includes(specifier)\n })\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/**\n * True when `<dir>`'s vite config wires the `infraKit()` PLUGIN specifically \u2014 not just the raw\n * `infraKitDev()` helper it wraps (see {@link usesInfraKitVite}, which matches either). Only the\n * plugin watches `.infra-kit/dev-context` and restarts vite when the resolved proxy changes; a\n * config that calls the helper directly bakes its proxy at config load and will not react to a\n * backend recovering mid-session (see `dev-server.ts`'s boot warning for this).\n *\n * No structural signal exists to check instead: the plugin writes nothing to disk at config load,\n * so this is the same conservative text match as {@link usesInfraKitVite} \u2014 a config source read,\n * not a module load. The substring is the plugin's call syntax, `infraKit(`; it cannot false-match\n * `infraKitDev(`, whose next character after `infraKit` is `D`, not `(`. A false negative (e.g. the\n * plugin re-exported from a shared preset under a different call shape) only costs a spurious\n * warning \u2014 never a missed one \u2014 which is the safe direction here.\n */\nexport function usesInfraKitVitePlugin(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n return fs.readFileSync(configPath, 'utf-8').includes('infraKit(')\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`).\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\n// A shared library may legally live beside the app that owns it \u2014 hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`,\n// and two backends depend on it. Scanning only `packages` left such a package watched by nobody: turbo\n// rebuilt its dist, the runner never saw the change, and every dependent backend kept serving stale code.\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n const isInside = (dir: string): boolean => {\n const normalizedDir = path.normalize(dir)\n\n return normalized === normalizedDir || normalized.startsWith(normalizedDir + path.sep)\n }\n\n const matchedPackageDir = packageDistDirs.find(isInside)\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find(isInside)\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of an in-memory dev run plan into the flat set of packages to launch.\n *\n * The plan is built by `infra-kit dev <app>` ({@link file://./app-plan.ts}), `--target`, and the\n * interactive wizard \u2014 never read from config. It names launch targets (`client/api`, `client/ui`, with\n * `*` allowed in the app position) and per-route proxy-source pins. Side-effect free: the discovered\n * app parts are passed in (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\n\n/** Where a proxy route resolves: a locally launched backend, or the deployed cloud target. */\nexport type ProxySource = 'local' | 'cloud'\n\n/** One run plan: target key \u2192 that target's per-route proxy pins. Omit `apps` to run every package. */\nexport interface DevPreset {\n apps?: Record<string, { proxy?: Record<string, ProxySource> }>\n}\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved plan: the flat set of packages derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /**\n * app \u2192 (route path \u2192 source) pins, as DECLARED by the plan.\n *\n * Not an input to proxy resolution, and never has been: the vite helper derives a route's source from\n * the dev-context fragments the runner writes, so a route is local iff its backend is actually up. This\n * map is the declared INTENT, and it has two readers:\n * - `validatePresetProxy` \u2014 the STATIC check, run by the bare-invocation wizard;\n * - `local-pairing.ts` \u2014 the RUNTIME check, which folds a `local` pin into the set of packages the run\n * intended to serve locally, and refuses when one of them is not actually up.\n */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a plan omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across plan keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTarget>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists, and flag a\n * named-but-missing package as unmatched (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; isGlob: boolean },\n): void => {\n const { app, part, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n state.targets.set(targetId(app, part), { app, part })\n}\n\n/**\n * Resolve a plan against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy pins. A missing named target lands in\n * `unmatched` rather than throwing \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset({ apps: { 'client/ui': {}, 'client/api': {} } }, { api: ['client'], ui: ['client'] })\n * // => { targets: [{ app: 'client', part: 'ui' }, { app: 'client', part: 'api' }],\n * // proxy: {}, localApps: ['client'], unmatched: [] }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets = [...state.targets.values()]\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** The `<app>/<part>` package keys actually being launched, after plan resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label: the set of `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A proxy-locality violation in a run plan. */\nexport interface PresetProxyIssue {\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (the wizard) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving the plan's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the plan's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n app,\n route,\n kind: 'unknown-route',\n message: `proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the selection` : `launch the api whose package is \"${pkg}\"`\n\n return {\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but nothing launches it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit a plan's per-route proxy pins: a route pinned to `local` is only valid when the backend\n * package it resolves to (per the frontend's `infra-kit.config.ts`) is actually launched by that same\n * plan. Catches the `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` pins are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { apps: { 'client/ui': { proxy: { '/api': 'local' } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ app: 'client', route: '/api', pkg: 'backend-api', kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (plan: DevPreset, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const resolved = resolvePreset(plan, ctx.discovered)\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n return Object.entries(resolved.proxy).flatMap(([app, routes]) => {\n return Object.entries(routes).flatMap(([route, source]) => {\n const issue = source === 'local' ? checkLocalRoute({ app, route, launchedPkgs, ctx }) : null\n\n return issue ? [issue] : []\n })\n })\n}\n"],
|
|
5
|
-
"mappings": "AAQA,UAAYA,MAAQ,UACpB,UAAYC,MAAU,YAYf,SAASC,EAAiBC,EAA0B,CACzD,IAAIC,EAAaD,EAEjB,QAASE,EAAI,EAAGA,EAAI,GAAIA,IAAK,CAC3B,IAAMC,EAAqB,OAAKF,EAAY,qBAAqB,EAEjE,GAAO,aAAWE,CAAa,EAC7B,OAAOF,EAETA,EAAkB,UAAQA,CAAU,CACtC,CAEA,MAAM,IAAI,MAAM,oDAAoD,CACtE,CAGO,SAASG,EAAeC,EAAiBC,EAAyB,CACvE,IAAMC,EAAe,OAAKF,EAAS,cAAc,EAEjD,GAAI,CAAI,aAAWE,CAAO,EAAG,OAAOD,EAEpC,GAAI,CACF,IAAME,EAAM,KAAK,MAAS,eAAaD,EAAS,OAAO,CAAC,EAExD,OAAO,OAAOC,EAAI,MAAS,SAAWA,EAAI,KAAOF,CACnD,MAAQ,CACN,OAAOA,CACT,CACF,CAGO,SAASG,EAAgBC,EAAkC,CAChE,IAAMC,EAAe,OAAKD,EAAM,MAAM,EAChCE,EAA2B,CAAC,EAElC,GAAI,CAAI,aAAWD,CAAO,EACxB,MAAM,IAAI,MAAM,6BAA6BA,CAAO,EAAE,EAGxD,IAAME,EACH,cAAYF,EAAS,CAAE,cAAe,EAAK,CAAC,EAC5C,OAAQG,GACAA,EAAO,YAAY,CAC3B,EACA,IAAKA,GACGA,EAAO,IAC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AAE,IACV,EAT6B,CAAC,EA4B5B,SAASC,EAAmB7B,EAAwB,CACzD,IAAM8B,EAAiB,CAAC,EAExB,QAAWC,KAAQJ,EAAiB,OAAK3B,EAAM,UAAU,CAAC,EAAG,CAC3D,IAAM0B,EAAUD,EAAqB,OAAKzB,EAAM,WAAY+B,CAAI,CAAC,EAE7DL,IAAY,QAAWI,EAAK,KAAKJ,CAAO,CAC9C,CAEA,IAAMzB,EAAe,OAAKD,EAAM,MAAM,EAEtC,QAAWgC,KAAOL,EAAY1B,CAAO,EACnC,QAAWgC,KAAQN,EAAiB,OAAK1B,EAAS+B,CAAG,CAAC,EAAG,CACvD,GAAIR,EAAc,IAAIS,CAAI,EAAG,SAE7B,IAAMC,EAAe,OAAKjC,EAAS+B,EAAKC,CAAI,EAG5C,GAAI,CAAI,aAAgB,OAAKC,EAAS,cAAc,CAAC,EAAG,SAExD,IAAMR,EAAUD,EAAgBS,CAAO,EAEnCR,IAAY,QAAWI,EAAK,KAAKJ,CAAO,CAC9C,CAGF,OAAOI,CACT,CAGO,SAASK,EAAejC,EAAyC,CACtE,OAAOA,EACJ,IAAK8B,GACQ,OAAKA,EAAI,KAAM,MAAM,CAClC,EACA,OAAQvB,GACG,aAAWA,CAAG,CACzB,CACL,CAkBO,SAAS2B,EACdC,EACAC,EACAC,EACsB,CACtB,IAAMC,EAAkB,YAAUH,CAAW,
|
|
4
|
+
"sourcesContent": ["/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the helper import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * Every module specifier that binds a UI to infra-kit's dev wiring \u2014 whether through the raw\n * `infraKitDev` helper or through the `@slip-stream-kit/vite` plugin that wraps it.\n *\n * Matched as a SUBSTRING of a config's import specifiers. This is what makes `managedPort` true, so a\n * MISSING entry is not cosmetic: the runner would stop claiming the port for every UI on that specifier,\n * and with it the hero URL. Drop the legacy entry once every consumer repo is migrated.\n */\n// A LIST, not a single literal, because the wiring moved packages twice: it used to ship from the\n// `infra-kit` CLI itself, then from `@slip-stream-kit/config` (the split that let the CLI become a global\n// install \u2014 a local `node_modules/.bin/infra-kit` would otherwise shadow the global bin, see that\n// package's readme), and the plugin form now ships from `@slip-stream-kit/vite`. Consumers migrate one\n// repo at a time, so all three specifiers are live.\n//\n// The substring match is why the config package could not be called `@infra-kit/vite`: that name\n// *contains* `infra-kit/vite`, so the legacy entry would have matched it by accident and hidden the very\n// coupling the split makes explicit. Neither `@slip-stream-kit/config/vite` nor `@slip-stream-kit/vite`\n// contains any other entry, so no entry here shadows another.\nexport const INFRA_KIT_VITE_SPECIFIERS = [\n '@slip-stream-kit/vite',\n '@slip-stream-kit/config/vite',\n 'infra-kit/vite',\n] as const\n\n/**\n * True when `<dir>`'s vite config references the `infraKitDev` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n const source = fs.readFileSync(configPath, 'utf-8')\n\n return INFRA_KIT_VITE_SPECIFIERS.some((specifier) => {\n return source.includes(specifier)\n })\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/**\n * True when `<dir>`'s vite config wires the `infraKit()` PLUGIN specifically \u2014 not just the raw\n * `infraKitDev()` helper it wraps (see {@link usesInfraKitVite}, which matches either). Only the\n * plugin watches `.infra-kit/dev-context` and restarts vite when the resolved proxy changes; a\n * config that calls the helper directly bakes its proxy at config load and will not react to a\n * backend recovering mid-session (see `dev-server.ts`'s boot warning for this).\n *\n * No structural signal exists to check instead: the plugin writes nothing to disk at config load,\n * so this is the same conservative text match as {@link usesInfraKitVite} \u2014 a config source read,\n * not a module load. The substring is the plugin's call syntax, `infraKit(`; it cannot false-match\n * `infraKitDev(`, whose next character after `infraKit` is `D`, not `(`. A false negative (e.g. the\n * plugin re-exported from a shared preset under a different call shape) only costs a spurious\n * warning \u2014 never a missed one \u2014 which is the safe direction here.\n */\nexport function usesInfraKitVitePlugin(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n return fs.readFileSync(configPath, 'utf-8').includes('infraKit(')\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`).\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\n// A shared library may legally live beside the app that owns it \u2014 hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`,\n// and two backends depend on it. Scanning only `packages` left such a package watched by nobody: turbo\n// rebuilt its dist, the runner never saw the change, and every dependent backend kept serving stale code.\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n\n const isInside = (dir: string): boolean => {\n const normalizedDir = path.normalize(dir)\n\n return normalized === normalizedDir || normalized.startsWith(normalizedDir + path.sep)\n }\n\n const matchedPackageDir = packageDistDirs.find(isInside)\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find(isInside)\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of an in-memory dev run plan into the flat set of packages to launch.\n *\n * The plan is built by `infra-kit dev <app>` ({@link file://./app-plan.ts}), `--target`, and the\n * interactive wizard \u2014 never read from config. It names launch targets (`client/api`, `client/ui`, with\n * `*` allowed in the app position) and per-route proxy-source pins. Side-effect free: the discovered\n * app parts are passed in (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\n\n/** Where a proxy route resolves: a locally launched backend, or the deployed cloud target. */\nexport type ProxySource = 'local' | 'cloud'\n\n/** One run plan: target key \u2192 that target's per-route proxy pins. Omit `apps` to run every package. */\nexport interface DevPreset {\n apps?: Record<string, { proxy?: Record<string, ProxySource> }>\n}\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved plan: the flat set of packages derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /**\n * app \u2192 (route path \u2192 source) pins, as DECLARED by the plan.\n *\n * Not an input to proxy resolution, and never has been: the vite helper derives a route's source from\n * the dev-context fragments the runner writes, so a route is local iff its backend is actually up. This\n * map is the declared INTENT, and it has two readers:\n * - `validatePresetProxy` \u2014 the STATIC check, run by the bare-invocation wizard;\n * - `local-pairing.ts` \u2014 the RUNTIME check, which folds a `local` pin into the set of packages the run\n * intended to serve locally, and refuses when one of them is not actually up.\n */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a plan omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across plan keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTarget>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists, and flag a\n * named-but-missing package as unmatched (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; isGlob: boolean },\n): void => {\n const { app, part, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n state.targets.set(targetId(app, part), { app, part })\n}\n\n/**\n * Resolve a plan against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy pins. A missing named target lands in\n * `unmatched` rather than throwing \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset({ apps: { 'client/ui': {}, 'client/api': {} } }, { api: ['client'], ui: ['client'] })\n * // => { targets: [{ app: 'client', part: 'ui' }, { app: 'client', part: 'api' }],\n * // proxy: {}, localApps: ['client'], unmatched: [] }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets = [...state.targets.values()]\n\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** The `<app>/<part>` package keys actually being launched, after plan resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label: the set of `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A proxy-locality violation in a run plan. */\nexport interface PresetProxyIssue {\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (the wizard) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving the plan's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the plan's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n app,\n route,\n kind: 'unknown-route',\n message: `proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the selection` : `launch the api whose package is \"${pkg}\"`\n\n return {\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but nothing launches it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit a plan's per-route proxy pins: a route pinned to `local` is only valid when the backend\n * package it resolves to (per the frontend's `infra-kit.config.ts`) is actually launched by that same\n * plan. Catches the `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` pins are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { apps: { 'client/ui': { proxy: { '/api': 'local' } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ app: 'client', route: '/api', pkg: 'backend-api', kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (plan: DevPreset, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const resolved = resolvePreset(plan, ctx.discovered)\n\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n return Object.entries(resolved.proxy).flatMap(([app, routes]) => {\n return Object.entries(routes).flatMap(([route, source]) => {\n const issue = source === 'local' ? checkLocalRoute({ app, route, launchedPkgs, ctx }) : null\n\n return issue ? [issue] : []\n })\n })\n}\n"],
|
|
5
|
+
"mappings": "AAQA,UAAYA,MAAQ,UACpB,UAAYC,MAAU,YAYf,SAASC,EAAiBC,EAA0B,CACzD,IAAIC,EAAaD,EAEjB,QAASE,EAAI,EAAGA,EAAI,GAAIA,IAAK,CAC3B,IAAMC,EAAqB,OAAKF,EAAY,qBAAqB,EAEjE,GAAO,aAAWE,CAAa,EAC7B,OAAOF,EAETA,EAAkB,UAAQA,CAAU,CACtC,CAEA,MAAM,IAAI,MAAM,oDAAoD,CACtE,CAGO,SAASG,EAAeC,EAAiBC,EAAyB,CACvE,IAAMC,EAAe,OAAKF,EAAS,cAAc,EAEjD,GAAI,CAAI,aAAWE,CAAO,EAAG,OAAOD,EAEpC,GAAI,CACF,IAAME,EAAM,KAAK,MAAS,eAAaD,EAAS,OAAO,CAAC,EAExD,OAAO,OAAOC,EAAI,MAAS,SAAWA,EAAI,KAAOF,CACnD,MAAQ,CACN,OAAOA,CACT,CACF,CAGO,SAASG,EAAgBC,EAAkC,CAChE,IAAMC,EAAe,OAAKD,EAAM,MAAM,EAChCE,EAA2B,CAAC,EAElC,GAAI,CAAI,aAAWD,CAAO,EACxB,MAAM,IAAI,MAAM,6BAA6BA,CAAO,EAAE,EAGxD,IAAME,EACH,cAAYF,EAAS,CAAE,cAAe,EAAK,CAAC,EAC5C,OAAQG,GACAA,EAAO,YAAY,CAC3B,EACA,IAAKA,GACGA,EAAO,IACf,EAEH,QAAWR,KAAWO,EAAS,CAC7B,IAAMR,EAAe,OAAKM,EAASL,EAAS,KAAK,EAC3CS,EAAsB,OAAKV,EAAS,gBAAgB,EAEnD,aAAWU,CAAc,GAC9BH,EAAK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AEpG,MAAO,CACL,IAAAlB,EACA,MAAAoB,EACA,IAAAF,EACA,KAAM,uBACN,QAAS,mBAAmBE,CAAK,sCAAiCF,CAAG,oDAA+CM,CAAI,aAAaJ,CAAK,cAC5I,CACF,EAgBaK,EAAsB,CAACC,EAAiBJ,IAAgD,CACnG,IAAMK,EAAWtB,EAAcqB,EAAMJ,EAAI,UAAU,EAE7CD,EAAe,IAAI,IACvBM,EAAS,UACN,IAAK3B,GACGsB,EAAI,YAAYtB,CAAG,CAC3B,EACA,OAAQkB,GACAA,IAAQ,MAChB,CACL,EAEA,OAAO,OAAO,QAAQS,EAAS,KAAK,EAAE,QAAQ,CAAC,CAAC3B,EAAK4B,CAAM,IAClD,OAAO,QAAQA,CAAM,EAAE,QAAQ,CAAC,CAACR,EAAOS,CAAM,IAAM,CACzD,IAAMC,EAAQD,IAAW,QAAUV,EAAgB,CAAE,IAAAnB,EAAK,MAAAoB,EAAO,aAAAC,EAAc,IAAAC,CAAI,CAAC,EAAI,KAExF,OAAOQ,EAAQ,CAACA,CAAK,EAAI,CAAC,CAC5B,CAAC,CACF,CACH",
|
|
6
6
|
"names": ["fs", "path", "findMonorepoRoot", "startDir", "currentDir", "i", "workspaceFile", "getPackageName", "apiPath", "appName", "pkgPath", "pkg", "discoverApiApps", "root", "appsDir", "apps", "appDirs", "dirent", "serverlessPath", "VITE_CONFIG_FILES", "INFRA_KIT_VITE_SPECIFIERS", "usesInfraKitVite", "dir", "file", "configPath", "source", "specifier", "usesInfraKitVitePlugin", "hasDevScript", "discoverUiApps", "uiPath", "normalizeAppInclude", "include", "filtered", "resolveSelfAppName", "relative", "firstSegment", "APP_PART_DIRS", "existingDistDir", "distDir", "subdirNames", "d", "getPackageDistDirs", "dirs", "name", "app", "part", "partDir", "getAppDistDirs", "classifyDistChange", "changedPath", "appDistDirs", "packageDistDirs", "normalized", "isInside", "normalizedDir", "matchedPackageDir", "ALL_TARGETS_KEYS", "explainTargetKey", "key", "segments", "appGlob", "part", "parseTargetKey", "error", "appsWithPart", "discovered", "allApps", "targetId", "app", "addTarget", "state", "spec", "isGlob", "resolvePreset", "preset", "entries", "cfg", "apps", "targets", "localApps", "t", "deriveTargetLabel", "input", "running", "ownerApp", "apiPkgByApp", "pkg", "checkLocalRoute", "route", "launchedPkgs", "ctx", "owner", "hint", "validatePresetProxy", "plan", "resolved", "routes", "source", "issue"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{a as ce}from"./chunk-MFAFQVTW.js";import{a as ae}from"./chunk-TCQXTDVZ.js";import{e as L,q as K,s as W}from"./chunk-GCOYOWGH.js";import ze from"node:process";import Ge from"node:process";var C={enabled:!1},Be=(e,t=r=>{Ge.stdout.write(r)})=>(C.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
|
+
`),e),ue=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)");for(let r of e.commands)ue(r)};var S={source:null},w=()=>S.source!==null,He=()=>w()||C.enabled,D=()=>!!ze.env.CI,Ue=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let o=e.INFRA_KIT_AGENT;return o==="1"||e.CLAUDECODE!==void 0&&!t&&o!=="0"?"env":null};var v=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:o,stderrExcerpt:n}=r;if(typeof o=="string"&&o.length>0)return o;if(typeof n=="string"&&n.length>0)return n;r=r.cause}},Je=(e,t)=>{let r=t.stderrExcerpt??v(e),o=[`failed to ${t.operation}`];return r&&o.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&o.push(`try: ${t.remediation}`),o.join(" \u2014 ")},u=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(Je(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??v(t)}};import k from"node:path";import fe from"node:process";import{$ as m}from"zx";var Xe=/^v?(\d+)\.(\d+)\.(\d+)$/,Ye=/^(\d+)\.(\d+)\.(\d+)$/,Ze=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,P="release/",F="release/v",me="refs/heads/",Qe="next";var de=new Set(["dev","main","next","hotfix","regular","release"]),h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},y=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},le=e=>e.startsWith(me)?e.slice(me.length):e,ge=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),q=e=>{if(e.length===0)throw new h('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new h(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Ze.test(e))throw new h(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(de.has(e))throw new h(`Release name "${e}" is reserved. Reserved names: ${[...de].join(", ")}.`)},V=e=>{let t=le(e.trim());if(!t.startsWith(P))return null;if(t.startsWith(F)){let o=t.slice(F.length),n=Ye.exec(o);if(n)return ge(Number(n[1]),Number(n[2]),Number(n[3]))}let r=t.slice(P.length);try{q(r)}catch{return null}return{kind:"name",name:r,raw:r}},et=e=>{let t=e.trim();if(le(t).startsWith(P)){let n=V(t);if(!n)throw new y(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=Xe.exec(t);if(o)return ge(Number(o[1]),Number(o[2]),Number(o[3]));if(t.toLowerCase()===Qe)throw new y('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');if(t.includes("@"))throw new y(`Cannot parse "${e}" as a release ref: the \`@date\` suffix belongs to \`release create\`; pass the version alone here and use \`--release-date\` on \`release edit\``);try{q(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new y(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:t,raw:t}},tt=e=>e.kind==="version"?`${F}${e.raw}`:`${P}${e.name}`,rt=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},ot=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,nt=e=>e.kind==="version"?`v${e.raw}`:e.name,it=e=>e.raw,G=e=>e==null?!1:V(e)!==null,pe=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},st=(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 o=pe(r?.a),n=pe(r?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<t.name?-1:e.name>t.name?1:0};var he=async e=>{let t=await m({cwd:e})`git worktree list --porcelain`,r=[],o=null;for(let n of t.stdout.split(`
|
|
3
|
+
`)){if(n.startsWith("worktree ")){o&&r.push(o),o={path:n.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}o&&(n.startsWith("branch ")?o.branch=n.slice(7).replace(/^refs\/heads\//,""):n==="detached"?o.detached=!0:n==="bare"?o.bare=!0:n==="locked"||n.startsWith("locked ")?o.locked=!0:(n==="prunable"||n.startsWith("prunable "))&&(o.prunable=!0))}return o&&r.push(o),r},at=async e=>{let t=await he(fe.cwd()),r=o=>e==="release"?G(o):o.startsWith("feature/");return t.map(o=>o.branch).filter(o=>o!==null&&r(o))},ct=e=>{let t=v(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},ut=({hasStderr:e})=>{if(w())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},R=async()=>{try{return(await m({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=ct(e)??v(e);throw new u(e,{operation:`resolve the project root from ${fe.cwd()}`,stderrExcerpt:t,remediation:ut({hasStderr:t!==void 0})})}},B=async e=>{let t=e??await R(),r=(await m({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=k.resolve(t,r);return o.includes(`${k.sep}.git${k.sep}modules${k.sep}`)?t:k.dirname(o)},ye=async()=>(await m`git rev-parse --abbrev-ref HEAD`).stdout.trim(),we=async()=>(await m`git status --porcelain`).stdout.split(`
|
|
4
|
+
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),mt=async()=>(await we()).length===0,dt=async()=>{let e=await R(),[t,r]=await Promise.all([m({cwd:e})`git rev-parse --absolute-git-dir`,m({cwd:e})`git rev-parse --git-common-dir`]),o=t.stdout.trim(),n=k.resolve(e,r.stdout.trim());return o!==n};var pt=async e=>(await m`git branch --list ${e}`).stdout.trim().length>0,lt=async e=>{(await m`git branch --list ${e}`).stdout.trim().length!==0&&await ye()!==e&&await m`git branch -D ${e}`},gt=async e=>{(await m`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await m`git push origin --delete ${e}`};import{$}from"zx";var ft=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}},ht=async(e,t,r)=>{try{return await $({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(o){if(o.exitCode===1)return!1;throw new u(o,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},yt=async(e,t)=>{let o=(await $({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
5
|
+
`)[0];return o?o.split(/\s+/)[0]??null:null},wt=async(e,t)=>{let r=t.map(o=>`${o.sha}:refs/heads/${o.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(o){return{refspecs:r,pushed:!1,stderr:o.stderr}}};import I from"node:path";import z from"node:process";import{$ as p}from"zx";var ke=async e=>{let t=e??z.cwd(),r=(await p({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=I.dirname(I.resolve(t,r)),n=z.env.INFRA_KIT_SESSION||String(z.pid);return I.join(`${o}${K}`,W.mergeDev,`.scratch-${n}`)},ve=e=>e.replace(/[^\w-]+/g,"-"),kt=(e,t)=>I.join(`${e}${K}`,W.mergeDev,ve(t)),H=async e=>{try{return await p({cwd:e,quiet:!0})`git rev-parse -q --verify MERGE_HEAD`,!0}catch{return!1}},vt=async e=>{if(await H(e))throw new u(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 p({cwd:e,quiet:!0})`git status --porcelain`).stdout.trim();if(t.length>0)throw new u(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"})},Rt=async e=>{let t=async r=>{try{await r()}catch{}};await H(e)&&await t(()=>p({cwd:e,quiet:!0})`git merge --abort`),await t(()=>p({cwd:e,quiet:!0})`git reset --hard`),await t(()=>p({cwd:e,quiet:!0})`git clean -fdx -e node_modules`)},xt=async(e,t)=>{let{cwd:r,anchor:o="origin/dev"}=e,n=await ke(r),s=async()=>{await p({cwd:r,quiet:!0})`git worktree add --detach ${n} ${o}`};try{await s()}catch(c){try{await p({cwd:r,quiet:!0})`git worktree prune`,await s()}catch{throw new u(c,{operation:"create the scratch worktree for the merge",remediation:`remove any stale checkout at ${n}, then retry`})}}let d={path:n,remove:async()=>{try{await p({cwd:r,quiet:!0})`git worktree remove --force ${n}`}catch{}}};try{return await t(d)}finally{await d.remove()}};import bt from"node:process";import Et from"pino";import Mt from"pino-pretty";var Ct=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],St=()=>{let e=bt.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),Et({level:e,redact:Ct},Mt({destination:2,ignore:t.join(","),colorize:!0,sync:!0}))},U=St();var j=class extends u{structuredContent;exitCode;constructor(t,r,o){super(void 0,o),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};import Pt from"node:fs/promises";import $t from"node:os";var It=async e=>{try{return await Pt.access(e),!0}catch{return!1}},J=e=>{let t=$t.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};import ne from"node:fs/promises";import Ae from"node:os";import E from"node:path";import Kt from"node:process";import{z as i}from"zod";var X=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var Re=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r])=>r!==t));var a=({key:e,id:t,note:r})=>({id:t,note:r,apply:o=>e in o?{changed:!0,result:Re(o,e)}:{changed:!1,result:o}});var xe=a({key:"dev",id:"drop-dev-key",note:'the unused "dev" key (a dev server port comes from <APP>_PORT / PORT, else the built-in default)'});var be=a({key:"devServersPresets",id:"drop-dev-presets-key",note:'the unused "devServersPresets" key (run `infra-kit dev <app>` instead of a preset name)'});var Ee=a({key:"devProxy",id:"drop-dev-proxy-key",note:'the retired "devProxy" key (dev URLs are port-free https://<release>.<package>.localhost)'});var Me=a({key:"envAutoLoad",id:"drop-env-auto-load-key",note:'the retired "envAutoLoad" key (env auto-load is gone \u2014 run `env-load -c <config>` in the terminal)'});var Ce=a({key:"environments",id:"drop-environments-key",note:`the retired "environments" key (deploy targets now come from each workflow's workflow_dispatch options, auth from the token store)`});var Se=a({key:"ide",id:"drop-ide-key",note:'the unused "ide" key (worktrees add/remove no longer edit a Cursor .code-workspace)'});var Pe=a({key:"taskManager",id:"drop-task-manager-key",note:'the unused "taskManager" key (Jira is configured by the JIRA_BASE_URL / JIRA_PROJECT_ID env vars in Doppler)'});var Y=[Se,Ce,Ee,Me,Pe,be,xe];var x=e=>Y.reduce((t,r)=>{let o=r.apply(t.result);return o.changed?{changed:!0,result:o.result,notes:[...t.notes,r.note]}:t},{changed:!1,result:e,notes:[]});var $e={withheld:!1},Z=()=>$e.withheld||D();import{randomBytes as jt}from"node:crypto";import g from"node:fs/promises";import Q from"node:path";import Ot from"node:process";var O=class extends Error{constructor(t){super(`${t} changed on disk since it was read`),this.name="ConfigFileChangedError"}},At=2,Tt=e=>/^([ \t]+)\S/m.exec(e)?.[1]??At,Nt=4095,A=async({path:e,raw:t,migrated:r,expectedMtimeMs:o})=>{let n=await g.realpath(e),s=Q.dirname(n),d=Q.basename(n),c=Q.join(s,`.${d}.${Ot.pid}.${jt(4).toString("hex")}.tmp`),N=`${JSON.stringify(r,null,Tt(t))}
|
|
7
|
+
`;try{await g.writeFile(c,N,"utf8");let l=await g.stat(n);if(l.mtimeMs!==o)throw new O(e);await g.chmod(c,l.mode&Nt),await g.rename(c,n)}catch(l){throw await g.rm(c,{force:!0}),l}},_t=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Lt=async e=>{let t=await g.stat(e),r=await g.readFile(e,"utf8");if(r.trim()==="")return{changed:!1,result:{},notes:[],path:e};let o=JSON.parse(r);if(!_t(o))return{changed:!1,result:{},notes:[],path:e};let n=x(o);return n.changed&&await A({path:e,raw:r,migrated:n.result,expectedMtimeMs:t.mtimeMs}),{...n,path:e}};var ee=async(e,t,r,{schema:o})=>{if(e.autoMigrate==="off")return{kind:"not-applicable"};let n=x(t);if(!n.changed)return{kind:"not-applicable"};let s=o.safeParse(n.result);if(!s.success)return{kind:"not-applicable"};if(e.required&&Z())return{kind:"ci-gated"};try{await A({path:e.path,raw:r,migrated:n.result,expectedMtimeMs:e.mtimeMs})}catch(d){return U.debug(d,`auto-migration could not rewrite ${e.path}`),{kind:"not-applicable"}}return U.warn(`Migrated ${J(e.path)}: removed ${n.notes.join(" and ")} (retired by infra-kit ${ae.version})`),{kind:"migrated",data:s.data}};var Ie="infra-kit.json";var Wt="infra-kit.json",Dt="projects",Ft=i.object({provider:i.literal("doppler"),config:i.object({name:i.string().min(1)})}),qt=i.discriminatedUnion("provider",[Ft]),Vt=["two-columns","three-pane"],Gt=i.object({layout:i.enum(Vt).optional()}).strict(),Bt=i.object({openInGithubDesktop:i.boolean().optional(),openInOrca:i.boolean().optional(),orca:Gt.optional()}).strict(),zt=i.enum(["disallow","allow","cli-only"]),je=i.string().regex(/^[A-Z_]\w*$/i,"must be a POSIX environment-variable name"),Ht=i.object({command:i.string().min(1),args:i.array(i.string()).default([]),env:i.array(je).min(1),unset:i.array(je).default([])}).strict().superRefine((e,t)=>{for(let r of e.env)ce.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`})}),Ut=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: it is the .mcp.json key of the retired infra-kit MCP server \u2014 pick another name'}),Ht),Oe=i.string().min(1).superRefine((e,t)=>{if(e.startsWith("/")||e.startsWith("\\")||/^[a-z]:/i.test(e)){t.addIssue({code:"custom",message:`"${e}" must be relative to the repository root`});return}let r=e.split(/[/\\]/).filter(n=>n!==""&&n!==".");r.includes("..")&&t.addIssue({code:"custom",message:`"${e}" must not contain a ".." segment`}),r[0]===".git"&&t.addIssue({code:"custom",message:`"${e}" must not be .git or a path inside it`}),e.includes("\\")&&t.addIssue({code:"custom",message:`"${e}" must use "/" as the separator, not "\\"`});let o=e.split("/");o.includes("")&&t.addIssue({code:"custom",message:`"${e}" must not have a trailing or doubled "/"`}),o.includes(".")&&t.addIssue({code:"custom",message:`"${e}" must not contain a "." segment; write it from the repository root, e.g. "vendor/configs"`})}),Te=i.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,'must be kebab-case: a-z, 0-9 and inner "-"'),Jt=i.object({path:Oe,target:Oe.optional(),module:Te.optional()}).strict(),Ne=i.object({copy:i.array(Jt).min(1),exclude:i.array(i.string().regex(/^[^/\\]+$/,'must be a single path segment, without "/"')).optional()}).strict(),_e=i.object({modules:i.array(Te)}).strict(),Xt=i.object({requiredScripts:i.array(i.string().min(1)).optional(),requiredFiles:i.array(i.string().min(1)).optional(),turbo:i.object({requiredTasks:i.array(i.string().min(1)).optional()}).strict().optional()}).strict(),Yt=i.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,'must be a DNS label: a-z, 0-9 and inner "-", at most 63 characters'),Zt=i.string().min(1),te=1,ie=i.object({$schema:i.string().optional(),configVersion:i.number().int().positive().optional(),envManagement:qt,defaultEnv:Zt.optional(),worktrees:Bt.optional(),protectedEnvs:zt.optional(),mcp:Ut.optional(),vendorSource:Ne.nullable().optional(),vendorTarget:_e.optional(),audit:Xt.optional(),aliasRepo:Yt.optional()}).strict(),Qt=443,Le=ie,oe=ie.partial(),Ke="two-columns",er=e=>e.worktrees?.orca?.layout??Ke,f=null,b=null,We=()=>`${Kt.cwd()} ${Ae.homedir()}`,De=()=>E.join(Ae.homedir(),L),Fe=()=>E.join(De(),Wt),qe=async()=>{let e=We();if(b&&b.key===e)return b.value;let t=await R(),r=await B(t),o=E.basename(r),n={main:E.join(t,Ie),userGlobal:Fe(),userProject:E.join(De(),Dt,o,Ie),projectName:o};return b={key:e,value:n},n},tr=async(e={})=>{let t=e.autoMigrate??"write",r=We(),o=await qe(),n;try{n=await ne.stat(o.main)}catch{f=null;let _=o.main.replace(/\.json$/,".yml");throw await re(_)?new Error(`infra-kit.json not found at ${o.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit setup --skip-tools\` to convert it.`):new Error(w()?`infra-kit.json not found at ${o.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 ${o.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[s,d]=await Promise.all([re(o.userGlobal),re(o.userProject)]),c={main:Number(n.mtimeMs),userGlobal:s?Number(s.mtimeMs):null,userProject:d?Number(d.mtimeMs):null};if(f&&f.key===r&&ir(f.mtimes,c))return f.value;let N=[{label:"infra-kit.json",path:o.main,required:!0,autoMigrate:t,mtimeMs:c.main},{label:"~/.infra-kit/infra-kit.json",path:o.userGlobal,required:!1,autoMigrate:t,mtimeMs:c.userGlobal},{label:`~/.infra-kit/projects/${o.projectName}/infra-kit.json`,path:o.userProject,required:!1,autoMigrate:t,mtimeMs:c.userProject}],l={};for(let _ of N){let se=await sr(_);se!==null&&(l={...l,...se})}let M=Le.safeParse(l);if(!M.success)throw new Error(`Invalid merged infra-kit config: ${i.prettifyError(M.error)}`);return f={key:r,mtimes:c,value:M.data},M.data},rr=()=>{f=null},or=()=>{f=null,b=null},re=async e=>{try{return await ne.stat(e)}catch{return null}},nr=async e=>{try{return await ne.readFile(e,"utf-8")}catch{return null}},ir=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(o=>e[o]===t[o])},Ve=e=>new Error(`${e.message}
|
|
8
|
+
A retired key on this branch \u2014 run \`infra-kit setup --skip-tools\` in this checkout and commit infra-kit.json.`),sr=async e=>{let t=await nr(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(d){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${d.message}`)}if(T(r)&&"envTokens"in r)throw new Error(hr(e));!e.required&&T(r)&&fr(e,r),e.required&&T(r)&&gr(r,e.path);let o=oe.safeParse(r);if(o.success)return o.data;let n=new Error(`Invalid ${e.label} at ${e.path}: ${i.prettifyError(o.error)}`);if(!T(r)||e.mtimeMs===null)throw n;let s=await ee({...e,mtimeMs:e.mtimeMs},r,t,{schema:oe});switch(s.kind){case"migrated":return s.data;case"ci-gated":throw Ve(n);case"not-applicable":throw n;default:return X(s)}},ar=e=>[`"mcp" is not allowed in ${e.label} (${e.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,"Move the block to the project infra-kit.json and run `infra-kit setup`.","For a machine-only override of one server (e.g. a local fork), use Claude Code directly:"," claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>","(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected)."].join(`
|
|
9
|
+
`),cr=e=>[`"vendorSource" is not allowed in ${e.label} (${e.path}): only the committed project file may mark a repository as the \`vendor sync\` source. In the machine-wide file it would make every repository on this machine a source; in a per-project override it would make this machine disagree with every other clone.`,"Move the block to the source repository's own infra-kit.json and commit it there."].join(`
|
|
10
|
+
`),ur=e=>[`"vendorTarget" is not allowed in ${e.label} (${e.path}): \`vendor sync\` reads it from the target repository's committed infra-kit.json only, so a per-machine copy would never be seen and would only make this clone disagree with the others.`,"Move the block to the target repository's own infra-kit.json and commit it there."].join(`
|
|
11
|
+
`),mr=e=>[`"audit" is not allowed in ${e.label} (${e.path}): the root audit gates CI, so a per-machine copy would make this machine pass or fail a different check list than CI.`,"Move the block to the project infra-kit.json and commit it there."].join(`
|
|
12
|
+
`),dr=e=>`"configVersion" is not allowed in ${e.label} (${e.path}): it versions the committed project file's shape, so a per-machine copy would describe nothing. Remove it from this file.`,pr=e=>[`"aliasRepo" is not allowed in ${e.label} (${e.path}): the vite and Playwright helpers read it from the project infra-kit.json only, so a per-machine copy would register a dev host they never aim at.`,"Move it to the project infra-kit.json and commit it there."].join(`
|
|
13
|
+
`),lr={aliasRepo:pr,configVersion:dr,mcp:ar,vendorSource:cr,vendorTarget:ur,audit:mr},gr=(e,t)=>{let{configVersion:r}=e;if(!(typeof r!="number"||r<=te))throw new j({status:"refused",reason:"config-version-unsupported",configVersion:r,supportedConfigVersion:te,agentMode:S.source},2,{operation:"load infra-kit.json",remediation:"update the infra-kit CLI: `pnpm add -g infra-kit@<version>` with the version `pnpm view infra-kit version` prints, then re-run",stderrExcerpt:`${t} declares configVersion ${r}; this CLI reads up to ${te}`})},fr=(e,t)=>{for(let[r,o]of Object.entries(lr))if(r in t)throw new Error(o(e))},T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hr=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(`
|
|
14
|
+
`);export{C as a,Be as b,ue as c,S as d,w as e,He as f,Ue as g,v as h,u as i,h as j,q as k,V as l,et as m,tt as n,rt as o,ot as p,nt as q,it as r,G as s,st as t,he as u,at as v,R as w,B as x,ye as y,we as z,mt as A,dt as B,pt as C,lt as D,gt as E,ft as F,ht as G,yt as H,wt as I,ve as J,kt as K,H as L,vt as M,Rt as N,xt as O,U as P,X as Q,It as R,J as S,$e as T,O as U,A as V,Lt as W,j as X,Ne as Y,_e as Z,ie as _,Qt as $,Le as aa,oe as ba,er as ca,Fe as da,qe as ea,tr as fa,rr as ga,or as ha};
|
|
15
|
+
//# sourceMappingURL=chunk-BPOPODWW.js.map
|