@forinda/kickjs-cli 5.5.1 → 5.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/dist/{run-plugins-tnHiahkq.mjs → builtins-CYSzLo7U.mjs} +2 -2
  3. package/dist/cli.mjs +4086 -2
  4. package/dist/config-ierHW69f.mjs +12 -0
  5. package/dist/{config-Buzo7RE1.mjs.map → config-ierHW69f.mjs.map} +1 -1
  6. package/dist/{generator-extension-m04pTdQi.mjs → generator-extension-BXLt3Tp_.mjs} +314 -78
  7. package/dist/generator-extension-BXLt3Tp_.mjs.map +1 -0
  8. package/dist/index.d.mts +141 -31
  9. package/dist/index.d.mts.map +1 -1
  10. package/dist/index.mjs +3 -2
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/{plugin-BnIpCxAe.mjs → plugin-D_nBy6VP.mjs} +3 -3
  13. package/dist/{plugin-BnIpCxAe.mjs.map → plugin-D_nBy6VP.mjs.map} +1 -1
  14. package/dist/project-root-CqGZOrRR.mjs +12 -0
  15. package/dist/project-root-CqGZOrRR.mjs.map +1 -0
  16. package/dist/{rolldown-runtime-Dnwyy6jt.mjs → rolldown-runtime-B8-Ifyj3.mjs} +1 -1
  17. package/dist/{builtins-DXPOvADa.mjs → run-plugins-Cvgyo_th.mjs} +90 -288
  18. package/dist/run-plugins-Cvgyo_th.mjs.map +1 -0
  19. package/dist/{typegen-CYaoTJ6r.mjs → typegen-C3G375CR.mjs} +4 -4
  20. package/dist/{typegen-CYaoTJ6r.mjs.map → typegen-C3G375CR.mjs.map} +1 -1
  21. package/dist/{types-RTdCiPdS.mjs → types-Kj2ldTnQ.mjs} +2 -2
  22. package/dist/types-Kj2ldTnQ.mjs.map +1 -0
  23. package/package.json +7 -6
  24. package/dist/builtins-DXPOvADa.mjs.map +0 -1
  25. package/dist/builtins-DYktFyU-.mjs +0 -3952
  26. package/dist/config-Bu3PcPYn.mjs +0 -11
  27. package/dist/config-Buzo7RE1.mjs +0 -12
  28. package/dist/generator-extension-m04pTdQi.mjs.map +0 -1
  29. package/dist/plugin-DZZsizSI.mjs +0 -11
  30. package/dist/typegen-COED-VIb.mjs +0 -116
  31. package/dist/types-RTdCiPdS.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v5.5.1
2
+ * @forinda/kickjs-cli v5.8.0
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,resolve as i}from"node:path";import{existsSync as a,readFileSync as o}from"node:fs";import{access as s,mkdir as c,readFile as l,writeFile as u}from"node:fs/promises";import*as d from"@clack/prompts";import f from"picocolors";import p from"pluralize";import{execFileSync as m,execSync as h}from"node:child_process";import{fileURLToPath as g,pathToFileURL as _}from"node:url";let v=!1;function y(e){v=e}const ee=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function b(e,r){v||(await c(t(e),{recursive:!0}),await u(e,r,`utf-8`),ee.has(n(e))&&await ne(e,r).catch(()=>{}))}let x;async function te(t){if(x!==void 0)return x;try{x=await import(e(r(t,`package.json`)).resolve(`oxfmt`))}catch{x=null}return x}async function ne(e,t){let n=await te(process.cwd());if(!n)return;let r=await re(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await u(e,i.code,`utf-8`)}const S=new Map;async function re(e){let n=t(e),i=n;if(S.has(i))return S.get(i);for(;;){let e=r(n,`.oxfmtrc.json`);if(a(e))try{let t=await l(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,S.set(i,n),n}catch{return S.set(i,null),null}let o=t(n);if(o===n)return S.set(i,null),null;n=o}}async function C(e){try{return await s(e),!0}catch{return!1}}const ie={GET:f.green,POST:f.cyan,PUT:f.yellow,PATCH:f.magenta,DELETE:f.red};function ae(e){return(ie[e]??f.dim)(e.padEnd(7))}function oe(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return f.red(t);case`WARNING`:return f.yellow(t);case`INFO`:return f.blue(f.dim(t));default:return t}}f.green(`✓`),f.red(`✖`),f.yellow(`⚠`),f.blue(`ℹ`);function se(e){d.intro(f.bgCyan(f.black(` ${e} `)))}function ce(e){d.outro(e)}function w(e){d.isCancel(e)&&(d.cancel(`Operation cancelled.`),process.exit(0))}async function le(e){let t=await d.text(e);return w(t),t}async function ue(e){let t=await d.select(e);return w(t),t}async function de(e){let t=await d.multiselect(e);return w(t),t}async function T(e){let t=await d.confirm(e);return w(t),t}function fe(){return d.spinner()}const E=d.log;function D(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function A(e){return p.plural(e)}function j(e){return p.plural(e)}function M(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const pe={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function me(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function he(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function N(e){return pe[e]??me(e)}function P(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${me(n)}${e}Repository`,repoFile:i[n]??`${he(n)}-${t}`}}function F(e){return e??`define`}function ge(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
11
+ import{t as e}from"./project-root-CqGZOrRR.mjs";import{createRequire as t}from"node:module";import{dirname as n,extname as r,join as i,resolve as a}from"node:path";import{existsSync as o,readFileSync as s}from"node:fs";import{access as c,mkdir as l,readFile as u,writeFile as d}from"node:fs/promises";import*as f from"@clack/prompts";import p from"picocolors";import m from"pluralize";import{execFileSync as h,execSync as g}from"node:child_process";import{fileURLToPath as _,pathToFileURL as v}from"node:url";let y=!1;function ee(e){y=e}const te=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function b(e,t){y||(await l(n(e),{recursive:!0}),await d(e,t,`utf-8`),te.has(r(e))&&await re(e,t).catch(()=>{}))}let x;async function ne(e){if(x!==void 0)return x;try{x=await import(t(i(e,`package.json`)).resolve(`oxfmt`))}catch{x=null}return x}async function re(e,t){let n=await ne(process.cwd());if(!n)return;let r=await ie(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await d(e,i.code,`utf-8`)}const S=new Map;async function ie(e){let t=n(e),r=t;if(S.has(r))return S.get(r);for(;;){let e=i(t,`.oxfmtrc.json`);if(o(e))try{let t=await u(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,S.set(r,n),n}catch{return S.set(r,null),null}let a=n(t);if(a===t)return S.set(r,null),null;t=a}}async function C(e){try{return await c(e),!0}catch{return!1}}const ae={GET:p.green,POST:p.cyan,PUT:p.yellow,PATCH:p.magenta,DELETE:p.red};function oe(e){return(ae[e]??p.dim)(e.padEnd(7))}function se(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return p.red(t);case`WARNING`:return p.yellow(t);case`INFO`:return p.blue(p.dim(t));default:return t}}p.green(`✓`),p.red(`✖`),p.yellow(`⚠`),p.blue(`ℹ`);function ce(e){f.intro(p.bgCyan(p.black(` ${e} `)))}function le(e){f.outro(e)}function w(e){f.isCancel(e)&&(f.cancel(`Operation cancelled.`),process.exit(0))}async function ue(e){let t=await f.text(e);return w(t),t}async function de(e){let t=await f.select(e);return w(t),t}async function fe(e){let t=await f.multiselect(e);return w(t),t}async function T(e){let t=await f.confirm(e);return w(t),t}function pe(){return f.spinner()}const E=f.log;function D(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function A(e){return m.plural(e)}function me(e){return m.plural(e)}function j(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const he={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function M(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ge(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function N(e){return he[e]??M(e)}function P(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${M(n)}${e}Repository`,repoFile:i[n]??`${ge(n)}-${t}`}}function F(e){return e??`define`}function _e(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
12
12
  * ${t} Module
13
13
  *
14
14
  * Self-contained feature module following Domain-Driven Design (DDD).
@@ -95,7 +95,7 @@ ${d}
95
95
  },
96
96
  }),
97
97
  })
98
- `}function _e(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
98
+ `}function ve(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
99
99
  * ${t} Module
100
100
  *
101
101
  * REST module with a flat folder structure.
@@ -167,7 +167,7 @@ ${d}
167
167
  },
