@forinda/kickjs-cli 5.11.1 → 6.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-docs-hbOXsAAh.mjs +12 -0
- package/dist/agent-docs-hbOXsAAh.mjs.map +1 -0
- package/dist/{builtins-BL1BhYEv.mjs → builtins-Dyk9a-mv.mjs} +2 -2
- package/dist/cli.mjs +151 -1376
- package/dist/config-DSpcRefL.mjs +13 -0
- package/dist/config-DSpcRefL.mjs.map +1 -0
- package/dist/doctor-559QZlHi.mjs +1221 -0
- package/dist/doctor-559QZlHi.mjs.map +1 -0
- package/dist/index.d.mts +663 -853
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-C4hfxiPw.mjs → plugin-DK01q7wy.mjs} +3 -3
- package/dist/{plugin-C4hfxiPw.mjs.map → plugin-DK01q7wy.mjs.map} +1 -1
- package/dist/{project-docs-CfB-KVN5.mjs → project-docs-CrfNQIZA.mjs} +6 -36
- package/dist/project-docs-CrfNQIZA.mjs.map +1 -0
- package/dist/{project-root-CDYKLnfG.mjs → project-root-BdTe6EpE.mjs} +3 -3
- package/dist/{project-root-CDYKLnfG.mjs.map → project-root-BdTe6EpE.mjs.map} +1 -1
- package/dist/{rolldown-runtime-CeWwRE8g.mjs → rolldown-runtime-CoN4EDcd.mjs} +1 -1
- package/dist/run-plugins-BAYoDnFI.mjs +636 -0
- package/dist/run-plugins-BAYoDnFI.mjs.map +1 -0
- package/dist/typegen-CwtvFZ0t.mjs +114 -0
- package/dist/typegen-CwtvFZ0t.mjs.map +1 -0
- package/dist/types-BKKzf_bU.mjs +11 -0
- package/package.json +13 -13
- package/dist/agent-docs-CXqrGZLl.mjs +0 -12
- package/dist/agent-docs-CXqrGZLl.mjs.map +0 -1
- package/dist/config-Cf8GU8CG.mjs +0 -13
- package/dist/config-Cf8GU8CG.mjs.map +0 -1
- package/dist/doctor-Dl709LzL.mjs +0 -2076
- package/dist/doctor-Dl709LzL.mjs.map +0 -1
- package/dist/project-docs-CfB-KVN5.mjs.map +0 -1
- package/dist/run-plugins-M_WVt-7a.mjs +0 -976
- package/dist/run-plugins-M_WVt-7a.mjs.map +0 -1
- package/dist/typegen-CezcLjMb.mjs +0 -114
- package/dist/typegen-CezcLjMb.mjs.map +0 -1
- package/dist/types-DvYczI2m.mjs +0 -12
- package/dist/types-DvYczI2m.mjs.map +0 -1
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/commands/doctor.ts","../src/
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/commands/doctor.ts","../src/plugin/types.ts","../src/config.ts","../src/generators/templates/types.ts","../src/generators/module.ts","../src/generators/adapter.ts","../src/generators/middleware.ts","../src/generators/guard.ts","../src/generators/service.ts","../src/generators/controller.ts","../src/generators/dto.ts","../src/generators/project.ts","../src/utils/project-root.ts","../src/typegen/scanner.ts","../src/typegen/plugin.ts","../src/generator-extension/discover.ts","../src/generator-extension/context.ts","../src/utils/naming.ts"],"mappings":";;;;;;AA0BA;;;;;;;;AAGU;AAGV;;;;UANiB,aAAA;EACf,GAAA;EACA,GAAA;EACA,QAAA;AAAA;AAAA,UAGe,YAAA;EAUL;EARV,IAAA;EACA,MAAA;EAQK;EANL,OAAA;EAOkB;EALlB,GAAA;AAAA;AAAA,KAGU,WAAA,IACV,GAAA,EAAK,aAAA,KACF,YAAA,GAAe,YAAA,YAAwB,OAAA,CAAQ,YAAA,GAAe,YAAA;;;;;;UAOlD,eAAA;EAP2B;EAS1C,MAAA,GAAS,WAAW;AAAA;;AATyD;AAO/E;;;;AAEsB;AAqCtB;;;;;;;;AAA4E;AA0B5E;;;;;;;;AAAkE;;;;ACnFlE;;;;AAAiE;AAGjE;iBDsDgB,qBAAA,CAAsB,GAAA,EAAK,eAAA,GAAkB,eAAe;;;ACtDzB;;;;AC7BnD;;;;;;;;;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s-cli
|
|
2
|
+
* @forinda/kickjs-cli v6.0.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{
|
|
11
|
+
import{A as e,M as t,O as n,c as r,d as i,f as a,h as o,j as s,l as c,n as l,o as u,p as d,s as f,t as p,u as m,v as h}from"./doctor-559QZlHi.mjs";import{i as g,r as _}from"./config-DSpcRefL.mjs";import{t as v}from"./project-root-BdTe6EpE.mjs";import{n as y,t as b}from"./types-BKKzf_bU.mjs";function x(e){return e}export{b as KickPluginConflictError,u as buildGeneratorContext,y as defineCliPlugin,_ as defineConfig,p as defineDoctorCheck,l as defineDoctorExtension,f as defineGenerator,x as defineTypegen,v as findProjectRoot,o as generateAdapter,m as generateController,c as generateDto,a as generateGuard,d as generateMiddleware,h as generateModule,i as generateService,r as initProject,g as loadKickConfig,n as pluralize,e as toCamelCase,s as toKebabCase,t as toPascalCase};
|
|
12
12
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli
|
|
2
|
+
* @forinda/kickjs-cli v6.0.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-
|
|
12
|
-
//# sourceMappingURL=plugin-
|
|
11
|
+
import{t as e}from"./rolldown-runtime-CoN4EDcd.mjs";import{t}from"./types-BKKzf_bU.mjs";function n(e,n=[]){let r=new Map;for(let n of e){let e=(r.get(n.name)??0)+1;if(r.set(n.name,e),e===2)throw new t(`plugin`,n.name,[n.name,n.name])}let i=new Map,a=[];for(let n of e)for(let e of n.commands??[]){let r=i.get(e.name);if(r)throw new t(`command`,e.name,[r,n.name]);i.set(e.name,n.name),a.push(e)}let o=new Set(n.map(e=>e.name)),s=[...a.filter(e=>!o.has(e.name)),...n],c=new Map,l=[];for(let n of e)for(let e of n.typegens??[]){let r=c.get(e.id);if(r)throw new t(`typegen`,e.id,[r,n.name]);c.set(e.id,n.name),l.push(e)}let u=new Map,d=[];for(let n of e)for(let e of n.generators??[]){let r=u.get(e.name);if(r)throw new t(`generator`,e.name,[r,n.name]);u.set(e.name,n.name),d.push({source:n.name,spec:e})}return{commands:s,typegens:l,generators:d,register:async(t,n)=>{let r;if(n)r={generators:d,...n};else{let{findProjectRoot:e}=await import(`./project-root-BdTe6EpE.mjs`).then(e=>e.n),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:d}}for(let n of e)n.register&&await n.register(t,r)}}}var r=e({mergeCliPlugins:()=>n});export{n,r as t};
|
|
12
|
+
//# sourceMappingURL=plugin-DK01q7wy.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-
|
|
1
|
+
{"version":3,"file":"plugin-DK01q7wy.mjs","names":[],"sources":["../src/plugin/merge.ts","../src/plugin/index.ts"],"sourcesContent":["// Plugin → unified registry merge.\n//\n// Resolution rules (per the v1 spec + dogfood pivot):\n// - duplicate plugin `name` across the input array → conflict error.\n// Catches the double-install case (built-in shipped twice, or\n// adopter requiring the same plugin twice).\n// - plugin commands appear first in the merged list, then adopter\n// commands; adopter `commands` of the same name override the\n// plugin entry (filter pass).\n// - duplicate command name across two plugins → conflict error\n// listing both plugin names. Adopter overriding a plugin is\n// allowed and not an error.\n// - duplicate typegen id across two plugins → same error. Typegens\n// have no adopter override path; only plugins contribute them.\n// - register() functions are collected in input order; the caller\n// invokes each one against the same Command program. They have no\n// id-level conflict surface — owners are responsible for picking\n// non-colliding command names inside their own register().\n// - plugin order = array order. No implicit precedence rules.\n\nimport type { Command } from 'commander'\n\nimport type { KickCommandDefinition } from '../config'\nimport type { TypegenPlugin } from '../typegen/plugin'\nimport type { GeneratorSpec } from '../generator-extension/define'\nimport type { DiscoveredGenerator } from '../generator-extension/discover'\nimport { KickPluginConflictError, type KickCliPlugin, type KickCliPluginContext } from './types'\n\nexport interface MergedPlugins {\n commands: KickCommandDefinition[]\n typegens: TypegenPlugin[]\n /** DiscoveredGenerator shape so this list slots into the existing\n * dispatch path next to package.json-discovered entries. `source`\n * carries the plugin name for error attribution. */\n generators: DiscoveredGenerator[]\n /**\n * Apply every plugin's register() in input order. ctx is optional so\n * tests + lightweight callers can invoke `register(program)` without\n * constructing a full context; it falls back to cwd=process.cwd(),\n * config=null, log=no-op.\n */\n register: (program: Command, ctx?: KickCliPluginContext) => Promise<void>\n}\n\nexport function mergeCliPlugins(\n plugins: readonly KickCliPlugin[],\n adopterCommands: readonly KickCommandDefinition[] = [],\n): MergedPlugins {\n // Plugin-name dedup — catches double-install.\n const seenPluginNames = new Map<string, number>()\n for (const p of plugins) {\n const count = (seenPluginNames.get(p.name) ?? 0) + 1\n seenPluginNames.set(p.name, count)\n if (count === 2) {\n throw new KickPluginConflictError('plugin', p.name, [p.name, p.name])\n }\n }\n\n const commandOwners = new Map<string, string>()\n const pluginCommands: KickCommandDefinition[] = []\n for (const p of plugins) {\n for (const cmd of p.commands ?? []) {\n const prior = commandOwners.get(cmd.name)\n if (prior) {\n throw new KickPluginConflictError('command', cmd.name, [prior, p.name])\n }\n commandOwners.set(cmd.name, p.name)\n pluginCommands.push(cmd)\n }\n }\n\n const adopterNames = new Set(adopterCommands.map((c) => c.name))\n const filteredPlugin = pluginCommands.filter((c) => !adopterNames.has(c.name))\n const commands = [...filteredPlugin, ...adopterCommands]\n\n const typegenOwners = new Map<string, string>()\n const typegens: TypegenPlugin[] = []\n for (const p of plugins) {\n for (const tg of p.typegens ?? []) {\n const prior = typegenOwners.get(tg.id)\n if (prior) {\n throw new KickPluginConflictError('typegen', tg.id, [prior, p.name])\n }\n typegenOwners.set(tg.id, p.name)\n typegens.push(tg)\n }\n }\n\n const generatorOwners = new Map<string, string>()\n const generators: DiscoveredGenerator[] = []\n for (const p of plugins) {\n for (const spec of p.generators ?? []) {\n const prior = generatorOwners.get(spec.name)\n if (prior) {\n throw new KickPluginConflictError('generator', spec.name, [prior, p.name])\n }\n generatorOwners.set(spec.name, p.name)\n generators.push({ source: p.name, spec: spec satisfies GeneratorSpec })\n }\n }\n\n /**\n * Apply every plugin's `register()` callback in input order against the\n * given Commander program. Each callback receives a {@link KickCliPluginContext}:\n * caller-supplied ctx wins (test fixtures can inject a different\n * workspace boundary); otherwise a default ctx is built with\n * `findProjectRoot(process.cwd())` as the project root, `cwd` matching\n * `process.cwd()`, null config, no-op log, and the merged generator set\n * threaded through so the `kick/generate` built-in can surface each as\n * a Commander subcommand. The dynamic import of `findProjectRoot` keeps\n * the caller-supplied fast path zero-cost.\n */\n const register = async (program: Command, ctx?: KickCliPluginContext): Promise<void> => {\n let resolved: KickCliPluginContext\n if (ctx) {\n resolved = { generators, ...ctx }\n } else {\n const { findProjectRoot } = await import('../utils/project-root')\n const cwd = process.cwd()\n resolved = {\n cwd,\n projectRoot: findProjectRoot(cwd),\n config: null,\n log: () => {},\n generators,\n }\n }\n for (const p of plugins) {\n if (p.register) await p.register(program, resolved)\n }\n }\n\n return { commands, typegens, generators, register }\n}\n","// Barrel intentionally omits `./builtins` — that module top-level-imports\n// every register*Command, which pulls heavy modules (project scaffolders,\n// fs reads at import time) into the graph. Importers that need the\n// builtin list go through `./plugin/builtins` directly; tests + adopter\n// plugins consuming only the contract types import from here.\n\nexport type { KickCliPlugin } from './types'\nexport { defineCliPlugin, KickPluginConflictError } from './types'\nexport { mergeCliPlugins, type MergedPlugins } from './merge'\n"],"mappings":";;;;;;;;;;wFA4CA,SAAgB,EACd,EACA,EAAoD,CAAC,EACtC,CAEf,IAAM,EAAkB,IAAI,IAC5B,IAAK,IAAM,KAAK,EAAS,CACvB,IAAM,GAAS,EAAgB,IAAI,EAAE,IAAI,GAAK,GAAK,EAE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AW,KAAK,CAAE,OAAQ,EAAE,KAAY,MAA6B,CAAC,CACxE,CAkCF,MAAO,CAAE,WAAU,WAAU,aAAY,eApBjB,EAAkB,IAA8C,CACtF,IAAI,EACJ,GAAI,EACF,EAAW,CAAE,aAAY,GAAG,CAAI,MAC3B,CACL,GAAM,CAAE,mBAAoB,MAAM,OAAO,8BAAwB,CAAA,KAAA,GAAA,EAAA,CAAA,EAC3D,EAAM,QAAQ,IAAI,EACxB,EAAW,CACT,MACA,YAAa,EAAgB,CAAG,EAChC,OAAQ,KACR,QAAW,CAAC,EACZ,YACF,CACF,CACA,IAAK,IAAM,KAAK,EACV,EAAE,UAAU,MAAM,EAAE,SAAS,EAAS,CAAQ,CAEtD,CAEkD,CACpD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli
|
|
2
|
+
* @forinda/kickjs-cli v6.0.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{existsSync as i}from"node:fs";import{access as a,mkdir as o,readFile as s,writeFile as c}from"node:fs/promises";import*as l from"@clack/prompts";import u from"picocolors";let d=!1;function f(e){d=e}const p=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function m(e,r){d||(await o(t(e),{recursive:!0}),await c(e,r,`utf-8`),p.has(n(e))&&await _(e,r).catch(()=>{}))}let h;async function g(t){if(h!==void 0)return h;try{h=await import(e(r(t,`package.json`)).resolve(`oxfmt`))}catch{h=null}return h}async function _(e,t){let n=await g(process.cwd());if(!n)return;let r=await y(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await c(e,i.code,`utf-8`)}const v=new Map;async function y(e){let n=t(e),a=n;if(v.has(a))return v.get(a);for(;;){let e=r(n,`.oxfmtrc.json`);if(i(e))try{let t=await s(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,v.set(a,n),n}catch{return v.set(a,null),null}let o=t(n);if(o===n)return v.set(a,null),null;n=o}}async function b(e){try{return await a(e),!0}catch{return!1}}const x={GET:u.green,POST:u.cyan,PUT:u.yellow,PATCH:u.magenta,DELETE:u.red};function S(e){return(x[e]??u.dim)(e.padEnd(7))}function C(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return u.red(t);case`WARNING`:return u.yellow(t);case`INFO`:return u.blue(u.dim(t));default:return t}}u.green(`✓`),u.red(`✖`),u.yellow(`⚠`),u.blue(`ℹ`);function w(e){l.intro(u.bgCyan(u.black(` ${e} `)))}function T(e){l.outro(e)}function E(e){l.isCancel(e)&&(l.cancel(`Operation cancelled.`),process.exit(0))}async function D(e){let t=await l.text(e);return E(t),t}async function O(e){let t=await l.select(e);return E(t),t}async function k(e){let t=await l.multiselect(e);return E(t),t}async function A(e){let t=await l.confirm(e);return E(t),t}function j(){return l.spinner()}const M=l.log;function N(e,t,n){let r={rest:`REST API`,ddd:`Domain-Driven Design`,cqrs:`CQRS + Event-Driven`,minimal:`Minimal`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`)
|
|
11
|
+
import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{existsSync as i}from"node:fs";import{access as a,mkdir as o,readFile as s,writeFile as c}from"node:fs/promises";import*as l from"@clack/prompts";import u from"picocolors";let d=!1;function f(e){d=e}const p=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function m(e,r){d||(await o(t(e),{recursive:!0}),await c(e,r,`utf-8`),p.has(n(e))&&await _(e,r).catch(()=>{}))}let h;async function g(t){if(h!==void 0)return h;try{h=await import(e(r(t,`package.json`)).resolve(`oxfmt`))}catch{h=null}return h}async function _(e,t){let n=await g(process.cwd());if(!n)return;let r=await y(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await c(e,i.code,`utf-8`)}const v=new Map;async function y(e){let n=t(e),a=n;if(v.has(a))return v.get(a);for(;;){let e=r(n,`.oxfmtrc.json`);if(i(e))try{let t=await s(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,v.set(a,n),n}catch{return v.set(a,null),null}let o=t(n);if(o===n)return v.set(a,null),null;n=o}}async function b(e){try{return await a(e),!0}catch{return!1}}const x={GET:u.green,POST:u.cyan,PUT:u.yellow,PATCH:u.magenta,DELETE:u.red};function S(e){return(x[e]??u.dim)(e.padEnd(7))}function C(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return u.red(t);case`WARNING`:return u.yellow(t);case`INFO`:return u.blue(u.dim(t));default:return t}}u.green(`✓`),u.red(`✖`),u.yellow(`⚠`),u.blue(`ℹ`);function w(e){l.intro(u.bgCyan(u.black(` ${e} `)))}function T(e){l.outro(e)}function E(e){l.isCancel(e)&&(l.cancel(`Operation cancelled.`),process.exit(0))}async function D(e){let t=await l.text(e);return E(t),t}async function O(e){let t=await l.select(e);return E(t),t}async function k(e){let t=await l.multiselect(e);return E(t),t}async function A(e){let t=await l.confirm(e);return E(t),t}function j(){return l.spinner()}const M=l.log;function N(e,t,n){let r={rest:`REST API`,ddd:`Domain-Driven Design`,cqrs:`CQRS + Event-Driven`,minimal:`Minimal`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),`# ${e}
|
|
12
12
|
|
|
13
13
|
A **${r[t]??`REST API`}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
|
|
14
14
|
|
|
@@ -309,34 +309,12 @@ package additions, env access patterns, troubleshooting) is detailed below.
|
|
|
309
309
|
|
|
310
310
|
Each module in \`src/modules/<name>/\` typically contains:
|
|
311
311
|
|
|
312
|
-
${t===`
|
|
312
|
+
${t===`rest`?`\`\`\`
|
|
313
313
|
<name>/
|
|
314
314
|
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
315
315
|
├── <name>.service.ts # Business logic (@Service)
|
|
316
316
|
├── <name>.repository.ts # Data access (@Repository)
|
|
317
|
-
├──
|
|
318
|
-
├── <name>.entity.ts # Domain entity (optional)
|
|
319
|
-
└── <name>.module.ts # Module definition (defineModule factory)
|
|
320
|
-
\`\`\`
|
|
321
|
-
`:t===`cqrs`?`\`\`\`
|
|
322
|
-
<name>/
|
|
323
|
-
├── commands/ # Write operations
|
|
324
|
-
│ ├── create-<name>.command.ts
|
|
325
|
-
│ └── create-<name>.handler.ts
|
|
326
|
-
├── queries/ # Read operations
|
|
327
|
-
│ ├── get-<name>.query.ts
|
|
328
|
-
│ └── get-<name>.handler.ts
|
|
329
|
-
├── events/ # Domain events
|
|
330
|
-
│ └── <name>-created.event.ts
|
|
331
|
-
├── <name>.controller.ts # HTTP routes
|
|
332
|
-
├── <name>.repository.ts # Data access
|
|
333
|
-
└── <name>.module.ts # Module definition (defineModule factory)
|
|
334
|
-
\`\`\`
|
|
335
|
-
`:t===`rest`?`\`\`\`
|
|
336
|
-
<name>/
|
|
337
|
-
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
338
|
-
├── <name>.service.ts # Business logic (@Service)
|
|
339
|
-
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
317
|
+
├── dtos/ # Request/response schemas (Zod)
|
|
340
318
|
└── <name>.module.ts # Module definition (defineModule factory)
|
|
341
319
|
\`\`\`
|
|
342
320
|
`:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
|
|
@@ -601,15 +579,7 @@ fast). The \`onError\` hook is async-permitted.
|
|
|
601
579
|
|
|
602
580
|
Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
|
|
603
581
|
|
|
604
|
-
|
|
605
|
-
| Decorator | Purpose |
|
|
606
|
-
|-----------|---------|
|
|
607
|
-
| \`@Job('name')\` | Queue job handler |
|
|
608
|
-
| \`@Process('queue')\` | Queue processor |
|
|
609
|
-
| \`@Cron('0 * * * *')\` | Cron schedule |
|
|
610
|
-
| \`@WsController()\` | WebSocket controller |
|
|
611
|
-
|
|
612
|
-
`:``}## Common Pitfalls
|
|
582
|
+
## Common Pitfalls
|
|
613
583
|
|
|
614
584
|
1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
|
|
615
585
|
2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
|
|
@@ -855,4 +825,4 @@ Codex / Cursor / Gemini / Claude Code without copy-pasting.
|
|
|
855
825
|
CLI template. Hand-edited content is overwritten — keep customisation
|
|
856
826
|
in \`.agents/COPILOT.local.md\`.
|
|
857
827
|
`}export{C as _,I as a,m as b,w as c,T as d,O as f,u as g,S as h,L as i,M as l,D as m,P as n,N as o,j as p,R as r,A as s,F as t,k as u,b as v,f as y};
|
|
858
|
-
//# sourceMappingURL=project-docs-
|
|
828
|
+
//# sourceMappingURL=project-docs-CrfNQIZA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project-docs-CrfNQIZA.mjs","names":["colors"],"sources":["../src/utils/fs.ts","../src/utils/colors.ts","../src/utils/prompts.ts","../src/generators/templates/project-docs.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { writeFile, mkdir, access, readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { dirname, extname, join } from 'node:path'\n\nlet _dryRun = false\nlet _format = true\n\n/** Enable/disable dry run mode globally for all writeFileSafe calls */\nexport function setDryRun(enabled: boolean): void {\n _dryRun = enabled\n}\n\n/**\n * Toggle oxfmt post-write formatting. Defaults to enabled — generators\n * always emit formatted output unless the caller opts out (rare; useful\n * for tests that want byte-stable assertions against raw template strings).\n */\nexport function setFormatOnWrite(enabled: boolean): void {\n _format = enabled\n}\n\n/** Extensions oxfmt can format. Anything else is written verbatim. */\nconst FORMATTABLE = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json', '.md'])\n\n/**\n * Write a file, creating parent directories if needed.\n *\n * After write, runs oxfmt against the file when:\n * - format-on-write is enabled (default)\n * - the extension is in {@link FORMATTABLE}\n * - oxfmt resolves from the user's project (or our own cwd)\n *\n * Failures (missing oxfmt, unparseable source, formatter crash) are\n * swallowed silently — formatting is a polish step, not a correctness\n * gate. The pre-commit hook still catches anything we couldn't format.\n *\n * Skips writing entirely in dry run mode.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n if (_dryRun) return\n await mkdir(dirname(filePath), { recursive: true })\n await writeFile(filePath, content, 'utf-8')\n if (_format && FORMATTABLE.has(extname(filePath))) {\n await formatFile(filePath, content).catch(() => {\n // Formatter missing or unparseable source — leave the unformatted\n // file in place. Pre-commit hook will catch shipping-blocker\n // formatting issues.\n })\n }\n}\n\ninterface OxfmtFormatResult {\n code: string\n errors: unknown[]\n}\n\ninterface OxfmtModule {\n format(\n fileName: string,\n sourceText: string,\n options?: Record<string, unknown>,\n ): Promise<OxfmtFormatResult>\n}\n\nlet _oxfmt: OxfmtModule | null | undefined = undefined\n\n/** Resolve oxfmt from the user's project; cache the result (or null) for the process. */\nasync function resolveOxfmt(cwd: string): Promise<OxfmtModule | null> {\n if (_oxfmt !== undefined) return _oxfmt\n try {\n const req = createRequire(join(cwd, 'package.json'))\n const oxfmtPath = req.resolve('oxfmt')\n _oxfmt = (await import(oxfmtPath)) as OxfmtModule\n } catch {\n _oxfmt = null\n }\n return _oxfmt\n}\n\nasync function formatFile(filePath: string, content: string): Promise<void> {\n const oxfmt = await resolveOxfmt(process.cwd())\n if (!oxfmt) return\n // The CLI binary auto-discovers `.oxfmtrc.json`, but the JS API\n // does NOT — we walk up from the file being formatted so adopters'\n // workspace config drives the output. Skip formatting entirely\n // when no config is found (matches the old prettier failure mode:\n // raw templates already follow project conventions).\n const options = await loadOxfmtConfig(filePath)\n if (options === null) return\n const result = await oxfmt.format(filePath, content, options)\n if (result.code === content) return\n await writeFile(filePath, result.code, 'utf-8')\n}\n\nconst _oxfmtConfigCache = new Map<string, Record<string, unknown> | null>()\n\n/**\n * Walk up from `filePath`'s directory looking for `.oxfmtrc.json`.\n * Returns `null` when no config is found anywhere on the path —\n * generators then leave the raw template alone (which already\n * follows project conventions). Cached per starting directory so\n * the walk is one-shot per generator run.\n */\nasync function loadOxfmtConfig(filePath: string): Promise<Record<string, unknown> | null> {\n let dir = dirname(filePath)\n const startDir = dir\n if (_oxfmtConfigCache.has(startDir)) return _oxfmtConfigCache.get(startDir)!\n while (true) {\n const configPath = join(dir, '.oxfmtrc.json')\n if (existsSync(configPath)) {\n try {\n const raw = await readFile(configPath, 'utf-8')\n const parsed = JSON.parse(raw) as Record<string, unknown>\n // The `$schema` and `ignorePatterns` fields are runner-only —\n // strip before passing to format() so it doesn't reject them\n // as unknown options.\n delete parsed['$schema']\n delete parsed.ignorePatterns\n _oxfmtConfigCache.set(startDir, parsed)\n return parsed\n } catch {\n _oxfmtConfigCache.set(startDir, null)\n return null\n }\n }\n const parent = dirname(dir)\n if (parent === dir) {\n _oxfmtConfigCache.set(startDir, null)\n return null\n }\n dir = parent\n }\n}\n\n/** Reset cached oxfmt resolution. Tests use this; production code shouldn't. */\nexport function clearFormatCache(): void {\n _oxfmt = undefined\n _oxfmtConfigCache.clear()\n}\n\n/** Ensure a directory exists */\nexport async function ensureDirectory(dir: string): Promise<void> {\n await mkdir(dir, { recursive: true })\n}\n\n/** Check if a file exists */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath)\n return true\n } catch {\n return false\n }\n}\n\n/** Read a JSON file */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function readJsonFile<T = any>(filePath: string): Promise<T> {\n const content = await readFile(filePath, 'utf-8')\n return JSON.parse(content)\n}\n","import pc from 'picocolors'\n\nexport { pc as colors }\n\nconst METHOD_COLOR_MAP: Record<string, (s: string) => string> = {\n GET: pc.green,\n POST: pc.cyan,\n PUT: pc.yellow,\n PATCH: pc.magenta,\n DELETE: pc.red,\n}\n\n/** Color an HTTP method string for terminal display */\nexport function httpMethodColor(method: string): string {\n const fn = METHOD_COLOR_MAP[method] ?? pc.dim\n return fn(method.padEnd(7))\n}\n\n/** Color a severity tag for terminal display (padded to 10 chars) */\nexport function severityColor(severity: string): string {\n const tag = `[${severity}]`.padEnd(10)\n switch (severity) {\n case 'CRITICAL':\n return pc.red(tag)\n case 'WARNING':\n return pc.yellow(tag)\n case 'INFO':\n return pc.blue(pc.dim(tag))\n default:\n return tag\n }\n}\n","import * as clack from '@clack/prompts'\nimport { colors } from './colors'\n\nexport const symbols = {\n success: colors.green('✓'),\n error: colors.red('✖'),\n warning: colors.yellow('⚠'),\n info: colors.blue('ℹ'),\n}\n\n/** Show branded intro banner */\nexport function intro(title: string): void {\n clack.intro(colors.bgCyan(colors.black(` ${title} `)))\n}\n\n/** Show closing message */\nexport function outro(message: string): void {\n clack.outro(message)\n}\n\n/** Handle cancellation — print message and exit */\nfunction handleCancel(value: unknown): void {\n if (clack.isCancel(value)) {\n clack.cancel('Operation cancelled.')\n process.exit(0)\n }\n}\n\n/** Text input prompt */\nexport async function text(opts: {\n message: string\n placeholder?: string\n defaultValue?: string\n validate?: (value: string) => string | void\n}): Promise<string> {\n const value = await clack.text(opts as any)\n handleCancel(value)\n return value as string\n}\n\n/** Single select prompt */\nexport async function select<T>(opts: {\n message: string\n options: { value: T; label: string; hint?: string }[]\n initialValue?: T\n}): Promise<T> {\n const value = await clack.select(opts as any)\n handleCancel(value)\n return value as T\n}\n\n/** Multi-select prompt with checkboxes */\nexport async function multiSelect<T>(opts: {\n message: string\n options: { value: T; label: string; hint?: string }[]\n required?: boolean\n initialValues?: T[]\n}): Promise<T[]> {\n const value = await clack.multiselect(opts as any)\n handleCancel(value)\n return value as T[]\n}\n\n/** Yes/no confirmation prompt */\nexport async function confirm(opts: {\n message: string\n active?: string\n inactive?: string\n initialValue?: boolean\n}): Promise<boolean> {\n const value = await clack.confirm(opts)\n handleCancel(value)\n return value as boolean\n}\n\n/** Create a spinner for progress indication */\nexport function spinner() {\n return clack.spinner()\n}\n\n/** Log utilities for styled messages inside clack flow */\nexport const log = clack.log\n","type ProjectTemplate = 'rest' | 'minimal'\n\n/** Generate README.md with project documentation */\nexport function generateReadme(name: string, template: ProjectTemplate, pm: string): string {\n const templateLabels: Record<string, string> = {\n rest: 'REST API',\n ddd: 'Domain-Driven Design',\n cqrs: 'CQRS + Event-Driven',\n minimal: 'Minimal',\n }\n\n const packages = ['@forinda/kickjs', '@forinda/kickjs-vite']\n if (template !== 'minimal') {\n packages.push('@forinda/kickjs-swagger', '@forinda/kickjs-devtools')\n }\n\n return `# ${name}\n\nA **${templateLabels[template] ?? 'REST API'}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.\n\n## Getting Started\n\n\\`\\`\\`bash\n${pm} install\nkick dev\n\\`\\`\\`\n\n## Scripts\n\n| Command | Description |\n|---|---|\n| \\`kick dev\\` | Start dev server with Vite HMR |\n| \\`kick build\\` | Production build |\n| \\`kick start\\` | Run production build |\n| \\`${pm} run test\\` | Run tests with Vitest |\n| \\`kick g module <name>\\` | Generate a DDD module |\n| \\`kick g scaffold <name> <fields...>\\` | Generate CRUD from field definitions |\n| \\`kick add <package>\\` | Add a KickJS package |\n\n## Project Structure\n\n\\`\\`\\`\nsrc/\n├── index.ts # Application entry point\n├── modules/ # Feature modules (controllers, services, repos)\n│ └── index.ts # Module registry\n└── ...\n\\`\\`\\`\n\n## Packages\n\n${packages.map((p) => `- \\`${p}\\``).join('\\n')}\n\n## Adding Features\n\n\\`\\`\\`bash\nkick add auth # Authentication (JWT, API key, OAuth)\nkick add swagger # OpenAPI documentation\nkick add ws # WebSocket support\nkick add queue # Background job processing\nkick add --list # Show all available packages\n\\`\\`\\`\n\nFor email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \\`defineAdapter()\\` / \\`definePlugin()\\` directly, so you keep control of the integration.\n\n## Environment Variables\n\nCopy \\`.env.example\\` to \\`.env\\` and configure:\n\n| Variable | Default | Description |\n|---|---|---|\n| \\`PORT\\` | \\`3000\\` | Server port |\n| \\`NODE_ENV\\` | \\`development\\` | Environment |\n\n## Learn More\n\n- [KickJS Documentation](https://forinda.github.io/kick-js/)\n- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)\n`\n}\n\n/**\n * Generate CLAUDE.md.\n *\n * v4 update: this file is intentionally thin. AGENTS.md is the\n * canonical, multi-agent project reference (Claude / Copilot /\n * Codex / Gemini / etc.) — duplicating it here meant two files\n * drifting out of sync after every framework change. The generated\n * CLAUDE.md now redirects there + adds Claude-specific affordances\n * only.\n */\nexport function generateClaude(name: string, _template: ProjectTemplate, pm: string): string {\n return `# CLAUDE.md — ${name}\n\n**Read \\`./.agents/AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project (Claude, Copilot, Codex, Gemini, etc.) —\nproject conventions, structure, decorator patterns, env wiring, CLI\ngenerators, every gotcha.\n\n**Then browse \\`./.agents/skills/\\`.** Each subdirectory is a single\ntask-oriented skill (\\`add-module/\\`, \\`write-controller-test/\\`,\n\\`bootstrap-export/\\`, \\`deny-list/\\`, …) containing a \\`SKILL.md\\`\nwith YAML frontmatter (\\`name\\`, \\`description\\`) and the recipe body.\nThe structure follows the Claude Code skills convention — agents that\nauto-load skills from \\`.agents/skills/\\` will pick each up by its\nfrontmatter. Use this directory as the playbook when executing common\nKickJS workflows.\n\nThis file is a thin Claude-specific layer on top of those two; when\nthey disagree on anything substantive, treat \\`.agents/AGENTS.md\\` as\nauthoritative and flag the discrepancy.\n\n## Why \\`.agents/\\` + this thin pointer\n\n\\`.agents/AGENTS.md\\` is what every agent reads (Codex, Cursor, Gemini,\nCopilot, Aider, …) — one canonical source so the prose doesn't drift\nacross copies. \\`CLAUDE.md\\` is what Claude Code automatically loads as\nproject context on each conversation, so it stays at the project root.\nKeeping CLAUDE.md slim and pointing at \\`.agents/\\` avoids two\nout-of-sync copies of the same content. Per-agent files\n(\\`.agents/GEMINI.md\\`, \\`.agents/COPILOT.md\\`) live alongside\n\\`AGENTS.md\\` for tool-specific notes that don't belong in the shared\nprose.\n\n## Claude-specific notes\n\n- **Slash commands** — \\`/help\\` for Claude Code commands; \\`/init\\`\n to refresh project memory if AGENTS.md changes substantially.\n- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.\n- **Persistent memory** — Claude maintains user/feedback/project/\n reference memories under \\`.claude/memory/\\`. If you ask for\n something that contradicts a remembered preference, Claude flags\n it before acting; corrections update memory automatically.\n- **Long-running tasks** — \\`/loop\\` and \\`/schedule\\` for recurring\n or background work. Useful for \"wait for the deploy then open a\n cleanup PR\" or \"every Monday triage the issue board\" patterns.\n\n## Quick reference (full version in .agents/AGENTS.md)\n\n\\`\\`\\`bash\n${pm} install # Install dependencies\nkick dev # Dev server with HMR + typegen\nkick build && kick start # Production\n${pm} run test # Vitest\n${pm} run typecheck # tsc --noEmit\n${pm} run format # Prettier\n\\`\\`\\`\n\n## v4 framework reminders\n\nWhen generating or modifying code in this project, stay aligned with the v4 conventions documented in \\`.agents/AGENTS.md\\`:\n\n- **Adapters**: \\`defineAdapter()\\` factory — never \\`class implements AppAdapter\\`.\n- **Plugins**: \\`definePlugin()\\` factory — never plain function returning \\`KickPlugin\\`.\n- **DI tokens**: \\`<scope>/<PascalKey>[/<suffix>]\\` — scope is lowercase, the key segment is **PascalCase** (e.g. \\`'app/Users/repository'\\`, \\`'mycorp/Cache/redis'\\`). First-party uses the reserved \\`'kick/'\\` prefix; this project owns its own scope.\n- **Decorators**: \\`@Controller()\\` (no path arg — mount prefix comes from \\`routes().path\\`).\n- **Module entry file** MUST be named \\`<name>.module.ts\\` and live under \\`src/modules/<name>/\\`. The Vite plugin auto-discovers \\`*.module.[tj]sx?\\` for graceful HMR — a misnamed \\`projects.ts\\` silently degrades every save into a full restart.\n- **Env**: schema lives in \\`src/config/index.ts\\`; \\`import './config'\\` MUST be the first import in \\`src/index.ts\\` (side-effect registers the schema before any \\`@Value\\` resolves).\n- **Assets**: drop new template files into \\`src/templates/<namespace>/\\`; the dev watcher auto-rebuilds the \\`KickAssets\\` augmentation + \\`assets.x.y()\\` re-walks on next call. No restart, no manual build.\n- **Context Contributors** (\\`defineContextDecorator\\`) over \\`@Middleware()\\` for ctx-population work.\n- **Repos under tests**: \\`Container.create()\\` for isolation — never \\`new Container()\\` or \\`getInstance().reset()\\`.\n- **Bootstrap export**: \\`src/index.ts\\` must end with \\`export const app = await bootstrap({ ... })\\`. The Vite plugin and \\`createTestApp\\` import the named \\`app\\`; without the export, HMR silently degrades to full restarts.\n- **Thin entry file**: aggregate \\`modules\\`, \\`middleware\\`, \\`plugins\\`, \\`adapters\\` in their own folders (\\`src/modules/index.ts\\`, \\`src/middleware/index.ts\\`, …) and pass them by name to \\`bootstrap()\\` — never inline the lists in \\`src/index.ts\\`.\n- **Refresh these files**: \\`kick g agents -f\\` regenerates \\`CLAUDE.md\\` at the project root and \\`.agents/AGENTS.md\\` + \\`.agents/GEMINI.md\\` + \\`.agents/COPILOT.md\\` + every \\`.agents/skills/<name>/SKILL.md\\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \\`.agents/AGENTS.local.md\\` or per-skill \\`SKILL.local.md\\` files alongside.\n\nFor everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \\`.agents/AGENTS.md\\`.\n`\n}\n\n// Legacy reference left as a comment for the v4 doc — the original\n// generator embedded ~400 lines of patterns here that duplicated\n// AGENTS.md. The chunk below is the unused remnant of that template\n// kept under a `false &&` guard so the diff stays reviewable; it can\n// be deleted in the next minor.\nfunction _LEGACY_FULL_CLAUDE_TEMPLATE_UNUSED(\n name: string,\n template: ProjectTemplate,\n pm: string,\n): string {\n const templateLabels: Record<string, string> = {\n rest: 'REST API',\n ddd: 'Domain-Driven Design',\n cqrs: 'CQRS + Event-Driven',\n minimal: 'Minimal Express',\n }\n\n return `# CLAUDE.md — ${name} Development Guide\n\n> **Read \\`AGENTS.md\\` first.** It is the canonical, multi-agent reference for this project (Claude, Copilot, Codex, Gemini, etc.). This file contains the same project context distilled for Claude, plus Claude-specific notes. When the two disagree on anything substantive, treat \\`AGENTS.md\\` as authoritative and flag the discrepancy.\n\n## Project Overview\n\nThis is a **${templateLabels[template] ?? 'REST API'}** application built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.\n\n## Quick Commands\n\n\\`\\`\\`bash\n${pm} install # Install dependencies\nkick dev # Start dev server with HMR\nkick build # Production build via Vite\nkick start # Run production build\n${pm} run test # Run tests with Vitest\n${pm} run typecheck # TypeScript type checking\n${pm} run format # Format code with Prettier\n\\`\\`\\`\n\n## Project Structure\n\n\\`\\`\\`\nsrc/\n├── index.ts # Application bootstrap\n├── modules/ # Feature modules (DDD/CQRS pattern)\n│ └── index.ts # Module registry\n└── ...\n\\`\\`\\`\n\n## Package Manager\n\n- Always use **${pm}** for this project\n- Run \\`${pm} install\\` to sync dependencies\n- Never mix package managers (npm/yarn/pnpm)\n\n## Code Style\n\n- **Prettier** — no semicolons, single quotes, trailing commas, 100 char width\n- **TypeScript strict mode** — all types required\n- Format before committing: \\`${pm} run format\\`\n- Type check with: \\`${pm} run typecheck\\`\n\n## Key Patterns\n\n### Controllers\n\nUse decorators to define routes. Annotate \\`ctx\\` with \\`Ctx<KickRoutes.X['method']>\\`\nto get fully-typed \\`ctx.params\\`, \\`ctx.body\\`, and \\`ctx.query\\` from the\ngenerated \\`KickRoutes\\` namespace (refreshed on \\`kick dev\\` and \\`kick typegen\\`).\n\n\\`\\`\\`ts\nimport { Controller, Get, Post, type Ctx } from '@forinda/kickjs'\n\n@Controller()\nexport class UserController {\n @Get('/')\n async findAll(ctx: Ctx<KickRoutes.UserController['findAll']>) {\n return ctx.json({ users: [] })\n }\n\n @Post('/')\n async create(ctx: Ctx<KickRoutes.UserController['create']>) {\n const data = ctx.body\n return ctx.created({ user: data })\n }\n}\n\\`\\`\\`\n\n### Services\n\nInject dependencies with \\`@Service()\\` and \\`@Autowired()\\`:\n\n\\`\\`\\`ts\nimport { Service, Autowired } from '@forinda/kickjs'\n\n@Service()\nexport class UserService {\n @Autowired()\n private userRepository!: UserRepository\n\n async findAll() {\n return this.userRepository.findAll()\n }\n}\n\\`\\`\\`\n\n### Modules\n\nModules are built with \\`defineModule()\\` and wire controllers via \\`buildRoutes()\\`. The legacy \\`class … implements AppModule\\` form keeps working — the loader accepts both — but new generators emit \\`defineModule\\` for parity with \\`defineAdapter\\` and \\`definePlugin\\`.\n\n> **Naming matters.** Module files **must** be named \\`<name>.module.ts\\` and live under \\`src/modules/\\`. The Vite plugin auto-discovers files matching \\`*.module.[tj]sx?\\` for HMR — a misnamed file (e.g., \\`projects.ts\\`) won't trigger a graceful module rebuild on save and will require a full server restart. The CLI generator (\\`kick g module <name>\\`) follows this convention automatically.\n\n\\`\\`\\`ts\n// src/modules/users/users.module.ts (named <feature>.module.ts)\nimport { defineModule } from '@forinda/kickjs'\nimport { UserController } from './user.controller'\n\nexport const UserModule = defineModule({\n name: 'UserModule',\n build: () => ({\n routes() {\n // Single route set — framework derives the router via buildRoutes(controller).\n return {\n path: '/users',\n controller: UserController,\n }\n },\n }),\n})\n\\`\\`\\`\n\n\\`routes()\\` can also return **an array** to mount multiple route sets under the same module — useful when one feature spans several controllers, or when you want a v1 and v2 surface of the same controller live side-by-side. Each route set carries an optional \\`version\\` field overriding the app default (\\`Application.defaultVersion\\`); the mount path becomes \\`/{apiPrefix}/v{version}{path}\\`:\n\n\\`\\`\\`ts\nimport { defineModule } from '@forinda/kickjs'\nimport { UsersV1Controller } from './v1/users.controller'\nimport { UsersV2Controller } from './v2/users.controller'\nimport { UserAdminController } from './admin/user-admin.controller'\n\nexport const UserModule = defineModule({\n name: 'UserModule',\n build: () => ({\n routes() {\n return [\n // /api/v1/users — legacy surface kept around for older clients\n { path: '/users', version: 1, controller: UsersV1Controller },\n // /api/v2/users — current surface\n { path: '/users', version: 2, controller: UsersV2Controller },\n // /api/v1/admin/users — admin surface, same module, different mount\n { path: '/admin/users', controller: UserAdminController },\n ]\n },\n }),\n})\n\\`\\`\\`\n\nRegister all modules in \\`src/modules/index.ts\\` via \\`defineModules()\\` — a chainable list builder that drops directly into \\`bootstrap({ modules })\\`. \\`kick g module <name>\\` appends \\`.mount(NewModule())\\` to the chain on every generation:\n\n\\`\\`\\`ts\nimport { defineModules } from '@forinda/kickjs'\nimport { UserModule } from './users/user.module'\nimport { TaskModule } from './tasks/task.module'\n\nexport const modules = defineModules().mount(UserModule()).mount(TaskModule())\n\\`\\`\\`\n\nThe flat-array form (\\`AppModuleEntry[] = [UserModule()]\\`) also works and is what \\`kick.config.ts > modules.style: 'class'\\` emits — both shapes feed the same loader.\n\n\\`\\`\\`ts\n// Setting on \\`kick.config.ts\\` to opt out of \\`defineModule\\` codegen.\nexport default defineConfig({\n pattern: 'rest',\n modules: {\n style: 'class', // emits \\`class FooModule implements AppModule { ... }\\`\n // + flat-array registry \\`[FooModule]\\`\n // default is 'define' (defineModule + defineModules chain).\n },\n})\n\\`\\`\\`\n\nWhen the project-wide style and existing module files drift (e.g. \\`style: 'define'\\` on a project that still has class-form modules), \\`kick g module\\` refuses with a pointer to \\`kick codemod modules --experimental --apply\\` which rewrites between the two forms in either direction.\n\n### RequestContext\n\nEvery controller method receives a \\`ctx\\` (alias \\`Ctx<TRoute>\\` or the\nloose \\`RequestContext\\`):\n\n\\`\\`\\`ts\nctx.body // Request body (parsed JSON)\nctx.params // Route params\nctx.query // Query string\nctx.headers // Request headers\nctx.requestId // Auto-generated request ID\nctx.session // Session data (if session middleware enabled)\nctx.file // Uploaded file (single)\nctx.files // Uploaded files (multiple)\n\n// Pagination helpers\nctx.qs(config) // Parse query with filters/sort/pagination\nctx.paginate(handler) // Auto-paginated response\n\n// Response helpers\nctx.json(data) // 200 OK with JSON\nctx.created(data) // 201 Created\nctx.noContent() // 204 No Content\nctx.notFound() // 404 Not Found\nctx.badRequest(msg) // 400 Bad Request\n\\`\\`\\`\n\n> **Context decorators** — when a middleware's only job is to populate \\`ctx.set/get\\` for the handler to read, prefer \\`defineContextDecorator()\\` over \\`@Middleware()\\`. Typed via \\`ContextMeta\\`, supports \\`dependsOn\\` ordering, validates the pipeline at boot. Full pattern reference in \\`AGENTS.md\\` and at <https://forinda.github.io/kick-js/guide/context-decorators>.\n\n## CLI Generators\n\nGenerate code with the \\`kick\\` CLI:\n\n\\`\\`\\`bash\nkick g module <name> # Full module (controller, service, DTOs, repo)\nkick g scaffold <name> <fields> # CRUD module from field definitions\nkick g controller <name> # Standalone controller\nkick g service <name> # Service class\nkick g middleware <name> # Express middleware\nkick g guard <name> # Route guard (auth, roles)\nkick g adapter <name> # AppAdapter with lifecycle hooks\nkick g dto <name> # Zod DTO schema\n\\`\\`\\`\n\n## Adding Packages\n\n\\`\\`\\`bash\nkick add auth # JWT, API key, OAuth strategies\nkick add swagger # OpenAPI docs from decorators\nkick add ws # WebSocket support\nkick add queue # Background jobs (BullMQ/RabbitMQ/Kafka)\nkick add prisma # Prisma ORM adapter\nkick add drizzle # Drizzle ORM adapter\nkick add devtools # Browser debug dashboard\nkick add --list # Show all available packages\n\n# For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and\n# notifications use the BYO recipes in https://forinda.github.io/kick-js/guide/\n# — they wire the upstream library through defineAdapter()/definePlugin() directly.\n\\`\\`\\`\n\n## Environment Configuration\n\nThe project's typed env schema lives in **\\`src/config/index.ts\\`** —\nextend the base schema there with your application-specific keys, and\nthe schema is auto-registered with kickjs at module load. The companion\n\\`src/index.ts\\` imports it as a side effect (\\`import './config'\\`) **before**\n\\`bootstrap()\\` runs, so every \\`@Service\\`, \\`@Controller\\`, \\`@Value\\`, and\n\\`ConfigService\\` resolution sees the validated extended values.\n\n> **Do not delete \\`import './config'\\` from \\`src/index.ts\\`.** It is the\n> registration step that wires \\`ConfigService\\` to your env schema.\n> Without it, \\`config.get('YOUR_KEY')\\` returns \\`undefined\\` for every\n> user-defined key and \\`@Value('YOUR_KEY')\\` only works because of a\n> raw \\`process.env\\` fallback (Zod coercion + defaults are skipped).\n\nEdit \\`.env\\` for variable values. Access them with \\`@Value()\\`:\n\n\\`\\`\\`ts\nimport { Value } from '@forinda/kickjs'\n\n@Service()\nexport class ApiService {\n @Value('API_KEY')\n private apiKey!: string\n\n @Value('PORT', 3000) // With default\n private port!: number\n}\n\\`\\`\\`\n\nOr use \\`ConfigService\\`:\n\n\\`\\`\\`ts\nimport { Service, Autowired, ConfigService } from '@forinda/kickjs'\n\n@Service()\nexport class AppService {\n @Autowired()\n private config!: ConfigService\n\n getPort() {\n // typed: number, Zod-coerced from baseEnvSchema\n return this.config.get('PORT')\n }\n}\n\\`\\`\\`\n\nHot-reload of \\`.env\\` changes during dev is wired up automatically via\n\\`envWatchPlugin()\\` in \\`vite.config.ts\\` — edit \\`.env\\`, the dev server\nreloads, and the next \\`config.get()\\` re-parses with the new values.\n\n### Standalone Env Utilities (No DI Required)\n\nThese functions work anywhere — scripts, CLI tools, plain files, outside \\`@Service\\`/\\`@Controller\\`:\n\n\\`\\`\\`ts\nimport { defineEnv, loadEnv, getEnv, reloadEnv, resetEnvCache, baseEnvSchema } from '@forinda/kickjs/config'\nimport { z } from 'zod'\n\n// Define and parse schema\nconst schema = defineEnv((base) =>\n base.extend({ DATABASE_URL: z.string().url() })\n)\nconst env = loadEnv(schema) // Parse + validate process.env\nconsole.log(env.PORT) // 3000 (coerced to number)\nconsole.log(env.DATABASE_URL) // validated URL string\n\n// Get single value\nconst port = getEnv('PORT') // typed after kick typegen\n\n// Reload after .env changes (HMR calls this automatically)\nreloadEnv()\n\n// Reset cache in tests that swap schemas\nresetEnvCache()\n\\`\\`\\`\n\n| Function | Purpose |\n|----------|---------|\n| \\`defineEnv(fn)\\` | Extend base schema with custom Zod keys |\n| \\`loadEnv(schema?)\\` | Parse \\`process.env\\`, validate, cache, return typed object |\n| \\`getEnv(key, schema?)\\` | Get single validated env value |\n| \\`reloadEnv()\\` | Re-read \\`.env\\` from disk, re-parse with same schema |\n| \\`resetEnvCache()\\` | Clear parsed cache AND registered schema (for tests) |\n| \\`baseEnvSchema\\` | Base Zod schema: \\`PORT\\`, \\`NODE_ENV\\`, \\`LOG_LEVEL\\` |\n\n## Standalone Utilities (No DI Required)\n\nThese utilities work outside decorated classes:\n\n### Logger\n\n\\`\\`\\`ts\nimport { Logger, createLogger } from '@forinda/kickjs'\n\nconst log = Logger.for('MyScript') // Static factory\nlog.info('Processing started')\nlog.error('Something failed')\n\nconst log2 = createLogger('Worker') // Function form\n\\`\\`\\`\n\n### Injection Tokens\n\n\\`\\`\\`ts\nimport { createToken } from '@forinda/kickjs'\n\n// Type-safe DI tokens for factory/interface binding.\n// Convention: '<scope>/<PascalKey>[/<suffix>]' — scope lowercase, key PascalCase.\nconst DB_URL = createToken<string>('app/Config/database-url')\nconst FEATURE_FLAGS = createToken<FeatureFlags>('app/Features')\n\\`\\`\\`\n\n### Reactivity\n\n\\`\\`\\`ts\nimport { ref, computed, watch, reactive } from '@forinda/kickjs'\n\nconst count = ref(0)\nconst doubled = computed(() => count.value * 2)\nconst stop = watch(() => count.value, (val) => console.log(val))\ncount.value++ // logs 1\n\\`\\`\\`\n\n### HTTP Errors\n\n\\`\\`\\`ts\nimport { HttpException, HttpStatus } from '@forinda/kickjs'\n\nthrow new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n\\`\\`\\`\n\n## Testing\n\nTests live in \\`src/**/*.test.ts\\`:\n\n\\`\\`\\`ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\ndescribe('UserController', () => {\n beforeEach(() => Container.reset())\n\n it('should return users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/users')\n expect(res.status).toBe(200)\n })\n})\n\\`\\`\\`\n\nRun tests:\n- \\`${pm} run test\\` — run all tests\n- \\`${pm} run test:watch\\` — watch mode\n\n## Decorators Reference\n\n### Route Decorators\n- \\`@Controller()\\` — mark a class as an HTTP controller (path comes from \\`routes().path\\`)\n- \\`@Get('/'), @Post('/'), @Put('/'), @Delete('/'), @Patch('/')\\` — HTTP methods\n- \\`@Middleware(fn)\\` — attach middleware\n- \\`@Public()\\` — skip authentication (requires @forinda/kickjs-auth)\n- \\`@Roles('admin', 'user')\\` — role-based access control\n\n### DI Decorators\n- \\`@Service()\\` — singleton service (DI-registered)\n- \\`@Repository()\\` — repository (semantic alias for @Service)\n- \\`@Autowired()\\` — property injection\n- \\`@Inject('token')\\` — token-based injection\n- \\`@Value('ENV_VAR')\\` — inject config value\n\n## Common Pitfalls\n\n1. **Decorators fire at import time** — make sure to import module classes in \\`src/modules/index.ts\\`\n2. **Tests need \\`Container.reset()\\`** — call in \\`beforeEach\\` to isolate DI state\n3. **Always use \\`ctx.body\\`** — never \\`req.body\\` directly\n4. **DI requires \\`reflect-metadata\\`** — already imported in \\`src/index.ts\\`\n5. **Vite HMR requires proper cleanup** — adapters should implement \\`shutdown()\\`\n6. **Never delete \\`import './config'\\` from \\`src/index.ts\\`** — that side-effect import registers the env schema with kickjs. Without it \\`ConfigService.get('YOUR_KEY')\\` returns \\`undefined\\` for every user-defined key. \\`@Value('YOUR_KEY')\\` *appears* to keep working but only via a raw \\`process.env\\` fallback (Zod coercion + schema defaults are silently skipped).\n\n## Learn More\n\n- [KickJS Documentation](https://forinda.github.io/kick-js/)\n- [API Reference](https://forinda.github.io/kick-js/api/)\n- [CLI Commands](https://forinda.github.io/kick-js/guide/cli-commands.html)\n- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)\n`\n}\n\n/** Generate AGENTS.md with AI agent guide */\nexport function generateAgents(name: string, template: ProjectTemplate, pm: string): string {\n return `# AGENTS.md — AI Agent Guide for ${name}\n\nThis guide is the **canonical, multi-agent reference** for this KickJS\napplication — Claude, Copilot, Codex, Gemini, etc. all read it first.\nPer-agent files (\\`CLAUDE.md\\`, \\`GEMINI.md\\`, etc.) are thin layers that\nadd tool-specific affordances on top.\n\n## Before You Start\n\n1. Run \\`${pm} install\\` to install dependencies\n2. Run \\`kick dev\\` to verify the app starts\n3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details\n\n## v4 Conventions (don't skip)\n\nKickJS v4 made a handful of structural changes from v3. Internalise these\nbefore generating or modifying code — they are the source of most agent\nmistakes:\n\n- **Adapters** — \\`defineAdapter()\\` factory. Never write \\`class Foo implements AppAdapter\\`.\n\n \\`\\`\\`ts\n export const MyAdapter = defineAdapter<MyOptions>({\n name: 'MyAdapter',\n defaults: { ... },\n build: (config) => ({\n beforeMount({ app }) { /* ... */ },\n afterStart({ server }) { /* ... */ },\n }),\n })\n \\`\\`\\`\n\n- **Plugins** — \\`definePlugin()\\` factory. Same shape, never plain function returning \\`KickPlugin\\`.\n\n- **DI tokens** — \\`<scope>/<PascalKey>[/<suffix>]\\`. Scope is lowercase,\n the key segment is **PascalCase** (the regex enforces both):\n\n \\`\\`\\`ts\n const USERS_REPO = createToken<UsersRepo>('app/Users/repository')\n const DB = createToken<Database>('app/Db/connection')\n \\`\\`\\`\n\n The \\`kick/\\` prefix is reserved for first-party packages; this project\n owns its own scope (\\`app/\\`, your domain name, etc.).\n\n- **\\`@Controller()\\`** takes **no path argument**. Mount prefix comes from\n the module's \\`routes()\\` return value, not the decorator. \\`@Controller('/users')\\`\n is a v3 leftover; the linter and codegen reject it.\n\n- **Env wiring** — \\`src/config/index.ts\\` calls \\`loadEnv(envSchema)\\` as a\n side effect. \\`src/index.ts\\` MUST have \\`import './config'\\` as its **first**\n import (before \\`bootstrap()\\`). Without it, \\`ConfigService.get('YOUR_KEY')\\`\n returns \\`undefined\\` and \\`@Value()\\` only works via raw \\`process.env\\` fallback\n (Zod coercion + defaults silently skipped).\n\n- **Module entry files MUST be named \\`<name>.module.ts\\`** — see the Vite\n HMR contract at the top of \"Module Pattern\" below. The CLI enforces this;\n hand-rolled files must too.\n\n- **Assets** — drop new template files into \\`src/templates/<namespace>/\\`\n (or wherever \\`kick.config.ts\\` points). The dev watcher auto-rebuilds the\n \\`KickAssets\\` augmentation; \\`assets.x.y()\\` re-walks on next call. No restart,\n no manual build step.\n\n- **Context over \\`@Middleware()\\`** — when a middleware's only job is to\n populate \\`ctx.set('key', value)\\`, use \\`defineHttpContextDecorator()\\`\n (HTTP) or \\`defineContextDecorator()\\` (transport-agnostic) instead.\n Typed via \\`ContextMeta\\`, ordered via \\`dependsOn\\`, validated at boot.\n Reserve \\`@Middleware()\\` for response short-circuit / stream mutation /\n pre-route-matching work.\n\n Two ground rules around the data flow — both stem from the fact that\n every per-request stage gets its OWN \\`RequestContext\\` instance, all\n reading/writing the SAME \\`AsyncLocalStorage\\`-backed Map:\n - **\\`resolve\\` and \\`onError\\` must RETURN the value.** The runner\n writes it via \\`ctx.set(reg.key, value)\\` on your behalf. Direct\n property assignment (\\`ctx.tenant = …\\`) sticks to the contributor\n instance only — the handler instance never sees it.\n - **Read across instances via \\`ctx.set\\` / \\`ctx.get\\`** (or\n \\`getRequestValue(key)\\` from a service that has no \\`ctx\\` reference\n — typed via \\`MetaValue<K>\\`). \\`ctx.req\\` works because the underlying\n Express request is shared; bespoke property assignments don't.\n\n- **Test isolation** — default to \\`Container.create()\\` for fresh DI state.\n Never \\`new Container()\\` and never \\`getInstance().reset()\\` — both leak\n registrations between tests.\n\n \\`\\`\\`ts\n const container = Container.create()\n // ... register test-scoped providers, run, discard\n \\`\\`\\`\n\n- **Bootstrap export** — \\`src/index.ts\\` MUST end with\n \\`export const app = await bootstrap({ ... })\\`. The Vite plugin imports\n the named \\`app\\` symbol to drive HMR module swaps; testing helpers\n (\\`createTestApp\\`) and the OpenAPI introspector also rely on it. Drop\n the \\`export\\` and \\`kick dev\\` will silently fall back to a full restart\n on every save while \\`createTestApp\\` complains about a missing handle.\n\n- **Keep \\`src/index.ts\\` thin** — collect plugins, modules, middleware, and\n adapters in dedicated folders and re-export aggregated arrays. Do **not**\n inline registration in the entry file:\n\n \\`\\`\\`ts\n // src/modules/index.ts — fluent chain (default for \\`modules.style: 'define'\\`)\n export const modules = defineModules().mount(HelloModule()).mount(UsersModule())\n // OR with \\`modules.style: 'class'\\`:\n // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]\n\n // src/middleware/index.ts\n export const middleware = [helmet(), cors(), requestId(), ...]\n\n // src/plugins/index.ts\n export const plugins = [MetricsPlugin(), AuditPlugin()]\n\n // src/adapters/index.ts\n export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]\n \\`\\`\\`\n\n \\`\\`\\`ts\n // src/index.ts — stays small; one import per category\n import 'reflect-metadata'\n import './config'\n import { bootstrap } from '@forinda/kickjs'\n import { modules } from './modules'\n import { middleware } from './middleware'\n import { plugins } from './plugins'\n import { adapters } from './adapters'\n\n export const app = await bootstrap({ modules, middleware, plugins, adapters })\n \\`\\`\\`\n\n This keeps the entry file diff-friendly, scales to dozens of modules\n without git churn, and lets each domain own its own registration list.\n The generators (\\`kick g module\\`, \\`kick g middleware\\`, \\`kick g plugin\\`,\n \\`kick g adapter\\`) follow this layout — manual additions should too.\n\nEverything else (controllers, services, modules, RequestContext API, generators,\npackage additions, env access patterns, troubleshooting) is detailed below.\n\n## Where to Find Things\n\n### Application Structure\n\n| What | Where |\n|------|-------|\n| Entry point | \\`src/index.ts\\` |\n| Module registry | \\`src/modules/index.ts\\` |\n| Feature modules | \\`src/modules/<module-name>/\\` |\n| **Module entry file** | \\`src/modules/<name>/<name>.module.ts\\` (filename suffix is required — see Vite HMR contract below) |\n| Env values | \\`.env\\` |\n| Env schema (Zod) | \\`src/config/index.ts\\` |\n| TypeScript config | \\`tsconfig.json\\` |\n| Vite config (HMR) | \\`vite.config.ts\\` |\n| Vitest config | \\`vitest.config.ts\\` |\n| Prettier config | \\`.prettierrc\\` |\n| CLI config | \\`kick.config.ts\\` |\n\n### Module Pattern (${template.toUpperCase()})\n\n> **Vite HMR auto-discovery contract:** module files **must** be named \\`<name>.module.ts\\` (or \\`.tsx\\`/\\`.js\\`/\\`.jsx\\`) and live under \\`src/modules/\\`. The Vite plugin scans for \\`*.module.[tj]sx?\\` to drive graceful HMR rebuilds; renaming a file to \\`projects.ts\\` (no \\`.module\\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\\`kick g module <name>\\`) follows the convention; manual files must too.\n\nEach module in \\`src/modules/<name>/\\` typically contains:\n\n${\n template === 'rest'\n ? `\\`\\`\\`\n<name>/\n├── <name>.controller.ts # HTTP routes (@Controller)\n├── <name>.service.ts # Business logic (@Service)\n├── <name>.repository.ts # Data access (@Repository)\n├── dtos/ # Request/response schemas (Zod)\n└── <name>.module.ts # Module definition (defineModule factory)\n\\`\\`\\`\n`\n : `\\`\\`\\`\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n\\`\\`\\`\n`\n}\n\n## Checklist: Adding a Feature\n\n### New Module (Recommended)\n\nUse the CLI generator for consistency:\n\n\\`\\`\\`bash\nkick g module <name> # Generate full module\n# or\nkick g scaffold <name> <fields> # Generate CRUD from fields\n\\`\\`\\`\n\nThen:\n- [ ] Review generated files in \\`src/modules/<name>/\\`\n- [ ] Verify module is registered in \\`src/modules/index.ts\\`\n- [ ] Update DTOs in \\`<name>.dto.ts\\` if needed\n- [ ] Implement business logic in \\`<name>.service.ts\\`\n- [ ] Run \\`kick dev\\` to test with HMR\n- [ ] Write tests in \\`<name>.test.ts\\`\n\n### Manual Controller\n\nIf not using generators:\n\n- [ ] Create \\`src/modules/<name>/<name>.controller.ts\\`\n- [ ] Add \\`@Controller()\\` decorator\n- [ ] Add route handlers with \\`@Get()\\`, \\`@Post()\\`, etc.\n- [ ] Create module file with \\`defineModule({ name, build: () => ({ routes() { return { path, controller } } }) })\\` — the framework derives the Express router from the controller. Class-form (\\`class XModule implements AppModule\\`) is the legacy alternative; toggle via \\`kick.config.ts > modules.style\\`.\n- [ ] Register module in \\`src/modules/index.ts\\`. Default form is the fluent chain: \\`defineModules().mount(MyModule()).mount(...)\\`. \\`kick g module <name>\\` appends \\`.mount(NewModule())\\` automatically.\n- [ ] Test with \\`kick dev\\`\n\n### Manual Service\n\n- [ ] Create \\`src/modules/<name>/<name>.service.ts\\`\n- [ ] Add \\`@Service()\\` decorator\n- [ ] Inject dependencies with \\`@Autowired()\\`\n- [ ] Inject via \\`@Autowired()\\` where needed\n- [ ] Write unit tests\n\n### New Middleware\n\n- [ ] Create \\`src/middleware/<name>.middleware.ts\\`\n- [ ] Export middleware function (Express format)\n- [ ] Register in \\`src/index.ts\\` or attach to routes with \\`@Middleware()\\`\n- [ ] Test with sample requests\n\n### Adding a Package\n\nUse \\`kick add\\` to install KickJS packages with correct peer dependencies:\n\n- [ ] Run \\`kick add <package>\\` (e.g., \\`kick add auth\\`)\n- [ ] Follow package-specific setup in terminal output\n- [ ] Update \\`src/index.ts\\` to register adapter (if needed)\n- [ ] Configure environment variables in \\`.env\\`\n- [ ] Test integration with \\`kick dev\\`\n\n## Common Tasks\n\n### Generate CRUD Module\n\n\\`\\`\\`bash\nkick g scaffold user name:string email:string:optional age:number\n\\`\\`\\`\n\nAppend \\`:optional\\` for optional fields (shell-safe, no quoting needed).\nQuoted \\`?\\` syntax also works: \\`\"email:string?\"\\` or \\`\"email?:string\"\\`.\n\nThis creates a full CRUD module with:\n- Controller with GET, POST, PUT, DELETE routes\n- Service with business logic\n- Repository with data access\n- DTOs with Zod validation\n\n### Add Authentication\n\n\\`\\`\\`bash\nkick add auth\n\\`\\`\\`\n\nThen configure in \\`src/index.ts\\`:\n\n\\`\\`\\`ts\nimport { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'\n\nbootstrap({\n modules,\n adapters: [\n AuthAdapter({\n strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],\n }),\n ],\n})\n\\`\\`\\`\n\n### Add Database (Prisma)\n\n\\`\\`\\`bash\nkick add prisma\n${pm} install prisma @prisma/client\nnpx prisma init\n# Edit prisma/schema.prisma\nnpx prisma migrate dev --name init\nkick g module user --repo prisma\n\\`\\`\\`\n\n### Add WebSocket Support\n\n\\`\\`\\`bash\nkick add ws\n\\`\\`\\`\n\nThen add adapter in \\`src/index.ts\\`:\n\n\\`\\`\\`ts\nimport { WsAdapter } from '@forinda/kickjs-ws'\n\nbootstrap({\n modules,\n adapters: [WsAdapter()],\n})\n\\`\\`\\`\n\nCreate WebSocket controller:\n\n\\`\\`\\`bash\nkick g controller chat --ws\n\\`\\`\\`\n\n## Testing Guidelines\n\nAll tests use Vitest:\n\n\\`\\`\\`ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\ndescribe('UserController', () => {\n it('should return users', async () => {\n // Container.create() — isolated DI state per test, never new Container()\n // and never getInstance().reset() (both leak registrations between tests).\n const container = Container.create()\n const app = await createTestApp([UserModule], { container })\n const res = await app.get('/users')\n\n expect(res.status).toBe(200)\n expect(res.body).toHaveProperty('users')\n })\n})\n\\`\\`\\`\n\nRun tests:\n- \\`${pm} run test\\` — run all tests once\n- \\`${pm} run test:watch\\` — watch mode\n- Individual file: \\`${pm} run test src/modules/user/user.test.ts\\`\n\n## Environment Variables\n\nSchema is declared in \\`src/config/index.ts\\` (extends the base\n\\`PORT\\`/\\`NODE_ENV\\`/\\`LOG_LEVEL\\` shape via \\`defineEnv\\`) and registered\nwith kickjs at module load. \\`src/index.ts\\` imports it via\n\\`import './config'\\` **before** \\`bootstrap()\\` so the cache is populated\nin time for DI. Add new keys to the schema, drop their values into\n\\`.env\\`, and they're typed everywhere.\n\nAccess patterns:\n\n1. **@Value() decorator** (recommended for known-at-construction keys):\n\\`\\`\\`ts\n@Value('DATABASE_URL')\nprivate dbUrl!: string\n\\`\\`\\`\n\n2. **ConfigService** (recommended for dynamic / method-scoped access):\n\\`\\`\\`ts\n@Autowired()\nprivate config!: ConfigService\n\nconst port = this.config.get('PORT') // typed: number\n\\`\\`\\`\n\n3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):\n\\`\\`\\`ts\nimport { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'\n\nconst env = loadEnv(schema) // Parse + validate all vars\nconst port = getEnv('PORT') // Single value lookup\nreloadEnv() // Re-read .env from disk\nresetEnvCache() // Full reset (for tests)\n\\`\\`\\`\n\n4. **Direct \\`process.env\\`** — avoid in app code; bypasses Zod\n coercion and the typed \\`KickEnv\\` registry.\n\n> **Pitfall**: never delete \\`import './config'\\` from \\`src/index.ts\\`.\n> If the schema is not registered before DI runs, \\`config.get()\\`\n> returns \\`undefined\\` for user keys (the base shape only) and\n> \\`@Value()\\` only works because of its raw \\`process.env\\` fallback —\n> Zod coercion + schema defaults are silently skipped.\n\n## Standalone Utilities (No DI Required)\n\nThese work anywhere — scripts, plain files, outside \\`@Service\\`/\\`@Controller\\`:\n\n| Utility | Import | Example |\n|---------|--------|---------|\n| \\`Logger.for(name)\\` | \\`@forinda/kickjs\\` | \\`const log = Logger.for('MyScript')\\` |\n| \\`createLogger(name)\\` | \\`@forinda/kickjs\\` | \\`const log = createLogger('Worker')\\` |\n| \\`createToken<T>(name)\\` | \\`@forinda/kickjs\\` | \\`const TOKEN = createToken<string>('app/Db/url')\\` |\n| \\`ref(value)\\` | \\`@forinda/kickjs\\` | \\`const count = ref(0)\\` |\n| \\`computed(fn)\\` | \\`@forinda/kickjs\\` | \\`const doubled = computed(() => count.value * 2)\\` |\n| \\`watch(source, cb)\\` | \\`@forinda/kickjs\\` | \\`watch(() => count.value, (v) => log(v))\\` |\n| \\`reactive(obj)\\` | \\`@forinda/kickjs\\` | \\`const state = reactive({ count: 0 })\\` |\n| \\`HttpException\\` | \\`@forinda/kickjs\\` | \\`throw new HttpException(404, 'Not found')\\` |\n| \\`HttpStatus\\` | \\`@forinda/kickjs\\` | \\`HttpStatus.NOT_FOUND // 404\\` |\n\n## Key Decorators\n\n### HTTP Routes\n| Decorator | Purpose |\n|-----------|---------|\n| \\`@Controller()\\` | Define route prefix |\n| \\`@Get('/'), @Post('/')\\` | HTTP method handlers |\n| \\`@Middleware(fn)\\` | Attach middleware |\n| \\`@Public()\\` | Skip auth (requires auth adapter) |\n| \\`@Roles('admin')\\` | Role-based access |\n\n### Dependency Injection\n| Decorator | Purpose |\n|-----------|---------|\n| \\`defineModule({...})\\` | Define feature module (factory; preferred — paired with \\`defineModules()\\` registry) |\n| \\`defineModules()\\` | Build the modules registry as a chainable list (\\`.mount(X())\\`) |\n| \\`AppModule\\` interface | Legacy module shape — \\`class X implements AppModule\\` (toggle via \\`modules.style: 'class'\\`) |\n| \\`@Service()\\` | Register singleton service |\n| \\`@Repository()\\` | Register repository |\n| \\`@Autowired()\\` | Property injection |\n| \\`@Inject('token')\\` | Token-based injection |\n| \\`@Value('VAR')\\` | Inject env variable |\n\n### Context Decorators\n\nTyped, ordered way to populate \\`ctx.set/get\\` keys before the handler runs.\nUse this **instead of \\`@Middleware()\\`** when the middleware's only output\nis a value other code reads off \\`ctx\\`.\n\n| Concept | Where it lives |\n|---------|----------------|\n| \\`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\\` | \\`@forinda/kickjs\\` |\n| Method/class decorator | \\`@LoadX\\` on a controller method/class |\n| Module hook | \\`build: () => ({ contributors() { return [...] } })\\` (\\`defineModule\\`) — or \\`AppModule.contributors?()\\` for class form |\n| Adapter hook | \\`AppAdapter.contributors?(): ContributorRegistration[]\\` |\n| Global registration | \\`bootstrap({ contributors: [LoadX.registration] })\\` |\n| Type augmentation | \\`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\\` |\n\nPrecedence high → low: **method > class > module > adapter > global**.\nCycles and missing \\`dependsOn\\` keys throw at \\`app.setup()\\` (boot fails\nfast). The \\`onError\\` hook is async-permitted.\n\nFull guide: <https://forinda.github.io/kick-js/guide/context-decorators>.\n\n## Common Pitfalls\n\n1. **Forgot to register module** — Add to \\`src/modules/index.ts\\` exports array\n2. **DI not working** — Ensure \\`reflect-metadata\\` is imported in \\`src/index.ts\\`\n3. **Tests failing randomly** — Sharing the global container between tests. Default to \\`Container.create()\\` per test (or per \\`beforeEach\\`) instead of \\`new Container()\\` / \\`getInstance().reset()\\`\n4. **Routes not found** — Check controller path and module registration\n5. **HMR not working** — Two checks: (a) \\`vite.config.ts\\` has \\`hmr: true\\`; (b) module file is named \\`<name>.module.ts\\` (or \\`.tsx\\`/\\`.js\\`/\\`.jsx\\`) and lives under \\`src/modules/\\`. The Vite plugin auto-discovers \\`*.module.[tj]sx?\\` for graceful HMR — a misnamed module file (e.g., \\`projects.ts\\`) silently degrades to a full restart on every save.\n6. **Decorators not working** — Check \\`tsconfig.json\\` has \\`experimentalDecorators: true\\`\n7. **\\`config.get('YOUR_KEY')\\` returns \\`undefined\\`** — \\`src/index.ts\\` is missing \\`import './config'\\`. That side-effect import registers the env schema with kickjs (\\`loadEnv(envSchema)\\` runs at module load). Without it, \\`ConfigService\\` falls back to the base schema (\\`PORT\\`/\\`NODE_ENV\\`/\\`LOG_LEVEL\\` only) and every user-defined key reads as \\`undefined\\`. \\`@Value()\\` may *appear* to work because of a raw \\`process.env\\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \\`src/index.ts\\` and \\`src/config/index.ts\\` first.\n8. **Used \\`@Middleware()\\` to compute a value for \\`ctx\\`** — prefer \\`defineContextDecorator()\\` (see Context Decorators above). It's typed via \\`ContextMeta\\`, supports \\`dependsOn\\` for ordering, and validates the pipeline at boot. \\`@Middleware()\\` is for response short-circuiting, stream mutation, and pre-route-matching work.\n9. **Context contributor's \\`dependsOn\\` key not produced anywhere** — boot throws \\`MissingContributorError\\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).\n10. **\\`bootstrap()\\` not exported** — \\`src/index.ts\\` calls \\`await bootstrap({ ... })\\` but discards the return value (no \\`export const app = ...\\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \\`createTestApp\\`/\\`@forinda/kickjs-testing\\` consumers can't import the handle either. Always: \\`export const app = await bootstrap({ ... })\\`.\n11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \\`kick g agents -f\\` (or \\`kick g agent-docs -f\\`) to regenerate from the latest CLI templates after \\`kick add\\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \\`AGENTS.local.md\\`.\n\n## CLI Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| \\`kick dev\\` | Dev server with HMR |\n| \\`kick dev:debug\\` | Dev server with debugger |\n| \\`kick build\\` | Production build |\n| \\`kick start\\` | Run production build |\n| \\`kick g module <names...>\\` | Generate one or more modules |\n| \\`kick g scaffold <name> <fields>\\` | Generate CRUD |\n| \\`kick g controller <name>\\` | Generate controller |\n| \\`kick g service <name>\\` | Generate service |\n| \\`kick g middleware <name>\\` | Generate middleware |\n| \\`kick add <package>\\` | Add KickJS package |\n| \\`kick add --list\\` | List available packages |\n| \\`kick rm module <names...>\\` | Remove one or more modules |\n\n> **Note:** When using \\`kick new\\` in scripts or CI, pass \\`-t\\` (or \\`--template\\`) and \\`-r\\` (or \\`--repo\\`) flags to bypass interactive prompts:\n> \\`\\`\\`bash\n> kick new my-api -t ddd -r prisma --pm ${pm} --no-git --no-install -f\n> \\`\\`\\`\n\n## Learn More\n\n- [KickJS Docs](https://forinda.github.io/kick-js/)\n- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)\n- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)\n- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)\n- [Testing](https://forinda.github.io/kick-js/api/testing.html)\n`\n}\n\n/**\n * One emitted skill — slug becomes the directory name under\n * `.agents/skills/<slug>/SKILL.md`. `frontmatterName` is the value\n * agents use to look the skill up at activation time and follows the\n * `kickjs-<slug>` convention to keep the skill registry namespaced.\n */\nexport interface KickJsSkillFile {\n /** kebab-case directory name (`add-module`, `write-controller-test`). */\n slug: string\n /** Full SKILL.md content with YAML frontmatter + body. */\n content: string\n}\n\n/**\n * Render every KickJS task-skill as its own `SKILL.md` file, ready to\n * write under `.agents/skills/<slug>/SKILL.md`. Each file follows the\n * standard Claude Code skill format:\n *\n * ```\n * ---\n * name: kickjs-<slug>\n * description: <when to use this skill>\n * ---\n *\n * <body>\n * ```\n *\n * Agents that auto-discover skills from `.agents/skills/` (Claude\n * Code, Copilot CLI plugins, Gemini's activate_skill) pick each up by\n * its frontmatter without us shipping an index file. The legacy\n * single-file format (`kickjs-skills.md`) is gone — adopters with\n * existing root-level copies keep them untouched until they run\n * `kick g agents -f --only skills`, which emits the new layout\n * alongside without deleting the old file.\n */\nexport function generateKickJsSkillFiles(\n name: string,\n _template: ProjectTemplate,\n pm: string,\n): KickJsSkillFile[] {\n const banner = `<!-- Generated by \\`kick g agents\\` for ${name}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`\n\n const skills: Array<{\n slug: string\n frontmatterName: string\n description: string\n body: string\n }> = [\n {\n slug: 'add-module',\n frontmatterName: 'kickjs-add-module',\n description:\n 'Use when the user asks to add a new feature module (controller + service + repo + DTOs).',\n body: `**Trigger phrases**: \"add a users module\", \"scaffold tasks\", \"new feature for X\".\n\n**Steps**:\n1. Run \\`kick g module <name>\\` (use plural form if the project pluralizes — check \\`kick.config.ts\\`).\n2. Verify the new folder under \\`src/modules/<name>/\\` contains \\`<name>.module.ts\\` (filename suffix is mandatory for Vite HMR).\n3. Confirm the module appears in \\`src/modules/index.ts\\` exports — generator does this automatically; verify if you bypassed it.\n4. Open \\`<name>.dto.ts\\` and tighten the Zod schemas to real fields (the generator emits placeholders).\n5. Run \\`${pm} run typecheck\\` and \\`${pm} run test\\` before claiming done.\n\n**Canonical module shape** — \\`defineModule\\` factory, never \\`class implements AppModule\\`:\n\n\\`\\`\\`ts\nexport const TodosModule = defineModule({\n name: 'TodosModule',\n build: () => ({\n register(container) {\n container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))\n },\n routes() {\n return { path: '/todos', controller: TodosController }\n },\n }),\n})\n\\`\\`\\`\n\nThe module file MUST include \\`import.meta.glob([...], { eager: true })\\` for every \\`@Service\\` / \\`@Repository\\` / \\`@Component\\` class — without it, decorators never fire and DI silently resolves to \\`undefined\\`.\n\n**Multiple route sets / versioning** — \\`routes()\\` may return an array with per-entry \\`version\\` override:\n\n\\`\\`\\`ts\nroutes() {\n return [\n { path: '/todos', controller: TodosController }, // /api/v1/todos\n { path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos\n ]\n}\n\\`\\`\\`\n\n**Conditional / per-tenant mounting** — use \\`bootstrap({ setup(registry) { registry.mount(...) } })\\`, not the static \\`modules\\` array.\n\n**Composition** — \\`defineModules().mount(TodosModule()).mount(UsersModule())\\` (fluent) or \\`AppModuleEntry[]\\` (array form).\n\n**Red flags** (stop and ask):\n- File created as \\`<name>.ts\\` instead of \\`<name>.module.ts\\` — Vite plugin's \\`*.module.[tj]sx?\\` glob doesn't pick it up; every save becomes a full restart.\n- \\`@Controller('/path')\\` with a path argument combined with module \\`routes().path\\` — duplicates the prefix. The decorator path is OpenAPI metadata only.\n- \\`TodosModule\\` in \\`bootstrap({ modules: [TodosModule] })\\` instead of \\`TodosModule()\\` — passing the factory instead of the invoked instance.\n- \\`routes()\\` returning \\`router: …\\` when a \\`controller:\\` would do — controller form is required for OpenAPI/Swagger introspection.\n- Module not registered in \\`src/modules/index.ts\\`.`,\n },\n {\n slug: 'add-adapter',\n frontmatterName: 'kickjs-add-adapter',\n description:\n 'Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).',\n body: `**Steps**:\n1. \\`kick g adapter <name>\\` to scaffold the boilerplate, OR install via \\`kick add <package>\\` for first-party adapters.\n2. The generated file uses \\`defineAdapter()\\` — never \\`class implements AppAdapter\\`.\n3. Add the adapter instance (note the parens) to \\`src/adapters/index.ts\\` — don't inline in \\`src/index.ts\\`.\n4. Pick the right hook and middleware phase deliberately.\n5. Verify with \\`kick dev\\` that the adapter's lifecycle logs fire.\n\n**Canonical shape** — factory closure owns instance state:\n\n\\`\\`\\`ts\nexport const RedisAdapter = defineAdapter<RedisConfig>({\n name: 'RedisAdapter',\n defaults: { url: 'redis://localhost' },\n build: (config) => {\n const client = createClient(config.url)\n return {\n beforeStart: ({ container }) => {\n container.registerInstance(REDIS_CLIENT, client)\n },\n afterStart: () => client.connect(),\n shutdown: () => client.quit(),\n }\n },\n})\n\n// In src/adapters/index.ts:\nexport const adapters = [RedisAdapter({ url: env.REDIS_URL })] // <-- note parens\n\\`\\`\\`\n\n**Lifecycle hook decision tree**:\n- \\`beforeMount\\` — register early routes that should bypass middleware (health, docs UI).\n- \\`beforeStart\\` — DI ready, server not listening yet. **Use this for \\`container.registerInstance(...)\\` calls** so they work under \\`createTestApp\\` too.\n- \\`afterStart\\` — server has \\`ctx.server\\` available. Only use for things that need a listening server (Socket.IO upgrades, port logging). **Doesn't fire under \\`createTestApp\\`.**\n- \\`shutdown\\` — runs concurrently via \\`Promise.allSettled\\`, so one failure doesn't block siblings (but errors are swallowed — log inside).\n\n**Middleware phases** (see \\`MiddlewarePhase\\` JSDoc):\n\\`beforeGlobal\\` | \\`afterGlobal\\` (default) | \\`beforeRoutes\\` | \\`afterRoutes\\` (fires only on fall-through — matched routes that respond skip it).\n\n**Multi-instance** — \\`.scoped('cache', { url: ... })\\` makes \\`name\\` become \\`RedisAdapter:cache\\`. **Deferred config** — \\`.async({ inject, useFactory })\\` for config that depends on DI-resolved services.\n\n**Red flags**:\n- \\`bootstrap({ adapters: [MyAdapter] })\\` — passed the factory, not the instance. Call it: \\`MyAdapter()\\`.\n- Inlining the adapter list directly in \\`src/index.ts\\` — entry file should stay thin.\n- Returning a plain object instead of going through \\`defineAdapter()\\` — type inference for \\`config\\` will be wrong.\n- Using \\`.async()\\` for an adapter that returns \\`middleware()\\` / \\`contributors()\\` / \\`beforeMount()\\` / \\`onRouteMount()\\` — those hooks have already run by the time \\`.async()\\` resolves and are silently skipped.\n- Cross-adapter ordering via array position when it's load-bearing — use \\`dependsOn: ['OtelAdapter']\\`; cycles throw \\`MountCycleError\\` at boot.\n- Using an adapter when the integration ships **modules + DI bindings + middleware** together → that's a plugin. Promote to \\`definePlugin()\\` (see \\`add-plugin\\` skill).\n\n**Nuances**:\n- \\`AdapterContext.server\\` is \\`undefined\\` outside \\`afterStart\\`.\n- \\`shutdown\\` errors are swallowed by \\`Promise.allSettled\\` — wrap in try/catch and log if you care.`,\n },\n {\n slug: 'add-plugin',\n frontmatterName: 'kickjs-add-plugin',\n description:\n 'Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).',\n body: `**When plugin > adapter**: a plugin is the right answer when the integration ships **more than one** of: a module, a DI binding, middleware, or another adapter. If you have a single hook (\\`beforeStart\\`) and no other contributions, use \\`defineAdapter\\` instead.\n\n**Canonical shape**:\n\n\\`\\`\\`ts\nimport { definePlugin } from '@forinda/kickjs'\n\nexport const AuthPlugin = definePlugin({\n name: 'AuthPlugin',\n defaults: { tokenTtl: '1h' },\n build: (config, { name }) => ({\n modules: () => [AuthModule()],\n adapters: () => [JwtAdapter({ ttl: config.tokenTtl })],\n middleware: () => [requestIdMiddleware()],\n register(container) {\n container.registerFactory(TOKEN_SIGNER, () => createSigner(config))\n },\n contributors() {\n return [LoadCurrentUser.registration]\n },\n onReady({ server }) {\n log.info(\\`AuthPlugin listening on port \\${server.address().port}\\`)\n },\n }),\n})\n\n// In bootstrap:\nbootstrap({ plugins: [AuthPlugin({ tokenTtl: env.TOKEN_TTL })] }) // <-- parens\n\\`\\`\\`\n\n**Inline plugin literal** — the canonical answer for one-off DI bindings. There's no top-level \\`register:\\` on \\`bootstrap\\` itself:\n\n\\`\\`\\`ts\nbootstrap({\n plugins: [{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } }],\n})\n\\`\\`\\`\n\n**Execution order** (memorize):\nplugin \\`register()\\` → plugin \\`middleware()\\` → plugin \\`modules()\\` + user modules → plugin \\`adapters()\\` + user adapters → server listens → plugin \\`onReady()\\`.\n\n**Static vs dynamic modules**: \\`modules()\\` returning an array is introspectable (Swagger, DevTools see it). \\`setup(registry)\\` is imperative — pick the latter when the module set depends on resolved config.\n\n**Multi-instance** — \\`.scoped('users', { url })\\`; derive unique DI tokens from \\`ctx.name\\` inside \\`build\\`:\n\n\\`\\`\\`ts\nbuild: (config, { name }) => ({\n register(c) {\n c.registerInstance(createToken(\\`cache/\\${name}\\`), client)\n },\n})\n\\`\\`\\`\n\n**Precedence**: plugin contributors land at \\`'adapter'\\` precedence — beat global, lose to module/class/method same-key.\n\n**Red flags**:\n- \\`bootstrap({ plugins: [AuthPlugin] })\\` — passed factory. Call it: \\`AuthPlugin()\\`.\n- Reaching for a plugin when an adapter would do (no modules, no DI bindings, no contributors) — overkill; use \\`defineAdapter()\\`.\n- \\`.async()\\` plugin that depends on \\`modules()\\` / \\`middleware()\\` / \\`adapters()\\` / \\`contributors()\\` — those are dropped. \\`.async()\\` only resolves \\`register()\\` + \\`onReady()\\`.\n- Confusing CLI plugins (\\`defineCliPlugin\\` from \\`@forinda/kickjs-cli\\`) with runtime plugins (\\`definePlugin\\` from \\`@forinda/kickjs\\`) — different surfaces, different registration sites.\n- \\`dependsOn: ['SomePlugin']\\` referring to a plugin not in the boot list — throws \\`MissingMountDepError\\` at boot.\n\n**Nuances**:\n- \\`definition\\` is \\`Object.freeze\\`'d metadata; useful for version checks (\\`compare(AuthPlugin.definition.version, '1.2.0')\\`) — not mountable.`,\n },\n {\n slug: 'write-controller-test',\n frontmatterName: 'kickjs-write-controller-test',\n description: 'Use when adding a Vitest test that exercises an HTTP route or DI graph.',\n body: `**Template** (copy/paste, adjust):\n\n\\`\\`\\`ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\nbeforeEach(() => {\n Container.reset() // isolated DI per test\n})\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/api/v1/users')\n expect(res.status).toBe(200)\n })\n})\n\\`\\`\\`\n\n**Typed handler signature** — pair with \\`kick typegen\\` so \\`ctx.body\\` / \\`params\\` / \\`query\\` are typed by the route's Zod schema:\n\n\\`\\`\\`ts\n@Post('/', { body: createTodoSchema })\ncreate(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route\n ctx.created(await this.service.create(ctx.body))\n}\n\\`\\`\\`\n\n**Red flags**:\n- \\`new Container()\\` — wrong; use \\`Container.reset()\\` in \\`beforeEach\\` or \\`Container.create()\\` for fully isolated graphs.\n- \\`Container.getInstance().reset()\\` — wrong; same fix.\n- Sharing a container instance across \\`it()\\` blocks — leaks registrations between tests.\n- Injecting a \\`Scope.REQUEST\\` service into a \\`SINGLETON\\` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.\n- Calling \\`getRequestValue<string>('traceId')\\` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.\n- Asserting on \\`res.body.requestId\\` when \\`requestId()\\` middleware isn't mounted in the test app — value will be \\`undefined\\`.\n- Using \\`Scope.REQUEST\\` services in a test without mounting \\`requestScopeMiddleware()\\` — \\`getRequestValue\\` silently returns \\`undefined\\`; \\`getRequestStore\\` throws.\n\n**Nuances**:\n- \\`@Inject\\` and \\`@Autowired\\` are interchangeable — same runtime, same types; pick by readability.\n- \\`@Value('MISSING_KEY')\\` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue.`,\n },\n {\n slug: 'env-wiring-check',\n frontmatterName: 'kickjs-env-wiring-check',\n description:\n \"Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.\",\n body: `**Diagnosis (in order)**:\n1. Open \\`src/index.ts\\`. The **first non-\\`reflect-metadata\\`** import MUST be \\`import './config'\\`.\n2. Open \\`src/config/index.ts\\`. It MUST call \\`loadEnv(envSchema)\\` as a top-level side effect — not just declare the schema:\n \\`\\`\\`ts\n import { loadEnv, defineEnv } from '@forinda/kickjs'\n const envSchema = defineEnv((base) => base.extend({ DATABASE_URL: z.string().url() }))\n export const env = loadEnv(envSchema)\n \\`\\`\\`\n3. The new key MUST be declared in the Zod schema. \\`@Value('NEW_KEY')\\` accepts any string at the type level and **falls back to raw \\`process.env\\`** when the schema doesn't know the key — silently skipping Zod coercion.\n4. After adding a key, re-run \\`kick typegen\\` (or restart \\`kick dev\\` if the typegen watcher missed it) so the global \\`KickEnv\\` augmentation picks it up.\n\n**Why \\`@Value\\` \"works\" but \\`ConfigService.get\\` doesn't**: \\`@Value\\` has the \\`process.env\\` fallback that masks missing-side-effect-import bugs; \\`ConfigService\\` has none. If \\`@Value('FOO')\\` returns a value but \\`ConfigService.get('FOO')\\` returns \\`undefined\\`, the side-effect import of \\`./config\\` is missing.\n\n**\\`reloadEnv\\` vs \\`resetEnvCache\\`** — distinct, frequently mixed up:\n- \\`reloadEnv()\\` — re-reads \\`process.env\\` against the **already registered** schema. Use in HMR plugins after \\`.env\\` file changes. Schema survives.\n- \\`resetEnvCache()\\` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.\n\n**Nuances**:\n- \\`loadEnv()\\` cache is **sticky**: once \\`loadEnv(extendedSchema)\\` runs anywhere, no-arg calls reuse it — but only if it actually ran. Schema downgrades silently if \\`src/config/index.ts\\` isn't imported.\n- \\`createConfigService(envSchema)\\` is deprecated; the typegen-driven \\`ConfigService\\` covers it.\n- \\`dotenv\\` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.\n- For HMR-friendly \\`.env\\` edits, add \\`envWatchPlugin()\\` to \\`vite.config.ts\\` — calls \\`reloadEnv()\\` automatically.\n\n**Fix recipe**: add the key to the schema; add \\`import './config'\\` as the first non-reflect-metadata import in \\`src/index.ts\\`; re-run \\`kick typegen\\`.`,\n },\n {\n slug: 'bootstrap-export',\n frontmatterName: 'kickjs-bootstrap-export',\n description:\n \"Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.\",\n body: `**Check** \\`src/index.ts\\`'s last line:\n\n\\`\\`\\`ts\n// CORRECT — Vite plugin + createTestApp import the named \\`app\\` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n\\`\\`\\`\n\nThe Vite plugin imports the named \\`app\\` symbol via \\`virtual:kickjs/app\\`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare \\`await bootstrap(...)\\` with no \\`export\\` — fix by adding \\`export const app =\\`.\n- Re-assigning \\`app\\` later in the file (\\`app = somethingElse\\`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling \\`bootstrap()\\` — only the entry should. Tests use \\`createTestApp\\` instead.`,\n },\n {\n slug: 'thin-entry-file',\n frontmatterName: 'kickjs-thin-entry-file',\n description:\n 'Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.',\n body: `**Refactor target**:\n\n\\`\\`\\`ts\n// src/modules/index.ts — fluent chain (default for \\`modules.style: 'define'\\`)\nexport const modules = defineModules().mount(HelloModule()).mount(UsersModule())\n// OR for class-form projects (\\`modules.style: 'class'\\`):\n// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]\n\n// src/middleware/index.ts — global middleware uses RAW EXPRESS signature\n// (req, res, next), NOT (ctx, next)\nexport const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]\n\n// src/plugins/index.ts\nexport const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]\n\n// src/adapters/index.ts\nexport const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]\n\n// src/index.ts — stays small\nimport 'reflect-metadata'\nimport './config' // MUST be early — side-effect schema load\nimport { bootstrap } from '@forinda/kickjs'\nimport { modules } from './modules'\nimport { middleware } from './middleware'\nimport { plugins } from './plugins'\nimport { adapters } from './adapters'\nexport const app = await bootstrap({ modules, middleware, plugins, adapters })\n\\`\\`\\`\n\n**One-off DI binding** — inline a literal plugin inside \\`plugins\\`, not a top-level option:\n\n\\`\\`\\`ts\nplugins: [\n ...plugins,\n { name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },\n]\n\\`\\`\\`\n\n**Red flags**:\n- Any \\`new SomeAdapter()\\` / \\`SomePlugin()\\` literal inside \\`bootstrap({ ... })\\` instead of imported from a category folder.\n- Mixing middleware signatures: \\`bootstrap({ middleware })\\` is **raw Express** \\`(req, res, next)\\`; \\`@Middleware()\\` decorators are \\`(ctx, next)\\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws \"Cannot read properties of undefined\".\n- \\`bootstrap({ register: ... })\\` — that option doesn't exist. Use an inline plugin.`,\n },\n {\n slug: 'context-contributor',\n frontmatterName: 'kickjs-context-contributor',\n description:\n \"Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).\",\n body: `**Pattern** (HTTP — most common):\n\n\\`\\`\\`ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// Optionally publish discoverability for tooling (Swagger, DevTools)\ndefineAugmentation('ContextMeta', {\n description: 'Per-request tenant resolved from x-tenant-id header.',\n example: { id: 'acme', name: 'Acme Inc' },\n})\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n ctx.json(ctx.get('project'))\n}\n\\`\\`\\`\n\nUse \\`defineContextDecorator\\` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — \\`Ctx\\` defaults to the smaller \\`ExecutionContext\\` surface (\\`get\\` / \\`set\\` / \\`requestId\\` only, no \\`req\\`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw \\`DuplicateContributorError\\`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in \\`dependsOn\\` → \\`ContributorCycleError\\`.\n- \\`dependsOn\\` referring to an unknown key → \\`MissingContributorError\\`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN \\`RequestContext\\` instance, but they all read/write the SAME \\`AsyncLocalStorage\\`-backed bag.\n- **\\`resolve\\` and \\`onError\\` must RETURN the value** — the runner writes it via \\`ctx.set(key, value)\\`. Direct property assignment (\\`ctx.tenant = …\\`) sticks to one instance only and the handler instance never sees it.\n- \\`ctx.set('tenant', x)\\` then \\`ctx.get('tenant')\\` works across instances. \\`ctx.req.headers[...]\\` works (the underlying Express request is shared).\n- Services with no \\`ctx\\` reference: \\`getRequestValue('tenant')\\` returns \\`MetaValue<'tenant'> | undefined\\` (typed via the augmented \\`ContextMeta\\`). For \\`requestId\\` use \\`getRequestStore()\\`.\n- **No \\`setRequestValue\\` — writes flow through \\`ctx.set\\` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- \\`optional: true\\` — \\`resolve\\` throws → key left unset; downstream sees \\`ctx.get(key) === undefined\\`.\n- \\`optional: false\\` (default) + \\`onError\\` — return a fallback value to write; return \\`undefined\\` to skip; throw to forward to the request error handler.\n- \\`optional: false\\` + no \\`onError\\` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep \\`@Middleware()\\` for those.\n\n**Red flags**:\n- \\`ctx.tenant = x\\` instead of returning the value from \\`resolve\\` — sticks to one instance only.\n- \\`defineAugmentation\\` without the \\`declare module\\` block (or vice-versa) — discoverability and types drift apart; \\`ctx.get('tenant')\\` becomes \\`unknown\\`.\n- Plugin / adapter authors using bare keys (\\`'state'\\`) instead of namespaced (\\`'@my-plugin/state'\\`) — collides with adopter keys.\n- \\`getRequestValue<string>('traceId')\\` — generic is the **key** type, not value type.`,\n },\n {\n slug: 'query-parsing-list-endpoint',\n frontmatterName: 'kickjs-query-parsing-list-endpoint',\n description:\n 'Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.',\n body: `**Canonical list endpoint**:\n\n\\`\\`\\`ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n\\`\\`\\`\n\n**Operator format** (fixed): \\`?filter=field:op:value\\` where \\`op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends\\`. Sort is \\`?sort=field:asc|desc\\`. Only the first two colons are delimiters, so timestamps work (\\`createdAt:gt:2026-01-01T00:00:00Z\\`).\n\n**Drizzle adopters** — pass a \\`DrizzleQueryParamsConfig\\` with column refs:\n\n\\`\\`\\`ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n\\`\\`\\`\n\n**ORM-agnostic builders** — implement \\`QueryBuilderAdapter<TResult, TConfig>\\` with \\`build(parsed, config)\\`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading \\`req.query.status\\` directly — bypasses the allow-list; opens unbounded filtering. Use \\`ctx.qs({ filterable })\\`.\n- Omitting \\`filterable\\` / \\`sortable\\` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use \\`ctx.paginate()\\`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the \\`PaginatedResponse<T>\\` contract.\n- Mixing string \\`searchable\\` config with column \\`searchColumns\\` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- \\`limit\\` is capped at 100 server-side; \\`q\\` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to \\`asc\\` when omitted (\\`?sort=createdAt\\` ≡ \\`?sort=createdAt:asc\\`).`,\n },\n {\n slug: 'use-asset-manager',\n frontmatterName: 'kickjs-use-asset-manager',\n description:\n 'Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.',\n body: `**Configure** \\`kick.config.ts\\`:\n\n\\`\\`\\`ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n\\`\\`\\`\n\n**Consume** via the typed Proxy — no \\`__dirname\\` arithmetic, dev/prod paths handled:\n\n\\`\\`\\`ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n\\`\\`\\`\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n\\`\\`\\`ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n\\`\\`\\`\n\n**Dynamic dispatch** (CMS templates, codegen) — \\`resolveAsset(ns, key)\\` throws \\`UnknownAssetError\\` with \\`{ namespace, key }\\` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n\\`\\`\\`ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n\\`\\`\\`\n\n**Red flags**:\n- Hand-rolled \\`process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')\\` — exactly what the asset manager replaces.\n- \\`keys: 'strip'\\` setting in \\`assetMap.<ns>\\` when basenames may collide — silent last-walk-wins data loss. Default \\`'auto'\\` keeps extensions only for colliding groups.\n- Non-default Vite \\`outDir\\` without mirroring in \\`kick.config.ts\\` — manifest writes at \\`dist/.kickjs-assets.json\\` but the resolver can't find it. Mirror via \\`build.outDir\\`.\n- Forgetting to re-run \\`kick typegen\\` after adding files — \\`assets.mails.newTemplate\\` is a tsc error even though the file ships. \\`kick dev\\` does this on-change; one-shot CI builds need \\`kick build\\` (or \\`kick build:assets\\` for manifest-only).\n- Same-name \\`welcome.ejs\\` + \\`welcome/login.ejs\\` — directory wins in the typed surface; the \\`.ejs\\` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): \\`KICK_ASSETS_ROOT\\` env override > built manifest at \\`build.outDir\\` / \\`dist\\` / \\`build\\` / \\`out\\` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — \\`**/*\\`, \\`**/*.ext\\`, \\`**/*.{a,b}\\` are guaranteed; exotic globs warn-once and accept everything. Run \\`kick build:assets\\` to exercise the real glob engine.`,\n },\n {\n slug: 'cli-commands-cheatsheet',\n frontmatterName: 'kickjs-cli-commands-cheatsheet',\n description:\n 'Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.',\n body: `**Top commands**:\n- \\`kick new <name>\\` — start a new project (prompts for template / repo / pm).\n- \\`kick dev\\` — local dev server with Vite HMR.\n- \\`kick build\\` — production bundle via Vite.\n- \\`kick start\\` — run the built artifact (\\`NODE_ENV=production\\` auto-set).\n- \\`kick g module <name>\\` — add a feature module; structure follows \\`pattern\\` in \\`kick.config.ts\\`.\n- \\`kick g scaffold <Name> <field:type>...\\` — full CRUD module from field definitions.\n- \\`kick add <pkg>\\` — install optional packages (auto-resolves peer deps + package manager).\n- \\`kick g --list\\` — list every available generator (built-ins + plugin-shipped).\n- \\`kick info\\` — environment / version dump for bug reports.\n- \\`kick inspect\\` — introspect a running app: routes, middleware, adapters, DI graph.\n\n**Useful flag combos**:\n\n\\`\\`\\`bash\nkick new my-api --yes # CI-safe: minimal + inmemory, no prompts\nkick new my-api -t ddd --pm ${pm} --no-git --install # Fully scriptable DDD scaffold\nkick new . --yes --force # Scaffold into current dir, clear existing files\nkick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax\nkick g agents -f --only skills # Refresh just the skills after upgrade\nkick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot\nkick inspect --port 4000 --json # Machine-readable route/adapter dump\nkick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project\n\\`\\`\\`\n\n**Lesser-known, high-value**:\n- \\`kick inspect --watch\\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \\`/_debug\\`.\n- \\`kick g agents -f\\` — regenerates \\`CLAUDE.md\\` (root) and \\`.agents/AGENTS.md\\` / \\`GEMINI.md\\` / \\`COPILOT.md\\` + every \\`.agents/skills/<slug>/SKILL.md\\` from the current CLI templates.\n- \\`kick dev:debug\\` — same flags as \\`kick dev\\` but opens a Node inspector port for IDE attach.\n- \\`kick list --all\\` (alias \\`kick ls --all\\`) — full optional-package catalog at this CLI version.\n- \\`kick typegen --watch\\` — standalone typegen watcher when \\`kick dev\\` isn't running.\n- \\`kick check\\` — preflight gate (typecheck + lint + format) before commit.\n- \\`kick codemod\\` — automated AST-level migration between framework versions.\n\n**Red flags**:\n- Using globally-installed \\`@forinda/kickjs-cli\\` while contributing to the monorepo — \\`pnpm link --global\\` from \\`packages/cli\\` so generators match the framework.\n- Writing \\`\"name:type?\"\\` for optional scaffold fields — \\`?\\` is a shell glob in bash/zsh; use \\`name:type:optional\\`.\n- Running \\`kick new <name> --yes\\` in a non-empty directory expecting it to wipe — \\`--yes\\` aborts without \\`--force\\`; pair them when destruction is intended.\n- Skipping \\`kick g config\\` on a legacy project then wondering why generators ignore \\`modules.dir\\` / \\`modules.repo\\`.\n- Editing \\`kick.config.ts\\` with deprecated top-level \\`modulesDir\\` / \\`defaultRepo\\` / \\`schemaDir\\` / \\`pluralize\\` instead of the nested \\`modules\\` block.`,\n },\n {\n slug: 'refresh-agent-docs',\n frontmatterName: 'kickjs-refresh-agent-docs',\n description:\n 'Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.',\n body: `**Steps**:\n1. \\`kick g agents -f --only both\\` — overwrites \\`CLAUDE.md\\` (root) and \\`.agents/AGENTS.md\\`.\n2. \\`kick g agents -f --only skills\\` — refreshes every \\`.agents/skills/<slug>/SKILL.md\\`.\n3. \\`kick g agents -f --only gemini\\` / \\`--only copilot\\` — refresh the per-agent files when needed.\n4. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \\`AGENTS.local.md\\` or per-skill \\`SKILL.local.md\\` alongside.\n5. Commit as \\`docs(agents): sync from CLI vX.Y\\`.\n\n**\\`.agents/\\` layout** (post-restructure):\n\n\\`\\`\\`\nCLAUDE.md # at root — Claude Code auto-loads from here\n.agents/\n├── AGENTS.md # canonical multi-agent reference\n├── GEMINI.md # Gemini-specific notes\n├── COPILOT.md # Copilot CLI notes\n└── skills/\n ├── add-module/SKILL.md\n ├── add-adapter/SKILL.md\n └── … # one SKILL.md per skill, frontmatter-namespaced\n\\`\\`\\`\n\nCustomisation goes in \\`.local.md\\` siblings (\\`AGENTS.local.md\\`, \\`skills/<slug>/SKILL.local.md\\`) — those are never overwritten.`,\n },\n {\n slug: 'deny-list',\n frontmatterName: 'kickjs-deny-list',\n description:\n 'Patterns to refuse outright when the user asks for them — they break v4 invariants.',\n body: `**Module / adapter / plugin shape**:\n- \\`class implements AppAdapter\\` → use \\`defineAdapter()\\`.\n- \\`class implements KickPlugin\\` / function returning \\`KickPlugin\\` → use \\`definePlugin()\\`.\n- \\`class implements AppModule\\` for new code → use \\`defineModule()\\`.\n- \\`bootstrap({ adapters: [MyAdapter] })\\` (factory) → \\`MyAdapter()\\` (instance, with parens).\n- \\`@Controller('/path')\\` with a path argument → drop the path; set the mount via \\`routes().path\\`. The decorator path is OpenAPI metadata only.\n- Module file named \\`<name>.ts\\` (no \\`.module\\` suffix) → rename to \\`<name>.module.ts\\`. Vite HMR's glob doesn't pick up the unsuffixed form.\n\n**DI**:\n- \\`new Container()\\` or \\`Container.getInstance().reset()\\` in tests → use \\`Container.reset()\\` in \\`beforeEach\\` (or \\`Container.create()\\` for fully isolated graphs).\n- DI tokens with \\`:\\` separator (\\`'app:db:url'\\`) or in PascalCase → use slash-delimited lower-case (\\`'app/db/url'\\`). First-party uses reserved \\`'kick/'\\` prefix.\n- \\`Symbol.for(...)\\` for DI tokens — globally interned, **collides across files**. Use \\`createToken<T>('name')\\`.\n- Raw string tokens (\\`@Inject('config')\\`) — silent collisions; widens to \\`unknown\\`. Use \\`createToken<T>\\`.\n- Injecting a \\`Scope.REQUEST\\` service into a \\`SINGLETON\\` — container throws at resolve time.\n\n**Bootstrap / entry file**:\n- \\`bootstrap({ ... })\\` without \\`export const app = ...\\` → always export. HMR degrades to full restart and \\`createTestApp\\` loses the handle.\n- \\`bootstrap({ register: ... })\\` — that option doesn't exist. Use an inline plugin in \\`plugins\\`.\n\n**Middleware**:\n- Using \\`(ctx, next)\\` for global middleware in \\`bootstrap({ middleware })\\` — global middleware uses raw Express \\`(req, res, next)\\`. Wrong signature throws \"Cannot read properties of undefined\".\n- Using \\`(req, res, next)\\` for an \\`@Middleware()\\` decorator — those use \\`(ctx, next)\\`.\n- \\`@Middleware()\\` whose only output is \\`ctx.set('x', v)\\` — should be a context decorator (typed, ordered, testable).\n\n**Context contributors**:\n- \\`ctx.tenant = x\\` from a contributor — only sticks to one \\`RequestContext\\` instance. **Return the value** so the runner writes it via \\`ctx.set(key, value)\\`.\n- \\`defineAugmentation('ContextMeta', ...)\\` without the matching \\`declare module '@forinda/kickjs'\\` block (or vice-versa).\n- \\`getRequestValue<string>('traceId')\\` — generic is the **key** type, not value type.\n\n**Env / config**:\n- \\`@Value('NEW_KEY')\\` without the key in the Zod schema — silent fallback to raw \\`process.env\\`, no coercion.\n- \\`resetEnvCache()\\` outside tests — drops the registered schema.\n\n**List endpoints**:\n- Reading \\`req.query.status\\` directly — bypasses the allow-list. Use \\`ctx.qs({ filterable })\\`.\n- Returning a bare array from a list endpoint — breaks the \\`PaginatedResponse<T>\\` contract. Use \\`ctx.paginate()\\`.\n\n**Assets**:\n- Hand-rolled \\`__dirname\\` arithmetic for template paths — use \\`assets.<ns>.<key>()\\` and add the namespace to \\`kick.config.ts assetMap\\`.`,\n },\n ]\n\n return skills.map((skill) => ({\n slug: skill.slug,\n content: `---\nname: ${skill.frontmatterName}\ndescription: ${skill.description}\n---\n\n${banner}\n\n${skill.body}\n`,\n }))\n}\n\n/**\n * @deprecated Kept only for back-compat with adopters who programmatically\n * import this function from `@forinda/kickjs-cli`. The CLI itself no\n * longer calls it — `kick g agents` emits per-skill SKILL.md files via\n * {@link generateKickJsSkillFiles}. Will be removed in a future minor.\n */\nexport function generateKickJsSkills(name: string, _template: ProjectTemplate, pm: string): string {\n return `# kickjs-skills.md — Task Skills for AI Agents (${name})\n\nThis file is the agent-facing **skills index** for KickJS work in this\nrepo. Each block below is a short, rigid workflow keyed to a specific\ntrigger (\"user wants to add a module\", \"tests are leaking state\", etc.).\n\n- Reference docs (narrative, exhaustive) → \\`AGENTS.md\\`.\n- Tool-specific notes → \\`CLAUDE.md\\`, \\`GEMINI.md\\`, etc.\n- **This file** → step-by-step recipes the agent should *execute*.\n\nRe-run \\`kick g agents -f --only skills\\` after framework upgrades to refresh.\n\n---\n\n## Skill: add-module\n\n\\`\\`\\`yaml\nname: kickjs-add-module\ndescription: Use when the user asks to add a new feature module (controller + service + repo + DTOs).\n\\`\\`\\`\n\n**Trigger phrases**: \"add a users module\", \"scaffold tasks\", \"new feature for X\".\n\n**Steps**:\n1. Run \\`kick g module <name>\\` (use plural form if the project pluralizes — check \\`kick.config.ts\\`).\n2. Verify the new folder under \\`src/modules/<name>/\\` contains \\`<name>.module.ts\\` (filename suffix is mandatory for HMR).\n3. Confirm the module appears in \\`src/modules/index.ts\\` exports — generator does this automatically; verify if you bypassed it.\n4. Open \\`<name>.dto.ts\\` and tighten the Zod schemas to real fields (the generator emits placeholders).\n5. Run \\`${pm} run typecheck\\` and \\`${pm} run test\\` before claiming done.\n\n**Red flags** (stop and ask):\n- File created as \\`<name>.ts\\` instead of \\`<name>.module.ts\\` — Vite won't HMR it.\n- Module not registered in \\`src/modules/index.ts\\`.\n- \\`@Controller('/path')\\` with a path argument — that's a v3 pattern; remove it (mount comes from \\`routes().path\\`).\n\n---\n\n## Skill: add-adapter\n\n\\`\\`\\`yaml\nname: kickjs-add-adapter\ndescription: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).\n\\`\\`\\`\n\n**Steps**:\n1. \\`kick g adapter <name>\\` to scaffold the boilerplate, OR install via \\`kick add <package>\\` for first-party adapters.\n2. The generated file uses \\`defineAdapter()\\` — never \\`class implements AppAdapter\\`.\n3. Add the adapter instance to \\`src/adapters/index.ts\\` (don't inline in \\`src/index.ts\\`).\n4. If the adapter contributes to \\`ctx.set/get\\`, prefer \\`AppAdapter.contributors?()\\` over a wrapping middleware.\n5. Verify with \\`kick dev\\` that the adapter's lifecycle logs fire.\n\n**Red flags**:\n- Inlining the adapter list directly in \\`src/index.ts\\` (entry file should stay thin).\n- Returning a plain object instead of going through \\`defineAdapter()\\` — type inference for \\`config\\` will be wrong.\n\n---\n\n## Skill: write-controller-test\n\n\\`\\`\\`yaml\nname: kickjs-write-controller-test\ndescription: Use when adding a Vitest test that exercises an HTTP route or DI graph.\n\\`\\`\\`\n\n**Template** (copy/paste, adjust):\n\n\\`\\`\\`ts\nimport { describe, it, expect } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const container = Container.create() // isolated DI per test\n const app = await createTestApp([UserModule], { container })\n const res = await app.get('/users')\n expect(res.status).toBe(200)\n })\n})\n\\`\\`\\`\n\n**Red flags**:\n- \\`new Container()\\` — wrong; use \\`Container.create()\\`.\n- \\`Container.getInstance().reset()\\` — wrong; same fix.\n- Sharing a container across \\`it()\\` blocks — leaks registrations.\n\n---\n\n## Skill: env-wiring-check\n\n\\`\\`\\`yaml\nname: kickjs-env-wiring-check\ndescription: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.\n\\`\\`\\`\n\n**Diagnosis**:\n1. Open \\`src/index.ts\\`. The **first non-\\`reflect-metadata\\`** import MUST be \\`import './config'\\`.\n2. Open \\`src/config/index.ts\\`. It MUST call \\`loadEnv(envSchema)\\` as a top-level side effect.\n3. The new key MUST be declared in the Zod schema there. \\`@Value('NEW_KEY')\\` won't work without a schema entry (it'll fall back to raw \\`process.env\\` and skip Zod coercion silently).\n\n**Fix**: add the key to the schema; ensure both side-effect imports above are present.\n\n---\n\n## Skill: bootstrap-export\n\n\\`\\`\\`yaml\nname: kickjs-bootstrap-export\ndescription: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.\n\\`\\`\\`\n\n**Check** \\`src/index.ts\\`'s last line:\n\n\\`\\`\\`ts\n// CORRECT\nexport const app = await bootstrap({ ... })\n\n// WRONG (HMR degrades to full restart, createTestApp loses the handle)\nawait bootstrap({ ... })\n\\`\\`\\`\n\nThe Vite plugin imports the named \\`app\\` symbol; testing helpers do too.\n\n---\n\n## Skill: thin-entry-file\n\n\\`\\`\\`yaml\nname: kickjs-thin-entry-file\ndescription: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.\n\\`\\`\\`\n\n**Refactor target**:\n\n\\`\\`\\`ts\n// src/modules/index.ts — fluent chain (default for \\`modules.style: 'define'\\`)\nexport const modules = defineModules().mount(HelloModule()).mount(UsersModule())\n// OR for class-form projects (\\`modules.style: 'class'\\`):\n// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]\n\n// src/middleware/index.ts\nexport const middleware = [helmet(), cors(), requestId(), ...]\n\n// src/plugins/index.ts\nexport const plugins = [MetricsPlugin(), ...]\n\n// src/adapters/index.ts\nexport const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]\n\n// src/index.ts — stays small\nimport 'reflect-metadata'\nimport './config'\nimport { bootstrap } from '@forinda/kickjs'\nimport { modules } from './modules'\nimport { middleware } from './middleware'\nimport { plugins } from './plugins'\nimport { adapters } from './adapters'\nexport const app = await bootstrap({ modules, middleware, plugins, adapters })\n\\`\\`\\`\n\n**Red flags**: any \\`new SomeAdapter()\\` or \\`SomePlugin()\\` literal inside \\`bootstrap({ ... })\\` instead of imported from a category folder.\n\n---\n\n## Skill: context-contributor\n\n\\`\\`\\`yaml\nname: kickjs-context-contributor\ndescription: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).\n\\`\\`\\`\n\n**Pattern** (HTTP — most common):\n\n\\`\\`\\`ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO },\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'],\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }\n\\`\\`\\`\n\nUse \\`defineContextDecorator\\` (no Http prefix) when authoring a contributor that must run across HTTP, WebSocket, queue, and cron transports — \\`Ctx\\` defaults to the smaller \\`ExecutionContext\\` surface (\\`get\\` / \\`set\\` / \\`requestId\\` only, no \\`req\\`).\n\nPrecedence high → low: **method > class > module > adapter > global**.\nCycles or unmet \\`dependsOn\\` keys throw \\`MissingContributorError\\` at boot.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN \\`RequestContext\\` instance, but they all read/write the SAME \\`AsyncLocalStorage\\`-backed bag.\n- **\\`resolve\\` and \\`onError\\` must RETURN the value** — the runner writes it via \\`ctx.set(key, value)\\`. Direct property assignment (\\`ctx.tenant = …\\`) sticks to one instance only and the handler instance never sees it.\n- \\`ctx.set('tenant', x)\\` then \\`ctx.get('tenant')\\` works across instances. \\`ctx.req.headers[...]\\` works (the underlying Express request is shared).\n- Services with no \\`ctx\\` reference: \\`getRequestValue('tenant')\\` returns \\`MetaValue<'tenant'> | undefined\\` (typed via the augmented \\`ContextMeta\\`). For \\`requestId\\` use \\`getRequestStore()\\`.\n- **No \\`setRequestValue\\` — writes flow through \\`ctx.set\\` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Don't use this for**: response short-circuit, stream mutation, or\npre-route-matching work — keep \\`@Middleware()\\` for those.\n\n---\n\n## Skill: refresh-agent-docs\n\n\\`\\`\\`yaml\nname: kickjs-refresh-agent-docs\ndescription: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.\n\\`\\`\\`\n\n**Steps**:\n1. \\`kick g agents -f --only both\\` — overwrites \\`AGENTS.md\\` and \\`CLAUDE.md\\`.\n2. \\`kick g agents -f --only skills\\` — refreshes \\`kickjs-skills.md\\` (this file).\n3. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \\`AGENTS.local.md\\` or appended section.\n4. Commit as \\`docs(agents): sync from CLI vX.Y\\`.\n\n---\n\n## Skill: deny-list\n\n\\`\\`\\`yaml\nname: kickjs-deny-list\ndescription: Patterns to refuse outright when the user asks for them — they break v4 invariants.\n\\`\\`\\`\n\n- \\`class implements AppAdapter\\` → use \\`defineAdapter()\\`.\n- \\`class implements KickPlugin\\` / function returning \\`KickPlugin\\` → use \\`definePlugin()\\`.\n- \\`@Controller('/path')\\` with a path argument → drop the path; set the mount via \\`routes().path\\`.\n- \\`new Container()\\` or \\`Container.getInstance().reset()\\` in tests → use \\`Container.create()\\`.\n- DI tokens with \\`:\\` separator (\\`'app:db:url'\\`) or in PascalCase → use slash-delimited lower-case (\\`'app/db/url'\\`).\n- \\`bootstrap({ ... })\\` without \\`export const app = ...\\` → always export.\n- Module file named \\`<name>.ts\\` (no \\`.module\\` suffix) → rename to \\`<name>.module.ts\\`.\n\n---\n\n## Learn More\n\n- [KickJS Docs](https://forinda.github.io/kick-js/)\n- [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)\n- [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)\n- [Testing](https://forinda.github.io/kick-js/api/testing.html)\n`\n}\n\n/**\n * Render the Gemini-specific agent file emitted at\n * `.agents/GEMINI.md`. Gemini CLI loads files matching its own\n * convention; this file pairs a pointer to the shared\n * `.agents/AGENTS.md` with notes specific to Gemini's tool surface\n * (activate_skill, sandboxed file ops, etc.). Adopters who don't use\n * Gemini can delete this file safely — the generator emits it as a\n * starting point, not a requirement.\n */\nexport function generateGemini(name: string, _template: ProjectTemplate, _pm: string): string {\n return `# GEMINI.md — ${name}\n\n**Read \\`./AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project — every convention, structure, decorator\npattern, env wiring rule, generator usage. This file is a thin\nGemini-specific layer; when the two disagree on anything substantive,\ntreat \\`AGENTS.md\\` as authoritative and flag the discrepancy.\n\n## Why this file\n\nGemini CLI auto-loads \\`GEMINI.md\\` when it lives alongside the\nagent-context files. Keeping it in \\`.agents/\\` next to \\`AGENTS.md\\`\nmeans Gemini reads the same shared prose as Codex / Cursor / Copilot\nwithout us copy-pasting.\n\n## Gemini-specific notes\n\n- **Skills activation** — Gemini activates skills via\n \\`activate_skill\\` (its native MCP-style tool); the equivalent on\n Claude Code is the \\`Skill\\` tool. Cross-reference the\n \\`kickjs-skills.md\\` index for the available triggers.\n- **Tool naming** — Gemini's tool names differ from Claude Code's\n (e.g. \\`read_file\\` vs \\`Read\\`, \\`run_terminal_command\\` vs\n \\`Bash\\`). The shared prose in \\`AGENTS.md\\` describes intents, not\n tool names; consult Gemini's docs for the concrete invocation.\n- **File ops** — Gemini's file edits are sandboxed; large refactors\n may need explicit confirmation. Prefer the smallest-possible-edit\n pattern.\n\n## Refreshing this file\n\n\\`kick g agents --only gemini -f\\` regenerates this file from the\nCLI template. Hand-edited content is overwritten — keep customisation\nin \\`.agents/GEMINI.local.md\\`.\n`\n}\n\n/**\n * Render the GitHub Copilot CLI agent file emitted at\n * `.agents/COPILOT.md`. Same pattern as `generateGemini` — thin\n * pointer to `.agents/AGENTS.md` with notes specific to Copilot\n * CLI's tool surface and conventions.\n */\nexport function generateCopilot(name: string, _template: ProjectTemplate, _pm: string): string {\n return `# COPILOT.md — ${name}\n\n**Read \\`./AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project — every convention, structure, decorator\npattern, env wiring rule, generator usage. This file is a thin\nCopilot-specific layer; when the two disagree on anything substantive,\ntreat \\`AGENTS.md\\` as authoritative and flag the discrepancy.\n\n## Why this file\n\nGitHub Copilot CLI auto-loads \\`COPILOT.md\\` when it lives alongside\nthe agent-context files. Keeping it in \\`.agents/\\` next to\n\\`AGENTS.md\\` means Copilot reads the same shared prose as\nCodex / Cursor / Gemini / Claude Code without copy-pasting.\n\n## Copilot-specific notes\n\n- **Skills** — Copilot CLI auto-discovers skills from installed\n plugins; cross-reference \\`kickjs-skills.md\\` for available\n triggers in this project.\n- **Tool naming** — Copilot's tool names differ from Claude Code's\n (\\`edit\\` vs \\`Edit\\`, \\`shell\\` vs \\`Bash\\`, etc.). The shared\n prose in \\`AGENTS.md\\` describes intents, not tool names; consult\n Copilot's docs for the concrete invocation.\n- **Confirmation flows** — Copilot CLI surfaces destructive\n operations through an explicit approval gate. Stage edits with\n short, focused diffs so each one is easy to review at the prompt.\n\n## Refreshing this file\n\n\\`kick g agents --only copilot -f\\` regenerates this file from the\nCLI template. Hand-edited content is overwritten — keep customisation\nin \\`.agents/COPILOT.local.md\\`.\n`\n}\n"],"mappings":";;;;;;;;;;yRAKA,IAAI,EAAU,GAId,SAAgB,EAAU,EAAwB,CAChD,EAAU,CACZ,CAYA,MAAM,EAAc,IAAI,IAAI,CAAC,MAAO,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,QAAS,KAAK,CAAC,EAgB1F,eAAsB,EAAc,EAAkB,EAAgC,CAChF,IACJ,MAAM,EAAM,EAAQ,CAAQ,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,MAAM,EAAU,EAAU,EAAS,OAAO,EAC3B,EAAY,IAAI,EAAQ,CAAQ,CAAC,GAC9C,MAAM,EAAW,EAAU,CAAO,CAAC,CAAC,UAAY,CAIhD,CAAC,EAEL,CAeA,IAAI,EAGJ,eAAe,EAAa,EAA0C,CACpE,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,GAAI,CAGF,EAAU,MAAM,OAFJ,EAAc,EAAK,EAAK,cAAc,CAC9B,CAAC,CAAC,QAAQ,OACC,EACjC,MAAQ,CACN,EAAS,IACX,CACA,OAAO,CACT,CAEA,eAAe,EAAW,EAAkB,EAAgC,CAC1E,IAAM,EAAQ,MAAM,EAAa,QAAQ,IAAI,CAAC,EAC9C,GAAI,CAAC,EAAO,OAMZ,IAAM,EAAU,MAAM,EAAgB,CAAQ,EAC9C,GAAI,IAAY,KAAM,OACtB,IAAM,EAAS,MAAM,EAAM,OAAO,EAAU,EAAS,CAAO,EACxD,EAAO,OAAS,GACpB,MAAM,EAAU,EAAU,EAAO,KAAM,OAAO,CAChD,CAEA,MAAM,E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
|
-
* @forinda/kickjs-cli
|
|
2
|
+
* @forinda/kickjs-cli v6.0.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-
|
|
12
|
-
//# sourceMappingURL=project-root-
|
|
11
|
+
import{t as e}from"./rolldown-runtime-CoN4EDcd.mjs";import{dirname as t,parse as n,resolve as r}from"node:path";import{existsSync as i}from"node:fs";var a=e({findProjectRoot:()=>s});const o=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function s(e=process.cwd()){let a=r(e),{root:s}=n(a),c=null,l=a;for(;;){for(let e of o)if(i(r(l,e)))return l;if(c===null&&i(r(l,`package.json`))&&(c=l),l===s)break;let e=t(l);if(e===l)break;l=e}return c??a}export{a as n,s as t};
|
|
12
|
+
//# sourceMappingURL=project-root-BdTe6EpE.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-root-
|
|
1
|
+
{"version":3,"file":"project-root-BdTe6EpE.mjs","names":[],"sources":["../src/utils/project-root.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, parse, resolve } from 'node:path'\n\nconst CONFIG_FILENAMES = ['kick.config.ts', 'kick.config.js', 'kick.config.mjs', 'kick.config.json']\n\n/**\n * Walk up from `startDir` looking for the project root. A directory\n * counts as the root when it contains any of:\n * - `kick.config.{ts,js,mjs,json}` (strongest signal)\n * - `package.json` (fallback when no config file exists yet)\n *\n * Returns the absolute path of the first matching directory, or\n * `startDir` itself when nothing was found (no surprises — callers\n * that didn't find a config still get a reasonable cwd).\n *\n * `kick.config.*` wins over `package.json` when both appear at\n * different levels, so adopters running `kick typegen` from `src/`\n * land on the project root that owns the config, not on the nearest\n * workspace package boundary in a monorepo.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n const start = resolve(startDir)\n const { root: fsRoot } = parse(start)\n\n let firstPackageJson: string | null = null\n let cursor = start\n while (true) {\n for (const name of CONFIG_FILENAMES) {\n if (existsSync(resolve(cursor, name))) return cursor\n }\n if (firstPackageJson === null && existsSync(resolve(cursor, 'package.json'))) {\n firstPackageJson = cursor\n }\n if (cursor === fsRoot) break\n const parent = dirname(cursor)\n if (parent === cursor) break\n cursor = parent\n }\n\n return firstPackageJson ?? start\n}\n"],"mappings":";;;;;;;;;;sLAGA,MAAM,EAAmB,CAAC,iBAAkB,iBAAkB,kBAAmB,kBAAkB,EAiBnG,SAAgB,EAAgB,EAAmB,QAAQ,IAAI,EAAW,CACxE,IAAM,EAAQ,EAAQ,CAAQ,EACxB,CAAE,KAAM,GAAW,EAAM,CAAK,EAEhC,EAAkC,KAClC,EAAS,EACb,OAAa,CACX,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAW,EAAQ,EAAQ,CAAI,CAAC,EAAG,OAAO,EAKhD,GAHI,IAAqB,MAAQ,EAAW,EAAQ,EAAQ,cAAc,CAAC,IACzE,EAAmB,GAEjB,IAAW,EAAQ,MACvB,IAAM,EAAS,EAAQ,CAAM,EAC7B,GAAI,IAAW,EAAQ,MACvB,EAAS,CACX,CAEA,OAAO,GAAoB,CAC7B"}
|