@forinda/kickjs-cli 5.2.0 → 5.2.3

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 (34) hide show
  1. package/dist/builtins-BdvmVAJ1.mjs +3740 -0
  2. package/dist/builtins-Du70nybS.mjs +1066 -0
  3. package/dist/builtins-Du70nybS.mjs.map +1 -0
  4. package/dist/cli.mjs +2 -120
  5. package/dist/config-Dzw8Ws4d.mjs +11 -0
  6. package/dist/config-lCKbrRnt.mjs +12 -0
  7. package/dist/{config-DDrgs-I3.mjs.map → config-lCKbrRnt.mjs.map} +1 -1
  8. package/dist/generator-extension-Cp5FUUAw.mjs +2687 -0
  9. package/dist/generator-extension-Cp5FUUAw.mjs.map +1 -0
  10. package/dist/index.mjs +2 -5
  11. package/dist/plugin-Dv2gKsuC.mjs +11 -0
  12. package/dist/plugin-VPl_QQGb.mjs +12 -0
  13. package/dist/{plugin-6_YlK-JG.mjs.map → plugin-VPl_QQGb.mjs.map} +1 -1
  14. package/dist/rolldown-runtime-B6QC8dMY.mjs +11 -0
  15. package/dist/{run-plugins-B1R0HG0g.mjs → run-plugins-CM1Af-4B.mjs} +2 -3
  16. package/dist/typegen-C6ZfoYTC.mjs +114 -0
  17. package/dist/typegen-CBI7dNXr.mjs +115 -0
  18. package/dist/{typegen-DugZmi-0.mjs.map → typegen-CBI7dNXr.mjs.map} +1 -1
  19. package/dist/types-n4LRUF_c.mjs +12 -0
  20. package/dist/{types-CGB8BiQh.mjs.map → types-n4LRUF_c.mjs.map} +1 -1
  21. package/package.json +5 -5
  22. package/dist/builtins-BW3g09hP.mjs +0 -8538
  23. package/dist/builtins-C_VfEGdg.mjs +0 -4182
  24. package/dist/builtins-C_VfEGdg.mjs.map +0 -1
  25. package/dist/config-DDrgs-I3.mjs +0 -171
  26. package/dist/config-DsQe2yzy.mjs +0 -169
  27. package/dist/generator-extension-DRNQpoZP.mjs +0 -4380
  28. package/dist/generator-extension-DRNQpoZP.mjs.map +0 -1
  29. package/dist/plugin-6_YlK-JG.mjs +0 -71
  30. package/dist/plugin-CQ0yYXyr.mjs +0 -80
  31. package/dist/rolldown-runtime-CYBbkZNy.mjs +0 -24
  32. package/dist/typegen-CYCsmCRF.mjs +0 -1351
  33. package/dist/typegen-DugZmi-0.mjs +0 -1353
  34. package/dist/types-CGB8BiQh.mjs +0 -25