168
168
  }),
169
169
  })
170
- `}function ve(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=F(i),o=` /**
170
+ `}function ye(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=F(i),o=` /**
171
171
  * Declare HTTP routes. Return value shape:
172
172
  *
173
173
  * - \`path\` — URL prefix for this route set.
@@ -207,7 +207,7 @@ ${o}
207
207
  },
208
208
  }),
209
209
  })
210
- `}function ye(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
210
+ `}function be(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
211
211
  import { ApiTags } from '@forinda/kickjs-swagger'
212
212
  import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
213
213
  import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
@@ -270,7 +270,7 @@ export class ${t}Controller {
270
270
  ctx.noContent()
271
271
  }
272
272
  }
273
- `}function be(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
273
+ `}function xe(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
274
274
  import { ApiTags } from '@forinda/kickjs-swagger'
275
275
  import { ${t}Service } from './${n}.service'
276
276
  import { create${t}Schema } from './dtos/create-${n}.dto'
@@ -325,7 +325,7 @@ export class ${t}Controller {
325
325
  ctx.noContent()
326
326
  }
327
327
  }
328
- `}function xe(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
328
+ `}function Se(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
329
329
 
330
330
  export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
331
331
  filterable: ['name'],
@@ -361,7 +361,7 @@ export type Update${t}DTO = z.infer<typeof update${t}Schema>
361
361
  createdAt: string
362
362
  updatedAt: string
363
363
  }
364
- `}function Se(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
364
+ `}function Ce(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
365
365
  * Create ${t} Use Case
366
366
  *
367
367
  * Application layer — orchestrates a single business operation.
@@ -603,7 +603,7 @@ export class ${o}${t}Repository implements I${t}Repository {
603
603
  this.store.delete(id)
604
604
  }
605
605
  }
606
- `}function Ce(e){let{pascal:t,kebab:n}=e;return`/**
606
+ `}function we(e){let{pascal:t,kebab:n}=e;return`/**
607
607
  * ${t} Domain Service
608
608
  *
609
609
  * Domain layer — contains business rules that don't belong to a single entity.
@@ -626,7 +626,7 @@ export class ${t}DomainService {
626
626
  }
627
627
  }
628
628
  }
629
- `}function we(e){let{pascal:t,kebab:n}=e;return`/**
629
+ `}function Te(e){let{pascal:t,kebab:n}=e;return`/**
630
630
  * ${t} Entity
631
631
  *
632
632
  * Domain layer — the core business object.
@@ -695,7 +695,7 @@ export class ${t} {
695
695
  }
696
696
  }
697
697
  }
698
- `}function Te(e){let{pascal:t}=e;return`/**
698
+ `}function Ee(e){let{pascal:t}=e;return`/**
699
699
  * ${t} ID Value Object
700
700
  *
701
701
  * Domain layer — wraps a primitive ID with type safety and validation.
@@ -843,7 +843,7 @@ describe('InMemory${t}Repository', () => {
843
843
  expect(found).toBeNull()
844
844
  })
845
845
  })
846
- `}function Ee(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
846
+ `}function De(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
847
847
  import type { ParsedQuery } from '@forinda/kickjs'
848
848
  import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
849
849
  import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
@@ -887,7 +887,7 @@ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
887
887
  sortable: ['name', 'createdAt'],
888
888
  searchable: ['name'],
889
889
  }
890
- `}function De(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o={inmemory:`InMemory${t}Repository`,drizzle:`Drizzle${t}Repository`,prisma:`Prisma${t}Repository`},s={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},c=o[i]??o.inmemory,l=s[i]??s.inmemory,u=a??`define`,d=`/**
890
+ `}function Oe(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o={inmemory:`InMemory${t}Repository`,drizzle:`Drizzle${t}Repository`,prisma:`Prisma${t}Repository`},s={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},c=o[i]??o.inmemory,l=s[i]??s.inmemory,u=a??`define`,d=`/**
891
891
  * ${t} Module — CQRS Pattern
892
892
  *
893
893
  * Separates read (queries) and write (commands) operations.
@@ -966,7 +966,7 @@ ${p}
966
966
  },
967
967
  }),
968
968
  })
969
- `}function Oe(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
969
+ `}function ke(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
970
970
  import { ApiTags } from '@forinda/kickjs-swagger'
971
971
  import { Create${t}Command } from './commands/create-${n}.command'
972
972
  import { Update${t}Command } from './commands/update-${n}.command'
@@ -1029,7 +1029,7 @@ export class ${t}Controller {
1029
1029
  ctx.noContent()
1030
1030
  }
1031
1031
  }
1032
- `}function ke(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1032
+ `}function Ae(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1033
1033
  import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
1034
1034
  import type { Create${t}DTO } from '../dtos/create-${n}.dto'
1035
1035
  import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
@@ -1083,7 +1083,7 @@ export class Delete${t}Command {
1083
1083
  this.events.emit('${n}.deleted', { id })
1084
1084
  }
1085
1085
  }
1086
- `}]}function Ae(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1086
+ `}]}function je(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1087
1087
  import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
1088
1088
  import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1089
1089
 
@@ -1111,7 +1111,7 @@ export class List${i}Query {
1111
1111
  return this.repo.findPaginated(parsed)
1112
1112
  }
1113
1113
  }
1114
- `}]}function je(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
1114
+ `}]}function Me(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
1115
1115
  import { EventEmitter } from 'node:events'
1116
1116
  import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1117
1117
 
@@ -1279,7 +1279,7 @@ export class Drizzle${t}Repository implements I${t}Repository {
1279
1279
  throw new Error('Drizzle ${t} repository not yet implemented')
1280
1280
  }
1281
1281
  }
1282
- `}function Me(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
1282
+ `}function Ne(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
1283
1283
  // TODO: Import your schema table and reference actual columns for type safety
1284
1284
  // import { ${n}s } from '@/db/schema'
1285
1285
 
@@ -1355,7 +1355,7 @@ export class Prisma${t}Repository implements I${t}Repository {
1355
1355
  await this.prisma.${a}.deleteMany({ where: { id } })
1356
1356
  }
1357
1357
  }
1358
- `}function Ne(e,t,n,r=[]){switch(t){case`cqrs`:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
1358
+ `}function Pe(e,t,n,r=[]){switch(t){case`cqrs`:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
1359
1359
  // Side-effect import — registers the extended env schema with kickjs
1360
1360
  // **before** any controller / service / @Value gets resolved. Without
1361
1361
  // this line ConfigService.get('YOUR_KEY') returns undefined because the
@@ -1425,14 +1425,14 @@ export const app = await bootstrap({
1425
1425
  express.json(),
1426
1426
  ],
1427
1427
  })
1428
- `}}}function Pe(){return`import { defineModules } from '@forinda/kickjs'
1428
+ `}}}function Fe(){return`import { defineModules } from '@forinda/kickjs'
1429
1429
  import { HelloModule } from './hello/hello.module'
1430
1430
 
1431
1431
  // Remove HelloModule and run: kick g module <name>
1432
1432
  // \`defineModules()\` returns a chainable list — \`kick g module\` appends
1433
1433
  // \`.mount(NewModule())\` to the chain on every generation.
1434
1434
  export const modules = defineModules().mount(HelloModule())
1435
- `}function Fe(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
1435
+ `}function Ie(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
1436
1436
  import { z } from 'zod'
1437
1437
 
1438
1438
  /**
@@ -1467,7 +1467,7 @@ const envSchema = defineEnv((base) =>
1467
1467
  export const env = loadEnv(envSchema)
1468
1468
 
1469
1469
  export default envSchema
1470
- `}function Ie(){return`import { Service } from '@forinda/kickjs'
1470
+ `}function Le(){return`import { Service } from '@forinda/kickjs'
1471
1471
 
1472
1472
  @Service()
1473
1473
  export class HelloService {
@@ -1479,7 +1479,7 @@ export class HelloService {
1479
1479
  return { status: 'ok', uptime: process.uptime() }
1480
1480
  }
1481
1481
  }
1482
- `}function Le(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
1482
+ `}function Re(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
1483
1483
  import { HelloService } from './hello.service'
1484
1484
 
1485
1485
  // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
@@ -1501,7 +1501,7 @@ export class HelloController {
1501
1501
  ctx.json(this.helloService.healthCheck())
1502
1502
  }
1503
1503
  }
1504
- `}function Re(){return`import { defineModule } from '@forinda/kickjs'
1504
+ `}function ze(){return`import { defineModule } from '@forinda/kickjs'
1505
1505
  import { HelloController } from './hello.controller'
1506
1506
 
1507
1507
  export const HelloModule = defineModule({
@@ -1522,7 +1522,7 @@ export const HelloModule = defineModule({
1522
1522
  },
1523
1523
  }),
1524
1524
  })
1525
- `}function ze(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
1525
+ `}function Be(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
1526
1526
 
1527
1527
  export default defineConfig({
1528
1528
  pattern: '${e}',
@@ -1566,7 +1566,7 @@ export default defineConfig({
1566
1566
  },
1567
1567
  ],
1568
1568
  })
1569
- `}async function Be(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,ve({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
1569
+ `}async function Ve(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,ye({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
1570
1570
 
1571
1571
  // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
1572
1572
  // \`kick typegen\` (auto-run on \`kick dev\`).
@@ -1578,19 +1578,19 @@ export class ${t}Controller {
1578
1578
  ctx.json({ message: '${t} list' })
1579
1579
  }
1580
1580
  }
1581
- `)}async function Ve(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,_e({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,be({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`${n}.service.ts`,Ee({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n})),await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let d={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},f={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},p=d[a]??`${k(a)}-${n}`,m=f[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${p}.repository.ts`,m()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${d.inmemory??`in-memory-${n}`}.repository`})))}async function He(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,De({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,Oe({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let d=ke({pascal:t,kebab:n});for(let e of d)await u(`commands/${e.file}`,e.content);let f=Ae({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await u(`queries/${e.file}`,e.content);let p=je({pascal:t,kebab:n});for(let e of p)await u(`events/${e.file}`,e.content);await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let m={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},h={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},g=m[a]??`${k(a)}-${n}`,_=h[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${g}.repository.ts`,_()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${m.inmemory??`in-memory-${n}`}.repository`})))}async function Ue(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noEntity:o,noTests:s,prismaClientPath:c,tokenScope:l,style:u,write:d}=e;await d(`${n}.module.ts`,ge({pascal:t,kebab:n,plural:r,repo:a,style:u})),await d(`constants.ts`,a===`drizzle`?Me({pascal:t,kebab:n}):xe({pascal:t,kebab:n})),await d(`presentation/${n}.controller.ts`,ye({pascal:t,kebab:n,plural:r,pluralPascal:i})),await d(`application/dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await d(`application/dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await d(`application/dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let f=Se({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await d(`application/use-cases/${e.file}`,e.content);await d(`domain/repositories/${n}.repository.ts`,z({pascal:t,kebab:n,tokenScope:l})),await d(`domain/services/${n}-domain.service.ts`,Ce({pascal:t,kebab:n}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>B({pascal:t,kebab:n}),drizzle:()=>G({pascal:t,kebab:n}),prisma:()=>K({pascal:t,kebab:n,prismaClientPath:c})},h=p[a]??`${k(a)}-${n}`,g=m[a]??(()=>V({pascal:t,kebab:n,repoType:a}));await d(`infrastructure/repositories/${h}.repository.ts`,g()),o||(await d(`domain/entities/${n}.entity.ts`,we({pascal:t,kebab:n})),await d(`domain/value-objects/${n}-id.vo.ts`,Te({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await d(`infrastructure/repositories/in-memory-${n}.repository.ts`,B({pascal:t,kebab:n})),await d(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await d(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r})))}function We(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Ge(e){let{name:t,modulesDir:n,noEntity:i,noTests:a,repo:o=`inmemory`,force:s,dryRun:c}=e,l=e.pluralize!==!1,u=e.pattern??`ddd`;e.minimal&&(u=`minimal`);let d=k(t),p=D(t),m=l?A(d):d,h=l?j(p):p,g=r(n,m),_=[],v=s??!1,y={kebab:d,pascal:p,plural:m,pluralPascal:h,moduleDir:g,repo:o,noEntity:i??!1,noTests:a??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=r(g,e);if(c){_.push(n);return}if(!v&&await C(n)&&!await T({message:`File exists: ${f.dim(e)}. Overwrite?`,initialValue:!1})){E.warn(`Skipped: ${e}`);return}await b(n,t),_.push(n)},files:_};switch(u){case`minimal`:await Be(y);break;case`rest`:await Ve(y);break;case`cqrs`:await He(y);break;default:await Ue(y);break}return c||await q(n,p,m,d,y.style),_}async function q(e,t,n,i,a=`define`){let o=r(e,`index.ts`),s=await C(o),c=`./${n}/${i}.module`,d=a===`class`?`${t}Module`:`${t}Module()`;if(!s){await b(o,a===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
1581
+ `)}async function He(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,ve({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,xe({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`${n}.service.ts`,De({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n})),await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let d={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},f={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},p=d[a]??`${k(a)}-${n}`,m=f[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${p}.repository.ts`,m()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${d.inmemory??`in-memory-${n}`}.repository`})))}async function Ue(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,Oe({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,ke({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let d=Ae({pascal:t,kebab:n});for(let e of d)await u(`commands/${e.file}`,e.content);let f=je({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await u(`queries/${e.file}`,e.content);let p=Me({pascal:t,kebab:n});for(let e of p)await u(`events/${e.file}`,e.content);await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let m={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},h={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},g=m[a]??`${k(a)}-${n}`,_=h[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${g}.repository.ts`,_()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${m.inmemory??`in-memory-${n}`}.repository`})))}async function We(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noEntity:o,noTests:s,prismaClientPath:c,tokenScope:l,style:u,write:d}=e;await d(`${n}.module.ts`,_e({pascal:t,kebab:n,plural:r,repo:a,style:u})),await d(`constants.ts`,a===`drizzle`?Ne({pascal:t,kebab:n}):Se({pascal:t,kebab:n})),await d(`presentation/${n}.controller.ts`,be({pascal:t,kebab:n,plural:r,pluralPascal:i})),await d(`application/dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await d(`application/dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await d(`application/dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let f=Ce({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await d(`application/use-cases/${e.file}`,e.content);await d(`domain/repositories/${n}.repository.ts`,z({pascal:t,kebab:n,tokenScope:l})),await d(`domain/services/${n}-domain.service.ts`,we({pascal:t,kebab:n}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>B({pascal:t,kebab:n}),drizzle:()=>G({pascal:t,kebab:n}),prisma:()=>K({pascal:t,kebab:n,prismaClientPath:c})},h=p[a]??`${k(a)}-${n}`,g=m[a]??(()=>V({pascal:t,kebab:n,repoType:a}));await d(`infrastructure/repositories/${h}.repository.ts`,g()),o||(await d(`domain/entities/${n}.entity.ts`,Te({pascal:t,kebab:n})),await d(`domain/value-objects/${n}-id.vo.ts`,Ee({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await d(`infrastructure/repositories/in-memory-${n}.repository.ts`,B({pascal:t,kebab:n})),await d(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await d(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r})))}function Ge(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Ke(e){let{name:t,modulesDir:n,noEntity:r,noTests:a,repo:o=`inmemory`,force:s,dryRun:c}=e,l=e.pluralize!==!1,u=e.pattern??`ddd`;e.minimal&&(u=`minimal`);let d=k(t),f=D(t),m=l?A(d):d,h=l?me(f):f,g=i(n,m),_=[],v=s??!1,y={kebab:d,pascal:f,plural:m,pluralPascal:h,moduleDir:g,repo:o,noEntity:r??!1,noTests:a??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=i(g,e);if(c){_.push(n);return}if(!v&&await C(n)&&!await T({message:`File exists: ${p.dim(e)}. Overwrite?`,initialValue:!1})){E.warn(`Skipped: ${e}`);return}await b(n,t),_.push(n)},files:_};switch(u){case`minimal`:await Ve(y);break;case`rest`:await He(y);break;case`cqrs`:await Ue(y);break;default:await We(y);break}return c||await q(n,f,m,d,y.style),_}async function q(e,t,n,r,a=`define`){let o=i(e,`index.ts`),s=await C(o),c=`./${n}/${r}.module`,l=a===`class`?`${t}Module`:`${t}Module()`;if(!s){await b(o,a===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
1582
1582
  import { ${t}Module } from '${c}'
1583
1583
 
1584
- export const modules: AppModuleEntry[] = [${d}]
1584
+ export const modules: AppModuleEntry[] = [${l}]
1585
1585
  `:`import { defineModules } from '@forinda/kickjs'
1586
1586
  import { ${t}Module } from '${c}'
1587
1587
 
1588
- export const modules = defineModules().mount(${d})
1589
- `);return}let f=await l(o,`utf-8`),p=`import { ${t}Module } from '${c}'`,m=M(c);if(!RegExp(`^import\\s*\\{[^}]*\\b${M(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${m}['"]`,`m`).test(f)){let e=f.lastIndexOf(`import `);if(e!==-1){let t=f.indexOf(`
1588
+ export const modules = defineModules().mount(${l})
1589
+ `);return}let f=await u(o,`utf-8`),p=`import { ${t}Module } from '${c}'`,m=j(c);if(!RegExp(`^import\\s*\\{[^}]*\\b${j(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${m}['"]`,`m`).test(f)){let e=f.lastIndexOf(`import `);if(e!==-1){let t=f.indexOf(`
1590
1590
  `,e);f=f.slice(0,t+1)+p+`
1591
1591
  `+f.slice(t+1)}else f=p+`
1592
- `+f}let h=Y(f);if(h){let e=f.slice(h.rhsStart,h.rhsEnd+1);RegExp(`\\b${M(t)}Module\\b`).test(e)||(f=J(f,d))}else f=J(f,d);await u(o,f,`utf-8`)}function J(e,t){let n=Y(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Y(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=qe(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Ke(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Ke(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Z(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Z(e,t);if(n===-1)break;i=n+1}return i}function X(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
1593
- `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function qe(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Z(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Je(e){let{name:t,outDir:n}=e,i=k(t),a=D(t),o=[],s=r(n,`${i}.adapter.ts`);return await b(s,`import {
1592
+ `+f}let h=Y(f);if(h){let e=f.slice(h.rhsStart,h.rhsEnd+1);RegExp(`\\b${j(t)}Module\\b`).test(e)||(f=J(f,l))}else f=J(f,l);await d(o,f,`utf-8`)}function J(e,t){let n=Y(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Y(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Je(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=qe(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function qe(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Z(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Z(e,t);if(n===-1)break;i=n+1}return i}function X(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
1593
+ `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function Je(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Z(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Ye(e){let{name:t,outDir:n}=e,r=k(t),a=D(t),o=[],s=i(n,`${r}.adapter.ts`);return await b(s,`import {
1594
1594
  defineAdapter,
1595
1595
  type AdapterContext,
1596
1596
  type AdapterMiddleware,
@@ -1627,7 +1627,7 @@ export interface ${a}AdapterConfig {
1627
1627
  * @example
1628
1628
  * \`\`\`ts
1629
1629
  * import { bootstrap } from '@forinda/kickjs'
1630
- * import { ${a}Adapter } from './adapters/${i}.adapter'
1630
+ * import { ${a}Adapter } from './adapters/${r}.adapter'
1631
1631
  *
1632
1632
  * bootstrap({
1633
1633
  * modules,
@@ -1686,7 +1686,7 @@ export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
1686
1686
  */
