@forinda/kickjs-cli 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{run-plugins-GOyvsWi5.mjs → builtins-BIpoT6cb.mjs} +2 -2
- package/dist/cli.mjs +4086 -2
- package/dist/config-BQUzGk6m.mjs +12 -0
- package/dist/{config-BSo8gLtM.mjs.map → config-BQUzGk6m.mjs.map} +1 -1
- package/dist/{generator-extension-CEYm6tuj.mjs → generator-extension-Cd2DU_XX.mjs} +264 -28
- package/dist/generator-extension-Cd2DU_XX.mjs.map +1 -0
- package/dist/index.d.mts +100 -30
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -0
- package/dist/{plugin-CVRofuDz.mjs → plugin-B6ANfh7O.mjs} +3 -3
- package/dist/{plugin-CVRofuDz.mjs.map → plugin-B6ANfh7O.mjs.map} +1 -1
- package/dist/project-root-Dsxhm7OL.mjs +12 -0
- package/dist/project-root-Dsxhm7OL.mjs.map +1 -0
- package/dist/{rolldown-runtime-BrsfUx5e.mjs → rolldown-runtime-jjtMmVBF.mjs} +1 -1
- package/dist/{builtins-BpWIctor.mjs → run-plugins-DaO1FtZb.mjs} +90 -288
- package/dist/run-plugins-DaO1FtZb.mjs.map +1 -0
- package/dist/{typegen-DyXcnNCk.mjs → typegen-D-1Q9yBD.mjs} +4 -4
- package/dist/{typegen-DyXcnNCk.mjs.map → typegen-D-1Q9yBD.mjs.map} +1 -1
- package/dist/{types-CYw_hoZY.mjs → types-Du3p7CZ5.mjs} +2 -2
- package/dist/types-Du3p7CZ5.mjs.map +1 -0
- package/package.json +8 -7
- package/dist/builtins-5aWa9xTa.mjs +0 -3952
- package/dist/builtins-BpWIctor.mjs.map +0 -1
- package/dist/config-BSo8gLtM.mjs +0 -12
- package/dist/config-BefQBc0L.mjs +0 -11
- package/dist/generator-extension-CEYm6tuj.mjs.map +0 -1
- package/dist/plugin-By4fjCki.mjs +0 -11
- package/dist/typegen-CZMLNEJQ.mjs +0 -116
- package/dist/types-CYw_hoZY.mjs.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v5.
|
|
2
|
+
* @forinda/kickjs-cli v5.7.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4088 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{
|
|
11
|
+
import{createRequire as e}from"node:module";import{Command as t}from"commander";import{cpSync as n,existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,rmSync as s,statSync as c,writeFileSync as l}from"node:fs";import u,{basename as d,dirname as f,extname as p,isAbsolute as m,join as h,parse as g,relative as _,resolve as v,sep as y}from"node:path";import{fileURLToPath as b,pathToFileURL as x}from"node:url";import{execFileSync as ee,execSync as S,fork as te,spawn as ne,spawnSync as re}from"node:child_process";import{access as ie,copyFile as ae,mkdir as oe,readFile as C,readdir as se,rm as ce,stat as le,unlink as ue,writeFile as w}from"node:fs/promises";import*as T from"@clack/prompts";import E from"picocolors";import de from"pluralize";import{glob as fe,globSync as pe}from"glob";import{groupAssetKeys as me}from"@forinda/kickjs";import{arch as he,platform as ge,release as _e}from"node:os";import{detectCompositeReferences as ve,generate as ye,migrateDown as be,migrateLatest as xe,migrateRollback as Se,migrateStatus as Ce,migrateUp as we,renderSchemaSource as Te,resolveDbConfig as Ee}from"@forinda/kickjs-db";var De=Object.defineProperty,D=(e,t)=>{let n={};for(var r in e)De(n,r,{get:e[r],enumerable:!0});return t||De(n,Symbol.toStringTag,{value:`Module`}),n};function Oe(e,t,n){S(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function ke(e,t,n){let r=re(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}function Ae(e,t){if(!t?.commands?.length)return;let n=new Set(e.commands.map(e=>e.name()));for(let r of t.commands){if(n.has(r.name)){console.warn(` Warning: custom command '${r.name}' skipped — conflicts with a built-in command`);continue}je(e,r)}}function je(e,t){let n=e.command(t.name).description(t.description);if(t.aliases)for(let e of t.aliases)n.alias(e);n.allowUnknownOption(!0),n.argument(`[args...]`,`Additional arguments passed to the command`),n.action(e=>{let n=e.join(` `),r=Array.isArray(t.steps)?t.steps:[t.steps];for(let e of r){let r=n?`${e} ${n}`:e;console.log(` $ ${r}`);try{Oe(r)}catch{console.error(` Command failed: ${t.name}`),process.exitCode=1;return}}})}var Me=D({BUILTIN_REPO_TYPES:()=>Pe,PACKAGE_MANAGERS:()=>Ne,defineConfig:()=>Fe,loadKickConfig:()=>k,resolveModuleConfig:()=>O,resolveTokenScope:()=>Ie,validateAssetMap:()=>ze});const Ne=[`pnpm`,`npm`,`yarn`,`bun`],Pe=[`drizzle`,`inmemory`,`prisma`];function Fe(e){return e}function Ie(e,t){if(e?.tokenScope&&typeof e.tokenScope==`string`&&e.tokenScope.length>0){let t=Le(e.tokenScope);if(t.length>0)return t}try{let e=h(t,`package.json`);if(r(e)){let t=JSON.parse(a(e,`utf-8`));if(typeof t.name==`string`&&t.name.length>0){let e=t.name.match(/^@([^/]+)\//),n=Le(e?e[1]:t.name);if(n.length>0)return n}}}catch{}return`app`}function Le(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}function O(e){if(!e)return{};let t={dir:e.modules?.dir,repo:e.modules?.repo,schemaDir:e.modules?.schemaDir,pluralize:e.modules?.pluralize,prismaClientPath:e.modules?.prismaClientPath,style:e.modules?.style};return t.style!==void 0&&t.style!==`define`&&t.style!==`class`&&(console.warn(` Warning: modules.style '${t.style}' is not a valid value (expected 'define' or 'class'). Falling back to 'define'.`),t.style=`define`),t.repo&&typeof t.repo==`string`&&!Pe.includes(t.repo)&&console.warn(` Warning: modules.repo '${t.repo}' is not a built-in type (${Pe.join(`, `)}). It will generate a stub repository. Use { name: '${t.repo}' } to silence this warning.`),t}const Re=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];async function k(e){let{findProjectRoot:t}=await Promise.resolve().then(()=>bo),n=t(e);for(let e of Re){let t=h(n,e);try{await ie(t)}catch{continue}if(e.endsWith(`.json`)){let e=await C(t,`utf-8`);return JSON.parse(e)}if(e.endsWith(`.ts`)){let r;try{r=await import(`jiti`)}catch(t){let n=t instanceof Error?t.message:String(t);n.includes(`Cannot find package 'jiti'`)||n.includes(`ERR_MODULE_NOT_FOUND`)?console.warn(`Warning: Failed to load ${e} — 'jiti' is required for TypeScript configs. Run \`pnpm add -D jiti\` (or your package manager's equivalent), or rename the file to kick.config.js / kick.config.mjs / kick.config.json.`):console.warn(`Warning: Failed to initialize jiti for ${e}: ${n}`);continue}try{let e=await r.createJiti(n,{interopDefault:!0,fsCache:!1}).import(t,{default:!0}),i=ze(e,n);for(let e of i)console.warn(` Warning: ${e}`);return e}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}try{let{pathToFileURL:e}=await import(`node:url`),r=await import(e(t).href),i=r.default??r,a=ze(i,n);for(let e of a)console.warn(` Warning: ${e}`);return i}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}return null}function ze(e,t){let n=[];if(!e?.assetMap)return n;let i=v(t);for(let[a,o]of Object.entries(e.assetMap)){if(!a||a.includes(`/`)){n.push(`assetMap key '${a}' is invalid — must be a non-empty string without '/'`);continue}if(typeof o?.src!=`string`||o.src.length===0){n.push(`assetMap.${a} is missing a non-empty 'src' field`);continue}r(v(t,o.src))||n.push(`assetMap.${a}.src ('${o.src}') does not exist — typegen + build will fail`),o.dest&&Be(v(t,o.dest),i)&&n.push(`assetMap.${a}.dest ('${o.dest}') resolves outside the project root — refusing to copy`)}return n}function Be(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function A(e){return e}var Ve=class extends Error{constructor(e,t,n){super(`Two plugins registered the same ${e} '${t}': ${n.join(`, `)}. Plugins must use unique ${e} names.`),this.name=`KickPluginConflictError`}};function He(e,t=[]){let n=new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new Ve(`plugin`,t.name,[t.name,t.name])}let r=new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new Ve(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new Ve(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new Ve(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r=n?{generators:u,...n}:{cwd:process.cwd(),config:null,log:()=>{},generators:u};for(let n of e)n.register&&await n.register(t,r)}}}var Ue=D({mergeCliPlugins:()=>He});let We=!1;function j(e){We=e}const Ge=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function M(e,t){We||(await oe(f(e),{recursive:!0}),await w(e,t,`utf-8`),Ge.has(p(e))&&await qe(e,t).catch(()=>{}))}let N;async function Ke(t){if(N!==void 0)return N;try{N=await import(e(h(t,`package.json`)).resolve(`oxfmt`))}catch{N=null}return N}async function qe(e,t){let n=await Ke(process.cwd());if(!n)return;let r=await Ye(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await w(e,i.code,`utf-8`)}const Je=new Map;async function Ye(e){let t=f(e),n=t;if(Je.has(n))return Je.get(n);for(;;){let e=h(t,`.oxfmtrc.json`);if(r(e))try{let t=await C(e,`utf-8`),r=JSON.parse(t);return delete r.$schema,delete r.ignorePatterns,Je.set(n,r),r}catch{return Je.set(n,null),null}let i=f(t);if(i===t)return Je.set(n,null),null;t=i}}async function Xe(e){try{return await ie(e),!0}catch{return!1}}const Ze={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function Qe(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 $e(e,t,n,r=[]){let i={"@forinda/kickjs":Qe(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=Ze[e];t&&!i[t]&&(i[t]=Qe(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":Qe(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":Qe(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 et(){return`import { defineConfig } from 'vite'
|
|
12
|
+
import { resolve } from 'node:path'
|
|
13
|
+
import swc from 'unplugin-swc'
|
|
14
|
+
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
|
|
15
|
+
|
|
16
|
+
export default defineConfig({
|
|
17
|
+
oxc: false,
|
|
18
|
+
plugins: [
|
|
19
|
+
swc.vite(),
|
|
20
|
+
kickjsVitePlugin({ entry: 'src/index.ts' }),
|
|
21
|
+
// Watches .env files and triggers a full reload on change so the
|
|
22
|
+
// dev server picks up env tweaks without a manual restart.
|
|
23
|
+
envWatchPlugin(),
|
|
24
|
+
],
|
|
25
|
+
resolve: {
|
|
26
|
+
alias: {
|
|
27
|
+
'@': resolve(__dirname, 'src'),
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
ssr: {
|
|
31
|
+
// Don't bundle pino — its worker-thread transport needs Node.js resolution
|
|
32
|
+
// to find pino-pretty at runtime for colored log output
|
|
33
|
+
external: ['pino', 'pino-pretty'],
|
|
34
|
+
},
|
|
35
|
+
build: {
|
|
36
|
+
target: 'node20',
|
|
37
|
+
ssr: true,
|
|
38
|
+
outDir: 'dist',
|
|
39
|
+
sourcemap: true,
|
|
40
|
+
rollupOptions: {
|
|
41
|
+
input: resolve(__dirname, 'src/index.ts'),
|
|
42
|
+
output: { format: 'esm' },
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
`}function tt(){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 nt(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function rt(){return`# https://editorconfig.org
|
|
47
|
+
root = true
|
|
48
|
+
|
|
49
|
+
[*]
|
|
50
|
+
indent_style = space
|
|
51
|
+
indent_size = 2
|
|
52
|
+
end_of_line = lf
|
|
53
|
+
charset = utf-8
|
|
54
|
+
trim_trailing_whitespace = true
|
|
55
|
+
insert_final_newline = true
|
|
56
|
+
|
|
57
|
+
[*.md]
|
|
58
|
+
trim_trailing_whitespace = false
|
|
59
|
+
`}function it(){return`node_modules/
|
|
60
|
+
dist/
|
|
61
|
+
.env
|
|
62
|
+
coverage/
|
|
63
|
+
.DS_Store
|
|
64
|
+
*.tsbuildinfo
|
|
65
|
+
.kickjs/
|
|
66
|
+
`}function at(){return`# Auto-detect text files and normalise line endings to LF
|
|
67
|
+
* text=auto eol=lf
|
|
68
|
+
|
|
69
|
+
# Explicitly mark generated / binary files
|
|
70
|
+
*.png binary
|
|
71
|
+
*.jpg binary
|
|
72
|
+
*.jpeg binary
|
|
73
|
+
*.gif binary
|
|
74
|
+
*.ico binary
|
|
75
|
+
*.woff binary
|
|
76
|
+
*.woff2 binary
|
|
77
|
+
*.ttf binary
|
|
78
|
+
*.eot binary
|
|
79
|
+
|
|
80
|
+
# Lock files — treat as generated
|
|
81
|
+
pnpm-lock.yaml -diff linguist-generated
|
|
82
|
+
yarn.lock -diff linguist-generated
|
|
83
|
+
package-lock.json -diff linguist-generated
|
|
84
|
+
`}function ot(){return`PORT=3000
|
|
85
|
+
NODE_ENV=development
|
|
86
|
+
`}function st(){return`PORT=3000
|
|
87
|
+
NODE_ENV=development
|
|
88
|
+
`}function ct(){return`import { defineConfig } from 'vitest/config'
|
|
89
|
+
import swc from 'unplugin-swc'
|
|
90
|
+
|
|
91
|
+
export default defineConfig({
|
|
92
|
+
plugins: [swc.vite()],
|
|
93
|
+
test: {
|
|
94
|
+
globals: true,
|
|
95
|
+
environment: 'node',
|
|
96
|
+
include: ['src/**/*.test.ts'],
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
`}function lt(e,t,n,r=[]){switch(t){case`cqrs`:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
|
|
100
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
101
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
102
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
103
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
104
|
+
import './config'
|
|
105
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
106
|
+
// import { WsAdapter } from '@forinda/kickjs-ws'
|
|
107
|
+
// import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
|
|
108
|
+
${t.length?t.join(`
|
|
109
|
+
`)+`
|
|
110
|
+
`:``}import { modules } from './modules'
|
|
111
|
+
|
|
112
|
+
// Export the app for the Vite plugin (dev mode)
|
|
113
|
+
export const app = await bootstrap({
|
|
114
|
+
modules,${t.length?`\n adapters: [\n${i.join(`
|
|
115
|
+
`)}\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],`:`
|
|
116
|
+
adapters: [
|
|
117
|
+
// Uncomment for WebSocket support:
|
|
118
|
+
// WsAdapter(),
|
|
119
|
+
// Uncomment when Redis is available:
|
|
120
|
+
// QueueAdapter({
|
|
121
|
+
// provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
|
|
122
|
+
// }),
|
|
123
|
+
],`}
|
|
124
|
+
})
|
|
125
|
+
`}case`minimal`:{let t=[],i=[];return r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({ info: { title: '${e}', version: '${n}' } }),`)),r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),`import 'reflect-metadata'
|
|
126
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
127
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
128
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
129
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
130
|
+
import './config'
|
|
131
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
132
|
+
${t.length?t.join(`
|
|
133
|
+
`)+`
|
|
134
|
+
`:``}import { modules } from './modules'
|
|
135
|
+
|
|
136
|
+
// Export the app for the Vite plugin (dev mode)
|
|
137
|
+
export const app = await bootstrap({ modules${i.length?`,\n adapters: [\n${i.join(`
|
|
138
|
+
`)}\n ]`:``} })
|
|
139
|
+
`}default:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
|
|
140
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
141
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
142
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
143
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
144
|
+
import './config'
|
|
145
|
+
import express from 'express'
|
|
146
|
+
import {
|
|
147
|
+
bootstrap,
|
|
148
|
+
requestId,
|
|
149
|
+
requestLogger,
|
|
150
|
+
helmet,
|
|
151
|
+
cors,
|
|
152
|
+
} from '@forinda/kickjs'
|
|
153
|
+
${t.length?t.join(`
|
|
154
|
+
`)+`
|
|
155
|
+
`:``}import { modules } from './modules'
|
|
156
|
+
|
|
157
|
+
// Export the app for the Vite plugin (dev mode)
|
|
158
|
+
export const app = await bootstrap({
|
|
159
|
+
modules,${i.length?`\n adapters: [\n${i.join(`
|
|
160
|
+
`)}\n ],`:``}
|
|
161
|
+
middleware: [
|
|
162
|
+
helmet(),
|
|
163
|
+
cors({ origin: '*' }),
|
|
164
|
+
requestId(),
|
|
165
|
+
requestLogger(),
|
|
166
|
+
express.json(),
|
|
167
|
+
],
|
|
168
|
+
})
|
|
169
|
+
`}}}function ut(){return`import { defineModules } from '@forinda/kickjs'
|
|
170
|
+
import { HelloModule } from './hello/hello.module'
|
|
171
|
+
|
|
172
|
+
// Remove HelloModule and run: kick g module <name>
|
|
173
|
+
// \`defineModules()\` returns a chainable list — \`kick g module\` appends
|
|
174
|
+
// \`.mount(NewModule())\` to the chain on every generation.
|
|
175
|
+
export const modules = defineModules().mount(HelloModule())
|
|
176
|
+
`}function dt(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
|
|
177
|
+
import { z } from 'zod'
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Project environment schema.
|
|
181
|
+
*
|
|
182
|
+
* Extend the base schema with your application's variables. The
|
|
183
|
+
* default export is the contract \`kick typegen\` reads to populate
|
|
184
|
+
* the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
|
|
185
|
+
* autocomplete and \`process.env.FOO\` typed.
|
|
186
|
+
*
|
|
187
|
+
* @example
|
|
188
|
+
* DATABASE_URL: z.string().url(),
|
|
189
|
+
* JWT_SECRET: z.string().min(32),
|
|
190
|
+
* REDIS_URL: z.string().url().optional(),
|
|
191
|
+
*/
|
|
192
|
+
const envSchema = defineEnv((base) =>
|
|
193
|
+
base.extend({
|
|
194
|
+
// DATABASE_URL: z.string().url(),
|
|
195
|
+
}),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* IMPORTANT — side effect: register the schema with kickjs's env cache
|
|
200
|
+
* **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
|
|
201
|
+
* this cache, and they will fall back to the base schema (or undefined)
|
|
202
|
+
* if no extended schema has been registered before they're resolved.
|
|
203
|
+
*
|
|
204
|
+
* As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
|
|
205
|
+
* top — before \`bootstrap()\` runs — every controller and service in the
|
|
206
|
+
* app sees the typed extended values.
|
|
207
|
+
*/
|
|
208
|
+
export const env = loadEnv(envSchema)
|
|
209
|
+
|
|
210
|
+
export default envSchema
|
|
211
|
+
`}function ft(){return`import { Service } from '@forinda/kickjs'
|
|
212
|
+
|
|
213
|
+
@Service()
|
|
214
|
+
export class HelloService {
|
|
215
|
+
greet(name: string) {
|
|
216
|
+
return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
healthCheck() {
|
|
220
|
+
return { status: 'ok', uptime: process.uptime() }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
`}function pt(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
|
|
224
|
+
import { HelloService } from './hello.service'
|
|
225
|
+
|
|
226
|
+
// \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
|
|
227
|
+
// \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
|
|
228
|
+
// scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
|
|
229
|
+
// See https://forinda.github.io/kick-js/guide/typegen.
|
|
230
|
+
|
|
231
|
+
@Controller()
|
|
232
|
+
export class HelloController {
|
|
233
|
+
@Autowired() private readonly helloService!: HelloService
|
|
234
|
+
|
|
235
|
+
@Get('/')
|
|
236
|
+
index(ctx: Ctx<KickRoutes.HelloController['index']>) {
|
|
237
|
+
ctx.json(this.helloService.greet('World'))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
@Get('/health')
|
|
241
|
+
health(ctx: Ctx<KickRoutes.HelloController['health']>) {
|
|
242
|
+
ctx.json(this.helloService.healthCheck())
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
`}function mt(){return`import { defineModule } from '@forinda/kickjs'
|
|
246
|
+
import { HelloController } from './hello.controller'
|
|
247
|
+
|
|
248
|
+
export const HelloModule = defineModule({
|
|
249
|
+
name: 'HelloModule',
|
|
250
|
+
build: () => ({
|
|
251
|
+
// \`register(container)\` is optional — only implement it when you need
|
|
252
|
+
// to bind a token to a concrete implementation, e.g.
|
|
253
|
+
// register(container) {
|
|
254
|
+
// container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
|
|
255
|
+
// }
|
|
256
|
+
// The HelloService uses @Service() so the decorator handles registration.
|
|
257
|
+
|
|
258
|
+
routes() {
|
|
259
|
+
return {
|
|
260
|
+
path: '/hello',
|
|
261
|
+
controller: HelloController,
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
}),
|
|
265
|
+
})
|
|
266
|
+
`}function ht(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
|
|
267
|
+
|
|
268
|
+
export default defineConfig({
|
|
269
|
+
pattern: '${e}',
|
|
270
|
+
// Pinned so \`kick add\` and other dep-installing commands always use the
|
|
271
|
+
// project's intended package manager, regardless of which lockfile exists.
|
|
272
|
+
packageManager: '${n}',
|
|
273
|
+
modules: {
|
|
274
|
+
dir: 'src/modules',
|
|
275
|
+
repo: ${[`drizzle`,`inmemory`,`prisma`].includes(t)?`'${t}'`:`{ name: '${t}' }`},
|
|
276
|
+
pluralize: true,
|
|
277
|
+
},
|
|
278
|
+
|
|
279
|
+
// \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
|
|
280
|
+
// resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
|
|
281
|
+
// Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
|
|
282
|
+
typegen: {
|
|
283
|
+
schemaValidator: 'zod',
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
commands: [
|
|
287
|
+
{
|
|
288
|
+
name: 'test',
|
|
289
|
+
description: 'Run tests with Vitest',
|
|
290
|
+
steps: 'npx vitest run',
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
name: 'format',
|
|
294
|
+
description: 'Format code with Prettier',
|
|
295
|
+
steps: 'npx prettier --write src/',
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
name: 'format:check',
|
|
299
|
+
description: 'Check formatting without writing',
|
|
300
|
+
steps: 'npx prettier --check src/',
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
name: 'ci:check',
|
|
304
|
+
description: 'Run typecheck + format check',
|
|
305
|
+
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
306
|
+
aliases: ['verify'],
|
|
307
|
+
},
|
|
308
|
+
],
|
|
309
|
+
})
|
|
310
|
+
`}function gt(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}
|
|
311
|
+
|
|
312
|
+
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.
|
|
313
|
+
|
|
314
|
+
## Getting Started
|
|
315
|
+
|
|
316
|
+
\`\`\`bash
|
|
317
|
+
${n} install
|
|
318
|
+
kick dev
|
|
319
|
+
\`\`\`
|
|
320
|
+
|
|
321
|
+
## Scripts
|
|
322
|
+
|
|
323
|
+
| Command | Description |
|
|
324
|
+
|---|---|
|
|
325
|
+
| \`kick dev\` | Start dev server with Vite HMR |
|
|
326
|
+
| \`kick build\` | Production build |
|
|
327
|
+
| \`kick start\` | Run production build |
|
|
328
|
+
| \`${n} run test\` | Run tests with Vitest |
|
|
329
|
+
| \`kick g module <name>\` | Generate a DDD module |
|
|
330
|
+
| \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
|
|
331
|
+
| \`kick add <package>\` | Add a KickJS package |
|
|
332
|
+
|
|
333
|
+
## Project Structure
|
|
334
|
+
|
|
335
|
+
\`\`\`
|
|
336
|
+
src/
|
|
337
|
+
├── index.ts # Application entry point
|
|
338
|
+
├── modules/ # Feature modules (controllers, services, repos)
|
|
339
|
+
│ └── index.ts # Module registry
|
|
340
|
+
└── ...
|
|
341
|
+
\`\`\`
|
|
342
|
+
|
|
343
|
+
## Packages
|
|
344
|
+
|
|
345
|
+
${i.map(e=>`- \`${e}\``).join(`
|
|
346
|
+
`)}
|
|
347
|
+
|
|
348
|
+
## Adding Features
|
|
349
|
+
|
|
350
|
+
\`\`\`bash
|
|
351
|
+
kick add auth # Authentication (JWT, API key, OAuth)
|
|
352
|
+
kick add swagger # OpenAPI documentation
|
|
353
|
+
kick add ws # WebSocket support
|
|
354
|
+
kick add queue # Background job processing
|
|
355
|
+
kick add --list # Show all available packages
|
|
356
|
+
\`\`\`
|
|
357
|
+
|
|
358
|
+
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.
|
|
359
|
+
|
|
360
|
+
## Environment Variables
|
|
361
|
+
|
|
362
|
+
Copy \`.env.example\` to \`.env\` and configure:
|
|
363
|
+
|
|
364
|
+
| Variable | Default | Description |
|
|
365
|
+
|---|---|---|
|
|
366
|
+
| \`PORT\` | \`3000\` | Server port |
|
|
367
|
+
| \`NODE_ENV\` | \`development\` | Environment |
|
|
368
|
+
|
|
369
|
+
## Learn More
|
|
370
|
+
|
|
371
|
+
- [KickJS Documentation](https://forinda.github.io/kick-js/)
|
|
372
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
373
|
+
`}function _t(e,t,n){return`# CLAUDE.md — ${e}
|
|
374
|
+
|
|
375
|
+
**Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
|
|
376
|
+
reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
|
|
377
|
+
project conventions, structure, decorator patterns, env wiring, CLI
|
|
378
|
+
generators, every gotcha.
|
|
379
|
+
|
|
380
|
+
**Then browse \`./.agents/skills/\`.** Each subdirectory is a single
|
|
381
|
+
task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
|
|
382
|
+
\`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
|
|
383
|
+
with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
|
|
384
|
+
The structure follows the Claude Code skills convention — agents that
|
|
385
|
+
auto-load skills from \`.agents/skills/\` will pick each up by its
|
|
386
|
+
frontmatter. Use this directory as the playbook when executing common
|
|
387
|
+
KickJS workflows.
|
|
388
|
+
|
|
389
|
+
This file is a thin Claude-specific layer on top of those two; when
|
|
390
|
+
they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
|
|
391
|
+
authoritative and flag the discrepancy.
|
|
392
|
+
|
|
393
|
+
## Why \`.agents/\` + this thin pointer
|
|
394
|
+
|
|
395
|
+
\`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
|
|
396
|
+
Copilot, Aider, …) — one canonical source so the prose doesn't drift
|
|
397
|
+
across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
|
|
398
|
+
project context on each conversation, so it stays at the project root.
|
|
399
|
+
Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
|
|
400
|
+
out-of-sync copies of the same content. Per-agent files
|
|
401
|
+
(\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
|
|
402
|
+
\`AGENTS.md\` for tool-specific notes that don't belong in the shared
|
|
403
|
+
prose.
|
|
404
|
+
|
|
405
|
+
## Claude-specific notes
|
|
406
|
+
|
|
407
|
+
- **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
|
|
408
|
+
to refresh project memory if AGENTS.md changes substantially.
|
|
409
|
+
- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
|
|
410
|
+
- **Persistent memory** — Claude maintains user/feedback/project/
|
|
411
|
+
reference memories under \`.claude/memory/\`. If you ask for
|
|
412
|
+
something that contradicts a remembered preference, Claude flags
|
|
413
|
+
it before acting; corrections update memory automatically.
|
|
414
|
+
- **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
|
|
415
|
+
or background work. Useful for "wait for the deploy then open a
|
|
416
|
+
cleanup PR" or "every Monday triage the issue board" patterns.
|
|
417
|
+
|
|
418
|
+
## Quick reference (full version in .agents/AGENTS.md)
|
|
419
|
+
|
|
420
|
+
\`\`\`bash
|
|
421
|
+
${n} install # Install dependencies
|
|
422
|
+
kick dev # Dev server with HMR + typegen
|
|
423
|
+
kick build && kick start # Production
|
|
424
|
+
${n} run test # Vitest
|
|
425
|
+
${n} run typecheck # tsc --noEmit
|
|
426
|
+
${n} run format # Prettier
|
|
427
|
+
\`\`\`
|
|
428
|
+
|
|
429
|
+
## v4 framework reminders
|
|
430
|
+
|
|
431
|
+
When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
|
|
432
|
+
|
|
433
|
+
- **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
|
|
434
|
+
- **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
|
|
435
|
+
- **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.
|
|
436
|
+
- **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
|
|
437
|
+
- **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.
|
|
438
|
+
- **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).
|
|
439
|
+
- **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.
|
|
440
|
+
- **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
|
|
441
|
+
- **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
|
|
442
|
+
- **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.
|
|
443
|
+
- **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\`.
|
|
444
|
+
- **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.
|
|
445
|
+
|
|
446
|
+
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
|
|
447
|
+
`}function vt(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
|
|
448
|
+
|
|
449
|
+
This guide is the **canonical, multi-agent reference** for this KickJS
|
|
450
|
+
application — Claude, Copilot, Codex, Gemini, etc. all read it first.
|
|
451
|
+
Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
|
|
452
|
+
add tool-specific affordances on top.
|
|
453
|
+
|
|
454
|
+
## Before You Start
|
|
455
|
+
|
|
456
|
+
1. Run \`${n} install\` to install dependencies
|
|
457
|
+
2. Run \`kick dev\` to verify the app starts
|
|
458
|
+
3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
|
|
459
|
+
|
|
460
|
+
## v4 Conventions (don't skip)
|
|
461
|
+
|
|
462
|
+
KickJS v4 made a handful of structural changes from v3. Internalise these
|
|
463
|
+
before generating or modifying code — they are the source of most agent
|
|
464
|
+
mistakes:
|
|
465
|
+
|
|
466
|
+
- **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
|
|
467
|
+
|
|
468
|
+
\`\`\`ts
|
|
469
|
+
export const MyAdapter = defineAdapter<MyOptions>({
|
|
470
|
+
name: 'MyAdapter',
|
|
471
|
+
defaults: { ... },
|
|
472
|
+
build: (config) => ({
|
|
473
|
+
beforeMount({ app }) { /* ... */ },
|
|
474
|
+
afterStart({ server }) { /* ... */ },
|
|
475
|
+
}),
|
|
476
|
+
})
|
|
477
|
+
\`\`\`
|
|
478
|
+
|
|
479
|
+
- **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
|
|
480
|
+
|
|
481
|
+
- **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
|
|
482
|
+
the key segment is **PascalCase** (the regex enforces both):
|
|
483
|
+
|
|
484
|
+
\`\`\`ts
|
|
485
|
+
const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
|
|
486
|
+
const DB = createToken<Database>('app/Db/connection')
|
|
487
|
+
\`\`\`
|
|
488
|
+
|
|
489
|
+
The \`kick/\` prefix is reserved for first-party packages; this project
|
|
490
|
+
owns its own scope (\`app/\`, your domain name, etc.).
|
|
491
|
+
|
|
492
|
+
- **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
|
|
493
|
+
the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
|
|
494
|
+
is a v3 leftover; the linter and codegen reject it.
|
|
495
|
+
|
|
496
|
+
- **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
|
|
497
|
+
side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
|
|
498
|
+
import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
|
|
499
|
+
returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
|
|
500
|
+
(Zod coercion + defaults silently skipped).
|
|
501
|
+
|
|
502
|
+
- **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
|
|
503
|
+
HMR contract at the top of "Module Pattern" below. The CLI enforces this;
|
|
504
|
+
hand-rolled files must too.
|
|
505
|
+
|
|
506
|
+
- **Assets** — drop new template files into \`src/templates/<namespace>/\`
|
|
507
|
+
(or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
|
|
508
|
+
\`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
|
|
509
|
+
no manual build step.
|
|
510
|
+
|
|
511
|
+
- **Context over \`@Middleware()\`** — when a middleware's only job is to
|
|
512
|
+
populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
|
|
513
|
+
(HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
|
|
514
|
+
Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
|
|
515
|
+
Reserve \`@Middleware()\` for response short-circuit / stream mutation /
|
|
516
|
+
pre-route-matching work.
|
|
517
|
+
|
|
518
|
+
Two ground rules around the data flow — both stem from the fact that
|
|
519
|
+
every per-request stage gets its OWN \`RequestContext\` instance, all
|
|
520
|
+
reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
|
|
521
|
+
- **\`resolve\` and \`onError\` must RETURN the value.** The runner
|
|
522
|
+
writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
|
|
523
|
+
property assignment (\`ctx.tenant = …\`) sticks to the contributor
|
|
524
|
+
instance only — the handler instance never sees it.
|
|
525
|
+
- **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
|
|
526
|
+
\`getRequestValue(key)\` from a service that has no \`ctx\` reference
|
|
527
|
+
— typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
|
|
528
|
+
Express request is shared; bespoke property assignments don't.
|
|
529
|
+
|
|
530
|
+
- **Test isolation** — default to \`Container.create()\` for fresh DI state.
|
|
531
|
+
Never \`new Container()\` and never \`getInstance().reset()\` — both leak
|
|
532
|
+
registrations between tests.
|
|
533
|
+
|
|
534
|
+
\`\`\`ts
|
|
535
|
+
const container = Container.create()
|
|
536
|
+
// ... register test-scoped providers, run, discard
|
|
537
|
+
\`\`\`
|
|
538
|
+
|
|
539
|
+
- **Bootstrap export** — \`src/index.ts\` MUST end with
|
|
540
|
+
\`export const app = await bootstrap({ ... })\`. The Vite plugin imports
|
|
541
|
+
the named \`app\` symbol to drive HMR module swaps; testing helpers
|
|
542
|
+
(\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
|
|
543
|
+
the \`export\` and \`kick dev\` will silently fall back to a full restart
|
|
544
|
+
on every save while \`createTestApp\` complains about a missing handle.
|
|
545
|
+
|
|
546
|
+
- **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
|
|
547
|
+
adapters in dedicated folders and re-export aggregated arrays. Do **not**
|
|
548
|
+
inline registration in the entry file:
|
|
549
|
+
|
|
550
|
+
\`\`\`ts
|
|
551
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
552
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
553
|
+
// OR with \`modules.style: 'class'\`:
|
|
554
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
555
|
+
|
|
556
|
+
// src/middleware/index.ts
|
|
557
|
+
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
558
|
+
|
|
559
|
+
// src/plugins/index.ts
|
|
560
|
+
export const plugins = [MetricsPlugin(), AuditPlugin()]
|
|
561
|
+
|
|
562
|
+
// src/adapters/index.ts
|
|
563
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
564
|
+
\`\`\`
|
|
565
|
+
|
|
566
|
+
\`\`\`ts
|
|
567
|
+
// src/index.ts — stays small; one import per category
|
|
568
|
+
import 'reflect-metadata'
|
|
569
|
+
import './config'
|
|
570
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
571
|
+
import { modules } from './modules'
|
|
572
|
+
import { middleware } from './middleware'
|
|
573
|
+
import { plugins } from './plugins'
|
|
574
|
+
import { adapters } from './adapters'
|
|
575
|
+
|
|
576
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
577
|
+
\`\`\`
|
|
578
|
+
|
|
579
|
+
This keeps the entry file diff-friendly, scales to dozens of modules
|
|
580
|
+
without git churn, and lets each domain own its own registration list.
|
|
581
|
+
The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
|
|
582
|
+
\`kick g adapter\`) follow this layout — manual additions should too.
|
|
583
|
+
|
|
584
|
+
Everything else (controllers, services, modules, RequestContext API, generators,
|
|
585
|
+
package additions, env access patterns, troubleshooting) is detailed below.
|
|
586
|
+
|
|
587
|
+
## Where to Find Things
|
|
588
|
+
|
|
589
|
+
### Application Structure
|
|
590
|
+
|
|
591
|
+
| What | Where |
|
|
592
|
+
|------|-------|
|
|
593
|
+
| Entry point | \`src/index.ts\` |
|
|
594
|
+
| Module registry | \`src/modules/index.ts\` |
|
|
595
|
+
| Feature modules | \`src/modules/<module-name>/\` |
|
|
596
|
+
| **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
|
|
597
|
+
| Env values | \`.env\` |
|
|
598
|
+
| Env schema (Zod) | \`src/config/index.ts\` |
|
|
599
|
+
| TypeScript config | \`tsconfig.json\` |
|
|
600
|
+
| Vite config (HMR) | \`vite.config.ts\` |
|
|
601
|
+
| Vitest config | \`vitest.config.ts\` |
|
|
602
|
+
| Prettier config | \`.prettierrc\` |
|
|
603
|
+
| CLI config | \`kick.config.ts\` |
|
|
604
|
+
|
|
605
|
+
### Module Pattern (${t.toUpperCase()})
|
|
606
|
+
|
|
607
|
+
> **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.
|
|
608
|
+
|
|
609
|
+
Each module in \`src/modules/<name>/\` typically contains:
|
|
610
|
+
|
|
611
|
+
${t===`ddd`?`\`\`\`
|
|
612
|
+
<name>/
|
|
613
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
614
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
615
|
+
├── <name>.repository.ts # Data access (@Repository)
|
|
616
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
617
|
+
├── <name>.entity.ts # Domain entity (optional)
|
|
618
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
619
|
+
\`\`\`
|
|
620
|
+
`:t===`cqrs`?`\`\`\`
|
|
621
|
+
<name>/
|
|
622
|
+
├── commands/ # Write operations
|
|
623
|
+
│ ├── create-<name>.command.ts
|
|
624
|
+
│ └── create-<name>.handler.ts
|
|
625
|
+
├── queries/ # Read operations
|
|
626
|
+
│ ├── get-<name>.query.ts
|
|
627
|
+
│ └── get-<name>.handler.ts
|
|
628
|
+
├── events/ # Domain events
|
|
629
|
+
│ └── <name>-created.event.ts
|
|
630
|
+
├── <name>.controller.ts # HTTP routes
|
|
631
|
+
├── <name>.repository.ts # Data access
|
|
632
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
633
|
+
\`\`\`
|
|
634
|
+
`:t===`rest`?`\`\`\`
|
|
635
|
+
<name>/
|
|
636
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
637
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
638
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
639
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
640
|
+
\`\`\`
|
|
641
|
+
`:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
|
|
642
|
+
|
|
643
|
+
## Checklist: Adding a Feature
|
|
644
|
+
|
|
645
|
+
### New Module (Recommended)
|
|
646
|
+
|
|
647
|
+
Use the CLI generator for consistency:
|
|
648
|
+
|
|
649
|
+
\`\`\`bash
|
|
650
|
+
kick g module <name> # Generate full module
|
|
651
|
+
# or
|
|
652
|
+
kick g scaffold <name> <fields> # Generate CRUD from fields
|
|
653
|
+
\`\`\`
|
|
654
|
+
|
|
655
|
+
Then:
|
|
656
|
+
- [ ] Review generated files in \`src/modules/<name>/\`
|
|
657
|
+
- [ ] Verify module is registered in \`src/modules/index.ts\`
|
|
658
|
+
- [ ] Update DTOs in \`<name>.dto.ts\` if needed
|
|
659
|
+
- [ ] Implement business logic in \`<name>.service.ts\`
|
|
660
|
+
- [ ] Run \`kick dev\` to test with HMR
|
|
661
|
+
- [ ] Write tests in \`<name>.test.ts\`
|
|
662
|
+
|
|
663
|
+
### Manual Controller
|
|
664
|
+
|
|
665
|
+
If not using generators:
|
|
666
|
+
|
|
667
|
+
- [ ] Create \`src/modules/<name>/<name>.controller.ts\`
|
|
668
|
+
- [ ] Add \`@Controller()\` decorator
|
|
669
|
+
- [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
|
|
670
|
+
- [ ] 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\`.
|
|
671
|
+
- [ ] 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.
|
|
672
|
+
- [ ] Test with \`kick dev\`
|
|
673
|
+
|
|
674
|
+
### Manual Service
|
|
675
|
+
|
|
676
|
+
- [ ] Create \`src/modules/<name>/<name>.service.ts\`
|
|
677
|
+
- [ ] Add \`@Service()\` decorator
|
|
678
|
+
- [ ] Inject dependencies with \`@Autowired()\`
|
|
679
|
+
- [ ] Inject via \`@Autowired()\` where needed
|
|
680
|
+
- [ ] Write unit tests
|
|
681
|
+
|
|
682
|
+
### New Middleware
|
|
683
|
+
|
|
684
|
+
- [ ] Create \`src/middleware/<name>.middleware.ts\`
|
|
685
|
+
- [ ] Export middleware function (Express format)
|
|
686
|
+
- [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
|
|
687
|
+
- [ ] Test with sample requests
|
|
688
|
+
|
|
689
|
+
### Adding a Package
|
|
690
|
+
|
|
691
|
+
Use \`kick add\` to install KickJS packages with correct peer dependencies:
|
|
692
|
+
|
|
693
|
+
- [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
|
|
694
|
+
- [ ] Follow package-specific setup in terminal output
|
|
695
|
+
- [ ] Update \`src/index.ts\` to register adapter (if needed)
|
|
696
|
+
- [ ] Configure environment variables in \`.env\`
|
|
697
|
+
- [ ] Test integration with \`kick dev\`
|
|
698
|
+
|
|
699
|
+
## Common Tasks
|
|
700
|
+
|
|
701
|
+
### Generate CRUD Module
|
|
702
|
+
|
|
703
|
+
\`\`\`bash
|
|
704
|
+
kick g scaffold user name:string email:string:optional age:number
|
|
705
|
+
\`\`\`
|
|
706
|
+
|
|
707
|
+
Append \`:optional\` for optional fields (shell-safe, no quoting needed).
|
|
708
|
+
Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
|
|
709
|
+
|
|
710
|
+
This creates a full CRUD module with:
|
|
711
|
+
- Controller with GET, POST, PUT, DELETE routes
|
|
712
|
+
- Service with business logic
|
|
713
|
+
- Repository with data access
|
|
714
|
+
- DTOs with Zod validation
|
|
715
|
+
|
|
716
|
+
### Add Authentication
|
|
717
|
+
|
|
718
|
+
\`\`\`bash
|
|
719
|
+
kick add auth
|
|
720
|
+
\`\`\`
|
|
721
|
+
|
|
722
|
+
Then configure in \`src/index.ts\`:
|
|
723
|
+
|
|
724
|
+
\`\`\`ts
|
|
725
|
+
import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
|
|
726
|
+
|
|
727
|
+
bootstrap({
|
|
728
|
+
modules,
|
|
729
|
+
adapters: [
|
|
730
|
+
AuthAdapter({
|
|
731
|
+
strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
|
|
732
|
+
}),
|
|
733
|
+
],
|
|
734
|
+
})
|
|
735
|
+
\`\`\`
|
|
736
|
+
|
|
737
|
+
### Add Database (Prisma)
|
|
738
|
+
|
|
739
|
+
\`\`\`bash
|
|
740
|
+
kick add prisma
|
|
741
|
+
${n} install prisma @prisma/client
|
|
742
|
+
npx prisma init
|
|
743
|
+
# Edit prisma/schema.prisma
|
|
744
|
+
npx prisma migrate dev --name init
|
|
745
|
+
kick g module user --repo prisma
|
|
746
|
+
\`\`\`
|
|
747
|
+
|
|
748
|
+
### Add WebSocket Support
|
|
749
|
+
|
|
750
|
+
\`\`\`bash
|
|
751
|
+
kick add ws
|
|
752
|
+
\`\`\`
|
|
753
|
+
|
|
754
|
+
Then add adapter in \`src/index.ts\`:
|
|
755
|
+
|
|
756
|
+
\`\`\`ts
|
|
757
|
+
import { WsAdapter } from '@forinda/kickjs-ws'
|
|
758
|
+
|
|
759
|
+
bootstrap({
|
|
760
|
+
modules,
|
|
761
|
+
adapters: [WsAdapter()],
|
|
762
|
+
})
|
|
763
|
+
\`\`\`
|
|
764
|
+
|
|
765
|
+
Create WebSocket controller:
|
|
766
|
+
|
|
767
|
+
\`\`\`bash
|
|
768
|
+
kick g controller chat --ws
|
|
769
|
+
\`\`\`
|
|
770
|
+
|
|
771
|
+
## Testing Guidelines
|
|
772
|
+
|
|
773
|
+
All tests use Vitest:
|
|
774
|
+
|
|
775
|
+
\`\`\`ts
|
|
776
|
+
import { describe, it, expect, beforeEach } from 'vitest'
|
|
777
|
+
import { Container } from '@forinda/kickjs'
|
|
778
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
779
|
+
|
|
780
|
+
describe('UserController', () => {
|
|
781
|
+
it('should return users', async () => {
|
|
782
|
+
// Container.create() — isolated DI state per test, never new Container()
|
|
783
|
+
// and never getInstance().reset() (both leak registrations between tests).
|
|
784
|
+
const container = Container.create()
|
|
785
|
+
const app = await createTestApp([UserModule], { container })
|
|
786
|
+
const res = await app.get('/users')
|
|
787
|
+
|
|
788
|
+
expect(res.status).toBe(200)
|
|
789
|
+
expect(res.body).toHaveProperty('users')
|
|
790
|
+
})
|
|
791
|
+
})
|
|
792
|
+
\`\`\`
|
|
793
|
+
|
|
794
|
+
Run tests:
|
|
795
|
+
- \`${n} run test\` — run all tests once
|
|
796
|
+
- \`${n} run test:watch\` — watch mode
|
|
797
|
+
- Individual file: \`${n} run test src/modules/user/user.test.ts\`
|
|
798
|
+
|
|
799
|
+
## Environment Variables
|
|
800
|
+
|
|
801
|
+
Schema is declared in \`src/config/index.ts\` (extends the base
|
|
802
|
+
\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
|
|
803
|
+
with kickjs at module load. \`src/index.ts\` imports it via
|
|
804
|
+
\`import './config'\` **before** \`bootstrap()\` so the cache is populated
|
|
805
|
+
in time for DI. Add new keys to the schema, drop their values into
|
|
806
|
+
\`.env\`, and they're typed everywhere.
|
|
807
|
+
|
|
808
|
+
Access patterns:
|
|
809
|
+
|
|
810
|
+
1. **@Value() decorator** (recommended for known-at-construction keys):
|
|
811
|
+
\`\`\`ts
|
|
812
|
+
@Value('DATABASE_URL')
|
|
813
|
+
private dbUrl!: string
|
|
814
|
+
\`\`\`
|
|
815
|
+
|
|
816
|
+
2. **ConfigService** (recommended for dynamic / method-scoped access):
|
|
817
|
+
\`\`\`ts
|
|
818
|
+
@Autowired()
|
|
819
|
+
private config!: ConfigService
|
|
820
|
+
|
|
821
|
+
const port = this.config.get('PORT') // typed: number
|
|
822
|
+
\`\`\`
|
|
823
|
+
|
|
824
|
+
3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
|
|
825
|
+
\`\`\`ts
|
|
826
|
+
import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
|
|
827
|
+
|
|
828
|
+
const env = loadEnv(schema) // Parse + validate all vars
|
|
829
|
+
const port = getEnv('PORT') // Single value lookup
|
|
830
|
+
reloadEnv() // Re-read .env from disk
|
|
831
|
+
resetEnvCache() // Full reset (for tests)
|
|
832
|
+
\`\`\`
|
|
833
|
+
|
|
834
|
+
4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
|
|
835
|
+
coercion and the typed \`KickEnv\` registry.
|
|
836
|
+
|
|
837
|
+
> **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
|
|
838
|
+
> If the schema is not registered before DI runs, \`config.get()\`
|
|
839
|
+
> returns \`undefined\` for user keys (the base shape only) and
|
|
840
|
+
> \`@Value()\` only works because of its raw \`process.env\` fallback —
|
|
841
|
+
> Zod coercion + schema defaults are silently skipped.
|
|
842
|
+
|
|
843
|
+
## Standalone Utilities (No DI Required)
|
|
844
|
+
|
|
845
|
+
These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
|
|
846
|
+
|
|
847
|
+
| Utility | Import | Example |
|
|
848
|
+
|---------|--------|---------|
|
|
849
|
+
| \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
|
|
850
|
+
| \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
|
|
851
|
+
| \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
|
|
852
|
+
| \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
|
|
853
|
+
| \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
|
|
854
|
+
| \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
|
|
855
|
+
| \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
|
|
856
|
+
| \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
|
|
857
|
+
| \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
|
|
858
|
+
|
|
859
|
+
## Key Decorators
|
|
860
|
+
|
|
861
|
+
### HTTP Routes
|
|
862
|
+
| Decorator | Purpose |
|
|
863
|
+
|-----------|---------|
|
|
864
|
+
| \`@Controller()\` | Define route prefix |
|
|
865
|
+
| \`@Get('/'), @Post('/')\` | HTTP method handlers |
|
|
866
|
+
| \`@Middleware(fn)\` | Attach middleware |
|
|
867
|
+
| \`@Public()\` | Skip auth (requires auth adapter) |
|
|
868
|
+
| \`@Roles('admin')\` | Role-based access |
|
|
869
|
+
|
|
870
|
+
### Dependency Injection
|
|
871
|
+
| Decorator | Purpose |
|
|
872
|
+
|-----------|---------|
|
|
873
|
+
| \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
|
|
874
|
+
| \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
|
|
875
|
+
| \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
|
|
876
|
+
| \`@Service()\` | Register singleton service |
|
|
877
|
+
| \`@Repository()\` | Register repository |
|
|
878
|
+
| \`@Autowired()\` | Property injection |
|
|
879
|
+
| \`@Inject('token')\` | Token-based injection |
|
|
880
|
+
| \`@Value('VAR')\` | Inject env variable |
|
|
881
|
+
|
|
882
|
+
### Context Decorators
|
|
883
|
+
|
|
884
|
+
Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
|
|
885
|
+
Use this **instead of \`@Middleware()\`** when the middleware's only output
|
|
886
|
+
is a value other code reads off \`ctx\`.
|
|
887
|
+
|
|
888
|
+
| Concept | Where it lives |
|
|
889
|
+
|---------|----------------|
|
|
890
|
+
| \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
|
|
891
|
+
| Method/class decorator | \`@LoadX\` on a controller method/class |
|
|
892
|
+
| Module hook | \`build: () => ({ contributors() { return [...] } })\` (\`defineModule\`) — or \`AppModule.contributors?()\` for class form |
|
|
893
|
+
| Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
|
|
894
|
+
| Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
|
|
895
|
+
| Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
|
|
896
|
+
|
|
897
|
+
Precedence high → low: **method > class > module > adapter > global**.
|
|
898
|
+
Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
|
|
899
|
+
fast). The \`onError\` hook is async-permitted.
|
|
900
|
+
|
|
901
|
+
Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
|
|
902
|
+
|
|
903
|
+
${t===`cqrs`?`### Background Jobs
|
|
904
|
+
| Decorator | Purpose |
|
|
905
|
+
|-----------|---------|
|
|
906
|
+
| \`@Job('name')\` | Queue job handler |
|
|
907
|
+
| \`@Process('queue')\` | Queue processor |
|
|
908
|
+
| \`@Cron('0 * * * *')\` | Cron schedule |
|
|
909
|
+
| \`@WsController()\` | WebSocket controller |
|
|
910
|
+
|
|
911
|
+
`:``}## Common Pitfalls
|
|
912
|
+
|
|
913
|
+
1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
|
|
914
|
+
2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
|
|
915
|
+
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()\`
|
|
916
|
+
4. **Routes not found** — Check controller path and module registration
|
|
917
|
+
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.
|
|
918
|
+
6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
|
|
919
|
+
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.
|
|
920
|
+
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.
|
|
921
|
+
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).
|
|
922
|
+
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({ ... })\`.
|
|
923
|
+
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\`.
|
|
924
|
+
|
|
925
|
+
## CLI Commands Reference
|
|
926
|
+
|
|
927
|
+
| Command | Description |
|
|
928
|
+
|---------|-------------|
|
|
929
|
+
| \`kick dev\` | Dev server with HMR |
|
|
930
|
+
| \`kick dev:debug\` | Dev server with debugger |
|
|
931
|
+
| \`kick build\` | Production build |
|
|
932
|
+
| \`kick start\` | Run production build |
|
|
933
|
+
| \`kick g module <names...>\` | Generate one or more modules |
|
|
934
|
+
| \`kick g scaffold <name> <fields>\` | Generate CRUD |
|
|
935
|
+
| \`kick g controller <name>\` | Generate controller |
|
|
936
|
+
| \`kick g service <name>\` | Generate service |
|
|
937
|
+
| \`kick g middleware <name>\` | Generate middleware |
|
|
938
|
+
| \`kick add <package>\` | Add KickJS package |
|
|
939
|
+
| \`kick add --list\` | List available packages |
|
|
940
|
+
| \`kick rm module <names...>\` | Remove one or more modules |
|
|
941
|
+
|
|
942
|
+
> **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
|
|
943
|
+
> \`\`\`bash
|
|
944
|
+
> kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
|
|
945
|
+
> \`\`\`
|
|
946
|
+
|
|
947
|
+
## Learn More
|
|
948
|
+
|
|
949
|
+
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
950
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
951
|
+
- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
952
|
+
- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
|
|
953
|
+
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
954
|
+
`}function yt(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".
|
|
955
|
+
|
|
956
|
+
**Steps**:
|
|
957
|
+
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
958
|
+
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
|
|
959
|
+
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
960
|
+
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
961
|
+
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
962
|
+
|
|
963
|
+
**Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
|
|
964
|
+
|
|
965
|
+
\`\`\`ts
|
|
966
|
+
export const TodosModule = defineModule({
|
|
967
|
+
name: 'TodosModule',
|
|
968
|
+
build: () => ({
|
|
969
|
+
register(container) {
|
|
970
|
+
container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
|
|
971
|
+
},
|
|
972
|
+
routes() {
|
|
973
|
+
return { path: '/todos', controller: TodosController }
|
|
974
|
+
},
|
|
975
|
+
}),
|
|
976
|
+
})
|
|
977
|
+
\`\`\`
|
|
978
|
+
|
|
979
|
+
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\`.
|
|
980
|
+
|
|
981
|
+
**Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
|
|
982
|
+
|
|
983
|
+
\`\`\`ts
|
|
984
|
+
routes() {
|
|
985
|
+
return [
|
|
986
|
+
{ path: '/todos', controller: TodosController }, // /api/v1/todos
|
|
987
|
+
{ path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
|
|
988
|
+
]
|
|
989
|
+
}
|
|
990
|
+
\`\`\`
|
|
991
|
+
|
|
992
|
+
**Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
|
|
993
|
+
|
|
994
|
+
**Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
|
|
995
|
+
|
|
996
|
+
**Red flags** (stop and ask):
|
|
997
|
+
- 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.
|
|
998
|
+
- \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
|
|
999
|
+
- \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
|
|
1000
|
+
- \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
|
|
1001
|
+
- 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**:
|
|
1002
|
+
|
|
1003
|
+
\`\`\`ts
|
|
1004
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
1005
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
1006
|
+
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
1007
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
1008
|
+
|
|
1009
|
+
// src/middleware/index.ts — global middleware uses RAW EXPRESS signature
|
|
1010
|
+
// (req, res, next), NOT (ctx, next)
|
|
1011
|
+
export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
|
|
1012
|
+
|
|
1013
|
+
// src/plugins/index.ts
|
|
1014
|
+
export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
|
|
1015
|
+
|
|
1016
|
+
// src/adapters/index.ts
|
|
1017
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
1018
|
+
|
|
1019
|
+
// src/index.ts — stays small
|
|
1020
|
+
import 'reflect-metadata'
|
|
1021
|
+
import './config' // MUST be early — side-effect schema load
|
|
1022
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1023
|
+
import { modules } from './modules'
|
|
1024
|
+
import { middleware } from './middleware'
|
|
1025
|
+
import { plugins } from './plugins'
|
|
1026
|
+
import { adapters } from './adapters'
|
|
1027
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
1028
|
+
\`\`\`
|
|
1029
|
+
|
|
1030
|
+
**One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
|
|
1031
|
+
|
|
1032
|
+
\`\`\`ts
|
|
1033
|
+
plugins: [
|
|
1034
|
+
...plugins,
|
|
1035
|
+
{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
|
|
1036
|
+
]
|
|
1037
|
+
\`\`\`
|
|
1038
|
+
|
|
1039
|
+
**Red flags**:
|
|
1040
|
+
- Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
1041
|
+
- 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".
|
|
1042
|
+
- \`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**:
|
|
1043
|
+
- \`kick new <name>\` — start a new project (prompts for template / repo / pm).
|
|
1044
|
+
- \`kick dev\` — local dev server with Vite HMR.
|
|
1045
|
+
- \`kick build\` — production bundle via Vite.
|
|
1046
|
+
- \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
|
|
1047
|
+
- \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
|
|
1048
|
+
- \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
|
|
1049
|
+
- \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
|
|
1050
|
+
- \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
|
|
1051
|
+
- \`kick info\` — environment / version dump for bug reports.
|
|
1052
|
+
- \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
|
|
1053
|
+
|
|
1054
|
+
**Useful flag combos**:
|
|
1055
|
+
|
|
1056
|
+
\`\`\`bash
|
|
1057
|
+
kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
|
|
1058
|
+
kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
|
|
1059
|
+
kick new . --yes --force # Scaffold into current dir, clear existing files
|
|
1060
|
+
kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
|
|
1061
|
+
kick g agents -f --only skills # Refresh just the skills after upgrade
|
|
1062
|
+
kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
|
|
1063
|
+
kick inspect --port 4000 --json # Machine-readable route/adapter dump
|
|
1064
|
+
kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
|
|
1065
|
+
\`\`\`
|
|
1066
|
+
|
|
1067
|
+
**Lesser-known, high-value**:
|
|
1068
|
+
- \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
|
|
1069
|
+
- \`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.
|
|
1070
|
+
- \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
|
|
1071
|
+
- \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
|
|
1072
|
+
- \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
|
|
1073
|
+
- \`kick check\` — preflight gate (typecheck + lint + format) before commit.
|
|
1074
|
+
- \`kick codemod\` — automated AST-level migration between framework versions.
|
|
1075
|
+
|
|
1076
|
+
**Red flags**:
|
|
1077
|
+
- Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
|
|
1078
|
+
- Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
|
|
1079
|
+
- Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
|
|
1080
|
+
- Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
|
|
1081
|
+
- 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:`---
|
|
1082
|
+
name: ${e.frontmatterName}
|
|
1083
|
+
description: ${e.description}
|
|
1084
|
+
---
|
|
1085
|
+
|
|
1086
|
+
${r}
|
|
1087
|
+
|
|
1088
|
+
${e.body}
|
|
1089
|
+
`}))}function bt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
|
|
1090
|
+
|
|
1091
|
+
This file is the agent-facing **skills index** for KickJS work in this
|
|
1092
|
+
repo. Each block below is a short, rigid workflow keyed to a specific
|
|
1093
|
+
trigger ("user wants to add a module", "tests are leaking state", etc.).
|
|
1094
|
+
|
|
1095
|
+
- Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
|
|
1096
|
+
- Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
|
|
1097
|
+
- **This file** → step-by-step recipes the agent should *execute*.
|
|
1098
|
+
|
|
1099
|
+
Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
|
|
1100
|
+
|
|
1101
|
+
---
|
|
1102
|
+
|
|
1103
|
+
## Skill: add-module
|
|
1104
|
+
|
|
1105
|
+
\`\`\`yaml
|
|
1106
|
+
name: kickjs-add-module
|
|
1107
|
+
description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
|
|
1108
|
+
\`\`\`
|
|
1109
|
+
|
|
1110
|
+
**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
1111
|
+
|
|
1112
|
+
**Steps**:
|
|
1113
|
+
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
1114
|
+
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
|
|
1115
|
+
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
1116
|
+
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
1117
|
+
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
1118
|
+
|
|
1119
|
+
**Red flags** (stop and ask):
|
|
1120
|
+
- File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
|
|
1121
|
+
- Module not registered in \`src/modules/index.ts\`.
|
|
1122
|
+
- \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
|
|
1123
|
+
|
|
1124
|
+
---
|
|
1125
|
+
|
|
1126
|
+
## Skill: add-adapter
|
|
1127
|
+
|
|
1128
|
+
\`\`\`yaml
|
|
1129
|
+
name: kickjs-add-adapter
|
|
1130
|
+
description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
|
|
1131
|
+
\`\`\`
|
|
1132
|
+
|
|
1133
|
+
**Steps**:
|
|
1134
|
+
1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
|
|
1135
|
+
2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
|
|
1136
|
+
3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
|
|
1137
|
+
4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
|
|
1138
|
+
5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
|
|
1139
|
+
|
|
1140
|
+
**Red flags**:
|
|
1141
|
+
- Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
|
|
1142
|
+
- Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
|
|
1143
|
+
|
|
1144
|
+
---
|
|
1145
|
+
|
|
1146
|
+
## Skill: write-controller-test
|
|
1147
|
+
|
|
1148
|
+
\`\`\`yaml
|
|
1149
|
+
name: kickjs-write-controller-test
|
|
1150
|
+
description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
|
|
1151
|
+
\`\`\`
|
|
1152
|
+
|
|
1153
|
+
**Template** (copy/paste, adjust):
|
|
1154
|
+
|
|
1155
|
+
\`\`\`ts
|
|
1156
|
+
import { describe, it, expect } from 'vitest'
|
|
1157
|
+
import { Container } from '@forinda/kickjs'
|
|
1158
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
1159
|
+
|
|
1160
|
+
describe('UserController', () => {
|
|
1161
|
+
it('returns users', async () => {
|
|
1162
|
+
const container = Container.create() // isolated DI per test
|
|
1163
|
+
const app = await createTestApp([UserModule], { container })
|
|
1164
|
+
const res = await app.get('/users')
|
|
1165
|
+
expect(res.status).toBe(200)
|
|
1166
|
+
})
|
|
1167
|
+
})
|
|
1168
|
+
\`\`\`
|
|
1169
|
+
|
|
1170
|
+
**Red flags**:
|
|
1171
|
+
- \`new Container()\` — wrong; use \`Container.create()\`.
|
|
1172
|
+
- \`Container.getInstance().reset()\` — wrong; same fix.
|
|
1173
|
+
- Sharing a container across \`it()\` blocks — leaks registrations.
|
|
1174
|
+
|
|
1175
|
+
---
|
|
1176
|
+
|
|
1177
|
+
## Skill: env-wiring-check
|
|
1178
|
+
|
|
1179
|
+
\`\`\`yaml
|
|
1180
|
+
name: kickjs-env-wiring-check
|
|
1181
|
+
description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
|
|
1182
|
+
\`\`\`
|
|
1183
|
+
|
|
1184
|
+
**Diagnosis**:
|
|
1185
|
+
1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
|
|
1186
|
+
2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
|
|
1187
|
+
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).
|
|
1188
|
+
|
|
1189
|
+
**Fix**: add the key to the schema; ensure both side-effect imports above are present.
|
|
1190
|
+
|
|
1191
|
+
---
|
|
1192
|
+
|
|
1193
|
+
## Skill: bootstrap-export
|
|
1194
|
+
|
|
1195
|
+
\`\`\`yaml
|
|
1196
|
+
name: kickjs-bootstrap-export
|
|
1197
|
+
description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
|
|
1198
|
+
\`\`\`
|
|
1199
|
+
|
|
1200
|
+
**Check** \`src/index.ts\`'s last line:
|
|
1201
|
+
|
|
1202
|
+
\`\`\`ts
|
|
1203
|
+
// CORRECT
|
|
1204
|
+
export const app = await bootstrap({ ... })
|
|
1205
|
+
|
|
1206
|
+
// WRONG (HMR degrades to full restart, createTestApp loses the handle)
|
|
1207
|
+
await bootstrap({ ... })
|
|
1208
|
+
\`\`\`
|
|
1209
|
+
|
|
1210
|
+
The Vite plugin imports the named \`app\` symbol; testing helpers do too.
|
|
1211
|
+
|
|
1212
|
+
---
|
|
1213
|
+
|
|
1214
|
+
## Skill: thin-entry-file
|
|
1215
|
+
|
|
1216
|
+
\`\`\`yaml
|
|
1217
|
+
name: kickjs-thin-entry-file
|
|
1218
|
+
description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
|
|
1219
|
+
\`\`\`
|
|
1220
|
+
|
|
1221
|
+
**Refactor target**:
|
|
1222
|
+
|
|
1223
|
+
\`\`\`ts
|
|
1224
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
1225
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
1226
|
+
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
1227
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
1228
|
+
|
|
1229
|
+
// src/middleware/index.ts
|
|
1230
|
+
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
1231
|
+
|
|
1232
|
+
// src/plugins/index.ts
|
|
1233
|
+
export const plugins = [MetricsPlugin(), ...]
|
|
1234
|
+
|
|
1235
|
+
// src/adapters/index.ts
|
|
1236
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
1237
|
+
|
|
1238
|
+
// src/index.ts — stays small
|
|
1239
|
+
import 'reflect-metadata'
|
|
1240
|
+
import './config'
|
|
1241
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1242
|
+
import { modules } from './modules'
|
|
1243
|
+
import { middleware } from './middleware'
|
|
1244
|
+
import { plugins } from './plugins'
|
|
1245
|
+
import { adapters } from './adapters'
|
|
1246
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
1247
|
+
\`\`\`
|
|
1248
|
+
|
|
1249
|
+
**Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
1250
|
+
|
|
1251
|
+
---
|
|
1252
|
+
|
|
1253
|
+
## Skill: context-contributor
|
|
1254
|
+
|
|
1255
|
+
\`\`\`yaml
|
|
1256
|
+
name: kickjs-context-contributor
|
|
1257
|
+
description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
|
|
1258
|
+
\`\`\`
|
|
1259
|
+
|
|
1260
|
+
**Pattern** (HTTP — most common):
|
|
1261
|
+
|
|
1262
|
+
\`\`\`ts
|
|
1263
|
+
import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
|
|
1264
|
+
|
|
1265
|
+
const LoadTenant = defineHttpContextDecorator({
|
|
1266
|
+
key: 'tenant',
|
|
1267
|
+
deps: { repo: TENANT_REPO },
|
|
1268
|
+
resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
|
|
1269
|
+
})
|
|
1270
|
+
|
|
1271
|
+
const LoadProject = defineHttpContextDecorator({
|
|
1272
|
+
key: 'project',
|
|
1273
|
+
dependsOn: ['tenant'],
|
|
1274
|
+
resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
|
|
1275
|
+
})
|
|
1276
|
+
|
|
1277
|
+
@LoadTenant
|
|
1278
|
+
@LoadProject
|
|
1279
|
+
@Get('/projects/:id')
|
|
1280
|
+
getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
|
|
1281
|
+
\`\`\`
|
|
1282
|
+
|
|
1283
|
+
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\`).
|
|
1284
|
+
|
|
1285
|
+
Precedence high → low: **method > class > module > adapter > global**.
|
|
1286
|
+
Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
|
|
1287
|
+
|
|
1288
|
+
**Critical rules — all stem from the same shared-via-ALS instance model**:
|
|
1289
|
+
- Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
|
|
1290
|
+
- **\`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.
|
|
1291
|
+
- \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
|
|
1292
|
+
- Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
|
|
1293
|
+
- **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.
|
|
1294
|
+
|
|
1295
|
+
**Don't use this for**: response short-circuit, stream mutation, or
|
|
1296
|
+
pre-route-matching work — keep \`@Middleware()\` for those.
|
|
1297
|
+
|
|
1298
|
+
---
|
|
1299
|
+
|
|
1300
|
+
## Skill: refresh-agent-docs
|
|
1301
|
+
|
|
1302
|
+
\`\`\`yaml
|
|
1303
|
+
name: kickjs-refresh-agent-docs
|
|
1304
|
+
description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
|
|
1305
|
+
\`\`\`
|
|
1306
|
+
|
|
1307
|
+
**Steps**:
|
|
1308
|
+
1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
|
|
1309
|
+
2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
|
|
1310
|
+
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.
|
|
1311
|
+
4. Commit as \`docs(agents): sync from CLI vX.Y\`.
|
|
1312
|
+
|
|
1313
|
+
---
|
|
1314
|
+
|
|
1315
|
+
## Skill: deny-list
|
|
1316
|
+
|
|
1317
|
+
\`\`\`yaml
|
|
1318
|
+
name: kickjs-deny-list
|
|
1319
|
+
description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
|
|
1320
|
+
\`\`\`
|
|
1321
|
+
|
|
1322
|
+
- \`class implements AppAdapter\` → use \`defineAdapter()\`.
|
|
1323
|
+
- \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
|
|
1324
|
+
- \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
|
|
1325
|
+
- \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
|
|
1326
|
+
- DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
|
|
1327
|
+
- \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
|
|
1328
|
+
- Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
|
|
1329
|
+
|
|
1330
|
+
---
|
|
1331
|
+
|
|
1332
|
+
## Learn More
|
|
1333
|
+
|
|
1334
|
+
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
1335
|
+
- [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
1336
|
+
- [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
|
|
1337
|
+
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
1338
|
+
`}function xt(e,t,n){return`# GEMINI.md — ${e}
|
|
1339
|
+
|
|
1340
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
1341
|
+
reference for this project — every convention, structure, decorator
|
|
1342
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
1343
|
+
Gemini-specific layer; when the two disagree on anything substantive,
|
|
1344
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
1345
|
+
|
|
1346
|
+
## Why this file
|
|
1347
|
+
|
|
1348
|
+
Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
|
|
1349
|
+
agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
|
|
1350
|
+
means Gemini reads the same shared prose as Codex / Cursor / Copilot
|
|
1351
|
+
without us copy-pasting.
|
|
1352
|
+
|
|
1353
|
+
## Gemini-specific notes
|
|
1354
|
+
|
|
1355
|
+
- **Skills activation** — Gemini activates skills via
|
|
1356
|
+
\`activate_skill\` (its native MCP-style tool); the equivalent on
|
|
1357
|
+
Claude Code is the \`Skill\` tool. Cross-reference the
|
|
1358
|
+
\`kickjs-skills.md\` index for the available triggers.
|
|
1359
|
+
- **Tool naming** — Gemini's tool names differ from Claude Code's
|
|
1360
|
+
(e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
|
|
1361
|
+
\`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
|
|
1362
|
+
tool names; consult Gemini's docs for the concrete invocation.
|
|
1363
|
+
- **File ops** — Gemini's file edits are sandboxed; large refactors
|
|
1364
|
+
may need explicit confirmation. Prefer the smallest-possible-edit
|
|
1365
|
+
pattern.
|
|
1366
|
+
|
|
1367
|
+
## Refreshing this file
|
|
1368
|
+
|
|
1369
|
+
\`kick g agents --only gemini -f\` regenerates this file from the
|
|
1370
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
1371
|
+
in \`.agents/GEMINI.local.md\`.
|
|
1372
|
+
`}function St(e,t,n){return`# COPILOT.md — ${e}
|
|
1373
|
+
|
|
1374
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
1375
|
+
reference for this project — every convention, structure, decorator
|
|
1376
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
1377
|
+
Copilot-specific layer; when the two disagree on anything substantive,
|
|
1378
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
1379
|
+
|
|
1380
|
+
## Why this file
|
|
1381
|
+
|
|
1382
|
+
GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
|
|
1383
|
+
the agent-context files. Keeping it in \`.agents/\` next to
|
|
1384
|
+
\`AGENTS.md\` means Copilot reads the same shared prose as
|
|
1385
|
+
Codex / Cursor / Gemini / Claude Code without copy-pasting.
|
|
1386
|
+
|
|
1387
|
+
## Copilot-specific notes
|
|
1388
|
+
|
|
1389
|
+
- **Skills** — Copilot CLI auto-discovers skills from installed
|
|
1390
|
+
plugins; cross-reference \`kickjs-skills.md\` for available
|
|
1391
|
+
triggers in this project.
|
|
1392
|
+
- **Tool naming** — Copilot's tool names differ from Claude Code's
|
|
1393
|
+
(\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
|
|
1394
|
+
prose in \`AGENTS.md\` describes intents, not tool names; consult
|
|
1395
|
+
Copilot's docs for the concrete invocation.
|
|
1396
|
+
- **Confirmation flows** — Copilot CLI surfaces destructive
|
|
1397
|
+
operations through an explicit approval gate. Stage edits with
|
|
1398
|
+
short, focused diffs so each one is easy to review at the prompt.
|
|
1399
|
+
|
|
1400
|
+
## Refreshing this file
|
|
1401
|
+
|
|
1402
|
+
\`kick g agents --only copilot -f\` regenerates this file from the
|
|
1403
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
1404
|
+
in \`.agents/COPILOT.local.md\`.
|
|
1405
|
+
`}const Ct=f(b(import.meta.url)),wt=JSON.parse(a(h(Ct,`..`,`package.json`),`utf-8`)),Tt=`^${wt.version}`,Et=[`@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 Dt(){let e=await Promise.all(Et.map(async e=>{try{let t=ee(`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,Tt]}));return Object.fromEntries(e)}async function Ot(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:i=`rest`,defaultRepo:a=`inmemory`,packages:o=[]}=e,s=n,c=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),c(`Resolving package versions...`);let l=await Dt();if(await M(h(s,`package.json`),$e(t,i,l,o)),await M(h(s,`vite.config.ts`),et()),await M(h(s,`tsconfig.json`),tt()),await M(h(s,`.prettierrc`),nt()),await M(h(s,`.editorconfig`),rt()),await M(h(s,`.gitignore`),it()),await M(h(s,`.gitattributes`),at()),await M(h(s,`.env`),ot()),await M(h(s,`.env.example`),st()),await M(h(s,`src/config/index.ts`),dt()),await M(h(s,`src/index.ts`),lt(t,i,wt.version,o)),await M(h(s,`src/modules/index.ts`),ut()),await M(h(s,`src/modules/hello/hello.service.ts`),ft()),await M(h(s,`src/modules/hello/hello.controller.ts`),pt()),await M(h(s,`src/modules/hello/hello.module.ts`),mt()),await M(h(s,`kick.config.ts`),ht(i,a,r)),await M(h(s,`vitest.config.ts`),ct()),await M(h(s,`README.md`),gt(t,i,r)),await M(h(s,`CLAUDE.md`),_t(t,i,r)),await M(h(s,`AGENTS.md`),vt(t,i,r)),await M(h(s,`kickjs-skills.md`),bt(t,i,r)),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{S(`${r} install`,{cwd:s,stdio:`inherit`}),console.log(`
|
|
1406
|
+
Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await Promise.resolve().then(()=>oa);await e({cwd:s,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{S(`git init`,{cwd:s,stdio:`pipe`}),S(`git branch -M main`,{cwd:s,stdio:`pipe`}),S(`git add -A`,{cwd:s,stdio:`pipe`}),S(`git commit -m "chore: initial commit from kick new"`,{cwd:s,stdio:`pipe`}),c(`Git repository initialized`)}catch{c(`Warning: git init failed (git may not be installed)`)}console.log(`
|
|
1407
|
+
Project scaffolded successfully!`),console.log();let u=s!==process.cwd();c(`Next steps:`),u&&c(` cd ${t}`),e.installDeps||c(` ${r} install`);let d={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};c(` ${d[i]??d.rest}`),c(` kick dev`),c(``),c(`Commands:`),c(` kick dev Start dev server with Vite HMR`),c(` kick build Production build via Vite`),c(` kick start Run production build`),c(``),c(`Generators:`),c(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),c(` kick g scaffold <n> <f..> CRUD module from field definitions`),c(` kick g controller <name> Standalone controller`),c(` kick g service <name> @Service() class`),c(` kick g middleware <name> Express middleware`),c(` kick g guard <name> Route guard (auth, roles, etc.)`),c(` kick g adapter <name> AppAdapter with lifecycle hooks`),c(` kick g dto <name> Zod DTO schema`),i===`cqrs`&&c(` kick g job <name> Queue job processor`),c(` kick g config Generate kick.config.ts`),c(``),c(`Add packages:`),c(` kick add <pkg> Install a KickJS package + peers`),c(` kick add --list Show all available packages`),c(``),c(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),c(``)}const kt={GET:E.green,POST:E.cyan,PUT:E.yellow,PATCH:E.magenta,DELETE:E.red};function At(e){return(kt[e]??E.dim)(e.padEnd(7))}function jt(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return E.red(t);case`WARNING`:return E.yellow(t);case`INFO`:return E.blue(E.dim(t));default:return t}}E.green(`✓`),E.red(`✖`),E.yellow(`⚠`),E.blue(`ℹ`);function Mt(e){T.intro(E.bgCyan(E.black(` ${e} `)))}function Nt(e){T.outro(e)}function Pt(e){T.isCancel(e)&&(T.cancel(`Operation cancelled.`),process.exit(0))}async function Ft(e){let t=await T.text(e);return Pt(t),t}async function It(e){let t=await T.select(e);return Pt(t),t}async function Lt(e){let t=await T.multiselect(e);return Pt(t),t}async function P(e){let t=await T.confirm(e);return Pt(t),t}function Rt(){return T.spinner()}const F=T.log,zt={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function Bt(e,t=process.cwd()){let n=t;for(;;){if(r(v(n,e)))return n;let t=f(n);if(t===n)return null;n=t}}function Vt(){return Bt(`pnpm-lock.yaml`)?`pnpm`:Bt(`yarn.lock`)?`yarn`:Bt(`bun.lockb`)||Bt(`bun.lock`)?`bun`:Bt(`package-lock.json`)?`npm`:null}function Ht(){let e=process.cwd();for(;e;){let t=v(e,`package.json`);if(r(t))try{let e=JSON.parse(a(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(Ne.includes(t))return t}}catch{}let n=f(e);if(n===e)return null;e=n}return null}async function Ut(e){if(e&&Ne.includes(e))return{pm:e,source:`flag`};let t=await k(process.cwd());if(t?.packageManager&&Ne.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=Ht();if(n)return{pm:n,source:`package.json`};let r=Vt();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function Wt(e){let{pm:t}=await Ut(e);return t}function Gt(e=!1){let t=Object.entries(zt),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
|
|
1408
|
+
Core packages (always installed by \`kick new\`):
|
|
1409
|
+
`);for(let e of r)console.log(a(e));if(e){console.log(`
|
|
1410
|
+
Optional packages (add as needed):
|
|
1411
|
+
`);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
|
|
1412
|
+
Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function Kt(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{Gt(!!e.all)})}function qt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){Gt(!!t.all);return}let{pm:n,source:r}=await Ut(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=zt[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
|
|
1413
|
+
`),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{S(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{S(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
|
|
1414
|
+
`)}})}const Jt=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function Yt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{Mt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await Ft({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=v(`.`),e=d(i)):i=v(t.directory||e),r(i)){let r=o(i);if(r.length>0){if(t.force)F.warn(`Clearing existing files in ${i}`);else if(n){F.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),Nt(`Aborted.`);return}else{F.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)F.message(` - ${e}`);if(r.length>5&&F.message(` ... and ${r.length-5} more`),!await P({message:E.red(`Remove all existing files and proceed?`),initialValue:!1})){Nt(`Aborted.`);return}}for(let e of r)s(v(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await It({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let c=t.pm;c||=n?await Wt(void 0):await It({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||(n?l=`inmemory`:(l=await It({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),l===`custom`&&(l=await Ft({message:`Custom repository name`,defaultValue:`custom`}))));let u;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();u=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else u=n?[]:await Lt({message:`Select packages to include`,options:[...Jt],required:!1});let f;f=t.git===void 0?n?!0:await P({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;p=t.install===void 0?n?!0:await P({message:`Install dependencies?`,initialValue:!0}):t.install,await Ot({name:e,directory:i,packageManager:c,initGit:f,installDeps:p,template:a,defaultRepo:l,packages:u}),Nt(`Done! Next steps: ${E.cyan(`cd ${e} && ${c} dev`)}`)})}function I(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function L(e){let t=I(e);return t.charAt(0).toLowerCase()+t.slice(1)}function R(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function z(e){return de.plural(e)}function Xt(e){return de.plural(e)}function Zt(e){return R(e).replace(/-/g,`_`)}function Qt(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=I(e.name),i=L(e.name),a=R(e.name),o=Zt(e.name),s={name:e.name,pascal:r,camel:i,kebab:a,snake:o,modulesDir:e.modulesDir??`src/modules`,cwd:t,args:e.args??[],flags:e.flags??{}};if(n){let e=z(a);s.pluralKebab=e,s.pluralPascal=I(e),s.pluralCamel=L(e)}return s}function $t(e,t){return v(e.cwd,t)}async function en(e){return import(x(e).href)}const tn=new Map;async function nn(e){let t=tn.get(e);if(t)return t;let n=rn(e);return tn.set(e,n),n}async function rn(t){let n=v(t,`package.json`);if(!r(n))return{generators:[],loaded:[],failed:[]};let i=an(JSON.parse(await C(n,`utf-8`))),a=e(v(t,`package.json`)),o=[],s=[],c=[];for(let e of i){let t;try{t=a.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await C(t,`utf-8`))}catch(t){c.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let i=n.kickjs.generators,l=v(f(t),i);if(!r(l)){c.push({source:e,reason:`kickjs.generators points to missing file: ${i}`});continue}let u;try{u=await en(l)}catch(t){c.push({source:e,reason:`failed to import manifest: ${t}`});continue}let d=u.default;if(!Array.isArray(d)){c.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of d){if(!on(t)){c.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}o.push({source:e,spec:t})}s.push(e)}return{generators:o,loaded:s,failed:c}}function an(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 on(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function sn(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return un(r.spec,r.source,e,n);let i=ln(await nn(n),e.generatorName);return i?un(i.spec,i.source,e,n):null}async function cn(e,t=[]){let n=await nn(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 ln(e,t){return e.generators.find(e=>e.spec.name===t)}async function un(e,t,n,r){let i=Qt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r}),a=await e.files(i),o=[];for(let e of a){let t=$t(i,e.path);await M(t,e.content),o.push(t)}return{files:o,source:t}}function B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const dn={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function fn(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function pn(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function mn(e){return dn[e]??fn(e)}function hn(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]??`${fn(n)}${e}Repository`,repoFile:i[n]??`${pn(n)}-${t}`}}function gn(e){return e??`define`}function _n(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=hn(t,n,i),c=gn(a),l=`/**
|
|
1415
|
+
* ${t} Module
|
|
1416
|
+
*
|
|
1417
|
+
* Self-contained feature module following Domain-Driven Design (DDD).
|
|
1418
|
+
* Registers dependencies in the DI container and declares HTTP routes.
|
|
1419
|
+
*
|
|
1420
|
+
* Structure:
|
|
1421
|
+
* presentation/ — HTTP controllers (entry points)
|
|
1422
|
+
* application/ — Use cases (orchestration) and DTOs (validation)
|
|
1423
|
+
* domain/ — Entities, value objects, repository interfaces, domain services
|
|
1424
|
+
* infrastructure/ — Repository implementations (currently ${mn(i)})
|
|
1425
|
+
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './domain/repositories/${n}.repository'
|
|
1426
|
+
import { ${o} } from './infrastructure/repositories/${s}.repository'
|
|
1427
|
+
import { ${t}Controller } from './presentation/${n}.controller'
|
|
1428
|
+
|
|
1429
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
1430
|
+
import.meta.glob(
|
|
1431
|
+
['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
|
|
1432
|
+
{ eager: true },
|
|
1433
|
+
)`,d=` /**
|
|
1434
|
+
* Declare HTTP routes for this module. Return value shape:
|
|
1435
|
+
*
|
|
1436
|
+
* - \`path\` — URL prefix for this route set, mounted under
|
|
1437
|
+
* \`/{apiPrefix}/v{version}{path}\`.
|
|
1438
|
+
* - \`controller\` — Controller class. Used both for the route
|
|
1439
|
+
* handler bindings and OpenAPI spec generation.
|
|
1440
|
+
* - \`version\` — Optional. Overrides the app-wide API version
|
|
1441
|
+
* for this route set only.
|
|
1442
|
+
*
|
|
1443
|
+
* Return an **array** to mount multiple route sets under the
|
|
1444
|
+
* same module (e.g. side-by-side v1 + v2 controllers):
|
|
1445
|
+
*
|
|
1446
|
+
* return [
|
|
1447
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
1448
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
1449
|
+
* ]
|
|
1450
|
+
*/`;return c===`class`?`${l}
|
|
1451
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
1452
|
+
${u}
|
|
1453
|
+
|
|
1454
|
+
export class ${t}Module implements AppModule {
|
|
1455
|
+
/**
|
|
1456
|
+
* Register module dependencies in the DI container.
|
|
1457
|
+
* Bind repository interface tokens to their implementations here.
|
|
1458
|
+
* Currently wired to ${mn(i)}. To swap implementations, change the factory target.
|
|
1459
|
+
*/
|
|
1460
|
+
register(container: Container): void {
|
|
1461
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
1462
|
+
container.resolve(${o}),
|
|
1463
|
+
)
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
1467
|
+
routes(): ModuleRoutes {
|
|
1468
|
+
return {
|
|
1469
|
+
path: '/${r}',
|
|
1470
|
+
controller: ${t}Controller,
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
`:`${l}
|
|
1475
|
+
import { defineModule } from '@forinda/kickjs'
|
|
1476
|
+
${u}
|
|
1477
|
+
|
|
1478
|
+
export const ${t}Module = defineModule({
|
|
1479
|
+
name: '${t}Module',
|
|
1480
|
+
build: () => ({
|
|
1481
|
+
/**
|
|
1482
|
+
* Register module dependencies in the DI container.
|
|
1483
|
+
* Bind repository interface tokens to their implementations here.
|
|
1484
|
+
* Currently wired to ${mn(i)}. To swap implementations, change the factory target.
|
|
1485
|
+
*/
|
|
1486
|
+
register(container) {
|
|
1487
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
1488
|
+
container.resolve(${o}),
|
|
1489
|
+
)
|
|
1490
|
+
},
|
|
1491
|
+
|
|
1492
|
+
${d}
|
|
1493
|
+
routes() {
|
|
1494
|
+
return {
|
|
1495
|
+
path: '/${r}',
|
|
1496
|
+
controller: ${t}Controller,
|
|
1497
|
+
}
|
|
1498
|
+
},
|
|
1499
|
+
}),
|
|
1500
|
+
})
|
|
1501
|
+
`}function vn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=hn(t,n,i),c=gn(a),l=`/**
|
|
1502
|
+
* ${t} Module
|
|
1503
|
+
*
|
|
1504
|
+
* REST module with a flat folder structure.
|
|
1505
|
+
* Controller delegates to service, service wraps the repository.
|
|
1506
|
+
*
|
|
1507
|
+
* Structure:
|
|
1508
|
+
* ${n}.controller.ts — HTTP routes (CRUD)
|
|
1509
|
+
* ${n}.service.ts — Business logic
|
|
1510
|
+
* ${n}.repository.ts — Repository interface
|
|
1511
|
+
* ${s}.repository.ts — Repository implementation
|
|
1512
|
+
* dtos/ — Request/response schemas
|
|
1513
|
+
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
|
|
1514
|
+
import { ${o} } from './${s}.repository'
|
|
1515
|
+
import { ${t}Controller } from './${n}.controller'
|
|
1516
|
+
|
|
1517
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
1518
|
+
import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })`,d=` /**
|
|
1519
|
+
* Declare HTTP routes for this module. Return value shape:
|
|
1520
|
+
*
|
|
1521
|
+
* - \`path\` — URL prefix for this route set.
|
|
1522
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
1523
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
1524
|
+
*
|
|
1525
|
+
* Return an **array** to mount multiple route sets — admin
|
|
1526
|
+
* surfaces, side-by-side v1 + v2 controllers, etc:
|
|
1527
|
+
*
|
|
1528
|
+
* return [
|
|
1529
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
1530
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
1531
|
+
* ]
|
|
1532
|
+
*/`;return c===`class`?`${l}
|
|
1533
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
1534
|
+
${u}
|
|
1535
|
+
|
|
1536
|
+
export class ${t}Module implements AppModule {
|
|
1537
|
+
register(container: Container): void {
|
|
1538
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
1539
|
+
container.resolve(${o}),
|
|
1540
|
+
)
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
1544
|
+
routes(): ModuleRoutes {
|
|
1545
|
+
return {
|
|
1546
|
+
path: '/${r}',
|
|
1547
|
+
controller: ${t}Controller,
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
`:`${l}
|
|
1552
|
+
import { defineModule } from '@forinda/kickjs'
|
|
1553
|
+
${u}
|
|
1554
|
+
|
|
1555
|
+
export const ${t}Module = defineModule({
|
|
1556
|
+
name: '${t}Module',
|
|
1557
|
+
build: () => ({
|
|
1558
|
+
register(container) {
|
|
1559
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
1560
|
+
container.resolve(${o}),
|
|
1561
|
+
)
|
|
1562
|
+
},
|
|
1563
|
+
|
|
1564
|
+
${d}
|
|
1565
|
+
routes() {
|
|
1566
|
+
return {
|
|
1567
|
+
path: '/${r}',
|
|
1568
|
+
controller: ${t}Controller,
|
|
1569
|
+
}
|
|
1570
|
+
},
|
|
1571
|
+
}),
|
|
1572
|
+
})
|
|
1573
|
+
`}function yn(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=gn(i),o=` /**
|
|
1574
|
+
* Declare HTTP routes. Return value shape:
|
|
1575
|
+
*
|
|
1576
|
+
* - \`path\` — URL prefix for this route set.
|
|
1577
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
1578
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
1579
|
+
*
|
|
1580
|
+
* Return an array to mount multiple route sets:
|
|
1581
|
+
*
|
|
1582
|
+
* return [
|
|
1583
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
1584
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
1585
|
+
* ]
|
|
1586
|
+
*/`;return a===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
1587
|
+
import { ${t}Controller } from './${n}.controller'
|
|
1588
|
+
|
|
1589
|
+
export class ${t}Module implements AppModule {
|
|
1590
|
+
${o.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
1591
|
+
routes(): ModuleRoutes {
|
|
1592
|
+
return {
|
|
1593
|
+
path: '/${r}',
|
|
1594
|
+
controller: ${t}Controller,
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
`:`import { defineModule } from '@forinda/kickjs'
|
|
1599
|
+
import { ${t}Controller } from './${n}.controller'
|
|
1600
|
+
|
|
1601
|
+
export const ${t}Module = defineModule({
|
|
1602
|
+
name: '${t}Module',
|
|
1603
|
+
build: () => ({
|
|
1604
|
+
${o}
|
|
1605
|
+
routes() {
|
|
1606
|
+
return {
|
|
1607
|
+
path: '/${r}',
|
|
1608
|
+
controller: ${t}Controller,
|
|
1609
|
+
}
|
|
1610
|
+
},
|
|
1611
|
+
}),
|
|
1612
|
+
})
|
|
1613
|
+
`}function bn(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'
|
|
1614
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
1615
|
+
import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
|
|
1616
|
+
import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
|
|
1617
|
+
import { List${i}UseCase } from '../application/use-cases/list-${r}.use-case'
|
|
1618
|
+
import { Update${t}UseCase } from '../application/use-cases/update-${n}.use-case'
|
|
1619
|
+
import { Delete${t}UseCase } from '../application/use-cases/delete-${n}.use-case'
|
|
1620
|
+
import { create${t}Schema } from '../application/dtos/create-${n}.dto'
|
|
1621
|
+
import { update${t}Schema } from '../application/dtos/update-${n}.dto'
|
|
1622
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from '../constants'
|
|
1623
|
+
|
|
1624
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
1625
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
1626
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
1627
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
1628
|
+
|
|
1629
|
+
@Controller()
|
|
1630
|
+
export class ${t}Controller {
|
|
1631
|
+
@Autowired() private readonly create${t}UseCase!: Create${t}UseCase
|
|
1632
|
+
@Autowired() private readonly get${t}UseCase!: Get${t}UseCase
|
|
1633
|
+
@Autowired() private readonly list${i}UseCase!: List${i}UseCase
|
|
1634
|
+
@Autowired() private readonly update${t}UseCase!: Update${t}UseCase
|
|
1635
|
+
@Autowired() private readonly delete${t}UseCase!: Delete${t}UseCase
|
|
1636
|
+
|
|
1637
|
+
@Get('/')
|
|
1638
|
+
@ApiTags('${t}')
|
|
1639
|
+
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
1640
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
1641
|
+
return ctx.paginate(
|
|
1642
|
+
(parsed) => this.list${i}UseCase.execute(parsed),
|
|
1643
|
+
${t.toUpperCase()}_QUERY_CONFIG,
|
|
1644
|
+
)
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
@Get('/:id')
|
|
1648
|
+
@ApiTags('${t}')
|
|
1649
|
+
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
1650
|
+
const result = await this.get${t}UseCase.execute(ctx.params.id)
|
|
1651
|
+
if (!result) return ctx.notFound('${t} not found')
|
|
1652
|
+
ctx.json(result)
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
1656
|
+
@ApiTags('${t}')
|
|
1657
|
+
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
1658
|
+
const result = await this.create${t}UseCase.execute(ctx.body)
|
|
1659
|
+
ctx.created(result)
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
1663
|
+
@ApiTags('${t}')
|
|
1664
|
+
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
1665
|
+
const result = await this.update${t}UseCase.execute(ctx.params.id, ctx.body)
|
|
1666
|
+
ctx.json(result)
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
@Delete('/:id')
|
|
1670
|
+
@ApiTags('${t}')
|
|
1671
|
+
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
1672
|
+
await this.delete${t}UseCase.execute(ctx.params.id)
|
|
1673
|
+
ctx.noContent()
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
`}function xn(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'
|
|
1677
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
1678
|
+
import { ${t}Service } from './${n}.service'
|
|
1679
|
+
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
1680
|
+
import { update${t}Schema } from './dtos/update-${n}.dto'
|
|
1681
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
1682
|
+
|
|
1683
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
1684
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
1685
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
1686
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
1687
|
+
|
|
1688
|
+
@Controller()
|
|
1689
|
+
export class ${t}Controller {
|
|
1690
|
+
@Autowired() private readonly ${r}Service!: ${t}Service
|
|
1691
|
+
|
|
1692
|
+
@Get('/')
|
|
1693
|
+
@ApiTags('${t}')
|
|
1694
|
+
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
1695
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
1696
|
+
return ctx.paginate(
|
|
1697
|
+
(parsed) => this.${r}Service.findPaginated(parsed),
|
|
1698
|
+
${t.toUpperCase()}_QUERY_CONFIG,
|
|
1699
|
+
)
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
@Get('/:id')
|
|
1703
|
+
@ApiTags('${t}')
|
|
1704
|
+
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
1705
|
+
const result = await this.${r}Service.findById(ctx.params.id)
|
|
1706
|
+
if (!result) return ctx.notFound('${t} not found')
|
|
1707
|
+
ctx.json(result)
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
1711
|
+
@ApiTags('${t}')
|
|
1712
|
+
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
1713
|
+
const result = await this.${r}Service.create(ctx.body)
|
|
1714
|
+
ctx.created(result)
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
1718
|
+
@ApiTags('${t}')
|
|
1719
|
+
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
1720
|
+
const result = await this.${r}Service.update(ctx.params.id, ctx.body)
|
|
1721
|
+
ctx.json(result)
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
@Delete('/:id')
|
|
1725
|
+
@ApiTags('${t}')
|
|
1726
|
+
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
1727
|
+
await this.${r}Service.delete(ctx.params.id)
|
|
1728
|
+
ctx.noContent()
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
`}function Sn(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
|
|
1732
|
+
|
|
1733
|
+
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
|
|
1734
|
+
filterable: ['name'],
|
|
1735
|
+
sortable: ['name', 'createdAt'],
|
|
1736
|
+
searchable: ['name'],
|
|
1737
|
+
}
|
|
1738
|
+
`}function Cn(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
1739
|
+
|
|
1740
|
+
/**
|
|
1741
|
+
* Create ${t} DTO — Zod schema for validating POST request bodies.
|
|
1742
|
+
* This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
|
|
1743
|
+
* It also generates OpenAPI request body docs when SwaggerAdapter is used.
|
|
1744
|
+
*
|
|
1745
|
+
* Add more fields as needed. Supported Zod types:
|
|
1746
|
+
* z.string(), z.number(), z.boolean(), z.enum([...]),
|
|
1747
|
+
* z.array(), z.object(), .optional(), .default(), .transform()
|
|
1748
|
+
*/
|
|
1749
|
+
export const create${t}Schema = z.object({
|
|
1750
|
+
name: z.string().min(1, 'Name is required').max(200),
|
|
1751
|
+
})
|
|
1752
|
+
|
|
1753
|
+
export type Create${t}DTO = z.infer<typeof create${t}Schema>
|
|
1754
|
+
`}function wn(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
1755
|
+
|
|
1756
|
+
export const update${t}Schema = z.object({
|
|
1757
|
+
name: z.string().min(1).max(200).optional(),
|
|
1758
|
+
})
|
|
1759
|
+
|
|
1760
|
+
export type Update${t}DTO = z.infer<typeof update${t}Schema>
|
|
1761
|
+
`}function Tn(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
1762
|
+
id: string
|
|
1763
|
+
name: string
|
|
1764
|
+
createdAt: string
|
|
1765
|
+
updatedAt: string
|
|
1766
|
+
}
|
|
1767
|
+
`}function En(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
|
|
1768
|
+
* Create ${t} Use Case
|
|
1769
|
+
*
|
|
1770
|
+
* Application layer — orchestrates a single business operation.
|
|
1771
|
+
* Use cases are thin: validate input (via DTO), call domain/repo, return response.
|
|
1772
|
+
* Keep business rules in the domain service, not here.
|
|
1773
|
+
*/
|
|
1774
|
+
import { Service, Inject } from '@forinda/kickjs'
|
|
1775
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
1776
|
+
import type { Create${t}DTO } from '../dtos/create-${n}.dto'
|
|
1777
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1778
|
+
|
|
1779
|
+
@Service()
|
|
1780
|
+
export class Create${t}UseCase {
|
|
1781
|
+
constructor(
|
|
1782
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1783
|
+
) {}
|
|
1784
|
+
|
|
1785
|
+
async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1786
|
+
return this.repo.create(dto)
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
`},{file:`get-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1790
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
1791
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1792
|
+
|
|
1793
|
+
@Service()
|
|
1794
|
+
export class Get${t}UseCase {
|
|
1795
|
+
constructor(
|
|
1796
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1797
|
+
) {}
|
|
1798
|
+
|
|
1799
|
+
async execute(id: string): Promise<${t}ResponseDTO | null> {
|
|
1800
|
+
return this.repo.findById(id)
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
`},{file:`list-${r}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1804
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
1805
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1806
|
+
|
|
1807
|
+
@Service()
|
|
1808
|
+
export class List${i}UseCase {
|
|
1809
|
+
constructor(
|
|
1810
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1811
|
+
) {}
|
|
1812
|
+
|
|
1813
|
+
async execute(parsed: ParsedQuery) {
|
|
1814
|
+
return this.repo.findPaginated(parsed)
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
`},{file:`update-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1818
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
1819
|
+
import type { Update${t}DTO } from '../dtos/update-${n}.dto'
|
|
1820
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
1821
|
+
|
|
1822
|
+
@Service()
|
|
1823
|
+
export class Update${t}UseCase {
|
|
1824
|
+
constructor(
|
|
1825
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1826
|
+
) {}
|
|
1827
|
+
|
|
1828
|
+
async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1829
|
+
return this.repo.update(id, dto)
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
`},{file:`delete-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
1833
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
|
|
1834
|
+
|
|
1835
|
+
@Service()
|
|
1836
|
+
export class Delete${t}UseCase {
|
|
1837
|
+
constructor(
|
|
1838
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
1839
|
+
) {}
|
|
1840
|
+
|
|
1841
|
+
async execute(id: string): Promise<void> {
|
|
1842
|
+
await this.repo.delete(id)
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
`}]}function Dn(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
|
|
1846
|
+
* ${t} Repository Interface
|
|
1847
|
+
*
|
|
1848
|
+
* Defines the contract for data access.
|
|
1849
|
+
* The interface declares what operations are available;
|
|
1850
|
+
* implementations (in-memory, Drizzle, Prisma) fulfill the contract.
|
|
1851
|
+
*
|
|
1852
|
+
* To swap implementations, change the factory in the module's register() method.
|
|
1853
|
+
*/
|
|
1854
|
+
import { createToken } from '@forinda/kickjs'
|
|
1855
|
+
import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
|
|
1856
|
+
import type { Create${t}DTO } from '${r}/create-${n}.dto'
|
|
1857
|
+
import type { Update${t}DTO } from '${r}/update-${n}.dto'
|
|
1858
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1859
|
+
|
|
1860
|
+
export interface I${t}Repository {
|
|
1861
|
+
findById(id: string): Promise<${t}ResponseDTO | null>
|
|
1862
|
+
findAll(): Promise<${t}ResponseDTO[]>
|
|
1863
|
+
findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
|
|
1864
|
+
create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
|
|
1865
|
+
update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
|
|
1866
|
+
delete(id: string): Promise<void>
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* Collision-safe DI token bound to \`I${t}Repository\`.
|
|
1871
|
+
* \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
|
|
1872
|
+
* \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
1873
|
+
* interface — no manual generic, no \`any\` cast.
|
|
1874
|
+
*
|
|
1875
|
+
* The \`'${i}/'\` prefix matches the project scope so
|
|
1876
|
+
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
1877
|
+
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
1878
|
+
*/
|
|
1879
|
+
export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
|
|
1880
|
+
`}function V(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
1881
|
+
* In-Memory ${t} Repository
|
|
1882
|
+
*
|
|
1883
|
+
* Implements the repository interface using a Map.
|
|
1884
|
+
* Useful for prototyping and testing. Replace with a database implementation
|
|
1885
|
+
* (Drizzle, Prisma, etc.) for production use.
|
|
1886
|
+
*
|
|
1887
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
1888
|
+
*/
|
|
1889
|
+
import { randomUUID } from 'node:crypto'
|
|
1890
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
1891
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1892
|
+
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
1893
|
+
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
1894
|
+
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
1895
|
+
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
1896
|
+
|
|
1897
|
+
@Repository()
|
|
1898
|
+
export class InMemory${t}Repository implements I${t}Repository {
|
|
1899
|
+
private store = new Map<string, ${t}ResponseDTO>()
|
|
1900
|
+
|
|
1901
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
1902
|
+
return this.store.get(id) ?? null
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
1906
|
+
return Array.from(this.store.values())
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
1910
|
+
const all = Array.from(this.store.values())
|
|
1911
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
1912
|
+
return { data, total: all.length }
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1916
|
+
const now = new Date().toISOString()
|
|
1917
|
+
const entity: ${t}ResponseDTO = {
|
|
1918
|
+
id: randomUUID(),
|
|
1919
|
+
name: dto.name,
|
|
1920
|
+
createdAt: now,
|
|
1921
|
+
updatedAt: now,
|
|
1922
|
+
}
|
|
1923
|
+
this.store.set(entity.id, entity)
|
|
1924
|
+
return entity
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1928
|
+
const existing = this.store.get(id)
|
|
1929
|
+
if (!existing) throw HttpException.notFound('${t} not found')
|
|
1930
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
1931
|
+
this.store.set(id, updated)
|
|
1932
|
+
return updated
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
async delete(id: string): Promise<void> {
|
|
1936
|
+
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
1937
|
+
this.store.delete(id)
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
`}function On(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`/**
|
|
1941
|
+
* ${o} ${t} Repository
|
|
1942
|
+
*
|
|
1943
|
+
* Stub implementation for a custom '${r}' repository.
|
|
1944
|
+
* Implements the repository interface using an in-memory Map as a placeholder.
|
|
1945
|
+
*
|
|
1946
|
+
* TODO: Replace the in-memory Map with your ${r} data-access logic.
|
|
1947
|
+
* See I${t}Repository for the interface contract.
|
|
1948
|
+
*
|
|
1949
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
1950
|
+
*/
|
|
1951
|
+
import { randomUUID } from 'node:crypto'
|
|
1952
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
1953
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1954
|
+
import type { I${t}Repository } from '${i}/${n}.repository'
|
|
1955
|
+
import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
|
|
1956
|
+
import type { Create${t}DTO } from '${a}/create-${n}.dto'
|
|
1957
|
+
import type { Update${t}DTO } from '${a}/update-${n}.dto'
|
|
1958
|
+
|
|
1959
|
+
@Repository()
|
|
1960
|
+
export class ${o}${t}Repository implements I${t}Repository {
|
|
1961
|
+
// TODO: Replace with your ${r} client/connection
|
|
1962
|
+
private store = new Map<string, ${t}ResponseDTO>()
|
|
1963
|
+
|
|
1964
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
1965
|
+
// TODO: Implement with ${r}
|
|
1966
|
+
return this.store.get(id) ?? null
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
1970
|
+
// TODO: Implement with ${r}
|
|
1971
|
+
return Array.from(this.store.values())
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
1975
|
+
// TODO: Implement with ${r}
|
|
1976
|
+
const all = Array.from(this.store.values())
|
|
1977
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
1978
|
+
return { data, total: all.length }
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
1982
|
+
// TODO: Implement with ${r}
|
|
1983
|
+
const now = new Date().toISOString()
|
|
1984
|
+
const entity: ${t}ResponseDTO = {
|
|
1985
|
+
id: randomUUID(),
|
|
1986
|
+
name: dto.name,
|
|
1987
|
+
createdAt: now,
|
|
1988
|
+
updatedAt: now,
|
|
1989
|
+
}
|
|
1990
|
+
this.store.set(entity.id, entity)
|
|
1991
|
+
return entity
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
1995
|
+
// TODO: Implement with ${r}
|
|
1996
|
+
const existing = this.store.get(id)
|
|
1997
|
+
if (!existing) throw HttpException.notFound('${t} not found')
|
|
1998
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
1999
|
+
this.store.set(id, updated)
|
|
2000
|
+
return updated
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
async delete(id: string): Promise<void> {
|
|
2004
|
+
// TODO: Implement with ${r}
|
|
2005
|
+
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
2006
|
+
this.store.delete(id)
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
`}function kn(e){let{pascal:t,kebab:n}=e;return`/**
|
|
2010
|
+
* ${t} Domain Service
|
|
2011
|
+
*
|
|
2012
|
+
* Domain layer — contains business rules that don't belong to a single entity.
|
|
2013
|
+
* Use this for cross-entity logic, validation rules, and domain invariants.
|
|
2014
|
+
* Keep it free of HTTP/framework concerns.
|
|
2015
|
+
*/
|
|
2016
|
+
import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
2017
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../repositories/${n}.repository'
|
|
2018
|
+
|
|
2019
|
+
@Service()
|
|
2020
|
+
export class ${t}DomainService {
|
|
2021
|
+
constructor(
|
|
2022
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2023
|
+
) {}
|
|
2024
|
+
|
|
2025
|
+
async ensureExists(id: string): Promise<void> {
|
|
2026
|
+
const entity = await this.repo.findById(id)
|
|
2027
|
+
if (!entity) {
|
|
2028
|
+
throw HttpException.notFound('${t} not found')
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
`}function An(e){let{pascal:t,kebab:n}=e;return`/**
|
|
2033
|
+
* ${t} Entity
|
|
2034
|
+
*
|
|
2035
|
+
* Domain layer — the core business object.
|
|
2036
|
+
* Uses a private constructor with static factory methods (create, reconstitute)
|
|
2037
|
+
* to enforce invariants. Properties are accessed via getters to maintain encapsulation.
|
|
2038
|
+
*
|
|
2039
|
+
* Patterns used:
|
|
2040
|
+
* - Private constructor: prevents direct instantiation
|
|
2041
|
+
* - create(): factory for new entities (generates ID, sets timestamps)
|
|
2042
|
+
* - reconstitute(): factory for rebuilding from persistence (no side effects)
|
|
2043
|
+
* - changeName(): mutation method that enforces business rules
|
|
2044
|
+
*/
|
|
2045
|
+
import { ${t}Id } from '../value-objects/${n}-id.vo'
|
|
2046
|
+
|
|
2047
|
+
interface ${t}Props {
|
|
2048
|
+
id: ${t}Id
|
|
2049
|
+
name: string
|
|
2050
|
+
createdAt: Date
|
|
2051
|
+
updatedAt: Date
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
export class ${t} {
|
|
2055
|
+
private constructor(private props: ${t}Props) {}
|
|
2056
|
+
|
|
2057
|
+
static create(params: { name: string }): ${t} {
|
|
2058
|
+
const now = new Date()
|
|
2059
|
+
return new ${t}({
|
|
2060
|
+
id: ${t}Id.create(),
|
|
2061
|
+
name: params.name,
|
|
2062
|
+
createdAt: now,
|
|
2063
|
+
updatedAt: now,
|
|
2064
|
+
})
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
static reconstitute(props: ${t}Props): ${t} {
|
|
2068
|
+
return new ${t}(props)
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
get id(): ${t}Id {
|
|
2072
|
+
return this.props.id
|
|
2073
|
+
}
|
|
2074
|
+
get name(): string {
|
|
2075
|
+
return this.props.name
|
|
2076
|
+
}
|
|
2077
|
+
get createdAt(): Date {
|
|
2078
|
+
return this.props.createdAt
|
|
2079
|
+
}
|
|
2080
|
+
get updatedAt(): Date {
|
|
2081
|
+
return this.props.updatedAt
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
changeName(name: string): void {
|
|
2085
|
+
if (!name || name.trim().length === 0) {
|
|
2086
|
+
throw new Error('Name cannot be empty')
|
|
2087
|
+
}
|
|
2088
|
+
this.props.name = name.trim()
|
|
2089
|
+
this.props.updatedAt = new Date()
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
toJSON() {
|
|
2093
|
+
return {
|
|
2094
|
+
id: this.props.id.toString(),
|
|
2095
|
+
name: this.props.name,
|
|
2096
|
+
createdAt: this.props.createdAt.toISOString(),
|
|
2097
|
+
updatedAt: this.props.updatedAt.toISOString(),
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
`}function jn(e){let{pascal:t}=e;return`/**
|
|
2102
|
+
* ${t} ID Value Object
|
|
2103
|
+
*
|
|
2104
|
+
* Domain layer — wraps a primitive ID with type safety and validation.
|
|
2105
|
+
* Value objects are immutable and compared by value, not reference.
|
|
2106
|
+
*
|
|
2107
|
+
* ${t}Id.create() — generate a new UUID
|
|
2108
|
+
* ${t}Id.from(id) — wrap an existing ID string (validates non-empty)
|
|
2109
|
+
* id.equals(other) — compare two IDs by value
|
|
2110
|
+
*/
|
|
2111
|
+
import { randomUUID } from 'node:crypto'
|
|
2112
|
+
|
|
2113
|
+
export class ${t}Id {
|
|
2114
|
+
private constructor(private readonly value: string) {}
|
|
2115
|
+
|
|
2116
|
+
static create(): ${t}Id {
|
|
2117
|
+
return new ${t}Id(randomUUID())
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
static from(id: string): ${t}Id {
|
|
2121
|
+
if (!id || id.trim().length === 0) {
|
|
2122
|
+
throw new Error('${t}Id cannot be empty')
|
|
2123
|
+
}
|
|
2124
|
+
return new ${t}Id(id)
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
toString(): string {
|
|
2128
|
+
return this.value
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
equals(other: ${t}Id): boolean {
|
|
2132
|
+
return this.value === other.value
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
`}function Mn(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
2136
|
+
import { Container } from '@forinda/kickjs'
|
|
2137
|
+
|
|
2138
|
+
describe('${t}Controller', () => {
|
|
2139
|
+
beforeEach(() => {
|
|
2140
|
+
Container.reset()
|
|
2141
|
+
})
|
|
2142
|
+
|
|
2143
|
+
it('should be defined', () => {
|
|
2144
|
+
expect(true).toBe(true)
|
|
2145
|
+
})
|
|
2146
|
+
|
|
2147
|
+
describe('POST /${r}', () => {
|
|
2148
|
+
it('should create a new ${n}', async () => {
|
|
2149
|
+
// TODO: Set up test module, call create endpoint, assert 201
|
|
2150
|
+
expect(true).toBe(true)
|
|
2151
|
+
})
|
|
2152
|
+
})
|
|
2153
|
+
|
|
2154
|
+
describe('GET /${r}', () => {
|
|
2155
|
+
it('should return paginated ${r}', async () => {
|
|
2156
|
+
// TODO: Set up test module, call list endpoint, assert { data, meta }
|
|
2157
|
+
expect(true).toBe(true)
|
|
2158
|
+
})
|
|
2159
|
+
})
|
|
2160
|
+
|
|
2161
|
+
describe('GET /${r}/:id', () => {
|
|
2162
|
+
it('should return a ${n} by id', async () => {
|
|
2163
|
+
// TODO: Create a ${n}, then fetch by id, assert match
|
|
2164
|
+
expect(true).toBe(true)
|
|
2165
|
+
})
|
|
2166
|
+
|
|
2167
|
+
it('should return 404 for non-existent ${n}', async () => {
|
|
2168
|
+
// TODO: Fetch non-existent id, assert 404
|
|
2169
|
+
expect(true).toBe(true)
|
|
2170
|
+
})
|
|
2171
|
+
})
|
|
2172
|
+
|
|
2173
|
+
describe('PUT /${r}/:id', () => {
|
|
2174
|
+
it('should update an existing ${n}', async () => {
|
|
2175
|
+
// TODO: Create, update, assert changes
|
|
2176
|
+
expect(true).toBe(true)
|
|
2177
|
+
})
|
|
2178
|
+
})
|
|
2179
|
+
|
|
2180
|
+
describe('DELETE /${r}/:id', () => {
|
|
2181
|
+
it('should delete a ${n}', async () => {
|
|
2182
|
+
// TODO: Create, delete, assert gone
|
|
2183
|
+
expect(true).toBe(true)
|
|
2184
|
+
})
|
|
2185
|
+
})
|
|
2186
|
+
})
|
|
2187
|
+
`}function Nn(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'
|
|
2188
|
+
import { InMemory${t}Repository } from '${i}'
|
|
2189
|
+
|
|
2190
|
+
describe('InMemory${t}Repository', () => {
|
|
2191
|
+
let repo: InMemory${t}Repository
|
|
2192
|
+
|
|
2193
|
+
beforeEach(() => {
|
|
2194
|
+
repo = new InMemory${t}Repository()
|
|
2195
|
+
})
|
|
2196
|
+
|
|
2197
|
+
it('should create and retrieve a ${n}', async () => {
|
|
2198
|
+
const created = await repo.create({ name: 'Test ${t}' })
|
|
2199
|
+
expect(created).toBeDefined()
|
|
2200
|
+
expect(created.name).toBe('Test ${t}')
|
|
2201
|
+
expect(created.id).toBeDefined()
|
|
2202
|
+
|
|
2203
|
+
const found = await repo.findById(created.id)
|
|
2204
|
+
expect(found).toEqual(created)
|
|
2205
|
+
})
|
|
2206
|
+
|
|
2207
|
+
it('should return null for non-existent id', async () => {
|
|
2208
|
+
const found = await repo.findById('non-existent')
|
|
2209
|
+
expect(found).toBeNull()
|
|
2210
|
+
})
|
|
2211
|
+
|
|
2212
|
+
it('should list all ${r}', async () => {
|
|
2213
|
+
await repo.create({ name: '${t} 1' })
|
|
2214
|
+
await repo.create({ name: '${t} 2' })
|
|
2215
|
+
|
|
2216
|
+
const all = await repo.findAll()
|
|
2217
|
+
expect(all).toHaveLength(2)
|
|
2218
|
+
})
|
|
2219
|
+
|
|
2220
|
+
it('should return paginated results', async () => {
|
|
2221
|
+
await repo.create({ name: '${t} 1' })
|
|
2222
|
+
await repo.create({ name: '${t} 2' })
|
|
2223
|
+
await repo.create({ name: '${t} 3' })
|
|
2224
|
+
|
|
2225
|
+
const result = await repo.findPaginated({
|
|
2226
|
+
filters: [],
|
|
2227
|
+
sort: [],
|
|
2228
|
+
search: '',
|
|
2229
|
+
pagination: { page: 1, limit: 2, offset: 0 },
|
|
2230
|
+
})
|
|
2231
|
+
|
|
2232
|
+
expect(result.data).toHaveLength(2)
|
|
2233
|
+
expect(result.total).toBe(3)
|
|
2234
|
+
})
|
|
2235
|
+
|
|
2236
|
+
it('should update a ${n}', async () => {
|
|
2237
|
+
const created = await repo.create({ name: 'Original' })
|
|
2238
|
+
const updated = await repo.update(created.id, { name: 'Updated' })
|
|
2239
|
+
expect(updated.name).toBe('Updated')
|
|
2240
|
+
})
|
|
2241
|
+
|
|
2242
|
+
it('should delete a ${n}', async () => {
|
|
2243
|
+
const created = await repo.create({ name: 'To Delete' })
|
|
2244
|
+
await repo.delete(created.id)
|
|
2245
|
+
const found = await repo.findById(created.id)
|
|
2246
|
+
expect(found).toBeNull()
|
|
2247
|
+
})
|
|
2248
|
+
})
|
|
2249
|
+
`}function Pn(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
2250
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
2251
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
|
|
2252
|
+
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
2253
|
+
import type { Create${t}DTO } from './dtos/create-${n}.dto'
|
|
2254
|
+
import type { Update${t}DTO } from './dtos/update-${n}.dto'
|
|
2255
|
+
|
|
2256
|
+
@Service()
|
|
2257
|
+
export class ${t}Service {
|
|
2258
|
+
constructor(
|
|
2259
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2260
|
+
) {}
|
|
2261
|
+
|
|
2262
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
2263
|
+
return this.repo.findById(id)
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
2267
|
+
return this.repo.findAll()
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
async findPaginated(parsed: ParsedQuery) {
|
|
2271
|
+
return this.repo.findPaginated(parsed)
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
2275
|
+
return this.repo.create(dto)
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
2279
|
+
return this.repo.update(id, dto)
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
async delete(id: string): Promise<void> {
|
|
2283
|
+
await this.repo.delete(id)
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
`}function Fn(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
2287
|
+
|
|
2288
|
+
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
2289
|
+
filterable: ['name'],
|
|
2290
|
+
sortable: ['name', 'createdAt'],
|
|
2291
|
+
searchable: ['name'],
|
|
2292
|
+
}
|
|
2293
|
+
`}function In(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=`/**
|
|
2294
|
+
* ${t} Module — CQRS Pattern
|
|
2295
|
+
*
|
|
2296
|
+
* Separates read (queries) and write (commands) operations.
|
|
2297
|
+
* Events are emitted after state changes and can be handled via
|
|
2298
|
+
* WebSocket broadcasts, queue jobs, or ETL pipelines.
|
|
2299
|
+
*
|
|
2300
|
+
* Structure:
|
|
2301
|
+
* commands/ — Write operations (create, update, delete)
|
|
2302
|
+
* queries/ — Read operations (get, list)
|
|
2303
|
+
* events/ — Domain events + handlers (WS broadcast, queue dispatch)
|
|
2304
|
+
* dtos/ — Request/response schemas
|
|
2305
|
+
*/`,f=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
|
|
2306
|
+
import { ${c} } from './${l}.repository'
|
|
2307
|
+
import { ${t}Controller } from './${n}.controller'
|
|
2308
|
+
|
|
2309
|
+
// Eagerly load decorated classes
|
|
2310
|
+
import.meta.glob(
|
|
2311
|
+
[
|
|
2312
|
+
'./commands/**/*.ts',
|
|
2313
|
+
'./queries/**/*.ts',
|
|
2314
|
+
'./events/**/*.ts',
|
|
2315
|
+
'!./**/*.test.ts',
|
|
2316
|
+
],
|
|
2317
|
+
{ eager: true },
|
|
2318
|
+
)`,p=` /**
|
|
2319
|
+
* Declare HTTP routes for this CQRS module. Return value shape:
|
|
2320
|
+
*
|
|
2321
|
+
* - \`path\` — URL prefix for this route set.
|
|
2322
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
2323
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
2324
|
+
*
|
|
2325
|
+
* Return an array to mount multiple route sets:
|
|
2326
|
+
*
|
|
2327
|
+
* return [
|
|
2328
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
2329
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
2330
|
+
* ]
|
|
2331
|
+
*/`;return u===`class`?`${d}
|
|
2332
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
2333
|
+
${f}
|
|
2334
|
+
|
|
2335
|
+
export class ${t}Module implements AppModule {
|
|
2336
|
+
register(container: Container): void {
|
|
2337
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
2338
|
+
container.resolve(${c}),
|
|
2339
|
+
)
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
${p.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
2343
|
+
routes(): ModuleRoutes {
|
|
2344
|
+
return {
|
|
2345
|
+
path: '/${r}',
|
|
2346
|
+
controller: ${t}Controller,
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
`:`${d}
|
|
2351
|
+
import { defineModule } from '@forinda/kickjs'
|
|
2352
|
+
${f}
|
|
2353
|
+
|
|
2354
|
+
export const ${t}Module = defineModule({
|
|
2355
|
+
name: '${t}Module',
|
|
2356
|
+
build: () => ({
|
|
2357
|
+
register(container) {
|
|
2358
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
2359
|
+
container.resolve(${c}),
|
|
2360
|
+
)
|
|
2361
|
+
},
|
|
2362
|
+
|
|
2363
|
+
${p}
|
|
2364
|
+
routes() {
|
|
2365
|
+
return {
|
|
2366
|
+
path: '/${r}',
|
|
2367
|
+
controller: ${t}Controller,
|
|
2368
|
+
}
|
|
2369
|
+
},
|
|
2370
|
+
}),
|
|
2371
|
+
})
|
|
2372
|
+
`}function Ln(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'
|
|
2373
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
2374
|
+
import { Create${t}Command } from './commands/create-${n}.command'
|
|
2375
|
+
import { Update${t}Command } from './commands/update-${n}.command'
|
|
2376
|
+
import { Delete${t}Command } from './commands/delete-${n}.command'
|
|
2377
|
+
import { Get${t}Query } from './queries/get-${n}.query'
|
|
2378
|
+
import { List${i}Query } from './queries/list-${r}.query'
|
|
2379
|
+
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
2380
|
+
import { update${t}Schema } from './dtos/update-${n}.dto'
|
|
2381
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
2382
|
+
|
|
2383
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
2384
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
2385
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
2386
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
2387
|
+
|
|
2388
|
+
@Controller()
|
|
2389
|
+
export class ${t}Controller {
|
|
2390
|
+
@Autowired() private readonly create${t}Command!: Create${t}Command
|
|
2391
|
+
@Autowired() private readonly update${t}Command!: Update${t}Command
|
|
2392
|
+
@Autowired() private readonly delete${t}Command!: Delete${t}Command
|
|
2393
|
+
@Autowired() private readonly get${t}Query!: Get${t}Query
|
|
2394
|
+
@Autowired() private readonly list${i}Query!: List${i}Query
|
|
2395
|
+
|
|
2396
|
+
@Get('/')
|
|
2397
|
+
@ApiTags('${t}')
|
|
2398
|
+
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
2399
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
2400
|
+
return ctx.paginate(
|
|
2401
|
+
(parsed) => this.list${i}Query.execute(parsed),
|
|
2402
|
+
${t.toUpperCase()}_QUERY_CONFIG,
|
|
2403
|
+
)
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
@Get('/:id')
|
|
2407
|
+
@ApiTags('${t}')
|
|
2408
|
+
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
2409
|
+
const result = await this.get${t}Query.execute(ctx.params.id)
|
|
2410
|
+
if (!result) return ctx.notFound('${t} not found')
|
|
2411
|
+
ctx.json(result)
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
2415
|
+
@ApiTags('${t}')
|
|
2416
|
+
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
2417
|
+
const result = await this.create${t}Command.execute(ctx.body)
|
|
2418
|
+
ctx.created(result)
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
2422
|
+
@ApiTags('${t}')
|
|
2423
|
+
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
2424
|
+
const result = await this.update${t}Command.execute(ctx.params.id, ctx.body)
|
|
2425
|
+
ctx.json(result)
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
@Delete('/:id')
|
|
2429
|
+
@ApiTags('${t}')
|
|
2430
|
+
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
2431
|
+
await this.delete${t}Command.execute(ctx.params.id)
|
|
2432
|
+
ctx.noContent()
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
`}function Rn(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
2436
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
2437
|
+
import type { Create${t}DTO } from '../dtos/create-${n}.dto'
|
|
2438
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
2439
|
+
import { ${t}Events } from '../events/${n}.events'
|
|
2440
|
+
|
|
2441
|
+
@Service()
|
|
2442
|
+
export class Create${t}Command {
|
|
2443
|
+
constructor(
|
|
2444
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2445
|
+
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
2446
|
+
) {}
|
|
2447
|
+
|
|
2448
|
+
async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
2449
|
+
const result = await this.repo.create(dto)
|
|
2450
|
+
this.events.emit('${n}.created', result)
|
|
2451
|
+
return result
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
`},{file:`update-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
2455
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
2456
|
+
import type { Update${t}DTO } from '../dtos/update-${n}.dto'
|
|
2457
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
2458
|
+
import { ${t}Events } from '../events/${n}.events'
|
|
2459
|
+
|
|
2460
|
+
@Service()
|
|
2461
|
+
export class Update${t}Command {
|
|
2462
|
+
constructor(
|
|
2463
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2464
|
+
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
2465
|
+
) {}
|
|
2466
|
+
|
|
2467
|
+
async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
2468
|
+
const result = await this.repo.update(id, dto)
|
|
2469
|
+
this.events.emit('${n}.updated', result)
|
|
2470
|
+
return result
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
`},{file:`delete-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
2474
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
2475
|
+
import { ${t}Events } from '../events/${n}.events'
|
|
2476
|
+
|
|
2477
|
+
@Service()
|
|
2478
|
+
export class Delete${t}Command {
|
|
2479
|
+
constructor(
|
|
2480
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2481
|
+
@Inject(${t}Events) private readonly events: ${t}Events,
|
|
2482
|
+
) {}
|
|
2483
|
+
|
|
2484
|
+
async execute(id: string): Promise<void> {
|
|
2485
|
+
await this.repo.delete(id)
|
|
2486
|
+
this.events.emit('${n}.deleted', { id })
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
`}]}function zn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
2490
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
2491
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
2492
|
+
|
|
2493
|
+
@Service()
|
|
2494
|
+
export class Get${t}Query {
|
|
2495
|
+
constructor(
|
|
2496
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2497
|
+
) {}
|
|
2498
|
+
|
|
2499
|
+
async execute(id: string): Promise<${t}ResponseDTO | null> {
|
|
2500
|
+
return this.repo.findById(id)
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
`},{file:`list-${r}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
2504
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
|
|
2505
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
2506
|
+
|
|
2507
|
+
@Service()
|
|
2508
|
+
export class List${i}Query {
|
|
2509
|
+
constructor(
|
|
2510
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
2511
|
+
) {}
|
|
2512
|
+
|
|
2513
|
+
async execute(parsed: ParsedQuery) {
|
|
2514
|
+
return this.repo.findPaginated(parsed)
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
`}]}function Bn(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
|
|
2518
|
+
import { EventEmitter } from 'node:events'
|
|
2519
|
+
import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
|
|
2520
|
+
|
|
2521
|
+
/**
|
|
2522
|
+
* ${t} domain event types.
|
|
2523
|
+
*
|
|
2524
|
+
* These events are emitted by commands after state changes.
|
|
2525
|
+
* Subscribe to them in event handlers for side effects:
|
|
2526
|
+
* - WebSocket broadcasts (real-time UI updates)
|
|
2527
|
+
* - Queue jobs (async processing, ETL pipelines)
|
|
2528
|
+
* - Audit logging
|
|
2529
|
+
* - Cache invalidation
|
|
2530
|
+
*/
|
|
2531
|
+
export interface ${t}EventMap {
|
|
2532
|
+
'${n}.created': ${t}ResponseDTO
|
|
2533
|
+
'${n}.updated': ${t}ResponseDTO
|
|
2534
|
+
'${n}.deleted': { id: string }
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
@Service()
|
|
2538
|
+
export class ${t}Events {
|
|
2539
|
+
private emitter = new EventEmitter()
|
|
2540
|
+
|
|
2541
|
+
emit<K extends keyof ${t}EventMap>(event: K, data: ${t}EventMap[K]): void {
|
|
2542
|
+
this.emitter.emit(event, data)
|
|
2543
|
+
}
|
|
2544
|
+
|
|
2545
|
+
on<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
|
|
2546
|
+
this.emitter.on(event, handler)
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
off<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
|
|
2550
|
+
this.emitter.off(event, handler)
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
`},{file:`on-${n}-change.handler.ts`,content:`import { Service, Autowired } from '@forinda/kickjs'
|
|
2554
|
+
import { ${t}Events } from './${n}.events'
|
|
2555
|
+
|
|
2556
|
+
/**
|
|
2557
|
+
* ${t} Change Event Handler
|
|
2558
|
+
*
|
|
2559
|
+
* Reacts to domain events emitted by commands.
|
|
2560
|
+
* Wire up side effects here:
|
|
2561
|
+
*
|
|
2562
|
+
* 1. WebSocket broadcast — notify connected clients in real-time
|
|
2563
|
+
* import { WsGateway } from '@forinda/kickjs-ws'
|
|
2564
|
+
* this.ws.broadcast('${n}-channel', { event, data })
|
|
2565
|
+
*
|
|
2566
|
+
* 2. Queue dispatch — offload heavy processing to background workers
|
|
2567
|
+
* import { QueueService } from '@forinda/kickjs-queue'
|
|
2568
|
+
* this.queue.add('${n}-etl', { action: event, payload: data })
|
|
2569
|
+
*
|
|
2570
|
+
* 3. ETL pipeline — transform and load data to external systems
|
|
2571
|
+
* await this.etlPipeline.process(data)
|
|
2572
|
+
*/
|
|
2573
|
+
@Service()
|
|
2574
|
+
export class On${t}ChangeHandler {
|
|
2575
|
+
@Autowired() private events!: ${t}Events
|
|
2576
|
+
|
|
2577
|
+
// Uncomment to inject WebSocket and Queue services:
|
|
2578
|
+
// @Autowired() private ws!: WsGateway
|
|
2579
|
+
// @Autowired() private queue!: QueueService
|
|
2580
|
+
|
|
2581
|
+
onInit(): void {
|
|
2582
|
+
this.events.on('${n}.created', (data) => {
|
|
2583
|
+
console.log('[${t}] Created:', data.id)
|
|
2584
|
+
// TODO: Broadcast via WebSocket
|
|
2585
|
+
// this.ws.broadcast('${n}-channel', { event: '${n}.created', data })
|
|
2586
|
+
// TODO: Dispatch to queue for async processing / ETL
|
|
2587
|
+
// this.queue.add('${n}-etl', { action: 'create', payload: data })
|
|
2588
|
+
})
|
|
2589
|
+
|
|
2590
|
+
this.events.on('${n}.updated', (data) => {
|
|
2591
|
+
console.log('[${t}] Updated:', data.id)
|
|
2592
|
+
// TODO: Broadcast via WebSocket
|
|
2593
|
+
// this.ws.broadcast('${n}-channel', { event: '${n}.updated', data })
|
|
2594
|
+
})
|
|
2595
|
+
|
|
2596
|
+
this.events.on('${n}.deleted', (data) => {
|
|
2597
|
+
console.log('[${t}] Deleted:', data.id)
|
|
2598
|
+
// TODO: Broadcast via WebSocket
|
|
2599
|
+
// this.ws.broadcast('${n}-channel', { event: '${n}.deleted', data })
|
|
2600
|
+
})
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
`}]}function Vn(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
2604
|
+
* Drizzle ${t} Repository
|
|
2605
|
+
*
|
|
2606
|
+
* Implements the repository interface using Drizzle ORM.
|
|
2607
|
+
* Uses buildFromColumns() with Column objects for type-safe query building.
|
|
2608
|
+
*
|
|
2609
|
+
* TODO: Update the schema import to match your Drizzle schema file.
|
|
2610
|
+
* TODO: Replace DRIZZLE_DB injection token with your actual database token.
|
|
2611
|
+
*
|
|
2612
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
2613
|
+
*/
|
|
2614
|
+
import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
|
|
2615
|
+
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
2616
|
+
import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
|
|
2617
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
2618
|
+
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
2619
|
+
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
2620
|
+
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
2621
|
+
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
2622
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from '../../constants'
|
|
2623
|
+
|
|
2624
|
+
// TODO: Import your Drizzle schema table — e.g.:
|
|
2625
|
+
// import { ${n}s } from '@/db/schema'
|
|
2626
|
+
|
|
2627
|
+
const queryAdapter = new DrizzleQueryAdapter({
|
|
2628
|
+
eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
|
|
2629
|
+
})
|
|
2630
|
+
|
|
2631
|
+
@Repository()
|
|
2632
|
+
export class Drizzle${t}Repository implements I${t}Repository {
|
|
2633
|
+
constructor(@Inject(DRIZZLE_DB) private db: any) {}
|
|
2634
|
+
|
|
2635
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
2636
|
+
// TODO: Implement with Drizzle
|
|
2637
|
+
// const row = this.db.select().from(${n}s).where(eq(${n}s.id, id)).get()
|
|
2638
|
+
// return row ?? null
|
|
2639
|
+
throw new Error('Drizzle ${t} repository not yet implemented — update schema imports and queries')
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
2643
|
+
// TODO: Implement with Drizzle
|
|
2644
|
+
// return this.db.select().from(${n}s).all()
|
|
2645
|
+
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
2649
|
+
// TODO: Use buildFromColumns() with your query config for type-safe filtering
|
|
2650
|
+
// const query = queryAdapter.buildFromColumns(parsed, ${t.toUpperCase()}_QUERY_CONFIG)
|
|
2651
|
+
//
|
|
2652
|
+
// const data = this.db
|
|
2653
|
+
// .select().from(${n}s).$dynamic()
|
|
2654
|
+
// .where(query.where).orderBy(...query.orderBy)
|
|
2655
|
+
// .limit(query.limit).offset(query.offset).all()
|
|
2656
|
+
//
|
|
2657
|
+
// const totalResult = this.db
|
|
2658
|
+
// .select({ count: count() }).from(${n}s)
|
|
2659
|
+
// .$dynamic().where(query.where).get()
|
|
2660
|
+
//
|
|
2661
|
+
// return { data, total: totalResult?.count ?? 0 }
|
|
2662
|
+
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
2666
|
+
// TODO: Implement with Drizzle
|
|
2667
|
+
// return this.db.insert(${n}s).values(dto).returning().get()
|
|
2668
|
+
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
2672
|
+
// TODO: Implement with Drizzle
|
|
2673
|
+
// const row = this.db.update(${n}s).set(dto).where(eq(${n}s.id, id)).returning().get()
|
|
2674
|
+
// if (!row) throw HttpException.notFound('${t} not found')
|
|
2675
|
+
// return row
|
|
2676
|
+
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
async delete(id: string): Promise<void> {
|
|
2680
|
+
// TODO: Implement with Drizzle
|
|
2681
|
+
// this.db.delete(${n}s).where(eq(${n}s.id, id)).run()
|
|
2682
|
+
throw new Error('Drizzle ${t} repository not yet implemented')
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
`}function Hn(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
|
|
2686
|
+
// TODO: Import your schema table and reference actual columns for type safety
|
|
2687
|
+
// import { ${n}s } from '@/db/schema'
|
|
2688
|
+
|
|
2689
|
+
export const ${t.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
|
|
2690
|
+
columns: {
|
|
2691
|
+
// Replace with actual Drizzle Column references for type-safe filtering:
|
|
2692
|
+
// name: ${n}s.name,
|
|
2693
|
+
// status: ${n}s.status,
|
|
2694
|
+
},
|
|
2695
|
+
sortable: {
|
|
2696
|
+
// name: ${n}s.name,
|
|
2697
|
+
// createdAt: ${n}s.createdAt,
|
|
2698
|
+
},
|
|
2699
|
+
searchColumns: [
|
|
2700
|
+
// ${n}s.name,
|
|
2701
|
+
],
|
|
2702
|
+
}
|
|
2703
|
+
`}function Un(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`/**
|
|
2704
|
+
* Prisma ${t} Repository
|
|
2705
|
+
*
|
|
2706
|
+
* Implements the repository interface using Prisma Client.
|
|
2707
|
+
* Requires a PrismaClient instance injected via the DI container.
|
|
2708
|
+
*
|
|
2709
|
+
* Ensure your Prisma schema has a '${t}' model defined.
|
|
2710
|
+
*
|
|
2711
|
+
* For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
|
|
2712
|
+
* @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
|
|
2713
|
+
*
|
|
2714
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
2715
|
+
*/
|
|
2716
|
+
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
2717
|
+
import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
|
|
2718
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
2719
|
+
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
2720
|
+
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
2721
|
+
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
2722
|
+
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
2723
|
+
|
|
2724
|
+
@Repository()
|
|
2725
|
+
export class Prisma${t}Repository implements I${t}Repository {
|
|
2726
|
+
@Inject(PRISMA_CLIENT) private prisma!: { ${a}: PrismaModelDelegate }
|
|
2727
|
+
|
|
2728
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
2729
|
+
return this.prisma.${a}.findUnique({ where: { id } }) as Promise<${t}ResponseDTO | null>
|
|
2730
|
+
}
|
|
2731
|
+
|
|
2732
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
2733
|
+
return this.prisma.${a}.findMany() as Promise<${t}ResponseDTO[]>
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
2737
|
+
const [data, total] = await Promise.all([
|
|
2738
|
+
this.prisma.${a}.findMany({
|
|
2739
|
+
skip: parsed.pagination.offset,
|
|
2740
|
+
take: parsed.pagination.limit,
|
|
2741
|
+
}) as Promise<${t}ResponseDTO[]>,
|
|
2742
|
+
this.prisma.${a}.count(),
|
|
2743
|
+
])
|
|
2744
|
+
return { data, total }
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
2748
|
+
return this.prisma.${a}.create({ data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
|
|
2749
|
+
}
|
|
2750
|
+
|
|
2751
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
2752
|
+
const existing = await this.prisma.${a}.findUnique({ where: { id } })
|
|
2753
|
+
if (!existing) throw HttpException.notFound('${t} not found')
|
|
2754
|
+
return this.prisma.${a}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
|
|
2755
|
+
}
|
|
2756
|
+
|
|
2757
|
+
async delete(id: string): Promise<void> {
|
|
2758
|
+
await this.prisma.${a}.deleteMany({ where: { id } })
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
`}async function Wn(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,yn({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
|
|
2762
|
+
|
|
2763
|
+
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
2764
|
+
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
2765
|
+
|
|
2766
|
+
@Controller()
|
|
2767
|
+
export class ${t}Controller {
|
|
2768
|
+
@Get('/')
|
|
2769
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
2770
|
+
ctx.json({ message: '${t} list' })
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
`)}async function Gn(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`,vn({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,Fn({pascal:t,kebab:n})),await u(`${n}.controller.ts`,xn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`${n}.service.ts`,Pn({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,Cn({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,wn({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,Tn({pascal:t,kebab:n})),await u(`${n}.repository.ts`,Dn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let d={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},f={inmemory:()=>V({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>Vn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>Un({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},p=d[a]??`${R(a)}-${n}`,m=f[a]??(()=>On({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`,V({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,Mn({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,Nn({pascal:t,kebab:n,plural:r,repoPrefix:`../${d.inmemory??`in-memory-${n}`}.repository`})))}async function Kn(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`,In({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,Fn({pascal:t,kebab:n})),await u(`${n}.controller.ts`,Ln({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`dtos/create-${n}.dto.ts`,Cn({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,wn({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,Tn({pascal:t,kebab:n}));let d=Rn({pascal:t,kebab:n});for(let e of d)await u(`commands/${e.file}`,e.content);let f=zn({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await u(`queries/${e.file}`,e.content);let p=Bn({pascal:t,kebab:n});for(let e of p)await u(`events/${e.file}`,e.content);await u(`${n}.repository.ts`,Dn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let m={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},h={inmemory:()=>V({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>Vn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>Un({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},g=m[a]??`${R(a)}-${n}`,_=h[a]??(()=>On({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${g}.repository.ts`,_()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,V({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,Mn({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,Nn({pascal:t,kebab:n,plural:r,repoPrefix:`../${m.inmemory??`in-memory-${n}`}.repository`})))}async function qn(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`,_n({pascal:t,kebab:n,plural:r,repo:a,style:u})),await d(`constants.ts`,a===`drizzle`?Hn({pascal:t,kebab:n}):Sn({pascal:t,kebab:n})),await d(`presentation/${n}.controller.ts`,bn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await d(`application/dtos/create-${n}.dto.ts`,Cn({pascal:t,kebab:n})),await d(`application/dtos/update-${n}.dto.ts`,wn({pascal:t,kebab:n})),await d(`application/dtos/${n}-response.dto.ts`,Tn({pascal:t,kebab:n}));let f=En({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`,Dn({pascal:t,kebab:n,tokenScope:l})),await d(`domain/services/${n}-domain.service.ts`,kn({pascal:t,kebab:n}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>V({pascal:t,kebab:n}),drizzle:()=>Vn({pascal:t,kebab:n}),prisma:()=>Un({pascal:t,kebab:n,prismaClientPath:c})},h=p[a]??`${R(a)}-${n}`,g=m[a]??(()=>On({pascal:t,kebab:n,repoType:a}));await d(`infrastructure/repositories/${h}.repository.ts`,g()),o||(await d(`domain/entities/${n}.entity.ts`,An({pascal:t,kebab:n})),await d(`domain/value-objects/${n}-id.vo.ts`,jn({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await d(`infrastructure/repositories/in-memory-${n}.repository.ts`,V({pascal:t,kebab:n})),await d(`__tests__/${n}.controller.test.ts`,Mn({pascal:t,kebab:n,plural:r})),await d(`__tests__/${n}.repository.test.ts`,Nn({pascal:t,kebab:n,plural:r})))}function Jn(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Yn(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`ddd`;e.minimal&&(l=`minimal`);let u=R(t),d=I(t),f=c?z(u):u,p=c?Xt(d):d,m=h(n,f),g=[],_=o??!1,v={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=h(m,e);if(s){g.push(n);return}if(!_&&await Xe(n)&&!await P({message:`File exists: ${E.dim(e)}. Overwrite?`,initialValue:!1})){F.warn(`Skipped: ${e}`);return}await M(n,t),g.push(n)},files:g};switch(l){case`minimal`:await Wn(v);break;case`rest`:await Gn(v);break;case`cqrs`:await Kn(v);break;default:await qn(v);break}return s||await Xn(n,d,f,u,v.style),g}async function Xn(e,t,n,r,i=`define`){let a=h(e,`index.ts`),o=await Xe(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await M(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
2774
|
+
import { ${t}Module } from '${s}'
|
|
2775
|
+
|
|
2776
|
+
export const modules: AppModuleEntry[] = [${c}]
|
|
2777
|
+
`:`import { defineModules } from '@forinda/kickjs'
|
|
2778
|
+
import { ${t}Module } from '${s}'
|
|
2779
|
+
|
|
2780
|
+
export const modules = defineModules().mount(${c})
|
|
2781
|
+
`);return}let l=await C(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=B(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${B(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
2782
|
+
`,e);l=l.slice(0,t+1)+u+`
|
|
2783
|
+
`+l.slice(t+1)}else l=u+`
|
|
2784
|
+
`+l}let f=Qn(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${B(t)}Module\\b`).test(e)||(l=Zn(l,c))}else l=Zn(l,c);await w(a,l,`utf-8`)}function Zn(e,t){let n=Qn(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 Qn(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=tr(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=$n(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function $n(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=nr(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=nr(e,t);if(n===-1)break;i=n+1}return i}function er(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
2785
|
+
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function tr(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=er(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 nr(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=er(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 rr(e){let{name:t,outDir:n}=e,r=R(t),i=I(t),a=[],o=h(n,`${r}.adapter.ts`);return await M(o,`import {
|
|
2786
|
+
defineAdapter,
|
|
2787
|
+
type AdapterContext,
|
|
2788
|
+
type AdapterMiddleware,
|
|
2789
|
+
type ContributorRegistrations,
|
|
2790
|
+
type Constructor,
|
|
2791
|
+
} from '@forinda/kickjs'
|
|
2792
|
+
|
|
2793
|
+
/**
|
|
2794
|
+
* Configuration for the ${i} adapter.
|
|
2795
|
+
*
|
|
2796
|
+
* Adapters typically take a small config object so callers can tune
|
|
2797
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
2798
|
+
* derived from the environment should be read inside the build
|
|
2799
|
+
* function via getEnv(), not forced onto the caller.
|
|
2800
|
+
*/
|
|
2801
|
+
export interface ${i}AdapterConfig {
|
|
2802
|
+
// Add your adapter configuration here, e.g.:
|
|
2803
|
+
// enabled?: boolean
|
|
2804
|
+
// apiKey?: string
|
|
2805
|
+
}
|
|
2806
|
+
|
|
2807
|
+
/**
|
|
2808
|
+
* ${i} adapter — built via \`defineAdapter()\` so callers get the
|
|
2809
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
2810
|
+
*
|
|
2811
|
+
* Hooks into the Application lifecycle to add middleware, routes,
|
|
2812
|
+
* Context Contributors, or external service connections.
|
|
2813
|
+
*
|
|
2814
|
+
* Every lifecycle hook below is OPTIONAL. The scaffold emits all of
|
|
2815
|
+
* them so adopters can browse what's available and delete what they
|
|
2816
|
+
* don't need — \`build()\` returning \`{}\` is also valid for an adapter
|
|
2817
|
+
* that only contributes config defaults.
|
|
2818
|
+
*
|
|
2819
|
+
* @example
|
|
2820
|
+
* \`\`\`ts
|
|
2821
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
2822
|
+
* import { ${i}Adapter } from './adapters/${r}.adapter'
|
|
2823
|
+
*
|
|
2824
|
+
* bootstrap({
|
|
2825
|
+
* modules,
|
|
2826
|
+
* adapters: [${i}Adapter({ /* config overrides *\\/ })],
|
|
2827
|
+
* })
|
|
2828
|
+
* \`\`\`
|
|
2829
|
+
*/
|
|
2830
|
+
export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
2831
|
+
name: '${i}Adapter',
|
|
2832
|
+
defaults: {
|
|
2833
|
+
// Default config values go here. The adopter's overrides shallow-merge
|
|
2834
|
+
// on top of these before \`build()\` runs.
|
|
2835
|
+
},
|
|
2836
|
+
build: (_config, { name: _name }) => {
|
|
2837
|
+
// Closures inside \`build()\` are how each adapter instance owns its
|
|
2838
|
+
// own state (database client, Map, timer handle, …). The same
|
|
2839
|
+
// \`_config\` is visible to every hook below.
|
|
2840
|
+
|
|
2841
|
+
return {
|
|
2842
|
+
/**
|
|
2843
|
+
* Express middleware entries the Application mounts at named phases.
|
|
2844
|
+
*
|
|
2845
|
+
* \`phase\` controls where each handler sits in the pipeline:
|
|
2846
|
+
* 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
|
|
2847
|
+
*
|
|
2848
|
+
* \`path\` (optional) scopes the entry to a path prefix.
|
|
2849
|
+
*
|
|
2850
|
+
* Delete this hook entirely if you don't add middleware.
|
|
2851
|
+
*/
|
|
2852
|
+
middleware(): AdapterMiddleware[] {
|
|
2853
|
+
return [
|
|
2854
|
+
// Example: add a custom header to all responses
|
|
2855
|
+
// {
|
|
2856
|
+
// phase: 'beforeGlobal',
|
|
2857
|
+
// handler: (_req, res, next) => {
|
|
2858
|
+
// res.setHeader('X-${i}', 'true')
|
|
2859
|
+
// next()
|
|
2860
|
+
// },
|
|
2861
|
+
// },
|
|
2862
|
+
// Example: scope a rate limiter to one path prefix
|
|
2863
|
+
// {
|
|
2864
|
+
// phase: 'beforeRoutes',
|
|
2865
|
+
// path: '/api/v1/auth',
|
|
2866
|
+
// handler: rateLimit({ max: 10 }),
|
|
2867
|
+
// },
|
|
2868
|
+
]
|
|
2869
|
+
},
|
|
2870
|
+
|
|
2871
|
+
/**
|
|
2872
|
+
* Runs BEFORE global middleware. Mount routes that should bypass the
|
|
2873
|
+
* middleware stack — health checks, docs UI, static assets, OAuth
|
|
2874
|
+
* callbacks. Anything you want reachable even if a global middleware
|
|
2875
|
+
* later in the chain rejects requests.
|
|
2876
|
+
*
|
|
2877
|
+
* Delete this hook if you have no early routes.
|
|
2878
|
+
*/
|
|
2879
|
+
beforeMount(_ctx: AdapterContext): void {
|
|
2880
|
+
// Example:
|
|
2881
|
+
// _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
|
|
2882
|
+
},
|
|
2883
|
+
|
|
2884
|
+
/**
|
|
2885
|
+
* Fires once per controller class as the router mounts. Use this to
|
|
2886
|
+
* collect route metadata for OpenAPI specs, dependency graphs, route
|
|
2887
|
+
* inventories, devtools dashboards.
|
|
2888
|
+
*
|
|
2889
|
+
* Delete this hook unless your adapter introspects the route registry.
|
|
2890
|
+
*/
|
|
2891
|
+
onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
|
|
2892
|
+
// Example (Swagger-style): collect routes for the spec.
|
|
2893
|
+
// openApiSpec.addController(_controllerClass, _mountPath)
|
|
2894
|
+
},
|
|
2895
|
+
|
|
2896
|
+
/**
|
|
2897
|
+
* Runs AFTER modules + routes are wired, BEFORE the server starts.
|
|
2898
|
+
* Right place for late-stage DI registrations or final config validation.
|
|
2899
|
+
*
|
|
2900
|
+
* Delete this hook if there's nothing to wire post-modules.
|
|
2901
|
+
*/
|
|
2902
|
+
beforeStart(_ctx: AdapterContext): void {
|
|
2903
|
+
// Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
2904
|
+
},
|
|
2905
|
+
|
|
2906
|
+
/**
|
|
2907
|
+
* Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
|
|
2908
|
+
* available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
|
|
2909
|
+
* gRPC, GraphQL subscriptions), warm caches, log a banner.
|
|
2910
|
+
*
|
|
2911
|
+
* Delete this hook if you don't need the running server reference.
|
|
2912
|
+
*/
|
|
2913
|
+
afterStart(_ctx: AdapterContext): void {
|
|
2914
|
+
// Example: const io = new Server(_ctx.server)
|
|
2915
|
+
},
|
|
2916
|
+
|
|
2917
|
+
/**
|
|
2918
|
+
* Returns Context Contributors to merge into every route's pipeline
|
|
2919
|
+
* at the \`'adapter'\` precedence level. Per-route handlers can
|
|
2920
|
+
* override the value at the method / class / module level.
|
|
2921
|
+
*
|
|
2922
|
+
* Delete this hook unless your adapter ships typed per-request values
|
|
2923
|
+
* (auth user, tenant, locale, feature flags, geo, etc).
|
|
2924
|
+
*/
|
|
2925
|
+
contributors(): ContributorRegistrations {
|
|
2926
|
+
return [
|
|
2927
|
+
// Example:
|
|
2928
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
2929
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
|
|
2930
|
+
// const Load${i} = defineHttpContextDecorator({
|
|
2931
|
+
// key: '${r}',
|
|
2932
|
+
// resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
|
|
2933
|
+
// })
|
|
2934
|
+
// return [Load${i}.registration]
|
|
2935
|
+
]
|
|
2936
|
+
},
|
|
2937
|
+
|
|
2938
|
+
/**
|
|
2939
|
+
* Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
|
|
2940
|
+
* resources the adapter owns: close connections, flush buffers,
|
|
2941
|
+
* cancel timers. The framework runs every adapter's \`shutdown\`
|
|
2942
|
+
* concurrently via \`Promise.allSettled\` — one failure won't block
|
|
2943
|
+
* sibling adapters.
|
|
2944
|
+
*
|
|
2945
|
+
* Delete this hook if your adapter holds no resources.
|
|
2946
|
+
*/
|
|
2947
|
+
async shutdown(): Promise<void> {
|
|
2948
|
+
// Example: await this.pool.end()
|
|
2949
|
+
// Example: clearInterval(this.heartbeatTimer)
|
|
2950
|
+
},
|
|
2951
|
+
}
|
|
2952
|
+
},
|
|
2953
|
+
})
|
|
2954
|
+
`),a.push(o),a}async function ir(e){let{name:t,outDir:n}=e,r=R(t),i=I(t),a=[],o=h(n,`${r}.plugin.ts`);return await M(o,`import {
|
|
2955
|
+
definePlugin,
|
|
2956
|
+
type AppAdapter,
|
|
2957
|
+
type AppModuleEntry,
|
|
2958
|
+
type Container,
|
|
2959
|
+
type ContributorRegistrations,
|
|
2960
|
+
} from '@forinda/kickjs'
|
|
2961
|
+
|
|
2962
|
+
/**
|
|
2963
|
+
* Configuration for the ${i} plugin.
|
|
2964
|
+
*
|
|
2965
|
+
* Plugins typically take a small config object so callers can tune
|
|
2966
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
2967
|
+
* derived from the environment should be read inside the build
|
|
2968
|
+
* function via getEnv(), not forced onto the caller.
|
|
2969
|
+
*/
|
|
2970
|
+
export interface ${i}PluginConfig {
|
|
2971
|
+
// Add your plugin config here, e.g.:
|
|
2972
|
+
// enabled?: boolean
|
|
2973
|
+
// apiKey?: string
|
|
2974
|
+
}
|
|
2975
|
+
|
|
2976
|
+
/**
|
|
2977
|
+
* ${i} plugin — built via \`definePlugin()\` so callers get the
|
|
2978
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
2979
|
+
*
|
|
2980
|
+
* A plugin bundles DI bindings, modules, adapters, and middleware
|
|
2981
|
+
* into one object that can be added to \`bootstrap({ plugins })\`.
|
|
2982
|
+
*
|
|
2983
|
+
* Lifecycle order (each hook is optional — delete the ones you don't
|
|
2984
|
+
* need and keep only the surface your plugin actually uses):
|
|
2985
|
+
*
|
|
2986
|
+
* 1. \`register(container)\` — runs before user modules load. Use
|
|
2987
|
+
* it to bind services that modules depend on.
|
|
2988
|
+
* 2. \`modules()\` — plugin modules load before user modules.
|
|
2989
|
+
* 3. \`adapters()\` — plugin adapters mount before user adapters.
|
|
2990
|
+
* 4. \`middleware()\` — plugin middleware runs before user middleware.
|
|
2991
|
+
* 5. \`contributors()\` — Context Contributors merged into every route.
|
|
2992
|
+
* 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
|
|
2993
|
+
* 7. \`shutdown()\` — runs on graceful shutdown.
|
|
2994
|
+
*
|
|
2995
|
+
* @example
|
|
2996
|
+
* \`\`\`ts
|
|
2997
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
2998
|
+
* import { ${i}Plugin } from './plugins/${r}.plugin'
|
|
2999
|
+
*
|
|
3000
|
+
* export const app = await bootstrap({
|
|
3001
|
+
* modules,
|
|
3002
|
+
* plugins: [${i}Plugin({ /* config overrides *\\/ })],
|
|
3003
|
+
* })
|
|
3004
|
+
* \`\`\`
|
|
3005
|
+
*/
|
|
3006
|
+
export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
3007
|
+
name: '${i}Plugin',
|
|
3008
|
+
defaults: {
|
|
3009
|
+
// Default config values go here
|
|
3010
|
+
},
|
|
3011
|
+
build: (_config, { name: _name }) => ({
|
|
3012
|
+
/**
|
|
3013
|
+
* Register DI bindings before modules load.
|
|
3014
|
+
* Use \`container.registerInstance(TOKEN, value)\` for singletons
|
|
3015
|
+
* and \`container.registerFactory(TOKEN, () => ...)\` for lazy
|
|
3016
|
+
* constructions.
|
|
3017
|
+
*/
|
|
3018
|
+
register(_container: Container): void {
|
|
3019
|
+
// Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
3020
|
+
},
|
|
3021
|
+
|
|
3022
|
+
/**
|
|
3023
|
+
* Return modules this plugin contributes to the app. These load
|
|
3024
|
+
* before user modules, so plugin controllers and services are
|
|
3025
|
+
* available for user code to \`@Autowired\`.
|
|
3026
|
+
*
|
|
3027
|
+
* Accepts both \`defineModule\`-style instances (call the factory:
|
|
3028
|
+
* \`ExampleModule()\`) and legacy \`class … implements AppModule\`
|
|
3029
|
+
* constructors.
|
|
3030
|
+
*/
|
|
3031
|
+
modules(): AppModuleEntry[] {
|
|
3032
|
+
return [
|
|
3033
|
+
// ExampleModule(),
|
|
3034
|
+
]
|
|
3035
|
+
},
|
|
3036
|
+
|
|
3037
|
+
/**
|
|
3038
|
+
* Return adapter instances to be added to the application.
|
|
3039
|
+
* Plugin adapters mount before user adapters.
|
|
3040
|
+
*/
|
|
3041
|
+
adapters(): AppAdapter[] {
|
|
3042
|
+
return [
|
|
3043
|
+
// MyAdapter({ ... }),
|
|
3044
|
+
]
|
|
3045
|
+
},
|
|
3046
|
+
|
|
3047
|
+
/**
|
|
3048
|
+
* Return Express middleware entries to be added to the global
|
|
3049
|
+
* pipeline. Plugin middleware runs before user-defined middleware.
|
|
3050
|
+
*/
|
|
3051
|
+
middleware(): unknown[] {
|
|
3052
|
+
return [
|
|
3053
|
+
// helmet(),
|
|
3054
|
+
// myCustomMiddleware(_config),
|
|
3055
|
+
]
|
|
3056
|
+
},
|
|
3057
|
+
|
|
3058
|
+
/**
|
|
3059
|
+
* Return Context Contributors to merge into every route's pipeline.
|
|
3060
|
+
* Plugins contribute at the same \`'adapter'\` precedence level as
|
|
3061
|
+
* adapters — overrideable per-route at the method / class / module
|
|
3062
|
+
* level. See https://forinda.github.io/kick-js/guide/context-decorators
|
|
3063
|
+
*
|
|
3064
|
+
* Delete this hook if your plugin doesn't ship typed per-request values.
|
|
3065
|
+
*/
|
|
3066
|
+
contributors(): ContributorRegistrations {
|
|
3067
|
+
return [
|
|
3068
|
+
// Example:
|
|
3069
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
3070
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
|
|
3071
|
+
// const Load${i} = defineHttpContextDecorator({
|
|
3072
|
+
// key: '${r}',
|
|
3073
|
+
// resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
|
|
3074
|
+
// })
|
|
3075
|
+
// return [Load${i}.registration]
|
|
3076
|
+
]
|
|
3077
|
+
},
|
|
3078
|
+
|
|
3079
|
+
/**
|
|
3080
|
+
* Called after the application has fully bootstrapped. Use this
|
|
3081
|
+
* for post-startup work like logging, health checks, or warming
|
|
3082
|
+
* a cache. Runs once per process.
|
|
3083
|
+
*/
|
|
3084
|
+
async onReady(_container: Container): Promise<void> {
|
|
3085
|
+
// const log = _container.resolve(Logger)
|
|
3086
|
+
// log.info('${i} plugin ready')
|
|
3087
|
+
},
|
|
3088
|
+
|
|
3089
|
+
/**
|
|
3090
|
+
* Called during graceful shutdown. Clean up any long-lived
|
|
3091
|
+
* resources this plugin owns (connections, timers, subscriptions).
|
|
3092
|
+
*/
|
|
3093
|
+
async shutdown(): Promise<void> {
|
|
3094
|
+
// Example: await this.connection?.close()
|
|
3095
|
+
},
|
|
3096
|
+
}),
|
|
3097
|
+
})
|
|
3098
|
+
`),a.push(o),a}const ar={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},or={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},sr={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function cr(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,pattern:o=`ddd`,shouldPluralize:s=!0}=e;if(n)return v(n);if(r){let e=o===`ddd`?ar:o===`cqrs`?sr:or,n=R(r),a=s?z(n):n,c=e[t]??``,l=h(i,a);return v(c?h(l,c):l)}return v(a)}async function lr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=cr({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=L(t),c=[],l=h(a,`${o}.middleware.ts`);return await M(l,`import type { Request, Response, NextFunction } from 'express'
|
|
3099
|
+
|
|
3100
|
+
export interface ${I(t)}Options {
|
|
3101
|
+
// Add configuration options here. The factory below closes over the
|
|
3102
|
+
// resolved options object; pass them at the call site —
|
|
3103
|
+
// \`${s}({ foo: 'bar' })\` — and the closure preserves them across
|
|
3104
|
+
// every request.
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
/**
|
|
3108
|
+
* ${I(t)} middleware.
|
|
3109
|
+
*
|
|
3110
|
+
* Usage in bootstrap (fires on every request):
|
|
3111
|
+
* middleware: [${s}()]
|
|
3112
|
+
*
|
|
3113
|
+
* Usage with adapter — phase controls *when* the handler runs:
|
|
3114
|
+
*
|
|
3115
|
+
* middleware() {
|
|
3116
|
+
* return [{ handler: ${s}(), phase: 'afterGlobal' }]
|
|
3117
|
+
* }
|
|
3118
|
+
*
|
|
3119
|
+
* Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
|
|
3120
|
+
* - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
|
|
3121
|
+
* request, before module routes run.
|
|
3122
|
+
* - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
|
|
3123
|
+
* OR a route handler called \`next()\` without ending the response.
|
|
3124
|
+
* Controllers that call \`ctx.json(…)\` end the chain and skip this
|
|
3125
|
+
* phase. For per-response work (logging, metrics) attach to
|
|
3126
|
+
* \`res.on('finish', …)\` from an earlier-phase middleware instead.
|
|
3127
|
+
*
|
|
3128
|
+
* Optional path scope — string, RegExp, or array of either:
|
|
3129
|
+
* middleware() {
|
|
3130
|
+
* return [{
|
|
3131
|
+
* handler: ${s}({ region: 'eu' }),
|
|
3132
|
+
* phase: 'afterGlobal',
|
|
3133
|
+
* path: ['/api', /^\\/admin/],
|
|
3134
|
+
* }]
|
|
3135
|
+
* }
|
|
3136
|
+
*
|
|
3137
|
+
* Usage with @Middleware decorator:
|
|
3138
|
+
* @Middleware(${s}())
|
|
3139
|
+
*/
|
|
3140
|
+
export function ${s}(options: ${I(t)}Options = {}) {
|
|
3141
|
+
return (req: Request, res: Response, next: NextFunction) => {
|
|
3142
|
+
// Implement your middleware logic here. \`options\` is captured by
|
|
3143
|
+
// closure — log or read it anywhere in this handler body.
|
|
3144
|
+
void options
|
|
3145
|
+
next()
|
|
3146
|
+
}
|
|
3147
|
+
}
|
|
3148
|
+
`),c.push(l),c}async function ur(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=cr({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=L(t),c=I(t),l=[],u=h(a,`${o}.guard.ts`);return await M(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
3149
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
3150
|
+
|
|
3151
|
+
/**
|
|
3152
|
+
* ${c} guard.
|
|
3153
|
+
*
|
|
3154
|
+
* Guards protect routes by checking conditions before the handler runs.
|
|
3155
|
+
* Return early with an error response to block access.
|
|
3156
|
+
*
|
|
3157
|
+
* Usage:
|
|
3158
|
+
* @Middleware(${s}Guard)
|
|
3159
|
+
* @Get('/protected')
|
|
3160
|
+
* async handler(ctx: RequestContext) { ... }
|
|
3161
|
+
*/
|
|
3162
|
+
export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<void> {
|
|
3163
|
+
// Example: check for an authorization header
|
|
3164
|
+
const header = ctx.headers.authorization
|
|
3165
|
+
if (!header?.startsWith('Bearer ')) {
|
|
3166
|
+
ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
|
|
3167
|
+
return
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
const token = header.slice(7)
|
|
3171
|
+
|
|
3172
|
+
try {
|
|
3173
|
+
// Verify the token using a service from the DI container
|
|
3174
|
+
// const container = Container.getInstance()
|
|
3175
|
+
// const authService = container.resolve(AuthService)
|
|
3176
|
+
// const payload = authService.verifyToken(token)
|
|
3177
|
+
// ctx.set('auth', payload)
|
|
3178
|
+
|
|
3179
|
+
next()
|
|
3180
|
+
} catch {
|
|
3181
|
+
ctx.res.status(401).json({ message: 'Invalid or expired token' })
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
`),l.push(u),l}async function dr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=cr({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=[],l=h(a,`${o}.service.ts`);return await M(l,`import { Service } from '@forinda/kickjs'
|
|
3185
|
+
|
|
3186
|
+
@Service()
|
|
3187
|
+
export class ${s}Service {
|
|
3188
|
+
// Inject dependencies via constructor
|
|
3189
|
+
// constructor(
|
|
3190
|
+
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
3191
|
+
// ) {}
|
|
3192
|
+
}
|
|
3193
|
+
`),c.push(l),c}async function fr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=cr({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=[],l=h(a,`${o}.controller.ts`);return await M(l,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
|
|
3194
|
+
|
|
3195
|
+
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
3196
|
+
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
3197
|
+
// will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
|
|
3198
|
+
// See https://forinda.github.io/kick-js/guide/typegen for details.
|
|
3199
|
+
|
|
3200
|
+
@Controller()
|
|
3201
|
+
export class ${s}Controller {
|
|
3202
|
+
// @Autowired() private readonly myService!: MyService
|
|
3203
|
+
|
|
3204
|
+
@Get('/')
|
|
3205
|
+
async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
|
|
3206
|
+
ctx.json({ message: '${s} list' })
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
@Post('/')
|
|
3210
|
+
async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
|
|
3211
|
+
ctx.created({ message: '${s} created', data: ctx.body })
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
`),c.push(l),c}async function pr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=cr({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=L(t),l=[],u=h(a,`${o}.dto.ts`);return await M(u,`import { z } from 'zod'
|
|
3215
|
+
|
|
3216
|
+
export const ${c}Schema = z.object({
|
|
3217
|
+
// Define your schema fields here
|
|
3218
|
+
name: z.string().min(1).max(200),
|
|
3219
|
+
})
|
|
3220
|
+
|
|
3221
|
+
export type ${s}DTO = z.infer<typeof ${c}Schema>
|
|
3222
|
+
`),l.push(u),l}async function mr(e){let t=h(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return r(t)&&!e.force&&!await P({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
3223
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await M(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
3224
|
+
|
|
3225
|
+
export default defineConfig({
|
|
3226
|
+
modules: {
|
|
3227
|
+
dir: '${n}',
|
|
3228
|
+
repo: '${i}',
|
|
3229
|
+
pluralize: true,
|
|
3230
|
+
},
|
|
3231
|
+
|
|
3232
|
+
typegen: {
|
|
3233
|
+
schemaValidator: 'zod',
|
|
3234
|
+
},
|
|
3235
|
+
|
|
3236
|
+
commands: [
|
|
3237
|
+
{
|
|
3238
|
+
name: 'test',
|
|
3239
|
+
description: 'Run tests with Vitest',
|
|
3240
|
+
steps: 'npx vitest run',
|
|
3241
|
+
},
|
|
3242
|
+
{
|
|
3243
|
+
name: 'format',
|
|
3244
|
+
description: 'Format code with Prettier',
|
|
3245
|
+
steps: 'npx prettier --write src/',
|
|
3246
|
+
},
|
|
3247
|
+
{
|
|
3248
|
+
name: 'format:check',
|
|
3249
|
+
description: 'Check formatting without writing',
|
|
3250
|
+
steps: 'npx prettier --check src/',
|
|
3251
|
+
},
|
|
3252
|
+
{
|
|
3253
|
+
name: 'ci:check',
|
|
3254
|
+
description: 'Run typecheck + format check',
|
|
3255
|
+
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
3256
|
+
aliases: ['verify'],
|
|
3257
|
+
},
|
|
3258
|
+
],
|
|
3259
|
+
})
|
|
3260
|
+
`),[t])}const hr=`.agents`,gr=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function _r(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function vr(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function yr(e,t){if(t)return t;try{let t=(await k(e))?.pattern;if(t&&gr.has(t))return t}catch{}return`ddd`}async function br(e){let t=e.only??`all`,n=_r(e.outDir,e.name),i=vr(e.outDir,e.pm),a=await yr(e.outDir,e.template),o=t===`agents`||t===`both`||t===`all`,s=t===`claude`||t===`both`||t===`all`,c=t===`skills`||t===`all`,l=t===`gemini`||t===`all`,u=t===`copilot`||t===`all`,d=[];if(o&&d.push({file:h(e.outDir,hr,`AGENTS.md`),render:()=>vt(n,a,i)}),s&&d.push({file:h(e.outDir,`CLAUDE.md`),render:()=>_t(n,a,i)}),c)for(let t of yt(n,a,i))d.push({file:h(e.outDir,hr,`skills`,t.slug,`SKILL.md`),render:()=>t.content});l&&d.push({file:h(e.outDir,hr,`GEMINI.md`),render:()=>xt(n,a,i)}),u&&d.push({file:h(e.outDir,hr,`COPILOT.md`),render:()=>St(n,a,i)});let f=[];for(let{file:t,render:n}of d){if(r(t)&&!e.force&&!await P({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await M(t,n()),f.push(t)}return f}function xr(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function H(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=xr(e,r);return i===-1?null:e.slice(r+1,i)}function U(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
3261
|
+
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`);return r+e.replace(n,``)}).join(`
|
|
3262
|
+
`)}function Sr(e){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,t)=>{let n=t.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`Container`&&e!==`type Container`&&e!==`type AppModule`&&e!==`AppModule`&&e!==`type ModuleRoutes`&&e!==`ModuleRoutes`);return n.includes(`defineModule`)||n.push(`defineModule`),`import { ${n.join(`, `)} } from '@forinda/kickjs'`})}function Cr(e,t){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,n)=>{let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`defineModule`);return t.container&&!r.includes(`Container`)&&r.push(`Container`),t.appModule&&!r.some(e=>e===`AppModule`||e===`type AppModule`)&&r.push(`type AppModule`),t.moduleRoutes&&!r.some(e=>e===`ModuleRoutes`||e===`type ModuleRoutes`)&&r.push(`type ModuleRoutes`),t.contributorRegistrations&&!r.some(e=>e===`ContributorRegistrations`||e===`type ContributorRegistrations`)&&r.push(`type ContributorRegistrations`),`import { ${r.join(`, `)} } from '@forinda/kickjs'`})}function wr(e){if(/\bdefineModule\s*\(/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+class\s+(\w+Module)\s+implements\s+AppModule\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no class form detected`};if(t.length>1)return{migrated:null,reason:`multiple module classes in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=xr(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=H(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=H(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=H(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Sr(s),p=``;return l&&(p+=` register(container) {${U(l,4,6)} },\n\n`),u&&(p+=` contributors() {${U(u,4,6)} },\n\n`),p+=` routes() {${U(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
3263
|
+
name: '${r}',
|
|
3264
|
+
build: () => ({
|
|
3265
|
+
${p}
|
|
3266
|
+
}),
|
|
3267
|
+
})`}${c}`}}function Tr(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=xr(e,i);if(a===-1)return{migrated:null,reason:`unbalanced defineModule braces`};let o=e.indexOf(`)`,a);if(o===-1)return{migrated:null,reason:`unbalanced defineModule call parens`};let s=e.slice(i+1,a),c=e.slice(0,n.index),l=o+1;for(;l<e.length&&(e[l]===`
|
|
3268
|
+
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=xr(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Cr(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${U(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${U(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${U(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
3269
|
+
${y}
|
|
3270
|
+
}
|
|
3271
|
+
`}${u}`}}function Er(e,t){return t===`class`?Tr(e):wr(e)}function Dr(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function Or(e){let t=[];return await n(v(e),0),t;async function n(e,r){let i;try{i=await se(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=h(e,a),o;try{o=await le(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function kr(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await se(e)}catch{return}await oe(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=h(e,a),o=h(t,a),s;try{s=await le(i)}catch{continue}s.isDirectory()?await r(i,o):(await ae(i,o),n++)}}}function Ar(e){return h(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function jr(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Or(e),s=await C(h(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Ar(r),await kr(e,c));let l=[];for(let e of o){let t=Er(await C(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await w(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=h(e,`index.ts`),d=null;try{d=await C(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Dr(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await w(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Mr(e,t){let n=await Or(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await C(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Nr(e){let{name:t,outDir:n}=e,r=I(t),i=R(t),a=L(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=h(n,e);await M(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
3272
|
+
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
3273
|
+
|
|
3274
|
+
/**
|
|
3275
|
+
* ${r} Job Processor
|
|
3276
|
+
*
|
|
3277
|
+
* Decorators:
|
|
3278
|
+
* @Job(queueName) — marks this class as a job processor for a queue
|
|
3279
|
+
* @Process(jobName?) — marks a method as the handler for a specific job type
|
|
3280
|
+
* - Without a name: handles all jobs in the queue
|
|
3281
|
+
* - With a name: handles only jobs matching that name
|
|
3282
|
+
*
|
|
3283
|
+
* To add jobs to this queue from a service or controller:
|
|
3284
|
+
* @Inject(QUEUE_MANAGER) private queue: QueueService
|
|
3285
|
+
* await this.queue.add('${o}', '${a}', { ... })
|
|
3286
|
+
*/
|
|
3287
|
+
@Job('${o}')
|
|
3288
|
+
export class ${r}Job {
|
|
3289
|
+
@Process()
|
|
3290
|
+
async handle(job: { name: string; data: any; id?: string }) {
|
|
3291
|
+
console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
|
|
3292
|
+
|
|
3293
|
+
// TODO: Implement job logic here
|
|
3294
|
+
// Example:
|
|
3295
|
+
// await this.emailService.send(job.data.to, job.data.subject, job.data.body)
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3298
|
+
@Process('${a}.priority')
|
|
3299
|
+
async handlePriority(job: { name: string; data: any; id?: string }) {
|
|
3300
|
+
console.log(\`Priority job: \${job.name}\`, job.data)
|
|
3301
|
+
// Handle high-priority variant of this job
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
`),s}const Pr={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function Fr(e){return e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=Pr[a];if(!o){let e=[...Object.keys(Pr),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}})}async function Ir(e){let{name:t,fields:n,modulesDir:r,noEntity:i,noTests:a,repo:o=`inmemory`,tokenScope:s=`app`,style:c=`define`}=e,l=e.pluralize!==!1,u=R(t),d=I(t);L(t);let f=l?z(u):u,p=l?Xt(d):d,m=h(r,f),g=[],_=async(e,t)=>{let n=h(m,e);await M(n,t),g.push(n)};await _(`${u}.module.ts`,Wr(d,u,f,c)),await _(`constants.ts`,Br(d,n)),await _(`presentation/${u}.controller.ts`,Gr(d,u,f,p)),await _(`application/dtos/create-${u}.dto.ts`,Lr(d,n)),await _(`application/dtos/update-${u}.dto.ts`,Rr(d,n)),await _(`application/dtos/${u}-response.dto.ts`,zr(d,n));let v=Jr(d,u,f,p);for(let e of v)await _(`application/use-cases/${e.file}`,e.content);return await _(`domain/repositories/${u}.repository.ts`,Kr(d,u,s)),await _(`domain/services/${u}-domain.service.ts`,qr(d,u)),o===`inmemory`&&await _(`infrastructure/repositories/in-memory-${u}.repository.ts`,Vr(d,u,n)),i||(await _(`domain/entities/${u}.entity.ts`,Hr(d,u,n)),await _(`domain/value-objects/${u}-id.vo.ts`,Ur(d))),await Xn(r,d,f,u,c),g}function Lr(e,t){return`import { z } from 'zod'
|
|
3305
|
+
|
|
3306
|
+
export const create${e}Schema = z.object({
|
|
3307
|
+
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
3308
|
+
`)}
|
|
3309
|
+
})
|
|
3310
|
+
|
|
3311
|
+
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
3312
|
+
`}function Rr(e,t){return`import { z } from 'zod'
|
|
3313
|
+
|
|
3314
|
+
export const update${e}Schema = z.object({
|
|
3315
|
+
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
3316
|
+
`)}
|
|
3317
|
+
})
|
|
3318
|
+
|
|
3319
|
+
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
3320
|
+
`}function zr(e,t){return`export interface ${e}ResponseDTO {
|
|
3321
|
+
id: string
|
|
3322
|
+
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
3323
|
+
`)}
|
|
3324
|
+
createdAt: string
|
|
3325
|
+
updatedAt: string
|
|
3326
|
+
}
|
|
3327
|
+
`}function Br(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
|
|
3328
|
+
|
|
3329
|
+
export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
|
|
3330
|
+
filterable: [${i}],
|
|
3331
|
+
sortable: [${a}],
|
|
3332
|
+
searchable: [${o}],
|
|
3333
|
+
}
|
|
3334
|
+
`}function Vr(e,t,n){return`import { randomUUID } from 'node:crypto'
|
|
3335
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
3336
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
3337
|
+
import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3338
|
+
import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
|
|
3339
|
+
import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
|
|
3340
|
+
import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
|
|
3341
|
+
|
|
3342
|
+
@Repository()
|
|
3343
|
+
export class InMemory${e}Repository implements I${e}Repository {
|
|
3344
|
+
private store = new Map<string, ${e}ResponseDTO>()
|
|
3345
|
+
|
|
3346
|
+
async findById(id: string): Promise<${e}ResponseDTO | null> {
|
|
3347
|
+
return this.store.get(id) ?? null
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
async findAll(): Promise<${e}ResponseDTO[]> {
|
|
3351
|
+
return Array.from(this.store.values())
|
|
3352
|
+
}
|
|
3353
|
+
|
|
3354
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
|
|
3355
|
+
const all = Array.from(this.store.values())
|
|
3356
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
3357
|
+
return { data, total: all.length }
|
|
3358
|
+
}
|
|
3359
|
+
|
|
3360
|
+
async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
|
|
3361
|
+
const now = new Date().toISOString()
|
|
3362
|
+
const entity: ${e}ResponseDTO = {
|
|
3363
|
+
id: randomUUID(),
|
|
3364
|
+
${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
|
|
3365
|
+
`)}
|
|
3366
|
+
createdAt: now,
|
|
3367
|
+
updatedAt: now,
|
|
3368
|
+
}
|
|
3369
|
+
this.store.set(entity.id, entity)
|
|
3370
|
+
return entity
|
|
3371
|
+
}
|
|
3372
|
+
|
|
3373
|
+
async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
|
|
3374
|
+
const existing = this.store.get(id)
|
|
3375
|
+
if (!existing) throw HttpException.notFound('${e} not found')
|
|
3376
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
3377
|
+
this.store.set(id, updated)
|
|
3378
|
+
return updated
|
|
3379
|
+
}
|
|
3380
|
+
|
|
3381
|
+
async delete(id: string): Promise<void> {
|
|
3382
|
+
if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
|
|
3383
|
+
this.store.delete(id)
|
|
3384
|
+
}
|
|
3385
|
+
}
|
|
3386
|
+
`}function Hr(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
|
|
3387
|
+
|
|
3388
|
+
interface ${e}Props {
|
|
3389
|
+
id: ${e}Id
|
|
3390
|
+
${n.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
3391
|
+
`)}
|
|
3392
|
+
createdAt: Date
|
|
3393
|
+
updatedAt: Date
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
export class ${e} {
|
|
3397
|
+
private constructor(private props: ${e}Props) {}
|
|
3398
|
+
|
|
3399
|
+
static create(params: { ${n.filter(e=>!e.optional).map(e=>`${e.name}: ${e.tsType}`).join(`; `)} }): ${e} {
|
|
3400
|
+
const now = new Date()
|
|
3401
|
+
return new ${e}({
|
|
3402
|
+
id: ${e}Id.create(),
|
|
3403
|
+
${n.filter(e=>!e.optional).map(e=>` ${e.name}: params.${e.name},`).join(`
|
|
3404
|
+
`)}
|
|
3405
|
+
createdAt: now,
|
|
3406
|
+
updatedAt: now,
|
|
3407
|
+
})
|
|
3408
|
+
}
|
|
3409
|
+
|
|
3410
|
+
static reconstitute(props: ${e}Props): ${e} {
|
|
3411
|
+
return new ${e}(props)
|
|
3412
|
+
}
|
|
3413
|
+
|
|
3414
|
+
get id(): ${e}Id { return this.props.id }
|
|
3415
|
+
${n.map(e=>` get ${e.name}(): ${e.tsType}${e.optional?` | undefined`:``} {
|
|
3416
|
+
return this.props.${e.name}
|
|
3417
|
+
}`).join(`
|
|
3418
|
+
`)}
|
|
3419
|
+
get createdAt(): Date { return this.props.createdAt }
|
|
3420
|
+
get updatedAt(): Date { return this.props.updatedAt }
|
|
3421
|
+
|
|
3422
|
+
toJSON() {
|
|
3423
|
+
return {
|
|
3424
|
+
id: this.props.id.toString(),
|
|
3425
|
+
${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
|
|
3426
|
+
`)}
|
|
3427
|
+
createdAt: this.props.createdAt.toISOString(),
|
|
3428
|
+
updatedAt: this.props.updatedAt.toISOString(),
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
}
|
|
3432
|
+
`}function Ur(e){return`import { randomUUID } from 'node:crypto'
|
|
3433
|
+
|
|
3434
|
+
export class ${e}Id {
|
|
3435
|
+
private constructor(private readonly value: string) {}
|
|
3436
|
+
|
|
3437
|
+
static create(): ${e}Id { return new ${e}Id(randomUUID()) }
|
|
3438
|
+
|
|
3439
|
+
static from(id: string): ${e}Id {
|
|
3440
|
+
if (!id || id.trim().length === 0) throw new Error('${e}Id cannot be empty')
|
|
3441
|
+
return new ${e}Id(id)
|
|
3442
|
+
}
|
|
3443
|
+
|
|
3444
|
+
toString(): string { return this.value }
|
|
3445
|
+
equals(other: ${e}Id): boolean { return this.value === other.value }
|
|
3446
|
+
}
|
|
3447
|
+
`}function Wr(e,t,n,r=`define`){let i=`import { ${e}Controller } from './presentation/${t}.controller'
|
|
3448
|
+
import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
|
|
3449
|
+
import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
|
|
3450
|
+
|
|
3451
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators
|
|
3452
|
+
// register in the DI container before the application bootstraps.
|
|
3453
|
+
import.meta.glob(
|
|
3454
|
+
['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
|
|
3455
|
+
{ eager: true },
|
|
3456
|
+
)`,a=` /**
|
|
3457
|
+
* Declare HTTP routes for this module. Return value shape:
|
|
3458
|
+
*
|
|
3459
|
+
* - \`path\` — URL prefix for this route set.
|
|
3460
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
3461
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
3462
|
+
*
|
|
3463
|
+
* Return an array to mount multiple route sets:
|
|
3464
|
+
*
|
|
3465
|
+
* return [
|
|
3466
|
+
* { path: '/${n}', version: 1, controller: ${e}V1Controller },
|
|
3467
|
+
* { path: '/${n}', version: 2, controller: ${e}V2Controller },
|
|
3468
|
+
* ]
|
|
3469
|
+
*/`;return r===`class`?`import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
3470
|
+
${i}
|
|
3471
|
+
|
|
3472
|
+
export class ${e}Module implements AppModule {
|
|
3473
|
+
/**
|
|
3474
|
+
* Bind the repository token to its concrete implementation.
|
|
3475
|
+
* Decorator-managed classes (@Service, @Controller, @Repository) are
|
|
3476
|
+
* registered automatically — only token-to-impl bindings need to live here.
|
|
3477
|
+
*/
|
|
3478
|
+
register(container: Container): void {
|
|
3479
|
+
container.registerFactory(
|
|
3480
|
+
${e.toUpperCase()}_REPOSITORY,
|
|
3481
|
+
() => container.resolve(InMemory${e}Repository),
|
|
3482
|
+
)
|
|
3483
|
+
}
|
|
3484
|
+
|
|
3485
|
+
${a.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
3486
|
+
routes(): ModuleRoutes {
|
|
3487
|
+
return {
|
|
3488
|
+
path: '/${n}',
|
|
3489
|
+
controller: ${e}Controller,
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
`:`import { defineModule } from '@forinda/kickjs'
|
|
3494
|
+
${i}
|
|
3495
|
+
|
|
3496
|
+
export const ${e}Module = defineModule({
|
|
3497
|
+
name: '${e}Module',
|
|
3498
|
+
build: () => ({
|
|
3499
|
+
/**
|
|
3500
|
+
* Bind the repository token to its concrete implementation.
|
|
3501
|
+
* Decorator-managed classes (@Service, @Controller, @Repository) are
|
|
3502
|
+
* registered automatically — only token-to-impl bindings need to live here.
|
|
3503
|
+
*/
|
|
3504
|
+
register(container) {
|
|
3505
|
+
container.registerFactory(
|
|
3506
|
+
${e.toUpperCase()}_REPOSITORY,
|
|
3507
|
+
() => container.resolve(InMemory${e}Repository),
|
|
3508
|
+
)
|
|
3509
|
+
},
|
|
3510
|
+
|
|
3511
|
+
${a}
|
|
3512
|
+
routes() {
|
|
3513
|
+
return {
|
|
3514
|
+
path: '/${n}',
|
|
3515
|
+
controller: ${e}Controller,
|
|
3516
|
+
}
|
|
3517
|
+
},
|
|
3518
|
+
}),
|
|
3519
|
+
})
|
|
3520
|
+
`}function Gr(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
3521
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
3522
|
+
import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
|
|
3523
|
+
import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
|
|
3524
|
+
import { List${r}UseCase } from '../application/use-cases/list-${n}.use-case'
|
|
3525
|
+
import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
|
|
3526
|
+
import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
|
|
3527
|
+
import { create${e}Schema } from '../application/dtos/create-${t}.dto'
|
|
3528
|
+
import { update${e}Schema } from '../application/dtos/update-${t}.dto'
|
|
3529
|
+
import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
|
|
3530
|
+
|
|
3531
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${e}Controller['<method>']>\`
|
|
3532
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
3533
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
3534
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
3535
|
+
|
|
3536
|
+
@Controller()
|
|
3537
|
+
export class ${e}Controller {
|
|
3538
|
+
@Autowired() private readonly create${e}UseCase!: Create${e}UseCase
|
|
3539
|
+
@Autowired() private readonly get${e}UseCase!: Get${e}UseCase
|
|
3540
|
+
@Autowired() private readonly list${r}UseCase!: List${r}UseCase
|
|
3541
|
+
@Autowired() private readonly update${e}UseCase!: Update${e}UseCase
|
|
3542
|
+
@Autowired() private readonly delete${e}UseCase!: Delete${e}UseCase
|
|
3543
|
+
|
|
3544
|
+
@Get('/')
|
|
3545
|
+
@ApiTags('${e}')
|
|
3546
|
+
@ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
|
|
3547
|
+
async list(ctx: Ctx<KickRoutes.${e}Controller['list']>) {
|
|
3548
|
+
return ctx.paginate(
|
|
3549
|
+
(parsed) => this.list${r}UseCase.execute(parsed),
|
|
3550
|
+
${e.toUpperCase()}_QUERY_CONFIG,
|
|
3551
|
+
)
|
|
3552
|
+
}
|
|
3553
|
+
|
|
3554
|
+
@Get('/:id')
|
|
3555
|
+
@ApiTags('${e}')
|
|
3556
|
+
async getById(ctx: Ctx<KickRoutes.${e}Controller['getById']>) {
|
|
3557
|
+
const result = await this.get${e}UseCase.execute(ctx.params.id)
|
|
3558
|
+
if (!result) return ctx.notFound('${e} not found')
|
|
3559
|
+
ctx.json(result)
|
|
3560
|
+
}
|
|
3561
|
+
|
|
3562
|
+
@Post('/', { body: create${e}Schema, name: 'Create${e}' })
|
|
3563
|
+
@ApiTags('${e}')
|
|
3564
|
+
async create(ctx: Ctx<KickRoutes.${e}Controller['create']>) {
|
|
3565
|
+
const result = await this.create${e}UseCase.execute(ctx.body)
|
|
3566
|
+
ctx.created(result)
|
|
3567
|
+
}
|
|
3568
|
+
|
|
3569
|
+
@Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
|
|
3570
|
+
@ApiTags('${e}')
|
|
3571
|
+
async update(ctx: Ctx<KickRoutes.${e}Controller['update']>) {
|
|
3572
|
+
const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
|
|
3573
|
+
ctx.json(result)
|
|
3574
|
+
}
|
|
3575
|
+
|
|
3576
|
+
@Delete('/:id')
|
|
3577
|
+
@ApiTags('${e}')
|
|
3578
|
+
async remove(ctx: Ctx<KickRoutes.${e}Controller['remove']>) {
|
|
3579
|
+
await this.delete${e}UseCase.execute(ctx.params.id)
|
|
3580
|
+
ctx.noContent()
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
`}function Kr(e,t,n){return`import { createToken } from '@forinda/kickjs'
|
|
3584
|
+
import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
|
|
3585
|
+
import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
|
|
3586
|
+
import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
|
|
3587
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
3588
|
+
|
|
3589
|
+
export interface I${e}Repository {
|
|
3590
|
+
findById(id: string): Promise<${e}ResponseDTO | null>
|
|
3591
|
+
findAll(): Promise<${e}ResponseDTO[]>
|
|
3592
|
+
findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
|
|
3593
|
+
create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
|
|
3594
|
+
update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
|
|
3595
|
+
delete(id: string): Promise<void>
|
|
3596
|
+
}
|
|
3597
|
+
|
|
3598
|
+
/**
|
|
3599
|
+
* Collision-safe DI token bound to \`I${e}Repository\`.
|
|
3600
|
+
* \`container.resolve(${e.toUpperCase()}_REPOSITORY)\` and
|
|
3601
|
+
* \`@Inject(${e.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
3602
|
+
* interface — no manual generic, no \`any\` cast.
|
|
3603
|
+
*
|
|
3604
|
+
* The \`'${n}/'\` prefix matches the project scope so
|
|
3605
|
+
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
3606
|
+
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
3607
|
+
*/
|
|
3608
|
+
export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
|
|
3609
|
+
`}function qr(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
3610
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
|
|
3611
|
+
|
|
3612
|
+
@Service()
|
|
3613
|
+
export class ${e}DomainService {
|
|
3614
|
+
constructor(
|
|
3615
|
+
@Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
|
|
3616
|
+
) {}
|
|
3617
|
+
|
|
3618
|
+
async ensureExists(id: string): Promise<void> {
|
|
3619
|
+
const entity = await this.repo.findById(id)
|
|
3620
|
+
if (!entity) throw HttpException.notFound('${e} not found')
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
`}function Jr(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
3624
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3625
|
+
import type { Create${e}DTO } from '../dtos/create-${t}.dto'
|
|
3626
|
+
|
|
3627
|
+
@Service()
|
|
3628
|
+
export class Create${e}UseCase {
|
|
3629
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
3630
|
+
async execute(dto: Create${e}DTO) { return this.repo.create(dto) }
|
|
3631
|
+
}
|
|
3632
|
+
`},{file:`get-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
3633
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3634
|
+
|
|
3635
|
+
@Service()
|
|
3636
|
+
export class Get${e}UseCase {
|
|
3637
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
3638
|
+
async execute(id: string) { return this.repo.findById(id) }
|
|
3639
|
+
}
|
|
3640
|
+
`},{file:`list-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
3641
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
3642
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3643
|
+
|
|
3644
|
+
@Service()
|
|
3645
|
+
export class List${r}UseCase {
|
|
3646
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
3647
|
+
async execute(parsed: ParsedQuery) { return this.repo.findPaginated(parsed) }
|
|
3648
|
+
}
|
|
3649
|
+
`},{file:`update-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
3650
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3651
|
+
import type { Update${e}DTO } from '../dtos/update-${t}.dto'
|
|
3652
|
+
|
|
3653
|
+
@Service()
|
|
3654
|
+
export class Update${e}UseCase {
|
|
3655
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
3656
|
+
async execute(id: string, dto: Update${e}DTO) { return this.repo.update(id, dto) }
|
|
3657
|
+
}
|
|
3658
|
+
`},{file:`delete-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
3659
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
3660
|
+
|
|
3661
|
+
@Service()
|
|
3662
|
+
export class Delete${e}UseCase {
|
|
3663
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
3664
|
+
async execute(id: string) { return this.repo.delete(id) }
|
|
3665
|
+
}
|
|
3666
|
+
`}]}async function Yr(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=R(t),o=I(t),s=[],c;if(e.outDir)c=v(e.outDir);else if(n){let e=R(n),t=i?z(e):e;c=v(h(r??`src/modules`,t,`__tests__`))}else c=v(`src/__tests__`);let l=h(c,`${a}.test.ts`);return await M(l,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
3667
|
+
import { Container } from '@forinda/kickjs'
|
|
3668
|
+
|
|
3669
|
+
describe('${o}', () => {
|
|
3670
|
+
beforeEach(() => {
|
|
3671
|
+
Container.reset()
|
|
3672
|
+
})
|
|
3673
|
+
|
|
3674
|
+
it('should be defined', () => {
|
|
3675
|
+
// TODO: Import and test your class/function here
|
|
3676
|
+
expect(true).toBe(true)
|
|
3677
|
+
})
|
|
3678
|
+
|
|
3679
|
+
it('should handle the happy path', async () => {
|
|
3680
|
+
// TODO: Set up test data and assertions
|
|
3681
|
+
expect(true).toBe(true)
|
|
3682
|
+
})
|
|
3683
|
+
|
|
3684
|
+
it('should handle edge cases', async () => {
|
|
3685
|
+
// TODO: Test error handling, empty inputs, etc.
|
|
3686
|
+
expect(true).toBe(true)
|
|
3687
|
+
})
|
|
3688
|
+
})
|
|
3689
|
+
`),s.push(l),s}const Xr=[`Service`,`Controller`,`Repository`,`Injectable`,`Component`,`Module`],Zr=[`.ts`,`.tsx`,`.mts`,`.cts`],Qr=[`node_modules`,`.kickjs`,`dist`,`build`,`.test.`,`.spec.`,`.d.ts`],$r=new RegExp(String.raw`@(${Xr.join(`|`)})\s*\([^)]*\)`+String.raw`(?:\s*@[A-Z]\w*(?:\s*\([^)]*\))?)*`+String.raw`\s*export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`,`g`),ei=new RegExp(String.raw`export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppModule\b`,`g`),ti=/(?:export\s+)?const\s+(\w+)\s*(?::\s*[^=]+)?=\s*createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,ni=/createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,ri=/@Inject\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,ii=/\b(defineAdapter|definePlugin)\s*(?:<[^>]*>)?\s*\(/g,ai=new RegExp(String.raw`export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppAdapter\b`,`g`),oi=/\bname\s*(?::\s*[^=]+)?=\s*['"`]([^'"`]+)['"`]/,si=/\bdefineAugmentation\s*\(\s*['"`]([^'"`]+)['"`]\s*(,\s*\{)?/g,ci=new RegExp(String.raw`@(${[`Get`,`Post`,`Put`,`Delete`,`Patch`].join(`|`)})\s*\(`,`g`);function li(e,t){let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r}return-1}function ui(e,t){let n=t;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`@`)break;let t=e.slice(n).match(/^@([A-Z]\w*)/);if(!t)break;for(n+=t[0].length;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]===`(`){let t=li(e,n);if(t<0)return null;n=t+1}}for(;n<e.length&&/\s/.test(e[n]);)n++;for(let t of[`public`,`private`,`protected`])if(e.slice(n,n+t.length)===t&&/\s/.test(e.charAt(n+t.length))){for(n+=t.length;n<e.length&&/\s/.test(e[n]);)n++;break}if(e.slice(n,n+5)===`async`&&/\s/.test(e.charAt(n+5)))for(n+=5;n<e.length&&/\s/.test(e[n]);)n++;let r=e.slice(n).match(/^([a-zA-Z_]\w*)\s*\(/);return r?{methodName:r[1],endPos:n+r[0].length}:null}function di(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function fi(e,t){let n=e.endsWith(`/`)?e.slice(0,-1):e;return!t||t===`/`?n||`/`:n+(t.startsWith(`/`)?t:`/`+t)||`/`}const pi=/\b(?:public\s+|private\s+|protected\s+)?routes\s*\([^)]*\)\s*(?::\s*[A-Za-z_][\w<>[\]\s,|]*\s*)?\{/g,mi=/\bpath\s*:\s*['"`]([^'"`]*)['"`]/g,hi=/\bcontroller\s*:\s*([A-Z]\w*)\b/g,gi=/\bimport\.meta\.glob\s*\(/g;function _i(e){let t=[];for(gi.lastIndex=0;gi.exec(e)!==null;){let n=gi.lastIndex-1,r=li(e,n);if(r<0)continue;let i=e.slice(n+1,r),a=/['"`]([^'"`]+)['"`]/g,o;for(;(o=a.exec(i))!==null;)t.push(o[1])}return t}function vi(e){let t=e.replace(/[.+^$()|[\]\\]/g,`\\$&`).replace(/\?/g,`.`).replace(/\*\*\//g,`___DOUBLESTAR_SLASH___`).replace(/\*\*/g,`___DOUBLESTAR___`).replace(/\*/g,`[^/]*`).replace(/___DOUBLESTAR_SLASH___/g,`(?:.+/)?`).replace(/___DOUBLESTAR___/g,`.*`);return RegExp(`^`+t+`$`)}function yi(e,t){let n=e.startsWith(`./`)?e:`./`+e,r=!1;for(let e of t){let t=e.startsWith(`!`);vi(t?e.slice(1):e).test(n)&&(r=!t)}return r}function bi(e){let t=[];pi.lastIndex=0;let n;for(;(n=pi.exec(e))!==null;){let r=e.indexOf(`{`,n.index+n[0].length-1);if(r<0)continue;let i=Mi(e,r);if(i<0)continue;let a=e.slice(r+1,i),o=[];mi.lastIndex=0;let s;for(;(s=mi.exec(a))!==null;)o.push(s[1]??``);let c=[];hi.lastIndex=0;let l;for(;(l=hi.exec(a))!==null;)c.push(l[1]);let u=Math.min(o.length,c.length);for(let e=0;e<u;e++)t.push({controller:c[e],mountPath:o[e]})}return t}function xi(e,t){let n=new RegExp(String.raw`\b${t}\s*:\s*([A-Za-z_$][\w$]*)`,`g`).exec(e);return n?n[1]:null}function Si(e,t){let n=new RegExp(String.raw`import\s*(?:type\s+)?\{[^}]*\b${t}\b[^}]*\}\s*from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(n)return n[1];let r=new RegExp(String.raw`import\s+(?:type\s+)?${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(r)return r[1];let i=new RegExp(String.raw`import\s*\*\s*as\s+${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);return i?i[1]:new RegExp(String.raw`(?:^|\n)\s*(?:export\s+)?const\s+${t}\b`).test(e)?``:null}function Ci(e,t){let n=/@ApiQueryParams\s*\(\s*([\s\S]*?)\s*\)\s*$/.exec(e);if(!n){let n=/@ApiQueryParams\s*\(([\s\S]*?)\)/.exec(e);return n?wi(n[1].trim(),t):null}return wi(n[1].trim(),t)}function wi(e,t){if(e.startsWith(`{`))return Ei(e);let n=/^([A-Za-z_]\w*)/.exec(e);if(n){let e=n[1],r=new RegExp(String.raw`const\s+${e}\s*(?::\s*[^=]+)?=\s*(\{[\s\S]*?\n\})`,`m`).exec(t);if(r)return Ei(r[1])}return{filterable:[],sortable:[],searchable:[]}}function Ti(e,t){let n=new RegExp(String.raw`${t}\s*:\s*\[([\s\S]*?)\]`).exec(e);return n?Array.from(n[1].matchAll(/['"`]([^'"`]+)['"`]/g)).map(e=>e[1]):[]}function Ei(e){return{filterable:Ti(e,`filterable`),sortable:Ti(e,`sortable`),searchable:Ti(e,`searchable`)}}async function Di(e,t){let n=t.extensions??Zr,r=t.exclude??Qr,i=[],a;try{a=await se(e,{withFileTypes:!0,encoding:`utf-8`})}catch{return i}for(let o of a){let a=h(e,o.name),s=_(t.cwd,a);r.some(e=>s.includes(e))||(o.isDirectory()?i.push(...await Di(a,t)):o.isFile()&&n.some(e=>o.name.endsWith(e))&&i.push(a))}return i}function W(e,t){return _(t,e).split(y).join(`/`)}function Oi(e,t,n){let r=[],i=W(t,n);$r.lastIndex=0;let a;for(;(a=$r.exec(e))!==null;){let[,e,n,o]=a;r.push({className:o,decorator:e,filePath:t,relativePath:i,isDefault:!!n})}ei.lastIndex=0;let o;for(;(o=ei.exec(e))!==null;){let[,e,n]=o;r.some(e=>e.className===n&&e.filePath===t)||r.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!!e})}return r}function ki(e,t,n){let r=[],i=W(t,n),a=new Set;ti.lastIndex=0;let o;for(;(o=ti.exec(e))!==null;){let[e,n,s]=o;a.add(e),r.push({name:s,variable:n,filePath:t,relativePath:i})}for(ni.lastIndex=0;(o=ni.exec(e))!==null;)a.has(o[0])||r.push({name:o[1],variable:null,filePath:t,relativePath:i});return r}function Ai(e,t,n,r,i=new Map){let a=[];if(r.length===0)return a;let o=W(t,n),s=[];for(let t of r){let n=new RegExp(String.raw`class\s+${t.className}\b`).exec(e);n?.index!==void 0&&s.push({cls:t,start:n.index})}s.sort((e,t)=>e.start-t.start);for(let n=0;n<s.length;n++){let{cls:r,start:c}=s[n],l=n+1<s.length?s[n+1].start:e.length,u=e.slice(c,l);ci.lastIndex=0;let d;for(;(d=ci.exec(u))!==null;){let n=d[1],s=d.index,c=ci.lastIndex-1,l=li(u,c);if(l<0)continue;let f=u.slice(c+1,l),p=f.match(/^\s*['"`]([^'"`]*)['"`]/),m=p&&p[1].length>0?p[1]:`/`,h=ui(u,l+1);if(!h)continue;let{methodName:g,endPos:_}=h;ci.lastIndex=_;let v=Ci(u.slice(s,_),e),y=xi(f,`body`),b=xi(f,`query`),x=xi(f,`params`),ee=i.get(r.className)??``,S=ee?fi(ee,m):m;a.push({controller:r.className,method:g,httpMethod:n.toUpperCase(),path:m,pathParams:di(S),queryFilterable:v?.filterable??null,querySortable:v?.sortable??null,querySearchable:v?.searchable??null,bodySchema:y?{identifier:y,source:Si(e,y)}:null,querySchema:b?{identifier:b,source:Si(e,b)}:null,paramsSchema:x?{identifier:x,source:Si(e,x)}:null,filePath:t,relativePath:o})}}return a}function ji(e,t,n){let r=[],i=W(t,n);ri.lastIndex=0;let a;for(;(a=ri.exec(e))!==null;)r.push({name:a[1],filePath:t,relativePath:i});return r}function Mi(e,t){let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function Ni(e,t,n){let r=[],i=W(t,n),a=new Set;ii.lastIndex=0;let o;for(;(o=ii.exec(e))!==null;){let n=o[1],s=ii.lastIndex-1,c=li(e,s);if(c<0)continue;let l=e.slice(s+1,c),u=/\bname\s*:\s*['"`]([^'"`]+)['"`]/.exec(l);if(!u)continue;let d=u[1],f=`${n}::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:n===`definePlugin`?`plugin`:`adapter`,name:d,filePath:t,relativePath:i}))}ai.lastIndex=0;let s;for(;(s=ai.exec(e))!==null;){let n=s.index,o=e.indexOf(`{`,n);if(o<0)continue;let c=Mi(e,o);if(c<0)continue;let l=e.slice(o+1,c),u=oi.exec(l);if(!u)continue;let d=u[1],f=`class::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:`adapter`,name:d,filePath:t,relativePath:i}))}return r}function Pi(e,t,n){let r=[],i=W(t,n);si.lastIndex=0;let a;for(;(a=si.exec(e))!==null;){let n=a[1],o=null,s=null;if(a[2]){let t=e.indexOf(`{`,a.index+a[0].length-1);if(t>=0){let n=Mi(e,t);if(n>=0){let r=e.slice(t+1,n);o=Fi(r,`description`),s=Fi(r,`example`)}}}r.push({name:n,description:o,example:s,filePath:t,relativePath:i})}return r}function Fi(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\`])`,`g`).exec(e);if(!n)return null;let r=n[1],i=n.index+n[0].length,a=i,o=null;for(;a<e.length;){let t=e[a];if(t===`\\`){a+=2;continue}if(t===r){o=e.slice(i,a);break}a++}return o===null?null:o.replace(/\\(.)/g,(e,t)=>t===`n`?`
|
|
3690
|
+
`:t===`t`?` `:t===`r`?`\r`:t)}const Ii=[`src/config/index.ts`,`src/config/env.ts`,`src/config.ts`,`src/env.ts`];async function Li(e,t){let n=t===`src/env.ts`?Ii:[t];for(let t of n){let n=v(e,t),r;try{r=await C(n,`utf-8`)}catch{continue}if(/\bdefineEnv\s*\(/.test(r)&&/export\s+default\b/.test(r))return{filePath:n,relativePath:W(n,e)}}return null}function Ri(e){let t=new Map;for(let n of e){let e=t.get(n.className)??[];e.push(n),t.set(n.className,e)}let n=[];for(let[e,r]of t)new Set(r.map(e=>e.filePath)).size>1&&n.push({className:e,classes:r});return n.sort((e,t)=>e.className.localeCompare(t.className)),n}async function zi(e){let t=await Di(v(e.root),e),n=[],r=[],i=[],a=[],o=[],s=[],c=new Map;for(let r of t){let t;try{t=await C(r,`utf-8`)}catch{continue}c.set(r,t),n.push(...Oi(t,r,e.cwd)),i.push(...ki(t,r,e.cwd)),a.push(...ji(t,r,e.cwd)),o.push(...Ni(t,r,e.cwd)),s.push(...Pi(t,r,e.cwd))}let l=new Map;for(let[,e]of c)for(let{controller:t,mountPath:n}of bi(e))l.has(t)||l.set(t,n);for(let[t,i]of c){let a=n.filter(e=>e.filePath===t);r.push(...Ai(i,t,e.cwd,a,l))}let u=[];for(let[e,t]of c){if(!/\.module\.[mc]?[tj]sx?$/.test(e))continue;let r=_i(t);if(r.length===0)continue;let i=e.replaceAll(y,`/`),a=i.slice(0,i.lastIndexOf(`/`));for(let t of n){if(t.decorator===`Module`)continue;let n=t.filePath.replaceAll(y,`/`);n.startsWith(a+`/`)&&n!==i&&(yi(n.slice(a.length+1),r)||u.push({className:t.className,filePath:t.filePath,relativePath:t.relativePath,moduleFilePath:e,decorator:t.decorator}))}}n.sort((e,t)=>e.className===t.className?e.relativePath.localeCompare(t.relativePath):e.className.localeCompare(t.className)),i.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),a.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),r.sort((e,t)=>e.controller.localeCompare(t.controller)||e.method.localeCompare(t.method)),o.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),s.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath));let d=Ri(n),f=await Li(e.cwd,e.envFile??`src/env.ts`);return u.sort((e,t)=>e.relativePath.localeCompare(t.relativePath)||e.className.localeCompare(t.className)),{classes:n,routes:r,tokens:i,injects:a,collisions:d,env:f,pluginsAndAdapters:o,augmentations:s,orphanedClasses:u}}const G="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n",Bi=new Set([`Service`,`Repository`,`Injectable`,`Component`]);var Vi=class extends Error{collisions;constructor(e){super(Hi(e)),this.name=`TokenCollisionError`,this.collisions=e}};function Hi(e){let t=[`kick typegen: token collision detected`];for(let n of e){t.push(``),t.push(` ${n.classes.length} classes named '${n.className}':`);for(let e of n.classes)t.push(` - ${e.relativePath}`)}return t.push(``),t.push(`Resolutions:`),t.push(` (a) Rename one of the classes`),t.push(` (b) Use createToken<T>('namespaced/Name') and import the token explicitly — see @forinda/kickjs`),t.push(` (c) Pass --allow-duplicates to namespace the registry keys automatically`),t.push(` (e.g. 'modules/users/UserService' instead of 'UserService')`),t.join(`
|
|
3691
|
+
`)}function Ui(e,t){let n=_(f(t),e).split(y).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),n}function Wi(e){let t=e.relativePath.replace(/^src\//,``).replace(/\.(ts|tsx|mts|cts)$/i,``).split(`/`);t.pop();let n=t.join(`/`);return n?`${n}/${e.className}`:e.className}function Gi(e,t,n){let r=new Set,i=[];for(let a of e){if(!Bi.has(a.decorator))continue;let e=n.has(a.className)?Wi(a):a.className;if(r.has(e))continue;r.add(e);let o=Ui(a.filePath,t),s=a.isDefault?`import('${o}').default`:`import('${o}').${a.className}`;i.push(` '${e}': ${s}`)}return`${G}
|
|
3692
|
+
declare module '@forinda/kickjs' {
|
|
3693
|
+
interface KickJsRegistry {
|
|
3694
|
+
${i.length?i.join(`
|
|
3695
|
+
`):" // (no services discovered yet — run `kick g service <name>` to add one)"}
|
|
3696
|
+
}
|
|
3697
|
+
}
|
|
3698
|
+
|
|
3699
|
+
export {}
|
|
3700
|
+
`}function Ki(e,t,n){return t.length===0?`${G}
|
|
3701
|
+
// ${n}
|
|
3702
|
+
export type ${e} = never
|
|
3703
|
+
`:`${G}
|
|
3704
|
+
export type ${e} =
|
|
3705
|
+
${[...new Set(t)].toSorted().map(e=>` | '${e}'`).join(`
|
|
3706
|
+
`)}
|
|
3707
|
+
`}function qi(e,t){return`${G}
|
|
3708
|
+
export type { ServiceToken } from './services'
|
|
3709
|
+
export type { ModuleToken } from './modules'
|
|
3710
|
+
|
|
3711
|
+
// The registry, routes, plugins, assets, and env augmentations are
|
|
3712
|
+
// loaded as side-effects — importing this file (or having it on
|
|
3713
|
+
// tsconfig include) is enough for \`container.resolve()\`,
|
|
3714
|
+
// \`Ctx<KickRoutes.UserController['getUser']>\`,
|
|
3715
|
+
// \`dependsOn: ['TenantAdapter']\`, \`assets.mails.welcome()\`, and
|
|
3716
|
+
// \`@Value('PORT')\` to resolve.
|
|
3717
|
+
import './registry'
|
|
3718
|
+
import './kick__routes'
|
|
3719
|
+
import './plugins'
|
|
3720
|
+
import './augmentations'
|
|
3721
|
+
${t?`import './kick__assets'
|
|
3722
|
+
`:``}${e?`import './kick__env'
|
|
3723
|
+
`:``}`}function Ji(e){let t=new Map;for(let n of e)t.has(n.name)||t.set(n.name,n);return`${G}
|
|
3724
|
+
declare module '@forinda/kickjs' {
|
|
3725
|
+
/**
|
|
3726
|
+
* Map of every plugin/adapter \`name\` discovered in the project. The
|
|
3727
|
+
* value type is the kind tag (\`'plugin'\` or \`'adapter'\`); the
|
|
3728
|
+
* \`keyof\` of this interface narrows \`dependsOn\` so misspelled deps
|
|
3729
|
+
* become compile errors instead of boot-time \`MissingMountDepError\`.
|
|
3730
|
+
*/
|
|
3731
|
+
interface KickJsPluginRegistry {
|
|
3732
|
+
${[...t.values()].toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>` '${e.name}': '${e.kind}'`).join(`
|
|
3733
|
+
`)||" // (no plugins/adapters discovered yet — `defineAdapter`/`definePlugin` calls feed this)"}
|
|
3734
|
+
}
|
|
3735
|
+
}
|
|
3736
|
+
|
|
3737
|
+
export {}
|
|
3738
|
+
`}function Yi(e){if(e.length===0)return`${G}
|
|
3739
|
+
// No augmentations discovered.
|
|
3740
|
+
//
|
|
3741
|
+
// Plugins advertise augmentable interfaces via:
|
|
3742
|
+
//
|
|
3743
|
+
// import { defineAugmentation } from '@forinda/kickjs'
|
|
3744
|
+
// defineAugmentation('FeatureFlags', {
|
|
3745
|
+
// description: 'Feature flag shape consumed by FlagsPlugin',
|
|
3746
|
+
// example: '{ beta: boolean; rolloutPercentage: number }',
|
|
3747
|
+
// })
|
|
3748
|
+
//
|
|
3749
|
+
// See \`docs/guide/typegen.md#augmentations\` for the full pattern.
|
|
3750
|
+
export {}
|
|
3751
|
+
`;let t=new Map;for(let n of e)t.has(n.name)||t.set(n.name,n);let n=[];for(let e of[...t.values()].toSorted((e,t)=>e.name.localeCompare(t.name))){let t=[];if(e.description)for(let n of e.description.split(`
|
|
3752
|
+
`))t.push(` * ${n}`);if(e.example){t.push(` * @example`," * ```ts");for(let n of e.example.split(`
|
|
3753
|
+
`))t.push(` * ${n}`);t.push(" * ```")}t.push(` * @see ${e.relativePath}`),n.push([`/**`,...t,` */`,`export interface ${e.name}Augmentation {}`].join(`
|
|
3754
|
+
`))}return`${G}
|
|
3755
|
+
// Catalogue of augmentable interfaces in this project. The interfaces
|
|
3756
|
+
// below are documentation only — augment the source-of-truth interfaces
|
|
3757
|
+
// in your own \`d.ts\` files (the framework declares the actual types).
|
|
3758
|
+
|
|
3759
|
+
${n.join(`
|
|
3760
|
+
|
|
3761
|
+
`)}
|
|
3762
|
+
`}async function Xi(e){let{classes:t,routes:n=[],tokens:r=[],injects:i=[],collisions:a=[],env:o=null,pluginsAndAdapters:s=[],augmentations:c=[],assets:l={entries:[],count:0},outDir:u,allowDuplicates:d=!1,schemaValidator:p=!1}=e;if(a.length>0&&!d)throw new Vi(a);await oe(u,{recursive:!0});let m=h(u,`registry.d.ts`),g=h(u,`services.d.ts`),_=h(u,`modules.d.ts`),v=h(u,`plugins.d.ts`),y=h(u,`augmentations.d.ts`),b=h(u,`index.d.ts`),x=new Set(a.map(e=>e.className)),ee=Gi(t,m,x),S=t.filter(e=>Bi.has(e.decorator)).map(e=>x.has(e.className)?Wi(e):e.className),te=r.map(e=>e.name),ne=i.map(e=>e.name),re=[...S,...te,...ne],ie=t.filter(e=>e.decorator===`Module`).map(e=>e.className),ae=Ki(`ServiceToken`,re,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)"),C=Ki(`ModuleToken`,ie,"(no @Module classes discovered — `kick g module <name>` to add one)"),se=Ji(s),ce=Yi(c),le=qi(o!==null,l.count>0);await w(m,ee,`utf-8`),await w(g,ae,`utf-8`),await w(_,C,`utf-8`),await w(v,se,`utf-8`),await w(y,ce,`utf-8`),await w(b,le,`utf-8`);let ue=[m,g,_,v,y,b];await w(h(f(u),`.gitignore`),`# Auto-generated by kick typegen
|
|
3763
|
+
*
|
|
3764
|
+
`,`utf-8`);let T=new Set(s.map(e=>e.name)).size,E=new Set(c.map(e=>e.name)).size;return{registryEntries:S.length,serviceTokens:new Set(re).size,moduleTokens:ie.length,routeEntries:n.length,pluginEntries:T,augmentationEntries:E,assetEntries:l.count,envWritten:o!==null,written:ue,resolvedCollisions:a.length}}const Zi=/^(kick\/)?([a-z][\w-]*\/[A-Z]\w*)(\/.+)?(:[a-z][\w-]+(:[a-z][\w-]+)*)?$/;function Qi(e){let t=[];for(let n of e){let e=n.name;e.startsWith(`kickjs.`)||Zi.test(e)||t.push({token:e,variable:n.variable,filePath:n.relativePath,reason:"does not match `<scope>/<PascalKey>[/<suffix>][:<instance>]`",suggestion:$i(e)})}return t}function $i(e){if(/^[A-Z]\w*$/.test(e))return`'<scope>/${e}' (e.g. 'mycorp/${e}')`;if(e.includes(`.`))return`consider '<scope>/PascalKey' instead of dotted form`;let t=/^([a-z][\w-]*)\/([a-z]\w*)$/.exec(e);if(t){let[,e,n]=t;return`'${e}/${n.charAt(0).toUpperCase()}${n.slice(1)}'`}}function ea(e,t){if(!e)return{entries:[],count:0};let n=new Map;for(let[r,i]of Object.entries(e)){if(!i||typeof i.src!=`string`)continue;let e=v(t,i.src);if(!aa(e))continue;let a=pe(i.glob??`**/*`,{cwd:e,nodir:!0,dot:!1,posix:!0});a.sort();let{pairs:o}=me(r,a,{strategy:i.keys??`auto`});for(let{key:e}of o){let t=e.slice(r.length+1);n.set(e,{namespace:r,key:t})}}return{entries:[...n.values()],count:n.size}}function ta(e){let t="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n";if(e.entries.length===0)return`${t}
|
|
3765
|
+
declare module '@forinda/kickjs' {
|
|
3766
|
+
/**
|
|
3767
|
+
* Map of every typed asset discovered in the project's assetMap.
|
|
3768
|
+
* (No assetMap entries discovered yet — declare with
|
|
3769
|
+
* \`assetMap: { name: { src: 'src/...' } }\` in kick.config.ts.)
|
|
3770
|
+
*/
|
|
3771
|
+
interface KickAssets {}
|
|
3772
|
+
}
|
|
3773
|
+
|
|
3774
|
+
export {}
|
|
3775
|
+
`;let n={};for(let t of e.entries){let e=`${t.namespace}/${t.key}`.split(`/`),r=n;for(let t=0;t<e.length-1;t++){let n=e[t],i=r[n];if(i===na){let e={};r[n]=e,r=e}else i||(r[n]={}),r=r[n]}let i=e[e.length-1];typeof r[i]!=`object`&&(r[i]=na)}return`${t}
|
|
3776
|
+
declare module '@forinda/kickjs' {
|
|
3777
|
+
/**
|
|
3778
|
+
* Map of every typed asset discovered in the project's assetMap.
|
|
3779
|
+
* Each leaf is a \`() => string\` thunk that returns the resolved
|
|
3780
|
+
* absolute path for the file in the current run mode (dev → src,
|
|
3781
|
+
* prod → dist).
|
|
3782
|
+
*/
|
|
3783
|
+
interface KickAssets {
|
|
3784
|
+
${ra(n,` `)}
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
|
|
3788
|
+
export {}
|
|
3789
|
+
`}const na=Symbol(`asset-leaf`);function ra(e,t){let n=Object.keys(e).toSorted(),r=[];for(let i of n){let n=e[i],a=ia(i)?i:JSON.stringify(i);n===na?r.push(`${t}${a}: () => string`):(r.push(`${t}${a}: {`),r.push(ra(n,`${t} `)),r.push(`${t}}`))}return r.join(`
|
|
3790
|
+
`)}function ia(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function aa(e){try{return c(e).isDirectory()}catch{return!1}}var oa=D({runTypegen:()=>K,sweepStaleTypegen:()=>ua,watchTypegen:()=>ca});function sa(e){let t=e.cwd??process.cwd();return{cwd:t,srcDir:v(t,e.srcDir??`src`),outDir:v(t,e.outDir??`.kickjs/types`),silent:e.silent??!1,allowDuplicates:e.allowDuplicates??!1,schemaValidator:e.schemaValidator??!1,envFile:e.envFile??`src/env.ts`}}async function K(e={}){let{cwd:t,srcDir:n,outDir:r,silent:i,allowDuplicates:a,schemaValidator:o,envFile:s}=sa(e),c=Date.now(),l=await zi({root:n,cwd:t,envFile:s===!1?void 0:s}),u=ea(e.assetMap,t),d=await Xi({classes:l.classes,routes:l.routes,tokens:l.tokens,injects:l.injects,collisions:l.collisions,env:s===!1?null:l.env,pluginsAndAdapters:l.pluginsAndAdapters,augmentations:l.augmentations,assets:u,outDir:r,allowDuplicates:a,schemaValidator:o}),f=[];if(e.runPlugins!==!1)try{let{runAllPluginTypegens:e}=await Promise.resolve().then(()=>xa),{loadKickConfig:n}=await Promise.resolve().then(()=>Me);f=await e({cwd:t,config:await n(t),silent:!0})}catch(e){if(!i){let t=e instanceof Error?e.message:String(e);console.warn(` kick typegen: plugin pipeline failed (${t}) — continuing`)}}e.runPlugins!==!1&&await ua(r,d.written,f,i);let p=Qi(l.tokens),m=Date.now()-c;if(!i){let e=r.replace(t+`/`,``),n=d.resolvedCollisions>0?`, ${d.resolvedCollisions} collisions namespaced`:``,i=d.envWritten?`, env typed`:``,a=d.pluginEntries>0?`, ${d.pluginEntries} plugins/adapters`:``,o=d.augmentationEntries>0?`, ${d.augmentationEntries} augmentations`:``,s=d.assetEntries>0?`, ${d.assetEntries} assets`:``;if(console.log(` kick typegen → ${d.serviceTokens} services, ${d.routeEntries} routes, ${d.moduleTokens} modules${a}${o}${s}${i}${n} → ${e} (${m}ms)`),p.length>0){console.warn(` kick typegen: ${p.length} token(s) don't match the §22.2 convention:`);for(let e of p){let t=e.variable?` [${e.variable}]`:``;console.warn(` '${e.token}' (${e.filePath})${t} — ${e.reason}`),e.suggestion&&console.warn(` → suggestion: ${e.suggestion}`)}}if(l.orphanedClasses.length>0){console.warn(` kick typegen: ${l.orphanedClasses.length} decorated class(es) not matched by any module's import.meta.glob():`);for(let e of l.orphanedClasses)console.warn(` @${e.decorator} ${e.className} (${e.relativePath})`),console.warn(` → not picked up by any glob in ${e.moduleFilePath}`)}}return{scan:l,result:d,tokenWarnings:p}}async function ca(e={}){let t=sa(e),{srcDir:n,silent:r,cwd:i}=t,a={...t,allowDuplicates:!0,runPlugins:!1},o=process.env.KICKJS_WATCH_POLLING===`1`||process.env.KICKJS_WATCH_POLLING===`true`,[{runAllPluginTypegens:s},{loadKickConfig:c}]=await Promise.all([Promise.resolve().then(()=>xa),Promise.resolve().then(()=>Me)]),l=await c(i),u=[],d=async()=>{try{u=(await K({...a})).result.written}catch(e){if(r)return;if(e instanceof Vi)console.error(`
|
|
3791
|
+
`+e.message+`
|
|
3792
|
+
`);else{let t=e instanceof Error?e.message:String(e);console.error(` kick typegen failed: ${t}`)}}},f=async()=>{try{let e=await s({cwd:i,config:l,silent:!0});await ua(t.outDir,u,e,!0)}catch{}};await d(),await f();let{watch:p}=await import(`node:fs`),m=null,h=e=>{e&&/\.(ts|tsx|mts|cts)$/.test(e)&&(e.includes(`.kickjs`)||e.endsWith(`.d.ts`)||(m&&clearTimeout(m),m=setTimeout(()=>{d().then(f)},100)))};if(o){r||console.log(` kick typegen: polling mode (KICKJS_WATCH_POLLING)`);let e=setInterval(()=>{la({...a,silent:!0},!0)},2e3);return()=>clearInterval(e)}let g;try{g=p(n,{recursive:!0},(e,t)=>{h(t)})}catch(e){r||console.warn(` kick typegen: watch mode unavailable (${e?.message??e}). Falling back to polling.`);let t=setInterval(()=>{la({...a,silent:!0},!0)},2e3);return()=>clearInterval(t)}return()=>{m&&clearTimeout(m),g.close()}}async function la(e,t){try{await K(e)}catch(e){if(t)return;if(e instanceof Vi)console.error(`
|
|
3793
|
+
`+e.message+`
|
|
3794
|
+
`);else{let t=e instanceof Error?e.message:String(e);console.error(` kick typegen failed: ${t}`)}}}async function ua(e,t,n,r){let i=new Set;for(let e of t)i.add(d(e));for(let e of n)e.outFile&&i.add(d(e.outFile));let a;try{a=await se(e)}catch{return[]}let o=[];for(let t of a){if(i.has(t))continue;let n=v(e,t);try{if(!(await le(n)).isFile())continue;await ue(n),o.push(t)}catch{}}return o.length>0&&!r&&console.log(` kick typegen: swept ${o.length} stale file(s): ${o.join(`, `)}`),o}const da=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function q(e){return e.parent?.opts()?.dryRun??!1}function J(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
|
|
3795
|
+
(dry run — no files were written)`),console.log()}async function fa(e){if(!e)try{let e=await k(process.cwd());await K({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const pa=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}];async function ma(){console.log(`
|
|
3796
|
+
Built-in generators:
|
|
3797
|
+
`);let e=Math.max(...pa.map(e=>e.name.length));for(let t of pa)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await k(process.cwd()),n=He(t?.plugins??[],t?.commands??[]),r=await cn(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
3798
|
+
Plugin generators:
|
|
3799
|
+
`);let e=Math.max(...r.generators.map(e=>`${e.spec.name} <name>`.length));for(let{source:t,spec:n}of r.generators){let r=`${n.name} <name>`;console.log(` kick g ${r.padEnd(e+2)} ${n.description} [${t}]`)}}if(r.failed.length>0){console.log(`
|
|
3800
|
+
Failed to load:
|
|
3801
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function ha(e,t,n){let r=await k(process.cwd()),i=O(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Jn(i.repo),s=t.pattern??r?.pattern??`ddd`,c=t.pluralize===!1?!1:i.pluralize??!0,l=Ie(r,process.cwd()),u=i.style??`define`;if(!n&&u===`define`){let e=await Mr(v(a),`define`);if(e.length>0){console.error(`\n ${E.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${E.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${E.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${E.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${E.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${E.dim(`// kick.config.ts`)}\n ${E.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let d=[];for(let r of e){let e=await Yn({name:r,modulesDir:v(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,dryRun:n,pluralize:c,prismaClientPath:i.prismaClientPath,tokenScope:l,style:i.style});d.push(...e)}J(d,n),await fa(n)}function ga(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,r)=>{if(t.list){await ma();return}if(!e||e.length===0){n.help();return}let i=q(r);j(i);let[a,o,...s]=e;if(a){let e=await k(process.cwd()),n=He(e?.plugins??[],e?.commands??[]),r=await sn({generatorName:a,itemName:o??``,args:s,flags:t,cwd:process.cwd()},n.generators);if(r){J(r.files,i);return}}await ha(e,t,i)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);j(r),await ha(e,{...n.optsWithGlobals(),...t},r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=q(n);j(r),J(await rr({name:e,outDir:v(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=q(n);j(r),J(await ir({name:e,outDir:v(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
|
|
3802
|
+
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=await k(process.cwd()),a=O(i),o=a.dir??`src/modules`;J(await lr({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
3803
|
+
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=await k(process.cwd()),a=O(i),o=a.dir??`src/modules`;J(await ur({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
3804
|
+
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=await k(process.cwd()),a=O(i),o=a.dir??`src/modules`;J(await dr({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
3805
|
+
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=await k(process.cwd()),a=O(i),o=a.dir??`src/modules`;J(await fr({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await fa(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
3806
|
+
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=await k(process.cwd()),a=O(i),o=a.dir??`src/modules`;J(await pr({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
3807
|
+
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=q(n);j(r);let i=O(await k(process.cwd())),a=i.dir??`src/modules`;J(await Yr({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=q(n);j(r),J(await Nr({name:e,outDir:v(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
3808
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
3809
|
+
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
3810
|
+
Optional: append :optional (shell-safe): description:text:optional
|
|
3811
|
+
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=q(r);j(i),t.length===0&&(console.error(`
|
|
3812
|
+
Error: At least one field is required.
|
|
3813
|
+
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
3814
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
3815
|
+
Optional: append :optional (shell-safe, no quoting needed)
|
|
3816
|
+
`),process.exit(1));let a=await k(process.cwd()),o=O(a),s=n.modulesDir??o.dir??`src/modules`,c=Fr(t),l=Ie(a,process.cwd()),u=a?.pattern??`ddd`;u!==`ddd`&&(console.error(`\n Error: 'kick g scaffold' currently only supports the DDD pattern.\n Detected project pattern: '${u}'.\n Workarounds:\n - Run 'kick g module ${e}' for the ${u} layout (no fields), then add fields manually.\n - Override the pattern for this scaffold by setting kick.config.ts pattern: 'ddd'.\n`),process.exit(1));let d=await Ir({name:e,fields:c,modulesDir:v(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:l,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);J(d,i),await fa(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=q(t);j(n),J(await mr({outDir:v(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=q(t);j(n);let r=e.only??`all`;if(!da.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${da.join(` | `)}`),process.exitCode=1;return}J(await br({outDir:v(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])_a(n,e)}function _a(e,t){let{source:n,spec:r}=t,i=r.args?.[0],a=i?.name??`itemName`,o=i?.required?`<${a}>`:`[${a}]`,s=`${r.name} ${o} [extraArgs...]`,c=e.command(s).description(`${r.description} [${n}]`);for(let e of r.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;c.option(n,e.description??``)}c.action(async(e,n,i,a)=>{let o=q(a);j(o);let s=await sn({generatorName:r.name,itemName:e??``,args:n??[],flags:i,cwd:process.cwd()},[t]);s&&J(s.files,o)})}async function va(e){let t=u.resolve(e.cwd,`.kickjs/types`);await oe(t,{recursive:!0});let n=new Map,i=e.scan??zi,a={cwd:e.cwd,config:e.config,async importTs(e){return await import(x(e).href)},async writeFile(t,n){let r=u.resolve(e.cwd,t);await oe(u.dirname(r),{recursive:!0}),await w(r,n,`utf8`)},getScanResult:e=>{let t=ya(e),r=n.get(t);return r||(r=i(e),n.set(t,r)),r},log:console},o=[];for(let n of e.plugins){let i=await n.generate(a);if(i===null){o.push({id:n.id,status:`skipped`});continue}let s=n.outExtension??`.d.ts`,c=u.join(t,`${n.id.replace(/\//g,`__`)}${s}`),l=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+i+`
|
|
3817
|
+
`,d=``;if(r(c)&&(d=await C(c,`utf8`)),d===l){o.push({id:n.id,status:`unchanged`,outFile:c});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${c})`);await w(c,l,`utf8`),o.push({id:n.id,status:`written`,outFile:c})}return o}function ya(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function ba(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var xa=D({applyDisableFilter:()=>ba,runAllPluginTypegens:()=>Sa});async function Sa(e){let{enabled:t,skipped:n,unknown:r}=ba(He([...ls,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await va({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function Ca(e,t){let{cwd:n,silent:r=!1}=t,a=t.distDir??e?.build?.outDir??`dist`,o=e?.assetMap;if(!o||Object.keys(o).length===0)return null;let s=r?()=>{}:console.log,c=v(n,a);i(c,{recursive:!0});let u=[],d={};for(let[e,t]of Object.entries(o)){let r=await wa(e,t,n,c);u.push(r.entrySummary),Object.assign(d,r.manifestSlice),s(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let f={version:1,entries:d},p=h(c,`.kickjs-assets.json`);return l(p,JSON.stringify(f,null,2)+`
|
|
3818
|
+
`,`utf-8`),s(` ✓ wrote manifest → ${_(n,p)} (${Object.keys(d).length} entries)`),{manifestPath:p,entries:u,manifest:f}}async function wa(e,t,a,o){let s=v(a,t.src),c=t.dest?v(a,t.dest):h(o,e);if(Ea(c,a))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};if(!r(s)||!Da(s))return{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};let l=await fe(t.glob??`**/*`,{cwd:s,nodir:!0,dot:!1,posix:!0});i(c,{recursive:!0});let u={},{pairs:d,collisionGroupsResolved:p}=me(e,[...l].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of d){let r=h(s,e),a=h(c,e);i(f(a),{recursive:!0}),n(r,a),u[t]=Ta(o,a)}return p>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${p} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:l.length},manifestSlice:u}}function Ta(e,t){return _(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function Ea(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function Da(e){try{return c(e).isDirectory()}catch{return!1}}function Oa(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function ka(e,t,n={}){t&&(process.env.PORT=t);let r=Oa(n.polling),i=process.cwd(),a=await k(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await K({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await Sa({cwd:i,config:a});let{createRequire:c}=await import(`node:module`),{createServer:l}=await import(x(c(v(`package.json`)).resolve(`vite`)).href),u=await l({configFile:v(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),d=a?.assetMap?Object.values(a.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>v(i,e)):[],f=e=>d.some(t=>e===t||e.startsWith(`${t}/`)),p=null,m=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=f(e);!t&&!n||(p&&clearTimeout(p),p=setTimeout(()=>{K({cwd:i,silent:!0,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1}).catch(()=>{}),Sa({cwd:i,config:a,silent:!0}).catch(()=>{})},100))};u.watcher.on(`add`,m),u.watcher.on(`unlink`,m),u.watcher.on(`change`,m),d.length>0&&u.watcher.add(d),await u.listen(),u.printUrls(),console.log(`
|
|
3819
|
+
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
3820
|
+
`);let h=async()=>{p&&clearTimeout(p),await u.close(),process.exit(0)};process.on(`SIGINT`,h),process.on(`SIGTERM`,h)}function Aa(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).action(async e=>{try{await ka(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
3821
|
+
Error: vite is not installed.
|
|
3822
|
+
Run: pnpm add -D vite unplugin-swc
|
|
3823
|
+
`):console.error(`
|
|
3824
|
+
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
3825
|
+
Building for production...
|
|
3826
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(x(e(v(`package.json`)).resolve(`vite`)).href);await t({configFile:v(`vite.config.ts`)});let a=await k(process.cwd()),o=a?.copyDirs??[];if(o.length>0){console.log(`
|
|
3827
|
+
Copying directories to dist...`);for(let e of o){let t=typeof e==`string`?e:e.src,a=typeof e==`string`?h(`dist`,e):e.dest??h(`dist`,t),o=v(t),s=v(a);if(!r(o)){console.log(` ⚠ Skipped ${t} (not found)`);continue}i(s,{recursive:!0}),n(o,s,{recursive:!0}),console.log(` ✓ ${t} → ${a}`)}}if(a?.assetMap&&Object.keys(a.assetMap).length>0){console.log(`
|
|
3828
|
+
Building asset map...`);try{await Ca(a,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
3829
|
+
Build complete.
|
|
3830
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await k(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
3831
|
+
Building asset map...`);try{await Ca(e,{cwd:process.cwd()}),console.log(`
|
|
3832
|
+
Asset build complete.
|
|
3833
|
+
`)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),ke(e.entry,t)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await ka(e.entry,e.port)}catch(e){console.error(`
|
|
3834
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function ja(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
|
|
3835
|
+
KickJS CLI
|
|
3836
|
+
|
|
3837
|
+
System:
|
|
3838
|
+
OS: ${ge()} ${_e()} (${he()})
|
|
3839
|
+
Node: ${process.version}
|
|
3840
|
+
|
|
3841
|
+
Packages:
|
|
3842
|
+
@forinda/kickjs workspace
|
|
3843
|
+
@forinda/kickjs-vite workspace
|
|
3844
|
+
@forinda/kickjs-cli workspace
|
|
3845
|
+
`)})}const{bold:Y,dim:X,green:Ma,red:Na,yellow:Pa,blue:Fa}=E;function Ia(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,a=[];return t&&a.push(`${t}d`),n&&a.push(`${n}h`),r&&a.push(`${r}m`),a.push(`${i}s`),a.join(` `)}async function La(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Ra(e,t){try{return await La(`${e}${t}`)}catch{return null}}async function za(e){let[t,n,r,i,a]=await Promise.all([Ra(e,`/health`),Ra(e,`/metrics`),Ra(e,`/routes`),Ra(e,`/container`),Ra(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function Ba(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=X(`─`.repeat(60));if(console.log(),console.log(Y(` KickJS Inspector`)+X(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Ma(`● healthy`):Na(`● `+n.status);console.log(` ${Y(`Health:`)} ${e}`)}else console.log(` ${Y(`Health:`)} ${Na(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Na:r.errorRate>0?Pa:Ma;console.log(` ${Y(`Uptime:`)} ${Ia(r.uptimeSeconds)}`),console.log(` ${Y(`Requests:`)} ${r.requests}`),console.log(` ${Y(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${X(`(`)}${t(e+`%`)}${X(`)`)}`)}if(a&&console.log(` ${Y(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${Y(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(Y(` Routes`)),console.log(s),console.log(` ${X(`METHOD`)} ${X(`PATH`.padEnd(36))} ${X(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${At(e.method)} ${t} ${Fa(e.controller)}.${X(e.handler)}`)}}console.log(s),console.log()}function Va(e){e.command(`inspect [url]`).description(`Connect to a running KickJS app and display debug info`).option(`-p, --port <port>`,`Override port`).option(`-w, --watch`,`Poll every 5 seconds`).option(`-j, --json`,`Output raw JSON`).action(async(e,t)=>{let n=e??`http://localhost:3000`;if(t.port)try{let e=new URL(n);e.port=t.port,n=e.origin}catch{n=`http://localhost:${t.port}`}let r=`${n.replace(/\/$/,``)}/_debug`,i=async()=>{try{let e=await za(r);t.json?console.log(JSON.stringify(e,null,2)):Ba(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Na(` ✖ Could not connect to ${n}`)),console.error(X(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Ha(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Z(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Ua=[{match(e,t){let n=Ha(e,[`config`,`get`])&&Z(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Z(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
|
|
3846
|
+
registers the env schema with kickjs at module-load time. Without it,
|
|
3847
|
+
ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
|
|
3848
|
+
and every user-defined key reads as undefined. @Value() may *appear* to
|
|
3849
|
+
work via a raw process.env fallback, but Zod coercion and schema defaults
|
|
3850
|
+
are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
|
|
3851
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
3852
|
+
import { modules } from './modules'
|
|
3853
|
+
`,codeAfter:`import 'reflect-metadata'
|
|
3854
|
+
import './config' // ← add this — registers env schema
|
|
3855
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
3856
|
+
import { modules } from './modules'
|
|
3857
|
+
`,docs:`https://forinda.github.io/kick-js/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Z(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return Z(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
|
|
3858
|
+
When vitest re-imports your modules across tests, the same class can be
|
|
3859
|
+
registered twice and the container throws. The fix is to wipe the
|
|
3860
|
+
container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
|
|
3861
|
+
import { Container } from '@forinda/kickjs'
|
|
3862
|
+
|
|
3863
|
+
describe('UserController', () => {
|
|
3864
|
+
beforeEach(() => Container.reset())
|
|
3865
|
+
|
|
3866
|
+
it('does the thing', async () => { /* ... */ })
|
|
3867
|
+
})`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Ha(e,[`Module`,`is not a function`])||Ha(e,[`Module`,`no exported member`])?{confidence:80,diagnosis:{id:`module-decorator-not-found`,title:`KickJS does not have a @Module decorator (different pattern from NestJS)`,explanation:`NestJS uses @Module({ controllers, providers }). KickJS uses an interface
|
|
3868
|
+
pattern instead: a class implements AppModule and exposes routes() that
|
|
3869
|
+
returns the controller wiring. This was a deliberate choice — modules
|
|
3870
|
+
become explicit values rather than metadata, which makes them easier to
|
|
3871
|
+
compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
|
|
3872
|
+
import { UserController } from './user.controller'
|
|
3873
|
+
|
|
3874
|
+
@Module({
|
|
3875
|
+
controllers: [UserController],
|
|
3876
|
+
})
|
|
3877
|
+
export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
|
|
3878
|
+
import { UserController } from './user.controller'
|
|
3879
|
+
|
|
3880
|
+
export class UserModule implements AppModule {
|
|
3881
|
+
routes(): ModuleRoutes {
|
|
3882
|
+
return {
|
|
3883
|
+
path: '/users',
|
|
3884
|
+
router: buildRoutes(UserController),
|
|
3885
|
+
controller: UserController,
|
|
3886
|
+
}
|
|
3887
|
+
}
|
|
3888
|
+
}`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}},{match(e,t){return/KickRoutes\s*\[\s*['"](GET|POST|PUT|PATCH|DELETE)/i.test(e)?{confidence:95,diagnosis:{id:`legacy-kick-routes-bracket-syntax`,title:`KickRoutes['POST /users'] is the legacy v1 syntax`,explanation:`KickJS v2 changed the typegen output from a flat string-keyed map to a
|
|
3889
|
+
namespaced shape: KickRoutes.UserController["create"] instead of
|
|
3890
|
+
KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
3891
|
+
and matches the actual class names so refactors propagate via
|
|
3892
|
+
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
3893
|
+
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
3894
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://forinda.github.io/kick-js/guide/typegen.html`}}:null}},{match(e,t){let n=Z(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Z(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
|
|
3895
|
+
cluster: { workers: N }, the framework forks N workers, each of which
|
|
3896
|
+
spins up its own Vite instance on a separate port. The fix landed in
|
|
3897
|
+
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
3898
|
+
silently skips cluster, with a warning. If you see this on an older
|
|
3899
|
+
version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
|
|
3900
|
+
modules,
|
|
3901
|
+
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
3902
|
+
})`,docs:`https://forinda.github.io/kick-js/guide/cluster.html`}}}},{match(e,t){return Z(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
|
|
3903
|
+
reflect-metadata polyfill. The polyfill must be imported once,
|
|
3904
|
+
before any decorator runs. Most projects do this at the top of
|
|
3905
|
+
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
3906
|
+
or "Reflect.getMetadata is not a function" errors at runtime.`,fix:`Add the import at the very top of src/index.ts:`,codeAfter:`import 'reflect-metadata' // ← must be the FIRST import
|
|
3907
|
+
import './config'
|
|
3908
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
3909
|
+
import { modules } from './modules'
|
|
3910
|
+
|
|
3911
|
+
export const app = await bootstrap({ modules })`,docs:`https://forinda.github.io/kick-js/guide/dependency-injection.html`}}:null}},{match(e,t){return Z(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
|
|
3912
|
+
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
3913
|
+
the most likely cause is that the module is missing from the exported
|
|
3914
|
+
array. The CLI usually wires this automatically, but a hand-edit can
|
|
3915
|
+
drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
3916
|
+
import { UserModule } from './users/user.module'
|
|
3917
|
+
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
3918
|
+
|
|
3919
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function Wa(e,t){let n=null;for(let r of Ua){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function Ga(e){let t=e.provider??`openai`,n=process.env.OPENAI_API_KEY;if(t===`openai`&&!n)return{kind:`unavailable`,reason:`OPENAI_API_KEY environment variable is not set`,suggestion:`Set OPENAI_API_KEY in your shell, e.g.
|
|
3920
|
+
export OPENAI_API_KEY="sk-..."
|
|
3921
|
+
|
|
3922
|
+
Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@forinda/kickjs-ai`)}catch{return{kind:`unavailable`,reason:`@forinda/kickjs-ai is not installed`,suggestion:`Install the AI package to enable the LLM fallback:
|
|
3923
|
+
kick add ai
|
|
3924
|
+
|
|
3925
|
+
Or manually:
|
|
3926
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Ka(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=qa((await a.chat({messages:[{role:`system`,content:o},{role:`user`,content:s}]})).content);return e?{kind:`ok`,diagnosis:e}:{kind:`error`,message:`The LLM responded but the payload was not valid JSON in the expected shape. Try again, or file an issue with the error text.`}}catch(e){return{kind:`error`,message:`LLM request failed: ${e instanceof Error?e.message:String(e)}`}}}function Ka(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
3927
|
+
`)}function qa(e){let t=[e,Ja(e),Ya(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Xa(t))return t}catch{continue}return null}function Ja(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Ya(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`&&r){i=!0;continue}if(o===`"`){r=!r;continue}if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Xa(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function Za(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await eo(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
3928
|
+
|
|
3929
|
+
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
3930
|
+
kick explain "config.get returned undefined"
|
|
3931
|
+
pnpm test 2>&1 | kick explain
|
|
3932
|
+
`),process.exit(1));let r=no(),i=Wa(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
3933
|
+
`);return}if(i){ro(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
3934
|
+
`),process.exit(2)),io(n,!1),process.exit(2));let a=await Ga({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Qa(a),null,2)+`
|
|
3935
|
+
`),process.exit(a.kind===`ok`?0:2)),$a(n,a),process.exit(a.kind===`ok`?0:2)})}function Qa(e){return e.kind===`ok`?{matched:!0,source:`ai`,diagnosis:e.diagnosis}:e.kind===`unavailable`?{matched:!1,aiUnavailable:!0,reason:e.reason}:{matched:!1,aiError:!0,error:e.message}}function $a(e,t){if(t.kind===`ok`){ro(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${oo(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${ao(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${oo(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function eo(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:to()}function to(){return new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n)),process.stdin.on(`error`,t)})}function no(){let e=process.cwd();return{cwd:e,hasFile:t=>r(v(e,t))}}function ro(e,t,n,r=!1){let i=oo(e.trim(),200),a=r?`AI-generated — verify before applying`:so(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${ao(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${ao(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${ao(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${ao(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
3936
|
+
`)}function io(e,t){let n=oo(e.trim(),200);process.stdout.write(`\n Explaining: ${n}\n\n`),t?process.stdout.write(` No known-issue matched, and --ai fallback is not yet wired.
|
|
3937
|
+
When @forinda/kickjs-ai ships its provider implementations,
|
|
3938
|
+
this command will call the configured LLM with the error +
|
|
3939
|
+
project context and return a structured fix.
|
|
3940
|
+
|
|
3941
|
+
`):process.stdout.write(` No known-issue matched. Things you can try:
|
|
3942
|
+
|
|
3943
|
+
1. Check the framework docs for the error keywords:
|
|
3944
|
+
https://forinda.github.io/kick-js/
|
|
3945
|
+
|
|
3946
|
+
2. Re-run with --ai to fall back to an LLM (requires
|
|
3947
|
+
@forinda/kickjs-ai with a configured provider):
|
|
3948
|
+
kick explain --ai "<your error>"
|
|
3949
|
+
|
|
3950
|
+
3. File an issue with the error text:
|
|
3951
|
+
https://github.com/forinda/kick-js/issues/new
|
|
3952
|
+
|
|
3953
|
+
`)}function ao(e,t){return e.split(`
|
|
3954
|
+
`).map(e=>`${t}${e}`).join(`
|
|
3955
|
+
`)}function oo(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function so(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function co(e){let t=e.command(`mcp`).description(`Model Context Protocol commands (start | init)`);t.command(`start`,{isDefault:!0}).description(`Run the built application as an MCP server over stdio`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`--node-arg <arg...>`,`Extra arguments to pass to node`).action(lo),t.command(`init`).description(`Generate .mcp.json for Claude Code / Cursor / Zed`).option(`-n, --name <name>`,`Server name (defaults to package.json name)`).option(`-o, --out <file>`,`Output file`,`.mcp.json`).option(`-f, --force`,`Overwrite an existing entry without prompting`).option(`--global`,`Write to ~/.mcp.json instead of the project root`).action(uo)}function lo(e){let t=v(e.entry);r(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],i=ne(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});i.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),i.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let a=e=>{i.killed||i.kill(e)};process.on(`SIGINT`,()=>a(`SIGINT`)),process.on(`SIGTERM`,()=>a(`SIGTERM`))}function uo(e){let t=process.cwd(),n=fo(t)??d(t),i=e.name??n,o=e.global?v(process.env.HOME??`.`,`.mcp.json`):v(t,e.out),s={command:`kick`,args:[`mcp`],cwd:t},c={mcpServers:{}};if(r(o))try{let e=a(o,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(c={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${o} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}c.mcpServers[i]&&!e.force&&(process.stderr.write(`Error: an entry for "${i}" already exists in ${o}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),c.mcpServers[i]=s,l(o,JSON.stringify(c,null,2)+`
|
|
3956
|
+
`,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${i}" to ${o}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function fo(e){let t=v(e,`package.json`);if(!r(t))return null;try{let e=a(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function po(e){e.command(`tinker`).description(`Interactive REPL with DI container and services loaded`).option(`-e, --entry <file>`,`Entry file to load`,`src/index.ts`).action(async e=>{let t=process.cwd(),n=v(t,e.entry);r(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let i=ho(t,`tsx`);i||(console.error(`
|
|
3957
|
+
Error: tsx not found. Install it: pnpm add -D tsx
|
|
3958
|
+
`),process.exit(1));let a=mo(n,e.entry),o=h(t,`.kick-tinker.mjs`),{writeFileSync:s,unlinkSync:c}=await import(`node:fs`);s(o,a,`utf-8`);try{let e=te(o,[],{cwd:t,execPath:i,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{c(o)}catch{}}})}function mo(e,t){return`
|
|
3959
|
+
import 'reflect-metadata'
|
|
3960
|
+
|
|
3961
|
+
// Prevent bootstrap() from starting the HTTP server
|
|
3962
|
+
process.env.KICK_TINKER = '1'
|
|
3963
|
+
|
|
3964
|
+
console.log('\\n 🔧 KickJS Tinker')
|
|
3965
|
+
console.log(' Loading: ${t}\\n')
|
|
3966
|
+
|
|
3967
|
+
// Load core
|
|
3968
|
+
let Container, Logger, HttpException, HttpStatus
|
|
3969
|
+
try {
|
|
3970
|
+
const core = await import('@forinda/kickjs')
|
|
3971
|
+
Container = core.Container
|
|
3972
|
+
Logger = core.Logger
|
|
3973
|
+
HttpException = core.HttpException
|
|
3974
|
+
HttpStatus = core.HttpStatus
|
|
3975
|
+
} catch {
|
|
3976
|
+
console.error(' Error: @forinda/kickjs not found.')
|
|
3977
|
+
console.error(' Install it: pnpm add @forinda/kickjs\\n')
|
|
3978
|
+
process.exit(1)
|
|
3979
|
+
}
|
|
3980
|
+
|
|
3981
|
+
// Load entry to trigger decorator registration
|
|
3982
|
+
try {
|
|
3983
|
+
await import('${x(e).href}')
|
|
3984
|
+
} catch (err) {
|
|
3985
|
+
console.warn(' Warning: ' + err.message)
|
|
3986
|
+
console.warn(' Container may be partially initialized.\\n')
|
|
3987
|
+
}
|
|
3988
|
+
|
|
3989
|
+
const container = Container.getInstance()
|
|
3990
|
+
|
|
3991
|
+
// Start REPL
|
|
3992
|
+
const repl = await import('node:repl')
|
|
3993
|
+
const server = repl.start({ prompt: 'kick> ', useGlobal: true })
|
|
3994
|
+
|
|
3995
|
+
server.context.container = container
|
|
3996
|
+
server.context.Container = Container
|
|
3997
|
+
server.context.resolve = (token) => container.resolve(token)
|
|
3998
|
+
server.context.Logger = Logger
|
|
3999
|
+
server.context.HttpException = HttpException
|
|
4000
|
+
server.context.HttpStatus = HttpStatus
|
|
4001
|
+
|
|
4002
|
+
console.log(' Available globals:')
|
|
4003
|
+
console.log(' container — DI container instance')
|
|
4004
|
+
console.log(' resolve(T) — shorthand for container.resolve(T)')
|
|
4005
|
+
console.log(' Container, Logger, HttpException, HttpStatus')
|
|
4006
|
+
console.log()
|
|
4007
|
+
|
|
4008
|
+
server.on('exit', () => {
|
|
4009
|
+
console.log('\\n Goodbye!\\n')
|
|
4010
|
+
process.exit(0)
|
|
4011
|
+
})
|
|
4012
|
+
`}function ho(e,t){let n=e;for(;;){let e=h(n,`node_modules`,`.bin`,t);if(r(e))return e;let i=v(n,`..`);if(i===n)break;n=i}return null}function go(e,t){let n=RegExp(`^\\s*${B(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
|
|
4013
|
+
`;)s++;else{for(s+=2;s+1<a.length&&!(a[s]===`*`&&a[s+1]===`/`);)s++;s+=2}continue}let t=a[s]??``;if(t===`'`||t===`"`||t==="`"){let e=t;for(s++;s<a.length&&a[s]!==e;)a[s]===`\\`&&s++,s++}else if(t===`(`)o++;else if(t===`)`&&(o--,o===0))break;s++}if(o!==0)break;let c=a.slice(t,s);if(n.test(c)){let t=e;for(;t>0&&(a[t-1]===` `||a[t-1]===` `||a[t-1]===`
|
|
4014
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function _o(e,t){let n=Qn(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=go(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${B(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function vo(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=R(t),o=I(t),s=i?z(a):a,c=h(n,s);if(!await Xe(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await P({message:E.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
4015
|
+
Cancelled.
|
|
4016
|
+
`);return}await ce(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=h(n,`index.ts`);if(await Xe(l)){let e=await C(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${B(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${B(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=_o(e,o),e=e.replace(/\n{3,}/g,`
|
|
4017
|
+
|
|
4018
|
+
`),e!==t&&(await w(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function yo(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=O(await k(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await vo({name:n,modulesDir:v(r),force:t.force,pluralize:i})})}var bo=D({findProjectRoot:()=>So});const xo=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function So(e=process.cwd()){let t=v(e),{root:n}=g(t),i=null,a=t;for(;;){for(let e of xo)if(r(v(a,e)))return a;if(i===null&&r(v(a,`package.json`))&&(i=a),a===n)break;let e=f(a);if(e===a)break;a=e}return i??t}function Co(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;console.warn(` kick typegen: unknown --schema-validator '${e}' (only 'zod' and 'false' are supported). Falling back to project config.`)}}function wo(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function To(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=So(process.cwd()),n=await k(t);if(e.list){let{mergeCliPlugins:e}=await Promise.resolve().then(()=>Ue),{builtinCliPlugins:t}=await Promise.resolve().then(()=>cs),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
|
|
4019
|
+
Registered typegen plugins:
|
|
4020
|
+
`);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let r=Co(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=wo(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ca(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{let{result:r}=await K(a),i=await Sa({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&i.some(e=>e.status===`written`)&&process.exit(1),e.check||await ua(v(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r.written,i,e.silent??!1)}}catch(e){e instanceof Vi?console.error(`
|
|
4021
|
+
`+e.message+`
|
|
4022
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Eo(e){let t=[];if(!r(e))return t;let n=o(e,{withFileTypes:!0});for(let r of n){let n=h(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Eo(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Do(e){try{return a(e,`utf-8`)}catch{return``}}const Oo=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function ko(e,t){let n=Do(h(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Oo.has(t.toLowerCase())||t.length<32)return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value or too short (< 32 chars) — change it`}}}for(let e of t)for(let t of[/JWT_SECRET['"]?\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i,/secret\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i])if(t.test(e))return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value in source code — use an environment variable`};return null}function Ao(e){for(let t of e)if(/cors\s*\(/.test(t)&&/origin\s*:\s*['"]\*['"]/.test(t))return{severity:`CRITICAL`,message:`CORS origin is '*' — restrict to your domains`};return null}function jo(e){for(let t of e)if(/rateLimit/i.test(t)||/@RateLimit/i.test(t))return null;return{severity:`WARNING`,message:`No rate limiting detected — add rateLimit() middleware or @RateLimit decorator`}}function Mo(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function No(e){let t=!1,n=!1;for(let r of e)/tokenStore/i.test(r)&&(t=!0),/MemoryTokenStore/i.test(r)&&(n=!0);return n?{severity:`WARNING`,message:`MemoryTokenStore detected — use a persistent store (Redis, DB) for production deployments`}:t?null:{severity:`WARNING`,message:`No token revocation store detected — consider adding one for auth token management`}}function Po(e){for(let t of e)if(/helmet\s*\(/.test(t))return/security\s*\.\s*helmet\s*.*false/.test(t)?{severity:`WARNING`,message:`Helmet security headers are disabled — enable them for production`}:{severity:`INFO`,message:`Helmet security headers active`};return{severity:`WARNING`,message:`Helmet not detected — add helmet() middleware for security headers`}}function Fo(e){for(let t of e)if(/AuthAdapter/i.test(t))return{severity:`INFO`,message:`AuthAdapter configured`};return{severity:`INFO`,message:`No AuthAdapter detected — add one if your app requires authentication`}}function Io(e){let t=Eo(h(e,`src`)).map(e=>Do(e)),n=[],r=ko(e,t);r&&n.push(r);let i=Ao(t);i&&n.push(i);let a=jo(t);a&&n.push(a);let o=Mo();o&&n.push(o);let s=No(t);return s&&n.push(s),n.push(Po(t)),n.push(Fo(t)),n}function Lo(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
|
|
4023
|
+
Usage: kick check --deploy
|
|
4024
|
+
|
|
4025
|
+
Available checks:
|
|
4026
|
+
--deploy Audit for production readiness (security, config, best practices)
|
|
4027
|
+
`);return}let t=process.cwd();Mt(`KickJS Deploy Check`);let n=Rt();n.start(`Scanning project...`);let r=Io(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)F.message(`${jt(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?E.red(`${a} critical`):`${a} critical`,o>0?E.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(Nt(E.red(`${l} — fix critical issues before deploying`)),process.exit(1)):Nt(E.green(`${l} — looking good!`))})}async function Q(e){return Ee({configPath:u.resolve(process.cwd(),e.config)})}async function $(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}async function Ro(e){if(e.adapter||(e.dialect??`postgres`)!==`postgres`||!e.connectionString)return null;let t=new(await(import(`pg`))).default.Pool({connectionString:e.connectionString});return{runner:t,cleanup:async()=>{await t.end()}}}function zo(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function Bo(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await Q(t),i=await Ro(r),a=i?e=>ve(i.runner,e):void 0;try{let i=await ye({name:e,config:r,cwd:n,empty:t.empty,detectCompositeRefs:a});if(i.status===`no-changes`){console.log(`No schema changes detected.`);return}if(i.empty){console.log(`Created empty migration ${i.migrationDir} (author up.sql + down.sql).`);return}let o=i.changeCount===1?``:`s`;console.log(`Created migration ${i.migrationDir} (${i.changeCount} change${o}).`)}finally{await i?.cleanup()}});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await xe({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await we({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await be({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Se({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{zo(await Ce({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await w(i,Te(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}function Vo(e){return e.optsWithGlobals().dryRun??!1}function Ho(e){e.command(`codemod`).description(`Codebase migration commands (AST-style rewrites — distinct from db migrate)`).command(`modules`).description(`Rewrite module declarations between class form and the defineModule factory.
|
|
4028
|
+
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
4029
|
+
--target define|class Override the migration direction.
|
|
4030
|
+
--apply Apply the changes (default: dry-run preview).
|
|
4031
|
+
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=Vo(t)||!e.apply;j(n),e.experimental||(console.error(`
|
|
4032
|
+
`+E.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
4033
|
+
The regex-based rewrite handles the shapes our templates produce.
|
|
4034
|
+
Hand-rolled modules with non-standard structures may be skipped.
|
|
4035
|
+
Always commit before running with --apply.
|
|
4036
|
+
`),process.exit(1));let r=O(await k(process.cwd())),i=v(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${E.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=E.dim(`→ ${a}`),s=n?E.dim(`(dry-run)`):E.bold(`(applying)`);console.log(`\n ${E.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${E.dim(i)}\n`);let c=e.backup!==!1&&!n,l=await jr(i,{dryRun:n,target:a,backup:c});if(l.backupDir){let e=l.backupDir;console.log(` ${E.green(`✓`)} backup: ${E.dim(e)}\n ${E.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !n&&e.backup===!1&&console.log(` ${E.dim(`(--no-backup — skipping snapshot)`)}\n`);let u=0,d=0;for(let e of l.files)if(e.status===`migrated`)u++,console.log(` ${E.green(`✓`)} ${e.path}`);else{d++;let t=E.dim(`(${e.reason??`skipped`})`);console.log(` ${E.dim(`-`)} ${e.path} ${t}`)}if(console.log(),l.indexStatus===`migrated`)console.log(` ${E.green(`✓`)} ${l.indexPath}`);else if(l.indexStatus===`skipped`){let e=E.dim(`(${l.indexReason??`skipped`})`);console.log(` ${E.dim(`-`)} ${l.indexPath} ${e}`)}else console.log(` ${E.dim(`-`)} ${l.indexPath} ${E.dim(`(not found)`)}`);let f=n?E.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${E.bold(String(u))} migrated, ${E.bold(String(d))} skipped${f}\n`)})}const Uo=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],Wo=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=Go(e.cwd);if(!t)return null;let n=u.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${Ko(u.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
|
|
4037
|
+
`)}});function Go(e){for(let t of Uo){let n=u.resolve(e,t);if(t.endsWith(`.ts`)){if(r(n))return n}else{let e=u.join(n,`index.ts`);if(r(e))return e}}return null}function Ko(e){return e.replace(/\\/g,`/`)}const qo=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!r(u.resolve(e.cwd,`kick.config.ts`)))return null;let t=await k(e.cwd);if(!t?.assetMap)return null;let n=ea(t.assetMap,e.cwd);return n.count===0?null:ta(n)}}),Jo="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n";function Yo(e,t,n){if(e.length===0)return`${Jo}
|
|
4038
|
+
// (no routes discovered yet — annotate a controller method with
|
|
4039
|
+
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
4040
|
+
declare global {
|
|
4041
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
4042
|
+
namespace KickRoutes {}
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
export {}
|
|
4046
|
+
`;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=Qo(e,r,t,n,i);return a?`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??Xo(e),l=Zo(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
|
|
4047
|
+
`))}return`${Jo}${$o(i)}
|
|
4048
|
+
declare global {
|
|
4049
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
4050
|
+
namespace KickRoutes {
|
|
4051
|
+
${o.join(`
|
|
4052
|
+
`)}
|
|
4053
|
+
}
|
|
4054
|
+
}
|
|
4055
|
+
|
|
4056
|
+
export {}
|
|
4057
|
+
`}function Xo(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function Zo(e){let t=[];return e.queryFilterable&&e.queryFilterable.length>0&&t.push(`Filterable: ${e.queryFilterable.join(`, `)}`),e.querySortable&&e.querySortable.length>0&&t.push(`Sortable: ${e.querySortable.join(`, `)}`),e.querySearchable&&e.querySearchable.length>0&&t.push(`Searchable: ${e.querySearchable.join(`, `)}`),t}function Qo(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=es(e.source,t,n);if(a===`unknown`)return null;let o=`${a}::${e.identifier}`,s=i.get(o)?.specifier;return s?s=i.get(o).specifier:(s=`_S${i.size}`,i.set(o,{identifier:e.identifier,specifier:s})),s}function $o(e){if(e.size===0)return``;let t=[];for(let[n,r]of e){let[e]=n.split(`::`);t.push(`import type { ${r.identifier} as ${r.specifier} } from '${e}'`)}return t.join(`
|
|
4058
|
+
`)+`
|
|
4059
|
+
`}function es(e,t,n){if(e===null)return`unknown`;let r=f(n);if(e===``){let e=_(r,t).split(y).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=_(r,v(f(t),e)).split(y).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const ts=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:ns(e),cwd:e.cwd,envFile:rs(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=u.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Yo(t.routes,r,n)}});function ns(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function rs(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function is(e,t){if(!e)return null;let n=_(f(t),e.filePath).split(y).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
|
|
4060
|
+
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
4061
|
+
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
4062
|
+
|
|
4063
|
+
// Importing the schema as a type lets us infer its shape without
|
|
4064
|
+
// pulling in any runtime code. \`Awaited<>\` strips an accidental
|
|
4065
|
+
// Promise wrap on dynamic-imported defaults.
|
|
4066
|
+
import type _envSchema from '${n}'
|
|
4067
|
+
|
|
4068
|
+
// Local type alias — interfaces can only \`extend\` an identifier,
|
|
4069
|
+
// not an inline import expression, so we resolve the schema's
|
|
4070
|
+
// inferred shape into a named type first.
|
|
4071
|
+
type _KickEnvShape = import('zod').infer<typeof _envSchema>
|
|
4072
|
+
|
|
4073
|
+
declare global {
|
|
4074
|
+
/**
|
|
4075
|
+
* Typed environment registry. Augmented from \`${e.relativePath}\`
|
|
4076
|
+
* so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
|
|
4077
|
+
* all type-safe and autocomplete.
|
|
4078
|
+
*/
|
|
4079
|
+
interface KickEnv extends _KickEnvShape {}
|
|
4080
|
+
|
|
4081
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
4082
|
+
namespace NodeJS {
|
|
4083
|
+
/**
|
|
4084
|
+
* Narrow \`process.env\` so known keys exist as \`string\` (the raw
|
|
4085
|
+
* pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
|
|
4086
|
+
* the schema's transforms internally; access \`process.env\` directly
|
|
4087
|
+
* only when you need the raw string. Unknown keys still resolve to
|
|
4088
|
+
* \`string | undefined\` via the base @types/node declaration.
|
|
4089
|
+
*/
|
|
4090
|
+
interface ProcessEnv extends Record<keyof KickEnv, string> {}
|
|
4091
|
+
}
|
|
4092
|
+
}
|
|
4093
|
+
|
|
4094
|
+
export {}
|
|
4095
|
+
`}const as=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ss(e);if(t===!1)return null;let n=await e.getScanResult({root:os(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=u.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return is(n.env,r)}});function os(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ss(e){return e.config?.typegen?.envFile}var cs=D({builtinCliPlugins:()=>ls});const ls=[A({name:`kick/init`,register:Yt}),A({name:`kick/generate`,register:ga}),A({name:`kick/run`,register:Aa}),A({name:`kick/info`,register:ja}),A({name:`kick/inspect`,register:Va}),A({name:`kick/add`,register:qt}),A({name:`kick/list`,register:Kt}),A({name:`kick/explain`,register:Za}),A({name:`kick/mcp`,register:co}),A({name:`kick/tinker`,register:po}),A({name:`kick/remove`,register:yo}),A({name:`kick/typegen`,register:To}),A({name:`kick/check`,register:Lo}),A({name:`kick/db`,register:Bo,typegens:[Wo()]}),A({name:`kick/codemod`,register:Ho}),A({name:`kick/assets`,typegens:[qo()]}),A({name:`kick/routes`,typegens:[ts()]}),A({name:`kick/env`,typegens:[as()]})],us=f(b(import.meta.url)),ds=JSON.parse(a(h(us,`..`,`package.json`),`utf-8`));async function fs(){let e=new t;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(ds.version);let n=So(process.cwd()),r=await k(n)??{},i=He([...ls,...r.plugins??[]],r.commands??[]);await i.register(e,{cwd:n,config:r,log:e=>console.log(e)}),Ae(e,{...r,commands:i.commands}),e.showHelpAfterError(),await e.parseAsync(process.argv)}fs().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{};
|