@forinda/kickjs-cli 6.8.0 → 6.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/agent-docs-BEaN-yVq.mjs +11 -0
  2. package/dist/{agent-docs-fKQUJYgz.mjs → agent-docs-NyyqHAxw.mjs} +3 -3
  3. package/dist/{agent-docs-fKQUJYgz.mjs.map → agent-docs-NyyqHAxw.mjs.map} +1 -1
  4. package/dist/{build-BDx9kJD_.mjs → build-CNy9rla8.mjs} +3 -3
  5. package/dist/{build-BDx9kJD_.mjs.map → build-CNy9rla8.mjs.map} +1 -1
  6. package/dist/build-DBdGEMiZ.mjs +12 -0
  7. package/dist/builtins-DR3wYkm4.mjs +1498 -0
  8. package/dist/{builtins-5XvbxXOT.mjs → builtins-epL6Z9Me.mjs} +2 -2
  9. package/dist/cli.mjs +2 -2888
  10. package/dist/config-BQy8iVib.mjs +12 -0
  11. package/dist/{config-13M-pdRz.mjs → config-BnGHE669.mjs} +3 -3
  12. package/dist/{config-13M-pdRz.mjs.map → config-BnGHE669.mjs.map} +1 -1
  13. package/dist/{doctor-ebixckGm.mjs → doctor-26f-Bu4P.mjs} +9 -8
  14. package/dist/doctor-26f-Bu4P.mjs.map +1 -0
  15. package/dist/{fullstack-1pSNtZTQ.mjs → fullstack-CeSmhGE2.mjs} +4 -4
  16. package/dist/{fullstack-1pSNtZTQ.mjs.map → fullstack-CeSmhGE2.mjs.map} +1 -1
  17. package/dist/{fullstack-DkQrZR8Y.mjs → fullstack-DUPLtANA.mjs} +3 -3
  18. package/dist/index.d.mts +3 -1
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -2
  21. package/dist/plugin-C3PeTJQb.mjs +11 -0
  22. package/dist/{plugin-CYc-Ejd5.mjs → plugin-RBStrEDQ.mjs} +3 -3
  23. package/dist/{plugin-CYc-Ejd5.mjs.map → plugin-RBStrEDQ.mjs.map} +1 -1
  24. package/dist/{project-BX9P1ntp.mjs → project-DxcX4ryE.mjs} +6 -6
  25. package/dist/{project-BX9P1ntp.mjs.map → project-DxcX4ryE.mjs.map} +1 -1
  26. package/dist/project-Op2Qt1bv.mjs +389 -0
  27. package/dist/{project-docs-ZT5I_aDa.mjs → project-docs-BQ022LVW.mjs} +2 -2
  28. package/dist/{project-docs-ZT5I_aDa.mjs.map → project-docs-BQ022LVW.mjs.map} +1 -1
  29. package/dist/project-docs-uEIleRls.mjs +928 -0
  30. package/dist/{project-root-DYE4IdOm.mjs → project-root-BifjB5PL.mjs} +3 -3
  31. package/dist/{project-root-DYE4IdOm.mjs.map → project-root-BifjB5PL.mjs.map} +1 -1
  32. package/dist/project-root-CtnL9FBb.mjs +11 -0
  33. package/dist/{prompts-DWyN3rhd.mjs → prompts-j1nmMgAf.mjs} +2 -2
  34. package/dist/{prompts-DWyN3rhd.mjs.map → prompts-j1nmMgAf.mjs.map} +1 -1
  35. package/dist/{rolldown-runtime-BhiQ_pHx.mjs → rolldown-runtime-DOk7ha8c.mjs} +1 -1
  36. package/dist/{run-plugins-EHBKYR0W.mjs → run-plugins-BouWvZvo.mjs} +50 -50
  37. package/dist/{run-plugins-EHBKYR0W.mjs.map → run-plugins-BouWvZvo.mjs.map} +1 -1
  38. package/dist/{typegen-BFMgqlSf.mjs → typegen-DRSOapGb.mjs} +5 -5
  39. package/dist/{typegen-BFMgqlSf.mjs.map → typegen-DRSOapGb.mjs.map} +1 -1
  40. package/dist/typegen-b-Siu3FR.mjs +113 -0
  41. package/dist/{types-BCWqa1Q6.mjs → types-DSOcCoe_.mjs} +1 -1
  42. package/package.json +4 -4
  43. package/dist/doctor-ebixckGm.mjs.map +0 -1
  44. package/dist/plugin-CQ0NPO0o.mjs +0 -13
  45. package/dist/plugin-CQ0NPO0o.mjs.map +0 -1
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.8.0
2
+ * @forinda/kickjs-cli v6.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,2890 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
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 S,execSync as C,fork as ee,spawn as te,spawnSync as ne}from"node:child_process";import{access as re,copyFile as ie,mkdir as ae,readFile as w,readdir as oe,rm as se,stat as ce,unlink as le,writeFile as T}from"node:fs/promises";import{KickPluginConflictError as ue,defineCliPlugin as E}from"@forinda/kickjs-cli-kit";import*as D from"@clack/prompts";import O from"picocolors";import de from"pluralize";import{parseSync as fe}from"oxc-parser";import{glob as pe,globSync as me}from"glob";import{groupAssetKeys as he}from"@forinda/kickjs";import{arch as ge,platform as _e,release as ve}from"node:os";var ye=Object.defineProperty,k=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n};function be(e,t,n){C(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function xe(e,t,n){let r=ne(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}function Se(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}Ce(e,r)}}function Ce(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{be(r)}catch{console.error(` Command failed: ${t.name}`),process.exitCode=1;return}}})}var we=k({BUILTIN_REPO_TYPES:()=>Ee,DEPRECATED_REPO_TYPES:()=>De,PACKAGE_MANAGERS:()=>Te,defineConfig:()=>ke,loadKickConfig:()=>j,resolveModuleConfig:()=>A,resolveTokenScope:()=>Ae,validateAssetMap:()=>Pe,warnIfDeprecatedRepo:()=>Oe,writeAssetConfigSnapshot:()=>Ne});const Te=[`pnpm`,`npm`,`yarn`,`bun`],Ee=[`inmemory`],De=[`prisma`,`drizzle`];function Oe(e){return De.includes(e)?(console.warn(` Note: the '${e}' repository preset is deprecated. Generating a generic custom repository named '${e}' instead — wire it to your DB by hand. Pass any name via \`--repo <name>\` or \`modules.repo: { name: '<name>' }\`.`),!0):!1}function ke(e){return e}function Ae(e,t){if(e?.tokenScope&&typeof e.tokenScope==`string`&&e.tokenScope.length>0){let t=je(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=je(e?e[1]:t.name);if(n.length>0)return n}}}catch{}return`app`}function je(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}function A(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`&&!Ee.includes(t.repo)&&(Oe(t.repo)||console.warn(` Warning: modules.repo '${t.repo}' is not a built-in type (${Ee.join(`, `)}). It will generate a stub repository. Use { name: '${t.repo}' } to silence this warning.`)),t}const Me=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];async function j(e){let{findProjectRoot:t}=await Promise.resolve().then(()=>tn),n=t(e);for(let e of Me){let t=h(n,e);try{await re(t)}catch{continue}if(e.endsWith(`.json`)){let e=await w(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=Pe(e,n);for(let e of i)console.warn(` Warning: ${e}`);return Ne(n,e),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=Pe(i,n);for(let e of a)console.warn(` Warning: ${e}`);return Ne(n,i),i}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}return null}function Ne(e,t){if(!(!t?.assetMap||Object.keys(t.assetMap).length===0))try{let n=h(e,`.kickjs`);i(n,{recursive:!0});let r={version:1,assetMap:t.assetMap,...t.build?.outDir?{build:{outDir:t.build.outDir}}:{}};l(h(n,`kick.config.json`),JSON.stringify(r,null,2)+`
12
- `,`utf-8`)}catch{}}function Pe(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&&Fe(v(t,o.dest),i)&&n.push(`assetMap.${a}.dest ('${o.dest}') resolves outside the project root — refusing to copy`)}return n}function Fe(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function Ie(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 ue(`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 ue(`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 ue(`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 ue(`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;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await Promise.resolve().then(()=>tn),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}var Le=k({mergeCliPlugins:()=>Ie});let Re=!1;function M(e){Re=e}const ze=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function N(e,t){Re||(await ae(f(e),{recursive:!0}),await T(e,t,`utf-8`),ze.has(p(e))&&await He(e,t).catch(()=>{}))}let Be;async function Ve(t){if(Be!==void 0)return Be;try{Be=await import(e(h(t,`package.json`)).resolve(`oxfmt`))}catch{Be=null}return Be}async function He(e,t){let n=await Ve(process.cwd());if(!n)return;let r=await We(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await T(e,i.code,`utf-8`)}const Ue=new Map;async function We(e){let t=f(e),n=t;if(Ue.has(n))return Ue.get(n);for(;;){let e=h(t,`.oxfmtrc.json`);if(r(e))try{let t=await w(e,`utf-8`),r=JSON.parse(t);return delete r.$schema,delete r.ignorePatterns,Ue.set(n,r),r}catch{return Ue.set(n,null),null}let i=f(t);if(i===t)return Ue.set(n,null),null;t=i}}async function Ge(e){try{return await re(e),!0}catch{return!1}}const Ke={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`},qe={zod:{name:`zod`,range:`^4.3.6`},valibot:{name:`valibot`,range:`^1.4.1`},yup:{name:`yup`,range:`^1.7.1`}};function Je(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 Ye(e,t,n,r=[],i=`zod`,a=`express`){let o=qe[i],s={"@forinda/kickjs":Je(n,`@forinda/kickjs`),"@forinda/kickjs-schema":Je(n,`@forinda/kickjs-schema`),dotenv:`^17.3.1`,"reflect-metadata":`^0.2.2`,[o.name]:o.range};a===`express`?s.express=`^5.1.0`:a===`fastify`?(s.fastify=`^5.0.0`,s[`@fastify/middie`]=`^9.0.0`,s[`serve-static`]=`^2.2.0`):a===`h3`&&(s.h3=`^1.0.0`,s[`serve-static`]=`^2.2.0`);for(let e of r){let t=Ke[e];t&&!s[t]&&(s[t]=Je(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`kick dev`,"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:s,devDependencies:{"@forinda/kickjs-cli":Je(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":Je(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,...a===`express`?{"@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 Xe(){return`import { defineConfig } from 'vite'
13
- import { resolve } from 'node:path'
14
- import swc from 'unplugin-swc'
15
- import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
16
-
17
- export default defineConfig({
18
- oxc: false,
19
- plugins: [
20
- swc.vite(),
21
- kickjsVitePlugin({ entry: 'src/index.ts' }),
22
- // Watches .env files and triggers a full reload on change so the
23
- // dev server picks up env tweaks without a manual restart.
24
- envWatchPlugin(),
25
- ],
26
- resolve: {
27
- alias: {
28
- '@': resolve(__dirname, 'src'),
29
- },
30
- },
31
- build: {
32
- target: 'node20',
33
- ssr: true,
34
- outDir: 'dist',
35
- sourcemap: true,
36
- rollupOptions: {
37
- input: resolve(__dirname, 'src/index.ts'),
38
- output: { format: 'esm' },
39
- },
40
- },
41
- })
42
- `}function Ze(){return JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,lib:[`ES2022`],types:[`node`,`vite/client`],strict:!0,esModuleInterop:!0,skipLibCheck:!0,sourceMap:!0,declaration:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,outDir:`dist`,paths:{"@/*":[`./src/*`]}},include:[`src`,`.kickjs/types/**/*.d.ts`,`.kickjs/types/**/*.ts`]},null,2)}function Qe(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function $e(){return`# https://editorconfig.org
43
- root = true
44
-
45
- [*]
46
- indent_style = space
47
- indent_size = 2
48
- end_of_line = lf
49
- charset = utf-8
50
- trim_trailing_whitespace = true
51
- insert_final_newline = true
52
-
53
- [*.md]
54
- trim_trailing_whitespace = false
55
- `}function et(){return`node_modules/
56
- dist/
57
- .env
58
- coverage/
59
- .DS_Store
60
- *.tsbuildinfo
61
- .kickjs/
62
- `}function tt(){return`# Auto-detect text files and normalise line endings to LF
63
- * text=auto eol=lf
64
-
65
- # Explicitly mark generated / binary files
66
- *.png binary
67
- *.jpg binary
68
- *.jpeg binary
69
- *.gif binary
70
- *.ico binary
71
- *.woff binary
72
- *.woff2 binary
73
- *.ttf binary
74
- *.eot binary
75
-
76
- # Lock files — treat as generated
77
- pnpm-lock.yaml -diff linguist-generated
78
- yarn.lock -diff linguist-generated
79
- package-lock.json -diff linguist-generated
80
- `}function nt(){return`PORT=3000
81
- NODE_ENV=development
82
- `}function rt(){return`PORT=3000
83
- NODE_ENV=development
84
- `}function it(){return`import { defineConfig } from 'vitest/config'
85
- import swc from 'unplugin-swc'
86
-
87
- export default defineConfig({
88
- plugins: [swc.vite()],
89
- test: {
90
- globals: true,
91
- environment: 'node',
92
- include: ['src/**/*.test.ts'],
93
- },
94
- })
95
- `}const at={express:{from:`@forinda/kickjs`,name:`expressRuntime`},fastify:{from:`@forinda/kickjs/fastify`,name:`fastifyRuntime`},h3:{from:`@forinda/kickjs/h3`,name:`h3Runtime`}};function ot(e,t,n,r=[],i=`express`){let a=at[i],o=i===`express`;switch(t){case`minimal`:{let t=[],i=[],s=o?`import { bootstrap, ${a.name} } from '@forinda/kickjs'`:`import { bootstrap } from '@forinda/kickjs'\nimport { ${a.name} } from '${a.from}'`;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(),`));let c=t.length?t.join(`
96
- `)+`
97
- `:``,l=i.length?`,\n adapters: [\n${i.join(`
98
- `)}\n ]`:``;return`import 'reflect-metadata'
99
- // Side-effect import — registers the extended env schema with kickjs
100
- // **before** any controller / service / @Value gets resolved. Without
101
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
102
- // cached schema would still be the base shape. See guide/configuration.
103
- import './config'
104
- ${s}
105
- ${c}import { modules } from './modules'
106
-
107
- // Export the app for the Vite plugin (dev mode)
108
- export const app = await bootstrap({ modules, runtime: ${a.name}()${l} })
109
- `}default:{let t=[],i=[];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 }),`));let s=t.length?t.join(`
110
- `)+`
111
- `:``,c=i.length?`\n adapters: [\n${i.join(`
112
- `)}\n ],`:``,l=[`bootstrap`,`requestId`,`requestLogger`,`helmet`,`cors`];o&&l.push(a.name);let u=o?`import express from 'express'\nimport {\n ${l.join(`,
113
- `)},\n} from '@forinda/kickjs'`:`import {\n ${l.join(`,
114
- `)},\n} from '@forinda/kickjs'\nimport { ${a.name} } from '${a.from}'`,d=o?`
115
- express.json(),`:``;return`import 'reflect-metadata'
116
- // Side-effect import — registers the extended env schema with kickjs
117
- // **before** any controller / service / @Value gets resolved. Without
118
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
119
- // cached schema would still be the base shape. See guide/configuration.
120
- import './config'
121
- ${u}
122
- ${s}import { modules } from './modules'
123
-
124
- // Export the app for the Vite plugin (dev mode)
125
- export const app = await bootstrap({
126
- modules,
127
- runtime: ${a.name}(),${c}
128
- middleware: [
129
- helmet(),
130
- cors({ origin: '*' }),
131
- requestId(),
132
- requestLogger(),${d}
133
- ],
134
- })
135
- `}}}function st(){return`import { defineModules } from '@forinda/kickjs'
136
- import { HelloModule } from './hello/hello.module'
137
-
138
- // Remove HelloModule and run: kick g module <name>
139
- // \`defineModules()\` returns a chainable list — \`kick g module\` appends
140
- // \`.mount(NewModule())\` to the chain on every generation.
141
- export const modules = defineModules().mount(HelloModule())
142
- `}function ct(e=`zod`){return e===`valibot`?`import { loadEnvFromSchema } from '@forinda/kickjs/config'
143
- import { fromValibot } from '@forinda/kickjs-schema/valibot'
144
- import * as v from 'valibot'
145
-
146
- /**
147
- * Project environment schema (Valibot).
148
- *
149
- * \`fromValibot\` wraps the Valibot schema as a \`KickSchema\` so the
150
- * env loader, validate middleware, and swagger spec generator all see
151
- * the same shape. The default export is the contract \`kick typegen\`
152
- * reads to populate \`KickEnv\` via \`InferSchemaOutput<typeof _envSchema>\`
153
- * — that's what makes \`@Value('FOO')\` autocomplete and
154
- * \`process.env.FOO\` typed.
155
- *
156
- * @example
157
- * DATABASE_URL: v.pipe(v.string(), v.url()),
158
- * JWT_SECRET: v.pipe(v.string(), v.minLength(32)),
159
- * REDIS_URL: v.optional(v.pipe(v.string(), v.url())),
160
- */
161
- const envSchema = fromValibot(
162
- v.object({
163
- PORT: v.optional(v.pipe(v.string(), v.transform(Number)), '3000'),
164
- NODE_ENV: v.optional(v.picklist(['development', 'production', 'test']), 'development'),
165
- LOG_LEVEL: v.optional(v.string(), 'info'),
166
- // DATABASE_URL: v.pipe(v.string(), v.url()),
167
- }),
168
- )
169
-
170
- /**
171
- * IMPORTANT — side effect: register the schema with kickjs's env cache
172
- * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
173
- * this cache, and they will fall back to the base schema (or undefined)
174
- * if no extended schema has been registered before they're resolved.
175
- *
176
- * As long as \`src/index.ts\` imports this file (\`import './config'\`) at
177
- * the top — before \`bootstrap()\` runs — every controller and service
178
- * in the app sees the typed extended values.
179
- */
180
- export const env = loadEnvFromSchema(envSchema)
181
-
182
- export default envSchema
183
- `:e===`yup`?`import { loadEnvFromSchema } from '@forinda/kickjs/config'
184
- import { fromYup } from '@forinda/kickjs-schema/yup'
185
- import * as yup from 'yup'
186
-
187
- /**
188
- * Project environment schema (Yup).
189
- *
190
- * \`fromYup\` wraps the Yup schema as a \`KickSchema\` so the env loader,
191
- * validate middleware, and swagger spec generator all see the same
192
- * shape. The default export is the contract \`kick typegen\` reads to
193
- * populate \`KickEnv\` via \`InferSchemaOutput<typeof _envSchema>\`.
194
- *
195
- * Note: Yup's \`.url()\` defaults to http/https; database connection
196
- * strings like \`postgres://\` use \`.matches(/^[a-z]+:\\/\\/.+/i)\` or
197
- * a plain \`.string().required()\`.
198
- *
199
- * @example
200
- * DATABASE_URL: yup.string().required(),
201
- * JWT_SECRET: yup.string().min(32).required(),
202
- * REDIS_URL: yup.string().url().optional(),
203
- */
204
- const envSchema = fromYup(
205
- yup.object({
206
- PORT: yup.number().default(3000),
207
- NODE_ENV: yup
208
- .string()
209
- .oneOf(['development', 'production', 'test'])
210
- .default('development'),
211
- LOG_LEVEL: yup.string().default('info'),
212
- // DATABASE_URL: yup.string().required(),
213
- }),
214
- )
215
-
216
- /**
217
- * IMPORTANT — side effect: register the schema with kickjs's env cache
218
- * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
219
- * this cache, and they will fall back to the base schema (or undefined)
220
- * if no extended schema has been registered before they're resolved.
221
- *
222
- * As long as \`src/index.ts\` imports this file (\`import './config'\`) at
223
- * the top — before \`bootstrap()\` runs — every controller and service
224
- * in the app sees the typed extended values.
225
- */
226
- export const env = loadEnvFromSchema(envSchema)
227
-
228
- export default envSchema
229
- `:`import { loadEnvFromSchema } from '@forinda/kickjs/config'
230
- import { fromZod } from '@forinda/kickjs-schema/zod'
231
- import { z } from 'zod'
232
-
233
- /**
234
- * Project environment schema (Zod).
235
- *
236
- * \`fromZod\` wraps the Zod schema as a \`KickSchema\` so the env loader,
237
- * validate middleware, and swagger spec generator all see the same
238
- * shape. The default export is the contract \`kick typegen\` reads to
239
- * populate \`KickEnv\` via \`InferSchemaOutput<typeof _envSchema>\` —
240
- * that's what makes \`@Value('FOO')\` autocomplete and
241
- * \`process.env.FOO\` typed.
242
- *
243
- * @example
244
- * DATABASE_URL: z.string().url(),
245
- * JWT_SECRET: z.string().min(32),
246
- * REDIS_URL: z.string().url().optional(),
247
- */
248
- const envSchema = fromZod(
249
- z.object({
250
- PORT: z.coerce.number().default(3000),
251
- NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
252
- LOG_LEVEL: z.string().default('info'),
253
- // DATABASE_URL: z.string().url(),
254
- }),
255
- )
256
-
257
- /**
258
- * IMPORTANT — side effect: register the schema with kickjs's env cache
259
- * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
260
- * this cache, and they will fall back to the base schema (or undefined)
261
- * if no extended schema has been registered before they're resolved.
262
- *
263
- * As long as \`src/index.ts\` imports this file (\`import './config'\`) at
264
- * the top — before \`bootstrap()\` runs — every controller and service
265
- * in the app sees the typed extended values.
266
- */
267
- export const env = loadEnvFromSchema(envSchema)
268
-
269
- export default envSchema
270
- `}function lt(){return`import { Service } from '@forinda/kickjs'
271
-
272
- @Service()
273
- export class HelloService {
274
- greet(name: string) {
275
- return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
276
- }
277
-
278
- healthCheck() {
279
- return { status: 'ok', uptime: process.uptime() }
280
- }
281
- }
282
- `}function ut(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
283
- import { HelloService } from './hello.service'
284
-
285
- // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
286
- // \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
287
- // scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
288
- // See https://kickjs.app/guide/typegen.
289
-
290
- @Controller()
291
- export class HelloController {
292
- @Autowired() private readonly helloService!: HelloService
293
-
294
- // Return-value handlers: the runtime sends the returned payload as
295
- // 200 json, and \`kick typegen\` infers the response type into
296
- // \`KickRoutes.Api\` — which is what makes the typed client
297
- // (@forinda/kickjs-client) end-to-end type-safe.
298
- @Get('/')
299
- index(_ctx: Ctx<KickRoutes.HelloController['index']>) {
300
- return this.helloService.greet('World')
301
- }
302
-
303
- @Get('/health')
304
- health(_ctx: Ctx<KickRoutes.HelloController['health']>) {
305
- return this.helloService.healthCheck()
306
- }
307
- }
308
- `}function dt(){return`import { defineModule } from '@forinda/kickjs'
309
- import { HelloController } from './hello.controller'
310
-
311
- export const HelloModule = defineModule({
312
- name: 'HelloModule',
313
- build: () => ({
314
- // \`register(container)\` is optional — only implement it when you need
315
- // to bind a token to a concrete implementation, e.g.
316
- // register(container) {
317
- // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
318
- // }
319
- // The HelloService uses @Service() so the decorator handles registration.
320
-
321
- routes() {
322
- return {
323
- path: '/hello',
324
- controller: HelloController,
325
- }
326
- },
327
- }),
328
- })
329
- `}function ft(e,t=`inmemory`,n=`pnpm`,r=`express`){return`import { defineConfig } from '@forinda/kickjs-cli'
330
-
331
- export default defineConfig({
332
- pattern: '${e}',
333
- // The HTTP engine this app boots on (matches \`bootstrap({ runtime })\` in
334
- // src/index.ts). Dep-aware commands read it: \`kick add upload\` installs the
335
- // engine's multipart driver, \`kick doctor\` checks the engine peers, and
336
- // \`kick typegen\` flips the runtime escape-hatch types to this engine.
337
- runtime: '${r}',
338
- // Pinned so \`kick add\` and other dep-installing commands always use the
339
- // project's intended package manager, regardless of which lockfile exists.
340
- packageManager: '${n}',
341
- modules: {
342
- dir: 'src/modules',
343
- repo: ${t===`inmemory`?`'inmemory'`:`{ name: '${t}' }`},
344
- pluralize: true,
345
- },
346
-
347
- // \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
348
- // resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
349
- // \`'kickjs-schema'\` routes inference through \`InferSchemaOutput\` so the
350
- // typegen works for any wrapped schema (Zod / Valibot / Yup). Switch
351
- // to \`'zod'\` if you ship Zod schemas without \`fromZod()\` wrapping, or
352
- // set \`schemaValidator: false\` to skip schema-driven body typing.
353
- typegen: {
354
- schemaValidator: 'kickjs-schema',
355
- },
356
-
357
- commands: [
358
- {
359
- name: 'test',
360
- description: 'Run tests with Vitest',
361
- steps: 'npx vitest run',
362
- },
363
- {
364
- name: 'format',
365
- description: 'Format code with Prettier',
366
- steps: 'npx prettier --write src/',
367
- },
368
- {
369
- name: 'format:check',
370
- description: 'Check formatting without writing',
371
- steps: 'npx prettier --check src/',
372
- },
373
- {
374
- name: 'ci:check',
375
- description: 'Run typecheck + format check',
376
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
377
- aliases: ['verify'],
378
- },
379
- ],
380
- })
381
- `}function pt(e,t,n){let r={rest:`REST API`,minimal:`Minimal`,fullstack:`Fullstack (KickJS API + typed web app)`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),`# ${e}
382
-
383
- A **${r[t]??`REST API`}** built with [KickJS](https://kickjs.app/) — a decorator-driven Node.js framework for TypeScript that runs on Express, Fastify, or h3 (swap the engine in one line).
384
-
385
- ## Getting Started
386
-
387
- \`\`\`bash
388
- ${n} install
389
- kick dev
390
- \`\`\`
391
-
392
- ## Scripts
393
-
394
- | Command | Description |
395
- |---|---|
396
- | \`kick dev\` | Start dev server with Vite HMR |
397
- | \`kick build\` | Production build |
398
- | \`kick start\` | Run production build |
399
- | \`${n} run test\` | Run tests with Vitest |
400
- | \`kick g module <name>\` | Generate a DDD module |
401
- | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
402
- | \`kick add <package>\` | Add a KickJS package |
403
-
404
- ## Project Structure
405
-
406
- \`\`\`
407
- src/
408
- ├── index.ts # Application entry point
409
- ├── modules/ # Feature modules (controllers, services, repos)
410
- │ └── index.ts # Module registry
411
- └── ...
412
- \`\`\`
413
-
414
- ## Packages
415
-
416
- ${i.map(e=>`- \`${e}\``).join(`
417
- `)}
418
-
419
- ## Adding Features
420
-
421
- \`\`\`bash
422
- kick add auth # Authentication (JWT, API key, OAuth)
423
- kick add swagger # OpenAPI documentation
424
- kick add ws # WebSocket support
425
- kick add queue # Background job processing
426
- kick add --list # Show all available packages
427
- \`\`\`
428
-
429
- For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://kickjs.app/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
430
-
431
- ## Environment Variables
432
-
433
- Copy \`.env.example\` to \`.env\` and configure:
434
-
435
- | Variable | Default | Description |
436
- |---|---|---|
437
- | \`PORT\` | \`3000\` | Server port |
438
- | \`NODE_ENV\` | \`development\` | Environment |
439
-
440
- ## Learn More
441
-
442
- - [KickJS Documentation](https://kickjs.app/)
443
- - [CLI Reference](https://kickjs.app/api/cli.html)
444
- `}function mt(e,t,n){return`# CLAUDE.md — ${e}
445
-
446
- **Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
447
- reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
448
- project conventions, structure, decorator patterns, env wiring, CLI
449
- generators, every gotcha.
450
-
451
- **Then browse \`./.agents/skills/\`.** Each subdirectory is a single
452
- task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
453
- \`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
454
- with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
455
- The structure follows the Claude Code skills convention — agents that
456
- auto-load skills from \`.agents/skills/\` will pick each up by its
457
- frontmatter. Use this directory as the playbook when executing common
458
- KickJS workflows.
459
-
460
- This file is a thin Claude-specific layer on top of those two; when
461
- they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
462
- authoritative and flag the discrepancy.
463
-
464
- ## Why \`.agents/\` + this thin pointer
465
-
466
- \`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
467
- Copilot, Aider, …) — one canonical source so the prose doesn't drift
468
- across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
469
- project context on each conversation, so it stays at the project root.
470
- Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
471
- out-of-sync copies of the same content. Per-agent files
472
- (\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
473
- \`AGENTS.md\` for tool-specific notes that don't belong in the shared
474
- prose.
475
-
476
- ## Claude-specific notes
477
-
478
- - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
479
- to refresh project memory if AGENTS.md changes substantially.
480
- - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
481
- - **Persistent memory** — Claude maintains user/feedback/project/
482
- reference memories under \`.claude/memory/\`. If you ask for
483
- something that contradicts a remembered preference, Claude flags
484
- it before acting; corrections update memory automatically.
485
- - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
486
- or background work. Useful for "wait for the deploy then open a
487
- cleanup PR" or "every Monday triage the issue board" patterns.
488
-
489
- ## Quick reference (full version in .agents/AGENTS.md)
490
-
491
- \`\`\`bash
492
- ${n} install # Install dependencies
493
- kick dev # Dev server with HMR + typegen
494
- kick build && kick start # Production
495
- ${n} run test # Vitest
496
- ${n} run typecheck # tsc --noEmit
497
- ${n} run format # Prettier
498
- \`\`\`
499
-
500
- ## v4 framework reminders
501
-
502
- When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
503
-
504
- - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
505
- - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
506
- - **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.
507
- - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
508
- - **HTTP runtime**: this app may run on Express, Fastify, or h3 — check \`kick.config.ts\` \`runtime\` (or \`bootstrap({ runtime })\`) before writing engine-specific code. Prefer engine-neutral \`ctx\` APIs (\`ctx.json\`/\`ctx.body\`/\`ctx.params\`/\`ctx.sse\`); don't assume \`ctx.req\` is an Express request. Uploads (\`@FileUpload\` → \`ctx.file\`/\`ctx.files\`) work on all three (\`kick add upload\` installs the driver). Full rules in \`.agents/AGENTS.md\` → "HTTP runtime".
509
- - **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.
510
- - **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).
511
- - **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.
512
- - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
513
- - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
514
- - **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.
515
- - **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\`.
516
- - **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.
517
-
518
- For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
519
- `}function ht(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
520
-
521
- This guide is the **canonical, multi-agent reference** for this KickJS
522
- application — Claude, Copilot, Codex, Gemini, etc. all read it first.
523
- Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
524
- add tool-specific affordances on top.
525
-
526
- ## Before You Start
527
-
528
- 1. Run \`${n} install\` to install dependencies
529
- 2. Run \`kick dev\` to verify the app starts${t===`fullstack`?`
530
-
531
- ## Fullstack workspace layout
532
-
533
- This is a WORKSPACE root — the KickJS API lives in \`server/\`, the typed web
534
- app in \`web/\`. Run both with \`${n===`pnpm`?`pnpm dev`:`${n} run dev:server + ${n} run dev:web`}\`.
535
-
536
- The type loop (do not break it):
537
- 1. \`server/\` handlers RETURN their payloads → \`kick typegen\` (auto under
538
- \`kick dev\`) emits \`server/.kickjs/types/kick__routes.ts\` incl. the flat
539
- \`KickRoutes.Api\` map with inferred response types.
540
- 2. \`web/src/types/kick-routes.d.ts\` imports that file TYPE-ONLY.
541
- 3. \`web/src/api.ts\` = \`createClient<KickApi>({ baseUrl: '/api/v1' })\`
542
- — every call site is typed from the server's handlers.
543
-
544
- Rules: kick commands (\`kick g\`, \`kick typegen\`, \`kick dev\`) run in
545
- \`server/\`; never import server runtime code into \`web/\` (the d.ts bridge is
546
- type-only); prefer return-value handlers so responses stay inferable.`:``}
547
- 3. Read the [KickJS documentation](https://kickjs.app/) for framework details
548
-
549
- ## HTTP runtime — DON'T assume Express-only
550
-
551
- KickJS is **engine-pluggable**. It runs on **Express (default), Fastify, or h3** —
552
- chosen with one line: \`bootstrap({ runtime: fastifyRuntime() })\`. Before writing
553
- any engine-specific code, **check which engine this project uses**:
554
-
555
- - \`kick.config.ts\` → the \`runtime\` field (\`'express'\` | \`'fastify'\` | \`'h3'\`), and/or
556
- - \`src/index.ts\` → the \`runtime:\` passed to \`bootstrap()\`, and/or
557
- - \`package.json\` → \`fastify\` / \`h3\` in deps.
558
-
559
- Rules that keep generated code correct on **every** engine:
560
-
561
- - **Prefer return-value handlers.** \`return payload\` sends 200 json on every
562
- engine and lets \`kick typegen\` infer the response type into
563
- \`KickRoutes.Api\` (consumed by the \`@forinda/kickjs-client\` typed client);
564
- \`reply(status, body)\` for non-200, \`reply.noContent()\` for 204. A declared
565
- \`{ response: schema }\` on the route feeds BOTH the OpenAPI success response
566
- and the typegen response type. \`ctx.json(...)\` stays fully supported but
567
- infers \`unknown\`.
568
- - **Lifecycle hooks:** \`@PostConstruct()\` after instantiation; \`@PreDestroy()\`
569
- when a REQUEST-scoped service's request closes (release transactions/handles).
570
- - **Write to \`ctx\`, not the raw request/response.** \`ctx.json()\`, \`ctx.body\`,
571
- \`ctx.params\`, \`ctx.query\`, \`ctx.set/get\`, \`ctx.sse()\` are engine-neutral and
572
- work identically everywhere. \`ctx.req\` / \`ctx.res\` are the engine-native
573
- objects — their **type follows the active runtime** (Express by default; the
574
- \`kick/runtime\` typegen retypes them to Fastify / h3 when \`runtime\` is set).
575
- Don't assume \`ctx.req\` is an \`express.Request\` in portable code.
576
- - **Global middleware** in \`bootstrap({ middleware })\` is connect-style
577
- \`(req, res, next)\` — it runs on all engines (Fastify via \`@fastify/middie\`,
578
- h3 via \`fromNodeMiddleware\`). But on Fastify / h3 the engine parses the body
579
- natively, so the default \`express.json()\` is **auto-skipped** (\`nativeBodyParsing\`).
580
- Don't add \`express.json()\` manually on those engines.
581
- - **File uploads** work on all three: \`@FileUpload({ mode, fieldName, ... })\` →
582
- \`ctx.file\` / \`ctx.files\` (same Multer-shaped object everywhere). Backends:
583
- Express \`multer\`, Fastify \`@fastify/multipart\`, h3 native. Run
584
- \`kick add upload\` to install the runtime-correct driver. The \`@FileUpload\`
585
- decorator is **memory-only** (portable); disk / custom-storage (\`storage\` /
586
- \`dest\`) is Express-only via the \`upload.single/array()\` middleware.
587
- - **Engine subpaths**: \`import { fastifyRuntime } from '@forinda/kickjs/fastify'\`
588
- or \`h3Runtime\` from \`'@forinda/kickjs/h3'\`. Express is the zero-config default
589
- (no import, nothing to install).
590
- - **Not supported on Fastify / h3**: \`ctx.render()\` (no view engine). Calling it
591
- throws a clear error rather than failing silently.
592
- - Run \`kick doctor\` to verify the runtime's engine peers + upload driver are installed.
593
-
594
- ## v4 Conventions (don't skip)
595
-
596
- KickJS v4 made a handful of structural changes from v3. Internalise these
597
- before generating or modifying code — they are the source of most agent
598
- mistakes:
599
-
600
- - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
601
-
602
- \`\`\`ts
603
- export const MyAdapter = defineAdapter<MyOptions>({
604
- name: 'MyAdapter',
605
- defaults: { ... },
606
- build: (config) => ({
607
- beforeMount({ app }) { /* ... */ },
608
- afterStart({ server }) { /* ... */ },
609
- }),
610
- })
611
- \`\`\`
612
-
613
- - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
614
-
615
- - **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
616
- the key segment is **PascalCase** (the regex enforces both):
617
-
618
- \`\`\`ts
619
- const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
620
- const DB = createToken<Database>('app/Db/connection')
621
- \`\`\`
622
-
623
- The \`kick/\` prefix is reserved for first-party packages; this project
624
- owns its own scope (\`app/\`, your domain name, etc.).
625
-
626
- - **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
627
- the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
628
- is a v3 leftover; the linter and codegen reject it.
629
-
630
- - **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
631
- side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
632
- import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
633
- returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
634
- (Zod coercion + defaults silently skipped).
635
-
636
- - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
637
- HMR contract at the top of "Module Pattern" below. The CLI enforces this;
638
- hand-rolled files must too.
639
-
640
- - **Assets** — drop new template files into \`src/templates/<namespace>/\`
641
- (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
642
- \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
643
- no manual build step.
644
-
645
- - **Context over \`@Middleware()\`** — when a middleware's only job is to
646
- populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
647
- (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
648
- Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
649
- Reserve \`@Middleware()\` for response short-circuit / stream mutation /
650
- pre-route-matching work.
651
-
652
- Two ground rules around the data flow — both stem from the fact that
653
- every per-request stage gets its OWN \`RequestContext\` instance, all
654
- reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
655
- - **\`resolve\` and \`onError\` must RETURN the value.** The runner
656
- writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
657
- property assignment (\`ctx.tenant = …\`) sticks to the contributor
658
- instance only — the handler instance never sees it.
659
- - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
660
- \`getRequestValue(key)\` from a service that has no \`ctx\` reference
661
- — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
662
- Express request is shared; bespoke property assignments don't.
663
-
664
- - **Test isolation** — default to \`Container.create()\` for fresh DI state.
665
- Never \`new Container()\` and never \`getInstance().reset()\` — both leak
666
- registrations between tests.
667
-
668
- \`\`\`ts
669
- const container = Container.create()
670
- // ... register test-scoped providers, run, discard
671
- \`\`\`
672
-
673
- - **Bootstrap export** — \`src/index.ts\` MUST end with
674
- \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
675
- the named \`app\` symbol to drive HMR module swaps; testing helpers
676
- (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
677
- the \`export\` and \`kick dev\` will silently fall back to a full restart
678
- on every save while \`createTestApp\` complains about a missing handle.
679
-
680
- - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
681
- adapters in dedicated folders and re-export aggregated arrays. Do **not**
682
- inline registration in the entry file:
683
-
684
- \`\`\`ts
685
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
686
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
687
- // OR with \`modules.style: 'class'\`:
688
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
689
-
690
- // src/middleware/index.ts
691
- export const middleware = [helmet(), cors(), requestId(), ...]
692
-
693
- // src/plugins/index.ts
694
- export const plugins = [MetricsPlugin(), AuditPlugin()]
695
-
696
- // src/adapters/index.ts
697
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
698
- \`\`\`
699
-
700
- \`\`\`ts
701
- // src/index.ts — stays small; one import per category
702
- import 'reflect-metadata'
703
- import './config'
704
- import { bootstrap } from '@forinda/kickjs'
705
- import { modules } from './modules'
706
- import { middleware } from './middleware'
707
- import { plugins } from './plugins'
708
- import { adapters } from './adapters'
709
-
710
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
711
- \`\`\`
712
-
713
- This keeps the entry file diff-friendly, scales to dozens of modules
714
- without git churn, and lets each domain own its own registration list.
715
- The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
716
- \`kick g adapter\`) follow this layout — manual additions should too.
717
-
718
- Everything else (controllers, services, modules, RequestContext API, generators,
719
- package additions, env access patterns, troubleshooting) is detailed below.
720
-
721
- ## Where to Find Things
722
-
723
- ### Application Structure
724
-
725
- | What | Where |
726
- |------|-------|
727
- | Entry point | \`src/index.ts\` |
728
- | Module registry | \`src/modules/index.ts\` |
729
- | Feature modules | \`src/modules/<module-name>/\` |
730
- | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
731
- | Env values | \`.env\` |
732
- | Env schema (Zod) | \`src/config/index.ts\` |
733
- | TypeScript config | \`tsconfig.json\` |
734
- | Vite config (HMR) | \`vite.config.ts\` |
735
- | Vitest config | \`vitest.config.ts\` |
736
- | Prettier config | \`.prettierrc\` |
737
- | CLI config | \`kick.config.ts\` |
738
-
739
- ### Module Pattern (${t.toUpperCase()})
740
-
741
- > **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.
742
-
743
- Each module in \`src/modules/<name>/\` typically contains:
744
-
745
- ${t===`rest`?`\`\`\`
746
- <name>/
747
- ├── <name>.controller.ts # HTTP routes (@Controller)
748
- ├── <name>.service.ts # Business logic (@Service)
749
- ├── <name>.repository.ts # Data access (@Repository)
750
- ├── dtos/ # Request/response schemas (Zod)
751
- └── <name>.module.ts # Module definition (defineModule factory)
752
- \`\`\`
753
- `:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
754
-
755
- ## Checklist: Adding a Feature
756
-
757
- ### New Module (Recommended)
758
-
759
- Use the CLI generator for consistency:
760
-
761
- \`\`\`bash
762
- kick g module <name> # Generate full module
763
- # or
764
- kick g scaffold <name> <fields> # Generate CRUD from fields
765
- \`\`\`
766
-
767
- Then:
768
- - [ ] Review generated files in \`src/modules/<name>/\`
769
- - [ ] Verify module is registered in \`src/modules/index.ts\`
770
- - [ ] Update DTOs in \`<name>.dto.ts\` if needed
771
- - [ ] Implement business logic in \`<name>.service.ts\`
772
- - [ ] Run \`kick dev\` to test with HMR
773
- - [ ] Write tests in \`<name>.test.ts\`
774
-
775
- ### Manual Controller
776
-
777
- If not using generators:
778
-
779
- - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
780
- - [ ] Add \`@Controller()\` decorator
781
- - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
782
- - [ ] 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\`.
783
- - [ ] 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.
784
- - [ ] Test with \`kick dev\`
785
-
786
- ### Manual Service
787
-
788
- - [ ] Create \`src/modules/<name>/<name>.service.ts\`
789
- - [ ] Add \`@Service()\` decorator
790
- - [ ] Inject dependencies with \`@Autowired()\`
791
- - [ ] Inject via \`@Autowired()\` where needed
792
- - [ ] Write unit tests
793
-
794
- ### New Middleware
795
-
796
- - [ ] Create \`src/middleware/<name>.middleware.ts\`
797
- - [ ] Export middleware function (Express format)
798
- - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
799
- - [ ] Test with sample requests
800
-
801
- ### Adding a Package
802
-
803
- Use \`kick add\` to install KickJS packages with correct peer dependencies:
804
-
805
- - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
806
- - [ ] Follow package-specific setup in terminal output
807
- - [ ] Update \`src/index.ts\` to register adapter (if needed)
808
- - [ ] Configure environment variables in \`.env\`
809
- - [ ] Test integration with \`kick dev\`
810
-
811
- ## Common Tasks
812
-
813
- ### Generate CRUD Module
814
-
815
- \`\`\`bash
816
- kick g scaffold user name:string email:string:optional age:number
817
- \`\`\`
818
-
819
- Append \`:optional\` for optional fields (shell-safe, no quoting needed).
820
- Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
821
-
822
- This creates a full CRUD module with:
823
- - Controller with GET, POST, PUT, DELETE routes
824
- - Service with business logic
825
- - Repository with data access
826
- - DTOs with Zod validation
827
-
828
- ### Add Authentication
829
-
830
- \`\`\`bash
831
- kick add auth
832
- \`\`\`
833
-
834
- Then configure in \`src/index.ts\`:
835
-
836
- \`\`\`ts
837
- import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
838
-
839
- bootstrap({
840
- modules,
841
- adapters: [
842
- AuthAdapter({
843
- strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
844
- }),
845
- ],
846
- })
847
- \`\`\`
848
-
849
- ### Add Database (Prisma)
850
-
851
- \`\`\`bash
852
- kick add prisma
853
- ${n} install prisma @prisma/client
854
- npx prisma init
855
- # Edit prisma/schema.prisma
856
- npx prisma migrate dev --name init
857
- kick g module user --repo prisma
858
- \`\`\`
859
-
860
- ### Add WebSocket Support
861
-
862
- \`\`\`bash
863
- kick add ws
864
- \`\`\`
865
-
866
- Then add adapter in \`src/index.ts\`:
867
-
868
- \`\`\`ts
869
- import { WsAdapter } from '@forinda/kickjs-ws'
870
-
871
- bootstrap({
872
- modules,
873
- adapters: [WsAdapter()],
874
- })
875
- \`\`\`
876
-
877
- Create WebSocket controller:
878
-
879
- \`\`\`bash
880
- kick g controller chat --ws
881
- \`\`\`
882
-
883
- ## Testing Guidelines
884
-
885
- All tests use Vitest:
886
-
887
- \`\`\`ts
888
- import { describe, it, expect, beforeEach } from 'vitest'
889
- import { Container } from '@forinda/kickjs'
890
- import { createTestApp } from '@forinda/kickjs-testing'
891
-
892
- describe('UserController', () => {
893
- it('should return users', async () => {
894
- // Container.create() — isolated DI state per test, never new Container()
895
- // and never getInstance().reset() (both leak registrations between tests).
896
- const container = Container.create()
897
- const app = await createTestApp([UserModule], { container })
898
- const res = await app.get('/users')
899
-
900
- expect(res.status).toBe(200)
901
- expect(res.body).toHaveProperty('users')
902
- })
903
- })
904
- \`\`\`
905
-
906
- Run tests:
907
- - \`${n} run test\` — run all tests once
908
- - \`${n} run test:watch\` — watch mode
909
- - Individual file: \`${n} run test src/modules/user/user.test.ts\`
910
-
911
- ## Environment Variables
912
-
913
- Schema is declared in \`src/config/index.ts\` (extends the base
914
- \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
915
- with kickjs at module load. \`src/index.ts\` imports it via
916
- \`import './config'\` **before** \`bootstrap()\` so the cache is populated
917
- in time for DI. Add new keys to the schema, drop their values into
918
- \`.env\`, and they're typed everywhere.
919
-
920
- Access patterns:
921
-
922
- 1. **@Value() decorator** (recommended for known-at-construction keys):
923
- \`\`\`ts
924
- @Value('DATABASE_URL')
925
- private dbUrl!: string
926
- \`\`\`
927
-
928
- 2. **ConfigService** (recommended for dynamic / method-scoped access):
929
- \`\`\`ts
930
- @Autowired()
931
- private config!: ConfigService
932
-
933
- const port = this.config.get('PORT') // typed: number
934
- \`\`\`
935
-
936
- 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
937
- \`\`\`ts
938
- import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
939
-
940
- const env = loadEnv(schema) // Parse + validate all vars
941
- const port = getEnv('PORT') // Single value lookup
942
- reloadEnv() // Re-read .env from disk
943
- resetEnvCache() // Full reset (for tests)
944
- \`\`\`
945
-
946
- 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
947
- coercion and the typed \`KickEnv\` registry.
948
-
949
- > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
950
- > If the schema is not registered before DI runs, \`config.get()\`
951
- > returns \`undefined\` for user keys (the base shape only) and
952
- > \`@Value()\` only works because of its raw \`process.env\` fallback —
953
- > Zod coercion + schema defaults are silently skipped.
954
-
955
- ## Standalone Utilities (No DI Required)
956
-
957
- These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
958
-
959
- | Utility | Import | Example |
960
- |---------|--------|---------|
961
- | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
962
- | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
963
- | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
964
- | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
965
- | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
966
- | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
967
- | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
968
- | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
969
- | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
970
-
971
- ## Key Decorators
972
-
973
- ### HTTP Routes
974
- | Decorator | Purpose |
975
- |-----------|---------|
976
- | \`@Controller()\` | Define route prefix |
977
- | \`@Get('/'), @Post('/')\` | HTTP method handlers |
978
- | \`@Middleware(fn)\` | Attach middleware |
979
- | \`@Public()\` | Skip auth (requires auth adapter) |
980
- | \`@Roles('admin')\` | Role-based access |
981
-
982
- ### Dependency Injection
983
- | Decorator | Purpose |
984
- |-----------|---------|
985
- | \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
986
- | \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
987
- | \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
988
- | \`@Service()\` | Register singleton service |
989
- | \`@Repository()\` | Register repository |
990
- | \`@Autowired()\` | Property injection |
991
- | \`@Inject('token')\` | Token-based injection |
992
- | \`@Value('VAR')\` | Inject env variable |
993
-
994
- ### Context Decorators
995
-
996
- Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
997
- Use this **instead of \`@Middleware()\`** when the middleware's only output
998
- is a value other code reads off \`ctx\`.
999
-
1000
- **Authoring** — pick the right factory:
1001
-
1002
- | Factory | When |
1003
- |---------|------|
1004
- | \`defineHttpContextDecorator(spec)\` | HTTP only (the common case). \`Ctx\` is \`RequestContext\`, so \`ctx.req\` / \`ctx.params\` / \`ctx.query\` are typed. |
1005
- | \`defineContextDecorator(spec)\` | Transport-agnostic (HTTP + WS + queue + cron). \`Ctx\` is \`ExecutionContext\` — only \`get\` / \`require\` / \`set\` / \`requestId\`. |
1006
- | \`<either>.withParams<P>()(spec)\` | The contributor takes per-call params. **Always use the curried form for params** — the positional form forces you to spell \`K\` and \`D\` and loses \`deps\` inference. |
1007
-
1008
- Spec fields: \`{ key, deps, dependsOn, optional, paramDefaults, requiredParams, onError, resolve }\`.
1009
-
1010
- **Call sites — all five, precedence high → low:**
1011
-
1012
- | # | Site | Form |
1013
- |---|------|------|
1014
- | 1 | Method | \`@LoadX\` / \`@LoadX({ ... })\` above a controller method |
1015
- | 2 | Class | \`@LoadX\` / \`@LoadX({ ... })\` above the controller class |
1016
- | 3 | Module | \`defineModule({ build: () => ({ contributors: () => [LoadX.registration] }) })\` — or \`AppModule.contributors?()\` in class form |
1017
- | 4 | Adapter | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
1018
- | 5 | Global | \`bootstrap({ contributors: [LoadX.registration] })\` |
1019
-
1020
- Sites 3–5 take **registrations**, not decorators:
1021
-
1022
- - \`LoadX.registration\` — uses \`paramDefaults\` as-is.
1023
- - \`LoadX.with({ ...params }).registration\` — call-site params merged over \`paramDefaults\`.
1024
-
1025
- Duplicate keys are resolved by precedence; the lower-precedence one is
1026
- dropped silently, which is how a method-level decorator overrides an
1027
- adapter-shipped default.
1028
-
1029
- **Params:** a **required** field of \`P\` with no \`paramDefaults\` entry must be
1030
- supplied at every call site — \`@LoadX\` bare, \`@LoadX()\`, and \`.registration\`
1031
- are compile errors for such a decorator. Never invent a placeholder default
1032
- just to make the type check; add \`requiredParams: ['field']\` for runtime
1033
- enforcement at JS call sites.
1034
-
1035
- **Reading values:** \`ctx.require('key')\` for values a contributor guarantees
1036
- (throws \`MissingContextValueError\`, returns a non-optional type);
1037
- \`ctx.get('key')\` for \`optional: true\` contributors and ad-hoc keys (returns
1038
- \`| undefined\`). Never \`ctx.get('key')!\` — it compiles even when the producing
1039
- decorator isn't applied to the route.
1040
-
1041
- | Concept | Where it lives |
1042
- |---------|----------------|
1043
- | Type augmentation (value types) | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
1044
- | Type augmentation (key-only) | \`declare module '@forinda/kickjs' { interface ContextKeys { ... } }\` — valid in \`dependsOn\`, value stays \`unknown\` |
1045
-
1046
- Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
1047
- fast). The \`onError\` hook is async-permitted.
1048
-
1049
- Full guide: <https://kickjs.app/guide/context-decorators>.
1050
-
1051
- ## Common Pitfalls
1052
-
1053
- 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
1054
- 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
1055
- 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()\`
1056
- 4. **Routes not found** — Check controller path and module registration
1057
- 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.
1058
- 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
1059
- 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.
1060
- 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.
1061
- 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).
1062
- 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({ ... })\`.
1063
- 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\`.
1064
-
1065
- ## CLI Commands Reference
1066
-
1067
- | Command | Description |
1068
- |---------|-------------|
1069
- | \`kick dev\` | Dev server with HMR |
1070
- | \`kick dev:debug\` | Dev server with debugger |
1071
- | \`kick build\` | Production build |
1072
- | \`kick start\` | Run production build |
1073
- | \`kick g module <names...>\` | Generate one or more modules |
1074
- | \`kick g scaffold <name> <fields>\` | Generate CRUD |
1075
- | \`kick g controller <name>\` | Generate controller |
1076
- | \`kick g service <name>\` | Generate service |
1077
- | \`kick g middleware <name>\` | Generate middleware |
1078
- | \`kick add <package>\` | Add KickJS package |
1079
- | \`kick add upload\` | Install the multipart upload driver for this project's runtime |
1080
- | \`kick add --list\` | List available packages |
1081
- | \`kick doctor\` | Pre-flight checks — runtime engine peers, upload driver, env wiring |
1082
- | \`kick rm module <names...>\` | Remove one or more modules |
1083
-
1084
- > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`), \`-r\` (or \`--repo\`), and \`--runtime express|fastify|h3\` to bypass interactive prompts:
1085
- > \`\`\`bash
1086
- > kick new my-api -t ddd -r prisma --runtime fastify --pm ${n} --no-git --no-install -f
1087
- > \`\`\`
1088
-
1089
- ## Learn More
1090
-
1091
- - [KickJS Docs](https://kickjs.app/)
1092
- - [CLI Reference](https://kickjs.app/api/cli.html)
1093
- - [Decorators Guide](https://kickjs.app/guide/decorators.html)
1094
- - [DI System](https://kickjs.app/guide/dependency-injection.html)
1095
- - [Testing](https://kickjs.app/api/testing.html)
1096
- `}function gt(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".
1097
-
1098
- **Steps**:
1099
- 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
1100
- 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
1101
- 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
1102
- 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
1103
- 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
1104
-
1105
- **Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
1106
-
1107
- \`\`\`ts
1108
- export const TodosModule = defineModule({
1109
- name: 'TodosModule',
1110
- build: () => ({
1111
- register(container) {
1112
- container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
1113
- },
1114
- routes() {
1115
- return { path: '/todos', controller: TodosController }
1116
- },
1117
- }),
1118
- })
1119
- \`\`\`
1120
-
1121
- The module file MUST include \`import.meta.glob([...], { eager: true })\` for every \`@Controller\` / \`@Service\` / \`@Repository\` / \`@Component\` class — without it, decorators never fire and DI silently resolves to \`undefined\` (or routes vanish). Use **recursive** patterns (\`./**/*.controller.ts\`) so the glob keeps working when you nest files into sub-folders (\`controllers/\`, \`presentation/\`, …). If you reorganise and a class stops loading, \`kick typegen\` flags it as orphaned and \`kick typegen --fix\` patches the glob for you.
1122
-
1123
- **Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
1124
-
1125
- \`\`\`ts
1126
- routes() {
1127
- return [
1128
- { path: '/todos', controller: TodosController }, // /api/v1/todos
1129
- { path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
1130
- ]
1131
- }
1132
- \`\`\`
1133
-
1134
- **Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
1135
-
1136
- **Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
1137
-
1138
- **Red flags** (stop and ask):
1139
- - 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.
1140
- - \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
1141
- - \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
1142
- - \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
1143
- - 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 })\nasync create(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route.\n // Returning (vs ctx.created) lets typegen infer the response type.\n return reply(201, 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**:
1144
-
1145
- \`\`\`ts
1146
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
1147
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
1148
- // OR for class-form projects (\`modules.style: 'class'\`):
1149
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
1150
-
1151
- // src/middleware/index.ts — global middleware uses RAW EXPRESS signature
1152
- // (req, res, next), NOT (ctx, next)
1153
- export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
1154
-
1155
- // src/plugins/index.ts
1156
- export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
1157
-
1158
- // src/adapters/index.ts
1159
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
1160
-
1161
- // src/index.ts — stays small
1162
- import 'reflect-metadata'
1163
- import './config' // MUST be early — side-effect schema load
1164
- import { bootstrap } from '@forinda/kickjs'
1165
- import { modules } from './modules'
1166
- import { middleware } from './middleware'
1167
- import { plugins } from './plugins'
1168
- import { adapters } from './adapters'
1169
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
1170
- \`\`\`
1171
-
1172
- **One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
1173
-
1174
- \`\`\`ts
1175
- plugins: [
1176
- ...plugins,
1177
- { name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
1178
- ]
1179
- \`\`\`
1180
-
1181
- **Red flags**:
1182
- - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
1183
- - 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".
1184
- - \`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.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\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**:
1185
- - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
1186
- - \`kick dev\` — local dev server with Vite HMR.
1187
- - \`kick build\` — production bundle via Vite.
1188
- - \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
1189
- - \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
1190
- - \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
1191
- - \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
1192
- - \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
1193
- - \`kick info\` — environment / version dump for bug reports.
1194
- - \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
1195
-
1196
- **Useful flag combos**:
1197
-
1198
- \`\`\`bash
1199
- kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
1200
- kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
1201
- kick new . --yes --force # Scaffold into current dir, clear existing files
1202
- kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
1203
- kick g agents -f --only skills # Refresh just the skills after upgrade
1204
- kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
1205
- kick inspect --port 4000 --json # Machine-readable route/adapter dump
1206
- kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
1207
- \`\`\`
1208
-
1209
- **Lesser-known, high-value**:
1210
- - \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
1211
- - \`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.
1212
- - \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
1213
- - \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
1214
- - \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
1215
- - \`kick check\` — preflight gate (typecheck + lint + format) before commit.
1216
- - \`kick codemod\` — automated AST-level migration between framework versions.
1217
-
1218
- **Red flags**:
1219
- - Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
1220
- - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
1221
- - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
1222
- - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
1223
- - 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:`---
1224
- name: ${e.frontmatterName}
1225
- description: ${e.description}
1226
- ---
1227
-
1228
- ${r}
1229
-
1230
- ${e.body}
1231
- `}))}function _t(e,t,n){return`# GEMINI.md — ${e}
1232
-
1233
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
1234
- reference for this project — every convention, structure, decorator
1235
- pattern, env wiring rule, generator usage. This file is a thin
1236
- Gemini-specific layer; when the two disagree on anything substantive,
1237
- treat \`AGENTS.md\` as authoritative and flag the discrepancy.
1238
-
1239
- ## Why this file
1240
-
1241
- Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
1242
- agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
1243
- means Gemini reads the same shared prose as Codex / Cursor / Copilot
1244
- without us copy-pasting.
1245
-
1246
- ## Gemini-specific notes
1247
-
1248
- - **Skills activation** — Gemini activates skills via
1249
- \`activate_skill\` (its native MCP-style tool); the equivalent on
1250
- Claude Code is the \`Skill\` tool. Cross-reference the
1251
- \`kickjs-skills.md\` index for the available triggers.
1252
- - **Tool naming** — Gemini's tool names differ from Claude Code's
1253
- (e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
1254
- \`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
1255
- tool names; consult Gemini's docs for the concrete invocation.
1256
- - **File ops** — Gemini's file edits are sandboxed; large refactors
1257
- may need explicit confirmation. Prefer the smallest-possible-edit
1258
- pattern.
1259
-
1260
- ## Refreshing this file
1261
-
1262
- \`kick g agents --only gemini -f\` regenerates this file from the
1263
- CLI template. Hand-edited content is overwritten — keep customisation
1264
- in \`.agents/GEMINI.local.md\`.
1265
- `}function vt(e,t,n){return`# COPILOT.md — ${e}
1266
-
1267
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
1268
- reference for this project — every convention, structure, decorator
1269
- pattern, env wiring rule, generator usage. This file is a thin
1270
- Copilot-specific layer; when the two disagree on anything substantive,
1271
- treat \`AGENTS.md\` as authoritative and flag the discrepancy.
1272
-
1273
- ## Why this file
1274
-
1275
- GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
1276
- the agent-context files. Keeping it in \`.agents/\` next to
1277
- \`AGENTS.md\` means Copilot reads the same shared prose as
1278
- Codex / Cursor / Gemini / Claude Code without copy-pasting.
1279
-
1280
- ## Copilot-specific notes
1281
-
1282
- - **Skills** — Copilot CLI auto-discovers skills from installed
1283
- plugins; cross-reference \`kickjs-skills.md\` for available
1284
- triggers in this project.
1285
- - **Tool naming** — Copilot's tool names differ from Claude Code's
1286
- (\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
1287
- prose in \`AGENTS.md\` describes intents, not tool names; consult
1288
- Copilot's docs for the concrete invocation.
1289
- - **Confirmation flows** — Copilot CLI surfaces destructive
1290
- operations through an explicit approval gate. Stage edits with
1291
- short, focused diffs so each one is easy to review at the prompt.
1292
-
1293
- ## Refreshing this file
1294
-
1295
- \`kick g agents --only copilot -f\` regenerates this file from the
1296
- CLI template. Hand-edited content is overwritten — keep customisation
1297
- in \`.agents/COPILOT.local.md\`.
1298
- `}const yt={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},zod:{pkg:`zod`,peers:[],description:`Zod schema validation (env, DTOs, OpenAPI) — wrap with fromZod()`},valibot:{pkg:`valibot`,peers:[],description:`Valibot schema validation — wrap with fromValibot()`},yup:{pkg:`yup`,peers:[],description:`Yup schema validation — wrap with fromYup()`},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`JWT, API key, OAuth strategies, @Public, @Roles (+ optional argon2/bcryptjs)`,deprecated:`auth is moving to BYO — compose @LoadAuthUser/@RequireRole/@Public from defineContextDecorator (see the BYO Auth recipe in the docs)`},ai:{pkg:`@forinda/kickjs-ai`,peers:[`zod`],description:`AI toolkit — LLM providers, tool definitions from controllers`},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`},pg:{pkg:`@forinda/kickjs-db`,peers:[`pg`],description:`kick/db + PostgreSQL driver (use @forinda/kickjs-db/pg)`},sqlite:{pkg:`@forinda/kickjs-db`,peers:[`better-sqlite3`],description:`kick/db + SQLite driver (use @forinda/kickjs-db/sqlite)`},mysql:{pkg:`@forinda/kickjs-db`,peers:[`mysql2`],description:`kick/db + MySQL driver (use @forinda/kickjs-db/mysql)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`,deprecated:"early-adoption adapter, no longer maintained — wire Drizzle directly (BYO), or use @forinda/kickjs-db, the built-in Kick ORM (`kick add db` / pg / sqlite / mysql)"},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`,deprecated:"early-adoption adapter, no longer maintained — wire Prisma directly (BYO), or use @forinda/kickjs-db, the built-in Kick ORM (`kick add db` / pg / sqlite / mysql)"},ws:{pkg:`@forinda/kickjs-ws`,peers:[`ws`],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`},"queue:redis-pubsub":{pkg:`@forinda/kickjs-queue`,peers:[`ioredis`],description:`Lightweight pub/sub via Redis (no persistence)`},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}},bt=Object.entries(yt).filter(([e,t])=>!t.core&&!t.deprecated&&!e.includes(`:`)&&![`pg`,`sqlite`,`mysql`,`zod`,`valibot`,`yup`].includes(e)).map(([e])=>e).join(`, `),xt={express:{prod:`multer`,dev:`@types/multer`,note:`Express uploads use multer (memory/disk storage, ctx.file / ctx.files).`},fastify:{prod:`@fastify/multipart`,note:`Fastify uploads use @fastify/multipart (buffered into ctx.file / ctx.files).`},h3:{note:`h3 parses multipart natively (readMultipartFormData) — no driver to install.`}};async function St(e=process.cwd()){let t=(await j(e))?.runtime;return t===`express`||t===`fastify`||t===`h3`?t:Ct(e)}function Ct(e=process.cwd()){let t=wt(`package.json`,e);if(t)try{let e=JSON.parse(a(v(t,`package.json`),`utf-8`)),n={...e.dependencies,...e.devDependencies};if(`fastify`in n)return`fastify`;if(`h3`in n)return`h3`}catch{}return`express`}function wt(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 Tt(){return wt(`pnpm-lock.yaml`)?`pnpm`:wt(`yarn.lock`)?`yarn`:wt(`bun.lockb`)||wt(`bun.lock`)?`bun`:wt(`package-lock.json`)?`npm`:null}function Et(){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(Te.includes(t))return t}}catch{}let n=f(e);if(n===e)return null;e=n}return null}async function Dt(e){if(e&&Te.includes(e))return{pm:e,source:`flag`};let t=await j(process.cwd());if(t?.packageManager&&Te.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=Et();if(n)return{pm:n,source:`package.json`};let r=Tt();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function Ot(e){let{pm:t}=await Dt(e);return t}function kt(e=!1){let t=Object.entries(yt),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(`, `)})`:``,a=t.deprecated?` [DEPRECATED — ${t.deprecated}]`:``;return` ${r} ${t.description}${i}${a}`};console.log(`
1299
- Core packages (always installed by \`kick new\`):
1300
- `);for(let e of r)console.log(a(e));if(e){console.log(`
1301
- Optional packages (add as needed):
1302
- `);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(`
1303
- Usage: kick add ai db swagger`),console.log(` kick add queue:bullmq`),console.log(` kick add upload # installs the multipart driver for your runtime`),console.log()}function At(e,t,n=`express`){let r=new Set,i=new Set,a=[],o=[],s=[];for(let c of e){if(c===`upload`){let e=xt[n];s.push(`upload (${n}): ${e.note}`),e.prod&&(t?i:r).add(e.prod),e.dev&&i.add(e.dev);continue}let e=yt[c];if(!e){a.push(c);continue}e.deprecated&&o.push(`'${c}' (${e.pkg}) is deprecated — ${e.deprecated}`);let l=t||e.dev?i:r;l.add(e.pkg);for(let t of e.peers)l.add(t)}return{prodDeps:[...r],devDeps:[...i],unknown:a,warnings:o,notices:s}}function jt(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=>{kt(!!e.all)})}function Mt(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){kt(!!t.all);return}let{pm:n,source:r}=await Dt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=await St(process.cwd()),{prodDeps:a,devDeps:o,unknown:s,warnings:c,notices:l}=At(e,!!t.dev,i);for(let e of c)console.warn(`\n WARNING: ${e}`);for(let e of l)console.log(`\n ${e}`);if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
1304
- `),a.length===0&&o.length===0))){if(a.length>0){let e=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{C(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.length>0){let e=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{C(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
1305
- `)}})}const Nt=f(b(import.meta.url)),Pt=JSON.parse(a(h(Nt,`..`,`package.json`),`utf-8`)),Ft=`^${Pt.version}`,It=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-schema`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`,`@forinda/kickjs-client`];async function Lt(){let e=await Promise.all(It.map(async e=>{try{let t=S(`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,Ft]}));return Object.fromEntries(e)}function Rt(e,t){try{let n=S(`npm`,[`view`,`${e}@${t}`,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();return n&&/^\d+\.\d+\.\d+/.test(n)?n:null}catch{return null}}function zt(e){return(e??``).replace(/^[\^~>=<\s]+/,``)}function Bt(e,t){let n=e=>zt(e).split(`-`)[0].split(`.`).map(e=>Number.parseInt(e,10)||0),[r=0,i=0,a=0]=n(e),[o=0,s=0,c=0]=n(t);return r===o?i===s?a>=c:i>s:r>o}function Vt(e,t,n){try{let r=S(`npm`,[`view`,`${e}@${t}`,`exports`,`--json`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(!r)return!1;let i=JSON.parse(r);return Object.prototype.hasOwnProperty.call(i,n)}catch{return!1}}async function Ht(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:i=`rest`,defaultRepo:a=`inmemory`,packages:o=[],schemaLib:s=`zod`,runtime:c=`express`}=e,l=n,u=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),u(`Resolving package versions...`);let d=await Lt();if(c!==`express`)if(Vt(`@forinda/kickjs`,`latest`,`./${c}`))u(`Using @forinda/kickjs@latest (stable ships the ${c} runtime)`);else{let e=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`],t=[],n=!1;for(let r of e){let e=Rt(r,`alpha`);e&&Bt(e,zt(d[r]))&&(d[r]=`^${e}`,t.push(`${r}@^${e}`),r===`@forinda/kickjs`&&(n=!0))}u(n?`Using the alpha channel for the ${c} runtime: ${t.join(`, `)}`:`WARNING: could not resolve @forinda/kickjs@alpha — the ${c} runtime subpath may be missing. After install, run: ${r} add @forinda/kickjs@alpha`)}await N(h(l,`package.json`),Ye(t,i,d,o,s,c)),await N(h(l,`vite.config.ts`),Xe()),await N(h(l,`tsconfig.json`),Ze()),await N(h(l,`.prettierrc`),Qe()),await N(h(l,`.editorconfig`),$e()),await N(h(l,`.gitignore`),et()),await N(h(l,`.gitattributes`),tt()),await N(h(l,`.env`),nt()),await N(h(l,`.env.example`),rt()),await N(h(l,`src/config/index.ts`),ct(s)),await N(h(l,`src/index.ts`),ot(t,i,Pt.version,o,c)),await N(h(l,`src/modules/index.ts`),st()),await N(h(l,`src/modules/hello/hello.service.ts`),lt()),await N(h(l,`src/modules/hello/hello.controller.ts`),ut()),await N(h(l,`src/modules/hello/hello.module.ts`),dt()),await N(h(l,`kick.config.ts`),ft(i,a,r,c)),await N(h(l,`vitest.config.ts`),it()),await N(h(l,`README.md`),pt(t,i,r));let{generateAgentDocs:f}=await Promise.resolve().then(()=>ir);if(await f({outDir:l,name:t,pm:r,template:i,only:`all`,force:!0}),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{C(`${r} install`,{cwd:l,stdio:`inherit`}),console.log(`
1306
- Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await Promise.resolve().then(()=>Va);await e({cwd:l,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{C(`git init`,{cwd:l,stdio:`pipe`}),C(`git branch -M main`,{cwd:l,stdio:`pipe`}),C(`git add -A`,{cwd:l,stdio:`pipe`}),C(`git commit -m "chore: initial commit from kick new"`,{cwd:l,stdio:`pipe`}),u(`Git repository initialized`)}catch{u(`Warning: git init failed (git may not be installed)`)}console.log(`
1307
- Project scaffolded successfully!`),console.log();let p=l!==process.cwd();u(`Next steps:`),p&&u(` cd ${t}`),e.installDeps||u(` ${r} install`);let m={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`};u(` ${m[i]??m.rest}`),u(` kick dev`),u(``),u(`Commands:`),u(` kick dev Start dev server with Vite HMR`),u(` kick build Production build via Vite`),u(` kick start Run production build`),u(``),u(`Generators:`),u(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),u(` kick g scaffold <n> <f..> CRUD module from field definitions`),u(` kick g controller <name> Standalone controller`),u(` kick g service <name> @Service() class`),u(` kick g middleware <name> Express middleware`),u(` kick g guard <name> Route guard (auth, roles, etc.)`),u(` kick g adapter <name> AppAdapter with lifecycle hooks`),u(` kick g dto <name> Zod DTO schema`),u(` kick g config Generate kick.config.ts`),u(``),u(`Add packages:`),u(` kick add <pkg> Install a KickJS package + peers`),u(` kick add --list Show all available packages`),u(``),u(`Available: ${bt}`),u(``)}const Ut={GET:O.green,POST:O.cyan,PUT:O.yellow,PATCH:O.magenta,DELETE:O.red};function Wt(e){return(Ut[e]??O.dim)(e.padEnd(7))}function Gt(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return O.red(t);case`WARNING`:return O.yellow(t);case`INFO`:return O.blue(O.dim(t));default:return t}}O.green(`✓`),O.red(`✖`),O.yellow(`⚠`),O.blue(`ℹ`);function Kt(e){D.intro(O.bgCyan(O.black(` ${e} `)))}function P(e){D.outro(e)}function qt(e){D.isCancel(e)&&(D.cancel(`Operation cancelled.`),process.exit(0))}async function Jt(e){let t=await D.text(e);return qt(t),t}async function Yt(e){let t=await D.select(e);return qt(t),t}async function Xt(e){let t=await D.multiselect(e);return qt(t),t}async function F(e){let t=await D.confirm(e);return qt(t),t}function Zt(){return D.spinner()}const I=D.log,Qt=[{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 $t(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 | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).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)=>{Kt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await Jt({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)I.warn(`Clearing existing files in ${i}`);else if(n){I.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),P(`Aborted.`);return}else{I.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)I.message(` - ${e}`);if(r.length>5&&I.message(` ... and ${r.length-5} more`),!await F({message:O.red(`Remove all existing files and proceed?`),initialValue:!1})){P(`Aborted.`);return}}for(let e of r)s(v(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await Yt({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let c=t.runtime;c||=n?`express`:await Yt({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let l=t.pm;l||=n?await Ot(void 0):await Yt({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let u=t.repo;u||=n?`inmemory`:await Jt({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Oe(u);let f=t.schema;f||=n?`zod`:await Yt({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(f)||(I.warn(`Unknown --schema "${f}", falling back to zod.`),f=`zod`);let p;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();p=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else p=n?[]:await Xt({message:`Select packages to include`,options:[...Qt],required:!1});let m;m=t.git===void 0?n?!0:await F({message:`Initialize git repository?`,initialValue:!0}):t.git;let h;if(h=t.install===void 0?n?!0:await F({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DkQrZR8Y.mjs`);await t({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l}${l===`pnpm`?` dev`:` run dev:server`}`)}`);return}await Ht({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,template:a,defaultRepo:u,packages:p,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l} dev`)}`)})}function L(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function R(e){let t=L(e);return t.charAt(0).toLowerCase()+t.slice(1)}function z(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function B(e){return de.plural(e)}function en(e){return de.plural(e)}var tn=k({findProjectRoot:()=>rn});const nn=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function rn(e=process.cwd()){let t=v(e),{root:n}=g(t),i=null,a=t;for(;;){for(let e of nn)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 an(e){return z(e).replace(/-/g,`_`)}function on(e){let t=e.cwd??process.cwd(),n=e.projectRoot??rn(t),r=e.pluralize??!0,i=L(e.name),a=R(e.name),o=z(e.name),s=an(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=B(o);c.pluralKebab=e,c.pluralPascal=L(e),c.pluralCamel=R(e)}return c}function sn(e,t){return v(e.cwd,t)}async function cn(e){return import(x(e).href)}const ln=new Map;async function un(e){let t=ln.get(e);if(t)return t;let n=dn(e);return ln.set(e,n),n}async function dn(t){let n=v(t,`package.json`);if(!r(n))return{generators:[],loaded:[],failed:[]};let i=fn(JSON.parse(await w(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 w(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 cn(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(!pn(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 fn(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 pn(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function mn(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return _n(r.spec,r.source,e,n);let i=gn(await un(n),e.generatorName);return i?_n(i.spec,i.source,e,n):null}async function hn(e,t=[]){let n=await un(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 gn(e,t){return e.generators.find(e=>e.spec.name===t)}async function _n(e,t,n,r){let i=on({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=sn(i,e.path);await N(t,e.content),o.push(t)}return{files:o,source:t}}function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function vn(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yn(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function bn(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]??`${vn(n)}${e}Repository`,repoFile:i[n]??`${yn(n)}-${t}`}}function xn(e){return e??`define`}function Sn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=bn(t,n,i),c=xn(a),l=`/**
1308
- * ${t} Module
1309
- *
1310
- * REST module with a flat folder structure.
1311
- * Controller delegates to service, service wraps the repository.
1312
- *
1313
- * Structure:
1314
- * ${n}.controller.ts — HTTP routes (CRUD)
1315
- * ${n}.service.ts — Business logic
1316
- * ${n}.repository.ts — Repository interface
1317
- * ${s}.repository.ts — Repository implementation
1318
- * dtos/ — Request/response schemas
1319
- */`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
1320
- import { ${o} } from './${s}.repository'
1321
- import { ${t}Controller } from './${n}.controller'
1322
-
1323
- // Eagerly load decorated classes so @Controller()/@Service()/@Repository() decorators
1324
- // register in the DI container. Recursive globs (./**/) so the module keeps working
1325
- // however you nest files (e.g. moving controllers into a controllers/ sub-folder).
1326
- import.meta.glob(
1327
- ['./**/*.controller.ts', './**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'],
1328
- { eager: true },
1329
- )`,d=` /**
1330
- * Declare HTTP routes for this module. Return value shape:
1331
- *
1332
- * - \`path\` — URL prefix for this route set.
1333
- * - \`controller\` — Controller class (also drives OpenAPI).
1334
- * - \`version\` — Optional. Overrides the app-wide API version.
1335
- *
1336
- * Return an **array** to mount multiple route sets — admin
1337
- * surfaces, side-by-side v1 + v2 controllers, etc:
1338
- *
1339
- * return [
1340
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
1341
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
1342
- * ]
1343
- */`;return c===`class`?`${l}
1344
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1345
- ${u}
1346
-
1347
- export class ${t}Module implements AppModule {
1348
- register(container: Container): void {
1349
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1350
- container.resolve(${o}),
1351
- )
1352
- }
1353
-
1354
- ${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
1355
- routes(): ModuleRoutes {
1356
- return {
1357
- path: '/${r}',
1358
- controller: ${t}Controller,
1359
- }
1360
- }
1361
- }
1362
- `:`${l}
1363
- import { defineModule } from '@forinda/kickjs'
1364
- ${u}
1365
-
1366
- export const ${t}Module = defineModule({
1367
- name: '${t}Module',
1368
- build: () => ({
1369
- register(container) {
1370
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1371
- container.resolve(${o}),
1372
- )
1373
- },
1374
-
1375
- ${d}
1376
- routes() {
1377
- return {
1378
- path: '/${r}',
1379
- controller: ${t}Controller,
1380
- }
1381
- },
1382
- }),
1383
- })
1384
- `}function Cn(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=xn(i),o=` /**
1385
- * Declare HTTP routes. Return value shape:
1386
- *
1387
- * - \`path\` — URL prefix for this route set.
1388
- * - \`controller\` — Controller class (also drives OpenAPI).
1389
- * - \`version\` — Optional. Overrides the app-wide API version.
1390
- *
1391
- * Return an array to mount multiple route sets:
1392
- *
1393
- * return [
1394
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
1395
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
1396
- * ]
1397
- */`;return a===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1398
- import { ${t}Controller } from './${n}.controller'
1399
-
1400
- export class ${t}Module implements AppModule {
1401
- ${o.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
1402
- routes(): ModuleRoutes {
1403
- return {
1404
- path: '/${r}',
1405
- controller: ${t}Controller,
1406
- }
1407
- }
1408
- }
1409
- `:`import { defineModule } from '@forinda/kickjs'
1410
- import { ${t}Controller } from './${n}.controller'
1411
-
1412
- export const ${t}Module = defineModule({
1413
- name: '${t}Module',
1414
- build: () => ({
1415
- ${o}
1416
- routes() {
1417
- return {
1418
- path: '/${r}',
1419
- controller: ${t}Controller,
1420
- }
1421
- },
1422
- }),
1423
- })
1424
- `}function wn(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'
1425
- import { ApiTags } from '@forinda/kickjs-swagger'
1426
- import { ${t}Service } from './${n}.service'
1427
- import { create${t}Schema } from './dtos/create-${n}.dto'
1428
- import { update${t}Schema } from './dtos/update-${n}.dto'
1429
- import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
1430
-
1431
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
1432
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1433
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1434
- // \`kick dev\`) — see https://kickjs.app/guide/typegen.
1435
-
1436
- @Controller()
1437
- export class ${t}Controller {
1438
- @Autowired() private readonly ${r}Service!: ${t}Service
1439
-
1440
- @Get('/')
1441
- @ApiTags('${t}')
1442
- @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
1443
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1444
- return ctx.paginate(
1445
- (parsed) => this.${r}Service.findPaginated(parsed),
1446
- ${t.toUpperCase()}_QUERY_CONFIG,
1447
- )
1448
- }
1449
-
1450
- @Get('/:id')
1451
- @ApiTags('${t}')
1452
- async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
1453
- const result = await this.${r}Service.findById(ctx.params.id)
1454
- if (!result) return ctx.notFound('${t} not found')
1455
- ctx.json(result)
1456
- }
1457
-
1458
- @Post('/', { body: create${t}Schema, name: 'Create${t}' })
1459
- @ApiTags('${t}')
1460
- async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
1461
- const result = await this.${r}Service.create(ctx.body)
1462
- ctx.created(result)
1463
- }
1464
-
1465
- @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
1466
- @ApiTags('${t}')
1467
- async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
1468
- const result = await this.${r}Service.update(ctx.params.id, ctx.body)
1469
- ctx.json(result)
1470
- }
1471
-
1472
- @Delete('/:id')
1473
- @ApiTags('${t}')
1474
- async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
1475
- await this.${r}Service.delete(ctx.params.id)
1476
- ctx.noContent()
1477
- }
1478
- }
1479
- `}function Tn(e){let{pascal:t}=e;return`import { z } from 'zod'
1480
-
1481
- /**
1482
- * Create ${t} DTO — Zod schema for validating POST request bodies.
1483
- * This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
1484
- * It also generates OpenAPI request body docs when SwaggerAdapter is used.
1485
- *
1486
- * Add more fields as needed. Supported Zod types:
1487
- * z.string(), z.number(), z.boolean(), z.enum([...]),
1488
- * z.array(), z.object(), .optional(), .default(), .transform()
1489
- */
1490
- export const create${t}Schema = z.object({
1491
- name: z.string().min(1, 'Name is required').max(200),
1492
- })
1493
-
1494
- export type Create${t}DTO = z.infer<typeof create${t}Schema>
1495
- `}function En(e){let{pascal:t}=e;return`import { z } from 'zod'
1496
-
1497
- export const update${t}Schema = z.object({
1498
- name: z.string().min(1).max(200).optional(),
1499
- })
1500
-
1501
- export type Update${t}DTO = z.infer<typeof update${t}Schema>
1502
- `}function Dn(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
1503
- id: string
1504
- name: string
1505
- createdAt: string
1506
- updatedAt: string
1507
- }
1508
- `}function On(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
1509
- * ${t} Repository Interface
1510
- *
1511
- * Defines the contract for data access.
1512
- * The interface declares what operations are available;
1513
- * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
1514
- *
1515
- * To swap implementations, change the factory in the module's register() method.
1516
- */
1517
- import { createToken } from '@forinda/kickjs'
1518
- import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
1519
- import type { Create${t}DTO } from '${r}/create-${n}.dto'
1520
- import type { Update${t}DTO } from '${r}/update-${n}.dto'
1521
- import type { ParsedQuery } from '@forinda/kickjs'
1522
-
1523
- export interface I${t}Repository {
1524
- findById(id: string): Promise<${t}ResponseDTO | null>
1525
- findAll(): Promise<${t}ResponseDTO[]>
1526
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
1527
- create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
1528
- update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
1529
- delete(id: string): Promise<void>
1530
- }
1531
-
1532
- /**
1533
- * Collision-safe DI token bound to \`I${t}Repository\`.
1534
- * \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
1535
- * \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
1536
- * interface — no manual generic, no \`any\` cast.
1537
- *
1538
- * The \`'${i}/'\` prefix matches the project scope so
1539
- * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
1540
- * adopters must NOT use the reserved \`'kick/'\` namespace.
1541
- */
1542
- export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
1543
- `}function kn(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
1544
- * In-Memory ${t} Repository
1545
- *
1546
- * Implements the repository interface using a Map.
1547
- * Useful for prototyping and testing. Replace with a database implementation
1548
- * (Drizzle, Prisma, etc.) for production use.
1549
- *
1550
- * @Repository() registers this class in the DI container as a singleton.
1551
- */
1552
- import { randomUUID } from 'node:crypto'
1553
- import { Repository, HttpException } from '@forinda/kickjs'
1554
- import type { ParsedQuery } from '@forinda/kickjs'
1555
- import type { I${t}Repository } from '${r}/${n}.repository'
1556
- import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
1557
- import type { Create${t}DTO } from '${i}/create-${n}.dto'
1558
- import type { Update${t}DTO } from '${i}/update-${n}.dto'
1559
-
1560
- @Repository()
1561
- export class InMemory${t}Repository implements I${t}Repository {
1562
- private store = new Map<string, ${t}ResponseDTO>()
1563
-
1564
- async findById(id: string): Promise<${t}ResponseDTO | null> {
1565
- return this.store.get(id) ?? null
1566
- }
1567
-
1568
- async findAll(): Promise<${t}ResponseDTO[]> {
1569
- return Array.from(this.store.values())
1570
- }
1571
-
1572
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1573
- const all = Array.from(this.store.values())
1574
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1575
- return { data, total: all.length }
1576
- }
1577
-
1578
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1579
- const now = new Date().toISOString()
1580
- const entity: ${t}ResponseDTO = {
1581
- id: randomUUID(),
1582
- ...dto,
1583
- createdAt: now,
1584
- updatedAt: now,
1585
- }
1586
- this.store.set(entity.id, entity)
1587
- return entity
1588
- }
1589
-
1590
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1591
- const existing = this.store.get(id)
1592
- if (!existing) throw HttpException.notFound('${t} not found')
1593
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1594
- this.store.set(id, updated)
1595
- return updated
1596
- }
1597
-
1598
- async delete(id: string): Promise<void> {
1599
- if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1600
- this.store.delete(id)
1601
- }
1602
- }
1603
- `}function An(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`/**
1604
- * ${o} ${t} Repository
1605
- *
1606
- * Stub implementation for a custom '${r}' repository.
1607
- * Implements the repository interface using an in-memory Map as a placeholder.
1608
- *
1609
- * TODO: Replace the in-memory Map with your ${r} data-access logic.
1610
- * See I${t}Repository for the interface contract.
1611
- *
1612
- * @Repository() registers this class in the DI container as a singleton.
1613
- */
1614
- import { randomUUID } from 'node:crypto'
1615
- import { Repository, HttpException } from '@forinda/kickjs'
1616
- import type { ParsedQuery } from '@forinda/kickjs'
1617
- import type { I${t}Repository } from '${i}/${n}.repository'
1618
- import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
1619
- import type { Create${t}DTO } from '${a}/create-${n}.dto'
1620
- import type { Update${t}DTO } from '${a}/update-${n}.dto'
1621
-
1622
- @Repository()
1623
- export class ${o}${t}Repository implements I${t}Repository {
1624
- // TODO: Replace with your ${r} client/connection
1625
- private store = new Map<string, ${t}ResponseDTO>()
1626
-
1627
- async findById(id: string): Promise<${t}ResponseDTO | null> {
1628
- // TODO: Implement with ${r}
1629
- return this.store.get(id) ?? null
1630
- }
1631
-
1632
- async findAll(): Promise<${t}ResponseDTO[]> {
1633
- // TODO: Implement with ${r}
1634
- return Array.from(this.store.values())
1635
- }
1636
-
1637
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1638
- // TODO: Implement with ${r}
1639
- const all = Array.from(this.store.values())
1640
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1641
- return { data, total: all.length }
1642
- }
1643
-
1644
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1645
- // TODO: Implement with ${r}
1646
- const now = new Date().toISOString()
1647
- const entity: ${t}ResponseDTO = {
1648
- id: randomUUID(),
1649
- ...dto,
1650
- createdAt: now,
1651
- updatedAt: now,
1652
- }
1653
- this.store.set(entity.id, entity)
1654
- return entity
1655
- }
1656
-
1657
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1658
- // TODO: Implement with ${r}
1659
- const existing = this.store.get(id)
1660
- if (!existing) throw HttpException.notFound('${t} not found')
1661
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1662
- this.store.set(id, updated)
1663
- return updated
1664
- }
1665
-
1666
- async delete(id: string): Promise<void> {
1667
- // TODO: Implement with ${r}
1668
- if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1669
- this.store.delete(id)
1670
- }
1671
- }
1672
- `}function jn(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
1673
- import { Container } from '@forinda/kickjs'
1674
-
1675
- describe('${t}Controller', () => {
1676
- beforeEach(() => {
1677
- Container.reset()
1678
- })
1679
-
1680
- it('should be defined', () => {
1681
- expect(true).toBe(true)
1682
- })
1683
-
1684
- describe('POST /${r}', () => {
1685
- it('should create a new ${n}', async () => {
1686
- // TODO: Set up test module, call create endpoint, assert 201
1687
- expect(true).toBe(true)
1688
- })
1689
- })
1690
-
1691
- describe('GET /${r}', () => {
1692
- it('should return paginated ${r}', async () => {
1693
- // TODO: Set up test module, call list endpoint, assert { data, meta }
1694
- expect(true).toBe(true)
1695
- })
1696
- })
1697
-
1698
- describe('GET /${r}/:id', () => {
1699
- it('should return a ${n} by id', async () => {
1700
- // TODO: Create a ${n}, then fetch by id, assert match
1701
- expect(true).toBe(true)
1702
- })
1703
-
1704
- it('should return 404 for non-existent ${n}', async () => {
1705
- // TODO: Fetch non-existent id, assert 404
1706
- expect(true).toBe(true)
1707
- })
1708
- })
1709
-
1710
- describe('PUT /${r}/:id', () => {
1711
- it('should update an existing ${n}', async () => {
1712
- // TODO: Create, update, assert changes
1713
- expect(true).toBe(true)
1714
- })
1715
- })
1716
-
1717
- describe('DELETE /${r}/:id', () => {
1718
- it('should delete a ${n}', async () => {
1719
- // TODO: Create, delete, assert gone
1720
- expect(true).toBe(true)
1721
- })
1722
- })
1723
- })
1724
- `}function Mn(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'
1725
- import { InMemory${t}Repository } from '${i}'
1726
-
1727
- describe('InMemory${t}Repository', () => {
1728
- let repo: InMemory${t}Repository
1729
-
1730
- beforeEach(() => {
1731
- repo = new InMemory${t}Repository()
1732
- })
1733
-
1734
- it('should create and retrieve a ${n}', async () => {
1735
- const created = await repo.create({ name: 'Test ${t}' })
1736
- expect(created).toBeDefined()
1737
- expect(created.name).toBe('Test ${t}')
1738
- expect(created.id).toBeDefined()
1739
-
1740
- const found = await repo.findById(created.id)
1741
- expect(found).toEqual(created)
1742
- })
1743
-
1744
- it('should return null for non-existent id', async () => {
1745
- const found = await repo.findById('non-existent')
1746
- expect(found).toBeNull()
1747
- })
1748
-
1749
- it('should list all ${r}', async () => {
1750
- await repo.create({ name: '${t} 1' })
1751
- await repo.create({ name: '${t} 2' })
1752
-
1753
- const all = await repo.findAll()
1754
- expect(all).toHaveLength(2)
1755
- })
1756
-
1757
- it('should return paginated results', async () => {
1758
- await repo.create({ name: '${t} 1' })
1759
- await repo.create({ name: '${t} 2' })
1760
- await repo.create({ name: '${t} 3' })
1761
-
1762
- const result = await repo.findPaginated({
1763
- filters: [],
1764
- sort: [],
1765
- search: '',
1766
- pagination: { page: 1, limit: 2, offset: 0 },
1767
- })
1768
-
1769
- expect(result.data).toHaveLength(2)
1770
- expect(result.total).toBe(3)
1771
- })
1772
-
1773
- it('should update a ${n}', async () => {
1774
- const created = await repo.create({ name: 'Original' })
1775
- const updated = await repo.update(created.id, { name: 'Updated' })
1776
- expect(updated.name).toBe('Updated')
1777
- })
1778
-
1779
- it('should delete a ${n}', async () => {
1780
- const created = await repo.create({ name: 'To Delete' })
1781
- await repo.delete(created.id)
1782
- const found = await repo.findById(created.id)
1783
- expect(found).toBeNull()
1784
- })
1785
- })
1786
- `}function Nn(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
1787
- import type { ParsedQuery } from '@forinda/kickjs'
1788
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
1789
- import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
1790
- import type { Create${t}DTO } from './dtos/create-${n}.dto'
1791
- import type { Update${t}DTO } from './dtos/update-${n}.dto'
1792
-
1793
- @Service()
1794
- export class ${t}Service {
1795
- constructor(
1796
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1797
- ) {}
1798
-
1799
- async findById(id: string): Promise<${t}ResponseDTO | null> {
1800
- return this.repo.findById(id)
1801
- }
1802
-
1803
- async findAll(): Promise<${t}ResponseDTO[]> {
1804
- return this.repo.findAll()
1805
- }
1806
-
1807
- async findPaginated(parsed: ParsedQuery) {
1808
- return this.repo.findPaginated(parsed)
1809
- }
1810
-
1811
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1812
- return this.repo.create(dto)
1813
- }
1814
-
1815
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1816
- return this.repo.update(id, dto)
1817
- }
1818
-
1819
- async delete(id: string): Promise<void> {
1820
- await this.repo.delete(id)
1821
- }
1822
- }
1823
- `}function Pn(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
1824
-
1825
- export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
1826
- filterable: ['name'],
1827
- sortable: ['name', 'createdAt'],
1828
- searchable: ['name'],
1829
- }
1830
- `}async function Fn(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,Cn({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
1831
-
1832
- // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
1833
- // \`kick typegen\` (auto-run on \`kick dev\`).
1834
-
1835
- @Controller()
1836
- export class ${t}Controller {
1837
- @Get('/')
1838
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1839
- ctx.json({ message: '${t} list' })
1840
- }
1841
- }
1842
- `)}async function In(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,write:l}=e;await l(`${n}.module.ts`,Sn({pascal:t,kebab:n,plural:r,repo:a,style:c})),await l(`${n}.constants.ts`,Pn({pascal:t,kebab:n})),await l(`${n}.controller.ts`,wn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`${n}.service.ts`,Nn({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,Tn({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,En({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,Dn({pascal:t,kebab:n})),await l(`${n}.repository.ts`,On({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:s}));let u=a===`inmemory`,d=u?`in-memory-${n}`:`${z(a)}-${n}`,f=u?kn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}):An({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});await l(`${d}.repository.ts`,f),o||(a!==`inmemory`&&await l(`in-memory-${n}.repository.ts`,kn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,jn({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,Mn({pascal:t,kebab:n,plural:r,repoPrefix:`../in-memory-${n}.repository`})))}function Ln(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Rn(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??`rest`;e.minimal&&(l=`minimal`);let u=z(t),d=L(t),f=c?B(u):u,p=c?en(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 Ge(n)&&!await F({message:`File exists: ${O.dim(e)}. Overwrite?`,initialValue:!1})){I.warn(`Skipped: ${e}`);return}await N(n,t),g.push(n)},files:g};switch(l){case`minimal`:await Fn(v);break;default:await In(v);break}return s||await zn(n,d,f,u,v.style),g}async function zn(e,t,n,r,i=`define`){let a=h(e,`index.ts`),o=await Ge(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await N(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
1843
- import { ${t}Module } from '${s}'
1844
-
1845
- export const modules: AppModuleEntry[] = [${c}]
1846
- `:`import { defineModules } from '@forinda/kickjs'
1847
- import { ${t}Module } from '${s}'
1848
-
1849
- export const modules = defineModules().mount(${c})
1850
- `);return}let l=await w(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=V(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${V(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
1851
- `,e);l=l.slice(0,t+1)+u+`
1852
- `+l.slice(t+1)}else l=u+`
1853
- `+l}let f=Vn(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${V(t)}Module\\b`).test(e)||(l=Bn(l,c))}else l=Bn(l,c);await T(a,l,`utf-8`)}function Bn(e,t){let n=Vn(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 Vn(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=Wn(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Hn(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Hn(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=Gn(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=Gn(e,t);if(n===-1)break;i=n+1}return i}function Un(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
1854
- `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function Wn(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=Un(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 Gn(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=Un(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 Kn(e){let{name:t,outDir:n}=e,r=z(t),i=L(t),a=[],o=h(n,`${r}.adapter.ts`);return await N(o,`import {
1855
- defineAdapter,
1856
- type AdapterContext,
1857
- type AdapterMiddleware,
1858
- type ContributorRegistrations,
1859
- type Constructor,
1860
- } from '@forinda/kickjs'
1861
-
1862
- /**
1863
- * Configuration for the ${i} adapter.
1864
- *
1865
- * Adapters typically take a small config object so callers can tune
1866
- * behaviour at bootstrap time. Keep the shape narrow — anything
1867
- * derived from the environment should be read inside the build
1868
- * function via getEnv(), not forced onto the caller.
1869
- */
1870
- export interface ${i}AdapterConfig {
1871
- // Add your adapter configuration here, e.g.:
1872
- // enabled?: boolean
1873
- // apiKey?: string
1874
- }
1875
-
1876
- /**
1877
- * ${i} adapter — built via \`defineAdapter()\` so callers get the
1878
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
1879
- *
1880
- * Hooks into the Application lifecycle to add middleware, routes,
1881
- * Context Contributors, or external service connections.
1882
- *
1883
- * Every lifecycle hook below is OPTIONAL. The scaffold emits all of
1884
- * them so adopters can browse what's available and delete what they
1885
- * don't need — \`build()\` returning \`{}\` is also valid for an adapter
1886
- * that only contributes config defaults.
1887
- *
1888
- * @example
1889
- * \`\`\`ts
1890
- * import { bootstrap } from '@forinda/kickjs'
1891
- * import { ${i}Adapter } from './adapters/${r}.adapter'
1892
- *
1893
- * bootstrap({
1894
- * modules,
1895
- * adapters: [${i}Adapter({ /* config overrides *\\/ })],
1896
- * })
1897
- * \`\`\`
1898
- */
1899
- export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
1900
- name: '${i}Adapter',
1901
- defaults: {
1902
- // Default config values go here. The adopter's overrides shallow-merge
1903
- // on top of these before \`build()\` runs.
1904
- },
1905
- build: (_config, { name: _name }) => {
1906
- // Closures inside \`build()\` are how each adapter instance owns its
1907
- // own state (database client, Map, timer handle, …). The same
1908
- // \`_config\` is visible to every hook below.
1909
-
1910
- return {
1911
- /**
1912
- * Express middleware entries the Application mounts at named phases.
1913
- *
1914
- * \`phase\` controls where each handler sits in the pipeline:
1915
- * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
1916
- *
1917
- * \`path\` (optional) scopes the entry to a path prefix.
1918
- *
1919
- * Delete this hook entirely if you don't add middleware.
1920
- */
1921
- middleware(): AdapterMiddleware[] {
1922
- return [
1923
- // Example: add a custom header to all responses
1924
- // {
1925
- // phase: 'beforeGlobal',
1926
- // handler: (_req, res, next) => {
1927
- // res.setHeader('X-${i}', 'true')
1928
- // next()
1929
- // },
1930
- // },
1931
- // Example: scope a rate limiter to one path prefix
1932
- // {
1933
- // phase: 'beforeRoutes',
1934
- // path: '/api/v1/auth',
1935
- // handler: rateLimit({ max: 10 }),
1936
- // },
1937
- ]
1938
- },
1939
-
1940
- /**
1941
- * Runs BEFORE global middleware. Mount routes that should bypass the
1942
- * middleware stack — health checks, docs UI, static assets, OAuth
1943
- * callbacks. Anything you want reachable even if a global middleware
1944
- * later in the chain rejects requests.
1945
- *
1946
- * Delete this hook if you have no early routes.
1947
- */
1948
- beforeMount(_ctx: AdapterContext): void {
1949
- // Example:
1950
- // _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
1951
- },
1952
-
1953
- /**
1954
- * Fires once per controller class as the router mounts. Use this to
1955
- * collect route metadata for OpenAPI specs, dependency graphs, route
1956
- * inventories, devtools dashboards.
1957
- *
1958
- * Delete this hook unless your adapter introspects the route registry.
1959
- */
1960
- onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
1961
- // Example (Swagger-style): collect routes for the spec.
1962
- // openApiSpec.addController(_controllerClass, _mountPath)
1963
- },
1964
-
1965
- /**
1966
- * Runs AFTER modules + routes are wired, BEFORE the server starts.
1967
- * Right place for late-stage DI registrations or final config validation.
1968
- *
1969
- * Delete this hook if there's nothing to wire post-modules.
1970
- */
1971
- beforeStart(_ctx: AdapterContext): void {
1972
- // Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
1973
- },
1974
-
1975
- /**
1976
- * Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
1977
- * available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
1978
- * gRPC, GraphQL subscriptions), warm caches, log a banner.
1979
- *
1980
- * Delete this hook if you don't need the running server reference.
1981
- */
1982
- afterStart(_ctx: AdapterContext): void {
1983
- // Example: const io = new Server(_ctx.server)
1984
- },
1985
-
1986
- /**
1987
- * Returns Context Contributors to merge into every route's pipeline
1988
- * at the \`'adapter'\` precedence level. Per-route handlers can
1989
- * override the value at the method / class / module level.
1990
- *
1991
- * Delete this hook unless your adapter ships typed per-request values
1992
- * (auth user, tenant, locale, feature flags, geo, etc).
1993
- */
1994
- contributors(): ContributorRegistrations {
1995
- return [
1996
- // Example:
1997
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
1998
- // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
1999
- // const Load${i} = defineHttpContextDecorator({
2000
- // key: '${r}',
2001
- // resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
2002
- // })
2003
- // return [Load${i}.registration]
2004
- ]
2005
- },
2006
-
2007
- /**
2008
- * Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
2009
- * resources the adapter owns: close connections, flush buffers,
2010
- * cancel timers. The framework runs every adapter's \`shutdown\`
2011
- * concurrently via \`Promise.allSettled\` — one failure won't block
2012
- * sibling adapters.
2013
- *
2014
- * Delete this hook if your adapter holds no resources.
2015
- */
2016
- async shutdown(): Promise<void> {
2017
- // Example: await this.pool.end()
2018
- // Example: clearInterval(this.heartbeatTimer)
2019
- },
2020
- }
2021
- },
2022
- })
2023
- `),a.push(o),a}async function qn(e){let{name:t,outDir:n}=e,r=z(t),i=L(t),a=[],o=h(n,`${r}.plugin.ts`);return await N(o,`import {
2024
- definePlugin,
2025
- type AppAdapter,
2026
- type AppModuleEntry,
2027
- type Container,
2028
- type ContributorRegistrations,
2029
- } from '@forinda/kickjs'
2030
-
2031
- /**
2032
- * Configuration for the ${i} plugin.
2033
- *
2034
- * Plugins typically take a small config object so callers can tune
2035
- * behaviour at bootstrap time. Keep the shape narrow — anything
2036
- * derived from the environment should be read inside the build
2037
- * function via getEnv(), not forced onto the caller.
2038
- */
2039
- export interface ${i}PluginConfig {
2040
- // Add your plugin config here, e.g.:
2041
- // enabled?: boolean
2042
- // apiKey?: string
2043
- }
2044
-
2045
- /**
2046
- * ${i} plugin — built via \`definePlugin()\` so callers get the
2047
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2048
- *
2049
- * A plugin bundles DI bindings, modules, adapters, and middleware
2050
- * into one object that can be added to \`bootstrap({ plugins })\`.
2051
- *
2052
- * Lifecycle order (each hook is optional — delete the ones you don't
2053
- * need and keep only the surface your plugin actually uses):
2054
- *
2055
- * 1. \`register(container)\` — runs before user modules load. Use
2056
- * it to bind services that modules depend on.
2057
- * 2. \`modules()\` — plugin modules load before user modules.
2058
- * 3. \`adapters()\` — plugin adapters mount before user adapters.
2059
- * 4. \`middleware()\` — plugin middleware runs before user middleware.
2060
- * 5. \`contributors()\` — Context Contributors merged into every route.
2061
- * 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
2062
- * 7. \`shutdown()\` — runs on graceful shutdown.
2063
- *
2064
- * @example
2065
- * \`\`\`ts
2066
- * import { bootstrap } from '@forinda/kickjs'
2067
- * import { ${i}Plugin } from './plugins/${r}.plugin'
2068
- *
2069
- * export const app = await bootstrap({
2070
- * modules,
2071
- * plugins: [${i}Plugin({ /* config overrides *\\/ })],
2072
- * })
2073
- * \`\`\`
2074
- */
2075
- export const ${i}Plugin = definePlugin<${i}PluginConfig>({
2076
- name: '${i}Plugin',
2077
- defaults: {
2078
- // Default config values go here
2079
- },
2080
- build: (_config, { name: _name }) => ({
2081
- /**
2082
- * Register DI bindings before modules load.
2083
- * Use \`container.registerInstance(TOKEN, value)\` for singletons
2084
- * and \`container.registerFactory(TOKEN, () => ...)\` for lazy
2085
- * constructions.
2086
- */
2087
- register(_container: Container): void {
2088
- // Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
2089
- },
2090
-
2091
- /**
2092
- * Return modules this plugin contributes to the app. These load
2093
- * before user modules, so plugin controllers and services are
2094
- * available for user code to \`@Autowired\`.
2095
- *
2096
- * Accepts both \`defineModule\`-style instances (call the factory:
2097
- * \`ExampleModule()\`) and legacy \`class … implements AppModule\`
2098
- * constructors.
2099
- */
2100
- modules(): AppModuleEntry[] {
2101
- return [
2102
- // ExampleModule(),
2103
- ]
2104
- },
2105
-
2106
- /**
2107
- * Return adapter instances to be added to the application.
2108
- * Plugin adapters mount before user adapters.
2109
- */
2110
- adapters(): AppAdapter[] {
2111
- return [
2112
- // MyAdapter({ ... }),
2113
- ]
2114
- },
2115
-
2116
- /**
2117
- * Return Express middleware entries to be added to the global
2118
- * pipeline. Plugin middleware runs before user-defined middleware.
2119
- */
2120
- middleware(): unknown[] {
2121
- return [
2122
- // helmet(),
2123
- // myCustomMiddleware(_config),
2124
- ]
2125
- },
2126
-
2127
- /**
2128
- * Return Context Contributors to merge into every route's pipeline.
2129
- * Plugins contribute at the same \`'adapter'\` precedence level as
2130
- * adapters — overrideable per-route at the method / class / module
2131
- * level. See https://kickjs.app/guide/context-decorators
2132
- *
2133
- * Delete this hook if your plugin doesn't ship typed per-request values.
2134
- */
2135
- contributors(): ContributorRegistrations {
2136
- return [
2137
- // Example:
2138
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
2139
- // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
2140
- // const Load${i} = defineHttpContextDecorator({
2141
- // key: '${r}',
2142
- // resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
2143
- // })
2144
- // return [Load${i}.registration]
2145
- ]
2146
- },
2147
-
2148
- /**
2149
- * Called after the application has fully bootstrapped. Use this
2150
- * for post-startup work like logging, health checks, or warming
2151
- * a cache. Runs once per process.
2152
- */
2153
- async onReady(_container: Container): Promise<void> {
2154
- // const log = _container.resolve(Logger)
2155
- // log.info('${i} plugin ready')
2156
- },
2157
-
2158
- /**
2159
- * Called during graceful shutdown. Clean up any long-lived
2160
- * resources this plugin owns (connections, timers, subscriptions).
2161
- */
2162
- async shutdown(): Promise<void> {
2163
- // Example: await this.connection?.close()
2164
- },
2165
- }),
2166
- })
2167
- `),a.push(o),a}const Jn={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function Yn(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return v(n);if(r){let e=Jn,n=z(r),a=o?B(n):n,s=e[t]??``,c=h(i,a);return v(s?h(c,s):c)}return v(a)}async function Xn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Yn({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=R(t),c=[],l=h(a,`${o}.middleware.ts`);return await N(l,`import type { Request, Response, NextFunction } from 'express'
2168
-
2169
- export interface ${L(t)}Options {
2170
- // Add configuration options here. The factory below closes over the
2171
- // resolved options object; pass them at the call site —
2172
- // \`${s}({ foo: 'bar' })\` — and the closure preserves them across
2173
- // every request.
2174
- }
2175
-
2176
- /**
2177
- * ${L(t)} middleware.
2178
- *
2179
- * Usage in bootstrap (fires on every request):
2180
- * middleware: [${s}()]
2181
- *
2182
- * Usage with adapter — phase controls *when* the handler runs:
2183
- *
2184
- * middleware() {
2185
- * return [{ handler: ${s}(), phase: 'afterGlobal' }]
2186
- * }
2187
- *
2188
- * Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
2189
- * - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
2190
- * request, before module routes run.
2191
- * - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
2192
- * OR a route handler called \`next()\` without ending the response.
2193
- * Controllers that call \`ctx.json(…)\` end the chain and skip this
2194
- * phase. For per-response work (logging, metrics) attach to
2195
- * \`res.on('finish', …)\` from an earlier-phase middleware instead.
2196
- *
2197
- * Optional path scope — string, RegExp, or array of either:
2198
- * middleware() {
2199
- * return [{
2200
- * handler: ${s}({ region: 'eu' }),
2201
- * phase: 'afterGlobal',
2202
- * path: ['/api', /^\\/admin/],
2203
- * }]
2204
- * }
2205
- *
2206
- * Usage with @Middleware decorator:
2207
- * @Middleware(${s}())
2208
- */
2209
- export function ${s}(options: ${L(t)}Options = {}) {
2210
- return (req: Request, res: Response, next: NextFunction) => {
2211
- // Implement your middleware logic here. \`options\` is captured by
2212
- // closure — log or read it anywhere in this handler body.
2213
- void options
2214
- next()
2215
- }
2216
- }
2217
- `),c.push(l),c}async function Zn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Yn({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=R(t),c=L(t),l=[],u=h(a,`${o}.guard.ts`);return await N(u,`import { Container, HttpException } from '@forinda/kickjs'
2218
- import type { RequestContext } from '@forinda/kickjs'
2219
-
2220
- /**
2221
- * ${c} guard.
2222
- *
2223
- * Guards protect routes by checking conditions before the handler runs.
2224
- * Return early with an error response to block access.
2225
- *
2226
- * Usage:
2227
- * @Middleware(${s}Guard)
2228
- * @Get('/protected')
2229
- * async handler(ctx: RequestContext) { ... }
2230
- */
2231
- export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<void> {
2232
- // Example: check for an authorization header
2233
- const header = ctx.headers.authorization
2234
- if (!header?.startsWith('Bearer ')) {
2235
- ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
2236
- return
2237
- }
2238
-
2239
- const token = header.slice(7)
2240
-
2241
- try {
2242
- // Verify the token using a service from the DI container
2243
- // const container = Container.getInstance()
2244
- // const authService = container.resolve(AuthService)
2245
- // const payload = authService.verifyToken(token)
2246
- // ctx.set('auth', payload)
2247
-
2248
- next()
2249
- } catch {
2250
- ctx.res.status(401).json({ message: 'Invalid or expired token' })
2251
- }
2252
- }
2253
- `),l.push(u),l}function Qn(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function $n(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=z(t),s=L(t),c=e.key??R(t),l=Array.isArray(e.params)?e.params:Qn(e.params),u=Yn({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
2254
- `)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,g=l.length>0?` // Every call site must supply these — no placeholder defaults.
2255
- // Add \`paramDefaults: { … }\` for any field whose default is
2256
- // genuinely correct for an undecorated route, and drop it from here.
2257
- requiredParams: [${l.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=l.length>0?`(ctx, _deps, params)`:`(ctx)`,v=l.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${f} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,y=`import { ${d} } from '@forinda/kickjs'
2258
- import type { ${f} } from '@forinda/kickjs'
2259
-
2260
- /**
2261
- * ${s} context contributor (${a}).
2262
- *
2263
- * Computes a value and writes it to \`ctx.set('${c}', …)\` before a
2264
- * matched handler runs — the typed, ordered alternative to
2265
- * \`@Middleware()\` when the only job is to populate \`ctx\`.
2266
- *
2267
- * Apply per method/class:
2268
- *
2269
- ${a===`http`?` * @${s}${l.length>0?`({ ${l[0]?.name}: … })`:``}
2270
- * @Get('/')
2271
- * handler(ctx: ${f}) {
2272
- * return ctx.json(ctx.require('${c}'))
2273
- * }`:` * // Any transport whose handler receives an ExecutionContext
2274
- * // (WebSocket, queue, cron). Attach via that transport's decorator,
2275
- * // or register the contributor at a module / bootstrap site below.
2276
- * handler(ctx: ${f}) {
2277
- * const value = ctx.require('${c}')
2278
- * }`}
2279
- *
2280
- * Or register at a module / adapter / bootstrap site — those take a
2281
- * \`ContributorRegistration\`, not the decorator itself:
2282
- *
2283
- * bootstrap({ contributors: [${s}${l.length>0?`.with({ ${l[0]?.name}: … })`:``}.registration] })
2284
- */
2285
-
2286
- // Register '${c}' so \`ctx.require('${c}')\` is typed and \`dependsOn: ['${c}']\`
2287
- // is checked. Replace \`unknown\` with the resolved value's real type.
2288
- // (For a key you only depend on — no value type needed — declare it in
2289
- // \`interface ContextKeys\` instead.)
2290
- declare module '@forinda/kickjs' {
2291
- interface ContextMeta {
2292
- '${c}': unknown
2293
- }
2294
- }
2295
- ${p}
2296
- export const ${s} = ${m}
2297
- key: '${c}',
2298
- ${g} resolve: ${_} => {
2299
- ${v}
2300
- // TODO: compute and return the value written to ctx.set('${c}', …)
2301
- throw new Error("${s} contributor: resolve() not implemented")
2302
- },
2303
- })
2304
- `,b=h(u,`${o}.contributor.ts`);return await N(b,y),[b]}async function er(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Yn({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=[],l=h(a,`${o}.service.ts`);return await N(l,`import { Service } from '@forinda/kickjs'
2305
-
2306
- @Service()
2307
- export class ${s}Service {
2308
- // Inject dependencies via constructor
2309
- // constructor(
2310
- // @Inject(MY_REPO) private readonly repo: IMyRepository,
2311
- // ) {}
2312
- }
2313
- `),c.push(l),c}async function tr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Yn({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=[],l=h(a,`${o}.controller.ts`);return await N(l,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
2314
-
2315
- // \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
2316
- // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
2317
- // will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
2318
- // See https://kickjs.app/guide/typegen for details.
2319
-
2320
- @Controller()
2321
- export class ${s}Controller {
2322
- // @Autowired() private readonly myService!: MyService
2323
-
2324
- @Get('/')
2325
- async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
2326
- ctx.json({ message: '${s} list' })
2327
- }
2328
-
2329
- @Post('/')
2330
- async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
2331
- ctx.created({ message: '${s} created', data: ctx.body })
2332
- }
2333
- }
2334
- `),c.push(l),c}async function nr(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Yn({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=R(t),l=[],u=h(a,`${o}.dto.ts`);return await N(u,`import { z } from 'zod'
2335
-
2336
- export const ${c}Schema = z.object({
2337
- // Define your schema fields here
2338
- name: z.string().min(1).max(200),
2339
- })
2340
-
2341
- export type ${s}DTO = z.infer<typeof ${c}Schema>
2342
- `),l.push(u),l}async function rr(e){let t=h(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return r(t)&&!e.force&&!await F({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
2343
- Skipped — existing kick.config.ts preserved.`),[]):(await N(t,`import { defineConfig } from '@forinda/kickjs-cli'
2344
-
2345
- export default defineConfig({
2346
- modules: {
2347
- dir: '${n}',
2348
- repo: '${i}',
2349
- pluralize: true,
2350
- },
2351
-
2352
- typegen: {
2353
- schemaValidator: 'zod',
2354
- },
2355
-
2356
- commands: [
2357
- {
2358
- name: 'test',
2359
- description: 'Run tests with Vitest',
2360
- steps: 'npx vitest run',
2361
- },
2362
- {
2363
- name: 'format',
2364
- description: 'Format code with Prettier',
2365
- steps: 'npx prettier --write src/',
2366
- },
2367
- {
2368
- name: 'format:check',
2369
- description: 'Check formatting without writing',
2370
- steps: 'npx prettier --check src/',
2371
- },
2372
- {
2373
- name: 'ci:check',
2374
- description: 'Run typecheck + format check',
2375
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
2376
- aliases: ['verify'],
2377
- },
2378
- ],
2379
- })
2380
- `),[t])}var ir=k({generateAgentDocs:()=>ur});const ar=`.agents`,or=new Set([`rest`,`minimal`,`fullstack`]);function sr(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 cr(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 lr(e,t){if(t)return t;try{let t=(await j(e))?.pattern;if(t&&or.has(t))return t}catch{}return`rest`}async function ur(e){let t=e.only??`all`,n=sr(e.outDir,e.name),i=cr(e.outDir,e.pm),a=await lr(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,ar,`AGENTS.md`),render:()=>ht(n,a,i)}),s&&d.push({file:h(e.outDir,`CLAUDE.md`),render:()=>mt(n,a,i)}),c)for(let t of gt(n,a,i))d.push({file:h(e.outDir,ar,`skills`,t.slug,`SKILL.md`),render:()=>t.content});l&&d.push({file:h(e.outDir,ar,`GEMINI.md`),render:()=>_t(n,a,i)}),u&&d.push({file:h(e.outDir,ar,`COPILOT.md`),render:()=>vt(n,a,i)});let f=[];for(let{file:t,render:n}of d){if(r(t)&&!e.force&&!await F({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await N(t,n()),f.push(t)}return f}function dr(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 fr(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=dr(e,r);return i===-1?null:e.slice(r+1,i)}function pr(e,t,n){let r=` `.repeat(n);return e.split(`
2381
- `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
2382
- `)}function mr(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 hr(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 gr(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=dr(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=fr(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=fr(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=fr(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=mr(s),p=``;return l&&(p+=` register(container) {${pr(l,4,6)} },\n\n`),u&&(p+=` contributors() {${pr(u,4,6)} },\n\n`),p+=` routes() {${pr(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
2383
- name: '${r}',
2384
- build: () => ({
2385
- ${p}
2386
- }),
2387
- })`}${c}`}}function _r(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=dr(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]===`
2388
- `||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=dr(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=fr(m,/register\s*\(([^)]*)\)\s*\{/),g=fr(m,/contributors\s*\(\s*\)\s*\{/),_=fr(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=hr(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${pr(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${pr(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${pr(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
2389
- ${y}
2390
- }
2391
- `}${u}`}}function vr(e,t){return t===`class`?_r(e):gr(e)}function yr(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 br(e){let t=[];return await n(v(e),0),t;async function n(e,r){let i;try{i=await oe(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 ce(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function xr(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await oe(e)}catch{return}await ae(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 ce(i)}catch{continue}s.isDirectory()?await r(i,o):(await ie(i,o),n++)}}}function Sr(e){return h(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function Cr(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await br(e),s=await w(h(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Sr(r),await xr(e,c));let l=[];for(let e of o){let t=vr(await w(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await T(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=h(e,`index.ts`),d=null;try{d=await w(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=yr(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await T(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function wr(e,t){let n=await br(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 w(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Tr(e){let{name:t,outDir:n}=e,r=L(t),i=z(t),a=R(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=h(n,e);await N(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
2392
- import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
2393
-
2394
- /**
2395
- * ${r} Job Processor
2396
- *
2397
- * Decorators:
2398
- * @Job(queueName) — marks this class as a job processor for a queue
2399
- * @Process(jobName?) — marks a method as the handler for a specific job type
2400
- * - Without a name: handles all jobs in the queue
2401
- * - With a name: handles only jobs matching that name
2402
- *
2403
- * To add jobs to this queue from a service or controller:
2404
- * @Inject(QUEUE_MANAGER) private queue: QueueService
2405
- * await this.queue.add('${o}', '${a}', { ... })
2406
- */
2407
- @Job('${o}')
2408
- export class ${r}Job {
2409
- @Process()
2410
- async handle(job: { name: string; data: any; id?: string }) {
2411
- console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
2412
-
2413
- // TODO: Implement job logic here
2414
- // Example:
2415
- // await this.emailService.send(job.data.to, job.data.subject, job.data.body)
2416
- }
2417
-
2418
- @Process('${a}.priority')
2419
- async handlePriority(job: { name: string; data: any; id?: string }) {
2420
- console.log(\`Priority job: \${job.name}\`, job.data)
2421
- // Handle high-priority variant of this job
2422
- }
2423
- }
2424
- `),s}const Er={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 Dr(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=Er[a];if(!o){let e=[...Object.keys(Er),`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 Or(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=z(t),l=L(t),u=s?B(c):c,d=s?en(l):l,f=h(r,u),p=[],m=async(e,t)=>{let n=h(f,e);await N(n,t),p.push(n)};await m(`${c}.module.ts`,Sn({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,Pn({pascal:l,kebab:c})),await m(`${c}.controller.ts`,wn({pascal:l,kebab:c,plural:u,pluralPascal:d})),await m(`${c}.service.ts`,Nn({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,kr(l,n)),await m(`dtos/update-${c}.dto.ts`,Ar(l,n)),await m(`dtos/${c}-response.dto.ts`,jr(l,n)),await m(`${c}.repository.ts`,On({pascal:l,kebab:c,dtoPrefix:`./dtos`,tokenScope:a}));let g=i===`inmemory`,_=g?`in-memory-${c}`:`${z(i)}-${c}`,v=g?kn({pascal:l,kebab:c,repoPrefix:`.`,dtoPrefix:`./dtos`}):An({pascal:l,kebab:c,repoType:i,repoPrefix:`.`,dtoPrefix:`./dtos`});return await m(`${_}.repository.ts`,v),await zn(r,l,u,c,o),p}function kr(e,t){return`import { z } from 'zod'
2425
-
2426
- export const create${e}Schema = z.object({
2427
- ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
2428
- `)}
2429
- })
2430
-
2431
- export type Create${e}DTO = z.infer<typeof create${e}Schema>
2432
- `}function Ar(e,t){return`import { z } from 'zod'
2433
-
2434
- export const update${e}Schema = z.object({
2435
- ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
2436
- `)}
2437
- })
2438
-
2439
- export type Update${e}DTO = z.infer<typeof update${e}Schema>
2440
- `}function jr(e,t){return`export interface ${e}ResponseDTO {
2441
- id: string
2442
- ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
2443
- `)}
2444
- createdAt: string
2445
- updatedAt: string
2446
- }
2447
- `}async function Mr(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=z(t),o=L(t),s=[],c;if(e.outDir)c=v(e.outDir);else if(n){let e=z(n),t=i?B(e):e;c=v(h(r??`src/modules`,t,`__tests__`))}else c=v(`src/__tests__`);let l=h(c,`${a}.test.ts`);return await N(l,`import { describe, it, expect, beforeEach } from 'vitest'
2448
- import { Container } from '@forinda/kickjs'
2449
-
2450
- describe('${o}', () => {
2451
- beforeEach(() => {
2452
- Container.reset()
2453
- })
2454
-
2455
- it('should be defined', () => {
2456
- // TODO: Import and test your class/function here
2457
- expect(true).toBe(true)
2458
- })
2459
-
2460
- it('should handle the happy path', async () => {
2461
- // TODO: Set up test data and assertions
2462
- expect(true).toBe(true)
2463
- })
2464
-
2465
- it('should handle edge cases', async () => {
2466
- // TODO: Test error handling, empty inputs, etc.
2467
- expect(true).toBe(true)
2468
- })
2469
- })
2470
- `),s.push(l),s}const Nr=[`classes`,`tokens`,`injects`,`pluginsAndAdapters`,`augmentations`,`contextKeys`,`routes`,`moduleMounts`,`globPatterns`];function Pr(e){if(!e||typeof e!=`object`)return!1;let t=e;return Nr.every(e=>Array.isArray(t[e]))}var Fr=class e{path;prev;next=new Map;nextSig=new Map;constructor(e,t){this.path=e,this.prev=t}static async load(t){let n=h(t,`scan.json`),r=new Map;try{let e=await w(n,`utf-8`),t=JSON.parse(e);if(t.version===2&&t.files)for(let[e,n]of Object.entries(t.files))n&&typeof n.sig==`string`&&Pr(n.extract)&&r.set(e,n)}catch{}return new e(n,r)}static async signature(e){try{let t=await ce(e);return`${t.mtimeMs}:${t.size}`}catch{return null}}get(e,t){let n=this.prev.get(e);return n&&n.sig===t?n.extract:null}set(e,t,n){this.next.set(e,n),this.nextSig.set(e,t)}cachedFiles(){return[...this.prev.keys()]}peek(e){return this.prev.get(e)?.extract??null}carry(e){let t=this.prev.get(e);return t?(this.next.set(e,t.extract),this.nextSig.set(e,t.sig),!0):!1}async save(){let e={};for(let[t,n]of this.next){let r=this.nextSig.get(t);r&&(e[t]={sig:r,extract:n})}let t={version:2,files:e};try{await ae(f(this.path),{recursive:!0}),await T(this.path,JSON.stringify(t),`utf-8`)}catch{}}};let Ir=null;function Lr(){return Ir??=new Set(ii),Ir}const Rr=new Set([`Get`,`Post`,`Put`,`Delete`,`Patch`]);function H(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(H(e)){t(e);for(let n of Object.keys(e)){if(n===`type`)continue;let r=e[n];typeof r==`object`&&r&&U(r,t)}}}function W(e){if(!H(e))return null;if(e.type===`Literal`&&typeof e.value==`string`)return e.value;if(e.type===`TemplateLiteral`){let t=e.quasis,n=e.expressions;if(t?.length===1&&(n?.length??0)===0){let e=t[0].value?.cooked;return typeof e==`string`?e:null}}return null}function G(e){return H(e)&&e.type===`Identifier`?e.name:null}function zr(e){return G(e.callee)}function K(e,t){if(!e||e.type!==`ObjectExpression`)return null;for(let n of e.properties??[]){if(n.type!==`Property`)continue;let e=n.key;if((G(e)??(e.type===`Literal`?String(e.value):W(e)))===t)return n.value}return null}function Br(e){let t=e.arguments?.[0];return H(t)&&t.type===`ObjectExpression`?t:null}function Vr(e,t){let n=K(e,t);if(!H(n)||n.type!==`ArrayExpression`)return[];let r=[];for(let e of n.elements??[]){let t=W(e);t!==null&&r.push(t)}return r}function Hr(e,t){return _(t,e).split(y).join(`/`)}function Ur(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function Wr(e,t){for(let n of e.implements??[]){let e=n.expression??n;if(G(e)===t)return!0;if(e.type===`TSQualifiedName`||e.type===`MemberExpression`){let n=e.right??e.property;if(n&&G(n)===t)return!0}}return!1}function Gr(e){return e.decorators??[]}function Kr(e){let t=e.expression;if(!H(t)||t.type!==`CallExpression`)return null;let n=zr(t);return n?{name:n,call:t}:null}function qr(e){let t=new Map,n=new Set;for(let r of e.body??[]){if(r.type===`ImportDeclaration`){let e=W(r.source)??``;for(let n of r.specifiers??[]){let r=G(n.local);r&&t.set(r,{source:e})}continue}let e=r.type===`VariableDeclaration`?r:r.type===`ExportNamedDeclaration`&&H(r.declaration)?r.declaration:null;if(H(e)&&e.type===`VariableDeclaration`)for(let t of e.declarations??[]){let e=G(t.id);e&&n.add(e)}}return{imports:t,topLevelConsts:n}}function Jr(e,t){let n=t.imports.get(e);return n?{identifier:e,source:n.source}:t.topLevelConsts.has(e)?{identifier:e,source:``}:{identifier:e,source:null}}function Yr(e,t){let n=[];for(let r of e){let e=Kr(r),i=e?e.name:G(r.expression);if(!i||Rr.has(i))continue;let a=t.imports.get(i);n.push({identifier:i,source:a?a.source:t.topLevelConsts.has(i)?``:null})}return n}const Xr=new Set([`bootstrap`,`createWebApp`,`Application`]);function Zr(e,t){if(!Xr.has(e))return!1;let n=t.imports.get(e)?.source;return n===`@forinda/kickjs`||(n?.startsWith(`@forinda/kickjs/`)??!1)}function Qr(e,t){let n={refs:[],resolved:!1},r=$r(e);if(!r||r.type!==`ArrayExpression`)return n;let i=[];for(let e of r.elements??[]){if(!H(e)||e.type!==`MemberExpression`||G(e.property)!==`registration`)return n;let r=e.object,a=G(r);if(!a&&H(r)&&r.type===`CallExpression`){let e=r.callee;H(e)&&e.type===`MemberExpression`&&G(e.property)===`with`&&(a=G(e.object))}if(!a)return n;let o=t.imports.get(a);i.push({identifier:a,source:o?o.source:t.topLevelConsts.has(a)?``:null})}return{refs:i,resolved:!0}}function $r(e){let t=e.value??e;if(!H(t))return null;if(t.type===`ArrayExpression`)return t;let n=t.body;if(!H(n))return null;if(n.type!==`BlockStatement`)return n;let r=(n.body??[]).filter(e=>e.type===`ReturnStatement`);if(r.length!==1)return null;let i=r[0].argument;return H(i)?i:null}function ei(e,t,n){let r=G(K(e,t));return r?Jr(r,n):null}function ti(e,t){for(let n of e){let e=Kr(n);if(!e||e.name!==`ApiQueryParams`)continue;let r=e.call.arguments?.[0],i=null;if(H(r)&&r.type===`ObjectExpression`)i=r;else{let e=G(r);if(e){let n=t.get(e);n&&n.type===`ObjectExpression`&&(i=n)}}return{filterable:Vr(i,`filterable`),sortable:Vr(i,`sortable`),searchable:Vr(i,`searchable`)}}return null}function ni(e,t,n){let r;try{let n=fe(t,e);if(n.errors.length>0)return null;r=n.program}catch{return null}let i=Hr(t,n),a=qr(r),o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h=new Set,g=new Set,_=new Map;U(r,e=>{if(e.type!==`VariableDeclarator`)return;let t=G(e.id),n=e.init;t&&H(n)&&_.set(n,t)});let v=new Set,y=new Map;for(let e of r.body??[]){let t=e.type===`VariableDeclaration`?e:e.type===`ExportNamedDeclaration`&&H(e.declaration)?e.declaration:null;if(H(t)&&t.type===`VariableDeclaration`)for(let e of t.declarations??[]){let t=G(e.id);t&&H(e.init)&&y.set(t,e.init)}}let b=[];for(let e of r.body??[])if(e.type===`ExportNamedDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&b.push({cls:t,isDefault:!1})}else if(e.type===`ExportDefaultDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&b.push({cls:t,isDefault:!0})}for(let{cls:e,isDefault:n}of b){let r=G(e.id);if(!r)continue;let a=null;for(let t of Gr(e)){let e=Kr(t);if(e&&Lr().has(e.name)){a=e.name;break}}a?o.push({className:r,decorator:a,filePath:t,relativePath:i,isDefault:n}):Wr(e,`AppModule`)&&o.push({className:r,decorator:`Module`,filePath:t,relativePath:i,isDefault:n})}for(let e of r.body??[]){if(e.type!==`ExportNamedDeclaration`||!H(e.declaration))continue;let n=e.declaration;if(n.type===`VariableDeclaration`)for(let e of n.declarations??[]){let n=G(e.id),r=e.init;!n||!H(r)||r.type!==`CallExpression`||zr(r)===`defineModule`&&(o.some(e=>e.className===n)||o.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1}))}}U(r,e=>{if(e.type===`VariableDeclarator`){let n=e.init;if(H(n)&&n.type===`CallExpression`&&zr(n)===`createToken`){let r=W(n.arguments?.[0]);r!==null&&(v.add(n),s.push({name:r,variable:G(e.id),filePath:t,relativePath:i}))}return}if(e.type!==`CallExpression`){if(e.type===`Decorator`){let n=Kr(e);if(n?.name===`Inject`){let e=W(n.call.arguments?.[0]);e!==null&&c.push({name:e,filePath:t,relativePath:i})}}return}let n=e.callee,r=zr(e);if(r===`createToken`&&!v.has(e)){let n=W(e.arguments?.[0]);n!==null&&s.push({name:n,variable:null,filePath:t,relativePath:i});return}if(r===`defineAdapter`||r===`definePlugin`){let n=W(K(Br(e),`name`));if(n!==null){let e=r===`definePlugin`?`plugin`:`adapter`,a=`${r}::${n}::${t}`;h.has(a)||(h.add(a),l.push({kind:e,name:n,filePath:t,relativePath:i}))}return}if(r===`defineAugmentation`){let n=e.arguments??[],r=W(n[0]);if(r!==null){let e=H(n[1])&&n[1].type===`ObjectExpression`?n[1]:null;u.push({name:r,description:W(K(e,`description`)),example:W(K(e,`example`)),filePath:t,relativePath:i})}return}if(r===`defineContextDecorator`||r===`defineHttpContextDecorator`){let n=W(K(Br(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,exportName:_.get(e)??null,filePath:t,relativePath:i}));return}if(H(n)&&n.type===`CallExpression`){let r=n.callee;if(H(r)&&r.type===`MemberExpression`&&G(r.property)===`withParams`){let n=G(r.object);if(n===`defineContextDecorator`||n===`defineHttpContextDecorator`){let n=W(K(Br(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,exportName:_.get(e)??null,filePath:t,relativePath:i}))}}return}if(H(n)&&n.type===`MemberExpression`&&G(n.property)===`glob`){let t=n.object;H(t)&&t.type===`MetaProperty`&&U(e.arguments,e=>{let t=W(e);t!==null&&m.push(t)})}});let x=[];U(r,e=>{if(e.type===`ClassDeclaration`||e.type===`ClassExpression`){let t=G(e.id);t&&x.push({cls:e,className:t})}});for(let{cls:e,className:n}of x){let r=o.find(e=>e.className===n),s=e.body?.body;if(Wr(e,`AppAdapter`))for(let e of s??[]){if(e.type!==`PropertyDefinition`||G(e.key)!==`name`)continue;let n=W(e.value);if(n===null)continue;let r=`class::${n}::${t}`;h.has(r)||(h.add(r),l.push({kind:`adapter`,name:n,filePath:t,relativePath:i}));break}for(let o of s??[]){if(o.type!==`MethodDefinition`)continue;let s=G(o.key);if(!s)continue;if(s===`routes`){ri(o.value,p);continue}if(!r)continue;let c=Gr(o),l=ti(c,y),u=[...Yr(Gr(e),a),...Yr(c,a)];for(let e of c){let o=Kr(e);if(!o||!Rr.has(o.name))continue;let c=o.call.arguments??[],d=W(c[0]),p=d&&d.length>0?d:`/`,m=H(c[1])&&c[1].type===`ObjectExpression`?c[1]:null;f.push({controller:n,method:s,httpMethod:o.name.toUpperCase(),path:p,pathParams:Ur(p),queryFilterable:l?.filterable??null,querySortable:l?.sortable??null,querySearchable:l?.searchable??null,bodySchema:ei(m,`body`,a),querySchema:ei(m,`query`,a),paramsSchema:ei(m,`params`,a),responseSchema:ei(m,`response`,a),filePath:t,relativePath:i,controllerIsDefaultExport:r.isDefault,appliedDecorators:u,mountedPath:p})}}}U(r,e=>{if(e.type!==`Property`||G(e.key)!==`routes`)return;let t=e.value;H(t)&&(t.type===`FunctionExpression`||t.type===`ArrowFunctionExpression`)&&ri(t,p)});let S=new Set,C=new Set;U(r,e=>{let t=e.type===`Property`&&G(e.key)===`contributors`,n=e.type===`MethodDefinition`&&G(e.key)===`contributors`;(t||n)&&C.add(e)});let ee=e=>e.properties??e.body?.body??[];U(r,e=>{if(e.type!==`ObjectExpression`&&e.type!==`ClassDeclaration`)return;let t=ee(e);if(t.map(e=>G(e.key)).includes(`routes`))for(let e of t)G(e.key)===`contributors`&&S.add(e)});let te=new Set;U(r,e=>{let t=e.type===`CallExpression`?zr(e):e.type===`NewExpression`?G(e.callee):null;if(t===null||!Zr(t,a))return;let n=Br(e);if(n)for(let e of n.properties??[])e.type===`Property`&&G(e.key)===`contributors`&&te.add(e)});let ne=e=>{if(e.size===0)return null;let n=[],r=!0;for(let t of e){let e=Qr(t,a);e.resolved||(r=!1),n.push(...e.refs)}return{refs:n,resolved:r,filePath:t}},re=ne(S),ie=ne(te);return{classes:o,tokens:s,injects:c,pluginsAndAdapters:l,augmentations:u,contextKeys:d,routes:f,moduleMounts:p,globPatterns:/\.module\.[mc]?[tj]sx?$/.test(t)?m:[],moduleContributors:re,appContributors:ie,hasNonDecoratorContributors:C.size>S.size+te.size}}function ri(e,t){let n=[],r=[];U(e.body,e=>{if(e.type!==`Property`)return;let t=G(e.key);if(t===`path`){let t=W(e.value);t!==null&&n.push(t)}else if(t===`controller`){let t=G(e.value);t&&/^[A-Z]/.test(t)&&r.push(t)}});let i=Math.min(n.length,r.length);for(let e=0;e<i;e++)t.push({controller:r[e],mountPath:n[e]})}const ii=[`Service`,`Controller`,`Repository`,`Injectable`,`Component`,`Module`],ai=[`.ts`,`.tsx`,`.mts`,`.cts`],oi=[`node_modules`,`.kickjs`,`dist`,`build`,`.test.`,`.spec.`,`.d.ts`],si=new RegExp(String.raw`@(${ii.join(`|`)})\s*\([^)]*\)`+String.raw`(?:\s*@[A-Z]\w*(?:\s*\([^)]*\))?)*`+String.raw`\s*export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`,`g`),ci=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`),li=/export\s+const\s+(\w+)\s*(?::\s*[^=]+)?=\s*defineModule\s*(?:<[^>]*>)?\s*\(/g,ui=/(?:export\s+)?const\s+(\w+)\s*(?::\s*[^=]+)?=\s*createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,di=/createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,fi=/@Inject\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,pi=/\b(defineAdapter|definePlugin)\s*(?:<[^>]*>)?\s*\(/g,mi=/(?:(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*)?\b(?:defineContextDecorator|defineHttpContextDecorator)\s*(?:\.withParams\s*<(?:[^<>]|<[^<>]*>)*>\s*\(\s*\))?\s*(?:<(?:[^<>]|<[^<>]*>)*>)?\s*\(/g,hi=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`),gi=/\bname\s*(?::\s*[^=]+)?=\s*['"`]([^'"`]+)['"`]/,_i=/\bdefineAugmentation\s*\(\s*['"`]([^'"`]+)['"`]\s*(,\s*\{)?/g,vi=new RegExp(String.raw`@(${[`Get`,`Post`,`Put`,`Delete`,`Patch`].join(`|`)})\s*\(`,`g`);function yi(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 bi(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=yi(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 xi(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function Si(e,t){let n=e.endsWith(`/`)?e.slice(0,-1):e;return!t||t===`/`?n||`/`:n+(t.startsWith(`/`)?t:`/`+t)||`/`}const Ci=/\b(?:public\s+|private\s+|protected\s+)?routes\s*\([^)]*\)\s*(?::\s*[A-Za-z_][\w<>[\]\s,|]*\s*)?\{/g,wi=/\bpath\s*:\s*['"`]([^'"`]*)['"`]/g,Ti=/\bcontroller\s*:\s*([A-Z]\w*)\b/g,Ei=/\bimport\.meta\.glob\s*\(/g;function Di(e){let t=[];for(Ei.lastIndex=0;Ei.exec(e)!==null;){let n=Ei.lastIndex-1,r=yi(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 Oi(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 ki(e,t){let n=e.startsWith(`./`)?e:`./`+e,r=!1;for(let e of t){let t=e.startsWith(`!`);Oi(t?e.slice(1):e).test(n)&&(r=!t)}return r}function Ai(e){let t=[];Ci.lastIndex=0;let n;for(;(n=Ci.exec(e))!==null;){let r=e.indexOf(`{`,n.index+n[0].length-1);if(r<0)continue;let i=Hi(e,r);if(i<0)continue;let a=e.slice(r+1,i),o=[];wi.lastIndex=0;let s;for(;(s=wi.exec(a))!==null;)o.push(s[1]??``);let c=[];Ti.lastIndex=0;let l;for(;(l=Ti.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 ji(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 Mi(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 Ni(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?Pi(n[1].trim(),t):null}return Pi(n[1].trim(),t)}function Pi(e,t){if(e.startsWith(`{`))return Ii(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 Ii(r[1])}return{filterable:[],sortable:[],searchable:[]}}function Fi(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 Ii(e){return{filterable:Fi(e,`filterable`),sortable:Fi(e,`sortable`),searchable:Fi(e,`searchable`)}}async function Li(e,t){let n=t.extensions??ai,r=t.exclude??oi,i=[],a;try{a=await oe(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 Li(a,t)):o.isFile()&&n.some(e=>o.name.endsWith(e))&&i.push(a))}return i}function q(e,t){return _(t,e).split(y).join(`/`)}function Ri(e,t,n){let r=[],i=q(t,n);si.lastIndex=0;let a;for(;(a=si.exec(e))!==null;){let[,e,n,o]=a;r.push({className:o,decorator:e,filePath:t,relativePath:i,isDefault:!!n})}ci.lastIndex=0;let o;for(;(o=ci.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})}li.lastIndex=0;let s;for(;(s=li.exec(e))!==null;){let[,e]=s;r.some(n=>n.className===e&&n.filePath===t)||r.push({className:e,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1})}return r}function zi(e,t,n){let r=[],i=q(t,n),a=new Set;ui.lastIndex=0;let o;for(;(o=ui.exec(e))!==null;){let[e,n,s]=o;a.add(e),r.push({name:s,variable:n,filePath:t,relativePath:i})}for(di.lastIndex=0;(o=di.exec(e))!==null;)a.has(o[0])||r.push({name:o[1],variable:null,filePath:t,relativePath:i});return r}function Bi(e,t,n,r,i=new Map){let a=[];if(r.length===0)return a;let o=q(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);vi.lastIndex=0;let d;for(;(d=vi.exec(u))!==null;){let n=d[1],s=d.index,c=vi.lastIndex-1,l=yi(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=bi(u,l+1);if(!h)continue;let{methodName:g,endPos:_}=h;vi.lastIndex=_;let v=Ni(u.slice(s,_),e),y=ji(f,`body`),b=ji(f,`query`),x=ji(f,`params`),S=ji(f,`response`),C=i.get(r.className)??``,ee=C?Si(C,m):m;a.push({controller:r.className,method:g,httpMethod:n.toUpperCase(),path:m,pathParams:xi(ee),queryFilterable:v?.filterable??null,querySortable:v?.sortable??null,querySearchable:v?.searchable??null,bodySchema:y?{identifier:y,source:Mi(e,y)}:null,querySchema:b?{identifier:b,source:Mi(e,b)}:null,paramsSchema:x?{identifier:x,source:Mi(e,x)}:null,responseSchema:S?{identifier:S,source:Mi(e,S)}:null,filePath:t,relativePath:o,controllerIsDefaultExport:r.isDefault,mountedPath:ee})}}return a}function Vi(e,t,n){let r=[],i=q(t,n);fi.lastIndex=0;let a;for(;(a=fi.exec(e))!==null;)r.push({name:a[1],filePath:t,relativePath:i});return r}function Hi(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,n){let r=[],i=q(t,n),a=new Set;pi.lastIndex=0;let o;for(;(o=pi.exec(e))!==null;){let n=o[1],s=pi.lastIndex-1,c=yi(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}))}hi.lastIndex=0;let s;for(;(s=hi.exec(e))!==null;){let n=s.index,o=e.indexOf(`{`,n);if(o<0)continue;let c=Hi(e,o);if(c<0)continue;let l=e.slice(o+1,c),u=gi.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 Wi(e,t,n){let r=[],i=q(t,n),a=new Set;mi.lastIndex=0;let o;for(;(o=mi.exec(e))!==null;){let n=mi.lastIndex-1,s=yi(e,n);if(s<0)continue;let c=e.slice(n+1,s),l=/\bkey\s*:\s*['"`]([^'"`]+)['"`]/.exec(c);if(!l)continue;let u=l[1];a.has(u)||(a.add(u),r.push({key:u,exportName:o[1]??null,filePath:t,relativePath:i}))}return r}function Gi(e,t,n){let r=[],i=q(t,n);_i.lastIndex=0;let a;for(;(a=_i.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=Hi(e,t);if(n>=0){let r=e.slice(t+1,n);o=Ki(r,`description`),s=Ki(r,`example`)}}}r.push({name:n,description:o,example:s,filePath:t,relativePath:i})}return r}function Ki(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`?`
2471
- `:t===`t`?` `:t===`r`?`\r`:t)}const qi=[`src/config/index.ts`,`src/config/env.ts`,`src/config.ts`,`src/env.ts`];async function Ji(e,t){let n=t===`src/env.ts`?qi:[t];for(let t of n){let n=v(e,t),r;try{r=await w(n,`utf-8`)}catch{continue}if(!(!/\bdefineEnv\s*\(/.test(r)&&!/\bfrom(Zod|Valibot|Yup)\s*\(/.test(r))&&/export\s+default\b/.test(r)&&!/export\s+default\s+loadEnvFromSchema\s*\(/.test(r))return{filePath:n,relativePath:q(n,e)}}return null}function Yi(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}const Xi=new Set([`Controller`,`Service`,`Repository`,`Injectable`,`Component`,`Module`,`Middleware`,`ApiQueryParams`,`Public`,`Roles`,`Cron`,`Cacheable`,`CacheEvict`,`FileUpload`,`Asset`,`Builder`,`PostConstruct`,`PreDestroy`,`Value`,`Inject`,`Autowired`]);function Zi(e){return e.split(y).join(`/`).replace(/\.[mc]?[tj]sx?$/,``)}function Qi(e,t,n){let r=Zi(n);if(t===``)return r===Zi(e);if(t.startsWith(`.`)){let n=Zi(v(f(e),t));return r===n||r===`${n}/index`}let i=t.replace(/^[@~#]\//,``);if(i===t&&t.startsWith(`@`))return!1;let a=Zi(i);return r===a||r.endsWith(`/${a}`)}function $i(e){let t=new Map,n=new Map;for(let t of e)if(t)for(let{controller:e}of t.moduleMounts)n.set(e,(n.get(e)??0)+1);for(let r of e)if(r?.moduleContributors)for(let{controller:e}of r.moduleMounts){if((n.get(e)??0)>1){t.set(e,`ambiguous`);continue}let i=t.get(e);t.set(e,i===void 0?r.moduleContributors:`ambiguous`)}return t}function ea(e,t,n,r=new Map,i=[]){if(n){for(let t of e)t.contextKeys=null;return}let a=new Map;for(let e of t){if(!e.exportName)continue;let t=a.get(e.exportName);t?t.push(e):a.set(e.exportName,[e])}for(let t of e){let e=t.appliedDecorators;if(!e){t.contextKeys=null;continue}let n=new Set,o=!0,s=(e,t)=>{if(t.source===null)return null;let n=(a.get(t.identifier)??[]).filter(n=>Qi(e,t.source,n.filePath));return n.length===1?n[0].key:null};for(let r of e){if(Xi.has(r.identifier))continue;let e=s(t.filePath,r);if(e===null){o=!1;break}n.add(e)}if(o)for(let e of i){if(!e.resolved){o=!1;break}for(let t of e.refs){let r=s(e.filePath,t);if(r===null){o=!1;break}n.add(r)}if(!o)break}if(o){let e=r.get(t.controller);if(e===`ambiguous`)o=!1;else if(e)if(!e.resolved)o=!1;else for(let t of e.refs){let r=s(e.filePath,t);if(r===null){o=!1;break}n.add(r)}}t.contextKeys=o?[...n].toSorted():null}}const ta=/\bcontributors\s*(?::|\()/;function na(e,t,n){return ni(e,t,n)||{...ra(e,t,n),hasNonDecoratorContributors:ta.test(e)}}function ra(e,t,n){let r=Ri(e,t,n);return{classes:r,tokens:zi(e,t,n),injects:Vi(e,t,n),pluginsAndAdapters:Ui(e,t,n),augmentations:Gi(e,t,n),contextKeys:Wi(e,t,n),routes:Bi(e,t,n,r,new Map),moduleMounts:Ai(e),globPatterns:/\.module\.[mc]?[tj]sx?$/.test(t)?Di(e):[],hasNonDecoratorContributors:!1}}async function ia(e,t,n){let r=n?await Fr.signature(e):null;if(n&&r){let t=n.get(e,r);if(t)return n.set(e,r,t),t}let i;try{i=await w(e,`utf-8`)}catch{return null}let a=na(i,e,t);return n&&r&&n.set(e,r,a),a}async function aa(e,t,n){let r=[],i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let t=i++;if(t>=e.length)return;r[t]=await n(e[t],t)}});return await Promise.all(a),r}async function oa(e){let t=(await Li(v(e.root),e)).toSorted(),n=e.cacheDir?await Fr.load(e.cacheDir):null,r=la(t,await aa(t,16,t=>ia(t,e.cwd,n))),i=await Ji(e.cwd,e.envFile??`src/env.ts`);return n&&await n.save(),{...r,env:i}}function sa(e,t,n){let r=n.extensions??ai,i=n.exclude??oi;if(!e.startsWith(t+y)&&e!==t||!r.some(t=>e.endsWith(t)))return!1;let a=_(n.cwd,e);return!i.some(e=>a.includes(e))}async function ca(e,t){if(!e.cacheDir)return oa(e);let n=v(e.root),r=await Fr.load(e.cacheDir),i=r.cachedFiles();if(i.length===0)return oa(e);let a=new Set(t.removed.map(t=>v(e.cwd,t))),o=t.changed.map(t=>v(e.cwd,t)).filter(t=>!a.has(t)&&sa(t,n,e)),s=new Set(o),c=new Set(i);for(let e of s)c.add(e);for(let e of a)c.delete(e);let l=new Map;await aa(o,16,async t=>{if(!c.has(t))return;let n=await Fr.signature(t),i;try{i=await w(t,`utf-8`)}catch{c.delete(t);return}let a=na(i,t,e.cwd);l.set(t,a),n&&r.set(t,n,a)});let u=[...c].toSorted(),d=la(u,u.map(e=>l.get(e)||(r.carry(e),r.peek(e)))),f=await Ji(e.cwd,e.envFile??`src/env.ts`);return await r.save(),{...d,env:f}}function la(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=new Map;for(let e of t)if(e)for(let{controller:t,mountPath:n}of e.moduleMounts)l.has(t)||l.set(t,n);let u=new Map;for(let d=0;d<e.length;d++){let f=t[d];if(f){n.push(...f.classes),i.push(...f.tokens),a.push(...f.injects),o.push(...f.pluginsAndAdapters),s.push(...f.augmentations),c.push(...f.contextKeys),f.globPatterns.length>0&&u.set(e[d],f.globPatterns);for(let e of f.routes){let t=l.get(e.controller);if(t){let n=Si(t,e.path);r.push({...e,pathParams:xi(n),mountedPath:n})}else r.push({...e,mountedPath:e.mountedPath??e.path})}}}ea(r,c,t.some(e=>e?.hasNonDecoratorContributors===!0),$i(t),t.flatMap(e=>e?.appContributors?[e.appContributors]:[]));let d=[];for(let[e,t]of u){if(!/\.module\.[mc]?[tj]sx?$/.test(e)||t.length===0)continue;let r=e.replaceAll(y,`/`),i=r.slice(0,r.lastIndexOf(`/`));for(let a of n){if(a.decorator===`Module`)continue;let n=a.filePath.replaceAll(y,`/`);n.startsWith(i+`/`)&&n!==r&&(ki(n.slice(i.length+1),t)||d.push({className:a.className,filePath:a.filePath,relativePath:a.relativePath,moduleFilePath:e,decorator:a.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)),c.sort((e,t)=>e.key.localeCompare(t.key)||e.relativePath.localeCompare(t.relativePath));let f=Yi(n);return d.sort((e,t)=>e.relativePath.localeCompare(t.relativePath)||e.className.localeCompare(t.className)),{classes:n,routes:r,tokens:i,injects:a,collisions:f,pluginsAndAdapters:o,augmentations:s,contextKeys:c,orphanedClasses:d}}function ua(e){let t=e.lastIndexOf(`.`);return t<=0?{stem:e,ext:``}:{stem:e.slice(0,t),ext:e.slice(t+1)}}function da(e){let t=e.replaceAll(`\\`,`/`),{stem:n,ext:r}=ua(t.slice(t.lastIndexOf(`/`)+1)),i=r||`ts`,a=n.lastIndexOf(`.`);return a>0?`./**/*.${n.slice(a+1)}.${i}`:`./**/*.${i}`}function fa(e){let t=new Set;for(let n of e)t.add(da(n.relativePath));return[...t].toSorted()}function pa(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r){if(t===`\\`){i++;continue}t===r&&(r=null);continue}if(t===`'`||t===`"`||t==="`")r=t;else if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return i}return-1}function ma(e,t,n,r){let i=null;for(let a=n;a<r;a++){let n=e[a];if(i){if(n===`\\`){a++;continue}n===i&&(i=null);continue}if(n===`'`||n===`"`||n==="`")i=n;else if(n===t)return a}return-1}function ha(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r){if(t===`\\`){i++;continue}t===r&&(r=null);continue}if(t===`'`||t===`"`||t==="`")r=t;else if(t===`[`)n++;else if(t===`]`&&(n--,n===0))return i}return-1}function ga(e){let t=/\bimport\.meta\.glob\s*\(/g,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.indexOf(`(`,r.index);if(t<0)continue;let i=pa(e,t);i<0||n.push({start:r.index,open:t,close:i})}return n}function _a(e,t){let n=ga(e);if(n.length===0)return null;let r=n.find(t=>/\beager\s*:\s*true\b/.test(e.slice(t.open,t.close+1)))??n[0],i=e.slice(r.start,r.close+1),a=new Set(Di(i).map(e=>e.startsWith(`!`)?e.slice(1):e)),o=t.filter(e=>!a.has(e));if(o.length===0)return null;let s=o.map(e=>`'${e}'`).join(`, `),c=ma(e,`[`,r.open,r.close);if(c>=0){let t=ha(e,c);if(t<0||t>r.close)return null;let n=e.slice(0,t);return n+(/[[,]\s*$/.test(n)?``:`, `)+s+e.slice(t)}let l=/(['"`])((?:\\.|(?!\1).)*)\1/,u=e.slice(r.open+1,r.close),d=l.exec(u);if(!d)return null;let f=r.open+1+d.index,p=f+d[0].length;return e.slice(0,f)+`[${d[0]}, ${s}]`+e.slice(p)}const J="/* 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",va=new Set([`Service`,`Repository`,`Injectable`,`Component`]);var ya=class extends Error{collisions;constructor(e){super(ba(e)),this.name=`TokenCollisionError`,this.collisions=e}};function ba(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(`
2472
- `)}function xa(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 Sa(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 Ca(e,t,n){let r=new Set,i=[];for(let a of e){if(!va.has(a.decorator))continue;let e=n.has(a.className)?Sa(a):a.className;if(r.has(e))continue;r.add(e);let o=xa(a.filePath,t),s=a.isDefault?`import('${o}').default`:`import('${o}').${a.className}`;i.push(` '${e}': ${s}`)}let a=i.length?i.join(`
2473
- `):" // (no services discovered yet — run `kick g service <name>` to add one)";return`${J}
2474
- declare module '@forinda/kickjs' {
2475
- interface KickJsRegistry {
2476
- ${a}
2477
- }
2478
- }
2479
-
2480
- export {}
2481
- `}function wa(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function Ta(e){let t=[...new Set(e.map(e=>e.key))].toSorted().map(e=>` ${wa(e)?e:JSON.stringify(e)}: true`).join(`
2482
- `);return`${J}
2483
- declare module '@forinda/kickjs' {
2484
- /**
2485
- * Key-only registry of every context key produced by a
2486
- * \`defineContextDecorator\` / \`defineHttpContextDecorator\` in the
2487
- * project. Feeds \`dependsOn\` typo-checking. Value types live in
2488
- * \`ContextMeta\`; this only records that the key exists.
2489
- */
2490
- interface ContextKeys {
2491
- ${t}
2492
- }
2493
- }
2494
-
2495
- export {}
2496
- `}function Ea(e,t,n){if(t.length===0)return`${J}
2497
- // ${n}
2498
- export type ${e} = never
2499
- `;let r=[...new Set(t)].toSorted();return`${J}
2500
- export type ${e} =
2501
- ${r.map(e=>` | '${e}'`).join(`
2502
- `)}
2503
- `}function Da(e,t,n,r){return[...e.filter(e=>va.has(e.decorator)).map(e=>r.has(e.className)?Sa(e):e.className),...t.map(e=>e.name),...n.map(e=>e.name)]}function Oa(e){return e.filter(e=>e.decorator===`Module`).map(e=>e.className)}function ka(e){let t=new Map;for(let n of e)t.has(n.name)||t.set(n.name,n);let n=[...t.values()].toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>` '${e.name}': '${e.kind}'`).join(`
2504
- `);return`${J}
2505
- declare module '@forinda/kickjs' {
2506
- /**
2507
- * Map of every plugin/adapter \`name\` discovered in the project. The
2508
- * value type is the kind tag (\`'plugin'\` or \`'adapter'\`); the
2509
- * \`keyof\` of this interface narrows \`dependsOn\` so misspelled deps
2510
- * become compile errors instead of boot-time \`MissingMountDepError\`.
2511
- */
2512
- interface KickJsPluginRegistry {
2513
- ${n||" // (no plugins/adapters discovered yet — `defineAdapter`/`definePlugin` calls feed this)"}
2514
- }
2515
- }
2516
-
2517
- export {}
2518
- `}function Aa(e){if(e.length===0)return`${J}
2519
- // No augmentations discovered.
2520
- //
2521
- // Plugins advertise augmentable interfaces via:
2522
- //
2523
- // import { defineAugmentation } from '@forinda/kickjs'
2524
- // defineAugmentation('FeatureFlags', {
2525
- // description: 'Feature flag shape consumed by FlagsPlugin',
2526
- // example: '{ beta: boolean; rolloutPercentage: number }',
2527
- // })
2528
- //
2529
- // See \`docs/guide/typegen.md#augmentations\` for the full pattern.
2530
- export {}
2531
- `;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(`
2532
- `))t.push(` * ${n}`);if(e.example){t.push(` * @example`," * ```ts");for(let n of e.example.split(`
2533
- `))t.push(` * ${n}`);t.push(" * ```")}t.push(` * @see ${e.relativePath}`),n.push([`/**`,...t,` */`,`export interface ${e.name}Augmentation {}`].join(`
2534
- `))}return`${J}
2535
- // Catalogue of augmentable interfaces in this project. The interfaces
2536
- // below are documentation only — augment the source-of-truth interfaces
2537
- // in your own \`d.ts\` files (the framework declares the actual types).
2538
-
2539
- ${n.join(`
2540
-
2541
- `)}
2542
- `}const ja=/^(kick\/)?([a-z][\w-]*\/[A-Z]\w*)(\/.+)?(:[a-z][\w-]+(:[a-z][\w-]+)*)?$/;function Ma(e){let t=[];for(let n of e){let e=n.name;e.startsWith(`kickjs.`)||ja.test(e)||t.push({token:e,variable:n.variable,filePath:n.relativePath,reason:"does not match `<scope>/<PascalKey>[/<suffix>][:<instance>]`",suggestion:Na(e)})}return t}function Na(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 Pa(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(!za(e))continue;let a=me(i.glob??`**/*`,{cwd:e,nodir:!0,dot:!1,posix:!0});a.sort();let{pairs:o}=he(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 Fa(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}
2543
- declare module '@forinda/kickjs' {
2544
- /**
2545
- * Map of every typed asset discovered in the project's assetMap.
2546
- * (No assetMap entries discovered yet — declare with
2547
- * \`assetMap: { name: { src: 'src/...' } }\` in kick.config.ts.)
2548
- */
2549
- interface KickAssets {}
2550
- }
2551
-
2552
- export {}
2553
- `;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===Ia){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]=Ia)}return`${t}
2554
- declare module '@forinda/kickjs' {
2555
- /**
2556
- * Map of every typed asset discovered in the project's assetMap.
2557
- * Each leaf is a \`() => string\` thunk that returns the resolved
2558
- * absolute path for the file in the current run mode (dev → src,
2559
- * prod → dist).
2560
- */
2561
- interface KickAssets {
2562
- ${La(n,` `)}
2563
- }
2564
- }
2565
-
2566
- export {}
2567
- `}const Ia=Symbol(`asset-leaf`);function La(e,t){let n=Object.keys(e).toSorted(),r=[];for(let i of n){let n=e[i],a=Ra(i)?i:JSON.stringify(i);n===Ia?r.push(`${t}${a}: () => string`):(r.push(`${t}${a}: {`),r.push(La(n,`${t} `)),r.push(`${t}}`))}return r.join(`
2568
- `)}function Ra(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function za(e){try{return c(e).isDirectory()}catch{return!1}}var Ba=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
2569
- `);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}},Va=k({runTypegen:()=>Ua,sweepStaleTypegen:()=>Ja,watchTypegen:()=>qa,writeTypegenArtifacts:()=>Ka});function Ha(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 Ua(e={}){let{cwd:t,srcDir:n,outDir:r,silent:i,allowDuplicates:a,envFile:o}=Ha(e),s=Date.now(),c={root:n,cwd:t,cacheDir:e.noCache?void 0:v(t,`.kickjs`,`cache`),envFile:o===!1?void 0:o},l=e.changedFiles?await ca(c,e.changedFiles):await oa(c);if(l.collisions.length>0&&!a)throw new ya(l.collisions);let u=Pa(e.assetMap,t),d=[],f=[];if(e.runPlugins!==!1){try{let{runAllPluginTypegens:n}=await Promise.resolve().then(()=>so),{loadKickConfig:r}=await Promise.resolve().then(()=>we);d=await n({cwd:t,config:await r(t),silent:!0,changedFiles:e.changedFiles})}catch(e){if(!i){let t=e instanceof Error?e.message:String(e);console.warn(` kick typegen: plugin pipeline failed (${t}) — continuing`)}}f.push(...await Ka(r,d,i))}let p=Ma(l.tokens),m=Ga(l,u.count,f),h=Date.now()-s;if(!i){let e=r.replace(t+`/`,``),n=m.resolvedCollisions>0?`, ${m.resolvedCollisions} collisions namespaced`:``,i=m.envWritten?`, env typed`:``,a=m.pluginEntries>0?`, ${m.pluginEntries} plugins/adapters`:``,o=m.augmentationEntries>0?`, ${m.augmentationEntries} augmentations`:``,s=m.assetEntries>0?`, ${m.assetEntries} assets`:``;if(console.log(` kick typegen → ${m.serviceTokens} services, ${m.routeEntries} routes, ${m.moduleTokens} modules${a}${o}${s}${i}${n} → ${e} (${h}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}`)}}}return l.orphanedClasses.length>0&&await Wa(l.orphanedClasses,{fix:e.fix??!1,silent:i}),{scan:l,result:m,tokenWarnings:p}}async function Wa(e,{fix:t,silent:n}){let r=new Map;for(let t of e){let e=r.get(t.moduleFilePath)??[];e.push(t),r.set(t.moduleFilePath,e)}if(t){let e=0,t=[];for(let[i,a]of r){let r=fa(a);try{let a=await w(i,`utf-8`),o=_a(a,r);o&&o!==a?(await T(i,o),e++,n||console.log(` kick typegen --fix: patched ${i}\n + ${r.join(`, `)}`)):t.push(i)}catch{t.push(i)}}if(!n&&(e>0&&console.log(` kick typegen --fix: updated ${e} module glob(s) — re-run typegen to pick up the now-loaded classes.`),t.length>0)){console.warn(` kick typegen --fix: could not auto-patch ${t.length} module(s) (no import.meta.glob() call found) — add the patterns by hand:`);for(let e of t){let t=r.get(e)??[];console.warn(` ${e}: ${fa(t).join(`, `)}`)}}return}if(!n){console.warn(` kick typegen: ${e.length} decorated class(es) not matched by any module's import.meta.glob():`);for(let[e,t]of r){for(let e of t)console.warn(` @${e.decorator} ${e.className} (${e.relativePath})`);let n=fa(t);console.warn(` → add to import.meta.glob([...]) in ${e}:`),console.warn(` ${n.map(e=>`'${e}'`).join(`, `)}`)}console.warn(" → or run `kick typegen --fix` to apply these automatically.")}}function Ga(e,t,n){let r=new Set(e.collisions.map(e=>e.className)),i=e.classes.filter(e=>va.has(e.decorator)),a=Da(e.classes,e.tokens,e.injects,r);return{registryEntries:i.length,serviceTokens:new Set(a).size,moduleTokens:Oa(e.classes).length,routeEntries:e.routes.length,pluginEntries:new Set(e.pluginsAndAdapters.map(e=>e.name)).size,augmentationEntries:new Set(e.augmentations.map(e=>e.name)).size,assetEntries:t,envWritten:e.env!==null,written:n,resolvedCollisions:e.collisions.length}}async function Ka(e,t,n){await ae(e,{recursive:!0}),await T(h(f(e),`.gitignore`),`# Auto-generated by kick typegen
2570
- *
2571
- `,`utf-8`);let r=t.filter(e=>e.outFile).map(e=>e.outFile);return await Ja(e,r,t,n),r}async function qa(e={}){let t=Ha(e),{srcDir:n,silent:r,cwd:i}=t,a={...t,allowDuplicates:!0,runPlugins:!1,noCache:e.noCache},o=process.env.KICKJS_WATCH_POLLING===`1`||process.env.KICKJS_WATCH_POLLING===`true`,[{runAllPluginTypegens:s},{loadKickConfig:c}]=await Promise.all([Promise.resolve().then(()=>so),Promise.resolve().then(()=>we)]),l=await c(i),u=async()=>{try{await Ua({...a})}catch(e){if(r)return;if(e instanceof ya)console.error(`
2572
- `+e.message+`
2573
- `);else{let t=e instanceof Error?e.message:String(e);console.error(` kick typegen failed: ${t}`)}}},d=async()=>{try{let e=await s({cwd:i,config:l,silent:!0});await Ka(t.outDir,e,!0)}catch{}};await u(),await d();let{watch:f}=await import(`node:fs`),p=null,m=e=>{e&&/\.(ts|tsx|mts|cts)$/.test(e)&&(e.includes(`.kickjs`)||e.endsWith(`.d.ts`)||(p&&clearTimeout(p),p=setTimeout(()=>{u().then(d)},100)))};if(o){r||console.log(` kick typegen: polling mode (KICKJS_WATCH_POLLING)`);let e=setInterval(()=>{u().then(d)},2e3);return()=>clearInterval(e)}let h;try{h=f(n,{recursive:!0},(e,t)=>{m(t)})}catch(e){r||console.warn(` kick typegen: watch mode unavailable (${e?.message??e}). Falling back to polling.`);let t=setInterval(()=>{u().then(d)},2e3);return()=>clearInterval(t)}return()=>{p&&clearTimeout(p),h.close()}}async function Ja(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 oe(e)}catch{return[]}let o=[];for(let t of a){if(!Ya.has(t)||i.has(t))continue;let n=v(e,t);try{if(!(await ce(n)).isFile())continue;await le(n),o.push(t)}catch{}}return o.length>0&&!r&&console.log(` kick typegen: swept ${o.length} stale file(s): ${o.join(`, `)}`),o}const Ya=new Set([`assets.d.ts`,`env.ts`,`routes.ts`,`registry.d.ts`,`services.d.ts`,`modules.d.ts`,`plugins.d.ts`,`augmentations.d.ts`,`index.d.ts`]),Xa=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function Y(e){return e.parent?.opts()?.dryRun??!1}function X(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(`
2574
- (dry run — no files were written)`),console.log()}async function Za(e){if(!e)try{let e=await j(process.cwd());await Ua({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 Qa=[{name:`module <name>`,description:`REST module (controller, service, DTOs, 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:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{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`}],$a=new Set(Qa.map(e=>e.name.split(` `)[0]));async function eo(){console.log(`
2575
- Built-in generators:
2576
- `);let e=Math.max(...Qa.map(e=>e.name.length));for(let t of Qa)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await j(process.cwd()),n=Ie(t?.plugins??[],t?.commands??[]),r=await hn(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
2577
- Plugin generators:
2578
- `);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(`
2579
- Failed to load:
2580
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function to(e,t,n){let r=await j(process.cwd()),i=A(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Ln(i.repo);t.repo&&Oe(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=Ae(r,process.cwd()),u=i.style??`define`;if(!n&&u===`define`){let e=await wr(v(a),`define`);if(e.length>0){console.error(`\n ${O.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${O.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${O.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 ${O.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${O.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${O.dim(`// kick.config.ts`)}\n ${O.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let d=[];for(let r of e){let e=await Rn({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)}X(d,n),await Za(n)}function no(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 name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | 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,r,i)=>{if(r.list){await eo();return}if(!e||e.length===0){n.help();return}let a=Y(i);M(a);let[o,s,...c]=e;if(o){let e=await j(process.cwd()),n=Ie(e?.plugins??[],e?.commands??[]),i=await mn({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){X(i.files,a);return}if(o!==`module`&&$a.has(o)){console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`),process.exitCode=1;return}}await to(e,r,a)});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 name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | 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=Y(n);M(r),await to(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=Y(n);M(r),X(await Kn({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=Y(n);M(r),X(await qn({name:e,outDir:v(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
2581
- 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=Y(n);M(r);let i=await j(process.cwd()),a=A(i),o=a.dir??`src/modules`;X(await Xn({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.)
2582
- 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=Y(n);M(r);let i=await j(process.cwd()),a=A(i),o=a.dir??`src/modules`;X(await Zn({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
2583
- --type http (default, RequestContext) | bare (ExecutionContext)
2584
- --params "source:string,region:number" → emits the withParams<T>() form
2585
- Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=Y(n);M(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await j(process.cwd()),o=A(a),s=o.dir??`src/modules`;X(await $n({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
2586
- 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=Y(n);M(r);let i=await j(process.cwd()),a=A(i),o=a.dir??`src/modules`;X(await er({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
2587
- 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=Y(n);M(r);let i=await j(process.cwd()),a=A(i),o=a.dir??`src/modules`;X(await tr({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Za(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
2588
- 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=Y(n);M(r);let i=await j(process.cwd()),a=A(i),o=a.dir??`src/modules`;X(await nr({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
2589
- 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=Y(n);M(r);let i=A(await j(process.cwd())),a=i.dir??`src/modules`;X(await Mr({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=Y(n);M(r),X(await Tr({name:e,outDir:v(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
2590
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
2591
- Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
2592
- Optional: append :optional (shell-safe): description:text:optional
2593
- 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=Y(r);M(i),t.length===0&&(console.error(`
2594
- Error: At least one field is required.
2595
- Usage: kick g scaffold <name> <field:type> [field:type...]
2596
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
2597
- Optional: append :optional (shell-safe, no quoting needed)
2598
- `),process.exit(1));let a=await j(process.cwd()),o=A(a),s=n.modulesDir??o.dir??`src/modules`,c=Dr(t),l=Ae(a,process.cwd()),u=await Or({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)`:``}`);X(u,i),await Za(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>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=Y(t);M(n),X(await rr({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 | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=Y(t);M(n);let r=e.only??`all`;if(!Xa.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${Xa.join(` | `)}`),process.exitCode=1;return}X(await ur({outDir:v(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])ro(n,e,t?.projectRoot)}function ro(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=Y(o);M(s);let c=await mn({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&X(c.files,s)})}async function io(e){let t=u.resolve(e.cwd,`.kickjs/types`);e.check||await ae(t,{recursive:!0});let n=new Map,i=e.scan??oa,a=u.resolve(e.cwd,`.kickjs`,`cache`),o=e.scan?void 0:e.changedFiles,s={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 ae(u.dirname(r),{recursive:!0}),await T(r,n,`utf8`)},getScanResult:e=>{let t=ao(e),r=n.get(t);if(!r){let s={cacheDir:a,...e};r=o?ca(s,o):i(s),n.set(t,r)}return r},log:console},c=[],l=[];for(let n of e.plugins){let i=n.outExtension??`.d.ts`,a=u.join(t,`${n.id.replace(/\//g,`__`)}${i}`),o;try{o=await n.generate(s)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});s.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),c.push({id:n.id,status:`error`,outFile:a});continue}if(o===null){c.push({id:n.id,status:`skipped`});continue}let d=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+o+`
2599
- `,f=``;if(r(a)&&(f=await w(a,`utf8`)),f===d){c.push({id:n.id,status:`unchanged`,outFile:a});continue}if(e.check){l.push({id:n.id,outFile:a}),c.push({id:n.id,status:`drifted`,outFile:a});continue}await T(a,d,`utf8`),c.push({id:n.id,status:`written`,outFile:a})}if(l.length>0)throw new Ba(l);return c}function ao(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 oo(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 so=k({applyDisableFilter:()=>oo,runAllPluginTypegens:()=>lo});function co(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function lo(e){let{enabled:t,skipped:n,unknown:r}=oo(Ie([...zc,...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 io({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&co())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof Ba||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}var uo=k({ASSET_MANIFEST_VERSION:()=>1,buildAssets:()=>fo});async function fo(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 po(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)+`
2600
- `,`utf-8`),s(` ✓ wrote manifest → ${_(n,p)} (${Object.keys(d).length} entries)`),{manifestPath:p,entries:u,manifest:f}}async function po(e,t,a,o){let s=v(a,t.src),c=t.dest?v(a,t.dest):h(o,e);if(go(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)||!_o(s))return{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};let l=await pe(t.glob??`**/*`,{cwd:s,nodir:!0,dot:!1,posix:!0});i(c,{recursive:!0});let u={},{pairs:d,collisionGroupsResolved:p}=he(e,[...l].toSorted(),{strategy:t.keys??`auto`}),m=0;for(let{rel:e,key:t}of d){let r=h(s,e),a=h(c,e);u[t]=ho(o,a),!mo(r,a)&&(i(f(a),{recursive:!0}),n(r,a),m++)}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:m},manifestSlice:u}}function mo(e,t){if(!r(t))return!1;try{let n=c(e),r=c(t);return r.size===n.size&&r.mtimeMs>=n.mtimeMs}catch{return!1}}function ho(e,t){return _(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function go(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function _o(e){try{return c(e).isDirectory()}catch{return!1}}function vo(e){let t=new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}function yo(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await Promise.resolve().then(()=>Va)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>so)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await Promise.resolve().then(()=>Va)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await Promise.resolve().then(()=>uo)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=u.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>u.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,d=e=>e.replaceAll(`\\`,`/`),f=c.map(d),p=e=>{let t=d(e);return f.some(e=>t===e||t.startsWith(`${e}/`))},m=vo(e.emitWarning),h=null,g=!1,_=new Set,v=new Set,y=!1,b=!1;function x(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>m.clear(`scan`)).catch(e=>m.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>m.clear(`plugins`)).catch(e=>m.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function S(){let e=y?void 0:{changed:[..._],removed:[...v]},t=b;_.clear(),v.clear(),y=!1,b=!1,x(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!g&&!d(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)y=!0,l&&(b=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=p(t);if(!n&&!r)return;r&&l&&(b=!0),n&&(e===`unlink`?(v.add(t),_.delete(t)):(_.add(t),v.delete(t)))}h&&clearTimeout(h),h=setTimeout(S,r)}},runOnce(){g||x(void 0,l)},dispose(){g=!0,h&&clearTimeout(h),h=null}}}function bo(e){let t=h(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`tsgo`,`tsc`]){let i=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let a of i){let i=h(t,a);if(r(i))return{cmd:i,args:[`--noEmit`],shell:n,kind:e}}}return null}function xo(e){let t=e.spawnFn??te,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function So(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
2601
- `):`${n.slice(0,t).join(`
2602
- `)}\n… ${n.length-t} more line(s)`}function Co(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function wo(e,t,n={}){t&&(process.env.PORT=t);let r=Co(n.polling),i=process.cwd(),a=await j(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ua({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})`)}let c=v(i,a?.typegen?.outDir??`.kickjs/types`);try{await Ka(c,await lo({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(x(l(v(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let d=await u({configFile:v(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),f=n.typecheck??a?.dev?.typecheck??!1,p=null,m=!0;if(f){let e=bo(i);e?p=xo({cwd:i,bin:e,onResult:e=>{d.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?m||(m=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(m=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(So(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let h=yo({cwd:i,config:a,emitWarning:e=>{console.warn(e),d.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>p?.schedule()});d.watcher.on(`add`,e=>h.handleWatchEvent(`add`,e)),d.watcher.on(`unlink`,e=>h.handleWatchEvent(`unlink`,e)),d.watcher.on(`change`,e=>h.handleWatchEvent(`change`,e)),d.watcher.on(`unlinkDir`,e=>h.handleWatchEvent(`unlinkDir`,e)),h.assetSrcRoots.length>0&&d.watcher.add([...h.assetSrcRoots]),await d.listen(),d.printUrls(),console.log(`
2603
- KickJS dev server running (Vite + @forinda/kickjs-vite)
2604
- `),p?.schedule();let g=!1,_=async()=>{if(!g){g=!0,h.dispose(),p?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,_),process.on(`SIGTERM`,_),process.on(`SIGBREAK`,_)}function To(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)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await wo(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
2605
- Error: vite is not installed.
2606
- Run: pnpm add -D vite unplugin-swc
2607
- `):console.error(`
2608
- Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
2609
- Building for production...
2610
- `);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 j(process.cwd()),o=a?.copyDirs??[];if(o.length>0){console.log(`
2611
- 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(`
2612
- Building asset map...`);try{await fo(a,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
2613
- Build complete.
2614
- `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await j(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
2615
- Building asset map...`);try{await fo(e,{cwd:process.cwd()}),console.log(`
2616
- Asset build complete.
2617
- `)}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)),xe(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 wo(e.entry,e.port)}catch(e){console.error(`
2618
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Eo(){try{let e=f(b(import.meta.url));return JSON.parse(a(h(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Do=new Set(Object.values(yt).filter(e=>e.deprecated).map(e=>e.pkg));function Oo(e){let t=h(e,`package.json`);if(!r(t))return[];let n;try{n=JSON.parse(a(t,`utf-8`))}catch{return[]}let i={...n.dependencies,...n.devDependencies};return Object.keys(i).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,o=h(e,`node_modules`,...t.split(`/`),`package.json`);if(r(o))try{n=JSON.parse(a(o,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:i[t]??null,deprecated:Do.has(t)}})}function ko(e){let t=e;for(;;){if(r(h(t,`package.json`)))return t;let e=f(t);if(e===t)return null;t=e}}function Ao(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Eo()}`,``,` System:`,` OS: ${_e()} ${ve()} (${ge()})`,` Node: ${process.version}`],t=ko(process.cwd()),n=t?Oo(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
2619
- `))})}const{bold:Z,dim:Q,green:jo,red:Mo,yellow:No,blue:Po}=O;function Fo(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 Io(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Lo(e,t){try{return await Io(`${e}${t}`)}catch{return null}}async function Ro(e){let[t,n,r,i,a]=await Promise.all([Lo(e,`/health`),Lo(e,`/metrics`),Lo(e,`/routes`),Lo(e,`/container`),Lo(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function zo(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=Q(`─`.repeat(60));if(console.log(),console.log(Z(` KickJS Inspector`)+Q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?jo(`● healthy`):Mo(`● `+n.status);console.log(` ${Z(`Health:`)} ${e}`)}else console.log(` ${Z(`Health:`)} ${Mo(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Mo:r.errorRate>0?No:jo;console.log(` ${Z(`Uptime:`)} ${Fo(r.uptimeSeconds)}`),console.log(` ${Z(`Requests:`)} ${r.requests}`),console.log(` ${Z(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${Q(`(`)}${t(e+`%`)}${Q(`)`)}`)}if(a&&console.log(` ${Z(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${Z(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(Z(` Routes`)),console.log(s),console.log(` ${Q(`METHOD`)} ${Q(`PATH`.padEnd(36))} ${Q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${Wt(e.method)} ${t} ${Po(e.controller)}.${Q(e.handler)}`)}}console.log(s),console.log()}function Bo(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 Ro(r);t.json?console.log(JSON.stringify(e,null,2)):zo(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Mo(` ✖ Could not connect to ${n}`)),console.error(Q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Vo(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function $(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Ho=[{match(e,t){let n=Vo(e,[`config`,`get`])&&$(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&$(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
2620
- registers the env schema with kickjs at module-load time. Without it,
2621
- ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
2622
- and every user-defined key reads as undefined. @Value() may *appear* to
2623
- work via a raw process.env fallback, but Zod coercion and schema defaults
2624
- are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
2625
- import { bootstrap } from '@forinda/kickjs'
2626
- import { modules } from './modules'
2627
- `,codeAfter:`import 'reflect-metadata'
2628
- import './config' // ← add this — registers env schema
2629
- import { bootstrap } from '@forinda/kickjs'
2630
- import { modules } from './modules'
2631
- `,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=$(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return $(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.
2632
- When vitest re-imports your modules across tests, the same class can be
2633
- registered twice and the container throws. The fix is to wipe the
2634
- 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'
2635
- import { Container } from '@forinda/kickjs'
2636
-
2637
- describe('UserController', () => {
2638
- beforeEach(() => Container.reset())
2639
-
2640
- it('does the thing', async () => { /* ... */ })
2641
- })`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Vo(e,[`Module`,`is not a function`])||Vo(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
2642
- pattern instead: a class implements AppModule and exposes routes() that
2643
- returns the controller wiring. This was a deliberate choice — modules
2644
- become explicit values rather than metadata, which makes them easier to
2645
- compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
2646
- import { UserController } from './user.controller'
2647
-
2648
- @Module({
2649
- controllers: [UserController],
2650
- })
2651
- export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
2652
- import { UserController } from './user.controller'
2653
-
2654
- export class UserModule implements AppModule {
2655
- routes(): ModuleRoutes {
2656
- return {
2657
- path: '/users',
2658
- router: buildRoutes(UserController),
2659
- controller: UserController,
2660
- }
2661
- }
2662
- }`,docs:`https://kickjs.app/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
2663
- namespaced shape: KickRoutes.UserController["create"] instead of
2664
- KickRoutes["POST /users"]. The new form is per-controller, per-method,
2665
- and matches the actual class names so refactors propagate via
2666
- rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
2667
- create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
2668
- create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=$(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=$(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
2669
- cluster: { workers: N }, the framework forks N workers, each of which
2670
- spins up its own Vite instance on a separate port. The fix landed in
2671
- v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
2672
- silently skips cluster, with a warning. If you see this on an older
2673
- 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({
2674
- modules,
2675
- cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
2676
- })`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return $(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
2677
- reflect-metadata polyfill. The polyfill must be imported once,
2678
- before any decorator runs. Most projects do this at the top of
2679
- src/index.ts; missing the import causes obscure "design:paramtypes"
2680
- 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
2681
- import './config'
2682
- import { bootstrap } from '@forinda/kickjs'
2683
- import { modules } from './modules'
2684
-
2685
- export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return $(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
2686
- generated a module via \`kick g module foo\` but the routes don't appear,
2687
- the most likely cause is that the module is missing from the exported
2688
- array. The CLI usually wires this automatically, but a hand-edit can
2689
- drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleEntry } from '@forinda/kickjs'
2690
- import { UserModule } from './users/user.module'
2691
- import { TaskModule } from './tasks/task.module' // ← was this missing?
2692
-
2693
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}}];function Uo(e,t){let n=null;for(let r of Ho){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 Wo(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.
2694
- export OPENAI_API_KEY="sk-..."
2695
-
2696
- 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:
2697
- kick add ai
2698
-
2699
- Or manually:
2700
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Go(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Ko((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 Go(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://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
2701
- `)}function Ko(e){let t=[e,qo(e),Jo(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Yo(t))return t}catch{continue}return null}function qo(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Jo(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 Yo(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 Xo(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 $o(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
2702
-
2703
- Pass a message as a positional arg, --message flag, or pipe via stdin:
2704
- kick explain "config.get returned undefined"
2705
- pnpm test 2>&1 | kick explain
2706
- `),process.exit(1));let r=ts(),i=Uo(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
2707
- `);return}if(i){ns(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
2708
- `),process.exit(2)),rs(n,!1),process.exit(2));let a=await Wo({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Zo(a),null,2)+`
2709
- `),process.exit(a.kind===`ok`?0:2)),Qo(n,a),process.exit(a.kind===`ok`?0:2)})}function Zo(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 Qo(e,t){if(t.kind===`ok`){ns(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${as(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${is(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${as(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function $o(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:es()}function es(){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 ts(){let e=process.cwd();return{cwd:e,hasFile:t=>r(v(e,t))}}function ns(e,t,n,r=!1){let i=as(e.trim(),200),a=r?`AI-generated — verify before applying`:os(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${is(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${is(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${is(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${is(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
2710
- `)}function rs(e,t){let n=as(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.
2711
- When @forinda/kickjs-ai ships its provider implementations,
2712
- this command will call the configured LLM with the error +
2713
- project context and return a structured fix.
2714
-
2715
- `):process.stdout.write(` No known-issue matched. Things you can try:
2716
-
2717
- 1. Check the framework docs for the error keywords:
2718
- https://kickjs.app/
2719
-
2720
- 2. Re-run with --ai to fall back to an LLM (requires
2721
- @forinda/kickjs-ai with a configured provider):
2722
- kick explain --ai "<your error>"
2723
-
2724
- 3. File an issue with the error text:
2725
- https://github.com/forinda/kick-js/issues/new
2726
-
2727
- `)}function is(e,t){return e.split(`
2728
- `).map(e=>`${t}${e}`).join(`
2729
- `)}function as(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function os(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function ss(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(cs),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(ls)}function cs(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=te(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 ls(e){let t=process.cwd(),n=us(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)+`
2730
- `,`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 us(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 ds(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=ps(t,`tsx`);i||(console.error(`
2731
- Error: tsx not found. Install it: pnpm add -D tsx
2732
- `),process.exit(1));let a=fs(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=ee(o,[],{cwd:t,execPath:i,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{c(o)}catch{}}})}function fs(e,t){return`
2733
- import 'reflect-metadata'
2734
-
2735
- // Prevent bootstrap() from starting the HTTP server
2736
- process.env.KICK_TINKER = '1'
2737
-
2738
- console.log('\\n 🔧 KickJS Tinker')
2739
- console.log(' Loading: ${t}\\n')
2740
-
2741
- // Load core
2742
- let Container, Logger, HttpException, HttpStatus
2743
- try {
2744
- const core = await import('@forinda/kickjs')
2745
- Container = core.Container
2746
- Logger = core.Logger
2747
- HttpException = core.HttpException
2748
- HttpStatus = core.HttpStatus
2749
- } catch {
2750
- console.error(' Error: @forinda/kickjs not found.')
2751
- console.error(' Install it: pnpm add @forinda/kickjs\\n')
2752
- process.exit(1)
2753
- }
2754
-
2755
- // Load entry to trigger decorator registration
2756
- try {
2757
- await import('${x(e).href}')
2758
- } catch (err) {
2759
- console.warn(' Warning: ' + err.message)
2760
- console.warn(' Container may be partially initialized.\\n')
2761
- }
2762
-
2763
- const container = Container.getInstance()
2764
-
2765
- // Start REPL
2766
- const repl = await import('node:repl')
2767
- const server = repl.start({ prompt: 'kick> ', useGlobal: true })
2768
-
2769
- server.context.container = container
2770
- server.context.Container = Container
2771
- server.context.resolve = (token) => container.resolve(token)
2772
- server.context.Logger = Logger
2773
- server.context.HttpException = HttpException
2774
- server.context.HttpStatus = HttpStatus
2775
-
2776
- console.log(' Available globals:')
2777
- console.log(' container — DI container instance')
2778
- console.log(' resolve(T) — shorthand for container.resolve(T)')
2779
- console.log(' Container, Logger, HttpException, HttpStatus')
2780
- console.log()
2781
-
2782
- server.on('exit', () => {
2783
- console.log('\\n Goodbye!\\n')
2784
- process.exit(0)
2785
- })
2786
- `}function ps(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 ms(e,t){let n=RegExp(`^\\s*${V(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]!==`
2787
- `;)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]===`
2788
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function hs(e,t){let n=Vn(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=ms(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${V(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 gs(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=z(t),o=L(t),s=i?B(a):a,c=h(n,s);if(!await Ge(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await F({message:O.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
2789
- Cancelled.
2790
- `);return}await se(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=h(n,`index.ts`);if(await Ge(l)){let e=await w(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${V(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${V(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=hs(e,o),e=e.replace(/\n{3,}/g,`
2791
-
2792
- `),e!==t&&(await T(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function _s(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=A(await j(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await gs({name:n,modulesDir:v(r),force:t.force,pluralize:i})})}function vs(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;if(e===`kickjs-schema`||e===`schema`)return`kickjs-schema`;console.warn(` kick typegen: unknown --schema-validator '${e}' (supported: 'zod', 'kickjs-schema', 'false'). Falling back to project config.`)}}function ys(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function bs(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: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=rn(process.cwd()),n=await j(t);if(e.list){let{mergeCliPlugins:e}=await Promise.resolve().then(()=>Le),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Rc),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(`
2793
- Registered typegen plugins:
2794
- `);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=vs(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=ys(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await qa(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{await Ua(a);let r=await lo({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1),e.check||await Ka(v(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof ya?console.error(`
2795
- `+e.message+`
2796
- `):e instanceof Ba?console.error(`
2797
- `+e.message+`
2798
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function xs(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(...xs(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Ss(e){try{return a(e,`utf-8`)}catch{return``}}const Cs=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function ws(e,t){let n=Ss(h(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Cs.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 Ts(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 Es(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 Ds(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Os(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 ks(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 As(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 js(e){let t=xs(h(e,`src`)).map(e=>Ss(e)),n=[],r=ws(e,t);r&&n.push(r);let i=Ts(t);i&&n.push(i);let a=Es(t);a&&n.push(a);let o=Ds();o&&n.push(o);let s=Os(t);return s&&n.push(s),n.push(ks(t)),n.push(As(t)),n}function Ms(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
2799
- Usage: kick check --deploy
2800
-
2801
- Available checks:
2802
- --deploy Audit for production readiness (security, config, best practices)
2803
- `);return}let t=process.cwd();Kt(`KickJS Deploy Check`);let n=Zt();n.start(`Scanning project...`);let r=js(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)I.message(`${Gt(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?O.red(`${a} critical`):`${a} critical`,o>0?O.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(P(O.red(`${l} — fix critical issues before deploying`)),process.exit(1)):P(O.green(`${l} — looking good!`))})}function Ns(e){try{return JSON.parse(a(e,`utf-8`))}catch{return null}}function Ps(e){try{return a(e,`utf-8`)}catch{return null}}function Fs(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function Is(e){let t=h(e,`tsconfig.json`);if(r(t))return Ls(t,new Set)}function Ls(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Ps(e);if(n===null)return null;let r=Fs(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={};for(let n of i){if(typeof n!=`string`)continue;let r=Rs(f(e),n);if(!r)continue;let i=Ls(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Rs(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return zs(v(e,t));let n=e;for(;;){let e=zs(h(n,`node_modules`,t));if(e)return e;let r=f(n);if(r===n)break;n=r}return null}function zs(e){if(r(e)){try{if(c(e).isDirectory()){let t=h(e,`tsconfig.json`);return r(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return r(t)?t:null}function Bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Vs(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
2804
- Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Hs(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function Us(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const Ws={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function Gs(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=Ws[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function Ks(e){if(!e.pkg||!Js(e.cwd))return null;let t=xt[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const qs=2e3;function Js(e){let t=h(e,`src`);if(!r(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,i=[t],a=0;for(;i.length>0&&a<qs;){let e=i.pop(),t;try{t=o(e,{withFileTypes:!0})}catch{continue}for(let r of t){if(a>=qs)break;let t=h(e,r.name);if(r.isDirectory()){r.name!==`node_modules`&&i.push(t);continue}if(/\.(ts|tsx|mts|cts)$/.test(r.name)&&(a++,n.test(Ps(t)??``)))return!0}}return!1}function Ys(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.
2805
- Install it: pnpm add reflect-metadata
2806
- Then import it at the top of src/index.ts:
2807
-
2808
- import 'reflect-metadata'
2809
- // ... rest of bootstrap`}}function Xs(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function Zs(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>h(e.cwd,t)).filter(e=>r(e)).filter(e=>/\bloadEnv\s*\(/.test(Ps(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>h(e.cwd,t)).find(e=>r(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let i=Ps(n)??``,a=f(n),o=[];for(let e of t){let t=_(a,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);o.push(n,r);let i=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(i){let e=`@/`+i[1],t=e.replace(/\/index$/,``);o.push(e,t)}}let s=-1;for(let e of new Set(o)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${Bs(e)}['"]`,`m`),n=i.match(t);n&&n.index!==void 0&&(s===-1||n.index<s)&&(s=n.index)}let c=i.search(/\bbootstrap\s*\(/),l=t.map(t=>_(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return s===-1?{name:`env wiring`,status:`fail`,message:l,fix:`An env-init file (${l}) calls \`loadEnv(...)\` but \`${_(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${_(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:c!==-1&&s>c?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function Qs(e,t=$s){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=o(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=h(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=c(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const $s=2e3;function ec(e){let t=h(e.cwd,`.kickjs`,`types`);if(!r(t))return null;let n=Qs(t);if(n===0)return null;let i=Date.now()-n,a=Math.floor(i/6e4);return a>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${a} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:a===0?`just now`:`${a}m ago`}}const tc=[()=>Vs(),Hs,Us,Gs,Ks,Ys,Xs,Zs,ec];async function nc(e,t={}){let n={cwd:e,pkg:Ns(h(e,`package.json`)),tsconfig:Is(e),runtime:t.runtime??`express`},r=[...tc,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function rc(e){switch(e){case`pass`:return O.green(`✔`);case`warn`:return O.yellow(`⚠`);case`fail`:return O.red(`✖`)}}function ic(e){let t=rc(e.status),n=e.message?` ${O.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function ac(e){return e.split(`
2810
- `).map(e=>` ${O.dim(`→`)} ${e}`).join(`
2811
- `)}function oc(e){return e?.doctor?.checks??[]}function sc(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=oc(await j(e)),n=await St(e);Kt(`KickJS Doctor`);let r=await nc(e,{extraChecks:t,runtime:n});for(let e of r)I.message(ic(e)),e.fix&&e.status!==`pass`&&I.message(ac(e.fix));let i=r.filter(e=>e.status===`pass`).length,a=r.filter(e=>e.status===`warn`).length,o=r.filter(e=>e.status===`fail`).length,s=[O.green(`${i} passed`),a>0?O.yellow(`${a} warning${a===1?``:`s`}`):`${a} warnings`,o>0?O.red(`${o} error${o===1?``:`s`}`):`${o} errors`].join(`, `);o>0?(P(`${s} — fix the errors above before running the app`),process.exit(1)):P(a>0?`${s} — review the warnings`:O.green(`${s} — your environment looks good`))})}function cc(e){return e.optsWithGlobals().dryRun??!1}function lc(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.
2812
- Direction defaults to \`modules.style\` from kick.config (or "define").
2813
- --target define|class Override the migration direction.
2814
- --apply Apply the changes (default: dry-run preview).
2815
- --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=cc(t)||!e.apply;M(n),e.experimental||(console.error(`
2816
- `+O.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
2817
- The regex-based rewrite handles the shapes our templates produce.
2818
- Hand-rolled modules with non-standard structures may be skipped.
2819
- Always commit before running with --apply.
2820
- `),process.exit(1));let r=A(await j(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 ${O.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=O.dim(`→ ${a}`),s=n?O.dim(`(dry-run)`):O.bold(`(applying)`);console.log(`\n ${O.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${O.dim(i)}\n`);let c=e.backup!==!1&&!n,l=await Cr(i,{dryRun:n,target:a,backup:c});if(l.backupDir){let e=l.backupDir;console.log(` ${O.green(`✓`)} backup: ${O.dim(e)}\n ${O.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${O.dim(`(--no-backup — skipping snapshot)`)}\n`);let u=0,d=0;for(let e of l.files)if(e.status===`migrated`)u++,console.log(` ${O.green(`✓`)} ${e.path}`);else{d++;let t=O.dim(`(${e.reason??`skipped`})`);console.log(` ${O.dim(`-`)} ${e.path} ${t}`)}if(console.log(),l.indexStatus===`migrated`)console.log(` ${O.green(`✓`)} ${l.indexPath}`);else if(l.indexStatus===`skipped`){let e=O.dim(`(${l.indexReason??`skipped`})`);console.log(` ${O.dim(`-`)} ${l.indexPath} ${e}`)}else console.log(` ${O.dim(`-`)} ${l.indexPath} ${O.dim(`(not found)`)}`);let f=n?O.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${O.bold(String(u))} migrated, ${O.bold(String(d))} skipped${f}\n`)})}const uc=()=>({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 j(e.cwd);if(!t?.assetMap)return null;let n=Pa(t.assetMap,e.cwd);return n.count===0?null:Fa(n)}}),dc="/* 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 fc(e,t,n,r={}){if(e.length===0)return`${dc}
2821
- // (no routes discovered yet — annotate a controller method with
2822
- // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
2823
- declare global {
2824
- // eslint-disable-next-line @typescript-eslint/no-namespace
2825
- namespace KickRoutes {
2826
- // Always present so \`createClient<KickRoutes.Api>\` compiles before the
2827
- // first route exists (fresh project / pre-controller typegen runs).
2828
- interface Api {}
2829
- }
2830
-
2831
- /** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
2832
- type KickApi = KickRoutes.Api
2833
- }
2834
-
2835
- /** Empty until the first route exists — see kick typegen. */
2836
- export const kickRpc = {} as const
2837
- `;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=gc(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??mc(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=hc(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${pc(e)}`,` }`)}n.push(` }`),l.push(n.join(`
2838
- `))}let u=[],d=new Set,f=new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;if(d.has(t)){r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`);continue}d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`)}let p=[` interface Api {`,...u,` }`].join(`
2839
- `);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=yc(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
2840
- `)}\n },`)}let g=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...m,`} as const`].join(`
2841
- `),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=vc(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
2842
- `)+`
2843
- `:``,b=_c(a)+y,x=l.join(`
2844
- `);return`${dc}${b}
2845
- declare global {
2846
- // eslint-disable-next-line @typescript-eslint/no-namespace
2847
- namespace KickRoutes {
2848
- ${x}
2849
- }
2850
-
2851
- /** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
2852
- type KickApi = KickRoutes.Api
2853
- }
2854
-
2855
- ${g}
2856
- `}function pc(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function mc(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 hc(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 gc(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=vc(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 _c(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(`
2857
- `)+`
2858
- `}function vc(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}function yc(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const bc=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:xc(e),cwd:e.cwd,envFile:Sc(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=u.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return fc(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function xc(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Sc(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Cc(e,t,n=`zod`){if(!e)return null;let r=_(f(t),e.filePath).split(y).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
2859
- // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
2860
- // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
2861
-
2862
- // Importing the schema as a type lets us infer its shape without
2863
- // pulling in any runtime code. \`Awaited<>\` strips an accidental
2864
- // Promise wrap on dynamic-imported defaults.
2865
- import type _envSchema from '${r}'
2866
-
2867
- ${n===`kickjs-schema`?`type _Raw = import('@forinda/kickjs-schema').InferSchemaOutput<typeof _envSchema>
2868
- type _Resolved = { [K in keyof _Raw]: _Raw[K] }
2869
- `:``}// Local type alias — interfaces can only \`extend\` an identifier,
2870
- // not an inline import expression, so we resolve the schema's
2871
- // inferred shape into a named type first.
2872
- type _KickEnvShape = ${n===`kickjs-schema`?`_Resolved`:`import('zod').infer<typeof _envSchema>`}
2873
-
2874
- declare global {
2875
- /**
2876
- * Typed environment registry. Augmented from \`${e.relativePath}\`
2877
- * so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
2878
- * all type-safe and autocomplete.
2879
- */
2880
- interface KickEnv extends _KickEnvShape {}
2881
-
2882
- // eslint-disable-next-line @typescript-eslint/no-namespace
2883
- namespace NodeJS {
2884
- /**
2885
- * Narrow \`process.env\` so known keys exist as \`string\` (the raw
2886
- * pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
2887
- * the schema's transforms internally; access \`process.env\` directly
2888
- * only when you need the raw string. Unknown keys still resolve to
2889
- * \`string | undefined\` via the base @types/node declaration.
2890
- */
2891
- interface ProcessEnv extends Record<keyof KickEnv, string> {}
2892
- }
2893
- }
2894
-
2895
- export {}
2896
- `}const wc=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Ec(e);if(t===!1)return null;let n=await e.getScanResult({root:Tc(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=u.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Cc(n.env,i,r)}});function Tc(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ec(e){return e.config?.typegen?.envFile}function Dc(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Oc(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function kc(e){return{root:Dc(e),cwd:e.cwd,envFile:Oc(e)}}const Ac=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(kc(e)),n=u.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ca(t.classes,n,r)}}),jc=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(kc(e)),n=new Set(t.collisions.map(e=>e.className));return Ea(`ServiceToken`,Da(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Mc=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return Ea(`ModuleToken`,Oa((await e.getScanResult(kc(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Nc=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ka((await e.getScanResult(kc(e))).pluginsAndAdapters)}}),Pc=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Aa((await e.getScanResult(kc(e))).augmentations)}}),Fc=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(kc(e));return t.contextKeys.length===0?null:Ta(t.contextKeys)}}),Ic={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Lc=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=Ic[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
2897
- `)}});var Rc=k({builtinCliPlugins:()=>zc});const zc=[E({name:`kick/init`,register:$t}),E({name:`kick/generate`,register:no}),E({name:`kick/run`,register:To}),E({name:`kick/info`,register:Ao}),E({name:`kick/inspect`,register:Bo}),E({name:`kick/add`,register:Mt}),E({name:`kick/list`,register:jt}),E({name:`kick/explain`,register:Xo}),E({name:`kick/mcp`,register:ss}),E({name:`kick/tinker`,register:ds}),E({name:`kick/remove`,register:_s}),E({name:`kick/typegen`,register:bs}),E({name:`kick/check`,register:Ms}),E({name:`kick/doctor`,register:sc}),E({name:`kick/codemod`,register:lc}),E({name:`kick/registry`,typegens:[Ac()]}),E({name:`kick/services`,typegens:[jc()]}),E({name:`kick/modules`,typegens:[Mc()]}),E({name:`kick/plugins`,typegens:[Nc()]}),E({name:`kick/augmentations`,typegens:[Pc()]}),E({name:`kick/context`,typegens:[Fc()]}),E({name:`kick/assets`,typegens:[uc()]}),E({name:`kick/routes`,typegens:[bc()]}),E({name:`kick/env`,typegens:[wc()]}),E({name:`kick/runtime`,typegens:[Lc()]})],Bc=f(b(import.meta.url)),Vc=JSON.parse(a(h(Bc,`..`,`package.json`),`utf-8`));async function Hc(){let e=new t;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(Vc.version);let n=rn(process.cwd()),r=n,i=await j(r)??{},a=Ie([...zc,...i.plugins??[]],i.commands??[]);await a.register(e,{cwd:r,projectRoot:n,config:i,log:e=>console.log(e)}),Se(e,{...i,commands:a.commands}),e.showHelpAfterError();let o=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(o)}Hc().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{N as a,Lt as i,ir as n,Ht as r,Va as t};
11
+ import{r as e,t}from"./builtins-DR3wYkm4.mjs";import{r as n}from"./config-BQy8iVib.mjs";import{n as r}from"./plugin-C3PeTJQb.mjs";import{t as i}from"./project-root-CtnL9FBb.mjs";import{Command as a}from"commander";import{readFileSync as o}from"node:fs";import{dirname as s,join as c}from"node:path";import{fileURLToPath as l}from"node:url";function u(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}d(e,r)}}function d(t,n){let r=t.command(n.name).description(n.description);if(n.aliases)for(let e of n.aliases)r.alias(e);r.allowUnknownOption(!0),r.argument(`[args...]`,`Additional arguments passed to the command`),r.action(t=>{let r=t.join(` `),i=Array.isArray(n.steps)?n.steps:[n.steps];for(let t of i){let i=r?`${t} ${r}`:t;console.log(` $ ${i}`);try{e(i)}catch{console.error(` Command failed: ${n.name}`),process.exitCode=1;return}}})}const f=s(l(import.meta.url)),p=JSON.parse(o(c(f,`..`,`package.json`),`utf-8`));async function m(){let e=new a;e.name(`kick`).description(`KickJS A production-grade, decorator-driven Node.js framework`).version(p.version);let o=i(process.cwd()),s=o,c=await n(s)??{},l=r([...t,...c.plugins??[]],c.commands??[]);await l.register(e,{cwd:s,projectRoot:o,config:c,log:e=>console.log(e)}),u(e,{...c,commands:l.commands}),e.showHelpAfterError();let d=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(d)}m().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{};