@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,3740 @@
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{t as e}from"./rolldown-runtime-B6QC8dMY.mjs";import{a as t,i as n,r,t as i}from"./config-Dzw8Ws4d.mjs";import{n as a,r as o}from"./plugin-Dv2gKsuC.mjs";import{a as s,i as c,o as l,r as u,s as d,t as f}from"./typegen-C6ZfoYTC.mjs";import{createRequire as p}from"node:module";import{cpSync as m,existsSync as h,mkdirSync as g,readFileSync as _,readdirSync as ee,rmSync as te,statSync as ne,writeFileSync as re}from"node:fs";import v,{basename as ie,dirname as y,extname as ae,isAbsolute as oe,join as b,relative as x,resolve as S,sep as se}from"node:path";import{fileURLToPath as ce,pathToFileURL as C}from"node:url";import{execSync as w,fork as le,spawn as ue,spawnSync as de}from"node:child_process";import{access as fe,mkdir as pe,readFile as T,rm as me,writeFile as E}from"node:fs/promises";import*as D from"@clack/prompts";import O from"picocolors";import he from"pluralize";import{glob as ge}from"glob";import{groupAssetKeys as _e}from"@forinda/kickjs";import{arch as ve,platform as ye,release as be}from"node:os";import{generate as xe,migrateDown as Se,migrateLatest as Ce,migrateRollback as we,migrateStatus as Te,migrateUp as Ee,renderSchemaSource as De,resolveDbConfig as Oe}from"@forinda/kickjs-db";function ke(e,t,n){w(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function Ae(e,t,n){let r=de(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}let je=!1;function k(e){je=e}const Me=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function A(e,t){je||(await pe(y(e),{recursive:!0}),await E(e,t,`utf-8`),Me.has(ae(e))&&await Pe(e,t).catch(()=>{}))}let j;async function Ne(e){if(j!==void 0)return j;try{j=await import(p(b(e,`package.json`)).resolve(`oxfmt`))}catch{j=null}return j}async function Pe(e,t){let n=await Ne(process.cwd());if(!n)return;let r=await Fe(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await E(e,i.code,`utf-8`)}const M=new Map;async function Fe(e){let t=y(e),n=t;if(M.has(n))return M.get(n);for(;;){let e=b(t,`.oxfmtrc.json`);if(h(e))try{let t=await T(e,`utf-8`),r=JSON.parse(t);return delete r.$schema,delete r.ignorePatterns,M.set(n,r),r}catch{return M.set(n,null),null}let r=y(t);if(r===t)return M.set(n,null),null;t=r}}async function N(e){try{return await fe(e),!0}catch{return!1}}const Ie={auth:`@forinda/kickjs-auth`,swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function Le(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=Ie[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 Re(){return`import { defineConfig } from 'vite'
12
+ import { resolve } from 'node:path'
13
+ import swc from 'unplugin-swc'
14
+ import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
15
+
16
+ export default defineConfig({
17
+ oxc: false,
18
+ plugins: [
19
+ swc.vite(),
20
+ kickjsVitePlugin({ entry: 'src/index.ts' }),
21
+ // Watches .env files and triggers a full reload on change so the
22
+ // dev server picks up env tweaks without a manual restart.
23
+ envWatchPlugin(),
24
+ ],
25
+ resolve: {
26
+ alias: {
27
+ '@': resolve(__dirname, 'src'),
28
+ },
29
+ },
30
+ ssr: {
31
+ // Don't bundle pino — its worker-thread transport needs Node.js resolution
32
+ // to find pino-pretty at runtime for colored log output
33
+ external: ['pino', 'pino-pretty'],
34
+ },
35
+ build: {
36
+ target: 'node20',
37
+ ssr: true,
38
+ outDir: 'dist',
39
+ sourcemap: true,
40
+ rollupOptions: {
41
+ input: resolve(__dirname, 'src/index.ts'),
42
+ output: { format: 'esm' },
43
+ },
44
+ },
45
+ })
46
+ `}function ze(){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 Be(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function Ve(){return`# https://editorconfig.org
47
+ root = true
48
+
49
+ [*]
50
+ indent_style = space
51
+ indent_size = 2
52
+ end_of_line = lf
53
+ charset = utf-8
54
+ trim_trailing_whitespace = true
55
+ insert_final_newline = true
56
+
57
+ [*.md]
58
+ trim_trailing_whitespace = false
59
+ `}function He(){return`node_modules/
60
+ dist/
61
+ .env
62
+ coverage/
63
+ .DS_Store
64
+ *.tsbuildinfo
65
+ .kickjs/
66
+ `}function Ue(){return`# Auto-detect text files and normalise line endings to LF
67
+ * text=auto eol=lf
68
+
69
+ # Explicitly mark generated / binary files
70
+ *.png binary
71
+ *.jpg binary
72
+ *.jpeg binary
73
+ *.gif binary
74
+ *.ico binary
75
+ *.woff binary
76
+ *.woff2 binary
77
+ *.ttf binary
78
+ *.eot binary
79
+
80
+ # Lock files — treat as generated
81
+ pnpm-lock.yaml -diff linguist-generated
82
+ yarn.lock -diff linguist-generated
83
+ package-lock.json -diff linguist-generated
84
+ `}function We(){return`PORT=3000
85
+ NODE_ENV=development
86
+ `}function Ge(){return`PORT=3000
87
+ NODE_ENV=development
88
+ `}function Ke(){return`import { defineConfig } from 'vitest/config'
89
+ import swc from 'unplugin-swc'
90
+
91
+ export default defineConfig({
92
+ plugins: [swc.vite()],
93
+ test: {
94
+ globals: true,
95
+ environment: 'node',
96
+ include: ['src/**/*.test.ts'],
97
+ },
98
+ })
99
+ `}function qe(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'
100
+ // Side-effect import — registers the extended env schema with kickjs
101
+ // **before** any controller / service / @Value gets resolved. Without
102
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
103
+ // cached schema would still be the base shape. See guide/configuration.
104
+ import './config'
105
+ import { bootstrap } from '@forinda/kickjs'
106
+ // import { WsAdapter } from '@forinda/kickjs-ws'
107
+ // import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
108
+ ${t.length?t.join(`
109
+ `)+`
110
+ `:``}import { modules } from './modules'
111
+
112
+ // Export the app for the Vite plugin (dev mode)
113
+ export const app = await bootstrap({
114
+ modules,${t.length?`\n adapters: [\n${i.join(`
115
+ `)}\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 ],`:`
116
+ adapters: [
117
+ // Uncomment for WebSocket support:
118
+ // WsAdapter(),
119
+ // Uncomment when Redis is available:
120
+ // QueueAdapter({
121
+ // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
122
+ // }),
123
+ ],`}
124
+ })
125
+ `}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'
126
+ // Side-effect import — registers the extended env schema with kickjs
127
+ // **before** any controller / service / @Value gets resolved. Without
128
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
129
+ // cached schema would still be the base shape. See guide/configuration.
130
+ import './config'
131
+ import { bootstrap } from '@forinda/kickjs'
132
+ ${t.length?t.join(`
133
+ `)+`
134
+ `:``}import { modules } from './modules'
135
+
136
+ // Export the app for the Vite plugin (dev mode)
137
+ export const app = await bootstrap({ modules${i.length?`,\n adapters: [\n${i.join(`
138
+ `)}\n ]`:``} })
139
+ `}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'
140
+ // Side-effect import — registers the extended env schema with kickjs
141
+ // **before** any controller / service / @Value gets resolved. Without
142
+ // this line ConfigService.get('YOUR_KEY') returns undefined because the
143
+ // cached schema would still be the base shape. See guide/configuration.
144
+ import './config'
145
+ import express from 'express'
146
+ import {
147
+ bootstrap,
148
+ requestId,
149
+ requestLogger,
150
+ helmet,
151
+ cors,
152
+ } from '@forinda/kickjs'
153
+ ${t.length?t.join(`
154
+ `)+`
155
+ `:``}import { modules } from './modules'
156
+
157
+ // Export the app for the Vite plugin (dev mode)
158
+ export const app = await bootstrap({
159
+ modules,${i.length?`\n adapters: [\n${i.join(`
160
+ `)}\n ],`:``}
161
+ middleware: [
162
+ helmet(),
163
+ cors({ origin: '*' }),
164
+ requestId(),
165
+ requestLogger(),
166
+ express.json(),
167
+ ],
168
+ })
169
+ `}}}function Je(){return`import type { AppModuleClass } from '@forinda/kickjs'
170
+ import { HelloModule } from './hello/hello.module'
171
+
172
+ // Remove HelloModule and run: kick g module <name>
173
+ export const modules: AppModuleClass[] = [HelloModule]
174
+ `}function Ye(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
175
+ import { z } from 'zod'
176
+
177
+ /**
178
+ * Project environment schema.
179
+ *
180
+ * Extend the base schema with your application's variables. The
181
+ * default export is the contract \`kick typegen\` reads to populate
182
+ * the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
183
+ * autocomplete and \`process.env.FOO\` typed.
184
+ *
185
+ * @example
186
+ * DATABASE_URL: z.string().url(),
187
+ * JWT_SECRET: z.string().min(32),
188
+ * REDIS_URL: z.string().url().optional(),
189
+ */
190
+ const envSchema = defineEnv((base) =>
191
+ base.extend({
192
+ // DATABASE_URL: z.string().url(),
193
+ }),
194
+ )
195
+
196
+ /**
197
+ * IMPORTANT — side effect: register the schema with kickjs's env cache
198
+ * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
199
+ * this cache, and they will fall back to the base schema (or undefined)
200
+ * if no extended schema has been registered before they're resolved.
201
+ *
202
+ * As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
203
+ * top — before \`bootstrap()\` runs — every controller and service in the
204
+ * app sees the typed extended values.
205
+ */
206
+ export const env = loadEnv(envSchema)
207
+
208
+ export default envSchema
209
+ `}function Xe(){return`import { Service } from '@forinda/kickjs'
210
+
211
+ @Service()
212
+ export class HelloService {
213
+ greet(name: string) {
214
+ return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
215
+ }
216
+
217
+ healthCheck() {
218
+ return { status: 'ok', uptime: process.uptime() }
219
+ }
220
+ }
221
+ `}function Ze(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
222
+ import { HelloService } from './hello.service'
223
+
224
+ // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
225
+ // \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
226
+ // scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
227
+ // See https://forinda.github.io/kick-js/guide/typegen.
228
+
229
+ @Controller()
230
+ export class HelloController {
231
+ @Autowired() private readonly helloService!: HelloService
232
+
233
+ @Get('/')
234
+ index(ctx: Ctx<KickRoutes.HelloController['index']>) {
235
+ ctx.json(this.helloService.greet('World'))
236
+ }
237
+
238
+ @Get('/health')
239
+ health(ctx: Ctx<KickRoutes.HelloController['health']>) {
240
+ ctx.json(this.helloService.healthCheck())
241
+ }
242
+ }
243
+ `}function Qe(){return`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
244
+ import { HelloController } from './hello.controller'
245
+
246
+ export class HelloModule implements AppModule {
247
+ // \`register(container)\` is optional — only implement it when you need
248
+ // to bind a token to a concrete implementation, e.g.
249
+ // register(container) {
250
+ // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
251
+ // }
252
+ // The HelloService uses @Service() so the decorator handles registration.
253
+
254
+ routes(): ModuleRoutes {
255
+ return {
256
+ path: '/hello',
257
+ router: buildRoutes(HelloController),
258
+ controller: HelloController,
259
+ }
260
+ }
261
+ }
262
+ `}function $e(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
263
+
264
+ export default defineConfig({
265
+ pattern: '${e}',
266
+ // Pinned so \`kick add\` and other dep-installing commands always use the
267
+ // project's intended package manager, regardless of which lockfile exists.
268
+ packageManager: '${n}',
269
+ modules: {
270
+ dir: 'src/modules',
271
+ repo: ${[`drizzle`,`inmemory`,`prisma`].includes(t)?`'${t}'`:`{ name: '${t}' }`},
272
+ pluralize: true,
273
+ },
274
+
275
+ // \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
276
+ // resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
277
+ // Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
278
+ typegen: {
279
+ schemaValidator: 'zod',
280
+ },
281
+
282
+ commands: [
283
+ {
284
+ name: 'test',
285
+ description: 'Run tests with Vitest',
286
+ steps: 'npx vitest run',
287
+ },
288
+ {
289
+ name: 'format',
290
+ description: 'Format code with Prettier',
291
+ steps: 'npx prettier --write src/',
292
+ },
293
+ {
294
+ name: 'format:check',
295
+ description: 'Check formatting without writing',
296
+ steps: 'npx prettier --check src/',
297
+ },
298
+ {
299
+ name: 'ci:check',
300
+ description: 'Run typecheck + format check',
301
+ steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
302
+ aliases: ['verify'],
303
+ },
304
+ ],
305
+ })
306
+ `}function et(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}
307
+
308
+ 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.
309
+
310
+ ## Getting Started
311
+
312
+ \`\`\`bash
313
+ ${n} install
314
+ kick dev
315
+ \`\`\`
316
+
317
+ ## Scripts
318
+
319
+ | Command | Description |
320
+ |---|---|
321
+ | \`kick dev\` | Start dev server with Vite HMR |
322
+ | \`kick build\` | Production build |
323
+ | \`kick start\` | Run production build |
324
+ | \`${n} run test\` | Run tests with Vitest |
325
+ | \`kick g module <name>\` | Generate a DDD module |
326
+ | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
327
+ | \`kick add <package>\` | Add a KickJS package |
328
+
329
+ ## Project Structure
330
+
331
+ \`\`\`
332
+ src/
333
+ ├── index.ts # Application entry point
334
+ ├── modules/ # Feature modules (controllers, services, repos)
335
+ │ └── index.ts # Module registry
336
+ └── ...
337
+ \`\`\`
338
+
339
+ ## Packages
340
+
341
+ ${i.map(e=>`- \`${e}\``).join(`
342
+ `)}
343
+
344
+ ## Adding Features
345
+
346
+ \`\`\`bash
347
+ kick add auth # Authentication (JWT, API key, OAuth)
348
+ kick add swagger # OpenAPI documentation
349
+ kick add ws # WebSocket support
350
+ kick add queue # Background job processing
351
+ kick add --list # Show all available packages
352
+ \`\`\`
353
+
354
+ 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.
355
+
356
+ ## Environment Variables
357
+
358
+ Copy \`.env.example\` to \`.env\` and configure:
359
+
360
+ | Variable | Default | Description |
361
+ |---|---|---|
362
+ | \`PORT\` | \`3000\` | Server port |
363
+ | \`NODE_ENV\` | \`development\` | Environment |
364
+
365
+ ## Learn More
366
+
367
+ - [KickJS Documentation](https://forinda.github.io/kick-js/)
368
+ - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
369
+ `}function tt(e,t,n){return`# CLAUDE.md — ${e}
370
+
371
+ **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
372
+ reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
373
+ project conventions, structure, decorator patterns, env wiring, CLI
374
+ generators, every gotcha.
375
+
376
+ **Then read \`./kickjs-skills.md\`.** That file is the task-oriented
377
+ skill index — short, rigid recipes keyed to triggers ("add-module",
378
+ "write-controller-test", "bootstrap-export", "deny-list", …). Use it
379
+ as the playbook when executing common KickJS workflows.
380
+
381
+ This file is a thin Claude-specific layer on top of those two; when
382
+ they disagree on anything substantive, treat \`AGENTS.md\` as
383
+ authoritative and flag the discrepancy.
384
+
385
+ ## Why two files
386
+
387
+ \`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
388
+ Claude Code automatically loads as project context on each
389
+ conversation. Keeping CLAUDE.md slim avoids two files drifting; the
390
+ redirect above ensures Claude pulls the canonical content without
391
+ us copy-pasting.
392
+
393
+ ## Claude-specific notes
394
+
395
+ - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
396
+ to refresh project memory if AGENTS.md changes substantially.
397
+ - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
398
+ - **Persistent memory** — Claude maintains user/feedback/project/
399
+ reference memories under \`.claude/memory/\`. If you ask for
400
+ something that contradicts a remembered preference, Claude flags
401
+ it before acting; corrections update memory automatically.
402
+ - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
403
+ or background work. Useful for "wait for the deploy then open a
404
+ cleanup PR" or "every Monday triage the issue board" patterns.
405
+
406
+ ## Quick reference (full version in AGENTS.md)
407
+
408
+ \`\`\`bash
409
+ ${n} install # Install dependencies
410
+ kick dev # Dev server with HMR + typegen
411
+ kick build && kick start # Production
412
+ ${n} run test # Vitest
413
+ ${n} run typecheck # tsc --noEmit
414
+ ${n} run format # Prettier
415
+ \`\`\`
416
+
417
+ ## v4 framework reminders
418
+
419
+ When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
420
+
421
+ - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
422
+ - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
423
+ - **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.
424
+ - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
425
+ - **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.
426
+ - **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).
427
+ - **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.
428
+ - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
429
+ - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
430
+ - **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.
431
+ - **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\`.
432
+ - **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\`.
433
+
434
+ For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
435
+ `}function nt(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
436
+
437
+ This guide is the **canonical, multi-agent reference** for this KickJS
438
+ application — Claude, Copilot, Codex, Gemini, etc. all read it first.
439
+ Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
440
+ add tool-specific affordances on top.
441
+
442
+ ## Before You Start
443
+
444
+ 1. Run \`${n} install\` to install dependencies
445
+ 2. Run \`kick dev\` to verify the app starts
446
+ 3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
447
+
448
+ ## v4 Conventions (don't skip)
449
+
450
+ KickJS v4 made a handful of structural changes from v3. Internalise these
451
+ before generating or modifying code — they are the source of most agent
452
+ mistakes:
453
+
454
+ - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
455
+
456
+ \`\`\`ts
457
+ export const MyAdapter = defineAdapter<MyOptions>({
458
+ name: 'MyAdapter',
459
+ defaults: { ... },
460
+ build: (config) => ({
461
+ beforeMount({ app }) { /* ... */ },
462
+ afterStart({ server }) { /* ... */ },
463
+ }),
464
+ })
465
+ \`\`\`
466
+
467
+ - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
468
+
469
+ - **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
470
+ the key segment is **PascalCase** (the regex enforces both):
471
+
472
+ \`\`\`ts
473
+ const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
474
+ const DB = createToken<Database>('app/Db/connection')
475
+ \`\`\`
476
+
477
+ The \`kick/\` prefix is reserved for first-party packages; this project
478
+ owns its own scope (\`app/\`, your domain name, etc.).
479
+
480
+ - **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
481
+ the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
482
+ is a v3 leftover; the linter and codegen reject it.
483
+
484
+ - **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
485
+ side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
486
+ import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
487
+ returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
488
+ (Zod coercion + defaults silently skipped).
489
+
490
+ - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
491
+ HMR contract at the top of "Module Pattern" below. The CLI enforces this;
492
+ hand-rolled files must too.
493
+
494
+ - **Assets** — drop new template files into \`src/templates/<namespace>/\`
495
+ (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
496
+ \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
497
+ no manual build step.
498
+
499
+ - **Context over \`@Middleware()\`** — when a middleware's only job is to
500
+ populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
501
+ (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
502
+ Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
503
+ Reserve \`@Middleware()\` for response short-circuit / stream mutation /
504
+ pre-route-matching work.
505
+
506
+ Two ground rules around the data flow — both stem from the fact that
507
+ every per-request stage gets its OWN \`RequestContext\` instance, all
508
+ reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
509
+ - **\`resolve\` and \`onError\` must RETURN the value.** The runner
510
+ writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
511
+ property assignment (\`ctx.tenant = …\`) sticks to the contributor
512
+ instance only — the handler instance never sees it.
513
+ - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
514
+ \`getRequestValue(key)\` from a service that has no \`ctx\` reference
515
+ — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
516
+ Express request is shared; bespoke property assignments don't.
517
+
518
+ - **Test isolation** — default to \`Container.create()\` for fresh DI state.
519
+ Never \`new Container()\` and never \`getInstance().reset()\` — both leak
520
+ registrations between tests.
521
+
522
+ \`\`\`ts
523
+ const container = Container.create()
524
+ // ... register test-scoped providers, run, discard
525
+ \`\`\`
526
+
527
+ - **Bootstrap export** — \`src/index.ts\` MUST end with
528
+ \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
529
+ the named \`app\` symbol to drive HMR module swaps; testing helpers
530
+ (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
531
+ the \`export\` and \`kick dev\` will silently fall back to a full restart
532
+ on every save while \`createTestApp\` complains about a missing handle.
533
+
534
+ - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
535
+ adapters in dedicated folders and re-export aggregated arrays. Do **not**
536
+ inline registration in the entry file:
537
+
538
+ \`\`\`ts
539
+ // src/modules/index.ts
540
+ export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
541
+
542
+ // src/middleware/index.ts
543
+ export const middleware = [helmet(), cors(), requestId(), ...]
544
+
545
+ // src/plugins/index.ts
546
+ export const plugins = [MetricsPlugin(), AuditPlugin()]
547
+
548
+ // src/adapters/index.ts
549
+ export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
550
+ \`\`\`
551
+
552
+ \`\`\`ts
553
+ // src/index.ts — stays small; one import per category
554
+ import 'reflect-metadata'
555
+ import './config'
556
+ import { bootstrap } from '@forinda/kickjs'
557
+ import { modules } from './modules'
558
+ import { middleware } from './middleware'
559
+ import { plugins } from './plugins'
560
+ import { adapters } from './adapters'
561
+
562
+ export const app = await bootstrap({ modules, middleware, plugins, adapters })
563
+ \`\`\`
564
+
565
+ This keeps the entry file diff-friendly, scales to dozens of modules
566
+ without git churn, and lets each domain own its own registration list.
567
+ The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
568
+ \`kick g adapter\`) follow this layout — manual additions should too.
569
+
570
+ Everything else (controllers, services, modules, RequestContext API, generators,
571
+ package additions, env access patterns, troubleshooting) is detailed below.
572
+
573
+ ## Where to Find Things
574
+
575
+ ### Application Structure
576
+
577
+ | What | Where |
578
+ |------|-------|
579
+ | Entry point | \`src/index.ts\` |
580
+ | Module registry | \`src/modules/index.ts\` |
581
+ | Feature modules | \`src/modules/<module-name>/\` |
582
+ | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
583
+ | Env values | \`.env\` |
584
+ | Env schema (Zod) | \`src/config/index.ts\` |
585
+ | TypeScript config | \`tsconfig.json\` |
586
+ | Vite config (HMR) | \`vite.config.ts\` |
587
+ | Vitest config | \`vitest.config.ts\` |
588
+ | Prettier config | \`.prettierrc\` |
589
+ | CLI config | \`kick.config.ts\` |
590
+
591
+ ### Module Pattern (${t.toUpperCase()})
592
+
593
+ > **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.
594
+
595
+ Each module in \`src/modules/<name>/\` typically contains:
596
+
597
+ ${t===`ddd`?`\`\`\`
598
+ <name>/
599
+ ├── <name>.controller.ts # HTTP routes (@Controller)
600
+ ├── <name>.service.ts # Business logic (@Service)
601
+ ├── <name>.repository.ts # Data access (@Repository)
602
+ ├── <name>.dto.ts # Request/response schemas (Zod)
603
+ ├── <name>.entity.ts # Domain entity (optional)
604
+ └── <name>.module.ts # Module definition (implements AppModule)
605
+ \`\`\`
606
+ `:t===`cqrs`?`\`\`\`
607
+ <name>/
608
+ ├── commands/ # Write operations
609
+ │ ├── create-<name>.command.ts
610
+ │ └── create-<name>.handler.ts
611
+ ├── queries/ # Read operations
612
+ │ ├── get-<name>.query.ts
613
+ │ └── get-<name>.handler.ts
614
+ ├── events/ # Domain events
615
+ │ └── <name>-created.event.ts
616
+ ├── <name>.controller.ts # HTTP routes
617
+ ├── <name>.repository.ts # Data access
618
+ └── <name>.module.ts # Module definition (implements AppModule)
619
+ \`\`\`
620
+ `:t===`rest`?`\`\`\`
621
+ <name>/
622
+ ├── <name>.controller.ts # HTTP routes (@Controller)
623
+ ├── <name>.service.ts # Business logic (@Service)
624
+ ├── <name>.dto.ts # Request/response schemas (Zod)
625
+ └── <name>.module.ts # Module definition (implements AppModule)
626
+ \`\`\`
627
+ `:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
628
+
629
+ ## Checklist: Adding a Feature
630
+
631
+ ### New Module (Recommended)
632
+
633
+ Use the CLI generator for consistency:
634
+
635
+ \`\`\`bash
636
+ kick g module <name> # Generate full module
637
+ # or
638
+ kick g scaffold <name> <fields> # Generate CRUD from fields
639
+ \`\`\`
640
+
641
+ Then:
642
+ - [ ] Review generated files in \`src/modules/<name>/\`
643
+ - [ ] Verify module is registered in \`src/modules/index.ts\`
644
+ - [ ] Update DTOs in \`<name>.dto.ts\` if needed
645
+ - [ ] Implement business logic in \`<name>.service.ts\`
646
+ - [ ] Run \`kick dev\` to test with HMR
647
+ - [ ] Write tests in \`<name>.test.ts\`
648
+
649
+ ### Manual Controller
650
+
651
+ If not using generators:
652
+
653
+ - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
654
+ - [ ] Add \`@Controller()\` decorator
655
+ - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
656
+ - [ ] Create module file implementing \`AppModule\` with \`routes()\` returning \`{ path, router: buildRoutes(Controller), controller }\`
657
+ - [ ] Register module in \`src/modules/index.ts\` (\`AppModuleClass[]\` array)
658
+ - [ ] Test with \`kick dev\`
659
+
660
+ ### Manual Service
661
+
662
+ - [ ] Create \`src/modules/<name>/<name>.service.ts\`
663
+ - [ ] Add \`@Service()\` decorator
664
+ - [ ] Inject dependencies with \`@Autowired()\`
665
+ - [ ] Inject via \`@Autowired()\` where needed
666
+ - [ ] Write unit tests
667
+
668
+ ### New Middleware
669
+
670
+ - [ ] Create \`src/middleware/<name>.middleware.ts\`
671
+ - [ ] Export middleware function (Express format)
672
+ - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
673
+ - [ ] Test with sample requests
674
+
675
+ ### Adding a Package
676
+
677
+ Use \`kick add\` to install KickJS packages with correct peer dependencies:
678
+
679
+ - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
680
+ - [ ] Follow package-specific setup in terminal output
681
+ - [ ] Update \`src/index.ts\` to register adapter (if needed)
682
+ - [ ] Configure environment variables in \`.env\`
683
+ - [ ] Test integration with \`kick dev\`
684
+
685
+ ## Common Tasks
686
+
687
+ ### Generate CRUD Module
688
+
689
+ \`\`\`bash
690
+ kick g scaffold user name:string email:string:optional age:number
691
+ \`\`\`
692
+
693
+ Append \`:optional\` for optional fields (shell-safe, no quoting needed).
694
+ Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
695
+
696
+ This creates a full CRUD module with:
697
+ - Controller with GET, POST, PUT, DELETE routes
698
+ - Service with business logic
699
+ - Repository with data access
700
+ - DTOs with Zod validation
701
+
702
+ ### Add Authentication
703
+
704
+ \`\`\`bash
705
+ kick add auth
706
+ \`\`\`
707
+
708
+ Then configure in \`src/index.ts\`:
709
+
710
+ \`\`\`ts
711
+ import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
712
+
713
+ bootstrap({
714
+ modules,
715
+ adapters: [
716
+ AuthAdapter({
717
+ strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
718
+ }),
719
+ ],
720
+ })
721
+ \`\`\`
722
+
723
+ ### Add Database (Prisma)
724
+
725
+ \`\`\`bash
726
+ kick add prisma
727
+ ${n} install prisma @prisma/client
728
+ npx prisma init
729
+ # Edit prisma/schema.prisma
730
+ npx prisma migrate dev --name init
731
+ kick g module user --repo prisma
732
+ \`\`\`
733
+
734
+ ### Add WebSocket Support
735
+
736
+ \`\`\`bash
737
+ kick add ws
738
+ \`\`\`
739
+
740
+ Then add adapter in \`src/index.ts\`:
741
+
742
+ \`\`\`ts
743
+ import { WsAdapter } from '@forinda/kickjs-ws'
744
+
745
+ bootstrap({
746
+ modules,
747
+ adapters: [WsAdapter()],
748
+ })
749
+ \`\`\`
750
+
751
+ Create WebSocket controller:
752
+
753
+ \`\`\`bash
754
+ kick g controller chat --ws
755
+ \`\`\`
756
+
757
+ ## Testing Guidelines
758
+
759
+ All tests use Vitest:
760
+
761
+ \`\`\`ts
762
+ import { describe, it, expect, beforeEach } from 'vitest'
763
+ import { Container } from '@forinda/kickjs'
764
+ import { createTestApp } from '@forinda/kickjs-testing'
765
+
766
+ describe('UserController', () => {
767
+ it('should return users', async () => {
768
+ // Container.create() — isolated DI state per test, never new Container()
769
+ // and never getInstance().reset() (both leak registrations between tests).
770
+ const container = Container.create()
771
+ const app = await createTestApp([UserModule], { container })
772
+ const res = await app.get('/users')
773
+
774
+ expect(res.status).toBe(200)
775
+ expect(res.body).toHaveProperty('users')
776
+ })
777
+ })
778
+ \`\`\`
779
+
780
+ Run tests:
781
+ - \`${n} run test\` — run all tests once
782
+ - \`${n} run test:watch\` — watch mode
783
+ - Individual file: \`${n} run test src/modules/user/user.test.ts\`
784
+
785
+ ## Environment Variables
786
+
787
+ Schema is declared in \`src/config/index.ts\` (extends the base
788
+ \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
789
+ with kickjs at module load. \`src/index.ts\` imports it via
790
+ \`import './config'\` **before** \`bootstrap()\` so the cache is populated
791
+ in time for DI. Add new keys to the schema, drop their values into
792
+ \`.env\`, and they're typed everywhere.
793
+
794
+ Access patterns:
795
+
796
+ 1. **@Value() decorator** (recommended for known-at-construction keys):
797
+ \`\`\`ts
798
+ @Value('DATABASE_URL')
799
+ private dbUrl!: string
800
+ \`\`\`
801
+
802
+ 2. **ConfigService** (recommended for dynamic / method-scoped access):
803
+ \`\`\`ts
804
+ @Autowired()
805
+ private config!: ConfigService
806
+
807
+ const port = this.config.get('PORT') // typed: number
808
+ \`\`\`
809
+
810
+ 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
811
+ \`\`\`ts
812
+ import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
813
+
814
+ const env = loadEnv(schema) // Parse + validate all vars
815
+ const port = getEnv('PORT') // Single value lookup
816
+ reloadEnv() // Re-read .env from disk
817
+ resetEnvCache() // Full reset (for tests)
818
+ \`\`\`
819
+
820
+ 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
821
+ coercion and the typed \`KickEnv\` registry.
822
+
823
+ > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
824
+ > If the schema is not registered before DI runs, \`config.get()\`
825
+ > returns \`undefined\` for user keys (the base shape only) and
826
+ > \`@Value()\` only works because of its raw \`process.env\` fallback —
827
+ > Zod coercion + schema defaults are silently skipped.
828
+
829
+ ## Standalone Utilities (No DI Required)
830
+
831
+ These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
832
+
833
+ | Utility | Import | Example |
834
+ |---------|--------|---------|
835
+ | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
836
+ | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
837
+ | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
838
+ | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
839
+ | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
840
+ | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
841
+ | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
842
+ | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
843
+ | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
844
+
845
+ ## Key Decorators
846
+
847
+ ### HTTP Routes
848
+ | Decorator | Purpose |
849
+ |-----------|---------|
850
+ | \`@Controller()\` | Define route prefix |
851
+ | \`@Get('/'), @Post('/')\` | HTTP method handlers |
852
+ | \`@Middleware(fn)\` | Attach middleware |
853
+ | \`@Public()\` | Skip auth (requires auth adapter) |
854
+ | \`@Roles('admin')\` | Role-based access |
855
+
856
+ ### Dependency Injection
857
+ | Decorator | Purpose |
858
+ |-----------|---------|
859
+ | \`AppModule\` interface | Define feature module (implements \`routes()\`) |
860
+ | \`@Service()\` | Register singleton service |
861
+ | \`@Repository()\` | Register repository |
862
+ | \`@Autowired()\` | Property injection |
863
+ | \`@Inject('token')\` | Token-based injection |
864
+ | \`@Value('VAR')\` | Inject env variable |
865
+
866
+ ### Context Decorators
867
+
868
+ Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
869
+ Use this **instead of \`@Middleware()\`** when the middleware's only output
870
+ is a value other code reads off \`ctx\`.
871
+
872
+ | Concept | Where it lives |
873
+ |---------|----------------|
874
+ | \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
875
+ | Method/class decorator | \`@LoadX\` on a controller method/class |
876
+ | Module hook | \`AppModule.contributors?(): ContributorRegistration[]\` |
877
+ | Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
878
+ | Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
879
+ | Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
880
+
881
+ Precedence high → low: **method > class > module > adapter > global**.
882
+ Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
883
+ fast). The \`onError\` hook is async-permitted.
884
+
885
+ Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
886
+
887
+ ${t===`cqrs`?`### Background Jobs
888
+ | Decorator | Purpose |
889
+ |-----------|---------|
890
+ | \`@Job('name')\` | Queue job handler |
891
+ | \`@Process('queue')\` | Queue processor |
892
+ | \`@Cron('0 * * * *')\` | Cron schedule |
893
+ | \`@WsController()\` | WebSocket controller |
894
+
895
+ `:``}## Common Pitfalls
896
+
897
+ 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
898
+ 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
899
+ 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()\`
900
+ 4. **Routes not found** — Check controller path and module registration
901
+ 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.
902
+ 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
903
+ 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.
904
+ 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.
905
+ 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).
906
+ 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({ ... })\`.
907
+ 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\`.
908
+
909
+ ## CLI Commands Reference
910
+
911
+ | Command | Description |
912
+ |---------|-------------|
913
+ | \`kick dev\` | Dev server with HMR |
914
+ | \`kick dev:debug\` | Dev server with debugger |
915
+ | \`kick build\` | Production build |
916
+ | \`kick start\` | Run production build |
917
+ | \`kick g module <names...>\` | Generate one or more modules |
918
+ | \`kick g scaffold <name> <fields>\` | Generate CRUD |
919
+ | \`kick g controller <name>\` | Generate controller |
920
+ | \`kick g service <name>\` | Generate service |
921
+ | \`kick g middleware <name>\` | Generate middleware |
922
+ | \`kick add <package>\` | Add KickJS package |
923
+ | \`kick add --list\` | List available packages |
924
+ | \`kick rm module <names...>\` | Remove one or more modules |
925
+
926
+ > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
927
+ > \`\`\`bash
928
+ > kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
929
+ > \`\`\`
930
+
931
+ ## Learn More
932
+
933
+ - [KickJS Docs](https://forinda.github.io/kick-js/)
934
+ - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
935
+ - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
936
+ - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
937
+ - [Testing](https://forinda.github.io/kick-js/api/testing.html)
938
+ `}function rt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
939
+
940
+ This file is the agent-facing **skills index** for KickJS work in this
941
+ repo. Each block below is a short, rigid workflow keyed to a specific
942
+ trigger ("user wants to add a module", "tests are leaking state", etc.).
943
+
944
+ - Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
945
+ - Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
946
+ - **This file** → step-by-step recipes the agent should *execute*.
947
+
948
+ Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
949
+
950
+ ---
951
+
952
+ ## Skill: add-module
953
+
954
+ \`\`\`yaml
955
+ name: kickjs-add-module
956
+ description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
957
+ \`\`\`
958
+
959
+ **Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
960
+
961
+ **Steps**:
962
+ 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
963
+ 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
964
+ 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
965
+ 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
966
+ 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
967
+
968
+ **Red flags** (stop and ask):
969
+ - File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
970
+ - Module not registered in \`src/modules/index.ts\`.
971
+ - \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
972
+
973
+ ---
974
+
975
+ ## Skill: add-adapter
976
+
977
+ \`\`\`yaml
978
+ name: kickjs-add-adapter
979
+ description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
980
+ \`\`\`
981
+
982
+ **Steps**:
983
+ 1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
984
+ 2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
985
+ 3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
986
+ 4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
987
+ 5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
988
+
989
+ **Red flags**:
990
+ - Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
991
+ - Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
992
+
993
+ ---
994
+
995
+ ## Skill: write-controller-test
996
+
997
+ \`\`\`yaml
998
+ name: kickjs-write-controller-test
999
+ description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
1000
+ \`\`\`
1001
+
1002
+ **Template** (copy/paste, adjust):
1003
+
1004
+ \`\`\`ts
1005
+ import { describe, it, expect } from 'vitest'
1006
+ import { Container } from '@forinda/kickjs'
1007
+ import { createTestApp } from '@forinda/kickjs-testing'
1008
+
1009
+ describe('UserController', () => {
1010
+ it('returns users', async () => {
1011
+ const container = Container.create() // isolated DI per test
1012
+ const app = await createTestApp([UserModule], { container })
1013
+ const res = await app.get('/users')
1014
+ expect(res.status).toBe(200)
1015
+ })
1016
+ })
1017
+ \`\`\`
1018
+
1019
+ **Red flags**:
1020
+ - \`new Container()\` — wrong; use \`Container.create()\`.
1021
+ - \`Container.getInstance().reset()\` — wrong; same fix.
1022
+ - Sharing a container across \`it()\` blocks — leaks registrations.
1023
+
1024
+ ---
1025
+
1026
+ ## Skill: env-wiring-check
1027
+
1028
+ \`\`\`yaml
1029
+ name: kickjs-env-wiring-check
1030
+ description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
1031
+ \`\`\`
1032
+
1033
+ **Diagnosis**:
1034
+ 1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
1035
+ 2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
1036
+ 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).
1037
+
1038
+ **Fix**: add the key to the schema; ensure both side-effect imports above are present.
1039
+
1040
+ ---
1041
+
1042
+ ## Skill: bootstrap-export
1043
+
1044
+ \`\`\`yaml
1045
+ name: kickjs-bootstrap-export
1046
+ description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
1047
+ \`\`\`
1048
+
1049
+ **Check** \`src/index.ts\`'s last line:
1050
+
1051
+ \`\`\`ts
1052
+ // CORRECT
1053
+ export const app = await bootstrap({ ... })
1054
+
1055
+ // WRONG (HMR degrades to full restart, createTestApp loses the handle)
1056
+ await bootstrap({ ... })
1057
+ \`\`\`
1058
+
1059
+ The Vite plugin imports the named \`app\` symbol; testing helpers do too.
1060
+
1061
+ ---
1062
+
1063
+ ## Skill: thin-entry-file
1064
+
1065
+ \`\`\`yaml
1066
+ name: kickjs-thin-entry-file
1067
+ description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
1068
+ \`\`\`
1069
+
1070
+ **Refactor target**:
1071
+
1072
+ \`\`\`ts
1073
+ // src/modules/index.ts
1074
+ export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
1075
+
1076
+ // src/middleware/index.ts
1077
+ export const middleware = [helmet(), cors(), requestId(), ...]
1078
+
1079
+ // src/plugins/index.ts
1080
+ export const plugins = [MetricsPlugin(), ...]
1081
+
1082
+ // src/adapters/index.ts
1083
+ export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
1084
+
1085
+ // src/index.ts — stays small
1086
+ import 'reflect-metadata'
1087
+ import './config'
1088
+ import { bootstrap } from '@forinda/kickjs'
1089
+ import { modules } from './modules'
1090
+ import { middleware } from './middleware'
1091
+ import { plugins } from './plugins'
1092
+ import { adapters } from './adapters'
1093
+ export const app = await bootstrap({ modules, middleware, plugins, adapters })
1094
+ \`\`\`
1095
+
1096
+ **Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
1097
+
1098
+ ---
1099
+
1100
+ ## Skill: context-contributor
1101
+
1102
+ \`\`\`yaml
1103
+ name: kickjs-context-contributor
1104
+ description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
1105
+ \`\`\`
1106
+
1107
+ **Pattern** (HTTP — most common):
1108
+
1109
+ \`\`\`ts
1110
+ import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
1111
+
1112
+ const LoadTenant = defineHttpContextDecorator({
1113
+ key: 'tenant',
1114
+ deps: { repo: TENANT_REPO },
1115
+ resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
1116
+ })
1117
+
1118
+ const LoadProject = defineHttpContextDecorator({
1119
+ key: 'project',
1120
+ dependsOn: ['tenant'],
1121
+ resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
1122
+ })
1123
+
1124
+ @LoadTenant
1125
+ @LoadProject
1126
+ @Get('/projects/:id')
1127
+ getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
1128
+ \`\`\`
1129
+
1130
+ 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\`).
1131
+
1132
+ Precedence high → low: **method > class > module > adapter > global**.
1133
+ Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
1134
+
1135
+ **Critical rules — all stem from the same shared-via-ALS instance model**:
1136
+ - Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
1137
+ - **\`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.
1138
+ - \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
1139
+ - Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
1140
+ - **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.
1141
+
1142
+ **Don't use this for**: response short-circuit, stream mutation, or
1143
+ pre-route-matching work — keep \`@Middleware()\` for those.
1144
+
1145
+ ---
1146
+
1147
+ ## Skill: refresh-agent-docs
1148
+
1149
+ \`\`\`yaml
1150
+ name: kickjs-refresh-agent-docs
1151
+ description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
1152
+ \`\`\`
1153
+
1154
+ **Steps**:
1155
+ 1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
1156
+ 2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
1157
+ 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.
1158
+ 4. Commit as \`docs(agents): sync from CLI vX.Y\`.
1159
+
1160
+ ---
1161
+
1162
+ ## Skill: deny-list
1163
+
1164
+ \`\`\`yaml
1165
+ name: kickjs-deny-list
1166
+ description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
1167
+ \`\`\`
1168
+
1169
+ - \`class implements AppAdapter\` → use \`defineAdapter()\`.
1170
+ - \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
1171
+ - \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
1172
+ - \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
1173
+ - DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
1174
+ - \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
1175
+ - Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
1176
+
1177
+ ---
1178
+
1179
+ ## Learn More
1180
+
1181
+ - [KickJS Docs](https://forinda.github.io/kick-js/)
1182
+ - [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
1183
+ - [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
1184
+ - [Testing](https://forinda.github.io/kick-js/api/testing.html)
1185
+ `}const it=y(ce(import.meta.url)),at=JSON.parse(_(b(it,`..`,`package.json`),`utf-8`)),ot=`^${at.version}`;async function st(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:i=`rest`,defaultRepo:a=`inmemory`,packages:o=[]}=e,s=n,c=e=>console.log(` ${e}`);if(console.log(`\n Creating KickJS project: ${t}\n`),await A(b(s,`package.json`),Le(t,i,ot,o)),await A(b(s,`vite.config.ts`),Re()),await A(b(s,`tsconfig.json`),ze()),await A(b(s,`.prettierrc`),Be()),await A(b(s,`.editorconfig`),Ve()),await A(b(s,`.gitignore`),He()),await A(b(s,`.gitattributes`),Ue()),await A(b(s,`.env`),We()),await A(b(s,`.env.example`),Ge()),await A(b(s,`src/config/index.ts`),Ye()),await A(b(s,`src/index.ts`),qe(t,i,at.version,o)),await A(b(s,`src/modules/index.ts`),Je()),await A(b(s,`src/modules/hello/hello.service.ts`),Xe()),await A(b(s,`src/modules/hello/hello.controller.ts`),Ze()),await A(b(s,`src/modules/hello/hello.module.ts`),Qe()),await A(b(s,`kick.config.ts`),$e(i,a,r)),await A(b(s,`vitest.config.ts`),Ke()),await A(b(s,`README.md`),et(t,i,r)),await A(b(s,`CLAUDE.md`),tt(t,i,r)),await A(b(s,`AGENTS.md`),nt(t,i,r)),await A(b(s,`kickjs-skills.md`),rt(t,i,r)),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{w(`${r} install`,{cwd:s,stdio:`inherit`}),console.log(`
1186
+ Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-C6ZfoYTC.mjs`).then(e=>e.n);await e({cwd:s,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{w(`git init`,{cwd:s,stdio:`pipe`}),w(`git branch -M main`,{cwd:s,stdio:`pipe`}),w(`git add -A`,{cwd:s,stdio:`pipe`}),w(`git commit -m "chore: initial commit from kick new"`,{cwd:s,stdio:`pipe`}),c(`Git repository initialized`)}catch{c(`Warning: git init failed (git may not be installed)`)}console.log(`
1187
+ Project scaffolded successfully!`),console.log();let l=s!==process.cwd();c(`Next steps:`),l&&c(` cd ${t}`),e.installDeps||c(` ${r} install`);let u={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`};c(` ${u[i]??u.rest}`),c(` kick dev`),c(``),c(`Commands:`),c(` kick dev Start dev server with Vite HMR`),c(` kick build Production build via Vite`),c(` kick start Run production build`),c(``),c(`Generators:`),c(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),c(` kick g scaffold <n> <f..> CRUD module from field definitions`),c(` kick g controller <name> Standalone controller`),c(` kick g service <name> @Service() class`),c(` kick g middleware <name> Express middleware`),c(` kick g guard <name> Route guard (auth, roles, etc.)`),c(` kick g adapter <name> AppAdapter with lifecycle hooks`),c(` kick g dto <name> Zod DTO schema`),i===`cqrs`&&c(` kick g job <name> Queue job processor`),c(` kick g config Generate kick.config.ts`),c(``),c(`Add packages:`),c(` kick add <pkg> Install a KickJS package + peers`),c(` kick add --list Show all available packages`),c(``),c(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),c(``)}const ct={GET:O.green,POST:O.cyan,PUT:O.yellow,PATCH:O.magenta,DELETE:O.red};function lt(e){return(ct[e]??O.dim)(e.padEnd(7))}function ut(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return O.red(t);case`WARNING`:return O.yellow(t);case`INFO`:return O.blue(O.dim(t));default:return t}}O.green(`✓`),O.red(`✖`),O.yellow(`⚠`),O.blue(`ℹ`);function dt(e){D.intro(O.bgCyan(O.black(` ${e} `)))}function P(e){D.outro(e)}function ft(e){D.isCancel(e)&&(D.cancel(`Operation cancelled.`),process.exit(0))}async function pt(e){let t=await D.text(e);return ft(t),t}async function mt(e){let t=await D.select(e);return ft(t),t}async function ht(e){let t=await D.multiselect(e);return ft(t),t}async function F(e){let t=await D.confirm(e);return ft(t),t}function gt(){return D.spinner()}const I=D.log,_t={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`Authentication — JWT, API key, and custom strategies`},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function L(e,t=process.cwd()){let n=t;for(;;){if(h(S(n,e)))return n;let t=y(n);if(t===n)return null;n=t}}function vt(){return L(`pnpm-lock.yaml`)?`pnpm`:L(`yarn.lock`)?`yarn`:L(`bun.lockb`)||L(`bun.lock`)?`bun`:L(`package-lock.json`)?`npm`:null}function yt(){let e=process.cwd();for(;e;){let t=S(e,`package.json`);if(h(t))try{let e=JSON.parse(_(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(i.includes(t))return t}}catch{}let n=y(e);if(n===e)return null;e=n}return null}async function bt(e){if(e&&i.includes(e))return{pm:e,source:`flag`};let t=await r(process.cwd());if(t?.packageManager&&i.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=yt();if(n)return{pm:n,source:`package.json`};let a=vt();return a?{pm:a,source:`lockfile`}:{pm:`npm`,source:`default`}}async function xt(e){let{pm:t}=await bt(e);return t}function St(e=!1){let t=Object.entries(_t),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
1188
+ Core packages (always installed by \`kick new\`):
1189
+ `);for(let e of r)console.log(a(e));if(e){console.log(`
1190
+ Optional packages (add as needed):
1191
+ `);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
1192
+ Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function Ct(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{St(!!e.all)})}function wt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){St(!!t.all);return}let{pm:n,source:r}=await bt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=_t[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
1193
+ `),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{w(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{w(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
1194
+ `)}})}const Tt=[{value:`auth`,label:`Auth`,hint:`JWT, OAuth, API keys`},{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function Et(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{dt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await pt({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=S(`.`),e=ie(r)):r=S(t.directory||e),h(r)){let i=ee(r);if(i.length>0){if(t.force)I.warn(`Clearing existing files in ${r}`);else if(n){I.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),P(`Aborted.`);return}else{I.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)I.message(` - ${e}`);if(i.length>5&&I.message(` ... and ${i.length-5} more`),!await F({message:O.red(`Remove all existing files and proceed?`),initialValue:!1})){P(`Aborted.`);return}}for(let e of i)te(S(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await mt({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let a=t.pm;a||=n?await xt(void 0):await mt({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let o=t.repo;o||(n?o=`inmemory`:(o=await mt({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),o===`custom`&&(o=await pt({message:`Custom repository name`,defaultValue:`custom`}))));let s;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();s=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else s=n?[]:await ht({message:`Select packages to include`,options:[...Tt],required:!1});let c;c=t.git===void 0?n?!0:await F({message:`Initialize git repository?`,initialValue:!0}):t.git;let l;l=t.install===void 0?n?!0:await F({message:`Install dependencies?`,initialValue:!0}):t.install,await st({name:e,directory:r,packageManager:a,initGit:c,installDeps:l,template:i,defaultRepo:o,packages:s}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${a} dev`)}`)})}function R(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function z(e){let t=R(e);return t.charAt(0).toLowerCase()+t.slice(1)}function B(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function V(e){return he.plural(e)}function Dt(e){return he.plural(e)}function Ot(e){return B(e).replace(/-/g,`_`)}function kt(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=R(e.name),i=z(e.name),a=B(e.name),o=Ot(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=V(a);s.pluralKebab=e,s.pluralPascal=R(e),s.pluralCamel=z(e)}return s}function At(e,t){return S(e.cwd,t)}async function jt(e){return import(C(e).href)}const Mt=new Map;async function Nt(e){let t=Mt.get(e);if(t)return t;let n=Pt(e);return Mt.set(e,n),n}async function Pt(e){let t=S(e,`package.json`);if(!h(t))return{generators:[],loaded:[],failed:[]};let n=Ft(JSON.parse(await T(t,`utf-8`))),r=p(S(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await T(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=S(y(t),s);if(!h(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await jt(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!It(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function Ft(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 It(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Lt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Bt(r.spec,r.source,e,n);let i=zt(await Nt(n),e.generatorName);return i?Bt(i.spec,i.source,e,n):null}async function Rt(e,t=[]){let n=await Nt(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 zt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Bt(e,t,n,r){let i=kt({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=At(i,e.path);await A(t,e.content),o.push(t)}return{files:o,source:t}}const Vt={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function Ht(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ut(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function Wt(e){return Vt[e]??Ht(e)}function Gt(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]??`${Ht(n)}${e}Repository`,repoFile:i[n]??`${Ut(n)}-${t}`}}function Kt(e){let{pascal:t,kebab:n,plural:r=``,repo:i}=e,{repoClass:a,repoFile:o}=Gt(t,n,i);return`/**
1195
+ * ${t} Module
1196
+ *
1197
+ * Self-contained feature module following Domain-Driven Design (DDD).
1198
+ * Registers dependencies in the DI container and declares HTTP routes.
1199
+ *
1200
+ * Structure:
1201
+ * presentation/ — HTTP controllers (entry points)
1202
+ * application/ — Use cases (orchestration) and DTOs (validation)
1203
+ * domain/ — Entities, value objects, repository interfaces, domain services
1204
+ * infrastructure/ — Repository implementations (currently ${Wt(i)})
1205
+ */
1206
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1207
+ import { buildRoutes } from '@forinda/kickjs'
1208
+ import { ${t.toUpperCase()}_REPOSITORY } from './domain/repositories/${n}.repository'
1209
+ import { ${a} } from './infrastructure/repositories/${o}.repository'
1210
+ import { ${t}Controller } from './presentation/${n}.controller'
1211
+
1212
+ // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
1213
+ import.meta.glob(
1214
+ ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
1215
+ { eager: true },
1216
+ )
1217
+
1218
+ export class ${t}Module implements AppModule {
1219
+ /**
1220
+ * Register module dependencies in the DI container.
1221
+ * Bind repository interface tokens to their implementations here.
1222
+ * Currently wired to ${Wt(i)}. To swap implementations, change the factory target.
1223
+ */
1224
+ register(container: Container): void {
1225
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1226
+ container.resolve(${a}),
1227
+ )
1228
+ }
1229
+
1230
+ /**
1231
+ * Declare HTTP routes for this module.
1232
+ * The path is prefixed with the global apiPrefix and version (e.g. /api/v1/${r}).
1233
+ * Passing 'controller' enables automatic OpenAPI spec generation via SwaggerAdapter.
1234
+ */
1235
+ routes(): ModuleRoutes {
1236
+ return {
1237
+ path: '/${r}',
1238
+ router: buildRoutes(${t}Controller),
1239
+ controller: ${t}Controller,
1240
+ }
1241
+ }
1242
+ }
1243
+ `}function qt(e){let{pascal:t,kebab:n,plural:r=``,repo:i}=e,{repoClass:a,repoFile:o}=Gt(t,n,i);return`/**
1244
+ * ${t} Module
1245
+ *
1246
+ * REST module with a flat folder structure.
1247
+ * Controller delegates to service, service wraps the repository.
1248
+ *
1249
+ * Structure:
1250
+ * ${n}.controller.ts — HTTP routes (CRUD)
1251
+ * ${n}.service.ts — Business logic
1252
+ * ${n}.repository.ts — Repository interface
1253
+ * ${o}.repository.ts — Repository implementation
1254
+ * dtos/ — Request/response schemas
1255
+ */
1256
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1257
+ import { buildRoutes } from '@forinda/kickjs'
1258
+ import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
1259
+ import { ${a} } from './${o}.repository'
1260
+ import { ${t}Controller } from './${n}.controller'
1261
+
1262
+ // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
1263
+ import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })
1264
+
1265
+ export class ${t}Module implements AppModule {
1266
+ register(container: Container): void {
1267
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1268
+ container.resolve(${a}),
1269
+ )
1270
+ }
1271
+
1272
+ routes(): ModuleRoutes {
1273
+ return {
1274
+ path: '/${r}',
1275
+ router: buildRoutes(${t}Controller),
1276
+ controller: ${t}Controller,
1277
+ }
1278
+ }
1279
+ }
1280
+ `}function Jt(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1281
+ import { buildRoutes } from '@forinda/kickjs'
1282
+ import { ${t}Controller } from './${n}.controller'
1283
+
1284
+ export class ${t}Module implements AppModule {
1285
+ routes(): ModuleRoutes {
1286
+ return {
1287
+ path: '/${r}',
1288
+ router: buildRoutes(${t}Controller),
1289
+ controller: ${t}Controller,
1290
+ }
1291
+ }
1292
+ }
1293
+ `}function Yt(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'
1294
+ import { ApiTags } from '@forinda/kickjs-swagger'
1295
+ import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
1296
+ import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
1297
+ import { List${i}UseCase } from '../application/use-cases/list-${r}.use-case'
1298
+ import { Update${t}UseCase } from '../application/use-cases/update-${n}.use-case'
1299
+ import { Delete${t}UseCase } from '../application/use-cases/delete-${n}.use-case'
1300
+ import { create${t}Schema } from '../application/dtos/create-${n}.dto'
1301
+ import { update${t}Schema } from '../application/dtos/update-${n}.dto'
1302
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from '../constants'
1303
+
1304
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
1305
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1306
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1307
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
1308
+
1309
+ @Controller()
1310
+ export class ${t}Controller {
1311
+ @Autowired() private readonly create${t}UseCase!: Create${t}UseCase
1312
+ @Autowired() private readonly get${t}UseCase!: Get${t}UseCase
1313
+ @Autowired() private readonly list${i}UseCase!: List${i}UseCase
1314
+ @Autowired() private readonly update${t}UseCase!: Update${t}UseCase
1315
+ @Autowired() private readonly delete${t}UseCase!: Delete${t}UseCase
1316
+
1317
+ @Get('/')
1318
+ @ApiTags('${t}')
1319
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
1320
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1321
+ return ctx.paginate(
1322
+ (parsed) => this.list${i}UseCase.execute(parsed),
1323
+ ${t.toUpperCase()}_QUERY_CONFIG,
1324
+ )
1325
+ }
1326
+
1327
+ @Get('/:id')
1328
+ @ApiTags('${t}')
1329
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
1330
+ const result = await this.get${t}UseCase.execute(ctx.params.id)
1331
+ if (!result) return ctx.notFound('${t} not found')
1332
+ ctx.json(result)
1333
+ }
1334
+
1335
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
1336
+ @ApiTags('${t}')
1337
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
1338
+ const result = await this.create${t}UseCase.execute(ctx.body)
1339
+ ctx.created(result)
1340
+ }
1341
+
1342
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
1343
+ @ApiTags('${t}')
1344
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
1345
+ const result = await this.update${t}UseCase.execute(ctx.params.id, ctx.body)
1346
+ ctx.json(result)
1347
+ }
1348
+
1349
+ @Delete('/:id')
1350
+ @ApiTags('${t}')
1351
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
1352
+ await this.delete${t}UseCase.execute(ctx.params.id)
1353
+ ctx.noContent()
1354
+ }
1355
+ }
1356
+ `}function Xt(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'
1357
+ import { ApiTags } from '@forinda/kickjs-swagger'
1358
+ import { ${t}Service } from './${n}.service'
1359
+ import { create${t}Schema } from './dtos/create-${n}.dto'
1360
+ import { update${t}Schema } from './dtos/update-${n}.dto'
1361
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
1362
+
1363
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
1364
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1365
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1366
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
1367
+
1368
+ @Controller()
1369
+ export class ${t}Controller {
1370
+ @Autowired() private readonly ${r}Service!: ${t}Service
1371
+
1372
+ @Get('/')
1373
+ @ApiTags('${t}')
1374
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
1375
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1376
+ return ctx.paginate(
1377
+ (parsed) => this.${r}Service.findPaginated(parsed),
1378
+ ${t.toUpperCase()}_QUERY_CONFIG,
1379
+ )
1380
+ }
1381
+
1382
+ @Get('/:id')
1383
+ @ApiTags('${t}')
1384
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
1385
+ const result = await this.${r}Service.findById(ctx.params.id)
1386
+ if (!result) return ctx.notFound('${t} not found')
1387
+ ctx.json(result)
1388
+ }
1389
+
1390
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
1391
+ @ApiTags('${t}')
1392
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
1393
+ const result = await this.${r}Service.create(ctx.body)
1394
+ ctx.created(result)
1395
+ }
1396
+
1397
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
1398
+ @ApiTags('${t}')
1399
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
1400
+ const result = await this.${r}Service.update(ctx.params.id, ctx.body)
1401
+ ctx.json(result)
1402
+ }
1403
+
1404
+ @Delete('/:id')
1405
+ @ApiTags('${t}')
1406
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
1407
+ await this.${r}Service.delete(ctx.params.id)
1408
+ ctx.noContent()
1409
+ }
1410
+ }
1411
+ `}function Zt(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
1412
+
1413
+ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
1414
+ filterable: ['name'],
1415
+ sortable: ['name', 'createdAt'],
1416
+ searchable: ['name'],
1417
+ }
1418
+ `}function Qt(e){let{pascal:t}=e;return`import { z } from 'zod'
1419
+
1420
+ /**
1421
+ * Create ${t} DTO — Zod schema for validating POST request bodies.
1422
+ * This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
1423
+ * It also generates OpenAPI request body docs when SwaggerAdapter is used.
1424
+ *
1425
+ * Add more fields as needed. Supported Zod types:
1426
+ * z.string(), z.number(), z.boolean(), z.enum([...]),
1427
+ * z.array(), z.object(), .optional(), .default(), .transform()
1428
+ */
1429
+ export const create${t}Schema = z.object({
1430
+ name: z.string().min(1, 'Name is required').max(200),
1431
+ })
1432
+
1433
+ export type Create${t}DTO = z.infer<typeof create${t}Schema>
1434
+ `}function $t(e){let{pascal:t}=e;return`import { z } from 'zod'
1435
+
1436
+ export const update${t}Schema = z.object({
1437
+ name: z.string().min(1).max(200).optional(),
1438
+ })
1439
+
1440
+ export type Update${t}DTO = z.infer<typeof update${t}Schema>
1441
+ `}function en(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
1442
+ id: string
1443
+ name: string
1444
+ createdAt: string
1445
+ updatedAt: string
1446
+ }
1447
+ `}function tn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
1448
+ * Create ${t} Use Case
1449
+ *
1450
+ * Application layer — orchestrates a single business operation.
1451
+ * Use cases are thin: validate input (via DTO), call domain/repo, return response.
1452
+ * Keep business rules in the domain service, not here.
1453
+ */
1454
+ import { Service, Inject } from '@forinda/kickjs'
1455
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1456
+ import type { Create${t}DTO } from '../dtos/create-${n}.dto'
1457
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1458
+
1459
+ @Service()
1460
+ export class Create${t}UseCase {
1461
+ constructor(
1462
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1463
+ ) {}
1464
+
1465
+ async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1466
+ return this.repo.create(dto)
1467
+ }
1468
+ }
1469
+ `},{file:`get-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1470
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1471
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1472
+
1473
+ @Service()
1474
+ export class Get${t}UseCase {
1475
+ constructor(
1476
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1477
+ ) {}
1478
+
1479
+ async execute(id: string): Promise<${t}ResponseDTO | null> {
1480
+ return this.repo.findById(id)
1481
+ }
1482
+ }
1483
+ `},{file:`list-${r}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1484
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1485
+ import type { ParsedQuery } from '@forinda/kickjs'
1486
+
1487
+ @Service()
1488
+ export class List${i}UseCase {
1489
+ constructor(
1490
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1491
+ ) {}
1492
+
1493
+ async execute(parsed: ParsedQuery) {
1494
+ return this.repo.findPaginated(parsed)
1495
+ }
1496
+ }
1497
+ `},{file:`update-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1498
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1499
+ import type { Update${t}DTO } from '../dtos/update-${n}.dto'
1500
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1501
+
1502
+ @Service()
1503
+ export class Update${t}UseCase {
1504
+ constructor(
1505
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1506
+ ) {}
1507
+
1508
+ async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1509
+ return this.repo.update(id, dto)
1510
+ }
1511
+ }
1512
+ `},{file:`delete-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1513
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1514
+
1515
+ @Service()
1516
+ export class Delete${t}UseCase {
1517
+ constructor(
1518
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1519
+ ) {}
1520
+
1521
+ async execute(id: string): Promise<void> {
1522
+ await this.repo.delete(id)
1523
+ }
1524
+ }
1525
+ `}]}function nn(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
1526
+ * ${t} Repository Interface
1527
+ *
1528
+ * Defines the contract for data access.
1529
+ * The interface declares what operations are available;
1530
+ * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
1531
+ *
1532
+ * To swap implementations, change the factory in the module's register() method.
1533
+ */
1534
+ import { createToken } from '@forinda/kickjs'
1535
+ import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
1536
+ import type { Create${t}DTO } from '${r}/create-${n}.dto'
1537
+ import type { Update${t}DTO } from '${r}/update-${n}.dto'
1538
+ import type { ParsedQuery } from '@forinda/kickjs'
1539
+
1540
+ export interface I${t}Repository {
1541
+ findById(id: string): Promise<${t}ResponseDTO | null>
1542
+ findAll(): Promise<${t}ResponseDTO[]>
1543
+ findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
1544
+ create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
1545
+ update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
1546
+ delete(id: string): Promise<void>
1547
+ }
1548
+
1549
+ /**
1550
+ * Collision-safe DI token bound to \`I${t}Repository\`.
1551
+ * \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
1552
+ * \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
1553
+ * interface — no manual generic, no \`any\` cast.
1554
+ *
1555
+ * The \`'${i}/'\` prefix matches the project scope so
1556
+ * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
1557
+ * adopters must NOT use the reserved \`'kick/'\` namespace.
1558
+ */
1559
+ export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
1560
+ `}function H(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
1561
+ * In-Memory ${t} Repository
1562
+ *
1563
+ * Implements the repository interface using a Map.
1564
+ * Useful for prototyping and testing. Replace with a database implementation
1565
+ * (Drizzle, Prisma, etc.) for production use.
1566
+ *
1567
+ * @Repository() registers this class in the DI container as a singleton.
1568
+ */
1569
+ import { randomUUID } from 'node:crypto'
1570
+ import { Repository, HttpException } from '@forinda/kickjs'
1571
+ import type { ParsedQuery } from '@forinda/kickjs'
1572
+ import type { I${t}Repository } from '${r}/${n}.repository'
1573
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
1574
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
1575
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
1576
+
1577
+ @Repository()
1578
+ export class InMemory${t}Repository implements I${t}Repository {
1579
+ private store = new Map<string, ${t}ResponseDTO>()
1580
+
1581
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
1582
+ return this.store.get(id) ?? null
1583
+ }
1584
+
1585
+ async findAll(): Promise<${t}ResponseDTO[]> {
1586
+ return Array.from(this.store.values())
1587
+ }
1588
+
1589
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1590
+ const all = Array.from(this.store.values())
1591
+ const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1592
+ return { data, total: all.length }
1593
+ }
1594
+
1595
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1596
+ const now = new Date().toISOString()
1597
+ const entity: ${t}ResponseDTO = {
1598
+ id: randomUUID(),
1599
+ name: dto.name,
1600
+ createdAt: now,
1601
+ updatedAt: now,
1602
+ }
1603
+ this.store.set(entity.id, entity)
1604
+ return entity
1605
+ }
1606
+
1607
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1608
+ const existing = this.store.get(id)
1609
+ if (!existing) throw HttpException.notFound('${t} not found')
1610
+ const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1611
+ this.store.set(id, updated)
1612
+ return updated
1613
+ }
1614
+
1615
+ async delete(id: string): Promise<void> {
1616
+ if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1617
+ this.store.delete(id)
1618
+ }
1619
+ }
1620
+ `}function rn(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`/**
1621
+ * ${o} ${t} Repository
1622
+ *
1623
+ * Stub implementation for a custom '${r}' repository.
1624
+ * Implements the repository interface using an in-memory Map as a placeholder.
1625
+ *
1626
+ * TODO: Replace the in-memory Map with your ${r} data-access logic.
1627
+ * See I${t}Repository for the interface contract.
1628
+ *
1629
+ * @Repository() registers this class in the DI container as a singleton.
1630
+ */
1631
+ import { randomUUID } from 'node:crypto'
1632
+ import { Repository, HttpException } from '@forinda/kickjs'
1633
+ import type { ParsedQuery } from '@forinda/kickjs'
1634
+ import type { I${t}Repository } from '${i}/${n}.repository'
1635
+ import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
1636
+ import type { Create${t}DTO } from '${a}/create-${n}.dto'
1637
+ import type { Update${t}DTO } from '${a}/update-${n}.dto'
1638
+
1639
+ @Repository()
1640
+ export class ${o}${t}Repository implements I${t}Repository {
1641
+ // TODO: Replace with your ${r} client/connection
1642
+ private store = new Map<string, ${t}ResponseDTO>()
1643
+
1644
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
1645
+ // TODO: Implement with ${r}
1646
+ return this.store.get(id) ?? null
1647
+ }
1648
+
1649
+ async findAll(): Promise<${t}ResponseDTO[]> {
1650
+ // TODO: Implement with ${r}
1651
+ return Array.from(this.store.values())
1652
+ }
1653
+
1654
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1655
+ // TODO: Implement with ${r}
1656
+ const all = Array.from(this.store.values())
1657
+ const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1658
+ return { data, total: all.length }
1659
+ }
1660
+
1661
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1662
+ // TODO: Implement with ${r}
1663
+ const now = new Date().toISOString()
1664
+ const entity: ${t}ResponseDTO = {
1665
+ id: randomUUID(),
1666
+ name: dto.name,
1667
+ createdAt: now,
1668
+ updatedAt: now,
1669
+ }
1670
+ this.store.set(entity.id, entity)
1671
+ return entity
1672
+ }
1673
+
1674
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1675
+ // TODO: Implement with ${r}
1676
+ const existing = this.store.get(id)
1677
+ if (!existing) throw HttpException.notFound('${t} not found')
1678
+ const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1679
+ this.store.set(id, updated)
1680
+ return updated
1681
+ }
1682
+
1683
+ async delete(id: string): Promise<void> {
1684
+ // TODO: Implement with ${r}
1685
+ if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1686
+ this.store.delete(id)
1687
+ }
1688
+ }
1689
+ `}function an(e){let{pascal:t,kebab:n}=e;return`/**
1690
+ * ${t} Domain Service
1691
+ *
1692
+ * Domain layer — contains business rules that don't belong to a single entity.
1693
+ * Use this for cross-entity logic, validation rules, and domain invariants.
1694
+ * Keep it free of HTTP/framework concerns.
1695
+ */
1696
+ import { Service, Inject, HttpException } from '@forinda/kickjs'
1697
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../repositories/${n}.repository'
1698
+
1699
+ @Service()
1700
+ export class ${t}DomainService {
1701
+ constructor(
1702
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1703
+ ) {}
1704
+
1705
+ async ensureExists(id: string): Promise<void> {
1706
+ const entity = await this.repo.findById(id)
1707
+ if (!entity) {
1708
+ throw HttpException.notFound('${t} not found')
1709
+ }
1710
+ }
1711
+ }
1712
+ `}function on(e){let{pascal:t,kebab:n}=e;return`/**
1713
+ * ${t} Entity
1714
+ *
1715
+ * Domain layer — the core business object.
1716
+ * Uses a private constructor with static factory methods (create, reconstitute)
1717
+ * to enforce invariants. Properties are accessed via getters to maintain encapsulation.
1718
+ *
1719
+ * Patterns used:
1720
+ * - Private constructor: prevents direct instantiation
1721
+ * - create(): factory for new entities (generates ID, sets timestamps)
1722
+ * - reconstitute(): factory for rebuilding from persistence (no side effects)
1723
+ * - changeName(): mutation method that enforces business rules
1724
+ */
1725
+ import { ${t}Id } from '../value-objects/${n}-id.vo'
1726
+
1727
+ interface ${t}Props {
1728
+ id: ${t}Id
1729
+ name: string
1730
+ createdAt: Date
1731
+ updatedAt: Date
1732
+ }
1733
+
1734
+ export class ${t} {
1735
+ private constructor(private props: ${t}Props) {}
1736
+
1737
+ static create(params: { name: string }): ${t} {
1738
+ const now = new Date()
1739
+ return new ${t}({
1740
+ id: ${t}Id.create(),
1741
+ name: params.name,
1742
+ createdAt: now,
1743
+ updatedAt: now,
1744
+ })
1745
+ }
1746
+
1747
+ static reconstitute(props: ${t}Props): ${t} {
1748
+ return new ${t}(props)
1749
+ }
1750
+
1751
+ get id(): ${t}Id {
1752
+ return this.props.id
1753
+ }
1754
+ get name(): string {
1755
+ return this.props.name
1756
+ }
1757
+ get createdAt(): Date {
1758
+ return this.props.createdAt
1759
+ }
1760
+ get updatedAt(): Date {
1761
+ return this.props.updatedAt
1762
+ }
1763
+
1764
+ changeName(name: string): void {
1765
+ if (!name || name.trim().length === 0) {
1766
+ throw new Error('Name cannot be empty')
1767
+ }
1768
+ this.props.name = name.trim()
1769
+ this.props.updatedAt = new Date()
1770
+ }
1771
+
1772
+ toJSON() {
1773
+ return {
1774
+ id: this.props.id.toString(),
1775
+ name: this.props.name,
1776
+ createdAt: this.props.createdAt.toISOString(),
1777
+ updatedAt: this.props.updatedAt.toISOString(),
1778
+ }
1779
+ }
1780
+ }
1781
+ `}function sn(e){let{pascal:t}=e;return`/**
1782
+ * ${t} ID Value Object
1783
+ *
1784
+ * Domain layer — wraps a primitive ID with type safety and validation.
1785
+ * Value objects are immutable and compared by value, not reference.
1786
+ *
1787
+ * ${t}Id.create() — generate a new UUID
1788
+ * ${t}Id.from(id) — wrap an existing ID string (validates non-empty)
1789
+ * id.equals(other) — compare two IDs by value
1790
+ */
1791
+ import { randomUUID } from 'node:crypto'
1792
+
1793
+ export class ${t}Id {
1794
+ private constructor(private readonly value: string) {}
1795
+
1796
+ static create(): ${t}Id {
1797
+ return new ${t}Id(randomUUID())
1798
+ }
1799
+
1800
+ static from(id: string): ${t}Id {
1801
+ if (!id || id.trim().length === 0) {
1802
+ throw new Error('${t}Id cannot be empty')
1803
+ }
1804
+ return new ${t}Id(id)
1805
+ }
1806
+
1807
+ toString(): string {
1808
+ return this.value
1809
+ }
1810
+
1811
+ equals(other: ${t}Id): boolean {
1812
+ return this.value === other.value
1813
+ }
1814
+ }
1815
+ `}function cn(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
1816
+ import { Container } from '@forinda/kickjs'
1817
+
1818
+ describe('${t}Controller', () => {
1819
+ beforeEach(() => {
1820
+ Container.reset()
1821
+ })
1822
+
1823
+ it('should be defined', () => {
1824
+ expect(true).toBe(true)
1825
+ })
1826
+
1827
+ describe('POST /${r}', () => {
1828
+ it('should create a new ${n}', async () => {
1829
+ // TODO: Set up test module, call create endpoint, assert 201
1830
+ expect(true).toBe(true)
1831
+ })
1832
+ })
1833
+
1834
+ describe('GET /${r}', () => {
1835
+ it('should return paginated ${r}', async () => {
1836
+ // TODO: Set up test module, call list endpoint, assert { data, meta }
1837
+ expect(true).toBe(true)
1838
+ })
1839
+ })
1840
+
1841
+ describe('GET /${r}/:id', () => {
1842
+ it('should return a ${n} by id', async () => {
1843
+ // TODO: Create a ${n}, then fetch by id, assert match
1844
+ expect(true).toBe(true)
1845
+ })
1846
+
1847
+ it('should return 404 for non-existent ${n}', async () => {
1848
+ // TODO: Fetch non-existent id, assert 404
1849
+ expect(true).toBe(true)
1850
+ })
1851
+ })
1852
+
1853
+ describe('PUT /${r}/:id', () => {
1854
+ it('should update an existing ${n}', async () => {
1855
+ // TODO: Create, update, assert changes
1856
+ expect(true).toBe(true)
1857
+ })
1858
+ })
1859
+
1860
+ describe('DELETE /${r}/:id', () => {
1861
+ it('should delete a ${n}', async () => {
1862
+ // TODO: Create, delete, assert gone
1863
+ expect(true).toBe(true)
1864
+ })
1865
+ })
1866
+ })
1867
+ `}function ln(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'
1868
+ import { InMemory${t}Repository } from '${i}'
1869
+
1870
+ describe('InMemory${t}Repository', () => {
1871
+ let repo: InMemory${t}Repository
1872
+
1873
+ beforeEach(() => {
1874
+ repo = new InMemory${t}Repository()
1875
+ })
1876
+
1877
+ it('should create and retrieve a ${n}', async () => {
1878
+ const created = await repo.create({ name: 'Test ${t}' })
1879
+ expect(created).toBeDefined()
1880
+ expect(created.name).toBe('Test ${t}')
1881
+ expect(created.id).toBeDefined()
1882
+
1883
+ const found = await repo.findById(created.id)
1884
+ expect(found).toEqual(created)
1885
+ })
1886
+
1887
+ it('should return null for non-existent id', async () => {
1888
+ const found = await repo.findById('non-existent')
1889
+ expect(found).toBeNull()
1890
+ })
1891
+
1892
+ it('should list all ${r}', async () => {
1893
+ await repo.create({ name: '${t} 1' })
1894
+ await repo.create({ name: '${t} 2' })
1895
+
1896
+ const all = await repo.findAll()
1897
+ expect(all).toHaveLength(2)
1898
+ })
1899
+
1900
+ it('should return paginated results', async () => {
1901
+ await repo.create({ name: '${t} 1' })
1902
+ await repo.create({ name: '${t} 2' })
1903
+ await repo.create({ name: '${t} 3' })
1904
+
1905
+ const result = await repo.findPaginated({
1906
+ filters: [],
1907
+ sort: [],
1908
+ search: '',
1909
+ pagination: { page: 1, limit: 2, offset: 0 },
1910
+ })
1911
+
1912
+ expect(result.data).toHaveLength(2)
1913
+ expect(result.total).toBe(3)
1914
+ })
1915
+
1916
+ it('should update a ${n}', async () => {
1917
+ const created = await repo.create({ name: 'Original' })
1918
+ const updated = await repo.update(created.id, { name: 'Updated' })
1919
+ expect(updated.name).toBe('Updated')
1920
+ })
1921
+
1922
+ it('should delete a ${n}', async () => {
1923
+ const created = await repo.create({ name: 'To Delete' })
1924
+ await repo.delete(created.id)
1925
+ const found = await repo.findById(created.id)
1926
+ expect(found).toBeNull()
1927
+ })
1928
+ })
1929
+ `}function un(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
1930
+ import type { ParsedQuery } from '@forinda/kickjs'
1931
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
1932
+ import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
1933
+ import type { Create${t}DTO } from './dtos/create-${n}.dto'
1934
+ import type { Update${t}DTO } from './dtos/update-${n}.dto'
1935
+
1936
+ @Service()
1937
+ export class ${t}Service {
1938
+ constructor(
1939
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1940
+ ) {}
1941
+
1942
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
1943
+ return this.repo.findById(id)
1944
+ }
1945
+
1946
+ async findAll(): Promise<${t}ResponseDTO[]> {
1947
+ return this.repo.findAll()
1948
+ }
1949
+
1950
+ async findPaginated(parsed: ParsedQuery) {
1951
+ return this.repo.findPaginated(parsed)
1952
+ }
1953
+
1954
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1955
+ return this.repo.create(dto)
1956
+ }
1957
+
1958
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1959
+ return this.repo.update(id, dto)
1960
+ }
1961
+
1962
+ async delete(id: string): Promise<void> {
1963
+ await this.repo.delete(id)
1964
+ }
1965
+ }
1966
+ `}function dn(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
1967
+
1968
+ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
1969
+ filterable: ['name'],
1970
+ sortable: ['name', 'createdAt'],
1971
+ searchable: ['name'],
1972
+ }
1973
+ `}function fn(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`/**
1974
+ * ${t} Module — CQRS Pattern
1975
+ *
1976
+ * Separates read (queries) and write (commands) operations.
1977
+ * Events are emitted after state changes and can be handled via
1978
+ * WebSocket broadcasts, queue jobs, or ETL pipelines.
1979
+ *
1980
+ * Structure:
1981
+ * commands/ — Write operations (create, update, delete)
1982
+ * queries/ — Read operations (get, list)
1983
+ * events/ — Domain events + handlers (WS broadcast, queue dispatch)
1984
+ * dtos/ — Request/response schemas
1985
+ */
1986
+ import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1987
+ import { buildRoutes } from '@forinda/kickjs'
1988
+ import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
1989
+ import { ${s} } from './${c}.repository'
1990
+ import { ${t}Controller } from './${n}.controller'
1991
+
1992
+ // Eagerly load decorated classes
1993
+ import.meta.glob(
1994
+ [
1995
+ './commands/**/*.ts',
1996
+ './queries/**/*.ts',
1997
+ './events/**/*.ts',
1998
+ '!./**/*.test.ts',
1999
+ ],
2000
+ { eager: true },
2001
+ )
2002
+
2003
+ export class ${t}Module implements AppModule {
2004
+ register(container: Container): void {
2005
+ container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
2006
+ container.resolve(${s}),
2007
+ )
2008
+ }
2009
+
2010
+ routes(): ModuleRoutes {
2011
+ return {
2012
+ path: '/${r}',
2013
+ router: buildRoutes(${t}Controller),
2014
+ controller: ${t}Controller,
2015
+ }
2016
+ }
2017
+ }
2018
+ `}function pn(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'
2019
+ import { ApiTags } from '@forinda/kickjs-swagger'
2020
+ import { Create${t}Command } from './commands/create-${n}.command'
2021
+ import { Update${t}Command } from './commands/update-${n}.command'
2022
+ import { Delete${t}Command } from './commands/delete-${n}.command'
2023
+ import { Get${t}Query } from './queries/get-${n}.query'
2024
+ import { List${i}Query } from './queries/list-${r}.query'
2025
+ import { create${t}Schema } from './dtos/create-${n}.dto'
2026
+ import { update${t}Schema } from './dtos/update-${n}.dto'
2027
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
2028
+
2029
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
2030
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
2031
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
2032
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
2033
+
2034
+ @Controller()
2035
+ export class ${t}Controller {
2036
+ @Autowired() private readonly create${t}Command!: Create${t}Command
2037
+ @Autowired() private readonly update${t}Command!: Update${t}Command
2038
+ @Autowired() private readonly delete${t}Command!: Delete${t}Command
2039
+ @Autowired() private readonly get${t}Query!: Get${t}Query
2040
+ @Autowired() private readonly list${i}Query!: List${i}Query
2041
+
2042
+ @Get('/')
2043
+ @ApiTags('${t}')
2044
+ @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
2045
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
2046
+ return ctx.paginate(
2047
+ (parsed) => this.list${i}Query.execute(parsed),
2048
+ ${t.toUpperCase()}_QUERY_CONFIG,
2049
+ )
2050
+ }
2051
+
2052
+ @Get('/:id')
2053
+ @ApiTags('${t}')
2054
+ async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
2055
+ const result = await this.get${t}Query.execute(ctx.params.id)
2056
+ if (!result) return ctx.notFound('${t} not found')
2057
+ ctx.json(result)
2058
+ }
2059
+
2060
+ @Post('/', { body: create${t}Schema, name: 'Create${t}' })
2061
+ @ApiTags('${t}')
2062
+ async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
2063
+ const result = await this.create${t}Command.execute(ctx.body)
2064
+ ctx.created(result)
2065
+ }
2066
+
2067
+ @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
2068
+ @ApiTags('${t}')
2069
+ async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
2070
+ const result = await this.update${t}Command.execute(ctx.params.id, ctx.body)
2071
+ ctx.json(result)
2072
+ }
2073
+
2074
+ @Delete('/:id')
2075
+ @ApiTags('${t}')
2076
+ async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
2077
+ await this.delete${t}Command.execute(ctx.params.id)
2078
+ ctx.noContent()
2079
+ }
2080
+ }
2081
+ `}function mn(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2082
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2083
+ import type { Create${t}DTO } from '../dtos/create-${n}.dto'
2084
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2085
+ import { ${t}Events } from '../events/${n}.events'
2086
+
2087
+ @Service()
2088
+ export class Create${t}Command {
2089
+ constructor(
2090
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2091
+ @Inject(${t}Events) private readonly events: ${t}Events,
2092
+ ) {}
2093
+
2094
+ async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2095
+ const result = await this.repo.create(dto)
2096
+ this.events.emit('${n}.created', result)
2097
+ return result
2098
+ }
2099
+ }
2100
+ `},{file:`update-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2101
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2102
+ import type { Update${t}DTO } from '../dtos/update-${n}.dto'
2103
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2104
+ import { ${t}Events } from '../events/${n}.events'
2105
+
2106
+ @Service()
2107
+ export class Update${t}Command {
2108
+ constructor(
2109
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2110
+ @Inject(${t}Events) private readonly events: ${t}Events,
2111
+ ) {}
2112
+
2113
+ async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2114
+ const result = await this.repo.update(id, dto)
2115
+ this.events.emit('${n}.updated', result)
2116
+ return result
2117
+ }
2118
+ }
2119
+ `},{file:`delete-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2120
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2121
+ import { ${t}Events } from '../events/${n}.events'
2122
+
2123
+ @Service()
2124
+ export class Delete${t}Command {
2125
+ constructor(
2126
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2127
+ @Inject(${t}Events) private readonly events: ${t}Events,
2128
+ ) {}
2129
+
2130
+ async execute(id: string): Promise<void> {
2131
+ await this.repo.delete(id)
2132
+ this.events.emit('${n}.deleted', { id })
2133
+ }
2134
+ }
2135
+ `}]}function hn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2136
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2137
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2138
+
2139
+ @Service()
2140
+ export class Get${t}Query {
2141
+ constructor(
2142
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2143
+ ) {}
2144
+
2145
+ async execute(id: string): Promise<${t}ResponseDTO | null> {
2146
+ return this.repo.findById(id)
2147
+ }
2148
+ }
2149
+ `},{file:`list-${r}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2150
+ import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2151
+ import type { ParsedQuery } from '@forinda/kickjs'
2152
+
2153
+ @Service()
2154
+ export class List${i}Query {
2155
+ constructor(
2156
+ @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2157
+ ) {}
2158
+
2159
+ async execute(parsed: ParsedQuery) {
2160
+ return this.repo.findPaginated(parsed)
2161
+ }
2162
+ }
2163
+ `}]}function gn(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
2164
+ import { EventEmitter } from 'node:events'
2165
+ import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2166
+
2167
+ /**
2168
+ * ${t} domain event types.
2169
+ *
2170
+ * These events are emitted by commands after state changes.
2171
+ * Subscribe to them in event handlers for side effects:
2172
+ * - WebSocket broadcasts (real-time UI updates)
2173
+ * - Queue jobs (async processing, ETL pipelines)
2174
+ * - Audit logging
2175
+ * - Cache invalidation
2176
+ */
2177
+ export interface ${t}EventMap {
2178
+ '${n}.created': ${t}ResponseDTO
2179
+ '${n}.updated': ${t}ResponseDTO
2180
+ '${n}.deleted': { id: string }
2181
+ }
2182
+
2183
+ @Service()
2184
+ export class ${t}Events {
2185
+ private emitter = new EventEmitter()
2186
+
2187
+ emit<K extends keyof ${t}EventMap>(event: K, data: ${t}EventMap[K]): void {
2188
+ this.emitter.emit(event, data)
2189
+ }
2190
+
2191
+ on<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
2192
+ this.emitter.on(event, handler)
2193
+ }
2194
+
2195
+ off<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
2196
+ this.emitter.off(event, handler)
2197
+ }
2198
+ }
2199
+ `},{file:`on-${n}-change.handler.ts`,content:`import { Service, Autowired } from '@forinda/kickjs'
2200
+ import { ${t}Events } from './${n}.events'
2201
+
2202
+ /**
2203
+ * ${t} Change Event Handler
2204
+ *
2205
+ * Reacts to domain events emitted by commands.
2206
+ * Wire up side effects here:
2207
+ *
2208
+ * 1. WebSocket broadcast — notify connected clients in real-time
2209
+ * import { WsGateway } from '@forinda/kickjs-ws'
2210
+ * this.ws.broadcast('${n}-channel', { event, data })
2211
+ *
2212
+ * 2. Queue dispatch — offload heavy processing to background workers
2213
+ * import { QueueService } from '@forinda/kickjs-queue'
2214
+ * this.queue.add('${n}-etl', { action: event, payload: data })
2215
+ *
2216
+ * 3. ETL pipeline — transform and load data to external systems
2217
+ * await this.etlPipeline.process(data)
2218
+ */
2219
+ @Service()
2220
+ export class On${t}ChangeHandler {
2221
+ @Autowired() private events!: ${t}Events
2222
+
2223
+ // Uncomment to inject WebSocket and Queue services:
2224
+ // @Autowired() private ws!: WsGateway
2225
+ // @Autowired() private queue!: QueueService
2226
+
2227
+ onInit(): void {
2228
+ this.events.on('${n}.created', (data) => {
2229
+ console.log('[${t}] Created:', data.id)
2230
+ // TODO: Broadcast via WebSocket
2231
+ // this.ws.broadcast('${n}-channel', { event: '${n}.created', data })
2232
+ // TODO: Dispatch to queue for async processing / ETL
2233
+ // this.queue.add('${n}-etl', { action: 'create', payload: data })
2234
+ })
2235
+
2236
+ this.events.on('${n}.updated', (data) => {
2237
+ console.log('[${t}] Updated:', data.id)
2238
+ // TODO: Broadcast via WebSocket
2239
+ // this.ws.broadcast('${n}-channel', { event: '${n}.updated', data })
2240
+ })
2241
+
2242
+ this.events.on('${n}.deleted', (data) => {
2243
+ console.log('[${t}] Deleted:', data.id)
2244
+ // TODO: Broadcast via WebSocket
2245
+ // this.ws.broadcast('${n}-channel', { event: '${n}.deleted', data })
2246
+ })
2247
+ }
2248
+ }
2249
+ `}]}function _n(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
2250
+ * Drizzle ${t} Repository
2251
+ *
2252
+ * Implements the repository interface using Drizzle ORM.
2253
+ * Uses buildFromColumns() with Column objects for type-safe query building.
2254
+ *
2255
+ * TODO: Update the schema import to match your Drizzle schema file.
2256
+ * TODO: Replace DRIZZLE_DB injection token with your actual database token.
2257
+ *
2258
+ * @Repository() registers this class in the DI container as a singleton.
2259
+ */
2260
+ import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
2261
+ import { Repository, HttpException, Inject } from '@forinda/kickjs'
2262
+ import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
2263
+ import type { ParsedQuery } from '@forinda/kickjs'
2264
+ import type { I${t}Repository } from '${r}/${n}.repository'
2265
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
2266
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
2267
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
2268
+ import { ${t.toUpperCase()}_QUERY_CONFIG } from '../../constants'
2269
+
2270
+ // TODO: Import your Drizzle schema table — e.g.:
2271
+ // import { ${n}s } from '@/db/schema'
2272
+
2273
+ const queryAdapter = new DrizzleQueryAdapter({
2274
+ eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
2275
+ })
2276
+
2277
+ @Repository()
2278
+ export class Drizzle${t}Repository implements I${t}Repository {
2279
+ constructor(@Inject(DRIZZLE_DB) private db: any) {}
2280
+
2281
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
2282
+ // TODO: Implement with Drizzle
2283
+ // const row = this.db.select().from(${n}s).where(eq(${n}s.id, id)).get()
2284
+ // return row ?? null
2285
+ throw new Error('Drizzle ${t} repository not yet implemented — update schema imports and queries')
2286
+ }
2287
+
2288
+ async findAll(): Promise<${t}ResponseDTO[]> {
2289
+ // TODO: Implement with Drizzle
2290
+ // return this.db.select().from(${n}s).all()
2291
+ throw new Error('Drizzle ${t} repository not yet implemented')
2292
+ }
2293
+
2294
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
2295
+ // TODO: Use buildFromColumns() with your query config for type-safe filtering
2296
+ // const query = queryAdapter.buildFromColumns(parsed, ${t.toUpperCase()}_QUERY_CONFIG)
2297
+ //
2298
+ // const data = this.db
2299
+ // .select().from(${n}s).$dynamic()
2300
+ // .where(query.where).orderBy(...query.orderBy)
2301
+ // .limit(query.limit).offset(query.offset).all()
2302
+ //
2303
+ // const totalResult = this.db
2304
+ // .select({ count: count() }).from(${n}s)
2305
+ // .$dynamic().where(query.where).get()
2306
+ //
2307
+ // return { data, total: totalResult?.count ?? 0 }
2308
+ throw new Error('Drizzle ${t} repository not yet implemented')
2309
+ }
2310
+
2311
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2312
+ // TODO: Implement with Drizzle
2313
+ // return this.db.insert(${n}s).values(dto).returning().get()
2314
+ throw new Error('Drizzle ${t} repository not yet implemented')
2315
+ }
2316
+
2317
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2318
+ // TODO: Implement with Drizzle
2319
+ // const row = this.db.update(${n}s).set(dto).where(eq(${n}s.id, id)).returning().get()
2320
+ // if (!row) throw HttpException.notFound('${t} not found')
2321
+ // return row
2322
+ throw new Error('Drizzle ${t} repository not yet implemented')
2323
+ }
2324
+
2325
+ async delete(id: string): Promise<void> {
2326
+ // TODO: Implement with Drizzle
2327
+ // this.db.delete(${n}s).where(eq(${n}s.id, id)).run()
2328
+ throw new Error('Drizzle ${t} repository not yet implemented')
2329
+ }
2330
+ }
2331
+ `}function vn(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
2332
+ // TODO: Import your schema table and reference actual columns for type safety
2333
+ // import { ${n}s } from '@/db/schema'
2334
+
2335
+ export const ${t.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
2336
+ columns: {
2337
+ // Replace with actual Drizzle Column references for type-safe filtering:
2338
+ // name: ${n}s.name,
2339
+ // status: ${n}s.status,
2340
+ },
2341
+ sortable: {
2342
+ // name: ${n}s.name,
2343
+ // createdAt: ${n}s.createdAt,
2344
+ },
2345
+ searchColumns: [
2346
+ // ${n}s.name,
2347
+ ],
2348
+ }
2349
+ `}function yn(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`/**
2350
+ * Prisma ${t} Repository
2351
+ *
2352
+ * Implements the repository interface using Prisma Client.
2353
+ * Requires a PrismaClient instance injected via the DI container.
2354
+ *
2355
+ * Ensure your Prisma schema has a '${t}' model defined.
2356
+ *
2357
+ * For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
2358
+ * @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
2359
+ *
2360
+ * @Repository() registers this class in the DI container as a singleton.
2361
+ */
2362
+ import { Repository, HttpException, Inject } from '@forinda/kickjs'
2363
+ import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
2364
+ import type { ParsedQuery } from '@forinda/kickjs'
2365
+ import type { I${t}Repository } from '${r}/${n}.repository'
2366
+ import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
2367
+ import type { Create${t}DTO } from '${i}/create-${n}.dto'
2368
+ import type { Update${t}DTO } from '${i}/update-${n}.dto'
2369
+
2370
+ @Repository()
2371
+ export class Prisma${t}Repository implements I${t}Repository {
2372
+ @Inject(PRISMA_CLIENT) private prisma!: { ${a}: PrismaModelDelegate }
2373
+
2374
+ async findById(id: string): Promise<${t}ResponseDTO | null> {
2375
+ return this.prisma.${a}.findUnique({ where: { id } }) as Promise<${t}ResponseDTO | null>
2376
+ }
2377
+
2378
+ async findAll(): Promise<${t}ResponseDTO[]> {
2379
+ return this.prisma.${a}.findMany() as Promise<${t}ResponseDTO[]>
2380
+ }
2381
+
2382
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
2383
+ const [data, total] = await Promise.all([
2384
+ this.prisma.${a}.findMany({
2385
+ skip: parsed.pagination.offset,
2386
+ take: parsed.pagination.limit,
2387
+ }) as Promise<${t}ResponseDTO[]>,
2388
+ this.prisma.${a}.count(),
2389
+ ])
2390
+ return { data, total }
2391
+ }
2392
+
2393
+ async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2394
+ return this.prisma.${a}.create({ data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
2395
+ }
2396
+
2397
+ async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2398
+ const existing = await this.prisma.${a}.findUnique({ where: { id } })
2399
+ if (!existing) throw HttpException.notFound('${t} not found')
2400
+ return this.prisma.${a}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
2401
+ }
2402
+
2403
+ async delete(id: string): Promise<void> {
2404
+ await this.prisma.${a}.deleteMany({ where: { id } })
2405
+ }
2406
+ }
2407
+ `}async function bn(e){let{pascal:t,kebab:n,plural:r,write:i}=e;await i(`${n}.module.ts`,Jt({pascal:t,kebab:n,plural:r})),await i(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
2408
+
2409
+ // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
2410
+ // \`kick typegen\` (auto-run on \`kick dev\`).
2411
+
2412
+ @Controller()
2413
+ export class ${t}Controller {
2414
+ @Get('/')
2415
+ async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
2416
+ ctx.json({ message: '${t} list' })
2417
+ }
2418
+ }
2419
+ `)}async function xn(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`,qt({pascal:t,kebab:n,plural:r,repo:a})),await l(`${n}.constants.ts`,dn({pascal:t,kebab:n})),await l(`${n}.controller.ts`,Xt({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`${n}.service.ts`,un({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,Qt({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,$t({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,en({pascal:t,kebab:n})),await l(`${n}.repository.ts`,nn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let u={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},d={inmemory:()=>H({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>_n({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>yn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},f=u[a]??`${B(a)}-${n}`,p=d[a]??(()=>rn({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`,H({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,cn({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,ln({pascal:t,kebab:n,plural:r,repoPrefix:`../${u.inmemory??`in-memory-${n}`}.repository`})))}async function Sn(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`,fn({pascal:t,kebab:n,plural:r,repo:a})),await l(`${n}.constants.ts`,dn({pascal:t,kebab:n})),await l(`${n}.controller.ts`,pn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`dtos/create-${n}.dto.ts`,Qt({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,$t({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,en({pascal:t,kebab:n}));let u=mn({pascal:t,kebab:n});for(let e of u)await l(`commands/${e.file}`,e.content);let d=hn({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of d)await l(`queries/${e.file}`,e.content);let f=gn({pascal:t,kebab:n});for(let e of f)await l(`events/${e.file}`,e.content);await l(`${n}.repository.ts`,nn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>H({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>_n({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>yn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},h=p[a]??`${B(a)}-${n}`,g=m[a]??(()=>rn({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`,H({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,cn({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,ln({pascal:t,kebab:n,plural:r,repoPrefix:`../${p.inmemory??`in-memory-${n}`}.repository`})))}async function Cn(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`,Kt({pascal:t,kebab:n,plural:r,repo:a})),await u(`constants.ts`,a===`drizzle`?vn({pascal:t,kebab:n}):Zt({pascal:t,kebab:n})),await u(`presentation/${n}.controller.ts`,Yt({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`application/dtos/create-${n}.dto.ts`,Qt({pascal:t,kebab:n})),await u(`application/dtos/update-${n}.dto.ts`,$t({pascal:t,kebab:n})),await u(`application/dtos/${n}-response.dto.ts`,en({pascal:t,kebab:n}));let d=tn({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`,nn({pascal:t,kebab:n,tokenScope:l})),await u(`domain/services/${n}-domain.service.ts`,an({pascal:t,kebab:n}));let f={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},p={inmemory:()=>H({pascal:t,kebab:n}),drizzle:()=>_n({pascal:t,kebab:n}),prisma:()=>yn({pascal:t,kebab:n,prismaClientPath:c})},m=f[a]??`${B(a)}-${n}`,h=p[a]??(()=>rn({pascal:t,kebab:n,repoType:a}));await u(`infrastructure/repositories/${m}.repository.ts`,h()),o||(await u(`domain/entities/${n}.entity.ts`,on({pascal:t,kebab:n})),await u(`domain/value-objects/${n}-id.vo.ts`,sn({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await u(`infrastructure/repositories/in-memory-${n}.repository.ts`,H({pascal:t,kebab:n})),await u(`__tests__/${n}.controller.test.ts`,cn({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,ln({pascal:t,kebab:n,plural:r})))}function wn(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Tn(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`ddd`;e.minimal&&(l=`minimal`);let u=B(t),d=R(t),f=c?V(u):u,p=c?Dt(d):d,m=b(n,f),h=[],g=o??!1,_={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,write:async(e,t)=>{let n=b(m,e);if(s){h.push(n);return}if(!g&&await N(n)&&!await F({message:`File exists: ${O.dim(e)}. Overwrite?`,initialValue:!1})){I.warn(`Skipped: ${e}`);return}await A(n,t),h.push(n)},files:h};switch(l){case`minimal`:await bn(_);break;case`rest`:await xn(_);break;case`cqrs`:await Sn(_);break;default:await Cn(_);break}return s||await En(n,d,f,u),h}async function En(e,t,n,r){let i=b(e,`index.ts`),a=await N(i),o=`./${n}/${r}.module`;if(!a){await A(i,`import type { AppModuleClass } from '@forinda/kickjs'
2420
+ import { ${t}Module } from '${o}'
2421
+
2422
+ export const modules: AppModuleClass[] = [${t}Module]
2423
+ `);return}let s=await T(i,`utf-8`),c=`import { ${t}Module } from '${o}'`;if(!s.includes(`${t}Module`)){let e=s.lastIndexOf(`import `);if(e!==-1){let t=s.indexOf(`
2424
+ `,e);s=s.slice(0,t+1)+c+`
2425
+ `+s.slice(t+1)}else s=c+`
2426
+ `+s;s=s.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 E(i,s,`utf-8`)}async function Dn(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=b(n,`${r}.adapter.ts`);return await A(o,`import {
2427
+ defineAdapter,
2428
+ type AdapterContext,
2429
+ type AdapterMiddleware,
2430
+ type ContributorRegistrations,
2431
+ type Constructor,
2432
+ } from '@forinda/kickjs'
2433
+
2434
+ /**
2435
+ * Configuration for the ${i} adapter.
2436
+ *
2437
+ * Adapters typically take a small config object so callers can tune
2438
+ * behaviour at bootstrap time. Keep the shape narrow — anything
2439
+ * derived from the environment should be read inside the build
2440
+ * function via getEnv(), not forced onto the caller.
2441
+ */
2442
+ export interface ${i}AdapterConfig {
2443
+ // Add your adapter configuration here, e.g.:
2444
+ // enabled?: boolean
2445
+ // apiKey?: string
2446
+ }
2447
+
2448
+ /**
2449
+ * ${i} adapter — built via \`defineAdapter()\` so callers get the
2450
+ * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2451
+ *
2452
+ * Hooks into the Application lifecycle to add middleware, routes,
2453
+ * Context Contributors, or external service connections.
2454
+ *
2455
+ * Every lifecycle hook below is OPTIONAL. The scaffold emits all of
2456
+ * them so adopters can browse what's available and delete what they
2457
+ * don't need — \`build()\` returning \`{}\` is also valid for an adapter
2458
+ * that only contributes config defaults.
2459
+ *
2460
+ * @example
2461
+ * \`\`\`ts
2462
+ * import { bootstrap } from '@forinda/kickjs'
2463
+ * import { ${i}Adapter } from './adapters/${r}.adapter'
2464
+ *
2465
+ * bootstrap({
2466
+ * modules,
2467
+ * adapters: [${i}Adapter({ /* config overrides *\\/ })],
2468
+ * })
2469
+ * \`\`\`
2470
+ */
2471
+ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
2472
+ name: '${i}Adapter',
2473
+ defaults: {
2474
+ // Default config values go here. The adopter's overrides shallow-merge
2475
+ // on top of these before \`build()\` runs.
2476
+ },
2477
+ build: (_config, { name: _name }) => {
2478
+ // Closures inside \`build()\` are how each adapter instance owns its
2479
+ // own state (database client, Map, timer handle, …). The same
2480
+ // \`_config\` is visible to every hook below.
2481
+
2482
+ return {
2483
+ /**
2484
+ * Express middleware entries the Application mounts at named phases.
2485
+ *
2486
+ * \`phase\` controls where each handler sits in the pipeline:
2487
+ * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
2488
+ *
2489
+ * \`path\` (optional) scopes the entry to a path prefix.
2490
+ *
2491
+ * Delete this hook entirely if you don't add middleware.
2492
+ */
2493
+ middleware(): AdapterMiddleware[] {
2494
+ return [
2495
+ // Example: add a custom header to all responses
2496
+ // {
2497
+ // phase: 'beforeGlobal',
2498
+ // handler: (_req, res, next) => {
2499
+ // res.setHeader('X-${i}', 'true')
2500
+ // next()
2501
+ // },
2502
+ // },
2503
+ // Example: scope a rate limiter to one path prefix
2504
+ // {
2505
+ // phase: 'beforeRoutes',
2506
+ // path: '/api/v1/auth',
2507
+ // handler: rateLimit({ max: 10 }),
2508
+ // },
2509
+ ]
2510
+ },
2511
+
2512
+ /**
2513
+ * Runs BEFORE global middleware. Mount routes that should bypass the
2514
+ * middleware stack — health checks, docs UI, static assets, OAuth
2515
+ * callbacks. Anything you want reachable even if a global middleware
2516
+ * later in the chain rejects requests.
2517
+ *
2518
+ * Delete this hook if you have no early routes.
2519
+ */
2520
+ beforeMount(_ctx: AdapterContext): void {
2521
+ // Example:
2522
+ // _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
2523
+ },
2524
+
2525
+ /**
2526
+ * Fires once per controller class as the router mounts. Use this to
2527
+ * collect route metadata for OpenAPI specs, dependency graphs, route
2528
+ * inventories, devtools dashboards.
2529
+ *
2530
+ * Delete this hook unless your adapter introspects the route registry.
2531
+ */
2532
+ onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
2533
+ // Example (Swagger-style): collect routes for the spec.
2534
+ // openApiSpec.addController(_controllerClass, _mountPath)
2535
+ },
2536
+
2537
+ /**
2538
+ * Runs AFTER modules + routes are wired, BEFORE the server starts.
2539
+ * Right place for late-stage DI registrations or final config validation.
2540
+ *
2541
+ * Delete this hook if there's nothing to wire post-modules.
2542
+ */
2543
+ beforeStart(_ctx: AdapterContext): void {
2544
+ // Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
2545
+ },
2546
+
2547
+ /**
2548
+ * Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
2549
+ * available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
2550
+ * gRPC, GraphQL subscriptions), warm caches, log a banner.
2551
+ *
2552
+ * Delete this hook if you don't need the running server reference.
2553
+ */
2554
+ afterStart(_ctx: AdapterContext): void {
2555
+ // Example: const io = new Server(_ctx.server)
2556
+ },
2557
+
2558
+ /**
2559
+ * Returns Context Contributors to merge into every route's pipeline
2560
+ * at the \`'adapter'\` precedence level. Per-route handlers can
2561
+ * override the value at the method / class / module level.
2562
+ *
2563
+ * Delete this hook unless your adapter ships typed per-request values
2564
+ * (auth user, tenant, locale, feature flags, geo, etc).
2565
+ */
2566
+ contributors(): ContributorRegistrations {
2567
+ return [
2568
+ // Example:
2569
+ // import { defineHttpContextDecorator } from '@forinda/kickjs'
2570
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
2571
+ // const Load${i} = defineHttpContextDecorator({
2572
+ // key: '${r}',
2573
+ // resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
2574
+ // })
2575
+ // return [Load${i}.registration]
2576
+ ]
2577
+ },
2578
+
2579
+ /**
2580
+ * Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
2581
+ * resources the adapter owns: close connections, flush buffers,
2582
+ * cancel timers. The framework runs every adapter's \`shutdown\`
2583
+ * concurrently via \`Promise.allSettled\` — one failure won't block
2584
+ * sibling adapters.
2585
+ *
2586
+ * Delete this hook if your adapter holds no resources.
2587
+ */
2588
+ async shutdown(): Promise<void> {
2589
+ // Example: await this.pool.end()
2590
+ // Example: clearInterval(this.heartbeatTimer)
2591
+ },
2592
+ }
2593
+ },
2594
+ })
2595
+ `),a.push(o),a}async function On(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=b(n,`${r}.plugin.ts`);return await A(o,`import {
2596
+ definePlugin,
2597
+ type AppAdapter,
2598
+ type AppModuleClass,
2599
+ type Container,
2600
+ type ContributorRegistrations,
2601
+ } from '@forinda/kickjs'
2602
+
2603
+ /**
2604
+ * Configuration for the ${i} plugin.
2605
+ *
2606
+ * Plugins typically take a small config object so callers can tune
2607
+ * behaviour at bootstrap time. Keep the shape narrow — anything
2608
+ * derived from the environment should be read inside the build
2609
+ * function via getEnv(), not forced onto the caller.
2610
+ */
2611
+ export interface ${i}PluginConfig {
2612
+ // Add your plugin config here, e.g.:
2613
+ // enabled?: boolean
2614
+ // apiKey?: string
2615
+ }
2616
+
2617
+ /**
2618
+ * ${i} plugin — built via \`definePlugin()\` so callers get the
2619
+ * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2620
+ *
2621
+ * A plugin bundles DI bindings, modules, adapters, and middleware
2622
+ * into one object that can be added to \`bootstrap({ plugins })\`.
2623
+ *
2624
+ * Lifecycle order (each hook is optional — delete the ones you don't
2625
+ * need and keep only the surface your plugin actually uses):
2626
+ *
2627
+ * 1. \`register(container)\` — runs before user modules load. Use
2628
+ * it to bind services that modules depend on.
2629
+ * 2. \`modules()\` — plugin modules load before user modules.
2630
+ * 3. \`adapters()\` — plugin adapters mount before user adapters.
2631
+ * 4. \`middleware()\` — plugin middleware runs before user middleware.
2632
+ * 5. \`contributors()\` — Context Contributors merged into every route.
2633
+ * 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
2634
+ * 7. \`shutdown()\` — runs on graceful shutdown.
2635
+ *
2636
+ * @example
2637
+ * \`\`\`ts
2638
+ * import { bootstrap } from '@forinda/kickjs'
2639
+ * import { ${i}Plugin } from './plugins/${r}.plugin'
2640
+ *
2641
+ * export const app = await bootstrap({
2642
+ * modules,
2643
+ * plugins: [${i}Plugin({ /* config overrides *\\/ })],
2644
+ * })
2645
+ * \`\`\`
2646
+ */
2647
+ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
2648
+ name: '${i}Plugin',
2649
+ defaults: {
2650
+ // Default config values go here
2651
+ },
2652
+ build: (_config, { name: _name }) => ({
2653
+ /**
2654
+ * Register DI bindings before modules load.
2655
+ * Use \`container.registerInstance(TOKEN, value)\` for singletons
2656
+ * and \`container.registerFactory(TOKEN, () => ...)\` for lazy
2657
+ * constructions.
2658
+ */
2659
+ register(_container: Container): void {
2660
+ // Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
2661
+ },
2662
+
2663
+ /**
2664
+ * Return module classes this plugin contributes to the app.
2665
+ * These load before user modules, so plugin controllers and
2666
+ * services are available for user code to \`@Autowired\`.
2667
+ */
2668
+ modules(): AppModuleClass[] {
2669
+ return [
2670
+ // ExampleModule,
2671
+ ]
2672
+ },
2673
+
2674
+ /**
2675
+ * Return adapter instances to be added to the application.
2676
+ * Plugin adapters mount before user adapters.
2677
+ */
2678
+ adapters(): AppAdapter[] {
2679
+ return [
2680
+ // MyAdapter({ ... }),
2681
+ ]
2682
+ },
2683
+
2684
+ /**
2685
+ * Return Express middleware entries to be added to the global
2686
+ * pipeline. Plugin middleware runs before user-defined middleware.
2687
+ */
2688
+ middleware(): unknown[] {
2689
+ return [
2690
+ // helmet(),
2691
+ // myCustomMiddleware(_config),
2692
+ ]
2693
+ },
2694
+
2695
+ /**
2696
+ * Return Context Contributors to merge into every route's pipeline.
2697
+ * Plugins contribute at the same \`'adapter'\` precedence level as
2698
+ * adapters — overrideable per-route at the method / class / module
2699
+ * level. See https://forinda.github.io/kick-js/guide/context-decorators
2700
+ *
2701
+ * Delete this hook if your plugin doesn't ship typed per-request values.
2702
+ */
2703
+ contributors(): ContributorRegistrations {
2704
+ return [
2705
+ // Example:
2706
+ // import { defineHttpContextDecorator } from '@forinda/kickjs'
2707
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
2708
+ // const Load${i} = defineHttpContextDecorator({
2709
+ // key: '${r}',
2710
+ // resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
2711
+ // })
2712
+ // return [Load${i}.registration]
2713
+ ]
2714
+ },
2715
+
2716
+ /**
2717
+ * Called after the application has fully bootstrapped. Use this
2718
+ * for post-startup work like logging, health checks, or warming
2719
+ * a cache. Runs once per process.
2720
+ */
2721
+ async onReady(_container: Container): Promise<void> {
2722
+ // const log = _container.resolve(Logger)
2723
+ // log.info('${i} plugin ready')
2724
+ },
2725
+
2726
+ /**
2727
+ * Called during graceful shutdown. Clean up any long-lived
2728
+ * resources this plugin owns (connections, timers, subscriptions).
2729
+ */
2730
+ async shutdown(): Promise<void> {
2731
+ // Example: await this.connection?.close()
2732
+ },
2733
+ }),
2734
+ })
2735
+ `),a.push(o),a}const kn={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},An={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},jn={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function U(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,pattern:o=`ddd`,shouldPluralize:s=!0}=e;if(n)return S(n);if(r){let e=o===`ddd`?kn:o===`cqrs`?jn:An,n=B(r),a=s?V(n):n,c=e[t]??``,l=b(i,a);return S(c?b(l,c):l)}return S(a)}async function Mn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=z(t),c=[],l=b(a,`${o}.middleware.ts`);return await A(l,`import type { Request, Response, NextFunction } from 'express'
2736
+
2737
+ export interface ${R(t)}Options {
2738
+ // Add configuration options here
2739
+ }
2740
+
2741
+ /**
2742
+ * ${R(t)} middleware.
2743
+ *
2744
+ * Usage in bootstrap:
2745
+ * middleware: [${s}()]
2746
+ *
2747
+ * Usage with adapter:
2748
+ * middleware() { return [{ handler: ${s}(), phase: 'afterGlobal' }] }
2749
+ *
2750
+ * Usage with @Middleware decorator:
2751
+ * @Middleware(${s}())
2752
+ */
2753
+ export function ${s}(options: ${R(t)}Options = {}) {
2754
+ return (req: Request, res: Response, next: NextFunction) => {
2755
+ // Implement your middleware logic here
2756
+ next()
2757
+ }
2758
+ }
2759
+ `),c.push(l),c}async function Nn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=z(t),c=R(t),l=[],u=b(a,`${o}.guard.ts`);return await A(u,`import { Container, HttpException } from '@forinda/kickjs'
2760
+ import type { RequestContext } from '@forinda/kickjs'
2761
+
2762
+ /**
2763
+ * ${c} guard.
2764
+ *
2765
+ * Guards protect routes by checking conditions before the handler runs.
2766
+ * Return early with an error response to block access.
2767
+ *
2768
+ * Usage:
2769
+ * @Middleware(${s}Guard)
2770
+ * @Get('/protected')
2771
+ * async handler(ctx: RequestContext) { ... }
2772
+ */
2773
+ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<void> {
2774
+ // Example: check for an authorization header
2775
+ const header = ctx.headers.authorization
2776
+ if (!header?.startsWith('Bearer ')) {
2777
+ ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
2778
+ return
2779
+ }
2780
+
2781
+ const token = header.slice(7)
2782
+
2783
+ try {
2784
+ // Verify the token using a service from the DI container
2785
+ // const container = Container.getInstance()
2786
+ // const authService = container.resolve(AuthService)
2787
+ // const payload = authService.verifyToken(token)
2788
+ // ctx.set('auth', payload)
2789
+
2790
+ next()
2791
+ } catch {
2792
+ ctx.res.status(401).json({ message: 'Invalid or expired token' })
2793
+ }
2794
+ }
2795
+ `),l.push(u),l}async function Pn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=b(a,`${o}.service.ts`);return await A(l,`import { Service } from '@forinda/kickjs'
2796
+
2797
+ @Service()
2798
+ export class ${s}Service {
2799
+ // Inject dependencies via constructor
2800
+ // constructor(
2801
+ // @Inject(MY_REPO) private readonly repo: IMyRepository,
2802
+ // ) {}
2803
+ }
2804
+ `),c.push(l),c}async function Fn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=b(a,`${o}.controller.ts`);return await A(l,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
2805
+
2806
+ // \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
2807
+ // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
2808
+ // will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
2809
+ // See https://forinda.github.io/kick-js/guide/typegen for details.
2810
+
2811
+ @Controller()
2812
+ export class ${s}Controller {
2813
+ // @Autowired() private readonly myService!: MyService
2814
+
2815
+ @Get('/')
2816
+ async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
2817
+ ctx.json({ message: '${s} list' })
2818
+ }
2819
+
2820
+ @Post('/')
2821
+ async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
2822
+ ctx.created({ message: '${s} created', data: ctx.body })
2823
+ }
2824
+ }
2825
+ `),c.push(l),c}async function In(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=z(t),l=[],u=b(a,`${o}.dto.ts`);return await A(u,`import { z } from 'zod'
2826
+
2827
+ export const ${c}Schema = z.object({
2828
+ // Define your schema fields here
2829
+ name: z.string().min(1).max(200),
2830
+ })
2831
+
2832
+ export type ${s}DTO = z.infer<typeof ${c}Schema>
2833
+ `),l.push(u),l}async function Ln(e){let t=b(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return h(t)&&!e.force&&!await F({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
2834
+ Skipped — existing kick.config.ts preserved.`),[]):(await A(t,`import { defineConfig } from '@forinda/kickjs-cli'
2835
+
2836
+ export default defineConfig({
2837
+ modules: {
2838
+ dir: '${n}',
2839
+ repo: '${r}',
2840
+ pluralize: true,
2841
+ },
2842
+
2843
+ typegen: {
2844
+ schemaValidator: 'zod',
2845
+ },
2846
+
2847
+ commands: [
2848
+ {
2849
+ name: 'test',
2850
+ description: 'Run tests with Vitest',
2851
+ steps: 'npx vitest run',
2852
+ },
2853
+ {
2854
+ name: 'format',
2855
+ description: 'Format code with Prettier',
2856
+ steps: 'npx prettier --write src/',
2857
+ },
2858
+ {
2859
+ name: 'format:check',
2860
+ description: 'Check formatting without writing',
2861
+ steps: 'npx prettier --check src/',
2862
+ },
2863
+ {
2864
+ name: 'ci:check',
2865
+ description: 'Run typecheck + format check',
2866
+ steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
2867
+ aliases: ['verify'],
2868
+ },
2869
+ ],
2870
+ })
2871
+ `),[t])}const Rn=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function zn(e,t){if(t)return t;try{let t=JSON.parse(_(b(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function Bn(e,t){if(t)return t;try{let t=JSON.parse(_(b(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function Vn(e,t){if(t)return t;try{let t=(await r(e))?.pattern;if(t&&Rn.has(t))return t}catch{}return`ddd`}async function Hn(e){let t=e.only??`all`,n=zn(e.outDir,e.name),r=Bn(e.outDir,e.pm),i=await Vn(e.outDir,e.template),a=t===`agents`||t===`both`||t===`all`,o=t===`claude`||t===`both`||t===`all`,s=t===`skills`||t===`all`,c=[];a&&c.push({file:b(e.outDir,`AGENTS.md`),render:()=>nt(n,i,r)}),o&&c.push({file:b(e.outDir,`CLAUDE.md`),render:()=>tt(n,i,r)}),s&&c.push({file:b(e.outDir,`kickjs-skills.md`),render:()=>rt(n,i,r)});let l=[];for(let{file:t,render:n}of c){if(h(t)&&!e.force&&!await F({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await A(t,n()),l.push(t)}return l}async function Un(e={}){let t=e.strategy??`jwt`,n=e.outDir??`src/modules/auth`,r=b(n,`dto`),i=[],a=b(n,`auth.module.ts`);await A(a,`import { Module } from '@forinda/kickjs'
2872
+ import { AuthController } from './auth.controller'
2873
+ import { AuthService } from './auth.service'
2874
+
2875
+ @Module({
2876
+ controllers: [AuthController],
2877
+ services: [AuthService],
2878
+ })
2879
+ export class AuthModule {}
2880
+ `),i.push(a);let o=b(n,`auth.controller.ts`);await A(o,t===`jwt`?Wn():Kn()),i.push(o);let s=b(n,`auth.service.ts`);await A(s,t===`jwt`?Gn():qn()),i.push(s);let c=b(r,`register.dto.ts`);await A(c,`import { z } from 'zod'
2881
+
2882
+ export const RegisterDto = z.object({
2883
+ email: z.string().email(),
2884
+ password: z.string().min(8),
2885
+ name: z.string().min(1).optional(),
2886
+ })
2887
+
2888
+ export type RegisterInput = z.infer<typeof RegisterDto>
2889
+ `),i.push(c);let l=b(r,`login.dto.ts`);await A(l,`import { z } from 'zod'
2890
+
2891
+ export const LoginDto = z.object({
2892
+ email: z.string().email(),
2893
+ password: z.string().min(1),
2894
+ })
2895
+
2896
+ export type LoginInput = z.infer<typeof LoginDto>
2897
+ `),i.push(l);let u=b(n,`auth.test.ts`);if(await A(u,`import { describe, it, expect } from 'vitest'
2898
+
2899
+ describe('Auth Module', () => {
2900
+ it.todo('POST /register — creates a new user')
2901
+ it.todo('POST /login — returns token for valid credentials')
2902
+ it.todo('POST /login — rejects invalid credentials')
2903
+ it.todo('POST /logout — invalidates session/token')
2904
+ it.todo('GET /me — returns authenticated user')
2905
+ })
2906
+ `),i.push(u),e.roleGuards!==!1){let e=b(n,`auth.guard.ts`);await A(e,`import { Roles } from '@forinda/kickjs-auth'
2907
+
2908
+ /**
2909
+ * Role-based access guard.
2910
+ * Usage: @Roles('admin') on a controller method.
2911
+ *
2912
+ * The AuthAdapter extracts the user's roles from the JWT/session
2913
+ * and the framework checks them automatically.
2914
+ */
2915
+ export const AdminOnly = Roles('admin')
2916
+ export const ManagerOnly = Roles('manager')
2917
+ `),i.push(e)}return i}function Wn(){return`import { Controller, Post, Get } from '@forinda/kickjs'
2918
+ import { Authenticated, Public } from '@forinda/kickjs-auth'
2919
+ import type { RequestContext } from '@forinda/kickjs'
2920
+ import { Autowired } from '@forinda/kickjs'
2921
+ import { AuthService } from './auth.service'
2922
+
2923
+ @Controller()
2924
+ @Authenticated()
2925
+ export class AuthController {
2926
+ @Autowired() private authService!: AuthService
2927
+
2928
+ @Post('/register')
2929
+ @Public()
2930
+ async register(ctx: RequestContext) {
2931
+ const result = await this.authService.register(ctx.body)
2932
+ return ctx.created(result)
2933
+ }
2934
+
2935
+ @Post('/login')
2936
+ @Public()
2937
+ async login(ctx: RequestContext) {
2938
+ const result = await this.authService.login(ctx.body)
2939
+ if (!result) return ctx.badRequest('Invalid credentials')
2940
+ return ctx.json(result)
2941
+ }
2942
+
2943
+ @Post('/logout')
2944
+ async logout(ctx: RequestContext) {
2945
+ return ctx.json({ message: 'Logged out' })
2946
+ }
2947
+
2948
+ @Get('/me')
2949
+ async me(ctx: RequestContext) {
2950
+ return ctx.json({ user: ctx.user })
2951
+ }
2952
+ }
2953
+ `}function Gn(){return`import { Service, Autowired } from '@forinda/kickjs'
2954
+ import { PasswordService } from '@forinda/kickjs-auth'
2955
+ import type { RegisterInput } from './dto/register.dto'
2956
+ import type { LoginInput } from './dto/login.dto'
2957
+
2958
+ // TODO: Replace with your User repository
2959
+ const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
2960
+
2961
+ @Service()
2962
+ export class AuthService {
2963
+ @Autowired() private password!: PasswordService
2964
+
2965
+ async register(input: RegisterInput) {
2966
+ const { email, password, name } = input
2967
+
2968
+ if (users.has(email)) {
2969
+ throw new Error('User already exists')
2970
+ }
2971
+
2972
+ const passwordHash = await this.password.hash(password)
2973
+ const id = crypto.randomUUID()
2974
+ users.set(email, { id, email, name, passwordHash })
2975
+
2976
+ return { id, email, name }
2977
+ }
2978
+
2979
+ async login(input: LoginInput) {
2980
+ const { email, password } = input
2981
+ const user = users.get(email)
2982
+ if (!user) return null
2983
+
2984
+ const valid = await this.password.verify(user.passwordHash, password)
2985
+ if (!valid) return null
2986
+
2987
+ // TODO: Generate JWT token here
2988
+ // const token = jwt.sign({ sub: user.id, email: user.email }, process.env.JWT_SECRET!)
2989
+ return { user: { id: user.id, email: user.email, name: user.name } }
2990
+ }
2991
+ }
2992
+ `}function Kn(){return`import { Controller, Post, Get } from '@forinda/kickjs'
2993
+ import { Authenticated, Public } from '@forinda/kickjs-auth'
2994
+ import { sessionLogin, sessionLogout } from '@forinda/kickjs-auth'
2995
+ import type { RequestContext } from '@forinda/kickjs'
2996
+ import { Autowired } from '@forinda/kickjs'
2997
+ import { AuthService } from './auth.service'
2998
+
2999
+ @Controller()
3000
+ @Authenticated()
3001
+ export class AuthController {
3002
+ @Autowired() private authService!: AuthService
3003
+
3004
+ @Post('/register')
3005
+ @Public()
3006
+ async register(ctx: RequestContext) {
3007
+ const result = await this.authService.register(ctx.body)
3008
+ return ctx.created(result)
3009
+ }
3010
+
3011
+ @Post('/login')
3012
+ @Public()
3013
+ async login(ctx: RequestContext) {
3014
+ const user = await this.authService.login(ctx.body)
3015
+ if (!user) return ctx.badRequest('Invalid credentials')
3016
+ await sessionLogin(ctx.session, user)
3017
+ return ctx.json({ message: 'Logged in', user })
3018
+ }
3019
+
3020
+ @Post('/logout')
3021
+ async logout(ctx: RequestContext) {
3022
+ await sessionLogout(ctx.session)
3023
+ return ctx.json({ message: 'Logged out' })
3024
+ }
3025
+
3026
+ @Get('/me')
3027
+ async me(ctx: RequestContext) {
3028
+ return ctx.json({ user: ctx.user })
3029
+ }
3030
+ }
3031
+ `}function qn(){return`import { Service, Autowired } from '@forinda/kickjs'
3032
+ import { PasswordService } from '@forinda/kickjs-auth'
3033
+ import type { RegisterInput } from './dto/register.dto'
3034
+ import type { LoginInput } from './dto/login.dto'
3035
+
3036
+ // TODO: Replace with your User repository
3037
+ const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
3038
+
3039
+ @Service()
3040
+ export class AuthService {
3041
+ @Autowired() private password!: PasswordService
3042
+
3043
+ async register(input: RegisterInput) {
3044
+ const { email, password, name } = input
3045
+
3046
+ if (users.has(email)) {
3047
+ throw new Error('User already exists')
3048
+ }
3049
+
3050
+ const passwordHash = await this.password.hash(password)
3051
+ const id = crypto.randomUUID()
3052
+ users.set(email, { id, email, name, passwordHash })
3053
+
3054
+ return { id, email, name }
3055
+ }
3056
+
3057
+ async login(input: LoginInput) {
3058
+ const { email, password } = input
3059
+ const user = users.get(email)
3060
+ if (!user) return null
3061
+
3062
+ const valid = await this.password.verify(user.passwordHash, password)
3063
+ if (!valid) return null
3064
+
3065
+ return { id: user.id, email: user.email, name: user.name }
3066
+ }
3067
+ }
3068
+ `}async function Jn(e){let{name:t,outDir:n}=e,r=R(t),i=B(t),a=z(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=b(n,e);await A(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
3069
+ import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
3070
+
3071
+ /**
3072
+ * ${r} Job Processor
3073
+ *
3074
+ * Decorators:
3075
+ * @Job(queueName) — marks this class as a job processor for a queue
3076
+ * @Process(jobName?) — marks a method as the handler for a specific job type
3077
+ * - Without a name: handles all jobs in the queue
3078
+ * - With a name: handles only jobs matching that name
3079
+ *
3080
+ * To add jobs to this queue from a service or controller:
3081
+ * @Inject(QUEUE_MANAGER) private queue: QueueService
3082
+ * await this.queue.add('${o}', '${a}', { ... })
3083
+ */
3084
+ @Job('${o}')
3085
+ export class ${r}Job {
3086
+ @Process()
3087
+ async handle(job: { name: string; data: any; id?: string }) {
3088
+ console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
3089
+
3090
+ // TODO: Implement job logic here
3091
+ // Example:
3092
+ // await this.emailService.send(job.data.to, job.data.subject, job.data.body)
3093
+ }
3094
+
3095
+ @Process('${a}.priority')
3096
+ async handlePriority(job: { name: string; data: any; id?: string }) {
3097
+ console.log(\`Priority job: \${job.name}\`, job.data)
3098
+ // Handle high-priority variant of this job
3099
+ }
3100
+ }
3101
+ `),s}const Yn={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function Xn(e){return e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=Yn[a];if(!o){let e=[...Object.keys(Yn),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}})}async function Zn(e){let{name:t,fields:n,modulesDir:r,noEntity:i,noTests:a,repo:o=`inmemory`,tokenScope:s=`app`}=e,c=e.pluralize!==!1,l=B(t),u=R(t);z(t);let d=c?V(l):l,f=c?Dt(u):u,p=b(r,d),m=[],h=async(e,t)=>{let n=b(p,e);await A(n,t),m.push(n)};await h(`${l}.module.ts`,ar(u,l,d)),await h(`constants.ts`,tr(u,n)),await h(`presentation/${l}.controller.ts`,or(u,l,d,f)),await h(`application/dtos/create-${l}.dto.ts`,Qn(u,n)),await h(`application/dtos/update-${l}.dto.ts`,$n(u,n)),await h(`application/dtos/${l}-response.dto.ts`,er(u,n));let g=lr(u,l,d,f);for(let e of g)await h(`application/use-cases/${e.file}`,e.content);return await h(`domain/repositories/${l}.repository.ts`,sr(u,l,s)),await h(`domain/services/${l}-domain.service.ts`,cr(u,l)),o===`inmemory`&&await h(`infrastructure/repositories/in-memory-${l}.repository.ts`,nr(u,l,n)),i||(await h(`domain/entities/${l}.entity.ts`,rr(u,l,n)),await h(`domain/value-objects/${l}-id.vo.ts`,ir(u))),await ur(r,u,d,l),m}function Qn(e,t){return`import { z } from 'zod'
3102
+
3103
+ export const create${e}Schema = z.object({
3104
+ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
3105
+ `)}
3106
+ })
3107
+
3108
+ export type Create${e}DTO = z.infer<typeof create${e}Schema>
3109
+ `}function $n(e,t){return`import { z } from 'zod'
3110
+
3111
+ export const update${e}Schema = z.object({
3112
+ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
3113
+ `)}
3114
+ })
3115
+
3116
+ export type Update${e}DTO = z.infer<typeof update${e}Schema>
3117
+ `}function er(e,t){return`export interface ${e}ResponseDTO {
3118
+ id: string
3119
+ ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
3120
+ `)}
3121
+ createdAt: string
3122
+ updatedAt: string
3123
+ }
3124
+ `}function tr(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
3125
+
3126
+ export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
3127
+ filterable: [${i}],
3128
+ sortable: [${a}],
3129
+ searchable: [${o}],
3130
+ }
3131
+ `}function nr(e,t,n){return`import { randomUUID } from 'node:crypto'
3132
+ import { Repository, HttpException } from '@forinda/kickjs'
3133
+ import type { ParsedQuery } from '@forinda/kickjs'
3134
+ import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
3135
+ import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
3136
+ import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
3137
+ import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
3138
+
3139
+ @Repository()
3140
+ export class InMemory${e}Repository implements I${e}Repository {
3141
+ private store = new Map<string, ${e}ResponseDTO>()
3142
+
3143
+ async findById(id: string): Promise<${e}ResponseDTO | null> {
3144
+ return this.store.get(id) ?? null
3145
+ }
3146
+
3147
+ async findAll(): Promise<${e}ResponseDTO[]> {
3148
+ return Array.from(this.store.values())
3149
+ }
3150
+
3151
+ async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
3152
+ const all = Array.from(this.store.values())
3153
+ const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
3154
+ return { data, total: all.length }
3155
+ }
3156
+
3157
+ async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
3158
+ const now = new Date().toISOString()
3159
+ const entity: ${e}ResponseDTO = {
3160
+ id: randomUUID(),
3161
+ ${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
3162
+ `)}
3163
+ createdAt: now,
3164
+ updatedAt: now,
3165
+ }
3166
+ this.store.set(entity.id, entity)
3167
+ return entity
3168
+ }
3169
+
3170
+ async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
3171
+ const existing = this.store.get(id)
3172
+ if (!existing) throw HttpException.notFound('${e} not found')
3173
+ const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
3174
+ this.store.set(id, updated)
3175
+ return updated
3176
+ }
3177
+
3178
+ async delete(id: string): Promise<void> {
3179
+ if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
3180
+ this.store.delete(id)
3181
+ }
3182
+ }
3183
+ `}function rr(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
3184
+
3185
+ interface ${e}Props {
3186
+ id: ${e}Id
3187
+ ${n.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
3188
+ `)}
3189
+ createdAt: Date
3190
+ updatedAt: Date
3191
+ }
3192
+
3193
+ export class ${e} {
3194
+ private constructor(private props: ${e}Props) {}
3195
+
3196
+ static create(params: { ${n.filter(e=>!e.optional).map(e=>`${e.name}: ${e.tsType}`).join(`; `)} }): ${e} {
3197
+ const now = new Date()
3198
+ return new ${e}({
3199
+ id: ${e}Id.create(),
3200
+ ${n.filter(e=>!e.optional).map(e=>` ${e.name}: params.${e.name},`).join(`
3201
+ `)}
3202
+ createdAt: now,
3203
+ updatedAt: now,
3204
+ })
3205
+ }
3206
+
3207
+ static reconstitute(props: ${e}Props): ${e} {
3208
+ return new ${e}(props)
3209
+ }
3210
+
3211
+ get id(): ${e}Id { return this.props.id }
3212
+ ${n.map(e=>` get ${e.name}(): ${e.tsType}${e.optional?` | undefined`:``} {
3213
+ return this.props.${e.name}
3214
+ }`).join(`
3215
+ `)}
3216
+ get createdAt(): Date { return this.props.createdAt }
3217
+ get updatedAt(): Date { return this.props.updatedAt }
3218
+
3219
+ toJSON() {
3220
+ return {
3221
+ id: this.props.id.toString(),
3222
+ ${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
3223
+ `)}
3224
+ createdAt: this.props.createdAt.toISOString(),
3225
+ updatedAt: this.props.updatedAt.toISOString(),
3226
+ }
3227
+ }
3228
+ }
3229
+ `}function ir(e){return`import { randomUUID } from 'node:crypto'
3230
+
3231
+ export class ${e}Id {
3232
+ private constructor(private readonly value: string) {}
3233
+
3234
+ static create(): ${e}Id { return new ${e}Id(randomUUID()) }
3235
+
3236
+ static from(id: string): ${e}Id {
3237
+ if (!id || id.trim().length === 0) throw new Error('${e}Id cannot be empty')
3238
+ return new ${e}Id(id)
3239
+ }
3240
+
3241
+ toString(): string { return this.value }
3242
+ equals(other: ${e}Id): boolean { return this.value === other.value }
3243
+ }
3244
+ `}function ar(e,t,n){return`import { type AppModule, type ModuleRoutes, Container, buildRoutes } from '@forinda/kickjs'
3245
+ import { ${e}Controller } from './presentation/${t}.controller'
3246
+ import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
3247
+ import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
3248
+
3249
+ // Eagerly load decorated classes so @Service()/@Repository() decorators
3250
+ // register in the DI container before the application bootstraps.
3251
+ import.meta.glob(
3252
+ ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
3253
+ { eager: true },
3254
+ )
3255
+
3256
+ export class ${e}Module implements AppModule {
3257
+ /**
3258
+ * Bind the repository token to its concrete implementation.
3259
+ * Decorator-managed classes (@Service, @Controller, @Repository) are
3260
+ * registered automatically — only token-to-impl bindings need to live here.
3261
+ */
3262
+ register(container: Container): void {
3263
+ container.registerFactory(
3264
+ ${e.toUpperCase()}_REPOSITORY,
3265
+ () => container.resolve(InMemory${e}Repository),
3266
+ )
3267
+ }
3268
+
3269
+ routes(): ModuleRoutes {
3270
+ return {
3271
+ path: '/${n}',
3272
+ router: buildRoutes(${e}Controller),
3273
+ controller: ${e}Controller,
3274
+ }
3275
+ }
3276
+ }
3277
+ `}function or(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
3278
+ import { ApiTags } from '@forinda/kickjs-swagger'
3279
+ import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
3280
+ import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
3281
+ import { List${r}UseCase } from '../application/use-cases/list-${n}.use-case'
3282
+ import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
3283
+ import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
3284
+ import { create${e}Schema } from '../application/dtos/create-${t}.dto'
3285
+ import { update${e}Schema } from '../application/dtos/update-${t}.dto'
3286
+ import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
3287
+
3288
+ // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${e}Controller['<method>']>\`
3289
+ // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
3290
+ // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
3291
+ // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
3292
+
3293
+ @Controller()
3294
+ export class ${e}Controller {
3295
+ @Autowired() private readonly create${e}UseCase!: Create${e}UseCase
3296
+ @Autowired() private readonly get${e}UseCase!: Get${e}UseCase
3297
+ @Autowired() private readonly list${r}UseCase!: List${r}UseCase
3298
+ @Autowired() private readonly update${e}UseCase!: Update${e}UseCase
3299
+ @Autowired() private readonly delete${e}UseCase!: Delete${e}UseCase
3300
+
3301
+ @Get('/')
3302
+ @ApiTags('${e}')
3303
+ @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
3304
+ async list(ctx: Ctx<KickRoutes.${e}Controller['list']>) {
3305
+ return ctx.paginate(
3306
+ (parsed) => this.list${r}UseCase.execute(parsed),
3307
+ ${e.toUpperCase()}_QUERY_CONFIG,
3308
+ )
3309
+ }
3310
+
3311
+ @Get('/:id')
3312
+ @ApiTags('${e}')
3313
+ async getById(ctx: Ctx<KickRoutes.${e}Controller['getById']>) {
3314
+ const result = await this.get${e}UseCase.execute(ctx.params.id)
3315
+ if (!result) return ctx.notFound('${e} not found')
3316
+ ctx.json(result)
3317
+ }
3318
+
3319
+ @Post('/', { body: create${e}Schema, name: 'Create${e}' })
3320
+ @ApiTags('${e}')
3321
+ async create(ctx: Ctx<KickRoutes.${e}Controller['create']>) {
3322
+ const result = await this.create${e}UseCase.execute(ctx.body)
3323
+ ctx.created(result)
3324
+ }
3325
+
3326
+ @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
3327
+ @ApiTags('${e}')
3328
+ async update(ctx: Ctx<KickRoutes.${e}Controller['update']>) {
3329
+ const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
3330
+ ctx.json(result)
3331
+ }
3332
+
3333
+ @Delete('/:id')
3334
+ @ApiTags('${e}')
3335
+ async remove(ctx: Ctx<KickRoutes.${e}Controller['remove']>) {
3336
+ await this.delete${e}UseCase.execute(ctx.params.id)
3337
+ ctx.noContent()
3338
+ }
3339
+ }
3340
+ `}function sr(e,t,n){return`import { createToken } from '@forinda/kickjs'
3341
+ import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
3342
+ import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
3343
+ import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
3344
+ import type { ParsedQuery } from '@forinda/kickjs'
3345
+
3346
+ export interface I${e}Repository {
3347
+ findById(id: string): Promise<${e}ResponseDTO | null>
3348
+ findAll(): Promise<${e}ResponseDTO[]>
3349
+ findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
3350
+ create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
3351
+ update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
3352
+ delete(id: string): Promise<void>
3353
+ }
3354
+
3355
+ /**
3356
+ * Collision-safe DI token bound to \`I${e}Repository\`.
3357
+ * \`container.resolve(${e.toUpperCase()}_REPOSITORY)\` and
3358
+ * \`@Inject(${e.toUpperCase()}_REPOSITORY)\` both return the typed
3359
+ * interface — no manual generic, no \`any\` cast.
3360
+ *
3361
+ * The \`'${n}/'\` prefix matches the project scope so
3362
+ * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
3363
+ * adopters must NOT use the reserved \`'kick/'\` namespace.
3364
+ */
3365
+ export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
3366
+ `}function cr(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
3367
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
3368
+
3369
+ @Service()
3370
+ export class ${e}DomainService {
3371
+ constructor(
3372
+ @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
3373
+ ) {}
3374
+
3375
+ async ensureExists(id: string): Promise<void> {
3376
+ const entity = await this.repo.findById(id)
3377
+ if (!entity) throw HttpException.notFound('${e} not found')
3378
+ }
3379
+ }
3380
+ `}function lr(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3381
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3382
+ import type { Create${e}DTO } from '../dtos/create-${t}.dto'
3383
+
3384
+ @Service()
3385
+ export class Create${e}UseCase {
3386
+ constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3387
+ async execute(dto: Create${e}DTO) { return this.repo.create(dto) }
3388
+ }
3389
+ `},{file:`get-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3390
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3391
+
3392
+ @Service()
3393
+ export class Get${e}UseCase {
3394
+ constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3395
+ async execute(id: string) { return this.repo.findById(id) }
3396
+ }
3397
+ `},{file:`list-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3398
+ import type { ParsedQuery } from '@forinda/kickjs'
3399
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3400
+
3401
+ @Service()
3402
+ export class List${r}UseCase {
3403
+ constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3404
+ async execute(parsed: ParsedQuery) { return this.repo.findPaginated(parsed) }
3405
+ }
3406
+ `},{file:`update-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3407
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3408
+ import type { Update${e}DTO } from '../dtos/update-${t}.dto'
3409
+
3410
+ @Service()
3411
+ export class Update${e}UseCase {
3412
+ constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3413
+ async execute(id: string, dto: Update${e}DTO) { return this.repo.update(id, dto) }
3414
+ }
3415
+ `},{file:`delete-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3416
+ import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3417
+
3418
+ @Service()
3419
+ export class Delete${e}UseCase {
3420
+ constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3421
+ async execute(id: string) { return this.repo.delete(id) }
3422
+ }
3423
+ `}]}async function ur(e,t,n,r){let i=b(e,`index.ts`),a=await N(i),o=`./${n}/${r}.module`;if(!a){await A(i,`import type { AppModuleClass } from '@forinda/kickjs'\nimport { ${t}Module } from '${o}'\n\nexport const modules: AppModuleClass[] = [${t}Module]\n`);return}let s=await T(i,`utf-8`),c=`import { ${t}Module } from '${o}'`;if(!s.includes(`${t}Module`)){let e=s.lastIndexOf(`import `);if(e!==-1){let t=s.indexOf(`
3424
+ `,e);s=s.slice(0,t+1)+c+`
3425
+ `+s.slice(t+1)}else s=c+`
3426
+ `+s;s=s.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 E(i,s,`utf-8`)}async function dr(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=B(t),o=R(t),s=[],c;if(e.outDir)c=S(e.outDir);else if(n){let e=B(n),t=i?V(e):e;c=S(b(r??`src/modules`,t,`__tests__`))}else c=S(`src/__tests__`);let l=b(c,`${a}.test.ts`);return await A(l,`import { describe, it, expect, beforeEach } from 'vitest'
3427
+ import { Container } from '@forinda/kickjs'
3428
+
3429
+ describe('${o}', () => {
3430
+ beforeEach(() => {
3431
+ Container.reset()
3432
+ })
3433
+
3434
+ it('should be defined', () => {
3435
+ // TODO: Import and test your class/function here
3436
+ expect(true).toBe(true)
3437
+ })
3438
+
3439
+ it('should handle the happy path', async () => {
3440
+ // TODO: Set up test data and assertions
3441
+ expect(true).toBe(true)
3442
+ })
3443
+
3444
+ it('should handle edge cases', async () => {
3445
+ // TODO: Test error handling, empty inputs, etc.
3446
+ expect(true).toBe(true)
3447
+ })
3448
+ })
3449
+ `),s.push(l),s}const fr=[`agents`,`claude`,`skills`,`both`,`all`];function W(e){return e.parent?.opts()?.dryRun??!1}function G(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
3450
+ (dry run — no files were written)`),console.log()}async function pr(e){if(!e)try{let e=await r(process.cwd());await f({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const mr=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}];async function hr(){console.log(`
3451
+ Built-in generators:
3452
+ `);let e=Math.max(...mr.map(e=>e.name.length));for(let t of mr)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await r(process.cwd()),n=a(t?.plugins??[],t?.commands??[]),i=await Rt(process.cwd(),n.generators);if(i.generators.length>0){console.log(`
3453
+ Plugin generators:
3454
+ `);let e=Math.max(...i.generators.map(e=>`${e.spec.name} <name>`.length));for(let{source:t,spec:n}of i.generators){let r=`${n.name} <name>`;console.log(` kick g ${r.padEnd(e+2)} ${n.description} [${t}]`)}}if(i.failed.length>0){console.log(`
3455
+ Failed to load:
3456
+ `);for(let{source:e,reason:t}of i.failed)console.log(` ${e} — ${t}`)}console.log()}async function gr(e,i,a){let o=await r(process.cwd()),s=n(o),c=i.modulesDir??s.dir??`src/modules`,l=i.repo??wn(s.repo),u=i.pattern??o?.pattern??`ddd`,d=i.pluralize===!1?!1:s.pluralize??!0,f=t(o,process.cwd()),p=[];for(let t of e){let e=await Tn({name:t,modulesDir:S(c),noEntity:i.entity===!1,noTests:i.tests===!1,repo:l,minimal:i.minimal,force:i.force,pattern:u,dryRun:a,pluralize:d,prismaClientPath:s.prismaClientPath,tokenScope:f});p.push(...e)}G(p,a),await pr(a)}function _r(e){let i=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{if(t.list){await hr();return}if(!e||e.length===0){i.help();return}let o=W(n);if(k(o),e.length>=2){let[n,i,...s]=e,c=await r(process.cwd()),l=a(c?.plugins??[],c?.commands??[]),u=await Lt({generatorName:n,itemName:i,args:s,flags:t,cwd:process.cwd()},l.generators);if(u){G(u.files,o);return}}await gr(e,t,o)});i.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=W(n);k(r),await gr(e,t,r)}),i.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=W(n);k(r),G(await Dn({name:e,outDir:S(t.out)}),r)}),i.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=W(n);k(r),G(await On({name:e,outDir:S(t.out)}),r)}),i.command(`middleware <name>`).description(`Generate an Express middleware function
3457
+ Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;G(await Mn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
3458
+ Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;G(await Nn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`service <name>`).description(`Generate a @Service() class
3459
+ Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;G(await Pn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
3460
+ Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;G(await Fn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a),await pr(a)}),i.command(`dto <name>`).description(`Generate a Zod DTO schema
3461
+ Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;G(await In({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`test <name>`).description(`Generate a Vitest test scaffold
3462
+ Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,i)=>{let a=W(i);k(a);let o=n(await r(process.cwd())),s=o.dir??`src/modules`;G(await dr({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pluralize:o.pluralize??!0}),a)}),i.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=W(n);k(r),G(await Jn({name:e,outDir:S(t.out),queue:t.queue}),r)}),i.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
3463
+ Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
3464
+ Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
3465
+ Optional: append :optional (shell-safe): description:text:optional
3466
+ or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,i,a,o)=>{let s=W(o);k(s),i.length===0&&(console.error(`
3467
+ Error: At least one field is required.
3468
+ Usage: kick g scaffold <name> <field:type> [field:type...]
3469
+ Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
3470
+ Optional: append :optional (shell-safe, no quoting needed)
3471
+ `),process.exit(1));let c=await r(process.cwd()),l=n(c),u=a.modulesDir??l.dir??`src/modules`,d=Xn(i),f=t(c,process.cwd()),p=await Zn({name:e,fields:d,modulesDir:S(u),noEntity:a.entity===!1,noTests:a.tests===!1,pluralize:a.pluralize===!1?!1:l.pluralize??!0,tokenScope:f});console.log(`\n Scaffolded ${e} with ${d.length} field(s):`);for(let e of d)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(p,s),await pr(s)}),i.command(`auth-scaffold`).description(`Generate a complete auth module (register, login, logout, password hashing)
3472
+ Includes controller, service, DTOs, and test stubs.`).option(`-s, --strategy <type>`,`Auth strategy: jwt | session`).option(`--role-guards`,`Generate role-based guards (default: true)`).option(`--no-role-guards`,`Skip role-based guard generation`).option(`-o, --out <dir>`,`Output directory`,`src/modules/auth`).action(async(e,t)=>{let n=W(t);k(n);let r=e.strategy;r||=await mt({message:`Auth strategy`,options:[{value:`jwt`,label:`JWT`,hint:`stateless token-based auth`},{value:`session`,label:`Session`,hint:`server-side session with cookies`}]});let i=e.roleGuards;i===void 0&&(i=await F({message:`Generate role-based guards?`,initialValue:!0})),G(await Un({strategy:r,outDir:e.out,roleGuards:i}),n)}),i.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=W(t);k(n),G(await Ln({outDir:S(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),i.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=W(t);k(n);let r=e.only??`all`;if(!fr.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${fr.join(` | `)}`),process.exitCode=1;return}G(await Hn({outDir:S(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)})}async function vr(e){let t=v.resolve(e.cwd,`.kickjs/types`);await pe(t,{recursive:!0});let n=new Map,r=e.scan??d,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(C(e).href)},async writeFile(t,n){let r=v.resolve(e.cwd,t);await pe(v.dirname(r),{recursive:!0}),await E(r,n,`utf8`)},getScanResult:e=>{let t=yr(e),i=n.get(t);return i||(i=r(e),n.set(t,i)),i},log:console},a=[];for(let n of e.plugins){let r=await n.generate(i);if(r===null){a.push({id:n.id,status:`skipped`});continue}let o=n.outExtension??`.d.ts`,s=v.join(t,`${n.id.replace(/\//g,`__`)}${o}`),c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+r+`
3473
+ `,l=``;if(h(s)&&(l=await T(s,`utf8`)),l===c){a.push({id:n.id,status:`unchanged`,outFile:s});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${s})`);await E(s,c,`utf8`),a.push({id:n.id,status:`written`,outFile:s})}return a}function yr(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function br(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var xr=e({applyDisableFilter:()=>br,runAllPluginTypegens:()=>Sr});async function Sr(e){let{enabled:t,skipped:n,unknown:r}=br(a([...Zi,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await vr({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function Cr(e,t){let{cwd:n,silent:r=!1}=t,i=t.distDir??e?.build?.outDir??`dist`,a=e?.assetMap;if(!a||Object.keys(a).length===0)return null;let o=r?()=>{}:console.log,s=S(n,i);g(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await wr(e,t,n,s);c.push(r.entrySummary),Object.assign(l,r.manifestSlice),o(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let u={version:1,entries:l},d=b(s,`.kickjs-assets.json`);return re(d,JSON.stringify(u,null,2)+`
3474
+ `,`utf-8`),o(` ✓ wrote manifest → ${x(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function wr(e,t,n,r){let i=S(n,t.src),a=t.dest?S(n,t.dest):b(r,e);if(Er(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:x(n,a),filesCopied:0},manifestSlice:{}};if(!h(i)||!Dr(i))return{entrySummary:{namespace:e,src:t.src,dest:x(n,a),filesCopied:0},manifestSlice:{}};let o=await ge(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});g(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=_e(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=b(i,e),o=b(a,e);g(y(o),{recursive:!0}),m(n,o),s[t]=Tr(r,o)}return l>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${l} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:x(n,a),filesCopied:o.length},manifestSlice:s}}function Tr(e,t){return x(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function Er(e,t){let n=x(t,e);return n===``?!1:n.startsWith(`..`)||oe(n)}function Dr(e){try{return ne(e).isDirectory()}catch{return!1}}function Or(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function kr(e,t,n={}){t&&(process.env.PORT=t);let i=Or(n.polling),a=process.cwd(),o=await r(a),s=o?.typegen?.schemaValidator??`zod`,c=o?.typegen?.envFile;try{await f({cwd:a,allowDuplicates:!0,schemaValidator:s,envFile:c,srcDir:o?.typegen?.srcDir,outDir:o?.typegen?.outDir,assetMap:o?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await Sr({cwd:a,config:o});let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(C(l(S(`package.json`)).resolve(`vite`)).href),d=await u({configFile:S(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...i?{watch:{usePolling:!0,interval:100}}:{}}}),p=o?.assetMap?Object.values(o.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>S(a,e)):[],m=e=>p.some(t=>e===t||e.startsWith(`${t}/`)),h=null,g=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=m(e);!t&&!n||(h&&clearTimeout(h),h=setTimeout(()=>{f({cwd:a,silent:!0,allowDuplicates:!0,schemaValidator:s,envFile:c,srcDir:o?.typegen?.srcDir,outDir:o?.typegen?.outDir,assetMap:o?.assetMap,runPlugins:!1}).catch(()=>{}),Sr({cwd:a,config:o,silent:!0}).catch(()=>{})},100))};d.watcher.on(`add`,g),d.watcher.on(`unlink`,g),d.watcher.on(`change`,g),p.length>0&&d.watcher.add(p),await d.listen(),d.printUrls(),console.log(`
3475
+ KickJS dev server running (Vite + @forinda/kickjs-vite)
3476
+ `);let _=async()=>{h&&clearTimeout(h),await d.close(),process.exit(0)};process.on(`SIGINT`,_),process.on(`SIGTERM`,_)}function Ar(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).action(async e=>{try{await kr(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
3477
+ Error: vite is not installed.
3478
+ Run: pnpm add -D vite unplugin-swc
3479
+ `):console.error(`
3480
+ Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
3481
+ Building for production...
3482
+ `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(C(e(S(`package.json`)).resolve(`vite`)).href);await t({configFile:S(`vite.config.ts`)});let n=await r(process.cwd()),i=n?.copyDirs??[];if(i.length>0){console.log(`
3483
+ Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?b(`dist`,e):e.dest??b(`dist`,t),r=S(t),i=S(n);if(!h(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}g(i,{recursive:!0}),m(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
3484
+ Building asset map...`);try{await Cr(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
3485
+ Build complete.
3486
+ `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await r(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
3487
+ Building asset map...`);try{await Cr(e,{cwd:process.cwd()}),console.log(`
3488
+ Asset build complete.
3489
+ `)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),Ae(e.entry,t)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await kr(e.entry,e.port)}catch(e){console.error(`
3490
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function jr(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
3491
+ KickJS CLI
3492
+
3493
+ System:
3494
+ OS: ${ye()} ${be()} (${ve()})
3495
+ Node: ${process.version}
3496
+
3497
+ Packages:
3498
+ @forinda/kickjs workspace
3499
+ @forinda/kickjs-vite workspace
3500
+ @forinda/kickjs-cli workspace
3501
+ `)})}const{bold:K,dim:q,green:Mr,red:Nr,yellow:Pr,blue:Fr}=O;function Ir(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,a=[];return t&&a.push(`${t}d`),n&&a.push(`${n}h`),r&&a.push(`${r}m`),a.push(`${i}s`),a.join(` `)}async function Lr(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await Lr(`${e}${t}`)}catch{return null}}async function Rr(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function zr(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Mr(`● healthy`):Nr(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${Nr(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Nr:r.errorRate>0?Pr:Mr;console.log(` ${K(`Uptime:`)} ${Ir(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${K(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(s),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${lt(e.method)} ${t} ${Fr(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function Br(e){e.command(`inspect [url]`).description(`Connect to a running KickJS app and display debug info`).option(`-p, --port <port>`,`Override port`).option(`-w, --watch`,`Poll every 5 seconds`).option(`-j, --json`,`Output raw JSON`).action(async(e,t)=>{let n=e??`http://localhost:3000`;if(t.port)try{let e=new URL(n);e.port=t.port,n=e.origin}catch{n=`http://localhost:${t.port}`}let r=`${n.replace(/\/$/,``)}/_debug`,i=async()=>{try{let e=await Rr(r);t.json?console.log(JSON.stringify(e,null,2)):zr(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Nr(` ✖ Could not connect to ${n}`)),console.error(q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Vr(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Y(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Hr=[{match(e,t){let n=Vr(e,[`config`,`get`])&&Y(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Y(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
3502
+ registers the env schema with kickjs at module-load time. Without it,
3503
+ ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
3504
+ and every user-defined key reads as undefined. @Value() may *appear* to
3505
+ work via a raw process.env fallback, but Zod coercion and schema defaults
3506
+ are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
3507
+ import { bootstrap } from '@forinda/kickjs'
3508
+ import { modules } from './modules'
3509
+ `,codeAfter:`import 'reflect-metadata'
3510
+ import './config' // ← add this — registers env schema
3511
+ import { bootstrap } from '@forinda/kickjs'
3512
+ import { modules } from './modules'
3513
+ `,docs:`https://forinda.github.io/kick-js/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Y(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return Y(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
3514
+ When vitest re-imports your modules across tests, the same class can be
3515
+ registered twice and the container throws. The fix is to wipe the
3516
+ container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
3517
+ import { Container } from '@forinda/kickjs'
3518
+
3519
+ describe('UserController', () => {
3520
+ beforeEach(() => Container.reset())
3521
+
3522
+ it('does the thing', async () => { /* ... */ })
3523
+ })`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Vr(e,[`Module`,`is not a function`])||Vr(e,[`Module`,`no exported member`])?{confidence:80,diagnosis:{id:`module-decorator-not-found`,title:`KickJS does not have a @Module decorator (different pattern from NestJS)`,explanation:`NestJS uses @Module({ controllers, providers }). KickJS uses an interface
3524
+ pattern instead: a class implements AppModule and exposes routes() that
3525
+ returns the controller wiring. This was a deliberate choice — modules
3526
+ become explicit values rather than metadata, which makes them easier to
3527
+ compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
3528
+ import { UserController } from './user.controller'
3529
+
3530
+ @Module({
3531
+ controllers: [UserController],
3532
+ })
3533
+ export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
3534
+ import { UserController } from './user.controller'
3535
+
3536
+ export class UserModule implements AppModule {
3537
+ routes(): ModuleRoutes {
3538
+ return {
3539
+ path: '/users',
3540
+ router: buildRoutes(UserController),
3541
+ controller: UserController,
3542
+ }
3543
+ }
3544
+ }`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}},{match(e,t){return/KickRoutes\s*\[\s*['"](GET|POST|PUT|PATCH|DELETE)/i.test(e)?{confidence:95,diagnosis:{id:`legacy-kick-routes-bracket-syntax`,title:`KickRoutes['POST /users'] is the legacy v1 syntax`,explanation:`KickJS v2 changed the typegen output from a flat string-keyed map to a
3545
+ namespaced shape: KickRoutes.UserController["create"] instead of
3546
+ KickRoutes["POST /users"]. The new form is per-controller, per-method,
3547
+ and matches the actual class names so refactors propagate via
3548
+ rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
3549
+ create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
3550
+ create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://forinda.github.io/kick-js/guide/typegen.html`}}:null}},{match(e,t){let n=Y(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Y(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
3551
+ cluster: { workers: N }, the framework forks N workers, each of which
3552
+ spins up its own Vite instance on a separate port. The fix landed in
3553
+ v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
3554
+ silently skips cluster, with a warning. If you see this on an older
3555
+ version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
3556
+ modules,
3557
+ cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
3558
+ })`,docs:`https://forinda.github.io/kick-js/guide/cluster.html`}}}},{match(e,t){return Y(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
3559
+ reflect-metadata polyfill. The polyfill must be imported once,
3560
+ before any decorator runs. Most projects do this at the top of
3561
+ src/index.ts; missing the import causes obscure "design:paramtypes"
3562
+ or "Reflect.getMetadata is not a function" errors at runtime.`,fix:`Add the import at the very top of src/index.ts:`,codeAfter:`import 'reflect-metadata' // ← must be the FIRST import
3563
+ import './config'
3564
+ import { bootstrap } from '@forinda/kickjs'
3565
+ import { modules } from './modules'
3566
+
3567
+ export const app = await bootstrap({ modules })`,docs:`https://forinda.github.io/kick-js/guide/dependency-injection.html`}}:null}},{match(e,t){return Y(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
3568
+ generated a module via \`kick g module foo\` but the routes don't appear,
3569
+ the most likely cause is that the module is missing from the exported
3570
+ array. The CLI usually wires this automatically, but a hand-edit can
3571
+ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleClass } from '@forinda/kickjs'
3572
+ import { UserModule } from './users/user.module'
3573
+ import { TaskModule } from './tasks/task.module' // ← was this missing?
3574
+
3575
+ export const modules: AppModuleClass[] = [UserModule, TaskModule]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function Ur(e,t){let n=null;for(let r of Hr){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function Wr(e){let t=e.provider??`openai`,n=process.env.OPENAI_API_KEY;if(t===`openai`&&!n)return{kind:`unavailable`,reason:`OPENAI_API_KEY environment variable is not set`,suggestion:`Set OPENAI_API_KEY in your shell, e.g.
3576
+ export OPENAI_API_KEY="sk-..."
3577
+
3578
+ Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@forinda/kickjs-ai`)}catch{return{kind:`unavailable`,reason:`@forinda/kickjs-ai is not installed`,suggestion:`Install the AI package to enable the LLM fallback:
3579
+ kick add ai
3580
+
3581
+ Or manually:
3582
+ pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Gr(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Kr((await a.chat({messages:[{role:`system`,content:o},{role:`user`,content:s}]})).content);return e?{kind:`ok`,diagnosis:e}:{kind:`error`,message:`The LLM responded but the payload was not valid JSON in the expected shape. Try again, or file an issue with the error text.`}}catch(e){return{kind:`error`,message:`LLM request failed: ${e instanceof Error?e.message:String(e)}`}}}function Gr(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
3583
+ `)}function Kr(e){let t=[e,qr(e),Jr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Yr(t))return t}catch{continue}return null}function qr(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Jr(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`&&r){i=!0;continue}if(o===`"`){r=!r;continue}if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Yr(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function Xr(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await $r(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
3584
+
3585
+ Pass a message as a positional arg, --message flag, or pipe via stdin:
3586
+ kick explain "config.get returned undefined"
3587
+ pnpm test 2>&1 | kick explain
3588
+ `),process.exit(1));let r=ti(),i=Ur(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
3589
+ `);return}if(i){ni(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
3590
+ `),process.exit(2)),ri(n,!1),process.exit(2));let a=await Wr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Zr(a),null,2)+`
3591
+ `),process.exit(a.kind===`ok`?0:2)),Qr(n,a),process.exit(a.kind===`ok`?0:2)})}function Zr(e){return e.kind===`ok`?{matched:!0,source:`ai`,diagnosis:e.diagnosis}:e.kind===`unavailable`?{matched:!1,aiUnavailable:!0,reason:e.reason}:{matched:!1,aiError:!0,error:e.message}}function Qr(e,t){if(t.kind===`ok`){ni(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${X(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function $r(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:ei()}function ei(){return new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n)),process.stdin.on(`error`,t)})}function ti(){let e=process.cwd();return{cwd:e,hasFile:t=>h(S(e,t))}}function ni(e,t,n,r=!1){let i=Z(e.trim(),200),a=r?`AI-generated — verify before applying`:ii(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${X(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${X(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${X(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${X(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
3592
+ `)}function ri(e,t){let n=Z(e.trim(),200);process.stdout.write(`\n Explaining: ${n}\n\n`),t?process.stdout.write(` No known-issue matched, and --ai fallback is not yet wired.
3593
+ When @forinda/kickjs-ai ships its provider implementations,
3594
+ this command will call the configured LLM with the error +
3595
+ project context and return a structured fix.
3596
+
3597
+ `):process.stdout.write(` No known-issue matched. Things you can try:
3598
+
3599
+ 1. Check the framework docs for the error keywords:
3600
+ https://forinda.github.io/kick-js/
3601
+
3602
+ 2. Re-run with --ai to fall back to an LLM (requires
3603
+ @forinda/kickjs-ai with a configured provider):
3604
+ kick explain --ai "<your error>"
3605
+
3606
+ 3. File an issue with the error text:
3607
+ https://github.com/forinda/kick-js/issues/new
3608
+
3609
+ `)}function X(e,t){return e.split(`
3610
+ `).map(e=>`${t}${e}`).join(`
3611
+ `)}function Z(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function ii(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function ai(e){let t=e.command(`mcp`).description(`Model Context Protocol commands (start | init)`);t.command(`start`,{isDefault:!0}).description(`Run the built application as an MCP server over stdio`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`--node-arg <arg...>`,`Extra arguments to pass to node`).action(oi),t.command(`init`).description(`Generate .mcp.json for Claude Code / Cursor / Zed`).option(`-n, --name <name>`,`Server name (defaults to package.json name)`).option(`-o, --out <file>`,`Output file`,`.mcp.json`).option(`-f, --force`,`Overwrite an existing entry without prompting`).option(`--global`,`Write to ~/.mcp.json instead of the project root`).action(si)}function oi(e){let t=S(e.entry);h(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],r=ue(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function si(e){let t=process.cwd(),n=ci(t)??ie(t),r=e.name??n,i=e.global?S(process.env.HOME??`.`,`.mcp.json`):S(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(h(i))try{let e=_(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,re(i,JSON.stringify(o,null,2)+`
3612
+ `,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function ci(e){let t=S(e,`package.json`);if(!h(t))return null;try{let e=_(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function li(e){e.command(`tinker`).description(`Interactive REPL with DI container and services loaded`).option(`-e, --entry <file>`,`Entry file to load`,`src/index.ts`).action(async e=>{let t=process.cwd(),n=S(t,e.entry);h(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=di(t,`tsx`);r||(console.error(`
3613
+ Error: tsx not found. Install it: pnpm add -D tsx
3614
+ `),process.exit(1));let i=ui(n,e.entry),a=b(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=le(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function ui(e,t){return`
3615
+ import 'reflect-metadata'
3616
+
3617
+ // Prevent bootstrap() from starting the HTTP server
3618
+ process.env.KICK_TINKER = '1'
3619
+
3620
+ console.log('\\n 🔧 KickJS Tinker')
3621
+ console.log(' Loading: ${t}\\n')
3622
+
3623
+ // Load core
3624
+ let Container, Logger, HttpException, HttpStatus
3625
+ try {
3626
+ const core = await import('@forinda/kickjs')
3627
+ Container = core.Container
3628
+ Logger = core.Logger
3629
+ HttpException = core.HttpException
3630
+ HttpStatus = core.HttpStatus
3631
+ } catch {
3632
+ console.error(' Error: @forinda/kickjs not found.')
3633
+ console.error(' Install it: pnpm add @forinda/kickjs\\n')
3634
+ process.exit(1)
3635
+ }
3636
+
3637
+ // Load entry to trigger decorator registration
3638
+ try {
3639
+ await import('${C(e).href}')
3640
+ } catch (err) {
3641
+ console.warn(' Warning: ' + err.message)
3642
+ console.warn(' Container may be partially initialized.\\n')
3643
+ }
3644
+
3645
+ const container = Container.getInstance()
3646
+
3647
+ // Start REPL
3648
+ const repl = await import('node:repl')
3649
+ const server = repl.start({ prompt: 'kick> ', useGlobal: true })
3650
+
3651
+ server.context.container = container
3652
+ server.context.Container = Container
3653
+ server.context.resolve = (token) => container.resolve(token)
3654
+ server.context.Logger = Logger
3655
+ server.context.HttpException = HttpException
3656
+ server.context.HttpStatus = HttpStatus
3657
+
3658
+ console.log(' Available globals:')
3659
+ console.log(' container — DI container instance')
3660
+ console.log(' resolve(T) — shorthand for container.resolve(T)')
3661
+ console.log(' Container, Logger, HttpException, HttpStatus')
3662
+ console.log()
3663
+
3664
+ server.on('exit', () => {
3665
+ console.log('\\n Goodbye!\\n')
3666
+ process.exit(0)
3667
+ })
3668
+ `}function di(e,t){let n=e;for(;;){let e=b(n,`node_modules`,`.bin`,t);if(h(e))return e;let r=S(n,`..`);if(r===n)break;n=r}return null}async function fi(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=B(t),o=R(t),s=i?V(a):a,c=b(n,s);if(!await N(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await F({message:O.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
3669
+ Cancelled.
3670
+ `);return}await me(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=b(n,`index.ts`);if(await N(l)){let e=await T(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${o}Module\\s*\\}\\s*from\\s*['"][^'"]*${s}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=e.replace(RegExp(`\\s*,?\\s*${o}Module\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),e=e.replace(/,(\s*])/,`$1`),e=e.replace(/\n{3,}/g,`
3671
+
3672
+ `),e!==t&&(await E(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function pi(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let i=n(await r(process.cwd())),a=t.modulesDir??i.dir??`src/modules`,o=t.pluralize===!1?!1:i.pluralize??!0;for(let n of e)await fi({name:n,modulesDir:S(a),force:t.force,pluralize:o})})}function mi(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;console.warn(` kick typegen: unknown --schema-validator '${e}' (only 'zod' and 'false' are supported). Falling back to project config.`)}}function hi(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function gi(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=process.cwd(),n=await r(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-Dv2gKsuC.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Xi),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
3673
+ Registered typegen plugins:
3674
+ `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let i=mi(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,a=hi(e.envFile)??n?.typegen?.envFile,o={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:i,envFile:a,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await u(o);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await f(o);let r=await Sr({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1)}}catch(e){e instanceof c?console.error(`
3675
+ `+e.message+`
3676
+ `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function _i(e){let t=[];if(!h(e))return t;let n=ee(e,{withFileTypes:!0});for(let r of n){let n=b(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(..._i(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function vi(e){try{return _(e,`utf-8`)}catch{return``}}const yi=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function bi(e,t){let n=vi(b(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(yi.has(t.toLowerCase())||t.length<32)return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value or too short (< 32 chars) — change it`}}}for(let e of t)for(let t of[/JWT_SECRET['"]?\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i,/secret\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i])if(t.test(e))return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value in source code — use an environment variable`};return null}function xi(e){for(let t of e)if(/cors\s*\(/.test(t)&&/origin\s*:\s*['"]\*['"]/.test(t))return{severity:`CRITICAL`,message:`CORS origin is '*' — restrict to your domains`};return null}function Si(e){for(let t of e)if(/rateLimit/i.test(t)||/@RateLimit/i.test(t))return null;return{severity:`WARNING`,message:`No rate limiting detected — add rateLimit() middleware or @RateLimit decorator`}}function Ci(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function wi(e){let t=!1,n=!1;for(let r of e)/tokenStore/i.test(r)&&(t=!0),/MemoryTokenStore/i.test(r)&&(n=!0);return n?{severity:`WARNING`,message:`MemoryTokenStore detected — use a persistent store (Redis, DB) for production deployments`}:t?null:{severity:`WARNING`,message:`No token revocation store detected — consider adding one for auth token management`}}function Ti(e){for(let t of e)if(/helmet\s*\(/.test(t))return/security\s*\.\s*helmet\s*.*false/.test(t)?{severity:`WARNING`,message:`Helmet security headers are disabled — enable them for production`}:{severity:`INFO`,message:`Helmet security headers active`};return{severity:`WARNING`,message:`Helmet not detected — add helmet() middleware for security headers`}}function Ei(e){for(let t of e)if(/AuthAdapter/i.test(t))return{severity:`INFO`,message:`AuthAdapter configured`};return{severity:`INFO`,message:`No AuthAdapter detected — add one if your app requires authentication`}}function Di(e){let t=_i(b(e,`src`)).map(e=>vi(e)),n=[],r=bi(e,t);r&&n.push(r);let i=xi(t);i&&n.push(i);let a=Si(t);a&&n.push(a);let o=Ci();o&&n.push(o);let s=wi(t);return s&&n.push(s),n.push(Ti(t)),n.push(Ei(t)),n}function Oi(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
3677
+ Usage: kick check --deploy
3678
+
3679
+ Available checks:
3680
+ --deploy Audit for production readiness (security, config, best practices)
3681
+ `);return}let t=process.cwd();dt(`KickJS Deploy Check`);let n=gt();n.start(`Scanning project...`);let r=Di(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)I.message(`${ut(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?O.red(`${a} critical`):`${a} critical`,o>0?O.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(P(O.red(`${l} — fix critical issues before deploying`)),process.exit(1)):P(O.green(`${l} — looking good!`))})}async function Q(e){return Oe({configPath:v.resolve(process.cwd(),e.config)})}async function $(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}function ki(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function Ai(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await xe({name:e,config:await Q(t),cwd:n,empty:t.empty});if(r.status===`no-changes`){console.log(`No schema changes detected.`);return}if(r.empty){console.log(`Created empty migration ${r.migrationDir} (author up.sql + down.sql).`);return}let i=r.changeCount===1?``:`s`;console.log(`Created migration ${r.migrationDir} (${r.changeCount} change${i}).`)});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ce({adapter:n,migrationsDir:t.migrationsDir});e.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${e.batch}: ${e.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ee({adapter:n,migrationsDir:t.migrationsDir});e.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${e.applied[0]} (batch ${e.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Se({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await we({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{ki(await Te({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await E(i,De(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}const ji=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],Mi=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=Ni(e.cwd);if(!t)return null;let n=v.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${Pi(v.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,`}`].join(`
3682
+ `)}});function Ni(e){for(let t of ji){let n=v.resolve(e,t);if(t.endsWith(`.ts`)){if(h(n))return n}else{let e=v.join(n,`index.ts`);if(h(e))return e}}return null}function Pi(e){return e.replace(/\\/g,`/`)}const Fi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!h(v.resolve(e.cwd,`kick.config.ts`)))return null;let t=await r(e.cwd);if(!t?.assetMap)return null;let n=s(t.assetMap,e.cwd);return n.count===0?null:l(n)}}),Ii="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n";function Li(e,t,n){if(e.length===0)return`${Ii}
3683
+ // (no routes discovered yet — annotate a controller method with
3684
+ // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
3685
+ declare global {
3686
+ // eslint-disable-next-line @typescript-eslint/no-namespace
3687
+ namespace KickRoutes {}
3688
+ }
3689
+
3690
+ export {}
3691
+ `;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=Bi(e,r,t,n,i);return a?`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??Ri(e),l=zi(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
3692
+ `))}return`${Ii}${Vi(i)}
3693
+ declare global {
3694
+ // eslint-disable-next-line @typescript-eslint/no-namespace
3695
+ namespace KickRoutes {
3696
+ ${o.join(`
3697
+ `)}
3698
+ }
3699
+ }
3700
+
3701
+ export {}
3702
+ `}function Ri(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function zi(e){let t=[];return e.queryFilterable&&e.queryFilterable.length>0&&t.push(`Filterable: ${e.queryFilterable.join(`, `)}`),e.querySortable&&e.querySortable.length>0&&t.push(`Sortable: ${e.querySortable.join(`, `)}`),e.querySearchable&&e.querySearchable.length>0&&t.push(`Searchable: ${e.querySearchable.join(`, `)}`),t}function Bi(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=Hi(e.source,t,n);if(a===`unknown`)return null;let o=`${a}::${e.identifier}`,s=i.get(o)?.specifier;return s?s=i.get(o).specifier:(s=`_S${i.size}`,i.set(o,{identifier:e.identifier,specifier:s})),s}function Vi(e){if(e.size===0)return``;let t=[];for(let[n,r]of e){let[e]=n.split(`::`);t.push(`import type { ${r.identifier} as ${r.specifier} } from '${e}'`)}return t.join(`
3703
+ `)+`
3704
+ `}function Hi(e,t,n){if(e===null)return`unknown`;let r=y(n);if(e===``){let e=x(r,t).split(se).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=x(r,S(y(t),e)).split(se).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const Ui=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Wi(e),cwd:e.cwd,envFile:Gi(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=v.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Li(t.routes,r,n)}});function Wi(e){return v.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Gi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Ki(e,t){if(!e)return null;let n=x(y(t),e.filePath).split(se).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
3705
+ // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
3706
+ // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
3707
+
3708
+ // Importing the schema as a type lets us infer its shape without
3709
+ // pulling in any runtime code. \`Awaited<>\` strips an accidental
3710
+ // Promise wrap on dynamic-imported defaults.
3711
+ import type _envSchema from '${n}'
3712
+
3713
+ // Local type alias — interfaces can only \`extend\` an identifier,
3714
+ // not an inline import expression, so we resolve the schema's
3715
+ // inferred shape into a named type first.
3716
+ type _KickEnvShape = import('zod').infer<typeof _envSchema>
3717
+
3718
+ declare global {
3719
+ /**
3720
+ * Typed environment registry. Augmented from \`${e.relativePath}\`
3721
+ * so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
3722
+ * all type-safe and autocomplete.
3723
+ */
3724
+ interface KickEnv extends _KickEnvShape {}
3725
+
3726
+ // eslint-disable-next-line @typescript-eslint/no-namespace
3727
+ namespace NodeJS {
3728
+ /**
3729
+ * Narrow \`process.env\` so known keys exist as \`string\` (the raw
3730
+ * pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
3731
+ * the schema's transforms internally; access \`process.env\` directly
3732
+ * only when you need the raw string. Unknown keys still resolve to
3733
+ * \`string | undefined\` via the base @types/node declaration.
3734
+ */
3735
+ interface ProcessEnv extends Record<keyof KickEnv, string> {}
3736
+ }
3737
+ }
3738
+
3739
+ export {}
3740
+ `}const qi=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Yi(e);if(t===!1)return null;let n=await e.getScanResult({root:Ji(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=v.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Ki(n.env,r)}});function Ji(e){return v.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Yi(e){return e.config?.typegen?.envFile}var Xi=e({builtinCliPlugins:()=>Zi});const Zi=[o({name:`kick/init`,register:Et}),o({name:`kick/generate`,register:_r}),o({name:`kick/run`,register:Ar}),o({name:`kick/info`,register:jr}),o({name:`kick/inspect`,register:Br}),o({name:`kick/add`,register:wt}),o({name:`kick/list`,register:Ct}),o({name:`kick/explain`,register:Xr}),o({name:`kick/mcp`,register:ai}),o({name:`kick/tinker`,register:li}),o({name:`kick/remove`,register:pi}),o({name:`kick/typegen`,register:gi}),o({name:`kick/check`,register:Oi}),o({name:`kick/db`,register:Ai,typegens:[Mi()]}),o({name:`kick/assets`,typegens:[Fi()]}),o({name:`kick/routes`,typegens:[Ui()]}),o({name:`kick/env`,typegens:[qi()]})];export{ke as i,Xi as n,xr as r,Zi as t};