@forinda/kickjs-cli 8.3.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/{agent-docs-VPtM_Kgj.mjs → agent-docs-CXX06wib.mjs} +2 -2
  2. package/dist/{agent-docs-CpoUa3NG.mjs → agent-docs-CXs5UDAM.mjs} +3 -3
  3. package/dist/{agent-docs-CpoUa3NG.mjs.map → agent-docs-CXs5UDAM.mjs.map} +1 -1
  4. package/dist/{build-BKNvIOBh.mjs → build-D3rNfcxu.mjs} +3 -3
  5. package/dist/{build-BKNvIOBh.mjs.map → build-D3rNfcxu.mjs.map} +1 -1
  6. package/dist/{build-BhoYGIVD.mjs → build-DwfrMHgx.mjs} +2 -2
  7. package/dist/{builtins-BvdsVFXh.mjs → builtins-D4pwODzu.mjs} +2 -2
  8. package/dist/{builtins-6FCYMic-.mjs → builtins-DtTYiDg0.mjs} +4 -4
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-LkaeajTr.mjs → config-BUYf44lU.mjs} +3 -3
  11. package/dist/{config-LkaeajTr.mjs.map → config-BUYf44lU.mjs.map} +1 -1
  12. package/dist/{config-3zv5pWqb.mjs → config-F1NW28_P.mjs} +2 -2
  13. package/dist/{doctor-3-n9AElz.mjs → doctor-Df6zCPr5.mjs} +4 -4
  14. package/dist/{doctor-3-n9AElz.mjs.map → doctor-Df6zCPr5.mjs.map} +1 -1
  15. package/dist/{fullstack-0D2Dgia_.mjs → fullstack-BcJ5lOwt.mjs} +17 -11
  16. package/dist/{fullstack-D_OHhyZX.mjs → fullstack-D3W7RS2W.mjs} +18 -12
  17. package/dist/fullstack-D3W7RS2W.mjs.map +1 -0
  18. package/dist/index.d.mts +7 -0
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -2
  21. package/dist/{plugin-MfCs1kvG.mjs → plugin-B-mP0jvi.mjs} +2 -2
  22. package/dist/{plugin-3V8ZP2h3.mjs → plugin-B8fmVbk8.mjs} +2 -2
  23. package/dist/{project-Evcbbdbq.mjs → project-5aAVIQV5.mjs} +5 -5
  24. package/dist/{project-D-8rOQYi.mjs → project-DdYD7xPw.mjs} +7 -7
  25. package/dist/project-DdYD7xPw.mjs.map +1 -0
  26. package/dist/{project-docs-B-qcYAX9.mjs → project-docs-BE8DKCWP.mjs} +73 -2
  27. package/dist/{project-docs-B6XKHBMO.mjs → project-docs-Y6vOc-Uj.mjs} +74 -3
  28. package/dist/project-docs-Y6vOc-Uj.mjs.map +1 -0
  29. package/dist/{project-root-6mdsMXwA.mjs → project-root-BzyIWFlH.mjs} +3 -3
  30. package/dist/{project-root-6mdsMXwA.mjs.map → project-root-BzyIWFlH.mjs.map} +1 -1
  31. package/dist/{project-root-CxadsnDd.mjs → project-root-CSHMf3L7.mjs} +2 -2
  32. package/dist/{prompts-BtUBi1ob.mjs → prompts-wFEGsPZt.mjs} +2 -2
  33. package/dist/{prompts-BtUBi1ob.mjs.map → prompts-wFEGsPZt.mjs.map} +1 -1
  34. package/dist/{rolldown-runtime-BeIFeoWC.mjs → rolldown-runtime-DzFISCwE.mjs} +1 -1
  35. package/dist/{run-plugins-lLfcDAbT.mjs → run-plugins-ByRyAAZe.mjs} +41 -41
  36. package/dist/run-plugins-ByRyAAZe.mjs.map +1 -0
  37. package/dist/{typegen-DLdD6SMm.mjs → typegen-BfOYvlWo.mjs} +4 -4
  38. package/dist/{typegen-yk3CJH18.mjs → typegen-Bx2IQ-w5.mjs} +5 -5
  39. package/dist/{typegen-yk3CJH18.mjs.map → typegen-Bx2IQ-w5.mjs.map} +1 -1
  40. package/dist/{types-HQhLYWkB.mjs → types-dUiZnaWm.mjs} +1 -1
  41. package/package.json +3 -3
  42. package/dist/fullstack-D_OHhyZX.mjs.map +0 -1
  43. package/dist/project-D-8rOQYi.mjs.map +0 -1
  44. package/dist/project-docs-B6XKHBMO.mjs.map +0 -1
  45. package/dist/run-plugins-lLfcDAbT.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-DdYD7xPw.mjs","names":[],"sources":["../src/generators/templates/project-app.ts","../src/utils/shell.ts","../src/generators/templates/project-config.ts","../src/commands/add.ts","../src/generators/project.ts"],"sourcesContent":["type ProjectTemplate = 'rest' | 'minimal'\nexport type ProjectRuntime = 'express' | 'fastify' | 'h3'\n\n/** Per-runtime import source + factory name for the scaffolded `runtime:` option. */\nconst RUNTIME_FACTORY: Record<ProjectRuntime, { from: string; name: string }> = {\n express: { from: '@forinda/kickjs', name: 'expressRuntime' },\n fastify: { from: '@forinda/kickjs/fastify', name: 'fastifyRuntime' },\n h3: { from: '@forinda/kickjs/h3', name: 'h3Runtime' },\n}\n\n/**\n * Generate src/index.ts entry file with template-specific bootstrap.\n *\n * The runtime is always emitted explicitly (`runtime: expressRuntime()` etc.)\n * so the entry file is self-documenting and switching engines is a one-line\n * edit. Fastify / h3 parse bodies natively, so the REST template skips the\n * `express.json()` middleware (and the `express` import) under those engines.\n *\n * All templates export the app for the Vite plugin (dev mode).\n */\nexport function generateEntryFile(\n name: string,\n template: ProjectTemplate,\n version: string,\n packages: string[] = [],\n runtime: ProjectRuntime = 'express',\n /**\n * When set, wire `SpaAdapter` at this `clientDir`. Used by the fullstack\n * template so `web/`'s build is served from the API's origin in\n * production. The adapter no-ops while the directory does not exist, so a\n * dev run (where the SPA is served by Vite) is unaffected.\n */\n spaClientDir?: string,\n): string {\n const factory = RUNTIME_FACTORY[runtime]\n const isExpress = runtime === 'express'\n\n switch (template) {\n case 'minimal': {\n const imports: string[] = []\n const adapters: string[] = []\n\n // The runtime factory comes from the core package for Express, or a\n // subpath for Fastify / h3.\n const kickImport = isExpress\n ? `import { bootstrap, ${factory.name} } from '@forinda/kickjs'`\n : `import { bootstrap } from '@forinda/kickjs'\\nimport { ${factory.name} } from '${factory.from}'`\n\n if (packages.includes('swagger')) {\n imports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`)\n adapters.push(` SwaggerAdapter({ info: { title: '${name}', version: '${version}' } }),`)\n }\n if (packages.includes('devtools')) {\n imports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`)\n adapters.push(` DevToolsAdapter(),`)\n }\n if (spaClientDir) {\n imports.push(`import { SpaAdapter } from '@forinda/kickjs/spa'`)\n // JSON.stringify, not a quoted template hole: this is arbitrary\n // caller-supplied path text being written into a TypeScript file, and\n // a quote, backslash, or newline in it would either break the emitted\n // module or quietly change the path it resolves. The raw value stays\n // out of the comment for the same reason.\n adapters.push(\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(spaClientDir)} }),`,\n )\n }\n const importsBlock = imports.length ? imports.join('\\n') + '\\n' : ''\n const adaptersBlock = adapters.length ? `,\\n adapters: [\\n${adapters.join('\\n')}\\n ]` : ''\n\n return `import 'reflect-metadata'\n// Side-effect import — registers the extended env schema with kickjs\n// **before** any controller / service / @Value gets resolved. Without\n// this line ConfigService.get('YOUR_KEY') returns undefined because the\n// cached schema would still be the base shape. See guide/configuration.\nimport './config'\n${kickImport}\n${importsBlock}import { modules } from './modules'\n\n// Export the app for the Vite plugin (dev mode)\nexport const app = await bootstrap({ modules, runtime: ${factory.name}()${adaptersBlock} })\n`\n }\n\n case 'rest':\n default: {\n // Build adapters based on user-selected packages\n const restImports: string[] = []\n const restAdapters: string[] = []\n\n if (packages.includes('devtools')) {\n restImports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`)\n restAdapters.push(` DevToolsAdapter(),`)\n }\n if (packages.includes('swagger')) {\n restImports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`)\n restAdapters.push(\n ` SwaggerAdapter({\\n info: { title: '${name}', version: '${version}' },\\n }),`,\n )\n }\n const restImportsBlock = restImports.length ? restImports.join('\\n') + '\\n' : ''\n const restAdaptersBlock = restAdapters.length\n ? `\\n adapters: [\\n${restAdapters.join('\\n')}\\n ],`\n : ''\n\n // Express needs `express.json()` for body parsing; Fastify / h3 parse\n // bodies natively, so adding it would consume the body stream twice.\n const kickNamed = ['bootstrap', 'requestId', 'requestLogger', 'helmet', 'cors']\n if (isExpress) kickNamed.push(factory.name)\n const kickImport = isExpress\n ? `import express from 'express'\\nimport {\\n ${kickNamed.join(',\\n ')},\\n} from '@forinda/kickjs'`\n : `import {\\n ${kickNamed.join(',\\n ')},\\n} from '@forinda/kickjs'\\nimport { ${factory.name} } from '${factory.from}'`\n const bodyParserLine = isExpress ? `\\n express.json(),` : ''\n\n return `import 'reflect-metadata'\n// Side-effect import — registers the extended env schema with kickjs\n// **before** any controller / service / @Value gets resolved. Without\n// this line ConfigService.get('YOUR_KEY') returns undefined because the\n// cached schema would still be the base shape. See guide/configuration.\nimport './config'\n${kickImport}\n${restImportsBlock}import { modules } from './modules'\n\n// Export the app for the Vite plugin (dev mode)\nexport const app = await bootstrap({\n modules,\n runtime: ${factory.name}(),${restAdaptersBlock}\n middlewares: [\n // Security headers. The framework injects helmet() with these defaults\n // anyway — declaring it here is what lets you CHANGE them, e.g.\n // helmet({ frameguard: 'SAMEORIGIN' }) or helmet({ hsts: false }).\n // Auto-injection stands down as soon as this line is present.\n helmet(),\n cors({ origin: '*' }),\n requestId(),\n requestLogger(),${bodyParserLine}\n ],\n})\n`\n }\n }\n}\n\n/** Generate src/modules/index.ts module registry */\nexport function generateModulesIndex(): string {\n return `import { defineModules } from '@forinda/kickjs'\nimport { HelloModule } from './hello/hello.module'\n\n// Remove HelloModule and run: kick g module <name>\n// \\`defineModules()\\` returns a chainable list — \\`kick g module\\` appends\n// \\`.mount(NewModule())\\` to the chain on every generation.\nexport const modules = defineModules().mount(HelloModule())\n`\n}\n\n/**\n * Generate `src/config/index.ts` — the project's typed env schema.\n *\n * Default-exports a `defineEnv(...)` schema so `kick typegen` can\n * infer it into the global `KickEnv` registry, and *also* calls\n * `loadEnvFromSchema(envSchema)` as a module-load side effect so `ConfigService`\n * and `@Value()` see the extended shape from the very first DI\n * resolution. The companion `src/index.ts` template adds\n * `import './config'` immediately after `reflect-metadata` so the\n * registration runs before `bootstrap()` constructs anything.\n *\n * After typegen runs:\n *\n * @Value('DATABASE_URL') private url!: Env<'DATABASE_URL'>\n * process.env.DATABASE_URL // typed as string\n *\n * Both autocomplete and type-check at compile time.\n */\nexport function generateEnvFile(schemaLib: 'zod' | 'valibot' | 'yup' = 'zod'): string {\n if (schemaLib === 'valibot') {\n return `import { loadEnvFromSchema } from '@forinda/kickjs/config'\nimport { fromValibot } from '@forinda/kickjs-schema/valibot'\nimport * as v from 'valibot'\n\n/**\n * Project environment schema (Valibot).\n *\n * \\`fromValibot\\` wraps the Valibot schema as a \\`KickSchema\\` so the\n * env loader, validate middleware, and swagger spec generator all see\n * the same shape. The default export is the contract \\`kick typegen\\`\n * reads to populate \\`KickEnv\\` via \\`InferSchemaOutput<typeof _envSchema>\\`\n * — that's what makes \\`@Value('FOO')\\` autocomplete and\n * \\`process.env.FOO\\` typed.\n *\n * @example\n * DATABASE_URL: v.pipe(v.string(), v.url()),\n * JWT_SECRET: v.pipe(v.string(), v.minLength(32)),\n * REDIS_URL: v.optional(v.pipe(v.string(), v.url())),\n */\nconst envSchema = fromValibot(\n v.object({\n PORT: v.optional(v.pipe(v.string(), v.transform(Number)), '3000'),\n NODE_ENV: v.optional(v.picklist(['development', 'production', 'test']), 'development'),\n LOG_LEVEL: v.optional(v.string(), 'info'),\n // DATABASE_URL: v.pipe(v.string(), v.url()),\n }),\n)\n\n/**\n * IMPORTANT — side effect: register the schema with kickjs's env cache\n * **at module-load time**. \\`ConfigService\\` and \\`@Value()\\` both consume\n * this cache, and they will fall back to the base schema (or undefined)\n * if no extended schema has been registered before they're resolved.\n *\n * As long as \\`src/index.ts\\` imports this file (\\`import './config'\\`) at\n * the top — before \\`bootstrap()\\` runs — every controller and service\n * in the app sees the typed extended values.\n */\nexport const env = loadEnvFromSchema(envSchema)\n\nexport default envSchema\n`\n }\n\n if (schemaLib === 'yup') {\n return `import { loadEnvFromSchema } from '@forinda/kickjs/config'\nimport { fromYup } from '@forinda/kickjs-schema/yup'\nimport * as yup from 'yup'\n\n/**\n * Project environment schema (Yup).\n *\n * \\`fromYup\\` wraps the Yup schema as a \\`KickSchema\\` so the env loader,\n * validate middleware, and swagger spec generator all see the same\n * shape. The default export is the contract \\`kick typegen\\` reads to\n * populate \\`KickEnv\\` via \\`InferSchemaOutput<typeof _envSchema>\\`.\n *\n * Note: Yup's \\`.url()\\` defaults to http/https; database connection\n * strings like \\`postgres://\\` use \\`.matches(/^[a-z]+:\\\\/\\\\/.+/i)\\` or\n * a plain \\`.string().required()\\`.\n *\n * @example\n * DATABASE_URL: yup.string().required(),\n * JWT_SECRET: yup.string().min(32).required(),\n * REDIS_URL: yup.string().url().optional(),\n */\nconst envSchema = fromYup(\n yup.object({\n PORT: yup.number().default(3000),\n NODE_ENV: yup\n .string()\n .oneOf(['development', 'production', 'test'])\n .default('development'),\n LOG_LEVEL: yup.string().default('info'),\n // DATABASE_URL: yup.string().required(),\n }),\n)\n\n/**\n * IMPORTANT — side effect: register the schema with kickjs's env cache\n * **at module-load time**. \\`ConfigService\\` and \\`@Value()\\` both consume\n * this cache, and they will fall back to the base schema (or undefined)\n * if no extended schema has been registered before they're resolved.\n *\n * As long as \\`src/index.ts\\` imports this file (\\`import './config'\\`) at\n * the top — before \\`bootstrap()\\` runs — every controller and service\n * in the app sees the typed extended values.\n */\nexport const env = loadEnvFromSchema(envSchema)\n\nexport default envSchema\n`\n }\n\n // zod (default)\n return `import { loadEnvFromSchema } from '@forinda/kickjs/config'\nimport { fromZod } from '@forinda/kickjs-schema/zod'\nimport { z } from 'zod'\n\n/**\n * Project environment schema (Zod).\n *\n * \\`fromZod\\` wraps the Zod schema as a \\`KickSchema\\` so the env loader,\n * validate middleware, and swagger spec generator all see the same\n * shape. The default export is the contract \\`kick typegen\\` reads to\n * populate \\`KickEnv\\` via \\`InferSchemaOutput<typeof _envSchema>\\` —\n * that's what makes \\`@Value('FOO')\\` autocomplete and\n * \\`process.env.FOO\\` typed.\n *\n * @example\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * REDIS_URL: z.string().url().optional(),\n */\nconst envSchema = fromZod(\n z.object({\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n // DATABASE_URL: z.string().url(),\n }),\n)\n\n/**\n * IMPORTANT — side effect: register the schema with kickjs's env cache\n * **at module-load time**. \\`ConfigService\\` and \\`@Value()\\` both consume\n * this cache, and they will fall back to the base schema (or undefined)\n * if no extended schema has been registered before they're resolved.\n *\n * As long as \\`src/index.ts\\` imports this file (\\`import './config'\\`) at\n * the top — before \\`bootstrap()\\` runs — every controller and service\n * in the app sees the typed extended values.\n */\nexport const env = loadEnvFromSchema(envSchema)\n\nexport default envSchema\n`\n}\n\n/** Generate src/modules/hello/hello.service.ts */\nexport function generateHelloService(): string {\n return `import { Service } from '@forinda/kickjs'\n\n@Service()\nexport class HelloService {\n greet(name: string) {\n return { message: \\`Hello \\${name} from KickJS!\\`, timestamp: new Date().toISOString() }\n }\n\n healthCheck() {\n return { status: 'ok', uptime: process.uptime() }\n }\n}\n`\n}\n\n/** Generate src/modules/hello/hello.controller.ts */\nexport function generateHelloController(): string {\n return `import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'\nimport { HelloService } from './hello.service'\n\n// \\`Ctx<KickRoutes.HelloController['<method>']>\\` is generated by\n// \\`kick typegen\\` (auto-run on \\`kick dev\\`). The first run after a fresh\n// scaffold creates \\`.kickjs/types/routes.ts\\` so this file typechecks.\n// See https://kickjs.app/guide/typegen.\n\n@Controller()\nexport class HelloController {\n @Autowired() private readonly helloService!: HelloService\n\n // Return-value handlers: the runtime sends the returned payload as\n // 200 json, and \\`kick typegen\\` infers the response type into\n // \\`KickRoutes.Api\\` — which is what makes the typed client\n // (@forinda/kickjs-client) end-to-end type-safe.\n @Get('/')\n index(_ctx: Ctx<KickRoutes.HelloController['index']>) {\n return this.helloService.greet('World')\n }\n\n @Get('/health')\n health(_ctx: Ctx<KickRoutes.HelloController['health']>) {\n return this.helloService.healthCheck()\n }\n}\n`\n}\n\n/** Generate src/modules/hello/hello.module.ts */\nexport function generateHelloModule(): string {\n return `import { defineModule } from '@forinda/kickjs'\nimport { HelloController } from './hello.controller'\n\nexport const HelloModule = defineModule({\n name: 'HelloModule',\n build: () => ({\n // \\`register(container)\\` is optional — only implement it when you need\n // to bind a token to a concrete implementation, e.g.\n // register(container) {\n // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))\n // }\n // The HelloService uses @Service() so the decorator handles registration.\n\n routes() {\n return {\n path: '/hello',\n controller: HelloController,\n }\n },\n }),\n})\n`\n}\n\n/** Generate kick.config.ts CLI configuration */\nexport function generateKickConfig(\n template: ProjectTemplate,\n defaultRepo: string = 'inmemory',\n packageManager: 'pnpm' | 'npm' | 'yarn' | 'bun' = 'pnpm',\n runtime: 'express' | 'fastify' | 'h3' = 'express',\n /** Emit the client route map — set for scaffolds whose frontend reads it. */\n withClientMap = false,\n): string {\n // `inmemory` is the only built-in; every other name (incl. the\n // deprecated prisma/drizzle) is emitted as a `{ name }` custom repo.\n const repoValue = defaultRepo === 'inmemory' ? `'inmemory'` : `{ name: '${defaultRepo}' }`\n\n return `import { defineConfig } from '@forinda/kickjs-cli'\n\nexport default defineConfig({\n pattern: '${template}',\n // The HTTP engine this app boots on (matches \\`bootstrap({ runtime })\\` in\n // src/index.ts). Dep-aware commands read it: \\`kick add upload\\` installs the\n // engine's multipart driver, \\`kick doctor\\` checks the engine peers, and\n // \\`kick typegen\\` flips the runtime escape-hatch types to this engine.\n runtime: '${runtime}',\n // Pinned so \\`kick add\\` and other dep-installing commands always use the\n // project's intended package manager, regardless of which lockfile exists.\n packageManager: '${packageManager}',\n modules: {\n dir: 'src/modules',\n repo: ${repoValue},\n pluralize: true,\n },\n\n // \\`kick typegen\\` populates \\`.kickjs/types/\\` so \\`Ctx<KickRoutes.X['method']>\\`\n // resolves to fully-typed params/body/query. Auto-runs on \\`kick dev\\`.\n // \\`'kickjs-schema'\\` routes inference through \\`InferSchemaOutput\\` so the\n // typegen works for any wrapped schema (Zod / Valibot / Yup). Switch\n // to \\`'zod'\\` if you ship Zod schemas without \\`fromZod()\\` wrapping, or\n // set \\`schemaValidator: false\\` to skip schema-driven body typing.\n typegen: {\n schemaValidator: 'kickjs-schema',${\n withClientMap\n ? `\n // web/ reads this map from the ambient KickClientApi namespace. Producing\n // it builds a TypeScript program over the server, so it stays off unless a\n // project actually consumes it.\n client: true,`\n : ''\n }\n },\n\n commands: [\n {\n name: 'test',\n description: 'Run tests with Vitest',\n steps: 'vitest run',\n },\n {\n name: 'lint',\n description: 'Lint with oxlint',\n steps: 'oxlint src/',\n },\n {\n name: 'format',\n description: 'Format code with oxfmt',\n steps: 'oxfmt src/',\n },\n {\n name: 'format:check',\n description: 'Check formatting without writing',\n steps: 'oxfmt --check src/',\n },\n {\n name: 'ci:check',\n description: 'Run typecheck + lint + format check',\n steps: ['kick typecheck', 'oxlint src/', 'oxfmt --check src/'],\n aliases: ['verify'],\n },\n ],\n})\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","type ProjectTemplate = 'rest' | 'minimal'\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'\nimport type { SchemaLib } from '../../config'\n\n/** Map of optional package names to their npm package identifiers */\nconst PACKAGE_DEPS: Record<string, string> = {\n swagger: '@forinda/kickjs-swagger',\n ws: '@forinda/kickjs-ws',\n queue: '@forinda/kickjs-queue',\n devtools: '@forinda/kickjs-devtools',\n}\n\n/**\n * Schema-lib runtime dependency ranges. Pinned to a recent release.\n *\n * Exactly one of these is installed, chosen by `--schema`; `zod` is the `--yes`\n * default for its ecosystem reach (OpenAPI generation, the Standard Schema\n * brand `kick typegen` reads). Whichever lands here is what `resolveSchemaLib`\n * later detects when generating DTO schemas.\n */\nconst SCHEMA_LIB_NAMES: Record<SchemaLib, string> = {\n zod: 'zod',\n valibot: 'valibot',\n yup: 'yup',\n}\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 sibling\n * `@forinda/kickjs-*` package we might add to the new project must\n * 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 in generators/project.ts.`,\n )\n }\n return v\n}\n\n/** Generate package.json with template-aware dependencies */\nexport function generatePackageJson(\n name: string,\n template: ProjectTemplate,\n versions: SiblingVersions,\n packages: string[] = [],\n schemaLib: SchemaLib = 'zod',\n runtime: 'express' | 'fastify' | 'h3' = 'express',\n /**\n * Pin the TypeScript 7 compiler API, needed to resolve the client route map\n * (`.kickjs/types/kick__client.d.ts`). Set by the fullstack generator, whose\n * web app reads that map from the ambient `KickClientApi` namespace.\n *\n * Deliberately a flag rather than `template === 'fullstack'`: the fullstack\n * workspace scaffolds its SERVER with `template: 'minimal'`, so keying off\n * the template name silently pinned nothing.\n */\n withClientMap = false,\n): string {\n const schemaLibName = SCHEMA_LIB_NAMES[schemaLib]\n const baseDeps: Record<string, string> = {\n '@forinda/kickjs': take(versions, '@forinda/kickjs'),\n // The schema-agnostic abstraction kickjs-schema wraps zod / valibot\n // / yup behind a single `KickSchema` interface — env validation,\n // body validation, and swagger spec generation all flow through\n // `detectSchema()`. Shipping it as a direct dep (rather than a peer)\n // keeps the new-project install one-step.\n '@forinda/kickjs-schema': take(versions, '@forinda/kickjs-schema'),\n // `dotenv` is an optional peer of @forinda/kickjs — scaffolded apps\n // get it pre-installed so `.env` files Just Work. Apps that load\n // env from the shell or a secret manager can drop this safely.\n dotenv: take(versions, 'dotenv'),\n 'reflect-metadata': take(versions, 'reflect-metadata'),\n [schemaLibName]: take(versions, schemaLibName),\n }\n\n // Engine peers for the chosen runtime (optional peers of @forinda/kickjs).\n if (runtime === 'express') {\n // Express is the engine itself.\n baseDeps.express = take(versions, 'express')\n } else if (runtime === 'fastify') {\n baseDeps.fastify = take(versions, 'fastify')\n baseDeps['@fastify/middie'] = take(versions, '@fastify/middie')\n // Static serving uses `serve-static` (no express dependency).\n baseDeps['serve-static'] = take(versions, 'serve-static')\n } else if (runtime === 'h3') {\n baseDeps.h3 = take(versions, 'h3')\n baseDeps['serve-static'] = take(versions, 'serve-static')\n }\n\n // Add user-selected optional packages — each looked up against\n // the resolved version map so they're independently up-to-date.\n for (const pkg of packages) {\n const dep = PACKAGE_DEPS[pkg]\n if (dep && !baseDeps[dep]) {\n baseDeps[dep] = take(versions, dep)\n }\n }\n\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: baseDeps,\n devDependencies: {\n '@forinda/kickjs-cli': take(versions, '@forinda/kickjs-cli'),\n // The generated AGENTS.md and the `write-controller-test` skill both\n // tell you to test with `createTestApp` + supertest. Shipping those\n // instructions without the packages means the first test a reader\n // writes fails on a missing import.\n '@forinda/kickjs-testing': take(versions, '@forinda/kickjs-testing'),\n '@forinda/kickjs-vite': take(versions, '@forinda/kickjs-vite'),\n '@types/supertest': take(versions, '@types/supertest'),\n '@swc/core': take(versions, '@swc/core'),\n // Express types only when Express is the engine (it's the only runtime\n // that imports `express` in src/index.ts).\n ...(runtime === 'express' ? { '@types/express': take(versions, '@types/express') } : {}),\n '@types/node': take(versions, '@types/node'),\n 'unplugin-swc': take(versions, 'unplugin-swc'),\n vite: take(versions, 'vite'),\n supertest: take(versions, 'supertest'),\n vitest: take(versions, 'vitest'),\n typescript: take(versions, 'typescript'),\n // Only scaffolds that consume the client route map pin the TypeScript 7\n // compiler API: it is a 10 kB shim over a 24 MB `typescript@6`, which is\n // not something to put in every project. Today that means fullstack,\n // whose web app reads the map from the ambient `KickClientApi`\n // namespace. rest/minimal have no frontend and stay lean.\n ...(withClientMap\n ? { '@typescript/typescript6': take(versions, '@typescript/typescript6') }\n : {}),\n oxfmt: take(versions, 'oxfmt'),\n oxlint: take(versions, 'oxlint'),\n },\n },\n null,\n 2,\n )\n}\n\n/**\n * Generate vite.config.ts with the KickJS Vite plugin.\n *\n * The plugin handles:\n * - SSR environment setup for backend Node.js code\n * - Virtual module generation (virtual:kickjs/app)\n * - Module auto-discovery (scans *.module.ts files)\n * - HMR with selective container invalidation\n * - Express mounting via configureServer() post-hook\n * - httpServer piping to adapters (WsAdapter, Socket.IO, etc.)\n */\nexport function generateViteConfig(options: { strictPort?: boolean } = {}): string {\n // The fullstack web app proxies /api to a fixed port. Without strictPort,\n // Vite moves to the next free port when that one is taken and the proxy\n // silently talks to whatever else holds it; with it, `kick dev` fails loudly.\n const server = options.strictPort\n ? ` server: {\n // web/vite.config.ts proxies /api to this port — fail instead of moving\n // to another port when it's taken, or the proxy would reach the wrong process.\n strictPort: true,\n },\n`\n : ''\n return `import { defineConfig } from 'vite'\nimport { fileURLToPath } from 'node:url'\nimport swc from 'unplugin-swc'\nimport { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'\n\nexport default defineConfig({\n oxc: false,\n plugins: [\n swc.vite(),\n kickjsVitePlugin({ entry: 'src/index.ts' }),\n // Watches .env files and triggers a full reload on change so the\n // dev server picks up env tweaks without a manual restart.\n envWatchPlugin(),\n ],\n${server} resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n },\n },\n build: {\n target: 'node20',\n ssr: true,\n outDir: 'dist',\n sourcemap: true,\n rollupOptions: {\n input: fileURLToPath(new URL('./src/index.ts', import.meta.url)),\n output: { format: 'esm' },\n },\n },\n})\n`\n}\n\n/**\n * `netlify.toml` for `kick build:netlify`.\n *\n * Netlify publishes a directory whatever else happens: with a frontend that\n * is its build, and without one it must be an empty directory the build\n * creates — otherwise Netlify serves the project's own files as static\n * content, and those shadow the function.\n */\nexport function generateNetlifyToml(options: {\n command: string\n publish: string\n spa: boolean\n}): string {\n const redirect = options.spa\n ? `\n# Client-side routes fall back to the app shell. The function claims /api/*\n# through its own \\`config.path\\`, so this rule never sees those requests.\n[[redirects]]\n from = \"/*\"\n to = \"/index.html\"\n status = 200\n`\n : ''\n return `[build]\n command = \"${options.command}\"\n publish = \"${options.publish}\"\n\n[build.environment]\n NODE_VERSION = \"22\"\n${redirect}`\n}\n\n/**\n * `vercel.json` for a Git-connected project. `framework: null` keeps Vercel\n * from treating the repo as a plain Vite app; the build writes\n * `.vercel/output`, which Vercel then deploys as-is.\n */\nexport function generateVercelJson(buildCommand: string): string {\n return `${JSON.stringify(\n {\n $schema: 'https://openapi.vercel.sh/vercel.json',\n framework: null,\n buildCommand,\n },\n null,\n 2,\n )}\\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/** Generate tsconfig.json with decorator support */\nexport function generateTsConfig(): string {\n return JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'bundler',\n lib: ['ES2022'],\n types: ['node', 'vite/client'],\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n sourceMap: true,\n declaration: true,\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n outDir: 'dist',\n // rootDir omitted so .kickjs/types/*.d.ts can sit outside src/\n paths: { '@/*': ['./src/*'] },\n },\n // .kickjs/types is generated by `kick typegen` and refreshed\n // automatically on `kick dev`. Including it here makes\n // `container.resolve()` and module discovery type-safe.\n // Both .d.ts and .ts are matched: registry/services/modules are\n // declarations, but routes.ts holds resolvable imports from your\n // controllers' Zod schemas (TS silently degrades inline `import('...')`\n // inside `.d.ts` files under `moduleResolution: 'bundler'`).\n include: ['src', '.kickjs/types/**/*.d.ts', '.kickjs/types/**/*.ts'],\n },\n null,\n 2,\n )\n}\n\n/**\n * Generate `.oxfmtrc.json`.\n *\n * oxfmt over prettier: same options, same output for these settings, one\n * binary instead of a package plus plugins — and it is what the framework\n * itself is formatted with, so a scaffold no longer arrives holding a\n * different tool than the project it came from.\n *\n * There is no `format` script. `pnpm exec oxfmt` is the command, and a\n * scaffold that opens with ten aliases teaches less than one that shows the\n * tools.\n */\nexport function generateFormatterConfig(): string {\n return JSON.stringify(\n {\n $schema: './node_modules/oxfmt/configuration_schema.json',\n semi: false,\n singleQuote: true,\n trailingComma: 'all',\n printWidth: 100,\n tabWidth: 2,\n ignorePatterns: ['**/dist/', '**/.kickjs/', '**/node_modules/'],\n },\n null,\n 2,\n )\n}\n\n/** Generate .editorconfig for consistent editor settings */\nexport function generateEditorConfig(): string {\n return `# https://editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.md]\ntrim_trailing_whitespace = false\n`\n}\n\n/** Generate .gitignore with common Node.js patterns */\nexport function generateGitIgnore(): string {\n return `node_modules/\ndist/\n.env\n# Machine-specific: each developer's test env differs (database names, ports).\n# The shared template is the committed \\`.env.test.example\\`.\n.env.test\n*.local\ncoverage/\n.DS_Store\n*.tsbuildinfo\n.kickjs/\n# Platform build output — written by \\`kick build:netlify\\` / \\`kick build:vercel\\`.\n.netlify/\n.vercel/\n`\n}\n\n/** Generate .gitattributes for consistent line endings */\nexport function generateGitAttributes(): string {\n return `# Auto-detect text files and normalise line endings to LF\n* text=auto eol=lf\n\n# Explicitly mark generated / binary files\n*.png binary\n*.jpg binary\n*.jpeg binary\n*.gif binary\n*.ico binary\n*.woff binary\n*.woff2 binary\n*.ttf binary\n*.eot binary\n\n# Lock files — treat as generated\npnpm-lock.yaml -diff linguist-generated\nyarn.lock -diff linguist-generated\npackage-lock.json -diff linguist-generated\n`\n}\n\n/** Generate .env file with default environment variables */\nexport function generateEnv(): string {\n return `PORT=3000\nNODE_ENV=development\n`\n}\n\n/** Generate .env.example file as a template */\nexport function generateEnvExample(): string {\n return `PORT=3000\nNODE_ENV=development\n`\n}\n\n/**\n * Generate `.env.test` — the environment the test suite runs against.\n *\n * Under a test run KickJS reads this file INSTEAD of `.env` (no layering,\n * no fallback), so scaffolding it is what makes a new project isolated by\n * default rather than inheriting the developer's environment.\n *\n * Deliberately NOT a copy of `.env.example`. The point of the file is that\n * a var it omits is *missing* rather than quietly inherited, so the suite\n * fails loudly on something it forgot to declare. Copying every key back\n * in would rebuild the exact trap this closes.\n *\n * `PORT=0` asks the OS for a free port, so a test run cannot collide with\n * a dev server already on 3000.\n *\n * Gitignored, like `.env`: values differ per machine, and a committed copy\n * turns every local tweak into a diff for the whole team. The shared\n * template is {@link generateEnvTestExample}.\n */\nexport function generateEnvTest(): string {\n return `# Read INSTEAD of .env when NODE_ENV=test (or under vitest).\n# No fallback to .env — declare here everything the suite needs, so a\n# missing var fails the run instead of silently resolving to your dev value.\n#\n# Not committed. Add new keys to .env.test.example too, with placeholder\n# values — never real endpoints or credentials.\nNODE_ENV=test\nPORT=0\nLOG_LEVEL=silent\n`\n}\n\n/** Generate `.env.test.example` — the committed template a fresh clone copies to `.env.test`. */\nexport function generateEnvTestExample(): string {\n return `# Template for .env.test. Copy it and fill in your machine's values:\n# cp .env.test.example .env.test\n${generateEnvTest()}`\n}\n\n/** Generate vitest.config.ts for test configuration */\nexport function generateVitestConfig(): string {\n return `import { defineConfig, mergeConfig } from 'vitest/config'\nimport viteConfig from './vite.config.ts'\n\n// A \\`vitest.config.ts\\` OVERRIDES \\`vite.config.ts\\` outright — vitest does not\n// merge the two, and it never reads tsconfig \\`paths\\`. Restating settings here\n// would mean the \\`@\\` alias lives in three files and drifts in two of them, so\n// merge the real config instead: the alias, plugins, and ssr externals all come\n// from one place.\nexport default mergeConfig(\n viteConfig,\n defineConfig({\n test: {\n globals: true,\n environment: 'node',\n include: ['src/**/*.test.ts'],\n },\n }),\n)\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'\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 /**\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 description: 'kick/db + PostgreSQL driver (use @forinda/kickjs-db/pg)',\n },\n sqlite: {\n pkg: '@forinda/kickjs-db',\n peers: ['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 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/sdk'],\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 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 .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 { prodDeps, devDeps, unknown, warnings, notices } = planAddPackages(\n packages,\n Boolean(opts.dev),\n runtime,\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)\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 // 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 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 console.log(`\\n Installation failed. Run manually:\\n ${cmd}\\n`)\n }\n }\n\n console.log(' Done!\\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 { captureCommand, captureCommandAsync } from '../utils/shell'\nimport {\n generatePackageJson,\n generateViteConfig,\n generateTsConfig,\n generateFormatterConfig,\n generateEditorConfig,\n generateGitIgnore,\n generateGitAttributes,\n generateEnv,\n generateEnvExample,\n generateEnvTest,\n generateEnvTestExample,\n generateVitestConfig,\n generateNetlifyToml,\n generateVercelJson,\n} from './templates/project-config'\nimport {\n generateEntryFile,\n generateEnvFile,\n generateModulesIndex,\n generateKickConfig,\n generateHelloService,\n generateHelloController,\n generateHelloModule,\n} from './templates/project-app'\nimport { generateReadme } from './templates/project-docs'\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 */\nconst 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 */\nconst 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 dotenv: { fallback: '^17.3.1' },\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}\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 /** Pin the compiler API + generate the client route map (fullstack). */\n withClientMap?: boolean\n /** Fail `kick dev` when its port is taken instead of moving (fullstack's /api proxy needs the port). */\n strictPort?: boolean\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 */\nexport async function initProject(options: InitProjectOptions): Promise<void> {\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 // ── package.json — template-aware deps ────────────────────────────\n await writeFileSafe(\n join(dir, 'package.json'),\n generatePackageJson(\n name,\n template,\n versions,\n packages,\n schemaLib,\n runtime,\n options.withClientMap,\n ),\n )\n\n // ── vite.config.ts — enables HMR + SWC for decorators ──────────────\n await writeFileSafe(\n join(dir, 'vite.config.ts'),\n generateViteConfig({ strictPort: options.strictPort }),\n )\n\n // ── tsconfig.json ───────────────────────────────────────────────────\n await writeFileSafe(join(dir, 'tsconfig.json'), generateTsConfig())\n\n // ── .oxfmtrc.json ───────────────────────────────────────────────────\n await writeFileSafe(join(dir, '.oxfmtrc.json'), generateFormatterConfig())\n\n // ── .editorconfig ─────────────────────────────────────────────────────\n await writeFileSafe(join(dir, '.editorconfig'), generateEditorConfig())\n\n // ── .gitignore ──────────────────────────────────────────────────────\n await writeFileSafe(join(dir, '.gitignore'), generateGitIgnore())\n\n // ── .gitattributes ────────────────────────────────────────────────────\n await writeFileSafe(join(dir, '.gitattributes'), generateGitAttributes())\n\n // ── .env ────────────────────────────────────────────────────────────\n await writeFileSafe(join(dir, '.env'), generateEnv())\n\n await writeFileSafe(join(dir, '.env.example'), generateEnvExample())\n\n // `.env.test` is read INSTEAD of `.env` under a test run, so scaffolding\n // it is what makes a new project isolated by default. Without it the\n // generated app ships the exact shape `kick doctor` warns about — a\n // `.env` plus a test runner — and its first test run prints the backfill\n // warning rather than being isolated. It is gitignored like `.env` —\n // values differ per machine — so the committed template is the example.\n await writeFileSafe(join(dir, '.env.test'), generateEnvTest())\n await writeFileSafe(join(dir, '.env.test.example'), generateEnvTestExample())\n\n // ── src/config/index.ts — typed env schema (read by `kick typegen`) ─\n // Lives under `src/config/` so the framework's \"config\" concept has a\n // single, conventional home. Old projects with `src/env.ts` still\n // work — `detectEnvFile()` searches both locations.\n await writeFileSafe(join(dir, 'src/config/index.ts'), generateEnvFile(schemaLib))\n\n // ── src/index.ts — template-aware entry point ─────────────────────\n await writeFileSafe(\n join(dir, 'src/index.ts'),\n generateEntryFile(name, template, cliPkg.version, packages, runtime, options.spaClientDir),\n )\n\n // ── src/modules/index.ts ────────────────────────────────────────────\n await writeFileSafe(join(dir, 'src/modules/index.ts'), generateModulesIndex())\n\n // ── src/modules/hello/ — sample module ─────────────────────────────\n await writeFileSafe(join(dir, 'src/modules/hello/hello.service.ts'), generateHelloService())\n await writeFileSafe(join(dir, 'src/modules/hello/hello.controller.ts'), generateHelloController())\n await writeFileSafe(join(dir, 'src/modules/hello/hello.module.ts'), generateHelloModule())\n\n // ── kick.config.ts — CLI configuration ─────────────────────────────\n await writeFileSafe(\n join(dir, 'kick.config.ts'),\n generateKickConfig(template, defaultRepo, packageManager, runtime, options.withClientMap),\n )\n\n // ── vitest.config.ts ────────────────────────────────────────────────\n await writeFileSafe(join(dir, 'vitest.config.ts'), generateVitestConfig())\n\n // ── README.md ────────────────────────────────────────────────────────\n await writeFileSafe(join(dir, 'README.md'), generateReadme(name, template, packageManager))\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 // ── Platform deploy config ───────────────────────────────────────────\n // Inert until you connect the project to a platform; `kick build:netlify`\n // / `kick build:vercel` are what they run.\n if (options.platformConfig !== false) {\n await writeFileSafe(\n join(dir, 'netlify.toml'),\n generateNetlifyToml({\n command: `${packageManager} run build:netlify`,\n // No frontend here: the function serves every path, and this empty\n // directory exists only so Netlify has something to publish.\n publish: 'dist/public',\n spa: false,\n }),\n )\n await writeFileSafe(\n join(dir, 'vercel.json'),\n generateVercelJson(`${packageManager} run build:vercel`),\n )\n }\n\n // ── Install-script approvals ─────────────────────────────────────────\n // Before install; see approveInstallScripts.\n if (options.approveInstallScripts !== false) {\n approveInstallScripts(packageManager, dir, { ...TEMPLATE_BUILDS, ...buildsFor(packages) })\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"],"mappings":";;;;;;;;;;yZAIA,MAAM,EAA0E,CAC9E,QAAS,CAAE,KAAM,kBAAmB,KAAM,gBAAiB,EAC3D,QAAS,CAAE,KAAM,0BAA2B,KAAM,gBAAiB,EACnE,GAAI,CAAE,KAAM,qBAAsB,KAAM,WAA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,EAAQ,aAAa,EAAI,KAAK,EAAe,SAAS,EAE3D,IAAM,EAAkC,CACtC,KAAM,qBACN,QAAS,mCACX,EACA,EAAI,KAAK,EAAQ,IAAa,EAAQ,MAAM,EAC5C,EAAI,YAAY,EAChB,EAAI,EAAE,EACN,EAAI,WAAW,EACf,EAAI,4DAA4D,EAChE,EAAI,uDAAuD,EAC3D,EAAI,kDAAkD,EACtD,EAAI,EAAE,EACN,EAAI,aAAa,EACjB,EAAI,iFAAiF,EACrF,EAAI,gEAAgE,EACpE,EAAI,mDAAmD,EACvD,EAAI,8CAA8C,EAClD,EAAI,8DAA8D,EAClE,EAAI,6DAA6D,EACjE,EAAI,6DAA6D,EACjE,EAAI,8DAA8D,EAClE,EAAI,qDAAqD,EACzD,EAAI,EAAE,EACN,EAAI,eAAe,EACnB,EAAI,8DAA8D,EAClE,EAAI,yDAAyD,EAC7D,EAAI,EAAE,EACN,EAAI,cAAc,GAAwB,EAC1C,EAAI,EAAE,CACR"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.3.0
2
+ * @forinda/kickjs-cli v8.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -400,6 +400,9 @@ Each of these has a skill with the steps and the traps:
400
400
  | Write a controller test | \`kickjs-write-controller-test\` |
401
401
  | List endpoint with filters / pagination | \`kickjs-query-parsing-list-endpoint\` |
402
402
  | Serve bundled assets | \`kickjs-use-asset-manager\` |
403
+ | Flag a route (public, exempt, unmetered) | \`kickjs-route-flags\` |
404
+ | Add a kick CLI command or generator | \`kickjs-cli-plugin\` |
405
+ | Deploy to Netlify / Vercel / Cloudflare | \`kickjs-deploy\` |
403
406
  | Anything else | \`kickjs-docs-lookup\` |
404
407
 
405
408
  ## Testing Guidelines
@@ -730,7 +733,75 @@ kick g config --force --repo postgres # Drop a kick.config.ts i
730
733
  - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
731
734
  - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
732
735
  - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
733
- - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
736
+ - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`route-flags`,frontmatterName:`kickjs-route-flags`,description:`Use when a fact about a route (public, CSRF-exempt, unmetered, expose as a tool) has to be read by auth, CSRF, rate limiting, OpenAPI or MCP — instead of repeating it as paths in each consumer.`,body:"A route flag is a named, inheritable fact about a route. It carries no\nbehaviour: it records something every consumer can read, so \"this endpoint is\nopen\" is declared once instead of restated as an auth contributor, a\n`csrf ignorePaths` entry and a `rateLimit skipPaths` entry — two of which are\npathname strings that cannot express `/users/:id`.\n\n**Steps**:\n1. Declare it once, in its own module:\n ```ts\n import { defineRouteFlag } from '@forinda/kickjs'\n\n export const Public = defineRouteFlag('auth.public')\n export const Limit = defineRouteFlag<{ rpm: number }>('rate.limit')\n ```\n2. Apply it. A class flag is inherited by every route under it; `.off` on a\n method removes it:\n ```ts\n @Public // every route below inherits it\n @Controller()\n export class WebhooksController {\n @Get('/health')\n health(ctx: RequestContext) {} // public\n\n @Public.off // the method wins\n @Post('/admin')\n admin(ctx: RequestContext) {} // not public\n\n @Limit({ rpm: 10 }) // flags can carry a value\n @Post('/login')\n login(ctx: RequestContext) {}\n }\n ```\n3. Read it from the consumer that already exists, rather than a new one.\n **Where a consumer is mounted decides how it reads flags** — everything\n after route matching gets `ctx.route`; anything before it does not:\n\n | Consumer | Mounted at | Reads flags by |\n | --- | --- | --- |\n | Handler | the route itself | `ctx.route?.flags.has('auth.public')` |\n | Guard / `@Middleware()` | `@Middleware(fn)` on a method or controller class | `ctx.route`, or the built-ins' `exemptWhen` |\n | `csrfGuard()` / `rateLimitGuard()` | same — `@Middleware()`, class or method | `exemptWhen: 'csrf.exempt'` |\n | Contributor | method > class > module `contributors()` > adapter `contributors()` > `bootstrap({ contributors })` | `skipWhen` / `onlyWhen` on the registration |\n | Global middleware (`rateLimit()`) | `bootstrap({ middlewares: [...] })` — runs **before** matching | the route policy table (`bindRoutePolicy`); `ctx.route` is `undefined` here |\n | Adapter middleware | `AppAdapter.middleware()`, phase `beforeGlobal` … `afterRoutes` | the policy table — the handler is Express-style `(req, res, next)`, so there is no `ctx` in any phase |\n | OpenAPI | `SwaggerAdapter({ publicFlag: 'auth.public' })` | read once at startup, not per request |\n | MCP / AI tools | `McpAdapter({ exposeWhen: 'mcp.tool', hideWhen: 'mcp.hidden' })` | read once at startup |\n\n The contributor row is the one that buys the most: those five levels mean a\n plugin's contributor can be skipped on one route (`skipWhen`) without\n forking it, and a method-level registration beats the adapter's.\n\n4. Run `kick typegen`. It writes the `KickRouteFlags` augmentation, so flag\n names autocomplete and a typo fails `tsc` instead of silently never matching.\n\n**Red flags**:\n- Writing `@Public(false)` to remove a flag — removal is `@Public.off`. A\n resolved flag is present or absent; `false` is a legitimate *value* for a\n flag declared `boolean`, and a presence check would still answer `true`.\n- A new consumer growing its own `skipPaths` / `ignorePaths` list — that is\n the duplication flags exist to remove, and path strings break on params and\n on any `apiPrefix` change.\n- `@Public.off` on a route that never inherited the flag — a no-op, and\n usually a sign the expected class-level flag is not there.\n- Reading `ctx.route` in global middleware — it is `undefined` before a route\n is matched (steps 1-6 of the pipeline). Move the check into a guard mounted\n with `@Middleware()`, or read the policy table.\n- Inventing a flag name per consumer (`auth.open`, `public`, `isPublic`). The\n framework names none of them; pick one name per fact and reuse it."},{slug:`cli-plugin`,frontmatterName:`kickjs-cli-plugin`,description:`Use when adding a kick <name> command, a kick g <name> generator, or a typegen emitter to this project or a package it ships.`,body:"A CLI plugin contributes commands, generators and typegen emitters to the\n`kick` CLI. Every built-in command ships as one, so the contract is the same\none the framework uses.\n\n**Steps**:\n1. Write the plugin. All four contribution kinds are optional:\n ```ts\n // kick-tool.ts\n import { defineCliPlugin } from '@forinda/kickjs-cli'\n\n export const toolPlugin = (options: { watch?: boolean } = {}) =>\n defineCliPlugin({\n // Stable id, unique across plugins — it names the plugin in conflict errors.\n name: 'my-tool',\n // Declarative: same shape as kick.config.ts `commands`.\n commands: [{ name: 'db:migrate', description: 'Apply migrations', steps: 'node ./scripts/migrate.js' }],\n // Programmatic: full commander API, when you need options or subcommands.\n register(program, ctx) {\n program\n .command('my-tool')\n .description('Do the thing')\n .option('--watch', 'Watch mode')\n .action(async () => {\n ctx.log(`running in ${ctx.projectRoot}`)\n // ctx.config is the loaded kick.config.ts\n })\n },\n })\n ```\n2. Register it in `kick.config.ts`:\n ```ts\n import { toolPlugin } from './kick-tool'\n\n export default defineConfig({ plugins: [toolPlugin()] })\n ```\n3. Check it is loaded, per contribution kind: `kick --help` lists a command,\n `kick g --list` lists a generator, `kick typegen` runs an emitter. A\n plugin that fails to load takes the whole CLI down with a conflict error,\n so silence here means the config never referenced it.\n\n**Which kind to use**: `commands` for a shell one-liner, `register` for\noptions / subcommands / async work, `generators` (`defineGenerator`) for\n`kick g <name>` scaffolders, `typegens` for a file under `.kickjs/types/`.\n\n**Red flags**:\n- Confusing this with a runtime plugin: `defineCliPlugin` (from\n `@forinda/kickjs-cli`) extends the CLI; `definePlugin` (from\n `@forinda/kickjs`) hooks the running app. They share nothing.\n- Claiming a command name a built-in owns (`build:netlify`, `typegen`,\n `generate`) — duplicate declarative names are a startup conflict, and\n `register` has no conflict detection at all, so it silently loses. Namespace\n your own (`my-tool:build`).\n- Doing real work inside `register` — it runs at CLI startup for every\n command, so it must only register. Put the work in the action.\n- Importing heavy dependencies at module scope. `await import()` them inside\n the action, so an unrelated `kick dev` does not pay for them."},{slug:`deploy`,frontmatterName:`kickjs-deploy`,description:`Use when deploying this app — Netlify, Vercel or Cloudflare Workers — or when an API route returns the SPA shell, the platform build fails, or the function is missing from a deploy.`,body:`**Netlify and Vercel** run the app as a Node function; the CLI builds both:
737
+
738
+ \`\`\`bash
739
+ ${e} run build:netlify # → .netlify/v1/functions/api.mjs
740
+ ${e} run build:vercel # → .vercel/output (Build Output API v3)
741
+ \`\`\`
742
+
743
+ Both bundle \`src/serverless.ts\` (\`createHandler\`), which is a second entry
744
+ beside \`src/index.ts\` — the long-running server. Keep the shared options in
745
+ one module both import, so they cannot drift.
746
+
747
+ Settings are detected from the layout: a workspace member beside a \`web\`
748
+ package publishes \`web/dist\` and routes \`/api/*\`; a standalone API takes
749
+ every path. Override in \`kick.config.ts\`:
750
+
751
+ \`\`\`ts
752
+ export default defineConfig({
753
+ deploy: { apiPath: '/api', staticDir: '../web/dist' },
754
+ })
755
+ \`\`\`
756
+
757
+ **Cloudflare Workers** is a different entry, not a third flag on this one.
758
+ Workers have no \`node:http\`, so \`createHandler\` cannot run there; use the
759
+ web entry over h3 v2:
760
+
761
+ \`\`\`ts
762
+ // src/worker.ts
763
+ import 'reflect-metadata'
764
+ import { createFetchHandler } from '@forinda/kickjs/web'
765
+ import * as h3 from 'h3' // v2 — passed in, edge bundlers have no createRequire
766
+ import { modules } from './modules'
767
+
768
+ export default createFetchHandler((env) => ({ h3, modules, env }))
769
+ \`\`\`
770
+
771
+ Two things make or break that deploy:
772
+
773
+ 1. **Pre-bundle it yourself.** Point \`wrangler.jsonc\`'s \`main\` at a bundle
774
+ built with SWC (the same Vite + \`unplugin-swc\` setup as the other
775
+ targets), never at \`src/worker.ts\`. Wrangler's own esbuild compiles
776
+ decorators as ES decorators and emits no decorator metadata, so DI fails
777
+ at startup with a \`getOwnMetadata\` TypeError before any request lands.
778
+ 2. **\`compatibility_flags = ["nodejs_compat"]\`** — request-scoped DI and
779
+ \`ctx.set\` / \`ctx.get\` ride on \`AsyncLocalStorage\`.
780
+ 3. **Do not \`import './config'\` here.** It is required in \`src/index.ts\` and
781
+ \`src/serverless.ts\`, and wrong in a Worker twice over: the config module
782
+ reaches for \`node:fs\` / \`createRequire\`, which kills the Worker at
783
+ startup, and \`loadEnvFromSchema\` parses \`process.env\`, which Workers do
784
+ not have. The \`env\` binding threaded through \`createFetchHandler\` is what
785
+ feeds \`ConfigService.get()\` and \`@Value()\` instead — so values arrive as
786
+ the raw strings the platform holds, without the schema's coercion or
787
+ defaults. Coerce where you read them.
788
+
789
+ Not available on Workers: views, SPA/static serving, \`@Asset\`, adapters and
790
+ plugins. Serve static files from Workers Assets or a separate deploy.
791
+
792
+ **Red flags**:
793
+ - An \`/api/*\` route returning \`index.html\` on Netlify — the function is not
794
+ routed. Check the deploy summary says a function was deployed, keep
795
+ \`preferStatic\` out of its config, and leave Netlify's **Package directory**
796
+ unset so it reads the function at the repo root.
797
+ - Committing \`.netlify/\` or \`.vercel/\` — both are build output.
798
+ - A frontend that builds somewhere other than \`web/dist\` and only one of
799
+ \`deploy.staticDir\`, \`SpaAdapter({ clientDir })\` and netlify.toml's
800
+ \`publish\` updated. All three name that directory.
801
+ - Pointing a platform at \`src/index.ts\` — it calls \`bootstrap()\`, which
802
+ listens on a port and registers signal handlers inside the function.
803
+ - Expecting \`kick build\` alone to produce a deployable function; it builds
804
+ the server. Run the target command after it.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
734
805
  surface. When the answer is not in one of them, read the docs rather than
735
806
  inferring it from nearby code: a wrong guess about a framework API compiles
736
807
  fine and fails at runtime.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.3.0
2
+ * @forinda/kickjs-cli v8.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -400,6 +400,9 @@ Each of these has a skill with the steps and the traps:
400
400
  | Write a controller test | \`kickjs-write-controller-test\` |
401
401
  | List endpoint with filters / pagination | \`kickjs-query-parsing-list-endpoint\` |
402
402
  | Serve bundled assets | \`kickjs-use-asset-manager\` |
403
+ | Flag a route (public, exempt, unmetered) | \`kickjs-route-flags\` |
404
+ | Add a kick CLI command or generator | \`kickjs-cli-plugin\` |
405
+ | Deploy to Netlify / Vercel / Cloudflare | \`kickjs-deploy\` |
403
406
  | Anything else | \`kickjs-docs-lookup\` |
404
407
 
405
408
  ## Testing Guidelines
@@ -730,7 +733,75 @@ kick g config --force --repo postgres # Drop a kick.config.ts i
730
733
  - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
731
734
  - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
732
735
  - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
733
- - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
736
+ - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`route-flags`,frontmatterName:`kickjs-route-flags`,description:`Use when a fact about a route (public, CSRF-exempt, unmetered, expose as a tool) has to be read by auth, CSRF, rate limiting, OpenAPI or MCP — instead of repeating it as paths in each consumer.`,body:"A route flag is a named, inheritable fact about a route. It carries no\nbehaviour: it records something every consumer can read, so \"this endpoint is\nopen\" is declared once instead of restated as an auth contributor, a\n`csrf ignorePaths` entry and a `rateLimit skipPaths` entry — two of which are\npathname strings that cannot express `/users/:id`.\n\n**Steps**:\n1. Declare it once, in its own module:\n ```ts\n import { defineRouteFlag } from '@forinda/kickjs'\n\n export const Public = defineRouteFlag('auth.public')\n export const Limit = defineRouteFlag<{ rpm: number }>('rate.limit')\n ```\n2. Apply it. A class flag is inherited by every route under it; `.off` on a\n method removes it:\n ```ts\n @Public // every route below inherits it\n @Controller()\n export class WebhooksController {\n @Get('/health')\n health(ctx: RequestContext) {} // public\n\n @Public.off // the method wins\n @Post('/admin')\n admin(ctx: RequestContext) {} // not public\n\n @Limit({ rpm: 10 }) // flags can carry a value\n @Post('/login')\n login(ctx: RequestContext) {}\n }\n ```\n3. Read it from the consumer that already exists, rather than a new one.\n **Where a consumer is mounted decides how it reads flags** — everything\n after route matching gets `ctx.route`; anything before it does not:\n\n | Consumer | Mounted at | Reads flags by |\n | --- | --- | --- |\n | Handler | the route itself | `ctx.route?.flags.has('auth.public')` |\n | Guard / `@Middleware()` | `@Middleware(fn)` on a method or controller class | `ctx.route`, or the built-ins' `exemptWhen` |\n | `csrfGuard()` / `rateLimitGuard()` | same — `@Middleware()`, class or method | `exemptWhen: 'csrf.exempt'` |\n | Contributor | method > class > module `contributors()` > adapter `contributors()` > `bootstrap({ contributors })` | `skipWhen` / `onlyWhen` on the registration |\n | Global middleware (`rateLimit()`) | `bootstrap({ middlewares: [...] })` — runs **before** matching | the route policy table (`bindRoutePolicy`); `ctx.route` is `undefined` here |\n | Adapter middleware | `AppAdapter.middleware()`, phase `beforeGlobal` … `afterRoutes` | the policy table — the handler is Express-style `(req, res, next)`, so there is no `ctx` in any phase |\n | OpenAPI | `SwaggerAdapter({ publicFlag: 'auth.public' })` | read once at startup, not per request |\n | MCP / AI tools | `McpAdapter({ exposeWhen: 'mcp.tool', hideWhen: 'mcp.hidden' })` | read once at startup |\n\n The contributor row is the one that buys the most: those five levels mean a\n plugin's contributor can be skipped on one route (`skipWhen`) without\n forking it, and a method-level registration beats the adapter's.\n\n4. Run `kick typegen`. It writes the `KickRouteFlags` augmentation, so flag\n names autocomplete and a typo fails `tsc` instead of silently never matching.\n\n**Red flags**:\n- Writing `@Public(false)` to remove a flag — removal is `@Public.off`. A\n resolved flag is present or absent; `false` is a legitimate *value* for a\n flag declared `boolean`, and a presence check would still answer `true`.\n- A new consumer growing its own `skipPaths` / `ignorePaths` list — that is\n the duplication flags exist to remove, and path strings break on params and\n on any `apiPrefix` change.\n- `@Public.off` on a route that never inherited the flag — a no-op, and\n usually a sign the expected class-level flag is not there.\n- Reading `ctx.route` in global middleware — it is `undefined` before a route\n is matched (steps 1-6 of the pipeline). Move the check into a guard mounted\n with `@Middleware()`, or read the policy table.\n- Inventing a flag name per consumer (`auth.open`, `public`, `isPublic`). The\n framework names none of them; pick one name per fact and reuse it."},{slug:`cli-plugin`,frontmatterName:`kickjs-cli-plugin`,description:`Use when adding a kick <name> command, a kick g <name> generator, or a typegen emitter to this project or a package it ships.`,body:"A CLI plugin contributes commands, generators and typegen emitters to the\n`kick` CLI. Every built-in command ships as one, so the contract is the same\none the framework uses.\n\n**Steps**:\n1. Write the plugin. All four contribution kinds are optional:\n ```ts\n // kick-tool.ts\n import { defineCliPlugin } from '@forinda/kickjs-cli'\n\n export const toolPlugin = (options: { watch?: boolean } = {}) =>\n defineCliPlugin({\n // Stable id, unique across plugins — it names the plugin in conflict errors.\n name: 'my-tool',\n // Declarative: same shape as kick.config.ts `commands`.\n commands: [{ name: 'db:migrate', description: 'Apply migrations', steps: 'node ./scripts/migrate.js' }],\n // Programmatic: full commander API, when you need options or subcommands.\n register(program, ctx) {\n program\n .command('my-tool')\n .description('Do the thing')\n .option('--watch', 'Watch mode')\n .action(async () => {\n ctx.log(`running in ${ctx.projectRoot}`)\n // ctx.config is the loaded kick.config.ts\n })\n },\n })\n ```\n2. Register it in `kick.config.ts`:\n ```ts\n import { toolPlugin } from './kick-tool'\n\n export default defineConfig({ plugins: [toolPlugin()] })\n ```\n3. Check it is loaded, per contribution kind: `kick --help` lists a command,\n `kick g --list` lists a generator, `kick typegen` runs an emitter. A\n plugin that fails to load takes the whole CLI down with a conflict error,\n so silence here means the config never referenced it.\n\n**Which kind to use**: `commands` for a shell one-liner, `register` for\noptions / subcommands / async work, `generators` (`defineGenerator`) for\n`kick g <name>` scaffolders, `typegens` for a file under `.kickjs/types/`.\n\n**Red flags**:\n- Confusing this with a runtime plugin: `defineCliPlugin` (from\n `@forinda/kickjs-cli`) extends the CLI; `definePlugin` (from\n `@forinda/kickjs`) hooks the running app. They share nothing.\n- Claiming a command name a built-in owns (`build:netlify`, `typegen`,\n `generate`) — duplicate declarative names are a startup conflict, and\n `register` has no conflict detection at all, so it silently loses. Namespace\n your own (`my-tool:build`).\n- Doing real work inside `register` — it runs at CLI startup for every\n command, so it must only register. Put the work in the action.\n- Importing heavy dependencies at module scope. `await import()` them inside\n the action, so an unrelated `kick dev` does not pay for them."},{slug:`deploy`,frontmatterName:`kickjs-deploy`,description:`Use when deploying this app — Netlify, Vercel or Cloudflare Workers — or when an API route returns the SPA shell, the platform build fails, or the function is missing from a deploy.`,body:`**Netlify and Vercel** run the app as a Node function; the CLI builds both:
737
+
738
+ \`\`\`bash
739
+ ${e} run build:netlify # → .netlify/v1/functions/api.mjs
740
+ ${e} run build:vercel # → .vercel/output (Build Output API v3)
741
+ \`\`\`
742
+
743
+ Both bundle \`src/serverless.ts\` (\`createHandler\`), which is a second entry
744
+ beside \`src/index.ts\` — the long-running server. Keep the shared options in
745
+ one module both import, so they cannot drift.
746
+
747
+ Settings are detected from the layout: a workspace member beside a \`web\`
748
+ package publishes \`web/dist\` and routes \`/api/*\`; a standalone API takes
749
+ every path. Override in \`kick.config.ts\`:
750
+
751
+ \`\`\`ts
752
+ export default defineConfig({
753
+ deploy: { apiPath: '/api', staticDir: '../web/dist' },
754
+ })
755
+ \`\`\`
756
+
757
+ **Cloudflare Workers** is a different entry, not a third flag on this one.
758
+ Workers have no \`node:http\`, so \`createHandler\` cannot run there; use the
759
+ web entry over h3 v2:
760
+
761
+ \`\`\`ts
762
+ // src/worker.ts
763
+ import 'reflect-metadata'
764
+ import { createFetchHandler } from '@forinda/kickjs/web'
765
+ import * as h3 from 'h3' // v2 — passed in, edge bundlers have no createRequire
766
+ import { modules } from './modules'
767
+
768
+ export default createFetchHandler((env) => ({ h3, modules, env }))
769
+ \`\`\`
770
+
771
+ Two things make or break that deploy:
772
+
773
+ 1. **Pre-bundle it yourself.** Point \`wrangler.jsonc\`'s \`main\` at a bundle
774
+ built with SWC (the same Vite + \`unplugin-swc\` setup as the other
775
+ targets), never at \`src/worker.ts\`. Wrangler's own esbuild compiles
776
+ decorators as ES decorators and emits no decorator metadata, so DI fails
777
+ at startup with a \`getOwnMetadata\` TypeError before any request lands.
778
+ 2. **\`compatibility_flags = ["nodejs_compat"]\`** — request-scoped DI and
779
+ \`ctx.set\` / \`ctx.get\` ride on \`AsyncLocalStorage\`.
780
+ 3. **Do not \`import './config'\` here.** It is required in \`src/index.ts\` and
781
+ \`src/serverless.ts\`, and wrong in a Worker twice over: the config module
782
+ reaches for \`node:fs\` / \`createRequire\`, which kills the Worker at
783
+ startup, and \`loadEnvFromSchema\` parses \`process.env\`, which Workers do
784
+ not have. The \`env\` binding threaded through \`createFetchHandler\` is what
785
+ feeds \`ConfigService.get()\` and \`@Value()\` instead — so values arrive as
786
+ the raw strings the platform holds, without the schema's coercion or
787
+ defaults. Coerce where you read them.
788
+
789
+ Not available on Workers: views, SPA/static serving, \`@Asset\`, adapters and
790
+ plugins. Serve static files from Workers Assets or a separate deploy.
791
+
792
+ **Red flags**:
793
+ - An \`/api/*\` route returning \`index.html\` on Netlify — the function is not
794
+ routed. Check the deploy summary says a function was deployed, keep
795
+ \`preferStatic\` out of its config, and leave Netlify's **Package directory**
796
+ unset so it reads the function at the repo root.
797
+ - Committing \`.netlify/\` or \`.vercel/\` — both are build output.
798
+ - A frontend that builds somewhere other than \`web/dist\` and only one of
799
+ \`deploy.staticDir\`, \`SpaAdapter({ clientDir })\` and netlify.toml's
800
+ \`publish\` updated. All three name that directory.
801
+ - Pointing a platform at \`src/index.ts\` — it calls \`bootstrap()\`, which
802
+ listens on a port and registers signal handlers inside the function.
803
+ - Expecting \`kick build\` alone to produce a deployable function; it builds
804
+ the server. Run the target command after it.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
734
805
  surface. When the answer is not in one of them, read the docs rather than
735
806
  inferring it from nearby code: a wrong guess about a framework API compiles
736
807
  fine and fails at runtime.
@@ -839,4 +910,4 @@ Codex / Cursor / Gemini / Claude Code without copy-pasting.
839
910
  CLI template. Hand-edited content is overwritten — keep customisation
840
911
  in \`.agents/COPILOT.local.md\`.
841
912
  `}export{C as a,u as c,w as i,f as l,b as n,y as o,T as r,v as s,x as t};
842
- //# sourceMappingURL=project-docs-B6XKHBMO.mjs.map
913
+ //# sourceMappingURL=project-docs-Y6vOc-Uj.mjs.map