1687
1687
  beforeMount(_ctx: AdapterContext): void {
1688
1688
  // Example:
1689
- // _ctx.app.get('/${i}/status', (_req, res) => res.json({ status: 'ok' }))
1689
+ // _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
1690
1690
  },
1691
1691
 
1692
1692
  /**
@@ -1734,10 +1734,10 @@ export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
1734
1734
  return [
1735
1735
  // Example:
1736
1736
  // import { defineHttpContextDecorator } from '@forinda/kickjs'
1737
- // declare module '@forinda/kickjs' { interface ContextMeta { ${i}: { id: string } } }
1737
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
1738
1738
  // const Load${a} = defineHttpContextDecorator({
1739
- // key: '${i}',
1740
- // resolve: (ctx) => ({ id: ctx.req.headers['x-${i}-id'] as string }),
1739
+ // key: '${r}',
1740
+ // resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
1741
1741
  // })
1742
1742
  // return [Load${a}.registration]
1743
1743
  ]
@@ -1759,31 +1759,57 @@ export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
1759
1759
  }
1760
1760
  },
1761
1761
  })
1762
- `),o.push(s),o}const Ye={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},Xe={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},Ze={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function Q(e){let{type:t,outDir:n,moduleName:a,modulesDir:o=`src/modules`,defaultDir:s,pattern:c=`ddd`,shouldPluralize:l=!0}=e;if(n)return i(n);if(a){let e=c===`ddd`?Ye:c===`cqrs`?Ze:Xe,n=k(a),s=l?A(n):n,u=e[t]??``,d=r(o,s);return i(u?r(d,u):d)}return i(s)}async function Qe(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/middleware`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=[],u=r(o,`${s}.middleware.ts`);return await b(u,`import type { Request, Response, NextFunction } from 'express'
1762
+ `),o.push(s),o}const Xe={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},Ze={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},Qe={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function Q(e){let{type:t,outDir:n,moduleName:r,modulesDir:o=`src/modules`,defaultDir:s,pattern:c=`ddd`,shouldPluralize:l=!0}=e;if(n)return a(n);if(r){let e=c===`ddd`?Xe:c===`cqrs`?Qe:Ze,n=k(r),s=l?A(n):n,u=e[t]??``,d=i(o,s);return a(u?i(d,u):d)}return a(s)}async function $e(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=[],u=i(o,`${s}.middleware.ts`);return await b(u,`import type { Request, Response, NextFunction } from 'express'
1763
1763
 
1764
1764
  export interface ${D(t)}Options {
1765
- // Add configuration options here
1765
+ // Add configuration options here. The factory below closes over the
1766
+ // resolved options object; pass them at the call site —
1767
+ // \`${c}({ foo: 'bar' })\` — and the closure preserves them across
1768
+ // every request.
1766
1769
  }
1767
1770
 
1768
1771
  /**
1769
1772
  * ${D(t)} middleware.
1770
1773
  *
1771
- * Usage in bootstrap:
1774
+ * Usage in bootstrap (fires on every request):
1772
1775
  * middleware: [${c}()]
1773
1776
  *
1774
- * Usage with adapter:
1775
- * middleware() { return [{ handler: ${c}(), phase: 'afterGlobal' }] }
1777
+ * Usage with adapter — phase controls *when* the handler runs:
1778
+ *
1779
+ * middleware() {
1780
+ * return [{ handler: ${c}(), phase: 'afterGlobal' }]
1781
+ * }
1782
+ *
1783
+ * Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
1784
+ * - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
1785
+ * request, before module routes run.
1786
+ * - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
1787
+ * OR a route handler called \`next()\` without ending the response.
1788
+ * Controllers that call \`ctx.json(…)\` end the chain and skip this
1789
+ * phase. For per-response work (logging, metrics) attach to
1790
+ * \`res.on('finish', …)\` from an earlier-phase middleware instead.
1791
+ *
1792
+ * Optional path scope — string, RegExp, or array of either:
1793
+ * middleware() {
1794
+ * return [{
1795
+ * handler: ${c}({ region: 'eu' }),
1796
+ * phase: 'afterGlobal',
1797
+ * path: ['/api', /^\\/admin/],
1798
+ * }]
1799
+ * }
1776
1800
  *
1777
1801
  * Usage with @Middleware decorator:
1778
1802
  * @Middleware(${c}())
1779
1803
  */