@@ -0,0 +1,2687 @@
1
+ /**
2
+ * @forinda/kickjs-cli v5.2.3
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
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{execSync as m}from"node:child_process";import{fileURLToPath as h,pathToFileURL as g}from"node:url";let _=!1;function v(e){_=e}const y=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function b(e,r){_||(await c(t(e),{recursive:!0}),await u(e,r,`utf-8`),y.has(n(e))&&await te(e,r).catch(()=>{}))}let x;async function ee(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 te(e,t){let n=await ee(process.cwd());if(!n)return;let r=await ne(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 ne(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 re={GET:f.green,POST:f.cyan,PUT:f.yellow,PATCH:f.magenta,DELETE:f.red};function ie(e){return(re[e]??f.dim)(e.padEnd(7))}function ae(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 oe(e){d.intro(f.bgCyan(f.black(` ${e} `)))}function se(e){d.outro(e)}function w(e){d.isCancel(e)&&(d.cancel(`Operation cancelled.`),process.exit(0))}async function ce(e){let t=await d.text(e);return w(t),t}async function le(e){let t=await d.select(e);return w(t),t}async function ue(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 de(){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)}const fe={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 pe(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function N(e){return fe[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]??`${pe(n)}-${t}`}}function me(e){let{pascal:t,kebab:n,plural:r=``,repo:i}=e,{repoClass:a,repoFile:o}=P(t,n,i);return`/**
12
+ * ${t} Module
13
+ *
14
+ * Self-contained feature module following Domain-Driven Design (DDD).
15
+ * Registers dependencies in the DI container and declares HTTP routes.
16
+ *
17
+ * Structure:
18
+ * presentation/ — HTTP controllers (entry points)
19
+ * application/ — Use cases (orchestration) and DTOs (validation)
20
+ * domain/ — Entities, value objects, repository interfaces, domain services
21
+ * infrastructure/ — Repository implementations (currently ${N(i)})
22
+ */
23
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
24
+ import { buildRoutes } from '@forinda/kickjs'
25
+ import { ${t.toUpperCase()}_REPOSITORY } from './domain/repositories/${n}.repository'
26
+ import { ${a} } from './infrastructure/repositories/${o}.repository'
27
+ import { ${t}Controller } from './presentation/${n}.controller'
28
+
29
+ // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
30
+ import.meta.glob(
31
+ ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
32
+ { eager: true },
33
+ )
34
+
35
+ export class ${t}Module implements AppModule {
36
+ /**
37
+ * Register module dependencies in the DI container.
38
+ * Bind repository interface tokens to their implementations here.
39
+ * Currently wired to ${N(i)}. To swap implementations, change the factory target.
40
+ */
41
+ register(container: Container): void {
42
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
43
+ container.resolve(${a}),
44
+ )
45
+ }
46
+
47
+ /**
48
+ * Declare HTTP routes for this module.
49
+ * The path is prefixed with the global apiPrefix and version (e.g. /api/v1/${r}).
50
+ * Passing 'controller' enables automatic OpenAPI spec generation via SwaggerAdapter.
51
+ */
52
+ routes(): ModuleRoutes {
53
+ return {
54
+ path: '/${r}',
55
+ router: buildRoutes(${t}Controller),
56
+ controller: ${t}Controller,
57
+ }
58
+ }
59
+ }
60
+ `}function he(e){let{pascal:t,kebab:n,plural:r=``,repo:i}=e,{repoClass:a,repoFile:o}=P(t,n,i);return`/**
61
+ * ${t} Module
62
+ *
63
+ * REST module with a flat folder structure.
64
+ * Controller delegates to service, service wraps the repository.
65
+ *
66
+ * Structure:
67
+ * ${n}.controller.ts — HTTP routes (CRUD)
68
+ * ${n}.service.ts — Business logic
69
+ * ${n}.repository.ts — Repository interface
70
+ * ${o}.repository.ts — Repository implementation
71
+ * dtos/ — Request/response schemas
72
+ */
73
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
74
+ import { buildRoutes } from '@forinda/kickjs'
75
+ import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
76
+ import { ${a} } from './${o}.repository'
77
+ import { ${t}Controller } from './${n}.controller'
78
+
79
+ // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
80
+ import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })
81
+
82
+ export class ${t}Module implements AppModule {
83
+ register(container: Container): void {
84
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
85
+ container.resolve(${a}),
86
+ )
87
+ }
88
+
89
+ routes(): ModuleRoutes {
90
+ return {
91
+ path: '/${r}',
92
+ router: buildRoutes(${t}Controller),
93
+ controller: ${t}Controller,
94
+ }
95
+ }
96
+ }
97
+ `}function ge(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
98
+ import { buildRoutes } from '@forinda/kickjs'
99
+ import { ${t}Controller } from './${n}.controller'
100
+
101
+ export class ${t}Module implements AppModule {
102
+ routes(): ModuleRoutes {
103
+ return {
104
+ path: '/${r}',
105
+ router: buildRoutes(${t}Controller),
106
+ controller: ${t}Controller,
107
+ }
108
+ }
109
+ }
110
+ `}function _e(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'
111
+ import { ApiTags } from '@forinda/kickjs-swagger'
112
+ import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
113
+ import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
114
+ import { List${i}UseCase } from '../application/use-cases/list-${r}.use-case'
115
+ import { Update${t}UseCase } from '../application/use-cases/update-${n}.use-case'
116
+ import { Delete${t}UseCase } from '../application/use-cases/delete-${n}.use-case'
117
+ import { create${t}Schema } from '../application/dtos/create-${n}.dto'
118
+ import { update${t}Schema } from '../application/dtos/update-${n}.dto'
119
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from '../constants'
120
+
121
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
122
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
123
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
124
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
125
+
126
+ @Controller()
127
+ export class ${t}Controller {
128
+ @Autowired() private readonly create${t}UseCase!: Create${t}UseCase
129
+ @Autowired() private readonly get${t}UseCase!: Get${t}UseCase
130
+ @Autowired() private readonly list${i}UseCase!: List${i}UseCase
131
+ @Autowired() private readonly update${t}UseCase!: Update${t}UseCase
132
+ @Autowired() private readonly delete${t}UseCase!: Delete${t}UseCase
133
+
134
+ @Get('/')
135
+ @ApiTags('${t}')
136
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
137
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
138
+ return ctx.paginate(
139
+ (parsed) => this.list${i}UseCase.execute(parsed),
140
+ ${t.toUpperCase()}_QUERY_CONFIG,
141
+ )
142
+ }
143
+
144
+ @Get('/:id')
145
+ @ApiTags('${t}')
146
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
147
+ const result = await this.get${t}UseCase.execute(ctx.params.id)
148
+ if (!result) return ctx.notFound('${t} not found')
149
+ ctx.json(result)
150
+ }
151
+
152
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
153
+ @ApiTags('${t}')
154
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
155
+ const result = await this.create${t}UseCase.execute(ctx.body)
156
+ ctx.created(result)
157
+ }
158
+
159
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
160
+ @ApiTags('${t}')
161
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
162
+ const result = await this.update${t}UseCase.execute(ctx.params.id, ctx.body)
163
+ ctx.json(result)
164
+ }
165
+
166
+ @Delete('/:id')
167
+ @ApiTags('${t}')
168
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
169
+ await this.delete${t}UseCase.execute(ctx.params.id)
170
+ ctx.noContent()
171
+ }
172
+ }
173
+ `}function ve(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'
174
+ import { ApiTags } from '@forinda/kickjs-swagger'
175
+ import { ${t}Service } from './${n}.service'
176
+ import { create${t}Schema } from './dtos/create-${n}.dto'
177
+ import { update${t}Schema } from './dtos/update-${n}.dto'
178
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
179
+
180
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
181
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
182
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
183
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
184
+
185
+ @Controller()
186
+ export class ${t}Controller {
187
+ @Autowired() private readonly ${r}Service!: ${t}Service
188
+
189
+ @Get('/')
190
+ @ApiTags('${t}')
191
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
192
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
193
+ return ctx.paginate(
194
+ (parsed) => this.${r}Service.findPaginated(parsed),
195
+ ${t.toUpperCase()}_QUERY_CONFIG,
196
+ )
197
+ }
198
+
199
+ @Get('/:id')
200
+ @ApiTags('${t}')
201
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
202
+ const result = await this.${r}Service.findById(ctx.params.id)
203
+ if (!result) return ctx.notFound('${t} not found')
204
+ ctx.json(result)
205
+ }
206
+
207
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
208
+ @ApiTags('${t}')
209
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
210
+ const result = await this.${r}Service.create(ctx.body)
211
+ ctx.created(result)
212
+ }
213
+
214
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
215
+ @ApiTags('${t}')
216
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
217
+ const result = await this.${r}Service.update(ctx.params.id, ctx.body)
218
+ ctx.json(result)
219
+ }
220
+
221
+ @Delete('/:id')
222
+ @ApiTags('${t}')
223
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
224
+ await this.${r}Service.delete(ctx.params.id)
225
+ ctx.noContent()
226
+ }
227
+ }
228
+ `}function ye(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
229
+
230
+ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
231
+ filterable: ['name'],
232
+ sortable: ['name', 'createdAt'],
233
+ searchable: ['name'],
234
+ }
235
+ `}function F(e){let{pascal:t}=e;return`import { z } from 'zod'
236
+
237
+ /**
238
+ * Create ${t} DTO — Zod schema for validating POST request bodies.
239
+ * This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
240
+ * It also generates OpenAPI request body docs when SwaggerAdapter is used.
241
+ *
242
+ * Add more fields as needed. Supported Zod types:
243
+ * z.string(), z.number(), z.boolean(), z.enum([...]),
244
+ * z.array(), z.object(), .optional(), .default(), .transform()
245
+ */
246
+ export const create${t}Schema = z.object({
247
+ name: z.string().min(1, 'Name is required').max(200),
248
+ })
249
+
250
+ export type Create${t}DTO = z.infer<typeof create${t}Schema>
251
+ `}function I(e){let{pascal:t}=e;return`import { z } from 'zod'
252
+
253
+ export const update${t}Schema = z.object({
254
+ name: z.string().min(1).max(200).optional(),
255
+ })
256
+
257
+ export type Update${t}DTO = z.infer<typeof update${t}Schema>
258
+ `}function L(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
259
+ id: string
260
+ name: string
261
+ createdAt: string
262
+ updatedAt: string
263
+ }
264
+ `}function be(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
265
+ * Create ${t} Use Case
266
+ *
267
+ * Application layer — orchestrates a single business operation.
268
+ * Use cases are thin: validate input (via DTO), call domain/repo, return response.
269
+ * Keep business rules in the domain service, not here.
270
+ */
271
+ import { Service, Inject } from '@forinda/kickjs'
272
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
273
+ import type { Create${t}DTO } from '../dtos/create-${n}.dto'
274
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
275
+
276
+ @Service()
277
+ export class Create${t}UseCase {
278
+ constructor(
279
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
280
+ ) {}
281
+
282
+ async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
283
+ return this.repo.create(dto)
284
+ }
285
+ }
286
+ `},{file:`get-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
287
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
288
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
289
+
290
+ @Service()
291
+ export class Get${t}UseCase {
292
+ constructor(
293
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
294
+ ) {}
295
+
296
+ async execute(id: string): Promise<${t}ResponseDTO | null> {
297
+ return this.repo.findById(id)
298
+ }
299
+ }
300
+ `},{file:`list-${r}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
301
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
302
+ import type { ParsedQuery } from '@forinda/kickjs'
303
+
304
+ @Service()
305
+ export class List${i}UseCase {
306
+ constructor(
307
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
308
+ ) {}
309
+
310
+ async execute(parsed: ParsedQuery) {
311
+ return this.repo.findPaginated(parsed)
312
+ }
313
+ }
314
+ `},{file:`update-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
315
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
316
+ import type { Update${t}DTO } from '../dtos/update-${n}.dto'
317
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
318
+
319
+ @Service()
320
+ export class Update${t}UseCase {
321
+ constructor(
322
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
323
+ ) {}
324
+
325
+ async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
326
+ return this.repo.update(id, dto)
327
+ }
328
+ }
329
+ `},{file:`delete-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
330
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
331
+
332
+ @Service()
333
+ export class Delete${t}UseCase {
334
+ constructor(
335
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
336
+ ) {}
337
+
338
+ async execute(id: string): Promise<void> {
339
+ await this.repo.delete(id)
340
+ }
341
+ }
342
+ `}]}function R(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
343
+ * ${t} Repository Interface
344
+ *
345
+ * Defines the contract for data access.
346
+ * The interface declares what operations are available;
347
+ * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
348
+ *
349
+ * To swap implementations, change the factory in the module's register() method.
350
+ */
351
+ import { createToken } from '@forinda/kickjs'
352
+ import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
353
+ import type { Create${t}DTO } from '${r}/create-${n}.dto'
354
+ import type { Update${t}DTO } from '${r}/update-${n}.dto'
355
+ import type { ParsedQuery } from '@forinda/kickjs'
356
+
357
+ export interface I${t}Repository {
358
+ findById(id: string): Promise<${t}ResponseDTO | null>
359
+ findAll(): Promise<${t}ResponseDTO[]>
360
+ findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
361
+ create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
362
+ update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
363
+ delete(id: string): Promise<void>
364
+ }
365
+
366
+ /**
367
+ * Collision-safe DI token bound to \`I${t}Repository\`.
368
+ * \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
369
+ * \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
370
+ * interface — no manual generic, no \`any\` cast.
371
+ *
372
+ * The \`'${i}/'\` prefix matches the project scope so
373
+ * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
374
+ * adopters must NOT use the reserved \`'kick/'\` namespace.
375
+ */
376
+ export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
377
+ `}function z(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
378
+ * In-Memory ${t} Repository
379
+ *
380
+ * Implements the repository interface using a Map.
381
+ * Useful for prototyping and testing. Replace with a database implementation
382
+ * (Drizzle, Prisma, etc.) for production use.
383
+ *
384
+ * @Repository() registers this class in the DI container as a singleton.
385
+ */
386
+ import { randomUUID } from 'node:crypto'
387
+ import { Repository, HttpException } from '@forinda/kickjs'
388
+ import type { ParsedQuery } from '@forinda/kickjs'
389
+ import type { I${t}Repository } from '${r}/${n}.repository'
390
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
391
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
392
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
393
+
394
+ @Repository()
395
+ export class InMemory${t}Repository implements I${t}Repository {
396
+ private store = new Map<string, ${t}ResponseDTO>()
397
+
398
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
399
+ return this.store.get(id) ?? null
400
+ }
401
+
402
+ async findAll(): Promise<${t}ResponseDTO[]> {
403
+ return Array.from(this.store.values())
404
+ }
405
+
406
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
407
+ const all = Array.from(this.store.values())
408
+ const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
409
+ return { data, total: all.length }
410
+ }
411
+
412
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
413
+ const now = new Date().toISOString()
414
+ const entity: ${t}ResponseDTO = {
415
+ id: randomUUID(),
416
+ name: dto.name,
417
+ createdAt: now,
418
+ updatedAt: now,
419
+ }
420
+ this.store.set(entity.id, entity)
421
+ return entity
422
+ }
423
+
424
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
425
+ const existing = this.store.get(id)
426
+ if (!existing) throw HttpException.notFound('${t} not found')
427
+ const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
428
+ this.store.set(id, updated)
429
+ return updated
430
+ }
431
+
432
+ async delete(id: string): Promise<void> {
433
+ if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
434
+ this.store.delete(id)
435
+ }
436
+ }
437
+ `}function B(e){let{pascal:t,kebab:n,repoType:r=``,repoPrefix:i=`../../domain/repositories`,dtoPrefix:a=`../../application/dtos`}=e,o=r.charAt(0).toUpperCase()+r.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
438
+ * ${o} ${t} Repository
439
+ *
440
+ * Stub implementation for a custom '${r}' repository.
441
+ * Implements the repository interface using an in-memory Map as a placeholder.
442
+ *
443
+ * TODO: Replace the in-memory Map with your ${r} data-access logic.
444
+ * See I${t}Repository for the interface contract.
445
+ *
446
+ * @Repository() registers this class in the DI container as a singleton.
447
+ */
448
+ import { randomUUID } from 'node:crypto'
449
+ import { Repository, HttpException } from '@forinda/kickjs'
450
+ import type { ParsedQuery } from '@forinda/kickjs'
451
+ import type { I${t}Repository } from '${i}/${n}.repository'
452
+ import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
453
+ import type { Create${t}DTO } from '${a}/create-${n}.dto'
454
+ import type { Update${t}DTO } from '${a}/update-${n}.dto'
455
+
456
+ @Repository()
457
+ export class ${o}${t}Repository implements I${t}Repository {
458
+ // TODO: Replace with your ${r} client/connection
459
+ private store = new Map<string, ${t}ResponseDTO>()
460
+
461
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
462
+ // TODO: Implement with ${r}
463
+ return this.store.get(id) ?? null
464
+ }
465
+
466
+ async findAll(): Promise<${t}ResponseDTO[]> {
467
+ // TODO: Implement with ${r}
468
+ return Array.from(this.store.values())
469
+ }
470
+
471
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
472
+ // TODO: Implement with ${r}
473
+ const all = Array.from(this.store.values())
474
+ const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
475
+ return { data, total: all.length }
476
+ }
477
+
478
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
479
+ // TODO: Implement with ${r}
480
+ const now = new Date().toISOString()
481
+ const entity: ${t}ResponseDTO = {
482
+ id: randomUUID(),
483
+ name: dto.name,
484
+ createdAt: now,
485
+ updatedAt: now,
486
+ }
487
+ this.store.set(entity.id, entity)
488
+ return entity
489
+ }
490
+
491
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
492
+ // TODO: Implement with ${r}
493
+ const existing = this.store.get(id)
494
+ if (!existing) throw HttpException.notFound('${t} not found')
495
+ const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
496
+ this.store.set(id, updated)
497
+ return updated
498
+ }
499
+
500
+ async delete(id: string): Promise<void> {
501
+ // TODO: Implement with ${r}
502
+ if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
503
+ this.store.delete(id)
504
+ }
505
+ }
506
+ `}function xe(e){let{pascal:t,kebab:n}=e;return`/**
507
+ * ${t} Domain Service
508
+ *
509
+ * Domain layer — contains business rules that don't belong to a single entity.
510
+ * Use this for cross-entity logic, validation rules, and domain invariants.
511
+ * Keep it free of HTTP/framework concerns.
512
+ */
513
+ import { Service, Inject, HttpException } from '@forinda/kickjs'
514
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../repositories/${n}.repository'
515
+
516
+ @Service()
517
+ export class ${t}DomainService {
518
+ constructor(
519
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
520
+ ) {}
521
+
522
+ async ensureExists(id: string): Promise<void> {
523
+ const entity = await this.repo.findById(id)
524
+ if (!entity) {
525
+ throw HttpException.notFound('${t} not found')
526
+ }
527
+ }
528
+ }
529
+ `}function Se(e){let{pascal:t,kebab:n}=e;return`/**
530
+ * ${t} Entity
531
+ *
532
+ * Domain layer — the core business object.
533
+ * Uses a private constructor with static factory methods (create, reconstitute)
534
+ * to enforce invariants. Properties are accessed via getters to maintain encapsulation.
535
+ *
536
+ * Patterns used:
537
+ * - Private constructor: prevents direct instantiation
538
+ * - create(): factory for new entities (generates ID, sets timestamps)
539
+ * - reconstitute(): factory for rebuilding from persistence (no side effects)
540
+ * - changeName(): mutation method that enforces business rules
541
+ */
542
+ import { ${t}Id } from '../value-objects/${n}-id.vo'
543
+
544
+ interface ${t}Props {
545
+ id: ${t}Id
546
+ name: string
547
+ createdAt: Date
548
+ updatedAt: Date
549
+ }
550
+
551
+ export class ${t} {
552
+ private constructor(private props: ${t}Props) {}
553
+
554
+ static create(params: { name: string }): ${t} {
555
+ const now = new Date()
556
+ return new ${t}({
557
+ id: ${t}Id.create(),
558
+ name: params.name,
559
+ createdAt: now,
560
+ updatedAt: now,
561
+ })
562
+ }
563
+
564
+ static reconstitute(props: ${t}Props): ${t} {
565
+ return new ${t}(props)
566
+ }
567
+
568
+ get id(): ${t}Id {
569
+ return this.props.id
570
+ }
571
+ get name(): string {
572
+ return this.props.name
573
+ }
574
+ get createdAt(): Date {
575
+ return this.props.createdAt
576
+ }
577
+ get updatedAt(): Date {
578
+ return this.props.updatedAt
579
+ }
580
+
581
+ changeName(name: string): void {
582
+ if (!name || name.trim().length === 0) {
583
+ throw new Error('Name cannot be empty')
584
+ }
585
+ this.props.name = name.trim()
586
+ this.props.updatedAt = new Date()
587
+ }
588
+
589
+ toJSON() {
590
+ return {
591
+ id: this.props.id.toString(),
592
+ name: this.props.name,
593
+ createdAt: this.props.createdAt.toISOString(),
594
+ updatedAt: this.props.updatedAt.toISOString(),
595
+ }
596
+ }
597
+ }
598
+ `}function Ce(e){let{pascal:t}=e;return`/**
599
+ * ${t} ID Value Object
600
+ *
601
+ * Domain layer — wraps a primitive ID with type safety and validation.
602
+ * Value objects are immutable and compared by value, not reference.
603
+ *
604
+ * ${t}Id.create() — generate a new UUID
605
+ * ${t}Id.from(id) — wrap an existing ID string (validates non-empty)
606
+ * id.equals(other) — compare two IDs by value
607
+ */
608
+ import { randomUUID } from 'node:crypto'
609
+
610
+ export class ${t}Id {
611
+ private constructor(private readonly value: string) {}
612
+
613
+ static create(): ${t}Id {
614
+ return new ${t}Id(randomUUID())
615
+ }
616
+
617
+ static from(id: string): ${t}Id {
618
+ if (!id || id.trim().length === 0) {
619
+ throw new Error('${t}Id cannot be empty')
620
+ }
621
+ return new ${t}Id(id)
622
+ }
623
+
624
+ toString(): string {
625
+ return this.value
626
+ }
627
+
628
+ equals(other: ${t}Id): boolean {
629
+ return this.value === other.value
630
+ }
631
+ }
632
+ `}function V(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
633
+ import { Container } from '@forinda/kickjs'
634
+
635
+ describe('${t}Controller', () => {
636
+ beforeEach(() => {
637
+ Container.reset()
638
+ })
639
+
640
+ it('should be defined', () => {
641
+ expect(true).toBe(true)
642
+ })
643
+
644
+ describe('POST /${r}', () => {
645
+ it('should create a new ${n}', async () => {
646
+ // TODO: Set up test module, call create endpoint, assert 201
647
+ expect(true).toBe(true)
648
+ })
649
+ })
650
+
651
+ describe('GET /${r}', () => {
652
+ it('should return paginated ${r}', async () => {
653
+ // TODO: Set up test module, call list endpoint, assert { data, meta }
654
+ expect(true).toBe(true)
655
+ })
656
+ })
657
+
658
+ describe('GET /${r}/:id', () => {
659
+ it('should return a ${n} by id', async () => {
660
+ // TODO: Create a ${n}, then fetch by id, assert match
661
+ expect(true).toBe(true)
662
+ })
663
+
664
+ it('should return 404 for non-existent ${n}', async () => {
665
+ // TODO: Fetch non-existent id, assert 404
666
+ expect(true).toBe(true)
667
+ })
668
+ })
669
+
670
+ describe('PUT /${r}/:id', () => {
671
+ it('should update an existing ${n}', async () => {
672
+ // TODO: Create, update, assert changes
673
+ expect(true).toBe(true)
674
+ })
675
+ })
676
+
677
+ describe('DELETE /${r}/:id', () => {
678
+ it('should delete a ${n}', async () => {
679
+ // TODO: Create, delete, assert gone
680
+ expect(true).toBe(true)
681
+ })
682
+ })
683
+ })
684
+ `}function H(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../infrastructure/repositories/in-memory-${n}.repository`}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
685
+ import { InMemory${t}Repository } from '${i}'
686
+
687
+ describe('InMemory${t}Repository', () => {
688
+ let repo: InMemory${t}Repository
689
+
690
+ beforeEach(() => {
691
+ repo = new InMemory${t}Repository()
692
+ })
693
+
694
+ it('should create and retrieve a ${n}', async () => {
695
+ const created = await repo.create({ name: 'Test ${t}' })
696
+ expect(created).toBeDefined()
697
+ expect(created.name).toBe('Test ${t}')
698
+ expect(created.id).toBeDefined()
699
+
700
+ const found = await repo.findById(created.id)
701
+ expect(found).toEqual(created)
702
+ })
703
+
704
+ it('should return null for non-existent id', async () => {
705
+ const found = await repo.findById('non-existent')
706
+ expect(found).toBeNull()
707
+ })
708
+
709
+ it('should list all ${r}', async () => {
710
+ await repo.create({ name: '${t} 1' })
711
+ await repo.create({ name: '${t} 2' })
712
+
713
+ const all = await repo.findAll()
714
+ expect(all).toHaveLength(2)
715
+ })
716
+
717
+ it('should return paginated results', async () => {
718
+ await repo.create({ name: '${t} 1' })
719
+ await repo.create({ name: '${t} 2' })
720
+ await repo.create({ name: '${t} 3' })
721
+
722
+ const result = await repo.findPaginated({
723
+ filters: [],
724
+ sort: [],
725
+ search: '',
726
+ pagination: { page: 1, limit: 2, offset: 0 },
727
+ })
728
+
729
+ expect(result.data).toHaveLength(2)
730
+ expect(result.total).toBe(3)
731
+ })
732
+
733
+ it('should update a ${n}', async () => {
734
+ const created = await repo.create({ name: 'Original' })
735
+ const updated = await repo.update(created.id, { name: 'Updated' })
736
+ expect(updated.name).toBe('Updated')
737
+ })
738
+
739
+ it('should delete a ${n}', async () => {
740
+ const created = await repo.create({ name: 'To Delete' })
741
+ await repo.delete(created.id)
742
+ const found = await repo.findById(created.id)
743
+ expect(found).toBeNull()
744
+ })
745
+ })
746
+ `}function we(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
747
+ import type { ParsedQuery } from '@forinda/kickjs'
748
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
749
+ import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
750
+ import type { Create${t}DTO } from './dtos/create-${n}.dto'
751
+ import type { Update${t}DTO } from './dtos/update-${n}.dto'
752
+
753
+ @Service()
754
+ export class ${t}Service {
755
+ constructor(
756
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
757
+ ) {}
758
+
759
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
760
+ return this.repo.findById(id)
761
+ }
762
+
763
+ async findAll(): Promise<${t}ResponseDTO[]> {
764
+ return this.repo.findAll()
765
+ }
766
+
767
+ async findPaginated(parsed: ParsedQuery) {
768
+ return this.repo.findPaginated(parsed)
769
+ }
770
+
771
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
772
+ return this.repo.create(dto)
773
+ }
774
+
775
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
776
+ return this.repo.update(id, dto)
777
+ }
778
+
779
+ async delete(id: string): Promise<void> {
780
+ await this.repo.delete(id)
781
+ }
782
+ }
783
+ `}function U(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
784
+
785
+ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
786
+ filterable: ['name'],
787
+ sortable: ['name', 'createdAt'],
788
+ searchable: ['name'],
789
+ }
790
+ `}function Te(e){let{pascal:t,kebab:n,plural:r=``,repo:i}=e,a={inmemory:`InMemory${t}Repository`,drizzle:`Drizzle${t}Repository`,prisma:`Prisma${t}Repository`},o={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},s=a[i]??a.inmemory,c=o[i]??o.inmemory;return`/**
791
+ * ${t} Module — CQRS Pattern
792
+ *
793
+ * Separates read (queries) and write (commands) operations.
794
+ * Events are emitted after state changes and can be handled via
795
+ * WebSocket broadcasts, queue jobs, or ETL pipelines.
796
+ *
797
+ * Structure:
798
+ * commands/ — Write operations (create, update, delete)
799
+ * queries/ — Read operations (get, list)
800
+ * events/ — Domain events + handlers (WS broadcast, queue dispatch)
801
+ * dtos/ — Request/response schemas
802
+ */
803
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
804
+ import { buildRoutes } from '@forinda/kickjs'
805
+ import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
806
+ import { ${s} } from './${c}.repository'
807
+ import { ${t}Controller } from './${n}.controller'
808
+
809
+ // Eagerly load decorated classes
810
+ import.meta.glob(
811
+ [
812
+ './commands/**/*.ts',
813
+ './queries/**/*.ts',
814
+ './events/**/*.ts',
815
+ '!./**/*.test.ts',
816
+ ],
817
+ { eager: true },
818
+ )
819
+
820
+ export class ${t}Module implements AppModule {
821
+ register(container: Container): void {
822
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
823
+ container.resolve(${s}),
824
+ )
825
+ }
826
+
827
+ routes(): ModuleRoutes {
828
+ return {
829
+ path: '/${r}',
830
+ router: buildRoutes(${t}Controller),
831
+ controller: ${t}Controller,
832
+ }
833
+ }
834
+ }
835
+ `}function Ee(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'
836
+ import { ApiTags } from '@forinda/kickjs-swagger'
837
+ import { Create${t}Command } from './commands/create-${n}.command'
838
+ import { Update${t}Command } from './commands/update-${n}.command'
839
+ import { Delete${t}Command } from './commands/delete-${n}.command'
840
+ import { Get${t}Query } from './queries/get-${n}.query'
841
+ import { List${i}Query } from './queries/list-${r}.query'
842
+ import { create${t}Schema } from './dtos/create-${n}.dto'
843
+ import { update${t}Schema } from './dtos/update-${n}.dto'
844
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
845
+
846
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
847
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
848
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
849
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
850
+
851
+ @Controller()
852
+ export class ${t}Controller {
853
+ @Autowired() private readonly create${t}Command!: Create${t}Command
854
+ @Autowired() private readonly update${t}Command!: Update${t}Command
855
+ @Autowired() private readonly delete${t}Command!: Delete${t}Command
856
+ @Autowired() private readonly get${t}Query!: Get${t}Query
857
+ @Autowired() private readonly list${i}Query!: List${i}Query
858
+
859
+ @Get('/')
860
+ @ApiTags('${t}')
861
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
862
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
863
+ return ctx.paginate(
864
+ (parsed) => this.list${i}Query.execute(parsed),
865
+ ${t.toUpperCase()}_QUERY_CONFIG,
866
+ )
867
+ }
868
+
869
+ @Get('/:id')
870
+ @ApiTags('${t}')
871
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
872
+ const result = await this.get${t}Query.execute(ctx.params.id)
873
+ if (!result) return ctx.notFound('${t} not found')
874
+ ctx.json(result)
875
+ }
876
+
877
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
878
+ @ApiTags('${t}')
879
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
880
+ const result = await this.create${t}Command.execute(ctx.body)
881
+ ctx.created(result)
882
+ }
883
+
884
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
885
+ @ApiTags('${t}')
886
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
887
+ const result = await this.update${t}Command.execute(ctx.params.id, ctx.body)
888
+ ctx.json(result)
889
+ }
890
+
891
+ @Delete('/:id')
892
+ @ApiTags('${t}')
893
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
894
+ await this.delete${t}Command.execute(ctx.params.id)
895
+ ctx.noContent()
896
+ }
897
+ }
898
+ `}function De(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
899
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
900
+ import type { Create${t}DTO } from '../dtos/create-${n}.dto'
901
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
902
+ import { ${t}Events } from '../events/${n}.events'
903
+
904
+ @Service()
905
+ export class Create${t}Command {
906
+ constructor(
907
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
908
+ @Inject(${t}Events) private readonly events: ${t}Events,
909
+ ) {}
910
+
911
+ async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
912
+ const result = await this.repo.create(dto)
913
+ this.events.emit('${n}.created', result)
914
+ return result
915
+ }
916
+ }
917
+ `},{file:`update-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
918
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
919
+ import type { Update${t}DTO } from '../dtos/update-${n}.dto'
920
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
921
+ import { ${t}Events } from '../events/${n}.events'
922
+
923
+ @Service()
924
+ export class Update${t}Command {
925
+ constructor(
926
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
927
+ @Inject(${t}Events) private readonly events: ${t}Events,
928
+ ) {}
929
+
930
+ async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
931
+ const result = await this.repo.update(id, dto)
932
+ this.events.emit('${n}.updated', result)
933
+ return result
934
+ }
935
+ }
936
+ `},{file:`delete-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
937
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
938
+ import { ${t}Events } from '../events/${n}.events'
939
+
940
+ @Service()
941
+ export class Delete${t}Command {
942
+ constructor(
943
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
944
+ @Inject(${t}Events) private readonly events: ${t}Events,
945
+ ) {}
946
+
947
+ async execute(id: string): Promise<void> {
948
+ await this.repo.delete(id)
949
+ this.events.emit('${n}.deleted', { id })
950
+ }
951
+ }
952
+ `}]}function Oe(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
953
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
954
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
955
+
956
+ @Service()
957
+ export class Get${t}Query {
958
+ constructor(
959
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
960
+ ) {}
961
+
962
+ async execute(id: string): Promise<${t}ResponseDTO | null> {
963
+ return this.repo.findById(id)
964
+ }
965
+ }
966
+ `},{file:`list-${r}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
967
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
968
+ import type { ParsedQuery } from '@forinda/kickjs'
969
+
970
+ @Service()
971
+ export class List${i}Query {
972
+ constructor(
973
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
974
+ ) {}
975
+
976
+ async execute(parsed: ParsedQuery) {
977
+ return this.repo.findPaginated(parsed)
978
+ }
979
+ }
980
+ `}]}function ke(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
981
+ import { EventEmitter } from 'node:events'
982
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
983
+
984
+ /**
985
+ * ${t} domain event types.
986
+ *
987
+ * These events are emitted by commands after state changes.
988
+ * Subscribe to them in event handlers for side effects:
989
+ * - WebSocket broadcasts (real-time UI updates)
990
+ * - Queue jobs (async processing, ETL pipelines)
991
+ * - Audit logging
992
+ * - Cache invalidation
993
+ */
994
+ export interface ${t}EventMap {
995
+ '${n}.created': ${t}ResponseDTO
996
+ '${n}.updated': ${t}ResponseDTO
997
+ '${n}.deleted': { id: string }
998
+ }
999
+
1000
+ @Service()
1001
+ export class ${t}Events {
1002
+ private emitter = new EventEmitter()
1003
+
1004
+ emit<K extends keyof ${t}EventMap>(event: K, data: ${t}EventMap[K]): void {
1005
+ this.emitter.emit(event, data)
1006
+ }
1007
+
1008
+ on<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
1009
+ this.emitter.on(event, handler)
1010
+ }
1011
+
1012
+ off<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
1013
+ this.emitter.off(event, handler)
1014
+ }
1015
+ }
1016
+ `},{file:`on-${n}-change.handler.ts`,content:`import { Service, Autowired } from '@forinda/kickjs'
1017
+ import { ${t}Events } from './${n}.events'
1018
+
1019
+ /**
1020
+ * ${t} Change Event Handler
1021
+ *
1022
+ * Reacts to domain events emitted by commands.
1023
+ * Wire up side effects here:
1024
+ *
1025
+ * 1. WebSocket broadcast — notify connected clients in real-time
1026
+ * import { WsGateway } from '@forinda/kickjs-ws'
1027
+ * this.ws.broadcast('${n}-channel', { event, data })
1028
+ *
1029
+ * 2. Queue dispatch — offload heavy processing to background workers
1030
+ * import { QueueService } from '@forinda/kickjs-queue'
1031
+ * this.queue.add('${n}-etl', { action: event, payload: data })
1032
+ *
1033
+ * 3. ETL pipeline — transform and load data to external systems
1034
+ * await this.etlPipeline.process(data)
1035
+ */
1036
+ @Service()
1037
+ export class On${t}ChangeHandler {
1038
+ @Autowired() private events!: ${t}Events
1039
+
1040
+ // Uncomment to inject WebSocket and Queue services:
1041
+ // @Autowired() private ws!: WsGateway
1042
+ // @Autowired() private queue!: QueueService
1043
+
1044
+ onInit(): void {
1045
+ this.events.on('${n}.created', (data) => {
1046
+ console.log('[${t}] Created:', data.id)
1047
+ // TODO: Broadcast via WebSocket
1048
+ // this.ws.broadcast('${n}-channel', { event: '${n}.created', data })
1049
+ // TODO: Dispatch to queue for async processing / ETL
1050
+ // this.queue.add('${n}-etl', { action: 'create', payload: data })
1051
+ })
1052
+
1053
+ this.events.on('${n}.updated', (data) => {
1054
+ console.log('[${t}] Updated:', data.id)
1055
+ // TODO: Broadcast via WebSocket
1056
+ // this.ws.broadcast('${n}-channel', { event: '${n}.updated', data })
1057
+ })
1058
+
1059
+ this.events.on('${n}.deleted', (data) => {
1060
+ console.log('[${t}] Deleted:', data.id)
1061
+ // TODO: Broadcast via WebSocket
1062
+ // this.ws.broadcast('${n}-channel', { event: '${n}.deleted', data })
1063
+ })
1064
+ }
1065
+ }
1066
+ `}]}function W(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
1067
+ * Drizzle ${t} Repository
1068
+ *
1069
+ * Implements the repository interface using Drizzle ORM.
1070
+ * Uses buildFromColumns() with Column objects for type-safe query building.
1071
+ *
1072
+ * TODO: Update the schema import to match your Drizzle schema file.
1073
+ * TODO: Replace DRIZZLE_DB injection token with your actual database token.
1074
+ *
1075
+ * @Repository() registers this class in the DI container as a singleton.
1076
+ */
1077
+ import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
1078
+ import { Repository, HttpException, Inject } from '@forinda/kickjs'
1079
+ import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
1080
+ import type { ParsedQuery } from '@forinda/kickjs'
1081
+ import type { I${t}Repository } from '${r}/${n}.repository'
1082
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
1083
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
1084
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
1085
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from '../../constants'
1086
+
1087
+ // TODO: Import your Drizzle schema table — e.g.:
1088
+ // import { ${n}s } from '@/db/schema'
1089
+
1090
+ const queryAdapter = new DrizzleQueryAdapter({
1091
+ eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
1092
+ })
1093
+
1094
+ @Repository()
1095
+ export class Drizzle${t}Repository implements I${t}Repository {
1096
+ constructor(@Inject(DRIZZLE_DB) private db: any) {}
1097
+
1098
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
1099
+ // TODO: Implement with Drizzle
1100
+ // const row = this.db.select().from(${n}s).where(eq(${n}s.id, id)).get()
1101
+ // return row ?? null
1102
+ throw new Error('Drizzle ${t} repository not yet implemented — update schema imports and queries')
1103
+ }
1104
+
1105
+ async findAll(): Promise<${t}ResponseDTO[]> {
1106
+ // TODO: Implement with Drizzle
1107
+ // return this.db.select().from(${n}s).all()
1108
+ throw new Error('Drizzle ${t} repository not yet implemented')
1109
+ }
1110
+
1111
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1112
+ // TODO: Use buildFromColumns() with your query config for type-safe filtering
1113
+ // const query = queryAdapter.buildFromColumns(parsed, ${t.toUpperCase()}_QUERY_CONFIG)
1114
+ //
1115
+ // const data = this.db
1116
+ // .select().from(${n}s).$dynamic()
1117
+ // .where(query.where).orderBy(...query.orderBy)
1118
+ // .limit(query.limit).offset(query.offset).all()
1119
+ //
1120
+ // const totalResult = this.db
1121
+ // .select({ count: count() }).from(${n}s)
1122
+ // .$dynamic().where(query.where).get()
1123
+ //
1124
+ // return { data, total: totalResult?.count ?? 0 }
1125
+ throw new Error('Drizzle ${t} repository not yet implemented')
1126
+ }
1127
+
1128
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1129
+ // TODO: Implement with Drizzle
1130
+ // return this.db.insert(${n}s).values(dto).returning().get()
1131
+ throw new Error('Drizzle ${t} repository not yet implemented')
1132
+ }
1133
+
1134
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1135
+ // TODO: Implement with Drizzle
1136
+ // const row = this.db.update(${n}s).set(dto).where(eq(${n}s.id, id)).returning().get()
1137
+ // if (!row) throw HttpException.notFound('${t} not found')
1138
+ // return row
1139
+ throw new Error('Drizzle ${t} repository not yet implemented')
1140
+ }
1141
+
1142
+ async delete(id: string): Promise<void> {
1143
+ // TODO: Implement with Drizzle
1144
+ // this.db.delete(${n}s).where(eq(${n}s.id, id)).run()
1145
+ throw new Error('Drizzle ${t} repository not yet implemented')
1146
+ }
1147
+ }
1148
+ `}function Ae(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
1149
+ // TODO: Import your schema table and reference actual columns for type safety
1150
+ // import { ${n}s } from '@/db/schema'
1151
+
1152
+ export const ${t.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
1153
+ columns: {
1154
+ // Replace with actual Drizzle Column references for type-safe filtering:
1155
+ // name: ${n}s.name,
1156
+ // status: ${n}s.status,
1157
+ },
1158
+ sortable: {
1159
+ // name: ${n}s.name,
1160
+ // createdAt: ${n}s.createdAt,
1161
+ },
1162
+ searchColumns: [
1163
+ // ${n}s.name,
1164
+ ],
1165
+ }
1166
+ `}function G(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e,a=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
1167
+ * Prisma ${t} Repository
1168
+ *
1169
+ * Implements the repository interface using Prisma Client.
1170
+ * Requires a PrismaClient instance injected via the DI container.
1171
+ *
1172
+ * Ensure your Prisma schema has a '${t}' model defined.
1173
+ *
1174
+ * For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
1175
+ * @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
1176
+ *
1177
+ * @Repository() registers this class in the DI container as a singleton.
1178
+ */
1179
+ import { Repository, HttpException, Inject } from '@forinda/kickjs'
1180
+ import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
1181
+ import type { ParsedQuery } from '@forinda/kickjs'
1182
+ import type { I${t}Repository } from '${r}/${n}.repository'
1183
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
1184
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
1185
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
1186
+
1187
+ @Repository()
1188
+ export class Prisma${t}Repository implements I${t}Repository {
1189
+ @Inject(PRISMA_CLIENT) private prisma!: { ${a}: PrismaModelDelegate }
1190
+
1191
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
1192
+ return this.prisma.${a}.findUnique({ where: { id } }) as Promise<${t}ResponseDTO | null>
1193
+ }
1194
+
1195
+ async findAll(): Promise<${t}ResponseDTO[]> {
1196
+ return this.prisma.${a}.findMany() as Promise<${t}ResponseDTO[]>
1197
+ }
1198
+
1199
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1200
+ const [data, total] = await Promise.all([
1201
+ this.prisma.${a}.findMany({
1202
+ skip: parsed.pagination.offset,
1203
+ take: parsed.pagination.limit,
1204
+ }) as Promise<${t}ResponseDTO[]>,
1205
+ this.prisma.${a}.count(),
1206
+ ])
1207
+ return { data, total }
1208
+ }
1209
+
1210
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1211
+ return this.prisma.${a}.create({ data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
1212
+ }
1213
+
1214
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1215
+ const existing = await this.prisma.${a}.findUnique({ where: { id } })
1216
+ if (!existing) throw HttpException.notFound('${t} not found')
1217
+ return this.prisma.${a}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
1218
+ }
1219
+
1220
+ async delete(id: string): Promise<void> {
1221
+ await this.prisma.${a}.deleteMany({ where: { id } })
1222
+ }
1223
+ }
1224
+ `}function je(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'
1225
+ // Side-effect import — registers the extended env schema with kickjs
1226
+ // **before** any controller / service / @Value gets resolved. Without
1227
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
1228
+ // cached schema would still be the base shape. See guide/configuration.
1229
+ import './config'
1230
+ import { bootstrap } from '@forinda/kickjs'
1231
+ // import { WsAdapter } from '@forinda/kickjs-ws'
1232
+ // import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
1233
+ ${t.length?t.join(`
1234
+ `)+`
1235
+ `:``}import { modules } from './modules'
1236
+
1237
+ // Export the app for the Vite plugin (dev mode)
1238
+ export const app = await bootstrap({
1239
+ modules,${t.length?`\n adapters: [\n${i.join(`
1240
+ `)}\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],`:`
1241
+ adapters: [
1242
+ // Uncomment for WebSocket support:
1243
+ // WsAdapter(),
1244
+ // Uncomment when Redis is available:
1245
+ // QueueAdapter({
1246
+ // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
1247
+ // }),
1248
+ ],`}
1249
+ })
1250
+ `}case`minimal`:{let t=[],i=[];return r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({ info: { title: '${e}', version: '${n}' } }),`)),r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),`import 'reflect-metadata'
1251
+ // Side-effect import — registers the extended env schema with kickjs
1252
+ // **before** any controller / service / @Value gets resolved. Without
1253
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
1254
+ // cached schema would still be the base shape. See guide/configuration.
1255
+ import './config'
1256
+ import { bootstrap } from '@forinda/kickjs'
1257
+ ${t.length?t.join(`
1258
+ `)+`
1259
+ `:``}import { modules } from './modules'
1260
+
1261
+ // Export the app for the Vite plugin (dev mode)
1262
+ export const app = await bootstrap({ modules${i.length?`,\n adapters: [\n${i.join(`
1263
+ `)}\n ]`:``} })
1264
+ `}default:{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'
1265
+ // Side-effect import — registers the extended env schema with kickjs
1266
+ // **before** any controller / service / @Value gets resolved. Without
1267
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
1268
+ // cached schema would still be the base shape. See guide/configuration.
1269
+ import './config'
1270
+ import express from 'express'
1271
+ import {
1272
+ bootstrap,
1273
+ requestId,
1274
+ requestLogger,
1275
+ helmet,
1276
+ cors,
1277
+ } from '@forinda/kickjs'
1278
+ ${t.length?t.join(`
1279
+ `)+`
1280
+ `:``}import { modules } from './modules'
1281
+
1282
+ // Export the app for the Vite plugin (dev mode)
1283
+ export const app = await bootstrap({
1284
+ modules,${i.length?`\n adapters: [\n${i.join(`
1285
+ `)}\n ],`:``}
1286
+ middleware: [
1287
+ helmet(),
1288
+ cors({ origin: '*' }),
1289
+ requestId(),
1290
+ requestLogger(),
1291
+ express.json(),
1292
+ ],
1293
+ })
1294
+ `}}}function Me(){return`import type { AppModuleClass } from '@forinda/kickjs'
1295
+ import { HelloModule } from './hello/hello.module'
1296
+
1297
+ // Remove HelloModule and run: kick g module <name>
1298
+ export const modules: AppModuleClass[] = [HelloModule]
1299
+ `}function Ne(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
1300
+ import { z } from 'zod'
1301
+
1302
+ /**
1303
+ * Project environment schema.
1304
+ *
1305
+ * Extend the base schema with your application's variables. The
1306
+ * default export is the contract \`kick typegen\` reads to populate
1307
+ * the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
1308
+ * autocomplete and \`process.env.FOO\` typed.
1309
+ *
1310
+ * @example
1311
+ * DATABASE_URL: z.string().url(),
1312
+ * JWT_SECRET: z.string().min(32),
1313
+ * REDIS_URL: z.string().url().optional(),
1314
+ */
1315
+ const envSchema = defineEnv((base) =>
1316
+ base.extend({
1317
+ // DATABASE_URL: z.string().url(),
1318
+ }),
1319
+ )
1320
+
1321
+ /**
1322
+ * IMPORTANT — side effect: register the schema with kickjs's env cache
1323
+ * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
1324
+ * this cache, and they will fall back to the base schema (or undefined)
1325
+ * if no extended schema has been registered before they're resolved.
1326
+ *
1327
+ * As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
1328
+ * top — before \`bootstrap()\` runs — every controller and service in the
1329
+ * app sees the typed extended values.
1330
+ */
1331
+ export const env = loadEnv(envSchema)
1332
+
1333
+ export default envSchema
1334
+ `}function Pe(){return`import { Service } from '@forinda/kickjs'
1335
+
1336
+ @Service()
1337
+ export class HelloService {
1338
+ greet(name: string) {
1339
+ return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
1340
+ }
1341
+
1342
+ healthCheck() {
1343
+ return { status: 'ok', uptime: process.uptime() }
1344
+ }
1345
+ }
1346
+ `}function Fe(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
1347
+ import { HelloService } from './hello.service'
1348
+
1349
+ // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
1350
+ // \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
1351
+ // scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
1352
+ // See https://forinda.github.io/kick-js/guide/typegen.
1353
+
1354
+ @Controller()
1355
+ export class HelloController {
1356
+ @Autowired() private readonly helloService!: HelloService
1357
+
1358
+ @Get('/')
1359
+ index(ctx: Ctx<KickRoutes.HelloController['index']>) {
1360
+ ctx.json(this.helloService.greet('World'))
1361
+ }
1362
+
1363
+ @Get('/health')
1364
+ health(ctx: Ctx<KickRoutes.HelloController['health']>) {
1365
+ ctx.json(this.helloService.healthCheck())
1366
+ }
1367
+ }
1368
+ `}function Ie(){return`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
1369
+ import { HelloController } from './hello.controller'
1370
+
1371
+ export class HelloModule implements AppModule {
1372
+ // \`register(container)\` is optional — only implement it when you need
1373
+ // to bind a token to a concrete implementation, e.g.
1374
+ // register(container) {
1375
+ // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
1376
+ // }
1377
+ // The HelloService uses @Service() so the decorator handles registration.
1378
+
1379
+ routes(): ModuleRoutes {
1380
+ return {
1381
+ path: '/hello',
1382
+ router: buildRoutes(HelloController),
1383
+ controller: HelloController,
1384
+ }
1385
+ }
1386
+ }
1387
+ `}function Le(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
1388
+
1389
+ export default defineConfig({
1390
+ pattern: '${e}',
1391
+ // Pinned so \`kick add\` and other dep-installing commands always use the
1392
+ // project's intended package manager, regardless of which lockfile exists.
1393
+ packageManager: '${n}',
1394
+ modules: {
1395
+ dir: 'src/modules',
1396
+ repo: ${[`drizzle`,`inmemory`,`prisma`].includes(t)?`'${t}'`:`{ name: '${t}' }`},
1397
+ pluralize: true,
1398
+ },
1399
+
1400
+ // \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
1401
+ // resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
1402
+ // Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
1403
+ typegen: {
1404
+ schemaValidator: 'zod',
1405
+ },
1406
+
1407
+ commands: [
1408
+ {
1409
+ name: 'test',
1410
+ description: 'Run tests with Vitest',
1411
+ steps: 'npx vitest run',
1412
+ },
1413
+ {
1414
+ name: 'format',
1415
+ description: 'Format code with Prettier',
1416
+ steps: 'npx prettier --write src/',
1417
+ },
1418
+ {
1419
+ name: 'format:check',
1420
+ description: 'Check formatting without writing',
1421
+ steps: 'npx prettier --check src/',
1422
+ },
1423
+ {
1424
+ name: 'ci:check',
1425
+ description: 'Run typecheck + format check',
1426
+ steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
1427
+ aliases: ['verify'],
1428
+ },
1429
+ ],
1430
+ })
1431
+ `}async function Re(e){let{pascal:t,kebab:n,plural:r,write:i}=e;await i(`${n}.module.ts`,ge({pascal:t,kebab:n,plural:r})),await i(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
1432
+
1433
+ // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
1434
+ // \`kick typegen\` (auto-run on \`kick dev\`).
1435
+
1436
+ @Controller()
1437
+ export class ${t}Controller {
1438
+ @Get('/')
1439
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1440
+ ctx.json({ message: '${t} list' })
1441
+ }
1442
+ }
1443
+ `)}async function ze(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,write:l}=e;await l(`${n}.module.ts`,he({pascal:t,kebab:n,plural:r,repo:a})),await l(`${n}.constants.ts`,U({pascal:t,kebab:n})),await l(`${n}.controller.ts`,ve({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`${n}.service.ts`,we({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,F({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,I({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,L({pascal:t,kebab:n})),await l(`${n}.repository.ts`,R({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let u={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},d={inmemory:()=>z({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>W({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},f=u[a]??`${k(a)}-${n}`,p=d[a]??(()=>B({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await l(`${f}.repository.ts`,p()),o||(a!==`inmemory`&&await l(`in-memory-${n}.repository.ts`,z({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,V({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,H({pascal:t,kebab:n,plural:r,repoPrefix:`../${u.inmemory??`in-memory-${n}`}.repository`})))}async function Be(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,write:l}=e;await l(`${n}.module.ts`,Te({pascal:t,kebab:n,plural:r,repo:a})),await l(`${n}.constants.ts`,U({pascal:t,kebab:n})),await l(`${n}.controller.ts`,Ee({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`dtos/create-${n}.dto.ts`,F({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,I({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,L({pascal:t,kebab:n}));let u=De({pascal:t,kebab:n});for(let e of u)await l(`commands/${e.file}`,e.content);let d=Oe({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of d)await l(`queries/${e.file}`,e.content);let f=ke({pascal:t,kebab:n});for(let e of f)await l(`events/${e.file}`,e.content);await l(`${n}.repository.ts`,R({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>z({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>W({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},h=p[a]??`${k(a)}-${n}`,g=m[a]??(()=>B({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await l(`${h}.repository.ts`,g()),o||(a!==`inmemory`&&await l(`in-memory-${n}.repository.ts`,z({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,V({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,H({pascal:t,kebab:n,plural:r,repoPrefix:`../${p.inmemory??`in-memory-${n}`}.repository`})))}async function Ve(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noEntity:o,noTests:s,prismaClientPath:c,tokenScope:l,write:u}=e;await u(`${n}.module.ts`,me({pascal:t,kebab:n,plural:r,repo:a})),await u(`constants.ts`,a===`drizzle`?Ae({pascal:t,kebab:n}):ye({pascal:t,kebab:n})),await u(`presentation/${n}.controller.ts`,_e({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`application/dtos/create-${n}.dto.ts`,F({pascal:t,kebab:n})),await u(`application/dtos/update-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`application/dtos/${n}-response.dto.ts`,L({pascal:t,kebab:n}));let d=be({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of d)await u(`application/use-cases/${e.file}`,e.content);await u(`domain/repositories/${n}.repository.ts`,R({pascal:t,kebab:n,tokenScope:l})),await u(`domain/services/${n}-domain.service.ts`,xe({pascal:t,kebab:n}));let f={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},p={inmemory:()=>z({pascal:t,kebab:n}),drizzle:()=>W({pascal:t,kebab:n}),prisma:()=>G({pascal:t,kebab:n,prismaClientPath:c})},m=f[a]??`${k(a)}-${n}`,h=p[a]??(()=>B({pascal:t,kebab:n,repoType:a}));await u(`infrastructure/repositories/${m}.repository.ts`,h()),o||(await u(`domain/entities/${n}.entity.ts`,Se({pascal:t,kebab:n})),await u(`domain/value-objects/${n}-id.vo.ts`,Ce({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await u(`infrastructure/repositories/in-memory-${n}.repository.ts`,z({pascal:t,kebab:n})),await u(`__tests__/${n}.controller.test.ts`,V({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,H({pascal:t,kebab:n,plural:r})))}function He(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Ue(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`,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 Re(y);break;case`rest`:await ze(y);break;case`cqrs`:await Be(y);break;default:await Ve(y);break}return c||await We(n,p,m,d),_}async function We(e,t,n,i){let a=r(e,`index.ts`),o=await C(a),s=`./${n}/${i}.module`;if(!o){await b(a,`import type { AppModuleClass } from '@forinda/kickjs'
1444
+ import { ${t}Module } from '${s}'
1445
+
1446
+ export const modules: AppModuleClass[] = [${t}Module]
1447
+ `);return}let c=await l(a,`utf-8`),d=`import { ${t}Module } from '${s}'`;if(!c.includes(`${t}Module`)){let e=c.lastIndexOf(`import `);if(e!==-1){let t=c.indexOf(`
1448
+ `,e);c=c.slice(0,t+1)+d+`
1449
+ `+c.slice(t+1)}else c=d+`
1450
+ `+c;c=c.replace(/(=\s*\[)([\s\S]*?)(])/,(e,n,r,i)=>{let a=r.trim();if(!a)return`${n}${t}Module${i}`;let o=a.endsWith(`,`)?``:`,`;return`${n}${r.trimEnd()}${o} ${t}Module${i}`})}await u(a,c,`utf-8`)}async function Ge(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 {
1451
+ defineAdapter,
1452
+ type AdapterContext,
1453
+ type AdapterMiddleware,
1454
+ type ContributorRegistrations,
1455
+ type Constructor,
1456
+ } from '@forinda/kickjs'
1457
+
1458
+ /**
1459
+ * Configuration for the ${a} adapter.
1460
+ *
1461
+ * Adapters typically take a small config object so callers can tune
1462
+ * behaviour at bootstrap time. Keep the shape narrow — anything
1463
+ * derived from the environment should be read inside the build
1464
+ * function via getEnv(), not forced onto the caller.
1465
+ */
1466
+ export interface ${a}AdapterConfig {
1467
+ // Add your adapter configuration here, e.g.:
1468
+ // enabled?: boolean
1469
+ // apiKey?: string
1470
+ }
1471
+
1472
+ /**
1473
+ * ${a} adapter — built via \`defineAdapter()\` so callers get the
1474
+ * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
1475
+ *
1476
+ * Hooks into the Application lifecycle to add middleware, routes,
1477
+ * Context Contributors, or external service connections.
1478
+ *
1479
+ * Every lifecycle hook below is OPTIONAL. The scaffold emits all of
1480
+ * them so adopters can browse what's available and delete what they
1481
+ * don't need — \`build()\` returning \`{}\` is also valid for an adapter
1482
+ * that only contributes config defaults.
1483
+ *
1484
+ * @example
1485
+ * \`\`\`ts
1486
+ * import { bootstrap } from '@forinda/kickjs'
1487
+ * import { ${a}Adapter } from './adapters/${i}.adapter'
1488
+ *
1489
+ * bootstrap({
1490
+ * modules,
1491
+ * adapters: [${a}Adapter({ /* config overrides *\\/ })],
1492
+ * })
1493
+ * \`\`\`
1494
+ */
1495
+ export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
1496
+ name: '${a}Adapter',
1497
+ defaults: {
1498
+ // Default config values go here. The adopter's overrides shallow-merge
1499
+ // on top of these before \`build()\` runs.
1500
+ },
1501
+ build: (_config, { name: _name }) => {
1502
+ // Closures inside \`build()\` are how each adapter instance owns its
1503
+ // own state (database client, Map, timer handle, …). The same
1504
+ // \`_config\` is visible to every hook below.
1505
+
1506
+ return {
1507
+ /**
1508
+ * Express middleware entries the Application mounts at named phases.
1509
+ *
1510
+ * \`phase\` controls where each handler sits in the pipeline:
1511
+ * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
1512
+ *
1513
+ * \`path\` (optional) scopes the entry to a path prefix.
1514
+ *
1515
+ * Delete this hook entirely if you don't add middleware.
1516
+ */
1517
+ middleware(): AdapterMiddleware[] {
1518
+ return [
1519
+ // Example: add a custom header to all responses
1520
+ // {
1521
+ // phase: 'beforeGlobal',
1522
+ // handler: (_req, res, next) => {
1523
+ // res.setHeader('X-${a}', 'true')
1524
+ // next()
1525
+ // },
1526
+ // },
1527
+ // Example: scope a rate limiter to one path prefix
1528
+ // {
1529
+ // phase: 'beforeRoutes',
1530
+ // path: '/api/v1/auth',
1531
+ // handler: rateLimit({ max: 10 }),
1532
+ // },
1533
+ ]
1534
+ },
1535
+
1536
+ /**
1537
+ * Runs BEFORE global middleware. Mount routes that should bypass the
1538
+ * middleware stack — health checks, docs UI, static assets, OAuth
1539
+ * callbacks. Anything you want reachable even if a global middleware
1540
+ * later in the chain rejects requests.
1541
+ *
1542
+ * Delete this hook if you have no early routes.
1543
+ */
1544
+ beforeMount(_ctx: AdapterContext): void {
1545
+ // Example:
1546
+ // _ctx.app.get('/${i}/status', (_req, res) => res.json({ status: 'ok' }))
1547
+ },
1548
+
1549
+ /**
1550
+ * Fires once per controller class as the router mounts. Use this to
1551
+ * collect route metadata for OpenAPI specs, dependency graphs, route
1552
+ * inventories, devtools dashboards.
1553
+ *
1554
+ * Delete this hook unless your adapter introspects the route registry.
1555
+ */
1556
+ onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
1557
+ // Example (Swagger-style): collect routes for the spec.
1558
+ // openApiSpec.addController(_controllerClass, _mountPath)
1559
+ },
1560
+
1561
+ /**
1562
+ * Runs AFTER modules + routes are wired, BEFORE the server starts.
1563
+ * Right place for late-stage DI registrations or final config validation.
1564
+ *
1565
+ * Delete this hook if there's nothing to wire post-modules.
1566
+ */
1567
+ beforeStart(_ctx: AdapterContext): void {
1568
+ // Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
1569
+ },
1570
+
1571
+ /**
1572
+ * Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
1573
+ * available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
1574
+ * gRPC, GraphQL subscriptions), warm caches, log a banner.
1575
+ *
1576
+ * Delete this hook if you don't need the running server reference.
1577
+ */
1578
+ afterStart(_ctx: AdapterContext): void {
1579
+ // Example: const io = new Server(_ctx.server)
1580
+ },
1581
+
1582
+ /**
1583
+ * Returns Context Contributors to merge into every route's pipeline
1584
+ * at the \`'adapter'\` precedence level. Per-route handlers can
1585
+ * override the value at the method / class / module level.
1586
+ *
1587
+ * Delete this hook unless your adapter ships typed per-request values
1588
+ * (auth user, tenant, locale, feature flags, geo, etc).
1589
+ */
1590
+ contributors(): ContributorRegistrations {
1591
+ return [
1592
+ // Example:
1593
+ // import { defineHttpContextDecorator } from '@forinda/kickjs'
1594
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${i}: { id: string } } }
1595
+ // const Load${a} = defineHttpContextDecorator({
1596
+ // key: '${i}',
1597
+ // resolve: (ctx) => ({ id: ctx.req.headers['x-${i}-id'] as string }),
1598
+ // })
1599
+ // return [Load${a}.registration]
1600
+ ]
1601
+ },
1602
+
1603
+ /**
1604
+ * Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
1605
+ * resources the adapter owns: close connections, flush buffers,
1606
+ * cancel timers. The framework runs every adapter's \`shutdown\`
1607
+ * concurrently via \`Promise.allSettled\` — one failure won't block
1608
+ * sibling adapters.
1609
+ *
1610
+ * Delete this hook if your adapter holds no resources.
1611
+ */
1612
+ async shutdown(): Promise<void> {
1613
+ // Example: await this.pool.end()
1614
+ // Example: clearInterval(this.heartbeatTimer)
1615
+ },
1616
+ }
1617
+ },
1618
+ })
1619
+ `),o.push(s),o}const Ke={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},qe={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},Je={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function K(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`?Ke:c===`cqrs`?Je:qe,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 Ye(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=K({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'
1620
+
1621
+ export interface ${D(t)}Options {
1622
+ // Add configuration options here
1623
+ }
1624
+
1625
+ /**
1626
+ * ${D(t)} middleware.
1627
+ *
1628
+ * Usage in bootstrap:
1629
+ * middleware: [${c}()]
1630
+ *
1631
+ * Usage with adapter:
1632
+ * middleware() { return [{ handler: ${c}(), phase: 'afterGlobal' }] }
1633
+ *
1634
+ * Usage with @Middleware decorator:
1635
+ * @Middleware(${c}())
1636
+ */
1637
+ export function ${c}(options: ${D(t)}Options = {}) {
1638
+ return (req: Request, res: Response, next: NextFunction) => {
1639
+ // Implement your middleware logic here
1640
+ next()
1641
+ }
1642
+ }
1643
+ `),l.push(u),l}async function Xe(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=K({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'
1644
+ import type { RequestContext } from '@forinda/kickjs'
1645
+
1646
+ /**
1647
+ * ${l} guard.
1648
+ *
1649
+ * Guards protect routes by checking conditions before the handler runs.
1650
+ * Return early with an error response to block access.
1651
+ *
1652
+ * Usage:
1653
+ * @Middleware(${c}Guard)
1654
+ * @Get('/protected')
1655
+ * async handler(ctx: RequestContext) { ... }
1656
+ */
1657
+ export async function ${c}Guard(ctx: RequestContext, next: () => void): Promise<void> {
1658
+ // Example: check for an authorization header
1659
+ const header = ctx.headers.authorization
1660
+ if (!header?.startsWith('Bearer ')) {
1661
+ ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
1662
+ return
1663
+ }
1664
+
1665
+ const token = header.slice(7)
1666
+
1667
+ try {
1668
+ // Verify the token using a service from the DI container
1669
+ // const container = Container.getInstance()
1670
+ // const authService = container.resolve(AuthService)
1671
+ // const payload = authService.verifyToken(token)
1672
+ // ctx.set('auth', payload)
1673
+
1674
+ next()
1675
+ } catch {
1676
+ ctx.res.status(401).json({ message: 'Invalid or expired token' })
1677
+ }
1678
+ }
1679
+ `),u.push(d),u}async function Ze(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=K({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'
1680
+
1681
+ @Service()
1682
+ export class ${c}Service {
1683
+ // Inject dependencies via constructor
1684
+ // constructor(
1685
+ // @Inject(MY_REPO) private readonly repo: IMyRepository,
1686
+ // ) {}
1687
+ }
1688
+ `),l.push(u),l}async function Qe(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=K({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'
1689
+
1690
+ // \`Ctx<KickRoutes.${c}Controller['<method>']>\` is generated by
1691
+ // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
1692
+ // will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
1693
+ // See https://forinda.github.io/kick-js/guide/typegen for details.
1694
+
1695
+ @Controller()
1696
+ export class ${c}Controller {
1697
+ // @Autowired() private readonly myService!: MyService
1698
+
1699
+ @Get('/')
1700
+ async list(ctx: Ctx<KickRoutes.${c}Controller['list']>) {
1701
+ ctx.json({ message: '${c} list' })
1702
+ }
1703
+
1704
+ @Post('/')
1705
+ async create(ctx: Ctx<KickRoutes.${c}Controller['create']>) {
1706
+ ctx.created({ message: '${c} created', data: ctx.body })
1707
+ }
1708
+ }
1709
+ `),l.push(u),l}async function $e(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=K({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'
1710
+
1711
+ export const ${l}Schema = z.object({
1712
+ // Define your schema fields here
1713
+ name: z.string().min(1).max(200),
1714
+ })
1715
+
1716
+ export type ${c}DTO = z.infer<typeof ${l}Schema>
1717
+ `),u.push(d),u}const et={auth:`@forinda/kickjs-auth`,swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function tt(e,t,n,r=[]){let i={"@forinda/kickjs":n,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=et[e];t&&!i[t]&&(i[t]=n)}return JSON.stringify({name:e,version:n.replace(`^`,``),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-vite":n,"@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 nt(){return`import { defineConfig } from 'vite'
1718
+ import { resolve } from 'node:path'
1719
+ import swc from 'unplugin-swc'
1720
+ import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
1721
+
1722
+ export default defineConfig({
1723
+ oxc: false,
1724
+ plugins: [
1725
+ swc.vite(),
1726
+ kickjsVitePlugin({ entry: 'src/index.ts' }),
1727
+ // Watches .env files and triggers a full reload on change so the
1728
+ // dev server picks up env tweaks without a manual restart.
1729
+ envWatchPlugin(),
1730
+ ],
1731
+ resolve: {
1732
+ alias: {
1733
+ '@': resolve(__dirname, 'src'),
1734
+ },
1735
+ },
1736
+ ssr: {
1737
+ // Don't bundle pino — its worker-thread transport needs Node.js resolution
1738
+ // to find pino-pretty at runtime for colored log output
1739
+ external: ['pino', 'pino-pretty'],
1740
+ },
1741
+ build: {
1742
+ target: 'node20',
1743
+ ssr: true,
1744
+ outDir: 'dist',
1745
+ sourcemap: true,
1746
+ rollupOptions: {
1747
+ input: resolve(__dirname, 'src/index.ts'),
1748
+ output: { format: 'esm' },
1749
+ },
1750
+ },
1751
+ })
1752
+ `}function rt(){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 it(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function at(){return`# https://editorconfig.org
1753
+ root = true
1754
+
1755
+ [*]
1756
+ indent_style = space
1757
+ indent_size = 2
1758
+ end_of_line = lf
1759
+ charset = utf-8
1760
+ trim_trailing_whitespace = true
1761
+ insert_final_newline = true
1762
+
1763
+ [*.md]
1764
+ trim_trailing_whitespace = false
1765
+ `}function ot(){return`node_modules/
1766
+ dist/
1767
+ .env
1768
+ coverage/
1769
+ .DS_Store
1770
+ *.tsbuildinfo
1771
+ .kickjs/
1772
+ `}function st(){return`# Auto-detect text files and normalise line endings to LF
1773
+ * text=auto eol=lf
1774
+
1775
+ # Explicitly mark generated / binary files
1776
+ *.png binary
1777
+ *.jpg binary
1778
+ *.jpeg binary
1779
+ *.gif binary
1780
+ *.ico binary
1781
+ *.woff binary
1782
+ *.woff2 binary
1783
+ *.ttf binary
1784
+ *.eot binary
1785
+
1786
+ # Lock files — treat as generated
1787
+ pnpm-lock.yaml -diff linguist-generated
1788
+ yarn.lock -diff linguist-generated
1789
+ package-lock.json -diff linguist-generated
1790
+ `}function ct(){return`PORT=3000
1791
+ NODE_ENV=development
1792
+ `}function lt(){return`PORT=3000
1793
+ NODE_ENV=development
1794
+ `}function ut(){return`import { defineConfig } from 'vitest/config'
1795
+ import swc from 'unplugin-swc'
1796
+
1797
+ export default defineConfig({
1798
+ plugins: [swc.vite()],
1799
+ test: {
1800
+ globals: true,
1801
+ environment: 'node',
1802
+ include: ['src/**/*.test.ts'],
1803
+ },
1804
+ })
1805
+ `}function dt(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}
1806
+
1807
+ 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.
1808
+
1809
+ ## Getting Started
1810
+
1811
+ \`\`\`bash
1812
+ ${n} install
1813
+ kick dev
1814
+ \`\`\`
1815
+
1816
+ ## Scripts
1817
+
1818
+ | Command | Description |
1819
+ |---|---|
1820
+ | \`kick dev\` | Start dev server with Vite HMR |
1821
+ | \`kick build\` | Production build |
1822
+ | \`kick start\` | Run production build |
1823
+ | \`${n} run test\` | Run tests with Vitest |
1824
+ | \`kick g module <name>\` | Generate a DDD module |
1825
+ | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
1826
+ | \`kick add <package>\` | Add a KickJS package |
1827
+
1828
+ ## Project Structure
1829
+
1830
+ \`\`\`
1831
+ src/
1832
+ ├── index.ts # Application entry point
1833
+ ├── modules/ # Feature modules (controllers, services, repos)
1834
+ │ └── index.ts # Module registry
1835
+ └── ...
1836
+ \`\`\`
1837
+
1838
+ ## Packages
1839
+
1840
+ ${i.map(e=>`- \`${e}\``).join(`
1841
+ `)}
1842
+
1843
+ ## Adding Features
1844
+
1845
+ \`\`\`bash
1846
+ kick add auth # Authentication (JWT, API key, OAuth)
1847
+ kick add swagger # OpenAPI documentation
1848
+ kick add ws # WebSocket support
1849
+ kick add queue # Background job processing
1850
+ kick add --list # Show all available packages
1851
+ \`\`\`
1852
+
1853
+ For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
1854
+
1855
+ ## Environment Variables
1856
+
1857
+ Copy \`.env.example\` to \`.env\` and configure:
1858
+
1859
+ | Variable | Default | Description |
1860
+ |---|---|---|
1861
+ | \`PORT\` | \`3000\` | Server port |
1862
+ | \`NODE_ENV\` | \`development\` | Environment |
1863
+
1864
+ ## Learn More
1865
+
1866
+ - [KickJS Documentation](https://forinda.github.io/kick-js/)
1867
+ - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
1868
+ `}function q(e,t,n){return`# CLAUDE.md — ${e}
1869
+
1870
+ **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
1871
+ reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
1872
+ project conventions, structure, decorator patterns, env wiring, CLI
1873
+ generators, every gotcha.
1874
+
1875
+ **Then read \`./kickjs-skills.md\`.** That file is the task-oriented
1876
+ skill index — short, rigid recipes keyed to triggers ("add-module",
1877
+ "write-controller-test", "bootstrap-export", "deny-list", …). Use it
1878
+ as the playbook when executing common KickJS workflows.
1879
+
1880
+ This file is a thin Claude-specific layer on top of those two; when
1881
+ they disagree on anything substantive, treat \`AGENTS.md\` as
1882
+ authoritative and flag the discrepancy.
1883
+
1884
+ ## Why two files
1885
+
1886
+ \`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
1887
+ Claude Code automatically loads as project context on each
1888
+ conversation. Keeping CLAUDE.md slim avoids two files drifting; the
1889
+ redirect above ensures Claude pulls the canonical content without
1890
+ us copy-pasting.
1891
+
1892
+ ## Claude-specific notes
1893
+
1894
+ - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
1895
+ to refresh project memory if AGENTS.md changes substantially.
1896
+ - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
1897
+ - **Persistent memory** — Claude maintains user/feedback/project/
1898
+ reference memories under \`.claude/memory/\`. If you ask for
1899
+ something that contradicts a remembered preference, Claude flags
1900
+ it before acting; corrections update memory automatically.
1901
+ - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
1902
+ or background work. Useful for "wait for the deploy then open a
1903
+ cleanup PR" or "every Monday triage the issue board" patterns.
1904
+
1905
+ ## Quick reference (full version in AGENTS.md)
1906
+
1907
+ \`\`\`bash
1908
+ ${n} install # Install dependencies
1909
+ kick dev # Dev server with HMR + typegen
1910
+ kick build && kick start # Production
1911
+ ${n} run test # Vitest
1912
+ ${n} run typecheck # tsc --noEmit
1913
+ ${n} run format # Prettier
1914
+ \`\`\`
1915
+
1916
+ ## v4 framework reminders
1917
+
1918
+ When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
1919
+
1920
+ - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
1921
+ - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
1922
+ - **DI tokens**: \`<scope>/<PascalKey>[/<suffix>]\` — scope is lowercase, the key segment is **PascalCase** (e.g. \`'app/Users/repository'\`, \`'mycorp/Cache/redis'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
1923
+ - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
1924
+ - **Module entry file** MUST be named \`<name>.module.ts\` and live under \`src/modules/<name>/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed \`projects.ts\` silently degrades every save into a full restart.
1925
+ - **Env**: schema lives in \`src/config/index.ts\`; \`import './config'\` MUST be the first import in \`src/index.ts\` (side-effect registers the schema before any \`@Value\` resolves).
1926
+ - **Assets**: drop new template files into \`src/templates/<namespace>/\`; the dev watcher auto-rebuilds the \`KickAssets\` augmentation + \`assets.x.y()\` re-walks on next call. No restart, no manual build.
1927
+ - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
1928
+ - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
1929
+ - **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.
1930
+ - **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\`.
1931
+ - **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\`.
1932
+
1933
+ For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
1934
+ `}function J(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
1935
+
1936
+ This guide is the **canonical, multi-agent reference** for this KickJS
1937
+ application — Claude, Copilot, Codex, Gemini, etc. all read it first.
1938
+ Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
1939
+ add tool-specific affordances on top.
1940
+
1941
+ ## Before You Start
1942
+
1943
+ 1. Run \`${n} install\` to install dependencies
1944
+ 2. Run \`kick dev\` to verify the app starts
1945
+ 3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
1946
+
1947
+ ## v4 Conventions (don't skip)
1948
+
1949
+ KickJS v4 made a handful of structural changes from v3. Internalise these
1950
+ before generating or modifying code — they are the source of most agent
1951
+ mistakes:
1952
+
1953
+ - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
1954
+
1955
+ \`\`\`ts
1956
+ export const MyAdapter = defineAdapter<MyOptions>({
1957
+ name: 'MyAdapter',
1958
+ defaults: { ... },
1959
+ build: (config) => ({
1960
+ beforeMount({ app }) { /* ... */ },
1961
+ afterStart({ server }) { /* ... */ },
1962
+ }),
1963
+ })
1964
+ \`\`\`
1965
+
1966
+ - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
1967
+
1968
+ - **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
1969
+ the key segment is **PascalCase** (the regex enforces both):
1970
+
1971
+ \`\`\`ts
1972
+ const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
1973
+ const DB = createToken<Database>('app/Db/connection')
1974
+ \`\`\`
1975
+
1976
+ The \`kick/\` prefix is reserved for first-party packages; this project
1977
+ owns its own scope (\`app/\`, your domain name, etc.).
1978
+
1979
+ - **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
1980
+ the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
1981
+ is a v3 leftover; the linter and codegen reject it.
1982
+
1983
+ - **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
1984
+ side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
1985
+ import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
1986
+ returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
1987
+ (Zod coercion + defaults silently skipped).
1988
+
1989
+ - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
1990
+ HMR contract at the top of "Module Pattern" below. The CLI enforces this;
1991
+ hand-rolled files must too.
1992
+
1993
+ - **Assets** — drop new template files into \`src/templates/<namespace>/\`
1994
+ (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
1995
+ \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
1996
+ no manual build step.
1997
+
1998
+ - **Context over \`@Middleware()\`** — when a middleware's only job is to
1999
+ populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
2000
+ (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
2001
+ Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
2002
+ Reserve \`@Middleware()\` for response short-circuit / stream mutation /
2003
+ pre-route-matching work.
2004
+
2005
+ Two ground rules around the data flow — both stem from the fact that
2006
+ every per-request stage gets its OWN \`RequestContext\` instance, all
2007
+ reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
2008
+ - **\`resolve\` and \`onError\` must RETURN the value.** The runner
2009
+ writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
2010
+ property assignment (\`ctx.tenant = …\`) sticks to the contributor
2011
+ instance only — the handler instance never sees it.
2012
+ - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
2013
+ \`getRequestValue(key)\` from a service that has no \`ctx\` reference
2014
+ — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
2015
+ Express request is shared; bespoke property assignments don't.
2016
+
2017
+ - **Test isolation** — default to \`Container.create()\` for fresh DI state.
2018
+ Never \`new Container()\` and never \`getInstance().reset()\` — both leak
2019
+ registrations between tests.
2020
+
2021
+ \`\`\`ts
2022
+ const container = Container.create()
2023
+ // ... register test-scoped providers, run, discard
2024
+ \`\`\`
2025
+
2026
+ - **Bootstrap export** — \`src/index.ts\` MUST end with
2027
+ \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
2028
+ the named \`app\` symbol to drive HMR module swaps; testing helpers
2029
+ (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
2030
+ the \`export\` and \`kick dev\` will silently fall back to a full restart
2031
+ on every save while \`createTestApp\` complains about a missing handle.
2032
+
2033
+ - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
2034
+ adapters in dedicated folders and re-export aggregated arrays. Do **not**
2035
+ inline registration in the entry file:
2036
+
2037
+ \`\`\`ts
2038
+ // src/modules/index.ts
2039
+ export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
2040
+
2041
+ // src/middleware/index.ts
2042
+ export const middleware = [helmet(), cors(), requestId(), ...]
2043
+
2044
+ // src/plugins/index.ts
2045
+ export const plugins = [MetricsPlugin(), AuditPlugin()]
2046
+
2047
+ // src/adapters/index.ts
2048
+ export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
2049
+ \`\`\`
2050
+
2051
+ \`\`\`ts
2052
+ // src/index.ts — stays small; one import per category
2053
+ import 'reflect-metadata'
2054
+ import './config'
2055
+ import { bootstrap } from '@forinda/kickjs'
2056
+ import { modules } from './modules'
2057
+ import { middleware } from './middleware'
2058
+ import { plugins } from './plugins'
2059
+ import { adapters } from './adapters'
2060
+
2061
+ export const app = await bootstrap({ modules, middleware, plugins, adapters })
2062
+ \`\`\`
2063
+
2064
+ This keeps the entry file diff-friendly, scales to dozens of modules
2065
+ without git churn, and lets each domain own its own registration list.
2066
+ The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
2067
+ \`kick g adapter\`) follow this layout — manual additions should too.
2068
+
2069
+ Everything else (controllers, services, modules, RequestContext API, generators,
2070
+ package additions, env access patterns, troubleshooting) is detailed below.
2071
+
2072
+ ## Where to Find Things
2073
+
2074
+ ### Application Structure
2075
+
2076
+ | What | Where |
2077
+ |------|-------|
2078
+ | Entry point | \`src/index.ts\` |
2079
+ | Module registry | \`src/modules/index.ts\` |
2080
+ | Feature modules | \`src/modules/<module-name>/\` |
2081
+ | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
2082
+ | Env values | \`.env\` |
2083
+ | Env schema (Zod) | \`src/config/index.ts\` |
2084
+ | TypeScript config | \`tsconfig.json\` |
2085
+ | Vite config (HMR) | \`vite.config.ts\` |
2086
+ | Vitest config | \`vitest.config.ts\` |
2087
+ | Prettier config | \`.prettierrc\` |
2088
+ | CLI config | \`kick.config.ts\` |
2089
+
2090
+ ### Module Pattern (${t.toUpperCase()})
2091
+
2092
+ > **Vite HMR auto-discovery contract:** module files **must** be named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and live under \`src/modules/\`. The Vite plugin scans for \`*.module.[tj]sx?\` to drive graceful HMR rebuilds; renaming a file to \`projects.ts\` (no \`.module\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\`kick g module <name>\`) follows the convention; manual files must too.
2093
+
2094
+ Each module in \`src/modules/<name>/\` typically contains:
2095
+
2096
+ ${t===`ddd`?`\`\`\`
2097
+ <name>/
2098
+ ├── <name>.controller.ts # HTTP routes (@Controller)
2099
+ ├── <name>.service.ts # Business logic (@Service)
2100
+ ├── <name>.repository.ts # Data access (@Repository)
2101
+ ├── <name>.dto.ts # Request/response schemas (Zod)
2102
+ ├── <name>.entity.ts # Domain entity (optional)
2103
+ └── <name>.module.ts # Module definition (implements AppModule)
2104
+ \`\`\`
2105
+ `:t===`cqrs`?`\`\`\`
2106
+ <name>/
2107
+ ├── commands/ # Write operations
2108
+ │ ├── create-<name>.command.ts
2109
+ │ └── create-<name>.handler.ts
2110
+ ├── queries/ # Read operations
2111
+ │ ├── get-<name>.query.ts
2112
+ │ └── get-<name>.handler.ts
2113
+ ├── events/ # Domain events
2114
+ │ └── <name>-created.event.ts
2115
+ ├── <name>.controller.ts # HTTP routes
2116
+ ├── <name>.repository.ts # Data access
2117
+ └── <name>.module.ts # Module definition (implements AppModule)
2118
+ \`\`\`
2119
+ `:t===`rest`?`\`\`\`
2120
+ <name>/
2121
+ ├── <name>.controller.ts # HTTP routes (@Controller)
2122
+ ├── <name>.service.ts # Business logic (@Service)
2123
+ ├── <name>.dto.ts # Request/response schemas (Zod)
2124
+ └── <name>.module.ts # Module definition (implements AppModule)
2125
+ \`\`\`
2126
+ `:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
2127
+
2128
+ ## Checklist: Adding a Feature
2129
+
2130
+ ### New Module (Recommended)
2131
+
2132
+ Use the CLI generator for consistency:
2133
+
2134
+ \`\`\`bash
2135
+ kick g module <name> # Generate full module
2136
+ # or
2137
+ kick g scaffold <name> <fields> # Generate CRUD from fields
2138
+ \`\`\`
2139
+
2140
+ Then:
2141
+ - [ ] Review generated files in \`src/modules/<name>/\`
2142
+ - [ ] Verify module is registered in \`src/modules/index.ts\`
2143
+ - [ ] Update DTOs in \`<name>.dto.ts\` if needed
2144
+ - [ ] Implement business logic in \`<name>.service.ts\`
2145
+ - [ ] Run \`kick dev\` to test with HMR
2146
+ - [ ] Write tests in \`<name>.test.ts\`
2147
+
2148
+ ### Manual Controller
2149
+
2150
+ If not using generators:
2151
+
2152
+ - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
2153
+ - [ ] Add \`@Controller()\` decorator
2154
+ - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
2155
+ - [ ] Create module file implementing \`AppModule\` with \`routes()\` returning \`{ path, router: buildRoutes(Controller), controller }\`
2156
+ - [ ] Register module in \`src/modules/index.ts\` (\`AppModuleClass[]\` array)
2157
+ - [ ] Test with \`kick dev\`
2158
+
2159
+ ### Manual Service
2160
+
2161
+ - [ ] Create \`src/modules/<name>/<name>.service.ts\`
2162
+ - [ ] Add \`@Service()\` decorator
2163
+ - [ ] Inject dependencies with \`@Autowired()\`
2164
+ - [ ] Inject via \`@Autowired()\` where needed
2165
+ - [ ] Write unit tests
2166
+
2167
+ ### New Middleware
2168
+
2169
+ - [ ] Create \`src/middleware/<name>.middleware.ts\`
2170
+ - [ ] Export middleware function (Express format)
2171
+ - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
2172
+ - [ ] Test with sample requests
2173
+
2174
+ ### Adding a Package
2175
+
2176
+ Use \`kick add\` to install KickJS packages with correct peer dependencies:
2177
+
2178
+ - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
2179
+ - [ ] Follow package-specific setup in terminal output
2180
+ - [ ] Update \`src/index.ts\` to register adapter (if needed)
2181
+ - [ ] Configure environment variables in \`.env\`
2182
+ - [ ] Test integration with \`kick dev\`
2183
+
2184
+ ## Common Tasks
2185
+
2186
+ ### Generate CRUD Module
2187
+
2188
+ \`\`\`bash
2189
+ kick g scaffold user name:string email:string:optional age:number
2190
+ \`\`\`
2191
+
2192
+ Append \`:optional\` for optional fields (shell-safe, no quoting needed).
2193
+ Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
2194
+
2195
+ This creates a full CRUD module with:
2196
+ - Controller with GET, POST, PUT, DELETE routes
2197
+ - Service with business logic
2198
+ - Repository with data access
2199
+ - DTOs with Zod validation
2200
+
2201
+ ### Add Authentication
2202
+
2203
+ \`\`\`bash
2204
+ kick add auth
2205
+ \`\`\`
2206
+
2207
+ Then configure in \`src/index.ts\`:
2208
+
2209
+ \`\`\`ts
2210
+ import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
2211
+
2212
+ bootstrap({
2213
+ modules,
2214
+ adapters: [
2215
+ AuthAdapter({
2216
+ strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
2217
+ }),
2218
+ ],
2219
+ })
2220
+ \`\`\`
2221
+
2222
+ ### Add Database (Prisma)
2223
+
2224
+ \`\`\`bash
2225
+ kick add prisma
2226
+ ${n} install prisma @prisma/client
2227
+ npx prisma init
2228
+ # Edit prisma/schema.prisma
2229
+ npx prisma migrate dev --name init
2230
+ kick g module user --repo prisma
2231
+ \`\`\`
2232
+
2233
+ ### Add WebSocket Support
2234
+
2235
+ \`\`\`bash
2236
+ kick add ws
2237
+ \`\`\`
2238
+
2239
+ Then add adapter in \`src/index.ts\`:
2240
+
2241
+ \`\`\`ts
2242
+ import { WsAdapter } from '@forinda/kickjs-ws'
2243
+
2244
+ bootstrap({
2245
+ modules,
2246
+ adapters: [WsAdapter()],
2247
+ })
2248
+ \`\`\`
2249
+
2250
+ Create WebSocket controller:
2251
+
2252
+ \`\`\`bash
2253
+ kick g controller chat --ws
2254
+ \`\`\`
2255
+
2256
+ ## Testing Guidelines
2257
+
2258
+ All tests use Vitest:
2259
+
2260
+ \`\`\`ts
2261
+ import { describe, it, expect, beforeEach } from 'vitest'
2262
+ import { Container } from '@forinda/kickjs'
2263
+ import { createTestApp } from '@forinda/kickjs-testing'
2264
+
2265
+ describe('UserController', () => {
2266
+ it('should return users', async () => {
2267
+ // Container.create() — isolated DI state per test, never new Container()
2268
+ // and never getInstance().reset() (both leak registrations between tests).
2269
+ const container = Container.create()
2270
+ const app = await createTestApp([UserModule], { container })
2271
+ const res = await app.get('/users')
2272
+
2273
+ expect(res.status).toBe(200)
2274
+ expect(res.body).toHaveProperty('users')
2275
+ })
2276
+ })
2277
+ \`\`\`
2278
+
2279
+ Run tests:
2280
+ - \`${n} run test\` — run all tests once
2281
+ - \`${n} run test:watch\` — watch mode
2282
+ - Individual file: \`${n} run test src/modules/user/user.test.ts\`
2283
+
2284
+ ## Environment Variables
2285
+
2286
+ Schema is declared in \`src/config/index.ts\` (extends the base
2287
+ \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
2288
+ with kickjs at module load. \`src/index.ts\` imports it via
2289
+ \`import './config'\` **before** \`bootstrap()\` so the cache is populated
2290
+ in time for DI. Add new keys to the schema, drop their values into
2291
+ \`.env\`, and they're typed everywhere.
2292
+
2293
+ Access patterns:
2294
+
2295
+ 1. **@Value() decorator** (recommended for known-at-construction keys):
2296
+ \`\`\`ts
2297
+ @Value('DATABASE_URL')
2298
+ private dbUrl!: string
2299
+ \`\`\`
2300
+
2301
+ 2. **ConfigService** (recommended for dynamic / method-scoped access):
2302
+ \`\`\`ts
2303
+ @Autowired()
2304
+ private config!: ConfigService
2305
+
2306
+ const port = this.config.get('PORT') // typed: number
2307
+ \`\`\`
2308
+
2309
+ 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
2310
+ \`\`\`ts
2311
+ import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
2312
+
2313
+ const env = loadEnv(schema) // Parse + validate all vars
2314
+ const port = getEnv('PORT') // Single value lookup
2315
+ reloadEnv() // Re-read .env from disk
2316
+ resetEnvCache() // Full reset (for tests)
2317
+ \`\`\`
2318
+
2319
+ 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
2320
+ coercion and the typed \`KickEnv\` registry.
2321
+
2322
+ > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
2323
+ > If the schema is not registered before DI runs, \`config.get()\`
2324
+ > returns \`undefined\` for user keys (the base shape only) and
2325
+ > \`@Value()\` only works because of its raw \`process.env\` fallback —
2326
+ > Zod coercion + schema defaults are silently skipped.
2327
+
2328
+ ## Standalone Utilities (No DI Required)
2329
+
2330
+ These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
2331
+
2332
+ | Utility | Import | Example |
2333
+ |---------|--------|---------|
2334
+ | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
2335
+ | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
2336
+ | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
2337
+ | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
2338
+ | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
2339
+ | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
2340
+ | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
2341
+ | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
2342
+ | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
2343
+
2344
+ ## Key Decorators
2345
+
2346
+ ### HTTP Routes
2347
+ | Decorator | Purpose |
2348
+ |-----------|---------|
2349
+ | \`@Controller()\` | Define route prefix |
2350
+ | \`@Get('/'), @Post('/')\` | HTTP method handlers |
2351
+ | \`@Middleware(fn)\` | Attach middleware |
2352
+ | \`@Public()\` | Skip auth (requires auth adapter) |
2353
+ | \`@Roles('admin')\` | Role-based access |
2354
+
2355
+ ### Dependency Injection
2356
+ | Decorator | Purpose |
2357
+ |-----------|---------|
2358
+ | \`AppModule\` interface | Define feature module (implements \`routes()\`) |
2359
+ | \`@Service()\` | Register singleton service |
2360
+ | \`@Repository()\` | Register repository |
2361
+ | \`@Autowired()\` | Property injection |
2362
+ | \`@Inject('token')\` | Token-based injection |
2363
+ | \`@Value('VAR')\` | Inject env variable |
2364
+
2365
+ ### Context Decorators
2366
+
2367
+ Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
2368
+ Use this **instead of \`@Middleware()\`** when the middleware's only output
2369
+ is a value other code reads off \`ctx\`.
2370
+
2371
+ | Concept | Where it lives |
2372
+ |---------|----------------|
2373
+ | \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
2374
+ | Method/class decorator | \`@LoadX\` on a controller method/class |
2375
+ | Module hook | \`AppModule.contributors?(): ContributorRegistration[]\` |
2376
+ | Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
2377
+ | Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
2378
+ | Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
2379
+
2380
+ Precedence high → low: **method > class > module > adapter > global**.
2381
+ Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
2382
+ fast). The \`onError\` hook is async-permitted.
2383
+
2384
+ Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
2385
+
2386
+ ${t===`cqrs`?`### Background Jobs
2387
+ | Decorator | Purpose |
2388
+ |-----------|---------|
2389
+ | \`@Job('name')\` | Queue job handler |
2390
+ | \`@Process('queue')\` | Queue processor |
2391
+ | \`@Cron('0 * * * *')\` | Cron schedule |
2392
+ | \`@WsController()\` | WebSocket controller |
2393
+
2394
+ `:``}## Common Pitfalls
2395
+
2396
+ 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
2397
+ 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
2398
+ 3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
2399
+ 4. **Routes not found** — Check controller path and module registration
2400
+ 5. **HMR not working** — Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
2401
+ 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
2402
+ 7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
2403
+ 8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
2404
+ 9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
2405
+ 10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
2406
+ 11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
2407
+
2408
+ ## CLI Commands Reference
2409
+
2410
+ | Command | Description |
2411
+ |---------|-------------|
2412
+ | \`kick dev\` | Dev server with HMR |
2413
+ | \`kick dev:debug\` | Dev server with debugger |
2414
+ | \`kick build\` | Production build |
2415
+ | \`kick start\` | Run production build |
2416
+ | \`kick g module <names...>\` | Generate one or more modules |
2417
+ | \`kick g scaffold <name> <fields>\` | Generate CRUD |
2418
+ | \`kick g controller <name>\` | Generate controller |
2419
+ | \`kick g service <name>\` | Generate service |
2420
+ | \`kick g middleware <name>\` | Generate middleware |
2421
+ | \`kick add <package>\` | Add KickJS package |
2422
+ | \`kick add --list\` | List available packages |
2423
+ | \`kick rm module <names...>\` | Remove one or more modules |
2424
+
2425
+ > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
2426
+ > \`\`\`bash
2427
+ > kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
2428
+ > \`\`\`
2429
+
2430
+ ## Learn More
2431
+
2432
+ - [KickJS Docs](https://forinda.github.io/kick-js/)
2433
+ - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
2434
+ - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
2435
+ - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
2436
+ - [Testing](https://forinda.github.io/kick-js/api/testing.html)
2437
+ `}function Y(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
2438
+
2439
+ This file is the agent-facing **skills index** for KickJS work in this
2440
+ repo. Each block below is a short, rigid workflow keyed to a specific
2441
+ trigger ("user wants to add a module", "tests are leaking state", etc.).
2442
+
2443
+ - Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
2444
+ - Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
2445
+ - **This file** → step-by-step recipes the agent should *execute*.
2446
+
2447
+ Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
2448
+
2449
+ ---
2450
+
2451
+ ## Skill: add-module
2452
+
2453
+ \`\`\`yaml
2454
+ name: kickjs-add-module
2455
+ description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
2456
+ \`\`\`
2457
+
2458
+ **Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
2459
+
2460
+ **Steps**:
2461
+ 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
2462
+ 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
2463
+ 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
2464
+ 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
2465
+ 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
2466
+
2467
+ **Red flags** (stop and ask):
2468
+ - File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
2469
+ - Module not registered in \`src/modules/index.ts\`.
2470
+ - \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
2471
+
2472
+ ---
2473
+
2474
+ ## Skill: add-adapter
2475
+
2476
+ \`\`\`yaml
2477
+ name: kickjs-add-adapter
2478
+ description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
2479
+ \`\`\`
2480
+
2481
+ **Steps**:
2482
+ 1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
2483
+ 2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
2484
+ 3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
2485
+ 4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
2486
+ 5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
2487
+
2488
+ **Red flags**:
2489
+ - Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
2490
+ - Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
2491
+
2492
+ ---
2493
+
2494
+ ## Skill: write-controller-test
2495
+
2496
+ \`\`\`yaml
2497
+ name: kickjs-write-controller-test
2498
+ description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
2499
+ \`\`\`
2500
+
2501
+ **Template** (copy/paste, adjust):
2502
+
2503
+ \`\`\`ts
2504
+ import { describe, it, expect } from 'vitest'
2505
+ import { Container } from '@forinda/kickjs'
2506
+ import { createTestApp } from '@forinda/kickjs-testing'
2507
+
2508
+ describe('UserController', () => {
2509
+ it('returns users', async () => {
2510
+ const container = Container.create() // isolated DI per test
2511
+ const app = await createTestApp([UserModule], { container })
2512
+ const res = await app.get('/users')
2513
+ expect(res.status).toBe(200)
2514
+ })
2515
+ })
2516
+ \`\`\`
2517
+
2518
+ **Red flags**:
2519
+ - \`new Container()\` — wrong; use \`Container.create()\`.
2520
+ - \`Container.getInstance().reset()\` — wrong; same fix.
2521
+ - Sharing a container across \`it()\` blocks — leaks registrations.
2522
+
2523
+ ---
2524
+
2525
+ ## Skill: env-wiring-check
2526
+
2527
+ \`\`\`yaml
2528
+ name: kickjs-env-wiring-check
2529
+ description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
2530
+ \`\`\`
2531
+
2532
+ **Diagnosis**:
2533
+ 1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
2534
+ 2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
2535
+ 3. The new key MUST be declared in the Zod schema there. \`@Value('NEW_KEY')\` won't work without a schema entry (it'll fall back to raw \`process.env\` and skip Zod coercion silently).
2536
+
2537
+ **Fix**: add the key to the schema; ensure both side-effect imports above are present.
2538
+
2539
+ ---
2540
+
2541
+ ## Skill: bootstrap-export
2542
+
2543
+ \`\`\`yaml
2544
+ name: kickjs-bootstrap-export
2545
+ description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
2546
+ \`\`\`
2547
+
2548
+ **Check** \`src/index.ts\`'s last line:
2549
+
2550
+ \`\`\`ts
2551
+ // CORRECT
2552
+ export const app = await bootstrap({ ... })
2553
+
2554
+ // WRONG (HMR degrades to full restart, createTestApp loses the handle)
2555
+ await bootstrap({ ... })
2556
+ \`\`\`
2557
+
2558
+ The Vite plugin imports the named \`app\` symbol; testing helpers do too.
2559
+
2560
+ ---
2561
+
2562
+ ## Skill: thin-entry-file
2563
+
2564
+ \`\`\`yaml
2565
+ name: kickjs-thin-entry-file
2566
+ description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
2567
+ \`\`\`
2568
+
2569
+ **Refactor target**:
2570
+
2571
+ \`\`\`ts
2572
+ // src/modules/index.ts
2573
+ export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
2574
+
2575
+ // src/middleware/index.ts
2576
+ export const middleware = [helmet(), cors(), requestId(), ...]
2577
+
2578
+ // src/plugins/index.ts
2579
+ export const plugins = [MetricsPlugin(), ...]
2580
+
2581
+ // src/adapters/index.ts
2582
+ export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
2583
+
2584
+ // src/index.ts — stays small
2585
+ import 'reflect-metadata'
2586
+ import './config'
2587
+ import { bootstrap } from '@forinda/kickjs'
2588
+ import { modules } from './modules'
2589
+ import { middleware } from './middleware'
2590
+ import { plugins } from './plugins'
2591
+ import { adapters } from './adapters'
2592
+ export const app = await bootstrap({ modules, middleware, plugins, adapters })
2593
+ \`\`\`
2594
+
2595
+ **Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
2596
+
2597
+ ---
2598
+
2599
+ ## Skill: context-contributor
2600
+
2601
+ \`\`\`yaml
2602
+ name: kickjs-context-contributor
2603
+ description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
2604
+ \`\`\`
2605
+
2606
+ **Pattern** (HTTP — most common):
2607
+
2608
+ \`\`\`ts
2609
+ import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
2610
+
2611
+ const LoadTenant = defineHttpContextDecorator({
2612
+ key: 'tenant',
2613
+ deps: { repo: TENANT_REPO },
2614
+ resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
2615
+ })
2616
+
2617
+ const LoadProject = defineHttpContextDecorator({
2618
+ key: 'project',
2619
+ dependsOn: ['tenant'],
2620
+ resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
2621
+ })
2622
+
2623
+ @LoadTenant
2624
+ @LoadProject
2625
+ @Get('/projects/:id')
2626
+ getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
2627
+ \`\`\`
2628
+
2629
+ Use \`defineContextDecorator\` (no Http prefix) when authoring a contributor that must run across HTTP, WebSocket, queue, and cron transports — \`Ctx\` defaults to the smaller \`ExecutionContext\` surface (\`get\` / \`set\` / \`requestId\` only, no \`req\`).
2630
+
2631
+ Precedence high → low: **method > class > module > adapter > global**.
2632
+ Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
2633
+
2634
+ **Critical rules — all stem from the same shared-via-ALS instance model**:
2635
+ - Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
2636
+ - **\`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.
2637
+ - \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
2638
+ - Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
2639
+ - **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.
2640
+
2641
+ **Don't use this for**: response short-circuit, stream mutation, or
2642
+ pre-route-matching work — keep \`@Middleware()\` for those.
2643
+
2644
+ ---
2645
+
2646
+ ## Skill: refresh-agent-docs
2647
+
2648
+ \`\`\`yaml
2649
+ name: kickjs-refresh-agent-docs
2650
+ description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
2651
+ \`\`\`
2652
+
2653
+ **Steps**:
2654
+ 1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
2655
+ 2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
2656
+ 3. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \`AGENTS.local.md\` or appended section.
2657
+ 4. Commit as \`docs(agents): sync from CLI vX.Y\`.
2658
+
2659
+ ---
2660
+
2661
+ ## Skill: deny-list
2662
+
2663
+ \`\`\`yaml
2664
+ name: kickjs-deny-list
2665
+ description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
2666
+ \`\`\`
2667
+
2668
+ - \`class implements AppAdapter\` → use \`defineAdapter()\`.
2669
+ - \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
2670
+ - \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
2671
+ - \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
2672
+ - DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
2673
+ - \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
2674
+ - Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
2675
+
2676
+ ---
2677
+
2678
+ ## Learn More
2679
+
2680
+ - [KickJS Docs](https://forinda.github.io/kick-js/)
2681
+ - [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
2682
+ - [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
2683
+ - [Testing](https://forinda.github.io/kick-js/api/testing.html)
2684
+ `}const ft=t(h(import.meta.url)),X=JSON.parse(o(r(ft,`..`,`package.json`),`utf-8`)),pt=`^${X.version}`;async function mt(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}`);if(console.log(`\n Creating KickJS project: ${t}\n`),await b(r(c,`package.json`),tt(t,a,pt,s)),await b(r(c,`vite.config.ts`),nt()),await b(r(c,`tsconfig.json`),rt()),await b(r(c,`.prettierrc`),it()),await b(r(c,`.editorconfig`),at()),await b(r(c,`.gitignore`),ot()),await b(r(c,`.gitattributes`),st()),await b(r(c,`.env`),ct()),await b(r(c,`.env.example`),lt()),await b(r(c,`src/config/index.ts`),Ne()),await b(r(c,`src/index.ts`),je(t,a,X.version,s)),await b(r(c,`src/modules/index.ts`),Me()),await b(r(c,`src/modules/hello/hello.service.ts`),Pe()),await b(r(c,`src/modules/hello/hello.controller.ts`),Fe()),await b(r(c,`src/modules/hello/hello.module.ts`),Ie()),await b(r(c,`kick.config.ts`),Le(a,o,i)),await b(r(c,`vitest.config.ts`),ut()),await b(r(c,`README.md`),dt(t,a,i)),await b(r(c,`CLAUDE.md`),q(t,a,i)),await b(r(c,`AGENTS.md`),J(t,a,i)),await b(r(c,`kickjs-skills.md`),Y(t,a,i)),e.installDeps){console.log(`\n Installing dependencies with ${i}...\n`);try{m(`${i} install`,{cwd:c,stdio:`inherit`}),console.log(`
2685
+ Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${i} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-CBI7dNXr.mjs`).then(e=>e.n);await e({cwd:c,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{m(`git init`,{cwd:c,stdio:`pipe`}),m(`git branch -M main`,{cwd:c,stdio:`pipe`}),m(`git add -A`,{cwd:c,stdio:`pipe`}),m(`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(`
2686
+ Project scaffolded successfully!`),console.log();let u=c!==process.cwd();l(`Next steps:`),u&&l(` cd ${t}`),e.installDeps||l(` ${i} install`);let d={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(` ${d[a]??d.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 ht(e){return e}function gt(e){return k(e).replace(/-/g,`_`)}function Z(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=D(e.name),i=O(e.name),a=k(e.name),o=gt(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 _t(e,t){return i(e.cwd,t)}async function vt(e){return import(g(e).href)}const Q=new Map;async function $(e){let t=Q.get(e);if(t)return t;let n=yt(e);return Q.set(e,n),n}async function yt(n){let r=i(n,`package.json`);if(!a(r))return{generators:[],loaded:[],failed:[]};let o=bt(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 vt(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(!xt(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 bt(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 xt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function St(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Tt(r.spec,r.source,e,n);let i=wt(await $(n),e.generatorName);return i?Tt(i.spec,i.source,e,n):null}async function Ct(e,t=[]){let n=await $(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 wt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Tt(e,t,n,r){let i=Z({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=_t(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}export{ie as A,oe as C,le as D,se as E,b as F,ae as M,C as N,de as O,v as P,T as S,ue as T,A as _,mt as a,k as b,Y as c,Ze as d,Xe as f,He as g,Ue as h,ht as i,f as j,ce as k,$e as l,Ge as m,St as n,J as o,Ye as p,Z as r,q as s,Ct as t,Qe as u,j as v,E as w,D as x,O as y};
2687
+ //# sourceMappingURL=generator-extension-Cp5FUUAw.mjs.map