@forinda/kickjs-cli 5.8.1 → 5.8.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.
- package/dist/agent-docs-BskiyzHm.mjs +12 -0
- package/dist/agent-docs-BskiyzHm.mjs.map +1 -0
- package/dist/{builtins-CF4q3JIg.mjs → builtins-DxlD3Bnh.mjs} +2 -2
- package/dist/cli.mjs +63 -312
- package/dist/{config-v6vsVMtc.mjs → config-DKQcNKrg.mjs} +3 -3
- package/dist/{config-v6vsVMtc.mjs.map → config-DKQcNKrg.mjs.map} +1 -1
- package/dist/generator-extension-CVVCnF6w.mjs +1977 -0
- package/dist/generator-extension-CVVCnF6w.mjs.map +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-1Oiz9_TD.mjs → plugin-HGOpDF54.mjs} +3 -3
- package/dist/{plugin-1Oiz9_TD.mjs.map → plugin-HGOpDF54.mjs.map} +1 -1
- package/dist/project-docs-DRR0mSJy.mjs +858 -0
- package/dist/project-docs-DRR0mSJy.mjs.map +1 -0
- package/dist/{project-root-BaUzB3D7.mjs → project-root-XvkHzCRu.mjs} +3 -3
- package/dist/{project-root-BaUzB3D7.mjs.map → project-root-XvkHzCRu.mjs.map} +1 -1
- package/dist/{rolldown-runtime-vNCSDkuE.mjs → rolldown-runtime-07ZxtVND.mjs} +1 -1
- package/dist/{run-plugins-Bg8kTYfa.mjs → run-plugins-BE1Dakam.mjs} +99 -99
- package/dist/run-plugins-BE1Dakam.mjs.map +1 -0
- package/dist/{typegen-B8lAhWXz.mjs → typegen-BK-C_dMm.mjs} +4 -4
- package/dist/{typegen-B8lAhWXz.mjs.map → typegen-BK-C_dMm.mjs.map} +1 -1
- package/dist/{types-BG2NeDgK.mjs → types-d0QsibKA.mjs} +2 -2
- package/dist/{types-BG2NeDgK.mjs.map → types-d0QsibKA.mjs.map} +1 -1
- package/package.json +7 -7
- package/dist/generator-extension-ChoCJW23.mjs +0 -3072
- package/dist/generator-extension-ChoCJW23.mjs.map +0 -1
- package/dist/run-plugins-Bg8kTYfa.mjs.map +0 -1
|
@@ -1,3072 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs-cli v5.8.1
|
|
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"./project-root-BaUzB3D7.mjs";import{createRequire as t}from"node:module";import{dirname as n,extname as r,join as i,resolve as a}from"node:path";import{existsSync as o,readFileSync as s}from"node:fs";import{access as c,mkdir as l,readFile as u,writeFile as d}from"node:fs/promises";import*as f from"@clack/prompts";import p from"picocolors";import m from"pluralize";import{execFileSync as h,execSync as g}from"node:child_process";import{fileURLToPath as _,pathToFileURL as v}from"node:url";let y=!1;function ee(e){y=e}const te=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function b(e,t){y||(await l(n(e),{recursive:!0}),await d(e,t,`utf-8`),te.has(r(e))&&await re(e,t).catch(()=>{}))}let x;async function ne(e){if(x!==void 0)return x;try{x=await import(t(i(e,`package.json`)).resolve(`oxfmt`))}catch{x=null}return x}async function re(e,t){let n=await ne(process.cwd());if(!n)return;let r=await ie(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await d(e,i.code,`utf-8`)}const S=new Map;async function ie(e){let t=n(e),r=t;if(S.has(r))return S.get(r);for(;;){let e=i(t,`.oxfmtrc.json`);if(o(e))try{let t=await u(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,S.set(r,n),n}catch{return S.set(r,null),null}let a=n(t);if(a===t)return S.set(r,null),null;t=a}}async function C(e){try{return await c(e),!0}catch{return!1}}const ae={GET:p.green,POST:p.cyan,PUT:p.yellow,PATCH:p.magenta,DELETE:p.red};function oe(e){return(ae[e]??p.dim)(e.padEnd(7))}function se(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return p.red(t);case`WARNING`:return p.yellow(t);case`INFO`:return p.blue(p.dim(t));default:return t}}p.green(`✓`),p.red(`✖`),p.yellow(`⚠`),p.blue(`ℹ`);function ce(e){f.intro(p.bgCyan(p.black(` ${e} `)))}function le(e){f.outro(e)}function w(e){f.isCancel(e)&&(f.cancel(`Operation cancelled.`),process.exit(0))}async function ue(e){let t=await f.text(e);return w(t),t}async function de(e){let t=await f.select(e);return w(t),t}async function fe(e){let t=await f.multiselect(e);return w(t),t}async function T(e){let t=await f.confirm(e);return w(t),t}function pe(){return f.spinner()}const E=f.log;function D(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function A(e){return m.plural(e)}function me(e){return m.plural(e)}function j(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const he={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function M(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ge(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function N(e){return he[e]??M(e)}function P(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${M(n)}${e}Repository`,repoFile:i[n]??`${ge(n)}-${t}`}}function F(e){return e??`define`}function _e(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
|
|
12
|
-
* ${t} Module
|
|
13
|
-
*
|
|
14
|
-
* Self-contained feature module following Domain-Driven Design (DDD).
|
|
15
|
-
* Registers dependencies in the DI container and declares HTTP routes.
|
|
16
|
-
*
|
|
17
|
-
* Structure:
|
|
18
|
-
* presentation/ — HTTP controllers (entry points)
|
|
19
|
-
* application/ — Use cases (orchestration) and DTOs (validation)
|
|
20
|
-
* domain/ — Entities, value objects, repository interfaces, domain services
|
|
21
|
-
* infrastructure/ — Repository implementations (currently ${N(i)})
|
|
22
|
-
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './domain/repositories/${n}.repository'
|
|
23
|
-
import { ${o} } from './infrastructure/repositories/${s}.repository'
|
|
24
|
-
import { ${t}Controller } from './presentation/${n}.controller'
|
|
25
|
-
|
|
26
|
-
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
27
|
-
import.meta.glob(
|
|
28
|
-
['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
|
|
29
|
-
{ eager: true },
|
|
30
|
-
)`,d=` /**
|
|
31
|
-
* Declare HTTP routes for this module. Return value shape:
|
|
32
|
-
*
|
|
33
|
-
* - \`path\` — URL prefix for this route set, mounted under
|
|
34
|
-
* \`/{apiPrefix}/v{version}{path}\`.
|
|
35
|
-
* - \`controller\` — Controller class. Used both for the route
|
|
36
|
-
* handler bindings and OpenAPI spec generation.
|
|
37
|
-
* - \`version\` — Optional. Overrides the app-wide API version
|
|
38
|
-
* for this route set only.
|
|
39
|
-
*
|
|
40
|
-
* Return an **array** to mount multiple route sets under the
|
|
41
|
-
* same module (e.g. side-by-side v1 + v2 controllers):
|
|
42
|
-
*
|
|
43
|
-
* return [
|
|
44
|
-
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
45
|
-
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
46
|
-
* ]
|
|
47
|
-
*/`;return c===`class`?`${l}
|
|
48
|
-
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
49
|
-
${u}
|
|
50
|
-
|
|
51
|
-
export class ${t}Module implements AppModule {
|
|
52
|
-
/**
|
|
53
|
-
* Register module dependencies in the DI container.
|
|
54
|
-
* Bind repository interface tokens to their implementations here.
|
|
55
|
-
* Currently wired to ${N(i)}. To swap implementations, change the factory target.
|
|
56
|
-
*/
|
|
57
|
-
register(container: Container): void {
|
|
58
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
59
|
-
container.resolve(${o}),
|
|
60
|
-
)
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
64
|
-
routes(): ModuleRoutes {
|
|
65
|
-
return {
|
|
66
|
-
path: '/${r}',
|
|
67
|
-
controller: ${t}Controller,
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
`:`${l}
|
|
72
|
-
import { defineModule } from '@forinda/kickjs'
|
|
73
|
-
${u}
|
|
74
|
-
|
|
75
|
-
export const ${t}Module = defineModule({
|
|
76
|
-
name: '${t}Module',
|
|
77
|
-
build: () => ({
|
|
78
|
-
/**
|
|
79
|
-
* Register module dependencies in the DI container.
|
|
80
|
-
* Bind repository interface tokens to their implementations here.
|
|
81
|
-
* Currently wired to ${N(i)}. To swap implementations, change the factory target.
|
|
82
|
-
*/
|
|
83
|
-
register(container) {
|
|
84
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
85
|
-
container.resolve(${o}),
|
|
86
|
-
)
|
|
87
|
-
},
|
|
88
|
-
|
|
89
|
-
${d}
|
|
90
|
-
routes() {
|
|
91
|
-
return {
|
|
92
|
-
path: '/${r}',
|
|
93
|
-
controller: ${t}Controller,
|
|
94
|
-
}
|
|
95
|
-
},
|
|
96
|
-
}),
|
|
97
|
-
})
|
|
98
|
-
`}function ve(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=P(t,n,i),c=F(a),l=`/**
|
|
99
|
-
* ${t} Module
|
|
100
|
-
*
|
|
101
|
-
* REST module with a flat folder structure.
|
|
102
|
-
* Controller delegates to service, service wraps the repository.
|
|
103
|
-
*
|
|
104
|
-
* Structure:
|
|
105
|
-
* ${n}.controller.ts — HTTP routes (CRUD)
|
|
106
|
-
* ${n}.service.ts — Business logic
|
|
107
|
-
* ${n}.repository.ts — Repository interface
|
|
108
|
-
* ${s}.repository.ts — Repository implementation
|
|
109
|
-
* dtos/ — Request/response schemas
|
|
110
|
-
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
|
|
111
|
-
import { ${o} } from './${s}.repository'
|
|
112
|
-
import { ${t}Controller } from './${n}.controller'
|
|
113
|
-
|
|
114
|
-
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
115
|
-
import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })`,d=` /**
|
|
116
|
-
* Declare HTTP routes for this module. Return value shape:
|
|
117
|
-
*
|
|
118
|
-
* - \`path\` — URL prefix for this route set.
|
|
119
|
-
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
120
|
-
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
121
|
-
*
|
|
122
|
-
* Return an **array** to mount multiple route sets — admin
|
|
123
|
-
* surfaces, side-by-side v1 + v2 controllers, etc:
|
|
124
|
-
*
|
|
125
|
-
* return [
|
|
126
|
-
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
127
|
-
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
128
|
-
* ]
|
|
129
|
-
*/`;return c===`class`?`${l}
|
|
130
|
-
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
131
|
-
${u}
|
|
132
|
-
|
|
133
|
-
export class ${t}Module implements AppModule {
|
|
134
|
-
register(container: Container): void {
|
|
135
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
136
|
-
container.resolve(${o}),
|
|
137
|
-
)
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
141
|
-
routes(): ModuleRoutes {
|
|
142
|
-
return {
|
|
143
|
-
path: '/${r}',
|
|
144
|
-
controller: ${t}Controller,
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
`:`${l}
|
|
149
|
-
import { defineModule } from '@forinda/kickjs'
|
|
150
|
-
${u}
|
|
151
|
-
|
|
152
|
-
export const ${t}Module = defineModule({
|
|
153
|
-
name: '${t}Module',
|
|
154
|
-
build: () => ({
|
|
155
|
-
register(container) {
|
|
156
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
157
|
-
container.resolve(${o}),
|
|
158
|
-
)
|
|
159
|
-
},
|
|
160
|
-
|
|
161
|
-
${d}
|
|
162
|
-
routes() {
|
|
163
|
-
return {
|
|
164
|
-
path: '/${r}',
|
|
165
|
-
controller: ${t}Controller,
|
|
166
|
-
}
|
|
167
|
-
},
|
|
168
|
-
}),
|
|
169
|
-
})
|
|
170
|
-
`}function ye(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=F(i),o=` /**
|
|
171
|
-
* Declare HTTP routes. Return value shape:
|
|
172
|
-
*
|
|
173
|
-
* - \`path\` — URL prefix for this route set.
|
|
174
|
-
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
175
|
-
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
176
|
-
*
|
|
177
|
-
* Return an array to mount multiple route sets:
|
|
178
|
-
*
|
|
179
|
-
* return [
|
|
180
|
-
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
181
|
-
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
182
|
-
* ]
|
|
183
|
-
*/`;return a===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
184
|
-
import { ${t}Controller } from './${n}.controller'
|
|
185
|
-
|
|
186
|
-
export class ${t}Module implements AppModule {
|
|
187
|
-
${o.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
188
|
-
routes(): ModuleRoutes {
|
|
189
|
-
return {
|
|
190
|
-
path: '/${r}',
|
|
191
|
-
controller: ${t}Controller,
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
`:`import { defineModule } from '@forinda/kickjs'
|
|
196
|
-
import { ${t}Controller } from './${n}.controller'
|
|
197
|
-
|
|
198
|
-
export const ${t}Module = defineModule({
|
|
199
|
-
name: '${t}Module',
|
|
200
|
-
build: () => ({
|
|
201
|
-
${o}
|
|
202
|
-
routes() {
|
|
203
|
-
return {
|
|
204
|
-
path: '/${r}',
|
|
205
|
-
controller: ${t}Controller,
|
|
206
|
-
}
|
|
207
|
-
},
|
|
208
|
-
}),
|
|
209
|
-
})
|
|
210
|
-
`}function be(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
211
|
-
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
212
|
-
import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
|
|
213
|
-
import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
|
|
214
|
-
import { List${i}UseCase } from '../application/use-cases/list-${r}.use-case'
|
|
215
|
-
import { Update${t}UseCase } from '../application/use-cases/update-${n}.use-case'
|
|
216
|
-
import { Delete${t}UseCase } from '../application/use-cases/delete-${n}.use-case'
|
|
217
|
-
import { create${t}Schema } from '../application/dtos/create-${n}.dto'
|
|
218
|
-
import { update${t}Schema } from '../application/dtos/update-${n}.dto'
|
|
219
|
-
import { ${t.toUpperCase()}_QUERY_CONFIG } from '../constants'
|
|
220
|
-
|
|
221
|
-
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
222
|
-
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
223
|
-
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
224
|
-
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
225
|
-
|
|
226
|
-
@Controller()
|
|
227
|
-
export class ${t}Controller {
|
|
228
|
-
@Autowired() private readonly create${t}UseCase!: Create${t}UseCase
|
|
229
|
-
@Autowired() private readonly get${t}UseCase!: Get${t}UseCase
|
|
230
|
-
@Autowired() private readonly list${i}UseCase!: List${i}UseCase
|
|
231
|
-
@Autowired() private readonly update${t}UseCase!: Update${t}UseCase
|
|
232
|
-
@Autowired() private readonly delete${t}UseCase!: Delete${t}UseCase
|
|
233
|
-
|
|
234
|
-
@Get('/')
|
|
235
|
-
@ApiTags('${t}')
|
|
236
|
-
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
237
|
-
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
238
|
-
return ctx.paginate(
|
|
239
|
-
(parsed) => this.list${i}UseCase.execute(parsed),
|
|
240
|
-
${t.toUpperCase()}_QUERY_CONFIG,
|
|
241
|
-
)
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
@Get('/:id')
|
|
245
|
-
@ApiTags('${t}')
|
|
246
|
-
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
247
|
-
const result = await this.get${t}UseCase.execute(ctx.params.id)
|
|
248
|
-
if (!result) return ctx.notFound('${t} not found')
|
|
249
|
-
ctx.json(result)
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
253
|
-
@ApiTags('${t}')
|
|
254
|
-
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
255
|
-
const result = await this.create${t}UseCase.execute(ctx.body)
|
|
256
|
-
ctx.created(result)
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
260
|
-
@ApiTags('${t}')
|
|
261
|
-
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
262
|
-
const result = await this.update${t}UseCase.execute(ctx.params.id, ctx.body)
|
|
263
|
-
ctx.json(result)
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
@Delete('/:id')
|
|
267
|
-
@ApiTags('${t}')
|
|
268
|
-
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
269
|
-
await this.delete${t}UseCase.execute(ctx.params.id)
|
|
270
|
-
ctx.noContent()
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
`}function xe(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
274
|
-
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
275
|
-
import { ${t}Service } from './${n}.service'
|
|
276
|
-
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
277
|
-
import { update${t}Schema } from './dtos/update-${n}.dto'
|
|
278
|
-
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
279
|
-
|
|
280
|
-
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
281
|
-
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
282
|
-
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
283
|
-
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
284
|
-
|
|
285
|
-
@Controller()
|
|
286
|
-
export class ${t}Controller {
|
|
287
|
-
@Autowired() private readonly ${r}Service!: ${t}Service
|
|
288
|
-
|
|
289
|
-
@Get('/')
|
|
290
|
-
@ApiTags('${t}')
|
|
291
|
-
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
292
|
-
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
293
|
-
return ctx.paginate(
|
|
294
|
-
(parsed) => this.${r}Service.findPaginated(parsed),
|
|
295
|
-
${t.toUpperCase()}_QUERY_CONFIG,
|
|
296
|
-
)
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
@Get('/:id')
|
|
300
|
-
@ApiTags('${t}')
|
|
301
|
-
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
302
|
-
const result = await this.${r}Service.findById(ctx.params.id)
|
|
303
|
-
if (!result) return ctx.notFound('${t} not found')
|
|
304
|
-
ctx.json(result)
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
308
|
-
@ApiTags('${t}')
|
|
309
|
-
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
310
|
-
const result = await this.${r}Service.create(ctx.body)
|
|
311
|
-
ctx.created(result)
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
315
|
-
@ApiTags('${t}')
|
|
316
|
-
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
317
|
-
const result = await this.${r}Service.update(ctx.params.id, ctx.body)
|
|
318
|
-
ctx.json(result)
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
@Delete('/:id')
|
|
322
|
-
@ApiTags('${t}')
|
|
323
|
-
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
324
|
-
await this.${r}Service.delete(ctx.params.id)
|
|
325
|
-
ctx.noContent()
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
`}function Se(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
|
|
329
|
-
|
|
330
|
-
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
|
|
331
|
-
filterable: ['name'],
|
|
332
|
-
sortable: ['name', 'createdAt'],
|
|
333
|
-
searchable: ['name'],
|
|
334
|
-
}
|
|
335
|
-
`}function I(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Create ${t} DTO — Zod schema for validating POST request bodies.
|
|
339
|
-
* This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
|
|
340
|
-
* It also generates OpenAPI request body docs when SwaggerAdapter is used.
|
|
341
|
-
*
|
|
342
|
-
* Add more fields as needed. Supported Zod types:
|
|
343
|
-
* z.string(), z.number(), z.boolean(), z.enum([...]),
|
|
344
|
-
* z.array(), z.object(), .optional(), .default(), .transform()
|
|
345
|
-
*/
|
|
346
|
-
export const create${t}Schema = z.object({
|
|
347
|
-
name: z.string().min(1, 'Name is required').max(200),
|
|
348
|
-
})
|
|
349
|
-
|
|
350
|
-
export type Create${t}DTO = z.infer<typeof create${t}Schema>
|
|
351
|
-
`}function L(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
352
|
-
|
|
353
|
-
export const update${t}Schema = z.object({
|
|
354
|
-
name: z.string().min(1).max(200).optional(),
|
|
355
|
-
})
|
|
356
|
-
|
|
357
|
-
export type Update${t}DTO = z.infer<typeof update${t}Schema>
|
|
358
|
-
`}function R(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
359
|
-
id: string
|
|
360
|
-
name: string
|
|
361
|
-
createdAt: string
|
|
362
|
-
updatedAt: string
|
|
363
|
-
}
|
|
364
|
-
`}function Ce(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
|
|
365
|
-
* Create ${t} Use Case
|
|
366
|
-
*
|
|
367
|
-
* Application layer — orchestrates a single business operation.
|
|
368
|
-
* Use cases are thin: validate input (via DTO), call domain/repo, return response.
|
|
369
|
-
* Keep business rules in the domain service, not here.
|
|
370
|
-
*/
|
|
371
|
-
import { Service, Inject } from '@forinda/kickjs'
|
|
372
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
373
|
-
import type { Create${t}DTO } from '../dtos/create-${n}.dto'
|
|
374
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
375
|
-
|
|
376
|
-
@Service()
|
|
377
|
-
export class Create${t}UseCase {
|
|
378
|
-
constructor(
|
|
379
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
380
|
-
) {}
|
|
381
|
-
|
|
382
|
-
async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
383
|
-
return this.repo.create(dto)
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
`},{file:`get-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
387
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
388
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
389
|
-
|
|
390
|
-
@Service()
|
|
391
|
-
export class Get${t}UseCase {
|
|
392
|
-
constructor(
|
|
393
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
394
|
-
) {}
|
|
395
|
-
|
|
396
|
-
async execute(id: string): Promise<${t}ResponseDTO | null> {
|
|
397
|
-
return this.repo.findById(id)
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
`},{file:`list-${r}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
401
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
402
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
403
|
-
|
|
404
|
-
@Service()
|
|
405
|
-
export class List${i}UseCase {
|
|
406
|
-
constructor(
|
|
407
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
408
|
-
) {}
|
|
409
|
-
|
|
410
|
-
async execute(parsed: ParsedQuery) {
|
|
411
|
-
return this.repo.findPaginated(parsed)
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
`},{file:`update-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
415
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
416
|
-
import type { Update${t}DTO } from '../dtos/update-${n}.dto'
|
|
417
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
418
|
-
|
|
419
|
-
@Service()
|
|
420
|
-
export class Update${t}UseCase {
|
|
421
|
-
constructor(
|
|
422
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
423
|
-
) {}
|
|
424
|
-
|
|
425
|
-
async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
426
|
-
return this.repo.update(id, dto)
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
`},{file:`delete-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
430
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
431
|
-
|
|
432
|
-
@Service()
|
|
433
|
-
export class Delete${t}UseCase {
|
|
434
|
-
constructor(
|
|
435
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
436
|
-
) {}
|
|
437
|
-
|
|
438
|
-
async execute(id: string): Promise<void> {
|
|
439
|
-
await this.repo.delete(id)
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
`}]}function z(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
|
|
443
|
-
* ${t} Repository Interface
|
|
444
|
-
*
|
|
445
|
-
* Defines the contract for data access.
|
|
446
|
-
* The interface declares what operations are available;
|
|
447
|
-
* implementations (in-memory, Drizzle, Prisma) fulfill the contract.
|
|
448
|
-
*
|
|
449
|
-
* To swap implementations, change the factory in the module's register() method.
|
|
450
|
-
*/
|
|
451
|
-
import { createToken } from '@forinda/kickjs'
|
|
452
|
-
import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
|
|
453
|
-
import type { Create${t}DTO } from '${r}/create-${n}.dto'
|
|
454
|
-
import type { Update${t}DTO } from '${r}/update-${n}.dto'
|
|
455
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
456
|
-
|
|
457
|
-
export interface I${t}Repository {
|
|
458
|
-
findById(id: string): Promise<${t}ResponseDTO | null>
|
|
459
|
-
findAll(): Promise<${t}ResponseDTO[]>
|
|
460
|
-
findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
|
|
461
|
-
create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
|
|
462
|
-
update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
|
|
463
|
-
delete(id: string): Promise<void>
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
/**
|
|
467
|
-
* Collision-safe DI token bound to \`I${t}Repository\`.
|
|
468
|
-
* \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
|
|
469
|
-
* \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
470
|
-
* interface — no manual generic, no \`any\` cast.
|
|
471
|
-
*
|
|
472
|
-
* The \`'${i}/'\` prefix matches the project scope so
|
|
473
|
-
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
474
|
-
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
475
|
-
*/
|
|
476
|
-
export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
|
|
477
|
-
`}function B(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
478
|
-
* In-Memory ${t} Repository
|
|
479
|
-
*
|
|
480
|
-
* Implements the repository interface using a Map.
|
|
481
|
-
* Useful for prototyping and testing. Replace with a database implementation
|
|
482
|
-
* (Drizzle, Prisma, etc.) for production use.
|
|
483
|
-
*
|
|
484
|
-
* @Repository() registers this class in the DI container as a singleton.
|
|
485
|
-
*/
|
|
486
|
-
import { randomUUID } from 'node:crypto'
|
|
487
|
-
import { Repository, HttpException } from '@forinda/kickjs'
|
|
488
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
489
|
-
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
490
|
-
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
491
|
-
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
492
|
-
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
493
|
-
|
|
494
|
-
@Repository()
|
|
495
|
-
export class InMemory${t}Repository implements I${t}Repository {
|
|
496
|
-
private store = new Map<string, ${t}ResponseDTO>()
|
|
497
|
-
|
|
498
|
-
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
499
|
-
return this.store.get(id) ?? null
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
503
|
-
return Array.from(this.store.values())
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
507
|
-
const all = Array.from(this.store.values())
|
|
508
|
-
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
509
|
-
return { data, total: all.length }
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
513
|
-
const now = new Date().toISOString()
|
|
514
|
-
const entity: ${t}ResponseDTO = {
|
|
515
|
-
id: randomUUID(),
|
|
516
|
-
name: dto.name,
|
|
517
|
-
createdAt: now,
|
|
518
|
-
updatedAt: now,
|
|
519
|
-
}
|
|
520
|
-
this.store.set(entity.id, entity)
|
|
521
|
-
return entity
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
525
|
-
const existing = this.store.get(id)
|
|
526
|
-
if (!existing) throw HttpException.notFound('${t} not found')
|
|
527
|
-
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
528
|
-
this.store.set(id, updated)
|
|
529
|
-
return updated
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
async delete(id: string): Promise<void> {
|
|
533
|
-
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
534
|
-
this.store.delete(id)
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
`}function V(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`/**
|
|
538
|
-
* ${o} ${t} Repository
|
|
539
|
-
*
|
|
540
|
-
* Stub implementation for a custom '${r}' repository.
|
|
541
|
-
* Implements the repository interface using an in-memory Map as a placeholder.
|
|
542
|
-
*
|
|
543
|
-
* TODO: Replace the in-memory Map with your ${r} data-access logic.
|
|
544
|
-
* See I${t}Repository for the interface contract.
|
|
545
|
-
*
|
|
546
|
-
* @Repository() registers this class in the DI container as a singleton.
|
|
547
|
-
*/
|
|
548
|
-
import { randomUUID } from 'node:crypto'
|
|
549
|
-
import { Repository, HttpException } from '@forinda/kickjs'
|
|
550
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
551
|
-
import type { I${t}Repository } from '${i}/${n}.repository'
|
|
552
|
-
import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
|
|
553
|
-
import type { Create${t}DTO } from '${a}/create-${n}.dto'
|
|
554
|
-
import type { Update${t}DTO } from '${a}/update-${n}.dto'
|
|
555
|
-
|
|
556
|
-
@Repository()
|
|
557
|
-
export class ${o}${t}Repository implements I${t}Repository {
|
|
558
|
-
// TODO: Replace with your ${r} client/connection
|
|
559
|
-
private store = new Map<string, ${t}ResponseDTO>()
|
|
560
|
-
|
|
561
|
-
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
562
|
-
// TODO: Implement with ${r}
|
|
563
|
-
return this.store.get(id) ?? null
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
567
|
-
// TODO: Implement with ${r}
|
|
568
|
-
return Array.from(this.store.values())
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
572
|
-
// TODO: Implement with ${r}
|
|
573
|
-
const all = Array.from(this.store.values())
|
|
574
|
-
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
575
|
-
return { data, total: all.length }
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
579
|
-
// TODO: Implement with ${r}
|
|
580
|
-
const now = new Date().toISOString()
|
|
581
|
-
const entity: ${t}ResponseDTO = {
|
|
582
|
-
id: randomUUID(),
|
|
583
|
-
name: dto.name,
|
|
584
|
-
createdAt: now,
|
|
585
|
-
updatedAt: now,
|
|
586
|
-
}
|
|
587
|
-
this.store.set(entity.id, entity)
|
|
588
|
-
return entity
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
592
|
-
// TODO: Implement with ${r}
|
|
593
|
-
const existing = this.store.get(id)
|
|
594
|
-
if (!existing) throw HttpException.notFound('${t} not found')
|
|
595
|
-
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
596
|
-
this.store.set(id, updated)
|
|
597
|
-
return updated
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
async delete(id: string): Promise<void> {
|
|
601
|
-
// TODO: Implement with ${r}
|
|
602
|
-
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
603
|
-
this.store.delete(id)
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
`}function we(e){let{pascal:t,kebab:n}=e;return`/**
|
|
607
|
-
* ${t} Domain Service
|
|
608
|
-
*
|
|
609
|
-
* Domain layer — contains business rules that don't belong to a single entity.
|
|
610
|
-
* Use this for cross-entity logic, validation rules, and domain invariants.
|
|
611
|
-
* Keep it free of HTTP/framework concerns.
|
|
612
|
-
*/
|
|
613
|
-
import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
614
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../repositories/${n}.repository'
|
|
615
|
-
|
|
616
|
-
@Service()
|
|
617
|
-
export class ${t}DomainService {
|
|
618
|
-
constructor(
|
|
619
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
620
|
-
) {}
|
|
621
|
-
|
|
622
|
-
async ensureExists(id: string): Promise<void> {
|
|
623
|
-
const entity = await this.repo.findById(id)
|
|
624
|
-
if (!entity) {
|
|
625
|
-
throw HttpException.notFound('${t} not found')
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
`}function Te(e){let{pascal:t,kebab:n}=e;return`/**
|
|
630
|
-
* ${t} Entity
|
|
631
|
-
*
|
|
632
|
-
* Domain layer — the core business object.
|
|
633
|
-
* Uses a private constructor with static factory methods (create, reconstitute)
|
|
634
|
-
* to enforce invariants. Properties are accessed via getters to maintain encapsulation.
|
|
635
|
-
*
|
|
636
|
-
* Patterns used:
|
|
637
|
-
* - Private constructor: prevents direct instantiation
|
|
638
|
-
* - create(): factory for new entities (generates ID, sets timestamps)
|
|
639
|
-
* - reconstitute(): factory for rebuilding from persistence (no side effects)
|
|
640
|
-
* - changeName(): mutation method that enforces business rules
|
|
641
|
-
*/
|
|
642
|
-
import { ${t}Id } from '../value-objects/${n}-id.vo'
|
|
643
|
-
|
|
644
|
-
interface ${t}Props {
|
|
645
|
-
id: ${t}Id
|
|
646
|
-
name: string
|
|
647
|
-
createdAt: Date
|
|
648
|
-
updatedAt: Date
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
export class ${t} {
|
|
652
|
-
private constructor(private props: ${t}Props) {}
|
|
653
|
-
|
|
654
|
-
static create(params: { name: string }): ${t} {
|
|
655
|
-
const now = new Date()
|
|
656
|
-
return new ${t}({
|
|
657
|
-
id: ${t}Id.create(),
|
|
658
|
-
name: params.name,
|
|
659
|
-
createdAt: now,
|
|
660
|
-
updatedAt: now,
|
|
661
|
-
})
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
static reconstitute(props: ${t}Props): ${t} {
|
|
665
|
-
return new ${t}(props)
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
get id(): ${t}Id {
|
|
669
|
-
return this.props.id
|
|
670
|
-
}
|
|
671
|
-
get name(): string {
|
|
672
|
-
return this.props.name
|
|
673
|
-
}
|
|
674
|
-
get createdAt(): Date {
|
|
675
|
-
return this.props.createdAt
|
|
676
|
-
}
|
|
677
|
-
get updatedAt(): Date {
|
|
678
|
-
return this.props.updatedAt
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
changeName(name: string): void {
|
|
682
|
-
if (!name || name.trim().length === 0) {
|
|
683
|
-
throw new Error('Name cannot be empty')
|
|
684
|
-
}
|
|
685
|
-
this.props.name = name.trim()
|
|
686
|
-
this.props.updatedAt = new Date()
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
toJSON() {
|
|
690
|
-
return {
|
|
691
|
-
id: this.props.id.toString(),
|
|
692
|
-
name: this.props.name,
|
|
693
|
-
createdAt: this.props.createdAt.toISOString(),
|
|
694
|
-
updatedAt: this.props.updatedAt.toISOString(),
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
`}function Ee(e){let{pascal:t}=e;return`/**
|
|
699
|
-
* ${t} ID Value Object
|
|
700
|
-
*
|
|
701
|
-
* Domain layer — wraps a primitive ID with type safety and validation.
|
|
702
|
-
* Value objects are immutable and compared by value, not reference.
|
|
703
|
-
*
|
|
704
|
-
* ${t}Id.create() — generate a new UUID
|
|
705
|
-
* ${t}Id.from(id) — wrap an existing ID string (validates non-empty)
|
|
706
|
-
* id.equals(other) — compare two IDs by value
|
|
707
|
-
*/
|
|
708
|
-
import { randomUUID } from 'node:crypto'
|
|
709
|
-
|
|
710
|
-
export class ${t}Id {
|
|
711
|
-
private constructor(private readonly value: string) {}
|
|
712
|
-
|
|
713
|
-
static create(): ${t}Id {
|
|
714
|
-
return new ${t}Id(randomUUID())
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
static from(id: string): ${t}Id {
|
|
718
|
-
if (!id || id.trim().length === 0) {
|
|
719
|
-
throw new Error('${t}Id cannot be empty')
|
|
720
|
-
}
|
|
721
|
-
return new ${t}Id(id)
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
toString(): string {
|
|
725
|
-
return this.value
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
equals(other: ${t}Id): boolean {
|
|
729
|
-
return this.value === other.value
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
`}function H(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
733
|
-
import { Container } from '@forinda/kickjs'
|
|
734
|
-
|
|
735
|
-
describe('${t}Controller', () => {
|
|
736
|
-
beforeEach(() => {
|
|
737
|
-
Container.reset()
|
|
738
|
-
})
|
|
739
|
-
|
|
740
|
-
it('should be defined', () => {
|
|
741
|
-
expect(true).toBe(true)
|
|
742
|
-
})
|
|
743
|
-
|
|
744
|
-
describe('POST /${r}', () => {
|
|
745
|
-
it('should create a new ${n}', async () => {
|
|
746
|
-
// TODO: Set up test module, call create endpoint, assert 201
|
|
747
|
-
expect(true).toBe(true)
|
|
748
|
-
})
|
|
749
|
-
})
|
|
750
|
-
|
|
751
|
-
describe('GET /${r}', () => {
|
|
752
|
-
it('should return paginated ${r}', async () => {
|
|
753
|
-
// TODO: Set up test module, call list endpoint, assert { data, meta }
|
|
754
|
-
expect(true).toBe(true)
|
|
755
|
-
})
|
|
756
|
-
})
|
|
757
|
-
|
|
758
|
-
describe('GET /${r}/:id', () => {
|
|
759
|
-
it('should return a ${n} by id', async () => {
|
|
760
|
-
// TODO: Create a ${n}, then fetch by id, assert match
|
|
761
|
-
expect(true).toBe(true)
|
|
762
|
-
})
|
|
763
|
-
|
|
764
|
-
it('should return 404 for non-existent ${n}', async () => {
|
|
765
|
-
// TODO: Fetch non-existent id, assert 404
|
|
766
|
-
expect(true).toBe(true)
|
|
767
|
-
})
|
|
768
|
-
})
|
|
769
|
-
|
|
770
|
-
describe('PUT /${r}/:id', () => {
|
|
771
|
-
it('should update an existing ${n}', async () => {
|
|
772
|
-
// TODO: Create, update, assert changes
|
|
773
|
-
expect(true).toBe(true)
|
|
774
|
-
})
|
|
775
|
-
})
|
|
776
|
-
|
|
777
|
-
describe('DELETE /${r}/:id', () => {
|
|
778
|
-
it('should delete a ${n}', async () => {
|
|
779
|
-
// TODO: Create, delete, assert gone
|
|
780
|
-
expect(true).toBe(true)
|
|
781
|
-
})
|
|
782
|
-
})
|
|
783
|
-
})
|
|
784
|
-
`}function U(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'
|
|
785
|
-
import { InMemory${t}Repository } from '${i}'
|
|
786
|
-
|
|
787
|
-
describe('InMemory${t}Repository', () => {
|
|
788
|
-
let repo: InMemory${t}Repository
|
|
789
|
-
|
|
790
|
-
beforeEach(() => {
|
|
791
|
-
repo = new InMemory${t}Repository()
|
|
792
|
-
})
|
|
793
|
-
|
|
794
|
-
it('should create and retrieve a ${n}', async () => {
|
|
795
|
-
const created = await repo.create({ name: 'Test ${t}' })
|
|
796
|
-
expect(created).toBeDefined()
|
|
797
|
-
expect(created.name).toBe('Test ${t}')
|
|
798
|
-
expect(created.id).toBeDefined()
|
|
799
|
-
|
|
800
|
-
const found = await repo.findById(created.id)
|
|
801
|
-
expect(found).toEqual(created)
|
|
802
|
-
})
|
|
803
|
-
|
|
804
|
-
it('should return null for non-existent id', async () => {
|
|
805
|
-
const found = await repo.findById('non-existent')
|
|
806
|
-
expect(found).toBeNull()
|
|
807
|
-
})
|
|
808
|
-
|
|
809
|
-
it('should list all ${r}', async () => {
|
|
810
|
-
await repo.create({ name: '${t} 1' })
|
|
811
|
-
await repo.create({ name: '${t} 2' })
|
|
812
|
-
|
|
813
|
-
const all = await repo.findAll()
|
|
814
|
-
expect(all).toHaveLength(2)
|
|
815
|
-
})
|
|
816
|
-
|
|
817
|
-
it('should return paginated results', async () => {
|
|
818
|
-
await repo.create({ name: '${t} 1' })
|
|
819
|
-
await repo.create({ name: '${t} 2' })
|
|
820
|
-
await repo.create({ name: '${t} 3' })
|
|
821
|
-
|
|
822
|
-
const result = await repo.findPaginated({
|
|
823
|
-
filters: [],
|
|
824
|
-
sort: [],
|
|
825
|
-
search: '',
|
|
826
|
-
pagination: { page: 1, limit: 2, offset: 0 },
|
|
827
|
-
})
|
|
828
|
-
|
|
829
|
-
expect(result.data).toHaveLength(2)
|
|
830
|
-
expect(result.total).toBe(3)
|
|
831
|
-
})
|
|
832
|
-
|
|
833
|
-
it('should update a ${n}', async () => {
|
|
834
|
-
const created = await repo.create({ name: 'Original' })
|
|
835
|
-
const updated = await repo.update(created.id, { name: 'Updated' })
|
|
836
|
-
expect(updated.name).toBe('Updated')
|
|
837
|
-
})
|
|
838
|
-
|
|
839
|
-
it('should delete a ${n}', async () => {
|
|
840
|
-
const created = await repo.create({ name: 'To Delete' })
|
|
841
|
-
await repo.delete(created.id)
|
|
842
|
-
const found = await repo.findById(created.id)
|
|
843
|
-
expect(found).toBeNull()
|
|
844
|
-
})
|
|
845
|
-
})
|
|
846
|
-
`}function De(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
847
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
848
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
|
|
849
|
-
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
850
|
-
import type { Create${t}DTO } from './dtos/create-${n}.dto'
|
|
851
|
-
import type { Update${t}DTO } from './dtos/update-${n}.dto'
|
|
852
|
-
|
|
853
|
-
@Service()
|
|
854
|
-
export class ${t}Service {
|
|
855
|
-
constructor(
|
|
856
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
857
|
-
) {}
|
|
858
|
-
|
|
859
|
-
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
860
|
-
return this.repo.findById(id)
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
864
|
-
return this.repo.findAll()
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
async findPaginated(parsed: ParsedQuery) {
|
|
868
|
-
return this.repo.findPaginated(parsed)
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
872
|
-
return this.repo.create(dto)
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
876
|
-
return this.repo.update(id, dto)
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
async delete(id: string): Promise<void> {
|
|
880
|
-
await this.repo.delete(id)
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
`}function W(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
884
|
-
|
|
885
|
-
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
886
|
-
filterable: ['name'],
|
|
887
|
-
sortable: ['name', 'createdAt'],
|
|
888
|
-
searchable: ['name'],
|
|
889
|
-
}
|
|
890
|
-
`}function Oe(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o={inmemory:`InMemory${t}Repository`,drizzle:`Drizzle${t}Repository`,prisma:`Prisma${t}Repository`},s={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},c=o[i]??o.inmemory,l=s[i]??s.inmemory,u=a??`define`,d=`/**
|
|
891
|
-
* ${t} Module — CQRS Pattern
|
|
892
|
-
*
|
|
893
|
-
* Separates read (queries) and write (commands) operations.
|
|
894
|
-
* Events are emitted after state changes and can be handled via
|
|
895
|
-
* WebSocket broadcasts, queue jobs, or ETL pipelines.
|
|
896
|
-
*
|
|
897
|
-
* Structure:
|
|
898
|
-
* commands/ — Write operations (create, update, delete)
|
|
899
|
-
* queries/ — Read operations (get, list)
|
|
900
|
-
* events/ — Domain events + handlers (WS broadcast, queue dispatch)
|
|
901
|
-
* dtos/ — Request/response schemas
|
|
902
|
-
*/`,f=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
|
|
903
|
-
import { ${c} } from './${l}.repository'
|
|
904
|
-
import { ${t}Controller } from './${n}.controller'
|
|
905
|
-
|
|
906
|
-
// Eagerly load decorated classes
|
|
907
|
-
import.meta.glob(
|
|
908
|
-
[
|
|
909
|
-
'./commands/**/*.ts',
|
|
910
|
-
'./queries/**/*.ts',
|
|
911
|
-
'./events/**/*.ts',
|
|
912
|
-
'!./**/*.test.ts',
|
|
913
|
-
],
|
|
914
|
-
{ eager: true },
|
|
915
|
-
)`,p=` /**
|
|
916
|
-
* Declare HTTP routes for this CQRS module. Return value shape:
|
|
917
|
-
*
|
|
918
|
-
* - \`path\` — URL prefix for this route set.
|
|
919
|
-
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
920
|
-
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
921
|
-
*
|
|
922
|
-
* Return an array to mount multiple route sets:
|
|
923
|
-
*
|
|
924
|
-
* return [
|
|
925
|
-
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
926
|
-
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
927
|
-
* ]
|
|
928
|
-
*/`;return u===`class`?`${d}
|
|
929
|
-
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
930
|
-
${f}
|
|
931
|
-
|
|
932
|
-
export class ${t}Module implements AppModule {
|
|
933
|
-
register(container: Container): void {
|
|
934
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
935
|
-
container.resolve(${c}),
|
|
936
|
-
)
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
${p.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
940
|
-
routes(): ModuleRoutes {
|
|
941
|
-
return {
|
|
942
|
-
path: '/${r}',
|
|
943
|
-
controller: ${t}Controller,
|
|
944
|
-
}
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
`:`${d}
|
|
948
|
-
import { defineModule } from '@forinda/kickjs'
|
|
949
|
-
${f}
|
|
950
|
-
|
|
951
|
-
export const ${t}Module = defineModule({
|
|
952
|
-
name: '${t}Module',
|
|
953
|
-
build: () => ({
|
|
954
|
-
register(container) {
|
|
955
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
956
|
-
container.resolve(${c}),
|
|
957
|
-
)
|
|
958
|
-
},
|
|
959
|
-
|
|
960
|
-
${p}
|
|
961
|
-
routes() {
|
|
962
|
-
return {
|
|
963
|
-
path: '/${r}',
|
|
964
|
-
controller: ${t}Controller,
|
|
965
|
-
}
|
|
966
|
-
},
|
|
967
|
-
}),
|
|
968
|
-
})
|
|
969
|
-
`}function ke(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
970
|
-
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
971
|
-
import { Create${t}Command } from './commands/create-${n}.command'
|
|
972
|
-
import { Update${t}Command } from './commands/update-${n}.command'
|
|
973
|
-
import { Delete${t}Command } from './commands/delete-${n}.command'
|
|
974
|
-
import { Get${t}Query } from './queries/get-${n}.query'
|
|
975
|
-
import { List${i}Query } from './queries/list-${r}.query'
|
|
976
|
-
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
977
|
-
import { update${t}Schema } from './dtos/update-${n}.dto'
|
|
978
|
-
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
979
|
-
|
|
980
|
-
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
981
|
-
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
982
|
-
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
983
|
-
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
984
|
-
|
|
985
|
-
@Controller()
|
|
986
|
-
export class ${t}Controller {
|
|
987
|
-
@Autowired() private readonly create${t}Command!: Create${t}Command
|
|
988
|
-
@Autowired() private readonly update${t}Command!: Update${t}Command
|
|
989
|
-
@Autowired() private readonly delete${t}Command!: Delete${t}Command
|
|
990
|
-
@Autowired() private readonly get${t}Query!: Get${t}Query
|
|
991
|
-
@Autowired() private readonly list${i}Query!: List${i}Query
|
|
992
|
-
|
|
993
|
-
@Get('/')
|
|
994
|
-
@ApiTags('${t}')
|
|
995
|
-
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
996
|
-
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
997
|
-
return ctx.paginate(
|
|
998
|
-
(parsed) => this.list${i}Query.execute(parsed),
|
|
999
|
-
${t.toUpperCase()}_QUERY_CONFIG,
|
|
1000
|
-
)
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
@Get('/:id')
|
|
1004
|
-
@ApiTags('${t}')
|
|
1005
|
-
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
1006
|
-
const result = await this.get${t}Query.execute(ctx.params.id)
|
|
1007
|
-
if (!result) return ctx.notFound('${t} not found')
|
|
1008
|
-
ctx.json(result)
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
1012
|
-
@ApiTags('${t}')
|
|
1013
|
-
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
1014
|
-
const result = await this.create${t}Command.execute(ctx.body)
|
|
1015
|
-
ctx.created(result)
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
1019
|
-
@ApiTags('${t}')
|
|
1020
|
-
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
1021
|
-
const result = await this.update${t}Command.execute(ctx.params.id, ctx.body)
|
|
1022
|
-
ctx.json(result)
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
@Delete('/:id')
|
|
1026
|
-
@ApiTags('${t}')
|
|
1027
|
-
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
1028
|
-
await this.delete${t}Command.execute(ctx.params.id)
|
|
1029
|
-
ctx.noContent()
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
`}function Ae(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1033
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
1034
|
-
import type { Create${t}DTO } from '../dtos/create-${n}.dto'
|
|
1035
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1036
|
-
import { ${t}Events } from '../events/${n}.events'
|
|
1037
|
-
|
|
1038
|
-
@Service()
|
|
1039
|
-
export class Create${t}Command {
|
|
1040
|
-
constructor(
|
|
1041
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1042
|
-
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
1043
|
-
) {}
|
|
1044
|
-
|
|
1045
|
-
async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1046
|
-
const result = await this.repo.create(dto)
|
|
1047
|
-
this.events.emit('${n}.created', result)
|
|
1048
|
-
return result
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
`},{file:`update-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1052
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
1053
|
-
import type { Update${t}DTO } from '../dtos/update-${n}.dto'
|
|
1054
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1055
|
-
import { ${t}Events } from '../events/${n}.events'
|
|
1056
|
-
|
|
1057
|
-
@Service()
|
|
1058
|
-
export class Update${t}Command {
|
|
1059
|
-
constructor(
|
|
1060
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1061
|
-
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
1062
|
-
) {}
|
|
1063
|
-
|
|
1064
|
-
async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1065
|
-
const result = await this.repo.update(id, dto)
|
|
1066
|
-
this.events.emit('${n}.updated', result)
|
|
1067
|
-
return result
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
`},{file:`delete-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1071
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
1072
|
-
import { ${t}Events } from '../events/${n}.events'
|
|
1073
|
-
|
|
1074
|
-
@Service()
|
|
1075
|
-
export class Delete${t}Command {
|
|
1076
|
-
constructor(
|
|
1077
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1078
|
-
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
1079
|
-
) {}
|
|
1080
|
-
|
|
1081
|
-
async execute(id: string): Promise<void> {
|
|
1082
|
-
await this.repo.delete(id)
|
|
1083
|
-
this.events.emit('${n}.deleted', { id })
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
`}]}function je(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1087
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
1088
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1089
|
-
|
|
1090
|
-
@Service()
|
|
1091
|
-
export class Get${t}Query {
|
|
1092
|
-
constructor(
|
|
1093
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1094
|
-
) {}
|
|
1095
|
-
|
|
1096
|
-
async execute(id: string): Promise<${t}ResponseDTO | null> {
|
|
1097
|
-
return this.repo.findById(id)
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
`},{file:`list-${r}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1101
|
-
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
1102
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1103
|
-
|
|
1104
|
-
@Service()
|
|
1105
|
-
export class List${i}Query {
|
|
1106
|
-
constructor(
|
|
1107
|
-
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1108
|
-
) {}
|
|
1109
|
-
|
|
1110
|
-
async execute(parsed: ParsedQuery) {
|
|
1111
|
-
return this.repo.findPaginated(parsed)
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
`}]}function Me(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
|
|
1115
|
-
import { EventEmitter } from 'node:events'
|
|
1116
|
-
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1117
|
-
|
|
1118
|
-
/**
|
|
1119
|
-
* ${t} domain event types.
|
|
1120
|
-
*
|
|
1121
|
-
* These events are emitted by commands after state changes.
|
|
1122
|
-
* Subscribe to them in event handlers for side effects:
|
|
1123
|
-
* - WebSocket broadcasts (real-time UI updates)
|
|
1124
|
-
* - Queue jobs (async processing, ETL pipelines)
|
|
1125
|
-
* - Audit logging
|
|
1126
|
-
* - Cache invalidation
|
|
1127
|
-
*/
|
|
1128
|
-
export interface ${t}EventMap {
|
|
1129
|
-
'${n}.created': ${t}ResponseDTO
|
|
1130
|
-
'${n}.updated': ${t}ResponseDTO
|
|
1131
|
-
'${n}.deleted': { id: string }
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
@Service()
|
|
1135
|
-
export class ${t}Events {
|
|
1136
|
-
private emitter = new EventEmitter()
|
|
1137
|
-
|
|
1138
|
-
emit<K extends keyof ${t}EventMap>(event: K, data: ${t}EventMap[K]): void {
|
|
1139
|
-
this.emitter.emit(event, data)
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
on<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
|
|
1143
|
-
this.emitter.on(event, handler)
|
|
1144
|
-
}
|
|
1145
|
-
|
|
1146
|
-
off<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
|
|
1147
|
-
this.emitter.off(event, handler)
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
`},{file:`on-${n}-change.handler.ts`,content:`import { Service, Autowired } from '@forinda/kickjs'
|
|
1151
|
-
import { ${t}Events } from './${n}.events'
|
|
1152
|
-
|
|
1153
|
-
/**
|
|
1154
|
-
* ${t} Change Event Handler
|
|
1155
|
-
*
|
|
1156
|
-
* Reacts to domain events emitted by commands.
|
|
1157
|
-
* Wire up side effects here:
|
|
1158
|
-
*
|
|
1159
|
-
* 1. WebSocket broadcast — notify connected clients in real-time
|
|
1160
|
-
* import { WsGateway } from '@forinda/kickjs-ws'
|
|
1161
|
-
* this.ws.broadcast('${n}-channel', { event, data })
|
|
1162
|
-
*
|
|
1163
|
-
* 2. Queue dispatch — offload heavy processing to background workers
|
|
1164
|
-
* import { QueueService } from '@forinda/kickjs-queue'
|
|
1165
|
-
* this.queue.add('${n}-etl', { action: event, payload: data })
|
|
1166
|
-
*
|
|
1167
|
-
* 3. ETL pipeline — transform and load data to external systems
|
|
1168
|
-
* await this.etlPipeline.process(data)
|
|
1169
|
-
*/
|
|
1170
|
-
@Service()
|
|
1171
|
-
export class On${t}ChangeHandler {
|
|
1172
|
-
@Autowired() private events!: ${t}Events
|
|
1173
|
-
|
|
1174
|
-
// Uncomment to inject WebSocket and Queue services:
|
|
1175
|
-
// @Autowired() private ws!: WsGateway
|
|
1176
|
-
// @Autowired() private queue!: QueueService
|
|
1177
|
-
|
|
1178
|
-
onInit(): void {
|
|
1179
|
-
this.events.on('${n}.created', (data) => {
|
|
1180
|
-
console.log('[${t}] Created:', data.id)
|
|
1181
|
-
// TODO: Broadcast via WebSocket
|
|
1182
|
-
// this.ws.broadcast('${n}-channel', { event: '${n}.created', data })
|
|
1183
|
-
// TODO: Dispatch to queue for async processing / ETL
|
|
1184
|
-
// this.queue.add('${n}-etl', { action: 'create', payload: data })
|
|
1185
|
-
})
|
|
1186
|
-
|
|
1187
|
-
this.events.on('${n}.updated', (data) => {
|
|
1188
|
-
console.log('[${t}] Updated:', data.id)
|
|
1189
|
-
// TODO: Broadcast via WebSocket
|
|
1190
|
-
// this.ws.broadcast('${n}-channel', { event: '${n}.updated', data })
|
|
1191
|
-
})
|
|
1192
|
-
|
|
1193
|
-
this.events.on('${n}.deleted', (data) => {
|
|
1194
|
-
console.log('[${t}] Deleted:', data.id)
|
|
1195
|
-
// TODO: Broadcast via WebSocket
|
|
1196
|
-
// this.ws.broadcast('${n}-channel', { event: '${n}.deleted', data })
|
|
1197
|
-
})
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
`}]}function G(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
1201
|
-
* Drizzle ${t} Repository
|
|
1202
|
-
*
|
|
1203
|
-
* Implements the repository interface using Drizzle ORM.
|
|
1204
|
-
* Uses buildFromColumns() with Column objects for type-safe query building.
|
|
1205
|
-
*
|
|
1206
|
-
* TODO: Update the schema import to match your Drizzle schema file.
|
|
1207
|
-
* TODO: Replace DRIZZLE_DB injection token with your actual database token.
|
|
1208
|
-
*
|
|
1209
|
-
* @Repository() registers this class in the DI container as a singleton.
|
|
1210
|
-
*/
|
|
1211
|
-
import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
|
|
1212
|
-
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
1213
|
-
import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
|
|
1214
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1215
|
-
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
1216
|
-
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
1217
|
-
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
1218
|
-
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
1219
|
-
import { ${t.toUpperCase()}_QUERY_CONFIG } from '../../constants'
|
|
1220
|
-
|
|
1221
|
-
// TODO: Import your Drizzle schema table — e.g.:
|
|
1222
|
-
// import { ${n}s } from '@/db/schema'
|
|
1223
|
-
|
|
1224
|
-
const queryAdapter = new DrizzleQueryAdapter({
|
|
1225
|
-
eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
|
|
1226
|
-
})
|
|
1227
|
-
|
|
1228
|
-
@Repository()
|
|
1229
|
-
export class Drizzle${t}Repository implements I${t}Repository {
|
|
1230
|
-
constructor(@Inject(DRIZZLE_DB) private db: any) {}
|
|
1231
|
-
|
|
1232
|
-
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
1233
|
-
// TODO: Implement with Drizzle
|
|
1234
|
-
// const row = this.db.select().from(${n}s).where(eq(${n}s.id, id)).get()
|
|
1235
|
-
// return row ?? null
|
|
1236
|
-
throw new Error('Drizzle ${t} repository not yet implemented — update schema imports and queries')
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
1240
|
-
// TODO: Implement with Drizzle
|
|
1241
|
-
// return this.db.select().from(${n}s).all()
|
|
1242
|
-
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
1243
|
-
}
|
|
1244
|
-
|
|
1245
|
-
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
1246
|
-
// TODO: Use buildFromColumns() with your query config for type-safe filtering
|
|
1247
|
-
// const query = queryAdapter.buildFromColumns(parsed, ${t.toUpperCase()}_QUERY_CONFIG)
|
|
1248
|
-
//
|
|
1249
|
-
// const data = this.db
|
|
1250
|
-
// .select().from(${n}s).$dynamic()
|
|
1251
|
-
// .where(query.where).orderBy(...query.orderBy)
|
|
1252
|
-
// .limit(query.limit).offset(query.offset).all()
|
|
1253
|
-
//
|
|
1254
|
-
// const totalResult = this.db
|
|
1255
|
-
// .select({ count: count() }).from(${n}s)
|
|
1256
|
-
// .$dynamic().where(query.where).get()
|
|
1257
|
-
//
|
|
1258
|
-
// return { data, total: totalResult?.count ?? 0 }
|
|
1259
|
-
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
1260
|
-
}
|
|
1261
|
-
|
|
1262
|
-
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1263
|
-
// TODO: Implement with Drizzle
|
|
1264
|
-
// return this.db.insert(${n}s).values(dto).returning().get()
|
|
1265
|
-
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1269
|
-
// TODO: Implement with Drizzle
|
|
1270
|
-
// const row = this.db.update(${n}s).set(dto).where(eq(${n}s.id, id)).returning().get()
|
|
1271
|
-
// if (!row) throw HttpException.notFound('${t} not found')
|
|
1272
|
-
// return row
|
|
1273
|
-
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
async delete(id: string): Promise<void> {
|
|
1277
|
-
// TODO: Implement with Drizzle
|
|
1278
|
-
// this.db.delete(${n}s).where(eq(${n}s.id, id)).run()
|
|
1279
|
-
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
`}function Ne(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
|
|
1283
|
-
// TODO: Import your schema table and reference actual columns for type safety
|
|
1284
|
-
// import { ${n}s } from '@/db/schema'
|
|
1285
|
-
|
|
1286
|
-
export const ${t.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
|
|
1287
|
-
columns: {
|
|
1288
|
-
// Replace with actual Drizzle Column references for type-safe filtering:
|
|
1289
|
-
// name: ${n}s.name,
|
|
1290
|
-
// status: ${n}s.status,
|
|
1291
|
-
},
|
|
1292
|
-
sortable: {
|
|
1293
|
-
// name: ${n}s.name,
|
|
1294
|
-
// createdAt: ${n}s.createdAt,
|
|
1295
|
-
},
|
|
1296
|
-
searchColumns: [
|
|
1297
|
-
// ${n}s.name,
|
|
1298
|
-
],
|
|
1299
|
-
}
|
|
1300
|
-
`}function K(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`/**
|
|
1301
|
-
* Prisma ${t} Repository
|
|
1302
|
-
*
|
|
1303
|
-
* Implements the repository interface using Prisma Client.
|
|
1304
|
-
* Requires a PrismaClient instance injected via the DI container.
|
|
1305
|
-
*
|
|
1306
|
-
* Ensure your Prisma schema has a '${t}' model defined.
|
|
1307
|
-
*
|
|
1308
|
-
* For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
|
|
1309
|
-
* @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
|
|
1310
|
-
*
|
|
1311
|
-
* @Repository() registers this class in the DI container as a singleton.
|
|
1312
|
-
*/
|
|
1313
|
-
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
1314
|
-
import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
|
|
1315
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1316
|
-
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
1317
|
-
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
1318
|
-
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
1319
|
-
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
1320
|
-
|
|
1321
|
-
@Repository()
|
|
1322
|
-
export class Prisma${t}Repository implements I${t}Repository {
|
|
1323
|
-
@Inject(PRISMA_CLIENT) private prisma!: { ${a}: PrismaModelDelegate }
|
|
1324
|
-
|
|
1325
|
-
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
1326
|
-
return this.prisma.${a}.findUnique({ where: { id } }) as Promise<${t}ResponseDTO | null>
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
1330
|
-
return this.prisma.${a}.findMany() as Promise<${t}ResponseDTO[]>
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
1334
|
-
const [data, total] = await Promise.all([
|
|
1335
|
-
this.prisma.${a}.findMany({
|
|
1336
|
-
skip: parsed.pagination.offset,
|
|
1337
|
-
take: parsed.pagination.limit,
|
|
1338
|
-
}) as Promise<${t}ResponseDTO[]>,
|
|
1339
|
-
this.prisma.${a}.count(),
|
|
1340
|
-
])
|
|
1341
|
-
return { data, total }
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1345
|
-
return this.prisma.${a}.create({ data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1349
|
-
const existing = await this.prisma.${a}.findUnique({ where: { id } })
|
|
1350
|
-
if (!existing) throw HttpException.notFound('${t} not found')
|
|
1351
|
-
return this.prisma.${a}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
async delete(id: string): Promise<void> {
|
|
1355
|
-
await this.prisma.${a}.deleteMany({ where: { id } })
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
`}function Pe(e,t,n,r=[]){switch(t){case`cqrs`:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
|
|
1359
|
-
// Side-effect import — registers the extended env schema with kickjs
|
|
1360
|
-
// **before** any controller / service / @Value gets resolved. Without
|
|
1361
|
-
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1362
|
-
// cached schema would still be the base shape. See guide/configuration.
|
|
1363
|
-
import './config'
|
|
1364
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
1365
|
-
// import { WsAdapter } from '@forinda/kickjs-ws'
|
|
1366
|
-
// import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
|
|
1367
|
-
${t.length?t.join(`
|
|
1368
|
-
`)+`
|
|
1369
|
-
`:``}import { modules } from './modules'
|
|
1370
|
-
|
|
1371
|
-
// Export the app for the Vite plugin (dev mode)
|
|
1372
|
-
export const app = await bootstrap({
|
|
1373
|
-
modules,${t.length?`\n adapters: [\n${i.join(`
|
|
1374
|
-
`)}\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 ],`:`
|
|
1375
|
-
adapters: [
|
|
1376
|
-
// Uncomment for WebSocket support:
|
|
1377
|
-
// WsAdapter(),
|
|
1378
|
-
// Uncomment when Redis is available:
|
|
1379
|
-
// QueueAdapter({
|
|
1380
|
-
// provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
|
|
1381
|
-
// }),
|
|
1382
|
-
],`}
|
|
1383
|
-
})
|
|
1384
|
-
`}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'
|
|
1385
|
-
// Side-effect import — registers the extended env schema with kickjs
|
|
1386
|
-
// **before** any controller / service / @Value gets resolved. Without
|
|
1387
|
-
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1388
|
-
// cached schema would still be the base shape. See guide/configuration.
|
|
1389
|
-
import './config'
|
|
1390
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
1391
|
-
${t.length?t.join(`
|
|
1392
|
-
`)+`
|
|
1393
|
-
`:``}import { modules } from './modules'
|
|
1394
|
-
|
|
1395
|
-
// Export the app for the Vite plugin (dev mode)
|
|
1396
|
-
export const app = await bootstrap({ modules${i.length?`,\n adapters: [\n${i.join(`
|
|
1397
|
-
`)}\n ]`:``} })
|
|
1398
|
-
`}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'
|
|
1399
|
-
// Side-effect import — registers the extended env schema with kickjs
|
|
1400
|
-
// **before** any controller / service / @Value gets resolved. Without
|
|
1401
|
-
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1402
|
-
// cached schema would still be the base shape. See guide/configuration.
|
|
1403
|
-
import './config'
|
|
1404
|
-
import express from 'express'
|
|
1405
|
-
import {
|
|
1406
|
-
bootstrap,
|
|
1407
|
-
requestId,
|
|
1408
|
-
requestLogger,
|
|
1409
|
-
helmet,
|
|
1410
|
-
cors,
|
|
1411
|
-
} from '@forinda/kickjs'
|
|
1412
|
-
${t.length?t.join(`
|
|
1413
|
-
`)+`
|
|
1414
|
-
`:``}import { modules } from './modules'
|
|
1415
|
-
|
|
1416
|
-
// Export the app for the Vite plugin (dev mode)
|
|
1417
|
-
export const app = await bootstrap({
|
|
1418
|
-
modules,${i.length?`\n adapters: [\n${i.join(`
|
|
1419
|
-
`)}\n ],`:``}
|
|
1420
|
-
middleware: [
|
|
1421
|
-
helmet(),
|
|
1422
|
-
cors({ origin: '*' }),
|
|
1423
|
-
requestId(),
|
|
1424
|
-
requestLogger(),
|
|
1425
|
-
express.json(),
|
|
1426
|
-
],
|
|
1427
|
-
})
|
|
1428
|
-
`}}}function Fe(){return`import { defineModules } from '@forinda/kickjs'
|
|
1429
|
-
import { HelloModule } from './hello/hello.module'
|
|
1430
|
-
|
|
1431
|
-
// Remove HelloModule and run: kick g module <name>
|
|
1432
|
-
// \`defineModules()\` returns a chainable list — \`kick g module\` appends
|
|
1433
|
-
// \`.mount(NewModule())\` to the chain on every generation.
|
|
1434
|
-
export const modules = defineModules().mount(HelloModule())
|
|
1435
|
-
`}function Ie(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
|
|
1436
|
-
import { z } from 'zod'
|
|
1437
|
-
|
|
1438
|
-
/**
|
|
1439
|
-
* Project environment schema.
|
|
1440
|
-
*
|
|
1441
|
-
* Extend the base schema with your application's variables. The
|
|
1442
|
-
* default export is the contract \`kick typegen\` reads to populate
|
|
1443
|
-
* the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
|
|
1444
|
-
* autocomplete and \`process.env.FOO\` typed.
|
|
1445
|
-
*
|
|
1446
|
-
* @example
|
|
1447
|
-
* DATABASE_URL: z.string().url(),
|
|
1448
|
-
* JWT_SECRET: z.string().min(32),
|
|
1449
|
-
* REDIS_URL: z.string().url().optional(),
|
|
1450
|
-
*/
|
|
1451
|
-
const envSchema = defineEnv((base) =>
|
|
1452
|
-
base.extend({
|
|
1453
|
-
// DATABASE_URL: z.string().url(),
|
|
1454
|
-
}),
|
|
1455
|
-
)
|
|
1456
|
-
|
|
1457
|
-
/**
|
|
1458
|
-
* IMPORTANT — side effect: register the schema with kickjs's env cache
|
|
1459
|
-
* **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
|
|
1460
|
-
* this cache, and they will fall back to the base schema (or undefined)
|
|
1461
|
-
* if no extended schema has been registered before they're resolved.
|
|
1462
|
-
*
|
|
1463
|
-
* As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
|
|
1464
|
-
* top — before \`bootstrap()\` runs — every controller and service in the
|
|
1465
|
-
* app sees the typed extended values.
|
|
1466
|
-
*/
|
|
1467
|
-
export const env = loadEnv(envSchema)
|
|
1468
|
-
|
|
1469
|
-
export default envSchema
|
|
1470
|
-
`}function Le(){return`import { Service } from '@forinda/kickjs'
|
|
1471
|
-
|
|
1472
|
-
@Service()
|
|
1473
|
-
export class HelloService {
|
|
1474
|
-
greet(name: string) {
|
|
1475
|
-
return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
|
|
1476
|
-
}
|
|
1477
|
-
|
|
1478
|
-
healthCheck() {
|
|
1479
|
-
return { status: 'ok', uptime: process.uptime() }
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
`}function Re(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
|
|
1483
|
-
import { HelloService } from './hello.service'
|
|
1484
|
-
|
|
1485
|
-
// \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
|
|
1486
|
-
// \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
|
|
1487
|
-
// scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
|
|
1488
|
-
// See https://forinda.github.io/kick-js/guide/typegen.
|
|
1489
|
-
|
|
1490
|
-
@Controller()
|
|
1491
|
-
export class HelloController {
|
|
1492
|
-
@Autowired() private readonly helloService!: HelloService
|
|
1493
|
-
|
|
1494
|
-
@Get('/')
|
|
1495
|
-
index(ctx: Ctx<KickRoutes.HelloController['index']>) {
|
|
1496
|
-
ctx.json(this.helloService.greet('World'))
|
|
1497
|
-
}
|
|
1498
|
-
|
|
1499
|
-
@Get('/health')
|
|
1500
|
-
health(ctx: Ctx<KickRoutes.HelloController['health']>) {
|
|
1501
|
-
ctx.json(this.helloService.healthCheck())
|
|
1502
|
-
}
|
|
1503
|
-
}
|
|
1504
|
-
`}function ze(){return`import { defineModule } from '@forinda/kickjs'
|
|
1505
|
-
import { HelloController } from './hello.controller'
|
|
1506
|
-
|
|
1507
|
-
export const HelloModule = defineModule({
|
|
1508
|
-
name: 'HelloModule',
|
|
1509
|
-
build: () => ({
|
|
1510
|
-
// \`register(container)\` is optional — only implement it when you need
|
|
1511
|
-
// to bind a token to a concrete implementation, e.g.
|
|
1512
|
-
// register(container) {
|
|
1513
|
-
// container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
|
|
1514
|
-
// }
|
|
1515
|
-
// The HelloService uses @Service() so the decorator handles registration.
|
|
1516
|
-
|
|
1517
|
-
routes() {
|
|
1518
|
-
return {
|
|
1519
|
-
path: '/hello',
|
|
1520
|
-
controller: HelloController,
|
|
1521
|
-
}
|
|
1522
|
-
},
|
|
1523
|
-
}),
|
|
1524
|
-
})
|
|
1525
|
-
`}function Be(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1526
|
-
|
|
1527
|
-
export default defineConfig({
|
|
1528
|
-
pattern: '${e}',
|
|
1529
|
-
// Pinned so \`kick add\` and other dep-installing commands always use the
|
|
1530
|
-
// project's intended package manager, regardless of which lockfile exists.
|
|
1531
|
-
packageManager: '${n}',
|
|
1532
|
-
modules: {
|
|
1533
|
-
dir: 'src/modules',
|
|
1534
|
-
repo: ${[`drizzle`,`inmemory`,`prisma`].includes(t)?`'${t}'`:`{ name: '${t}' }`},
|
|
1535
|
-
pluralize: true,
|
|
1536
|
-
},
|
|
1537
|
-
|
|
1538
|
-
// \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
|
|
1539
|
-
// resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
|
|
1540
|
-
// Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
|
|
1541
|
-
typegen: {
|
|
1542
|
-
schemaValidator: 'zod',
|
|
1543
|
-
},
|
|
1544
|
-
|
|
1545
|
-
commands: [
|
|
1546
|
-
{
|
|
1547
|
-
name: 'test',
|
|
1548
|
-
description: 'Run tests with Vitest',
|
|
1549
|
-
steps: 'npx vitest run',
|
|
1550
|
-
},
|
|
1551
|
-
{
|
|
1552
|
-
name: 'format',
|
|
1553
|
-
description: 'Format code with Prettier',
|
|
1554
|
-
steps: 'npx prettier --write src/',
|
|
1555
|
-
},
|
|
1556
|
-
{
|
|
1557
|
-
name: 'format:check',
|
|
1558
|
-
description: 'Check formatting without writing',
|
|
1559
|
-
steps: 'npx prettier --check src/',
|
|
1560
|
-
},
|
|
1561
|
-
{
|
|
1562
|
-
name: 'ci:check',
|
|
1563
|
-
description: 'Run typecheck + format check',
|
|
1564
|
-
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
1565
|
-
aliases: ['verify'],
|
|
1566
|
-
},
|
|
1567
|
-
],
|
|
1568
|
-
})
|
|
1569
|
-
`}async function Ve(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,ye({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
|
|
1570
|
-
|
|
1571
|
-
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
1572
|
-
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
1573
|
-
|
|
1574
|
-
@Controller()
|
|
1575
|
-
export class ${t}Controller {
|
|
1576
|
-
@Get('/')
|
|
1577
|
-
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
1578
|
-
ctx.json({ message: '${t} list' })
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
`)}async function He(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,ve({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,xe({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`${n}.service.ts`,De({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n})),await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let d={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},f={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},p=d[a]??`${k(a)}-${n}`,m=f[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${p}.repository.ts`,m()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${d.inmemory??`in-memory-${n}`}.repository`})))}async function Ue(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,Oe({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,W({pascal:t,kebab:n})),await u(`${n}.controller.ts`,ke({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let d=Ae({pascal:t,kebab:n});for(let e of d)await u(`commands/${e.file}`,e.content);let f=je({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await u(`queries/${e.file}`,e.content);let p=Me({pascal:t,kebab:n});for(let e of p)await u(`events/${e.file}`,e.content);await u(`${n}.repository.ts`,z({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let m={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},h={inmemory:()=>B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>G({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>K({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},g=m[a]??`${k(a)}-${n}`,_=h[a]??(()=>V({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${g}.repository.ts`,_()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,B({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r,repoPrefix:`../${m.inmemory??`in-memory-${n}`}.repository`})))}async function We(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noEntity:o,noTests:s,prismaClientPath:c,tokenScope:l,style:u,write:d}=e;await d(`${n}.module.ts`,_e({pascal:t,kebab:n,plural:r,repo:a,style:u})),await d(`constants.ts`,a===`drizzle`?Ne({pascal:t,kebab:n}):Se({pascal:t,kebab:n})),await d(`presentation/${n}.controller.ts`,be({pascal:t,kebab:n,plural:r,pluralPascal:i})),await d(`application/dtos/create-${n}.dto.ts`,I({pascal:t,kebab:n})),await d(`application/dtos/update-${n}.dto.ts`,L({pascal:t,kebab:n})),await d(`application/dtos/${n}-response.dto.ts`,R({pascal:t,kebab:n}));let f=Ce({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await d(`application/use-cases/${e.file}`,e.content);await d(`domain/repositories/${n}.repository.ts`,z({pascal:t,kebab:n,tokenScope:l})),await d(`domain/services/${n}-domain.service.ts`,we({pascal:t,kebab:n}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>B({pascal:t,kebab:n}),drizzle:()=>G({pascal:t,kebab:n}),prisma:()=>K({pascal:t,kebab:n,prismaClientPath:c})},h=p[a]??`${k(a)}-${n}`,g=m[a]??(()=>V({pascal:t,kebab:n,repoType:a}));await d(`infrastructure/repositories/${h}.repository.ts`,g()),o||(await d(`domain/entities/${n}.entity.ts`,Te({pascal:t,kebab:n})),await d(`domain/value-objects/${n}-id.vo.ts`,Ee({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await d(`infrastructure/repositories/in-memory-${n}.repository.ts`,B({pascal:t,kebab:n})),await d(`__tests__/${n}.controller.test.ts`,H({pascal:t,kebab:n,plural:r})),await d(`__tests__/${n}.repository.test.ts`,U({pascal:t,kebab:n,plural:r})))}function Ge(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Ke(e){let{name:t,modulesDir:n,noEntity:r,noTests:a,repo:o=`inmemory`,force:s,dryRun:c}=e,l=e.pluralize!==!1,u=e.pattern??`ddd`;e.minimal&&(u=`minimal`);let d=k(t),f=D(t),m=l?A(d):d,h=l?me(f):f,g=i(n,m),_=[],v=s??!1,y={kebab:d,pascal:f,plural:m,pluralPascal:h,moduleDir:g,repo:o,noEntity:r??!1,noTests:a??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=i(g,e);if(c){_.push(n);return}if(!v&&await C(n)&&!await T({message:`File exists: ${p.dim(e)}. Overwrite?`,initialValue:!1})){E.warn(`Skipped: ${e}`);return}await b(n,t),_.push(n)},files:_};switch(u){case`minimal`:await Ve(y);break;case`rest`:await He(y);break;case`cqrs`:await Ue(y);break;default:await We(y);break}return c||await q(n,f,m,d,y.style),_}async function q(e,t,n,r,a=`define`){let o=i(e,`index.ts`),s=await C(o),c=`./${n}/${r}.module`,l=a===`class`?`${t}Module`:`${t}Module()`;if(!s){await b(o,a===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
1582
|
-
import { ${t}Module } from '${c}'
|
|
1583
|
-
|
|
1584
|
-
export const modules: AppModuleEntry[] = [${l}]
|
|
1585
|
-
`:`import { defineModules } from '@forinda/kickjs'
|
|
1586
|
-
import { ${t}Module } from '${c}'
|
|
1587
|
-
|
|
1588
|
-
export const modules = defineModules().mount(${l})
|
|
1589
|
-
`);return}let f=await u(o,`utf-8`),p=`import { ${t}Module } from '${c}'`,m=j(c);if(!RegExp(`^import\\s*\\{[^}]*\\b${j(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${m}['"]`,`m`).test(f)){let e=f.lastIndexOf(`import `);if(e!==-1){let t=f.indexOf(`
|
|
1590
|
-
`,e);f=f.slice(0,t+1)+p+`
|
|
1591
|
-
`+f.slice(t+1)}else f=p+`
|
|
1592
|
-
`+f}let h=Y(f);if(h){let e=f.slice(h.rhsStart,h.rhsEnd+1);RegExp(`\\b${j(t)}Module\\b`).test(e)||(f=J(f,l))}else f=J(f,l);await d(o,f,`utf-8`)}function J(e,t){let n=Y(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Y(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Je(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=qe(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function qe(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Z(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Z(e,t);if(n===-1)break;i=n+1}return i}function X(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
1593
|
-
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function Je(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Z(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=X(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Ye(e){let{name:t,outDir:n}=e,r=k(t),a=D(t),o=[],s=i(n,`${r}.adapter.ts`);return await b(s,`import {
|
|
1594
|
-
defineAdapter,
|
|
1595
|
-
type AdapterContext,
|
|
1596
|
-
type AdapterMiddleware,
|
|
1597
|
-
type ContributorRegistrations,
|
|
1598
|
-
type Constructor,
|
|
1599
|
-
} from '@forinda/kickjs'
|
|
1600
|
-
|
|
1601
|
-
/**
|
|
1602
|
-
* Configuration for the ${a} adapter.
|
|
1603
|
-
*
|
|
1604
|
-
* Adapters typically take a small config object so callers can tune
|
|
1605
|
-
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
1606
|
-
* derived from the environment should be read inside the build
|
|
1607
|
-
* function via getEnv(), not forced onto the caller.
|
|
1608
|
-
*/
|
|
1609
|
-
export interface ${a}AdapterConfig {
|
|
1610
|
-
// Add your adapter configuration here, e.g.:
|
|
1611
|
-
// enabled?: boolean
|
|
1612
|
-
// apiKey?: string
|
|
1613
|
-
}
|
|
1614
|
-
|
|
1615
|
-
/**
|
|
1616
|
-
* ${a} adapter — built via \`defineAdapter()\` so callers get the
|
|
1617
|
-
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
1618
|
-
*
|
|
1619
|
-
* Hooks into the Application lifecycle to add middleware, routes,
|
|
1620
|
-
* Context Contributors, or external service connections.
|
|
1621
|
-
*
|
|
1622
|
-
* Every lifecycle hook below is OPTIONAL. The scaffold emits all of
|
|
1623
|
-
* them so adopters can browse what's available and delete what they
|
|
1624
|
-
* don't need — \`build()\` returning \`{}\` is also valid for an adapter
|
|
1625
|
-
* that only contributes config defaults.
|
|
1626
|
-
*
|
|
1627
|
-
* @example
|
|
1628
|
-
* \`\`\`ts
|
|
1629
|
-
* import { bootstrap } from '@forinda/kickjs'
|
|
1630
|
-
* import { ${a}Adapter } from './adapters/${r}.adapter'
|
|
1631
|
-
*
|
|
1632
|
-
* bootstrap({
|
|
1633
|
-
* modules,
|
|
1634
|
-
* adapters: [${a}Adapter({ /* config overrides *\\/ })],
|
|
1635
|
-
* })
|
|
1636
|
-
* \`\`\`
|
|
1637
|
-
*/
|
|
1638
|
-
export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
|
|
1639
|
-
name: '${a}Adapter',
|
|
1640
|
-
defaults: {
|
|
1641
|
-
// Default config values go here. The adopter's overrides shallow-merge
|
|
1642
|
-
// on top of these before \`build()\` runs.
|
|
1643
|
-
},
|
|
1644
|
-
build: (_config, { name: _name }) => {
|
|
1645
|
-
// Closures inside \`build()\` are how each adapter instance owns its
|
|
1646
|
-
// own state (database client, Map, timer handle, …). The same
|
|
1647
|
-
// \`_config\` is visible to every hook below.
|
|
1648
|
-
|
|
1649
|
-
return {
|
|
1650
|
-
/**
|
|
1651
|
-
* Express middleware entries the Application mounts at named phases.
|
|
1652
|
-
*
|
|
1653
|
-
* \`phase\` controls where each handler sits in the pipeline:
|
|
1654
|
-
* 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
|
|
1655
|
-
*
|
|
1656
|
-
* \`path\` (optional) scopes the entry to a path prefix.
|
|
1657
|
-
*
|
|
1658
|
-
* Delete this hook entirely if you don't add middleware.
|
|
1659
|
-
*/
|
|
1660
|
-
middleware(): AdapterMiddleware[] {
|
|
1661
|
-
return [
|
|
1662
|
-
// Example: add a custom header to all responses
|
|
1663
|
-
// {
|
|
1664
|
-
// phase: 'beforeGlobal',
|
|
1665
|
-
// handler: (_req, res, next) => {
|
|
1666
|
-
// res.setHeader('X-${a}', 'true')
|
|
1667
|
-
// next()
|
|
1668
|
-
// },
|
|
1669
|
-
// },
|
|
1670
|
-
// Example: scope a rate limiter to one path prefix
|
|
1671
|
-
// {
|
|
1672
|
-
// phase: 'beforeRoutes',
|
|
1673
|
-
// path: '/api/v1/auth',
|
|
1674
|
-
// handler: rateLimit({ max: 10 }),
|
|
1675
|
-
// },
|
|
1676
|
-
]
|
|
1677
|
-
},
|
|
1678
|
-
|
|
1679
|
-
/**
|
|
1680
|
-
* Runs BEFORE global middleware. Mount routes that should bypass the
|
|
1681
|
-
* middleware stack — health checks, docs UI, static assets, OAuth
|
|
1682
|
-
* callbacks. Anything you want reachable even if a global middleware
|
|
1683
|
-
* later in the chain rejects requests.
|
|
1684
|
-
*
|
|
1685
|
-
* Delete this hook if you have no early routes.
|
|
1686
|
-
*/
|
|
1687
|
-
beforeMount(_ctx: AdapterContext): void {
|
|
1688
|
-
// Example:
|
|
1689
|
-
// _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
|
|
1690
|
-
},
|
|
1691
|
-
|
|
1692
|
-
/**
|
|
1693
|
-
* Fires once per controller class as the router mounts. Use this to
|
|
1694
|
-
* collect route metadata for OpenAPI specs, dependency graphs, route
|
|
1695
|
-
* inventories, devtools dashboards.
|
|
1696
|
-
*
|
|
1697
|
-
* Delete this hook unless your adapter introspects the route registry.
|
|
1698
|
-
*/
|
|
1699
|
-
onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
|
|
1700
|
-
// Example (Swagger-style): collect routes for the spec.
|
|
1701
|
-
// openApiSpec.addController(_controllerClass, _mountPath)
|
|
1702
|
-
},
|
|
1703
|
-
|
|
1704
|
-
/**
|
|
1705
|
-
* Runs AFTER modules + routes are wired, BEFORE the server starts.
|
|
1706
|
-
* Right place for late-stage DI registrations or final config validation.
|
|
1707
|
-
*
|
|
1708
|
-
* Delete this hook if there's nothing to wire post-modules.
|
|
1709
|
-
*/
|
|
1710
|
-
beforeStart(_ctx: AdapterContext): void {
|
|
1711
|
-
// Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
1712
|
-
},
|
|
1713
|
-
|
|
1714
|
-
/**
|
|
1715
|
-
* Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
|
|
1716
|
-
* available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
|
|
1717
|
-
* gRPC, GraphQL subscriptions), warm caches, log a banner.
|
|
1718
|
-
*
|
|
1719
|
-
* Delete this hook if you don't need the running server reference.
|
|
1720
|
-
*/
|
|
1721
|
-
afterStart(_ctx: AdapterContext): void {
|
|
1722
|
-
// Example: const io = new Server(_ctx.server)
|
|
1723
|
-
},
|
|
1724
|
-
|
|
1725
|
-
/**
|
|
1726
|
-
* Returns Context Contributors to merge into every route's pipeline
|
|
1727
|
-
* at the \`'adapter'\` precedence level. Per-route handlers can
|
|
1728
|
-
* override the value at the method / class / module level.
|
|
1729
|
-
*
|
|
1730
|
-
* Delete this hook unless your adapter ships typed per-request values
|
|
1731
|
-
* (auth user, tenant, locale, feature flags, geo, etc).
|
|
1732
|
-
*/
|
|
1733
|
-
contributors(): ContributorRegistrations {
|
|
1734
|
-
return [
|
|
1735
|
-
// Example:
|
|
1736
|
-
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
1737
|
-
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
|
|
1738
|
-
// const Load${a} = defineHttpContextDecorator({
|
|
1739
|
-
// key: '${r}',
|
|
1740
|
-
// resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
|
|
1741
|
-
// })
|
|
1742
|
-
// return [Load${a}.registration]
|
|
1743
|
-
]
|
|
1744
|
-
},
|
|
1745
|
-
|
|
1746
|
-
/**
|
|
1747
|
-
* Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
|
|
1748
|
-
* resources the adapter owns: close connections, flush buffers,
|
|
1749
|
-
* cancel timers. The framework runs every adapter's \`shutdown\`
|
|
1750
|
-
* concurrently via \`Promise.allSettled\` — one failure won't block
|
|
1751
|
-
* sibling adapters.
|
|
1752
|
-
*
|
|
1753
|
-
* Delete this hook if your adapter holds no resources.
|
|
1754
|
-
*/
|
|
1755
|
-
async shutdown(): Promise<void> {
|
|
1756
|
-
// Example: await this.pool.end()
|
|
1757
|
-
// Example: clearInterval(this.heartbeatTimer)
|
|
1758
|
-
},
|
|
1759
|
-
}
|
|
1760
|
-
},
|
|
1761
|
-
})
|
|
1762
|
-
`),o.push(s),o}const Xe={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},Ze={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},Qe={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function Q(e){let{type:t,outDir:n,moduleName:r,modulesDir:o=`src/modules`,defaultDir:s,pattern:c=`ddd`,shouldPluralize:l=!0}=e;if(n)return a(n);if(r){let e=c===`ddd`?Xe:c===`cqrs`?Qe:Ze,n=k(r),s=l?A(n):n,u=e[t]??``,d=i(o,s);return a(u?i(d,u):d)}return a(s)}async function $e(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=[],u=i(o,`${s}.middleware.ts`);return await b(u,`import type { Request, Response, NextFunction } from 'express'
|
|
1763
|
-
|
|
1764
|
-
export interface ${D(t)}Options {
|
|
1765
|
-
// Add configuration options here. The factory below closes over the
|
|
1766
|
-
// resolved options object; pass them at the call site —
|
|
1767
|
-
// \`${c}({ foo: 'bar' })\` — and the closure preserves them across
|
|
1768
|
-
// every request.
|
|
1769
|
-
}
|
|
1770
|
-
|
|
1771
|
-
/**
|
|
1772
|
-
* ${D(t)} middleware.
|
|
1773
|
-
*
|
|
1774
|
-
* Usage in bootstrap (fires on every request):
|
|
1775
|
-
* middleware: [${c}()]
|
|
1776
|
-
*
|
|
1777
|
-
* Usage with adapter — phase controls *when* the handler runs:
|
|
1778
|
-
*
|
|
1779
|
-
* middleware() {
|
|
1780
|
-
* return [{ handler: ${c}(), phase: 'afterGlobal' }]
|
|
1781
|
-
* }
|
|
1782
|
-
*
|
|
1783
|
-
* Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
|
|
1784
|
-
* - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
|
|
1785
|
-
* request, before module routes run.
|
|
1786
|
-
* - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
|
|
1787
|
-
* OR a route handler called \`next()\` without ending the response.
|
|
1788
|
-
* Controllers that call \`ctx.json(…)\` end the chain and skip this
|
|
1789
|
-
* phase. For per-response work (logging, metrics) attach to
|
|
1790
|
-
* \`res.on('finish', …)\` from an earlier-phase middleware instead.
|
|
1791
|
-
*
|
|
1792
|
-
* Optional path scope — string, RegExp, or array of either:
|
|
1793
|
-
* middleware() {
|
|
1794
|
-
* return [{
|
|
1795
|
-
* handler: ${c}({ region: 'eu' }),
|
|
1796
|
-
* phase: 'afterGlobal',
|
|
1797
|
-
* path: ['/api', /^\\/admin/],
|
|
1798
|
-
* }]
|
|
1799
|
-
* }
|
|
1800
|
-
*
|
|
1801
|
-
* Usage with @Middleware decorator:
|
|
1802
|
-
* @Middleware(${c}())
|
|
1803
|
-
*/
|
|
1804
|
-
export function ${c}(options: ${D(t)}Options = {}) {
|
|
1805
|
-
return (req: Request, res: Response, next: NextFunction) => {
|
|
1806
|
-
// Implement your middleware logic here. \`options\` is captured by
|
|
1807
|
-
// closure — log or read it anywhere in this handler body.
|
|
1808
|
-
void options
|
|
1809
|
-
next()
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
`),l.push(u),l}async function et(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=D(t),u=[],d=i(o,`${s}.guard.ts`);return await b(d,`import { Container, HttpException } from '@forinda/kickjs'
|
|
1813
|
-
import type { RequestContext } from '@forinda/kickjs'
|
|
1814
|
-
|
|
1815
|
-
/**
|
|
1816
|
-
* ${l} guard.
|
|
1817
|
-
*
|
|
1818
|
-
* Guards protect routes by checking conditions before the handler runs.
|
|
1819
|
-
* Return early with an error response to block access.
|
|
1820
|
-
*
|
|
1821
|
-
* Usage:
|
|
1822
|
-
* @Middleware(${c}Guard)
|
|
1823
|
-
* @Get('/protected')
|
|
1824
|
-
* async handler(ctx: RequestContext) { ... }
|
|
1825
|
-
*/
|
|
1826
|
-
export async function ${c}Guard(ctx: RequestContext, next: () => void): Promise<void> {
|
|
1827
|
-
// Example: check for an authorization header
|
|
1828
|
-
const header = ctx.headers.authorization
|
|
1829
|
-
if (!header?.startsWith('Bearer ')) {
|
|
1830
|
-
ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
|
|
1831
|
-
return
|
|
1832
|
-
}
|
|
1833
|
-
|
|
1834
|
-
const token = header.slice(7)
|
|
1835
|
-
|
|
1836
|
-
try {
|
|
1837
|
-
// Verify the token using a service from the DI container
|
|
1838
|
-
// const container = Container.getInstance()
|
|
1839
|
-
// const authService = container.resolve(AuthService)
|
|
1840
|
-
// const payload = authService.verifyToken(token)
|
|
1841
|
-
// ctx.set('auth', payload)
|
|
1842
|
-
|
|
1843
|
-
next()
|
|
1844
|
-
} catch {
|
|
1845
|
-
ctx.res.status(401).json({ message: 'Invalid or expired token' })
|
|
1846
|
-
}
|
|
1847
|
-
}
|
|
1848
|
-
`),u.push(d),u}async function tt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=i(o,`${s}.service.ts`);return await b(u,`import { Service } from '@forinda/kickjs'
|
|
1849
|
-
|
|
1850
|
-
@Service()
|
|
1851
|
-
export class ${c}Service {
|
|
1852
|
-
// Inject dependencies via constructor
|
|
1853
|
-
// constructor(
|
|
1854
|
-
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1855
|
-
// ) {}
|
|
1856
|
-
}
|
|
1857
|
-
`),l.push(u),l}async function nt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=[],u=i(o,`${s}.controller.ts`);return await b(u,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
|
|
1858
|
-
|
|
1859
|
-
// \`Ctx<KickRoutes.${c}Controller['<method>']>\` is generated by
|
|
1860
|
-
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
1861
|
-
// will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
|
|
1862
|
-
// See https://forinda.github.io/kick-js/guide/typegen for details.
|
|
1863
|
-
|
|
1864
|
-
@Controller()
|
|
1865
|
-
export class ${c}Controller {
|
|
1866
|
-
// @Autowired() private readonly myService!: MyService
|
|
1867
|
-
|
|
1868
|
-
@Get('/')
|
|
1869
|
-
async list(ctx: Ctx<KickRoutes.${c}Controller['list']>) {
|
|
1870
|
-
ctx.json({ message: '${c} list' })
|
|
1871
|
-
}
|
|
1872
|
-
|
|
1873
|
-
@Post('/')
|
|
1874
|
-
async create(ctx: Ctx<KickRoutes.${c}Controller['create']>) {
|
|
1875
|
-
ctx.created({ message: '${c} created', data: ctx.body })
|
|
1876
|
-
}
|
|
1877
|
-
}
|
|
1878
|
-
`),l.push(u),l}async function rt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=Q({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=D(t),l=O(t),u=[],d=i(o,`${s}.dto.ts`);return await b(d,`import { z } from 'zod'
|
|
1879
|
-
|
|
1880
|
-
export const ${l}Schema = z.object({
|
|
1881
|
-
// Define your schema fields here
|
|
1882
|
-
name: z.string().min(1).max(200),
|
|
1883
|
-
})
|
|
1884
|
-
|
|
1885
|
-
export type ${c}DTO = z.infer<typeof ${l}Schema>
|
|
1886
|
-
`),u.push(d),u}const it={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function $(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function at(e,t,n,r=[]){let i={"@forinda/kickjs":$(n,`@forinda/kickjs`),dotenv:`^17.3.1`,express:`^5.1.0`,"reflect-metadata":`^0.2.2`,zod:`^4.3.6`,pino:`^10.3.1`,"pino-pretty":`^13.1.3`};for(let e of r){let t=it[e];t&&!i[t]&&(i[t]=$(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:i,devDependencies:{"@forinda/kickjs-cli":$(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":$(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,"@types/express":`^5.0.6`,"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function ot(){return`import { defineConfig } from 'vite'
|
|
1887
|
-
import { resolve } from 'node:path'
|
|
1888
|
-
import swc from 'unplugin-swc'
|
|
1889
|
-
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
|
|
1890
|
-
|
|
1891
|
-
export default defineConfig({
|
|
1892
|
-
oxc: false,
|
|
1893
|
-
plugins: [
|
|
1894
|
-
swc.vite(),
|
|
1895
|
-
kickjsVitePlugin({ entry: 'src/index.ts' }),
|
|
1896
|
-
// Watches .env files and triggers a full reload on change so the
|
|
1897
|
-
// dev server picks up env tweaks without a manual restart.
|
|
1898
|
-
envWatchPlugin(),
|
|
1899
|
-
],
|
|
1900
|
-
resolve: {
|
|
1901
|
-
alias: {
|
|
1902
|
-
'@': resolve(__dirname, 'src'),
|
|
1903
|
-
},
|
|
1904
|
-
},
|
|
1905
|
-
ssr: {
|
|
1906
|
-
// Don't bundle pino — its worker-thread transport needs Node.js resolution
|
|
1907
|
-
// to find pino-pretty at runtime for colored log output
|
|
1908
|
-
external: ['pino', 'pino-pretty'],
|
|
1909
|
-
},
|
|
1910
|
-
build: {
|
|
1911
|
-
target: 'node20',
|
|
1912
|
-
ssr: true,
|
|
1913
|
-
outDir: 'dist',
|
|
1914
|
-
sourcemap: true,
|
|
1915
|
-
rollupOptions: {
|
|
1916
|
-
input: resolve(__dirname, 'src/index.ts'),
|
|
1917
|
-
output: { format: 'esm' },
|
|
1918
|
-
},
|
|
1919
|
-
},
|
|
1920
|
-
})
|
|
1921
|
-
`}function st(){return JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,lib:[`ES2022`],types:[`node`,`vite/client`],strict:!0,esModuleInterop:!0,skipLibCheck:!0,sourceMap:!0,declaration:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,outDir:`dist`,paths:{"@/*":[`./src/*`]}},include:[`src`,`.kickjs/types/**/*.d.ts`,`.kickjs/types/**/*.ts`]},null,2)}function ct(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function lt(){return`# https://editorconfig.org
|
|
1922
|
-
root = true
|
|
1923
|
-
|
|
1924
|
-
[*]
|
|
1925
|
-
indent_style = space
|
|
1926
|
-
indent_size = 2
|
|
1927
|
-
end_of_line = lf
|
|
1928
|
-
charset = utf-8
|
|
1929
|
-
trim_trailing_whitespace = true
|
|
1930
|
-
insert_final_newline = true
|
|
1931
|
-
|
|
1932
|
-
[*.md]
|
|
1933
|
-
trim_trailing_whitespace = false
|
|
1934
|
-
`}function ut(){return`node_modules/
|
|
1935
|
-
dist/
|
|
1936
|
-
.env
|
|
1937
|
-
coverage/
|
|
1938
|
-
.DS_Store
|
|
1939
|
-
*.tsbuildinfo
|
|
1940
|
-
.kickjs/
|
|
1941
|
-
`}function dt(){return`# Auto-detect text files and normalise line endings to LF
|
|
1942
|
-
* text=auto eol=lf
|
|
1943
|
-
|
|
1944
|
-
# Explicitly mark generated / binary files
|
|
1945
|
-
*.png binary
|
|
1946
|
-
*.jpg binary
|
|
1947
|
-
*.jpeg binary
|
|
1948
|
-
*.gif binary
|
|
1949
|
-
*.ico binary
|
|
1950
|
-
*.woff binary
|
|
1951
|
-
*.woff2 binary
|
|
1952
|
-
*.ttf binary
|
|
1953
|
-
*.eot binary
|
|
1954
|
-
|
|
1955
|
-
# Lock files — treat as generated
|
|
1956
|
-
pnpm-lock.yaml -diff linguist-generated
|
|
1957
|
-
yarn.lock -diff linguist-generated
|
|
1958
|
-
package-lock.json -diff linguist-generated
|
|
1959
|
-
`}function ft(){return`PORT=3000
|
|
1960
|
-
NODE_ENV=development
|
|
1961
|
-
`}function pt(){return`PORT=3000
|
|
1962
|
-
NODE_ENV=development
|
|
1963
|
-
`}function mt(){return`import { defineConfig } from 'vitest/config'
|
|
1964
|
-
import swc from 'unplugin-swc'
|
|
1965
|
-
|
|
1966
|
-
export default defineConfig({
|
|
1967
|
-
plugins: [swc.vite()],
|
|
1968
|
-
test: {
|
|
1969
|
-
globals: true,
|
|
1970
|
-
environment: 'node',
|
|
1971
|
-
include: ['src/**/*.test.ts'],
|
|
1972
|
-
},
|
|
1973
|
-
})
|
|
1974
|
-
`}function ht(e,t,n){let r={rest:`REST API`,ddd:`Domain-Driven Design`,cqrs:`CQRS + Event-Driven`,minimal:`Minimal`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),t===`cqrs`&&i.push(`@forinda/kickjs-queue`,`@forinda/kickjs-ws`),`# ${e}
|
|
1975
|
-
|
|
1976
|
-
A **${r[t]??`REST API`}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
|
|
1977
|
-
|
|
1978
|
-
## Getting Started
|
|
1979
|
-
|
|
1980
|
-
\`\`\`bash
|
|
1981
|
-
${n} install
|
|
1982
|
-
kick dev
|
|
1983
|
-
\`\`\`
|
|
1984
|
-
|
|
1985
|
-
## Scripts
|
|
1986
|
-
|
|
1987
|
-
| Command | Description |
|
|
1988
|
-
|---|---|
|
|
1989
|
-
| \`kick dev\` | Start dev server with Vite HMR |
|
|
1990
|
-
| \`kick build\` | Production build |
|
|
1991
|
-
| \`kick start\` | Run production build |
|
|
1992
|
-
| \`${n} run test\` | Run tests with Vitest |
|
|
1993
|
-
| \`kick g module <name>\` | Generate a DDD module |
|
|
1994
|
-
| \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
|
|
1995
|
-
| \`kick add <package>\` | Add a KickJS package |
|
|
1996
|
-
|
|
1997
|
-
## Project Structure
|
|
1998
|
-
|
|
1999
|
-
\`\`\`
|
|
2000
|
-
src/
|
|
2001
|
-
├── index.ts # Application entry point
|
|
2002
|
-
├── modules/ # Feature modules (controllers, services, repos)
|
|
2003
|
-
│ └── index.ts # Module registry
|
|
2004
|
-
└── ...
|
|
2005
|
-
\`\`\`
|
|
2006
|
-
|
|
2007
|
-
## Packages
|
|
2008
|
-
|
|
2009
|
-
${i.map(e=>`- \`${e}\``).join(`
|
|
2010
|
-
`)}
|
|
2011
|
-
|
|
2012
|
-
## Adding Features
|
|
2013
|
-
|
|
2014
|
-
\`\`\`bash
|
|
2015
|
-
kick add auth # Authentication (JWT, API key, OAuth)
|
|
2016
|
-
kick add swagger # OpenAPI documentation
|
|
2017
|
-
kick add ws # WebSocket support
|
|
2018
|
-
kick add queue # Background job processing
|
|
2019
|
-
kick add --list # Show all available packages
|
|
2020
|
-
\`\`\`
|
|
2021
|
-
|
|
2022
|
-
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.
|
|
2023
|
-
|
|
2024
|
-
## Environment Variables
|
|
2025
|
-
|
|
2026
|
-
Copy \`.env.example\` to \`.env\` and configure:
|
|
2027
|
-
|
|
2028
|
-
| Variable | Default | Description |
|
|
2029
|
-
|---|---|---|
|
|
2030
|
-
| \`PORT\` | \`3000\` | Server port |
|
|
2031
|
-
| \`NODE_ENV\` | \`development\` | Environment |
|
|
2032
|
-
|
|
2033
|
-
## Learn More
|
|
2034
|
-
|
|
2035
|
-
- [KickJS Documentation](https://forinda.github.io/kick-js/)
|
|
2036
|
-
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
2037
|
-
`}function gt(e,t,n){return`# CLAUDE.md — ${e}
|
|
2038
|
-
|
|
2039
|
-
**Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
|
|
2040
|
-
reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
|
|
2041
|
-
project conventions, structure, decorator patterns, env wiring, CLI
|
|
2042
|
-
generators, every gotcha.
|
|
2043
|
-
|
|
2044
|
-
**Then browse \`./.agents/skills/\`.** Each subdirectory is a single
|
|
2045
|
-
task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
|
|
2046
|
-
\`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
|
|
2047
|
-
with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
|
|
2048
|
-
The structure follows the Claude Code skills convention — agents that
|
|
2049
|
-
auto-load skills from \`.agents/skills/\` will pick each up by its
|
|
2050
|
-
frontmatter. Use this directory as the playbook when executing common
|
|
2051
|
-
KickJS workflows.
|
|
2052
|
-
|
|
2053
|
-
This file is a thin Claude-specific layer on top of those two; when
|
|
2054
|
-
they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
|
|
2055
|
-
authoritative and flag the discrepancy.
|
|
2056
|
-
|
|
2057
|
-
## Why \`.agents/\` + this thin pointer
|
|
2058
|
-
|
|
2059
|
-
\`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
|
|
2060
|
-
Copilot, Aider, …) — one canonical source so the prose doesn't drift
|
|
2061
|
-
across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
|
|
2062
|
-
project context on each conversation, so it stays at the project root.
|
|
2063
|
-
Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
|
|
2064
|
-
out-of-sync copies of the same content. Per-agent files
|
|
2065
|
-
(\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
|
|
2066
|
-
\`AGENTS.md\` for tool-specific notes that don't belong in the shared
|
|
2067
|
-
prose.
|
|
2068
|
-
|
|
2069
|
-
## Claude-specific notes
|
|
2070
|
-
|
|
2071
|
-
- **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
|
|
2072
|
-
to refresh project memory if AGENTS.md changes substantially.
|
|
2073
|
-
- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
|
|
2074
|
-
- **Persistent memory** — Claude maintains user/feedback/project/
|
|
2075
|
-
reference memories under \`.claude/memory/\`. If you ask for
|
|
2076
|
-
something that contradicts a remembered preference, Claude flags
|
|
2077
|
-
it before acting; corrections update memory automatically.
|
|
2078
|
-
- **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
|
|
2079
|
-
or background work. Useful for "wait for the deploy then open a
|
|
2080
|
-
cleanup PR" or "every Monday triage the issue board" patterns.
|
|
2081
|
-
|
|
2082
|
-
## Quick reference (full version in .agents/AGENTS.md)
|
|
2083
|
-
|
|
2084
|
-
\`\`\`bash
|
|
2085
|
-
${n} install # Install dependencies
|
|
2086
|
-
kick dev # Dev server with HMR + typegen
|
|
2087
|
-
kick build && kick start # Production
|
|
2088
|
-
${n} run test # Vitest
|
|
2089
|
-
${n} run typecheck # tsc --noEmit
|
|
2090
|
-
${n} run format # Prettier
|
|
2091
|
-
\`\`\`
|
|
2092
|
-
|
|
2093
|
-
## v4 framework reminders
|
|
2094
|
-
|
|
2095
|
-
When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
|
|
2096
|
-
|
|
2097
|
-
- **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
|
|
2098
|
-
- **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
|
|
2099
|
-
- **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.
|
|
2100
|
-
- **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
|
|
2101
|
-
- **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.
|
|
2102
|
-
- **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).
|
|
2103
|
-
- **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.
|
|
2104
|
-
- **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
|
|
2105
|
-
- **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
|
|
2106
|
-
- **Bootstrap export**: \`src/index.ts\` must end with \`export const app = await bootstrap({ ... })\`. The Vite plugin and \`createTestApp\` import the named \`app\`; without the export, HMR silently degrades to full restarts.
|
|
2107
|
-
- **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
|
|
2108
|
-
- **Refresh these files**: \`kick g agents -f\` regenerates \`CLAUDE.md\` at the project root and \`.agents/AGENTS.md\` + \`.agents/GEMINI.md\` + \`.agents/COPILOT.md\` + every \`.agents/skills/<name>/SKILL.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`.agents/AGENTS.local.md\` or per-skill \`SKILL.local.md\` files alongside.
|
|
2109
|
-
|
|
2110
|
-
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
|
|
2111
|
-
`}function _t(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
|
|
2112
|
-
|
|
2113
|
-
This guide is the **canonical, multi-agent reference** for this KickJS
|
|
2114
|
-
application — Claude, Copilot, Codex, Gemini, etc. all read it first.
|
|
2115
|
-
Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
|
|
2116
|
-
add tool-specific affordances on top.
|
|
2117
|
-
|
|
2118
|
-
## Before You Start
|
|
2119
|
-
|
|
2120
|
-
1. Run \`${n} install\` to install dependencies
|
|
2121
|
-
2. Run \`kick dev\` to verify the app starts
|
|
2122
|
-
3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
|
|
2123
|
-
|
|
2124
|
-
## v4 Conventions (don't skip)
|
|
2125
|
-
|
|
2126
|
-
KickJS v4 made a handful of structural changes from v3. Internalise these
|
|
2127
|
-
before generating or modifying code — they are the source of most agent
|
|
2128
|
-
mistakes:
|
|
2129
|
-
|
|
2130
|
-
- **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
|
|
2131
|
-
|
|
2132
|
-
\`\`\`ts
|
|
2133
|
-
export const MyAdapter = defineAdapter<MyOptions>({
|
|
2134
|
-
name: 'MyAdapter',
|
|
2135
|
-
defaults: { ... },
|
|
2136
|
-
build: (config) => ({
|
|
2137
|
-
beforeMount({ app }) { /* ... */ },
|
|
2138
|
-
afterStart({ server }) { /* ... */ },
|
|
2139
|
-
}),
|
|
2140
|
-
})
|
|
2141
|
-
\`\`\`
|
|
2142
|
-
|
|
2143
|
-
- **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
|
|
2144
|
-
|
|
2145
|
-
- **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
|
|
2146
|
-
the key segment is **PascalCase** (the regex enforces both):
|
|
2147
|
-
|
|
2148
|
-
\`\`\`ts
|
|
2149
|
-
const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
|
|
2150
|
-
const DB = createToken<Database>('app/Db/connection')
|
|
2151
|
-
\`\`\`
|
|
2152
|
-
|
|
2153
|
-
The \`kick/\` prefix is reserved for first-party packages; this project
|
|
2154
|
-
owns its own scope (\`app/\`, your domain name, etc.).
|
|
2155
|
-
|
|
2156
|
-
- **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
|
|
2157
|
-
the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
|
|
2158
|
-
is a v3 leftover; the linter and codegen reject it.
|
|
2159
|
-
|
|
2160
|
-
- **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
|
|
2161
|
-
side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
|
|
2162
|
-
import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
|
|
2163
|
-
returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
|
|
2164
|
-
(Zod coercion + defaults silently skipped).
|
|
2165
|
-
|
|
2166
|
-
- **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
|
|
2167
|
-
HMR contract at the top of "Module Pattern" below. The CLI enforces this;
|
|
2168
|
-
hand-rolled files must too.
|
|
2169
|
-
|
|
2170
|
-
- **Assets** — drop new template files into \`src/templates/<namespace>/\`
|
|
2171
|
-
(or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
|
|
2172
|
-
\`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
|
|
2173
|
-
no manual build step.
|
|
2174
|
-
|
|
2175
|
-
- **Context over \`@Middleware()\`** — when a middleware's only job is to
|
|
2176
|
-
populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
|
|
2177
|
-
(HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
|
|
2178
|
-
Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
|
|
2179
|
-
Reserve \`@Middleware()\` for response short-circuit / stream mutation /
|
|
2180
|
-
pre-route-matching work.
|
|
2181
|
-
|
|
2182
|
-
Two ground rules around the data flow — both stem from the fact that
|
|
2183
|
-
every per-request stage gets its OWN \`RequestContext\` instance, all
|
|
2184
|
-
reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
|
|
2185
|
-
- **\`resolve\` and \`onError\` must RETURN the value.** The runner
|
|
2186
|
-
writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
|
|
2187
|
-
property assignment (\`ctx.tenant = …\`) sticks to the contributor
|
|
2188
|
-
instance only — the handler instance never sees it.
|
|
2189
|
-
- **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
|
|
2190
|
-
\`getRequestValue(key)\` from a service that has no \`ctx\` reference
|
|
2191
|
-
— typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
|
|
2192
|
-
Express request is shared; bespoke property assignments don't.
|
|
2193
|
-
|
|
2194
|
-
- **Test isolation** — default to \`Container.create()\` for fresh DI state.
|
|
2195
|
-
Never \`new Container()\` and never \`getInstance().reset()\` — both leak
|
|
2196
|
-
registrations between tests.
|
|
2197
|
-
|
|
2198
|
-
\`\`\`ts
|
|
2199
|
-
const container = Container.create()
|
|
2200
|
-
// ... register test-scoped providers, run, discard
|
|
2201
|
-
\`\`\`
|
|
2202
|
-
|
|
2203
|
-
- **Bootstrap export** — \`src/index.ts\` MUST end with
|
|
2204
|
-
\`export const app = await bootstrap({ ... })\`. The Vite plugin imports
|
|
2205
|
-
the named \`app\` symbol to drive HMR module swaps; testing helpers
|
|
2206
|
-
(\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
|
|
2207
|
-
the \`export\` and \`kick dev\` will silently fall back to a full restart
|
|
2208
|
-
on every save while \`createTestApp\` complains about a missing handle.
|
|
2209
|
-
|
|
2210
|
-
- **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
|
|
2211
|
-
adapters in dedicated folders and re-export aggregated arrays. Do **not**
|
|
2212
|
-
inline registration in the entry file:
|
|
2213
|
-
|
|
2214
|
-
\`\`\`ts
|
|
2215
|
-
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
2216
|
-
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
2217
|
-
// OR with \`modules.style: 'class'\`:
|
|
2218
|
-
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
2219
|
-
|
|
2220
|
-
// src/middleware/index.ts
|
|
2221
|
-
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
2222
|
-
|
|
2223
|
-
// src/plugins/index.ts
|
|
2224
|
-
export const plugins = [MetricsPlugin(), AuditPlugin()]
|
|
2225
|
-
|
|
2226
|
-
// src/adapters/index.ts
|
|
2227
|
-
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
2228
|
-
\`\`\`
|
|
2229
|
-
|
|
2230
|
-
\`\`\`ts
|
|
2231
|
-
// src/index.ts — stays small; one import per category
|
|
2232
|
-
import 'reflect-metadata'
|
|
2233
|
-
import './config'
|
|
2234
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
2235
|
-
import { modules } from './modules'
|
|
2236
|
-
import { middleware } from './middleware'
|
|
2237
|
-
import { plugins } from './plugins'
|
|
2238
|
-
import { adapters } from './adapters'
|
|
2239
|
-
|
|
2240
|
-
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
2241
|
-
\`\`\`
|
|
2242
|
-
|
|
2243
|
-
This keeps the entry file diff-friendly, scales to dozens of modules
|
|
2244
|
-
without git churn, and lets each domain own its own registration list.
|
|
2245
|
-
The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
|
|
2246
|
-
\`kick g adapter\`) follow this layout — manual additions should too.
|
|
2247
|
-
|
|
2248
|
-
Everything else (controllers, services, modules, RequestContext API, generators,
|
|
2249
|
-
package additions, env access patterns, troubleshooting) is detailed below.
|
|
2250
|
-
|
|
2251
|
-
## Where to Find Things
|
|
2252
|
-
|
|
2253
|
-
### Application Structure
|
|
2254
|
-
|
|
2255
|
-
| What | Where |
|
|
2256
|
-
|------|-------|
|
|
2257
|
-
| Entry point | \`src/index.ts\` |
|
|
2258
|
-
| Module registry | \`src/modules/index.ts\` |
|
|
2259
|
-
| Feature modules | \`src/modules/<module-name>/\` |
|
|
2260
|
-
| **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
|
|
2261
|
-
| Env values | \`.env\` |
|
|
2262
|
-
| Env schema (Zod) | \`src/config/index.ts\` |
|
|
2263
|
-
| TypeScript config | \`tsconfig.json\` |
|
|
2264
|
-
| Vite config (HMR) | \`vite.config.ts\` |
|
|
2265
|
-
| Vitest config | \`vitest.config.ts\` |
|
|
2266
|
-
| Prettier config | \`.prettierrc\` |
|
|
2267
|
-
| CLI config | \`kick.config.ts\` |
|
|
2268
|
-
|
|
2269
|
-
### Module Pattern (${t.toUpperCase()})
|
|
2270
|
-
|
|
2271
|
-
> **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.
|
|
2272
|
-
|
|
2273
|
-
Each module in \`src/modules/<name>/\` typically contains:
|
|
2274
|
-
|
|
2275
|
-
${t===`ddd`?`\`\`\`
|
|
2276
|
-
<name>/
|
|
2277
|
-
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
2278
|
-
├── <name>.service.ts # Business logic (@Service)
|
|
2279
|
-
├── <name>.repository.ts # Data access (@Repository)
|
|
2280
|
-
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
2281
|
-
├── <name>.entity.ts # Domain entity (optional)
|
|
2282
|
-
└── <name>.module.ts # Module definition (defineModule factory)
|
|
2283
|
-
\`\`\`
|
|
2284
|
-
`:t===`cqrs`?`\`\`\`
|
|
2285
|
-
<name>/
|
|
2286
|
-
├── commands/ # Write operations
|
|
2287
|
-
│ ├── create-<name>.command.ts
|
|
2288
|
-
│ └── create-<name>.handler.ts
|
|
2289
|
-
├── queries/ # Read operations
|
|
2290
|
-
│ ├── get-<name>.query.ts
|
|
2291
|
-
│ └── get-<name>.handler.ts
|
|
2292
|
-
├── events/ # Domain events
|
|
2293
|
-
│ └── <name>-created.event.ts
|
|
2294
|
-
├── <name>.controller.ts # HTTP routes
|
|
2295
|
-
├── <name>.repository.ts # Data access
|
|
2296
|
-
└── <name>.module.ts # Module definition (defineModule factory)
|
|
2297
|
-
\`\`\`
|
|
2298
|
-
`:t===`rest`?`\`\`\`
|
|
2299
|
-
<name>/
|
|
2300
|
-
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
2301
|
-
├── <name>.service.ts # Business logic (@Service)
|
|
2302
|
-
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
2303
|
-
└── <name>.module.ts # Module definition (defineModule factory)
|
|
2304
|
-
\`\`\`
|
|
2305
|
-
`:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
|
|
2306
|
-
|
|
2307
|
-
## Checklist: Adding a Feature
|
|
2308
|
-
|
|
2309
|
-
### New Module (Recommended)
|
|
2310
|
-
|
|
2311
|
-
Use the CLI generator for consistency:
|
|
2312
|
-
|
|
2313
|
-
\`\`\`bash
|
|
2314
|
-
kick g module <name> # Generate full module
|
|
2315
|
-
# or
|
|
2316
|
-
kick g scaffold <name> <fields> # Generate CRUD from fields
|
|
2317
|
-
\`\`\`
|
|
2318
|
-
|
|
2319
|
-
Then:
|
|
2320
|
-
- [ ] Review generated files in \`src/modules/<name>/\`
|
|
2321
|
-
- [ ] Verify module is registered in \`src/modules/index.ts\`
|
|
2322
|
-
- [ ] Update DTOs in \`<name>.dto.ts\` if needed
|
|
2323
|
-
- [ ] Implement business logic in \`<name>.service.ts\`
|
|
2324
|
-
- [ ] Run \`kick dev\` to test with HMR
|
|
2325
|
-
- [ ] Write tests in \`<name>.test.ts\`
|
|
2326
|
-
|
|
2327
|
-
### Manual Controller
|
|
2328
|
-
|
|
2329
|
-
If not using generators:
|
|
2330
|
-
|
|
2331
|
-
- [ ] Create \`src/modules/<name>/<name>.controller.ts\`
|
|
2332
|
-
- [ ] Add \`@Controller()\` decorator
|
|
2333
|
-
- [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
|
|
2334
|
-
- [ ] Create module file with \`defineModule({ name, build: () => ({ routes() { return { path, controller } } }) })\` — the framework derives the Express router from the controller. Class-form (\`class XModule implements AppModule\`) is the legacy alternative; toggle via \`kick.config.ts > modules.style\`.
|
|
2335
|
-
- [ ] Register module in \`src/modules/index.ts\`. Default form is the fluent chain: \`defineModules().mount(MyModule()).mount(...)\`. \`kick g module <name>\` appends \`.mount(NewModule())\` automatically.
|
|
2336
|
-
- [ ] Test with \`kick dev\`
|
|
2337
|
-
|
|
2338
|
-
### Manual Service
|
|
2339
|
-
|
|
2340
|
-
- [ ] Create \`src/modules/<name>/<name>.service.ts\`
|
|
2341
|
-
- [ ] Add \`@Service()\` decorator
|
|
2342
|
-
- [ ] Inject dependencies with \`@Autowired()\`
|
|
2343
|
-
- [ ] Inject via \`@Autowired()\` where needed
|
|
2344
|
-
- [ ] Write unit tests
|
|
2345
|
-
|
|
2346
|
-
### New Middleware
|
|
2347
|
-
|
|
2348
|
-
- [ ] Create \`src/middleware/<name>.middleware.ts\`
|
|
2349
|
-
- [ ] Export middleware function (Express format)
|
|
2350
|
-
- [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
|
|
2351
|
-
- [ ] Test with sample requests
|
|
2352
|
-
|
|
2353
|
-
### Adding a Package
|
|
2354
|
-
|
|
2355
|
-
Use \`kick add\` to install KickJS packages with correct peer dependencies:
|
|
2356
|
-
|
|
2357
|
-
- [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
|
|
2358
|
-
- [ ] Follow package-specific setup in terminal output
|
|
2359
|
-
- [ ] Update \`src/index.ts\` to register adapter (if needed)
|
|
2360
|
-
- [ ] Configure environment variables in \`.env\`
|
|
2361
|
-
- [ ] Test integration with \`kick dev\`
|
|
2362
|
-
|
|
2363
|
-
## Common Tasks
|
|
2364
|
-
|
|
2365
|
-
### Generate CRUD Module
|
|
2366
|
-
|
|
2367
|
-
\`\`\`bash
|
|
2368
|
-
kick g scaffold user name:string email:string:optional age:number
|
|
2369
|
-
\`\`\`
|
|
2370
|
-
|
|
2371
|
-
Append \`:optional\` for optional fields (shell-safe, no quoting needed).
|
|
2372
|
-
Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
|
|
2373
|
-
|
|
2374
|
-
This creates a full CRUD module with:
|
|
2375
|
-
- Controller with GET, POST, PUT, DELETE routes
|
|
2376
|
-
- Service with business logic
|
|
2377
|
-
- Repository with data access
|
|
2378
|
-
- DTOs with Zod validation
|
|
2379
|
-
|
|
2380
|
-
### Add Authentication
|
|
2381
|
-
|
|
2382
|
-
\`\`\`bash
|
|
2383
|
-
kick add auth
|
|
2384
|
-
\`\`\`
|
|
2385
|
-
|
|
2386
|
-
Then configure in \`src/index.ts\`:
|
|
2387
|
-
|
|
2388
|
-
\`\`\`ts
|
|
2389
|
-
import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
|
|
2390
|
-
|
|
2391
|
-
bootstrap({
|
|
2392
|
-
modules,
|
|
2393
|
-
adapters: [
|
|
2394
|
-
AuthAdapter({
|
|
2395
|
-
strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
|
|
2396
|
-
}),
|
|
2397
|
-
],
|
|
2398
|
-
})
|
|
2399
|
-
\`\`\`
|
|
2400
|
-
|
|
2401
|
-
### Add Database (Prisma)
|
|
2402
|
-
|
|
2403
|
-
\`\`\`bash
|
|
2404
|
-
kick add prisma
|
|
2405
|
-
${n} install prisma @prisma/client
|
|
2406
|
-
npx prisma init
|
|
2407
|
-
# Edit prisma/schema.prisma
|
|
2408
|
-
npx prisma migrate dev --name init
|
|
2409
|
-
kick g module user --repo prisma
|
|
2410
|
-
\`\`\`
|
|
2411
|
-
|
|
2412
|
-
### Add WebSocket Support
|
|
2413
|
-
|
|
2414
|
-
\`\`\`bash
|
|
2415
|
-
kick add ws
|
|
2416
|
-
\`\`\`
|
|
2417
|
-
|
|
2418
|
-
Then add adapter in \`src/index.ts\`:
|
|
2419
|
-
|
|
2420
|
-
\`\`\`ts
|
|
2421
|
-
import { WsAdapter } from '@forinda/kickjs-ws'
|
|
2422
|
-
|
|
2423
|
-
bootstrap({
|
|
2424
|
-
modules,
|
|
2425
|
-
adapters: [WsAdapter()],
|
|
2426
|
-
})
|
|
2427
|
-
\`\`\`
|
|
2428
|
-
|
|
2429
|
-
Create WebSocket controller:
|
|
2430
|
-
|
|
2431
|
-
\`\`\`bash
|
|
2432
|
-
kick g controller chat --ws
|
|
2433
|
-
\`\`\`
|
|
2434
|
-
|
|
2435
|
-
## Testing Guidelines
|
|
2436
|
-
|
|
2437
|
-
All tests use Vitest:
|
|
2438
|
-
|
|
2439
|
-
\`\`\`ts
|
|
2440
|
-
import { describe, it, expect, beforeEach } from 'vitest'
|
|
2441
|
-
import { Container } from '@forinda/kickjs'
|
|
2442
|
-
import { createTestApp } from '@forinda/kickjs-testing'
|
|
2443
|
-
|
|
2444
|
-
describe('UserController', () => {
|
|
2445
|
-
it('should return users', async () => {
|
|
2446
|
-
// Container.create() — isolated DI state per test, never new Container()
|
|
2447
|
-
// and never getInstance().reset() (both leak registrations between tests).
|
|
2448
|
-
const container = Container.create()
|
|
2449
|
-
const app = await createTestApp([UserModule], { container })
|
|
2450
|
-
const res = await app.get('/users')
|
|
2451
|
-
|
|
2452
|
-
expect(res.status).toBe(200)
|
|
2453
|
-
expect(res.body).toHaveProperty('users')
|
|
2454
|
-
})
|
|
2455
|
-
})
|
|
2456
|
-
\`\`\`
|
|
2457
|
-
|
|
2458
|
-
Run tests:
|
|
2459
|
-
- \`${n} run test\` — run all tests once
|
|
2460
|
-
- \`${n} run test:watch\` — watch mode
|
|
2461
|
-
- Individual file: \`${n} run test src/modules/user/user.test.ts\`
|
|
2462
|
-
|
|
2463
|
-
## Environment Variables
|
|
2464
|
-
|
|
2465
|
-
Schema is declared in \`src/config/index.ts\` (extends the base
|
|
2466
|
-
\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
|
|
2467
|
-
with kickjs at module load. \`src/index.ts\` imports it via
|
|
2468
|
-
\`import './config'\` **before** \`bootstrap()\` so the cache is populated
|
|
2469
|
-
in time for DI. Add new keys to the schema, drop their values into
|
|
2470
|
-
\`.env\`, and they're typed everywhere.
|
|
2471
|
-
|
|
2472
|
-
Access patterns:
|
|
2473
|
-
|
|
2474
|
-
1. **@Value() decorator** (recommended for known-at-construction keys):
|
|
2475
|
-
\`\`\`ts
|
|
2476
|
-
@Value('DATABASE_URL')
|
|
2477
|
-
private dbUrl!: string
|
|
2478
|
-
\`\`\`
|
|
2479
|
-
|
|
2480
|
-
2. **ConfigService** (recommended for dynamic / method-scoped access):
|
|
2481
|
-
\`\`\`ts
|
|
2482
|
-
@Autowired()
|
|
2483
|
-
private config!: ConfigService
|
|
2484
|
-
|
|
2485
|
-
const port = this.config.get('PORT') // typed: number
|
|
2486
|
-
\`\`\`
|
|
2487
|
-
|
|
2488
|
-
3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
|
|
2489
|
-
\`\`\`ts
|
|
2490
|
-
import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
|
|
2491
|
-
|
|
2492
|
-
const env = loadEnv(schema) // Parse + validate all vars
|
|
2493
|
-
const port = getEnv('PORT') // Single value lookup
|
|
2494
|
-
reloadEnv() // Re-read .env from disk
|
|
2495
|
-
resetEnvCache() // Full reset (for tests)
|
|
2496
|
-
\`\`\`
|
|
2497
|
-
|
|
2498
|
-
4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
|
|
2499
|
-
coercion and the typed \`KickEnv\` registry.
|
|
2500
|
-
|
|
2501
|
-
> **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
|
|
2502
|
-
> If the schema is not registered before DI runs, \`config.get()\`
|
|
2503
|
-
> returns \`undefined\` for user keys (the base shape only) and
|
|
2504
|
-
> \`@Value()\` only works because of its raw \`process.env\` fallback —
|
|
2505
|
-
> Zod coercion + schema defaults are silently skipped.
|
|
2506
|
-
|
|
2507
|
-
## Standalone Utilities (No DI Required)
|
|
2508
|
-
|
|
2509
|
-
These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
|
|
2510
|
-
|
|
2511
|
-
| Utility | Import | Example |
|
|
2512
|
-
|---------|--------|---------|
|
|
2513
|
-
| \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
|
|
2514
|
-
| \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
|
|
2515
|
-
| \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
|
|
2516
|
-
| \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
|
|
2517
|
-
| \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
|
|
2518
|
-
| \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
|
|
2519
|
-
| \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
|
|
2520
|
-
| \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
|
|
2521
|
-
| \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
|
|
2522
|
-
|
|
2523
|
-
## Key Decorators
|
|
2524
|
-
|
|
2525
|
-
### HTTP Routes
|
|
2526
|
-
| Decorator | Purpose |
|
|
2527
|
-
|-----------|---------|
|
|
2528
|
-
| \`@Controller()\` | Define route prefix |
|
|
2529
|
-
| \`@Get('/'), @Post('/')\` | HTTP method handlers |
|
|
2530
|
-
| \`@Middleware(fn)\` | Attach middleware |
|
|
2531
|
-
| \`@Public()\` | Skip auth (requires auth adapter) |
|
|
2532
|
-
| \`@Roles('admin')\` | Role-based access |
|
|
2533
|
-
|
|
2534
|
-
### Dependency Injection
|
|
2535
|
-
| Decorator | Purpose |
|
|
2536
|
-
|-----------|---------|
|
|
2537
|
-
| \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
|
|
2538
|
-
| \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
|
|
2539
|
-
| \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
|
|
2540
|
-
| \`@Service()\` | Register singleton service |
|
|
2541
|
-
| \`@Repository()\` | Register repository |
|
|
2542
|
-
| \`@Autowired()\` | Property injection |
|
|
2543
|
-
| \`@Inject('token')\` | Token-based injection |
|
|
2544
|
-
| \`@Value('VAR')\` | Inject env variable |
|
|
2545
|
-
|
|
2546
|
-
### Context Decorators
|
|
2547
|
-
|
|
2548
|
-
Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
|
|
2549
|
-
Use this **instead of \`@Middleware()\`** when the middleware's only output
|
|
2550
|
-
is a value other code reads off \`ctx\`.
|
|
2551
|
-
|
|
2552
|
-
| Concept | Where it lives |
|
|
2553
|
-
|---------|----------------|
|
|
2554
|
-
| \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
|
|
2555
|
-
| Method/class decorator | \`@LoadX\` on a controller method/class |
|
|
2556
|
-
| Module hook | \`build: () => ({ contributors() { return [...] } })\` (\`defineModule\`) — or \`AppModule.contributors?()\` for class form |
|
|
2557
|
-
| Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
|
|
2558
|
-
| Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
|
|
2559
|
-
| Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
|
|
2560
|
-
|
|
2561
|
-
Precedence high → low: **method > class > module > adapter > global**.
|
|
2562
|
-
Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
|
|
2563
|
-
fast). The \`onError\` hook is async-permitted.
|
|
2564
|
-
|
|
2565
|
-
Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
|
|
2566
|
-
|
|
2567
|
-
${t===`cqrs`?`### Background Jobs
|
|
2568
|
-
| Decorator | Purpose |
|
|
2569
|
-
|-----------|---------|
|
|
2570
|
-
| \`@Job('name')\` | Queue job handler |
|
|
2571
|
-
| \`@Process('queue')\` | Queue processor |
|
|
2572
|
-
| \`@Cron('0 * * * *')\` | Cron schedule |
|
|
2573
|
-
| \`@WsController()\` | WebSocket controller |
|
|
2574
|
-
|
|
2575
|
-
`:``}## Common Pitfalls
|
|
2576
|
-
|
|
2577
|
-
1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
|
|
2578
|
-
2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
|
|
2579
|
-
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()\`
|
|
2580
|
-
4. **Routes not found** — Check controller path and module registration
|
|
2581
|
-
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.
|
|
2582
|
-
6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
|
|
2583
|
-
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.
|
|
2584
|
-
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.
|
|
2585
|
-
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).
|
|
2586
|
-
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({ ... })\`.
|
|
2587
|
-
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\`.
|
|
2588
|
-
|
|
2589
|
-
## CLI Commands Reference
|
|
2590
|
-
|
|
2591
|
-
| Command | Description |
|
|
2592
|
-
|---------|-------------|
|
|
2593
|
-
| \`kick dev\` | Dev server with HMR |
|
|
2594
|
-
| \`kick dev:debug\` | Dev server with debugger |
|
|
2595
|
-
| \`kick build\` | Production build |
|
|
2596
|
-
| \`kick start\` | Run production build |
|
|
2597
|
-
| \`kick g module <names...>\` | Generate one or more modules |
|
|
2598
|
-
| \`kick g scaffold <name> <fields>\` | Generate CRUD |
|
|
2599
|
-
| \`kick g controller <name>\` | Generate controller |
|
|
2600
|
-
| \`kick g service <name>\` | Generate service |
|
|
2601
|
-
| \`kick g middleware <name>\` | Generate middleware |
|
|
2602
|
-
| \`kick add <package>\` | Add KickJS package |
|
|
2603
|
-
| \`kick add --list\` | List available packages |
|
|
2604
|
-
| \`kick rm module <names...>\` | Remove one or more modules |
|
|
2605
|
-
|
|
2606
|
-
> **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
|
|
2607
|
-
> \`\`\`bash
|
|
2608
|
-
> kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
|
|
2609
|
-
> \`\`\`
|
|
2610
|
-
|
|
2611
|
-
## Learn More
|
|
2612
|
-
|
|
2613
|
-
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
2614
|
-
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
2615
|
-
- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
2616
|
-
- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
|
|
2617
|
-
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
2618
|
-
`}function vt(e,t,n){let r=`<!-- Generated by \`kick g agents\` for ${e}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`;return[{slug:`add-module`,frontmatterName:`kickjs-add-module`,description:`Use when the user asks to add a new feature module (controller + service + repo + DTOs).`,body:`**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
2619
|
-
|
|
2620
|
-
**Steps**:
|
|
2621
|
-
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
2622
|
-
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
|
|
2623
|
-
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
2624
|
-
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
2625
|
-
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
2626
|
-
|
|
2627
|
-
**Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
|
|
2628
|
-
|
|
2629
|
-
\`\`\`ts
|
|
2630
|
-
export const TodosModule = defineModule({
|
|
2631
|
-
name: 'TodosModule',
|
|
2632
|
-
build: () => ({
|
|
2633
|
-
register(container) {
|
|
2634
|
-
container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
|
|
2635
|
-
},
|
|
2636
|
-
routes() {
|
|
2637
|
-
return { path: '/todos', controller: TodosController }
|
|
2638
|
-
},
|
|
2639
|
-
}),
|
|
2640
|
-
})
|
|
2641
|
-
\`\`\`
|
|
2642
|
-
|
|
2643
|
-
The module file MUST include \`import.meta.glob([...], { eager: true })\` for every \`@Service\` / \`@Repository\` / \`@Component\` class — without it, decorators never fire and DI silently resolves to \`undefined\`.
|
|
2644
|
-
|
|
2645
|
-
**Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
|
|
2646
|
-
|
|
2647
|
-
\`\`\`ts
|
|
2648
|
-
routes() {
|
|
2649
|
-
return [
|
|
2650
|
-
{ path: '/todos', controller: TodosController }, // /api/v1/todos
|
|
2651
|
-
{ path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
|
|
2652
|
-
]
|
|
2653
|
-
}
|
|
2654
|
-
\`\`\`
|
|
2655
|
-
|
|
2656
|
-
**Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
|
|
2657
|
-
|
|
2658
|
-
**Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
|
|
2659
|
-
|
|
2660
|
-
**Red flags** (stop and ask):
|
|
2661
|
-
- File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite plugin's \`*.module.[tj]sx?\` glob doesn't pick it up; every save becomes a full restart.
|
|
2662
|
-
- \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
|
|
2663
|
-
- \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
|
|
2664
|
-
- \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
|
|
2665
|
-
- Module not registered in \`src/modules/index.ts\`.`},{slug:`add-adapter`,frontmatterName:`kickjs-add-adapter`,description:`Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).`,body:"**Steps**:\n1. `kick g adapter <name>` to scaffold the boilerplate, OR install via `kick add <package>` for first-party adapters.\n2. The generated file uses `defineAdapter()` — never `class implements AppAdapter`.\n3. Add the adapter instance (note the parens) to `src/adapters/index.ts` — don't inline in `src/index.ts`.\n4. Pick the right hook and middleware phase deliberately.\n5. Verify with `kick dev` that the adapter's lifecycle logs fire.\n\n**Canonical shape** — factory closure owns instance state:\n\n```ts\nexport const RedisAdapter = defineAdapter<RedisConfig>({\n name: 'RedisAdapter',\n defaults: { url: 'redis://localhost' },\n build: (config) => {\n const client = createClient(config.url)\n return {\n beforeStart: ({ container }) => {\n container.registerInstance(REDIS_CLIENT, client)\n },\n afterStart: () => client.connect(),\n shutdown: () => client.quit(),\n }\n },\n})\n\n// In src/adapters/index.ts:\nexport const adapters = [RedisAdapter({ url: env.REDIS_URL })] // <-- note parens\n```\n\n**Lifecycle hook decision tree**:\n- `beforeMount` — register early routes that should bypass middleware (health, docs UI).\n- `beforeStart` — DI ready, server not listening yet. **Use this for `container.registerInstance(...)` calls** so they work under `createTestApp` too.\n- `afterStart` — server has `ctx.server` available. Only use for things that need a listening server (Socket.IO upgrades, port logging). **Doesn't fire under `createTestApp`.**\n- `shutdown` — runs concurrently via `Promise.allSettled`, so one failure doesn't block siblings (but errors are swallowed — log inside).\n\n**Middleware phases** (see `MiddlewarePhase` JSDoc):\n`beforeGlobal` | `afterGlobal` (default) | `beforeRoutes` | `afterRoutes` (fires only on fall-through — matched routes that respond skip it).\n\n**Multi-instance** — `.scoped('cache', { url: ... })` makes `name` become `RedisAdapter:cache`. **Deferred config** — `.async({ inject, useFactory })` for config that depends on DI-resolved services.\n\n**Red flags**:\n- `bootstrap({ adapters: [MyAdapter] })` — passed the factory, not the instance. Call it: `MyAdapter()`.\n- Inlining the adapter list directly in `src/index.ts` — entry file should stay thin.\n- Returning a plain object instead of going through `defineAdapter()` — type inference for `config` will be wrong.\n- Using `.async()` for an adapter that returns `middleware()` / `contributors()` / `beforeMount()` / `onRouteMount()` — those hooks have already run by the time `.async()` resolves and are silently skipped.\n- Cross-adapter ordering via array position when it's load-bearing — use `dependsOn: ['OtelAdapter']`; cycles throw `MountCycleError` at boot.\n- Using an adapter when the integration ships **modules + DI bindings + middleware** together → that's a plugin. Promote to `definePlugin()` (see `add-plugin` skill).\n\n**Nuances**:\n- `AdapterContext.server` is `undefined` outside `afterStart`.\n- `shutdown` errors are swallowed by `Promise.allSettled` — wrap in try/catch and log if you care."},{slug:`add-plugin`,frontmatterName:`kickjs-add-plugin`,description:`Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).`,body:"**When plugin > adapter**: a plugin is the right answer when the integration ships **more than one** of: a module, a DI binding, middleware, or another adapter. If you have a single hook (`beforeStart`) and no other contributions, use `defineAdapter` instead.\n\n**Canonical shape**:\n\n```ts\nimport { definePlugin } from '@forinda/kickjs'\n\nexport const AuthPlugin = definePlugin({\n name: 'AuthPlugin',\n defaults: { tokenTtl: '1h' },\n build: (config, { name }) => ({\n modules: () => [AuthModule()],\n adapters: () => [JwtAdapter({ ttl: config.tokenTtl })],\n middleware: () => [requestIdMiddleware()],\n register(container) {\n container.registerFactory(TOKEN_SIGNER, () => createSigner(config))\n },\n contributors() {\n return [LoadCurrentUser.registration]\n },\n onReady({ server }) {\n log.info(`AuthPlugin listening on port ${server.address().port}`)\n },\n }),\n})\n\n// In bootstrap:\nbootstrap({ plugins: [AuthPlugin({ tokenTtl: env.TOKEN_TTL })] }) // <-- parens\n```\n\n**Inline plugin literal** — the canonical answer for one-off DI bindings. There's no top-level `register:` on `bootstrap` itself:\n\n```ts\nbootstrap({\n plugins: [{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } }],\n})\n```\n\n**Execution order** (memorize):\nplugin `register()` → plugin `middleware()` → plugin `modules()` + user modules → plugin `adapters()` + user adapters → server listens → plugin `onReady()`.\n\n**Static vs dynamic modules**: `modules()` returning an array is introspectable (Swagger, DevTools see it). `setup(registry)` is imperative — pick the latter when the module set depends on resolved config.\n\n**Multi-instance** — `.scoped('users', { url })`; derive unique DI tokens from `ctx.name` inside `build`:\n\n```ts\nbuild: (config, { name }) => ({\n register(c) {\n c.registerInstance(createToken(`cache/${name}`), client)\n },\n})\n```\n\n**Precedence**: plugin contributors land at `'adapter'` precedence — beat global, lose to module/class/method same-key.\n\n**Red flags**:\n- `bootstrap({ plugins: [AuthPlugin] })` — passed factory. Call it: `AuthPlugin()`.\n- Reaching for a plugin when an adapter would do (no modules, no DI bindings, no contributors) — overkill; use `defineAdapter()`.\n- `.async()` plugin that depends on `modules()` / `middleware()` / `adapters()` / `contributors()` — those are dropped. `.async()` only resolves `register()` + `onReady()`.\n- Confusing CLI plugins (`defineCliPlugin` from `@forinda/kickjs-cli`) with runtime plugins (`definePlugin` from `@forinda/kickjs`) — different surfaces, different registration sites.\n- `dependsOn: ['SomePlugin']` referring to a plugin not in the boot list — throws `MissingMountDepError` at boot.\n\n**Nuances**:\n- `definition` is `Object.freeze`'d metadata; useful for version checks (`compare(AuthPlugin.definition.version, '1.2.0')`) — not mountable."},{slug:`write-controller-test`,frontmatterName:`kickjs-write-controller-test`,description:`Use when adding a Vitest test that exercises an HTTP route or DI graph.`,body:"**Template** (copy/paste, adjust):\n\n```ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\nbeforeEach(() => {\n Container.reset() // isolated DI per test\n})\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/api/v1/users')\n expect(res.status).toBe(200)\n })\n})\n```\n\n**Typed handler signature** — pair with `kick typegen` so `ctx.body` / `params` / `query` are typed by the route's Zod schema:\n\n```ts\n@Post('/', { body: createTodoSchema })\ncreate(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route\n ctx.created(await this.service.create(ctx.body))\n}\n```\n\n**Red flags**:\n- `new Container()` — wrong; use `Container.reset()` in `beforeEach` or `Container.create()` for fully isolated graphs.\n- `Container.getInstance().reset()` — wrong; same fix.\n- Sharing a container instance across `it()` blocks — leaks registrations between tests.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.\n- Calling `getRequestValue<string>('traceId')` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.\n- Asserting on `res.body.requestId` when `requestId()` middleware isn't mounted in the test app — value will be `undefined`.\n- Using `Scope.REQUEST` services in a test without mounting `requestScopeMiddleware()` — `getRequestValue` silently returns `undefined`; `getRequestStore` throws.\n\n**Nuances**:\n- `@Inject` and `@Autowired` are interchangeable — same runtime, same types; pick by readability.\n- `@Value('MISSING_KEY')` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue."},{slug:`env-wiring-check`,frontmatterName:`kickjs-env-wiring-check`,description:`Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.`,body:"**Diagnosis (in order)**:\n1. Open `src/index.ts`. The **first non-`reflect-metadata`** import MUST be `import './config'`.\n2. Open `src/config/index.ts`. It MUST call `loadEnv(envSchema)` as a top-level side effect — not just declare the schema:\n ```ts\n import { loadEnv, defineEnv } from '@forinda/kickjs'\n const envSchema = defineEnv((base) => base.extend({ DATABASE_URL: z.string().url() }))\n export const env = loadEnv(envSchema)\n ```\n3. The new key MUST be declared in the Zod schema. `@Value('NEW_KEY')` accepts any string at the type level and **falls back to raw `process.env`** when the schema doesn't know the key — silently skipping Zod coercion.\n4. After adding a key, re-run `kick typegen` (or restart `kick dev` if the typegen watcher missed it) so the global `KickEnv` augmentation picks it up.\n\n**Why `@Value` \"works\" but `ConfigService.get` doesn't**: `@Value` has the `process.env` fallback that masks missing-side-effect-import bugs; `ConfigService` has none. If `@Value('FOO')` returns a value but `ConfigService.get('FOO')` returns `undefined`, the side-effect import of `./config` is missing.\n\n**`reloadEnv` vs `resetEnvCache`** — distinct, frequently mixed up:\n- `reloadEnv()` — re-reads `process.env` against the **already registered** schema. Use in HMR plugins after `.env` file changes. Schema survives.\n- `resetEnvCache()` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.\n\n**Nuances**:\n- `loadEnv()` cache is **sticky**: once `loadEnv(extendedSchema)` runs anywhere, no-arg calls reuse it — but only if it actually ran. Schema downgrades silently if `src/config/index.ts` isn't imported.\n- `createConfigService(envSchema)` is deprecated; the typegen-driven `ConfigService` covers it.\n- `dotenv` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.\n- For HMR-friendly `.env` edits, add `envWatchPlugin()` to `vite.config.ts` — calls `reloadEnv()` automatically.\n\n**Fix recipe**: add the key to the schema; add `import './config'` as the first non-reflect-metadata import in `src/index.ts`; re-run `kick typegen`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,body:"**Check** `src/index.ts`'s last line:\n\n```ts\n// CORRECT — Vite plugin + createTestApp import the named `app` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n```\n\nThe Vite plugin imports the named `app` symbol via `virtual:kickjs/app`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare `await bootstrap(...)` with no `export` — fix by adding `export const app =`.\n- Re-assigning `app` later in the file (`app = somethingElse`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling `bootstrap()` — only the entry should. Tests use `createTestApp` instead."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
|
|
2666
|
-
|
|
2667
|
-
\`\`\`ts
|
|
2668
|
-
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
2669
|
-
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
2670
|
-
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
2671
|
-
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
2672
|
-
|
|
2673
|
-
// src/middleware/index.ts — global middleware uses RAW EXPRESS signature
|
|
2674
|
-
// (req, res, next), NOT (ctx, next)
|
|
2675
|
-
export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
|
|
2676
|
-
|
|
2677
|
-
// src/plugins/index.ts
|
|
2678
|
-
export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
|
|
2679
|
-
|
|
2680
|
-
// src/adapters/index.ts
|
|
2681
|
-
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
2682
|
-
|
|
2683
|
-
// src/index.ts — stays small
|
|
2684
|
-
import 'reflect-metadata'
|
|
2685
|
-
import './config' // MUST be early — side-effect schema load
|
|
2686
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
2687
|
-
import { modules } from './modules'
|
|
2688
|
-
import { middleware } from './middleware'
|
|
2689
|
-
import { plugins } from './plugins'
|
|
2690
|
-
import { adapters } from './adapters'
|
|
2691
|
-
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
2692
|
-
\`\`\`
|
|
2693
|
-
|
|
2694
|
-
**One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
|
|
2695
|
-
|
|
2696
|
-
\`\`\`ts
|
|
2697
|
-
plugins: [
|
|
2698
|
-
...plugins,
|
|
2699
|
-
{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
|
|
2700
|
-
]
|
|
2701
|
-
\`\`\`
|
|
2702
|
-
|
|
2703
|
-
**Red flags**:
|
|
2704
|
-
- Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
2705
|
-
- Mixing middleware signatures: \`bootstrap({ middleware })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws "Cannot read properties of undefined".
|
|
2706
|
-
- \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// Optionally publish discoverability for tooling (Swagger, DevTools)\ndefineAugmentation('ContextMeta', {\n description: 'Per-request tenant resolved from x-tenant-id header.',\n example: { id: 'acme', name: 'Acme Inc' },\n})\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n ctx.json(ctx.get('project'))\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying Express request is shared).\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- `defineAugmentation` without the `declare module` block (or vice-versa) — discoverability and types drift apart; `ctx.get('tenant')` becomes `unknown`.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
|
|
2707
|
-
- \`kick new <name>\` — start a new project (prompts for template / repo / pm).
|
|
2708
|
-
- \`kick dev\` — local dev server with Vite HMR.
|
|
2709
|
-
- \`kick build\` — production bundle via Vite.
|
|
2710
|
-
- \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
|
|
2711
|
-
- \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
|
|
2712
|
-
- \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
|
|
2713
|
-
- \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
|
|
2714
|
-
- \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
|
|
2715
|
-
- \`kick info\` — environment / version dump for bug reports.
|
|
2716
|
-
- \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
|
|
2717
|
-
|
|
2718
|
-
**Useful flag combos**:
|
|
2719
|
-
|
|
2720
|
-
\`\`\`bash
|
|
2721
|
-
kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
|
|
2722
|
-
kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
|
|
2723
|
-
kick new . --yes --force # Scaffold into current dir, clear existing files
|
|
2724
|
-
kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
|
|
2725
|
-
kick g agents -f --only skills # Refresh just the skills after upgrade
|
|
2726
|
-
kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
|
|
2727
|
-
kick inspect --port 4000 --json # Machine-readable route/adapter dump
|
|
2728
|
-
kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
|
|
2729
|
-
\`\`\`
|
|
2730
|
-
|
|
2731
|
-
**Lesser-known, high-value**:
|
|
2732
|
-
- \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
|
|
2733
|
-
- \`kick g agents -f\` — regenerates \`CLAUDE.md\` (root) and \`.agents/AGENTS.md\` / \`GEMINI.md\` / \`COPILOT.md\` + every \`.agents/skills/<slug>/SKILL.md\` from the current CLI templates.
|
|
2734
|
-
- \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
|
|
2735
|
-
- \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
|
|
2736
|
-
- \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
|
|
2737
|
-
- \`kick check\` — preflight gate (typecheck + lint + format) before commit.
|
|
2738
|
-
- \`kick codemod\` — automated AST-level migration between framework versions.
|
|
2739
|
-
|
|
2740
|
-
**Red flags**:
|
|
2741
|
-
- Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
|
|
2742
|
-
- Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
|
|
2743
|
-
- Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
|
|
2744
|
-
- Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
|
|
2745
|
-
- Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`refresh-agent-docs`,frontmatterName:`kickjs-refresh-agent-docs`,description:`Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.`,body:"**Steps**:\n1. `kick g agents -f --only both` — overwrites `CLAUDE.md` (root) and `.agents/AGENTS.md`.\n2. `kick g agents -f --only skills` — refreshes every `.agents/skills/<slug>/SKILL.md`.\n3. `kick g agents -f --only gemini` / `--only copilot` — refresh the per-agent files when needed.\n4. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate `AGENTS.local.md` or per-skill `SKILL.local.md` alongside.\n5. Commit as `docs(agents): sync from CLI vX.Y`.\n\n**`.agents/` layout** (post-restructure):\n\n```\nCLAUDE.md # at root — Claude Code auto-loads from here\n.agents/\n├── AGENTS.md # canonical multi-agent reference\n├── GEMINI.md # Gemini-specific notes\n├── COPILOT.md # Copilot CLI notes\n└── skills/\n ├── add-module/SKILL.md\n ├── add-adapter/SKILL.md\n └── … # one SKILL.md per skill, frontmatter-namespaced\n```\n\nCustomisation goes in `.local.md` siblings (`AGENTS.local.md`, `skills/<slug>/SKILL.local.md`) — those are never overwritten."},{slug:`deny-list`,frontmatterName:`kickjs-deny-list`,description:`Patterns to refuse outright when the user asks for them — they break v4 invariants.`,body:"**Module / adapter / plugin shape**:\n- `class implements AppAdapter` → use `defineAdapter()`.\n- `class implements KickPlugin` / function returning `KickPlugin` → use `definePlugin()`.\n- `class implements AppModule` for new code → use `defineModule()`.\n- `bootstrap({ adapters: [MyAdapter] })` (factory) → `MyAdapter()` (instance, with parens).\n- `@Controller('/path')` with a path argument → drop the path; set the mount via `routes().path`. The decorator path is OpenAPI metadata only.\n- Module file named `<name>.ts` (no `.module` suffix) → rename to `<name>.module.ts`. Vite HMR's glob doesn't pick up the unsuffixed form.\n\n**DI**:\n- `new Container()` or `Container.getInstance().reset()` in tests → use `Container.reset()` in `beforeEach` (or `Container.create()` for fully isolated graphs).\n- DI tokens with `:` separator (`'app:db:url'`) or in PascalCase → use slash-delimited lower-case (`'app/db/url'`). First-party uses reserved `'kick/'` prefix.\n- `Symbol.for(...)` for DI tokens — globally interned, **collides across files**. Use `createToken<T>('name')`.\n- Raw string tokens (`@Inject('config')`) — silent collisions; widens to `unknown`. Use `createToken<T>`.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve time.\n\n**Bootstrap / entry file**:\n- `bootstrap({ ... })` without `export const app = ...` → always export. HMR degrades to full restart and `createTestApp` loses the handle.\n- `bootstrap({ register: ... })` — that option doesn't exist. Use an inline plugin in `plugins`.\n\n**Middleware**:\n- Using `(ctx, next)` for global middleware in `bootstrap({ middleware })` — global middleware uses raw Express `(req, res, next)`. Wrong signature throws \"Cannot read properties of undefined\".\n- Using `(req, res, next)` for an `@Middleware()` decorator — those use `(ctx, next)`.\n- `@Middleware()` whose only output is `ctx.set('x', v)` — should be a context decorator (typed, ordered, testable).\n\n**Context contributors**:\n- `ctx.tenant = x` from a contributor — only sticks to one `RequestContext` instance. **Return the value** so the runner writes it via `ctx.set(key, value)`.\n- `defineAugmentation('ContextMeta', ...)` without the matching `declare module '@forinda/kickjs'` block (or vice-versa).\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type.\n\n**Env / config**:\n- `@Value('NEW_KEY')` without the key in the Zod schema — silent fallback to raw `process.env`, no coercion.\n- `resetEnvCache()` outside tests — drops the registered schema.\n\n**List endpoints**:\n- Reading `req.query.status` directly — bypasses the allow-list. Use `ctx.qs({ filterable })`.\n- Returning a bare array from a list endpoint — breaks the `PaginatedResponse<T>` contract. Use `ctx.paginate()`.\n\n**Assets**:\n- Hand-rolled `__dirname` arithmetic for template paths — use `assets.<ns>.<key>()` and add the namespace to `kick.config.ts assetMap`."}].map(e=>({slug:e.slug,content:`---
|
|
2746
|
-
name: ${e.frontmatterName}
|
|
2747
|
-
description: ${e.description}
|
|
2748
|
-
---
|
|
2749
|
-
|
|
2750
|
-
${r}
|
|
2751
|
-
|
|
2752
|
-
${e.body}
|
|
2753
|
-
`}))}function yt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
|
|
2754
|
-
|
|
2755
|
-
This file is the agent-facing **skills index** for KickJS work in this
|
|
2756
|
-
repo. Each block below is a short, rigid workflow keyed to a specific
|
|
2757
|
-
trigger ("user wants to add a module", "tests are leaking state", etc.).
|
|
2758
|
-
|
|
2759
|
-
- Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
|
|
2760
|
-
- Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
|
|
2761
|
-
- **This file** → step-by-step recipes the agent should *execute*.
|
|
2762
|
-
|
|
2763
|
-
Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
|
|
2764
|
-
|
|
2765
|
-
---
|
|
2766
|
-
|
|
2767
|
-
## Skill: add-module
|
|
2768
|
-
|
|
2769
|
-
\`\`\`yaml
|
|
2770
|
-
name: kickjs-add-module
|
|
2771
|
-
description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
|
|
2772
|
-
\`\`\`
|
|
2773
|
-
|
|
2774
|
-
**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
2775
|
-
|
|
2776
|
-
**Steps**:
|
|
2777
|
-
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
2778
|
-
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
|
|
2779
|
-
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
2780
|
-
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
2781
|
-
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
2782
|
-
|
|
2783
|
-
**Red flags** (stop and ask):
|
|
2784
|
-
- File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
|
|
2785
|
-
- Module not registered in \`src/modules/index.ts\`.
|
|
2786
|
-
- \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
|
|
2787
|
-
|
|
2788
|
-
---
|
|
2789
|
-
|
|
2790
|
-
## Skill: add-adapter
|
|
2791
|
-
|
|
2792
|
-
\`\`\`yaml
|
|
2793
|
-
name: kickjs-add-adapter
|
|
2794
|
-
description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
|
|
2795
|
-
\`\`\`
|
|
2796
|
-
|
|
2797
|
-
**Steps**:
|
|
2798
|
-
1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
|
|
2799
|
-
2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
|
|
2800
|
-
3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
|
|
2801
|
-
4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
|
|
2802
|
-
5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
|
|
2803
|
-
|
|
2804
|
-
**Red flags**:
|
|
2805
|
-
- Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
|
|
2806
|
-
- Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
|
|
2807
|
-
|
|
2808
|
-
---
|
|
2809
|
-
|
|
2810
|
-
## Skill: write-controller-test
|
|
2811
|
-
|
|
2812
|
-
\`\`\`yaml
|
|
2813
|
-
name: kickjs-write-controller-test
|
|
2814
|
-
description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
|
|
2815
|
-
\`\`\`
|
|
2816
|
-
|
|
2817
|
-
**Template** (copy/paste, adjust):
|
|
2818
|
-
|
|
2819
|
-
\`\`\`ts
|
|
2820
|
-
import { describe, it, expect } from 'vitest'
|
|
2821
|
-
import { Container } from '@forinda/kickjs'
|
|
2822
|
-
import { createTestApp } from '@forinda/kickjs-testing'
|
|
2823
|
-
|
|
2824
|
-
describe('UserController', () => {
|
|
2825
|
-
it('returns users', async () => {
|
|
2826
|
-
const container = Container.create() // isolated DI per test
|
|
2827
|
-
const app = await createTestApp([UserModule], { container })
|
|
2828
|
-
const res = await app.get('/users')
|
|
2829
|
-
expect(res.status).toBe(200)
|
|
2830
|
-
})
|
|
2831
|
-
})
|
|
2832
|
-
\`\`\`
|
|
2833
|
-
|
|
2834
|
-
**Red flags**:
|
|
2835
|
-
- \`new Container()\` — wrong; use \`Container.create()\`.
|
|
2836
|
-
- \`Container.getInstance().reset()\` — wrong; same fix.
|
|
2837
|
-
- Sharing a container across \`it()\` blocks — leaks registrations.
|
|
2838
|
-
|
|
2839
|
-
---
|
|
2840
|
-
|
|
2841
|
-
## Skill: env-wiring-check
|
|
2842
|
-
|
|
2843
|
-
\`\`\`yaml
|
|
2844
|
-
name: kickjs-env-wiring-check
|
|
2845
|
-
description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
|
|
2846
|
-
\`\`\`
|
|
2847
|
-
|
|
2848
|
-
**Diagnosis**:
|
|
2849
|
-
1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
|
|
2850
|
-
2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
|
|
2851
|
-
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).
|
|
2852
|
-
|
|
2853
|
-
**Fix**: add the key to the schema; ensure both side-effect imports above are present.
|
|
2854
|
-
|
|
2855
|
-
---
|
|
2856
|
-
|
|
2857
|
-
## Skill: bootstrap-export
|
|
2858
|
-
|
|
2859
|
-
\`\`\`yaml
|
|
2860
|
-
name: kickjs-bootstrap-export
|
|
2861
|
-
description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
|
|
2862
|
-
\`\`\`
|
|
2863
|
-
|
|
2864
|
-
**Check** \`src/index.ts\`'s last line:
|
|
2865
|
-
|
|
2866
|
-
\`\`\`ts
|
|
2867
|
-
// CORRECT
|
|
2868
|
-
export const app = await bootstrap({ ... })
|
|
2869
|
-
|
|
2870
|
-
// WRONG (HMR degrades to full restart, createTestApp loses the handle)
|
|
2871
|
-
await bootstrap({ ... })
|
|
2872
|
-
\`\`\`
|
|
2873
|
-
|
|
2874
|
-
The Vite plugin imports the named \`app\` symbol; testing helpers do too.
|
|
2875
|
-
|
|
2876
|
-
---
|
|
2877
|
-
|
|
2878
|
-
## Skill: thin-entry-file
|
|
2879
|
-
|
|
2880
|
-
\`\`\`yaml
|
|
2881
|
-
name: kickjs-thin-entry-file
|
|
2882
|
-
description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
|
|
2883
|
-
\`\`\`
|
|
2884
|
-
|
|
2885
|
-
**Refactor target**:
|
|
2886
|
-
|
|
2887
|
-
\`\`\`ts
|
|
2888
|
-
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
2889
|
-
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
2890
|
-
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
2891
|
-
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
2892
|
-
|
|
2893
|
-
// src/middleware/index.ts
|
|
2894
|
-
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
2895
|
-
|
|
2896
|
-
// src/plugins/index.ts
|
|
2897
|
-
export const plugins = [MetricsPlugin(), ...]
|
|
2898
|
-
|
|
2899
|
-
// src/adapters/index.ts
|
|
2900
|
-
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
2901
|
-
|
|
2902
|
-
// src/index.ts — stays small
|
|
2903
|
-
import 'reflect-metadata'
|
|
2904
|
-
import './config'
|
|
2905
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
2906
|
-
import { modules } from './modules'
|
|
2907
|
-
import { middleware } from './middleware'
|
|
2908
|
-
import { plugins } from './plugins'
|
|
2909
|
-
import { adapters } from './adapters'
|
|
2910
|
-
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
2911
|
-
\`\`\`
|
|
2912
|
-
|
|
2913
|
-
**Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
2914
|
-
|
|
2915
|
-
---
|
|
2916
|
-
|
|
2917
|
-
## Skill: context-contributor
|
|
2918
|
-
|
|
2919
|
-
\`\`\`yaml
|
|
2920
|
-
name: kickjs-context-contributor
|
|
2921
|
-
description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
|
|
2922
|
-
\`\`\`
|
|
2923
|
-
|
|
2924
|
-
**Pattern** (HTTP — most common):
|
|
2925
|
-
|
|
2926
|
-
\`\`\`ts
|
|
2927
|
-
import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
|
|
2928
|
-
|
|
2929
|
-
const LoadTenant = defineHttpContextDecorator({
|
|
2930
|
-
key: 'tenant',
|
|
2931
|
-
deps: { repo: TENANT_REPO },
|
|
2932
|
-
resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
|
|
2933
|
-
})
|
|
2934
|
-
|
|
2935
|
-
const LoadProject = defineHttpContextDecorator({
|
|
2936
|
-
key: 'project',
|
|
2937
|
-
dependsOn: ['tenant'],
|
|
2938
|
-
resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
|
|
2939
|
-
})
|
|
2940
|
-
|
|
2941
|
-
@LoadTenant
|
|
2942
|
-
@LoadProject
|
|
2943
|
-
@Get('/projects/:id')
|
|
2944
|
-
getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
|
|
2945
|
-
\`\`\`
|
|
2946
|
-
|
|
2947
|
-
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\`).
|
|
2948
|
-
|
|
2949
|
-
Precedence high → low: **method > class > module > adapter > global**.
|
|
2950
|
-
Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
|
|
2951
|
-
|
|
2952
|
-
**Critical rules — all stem from the same shared-via-ALS instance model**:
|
|
2953
|
-
- Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
|
|
2954
|
-
- **\`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.
|
|
2955
|
-
- \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
|
|
2956
|
-
- Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
|
|
2957
|
-
- **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.
|
|
2958
|
-
|
|
2959
|
-
**Don't use this for**: response short-circuit, stream mutation, or
|
|
2960
|
-
pre-route-matching work — keep \`@Middleware()\` for those.
|
|
2961
|
-
|
|
2962
|
-
---
|
|
2963
|
-
|
|
2964
|
-
## Skill: refresh-agent-docs
|
|
2965
|
-
|
|
2966
|
-
\`\`\`yaml
|
|
2967
|
-
name: kickjs-refresh-agent-docs
|
|
2968
|
-
description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
|
|
2969
|
-
\`\`\`
|
|
2970
|
-
|
|
2971
|
-
**Steps**:
|
|
2972
|
-
1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
|
|
2973
|
-
2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
|
|
2974
|
-
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.
|
|
2975
|
-
4. Commit as \`docs(agents): sync from CLI vX.Y\`.
|
|
2976
|
-
|
|
2977
|
-
---
|
|
2978
|
-
|
|
2979
|
-
## Skill: deny-list
|
|
2980
|
-
|
|
2981
|
-
\`\`\`yaml
|
|
2982
|
-
name: kickjs-deny-list
|
|
2983
|
-
description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
|
|
2984
|
-
\`\`\`
|
|
2985
|
-
|
|
2986
|
-
- \`class implements AppAdapter\` → use \`defineAdapter()\`.
|
|
2987
|
-
- \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
|
|
2988
|
-
- \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
|
|
2989
|
-
- \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
|
|
2990
|
-
- DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
|
|
2991
|
-
- \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
|
|
2992
|
-
- Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
|
|
2993
|
-
|
|
2994
|
-
---
|
|
2995
|
-
|
|
2996
|
-
## Learn More
|
|
2997
|
-
|
|
2998
|
-
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
2999
|
-
- [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
3000
|
-
- [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
|
|
3001
|
-
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
3002
|
-
`}function bt(e,t,n){return`# GEMINI.md — ${e}
|
|
3003
|
-
|
|
3004
|
-
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
3005
|
-
reference for this project — every convention, structure, decorator
|
|
3006
|
-
pattern, env wiring rule, generator usage. This file is a thin
|
|
3007
|
-
Gemini-specific layer; when the two disagree on anything substantive,
|
|
3008
|
-
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
3009
|
-
|
|
3010
|
-
## Why this file
|
|
3011
|
-
|
|
3012
|
-
Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
|
|
3013
|
-
agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
|
|
3014
|
-
means Gemini reads the same shared prose as Codex / Cursor / Copilot
|
|
3015
|
-
without us copy-pasting.
|
|
3016
|
-
|
|
3017
|
-
## Gemini-specific notes
|
|
3018
|
-
|
|
3019
|
-
- **Skills activation** — Gemini activates skills via
|
|
3020
|
-
\`activate_skill\` (its native MCP-style tool); the equivalent on
|
|
3021
|
-
Claude Code is the \`Skill\` tool. Cross-reference the
|
|
3022
|
-
\`kickjs-skills.md\` index for the available triggers.
|
|
3023
|
-
- **Tool naming** — Gemini's tool names differ from Claude Code's
|
|
3024
|
-
(e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
|
|
3025
|
-
\`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
|
|
3026
|
-
tool names; consult Gemini's docs for the concrete invocation.
|
|
3027
|
-
- **File ops** — Gemini's file edits are sandboxed; large refactors
|
|
3028
|
-
may need explicit confirmation. Prefer the smallest-possible-edit
|
|
3029
|
-
pattern.
|
|
3030
|
-
|
|
3031
|
-
## Refreshing this file
|
|
3032
|
-
|
|
3033
|
-
\`kick g agents --only gemini -f\` regenerates this file from the
|
|
3034
|
-
CLI template. Hand-edited content is overwritten — keep customisation
|
|
3035
|
-
in \`.agents/GEMINI.local.md\`.
|
|
3036
|
-
`}function xt(e,t,n){return`# COPILOT.md — ${e}
|
|
3037
|
-
|
|
3038
|
-
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
3039
|
-
reference for this project — every convention, structure, decorator
|
|
3040
|
-
pattern, env wiring rule, generator usage. This file is a thin
|
|
3041
|
-
Copilot-specific layer; when the two disagree on anything substantive,
|
|
3042
|
-
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
3043
|
-
|
|
3044
|
-
## Why this file
|
|
3045
|
-
|
|
3046
|
-
GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
|
|
3047
|
-
the agent-context files. Keeping it in \`.agents/\` next to
|
|
3048
|
-
\`AGENTS.md\` means Copilot reads the same shared prose as
|
|
3049
|
-
Codex / Cursor / Gemini / Claude Code without copy-pasting.
|
|
3050
|
-
|
|
3051
|
-
## Copilot-specific notes
|
|
3052
|
-
|
|
3053
|
-
- **Skills** — Copilot CLI auto-discovers skills from installed
|
|
3054
|
-
plugins; cross-reference \`kickjs-skills.md\` for available
|
|
3055
|
-
triggers in this project.
|
|
3056
|
-
- **Tool naming** — Copilot's tool names differ from Claude Code's
|
|
3057
|
-
(\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
|
|
3058
|
-
prose in \`AGENTS.md\` describes intents, not tool names; consult
|
|
3059
|
-
Copilot's docs for the concrete invocation.
|
|
3060
|
-
- **Confirmation flows** — Copilot CLI surfaces destructive
|
|
3061
|
-
operations through an explicit approval gate. Stage edits with
|
|
3062
|
-
short, focused diffs so each one is easy to review at the prompt.
|
|
3063
|
-
|
|
3064
|
-
## Refreshing this file
|
|
3065
|
-
|
|
3066
|
-
\`kick g agents --only copilot -f\` regenerates this file from the
|
|
3067
|
-
CLI template. Hand-edited content is overwritten — keep customisation
|
|
3068
|
-
in \`.agents/COPILOT.local.md\`.
|
|
3069
|
-
`}const St=n(_(import.meta.url)),Ct=JSON.parse(s(i(St,`..`,`package.json`),`utf-8`)),wt=`^${Ct.version}`,Tt=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`];async function Et(){let e=await Promise.all(Tt.map(async e=>{try{let t=h(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,wt]}));return Object.fromEntries(e)}async function Dt(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:a=`rest`,defaultRepo:o=`inmemory`,packages:s=[]}=e,c=n,l=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),l(`Resolving package versions...`);let u=await Et();if(await b(i(c,`package.json`),at(t,a,u,s)),await b(i(c,`vite.config.ts`),ot()),await b(i(c,`tsconfig.json`),st()),await b(i(c,`.prettierrc`),ct()),await b(i(c,`.editorconfig`),lt()),await b(i(c,`.gitignore`),ut()),await b(i(c,`.gitattributes`),dt()),await b(i(c,`.env`),ft()),await b(i(c,`.env.example`),pt()),await b(i(c,`src/config/index.ts`),Ie()),await b(i(c,`src/index.ts`),Pe(t,a,Ct.version,s)),await b(i(c,`src/modules/index.ts`),Fe()),await b(i(c,`src/modules/hello/hello.service.ts`),Le()),await b(i(c,`src/modules/hello/hello.controller.ts`),Re()),await b(i(c,`src/modules/hello/hello.module.ts`),ze()),await b(i(c,`kick.config.ts`),Be(a,o,r)),await b(i(c,`vitest.config.ts`),mt()),await b(i(c,`README.md`),ht(t,a,r)),await b(i(c,`CLAUDE.md`),gt(t,a,r)),await b(i(c,`AGENTS.md`),_t(t,a,r)),await b(i(c,`kickjs-skills.md`),yt(t,a,r)),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{g(`${r} install`,{cwd:c,stdio:`inherit`}),console.log(`
|
|
3070
|
-
Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-B8lAhWXz.mjs`).then(e=>e.r);await e({cwd:c,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{g(`git init`,{cwd:c,stdio:`pipe`}),g(`git branch -M main`,{cwd:c,stdio:`pipe`}),g(`git add -A`,{cwd:c,stdio:`pipe`}),g(`git commit -m "chore: initial commit from kick new"`,{cwd:c,stdio:`pipe`}),l(`Git repository initialized`)}catch{l(`Warning: git init failed (git may not be installed)`)}console.log(`
|
|
3071
|
-
Project scaffolded successfully!`),console.log();let d=c!==process.cwd();l(`Next steps:`),d&&l(` cd ${t}`),e.installDeps||l(` ${r} install`);let f={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};l(` ${f[a]??f.rest}`),l(` kick dev`),l(``),l(`Commands:`),l(` kick dev Start dev server with Vite HMR`),l(` kick build Production build via Vite`),l(` kick start Run production build`),l(``),l(`Generators:`),l(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),l(` kick g scaffold <n> <f..> CRUD module from field definitions`),l(` kick g controller <name> Standalone controller`),l(` kick g service <name> @Service() class`),l(` kick g middleware <name> Express middleware`),l(` kick g guard <name> Route guard (auth, roles, etc.)`),l(` kick g adapter <name> AppAdapter with lifecycle hooks`),l(` kick g dto <name> Zod DTO schema`),a===`cqrs`&&l(` kick g job <name> Queue job processor`),l(` kick g config Generate kick.config.ts`),l(``),l(`Add packages:`),l(` kick add <pkg> Install a KickJS package + peers`),l(` kick add --list Show all available packages`),l(``),l(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),l(``)}function Ot(e){return e}function kt(e){return k(e).replace(/-/g,`_`)}function At(t){let n=t.cwd??process.cwd(),r=t.projectRoot??e(n),i=t.pluralize??!0,a=D(t.name),o=O(t.name),s=k(t.name),c=kt(t.name),l={name:t.name,pascal:a,camel:o,kebab:s,snake:c,modulesDir:t.modulesDir??`src/modules`,cwd:n,projectRoot:r,args:t.args??[],flags:t.flags??{}};if(i){let e=A(s);l.pluralKebab=e,l.pluralPascal=D(e),l.pluralCamel=O(e)}return l}function jt(e,t){return a(e.cwd,t)}async function Mt(e){return import(v(e).href)}const Nt=new Map;async function Pt(e){let t=Nt.get(e);if(t)return t;let n=Ft(e);return Nt.set(e,n),n}async function Ft(e){let r=a(e,`package.json`);if(!o(r))return{generators:[],loaded:[],failed:[]};let i=It(JSON.parse(await u(r,`utf-8`))),s=t(a(e,`package.json`)),c=[],l=[],d=[];for(let e of i){let t;try{t=s.resolve(`${e}/package.json`)}catch{continue}let r;try{r=JSON.parse(await u(t,`utf-8`))}catch(t){d.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!r.kickjs?.generators)continue;let i=r.kickjs.generators,f=a(n(t),i);if(!o(f)){d.push({source:e,reason:`kickjs.generators points to missing file: ${i}`});continue}let p;try{p=await Mt(f)}catch(t){d.push({source:e,reason:`failed to import manifest: ${t}`});continue}let m=p.default;if(!Array.isArray(m)){d.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of m){if(!Lt(t)){d.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}c.push({source:e,spec:t})}l.push(e)}return{generators:c,loaded:l,failed:d}}function It(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Lt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Rt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Vt(r.spec,r.source,e,n);let i=Bt(await Pt(n),e.generatorName);return i?Vt(i.spec,i.source,e,n):null}async function zt(e,t=[]){let n=await Pt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function Bt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Vt(e,t,n,r){let i=At({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=jt(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}export{fe as A,b as B,me as C,T as D,D as E,oe as F,p as I,se as L,de as M,pe as N,ce as O,ue as P,C as R,A as S,k as T,q as _,Dt as a,Ge as b,xt as c,rt as d,nt as f,Ye as g,$e as h,Ot as i,le as j,E as k,bt as l,et as m,Rt as n,_t as o,tt as p,At as r,gt as s,zt as t,vt as u,Y as v,O as w,j as x,Ke as y,ee as z};
|
|
3072
|
-
//# sourceMappingURL=generator-extension-ChoCJW23.mjs.map
|