@forinda/kickjs-cli 8.7.2 → 8.7.4
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/{agent-docs-BzwCxWX9.mjs → agent-docs-D1NiioiC.mjs} +3 -3
- package/dist/{agent-docs-BzwCxWX9.mjs.map → agent-docs-D1NiioiC.mjs.map} +1 -1
- package/dist/{agent-docs-DxQsg7M-.mjs → agent-docs-eYzqOuhH.mjs} +2 -2
- package/dist/{build-Ch7dqfhz.mjs → build-C8hFoe4D.mjs} +3 -3
- package/dist/{build-Ch7dqfhz.mjs.map → build-C8hFoe4D.mjs.map} +1 -1
- package/dist/{build-CLQUmNoi.mjs → build-Dn_E-sU-.mjs} +2 -2
- package/dist/{builtins-CowtBaMB.mjs → builtins-9-5q51ha.mjs} +2 -2
- package/dist/{builtins-BYd-QNZz.mjs → builtins-BVbO6V8X.mjs} +4 -4
- package/dist/cli.mjs +2 -2
- package/dist/{config-BrTjgY_m.mjs → config-Bz95PNHt.mjs} +3 -3
- package/dist/{config-BrTjgY_m.mjs.map → config-Bz95PNHt.mjs.map} +1 -1
- package/dist/{config-BmRvi4Ie.mjs → config-SmN68KnC.mjs} +2 -2
- package/dist/{doctor-DY64AQdA.mjs → doctor-Dkavyt1v.mjs} +4 -4
- package/dist/{doctor-DY64AQdA.mjs.map → doctor-Dkavyt1v.mjs.map} +1 -1
- package/dist/{fs-eFxLGjBT.mjs → fs-BIgSYmdZ.mjs} +1 -1
- package/dist/{fs-CtM-VHOb.mjs → fs-BOhfpM_y.mjs} +2 -2
- package/dist/{fs-CtM-VHOb.mjs.map → fs-BOhfpM_y.mjs.map} +1 -1
- package/dist/{fullstack-BMY4Qy-E.mjs → fullstack-4Yb4WDLh.mjs} +3 -3
- package/dist/{fullstack-DUz0MbT_.mjs → fullstack-BJIm48KV.mjs} +4 -4
- package/dist/{fullstack-DUz0MbT_.mjs.map → fullstack-BJIm48KV.mjs.map} +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-BxV7eEIm.mjs → plugin-CM08_8-x.mjs} +2 -2
- package/dist/{plugin-C0SJkHl9.mjs → plugin-q9-AlF6C.mjs} +2 -2
- package/dist/{project-Du-I3cJ9.mjs → project-B3xCFdaS.mjs} +5 -5
- package/dist/{project-Du-I3cJ9.mjs.map → project-B3xCFdaS.mjs.map} +1 -1
- package/dist/{project-D13jeAnH.mjs → project-D_obb3C8.mjs} +4 -4
- package/dist/{project-root-Bz4rAKEK.mjs → project-root-BkMyQ-hx.mjs} +2 -2
- package/dist/{project-root-DcbF8dZ3.mjs → project-root-gBoWn2mp.mjs} +3 -3
- package/dist/{project-root-DcbF8dZ3.mjs.map → project-root-gBoWn2mp.mjs.map} +1 -1
- package/dist/{prompts-DUjK2Pb0.mjs → prompts-_yTG-mXU.mjs} +2 -2
- package/dist/{prompts-DUjK2Pb0.mjs.map → prompts-_yTG-mXU.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DwxUEhrp.mjs → rolldown-runtime-dZfrrS4X.mjs} +1 -1
- package/dist/{run-plugins-D_kRD0TN.mjs → run-plugins-BIQikATV.mjs} +4 -4
- package/dist/{run-plugins-D_kRD0TN.mjs.map → run-plugins-BIQikATV.mjs.map} +1 -1
- package/dist/{typegen-CSW8oZn2.mjs → typegen-CD1WVcaP.mjs} +4 -4
- package/dist/{typegen-DXcs_Smo.mjs → typegen-F8fT5eSE.mjs} +5 -5
- package/dist/{typegen-DXcs_Smo.mjs.map → typegen-F8fT5eSE.mjs.map} +1 -1
- package/dist/{types-DplUJBtq.mjs → types-DqUW9c4J.mjs} +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-Du-I3cJ9.mjs","names":["indentBlock"],"sources":["../src/scaffold/overlay.ts","../src/utils/shell.ts","../src/generators/templates/project-config.ts","../src/scaffold/wire.ts","../src/commands/add-wire.ts","../src/commands/add.ts","../src/generators/project.ts"],"sourcesContent":["/**\n * Overlay scaffolding — project files as real directories instead of TS\n * functions that return strings.\n *\n * A layer is a directory under `packages/cli/templates/`:\n *\n * - `files/` mirrors the project. Layers render in order; a later layer's\n * file replaces an earlier one at the same path, and a `<name>.append` file\n * is added to the end of `<name>` instead.\n * - `feature.json` (optional) lists the packages the layer needs and its\n * **integrations**: entries for the slots that shared files expose.\n *\n * File names: a `_dot_` path segment prefix becomes `.` (`_dot_gitignore` →\n * `.gitignore`), because npm publish drops or rewrites real dotfiles.\n *\n * Slots: a shared file marks where layers plug in with a comment line.\n * `// @kick:imports` becomes the merged import statements of every rendered\n * integration; `// @kick:<slot>` becomes that slot's entries, one `code,` per\n * line at the marker's indentation. An empty slot inside its own `key: [` …\n * `],` block drops the whole block, so an app with no adapters has no\n * `adapters: []`. This is what keeps layers out of each other's way: swagger\n * never edits the entry file, it declares an `adapter` entry.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, join, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst here = dirname(fileURLToPath(import.meta.url))\n\n/**\n * `packages/cli/templates` — one level above the bundle (`dist/*.mjs`), two\n * above this source file (`src/scaffold/overlay.ts`), so tests can import it\n * from source.\n */\nexport const TEMPLATES_DIR = [\n join(here, '..', 'templates'),\n join(here, '..', '..', 'templates'),\n].find((dir) => existsSync(join(dir, 'base')))!\n\n/** An import an integration needs. Merged per module across integrations. */\nexport interface ImportSpec {\n from: string\n names?: string[]\n default?: string\n}\n\n/**\n * What a layer contributes to shared files. With a `slot`, `code` is\n * rendered there and `import` only when that slot exists in the file — so an\n * `express.json()` middleware doesn't leave an unused `express` import in a\n * template without a middleware list. Without a `slot`, `import` is always\n * rendered.\n */\nexport interface Integration {\n import?: ImportSpec\n slot?: string\n code?: string\n}\n\n/** `feature.json`. Package versions come from the scaffold's resolved version map. */\nexport interface FeatureManifest {\n dependencies?: string[]\n devDependencies?: string[]\n /** Install-script answers for packages this layer pulls in (see `approveInstallScripts`). */\n builds?: Record<string, boolean>\n integrations?: Integration[]\n}\n\nexport interface RenderedProject {\n files: Map<string, string>\n dependencies: string[]\n devDependencies: string[]\n builds: Record<string, boolean>\n /** Every layer's integrations plus `extra`, in layer order — `kick add` wires these. */\n integrations: Integration[]\n}\n\n/** The project path a template file lands at: `_dot_` segment prefixes become `.`. */\nexport function outputPath(templatePath: string): string {\n return templatePath\n .split('/')\n .map((segment) => (segment.startsWith('_dot_') ? `.${segment.slice(5)}` : segment))\n .join('/')\n}\n\n/**\n * Render layers into project files plus the packages they need. Pure apart\n * from reading the template directories; the caller writes the files.\n *\n * `extra` adds integrations computed at scaffold time (a value the user\n * typed can't live in a static layer). `vars` fills `{{name}}` in\n * integration code.\n */\nexport function renderLayers(\n layers: readonly string[],\n options: {\n templatesDir?: string\n extra?: Integration[]\n vars?: Record<string, string>\n } = {},\n): RenderedProject {\n const templatesDir = options.templatesDir ?? TEMPLATES_DIR\n const files = new Map<string, string>()\n const dependencies: string[] = []\n const devDependencies: string[] = []\n const builds: Record<string, boolean> = {}\n const integrations: Integration[] = []\n\n for (const layer of layers) {\n const dir = join(templatesDir, layer)\n if (!existsSync(dir)) throw new Error(`Unknown scaffold layer \"${layer}\" (${dir})`)\n\n const manifestPath = join(dir, 'feature.json')\n if (existsSync(manifestPath)) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as FeatureManifest\n dependencies.push(...(manifest.dependencies ?? []))\n devDependencies.push(...(manifest.devDependencies ?? []))\n Object.assign(builds, manifest.builds)\n integrations.push(...(manifest.integrations ?? []))\n }\n\n const root = join(dir, 'files')\n if (!existsSync(root)) continue\n // String entries, not Dirents: `Dirent.parentPath` needs Node 20.12.\n for (const rel of readdirSync(root, { recursive: true, encoding: 'utf-8' }).toSorted()) {\n const abs = join(root, rel)\n if (!statSync(abs).isFile()) continue\n const contents = readFileSync(abs, 'utf-8')\n const path = outputPath(rel.split(sep).join('/'))\n if (path.endsWith('.append')) {\n const target = path.slice(0, -'.append'.length)\n files.set(target, (files.get(target) ?? '') + contents)\n } else {\n files.set(path, contents)\n }\n }\n }\n\n integrations.push(...(options.extra ?? []))\n const vars = options.vars ?? {}\n const fill = (text: string) => text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key) => vars[key] ?? all)\n for (const [path, contents] of files) {\n if (contents.includes('// @kick:')) files.set(path, renderSlots(contents, integrations, fill))\n }\n\n return {\n files,\n dependencies: [...new Set(dependencies)],\n devDependencies: [...new Set(devDependencies)],\n builds,\n integrations,\n }\n}\n\n/**\n * Fill `{{name}}` placeholders in rendered files. Separate from rendering so\n * a value can depend on the result (README lists the packages the layers\n * chose). Unknown names are left as written.\n */\nexport function fillVars(\n files: ReadonlyMap<string, string>,\n vars: Record<string, string>,\n): Map<string, string> {\n const fill = (text: string) =>\n text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key: string) => (key in vars ? vars[key]! : all))\n return new Map([...files].map(([path, contents]) => [path, fill(contents)]))\n}\n\nconst MARKER = /^([ \\t]*)\\/\\/ @kick:([\\w-]+)[ \\t]*$/\n\n/** Fill one file's slot markers. */\nexport function renderSlots(\n source: string,\n integrations: readonly Integration[],\n fill: (text: string) => string = (text) => text,\n): string {\n const lines = source.split('\\n')\n const slots = new Set(lines.map((line) => MARKER.exec(line)?.[2]).filter(Boolean))\n const active = integrations.filter((i) => !i.slot || slots.has(i.slot))\n\n const out: string[] = []\n for (let i = 0; i < lines.length; i++) {\n const match = MARKER.exec(lines[i]!)\n if (!match) {\n out.push(lines[i]!)\n continue\n }\n const [, indent, slot] = match as unknown as [string, string, string]\n const rendered =\n slot === 'imports'\n ? renderImports(active.flatMap((entry) => (entry.import ? [entry.import] : [])))\n : active\n .filter((entry) => entry.slot === slot && entry.code)\n .map((entry) => indentBlock(`${fill(entry.code!)},`, indent))\n if (rendered.length > 0) {\n out.push(...rendered)\n continue\n }\n // Empty: drop an enclosing `key: [` … `],` block that holds only this marker.\n const prev = out.at(-1)\n if (prev?.trimEnd().endsWith('[') && lines[i + 1]?.trim().startsWith(']')) {\n out.pop()\n i++\n }\n }\n return out.join('\\n')\n}\n\nfunction indentBlock(code: string, indent: string): string {\n return code\n .split('\\n')\n .map((line) => (line ? indent + line : line))\n .join('\\n')\n}\n\n/** One statement per module, names merged in first-seen order; wrapped past 100 columns. */\nexport function renderImports(specs: readonly ImportSpec[]): string[] {\n const byModule = new Map<string, { names: string[]; default?: string }>()\n for (const spec of specs) {\n const entry = byModule.get(spec.from) ?? { names: [] }\n entry.default ??= spec.default\n for (const name of spec.names ?? []) if (!entry.names.includes(name)) entry.names.push(name)\n byModule.set(spec.from, entry)\n }\n return [...byModule].map(([from, { names, default: def }]) => {\n const parts = [def, names.length ? `{ ${names.join(', ')} }` : undefined].filter(Boolean)\n const line = `import ${parts.join(', ')} from '${from}'`\n if (line.length <= 100 || names.length === 0) return line\n const head = def ? `${def}, ` : ''\n return `import ${head}{\\n${names.map((n) => ` ${n},`).join('\\n')}\\n} from '${from}'`\n })\n}\n","import { execFile, execFileSync, execSync, spawnSync } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Characters an argument may not contain when it has to travel through\n * `cmd.exe`.\n *\n * The first group is shell syntax — `cmd.exe` would interpret these rather\n * than pass them through. The trailing `\\\\` is different in kind: a backslash\n * is not shell syntax, but Windows command-line quoting mangles it. Node's\n * argv encoder doubles trailing backslashes, and a backslash immediately\n * before a closing quote escapes that quote, so a single argument silently\n * splits in two:\n *\n * ['C:\\\\some path\\\\'] → cmd receives ['\"C:\\\\some', 'path\\\\\"']\n * ['no-space\\\\'] → cmd receives ['no-space\\\\\\\\']\n *\n * Correct escaping is possible but fiddly, and no caller in this CLI needs it\n * — arguments here are package names, dist-tags, subcommands and flags, and\n * working directories travel via the `cwd` option rather than as arguments.\n * So a backslash is rejected outright: a loud `null` beats a silently\n * corrupted argument, which is the exact failure mode this module exists to\n * eliminate.\n */\nconst CMD_UNSAFE = /[&|<>^\"'`(){}[\\];!%\\r\\n\\\\]/\n\n/**\n * Build the `[file, args]` pair to hand to `execFileSync`, routing through\n * `cmd.exe` on Windows so `.cmd` shims are launchable.\n *\n * On Windows, `npm` / `pnpm` / `yarn` / `bun` are `.cmd` batch shims, not\n * `.exe`s, and `execFileSync` cannot launch either spelling:\n *\n * - `execFileSync('npm', …)` → ENOENT (there is no `npm.exe` on PATH)\n * - `execFileSync('npm.cmd', …)` → EINVAL (Node >= 18.20 / 20.12 refuses to\n * spawn batch files without a\n * shell — CVE-2024-27980)\n *\n * Both failures are silent wherever the caller swallows the error, so the\n * command looks like it \"returned nothing\" rather than \"never ran\".\n *\n * `/d` skips AutoRun registry commands, `/s` makes cmd treat everything after\n * `/c` as one verbatim string (it strips only the outer quote pair Node adds).\n * Returns `null` when an argument is unsafe to pass through — refusing to run\n * beats running something the shell rewrote.\n *\n * `platform` is injectable so both branches are unit-testable from any host\n * OS; production callers use the default. It is read per call rather than\n * captured at import time for the same reason.\n */\nexport function shellSafeInvocation(\n file: string,\n args: string[],\n platform: NodeJS.Platform = process.platform,\n): [string, string[]] | null {\n if (platform !== 'win32') return [file, args]\n if (CMD_UNSAFE.test(file) || args.some((a) => CMD_UNSAFE.test(a))) return null\n const command = [file, ...args].map((a) => (a.includes(' ') ? `\"${a}\"` : a)).join(' ')\n return [process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', command]]\n}\n\n/**\n * Run a command and capture its trimmed stdout, cross-platform.\n *\n * Returns `null` if the command is missing, exits non-zero, times out, or\n * carries arguments unsafe to pass through `cmd.exe`. Callers treat `null` as\n * \"unknown\" and fall back — the point of this helper is that a Windows `.cmd`\n * shim no longer masquerades as a failed command.\n */\nexport function captureCommand(\n file: string,\n args: string[],\n opts: { timeout?: number; cwd?: string } = {},\n): string | null {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) return null\n try {\n const out = execFileSync(invocation[0], invocation[1], {\n encoding: 'utf-8',\n timeout: opts.timeout ?? 5000,\n cwd: opts.cwd,\n stdio: ['ignore', 'pipe', 'ignore'],\n windowsHide: true,\n })\n const trimmed = out.toString().trim()\n return trimmed || null\n } catch {\n return null\n }\n}\n\n/**\n * Run a command with inherited stdio, cross-platform. Throws on failure so\n * callers can decide whether a missing package manager is fatal.\n */\nexport function runCommand(file: string, args: string[], opts: { cwd?: string } = {}): void {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) throw new Error(`Refusing to run '${file}': unsafe arguments`)\n execFileSync(invocation[0], invocation[1], {\n cwd: opts.cwd,\n stdio: 'inherit',\n windowsHide: true,\n })\n}\n\n/**\n * Run a shell command synchronously, printing output.\n *\n * On Windows, `execSync` spawns via `cmd.exe` by default, which means\n * POSIX-style inline env prefixes like `FOO=bar node app.js` do NOT work.\n * Callers that need environment variables should pass them in the `env`\n * option instead of prepending them to the command string — see\n * `runNodeWithEnv` for the cross-platform helper that avoids a shell\n * entirely.\n */\nexport function runShellCommand(command: string, cwd?: string, env?: NodeJS.ProcessEnv): void {\n execSync(command, {\n cwd,\n stdio: 'inherit',\n env: env ? { ...process.env, ...env } : process.env,\n })\n}\n\n/**\n * Cross-platform way to launch a Node.js process with a set of\n * environment variables. Uses `spawnSync` with an argument array so no\n * shell is involved — the `VAR=value node ...` POSIX prefix syntax that\n * `runShellCommand` relied on breaks on cmd.exe and PowerShell.\n */\nexport function runNodeWithEnv(entry: string, env: NodeJS.ProcessEnv, cwd?: string): void {\n const result = spawnSync(process.execPath, [entry], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...env },\n })\n if (result.status !== 0) {\n process.exit(result.status ?? 1)\n }\n}\n\n/**\n * Async twin of `captureCommand` — same Windows `.cmd` routing, same\n * `null`-on-any-failure contract, but genuinely concurrent.\n *\n * `captureCommand` is `execFileSync`, so `Promise.all` over it runs the\n * commands one after another. Callers that fan out over a list of network\n * queries (`npm view` per package) need real concurrency, otherwise the\n * per-call timeout multiplies by the list length.\n */\nexport async function captureCommandAsync(\n file: string,\n args: string[],\n opts: { timeout?: number; cwd?: string } = {},\n): Promise<string | null> {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) return null\n try {\n const { stdout } = await execFileAsync(invocation[0], invocation[1], {\n encoding: 'utf-8',\n timeout: opts.timeout ?? 5000,\n cwd: opts.cwd,\n windowsHide: true,\n })\n return stdout.toString().trim() || null\n } catch {\n return null\n }\n}\n","// `SchemaLib` is defined next to `resolveSchemaLib` in ../../config, so the\n// scaffold that installs the library and the generators that import from it\n// read the same list. Re-exported here for existing importers.\nexport type { SchemaLib } from '../../config'\n\n/**\n * Map of package name → semver range string (`^x.y.z`). Resolved\n * from `npm view <name> version` upstream so per-package independent\n * versioning is honoured at scaffold time. Every package a scaffold layer\n * lists must appear here; missing keys throw during package.json generation\n * (loud failure beats silently shipping `^undefined`).\n */\nexport type SiblingVersions = Record<string, string>\n\nfunction take(versions: SiblingVersions, name: string): string {\n const v = versions[name]\n if (!v) {\n throw new Error(\n `generatePackageJson: missing resolved version for ${name}. ` +\n `Add it to SIBLING_PACKAGES or THIRD_PARTY_PACKAGES in generators/project.ts.`,\n )\n }\n return v\n}\n\n/** Name → resolved range, sorted by name (the order npm and pnpm write). */\nfunction pinned(names: readonly string[], versions: SiblingVersions): Record<string, string> {\n return Object.fromEntries(names.toSorted().map((name) => [name, take(versions, name)]))\n}\n\n/**\n * Generate package.json. Which packages it lists comes from the scaffold\n * layers (`templates/<layer>/feature.json`); the ranges come from `versions`.\n */\nexport function generatePackageJson(\n name: string,\n versions: SiblingVersions,\n packages: { dependencies: readonly string[]; devDependencies: readonly string[] },\n): string {\n return JSON.stringify(\n {\n name,\n // Project starts at 0.0.0 — adopters bump as they ship. Tying\n // the project version to the CLI version (the previous\n // behaviour) made every scaffolded app `5.4.0` on day one,\n // which broke npm publishing for adopters trying their first\n // release.\n version: '0.0.0',\n type: 'module',\n scripts: {\n // `kick dev` (not bare `vite`): it boots Vite itself AND owns the\n // typegen-on-save watcher. Plain `vite` gives working HMR but\n // frozen `.kickjs/types` — new routes silently lose their typing\n // until a manual `kick typegen`.\n // Four scripts, not ten. Everything dropped from here is still one\n // command away — `kick dev:debug`, `kick typegen`, `pnpm exec vitest`,\n // `pnpm exec tsc --noEmit` — and a scaffold that opens with a wall of\n // aliases teaches less than one that shows the binary.\n //\n // `lint: 'eslint src/'` used to be here without eslint ever being a\n // dependency, so `lint` failed with \"command not found\" in every\n // generated project.\n dev: 'kick dev',\n build: 'kick build',\n start: 'kick start',\n test: 'vitest run',\n // Serverless targets — see guide/serverless.md. Each bundles\n // src/serverless.ts and writes the platform's build output.\n 'build:netlify': 'kick build && kick build:netlify',\n 'build:vercel': 'kick build && kick build:vercel',\n },\n dependencies: pinned(packages.dependencies, versions),\n devDependencies: pinned(packages.devDependencies, versions),\n },\n null,\n 2,\n )\n}\n\n/**\n * Answer pnpm's build-script approvals for `builds` in pnpm-workspace.yaml text,\n * in both formats pnpm has used, so any pnpm 10+ reads them:\n *\n * - `allowBuilds` (pnpm 10.26+; pnpm 11 reads only this)\n * - `onlyBuiltDependencies` / `ignoredBuiltDependencies` (pnpm before 10.26)\n *\n * Each version ignores the format it doesn't read. An existing answer wins: an\n * `allowBuilds` key set to true/false, or a name already in either list, is left\n * alone. A missing key or pnpm's `set this to true or false` placeholder is filled in.\n */\nexport function setAllowBuilds(yaml: string, builds: Record<string, boolean>): string {\n const entries = Object.entries(builds)\n if (entries.length === 0) return yaml\n const lines = yaml === '' ? [] : yaml.replace(/\\n$/, '').split('\\n')\n const unquote = (text: string) => text.trim().replace(/^['\"]|['\"]$/g, '')\n const quote = (name: string) => (/^[\\w-]+$/.test(name) ? name : `'${name}'`)\n\n /** Line range of a top-level block's indented entries; appended when missing and `create`. */\n const block = (key: string, create: boolean): { start: number; end: number } | undefined => {\n let start = lines.findIndex((line) => line.replace(/\\s+$/, '') === `${key}:`)\n if (start === -1) {\n if (!create) return undefined\n if (lines.length > 0 && lines[lines.length - 1] !== '') lines.push('')\n lines.push(`${key}:`)\n start = lines.length - 1\n }\n // The block runs to the next unindented line; blank lines inside it don't end it.\n let end = start + 1\n for (let i = start + 1; i < lines.length && /^(\\s|$)/.test(lines[i]); i++) {\n if (lines[i].trim() !== '') end = i + 1\n }\n return { start, end }\n }\n\n const answers: Array<[string, boolean]> = []\n for (const [name, allow] of entries) {\n const { start, end } = block('allowBuilds', true)!\n const index = lines\n .slice(start + 1, end)\n .findIndex((line) => unquote(line.split(':')[0]) === name)\n const answered =\n index === -1 ? undefined : /:\\s*(true|false)\\s*$/.exec(lines[start + 1 + index])\n if (answered) {\n answers.push([name, answered[1] === 'true'])\n continue\n }\n const entry = ` ${quote(name)}: ${allow}`\n if (index === -1) lines.splice(end, 0, entry)\n else lines[start + 1 + index] = entry\n answers.push([name, allow])\n }\n\n const lists = ['onlyBuiltDependencies', 'ignoredBuiltDependencies']\n for (const [name, allow] of answers) {\n const listed = lists.some((key) => {\n const range = block(key, false)\n return (\n range !== undefined &&\n lines\n .slice(range.start + 1, range.end)\n .some((line) => unquote(line.replace(/^\\s*-/, '')) === name)\n )\n })\n if (listed) continue\n const { end } = block(allow ? lists[0] : lists[1], true)!\n lines.splice(end, 0, ` - ${quote(name)}`)\n }\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * Apply a layer's integrations to an EXISTING entry file — what `kick add`\n * does after installing a package that has a scaffold layer.\n *\n * `kick new` renders slots into a template it owns. An existing\n * `src/index.ts` is the user's file, so this never re-renders it: it finds\n * the `bootstrap({ ... })` call with oxc and splices text in — an entry at\n * the end of `adapters: [...]` (the array is created when missing), and the\n * import merged into an existing one from the same module or added after the\n * last import. Everything else in the file is left byte-for-byte alone.\n *\n * Idempotent: an entry whose call (`SwaggerAdapter(`) is already in the\n * array is skipped. When the file doesn't have the expected shape (no\n * `bootstrap({ ... })`, or `adapters` isn't an array literal), the entry is\n * returned as `manual` for the caller to print instead of guessing.\n */\nimport { parseSync } from 'oxc-parser'\n\nimport type { ImportSpec, Integration } from './overlay'\n\n/** Which `bootstrap()` option each slot appends to. */\nconst SLOT_PROPERTY: Record<string, string> = {\n adapter: 'adapters',\n middleware: 'middlewares',\n}\n\nexport interface WireResult {\n source: string\n /** Entries added, by the call they make (`SwaggerAdapter`). */\n added: string[]\n /** Entries already present. */\n present: string[]\n /** Entries that couldn't be placed — print them for the user. */\n manual: Integration[]\n}\n\ntype Node = { type: string; start: number; end: number; [key: string]: any }\n\nexport function wireIntegrations(\n source: string,\n integrations: readonly Integration[],\n fill: (text: string) => string = (text) => text,\n file = 'src/index.ts',\n): WireResult {\n const result: WireResult = { source, added: [], present: [], manual: [] }\n for (const integration of integrations) {\n if (!integration.slot || !integration.code) continue\n const property = SLOT_PROPERTY[integration.slot]\n const code = fill(integration.code)\n const call = callName(code)\n const program = parseSync(file, result.source).program as unknown as Node\n const options = property ? findBootstrapOptions(program) : undefined\n if (!options) {\n result.manual.push({ ...integration, code })\n continue\n }\n\n const prop = options.properties.find(\n (p: Node) => p.type === 'Property' && (p.key?.name ?? p.key?.value) === property,\n ) as Node | undefined\n if (prop && prop.value.type !== 'ArrayExpression') {\n result.manual.push({ ...integration, code })\n continue\n }\n // Under the name this file calls it: `import { SwaggerAdapter as SA }` → `SA(`.\n const local =\n call && integration.import ? localName(program, integration.import.from, call) : call\n if (\n prop &&\n local &&\n result.source.slice(prop.value.start, prop.value.end).includes(`${local}(`)\n ) {\n result.present.push(call ?? firstLine(code))\n continue\n }\n\n result.source = prop\n ? appendToArray(result.source, prop.value, code)\n : addProperty(result.source, options, property!, code)\n if (integration.import) result.source = addImport(result.source, integration.import, file)\n result.added.push(call ?? firstLine(code))\n }\n return result\n}\n\n/** The object literal passed to the first `bootstrap(...)` call. */\nfunction findBootstrapOptions(program: Node): Node | undefined {\n let found: Node | undefined\n const visit = (node: unknown): void => {\n if (found || !node || typeof node !== 'object') return\n if (Array.isArray(node)) return node.forEach(visit)\n const n = node as Node\n if (\n n.type === 'CallExpression' &&\n n.callee?.type === 'Identifier' &&\n n.callee.name === 'bootstrap' &&\n n.arguments?.[0]?.type === 'ObjectExpression'\n ) {\n found = n.arguments[0]\n return\n }\n for (const key in n) visit(n[key])\n }\n visit(program)\n return found\n}\n\n/** The local binding of `imported` from `from`, when this file imports it (possibly renamed). */\nfunction localName(program: Node, from: string, imported: string): string {\n for (const node of program.body as Node[]) {\n if (node.type !== 'ImportDeclaration' || node.source.value !== from) continue\n for (const specifier of node.specifiers as Node[]) {\n const name = specifier.imported?.name ?? specifier.imported?.value\n if (specifier.type === 'ImportSpecifier' && name === imported) return specifier.local.name\n }\n }\n return imported\n}\n\n/** `SwaggerAdapter` for `// comment\\nSwaggerAdapter({ ... })`. */\nfunction callName(code: string): string | undefined {\n const line = code.split('\\n').find((l) => l.trim() && !l.trim().startsWith('//'))\n return /^\\s*([A-Za-z_$][\\w$.]*)\\s*\\(/.exec(line ?? '')?.[1]\n}\n\nconst firstLine = (code: string) =>\n code\n .split('\\n')\n .find((l) => l.trim() && !l.trim().startsWith('//'))\n ?.trim() ?? code\n\nconst lineIndent = (source: string, offset: number) =>\n /^[ \\t]*/.exec(source.slice(source.lastIndexOf('\\n', offset - 1) + 1))![0]\n\nconst indentBlock = (code: string, indent: string) =>\n code\n .split('\\n')\n .map((line) => (line ? indent + line : line))\n .join('\\n')\n\nfunction appendToArray(source: string, array: Node, code: string): string {\n const elements = (array.elements as Array<Node | null>).filter(Boolean) as Node[]\n const arrayIndent = lineIndent(source, array.start)\n if (elements.length === 0) {\n const inner = indentBlock(`${code},`, `${arrayIndent} `)\n return `${source.slice(0, array.start)}[\\n${inner}\\n${arrayIndent}]${source.slice(array.end)}`\n }\n const last = elements.at(-1)!\n const indent = lineIndent(source, last.start)\n // After the last element's trailing comma when it has one.\n const after = source.slice(last.end, array.end - 1)\n const comma = after.match(/^\\s*,/)\n const at = comma ? last.end + comma[0].length : last.end\n const entry = `\\n${indentBlock(`${code},`, indent)}`\n return comma\n ? source.slice(0, at) + entry + source.slice(at)\n : `${source.slice(0, at)},${entry.replace(/,$/, '')}${source.slice(at)}`\n}\n\nfunction addProperty(source: string, object: Node, property: string, code: string): string {\n const props = object.properties as Node[]\n const last = props.at(-1)\n const indent = last ? lineIndent(source, last.start) : `${lineIndent(source, object.start)} `\n const block = `${indent}${property}: [\\n${indentBlock(`${code},`, `${indent} `)}\\n${indent}],`\n if (!last) {\n return `${source.slice(0, object.start)}{\\n${block}\\n${lineIndent(source, object.start)}}${source.slice(object.end)}`\n }\n const after = source.slice(last.end, object.end - 1)\n const comma = after.match(/^\\s*,/)\n const at = comma ? last.end + comma[0].length : last.end\n // A one-line `bootstrap({ modules })` becomes multi-line; the project's\n // formatter tidies the rest.\n return `${source.slice(0, at)}${comma ? '' : ','}\\n${block}${source.slice(at)}`\n}\n\n/** Add `spec`'s names to an import from the same module, or a new import after the last one. */\nexport function addImport(source: string, spec: ImportSpec, file = 'src/index.ts'): string {\n const program = parseSync(file, source).program as unknown as Node\n const imports = (program.body as Node[]).filter((n) => n.type === 'ImportDeclaration')\n const existing = imports.find(\n (n) =>\n n.source.value === spec.from &&\n n.importKind !== 'type' &&\n // A side-effect `import 'x'` has nothing to merge into.\n n.specifiers.length > 0 &&\n !n.specifiers.some((s: Node) => s.type === 'ImportNamespaceSpecifier'),\n )\n const names = spec.names ?? []\n\n if (existing) {\n const have = new Set(existing.specifiers.map((s: Node) => s.local?.name))\n const missing = names.filter((name) => !have.has(name))\n if (missing.length === 0) return source\n const named = existing.specifiers.filter((s: Node) => s.type === 'ImportSpecifier')\n if (named.length > 0) {\n const at = named.at(-1).end\n return `${source.slice(0, at)}, ${missing.join(', ')}${source.slice(at)}`\n }\n // Only a default import: `import d from 'x'` → `import d, { a } from 'x'`.\n const def = existing.specifiers[0]\n return `${source.slice(0, def.end)}, { ${missing.join(', ')} }${source.slice(def.end)}`\n }\n\n const parts = [spec.default, names.length ? `{ ${names.join(', ')} }` : undefined].filter(Boolean)\n const line = `import ${parts.join(', ')} from '${spec.from}'`\n const last = imports.at(-1)\n if (!last) return `${line}\\n${source}`\n return `${source.slice(0, last.end)}\\n${line}${source.slice(last.end)}`\n}\n","/**\n * `kick add` wiring — apply a package's scaffold layer to an existing app:\n * its packages join the install, its `.env` lines are added, and its adapter\n * is spliced into the entry file (see `scaffold/wire.ts`).\n */\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { writeFileSafe } from '../utils/fs'\nimport { renderLayers, type Integration, type RenderedProject } from '../scaffold/overlay'\nimport { wireIntegrations, type WireResult } from '../scaffold/wire'\n\n/**\n * `kick add` names with a layer. `queue` means BullMQ, as it does in\n * `kick new`; `queue:rabbitmq` / `queue:kafka` pick another provider, which\n * the layer doesn't configure, so they install only.\n */\nexport const FEATURE_LAYERS: Record<string, string> = {\n swagger: 'feature-swagger',\n devtools: 'feature-devtools',\n ws: 'feature-ws',\n queue: 'feature-queue',\n 'queue:bullmq': 'feature-queue',\n}\n\n/** The layers `packages` bring, rendered — or undefined when none has one. */\nexport function planWiring(packages: readonly string[]): RenderedProject | undefined {\n const layers = [...new Set(packages.map((name) => FEATURE_LAYERS[name]).filter(Boolean))]\n return layers.length > 0 ? renderLayers(layers as string[]) : undefined\n}\n\n/** The entry file to wire: `--entry`, else `src/index.ts` / `src/main.ts`. */\nexport function findEntry(cwd: string, entry?: string): string | undefined {\n const candidates = entry ? [entry] : ['src/index.ts', 'src/main.ts']\n return candidates.find((file) => existsSync(join(cwd, file)))\n}\n\n/**\n * Files among `files` with uncommitted changes. Outside a git repository\n * (or without git) nothing counts as dirty.\n */\nexport function dirtyFiles(cwd: string, files: readonly string[]): string[] {\n try {\n const out = execFileSync('git', ['status', '--porcelain', '--', ...files], {\n cwd,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n return out\n .split('\\n')\n .filter(Boolean)\n .map((line) => line.slice(3))\n } catch {\n return []\n }\n}\n\n/**\n * Write a layer's non-entry files. A file that exists only gains the lines it\n * doesn't already have (`.env` keeps its values); a missing one is created.\n * Returns the paths changed.\n */\nexport async function applyLayerFiles(\n cwd: string,\n files: ReadonlyMap<string, string>,\n): Promise<string[]> {\n const changed: string[] = []\n for (const [path, contents] of files) {\n const abs = join(cwd, path)\n if (!existsSync(abs)) {\n await writeFileSafe(abs, contents)\n changed.push(path)\n continue\n }\n const current = readFileSync(abs, 'utf-8')\n const have = new Set(current.split('\\n').map((line) => envKey(line) ?? line))\n const missing = contents\n .split('\\n')\n .filter((line) => line.trim() && !have.has(envKey(line) ?? line))\n if (missing.length === 0) continue\n const sep = current === '' || current.endsWith('\\n') ? '' : '\\n'\n await writeFileSafe(abs, `${current}${sep}${missing.join('\\n')}\\n`)\n changed.push(path)\n }\n return changed\n}\n\n/** `REDIS_HOST` for `REDIS_HOST=…`, so an existing value counts as present. */\nconst envKey = (line: string) => /^\\s*([A-Za-z_][\\w]*)\\s*=/.exec(line)?.[1]\n\n/** Splice the integrations into the entry file and write it back when it changed. */\nexport async function wireEntry(\n cwd: string,\n entry: string,\n integrations: readonly Integration[],\n): Promise<WireResult> {\n const abs = join(cwd, entry)\n const source = readFileSync(abs, 'utf-8')\n const result = wireIntegrations(source, integrations, projectVars(cwd), entry)\n if (result.source !== source) await writeFileSafe(abs, result.source)\n return result\n}\n\n/** Fill `{{name}}` / `{{version}}` from the project's package.json. */\nexport function projectVars(cwd: string): (text: string) => string {\n const pkg = readPackageJson(cwd)\n const vars: Record<string, string> = {\n name: String(pkg.name ?? 'app'),\n version: String(pkg.version ?? '0.0.0'),\n }\n return (text) => text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key) => vars[key] ?? all)\n}\n\nfunction readPackageJson(cwd: string): Record<string, unknown> {\n try {\n return JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf-8'))\n } catch {\n return {}\n }\n}\n\n/** What to paste by hand for entries that couldn't be placed. */\nexport function manualSnippet(entries: readonly Integration[]): string {\n const imports = entries\n .flatMap((e) => (e.import ? [e.import] : []))\n .map((spec) => {\n const parts = [spec.default, spec.names?.length ? `{ ${spec.names.join(', ')} }` : undefined]\n return `import ${parts.filter(Boolean).join(', ')} from '${spec.from}'`\n })\n const code = entries.map((e) => `${e.code},`)\n return [...imports, '', '// in bootstrap({ adapters: [ ... ] }):', ...code].join('\\n')\n}\n","import { execSync } from 'node:child_process'\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport type { Command } from 'commander'\nimport { loadKickConfig, PACKAGE_MANAGERS, type PackageManager } from '../config'\nimport { setAllowBuilds } from '../generators/templates/project-config'\nimport {\n applyLayerFiles,\n dirtyFiles,\n findEntry,\n manualSnippet,\n planWiring,\n projectVars,\n wireEntry,\n} from './add-wire'\n\ninterface PackageEntry {\n pkg: string\n peers: string[]\n /**\n * Peers depend on the project's HTTP engine, so they are resolved from\n * {@link resolveAppRuntime} rather than listed statically. Set on the\n * framework package itself: the engine is chosen at `bootstrap({ runtime })`,\n * so a Fastify project must not be handed `express`.\n */\n enginePeers?: boolean\n description: string\n dev?: boolean\n /** Type packages for peers that ship without their own types — installed as dev dependencies. */\n typePeers?: string[]\n /**\n * `true` for packages every project needs (framework + Vite plugin +\n * CLI). `kick new` installs these regardless of options chosen, and\n * future package-removal flows refuse to drop them.\n */\n core?: boolean\n /**\n * Set when the package still installs but should no longer be the\n * default choice. The string is the migration hint shown both in\n * `kick add --list --all` and as a warning when the package is added.\n */\n deprecated?: string\n /**\n * Install-script answers for dependencies this package pulls in.\n * Package managers block or skip unanswered scripts (see approveInstallScripts),\n * so `kick add` and `kick new` record these answers before installing.\n */\n builds?: Record<string, boolean>\n}\n\n/** Registry of KickJS packages and their required peer dependencies */\nexport const PACKAGE_REGISTRY: Record<string, PackageEntry> = {\n // Core (always installed by kick new — required for the framework to run)\n kickjs: {\n pkg: '@forinda/kickjs',\n // Resolved per runtime — see `enginePeers` / ENGINE_PEERS.\n peers: [],\n enginePeers: true,\n description: 'Unified framework: DI, decorators, routing, middleware',\n core: true,\n },\n vite: {\n pkg: '@forinda/kickjs-vite',\n peers: ['vite'],\n description: 'Vite plugin: dev server, HMR, module discovery',\n dev: true,\n core: true,\n },\n cli: {\n pkg: '@forinda/kickjs-cli',\n peers: [],\n description: 'CLI tool and code generators',\n dev: true,\n core: true,\n },\n\n // Schema validation — the validator backing env + DTO + OpenAPI\n // schemas. `@forinda/kickjs-schema` (a core dep) wraps whichever one\n // you pick behind `KickSchema`, but the validator itself is an\n // optional peer of `@forinda/kickjs`, so it must be installed\n // explicitly or the app errors at startup (\"Cannot find module\n // 'zod'\"). `kick new` installs the chosen one; `kick add` lets an\n // existing project add/switch.\n zod: {\n pkg: 'zod',\n peers: [],\n description: 'Zod schema validation (env, DTOs, OpenAPI) — wrap with fromZod()',\n },\n valibot: {\n pkg: 'valibot',\n peers: [],\n description: 'Valibot schema validation — wrap with fromValibot()',\n },\n yup: {\n pkg: 'yup',\n peers: [],\n description: 'Yup schema validation — wrap with fromYup()',\n },\n\n // AI — requires zod (^4) for tool/schema definitions.\n ai: {\n pkg: '@forinda/kickjs-ai',\n peers: ['zod'],\n description: 'AI toolkit — LLM providers, tool definitions from controllers',\n },\n\n // API\n swagger: {\n pkg: '@forinda/kickjs-swagger',\n peers: [],\n description: 'OpenAPI spec + Swagger UI + ReDoc',\n // swagger-ui-dist depends on @scarf/scarf, which has a postinstall script.\n builds: { '@scarf/scarf': true },\n },\n // Database — the dialect adapters now ship as subpaths of\n // `@forinda/kickjs-db` (`/pg`, `/sqlite`, `/mysql`), so each `kick add`\n // pulls the core package plus the one driver you need.\n db: {\n pkg: '@forinda/kickjs-db',\n peers: [],\n description: 'kick/db core — schema DSL, migrations, KickDbClient, customType',\n },\n pg: {\n pkg: '@forinda/kickjs-db',\n peers: ['pg'],\n typePeers: ['@types/pg'],\n description: 'kick/db + PostgreSQL driver (use @forinda/kickjs-db/pg)',\n },\n sqlite: {\n pkg: '@forinda/kickjs-db',\n peers: ['better-sqlite3'],\n // A native addon — its install script compiles or downloads the binary,\n // and pnpm 10+ fails the install (ERR_PNPM_IGNORED_BUILDS) until it's allowed.\n builds: { 'better-sqlite3': true },\n typePeers: ['@types/better-sqlite3'],\n description: 'kick/db + SQLite driver (use @forinda/kickjs-db/sqlite)',\n },\n mysql: {\n pkg: '@forinda/kickjs-db',\n peers: ['mysql2'],\n description: 'kick/db + MySQL driver (use @forinda/kickjs-db/mysql)',\n },\n\n // Real-time\n ws: {\n pkg: '@forinda/kickjs-ws',\n peers: ['ws'],\n description: 'WebSocket with @WsController decorators',\n },\n\n // DevTools\n devtools: {\n pkg: '@forinda/kickjs-devtools',\n peers: [],\n description: 'Development dashboard — routes, DI, metrics, health',\n dev: true,\n },\n\n // Queue\n queue: {\n pkg: '@forinda/kickjs-queue',\n peers: [],\n description: 'Queue adapter (BullMQ/RabbitMQ/Kafka)',\n },\n 'queue:bullmq': {\n pkg: '@forinda/kickjs-queue',\n peers: ['bullmq', 'ioredis'],\n // bullmq → msgpackr → msgpackr-extract (optional native addon). msgpackr\n // falls back to JS without it, so the script is declined — but it must be\n // answered, or pnpm 10+ fails the install (ERR_PNPM_IGNORED_BUILDS).\n builds: { 'msgpackr-extract': false },\n description: 'Queue with BullMQ + Redis',\n },\n 'queue:rabbitmq': {\n pkg: '@forinda/kickjs-queue',\n peers: ['amqplib'],\n description: 'Queue with RabbitMQ',\n },\n 'queue:kafka': {\n pkg: '@forinda/kickjs-queue',\n peers: ['kafkajs'],\n description: 'Queue with Kafka',\n },\n 'queue:redis-pubsub': {\n pkg: '@forinda/kickjs-queue',\n peers: ['ioredis'],\n description: 'Lightweight pub/sub via Redis (no persistence)',\n },\n\n // MCP — Model Context Protocol server\n mcp: {\n pkg: '@forinda/kickjs-mcp',\n peers: ['@modelcontextprotocol/server'],\n description: 'Model Context Protocol server — expose @Controller endpoints as AI tools',\n },\n\n // Testing\n testing: {\n pkg: '@forinda/kickjs-testing',\n peers: [],\n description: 'Test utilities and TestModule builder',\n dev: true,\n },\n}\n\n/**\n * Headline `kick add` packages shown after scaffolding — derived from\n * {@link PACKAGE_REGISTRY} so it can never advertise a deprecated package (the\n * old hardcoded list included auth / drizzle / prisma, all three since removed).\n * Excludes core packages\n * (already installed), deprecated ones, `:` sub-variants (e.g. `queue:bullmq`),\n * and the db-dialect / schema-lib duplicates that clutter a one-line summary.\n * `kick add --list` shows the full catalog.\n */\nexport const AVAILABLE_ADD_PACKAGES = Object.entries(PACKAGE_REGISTRY)\n .filter(\n ([name, entry]) =>\n !entry.core &&\n !entry.deprecated &&\n !name.includes(':') &&\n !['pg', 'sqlite', 'mysql', 'zod', 'valibot', 'yup'].includes(name),\n )\n .map(([name]) => name)\n .join(', ')\n\n/**\n * The `upload` catalog name is special — file uploads ship inside\n * `@forinda/kickjs` itself, so there's no package to install. What an app\n * needs is the multipart DRIVER for its HTTP runtime, and that differs per\n * engine. `planAddPackages` resolves `upload` against the configured runtime\n * (see {@link KickConfig.runtime}); `kick doctor` validates the same mapping.\n */\n/**\n * Engine peers per runtime — the same set `kick new` scaffolds for the chosen\n * engine (`generators/templates/project-config.ts`). `@forinda/kickjs` declares\n * all three as optional peers; which ones a project actually needs is decided\n * by `bootstrap({ runtime })`, so installing them is a runtime-dependent\n * question, not a static dependency.\n */\nexport const ENGINE_PEERS: Record<'express' | 'fastify' | 'h3', readonly string[]> = {\n express: ['express'],\n // `serve-static` rather than express for static files — no express dependency.\n fastify: ['fastify', '@fastify/middie', 'serve-static'],\n h3: ['h3', 'serve-static'],\n}\n\nexport const UPLOAD_DRIVERS: Record<\n 'express' | 'fastify' | 'h3',\n { prod?: string; dev?: string; note: string }\n> = {\n express: {\n prod: 'multer',\n dev: '@types/multer',\n note: 'Express uploads use multer (memory/disk storage, ctx.file / ctx.files).',\n },\n fastify: {\n prod: '@fastify/multipart',\n note: 'Fastify uploads use @fastify/multipart (buffered into ctx.file / ctx.files).',\n },\n h3: {\n note: 'h3 parses multipart natively (readMultipartFormData) — no driver to install.',\n },\n}\n\nexport type AppRuntime = 'express' | 'fastify' | 'h3'\n\n/**\n * Resolve the project's HTTP runtime: the `runtime` field in kick.config\n * (authoritative — `kick new` writes it), falling back to sniffing installed\n * deps in the nearest package.json (`fastify` → fastify, `h3` → h3), else\n * `express` (the default engine). Lets `kick add upload` / `kick doctor` pick\n * the engine-correct multipart driver even in projects scaffolded before the\n * `runtime` field existed.\n */\n/** Validate `--runtime`, returning undefined when absent and exiting on a bad value. */\nexport function parseRuntimeFlag(value: unknown): AppRuntime | undefined {\n if (value === undefined) return undefined\n if (value === 'express' || value === 'fastify' || value === 'h3') return value\n throw new Error(`Invalid --runtime '${String(value)}'. Expected express, fastify or h3.`)\n}\n\nexport async function resolveAppRuntime(cwd = process.cwd()): Promise<AppRuntime> {\n return (await resolveAppRuntimeDetailed(cwd)).runtime\n}\n\n/**\n * As {@link resolveAppRuntime}, but says whether the answer was a guess.\n *\n * `kick.config.ts`'s `runtime` is authoritative and never ambiguous. Sniffing\n * is, so callers that act on the result — installing engine peers — surface the\n * ambiguity instead of silently picking.\n */\nexport async function resolveAppRuntimeDetailed(\n cwd = process.cwd(),\n): Promise<RuntimeDetection & { fromConfig: boolean }> {\n const config = await loadKickConfig(cwd)\n const fromConfig = (config as { runtime?: AppRuntime } | null)?.runtime\n if (fromConfig === 'express' || fromConfig === 'fastify' || fromConfig === 'h3') {\n return { runtime: fromConfig, candidates: [fromConfig], ambiguous: false, fromConfig: true }\n }\n return { ...detectRuntimeFromDepsDetailed(cwd), fromConfig: false }\n}\n\n/** Sniff the runtime from installed deps when kick.config has no `runtime`. */\n/**\n * Sniff result, with enough detail for a caller to say when it is guessing.\n *\n * `ambiguous` means more than one engine is installed and nothing settles which\n * one the app boots on. That happens legitimately — a project on Express with\n * Fastify in devDependencies for a benchmark — and the old precedence order\n * (fastify first, whether prod or dev) answered `fastify` there, which installed\n * the wrong engine peers.\n */\nexport interface RuntimeDetection {\n runtime: AppRuntime\n /** Engines found, in `dependencies` then `devDependencies`. */\n candidates: AppRuntime[]\n ambiguous: boolean\n}\n\nconst ENGINE_BY_PACKAGE: ReadonlyArray<readonly [string, AppRuntime]> = [\n ['express', 'express'],\n ['fastify', 'fastify'],\n ['h3', 'h3'],\n]\n\n/** Sniff the runtime from installed deps when kick.config has no `runtime`. */\nexport function detectRuntimeFromDepsDetailed(cwd = process.cwd()): RuntimeDetection {\n const dir = findUp('package.json', cwd)\n if (!dir) return { runtime: 'express', candidates: [], ambiguous: false }\n\n let prod: Record<string, unknown> = {}\n let dev: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf-8'))\n prod = (pkg.dependencies ?? {}) as Record<string, unknown>\n dev = (pkg.devDependencies ?? {}) as Record<string, unknown>\n } catch {\n return { runtime: 'express', candidates: [], ambiguous: false }\n }\n\n const inProd = ENGINE_BY_PACKAGE.filter(([p]) => p in prod).map(([, r]) => r)\n const inDev = ENGINE_BY_PACKAGE.filter(([p]) => p in dev && !(p in prod)).map(([, r]) => r)\n const candidates = [...inProd, ...inDev]\n\n // A runtime dependency outranks a dev one: you deploy on what you ship. That\n // IS a resolution, so it is not ambiguous — reporting otherwise made the\n // refusal below block the exact case this rule exists to allow (an Express\n // app keeping fastify in devDependencies for a benchmark).\n if (inProd.length === 1) return { runtime: inProd[0], candidates, ambiguous: false }\n if (inProd.length === 0 && inDev.length === 1) {\n return { runtime: inDev[0], candidates, ambiguous: false }\n }\n if (candidates.length === 0) return { runtime: 'express', candidates, ambiguous: false }\n\n // Two or more engines at the same level — nothing here can tell them apart.\n // Default to the framework default and let the caller say it is guessing.\n return { runtime: 'express', candidates, ambiguous: true }\n}\n\n/** Back-compat wrapper — the runtime only. */\nexport function detectRuntimeFromDeps(cwd = process.cwd()): AppRuntime {\n return detectRuntimeFromDepsDetailed(cwd).runtime\n}\n\n/**\n * Walk up from `fromDir` to filesystem root, returning the first\n * directory that contains `name`. Lets monorepo sub-packages pick up\n * lockfiles and `packageManager` fields living at the workspace root.\n */\nfunction findUp(name: string, fromDir = process.cwd()): string | null {\n let current = fromDir\n while (true) {\n if (existsSync(resolve(current, name))) return current\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nfunction detectFromLockfile(): PackageManager | null {\n if (findUp('pnpm-lock.yaml')) return 'pnpm'\n if (findUp('yarn.lock')) return 'yarn'\n if (findUp('bun.lockb') || findUp('bun.lock')) return 'bun'\n if (findUp('package-lock.json')) return 'npm'\n return null\n}\n\n/**\n * Read `packageManager` from the nearest ancestor `package.json` that\n * declares the field (corepack convention: `\"pnpm@10.0.0\"`). Climbs so\n * monorepo sub-packages inherit the workspace pm even when their own\n * package.json omits the field.\n */\nfunction packageManagerFromPackageJson(): PackageManager | null {\n let dir: string | null = process.cwd()\n while (dir) {\n const pkgPath = resolve(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))\n const field: unknown = pkg.packageManager\n if (typeof field === 'string') {\n const name = field.split('@')[0] as PackageManager\n if (PACKAGE_MANAGERS.includes(name)) return name\n }\n } catch {\n // ignore — keep climbing\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n return null\n}\n\nexport type PackageManagerSource = 'flag' | 'config' | 'package.json' | 'lockfile' | 'default'\n\n/**\n * Resolve which package manager to use, in priority order:\n * 1. `--pm` CLI flag\n * 2. `packageManager` in kick.config\n * 3. `packageManager` in nearest ancestor package.json (corepack)\n * 4. Nearest ancestor lockfile (pnpm-lock.yaml → yarn.lock → bun.lock → package-lock.json)\n * 5. `'npm'` fallback\n *\n * Returns the chosen pm plus the source for callers that want to log\n * the resolution path.\n */\nexport async function resolvePackageManagerWithSource(\n flagPm: string | undefined,\n): Promise<{ pm: PackageManager; source: PackageManagerSource }> {\n if (flagPm && PACKAGE_MANAGERS.includes(flagPm as PackageManager)) {\n return { pm: flagPm as PackageManager, source: 'flag' }\n }\n\n const config = await loadKickConfig(process.cwd())\n if (config?.packageManager && PACKAGE_MANAGERS.includes(config.packageManager)) {\n return { pm: config.packageManager, source: 'config' }\n }\n\n const fromPkg = packageManagerFromPackageJson()\n if (fromPkg) return { pm: fromPkg, source: 'package.json' }\n\n const fromLock = detectFromLockfile()\n if (fromLock) return { pm: fromLock, source: 'lockfile' }\n\n return { pm: 'npm', source: 'default' }\n}\n\n/** Convenience wrapper for callers that don't care about the source. */\nexport async function resolvePackageManager(flagPm: string | undefined): Promise<PackageManager> {\n const { pm } = await resolvePackageManagerWithSource(flagPm)\n return pm\n}\n\n/**\n * Print the package catalog. By default shows just the three core\n * packages every project always has — the optional list churns\n * (packages added, deprecated, removed) and a long enumeration in CLI\n * output / docs goes stale within a release. Pass `all = true` to dump\n * everything; that's what `kick add --list --all` triggers when an\n * adopter genuinely wants the live catalog.\n */\nexport function printPackageList(all = false, runtime?: 'express' | 'fastify' | 'h3'): void {\n const entries = Object.entries(PACKAGE_REGISTRY)\n const maxName = Math.max(...entries.map(([k]) => k.length))\n const core = entries.filter(([, info]) => info.core)\n const optional = entries.filter(([, info]) => !info.core)\n\n const formatRow = ([name, info]: [string, PackageEntry]): string => {\n const padded = name.padEnd(maxName + 2)\n // Engine peers depend on the runtime, so name it rather than printing a\n // list that would be wrong for two projects out of three.\n const resolved = info.enginePeers\n ? [...info.peers, ...ENGINE_PEERS[runtime ?? 'express']]\n : info.peers\n const engineNote = info.enginePeers ? ` [${runtime ?? 'express'} engine]` : ''\n const peers = resolved.length ? ` (+ ${resolved.join(', ')})${engineNote}` : ''\n const deprecated = info.deprecated ? ` [DEPRECATED — ${info.deprecated}]` : ''\n return ` ${padded} ${info.description}${peers}${deprecated}`\n }\n\n console.log('\\n Core packages (always installed by `kick new`):\\n')\n for (const row of core) console.log(formatRow(row))\n\n if (all) {\n console.log('\\n Optional packages (add as needed):\\n')\n for (const row of optional) console.log(formatRow(row))\n } else {\n console.log(`\\n Plus ${optional.length} optional packages (swagger, db, queue, …).`)\n console.log(' Run `kick add --list --all` for the full catalog.')\n }\n\n console.log('\\n Usage: kick add ai db swagger')\n console.log(' kick add queue:bullmq')\n console.log(' kick add upload # installs the multipart driver for your runtime')\n console.log()\n}\n\n/** Build tools every template installs: swc compiles the decorators, esbuild is Vite's. */\nexport const TEMPLATE_BUILDS: Record<string, boolean> = { '@swc/core': true, esbuild: true }\n\n/**\n * Record install-script answers where `pm` reads them, in `dir`:\n *\n * - pnpm 10+: pnpm-workspace.yaml, in both approval formats (see setAllowBuilds).\n * Unanswered scripts are skipped with a warning before pnpm 11; pnpm 11 fails\n * the install and every later `pnpm exec` with ERR_PNPM_IGNORED_BUILDS.\n * - npm 11.19+: `allowScripts` in package.json. Unanswered scripts are skipped\n * with a warning.\n * - bun: `trustedDependencies` in package.json. Untrusted scripts are skipped.\n * Only approvals are written; bun has no deny entry.\n * - yarn runs dependency scripts, so there is nothing to write.\n *\n * Existing answers win: a scaffold or `kick add` never overrides a decision\n * already in the file. Returns the file it changed, if any.\n */\nexport function approveInstallScripts(\n pm: PackageManager,\n dir: string,\n builds: Record<string, boolean>,\n): string | undefined {\n if (pm === 'pnpm') {\n const file = resolve(dir, 'pnpm-workspace.yaml')\n const before = existsSync(file) ? readFileSync(file, 'utf-8') : ''\n const after = setAllowBuilds(before, builds)\n if (after === before) return undefined\n writeFileSync(file, after)\n return file\n }\n if (pm !== 'npm' && pm !== 'bun') return undefined\n\n const file = resolve(dir, 'package.json')\n if (!existsSync(file)) return undefined\n const pkg = JSON.parse(readFileSync(file, 'utf-8'))\n let changed = false\n if (pm === 'npm') {\n const allow: Record<string, boolean> = pkg.allowScripts ?? {}\n for (const [name, value] of Object.entries(builds)) {\n // npm also accepts version-pinned keys (`esbuild@0.28.2`).\n if (Object.keys(allow).some((key) => key === name || key.startsWith(`${name}@`))) continue\n allow[name] = value\n changed = true\n }\n pkg.allowScripts = allow\n } else {\n const trusted: string[] = pkg.trustedDependencies ?? []\n for (const [name, value] of Object.entries(builds)) {\n if (!value || trusted.includes(name)) continue\n trusted.push(name)\n changed = true\n }\n pkg.trustedDependencies = trusted\n }\n if (!changed) return undefined\n writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\\n`)\n return file\n}\n\n/**\n * Where `pm` reads install-script answers from: the workspace root when the\n * project is a workspace member (fullstack server/), else the current directory.\n */\nfunction installRoot(pm: PackageManager): string {\n if (pm === 'pnpm') return findUp('pnpm-workspace.yaml') ?? process.cwd()\n for (let dir = process.cwd(); ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf-8')).workspaces) return dir\n } catch {\n // no package.json here, or not JSON — keep walking\n }\n if (dirname(dir) === dir) return process.cwd()\n }\n}\n\n/** Merged install-script answers for catalog entries (unknown names skipped). */\nexport function buildsFor(packages: string[]): Record<string, boolean> {\n return Object.assign({}, ...packages.map((name) => PACKAGE_REGISTRY[name]?.builds ?? {}))\n}\n\nexport interface AddPlan {\n prodDeps: string[]\n devDeps: string[]\n unknown: string[]\n /** Deprecation notices for requested entries — print, then install anyway. */\n warnings: string[]\n /** Informational notes (e.g. the upload driver chosen for the runtime). */\n notices: string[]\n}\n\n/**\n * Pure resolution step for `kick add` — maps requested catalog names to\n * the npm packages (plus peers) to install, split prod/dev. Kept free\n * of I/O so the catalog rules (dev defaults, deprecations, unknown\n * handling) are unit-testable without spawning a package manager.\n */\nexport function planAddPackages(\n packages: string[],\n forceDev: boolean,\n runtime: AppRuntime = 'express',\n): AddPlan {\n const prodDeps = new Set<string>()\n const devDeps = new Set<string>()\n const unknown: string[] = []\n const warnings: string[] = []\n const notices: string[] = []\n\n for (const name of packages) {\n // `upload` isn't a package — it's the runtime's multipart driver. File\n // uploads ship in @forinda/kickjs; only the engine backend needs adding.\n if (name === 'upload') {\n const driver = UPLOAD_DRIVERS[runtime]\n notices.push(`upload (${runtime}): ${driver.note}`)\n if (driver.prod) (forceDev ? devDeps : prodDeps).add(driver.prod)\n if (driver.dev) devDeps.add(driver.dev)\n continue\n }\n\n const entry = PACKAGE_REGISTRY[name]\n if (!entry) {\n unknown.push(name)\n continue\n }\n if (entry.deprecated) {\n warnings.push(`'${name}' (${entry.pkg}) is deprecated — ${entry.deprecated}`)\n }\n const target = forceDev || entry.dev ? devDeps : prodDeps\n target.add(entry.pkg)\n for (const peer of entry.peers) {\n target.add(peer)\n }\n for (const types of entry.typePeers ?? []) devDeps.add(types)\n if (entry.enginePeers) {\n const enginePeers = ENGINE_PEERS[runtime]\n for (const peer of enginePeers) target.add(peer)\n notices.push(`${name} (${runtime}): engine peers ${enginePeers.join(', ')}`)\n }\n }\n\n return { prodDeps: [...prodDeps], devDeps: [...devDeps], unknown, warnings, notices }\n}\n\nexport function registerListCommand(program: Command): void {\n program\n .command('list')\n .alias('ls')\n .description('List KickJS packages (core only; pair with --all for the full catalog)')\n .option('--all', 'Include the full optional catalog')\n .option('--runtime <engine>', 'HTTP engine to show peers for: express | fastify | h3')\n .action(async (opts: { all?: boolean; runtime?: string }) => {\n printPackageList(\n Boolean(opts.all),\n parseRuntimeFlag(opts.runtime) ?? (await resolveAppRuntime()),\n )\n })\n}\n\nexport function registerAddCommand(program: Command): void {\n program\n .command('add [packages...]')\n .description('Add KickJS packages with their required dependencies')\n .option('--pm <manager>', 'Package manager override')\n .option('-D, --dev', 'Install as dev dependency')\n .option('--list', 'List packages (core only by default; pair with --all)')\n .option(\n '--runtime <engine>',\n 'HTTP engine for peer resolution: express | fastify | h3 (overrides kick.config.ts)',\n )\n .option('--all', 'When listing, include the full optional catalog')\n .option('--no-wire', 'Install only — do not add adapters to the entry file or .env')\n .option('--entry <file>', 'Entry file to wire (default: src/index.ts, then src/main.ts)')\n .option('-f, --force', 'Wire even when the files it edits have uncommitted changes')\n .action(async (packages: string[], opts: any) => {\n // List mode\n if (opts.list || packages.length === 0) {\n printPackageList(\n Boolean(opts.all),\n parseRuntimeFlag(opts.runtime) ?? (await resolveAppRuntime()),\n )\n return\n }\n\n const { pm, source } = await resolvePackageManagerWithSource(opts.pm)\n console.log(`\\n Using ${pm} (resolved from ${source})`)\n // Resolve the runtime so `kick add upload` installs the right multipart\n // driver (express → multer, fastify → @fastify/multipart, h3 → none) and\n // the framework gets the engine peers it actually runs on.\n const fromFlag = parseRuntimeFlag(opts.runtime)\n const detection = await resolveAppRuntimeDetailed(process.cwd())\n const runtime = fromFlag ?? detection.runtime\n\n // Two engines at the same dependency level and nothing to break the tie.\n // Installing writes package.json and node_modules, so guessing here\n // leaves an adopter to undo it by hand — refuse instead, with both ways\n // to say what the app actually boots on.\n if (!fromFlag && detection.ambiguous) {\n console.error(\n `\\n Cannot tell which HTTP engine this app boots on: found ` +\n `${detection.candidates.join(', ')} in package.json.\\n` +\n `\\n Installing engine peers for the wrong one is worse than not installing them, so:\\n` +\n ` • set \\`runtime: '<engine>'\\` in kick.config.ts (permanent, also fixes kick doctor), or\\n` +\n ` • pass --runtime <${detection.candidates.join('|')}> for this command\\n`,\n )\n process.exitCode = 1\n return\n }\n const plan = planAddPackages(packages, Boolean(opts.dev), runtime)\n const { unknown, warnings, notices } = plan\n let { prodDeps, devDeps } = plan\n\n // Packages with a scaffold layer (swagger, devtools, ws, queue) are also\n // wired: their adapter goes into the entry file and their .env lines in.\n // The entry file imports them, so they install as regular dependencies\n // (devtools is otherwise a dev dependency), with the peers the layer uses.\n const cwd = process.cwd()\n // A mistyped --entry would otherwise install first and only then say\n // there was nothing to wire.\n if (opts.entry && !existsSync(resolve(cwd, opts.entry))) {\n console.error(`\\n --entry ${opts.entry} does not exist.\\n`)\n process.exitCode = 1\n return\n }\n const wiring = opts.wire === false ? undefined : planWiring(packages)\n const entry = wiring ? findEntry(cwd, opts.entry) : undefined\n if (wiring) {\n prodDeps = [...new Set([...prodDeps, ...wiring.dependencies])]\n devDeps = [\n ...new Set([...devDeps, ...wiring.devDependencies].filter((d) => !prodDeps.includes(d))),\n ]\n // Wiring edits files in place; refuse over uncommitted work there, so\n // the change stays reviewable (and revertable) as its own diff.\n const dirty = dirtyFiles(cwd, [...(entry ? [entry] : []), ...wiring.files.keys()])\n if (dirty.length > 0 && !opts.force) {\n console.error(\n `\\n ${dirty.join(', ')} ${dirty.length === 1 ? 'has' : 'have'} uncommitted changes, ` +\n `and kick add would edit ${dirty.length === 1 ? 'it' : 'them'}.\\n` +\n ` Commit or stash first, pass --force to edit anyway, or --no-wire to install only.\\n`,\n )\n process.exitCode = 1\n return\n }\n }\n\n for (const warning of warnings) {\n console.warn(`\\n WARNING: ${warning}`)\n }\n\n for (const notice of notices) {\n console.log(`\\n ${notice}`)\n }\n\n if (unknown.length > 0) {\n console.log(`\\n Unknown packages: ${unknown.join(', ')}`)\n console.log(' Run \"kick add --list\" to see available packages.\\n')\n if (prodDeps.length === 0 && devDeps.length === 0) return\n }\n\n // Answer install-script approvals before installing, so the package\n // manager doesn't block the scripts these packages bring in.\n const builds = { ...buildsFor(packages), ...wiring?.builds }\n if (Object.keys(builds).length > 0) {\n const file = approveInstallScripts(pm, installRoot(pm), builds)\n if (file) console.log(`\\n Approved install scripts in ${file}`)\n }\n\n let installed = true\n // Install production dependencies\n if (prodDeps.length > 0) {\n const deps = prodDeps\n const cmd = `${pm} add ${deps.join(' ')}`\n console.log(`\\n Installing ${deps.length} dependency(ies):`)\n for (const dep of deps) console.log(` + ${dep}`)\n console.log()\n try {\n execSync(cmd, { stdio: 'inherit' })\n } catch {\n installed = false\n console.log(`\\n Installation failed. Run manually:\\n ${cmd}\\n`)\n }\n }\n\n // Install dev dependencies\n if (devDeps.length > 0) {\n const deps = devDeps\n const cmd = `${pm} add -D ${deps.join(' ')}`\n console.log(`\\n Installing ${deps.length} dev dependency(ies):`)\n for (const dep of deps) console.log(` + ${dep} (dev)`)\n console.log()\n try {\n execSync(cmd, { stdio: 'inherit' })\n } catch {\n installed = false\n console.log(`\\n Installation failed. Run manually:\\n ${cmd}\\n`)\n }\n }\n\n if (wiring) {\n if (!installed) {\n console.log(' Skipped wiring — the install did not finish.\\n')\n } else {\n for (const path of await applyLayerFiles(cwd, wiring.files)) {\n console.log(` Updated ${path}`)\n }\n const result = entry ? await wireEntry(cwd, entry, wiring.integrations) : undefined\n for (const name of result?.added ?? []) console.log(` Added ${name} to ${entry}`)\n for (const name of result?.present ?? []) console.log(` ${name} is already in ${entry}`)\n const fill = projectVars(cwd)\n const manual = result\n ? result.manual\n : wiring.integrations\n .filter((i) => i.slot && i.code)\n .map((i) => ({ ...i, code: fill(i.code!) }))\n if (manual.length > 0) {\n console.log(\n `\\n ${entry ? `Could not find bootstrap({ adapters: [...] }) in ${entry}` : 'No entry file found'}` +\n ' — add this yourself:\\n',\n )\n console.log(manualSnippet(manual).replace(/^/gm, ' '))\n console.log()\n }\n }\n }\n\n if (installed) {\n console.log(' Done!\\n')\n } else {\n console.log(' Finished with errors — the install above did not complete.\\n')\n process.exitCode = 1\n }\n })\n}\n","import { join, dirname } from 'node:path'\nimport { execSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { writeFileSafe } from '../utils/fs'\nimport { fillVars, renderLayers, TEMPLATES_DIR, type Integration } from '../scaffold/overlay'\nimport { captureCommand, captureCommandAsync } from '../utils/shell'\nimport { generatePackageJson } from './templates/project-config'\nimport {\n AVAILABLE_ADD_PACKAGES,\n TEMPLATE_BUILDS,\n approveInstallScripts,\n buildsFor,\n} from '../commands/add'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The CLI's own package.json sits one level up from the bundle\n * (`dist/project-*.mjs`) but two levels up from this source file\n * (`src/generators/project.ts`). Checking both is what lets this module be\n * imported from a test at all — reading only the bundle-relative path threw\n * ENOENT the moment anything imported it from source, which is why the\n * version-resolution path shipped untested.\n */\nconst cliPkg = JSON.parse(\n readFileSync(\n [join(__dirname, '..', 'package.json'), join(__dirname, '..', '..', 'package.json')].find(\n existsSync,\n )!,\n 'utf-8',\n ),\n)\n\n/**\n * Sibling `@forinda/kickjs-*` packages whose versions are resolved\n * independently when scaffolding a new project. Each entry is queried\n * via `npm view <name> version`; failure falls back to `latest`\n * (see `fallbackRange`).\n *\n * Per-package independent versioning landed with changesets — before\n * that, every sibling shipped in lockstep with the CLI so a single\n * pin was correct. Now `@forinda/kickjs@5.5.0` may pair with\n * `@forinda/kickjs-cli@5.4.2` and `@forinda/kickjs-swagger@5.3.1`;\n * pinning them all to the CLI's version under-installs adopters.\n */\nexport const SIBLING_PACKAGES = [\n '@forinda/kickjs',\n '@forinda/kickjs-cli',\n '@forinda/kickjs-schema',\n '@forinda/kickjs-vite',\n '@forinda/kickjs-swagger',\n '@forinda/kickjs-ws',\n '@forinda/kickjs-queue',\n '@forinda/kickjs-devtools',\n '@forinda/kickjs-testing',\n '@forinda/kickjs-client',\n] as const\n\n/**\n * Third-party dependencies the templates install, resolved at scaffold time\n * instead of pinned here — a pin means every React, Vitest or oxlint release\n * needs a CLI release to reach new projects, and the pins drift apart (the\n * fullstack web app shipped vite ^7 while the server template was on ^8).\n *\n * `cap` is the range a package may float within, for the ones where a new\n * major changes what the templates generate or what KickJS peers on: the\n * engine packages, the schema libraries, and the toolchain the generated\n * configs are written against. Everything else tracks `latest`.\n *\n * The value is the fallback: what gets written when `npm view` says nothing\n * (offline, registry down), so a scaffold without network still installs.\n */\nexport const THIRD_PARTY_PACKAGES: Record<string, { fallback: string; cap?: string }> = {\n // Frontend — the fullstack web app. Nothing the template writes is\n // version-specific (`createRoot`, JSX, a plugin call), so these float.\n react: { fallback: '^19.0.0' },\n 'react-dom': { fallback: '^19.0.0' },\n '@types/react': { fallback: '^19.0.0' },\n '@types/react-dom': { fallback: '^19.0.0' },\n '@vitejs/plugin-react': { fallback: '^5.0.0' },\n // Toolchain.\n '@types/node': { fallback: '^25.0.0' },\n '@types/supertest': { fallback: '^7.2.1' },\n supertest: { fallback: '^7.2.2' },\n vitest: { fallback: '^4.1.2' },\n '@swc/core': { fallback: '^1.15.21' },\n 'unplugin-swc': { fallback: '^1.5.9' },\n oxfmt: { fallback: '^0.65.0' },\n oxlint: { fallback: '^1.80.0' },\n // Capped: an optional peer of @forinda/kickjs at this major. Uncapped,\n // `latest` (18) installed with an unmet-peer warning on every scaffold.\n dotenv: { fallback: '^17.3.1', cap: '^17' },\n 'reflect-metadata': { fallback: '^0.2.2' },\n // Capped — a new major here breaks the generated project, not just its deps.\n // vite: `@forinda/kickjs-vite` peers on it and the generated vite.config.ts\n // is written against this major.\n vite: { fallback: '^8.0.3', cap: '^8' },\n // typescript: the generated tsconfig.json targets this major.\n typescript: { fallback: '^7.0.2', cap: '^7' },\n '@typescript/typescript6': { fallback: '^6.0.2', cap: '^6' },\n // HTTP engines: `bootstrap({ runtime })` peers on the major.\n express: { fallback: '^5.1.0', cap: '^5' },\n '@types/express': { fallback: '^5.0.6', cap: '^5' },\n fastify: { fallback: '^5.0.0', cap: '^5' },\n '@fastify/middie': { fallback: '^9.0.0', cap: '^9' },\n // h3 v2 is a different runtime (`./h3-web`), not an upgrade of this one.\n h3: { fallback: '^1.0.0', cap: '^1' },\n 'serve-static': { fallback: '^2.2.0', cap: '^2' },\n // Schema libraries: `@forinda/kickjs-schema` adapts one major each.\n zod: { fallback: '^4.3.6', cap: '^4' },\n valibot: { fallback: '^1.4.1', cap: '^1' },\n yup: { fallback: '^1.7.1', cap: '^1' },\n // Peers of the optional packages (`--packages ws,queue`), capped at the\n // major those packages peer on.\n ws: { fallback: '^8.18.0', cap: '^8' },\n bullmq: { fallback: '^5.0.0', cap: '^5' },\n ioredis: { fallback: '^5.0.0', cap: '^5' },\n}\n\n/**\n * Newest version matching `spec`. A bare name asks for the `latest` tag and\n * npm prints one version; a range prints every match as JSON, newest last.\n */\nexport function parseNpmVersion(output: string | null): string | null {\n if (!output) return null\n const trimmed = output.trim()\n if (/^\\d+\\.\\d+\\.\\d+/.test(trimmed)) return trimmed.split(/\\s/)[0]!\n try {\n const parsed = JSON.parse(trimmed) as unknown\n const list = Array.isArray(parsed) ? parsed : [parsed]\n const versions = list.filter((v): v is string => typeof v === 'string')\n return versions.length > 0 ? versions[versions.length - 1]! : null\n } catch {\n return null\n }\n}\n\n/**\n * Range to write when `npm view <name> version` gives us nothing.\n *\n * It must never be the CLI's own version. Sibling packages version\n * independently, so `@forinda/kickjs-vite@^${cliVersion}` names a release\n * that does not exist — the scaffold then dies at install time with\n * `npm error 404 '@forinda/kickjs-vite@^6.14.1' is not in this registry`,\n * which is worse than the under-install this fallback was meant to avoid.\n * `latest` is the one range that is always resolvable and always current.\n *\n * The CLI itself is the exception: its version IS the CLI's version, and\n * pinning it keeps a scaffold reproducible against the CLI that made it.\n */\nfunction fallbackRange(name: string): string {\n return name === '@forinda/kickjs-cli' ? `^${cliPkg.version}` : 'latest'\n}\n\n/**\n * Resolve the latest published version of every sibling package via\n * `npm view <name> version` (through `captureCommandAsync`, which routes\n * around Windows' `.cmd` shims — see utils/shell.ts).\n *\n * The timeout is generous and the queries are genuinely concurrent: a\n * warm `npm view` against the public registry measures 0.6–3.6s per\n * package, so the old 5s budget was one slow response away from expiring,\n * and the sync `captureCommand` under `Promise.all` ran all ten serially\n * — making the per-call budget the only thing standing between a scaffold\n * and a package.json full of fallbacks.\n */\n/**\n * Run `task` over every item, at most `limit` at a time. Each `npm view` is a\n * process; the full list is 37 of them, and firing all of them at once can\n * exhaust process or memory limits on a small machine (CI containers, a\n * Raspberry Pi) — which fails the scaffold rather than slowing it.\n */\nasync function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = Array.from({ length: items.length })\n let next = 0\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n while (next < items.length) {\n const index = next++\n results[index] = await task(items[index]!)\n }\n })\n await Promise.all(workers)\n return results\n}\n\n/**\n * How long the whole resolution may take before the rest of the packages take\n * their fallback ranges. Node's `timeout` applies per child process, so a\n * stalled registry would otherwise cost one timeout per wave of the worker\n * pool — 37 lookups, 8 at a time, is five waves and over a minute of a\n * scaffold sitting still.\n */\nexport const VERSION_LOOKUP_BUDGET_MS = 20_000\n\nexport async function resolveSiblingVersions(): Promise<Record<string, string>> {\n const queries = [\n ...SIBLING_PACKAGES.map((name) => ({ name, fallback: fallbackRange(name), cap: undefined })),\n ...Object.entries(THIRD_PARTY_PACKAGES).map(([name, entry]) => ({ name, ...entry })),\n ]\n\n const deadline = Date.now() + VERSION_LOOKUP_BUDGET_MS\n\n const resolved = await mapWithConcurrency(queries, 8, async ({ name, fallback, cap }) => {\n // Out of budget: take the fallback rather than start another probe.\n const remaining = deadline - Date.now()\n if (remaining <= 0) return [name, fallback] as const\n\n // Network failure / package not yet published / npm unavailable all\n // surface as null → fall back to a range that always resolves.\n const spec = cap ? `${name}@${cap}` : name\n const out = await captureCommandAsync(\n 'npm',\n // A capped query matches many versions; npm prints them as JSON.\n cap ? ['view', spec, 'version', '--json'] : ['view', spec, 'version'],\n { timeout: remaining },\n )\n const version = parseNpmVersion(out)\n return [name, version ? `^${version}` : fallback] as const\n })\n\n return Object.fromEntries(resolved)\n}\n\n/**\n * Resolve the published version of a package at a given dist-tag\n * (`npm view <name>@<tag> version`). Returns `null` on any failure. Used\n * to pin `@forinda/kickjs` to the `alpha` channel when scaffolding a\n * Fastify / h3 app — the engine subpaths (`@forinda/kickjs/fastify`,\n * `/h3`) ship only on the alpha until the runtimes land in a stable\n * release, so the default `latest` resolution would install a kickjs\n * that doesn't export them (→ Vite \"./h3 is not exported\" at boot).\n * Returns the bare version; the caller applies a `^` range so the project\n * floats to newer alphas and auto-graduates to stable (a caret over a\n * prerelease matches same-tuple prereleases ≥ it, plus later stables `< next\n * major`).\n */\nfunction resolveVersionAtTag(name: string, tag: string): string | null {\n const out = captureCommand('npm', ['view', `${name}@${tag}`, 'version'], { timeout: 20_000 })\n return out && /^\\d+\\.\\d+\\.\\d+/.test(out) ? out : null\n}\n\n/**\n * Whether the package at a given dist-tag exports a subpath (e.g. `./h3`).\n * Reads the `exports` map via `npm view <name>@<tag> exports --json`. Used to\n * gate the alpha-pin: if `latest` already ships the engine subpath, the runtime\n * has graduated to stable and we should NOT downgrade to an older alpha.\n * Returns `false` on any failure (missing field / network / unparseable) so the\n * caller treats \"unknown\" as \"not present\" and falls through to the alpha path.\n */\n/** Strip a leading range operator (`^1.2.3` / `~1.2.3` → `1.2.3`). */\nfunction stripRange(range: string | undefined): string {\n return (range ?? '').replace(/^[\\^~>=<\\s]+/, '')\n}\n\n/**\n * Compare the release cores (major.minor.patch, ignoring any `-prerelease`\n * suffix) of two versions: is `a` >= `b`? Used to guard the alpha-pin so a\n * package is never downgraded onto a stale prerelease whose stable line has\n * already moved past it. A coarse compare is enough here — we only need\n * \"is this alpha at least as new as the stable we'd otherwise install\".\n */\nfunction baseVersionGte(a: string, b: string): boolean {\n const core = (v: string): number[] =>\n stripRange(v)\n .split('-')[0]!\n .split('.')\n .map((n) => Number.parseInt(n, 10) || 0)\n const [a0 = 0, a1 = 0, a2 = 0] = core(a)\n const [b0 = 0, b1 = 0, b2 = 0] = core(b)\n if (a0 !== b0) return a0 > b0\n if (a1 !== b1) return a1 > b1\n return a2 >= b2\n}\n\nfunction tagExportsSubpath(name: string, tag: string, subpath: string): boolean {\n const out = captureCommand('npm', ['view', `${name}@${tag}`, 'exports', '--json'], {\n timeout: 20_000,\n })\n if (!out) return false\n try {\n const exportsMap = JSON.parse(out) as Record<string, unknown>\n return Object.prototype.hasOwnProperty.call(exportsMap, subpath)\n } catch {\n return false\n }\n}\n\ntype ProjectTemplate = 'rest' | 'minimal'\ntype SchemaLib = 'zod' | 'valibot' | 'yup'\n\ninterface InitProjectOptions {\n name: string\n directory: string\n packageManager?: 'pnpm' | 'npm' | 'yarn' | 'bun'\n initGit?: boolean\n installDeps?: boolean\n template?: ProjectTemplate\n defaultRepo?: string\n packages?: string[]\n /** Schema library to scaffold env / DTOs with. Defaults to `zod`. */\n schemaLib?: SchemaLib\n /** HTTP engine to scaffold. Defaults to `express`. */\n runtime?: 'express' | 'fastify' | 'h3'\n /** Wire `SpaAdapter` at this clientDir (fullstack template). */\n spaClientDir?: string\n /**\n * Layers rendered after the selection's — `server-fullstack` for the\n * fullstack workspace's server (strict port, client route map, TS 6 pin).\n */\n extraLayers?: string[]\n /**\n * Record install-script approvals for the package manager (pnpm-workspace.yaml,\n * or package.json for npm/bun). Default true; false when the project is a\n * member of a workspace whose root records them.\n */\n approveInstallScripts?: boolean\n /**\n * Write netlify.toml / vercel.json. Default true; false for a workspace\n * member — the platforms build from the root, which owns those files.\n */\n platformConfig?: boolean\n /**\n * Ranges resolved by the caller. The fullstack generator passes one map for\n * the whole workspace: resolving per package lets a failed lookup fall back\n * on one side and succeed on the other, which is how server/ and web/ end\n * up on different vite or TypeScript majors.\n */\n versions?: Record<string, string>\n}\n\n/** Scaffold a new KickJS project */\n/**\n * Scaffold a project. Returns the install-script answers it needs, so a\n * caller that installs from elsewhere (the fullstack workspace root) can\n * record them there.\n */\nexport async function initProject(\n options: InitProjectOptions,\n): Promise<{ builds: Record<string, boolean> }> {\n const {\n name,\n directory,\n packageManager = 'pnpm',\n template = 'rest',\n defaultRepo = 'inmemory',\n packages = [],\n schemaLib = 'zod',\n runtime = 'express',\n } = options\n const dir = directory\n\n const log = (msg: string) => console.log(` ${msg}`)\n\n console.log(`\\n Creating KickJS project: ${name}\\n`)\n\n // Resolve published version of every sibling kickjs package in\n // parallel. Per-package independent versioning means\n // `@forinda/kickjs@5.5.0` may pair with `@forinda/kickjs-cli@5.4.2`\n // and `@forinda/kickjs-swagger@5.3.1`; pinning every dep to the\n // CLI's own version under-installs adopters whenever a sibling\n // bumps independently. `npm view` fallback keeps the scaffold\n // working offline.\n if (!options.versions) log('Resolving package versions...')\n const versions = options.versions ?? (await resolveSiblingVersions())\n\n // A 'latest' range means the registry query failed for that package. The\n // install still works, but the pin is looser than intended and the user\n // should know why their package.json does not read like the docs.\n const unresolved = Object.keys(versions).filter((name) => versions[name] === 'latest')\n if (unresolved.length > 0) {\n log(`WARNING: could not reach npm for ${unresolved.join(', ')} — pinned to 'latest'`)\n }\n\n // The pluggable-runtimes work (Fastify / h3 engine subpaths, the\n // `kick/runtime` typegen, `kick add upload`, `kick doctor` runtime checks)\n // ships only on the `alpha` channel until it lands in a stable release. So a\n // non-Express scaffold needs the alpha of every package that carries runtime\n // behavior, not just `@forinda/kickjs`:\n // - `@forinda/kickjs` — the `./fastify` / `./h3` export subpaths the\n // app imports (stable lacks them → Vite boot\n // error `\"./h3\" is not exported`).\n // - `@forinda/kickjs-cli` — `--runtime`, `kick add upload`, `kick doctor`,\n // the `kick/runtime` typegen plugin.\n // - `@forinda/kickjs-vite` — the dev loop co-versioned with the above.\n // Gated on whether `@forinda/kickjs@latest` already exports the chosen engine\n // subpath: once that's true the runtimes are stable and we keep `latest` for\n // everything (self-retiring — no code change needed at graduation). Each pin\n // is guarded so it never DOWNGRADES (an alpha can be older than latest — e.g.\n // a package whose stable moved on past an old prerelease). Express is exempt.\n if (runtime !== 'express') {\n const subpath = `./${runtime}` // './fastify' | './h3'\n if (tagExportsSubpath('@forinda/kickjs', 'latest', subpath)) {\n log(`Using @forinda/kickjs@latest (stable ships the ${runtime} runtime)`)\n } else {\n const RUNTIME_PKGS = ['@forinda/kickjs', '@forinda/kickjs-cli', '@forinda/kickjs-vite']\n const pinned: string[] = []\n let kickjsPinned = false\n for (const pkg of RUNTIME_PKGS) {\n const alpha = resolveVersionAtTag(pkg, 'alpha')\n // Only switch when the alpha is newer-or-equal to the stable we'd\n // otherwise install — never downgrade onto a stale prerelease. Use a\n // `^` range (not an exact pin) so the project picks up newer alphas and\n // auto-graduates to the stable release once it ships.\n if (alpha && baseVersionGte(alpha, stripRange(versions[pkg]))) {\n versions[pkg] = `^${alpha}`\n pinned.push(`${pkg}@^${alpha}`)\n if (pkg === '@forinda/kickjs') kickjsPinned = true\n }\n }\n if (kickjsPinned) {\n log(`Using the alpha channel for the ${runtime} runtime: ${pinned.join(', ')}`)\n } else {\n log(\n `WARNING: could not resolve @forinda/kickjs@alpha — the ${runtime} runtime subpath ` +\n `may be missing. After install, run: ${packageManager} add @forinda/kickjs@alpha`,\n )\n }\n }\n }\n\n // ── Layers — templates/<layer>/ ──────────────────────────────────\n // Everything that follows from the options: the entry file (runtime,\n // adapters), the env schema, .env additions and the package lists.\n const unknown = packages.filter((pkg) => !existsSync(join(TEMPLATES_DIR, `feature-${pkg}`)))\n if (unknown.length > 0) {\n log(\n `WARNING: skipping unknown package(s): ${unknown.join(', ')} — add them later with kick add`,\n )\n }\n const project = renderLayers(\n [\n ...scaffoldLayers({ template, runtime, schemaLib, packages }),\n // netlify.toml / vercel.json — inert until the project is connected to\n // a platform. A workspace member leaves them to the root.\n ...(options.platformConfig !== false ? ['host-config'] : []),\n ...(options.extraLayers ?? []),\n ],\n {\n vars: { name, version: cliPkg.version },\n extra: [\n // `inmemory` is the only built-in; any other name is a `{ name }` custom repo.\n {\n slot: 'repo',\n code:\n defaultRepo === 'inmemory'\n ? `repo: 'inmemory'`\n : `repo: { name: '${defaultRepo.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}' }`,\n },\n ...(options.spaClientDir ? [spaIntegration(options.spaClientDir)] : []),\n ],\n },\n )\n\n // ── package.json ─────────────────────────────────────────────────────\n await writeFileSafe(join(dir, 'package.json'), generatePackageJson(name, versions, project))\n\n // tsconfig, vite/vitest/kick config, formatter/editor/git config, .env\n // files (`.env.test` is read INSTEAD of `.env` under a test run, so\n // shipping it isolates a new project's tests), README, the hello module,\n // `src/config/index.ts` (the typed env schema `kick typegen` reads) and\n // `src/index.ts`.\n const files = fillVars(project.files, {\n name,\n template,\n runtime,\n packageManager,\n templateLabel: template === 'rest' ? 'REST API' : 'Minimal',\n packages: [...project.dependencies, ...project.devDependencies]\n .filter((pkg) => pkg.startsWith('@forinda/'))\n .map((pkg) => `- \\`${pkg}\\``)\n .join('\\n'),\n })\n for (const [path, contents] of files) {\n await writeFileSafe(join(dir, path), contents)\n }\n\n // ── Agent docs ──────────────────────────────────────────────────────\n // Delegate to `generateAgentDocs()` so `kick new` emits the same\n // `.agents/` subfolder layout as `kick g agents -f`. Otherwise the\n // two paths drifted: kick new was writing the legacy flat layout\n // (root-level AGENTS.md + kickjs-skills.md) while kick g agents\n // emits the per-skill SKILL.md format under .agents/. `force: true`\n // because the project directory is fresh — no overwrite prompts\n // make sense during init.\n const { generateAgentDocs } = await import('./agent-docs')\n await generateAgentDocs({\n outDir: dir,\n name,\n pm: packageManager,\n template,\n only: 'all',\n force: true,\n })\n\n // ── Install-script approvals ─────────────────────────────────────────\n // Before install; see approveInstallScripts.\n const builds = { ...TEMPLATE_BUILDS, ...buildsFor(packages), ...project.builds }\n if (options.approveInstallScripts !== false) {\n approveInstallScripts(packageManager, dir, builds)\n }\n\n // ── Install Dependencies ────────────────────────────────────────────\n // Install BEFORE git init so the lockfile is included in the first commit.\n if (options.installDeps) {\n console.log(`\\n Installing dependencies with ${packageManager}...\\n`)\n try {\n execSync(`${packageManager} install`, { cwd: dir, stdio: 'inherit' })\n console.log('\\n Dependencies installed successfully!')\n } catch {\n console.log(`\\n Warning: ${packageManager} install failed. Run it manually.`)\n }\n }\n\n // ── Initial typegen ────────────────────────────────────────────────\n // Run typegen once so the freshly-scaffolded HelloController's\n // `Ctx<KickRoutes.HelloController['index']>` references resolve in\n // the user's editor immediately. Failures are non-fatal.\n try {\n const { runTypegen } = await import('../typegen')\n await runTypegen({ cwd: dir, allowDuplicates: true, silent: true })\n } catch {\n // First-run typegen errors are non-fatal — `kick dev` will retry.\n }\n\n // ── Git Init ─────────────────────────────────────────────────────────\n // Runs after install + typegen so lockfile and generated types are\n // included in the initial commit.\n if (options.initGit) {\n try {\n execSync('git init', { cwd: dir, stdio: 'pipe' })\n execSync('git branch -M main', { cwd: dir, stdio: 'pipe' })\n execSync('git add -A', { cwd: dir, stdio: 'pipe' })\n execSync('git commit -m \"chore: initial commit from kick new\"', {\n cwd: dir,\n stdio: 'pipe',\n })\n log('Git repository initialized')\n } catch {\n log('Warning: git init failed (git may not be installed)')\n }\n }\n\n console.log('\\n Project scaffolded successfully!')\n console.log()\n\n const needsCd = dir !== process.cwd()\n log('Next steps:')\n if (needsCd) log(` cd ${name}`)\n if (!options.installDeps) log(` ${packageManager} install`)\n\n const genHint: Record<string, string> = {\n rest: 'kick g module user',\n minimal: '# add your routes to src/index.ts',\n }\n log(` ${genHint[template] ?? genHint.rest}`)\n log(' kick dev')\n log('')\n log('Commands:')\n log(' kick dev Start dev server with Vite HMR')\n log(' kick build Production build via Vite')\n log(' kick start Run production build')\n log('')\n log('Generators:')\n log(' kick g module <name> REST module (controller, service, DTOs, repository)')\n log(' kick g scaffold <n> <f..> CRUD module from field definitions')\n log(' kick g controller <name> Standalone controller')\n log(' kick g service <name> @Service() class')\n log(' kick g middleware <name> Global connect-style middleware')\n log(' kick g guard <name> Route guard (auth, roles, etc.)')\n log(' kick g adapter <name> AppAdapter with lifecycle hooks')\n log(' kick g dto <name> DTO schema (Zod / Valibot / Yup)')\n log(' kick g config Generate kick.config.ts')\n log('')\n log('Add packages:')\n log(' kick add <pkg> Install a KickJS package + peers')\n log(' kick add --list Show all available packages')\n log('')\n log(`Available: ${AVAILABLE_ADD_PACKAGES}`)\n log('')\n\n return { builds }\n}\n\n/**\n * `SpaAdapter` for the fullstack server, which serves `web/`'s build from the\n * API's origin in production. The path is text the caller chose, so it goes\n * in through JSON.stringify — a quote, backslash or newline in it would\n * otherwise break the emitted module or change the path it resolves.\n */\nexport function spaIntegration(clientDir: string): Integration {\n return {\n import: { from: '@forinda/kickjs/spa', names: ['SpaAdapter'] },\n slot: 'adapter',\n code:\n '// Serves the built frontend from this origin in production.\\n' +\n '// Inert until the client build exists, so `kick dev` (where Vite\\n' +\n '// serves the client and proxies /api here) is unaffected.\\n' +\n `SpaAdapter({ clientDir: ${JSON.stringify(clientDir)} })`,\n }\n}\n\n/**\n * The layers a `kick new` selection renders, in order. Unknown package\n * names are left out (the caller warns about them).\n */\nexport function scaffoldLayers(selection: {\n template: 'rest' | 'minimal'\n runtime: 'express' | 'fastify' | 'h3'\n schemaLib: SchemaLib\n packages: readonly string[]\n}): string[] {\n return [\n 'base',\n `template-${selection.template}`,\n `runtime-${selection.runtime}`,\n `schema-${selection.schemaLib}`,\n ...selection.packages\n .filter((pkg) => existsSync(join(TEMPLATES_DIR, `feature-${pkg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A,YAAY,EAAU,WACtB,WAAW,EAAU,UACrB,UAAU,EAAU,YACpB,GAAG,EAAU,SACV,OAAQ,GAAQ,EAAW,EAAK,EAAe,WAAW,GAAK,CAAC,CAAC,CAAC,CAClE,IAAK,GAAQ,WAAW,GAAK,CAClC,CACF"}
|
|
1
|
+
{"version":3,"file":"project-B3xCFdaS.mjs","names":["indentBlock"],"sources":["../src/scaffold/overlay.ts","../src/utils/shell.ts","../src/generators/templates/project-config.ts","../src/scaffold/wire.ts","../src/commands/add-wire.ts","../src/commands/add.ts","../src/generators/project.ts"],"sourcesContent":["/**\n * Overlay scaffolding — project files as real directories instead of TS\n * functions that return strings.\n *\n * A layer is a directory under `packages/cli/templates/`:\n *\n * - `files/` mirrors the project. Layers render in order; a later layer's\n * file replaces an earlier one at the same path, and a `<name>.append` file\n * is added to the end of `<name>` instead.\n * - `feature.json` (optional) lists the packages the layer needs and its\n * **integrations**: entries for the slots that shared files expose.\n *\n * File names: a `_dot_` path segment prefix becomes `.` (`_dot_gitignore` →\n * `.gitignore`), because npm publish drops or rewrites real dotfiles.\n *\n * Slots: a shared file marks where layers plug in with a comment line.\n * `// @kick:imports` becomes the merged import statements of every rendered\n * integration; `// @kick:<slot>` becomes that slot's entries, one `code,` per\n * line at the marker's indentation. An empty slot inside its own `key: [` …\n * `],` block drops the whole block, so an app with no adapters has no\n * `adapters: []`. This is what keeps layers out of each other's way: swagger\n * never edits the entry file, it declares an `adapter` entry.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, join, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst here = dirname(fileURLToPath(import.meta.url))\n\n/**\n * `packages/cli/templates` — one level above the bundle (`dist/*.mjs`), two\n * above this source file (`src/scaffold/overlay.ts`), so tests can import it\n * from source.\n */\nexport const TEMPLATES_DIR = [\n join(here, '..', 'templates'),\n join(here, '..', '..', 'templates'),\n].find((dir) => existsSync(join(dir, 'base')))!\n\n/** An import an integration needs. Merged per module across integrations. */\nexport interface ImportSpec {\n from: string\n names?: string[]\n default?: string\n}\n\n/**\n * What a layer contributes to shared files. With a `slot`, `code` is\n * rendered there and `import` only when that slot exists in the file — so an\n * `express.json()` middleware doesn't leave an unused `express` import in a\n * template without a middleware list. Without a `slot`, `import` is always\n * rendered.\n */\nexport interface Integration {\n import?: ImportSpec\n slot?: string\n code?: string\n}\n\n/** `feature.json`. Package versions come from the scaffold's resolved version map. */\nexport interface FeatureManifest {\n dependencies?: string[]\n devDependencies?: string[]\n /** Install-script answers for packages this layer pulls in (see `approveInstallScripts`). */\n builds?: Record<string, boolean>\n integrations?: Integration[]\n}\n\nexport interface RenderedProject {\n files: Map<string, string>\n dependencies: string[]\n devDependencies: string[]\n builds: Record<string, boolean>\n /** Every layer's integrations plus `extra`, in layer order — `kick add` wires these. */\n integrations: Integration[]\n}\n\n/** The project path a template file lands at: `_dot_` segment prefixes become `.`. */\nexport function outputPath(templatePath: string): string {\n return templatePath\n .split('/')\n .map((segment) => (segment.startsWith('_dot_') ? `.${segment.slice(5)}` : segment))\n .join('/')\n}\n\n/**\n * Render layers into project files plus the packages they need. Pure apart\n * from reading the template directories; the caller writes the files.\n *\n * `extra` adds integrations computed at scaffold time (a value the user\n * typed can't live in a static layer). `vars` fills `{{name}}` in\n * integration code.\n */\nexport function renderLayers(\n layers: readonly string[],\n options: {\n templatesDir?: string\n extra?: Integration[]\n vars?: Record<string, string>\n } = {},\n): RenderedProject {\n const templatesDir = options.templatesDir ?? TEMPLATES_DIR\n const files = new Map<string, string>()\n const dependencies: string[] = []\n const devDependencies: string[] = []\n const builds: Record<string, boolean> = {}\n const integrations: Integration[] = []\n\n for (const layer of layers) {\n const dir = join(templatesDir, layer)\n if (!existsSync(dir)) throw new Error(`Unknown scaffold layer \"${layer}\" (${dir})`)\n\n const manifestPath = join(dir, 'feature.json')\n if (existsSync(manifestPath)) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as FeatureManifest\n dependencies.push(...(manifest.dependencies ?? []))\n devDependencies.push(...(manifest.devDependencies ?? []))\n Object.assign(builds, manifest.builds)\n integrations.push(...(manifest.integrations ?? []))\n }\n\n const root = join(dir, 'files')\n if (!existsSync(root)) continue\n // String entries, not Dirents: `Dirent.parentPath` needs Node 20.12.\n for (const rel of readdirSync(root, { recursive: true, encoding: 'utf-8' }).toSorted()) {\n const abs = join(root, rel)\n if (!statSync(abs).isFile()) continue\n const contents = readFileSync(abs, 'utf-8')\n const path = outputPath(rel.split(sep).join('/'))\n if (path.endsWith('.append')) {\n const target = path.slice(0, -'.append'.length)\n files.set(target, (files.get(target) ?? '') + contents)\n } else {\n files.set(path, contents)\n }\n }\n }\n\n integrations.push(...(options.extra ?? []))\n const vars = options.vars ?? {}\n const fill = (text: string) => text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key) => vars[key] ?? all)\n for (const [path, contents] of files) {\n if (contents.includes('// @kick:')) files.set(path, renderSlots(contents, integrations, fill))\n }\n\n return {\n files,\n dependencies: [...new Set(dependencies)],\n devDependencies: [...new Set(devDependencies)],\n builds,\n integrations,\n }\n}\n\n/**\n * Fill `{{name}}` placeholders in rendered files. Separate from rendering so\n * a value can depend on the result (README lists the packages the layers\n * chose). Unknown names are left as written.\n */\nexport function fillVars(\n files: ReadonlyMap<string, string>,\n vars: Record<string, string>,\n): Map<string, string> {\n const fill = (text: string) =>\n text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key: string) => (key in vars ? vars[key]! : all))\n return new Map([...files].map(([path, contents]) => [path, fill(contents)]))\n}\n\nconst MARKER = /^([ \\t]*)\\/\\/ @kick:([\\w-]+)[ \\t]*$/\n\n/** Fill one file's slot markers. */\nexport function renderSlots(\n source: string,\n integrations: readonly Integration[],\n fill: (text: string) => string = (text) => text,\n): string {\n const lines = source.split('\\n')\n const slots = new Set(lines.map((line) => MARKER.exec(line)?.[2]).filter(Boolean))\n const active = integrations.filter((i) => !i.slot || slots.has(i.slot))\n\n const out: string[] = []\n for (let i = 0; i < lines.length; i++) {\n const match = MARKER.exec(lines[i]!)\n if (!match) {\n out.push(lines[i]!)\n continue\n }\n const [, indent, slot] = match as unknown as [string, string, string]\n const rendered =\n slot === 'imports'\n ? renderImports(active.flatMap((entry) => (entry.import ? [entry.import] : [])))\n : active\n .filter((entry) => entry.slot === slot && entry.code)\n .map((entry) => indentBlock(`${fill(entry.code!)},`, indent))\n if (rendered.length > 0) {\n out.push(...rendered)\n continue\n }\n // Empty: drop an enclosing `key: [` … `],` block that holds only this marker.\n const prev = out.at(-1)\n if (prev?.trimEnd().endsWith('[') && lines[i + 1]?.trim().startsWith(']')) {\n out.pop()\n i++\n }\n }\n return out.join('\\n')\n}\n\nfunction indentBlock(code: string, indent: string): string {\n return code\n .split('\\n')\n .map((line) => (line ? indent + line : line))\n .join('\\n')\n}\n\n/** One statement per module, names merged in first-seen order; wrapped past 100 columns. */\nexport function renderImports(specs: readonly ImportSpec[]): string[] {\n const byModule = new Map<string, { names: string[]; default?: string }>()\n for (const spec of specs) {\n const entry = byModule.get(spec.from) ?? { names: [] }\n entry.default ??= spec.default\n for (const name of spec.names ?? []) if (!entry.names.includes(name)) entry.names.push(name)\n byModule.set(spec.from, entry)\n }\n return [...byModule].map(([from, { names, default: def }]) => {\n const parts = [def, names.length ? `{ ${names.join(', ')} }` : undefined].filter(Boolean)\n const line = `import ${parts.join(', ')} from '${from}'`\n if (line.length <= 100 || names.length === 0) return line\n const head = def ? `${def}, ` : ''\n return `import ${head}{\\n${names.map((n) => ` ${n},`).join('\\n')}\\n} from '${from}'`\n })\n}\n","import { execFile, execFileSync, execSync, spawnSync } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Characters an argument may not contain when it has to travel through\n * `cmd.exe`.\n *\n * The first group is shell syntax — `cmd.exe` would interpret these rather\n * than pass them through. The trailing `\\\\` is different in kind: a backslash\n * is not shell syntax, but Windows command-line quoting mangles it. Node's\n * argv encoder doubles trailing backslashes, and a backslash immediately\n * before a closing quote escapes that quote, so a single argument silently\n * splits in two:\n *\n * ['C:\\\\some path\\\\'] → cmd receives ['\"C:\\\\some', 'path\\\\\"']\n * ['no-space\\\\'] → cmd receives ['no-space\\\\\\\\']\n *\n * Correct escaping is possible but fiddly, and no caller in this CLI needs it\n * — arguments here are package names, dist-tags, subcommands and flags, and\n * working directories travel via the `cwd` option rather than as arguments.\n * So a backslash is rejected outright: a loud `null` beats a silently\n * corrupted argument, which is the exact failure mode this module exists to\n * eliminate.\n */\nconst CMD_UNSAFE = /[&|<>^\"'`(){}[\\];!%\\r\\n\\\\]/\n\n/**\n * Build the `[file, args]` pair to hand to `execFileSync`, routing through\n * `cmd.exe` on Windows so `.cmd` shims are launchable.\n *\n * On Windows, `npm` / `pnpm` / `yarn` / `bun` are `.cmd` batch shims, not\n * `.exe`s, and `execFileSync` cannot launch either spelling:\n *\n * - `execFileSync('npm', …)` → ENOENT (there is no `npm.exe` on PATH)\n * - `execFileSync('npm.cmd', …)` → EINVAL (Node >= 18.20 / 20.12 refuses to\n * spawn batch files without a\n * shell — CVE-2024-27980)\n *\n * Both failures are silent wherever the caller swallows the error, so the\n * command looks like it \"returned nothing\" rather than \"never ran\".\n *\n * `/d` skips AutoRun registry commands, `/s` makes cmd treat everything after\n * `/c` as one verbatim string (it strips only the outer quote pair Node adds).\n * Returns `null` when an argument is unsafe to pass through — refusing to run\n * beats running something the shell rewrote.\n *\n * `platform` is injectable so both branches are unit-testable from any host\n * OS; production callers use the default. It is read per call rather than\n * captured at import time for the same reason.\n */\nexport function shellSafeInvocation(\n file: string,\n args: string[],\n platform: NodeJS.Platform = process.platform,\n): [string, string[]] | null {\n if (platform !== 'win32') return [file, args]\n if (CMD_UNSAFE.test(file) || args.some((a) => CMD_UNSAFE.test(a))) return null\n const command = [file, ...args].map((a) => (a.includes(' ') ? `\"${a}\"` : a)).join(' ')\n return [process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', command]]\n}\n\n/**\n * Run a command and capture its trimmed stdout, cross-platform.\n *\n * Returns `null` if the command is missing, exits non-zero, times out, or\n * carries arguments unsafe to pass through `cmd.exe`. Callers treat `null` as\n * \"unknown\" and fall back — the point of this helper is that a Windows `.cmd`\n * shim no longer masquerades as a failed command.\n */\nexport function captureCommand(\n file: string,\n args: string[],\n opts: { timeout?: number; cwd?: string } = {},\n): string | null {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) return null\n try {\n const out = execFileSync(invocation[0], invocation[1], {\n encoding: 'utf-8',\n timeout: opts.timeout ?? 5000,\n cwd: opts.cwd,\n stdio: ['ignore', 'pipe', 'ignore'],\n windowsHide: true,\n })\n const trimmed = out.toString().trim()\n return trimmed || null\n } catch {\n return null\n }\n}\n\n/**\n * Run a command with inherited stdio, cross-platform. Throws on failure so\n * callers can decide whether a missing package manager is fatal.\n */\nexport function runCommand(file: string, args: string[], opts: { cwd?: string } = {}): void {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) throw new Error(`Refusing to run '${file}': unsafe arguments`)\n execFileSync(invocation[0], invocation[1], {\n cwd: opts.cwd,\n stdio: 'inherit',\n windowsHide: true,\n })\n}\n\n/**\n * Run a shell command synchronously, printing output.\n *\n * On Windows, `execSync` spawns via `cmd.exe` by default, which means\n * POSIX-style inline env prefixes like `FOO=bar node app.js` do NOT work.\n * Callers that need environment variables should pass them in the `env`\n * option instead of prepending them to the command string — see\n * `runNodeWithEnv` for the cross-platform helper that avoids a shell\n * entirely.\n */\nexport function runShellCommand(command: string, cwd?: string, env?: NodeJS.ProcessEnv): void {\n execSync(command, {\n cwd,\n stdio: 'inherit',\n env: env ? { ...process.env, ...env } : process.env,\n })\n}\n\n/**\n * Cross-platform way to launch a Node.js process with a set of\n * environment variables. Uses `spawnSync` with an argument array so no\n * shell is involved — the `VAR=value node ...` POSIX prefix syntax that\n * `runShellCommand` relied on breaks on cmd.exe and PowerShell.\n */\nexport function runNodeWithEnv(entry: string, env: NodeJS.ProcessEnv, cwd?: string): void {\n const result = spawnSync(process.execPath, [entry], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...env },\n })\n if (result.status !== 0) {\n process.exit(result.status ?? 1)\n }\n}\n\n/**\n * Async twin of `captureCommand` — same Windows `.cmd` routing, same\n * `null`-on-any-failure contract, but genuinely concurrent.\n *\n * `captureCommand` is `execFileSync`, so `Promise.all` over it runs the\n * commands one after another. Callers that fan out over a list of network\n * queries (`npm view` per package) need real concurrency, otherwise the\n * per-call timeout multiplies by the list length.\n */\nexport async function captureCommandAsync(\n file: string,\n args: string[],\n opts: { timeout?: number; cwd?: string } = {},\n): Promise<string | null> {\n const invocation = shellSafeInvocation(file, args)\n if (!invocation) return null\n try {\n const { stdout } = await execFileAsync(invocation[0], invocation[1], {\n encoding: 'utf-8',\n timeout: opts.timeout ?? 5000,\n cwd: opts.cwd,\n windowsHide: true,\n })\n return stdout.toString().trim() || null\n } catch {\n return null\n }\n}\n","// `SchemaLib` is defined next to `resolveSchemaLib` in ../../config, so the\n// scaffold that installs the library and the generators that import from it\n// read the same list. Re-exported here for existing importers.\nexport type { SchemaLib } from '../../config'\n\n/**\n * Map of package name → semver range string (`^x.y.z`). Resolved\n * from `npm view <name> version` upstream so per-package independent\n * versioning is honoured at scaffold time. Every package a scaffold layer\n * lists must appear here; missing keys throw during package.json generation\n * (loud failure beats silently shipping `^undefined`).\n */\nexport type SiblingVersions = Record<string, string>\n\nfunction take(versions: SiblingVersions, name: string): string {\n const v = versions[name]\n if (!v) {\n throw new Error(\n `generatePackageJson: missing resolved version for ${name}. ` +\n `Add it to SIBLING_PACKAGES or THIRD_PARTY_PACKAGES in generators/project.ts.`,\n )\n }\n return v\n}\n\n/** Name → resolved range, sorted by name (the order npm and pnpm write). */\nfunction pinned(names: readonly string[], versions: SiblingVersions): Record<string, string> {\n return Object.fromEntries(names.toSorted().map((name) => [name, take(versions, name)]))\n}\n\n/**\n * Generate package.json. Which packages it lists comes from the scaffold\n * layers (`templates/<layer>/feature.json`); the ranges come from `versions`.\n */\nexport function generatePackageJson(\n name: string,\n versions: SiblingVersions,\n packages: { dependencies: readonly string[]; devDependencies: readonly string[] },\n): string {\n return JSON.stringify(\n {\n name,\n // Project starts at 0.0.0 — adopters bump as they ship. Tying\n // the project version to the CLI version (the previous\n // behaviour) made every scaffolded app `5.4.0` on day one,\n // which broke npm publishing for adopters trying their first\n // release.\n version: '0.0.0',\n type: 'module',\n scripts: {\n // `kick dev` (not bare `vite`): it boots Vite itself AND owns the\n // typegen-on-save watcher. Plain `vite` gives working HMR but\n // frozen `.kickjs/types` — new routes silently lose their typing\n // until a manual `kick typegen`.\n // Four scripts, not ten. Everything dropped from here is still one\n // command away — `kick dev:debug`, `kick typegen`, `pnpm exec vitest`,\n // `pnpm exec tsc --noEmit` — and a scaffold that opens with a wall of\n // aliases teaches less than one that shows the binary.\n //\n // `lint: 'eslint src/'` used to be here without eslint ever being a\n // dependency, so `lint` failed with \"command not found\" in every\n // generated project.\n dev: 'kick dev',\n build: 'kick build',\n start: 'kick start',\n test: 'vitest run',\n // Serverless targets — see guide/serverless.md. Each bundles\n // src/serverless.ts and writes the platform's build output.\n 'build:netlify': 'kick build && kick build:netlify',\n 'build:vercel': 'kick build && kick build:vercel',\n },\n dependencies: pinned(packages.dependencies, versions),\n devDependencies: pinned(packages.devDependencies, versions),\n },\n null,\n 2,\n )\n}\n\n/**\n * Answer pnpm's build-script approvals for `builds` in pnpm-workspace.yaml text,\n * in both formats pnpm has used, so any pnpm 10+ reads them:\n *\n * - `allowBuilds` (pnpm 10.26+; pnpm 11 reads only this)\n * - `onlyBuiltDependencies` / `ignoredBuiltDependencies` (pnpm before 10.26)\n *\n * Each version ignores the format it doesn't read. An existing answer wins: an\n * `allowBuilds` key set to true/false, or a name already in either list, is left\n * alone. A missing key or pnpm's `set this to true or false` placeholder is filled in.\n */\nexport function setAllowBuilds(yaml: string, builds: Record<string, boolean>): string {\n const entries = Object.entries(builds)\n if (entries.length === 0) return yaml\n const lines = yaml === '' ? [] : yaml.replace(/\\n$/, '').split('\\n')\n const unquote = (text: string) => text.trim().replace(/^['\"]|['\"]$/g, '')\n const quote = (name: string) => (/^[\\w-]+$/.test(name) ? name : `'${name}'`)\n\n /** Line range of a top-level block's indented entries; appended when missing and `create`. */\n const block = (key: string, create: boolean): { start: number; end: number } | undefined => {\n let start = lines.findIndex((line) => line.replace(/\\s+$/, '') === `${key}:`)\n if (start === -1) {\n if (!create) return undefined\n if (lines.length > 0 && lines[lines.length - 1] !== '') lines.push('')\n lines.push(`${key}:`)\n start = lines.length - 1\n }\n // The block runs to the next unindented line; blank lines inside it don't end it.\n let end = start + 1\n for (let i = start + 1; i < lines.length && /^(\\s|$)/.test(lines[i]); i++) {\n if (lines[i].trim() !== '') end = i + 1\n }\n return { start, end }\n }\n\n const answers: Array<[string, boolean]> = []\n for (const [name, allow] of entries) {\n const { start, end } = block('allowBuilds', true)!\n const index = lines\n .slice(start + 1, end)\n .findIndex((line) => unquote(line.split(':')[0]) === name)\n const answered =\n index === -1 ? undefined : /:\\s*(true|false)\\s*$/.exec(lines[start + 1 + index])\n if (answered) {\n answers.push([name, answered[1] === 'true'])\n continue\n }\n const entry = ` ${quote(name)}: ${allow}`\n if (index === -1) lines.splice(end, 0, entry)\n else lines[start + 1 + index] = entry\n answers.push([name, allow])\n }\n\n const lists = ['onlyBuiltDependencies', 'ignoredBuiltDependencies']\n for (const [name, allow] of answers) {\n const listed = lists.some((key) => {\n const range = block(key, false)\n return (\n range !== undefined &&\n lines\n .slice(range.start + 1, range.end)\n .some((line) => unquote(line.replace(/^\\s*-/, '')) === name)\n )\n })\n if (listed) continue\n const { end } = block(allow ? lists[0] : lists[1], true)!\n lines.splice(end, 0, ` - ${quote(name)}`)\n }\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * Apply a layer's integrations to an EXISTING entry file — what `kick add`\n * does after installing a package that has a scaffold layer.\n *\n * `kick new` renders slots into a template it owns. An existing\n * `src/index.ts` is the user's file, so this never re-renders it: it finds\n * the `bootstrap({ ... })` call with oxc and splices text in — an entry at\n * the end of `adapters: [...]` (the array is created when missing), and the\n * import merged into an existing one from the same module or added after the\n * last import. Everything else in the file is left byte-for-byte alone.\n *\n * Idempotent: an entry whose call (`SwaggerAdapter(`) is already in the\n * array is skipped. When the file doesn't have the expected shape (no\n * `bootstrap({ ... })`, or `adapters` isn't an array literal), the entry is\n * returned as `manual` for the caller to print instead of guessing.\n */\nimport { parseSync } from 'oxc-parser'\n\nimport type { ImportSpec, Integration } from './overlay'\n\n/** Which `bootstrap()` option each slot appends to. */\nconst SLOT_PROPERTY: Record<string, string> = {\n adapter: 'adapters',\n middleware: 'middlewares',\n}\n\nexport interface WireResult {\n source: string\n /** Entries added, by the call they make (`SwaggerAdapter`). */\n added: string[]\n /** Entries already present. */\n present: string[]\n /** Entries that couldn't be placed — print them for the user. */\n manual: Integration[]\n}\n\ntype Node = { type: string; start: number; end: number; [key: string]: any }\n\nexport function wireIntegrations(\n source: string,\n integrations: readonly Integration[],\n fill: (text: string) => string = (text) => text,\n file = 'src/index.ts',\n): WireResult {\n const result: WireResult = { source, added: [], present: [], manual: [] }\n for (const integration of integrations) {\n if (!integration.slot || !integration.code) continue\n const property = SLOT_PROPERTY[integration.slot]\n const code = fill(integration.code)\n const call = callName(code)\n const program = parseSync(file, result.source).program as unknown as Node\n const options = property ? findBootstrapOptions(program) : undefined\n if (!options) {\n result.manual.push({ ...integration, code })\n continue\n }\n\n const prop = options.properties.find(\n (p: Node) => p.type === 'Property' && (p.key?.name ?? p.key?.value) === property,\n ) as Node | undefined\n if (prop && prop.value.type !== 'ArrayExpression') {\n result.manual.push({ ...integration, code })\n continue\n }\n // Under the name this file calls it: `import { SwaggerAdapter as SA }` → `SA(`.\n const local =\n call && integration.import ? localName(program, integration.import.from, call) : call\n if (\n prop &&\n local &&\n result.source.slice(prop.value.start, prop.value.end).includes(`${local}(`)\n ) {\n result.present.push(call ?? firstLine(code))\n continue\n }\n\n result.source = prop\n ? appendToArray(result.source, prop.value, code)\n : addProperty(result.source, options, property!, code)\n if (integration.import) result.source = addImport(result.source, integration.import, file)\n result.added.push(call ?? firstLine(code))\n }\n return result\n}\n\n/** The object literal passed to the first `bootstrap(...)` call. */\nfunction findBootstrapOptions(program: Node): Node | undefined {\n let found: Node | undefined\n const visit = (node: unknown): void => {\n if (found || !node || typeof node !== 'object') return\n if (Array.isArray(node)) return node.forEach(visit)\n const n = node as Node\n if (\n n.type === 'CallExpression' &&\n n.callee?.type === 'Identifier' &&\n n.callee.name === 'bootstrap' &&\n n.arguments?.[0]?.type === 'ObjectExpression'\n ) {\n found = n.arguments[0]\n return\n }\n for (const key in n) visit(n[key])\n }\n visit(program)\n return found\n}\n\n/** The local binding of `imported` from `from`, when this file imports it (possibly renamed). */\nfunction localName(program: Node, from: string, imported: string): string {\n for (const node of program.body as Node[]) {\n if (node.type !== 'ImportDeclaration' || node.source.value !== from) continue\n for (const specifier of node.specifiers as Node[]) {\n const name = specifier.imported?.name ?? specifier.imported?.value\n if (specifier.type === 'ImportSpecifier' && name === imported) return specifier.local.name\n }\n }\n return imported\n}\n\n/** `SwaggerAdapter` for `// comment\\nSwaggerAdapter({ ... })`. */\nfunction callName(code: string): string | undefined {\n const line = code.split('\\n').find((l) => l.trim() && !l.trim().startsWith('//'))\n return /^\\s*([A-Za-z_$][\\w$.]*)\\s*\\(/.exec(line ?? '')?.[1]\n}\n\nconst firstLine = (code: string) =>\n code\n .split('\\n')\n .find((l) => l.trim() && !l.trim().startsWith('//'))\n ?.trim() ?? code\n\nconst lineIndent = (source: string, offset: number) =>\n /^[ \\t]*/.exec(source.slice(source.lastIndexOf('\\n', offset - 1) + 1))![0]\n\nconst indentBlock = (code: string, indent: string) =>\n code\n .split('\\n')\n .map((line) => (line ? indent + line : line))\n .join('\\n')\n\nfunction appendToArray(source: string, array: Node, code: string): string {\n const elements = (array.elements as Array<Node | null>).filter(Boolean) as Node[]\n const arrayIndent = lineIndent(source, array.start)\n if (elements.length === 0) {\n const inner = indentBlock(`${code},`, `${arrayIndent} `)\n return `${source.slice(0, array.start)}[\\n${inner}\\n${arrayIndent}]${source.slice(array.end)}`\n }\n const last = elements.at(-1)!\n const indent = lineIndent(source, last.start)\n // After the last element's trailing comma when it has one.\n const after = source.slice(last.end, array.end - 1)\n const comma = after.match(/^\\s*,/)\n const at = comma ? last.end + comma[0].length : last.end\n const entry = `\\n${indentBlock(`${code},`, indent)}`\n return comma\n ? source.slice(0, at) + entry + source.slice(at)\n : `${source.slice(0, at)},${entry.replace(/,$/, '')}${source.slice(at)}`\n}\n\nfunction addProperty(source: string, object: Node, property: string, code: string): string {\n const props = object.properties as Node[]\n const last = props.at(-1)\n const indent = last ? lineIndent(source, last.start) : `${lineIndent(source, object.start)} `\n const block = `${indent}${property}: [\\n${indentBlock(`${code},`, `${indent} `)}\\n${indent}],`\n if (!last) {\n return `${source.slice(0, object.start)}{\\n${block}\\n${lineIndent(source, object.start)}}${source.slice(object.end)}`\n }\n const after = source.slice(last.end, object.end - 1)\n const comma = after.match(/^\\s*,/)\n const at = comma ? last.end + comma[0].length : last.end\n // A one-line `bootstrap({ modules })` becomes multi-line; the project's\n // formatter tidies the rest.\n return `${source.slice(0, at)}${comma ? '' : ','}\\n${block}${source.slice(at)}`\n}\n\n/** Add `spec`'s names to an import from the same module, or a new import after the last one. */\nexport function addImport(source: string, spec: ImportSpec, file = 'src/index.ts'): string {\n const program = parseSync(file, source).program as unknown as Node\n const imports = (program.body as Node[]).filter((n) => n.type === 'ImportDeclaration')\n const existing = imports.find(\n (n) =>\n n.source.value === spec.from &&\n n.importKind !== 'type' &&\n // A side-effect `import 'x'` has nothing to merge into.\n n.specifiers.length > 0 &&\n !n.specifiers.some((s: Node) => s.type === 'ImportNamespaceSpecifier'),\n )\n const names = spec.names ?? []\n\n if (existing) {\n const have = new Set(existing.specifiers.map((s: Node) => s.local?.name))\n const missing = names.filter((name) => !have.has(name))\n if (missing.length === 0) return source\n const named = existing.specifiers.filter((s: Node) => s.type === 'ImportSpecifier')\n if (named.length > 0) {\n const at = named.at(-1).end\n return `${source.slice(0, at)}, ${missing.join(', ')}${source.slice(at)}`\n }\n // Only a default import: `import d from 'x'` → `import d, { a } from 'x'`.\n const def = existing.specifiers[0]\n return `${source.slice(0, def.end)}, { ${missing.join(', ')} }${source.slice(def.end)}`\n }\n\n const parts = [spec.default, names.length ? `{ ${names.join(', ')} }` : undefined].filter(Boolean)\n const line = `import ${parts.join(', ')} from '${spec.from}'`\n const last = imports.at(-1)\n if (!last) return `${line}\\n${source}`\n return `${source.slice(0, last.end)}\\n${line}${source.slice(last.end)}`\n}\n","/**\n * `kick add` wiring — apply a package's scaffold layer to an existing app:\n * its packages join the install, its `.env` lines are added, and its adapter\n * is spliced into the entry file (see `scaffold/wire.ts`).\n */\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { writeFileSafe } from '../utils/fs'\nimport { renderLayers, type Integration, type RenderedProject } from '../scaffold/overlay'\nimport { wireIntegrations, type WireResult } from '../scaffold/wire'\n\n/**\n * `kick add` names with a layer. `queue` means BullMQ, as it does in\n * `kick new`; `queue:rabbitmq` / `queue:kafka` pick another provider, which\n * the layer doesn't configure, so they install only.\n */\nexport const FEATURE_LAYERS: Record<string, string> = {\n swagger: 'feature-swagger',\n devtools: 'feature-devtools',\n ws: 'feature-ws',\n queue: 'feature-queue',\n 'queue:bullmq': 'feature-queue',\n}\n\n/** The layers `packages` bring, rendered — or undefined when none has one. */\nexport function planWiring(packages: readonly string[]): RenderedProject | undefined {\n const layers = [...new Set(packages.map((name) => FEATURE_LAYERS[name]).filter(Boolean))]\n return layers.length > 0 ? renderLayers(layers as string[]) : undefined\n}\n\n/** The entry file to wire: `--entry`, else `src/index.ts` / `src/main.ts`. */\nexport function findEntry(cwd: string, entry?: string): string | undefined {\n const candidates = entry ? [entry] : ['src/index.ts', 'src/main.ts']\n return candidates.find((file) => existsSync(join(cwd, file)))\n}\n\n/**\n * Files among `files` with uncommitted changes. Outside a git repository\n * (or without git) nothing counts as dirty.\n */\nexport function dirtyFiles(cwd: string, files: readonly string[]): string[] {\n try {\n const out = execFileSync('git', ['status', '--porcelain', '--', ...files], {\n cwd,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n return out\n .split('\\n')\n .filter(Boolean)\n .map((line) => line.slice(3))\n } catch {\n return []\n }\n}\n\n/**\n * Write a layer's non-entry files. A file that exists only gains the lines it\n * doesn't already have (`.env` keeps its values); a missing one is created.\n * Returns the paths changed.\n */\nexport async function applyLayerFiles(\n cwd: string,\n files: ReadonlyMap<string, string>,\n): Promise<string[]> {\n const changed: string[] = []\n for (const [path, contents] of files) {\n const abs = join(cwd, path)\n if (!existsSync(abs)) {\n await writeFileSafe(abs, contents)\n changed.push(path)\n continue\n }\n const current = readFileSync(abs, 'utf-8')\n const have = new Set(current.split('\\n').map((line) => envKey(line) ?? line))\n const missing = contents\n .split('\\n')\n .filter((line) => line.trim() && !have.has(envKey(line) ?? line))\n if (missing.length === 0) continue\n const sep = current === '' || current.endsWith('\\n') ? '' : '\\n'\n await writeFileSafe(abs, `${current}${sep}${missing.join('\\n')}\\n`)\n changed.push(path)\n }\n return changed\n}\n\n/** `REDIS_HOST` for `REDIS_HOST=…`, so an existing value counts as present. */\nconst envKey = (line: string) => /^\\s*([A-Za-z_][\\w]*)\\s*=/.exec(line)?.[1]\n\n/** Splice the integrations into the entry file and write it back when it changed. */\nexport async function wireEntry(\n cwd: string,\n entry: string,\n integrations: readonly Integration[],\n): Promise<WireResult> {\n const abs = join(cwd, entry)\n const source = readFileSync(abs, 'utf-8')\n const result = wireIntegrations(source, integrations, projectVars(cwd), entry)\n if (result.source !== source) await writeFileSafe(abs, result.source)\n return result\n}\n\n/** Fill `{{name}}` / `{{version}}` from the project's package.json. */\nexport function projectVars(cwd: string): (text: string) => string {\n const pkg = readPackageJson(cwd)\n const vars: Record<string, string> = {\n name: String(pkg.name ?? 'app'),\n version: String(pkg.version ?? '0.0.0'),\n }\n return (text) => text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key) => vars[key] ?? all)\n}\n\nfunction readPackageJson(cwd: string): Record<string, unknown> {\n try {\n return JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf-8'))\n } catch {\n return {}\n }\n}\n\n/** What to paste by hand for entries that couldn't be placed. */\nexport function manualSnippet(entries: readonly Integration[]): string {\n const imports = entries\n .flatMap((e) => (e.import ? [e.import] : []))\n .map((spec) => {\n const parts = [spec.default, spec.names?.length ? `{ ${spec.names.join(', ')} }` : undefined]\n return `import ${parts.filter(Boolean).join(', ')} from '${spec.from}'`\n })\n const code = entries.map((e) => `${e.code},`)\n return [...imports, '', '// in bootstrap({ adapters: [ ... ] }):', ...code].join('\\n')\n}\n","import { execSync } from 'node:child_process'\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport type { Command } from 'commander'\nimport { loadKickConfig, PACKAGE_MANAGERS, type PackageManager } from '../config'\nimport { setAllowBuilds } from '../generators/templates/project-config'\nimport {\n applyLayerFiles,\n dirtyFiles,\n findEntry,\n manualSnippet,\n planWiring,\n projectVars,\n wireEntry,\n} from './add-wire'\n\ninterface PackageEntry {\n pkg: string\n peers: string[]\n /**\n * Peers depend on the project's HTTP engine, so they are resolved from\n * {@link resolveAppRuntime} rather than listed statically. Set on the\n * framework package itself: the engine is chosen at `bootstrap({ runtime })`,\n * so a Fastify project must not be handed `express`.\n */\n enginePeers?: boolean\n description: string\n dev?: boolean\n /** Type packages for peers that ship without their own types — installed as dev dependencies. */\n typePeers?: string[]\n /**\n * `true` for packages every project needs (framework + Vite plugin +\n * CLI). `kick new` installs these regardless of options chosen, and\n * future package-removal flows refuse to drop them.\n */\n core?: boolean\n /**\n * Set when the package still installs but should no longer be the\n * default choice. The string is the migration hint shown both in\n * `kick add --list --all` and as a warning when the package is added.\n */\n deprecated?: string\n /**\n * Install-script answers for dependencies this package pulls in.\n * Package managers block or skip unanswered scripts (see approveInstallScripts),\n * so `kick add` and `kick new` record these answers before installing.\n */\n builds?: Record<string, boolean>\n}\n\n/** Registry of KickJS packages and their required peer dependencies */\nexport const PACKAGE_REGISTRY: Record<string, PackageEntry> = {\n // Core (always installed by kick new — required for the framework to run)\n kickjs: {\n pkg: '@forinda/kickjs',\n // Resolved per runtime — see `enginePeers` / ENGINE_PEERS.\n peers: [],\n enginePeers: true,\n description: 'Unified framework: DI, decorators, routing, middleware',\n core: true,\n },\n vite: {\n pkg: '@forinda/kickjs-vite',\n peers: ['vite'],\n description: 'Vite plugin: dev server, HMR, module discovery',\n dev: true,\n core: true,\n },\n cli: {\n pkg: '@forinda/kickjs-cli',\n peers: [],\n description: 'CLI tool and code generators',\n dev: true,\n core: true,\n },\n\n // Schema validation — the validator backing env + DTO + OpenAPI\n // schemas. `@forinda/kickjs-schema` (a core dep) wraps whichever one\n // you pick behind `KickSchema`, but the validator itself is an\n // optional peer of `@forinda/kickjs`, so it must be installed\n // explicitly or the app errors at startup (\"Cannot find module\n // 'zod'\"). `kick new` installs the chosen one; `kick add` lets an\n // existing project add/switch.\n zod: {\n pkg: 'zod',\n peers: [],\n description: 'Zod schema validation (env, DTOs, OpenAPI) — wrap with fromZod()',\n },\n valibot: {\n pkg: 'valibot',\n peers: [],\n description: 'Valibot schema validation — wrap with fromValibot()',\n },\n yup: {\n pkg: 'yup',\n peers: [],\n description: 'Yup schema validation — wrap with fromYup()',\n },\n\n // AI — requires zod (^4) for tool/schema definitions.\n ai: {\n pkg: '@forinda/kickjs-ai',\n peers: ['zod'],\n description: 'AI toolkit — LLM providers, tool definitions from controllers',\n },\n\n // API\n swagger: {\n pkg: '@forinda/kickjs-swagger',\n peers: [],\n description: 'OpenAPI spec + Swagger UI + ReDoc',\n // swagger-ui-dist depends on @scarf/scarf, which has a postinstall script.\n builds: { '@scarf/scarf': true },\n },\n // Database — the dialect adapters now ship as subpaths of\n // `@forinda/kickjs-db` (`/pg`, `/sqlite`, `/mysql`), so each `kick add`\n // pulls the core package plus the one driver you need.\n db: {\n pkg: '@forinda/kickjs-db',\n peers: [],\n description: 'kick/db core — schema DSL, migrations, KickDbClient, customType',\n },\n pg: {\n pkg: '@forinda/kickjs-db',\n peers: ['pg'],\n typePeers: ['@types/pg'],\n description: 'kick/db + PostgreSQL driver (use @forinda/kickjs-db/pg)',\n },\n sqlite: {\n pkg: '@forinda/kickjs-db',\n peers: ['better-sqlite3'],\n // A native addon — its install script compiles or downloads the binary,\n // and pnpm 10+ fails the install (ERR_PNPM_IGNORED_BUILDS) until it's allowed.\n builds: { 'better-sqlite3': true },\n typePeers: ['@types/better-sqlite3'],\n description: 'kick/db + SQLite driver (use @forinda/kickjs-db/sqlite)',\n },\n mysql: {\n pkg: '@forinda/kickjs-db',\n peers: ['mysql2'],\n description: 'kick/db + MySQL driver (use @forinda/kickjs-db/mysql)',\n },\n\n // Real-time\n ws: {\n pkg: '@forinda/kickjs-ws',\n peers: ['ws'],\n description: 'WebSocket with @WsController decorators',\n },\n\n // DevTools\n devtools: {\n pkg: '@forinda/kickjs-devtools',\n peers: [],\n description: 'Development dashboard — routes, DI, metrics, health',\n dev: true,\n },\n\n // Queue\n queue: {\n pkg: '@forinda/kickjs-queue',\n peers: [],\n description: 'Queue adapter (BullMQ/RabbitMQ/Kafka)',\n },\n 'queue:bullmq': {\n pkg: '@forinda/kickjs-queue',\n peers: ['bullmq', 'ioredis'],\n // bullmq → msgpackr → msgpackr-extract (optional native addon). msgpackr\n // falls back to JS without it, so the script is declined — but it must be\n // answered, or pnpm 10+ fails the install (ERR_PNPM_IGNORED_BUILDS).\n builds: { 'msgpackr-extract': false },\n description: 'Queue with BullMQ + Redis',\n },\n 'queue:rabbitmq': {\n pkg: '@forinda/kickjs-queue',\n peers: ['amqplib'],\n description: 'Queue with RabbitMQ',\n },\n 'queue:kafka': {\n pkg: '@forinda/kickjs-queue',\n peers: ['kafkajs'],\n description: 'Queue with Kafka',\n },\n 'queue:redis-pubsub': {\n pkg: '@forinda/kickjs-queue',\n peers: ['ioredis'],\n description: 'Lightweight pub/sub via Redis (no persistence)',\n },\n\n // MCP — Model Context Protocol server\n mcp: {\n pkg: '@forinda/kickjs-mcp',\n peers: ['@modelcontextprotocol/server'],\n description: 'Model Context Protocol server — expose @Controller endpoints as AI tools',\n },\n\n // Testing\n testing: {\n pkg: '@forinda/kickjs-testing',\n peers: [],\n description: 'Test utilities and TestModule builder',\n dev: true,\n },\n}\n\n/**\n * Headline `kick add` packages shown after scaffolding — derived from\n * {@link PACKAGE_REGISTRY} so it can never advertise a deprecated package (the\n * old hardcoded list included auth / drizzle / prisma, all three since removed).\n * Excludes core packages\n * (already installed), deprecated ones, `:` sub-variants (e.g. `queue:bullmq`),\n * and the db-dialect / schema-lib duplicates that clutter a one-line summary.\n * `kick add --list` shows the full catalog.\n */\nexport const AVAILABLE_ADD_PACKAGES = Object.entries(PACKAGE_REGISTRY)\n .filter(\n ([name, entry]) =>\n !entry.core &&\n !entry.deprecated &&\n !name.includes(':') &&\n !['pg', 'sqlite', 'mysql', 'zod', 'valibot', 'yup'].includes(name),\n )\n .map(([name]) => name)\n .join(', ')\n\n/**\n * The `upload` catalog name is special — file uploads ship inside\n * `@forinda/kickjs` itself, so there's no package to install. What an app\n * needs is the multipart DRIVER for its HTTP runtime, and that differs per\n * engine. `planAddPackages` resolves `upload` against the configured runtime\n * (see {@link KickConfig.runtime}); `kick doctor` validates the same mapping.\n */\n/**\n * Engine peers per runtime — the same set `kick new` scaffolds for the chosen\n * engine (`generators/templates/project-config.ts`). `@forinda/kickjs` declares\n * all three as optional peers; which ones a project actually needs is decided\n * by `bootstrap({ runtime })`, so installing them is a runtime-dependent\n * question, not a static dependency.\n */\nexport const ENGINE_PEERS: Record<'express' | 'fastify' | 'h3', readonly string[]> = {\n express: ['express'],\n // `serve-static` rather than express for static files — no express dependency.\n fastify: ['fastify', '@fastify/middie', 'serve-static'],\n h3: ['h3', 'serve-static'],\n}\n\nexport const UPLOAD_DRIVERS: Record<\n 'express' | 'fastify' | 'h3',\n { prod?: string; dev?: string; note: string }\n> = {\n express: {\n prod: 'multer',\n dev: '@types/multer',\n note: 'Express uploads use multer (memory/disk storage, ctx.file / ctx.files).',\n },\n fastify: {\n prod: '@fastify/multipart',\n note: 'Fastify uploads use @fastify/multipart (buffered into ctx.file / ctx.files).',\n },\n h3: {\n note: 'h3 parses multipart natively (readMultipartFormData) — no driver to install.',\n },\n}\n\nexport type AppRuntime = 'express' | 'fastify' | 'h3'\n\n/**\n * Resolve the project's HTTP runtime: the `runtime` field in kick.config\n * (authoritative — `kick new` writes it), falling back to sniffing installed\n * deps in the nearest package.json (`fastify` → fastify, `h3` → h3), else\n * `express` (the default engine). Lets `kick add upload` / `kick doctor` pick\n * the engine-correct multipart driver even in projects scaffolded before the\n * `runtime` field existed.\n */\n/** Validate `--runtime`, returning undefined when absent and exiting on a bad value. */\nexport function parseRuntimeFlag(value: unknown): AppRuntime | undefined {\n if (value === undefined) return undefined\n if (value === 'express' || value === 'fastify' || value === 'h3') return value\n throw new Error(`Invalid --runtime '${String(value)}'. Expected express, fastify or h3.`)\n}\n\nexport async function resolveAppRuntime(cwd = process.cwd()): Promise<AppRuntime> {\n return (await resolveAppRuntimeDetailed(cwd)).runtime\n}\n\n/**\n * As {@link resolveAppRuntime}, but says whether the answer was a guess.\n *\n * `kick.config.ts`'s `runtime` is authoritative and never ambiguous. Sniffing\n * is, so callers that act on the result — installing engine peers — surface the\n * ambiguity instead of silently picking.\n */\nexport async function resolveAppRuntimeDetailed(\n cwd = process.cwd(),\n): Promise<RuntimeDetection & { fromConfig: boolean }> {\n const config = await loadKickConfig(cwd)\n const fromConfig = (config as { runtime?: AppRuntime } | null)?.runtime\n if (fromConfig === 'express' || fromConfig === 'fastify' || fromConfig === 'h3') {\n return { runtime: fromConfig, candidates: [fromConfig], ambiguous: false, fromConfig: true }\n }\n return { ...detectRuntimeFromDepsDetailed(cwd), fromConfig: false }\n}\n\n/** Sniff the runtime from installed deps when kick.config has no `runtime`. */\n/**\n * Sniff result, with enough detail for a caller to say when it is guessing.\n *\n * `ambiguous` means more than one engine is installed and nothing settles which\n * one the app boots on. That happens legitimately — a project on Express with\n * Fastify in devDependencies for a benchmark — and the old precedence order\n * (fastify first, whether prod or dev) answered `fastify` there, which installed\n * the wrong engine peers.\n */\nexport interface RuntimeDetection {\n runtime: AppRuntime\n /** Engines found, in `dependencies` then `devDependencies`. */\n candidates: AppRuntime[]\n ambiguous: boolean\n}\n\nconst ENGINE_BY_PACKAGE: ReadonlyArray<readonly [string, AppRuntime]> = [\n ['express', 'express'],\n ['fastify', 'fastify'],\n ['h3', 'h3'],\n]\n\n/** Sniff the runtime from installed deps when kick.config has no `runtime`. */\nexport function detectRuntimeFromDepsDetailed(cwd = process.cwd()): RuntimeDetection {\n const dir = findUp('package.json', cwd)\n if (!dir) return { runtime: 'express', candidates: [], ambiguous: false }\n\n let prod: Record<string, unknown> = {}\n let dev: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf-8'))\n prod = (pkg.dependencies ?? {}) as Record<string, unknown>\n dev = (pkg.devDependencies ?? {}) as Record<string, unknown>\n } catch {\n return { runtime: 'express', candidates: [], ambiguous: false }\n }\n\n const inProd = ENGINE_BY_PACKAGE.filter(([p]) => p in prod).map(([, r]) => r)\n const inDev = ENGINE_BY_PACKAGE.filter(([p]) => p in dev && !(p in prod)).map(([, r]) => r)\n const candidates = [...inProd, ...inDev]\n\n // A runtime dependency outranks a dev one: you deploy on what you ship. That\n // IS a resolution, so it is not ambiguous — reporting otherwise made the\n // refusal below block the exact case this rule exists to allow (an Express\n // app keeping fastify in devDependencies for a benchmark).\n if (inProd.length === 1) return { runtime: inProd[0], candidates, ambiguous: false }\n if (inProd.length === 0 && inDev.length === 1) {\n return { runtime: inDev[0], candidates, ambiguous: false }\n }\n if (candidates.length === 0) return { runtime: 'express', candidates, ambiguous: false }\n\n // Two or more engines at the same level — nothing here can tell them apart.\n // Default to the framework default and let the caller say it is guessing.\n return { runtime: 'express', candidates, ambiguous: true }\n}\n\n/** Back-compat wrapper — the runtime only. */\nexport function detectRuntimeFromDeps(cwd = process.cwd()): AppRuntime {\n return detectRuntimeFromDepsDetailed(cwd).runtime\n}\n\n/**\n * Walk up from `fromDir` to filesystem root, returning the first\n * directory that contains `name`. Lets monorepo sub-packages pick up\n * lockfiles and `packageManager` fields living at the workspace root.\n */\nfunction findUp(name: string, fromDir = process.cwd()): string | null {\n let current = fromDir\n while (true) {\n if (existsSync(resolve(current, name))) return current\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nfunction detectFromLockfile(): PackageManager | null {\n if (findUp('pnpm-lock.yaml')) return 'pnpm'\n if (findUp('yarn.lock')) return 'yarn'\n if (findUp('bun.lockb') || findUp('bun.lock')) return 'bun'\n if (findUp('package-lock.json')) return 'npm'\n return null\n}\n\n/**\n * Read `packageManager` from the nearest ancestor `package.json` that\n * declares the field (corepack convention: `\"pnpm@10.0.0\"`). Climbs so\n * monorepo sub-packages inherit the workspace pm even when their own\n * package.json omits the field.\n */\nfunction packageManagerFromPackageJson(): PackageManager | null {\n let dir: string | null = process.cwd()\n while (dir) {\n const pkgPath = resolve(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))\n const field: unknown = pkg.packageManager\n if (typeof field === 'string') {\n const name = field.split('@')[0] as PackageManager\n if (PACKAGE_MANAGERS.includes(name)) return name\n }\n } catch {\n // ignore — keep climbing\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n return null\n}\n\nexport type PackageManagerSource = 'flag' | 'config' | 'package.json' | 'lockfile' | 'default'\n\n/**\n * Resolve which package manager to use, in priority order:\n * 1. `--pm` CLI flag\n * 2. `packageManager` in kick.config\n * 3. `packageManager` in nearest ancestor package.json (corepack)\n * 4. Nearest ancestor lockfile (pnpm-lock.yaml → yarn.lock → bun.lock → package-lock.json)\n * 5. `'npm'` fallback\n *\n * Returns the chosen pm plus the source for callers that want to log\n * the resolution path.\n */\nexport async function resolvePackageManagerWithSource(\n flagPm: string | undefined,\n): Promise<{ pm: PackageManager; source: PackageManagerSource }> {\n if (flagPm && PACKAGE_MANAGERS.includes(flagPm as PackageManager)) {\n return { pm: flagPm as PackageManager, source: 'flag' }\n }\n\n const config = await loadKickConfig(process.cwd())\n if (config?.packageManager && PACKAGE_MANAGERS.includes(config.packageManager)) {\n return { pm: config.packageManager, source: 'config' }\n }\n\n const fromPkg = packageManagerFromPackageJson()\n if (fromPkg) return { pm: fromPkg, source: 'package.json' }\n\n const fromLock = detectFromLockfile()\n if (fromLock) return { pm: fromLock, source: 'lockfile' }\n\n return { pm: 'npm', source: 'default' }\n}\n\n/** Convenience wrapper for callers that don't care about the source. */\nexport async function resolvePackageManager(flagPm: string | undefined): Promise<PackageManager> {\n const { pm } = await resolvePackageManagerWithSource(flagPm)\n return pm\n}\n\n/**\n * Print the package catalog. By default shows just the three core\n * packages every project always has — the optional list churns\n * (packages added, deprecated, removed) and a long enumeration in CLI\n * output / docs goes stale within a release. Pass `all = true` to dump\n * everything; that's what `kick add --list --all` triggers when an\n * adopter genuinely wants the live catalog.\n */\nexport function printPackageList(all = false, runtime?: 'express' | 'fastify' | 'h3'): void {\n const entries = Object.entries(PACKAGE_REGISTRY)\n const maxName = Math.max(...entries.map(([k]) => k.length))\n const core = entries.filter(([, info]) => info.core)\n const optional = entries.filter(([, info]) => !info.core)\n\n const formatRow = ([name, info]: [string, PackageEntry]): string => {\n const padded = name.padEnd(maxName + 2)\n // Engine peers depend on the runtime, so name it rather than printing a\n // list that would be wrong for two projects out of three.\n const resolved = info.enginePeers\n ? [...info.peers, ...ENGINE_PEERS[runtime ?? 'express']]\n : info.peers\n const engineNote = info.enginePeers ? ` [${runtime ?? 'express'} engine]` : ''\n const peers = resolved.length ? ` (+ ${resolved.join(', ')})${engineNote}` : ''\n const deprecated = info.deprecated ? ` [DEPRECATED — ${info.deprecated}]` : ''\n return ` ${padded} ${info.description}${peers}${deprecated}`\n }\n\n console.log('\\n Core packages (always installed by `kick new`):\\n')\n for (const row of core) console.log(formatRow(row))\n\n if (all) {\n console.log('\\n Optional packages (add as needed):\\n')\n for (const row of optional) console.log(formatRow(row))\n } else {\n console.log(`\\n Plus ${optional.length} optional packages (swagger, db, queue, …).`)\n console.log(' Run `kick add --list --all` for the full catalog.')\n }\n\n console.log('\\n Usage: kick add ai db swagger')\n console.log(' kick add queue:bullmq')\n console.log(' kick add upload # installs the multipart driver for your runtime')\n console.log()\n}\n\n/** Build tools every template installs: swc compiles the decorators, esbuild is Vite's. */\nexport const TEMPLATE_BUILDS: Record<string, boolean> = { '@swc/core': true, esbuild: true }\n\n/**\n * Record install-script answers where `pm` reads them, in `dir`:\n *\n * - pnpm 10+: pnpm-workspace.yaml, in both approval formats (see setAllowBuilds).\n * Unanswered scripts are skipped with a warning before pnpm 11; pnpm 11 fails\n * the install and every later `pnpm exec` with ERR_PNPM_IGNORED_BUILDS.\n * - npm 11.19+: `allowScripts` in package.json. Unanswered scripts are skipped\n * with a warning.\n * - bun: `trustedDependencies` in package.json. Untrusted scripts are skipped.\n * Only approvals are written; bun has no deny entry.\n * - yarn runs dependency scripts, so there is nothing to write.\n *\n * Existing answers win: a scaffold or `kick add` never overrides a decision\n * already in the file. Returns the file it changed, if any.\n */\nexport function approveInstallScripts(\n pm: PackageManager,\n dir: string,\n builds: Record<string, boolean>,\n): string | undefined {\n if (pm === 'pnpm') {\n const file = resolve(dir, 'pnpm-workspace.yaml')\n const before = existsSync(file) ? readFileSync(file, 'utf-8') : ''\n const after = setAllowBuilds(before, builds)\n if (after === before) return undefined\n writeFileSync(file, after)\n return file\n }\n if (pm !== 'npm' && pm !== 'bun') return undefined\n\n const file = resolve(dir, 'package.json')\n if (!existsSync(file)) return undefined\n const pkg = JSON.parse(readFileSync(file, 'utf-8'))\n let changed = false\n if (pm === 'npm') {\n const allow: Record<string, boolean> = pkg.allowScripts ?? {}\n for (const [name, value] of Object.entries(builds)) {\n // npm also accepts version-pinned keys (`esbuild@0.28.2`).\n if (Object.keys(allow).some((key) => key === name || key.startsWith(`${name}@`))) continue\n allow[name] = value\n changed = true\n }\n pkg.allowScripts = allow\n } else {\n const trusted: string[] = pkg.trustedDependencies ?? []\n for (const [name, value] of Object.entries(builds)) {\n if (!value || trusted.includes(name)) continue\n trusted.push(name)\n changed = true\n }\n pkg.trustedDependencies = trusted\n }\n if (!changed) return undefined\n writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\\n`)\n return file\n}\n\n/**\n * Where `pm` reads install-script answers from: the workspace root when the\n * project is a workspace member (fullstack server/), else the current directory.\n */\nfunction installRoot(pm: PackageManager): string {\n if (pm === 'pnpm') return findUp('pnpm-workspace.yaml') ?? process.cwd()\n for (let dir = process.cwd(); ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf-8')).workspaces) return dir\n } catch {\n // no package.json here, or not JSON — keep walking\n }\n if (dirname(dir) === dir) return process.cwd()\n }\n}\n\n/** Merged install-script answers for catalog entries (unknown names skipped). */\nexport function buildsFor(packages: string[]): Record<string, boolean> {\n return Object.assign({}, ...packages.map((name) => PACKAGE_REGISTRY[name]?.builds ?? {}))\n}\n\nexport interface AddPlan {\n prodDeps: string[]\n devDeps: string[]\n unknown: string[]\n /** Deprecation notices for requested entries — print, then install anyway. */\n warnings: string[]\n /** Informational notes (e.g. the upload driver chosen for the runtime). */\n notices: string[]\n}\n\n/**\n * Pure resolution step for `kick add` — maps requested catalog names to\n * the npm packages (plus peers) to install, split prod/dev. Kept free\n * of I/O so the catalog rules (dev defaults, deprecations, unknown\n * handling) are unit-testable without spawning a package manager.\n */\nexport function planAddPackages(\n packages: string[],\n forceDev: boolean,\n runtime: AppRuntime = 'express',\n): AddPlan {\n const prodDeps = new Set<string>()\n const devDeps = new Set<string>()\n const unknown: string[] = []\n const warnings: string[] = []\n const notices: string[] = []\n\n for (const name of packages) {\n // `upload` isn't a package — it's the runtime's multipart driver. File\n // uploads ship in @forinda/kickjs; only the engine backend needs adding.\n if (name === 'upload') {\n const driver = UPLOAD_DRIVERS[runtime]\n notices.push(`upload (${runtime}): ${driver.note}`)\n if (driver.prod) (forceDev ? devDeps : prodDeps).add(driver.prod)\n if (driver.dev) devDeps.add(driver.dev)\n continue\n }\n\n const entry = PACKAGE_REGISTRY[name]\n if (!entry) {\n unknown.push(name)\n continue\n }\n if (entry.deprecated) {\n warnings.push(`'${name}' (${entry.pkg}) is deprecated — ${entry.deprecated}`)\n }\n const target = forceDev || entry.dev ? devDeps : prodDeps\n target.add(entry.pkg)\n for (const peer of entry.peers) {\n target.add(peer)\n }\n for (const types of entry.typePeers ?? []) devDeps.add(types)\n if (entry.enginePeers) {\n const enginePeers = ENGINE_PEERS[runtime]\n for (const peer of enginePeers) target.add(peer)\n notices.push(`${name} (${runtime}): engine peers ${enginePeers.join(', ')}`)\n }\n }\n\n return { prodDeps: [...prodDeps], devDeps: [...devDeps], unknown, warnings, notices }\n}\n\nexport function registerListCommand(program: Command): void {\n program\n .command('list')\n .alias('ls')\n .description('List KickJS packages (core only; pair with --all for the full catalog)')\n .option('--all', 'Include the full optional catalog')\n .option('--runtime <engine>', 'HTTP engine to show peers for: express | fastify | h3')\n .action(async (opts: { all?: boolean; runtime?: string }) => {\n printPackageList(\n Boolean(opts.all),\n parseRuntimeFlag(opts.runtime) ?? (await resolveAppRuntime()),\n )\n })\n}\n\nexport function registerAddCommand(program: Command): void {\n program\n .command('add [packages...]')\n .description('Add KickJS packages with their required dependencies')\n .option('--pm <manager>', 'Package manager override')\n .option('-D, --dev', 'Install as dev dependency')\n .option('--list', 'List packages (core only by default; pair with --all)')\n .option(\n '--runtime <engine>',\n 'HTTP engine for peer resolution: express | fastify | h3 (overrides kick.config.ts)',\n )\n .option('--all', 'When listing, include the full optional catalog')\n .option('--no-wire', 'Install only — do not add adapters to the entry file or .env')\n .option('--entry <file>', 'Entry file to wire (default: src/index.ts, then src/main.ts)')\n .option('-f, --force', 'Wire even when the files it edits have uncommitted changes')\n .action(async (packages: string[], opts: any) => {\n // List mode\n if (opts.list || packages.length === 0) {\n printPackageList(\n Boolean(opts.all),\n parseRuntimeFlag(opts.runtime) ?? (await resolveAppRuntime()),\n )\n return\n }\n\n const { pm, source } = await resolvePackageManagerWithSource(opts.pm)\n console.log(`\\n Using ${pm} (resolved from ${source})`)\n // Resolve the runtime so `kick add upload` installs the right multipart\n // driver (express → multer, fastify → @fastify/multipart, h3 → none) and\n // the framework gets the engine peers it actually runs on.\n const fromFlag = parseRuntimeFlag(opts.runtime)\n const detection = await resolveAppRuntimeDetailed(process.cwd())\n const runtime = fromFlag ?? detection.runtime\n\n // Two engines at the same dependency level and nothing to break the tie.\n // Installing writes package.json and node_modules, so guessing here\n // leaves an adopter to undo it by hand — refuse instead, with both ways\n // to say what the app actually boots on.\n if (!fromFlag && detection.ambiguous) {\n console.error(\n `\\n Cannot tell which HTTP engine this app boots on: found ` +\n `${detection.candidates.join(', ')} in package.json.\\n` +\n `\\n Installing engine peers for the wrong one is worse than not installing them, so:\\n` +\n ` • set \\`runtime: '<engine>'\\` in kick.config.ts (permanent, also fixes kick doctor), or\\n` +\n ` • pass --runtime <${detection.candidates.join('|')}> for this command\\n`,\n )\n process.exitCode = 1\n return\n }\n const plan = planAddPackages(packages, Boolean(opts.dev), runtime)\n const { unknown, warnings, notices } = plan\n let { prodDeps, devDeps } = plan\n\n // Packages with a scaffold layer (swagger, devtools, ws, queue) are also\n // wired: their adapter goes into the entry file and their .env lines in.\n // The entry file imports them, so they install as regular dependencies\n // (devtools is otherwise a dev dependency), with the peers the layer uses.\n const cwd = process.cwd()\n // A mistyped --entry would otherwise install first and only then say\n // there was nothing to wire.\n if (opts.entry && !existsSync(resolve(cwd, opts.entry))) {\n console.error(`\\n --entry ${opts.entry} does not exist.\\n`)\n process.exitCode = 1\n return\n }\n const wiring = opts.wire === false ? undefined : planWiring(packages)\n const entry = wiring ? findEntry(cwd, opts.entry) : undefined\n if (wiring) {\n prodDeps = [...new Set([...prodDeps, ...wiring.dependencies])]\n devDeps = [\n ...new Set([...devDeps, ...wiring.devDependencies].filter((d) => !prodDeps.includes(d))),\n ]\n // Wiring edits files in place; refuse over uncommitted work there, so\n // the change stays reviewable (and revertable) as its own diff.\n const dirty = dirtyFiles(cwd, [...(entry ? [entry] : []), ...wiring.files.keys()])\n if (dirty.length > 0 && !opts.force) {\n console.error(\n `\\n ${dirty.join(', ')} ${dirty.length === 1 ? 'has' : 'have'} uncommitted changes, ` +\n `and kick add would edit ${dirty.length === 1 ? 'it' : 'them'}.\\n` +\n ` Commit or stash first, pass --force to edit anyway, or --no-wire to install only.\\n`,\n )\n process.exitCode = 1\n return\n }\n }\n\n for (const warning of warnings) {\n console.warn(`\\n WARNING: ${warning}`)\n }\n\n for (const notice of notices) {\n console.log(`\\n ${notice}`)\n }\n\n if (unknown.length > 0) {\n console.log(`\\n Unknown packages: ${unknown.join(', ')}`)\n console.log(' Run \"kick add --list\" to see available packages.\\n')\n if (prodDeps.length === 0 && devDeps.length === 0) return\n }\n\n // Answer install-script approvals before installing, so the package\n // manager doesn't block the scripts these packages bring in.\n const builds = { ...buildsFor(packages), ...wiring?.builds }\n if (Object.keys(builds).length > 0) {\n const file = approveInstallScripts(pm, installRoot(pm), builds)\n if (file) console.log(`\\n Approved install scripts in ${file}`)\n }\n\n let installed = true\n // Install production dependencies\n if (prodDeps.length > 0) {\n const deps = prodDeps\n const cmd = `${pm} add ${deps.join(' ')}`\n console.log(`\\n Installing ${deps.length} dependency(ies):`)\n for (const dep of deps) console.log(` + ${dep}`)\n console.log()\n try {\n execSync(cmd, { stdio: 'inherit' })\n } catch {\n installed = false\n console.log(`\\n Installation failed. Run manually:\\n ${cmd}\\n`)\n }\n }\n\n // Install dev dependencies\n if (devDeps.length > 0) {\n const deps = devDeps\n const cmd = `${pm} add -D ${deps.join(' ')}`\n console.log(`\\n Installing ${deps.length} dev dependency(ies):`)\n for (const dep of deps) console.log(` + ${dep} (dev)`)\n console.log()\n try {\n execSync(cmd, { stdio: 'inherit' })\n } catch {\n installed = false\n console.log(`\\n Installation failed. Run manually:\\n ${cmd}\\n`)\n }\n }\n\n if (wiring) {\n if (!installed) {\n console.log(' Skipped wiring — the install did not finish.\\n')\n } else {\n for (const path of await applyLayerFiles(cwd, wiring.files)) {\n console.log(` Updated ${path}`)\n }\n const result = entry ? await wireEntry(cwd, entry, wiring.integrations) : undefined\n for (const name of result?.added ?? []) console.log(` Added ${name} to ${entry}`)\n for (const name of result?.present ?? []) console.log(` ${name} is already in ${entry}`)\n const fill = projectVars(cwd)\n const manual = result\n ? result.manual\n : wiring.integrations\n .filter((i) => i.slot && i.code)\n .map((i) => ({ ...i, code: fill(i.code!) }))\n if (manual.length > 0) {\n console.log(\n `\\n ${entry ? `Could not find bootstrap({ adapters: [...] }) in ${entry}` : 'No entry file found'}` +\n ' — add this yourself:\\n',\n )\n console.log(manualSnippet(manual).replace(/^/gm, ' '))\n console.log()\n }\n }\n }\n\n if (installed) {\n console.log(' Done!\\n')\n } else {\n console.log(' Finished with errors — the install above did not complete.\\n')\n process.exitCode = 1\n }\n })\n}\n","import { join, dirname } from 'node:path'\nimport { execSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { writeFileSafe } from '../utils/fs'\nimport { fillVars, renderLayers, TEMPLATES_DIR, type Integration } from '../scaffold/overlay'\nimport { captureCommand, captureCommandAsync } from '../utils/shell'\nimport { generatePackageJson } from './templates/project-config'\nimport {\n AVAILABLE_ADD_PACKAGES,\n TEMPLATE_BUILDS,\n approveInstallScripts,\n buildsFor,\n} from '../commands/add'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The CLI's own package.json sits one level up from the bundle\n * (`dist/project-*.mjs`) but two levels up from this source file\n * (`src/generators/project.ts`). Checking both is what lets this module be\n * imported from a test at all — reading only the bundle-relative path threw\n * ENOENT the moment anything imported it from source, which is why the\n * version-resolution path shipped untested.\n */\nconst cliPkg = JSON.parse(\n readFileSync(\n [join(__dirname, '..', 'package.json'), join(__dirname, '..', '..', 'package.json')].find(\n existsSync,\n )!,\n 'utf-8',\n ),\n)\n\n/**\n * Sibling `@forinda/kickjs-*` packages whose versions are resolved\n * independently when scaffolding a new project. Each entry is queried\n * via `npm view <name> version`; failure falls back to `latest`\n * (see `fallbackRange`).\n *\n * Per-package independent versioning landed with changesets — before\n * that, every sibling shipped in lockstep with the CLI so a single\n * pin was correct. Now `@forinda/kickjs@5.5.0` may pair with\n * `@forinda/kickjs-cli@5.4.2` and `@forinda/kickjs-swagger@5.3.1`;\n * pinning them all to the CLI's version under-installs adopters.\n */\nexport const SIBLING_PACKAGES = [\n '@forinda/kickjs',\n '@forinda/kickjs-cli',\n '@forinda/kickjs-schema',\n '@forinda/kickjs-vite',\n '@forinda/kickjs-swagger',\n '@forinda/kickjs-ws',\n '@forinda/kickjs-queue',\n '@forinda/kickjs-devtools',\n '@forinda/kickjs-testing',\n '@forinda/kickjs-client',\n] as const\n\n/**\n * Third-party dependencies the templates install, resolved at scaffold time\n * instead of pinned here — a pin means every React, Vitest or oxlint release\n * needs a CLI release to reach new projects, and the pins drift apart (the\n * fullstack web app shipped vite ^7 while the server template was on ^8).\n *\n * `cap` is the range a package may float within, for the ones where a new\n * major changes what the templates generate or what KickJS peers on: the\n * engine packages, the schema libraries, and the toolchain the generated\n * configs are written against. Everything else tracks `latest`.\n *\n * The value is the fallback: what gets written when `npm view` says nothing\n * (offline, registry down), so a scaffold without network still installs.\n */\nexport const THIRD_PARTY_PACKAGES: Record<string, { fallback: string; cap?: string }> = {\n // Frontend — the fullstack web app. Nothing the template writes is\n // version-specific (`createRoot`, JSX, a plugin call), so these float.\n react: { fallback: '^19.0.0' },\n 'react-dom': { fallback: '^19.0.0' },\n '@types/react': { fallback: '^19.0.0' },\n '@types/react-dom': { fallback: '^19.0.0' },\n '@vitejs/plugin-react': { fallback: '^5.0.0' },\n // Toolchain.\n '@types/node': { fallback: '^25.0.0' },\n '@types/supertest': { fallback: '^7.2.1' },\n supertest: { fallback: '^7.2.2' },\n vitest: { fallback: '^4.1.2' },\n '@swc/core': { fallback: '^1.15.21' },\n 'unplugin-swc': { fallback: '^1.5.9' },\n oxfmt: { fallback: '^0.65.0' },\n oxlint: { fallback: '^1.80.0' },\n // Capped: an optional peer of @forinda/kickjs at this major. Uncapped,\n // `latest` (18) installed with an unmet-peer warning on every scaffold.\n dotenv: { fallback: '^17.3.1', cap: '^17' },\n 'reflect-metadata': { fallback: '^0.2.2' },\n // Capped — a new major here breaks the generated project, not just its deps.\n // vite: `@forinda/kickjs-vite` peers on it and the generated vite.config.ts\n // is written against this major.\n vite: { fallback: '^8.0.3', cap: '^8' },\n // typescript: the generated tsconfig.json targets this major.\n typescript: { fallback: '^7.0.2', cap: '^7' },\n '@typescript/typescript6': { fallback: '^6.0.2', cap: '^6' },\n // HTTP engines: `bootstrap({ runtime })` peers on the major.\n express: { fallback: '^5.1.0', cap: '^5' },\n '@types/express': { fallback: '^5.0.6', cap: '^5' },\n fastify: { fallback: '^5.0.0', cap: '^5' },\n '@fastify/middie': { fallback: '^9.0.0', cap: '^9' },\n // h3 v2 is a different runtime (`./h3-web`), not an upgrade of this one.\n h3: { fallback: '^1.0.0', cap: '^1' },\n 'serve-static': { fallback: '^2.2.0', cap: '^2' },\n // Schema libraries: `@forinda/kickjs-schema` adapts one major each.\n zod: { fallback: '^4.3.6', cap: '^4' },\n valibot: { fallback: '^1.4.1', cap: '^1' },\n yup: { fallback: '^1.7.1', cap: '^1' },\n // Peers of the optional packages (`--packages ws,queue`), capped at the\n // major those packages peer on.\n ws: { fallback: '^8.18.0', cap: '^8' },\n bullmq: { fallback: '^5.0.0', cap: '^5' },\n ioredis: { fallback: '^5.0.0', cap: '^5' },\n}\n\n/**\n * Newest version matching `spec`. A bare name asks for the `latest` tag and\n * npm prints one version; a range prints every match as JSON, newest last.\n */\nexport function parseNpmVersion(output: string | null): string | null {\n if (!output) return null\n const trimmed = output.trim()\n if (/^\\d+\\.\\d+\\.\\d+/.test(trimmed)) return trimmed.split(/\\s/)[0]!\n try {\n const parsed = JSON.parse(trimmed) as unknown\n const list = Array.isArray(parsed) ? parsed : [parsed]\n const versions = list.filter((v): v is string => typeof v === 'string')\n return versions.length > 0 ? versions[versions.length - 1]! : null\n } catch {\n return null\n }\n}\n\n/**\n * Range to write when `npm view <name> version` gives us nothing.\n *\n * It must never be the CLI's own version. Sibling packages version\n * independently, so `@forinda/kickjs-vite@^${cliVersion}` names a release\n * that does not exist — the scaffold then dies at install time with\n * `npm error 404 '@forinda/kickjs-vite@^6.14.1' is not in this registry`,\n * which is worse than the under-install this fallback was meant to avoid.\n * `latest` is the one range that is always resolvable and always current.\n *\n * The CLI itself is the exception: its version IS the CLI's version, and\n * pinning it keeps a scaffold reproducible against the CLI that made it.\n */\nfunction fallbackRange(name: string): string {\n return name === '@forinda/kickjs-cli' ? `^${cliPkg.version}` : 'latest'\n}\n\n/**\n * Resolve the latest published version of every sibling package via\n * `npm view <name> version` (through `captureCommandAsync`, which routes\n * around Windows' `.cmd` shims — see utils/shell.ts).\n *\n * The timeout is generous and the queries are genuinely concurrent: a\n * warm `npm view` against the public registry measures 0.6–3.6s per\n * package, so the old 5s budget was one slow response away from expiring,\n * and the sync `captureCommand` under `Promise.all` ran all ten serially\n * — making the per-call budget the only thing standing between a scaffold\n * and a package.json full of fallbacks.\n */\n/**\n * Run `task` over every item, at most `limit` at a time. Each `npm view` is a\n * process; the full list is 37 of them, and firing all of them at once can\n * exhaust process or memory limits on a small machine (CI containers, a\n * Raspberry Pi) — which fails the scaffold rather than slowing it.\n */\nasync function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = Array.from({ length: items.length })\n let next = 0\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n while (next < items.length) {\n const index = next++\n results[index] = await task(items[index]!)\n }\n })\n await Promise.all(workers)\n return results\n}\n\n/**\n * How long the whole resolution may take before the rest of the packages take\n * their fallback ranges. Node's `timeout` applies per child process, so a\n * stalled registry would otherwise cost one timeout per wave of the worker\n * pool — 37 lookups, 8 at a time, is five waves and over a minute of a\n * scaffold sitting still.\n */\nexport const VERSION_LOOKUP_BUDGET_MS = 20_000\n\nexport async function resolveSiblingVersions(): Promise<Record<string, string>> {\n const queries = [\n ...SIBLING_PACKAGES.map((name) => ({ name, fallback: fallbackRange(name), cap: undefined })),\n ...Object.entries(THIRD_PARTY_PACKAGES).map(([name, entry]) => ({ name, ...entry })),\n ]\n\n const deadline = Date.now() + VERSION_LOOKUP_BUDGET_MS\n\n const resolved = await mapWithConcurrency(queries, 8, async ({ name, fallback, cap }) => {\n // Out of budget: take the fallback rather than start another probe.\n const remaining = deadline - Date.now()\n if (remaining <= 0) return [name, fallback] as const\n\n // Network failure / package not yet published / npm unavailable all\n // surface as null → fall back to a range that always resolves.\n const spec = cap ? `${name}@${cap}` : name\n const out = await captureCommandAsync(\n 'npm',\n // A capped query matches many versions; npm prints them as JSON.\n cap ? ['view', spec, 'version', '--json'] : ['view', spec, 'version'],\n { timeout: remaining },\n )\n const version = parseNpmVersion(out)\n return [name, version ? `^${version}` : fallback] as const\n })\n\n return Object.fromEntries(resolved)\n}\n\n/**\n * Resolve the published version of a package at a given dist-tag\n * (`npm view <name>@<tag> version`). Returns `null` on any failure. Used\n * to pin `@forinda/kickjs` to the `alpha` channel when scaffolding a\n * Fastify / h3 app — the engine subpaths (`@forinda/kickjs/fastify`,\n * `/h3`) ship only on the alpha until the runtimes land in a stable\n * release, so the default `latest` resolution would install a kickjs\n * that doesn't export them (→ Vite \"./h3 is not exported\" at boot).\n * Returns the bare version; the caller applies a `^` range so the project\n * floats to newer alphas and auto-graduates to stable (a caret over a\n * prerelease matches same-tuple prereleases ≥ it, plus later stables `< next\n * major`).\n */\nfunction resolveVersionAtTag(name: string, tag: string): string | null {\n const out = captureCommand('npm', ['view', `${name}@${tag}`, 'version'], { timeout: 20_000 })\n return out && /^\\d+\\.\\d+\\.\\d+/.test(out) ? out : null\n}\n\n/**\n * Whether the package at a given dist-tag exports a subpath (e.g. `./h3`).\n * Reads the `exports` map via `npm view <name>@<tag> exports --json`. Used to\n * gate the alpha-pin: if `latest` already ships the engine subpath, the runtime\n * has graduated to stable and we should NOT downgrade to an older alpha.\n * Returns `false` on any failure (missing field / network / unparseable) so the\n * caller treats \"unknown\" as \"not present\" and falls through to the alpha path.\n */\n/** Strip a leading range operator (`^1.2.3` / `~1.2.3` → `1.2.3`). */\nfunction stripRange(range: string | undefined): string {\n return (range ?? '').replace(/^[\\^~>=<\\s]+/, '')\n}\n\n/**\n * Compare the release cores (major.minor.patch, ignoring any `-prerelease`\n * suffix) of two versions: is `a` >= `b`? Used to guard the alpha-pin so a\n * package is never downgraded onto a stale prerelease whose stable line has\n * already moved past it. A coarse compare is enough here — we only need\n * \"is this alpha at least as new as the stable we'd otherwise install\".\n */\nfunction baseVersionGte(a: string, b: string): boolean {\n const core = (v: string): number[] =>\n stripRange(v)\n .split('-')[0]!\n .split('.')\n .map((n) => Number.parseInt(n, 10) || 0)\n const [a0 = 0, a1 = 0, a2 = 0] = core(a)\n const [b0 = 0, b1 = 0, b2 = 0] = core(b)\n if (a0 !== b0) return a0 > b0\n if (a1 !== b1) return a1 > b1\n return a2 >= b2\n}\n\nfunction tagExportsSubpath(name: string, tag: string, subpath: string): boolean {\n const out = captureCommand('npm', ['view', `${name}@${tag}`, 'exports', '--json'], {\n timeout: 20_000,\n })\n if (!out) return false\n try {\n const exportsMap = JSON.parse(out) as Record<string, unknown>\n return Object.prototype.hasOwnProperty.call(exportsMap, subpath)\n } catch {\n return false\n }\n}\n\ntype ProjectTemplate = 'rest' | 'minimal'\ntype SchemaLib = 'zod' | 'valibot' | 'yup'\n\ninterface InitProjectOptions {\n name: string\n directory: string\n packageManager?: 'pnpm' | 'npm' | 'yarn' | 'bun'\n initGit?: boolean\n installDeps?: boolean\n template?: ProjectTemplate\n defaultRepo?: string\n packages?: string[]\n /** Schema library to scaffold env / DTOs with. Defaults to `zod`. */\n schemaLib?: SchemaLib\n /** HTTP engine to scaffold. Defaults to `express`. */\n runtime?: 'express' | 'fastify' | 'h3'\n /** Wire `SpaAdapter` at this clientDir (fullstack template). */\n spaClientDir?: string\n /**\n * Layers rendered after the selection's — `server-fullstack` for the\n * fullstack workspace's server (strict port, client route map, TS 6 pin).\n */\n extraLayers?: string[]\n /**\n * Record install-script approvals for the package manager (pnpm-workspace.yaml,\n * or package.json for npm/bun). Default true; false when the project is a\n * member of a workspace whose root records them.\n */\n approveInstallScripts?: boolean\n /**\n * Write netlify.toml / vercel.json. Default true; false for a workspace\n * member — the platforms build from the root, which owns those files.\n */\n platformConfig?: boolean\n /**\n * Ranges resolved by the caller. The fullstack generator passes one map for\n * the whole workspace: resolving per package lets a failed lookup fall back\n * on one side and succeed on the other, which is how server/ and web/ end\n * up on different vite or TypeScript majors.\n */\n versions?: Record<string, string>\n}\n\n/** Scaffold a new KickJS project */\n/**\n * Scaffold a project. Returns the install-script answers it needs, so a\n * caller that installs from elsewhere (the fullstack workspace root) can\n * record them there.\n */\nexport async function initProject(\n options: InitProjectOptions,\n): Promise<{ builds: Record<string, boolean> }> {\n const {\n name,\n directory,\n packageManager = 'pnpm',\n template = 'rest',\n defaultRepo = 'inmemory',\n packages = [],\n schemaLib = 'zod',\n runtime = 'express',\n } = options\n const dir = directory\n\n const log = (msg: string) => console.log(` ${msg}`)\n\n console.log(`\\n Creating KickJS project: ${name}\\n`)\n\n // Resolve published version of every sibling kickjs package in\n // parallel. Per-package independent versioning means\n // `@forinda/kickjs@5.5.0` may pair with `@forinda/kickjs-cli@5.4.2`\n // and `@forinda/kickjs-swagger@5.3.1`; pinning every dep to the\n // CLI's own version under-installs adopters whenever a sibling\n // bumps independently. `npm view` fallback keeps the scaffold\n // working offline.\n if (!options.versions) log('Resolving package versions...')\n const versions = options.versions ?? (await resolveSiblingVersions())\n\n // A 'latest' range means the registry query failed for that package. The\n // install still works, but the pin is looser than intended and the user\n // should know why their package.json does not read like the docs.\n const unresolved = Object.keys(versions).filter((name) => versions[name] === 'latest')\n if (unresolved.length > 0) {\n log(`WARNING: could not reach npm for ${unresolved.join(', ')} — pinned to 'latest'`)\n }\n\n // The pluggable-runtimes work (Fastify / h3 engine subpaths, the\n // `kick/runtime` typegen, `kick add upload`, `kick doctor` runtime checks)\n // ships only on the `alpha` channel until it lands in a stable release. So a\n // non-Express scaffold needs the alpha of every package that carries runtime\n // behavior, not just `@forinda/kickjs`:\n // - `@forinda/kickjs` — the `./fastify` / `./h3` export subpaths the\n // app imports (stable lacks them → Vite boot\n // error `\"./h3\" is not exported`).\n // - `@forinda/kickjs-cli` — `--runtime`, `kick add upload`, `kick doctor`,\n // the `kick/runtime` typegen plugin.\n // - `@forinda/kickjs-vite` — the dev loop co-versioned with the above.\n // Gated on whether `@forinda/kickjs@latest` already exports the chosen engine\n // subpath: once that's true the runtimes are stable and we keep `latest` for\n // everything (self-retiring — no code change needed at graduation). Each pin\n // is guarded so it never DOWNGRADES (an alpha can be older than latest — e.g.\n // a package whose stable moved on past an old prerelease). Express is exempt.\n if (runtime !== 'express') {\n const subpath = `./${runtime}` // './fastify' | './h3'\n if (tagExportsSubpath('@forinda/kickjs', 'latest', subpath)) {\n log(`Using @forinda/kickjs@latest (stable ships the ${runtime} runtime)`)\n } else {\n const RUNTIME_PKGS = ['@forinda/kickjs', '@forinda/kickjs-cli', '@forinda/kickjs-vite']\n const pinned: string[] = []\n let kickjsPinned = false\n for (const pkg of RUNTIME_PKGS) {\n const alpha = resolveVersionAtTag(pkg, 'alpha')\n // Only switch when the alpha is newer-or-equal to the stable we'd\n // otherwise install — never downgrade onto a stale prerelease. Use a\n // `^` range (not an exact pin) so the project picks up newer alphas and\n // auto-graduates to the stable release once it ships.\n if (alpha && baseVersionGte(alpha, stripRange(versions[pkg]))) {\n versions[pkg] = `^${alpha}`\n pinned.push(`${pkg}@^${alpha}`)\n if (pkg === '@forinda/kickjs') kickjsPinned = true\n }\n }\n if (kickjsPinned) {\n log(`Using the alpha channel for the ${runtime} runtime: ${pinned.join(', ')}`)\n } else {\n log(\n `WARNING: could not resolve @forinda/kickjs@alpha — the ${runtime} runtime subpath ` +\n `may be missing. After install, run: ${packageManager} add @forinda/kickjs@alpha`,\n )\n }\n }\n }\n\n // ── Layers — templates/<layer>/ ──────────────────────────────────\n // Everything that follows from the options: the entry file (runtime,\n // adapters), the env schema, .env additions and the package lists.\n const unknown = packages.filter((pkg) => !existsSync(join(TEMPLATES_DIR, `feature-${pkg}`)))\n if (unknown.length > 0) {\n log(\n `WARNING: skipping unknown package(s): ${unknown.join(', ')} — add them later with kick add`,\n )\n }\n const project = renderLayers(\n [\n ...scaffoldLayers({ template, runtime, schemaLib, packages }),\n // netlify.toml / vercel.json — inert until the project is connected to\n // a platform. A workspace member leaves them to the root.\n ...(options.platformConfig !== false ? ['host-config'] : []),\n ...(options.extraLayers ?? []),\n ],\n {\n vars: { name, version: cliPkg.version },\n extra: [\n // `inmemory` is the only built-in; any other name is a `{ name }` custom repo.\n {\n slot: 'repo',\n code:\n defaultRepo === 'inmemory'\n ? `repo: 'inmemory'`\n : `repo: { name: '${defaultRepo.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}' }`,\n },\n ...(options.spaClientDir ? [spaIntegration(options.spaClientDir)] : []),\n ],\n },\n )\n\n // ── package.json ─────────────────────────────────────────────────────\n await writeFileSafe(join(dir, 'package.json'), generatePackageJson(name, versions, project))\n\n // tsconfig, vite/vitest/kick config, formatter/editor/git config, .env\n // files (`.env.test` is read INSTEAD of `.env` under a test run, so\n // shipping it isolates a new project's tests), README, the hello module,\n // `src/config/index.ts` (the typed env schema `kick typegen` reads) and\n // `src/index.ts`.\n const files = fillVars(project.files, {\n name,\n template,\n runtime,\n packageManager,\n templateLabel: template === 'rest' ? 'REST API' : 'Minimal',\n packages: [...project.dependencies, ...project.devDependencies]\n .filter((pkg) => pkg.startsWith('@forinda/'))\n .map((pkg) => `- \\`${pkg}\\``)\n .join('\\n'),\n })\n for (const [path, contents] of files) {\n await writeFileSafe(join(dir, path), contents)\n }\n\n // ── Agent docs ──────────────────────────────────────────────────────\n // Delegate to `generateAgentDocs()` so `kick new` emits the same\n // `.agents/` subfolder layout as `kick g agents -f`. Otherwise the\n // two paths drifted: kick new was writing the legacy flat layout\n // (root-level AGENTS.md + kickjs-skills.md) while kick g agents\n // emits the per-skill SKILL.md format under .agents/. `force: true`\n // because the project directory is fresh — no overwrite prompts\n // make sense during init.\n const { generateAgentDocs } = await import('./agent-docs')\n await generateAgentDocs({\n outDir: dir,\n name,\n pm: packageManager,\n template,\n only: 'all',\n force: true,\n })\n\n // ── Install-script approvals ─────────────────────────────────────────\n // Before install; see approveInstallScripts.\n const builds = { ...TEMPLATE_BUILDS, ...buildsFor(packages), ...project.builds }\n if (options.approveInstallScripts !== false) {\n approveInstallScripts(packageManager, dir, builds)\n }\n\n // ── Install Dependencies ────────────────────────────────────────────\n // Install BEFORE git init so the lockfile is included in the first commit.\n if (options.installDeps) {\n console.log(`\\n Installing dependencies with ${packageManager}...\\n`)\n try {\n execSync(`${packageManager} install`, { cwd: dir, stdio: 'inherit' })\n console.log('\\n Dependencies installed successfully!')\n } catch {\n console.log(`\\n Warning: ${packageManager} install failed. Run it manually.`)\n }\n }\n\n // ── Initial typegen ────────────────────────────────────────────────\n // Run typegen once so the freshly-scaffolded HelloController's\n // `Ctx<KickRoutes.HelloController['index']>` references resolve in\n // the user's editor immediately. Failures are non-fatal.\n try {\n const { runTypegen } = await import('../typegen')\n await runTypegen({ cwd: dir, allowDuplicates: true, silent: true })\n } catch {\n // First-run typegen errors are non-fatal — `kick dev` will retry.\n }\n\n // ── Git Init ─────────────────────────────────────────────────────────\n // Runs after install + typegen so lockfile and generated types are\n // included in the initial commit.\n if (options.initGit) {\n try {\n execSync('git init', { cwd: dir, stdio: 'pipe' })\n execSync('git branch -M main', { cwd: dir, stdio: 'pipe' })\n execSync('git add -A', { cwd: dir, stdio: 'pipe' })\n execSync('git commit -m \"chore: initial commit from kick new\"', {\n cwd: dir,\n stdio: 'pipe',\n })\n log('Git repository initialized')\n } catch {\n log('Warning: git init failed (git may not be installed)')\n }\n }\n\n console.log('\\n Project scaffolded successfully!')\n console.log()\n\n const needsCd = dir !== process.cwd()\n log('Next steps:')\n if (needsCd) log(` cd ${name}`)\n if (!options.installDeps) log(` ${packageManager} install`)\n\n const genHint: Record<string, string> = {\n rest: 'kick g module user',\n minimal: '# add your routes to src/index.ts',\n }\n log(` ${genHint[template] ?? genHint.rest}`)\n log(' kick dev')\n log('')\n log('Commands:')\n log(' kick dev Start dev server with Vite HMR')\n log(' kick build Production build via Vite')\n log(' kick start Run production build')\n log('')\n log('Generators:')\n log(' kick g module <name> REST module (controller, service, DTOs, repository)')\n log(' kick g scaffold <n> <f..> CRUD module from field definitions')\n log(' kick g controller <name> Standalone controller')\n log(' kick g service <name> @Service() class')\n log(' kick g middleware <name> Global connect-style middleware')\n log(' kick g guard <name> Route guard (auth, roles, etc.)')\n log(' kick g adapter <name> AppAdapter with lifecycle hooks')\n log(' kick g dto <name> DTO schema (Zod / Valibot / Yup)')\n log(' kick g config Generate kick.config.ts')\n log('')\n log('Add packages:')\n log(' kick add <pkg> Install a KickJS package + peers')\n log(' kick add --list Show all available packages')\n log('')\n log(`Available: ${AVAILABLE_ADD_PACKAGES}`)\n log('')\n\n return { builds }\n}\n\n/**\n * `SpaAdapter` for the fullstack server, which serves `web/`'s build from the\n * API's origin in production. The path is text the caller chose, so it goes\n * in through JSON.stringify — a quote, backslash or newline in it would\n * otherwise break the emitted module or change the path it resolves.\n */\nexport function spaIntegration(clientDir: string): Integration {\n return {\n import: { from: '@forinda/kickjs/spa', names: ['SpaAdapter'] },\n slot: 'adapter',\n code:\n '// Serves the built frontend from this origin in production.\\n' +\n '// Inert until the client build exists, so `kick dev` (where Vite\\n' +\n '// serves the client and proxies /api here) is unaffected.\\n' +\n `SpaAdapter({ clientDir: ${JSON.stringify(clientDir)} })`,\n }\n}\n\n/**\n * The layers a `kick new` selection renders, in order. Unknown package\n * names are left out (the caller warns about them).\n */\nexport function scaffoldLayers(selection: {\n template: 'rest' | 'minimal'\n runtime: 'express' | 'fastify' | 'h3'\n schemaLib: SchemaLib\n packages: readonly string[]\n}): string[] {\n return [\n 'base',\n `template-${selection.template}`,\n `runtime-${selection.runtime}`,\n `schema-${selection.schemaLib}`,\n ...selection.packages\n .filter((pkg) => existsSync(join(TEMPLATES_DIR, `feature-${pkg}`)))\n .map((pkg) => `feature-${pkg}`),\n ]\n}\n"],"mappings":";;;;;;;;;;udA2BA,MAAM,EAAO,EAAQ,EAAc,YAAY,GAAG,CAAC,EAOtC,EAAgB,CAC3B,EAAK,EAAM,KAAM,WAAW,EAC5B,EAAK,EAAM,KAAM,KAAM,WAAW,CACpC,CAAC,CAAC,KAAM,GAAQ,EAAW,EAAK,EAAK,MAAM,CAAC,CAAC,EAyC7C,SAAgB,EAAW,EAA8B,CACvD,OAAO,EACJ,MAAM,GAAG,CAAC,CACV,IAAK,GAAa,EAAQ,WAAW,OAAO,EAAI,IAAI,EAAQ,MAAM,CAAC,IAAM,CAAQ,CAAC,CAClF,KAAK,GAAG,CACb,CAUA,SAAgB,EACd,EACA,EAII,CAAC,EACY,CACjB,IAAM,EAAe,EAAQ,cAAgB,EACvC,EAAQ,IAAI,IACZ,EAAyB,CAAC,EAC1B,EAA4B,CAAC,EAC7B,EAAkC,CAAC,EACnC,EAA8B,CAAC,EAErC,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAM,EAAK,EAAc,CAAK,EACpC,GAAI,CAAC,EAAW,CAAG,EAAG,MAAU,MAAM,2BAA2B,EAAM,KAAK,EAAI,EAAE,EAElF,IAAM,EAAe,EAAK,EAAK,cAAc,EAC7C,GAAI,EAAW,CAAY,EAAG,CAC5B,IAAM,EAAW,KAAK,MAAM,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