1780
1804
  export function ${c}(options: ${D(t)}Options = {}) {
1781
1805
  return (req: Request, res: Response, next: NextFunction) => {
1782
- // Implement your middleware logic here
1806
+ // Implement your middleware logic here. \`options\` is captured by
1807
+ // closure — log or read it anywhere in this handler body.
1808
+ void options
1783
1809
  next()
1784
1810
  }
1785
1811
  }
1786
- `),l.push(u),l}async function $e(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/guards`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=D(t),u=[],d=r(o,`${s}.guard.ts`);return await b(d,`import { Container, HttpException } from '@forinda/kickjs'
1812
+ `),l.push(u),l}async function et(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=D(t),u=[],d=i(o,`${s}.guard.ts`);return await b(d,`import { Container, HttpException } from '@forinda/kickjs'
1787
1813
  import type { RequestContext } from '@forinda/kickjs'
1788
1814
 
1789
1815
  /**
@@ -1819,7 +1845,7 @@ export async function ${c}Guard(ctx: RequestContext, next: () => void): Promise<
1819
1845
  ctx.res.status(401).json({ message: 'Invalid or expired token' })
1820
1846
  }
1821
1847
  }
1822
- `),u.push(d),u}async function et(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/services`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=r(o,`${s}.service.ts`);return await b(u,`import { Service } from '@forinda/kickjs'
1848
+ `),u.push(d),u}async function tt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=i(o,`${s}.service.ts`);return await b(u,`import { Service } from '@forinda/kickjs'
1823
1849
 
1824
1850
  @Service()
1825
1851
  export class ${c}Service {
@@ -1828,7 +1854,7 @@ export class ${c}Service {
1828
1854
  // @Inject(MY_REPO) private readonly repo: IMyRepository,
1829
1855
  // ) {}
1830
1856
  }
1831
- `),l.push(u),l}async function tt(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/controllers`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=r(o,`${s}.controller.ts`);return await b(u,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
1857
+ `),l.push(u),l}async function nt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=i(o,`${s}.controller.ts`);return await b(u,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
1832
1858
 
1833
1859
  // \`Ctx<KickRoutes.${c}Controller['<method>']>\` is generated by
1834
1860
  // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
@@ -1849,7 +1875,7 @@ export class ${c}Controller {
1849
1875
  ctx.created({ message: '${c} created', data: ctx.body })
1850
1876
  }
1851
1877
  }
1852
- `),l.push(u),l}async function nt(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/dtos`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=O(t),u=[],d=r(o,`${s}.dto.ts`);return await b(d,`import { z } from 'zod'
1878
+ `),l.push(u),l}async function rt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=O(t),u=[],d=i(o,`${s}.dto.ts`);return await b(d,`import { z } from 'zod'
1853
1879
 
1854
1880
  export const ${l}Schema = z.object({
1855
1881
  // Define your schema fields here
@@ -1857,7 +1883,7 @@ export const ${l}Schema = z.object({
1857
1883
  })
1858
1884
 
1859
1885
  export type ${c}DTO = z.infer<typeof ${l}Schema>
1860
- `),u.push(d),u}const rt={auth:`@forinda/kickjs-auth`,swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function $(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function it(e,t,n,r=[]){let i={"@forinda/kickjs":$(n,`@forinda/kickjs`),dotenv:`^17.3.1`,express:`^5.1.0`,"reflect-metadata":`^0.2.2`,zod:`^4.3.6`,pino:`^10.3.1`,"pino-pretty":`^13.1.3`};for(let e of r){let t=rt[e];t&&!i[t]&&(i[t]=$(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:i,devDependencies:{"@forinda/kickjs-cli":$(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":$(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,"@types/express":`^5.0.6`,"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function at(){return`import { defineConfig } from 'vite'
1886
+ `),u.push(d),u}const it={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function $(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function at(e,t,n,r=[]){let i={"@forinda/kickjs":$(n,`@forinda/kickjs`),dotenv:`^17.3.1`,express:`^5.1.0`,"reflect-metadata":`^0.2.2`,zod:`^4.3.6`,pino:`^10.3.1`,"pino-pretty":`^13.1.3`};for(let e of r){let t=it[e];t&&!i[t]&&(i[t]=$(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:i,devDependencies:{"@forinda/kickjs-cli":$(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":$(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,"@types/express":`^5.0.6`,"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function ot(){return`import { defineConfig } from 'vite'
1861
1887
  import { resolve } from 'node:path'
1862
1888
  import swc from 'unplugin-swc'
1863
1889
  import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
@@ -1892,7 +1918,7 @@ export default defineConfig({
1892
1918
  },
1893
1919
  },
1894
1920
  })
1895
- `}function ot(){return JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,lib:[`ES2022`],types:[`node`,`vite/client`],strict:!0,esModuleInterop:!0,skipLibCheck:!0,sourceMap:!0,declaration:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,outDir:`dist`,paths:{"@/*":[`./src/*`]}},include:[`src`,`.kickjs/types/**/*.d.ts`,`.kickjs/types/**/*.ts`]},null,2)}function st(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function ct(){return`# https://editorconfig.org
1921
+ `}function st(){return JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,lib:[`ES2022`],types:[`node`,`vite/client`],strict:!0,esModuleInterop:!0,skipLibCheck:!0,sourceMap:!0,declaration:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,outDir:`dist`,paths:{"@/*":[`./src/*`]}},include:[`src`,`.kickjs/types/**/*.d.ts`,`.kickjs/types/**/*.ts`]},null,2)}function ct(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function lt(){return`# https://editorconfig.org
1896
1922
  root = true
1897
1923
 
1898
1924
  [*]
@@ -1905,14 +1931,14 @@ insert_final_newline = true
1905
1931
 
1906
1932
  [*.md]
1907
1933
  trim_trailing_whitespace = false
1908
- `}function lt(){return`node_modules/
1934
+ `}function ut(){return`node_modules/
1909
1935
  dist/
1910
1936
  .env
1911
1937
  coverage/
1912
1938
  .DS_Store
1913
1939
  *.tsbuildinfo
1914
1940
  .kickjs/
1915
- `}function ut(){return`# Auto-detect text files and normalise line endings to LF
1941
+ `}function dt(){return`# Auto-detect text files and normalise line endings to LF
1916
1942
  * text=auto eol=lf
1917
1943
 
1918
1944
  # Explicitly mark generated / binary files
@@ -1930,11 +1956,11 @@ coverage/
1930
1956
  pnpm-lock.yaml -diff linguist-generated
1931
1957
  yarn.lock -diff linguist-generated
1932
1958
  package-lock.json -diff linguist-generated
1933
- `}function dt(){return`PORT=3000
1934
- NODE_ENV=development
1935
1959
  `}function ft(){return`PORT=3000
1936
1960
  NODE_ENV=development
1937
- `}function pt(){return`import { defineConfig } from 'vitest/config'
1961
+ `}function pt(){return`PORT=3000
1962
+ NODE_ENV=development
1963
+ `}function mt(){return`import { defineConfig } from 'vitest/config'
1938
1964
  import swc from 'unplugin-swc'
1939
1965
 
1940
1966
  export default defineConfig({
@@ -1945,7 +1971,7 @@ export default defineConfig({
1945
1971
  include: ['src/**/*.test.ts'],
1946
1972
  },
1947
1973
  })
1948
- `}function mt(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`),t===`cqrs`&&i.push(`@forinda/kickjs-queue`,`@forinda/kickjs-ws`),`# ${e}
1974
+ `}function ht(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`),t===`cqrs`&&i.push(`@forinda/kickjs-queue`,`@forinda/kickjs-ws`),`# ${e}
1949
1975
 
1950
1976
  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.
1951
1977
 
@@ -2008,29 +2034,37 @@ Copy \`.env.example\` to \`.env\` and configure:
2008
2034
 
2009
2035
  - [KickJS Documentation](https://forinda.github.io/kick-js/)
2010
2036
  - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
2011
- `}function ht(e,t,n){return`# CLAUDE.md — ${e}
2037
+ `}function gt(e,t,n){return`# CLAUDE.md — ${e}
2012
2038
 
2013
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
2039
+ **Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
2014
2040
  reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
2015
2041
  project conventions, structure, decorator patterns, env wiring, CLI
2016
2042
  generators, every gotcha.
2017
2043
 
2018
- **Then read \`./kickjs-skills.md\`.** That file is the task-oriented
2019
- skill index — short, rigid recipes keyed to triggers ("add-module",
2020
- "write-controller-test", "bootstrap-export", "deny-list", …). Use it
2021
- as the playbook when executing common KickJS workflows.
2044
+ **Then browse \`./.agents/skills/\`.** Each subdirectory is a single
2045
+ task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
2046
+ \`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
2047
+ with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
2048
+ The structure follows the Claude Code skills convention — agents that
2049
+ auto-load skills from \`.agents/skills/\` will pick each up by its
2050
+ frontmatter. Use this directory as the playbook when executing common
2051
+ KickJS workflows.
2022
2052
 
2023
2053
  This file is a thin Claude-specific layer on top of those two; when
2024
- they disagree on anything substantive, treat \`AGENTS.md\` as
2054
+ they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
2025
2055
  authoritative and flag the discrepancy.
2026
2056
 
2027
- ## Why two files
2057
+ ## Why \`.agents/\` + this thin pointer
2028
2058
 
2029
- \`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
2030
- Claude Code automatically loads as project context on each
2031
- conversation. Keeping CLAUDE.md slim avoids two files drifting; the
2032
- redirect above ensures Claude pulls the canonical content without
2033
- us copy-pasting.
2059
+ \`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
2060
+ Copilot, Aider, …) one canonical source so the prose doesn't drift
2061
+ across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
2062
+ project context on each conversation, so it stays at the project root.
2063
+ Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
2064
+ out-of-sync copies of the same content. Per-agent files
2065
+ (\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
2066
+ \`AGENTS.md\` for tool-specific notes that don't belong in the shared
2067
+ prose.
2034
2068
 
2035
2069
  ## Claude-specific notes
2036
2070
 
@@ -2045,7 +2079,7 @@ us copy-pasting.
2045
2079
  or background work. Useful for "wait for the deploy then open a
2046
2080
  cleanup PR" or "every Monday triage the issue board" patterns.
2047
2081
 
2048
- ## Quick reference (full version in AGENTS.md)
2082
+ ## Quick reference (full version in .agents/AGENTS.md)
2049
2083
 
2050
2084
  \`\`\`bash
2051
2085
  ${n} install # Install dependencies
@@ -2058,7 +2092,7 @@ ${n} run format # Prettier
2058
2092
 
2059
2093
  ## v4 framework reminders
2060
2094
 
2061
- When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
2095
+ When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
2062
2096
 
2063
2097
  - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
2064
2098
  - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
@@ -2071,10 +2105,10 @@ When generating or modifying code in this project, stay aligned with the v4 conv
2071
2105
  - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
2072
2106
  - **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.
2073
2107
  - **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\`.
2074
- - **Refresh these files**: \`kick g agents -f\` regenerates \`AGENTS.md\` + \`CLAUDE.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`AGENTS.local.md\`.
2108
+ - **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.
2075
2109
 
2076
- For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
2077
- `}function gt(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
2110
+ For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
2111
+ `}function _t(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
2078
2112
 
2079
2113
  This guide is the **canonical, multi-agent reference** for this KickJS
2080
2114
  application — Claude, Copilot, Codex, Gemini, etc. all read it first.
@@ -2581,7 +2615,142 @@ ${t===`cqrs`?`### Background Jobs
2581
2615
  - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
2582
2616
  - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
2583
2617
  - [Testing](https://forinda.github.io/kick-js/api/testing.html)
2584
- `}function _t(e,t,n){return`# kickjs-skills.md Task Skills for AI Agents (${e})
2618
+ `}function vt(e,t,n){let r=`<!-- Generated by \`kick g agents\` for ${e}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`;return[{slug:`add-module`,frontmatterName:`kickjs-add-module`,description:`Use when the user asks to add a new feature module (controller + service + repo + DTOs).`,body:`**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
2619
+
2620
+ **Steps**:
2621
+ 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
2622
+ 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
2623
+ 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
2624
+ 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
2625
+ 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
2626
+
2627
+ **Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
2628
+
2629
+ \`\`\`ts
2630
+ export const TodosModule = defineModule({
2631
+ name: 'TodosModule',
2632
+ build: () => ({
2633
+ register(container) {
2634
+ container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
2635
+ },
2636
+ routes() {
2637
+ return { path: '/todos', controller: TodosController }
2638
+ },
2639
+ }),
2640
+ })
2641
+ \`\`\`
2642
+
2643
+ The 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\`.
2644
+
2645
+ **Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
2646
+
2647
+ \`\`\`ts
2648
+ routes() {
2649
+ return [
2650
+ { path: '/todos', controller: TodosController }, // /api/v1/todos
2651
+ { path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
2652
+ ]
2653
+ }
2654
+ \`\`\`
2655
+
2656
+ **Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
2657
+
2658
+ **Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
2659
+
2660
+ **Red flags** (stop and ask):
2661
+ - 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.
2662
+ - \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
2663
+ - \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
2664
+ - \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
2665
+ - Module not registered in \`src/modules/index.ts\`.`},{slug:`add-adapter`,frontmatterName:`kickjs-add-adapter`,description:`Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).`,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."},{slug:`add-plugin`,frontmatterName:`kickjs-add-plugin`,description:`Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).`,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."},{slug:`write-controller-test`,frontmatterName:`kickjs-write-controller-test`,description:`Use when adding a Vitest test that exercises an HTTP route or DI graph.`,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."},{slug:`env-wiring-check`,frontmatterName:`kickjs-env-wiring-check`,description:`Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.`,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`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,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."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
2666
+
2667
+ \`\`\`ts
2668
+ // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
2669
+ export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
2670
+ // OR for class-form projects (\`modules.style: 'class'\`):
2671
+ // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
2672
+
2673
+ // src/middleware/index.ts — global middleware uses RAW EXPRESS signature
2674
+ // (req, res, next), NOT (ctx, next)
2675
+ export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
2676
+
2677
+ // src/plugins/index.ts
2678
+ export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
2679
+
2680
+ // src/adapters/index.ts
2681
+ export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
2682
+
2683
+ // src/index.ts — stays small
2684
+ import 'reflect-metadata'
2685
+ import './config' // MUST be early — side-effect schema load
2686
+ import { bootstrap } from '@forinda/kickjs'
2687
+ import { modules } from './modules'
2688
+ import { middleware } from './middleware'
2689
+ import { plugins } from './plugins'
2690
+ import { adapters } from './adapters'
2691
+ export const app = await bootstrap({ modules, middleware, plugins, adapters })
2692
+ \`\`\`
2693
+
2694
+ **One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
2695
+
2696
+ \`\`\`ts
2697
+ plugins: [
2698
+ ...plugins,
2699
+ { name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
2700
+ ]
2701
+ \`\`\`
2702
+
2703
+ **Red flags**:
2704
+ - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
2705
+ - 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".
2706
+ - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,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."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,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`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,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."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
2707
+ - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
2708
+ - \`kick dev\` — local dev server with Vite HMR.
2709
+ - \`kick build\` — production bundle via Vite.
2710
+ - \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
2711
+ - \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
2712
+ - \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
2713
+ - \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
2714
+ - \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
2715
+ - \`kick info\` — environment / version dump for bug reports.
2716
+ - \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
2717
+
2718
+ **Useful flag combos**:
2719
+
2720
+ \`\`\`bash
2721
+ kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
2722
+ kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
2723
+ kick new . --yes --force # Scaffold into current dir, clear existing files
2724
+ kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
2725
+ kick g agents -f --only skills # Refresh just the skills after upgrade
2726
+ kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
2727
+ kick inspect --port 4000 --json # Machine-readable route/adapter dump
2728
+ kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
2729
+ \`\`\`
2730
+
2731
+ **Lesser-known, high-value**:
2732
+ - \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
2733
+ - \`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.
2734
+ - \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
2735
+ - \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
2736
+ - \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
2737
+ - \`kick check\` — preflight gate (typecheck + lint + format) before commit.
2738
+ - \`kick codemod\` — automated AST-level migration between framework versions.
2739
+
2740
+ **Red flags**:
2741
+ - Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
2742
+ - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
2743
+ - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
2744
+ - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
2745
+ - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`refresh-agent-docs`,frontmatterName:`kickjs-refresh-agent-docs`,description:`Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.`,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."},{slug:`deny-list`,frontmatterName:`kickjs-deny-list`,description:`Patterns to refuse outright when the user asks for them — they break v4 invariants.`,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`."}].map(e=>({slug:e.slug,content:`---
2746
+ name: ${e.frontmatterName}
2747
+ description: ${e.description}
2748
+ ---
2749
+
2750
+ ${r}
2751
+
2752
+ ${e.body}
2753
+ `}))}function yt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
2585
2754
 
2586
2755
  This file is the agent-facing **skills index** for KickJS work in this
2587
2756
  repo. Each block below is a short, rigid workflow keyed to a specific
@@ -2830,7 +2999,74 @@ description: Patterns to refuse outright when the user asks for them — they br
2830
2999
  - [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
2831
3000
  - [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
2832
3001
  - [Testing](https://forinda.github.io/kick-js/api/testing.html)
2833
- `}const vt=t(g(import.meta.url)),yt=JSON.parse(o(r(vt,`..`,`package.json`),`utf-8`)),bt=`^${yt.version}`,xt=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`,`@forinda/kickjs-auth`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`];async function St(){let e=await Promise.all(xt.map(async e=>{try{let t=m(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,bt]}));return Object.fromEntries(e)}async function Ct(e){let{name:t,directory:n,packageManager:i=`pnpm`,template:a=`rest`,defaultRepo:o=`inmemory`,packages:s=[]}=e,c=n,l=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),l(`Resolving package versions...`);let u=await St();if(await b(r(c,`package.json`),it(t,a,u,s)),await b(r(c,`vite.config.ts`),at()),await b(r(c,`tsconfig.json`),ot()),await b(r(c,`.prettierrc`),st()),await b(r(c,`.editorconfig`),ct()),await b(r(c,`.gitignore`),lt()),await b(r(c,`.gitattributes`),ut()),await b(r(c,`.env`),dt()),await b(r(c,`.env.example`),ft()),await b(r(c,`src/config/index.ts`),Fe()),await b(r(c,`src/index.ts`),Ne(t,a,yt.version,s)),await b(r(c,`src/modules/index.ts`),Pe()),await b(r(c,`src/modules/hello/hello.service.ts`),Ie()),await b(r(c,`src/modules/hello/hello.controller.ts`),Le()),await b(r(c,`src/modules/hello/hello.module.ts`),Re()),await b(r(c,`kick.config.ts`),ze(a,o,i)),await b(r(c,`vitest.config.ts`),pt()),await b(r(c,`README.md`),mt(t,a,i)),await b(r(c,`CLAUDE.md`),ht(t,a,i)),await b(r(c,`AGENTS.md`),gt(t,a,i)),await b(r(c,`kickjs-skills.md`),_t(t,a,i)),e.installDeps){console.log(`\n Installing dependencies with ${i}...\n`);try{h(`${i} install`,{cwd:c,stdio:`inherit`}),console.log(`
2834
- Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${i} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-CYaoTJ6r.mjs`).then(e=>e.r);await e({cwd:c,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{h(`git init`,{cwd:c,stdio:`pipe`}),h(`git branch -M main`,{cwd:c,stdio:`pipe`}),h(`git add -A`,{cwd:c,stdio:`pipe`}),h(`git commit -m "chore: initial commit from kick new"`,{cwd:c,stdio:`pipe`}),l(`Git repository initialized`)}catch{l(`Warning: git init failed (git may not be installed)`)}console.log(`
2835
- Project scaffolded successfully!`),console.log();let d=c!==process.cwd();l(`Next steps:`),d&&l(` cd ${t}`),e.installDeps||l(` ${i} install`);let f={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};l(` ${f[a]??f.rest}`),l(` kick dev`),l(``),l(`Commands:`),l(` kick dev Start dev server with Vite HMR`),l(` kick build Production build via Vite`),l(` kick start Run production build`),l(``),l(`Generators:`),l(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),l(` kick g scaffold <n> <f..> CRUD module from field definitions`),l(` kick g controller <name> Standalone controller`),l(` kick g service <name> @Service() class`),l(` kick g middleware <name> Express middleware`),l(` kick g guard <name> Route guard (auth, roles, etc.)`),l(` kick g adapter <name> AppAdapter with lifecycle hooks`),l(` kick g dto <name> Zod DTO schema`),a===`cqrs`&&l(` kick g job <name> Queue job processor`),l(` kick g config Generate kick.config.ts`),l(``),l(`Add packages:`),l(` kick add <pkg> Install a KickJS package + peers`),l(` kick add --list Show all available packages`),l(``),l(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),l(``)}function wt(e){return e}function Tt(e){return k(e).replace(/-/g,`_`)}function Et(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=D(e.name),i=O(e.name),a=k(e.name),o=Tt(e.name),s={name:e.name,pascal:r,camel:i,kebab:a,snake:o,modulesDir:e.modulesDir??`src/modules`,cwd:t,args:e.args??[],flags:e.flags??{}};if(n){let e=A(a);s.pluralKebab=e,s.pluralPascal=D(e),s.pluralCamel=O(e)}return s}function Dt(e,t){return i(e.cwd,t)}async function Ot(e){return import(_(e).href)}const kt=new Map;async function At(e){let t=kt.get(e);if(t)return t;let n=jt(e);return kt.set(e,n),n}async function jt(n){let r=i(n,`package.json`);if(!a(r))return{generators:[],loaded:[],failed:[]};let o=Mt(JSON.parse(await l(r,`utf-8`))),s=e(i(n,`package.json`)),c=[],u=[],d=[];for(let e of o){let n;try{n=s.resolve(`${e}/package.json`)}catch{continue}let r;try{r=JSON.parse(await l(n,`utf-8`))}catch(t){d.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!r.kickjs?.generators)continue;let o=r.kickjs.generators,f=i(t(n),o);if(!a(f)){d.push({source:e,reason:`kickjs.generators points to missing file: ${o}`});continue}let p;try{p=await Ot(f)}catch(t){d.push({source:e,reason:`failed to import manifest: ${t}`});continue}let m=p.default;if(!Array.isArray(m)){d.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of m){if(!Nt(t)){d.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}c.push({source:e,spec:t})}u.push(e)}return{generators:c,loaded:u,failed:d}}function Mt(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Nt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Pt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Lt(r.spec,r.source,e,n);let i=It(await At(n),e.generatorName);return i?Lt(i.spec,i.source,e,n):null}async function Ft(e,t=[]){let n=await At(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function It(e,t){return e.generators.find(e=>e.spec.name===t)}async function Lt(e,t,n,r){let i=Et({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r}),a=await e.files(i),o=[];for(let e of a){let t=Dt(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}export{ue as A,k as C,E as D,se as E,oe as F,C as I,y as L,le as M,ae as N,de as O,f as P,b as R,O as S,T,Ge as _,Ct as a,A as b,_t as c,et as d,$e as f,Y as g,q as h,wt as i,fe as j,ce as k,nt as l,Je as m,Pt as n,gt as o,Qe as p,Et as r,ht as s,Ft as t,tt as u,We as v,D as w,j as x,M as y};
2836
- //# sourceMappingURL=generator-extension-m04pTdQi.mjs.map
3002
+ `}function bt(e,t,n){return`# GEMINI.md ${e}
3003
+
3004
+ **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
3005
+ reference for this project — every convention, structure, decorator
3006
+ pattern, env wiring rule, generator usage. This file is a thin
3007
+ Gemini-specific layer; when the two disagree on anything substantive,
3008
+ treat \`AGENTS.md\` as authoritative and flag the discrepancy.
3009
+
3010
+ ## Why this file
3011
+
3012
+ Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
3013
+ agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
3014
+ means Gemini reads the same shared prose as Codex / Cursor / Copilot
3015
+ without us copy-pasting.
3016
+
3017
+ ## Gemini-specific notes
3018
+
3019
+ - **Skills activation** — Gemini activates skills via
3020
+ \`activate_skill\` (its native MCP-style tool); the equivalent on
3021
+ Claude Code is the \`Skill\` tool. Cross-reference the
3022
+ \`kickjs-skills.md\` index for the available triggers.
3023
+ - **Tool naming** — Gemini's tool names differ from Claude Code's
3024
+ (e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
3025
+ \`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
3026
+ tool names; consult Gemini's docs for the concrete invocation.
3027
+ - **File ops** — Gemini's file edits are sandboxed; large refactors
3028
+ may need explicit confirmation. Prefer the smallest-possible-edit
3029
+ pattern.
3030
+
3031
+ ## Refreshing this file
3032
+
3033
+ \`kick g agents --only gemini -f\` regenerates this file from the
3034
+ CLI template. Hand-edited content is overwritten — keep customisation
3035
+ in \`.agents/GEMINI.local.md\`.
3036
+ `}function xt(e,t,n){return`# COPILOT.md — ${e}
3037
+
3038
+ **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
3039
+ reference for this project — every convention, structure, decorator
3040
+ pattern, env wiring rule, generator usage. This file is a thin
3041
+ Copilot-specific layer; when the two disagree on anything substantive,
3042
+ treat \`AGENTS.md\` as authoritative and flag the discrepancy.
3043
+
3044
+ ## Why this file
3045
+
3046
+ GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
3047
+ the agent-context files. Keeping it in \`.agents/\` next to
3048
+ \`AGENTS.md\` means Copilot reads the same shared prose as
3049
+ Codex / Cursor / Gemini / Claude Code without copy-pasting.
3050
+
3051
+ ## Copilot-specific notes
3052
+
3053
+ - **Skills** — Copilot CLI auto-discovers skills from installed
3054
+ plugins; cross-reference \`kickjs-skills.md\` for available
3055
+ triggers in this project.
3056
+ - **Tool naming** — Copilot's tool names differ from Claude Code's
3057
+ (\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
3058
+ prose in \`AGENTS.md\` describes intents, not tool names; consult
3059
+ Copilot's docs for the concrete invocation.
3060
+ - **Confirmation flows** — Copilot CLI surfaces destructive
3061
+ operations through an explicit approval gate. Stage edits with
3062
+ short, focused diffs so each one is easy to review at the prompt.
3063
+
3064
+ ## Refreshing this file
3065
+
3066
+ \`kick g agents --only copilot -f\` regenerates this file from the
3067
+ CLI template. Hand-edited content is overwritten — keep customisation
3068
+ in \`.agents/COPILOT.local.md\`.
3069
+ `}const St=n(_(import.meta.url)),Ct=JSON.parse(s(i(St,`..`,`package.json`),`utf-8`)),wt=`^${Ct.version}`,Tt=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`];async function Et(){let e=await Promise.all(Tt.map(async e=>{try{let t=h(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,wt]}));return Object.fromEntries(e)}async function Dt(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:a=`rest`,defaultRepo:o=`inmemory`,packages:s=[]}=e,c=n,l=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),l(`Resolving package versions...`);let u=await Et();if(await b(i(c,`package.json`),at(t,a,u,s)),await b(i(c,`vite.config.ts`),ot()),await b(i(c,`tsconfig.json`),st()),await b(i(c,`.prettierrc`),ct()),await b(i(c,`.editorconfig`),lt()),await b(i(c,`.gitignore`),ut()),await b(i(c,`.gitattributes`),dt()),await b(i(c,`.env`),ft()),await b(i(c,`.env.example`),pt()),await b(i(c,`src/config/index.ts`),Ie()),await b(i(c,`src/index.ts`),Pe(t,a,Ct.version,s)),await b(i(c,`src/modules/index.ts`),Fe()),await b(i(c,`src/modules/hello/hello.service.ts`),Le()),await b(i(c,`src/modules/hello/hello.controller.ts`),Re()),await b(i(c,`src/modules/hello/hello.module.ts`),ze()),await b(i(c,`kick.config.ts`),Be(a,o,r)),await b(i(c,`vitest.config.ts`),mt()),await b(i(c,`README.md`),ht(t,a,r)),await b(i(c,`CLAUDE.md`),gt(t,a,r)),await b(i(c,`AGENTS.md`),_t(t,a,r)),await b(i(c,`kickjs-skills.md`),yt(t,a,r)),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{g(`${r} install`,{cwd:c,stdio:`inherit`}),console.log(`
3070
+ Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-C3G375CR.mjs`).then(e=>e.r);await e({cwd:c,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{g(`git init`,{cwd:c,stdio:`pipe`}),g(`git branch -M main`,{cwd:c,stdio:`pipe`}),g(`git add -A`,{cwd:c,stdio:`pipe`}),g(`git commit -m "chore: initial commit from kick new"`,{cwd:c,stdio:`pipe`}),l(`Git repository initialized`)}catch{l(`Warning: git init failed (git may not be installed)`)}console.log(`
3071
+ Project scaffolded successfully!`),console.log();let d=c!==process.cwd();l(`Next steps:`),d&&l(` cd ${t}`),e.installDeps||l(` ${r} install`);let f={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};l(` ${f[a]??f.rest}`),l(` kick dev`),l(``),l(`Commands:`),l(` kick dev Start dev server with Vite HMR`),l(` kick build Production build via Vite`),l(` kick start Run production build`),l(``),l(`Generators:`),l(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),l(` kick g scaffold <n> <f..> CRUD module from field definitions`),l(` kick g controller <name> Standalone controller`),l(` kick g service <name> @Service() class`),l(` kick g middleware <name> Express middleware`),l(` kick g guard <name> Route guard (auth, roles, etc.)`),l(` kick g adapter <name> AppAdapter with lifecycle hooks`),l(` kick g dto <name> Zod DTO schema`),a===`cqrs`&&l(` kick g job <name> Queue job processor`),l(` kick g config Generate kick.config.ts`),l(``),l(`Add packages:`),l(` kick add <pkg> Install a KickJS package + peers`),l(` kick add --list Show all available packages`),l(``),l(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),l(``)}function Ot(e){return e}function kt(e){return k(e).replace(/-/g,`_`)}function At(t){let n=t.cwd??process.cwd(),r=t.projectRoot??e(n),i=t.pluralize??!0,a=D(t.name),o=O(t.name),s=k(t.name),c=kt(t.name),l={name:t.name,pascal:a,camel:o,kebab:s,snake:c,modulesDir:t.modulesDir??`src/modules`,cwd:n,projectRoot:r,args:t.args??[],flags:t.flags??{}};if(i){let e=A(s);l.pluralKebab=e,l.pluralPascal=D(e),l.pluralCamel=O(e)}return l}function jt(e,t){return a(e.cwd,t)}async function Mt(e){return import(v(e).href)}const Nt=new Map;async function Pt(e){let t=Nt.get(e);if(t)return t;let n=Ft(e);return Nt.set(e,n),n}async function Ft(e){let r=a(e,`package.json`);if(!o(r))return{generators:[],loaded:[],failed:[]};let i=It(JSON.parse(await u(r,`utf-8`))),s=t(a(e,`package.json`)),c=[],l=[],d=[];for(let e of i){let t;try{t=s.resolve(`${e}/package.json`)}catch{continue}let r;try{r=JSON.parse(await u(t,`utf-8`))}catch(t){d.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!r.kickjs?.generators)continue;let i=r.kickjs.generators,f=a(n(t),i);if(!o(f)){d.push({source:e,reason:`kickjs.generators points to missing file: ${i}`});continue}let p;try{p=await Mt(f)}catch(t){d.push({source:e,reason:`failed to import manifest: ${t}`});continue}let m=p.default;if(!Array.isArray(m)){d.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of m){if(!Lt(t)){d.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}c.push({source:e,spec:t})}l.push(e)}return{generators:c,loaded:l,failed:d}}function It(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Lt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Rt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Vt(r.spec,r.source,e,n);let i=Bt(await Pt(n),e.generatorName);return i?Vt(i.spec,i.source,e,n):null}async function zt(e,t=[]){let n=await Pt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function Bt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Vt(e,t,n,r){let i=At({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=jt(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}export{fe as A,b as B,me as C,T as D,D as E,oe as F,p as I,se as L,de as M,pe as N,ce as O,ue as P,C as R,A as S,k as T,q as _,Dt as a,Ge as b,xt as c,rt as d,nt as f,Ye as g,$e as h,Ot as i,le as j,E as k,bt as l,et as m,Rt as n,_t as o,tt as p,At as r,gt as s,zt as t,vt as u,Y as v,O as w,j as x,Ke as y,ee as z};
3072
+ //# sourceMappingURL=generator-extension-BXLt3Tp_.mjs.map