@forinda/kickjs-cli 5.11.0 → 6.0.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 (37) hide show
  1. package/dist/agent-docs-Dmku65k2.mjs +12 -0
  2. package/dist/agent-docs-Dmku65k2.mjs.map +1 -0
  3. package/dist/{builtins-DOQNq7JT.mjs → builtins-G49e_Qsj.mjs} +2 -2
  4. package/dist/cli.mjs +151 -1376
  5. package/dist/config-DdtRfl33.mjs +13 -0
  6. package/dist/config-DdtRfl33.mjs.map +1 -0
  7. package/dist/doctor-SUUDEI1J.mjs +1221 -0
  8. package/dist/doctor-SUUDEI1J.mjs.map +1 -0
  9. package/dist/index.d.mts +663 -853
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +2 -2
  12. package/dist/{plugin-CcuuVb2P.mjs → plugin-Dg0Lk2Lp.mjs} +3 -3
  13. package/dist/{plugin-CcuuVb2P.mjs.map → plugin-Dg0Lk2Lp.mjs.map} +1 -1
  14. package/dist/{project-docs-CjnHf0Wd.mjs → project-docs-C-dA6-TO.mjs} +6 -36
  15. package/dist/project-docs-C-dA6-TO.mjs.map +1 -0
  16. package/dist/{project-root-SRoIXPwv.mjs → project-root-so4F5DRN.mjs} +3 -3
  17. package/dist/{project-root-SRoIXPwv.mjs.map → project-root-so4F5DRN.mjs.map} +1 -1
  18. package/dist/{rolldown-runtime-BOORVFz_.mjs → rolldown-runtime-DrKbExWn.mjs} +1 -1
  19. package/dist/run-plugins-B2_AT35s.mjs +636 -0
  20. package/dist/run-plugins-B2_AT35s.mjs.map +1 -0
  21. package/dist/typegen-5MX2F5iL.mjs +114 -0
  22. package/dist/typegen-5MX2F5iL.mjs.map +1 -0
  23. package/dist/types-C5PH0h7Z.mjs +11 -0
  24. package/package.json +13 -13
  25. package/dist/agent-docs-BuCTT-9g.mjs +0 -12
  26. package/dist/agent-docs-BuCTT-9g.mjs.map +0 -1
  27. package/dist/config-DW9HQc2u.mjs +0 -13
  28. package/dist/config-DW9HQc2u.mjs.map +0 -1
  29. package/dist/doctor-Cin9GYv9.mjs +0 -2076
  30. package/dist/doctor-Cin9GYv9.mjs.map +0 -1
  31. package/dist/project-docs-CjnHf0Wd.mjs.map +0 -1
  32. package/dist/run-plugins-fsoovaEF.mjs +0 -976
  33. package/dist/run-plugins-fsoovaEF.mjs.map +0 -1
  34. package/dist/typegen-CSLwAvgI.mjs +0 -114
  35. package/dist/typegen-CSLwAvgI.mjs.map +0 -1
  36. package/dist/types-BZ1L4hvm.mjs +0 -12
  37. package/dist/types-BZ1L4hvm.mjs.map +0 -1
@@ -1,976 +0,0 @@
1
- /**
2
- * @forinda/kickjs-cli v5.11.0
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import{_ as e,b as t,c as n,d as r,f as i,g as a,h as o,l as s,m as c,p as l,s as u,u as d,v as f,y as p}from"./project-docs-CjnHf0Wd.mjs";import{C as m,S as h,T as g,_,a as v,b as y,c as b,d as ee,f as te,g as ne,h as re,i as ie,l as ae,m as oe,p as se,r as ce,u as le,v as ue,w as x,x as de,y as fe}from"./doctor-Cin9GYv9.mjs";import{a as S,i as C,o as pe,t as me}from"./config-DW9HQc2u.mjs";import{t as he}from"./project-root-SRoIXPwv.mjs";import{n as w}from"./types-BZ1L4hvm.mjs";import{n as ge}from"./agent-docs-BuCTT-9g.mjs";import{n as _e}from"./plugin-CcuuVb2P.mjs";import{a as ve,c as ye,d as be,f as xe,h as Se,i as Ce,l as we,m as Te,o as Ee,p as De,r as Oe,s as ke,t as T,u as Ae}from"./typegen-CSLwAvgI.mjs";import E,{basename as je,dirname as D,isAbsolute as Me,join as O,relative as k,resolve as A,sep as Ne}from"node:path";import{cpSync as Pe,existsSync as j,mkdirSync as M,readFileSync as N,readdirSync as Fe,rmSync as Ie,statSync as Le,writeFileSync as Re}from"node:fs";import{copyFile as ze,mkdir as Be,readFile as P,readdir as Ve,rm as He,stat as Ue,writeFile as F}from"node:fs/promises";import{execSync as We,fork as Ge,spawn as Ke,spawnSync as qe}from"node:child_process";import{pathToFileURL as I}from"node:url";import{glob as Je}from"glob";import{groupAssetKeys as Ye}from"@forinda/kickjs";import{arch as Xe,platform as Ze,release as Qe}from"node:os";import{detectCompositeReferences as $e,generate as et,migrateDown as tt,migrateLatest as nt,migrateRollback as rt,migrateStatus as it,migrateUp as at,renderSchemaSource as ot,resolveDbConfig as st}from"@forinda/kickjs-db";const ct={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},"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}};function L(e,t=process.cwd()){let n=t;for(;;){if(j(A(n,e)))return n;let t=D(n);if(t===n)return null;n=t}}function lt(){return L(`pnpm-lock.yaml`)?`pnpm`:L(`yarn.lock`)?`yarn`:L(`bun.lockb`)||L(`bun.lock`)?`bun`:L(`package-lock.json`)?`npm`:null}function ut(){let e=process.cwd();for(;e;){let t=A(e,`package.json`);if(j(t))try{let e=JSON.parse(N(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(me.includes(t))return t}}catch{}let n=D(e);if(n===e)return null;e=n}return null}async function dt(e){if(e&&me.includes(e))return{pm:e,source:`flag`};let t=await C(process.cwd());if(t?.packageManager&&me.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=ut();if(n)return{pm:n,source:`package.json`};let r=lt();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function ft(e){let{pm:t}=await dt(e);return t}function pt(e=!1){let t=Object.entries(ct),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
12
- Core packages (always installed by \`kick new\`):
13
- `);for(let e of r)console.log(a(e));if(e){console.log(`
14
- Optional packages (add as needed):
15
- `);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(`
16
- Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function mt(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=>{pt(!!e.all)})}function ht(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){pt(!!t.all);return}let{pm:n,source:r}=await dt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=ct[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
17
- `),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{We(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{We(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
18
- `)}})}const gt=[{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 | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).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)=>{n(`KickJS — Create a new project`);let o=!!(t.yes||t.nonInteractive);e||=o?`my-api`:await c({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let l;if(e===`.`?(l=A(`.`),e=je(l)):l=A(t.directory||e),j(l)){let n=Fe(l);if(n.length>0){if(t.force)s.warn(`Clearing existing files in ${l}`);else if(o){s.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{s.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)s.message(` - ${e}`);if(n.length>5&&s.message(` ... and ${n.length-5} more`),!await u({message:a.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of n)Ie(A(l,e),{recursive:!0,force:!0})}}let f=t.template;f||=o?`minimal`:await i({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let p=t.pm;p||=o?await ft(void 0):await i({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let m=t.repo;m||(o?m=`inmemory`:(m=await i({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),m===`custom`&&(m=await c({message:`Custom repository name`,defaultValue:`custom`}))));let h=t.schema;h||=o?`zod`:await i({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(h)||(s.warn(`Unknown --schema "${h}", falling back to zod.`),h=`zod`);let g;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();g=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else g=o?[]:await d({message:`Select packages to include`,options:[...gt],required:!1});let _;_=t.git===void 0?o?!0:await u({message:`Initialize git repository?`,initialValue:!0}):t.git;let v;v=t.install===void 0?o?!0:await u({message:`Install dependencies?`,initialValue:!0}):t.install,await b({name:e,directory:l,packageManager:p,initGit:_,installDeps:v,template:f,defaultRepo:m,packages:g,schemaLib:h}),r(`Done! Next steps: ${a.cyan(`cd ${e} && ${p} dev`)}`)})}async function vt(e){let{name:n,outDir:r}=e,i=x(n),a=g(n),o=[],s=O(r,`${i}.plugin.ts`);return await t(s,`import {
19
- definePlugin,
20
- type AppAdapter,
21
- type AppModuleEntry,
22
- type Container,
23
- type ContributorRegistrations,
24
- } from '@forinda/kickjs'
25
-
26
- /**
27
- * Configuration for the ${a} plugin.
28
- *
29
- * Plugins typically take a small config object so callers can tune
30
- * behaviour at bootstrap time. Keep the shape narrow — anything
31
- * derived from the environment should be read inside the build
32
- * function via getEnv(), not forced onto the caller.
33
- */
34
- export interface ${a}PluginConfig {
35
- // Add your plugin config here, e.g.:
36
- // enabled?: boolean
37
- // apiKey?: string
38
- }
39
-
40
- /**
41
- * ${a} plugin — built via \`definePlugin()\` so callers get the
42
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
43
- *
44
- * A plugin bundles DI bindings, modules, adapters, and middleware
45
- * into one object that can be added to \`bootstrap({ plugins })\`.
46
- *
47
- * Lifecycle order (each hook is optional — delete the ones you don't
48
- * need and keep only the surface your plugin actually uses):
49
- *
50
- * 1. \`register(container)\` — runs before user modules load. Use
51
- * it to bind services that modules depend on.
52
- * 2. \`modules()\` — plugin modules load before user modules.
53
- * 3. \`adapters()\` — plugin adapters mount before user adapters.
54
- * 4. \`middleware()\` — plugin middleware runs before user middleware.
55
- * 5. \`contributors()\` — Context Contributors merged into every route.
56
- * 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
57
- * 7. \`shutdown()\` — runs on graceful shutdown.
58
- *
59
- * @example
60
- * \`\`\`ts
61
- * import { bootstrap } from '@forinda/kickjs'
62
- * import { ${a}Plugin } from './plugins/${i}.plugin'
63
- *
64
- * export const app = await bootstrap({
65
- * modules,
66
- * plugins: [${a}Plugin({ /* config overrides *\\/ })],
67
- * })
68
- * \`\`\`
69
- */
70
- export const ${a}Plugin = definePlugin<${a}PluginConfig>({
71
- name: '${a}Plugin',
72
- defaults: {
73
- // Default config values go here
74
- },
75
- build: (_config, { name: _name }) => ({
76
- /**
77
- * Register DI bindings before modules load.
78
- * Use \`container.registerInstance(TOKEN, value)\` for singletons
79
- * and \`container.registerFactory(TOKEN, () => ...)\` for lazy
80
- * constructions.
81
- */
82
- register(_container: Container): void {
83
- // Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
84
- },
85
-
86
- /**
87
- * Return modules this plugin contributes to the app. These load
88
- * before user modules, so plugin controllers and services are
89
- * available for user code to \`@Autowired\`.
90
- *
91
- * Accepts both \`defineModule\`-style instances (call the factory:
92
- * \`ExampleModule()\`) and legacy \`class … implements AppModule\`
93
- * constructors.
94
- */
95
- modules(): AppModuleEntry[] {
96
- return [
97
- // ExampleModule(),
98
- ]
99
- },
100
-
101
- /**
102
- * Return adapter instances to be added to the application.
103
- * Plugin adapters mount before user adapters.
104
- */
105
- adapters(): AppAdapter[] {
106
- return [
107
- // MyAdapter({ ... }),
108
- ]
109
- },
110
-
111
- /**
112
- * Return Express middleware entries to be added to the global
113
- * pipeline. Plugin middleware runs before user-defined middleware.
114
- */
115
- middleware(): unknown[] {
116
- return [
117
- // helmet(),
118
- // myCustomMiddleware(_config),
119
- ]
120
- },
121
-
122
- /**
123
- * Return Context Contributors to merge into every route's pipeline.
124
- * Plugins contribute at the same \`'adapter'\` precedence level as
125
- * adapters — overrideable per-route at the method / class / module
126
- * level. See https://forinda.github.io/kick-js/guide/context-decorators
127
- *
128
- * Delete this hook if your plugin doesn't ship typed per-request values.
129
- */
130
- contributors(): ContributorRegistrations {
131
- return [
132
- // Example:
133
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
134
- // declare module '@forinda/kickjs' { interface ContextMeta { ${i}: { foo: string } } }
135
- // const Load${a} = defineHttpContextDecorator({
136
- // key: '${i}',
137
- // resolve: (ctx) => ({ foo: ctx.req.headers['x-${i}'] as string }),
138
- // })
139
- // return [Load${a}.registration]
140
- ]
141
- },
142
-
143
- /**
144
- * Called after the application has fully bootstrapped. Use this
145
- * for post-startup work like logging, health checks, or warming
146
- * a cache. Runs once per process.
147
- */
148
- async onReady(_container: Container): Promise<void> {
149
- // const log = _container.resolve(Logger)
150
- // log.info('${a} plugin ready')
151
- },
152
-
153
- /**
154
- * Called during graceful shutdown. Clean up any long-lived
155
- * resources this plugin owns (connections, timers, subscriptions).
156
- */
157
- async shutdown(): Promise<void> {
158
- // Example: await this.connection?.close()
159
- },
160
- }),
161
- })
162
- `),o.push(s),o}function yt(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):[]}function bt(e){switch(e){case`string`:return`''`;case`number`:return`0`;case`boolean`:return`false`;default:return null}}async function xt(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=x(n),c=g(n),l=e.key??m(n),u=Array.isArray(e.params)?e.params:yt(e.params),d=oe({type:`contributor`,outDir:e.outDir,moduleName:r,modulesDir:i,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!0}),f=o===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,p=o===`http`?`RequestContext`:`ExecutionContext`,h=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
163
- `)}\n}\n`:``,_=u.length>0?`${f}.withParams<${c}Params>()({`:`${f}({`,v=u.map(e=>({name:e.name,def:bt(e.type)})).filter(e=>e.def!==null).map(e=>` ${e.name}: ${e.def},`),y=u.length>0?` paramDefaults: {\n${v.join(`
164
- `)}\n },\n`:``,b=u.length>0?`(ctx, _deps, params)`:`(ctx)`,ee=u.length>0?` // \`params\` is typed as ${c}Params (call-site overrides merged onto paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,te=`import { ${f} } from '@forinda/kickjs'
165
- import type { ${p} } from '@forinda/kickjs'
166
-
167
- /**
168
- * ${c} context contributor (${o}).
169
- *
170
- * Computes a value and writes it to \`ctx.set('${l}', …)\` before a
171
- * matched handler runs — the typed, ordered alternative to
172
- * \`@Middleware()\` when the only job is to populate \`ctx\`.
173
- *
174
- * Apply per method/class, or register globally via
175
- * \`bootstrap({ contributors: [${c}] })\`:
176
- *
177
- * @${c}${u.length>0?`({ ${u[0]?.name}: … })`:``}
178
- * @Get('/')
179
- * handler(ctx: ${p}) {
180
- * return ctx.json(ctx.get('${l}'))
181
- * }
182
- */
183
-
184
- // Register '${l}' so \`ctx.get('${l}')\` is typed and \`dependsOn: ['${l}']\`
185
- // is checked. Replace \`unknown\` with the resolved value's real type.
186
- // (For a key you only depend on — no value type needed — declare it in
187
- // \`interface ContextKeys\` instead.)
188
- declare module '@forinda/kickjs' {
189
- interface ContextMeta {
190
- '${l}': unknown
191
- }
192
- }
193
- ${h}
194
- export const ${c} = ${_}
195
- key: '${l}',
196
- ${y} resolve: ${b} => {
197
- ${ee}
198
- // TODO: compute and return the value written to ctx.set('${l}', …)
199
- throw new Error("${c} contributor: resolve() not implemented")
200
- },
201
- })
202
- `,ne=O(d,`${s}.contributor.ts`);return await t(ne,te),[ne]}async function St(e){let n=O(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return j(n)&&!e.force&&!await u({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
203
- Skipped — existing kick.config.ts preserved.`),[]):(await t(n,`import { defineConfig } from '@forinda/kickjs-cli'
204
-
205
- export default defineConfig({
206
- modules: {
207
- dir: '${r}',
208
- repo: '${i}',
209
- pluralize: true,
210
- },
211
-
212
- typegen: {
213
- schemaValidator: 'zod',
214
- },
215
-
216
- commands: [
217
- {
218
- name: 'test',
219
- description: 'Run tests with Vitest',
220
- steps: 'npx vitest run',
221
- },
222
- {
223
- name: 'format',
224
- description: 'Format code with Prettier',
225
- steps: 'npx prettier --write src/',
226
- },
227
- {
228
- name: 'format:check',
229
- description: 'Check formatting without writing',
230
- steps: 'npx prettier --check src/',
231
- },
232
- {
233
- name: 'ci:check',
234
- description: 'Run typecheck + format check',
235
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
236
- aliases: ['verify'],
237
- },
238
- ],
239
- })
240
- `),[n])}function R(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 z(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=R(e,r);return i===-1?null:e.slice(r+1,i)}function B(e,t,n){let r=` `.repeat(n);return e.split(`
241
- `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`);return r+e.replace(n,``)}).join(`
242
- `)}function Ct(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 wt(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 Tt(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=R(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=z(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=z(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=z(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Ct(s),p=``;return l&&(p+=` register(container) {${B(l,4,6)} },\n\n`),u&&(p+=` contributors() {${B(u,4,6)} },\n\n`),p+=` routes() {${B(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
243
- name: '${r}',
244
- build: () => ({
245
- ${p}
246
- }),
247
- })`}${c}`}}function Et(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=R(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]===`
248
- `||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=R(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=z(m,/register\s*\(([^)]*)\)\s*\{/),g=z(m,/contributors\s*\(\s*\)\s*\{/),_=z(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=wt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${B(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${B(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${B(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
249
- ${y}
250
- }
251
- `}${u}`}}function Dt(e,t){return t===`class`?Et(e):Tt(e)}function Ot(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 kt(e){let t=[];return await n(A(e),0),t;async function n(e,r){let i;try{i=await Ve(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=O(e,a),o;try{o=await Ue(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function At(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Ve(e)}catch{return}await Be(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=O(e,a),o=O(t,a),s;try{s=await Ue(i)}catch{continue}s.isDirectory()?await r(i,o):(await ze(i,o),n++)}}}function jt(e){return O(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function Mt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await kt(e),s=await P(O(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=jt(r),await At(e,c));let l=[];for(let e of o){let t=Dt(await P(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await F(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=O(e,`index.ts`),d=null;try{d=await P(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Ot(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await F(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Nt(e,t){let n=await kt(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 P(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Pt(e){let{name:n,outDir:r}=e,i=g(n),a=x(n),o=m(n),s=e.queue??`${a}-queue`,c=[];return await(async(e,n)=>{let i=O(r,e);await t(i,n),c.push(i)})(`${a}.job.ts`,`import { Inject } from '@forinda/kickjs'
252
- import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
253
-
254
- /**
255
- * ${i} Job Processor
256
- *
257
- * Decorators:
258
- * @Job(queueName) — marks this class as a job processor for a queue
259
- * @Process(jobName?) — marks a method as the handler for a specific job type
260
- * - Without a name: handles all jobs in the queue
261
- * - With a name: handles only jobs matching that name
262
- *
263
- * To add jobs to this queue from a service or controller:
264
- * @Inject(QUEUE_MANAGER) private queue: QueueService
265
- * await this.queue.add('${s}', '${o}', { ... })
266
- */
267
- @Job('${s}')
268
- export class ${i}Job {
269
- @Process()
270
- async handle(job: { name: string; data: any; id?: string }) {
271
- console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
272
-
273
- // TODO: Implement job logic here
274
- // Example:
275
- // await this.emailService.send(job.data.to, job.data.subject, job.data.body)
276
- }
277
-
278
- @Process('${o}.priority')
279
- async handlePriority(job: { name: string; data: any; id?: string }) {
280
- console.log(\`Priority job: \${job.name}\`, job.data)
281
- // Handle high-priority variant of this job
282
- }
283
- }
284
- `),c}const Ft={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 It(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=Ft[a];if(!o){let e=[...Object.keys(Ft),`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 Lt(e){let{name:n,fields:r,modulesDir:i,noEntity:a,noTests:o,repo:s=`inmemory`,tokenScope:c=`app`,style:l=`define`}=e,u=e.pluralize!==!1,d=x(n),f=g(n);m(n);let p=u?de(d):d,_=u?h(f):f,v=O(i,p),y=[],b=async(e,n)=>{let r=O(v,e);await t(r,n),y.push(r)};await b(`${d}.module.ts`,Gt(f,d,p,l)),await b(`constants.ts`,Vt(f,r)),await b(`presentation/${d}.controller.ts`,Kt(f,d,p,_)),await b(`application/dtos/create-${d}.dto.ts`,Rt(f,r)),await b(`application/dtos/update-${d}.dto.ts`,zt(f,r)),await b(`application/dtos/${d}-response.dto.ts`,Bt(f,r));let ee=Yt(f,d,p,_);for(let e of ee)await b(`application/use-cases/${e.file}`,e.content);return await b(`domain/repositories/${d}.repository.ts`,qt(f,d,c)),await b(`domain/services/${d}-domain.service.ts`,Jt(f,d)),s===`inmemory`&&await b(`infrastructure/repositories/in-memory-${d}.repository.ts`,Ht(f,d,r)),a||(await b(`domain/entities/${d}.entity.ts`,Ut(f,d,r)),await b(`domain/value-objects/${d}-id.vo.ts`,Wt(f))),await ne(i,f,p,d,l),y}function Rt(e,t){return`import { z } from 'zod'
285
-
286
- export const create${e}Schema = z.object({
287
- ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
288
- `)}
289
- })
290
-
291
- export type Create${e}DTO = z.infer<typeof create${e}Schema>
292
- `}function zt(e,t){return`import { z } from 'zod'
293
-
294
- export const update${e}Schema = z.object({
295
- ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
296
- `)}
297
- })
298
-
299
- export type Update${e}DTO = z.infer<typeof update${e}Schema>
300
- `}function Bt(e,t){return`export interface ${e}ResponseDTO {
301
- id: string
302
- ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
303
- `)}
304
- createdAt: string
305
- updatedAt: string
306
- }
307
- `}function Vt(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
308
-
309
- export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
310
- filterable: [${i}],
311
- sortable: [${a}],
312
- searchable: [${o}],
313
- }
314
- `}function Ht(e,t,n){return`import { randomUUID } from 'node:crypto'
315
- import { Repository, HttpException } from '@forinda/kickjs'
316
- import type { ParsedQuery } from '@forinda/kickjs'
317
- import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
318
- import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
319
- import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
320
- import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
321
-
322
- @Repository()
323
- export class InMemory${e}Repository implements I${e}Repository {
324
- private store = new Map<string, ${e}ResponseDTO>()
325
-
326
- async findById(id: string): Promise<${e}ResponseDTO | null> {
327
- return this.store.get(id) ?? null
328
- }
329
-
330
- async findAll(): Promise<${e}ResponseDTO[]> {
331
- return Array.from(this.store.values())
332
- }
333
-
334
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
335
- const all = Array.from(this.store.values())
336
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
337
- return { data, total: all.length }
338
- }
339
-
340
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
341
- const now = new Date().toISOString()
342
- const entity: ${e}ResponseDTO = {
343
- id: randomUUID(),
344
- ${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
345
- `)}
346
- createdAt: now,
347
- updatedAt: now,
348
- }
349
- this.store.set(entity.id, entity)
350
- return entity
351
- }
352
-
353
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
354
- const existing = this.store.get(id)
355
- if (!existing) throw HttpException.notFound('${e} not found')
356
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
357
- this.store.set(id, updated)
358
- return updated
359
- }
360
-
361
- async delete(id: string): Promise<void> {
362
- if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
363
- this.store.delete(id)
364
- }
365
- }
366
- `}function Ut(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
367
-
368
- interface ${e}Props {
369
- id: ${e}Id
370
- ${n.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
371
- `)}
372
- createdAt: Date
373
- updatedAt: Date
374
- }
375
-
376
- export class ${e} {
377
- private constructor(private props: ${e}Props) {}
378
-
379
- static create(params: { ${n.filter(e=>!e.optional).map(e=>`${e.name}: ${e.tsType}`).join(`; `)} }): ${e} {
380
- const now = new Date()
381
- return new ${e}({
382
- id: ${e}Id.create(),
383
- ${n.filter(e=>!e.optional).map(e=>` ${e.name}: params.${e.name},`).join(`
384
- `)}
385
- createdAt: now,
386
- updatedAt: now,
387
- })
388
- }
389
-
390
- static reconstitute(props: ${e}Props): ${e} {
391
- return new ${e}(props)
392
- }
393
-
394
- get id(): ${e}Id { return this.props.id }
395
- ${n.map(e=>` get ${e.name}(): ${e.tsType}${e.optional?` | undefined`:``} {
396
- return this.props.${e.name}
397
- }`).join(`
398
- `)}
399
- get createdAt(): Date { return this.props.createdAt }
400
- get updatedAt(): Date { return this.props.updatedAt }
401
-
402
- toJSON() {
403
- return {
404
- id: this.props.id.toString(),
405
- ${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
406
- `)}
407
- createdAt: this.props.createdAt.toISOString(),
408
- updatedAt: this.props.updatedAt.toISOString(),
409
- }
410
- }
411
- }
412
- `}function Wt(e){return`import { randomUUID } from 'node:crypto'
413
-
414
- export class ${e}Id {
415
- private constructor(private readonly value: string) {}
416
-
417
- static create(): ${e}Id { return new ${e}Id(randomUUID()) }
418
-
419
- static from(id: string): ${e}Id {
420
- if (!id || id.trim().length === 0) throw new Error('${e}Id cannot be empty')
421
- return new ${e}Id(id)
422
- }
423
-
424
- toString(): string { return this.value }
425
- equals(other: ${e}Id): boolean { return this.value === other.value }
426
- }
427
- `}function Gt(e,t,n,r=`define`){let i=`import { ${e}Controller } from './presentation/${t}.controller'
428
- import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
429
- import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
430
-
431
- // Eagerly load decorated classes so @Service()/@Repository() decorators
432
- // register in the DI container before the application bootstraps.
433
- import.meta.glob(
434
- ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
435
- { eager: true },
436
- )`,a=` /**
437
- * Declare HTTP routes for this module. Return value shape:
438
- *
439
- * - \`path\` — URL prefix for this route set.
440
- * - \`controller\` — Controller class (also drives OpenAPI).
441
- * - \`version\` — Optional. Overrides the app-wide API version.
442
- *
443
- * Return an array to mount multiple route sets:
444
- *
445
- * return [
446
- * { path: '/${n}', version: 1, controller: ${e}V1Controller },
447
- * { path: '/${n}', version: 2, controller: ${e}V2Controller },
448
- * ]
449
- */`;return r===`class`?`import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
450
- ${i}
451
-
452
- export class ${e}Module implements AppModule {
453
- /**
454
- * Bind the repository token to its concrete implementation.
455
- * Decorator-managed classes (@Service, @Controller, @Repository) are
456
- * registered automatically — only token-to-impl bindings need to live here.
457
- */
458
- register(container: Container): void {
459
- container.registerFactory(
460
- ${e.toUpperCase()}_REPOSITORY,
461
- () => container.resolve(InMemory${e}Repository),
462
- )
463
- }
464
-
465
- ${a.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
466
- routes(): ModuleRoutes {
467
- return {
468
- path: '/${n}',
469
- controller: ${e}Controller,
470
- }
471
- }
472
- }
473
- `:`import { defineModule } from '@forinda/kickjs'
474
- ${i}
475
-
476
- export const ${e}Module = defineModule({
477
- name: '${e}Module',
478
- build: () => ({
479
- /**
480
- * Bind the repository token to its concrete implementation.
481
- * Decorator-managed classes (@Service, @Controller, @Repository) are
482
- * registered automatically — only token-to-impl bindings need to live here.
483
- */
484
- register(container) {
485
- container.registerFactory(
486
- ${e.toUpperCase()}_REPOSITORY,
487
- () => container.resolve(InMemory${e}Repository),
488
- )
489
- },
490
-
491
- ${a}
492
- routes() {
493
- return {
494
- path: '/${n}',
495
- controller: ${e}Controller,
496
- }
497
- },
498
- }),
499
- })
500
- `}function Kt(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
501
- import { ApiTags } from '@forinda/kickjs-swagger'
502
- import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
503
- import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
504
- import { List${r}UseCase } from '../application/use-cases/list-${n}.use-case'
505
- import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
506
- import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
507
- import { create${e}Schema } from '../application/dtos/create-${t}.dto'
508
- import { update${e}Schema } from '../application/dtos/update-${t}.dto'
509
- import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
510
-
511
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${e}Controller['<method>']>\`
512
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
513
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
514
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
515
-
516
- @Controller()
517
- export class ${e}Controller {
518
- @Autowired() private readonly create${e}UseCase!: Create${e}UseCase
519
- @Autowired() private readonly get${e}UseCase!: Get${e}UseCase
520
- @Autowired() private readonly list${r}UseCase!: List${r}UseCase
521
- @Autowired() private readonly update${e}UseCase!: Update${e}UseCase
522
- @Autowired() private readonly delete${e}UseCase!: Delete${e}UseCase
523
-
524
- @Get('/')
525
- @ApiTags('${e}')
526
- @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
527
- async list(ctx: Ctx<KickRoutes.${e}Controller['list']>) {
528
- return ctx.paginate(
529
- (parsed) => this.list${r}UseCase.execute(parsed),
530
- ${e.toUpperCase()}_QUERY_CONFIG,
531
- )
532
- }
533
-
534
- @Get('/:id')
535
- @ApiTags('${e}')
536
- async getById(ctx: Ctx<KickRoutes.${e}Controller['getById']>) {
537
- const result = await this.get${e}UseCase.execute(ctx.params.id)
538
- if (!result) return ctx.notFound('${e} not found')
539
- ctx.json(result)
540
- }
541
-
542
- @Post('/', { body: create${e}Schema, name: 'Create${e}' })
543
- @ApiTags('${e}')
544
- async create(ctx: Ctx<KickRoutes.${e}Controller['create']>) {
545
- const result = await this.create${e}UseCase.execute(ctx.body)
546
- ctx.created(result)
547
- }
548
-
549
- @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
550
- @ApiTags('${e}')
551
- async update(ctx: Ctx<KickRoutes.${e}Controller['update']>) {
552
- const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
553
- ctx.json(result)
554
- }
555
-
556
- @Delete('/:id')
557
- @ApiTags('${e}')
558
- async remove(ctx: Ctx<KickRoutes.${e}Controller['remove']>) {
559
- await this.delete${e}UseCase.execute(ctx.params.id)
560
- ctx.noContent()
561
- }
562
- }
563
- `}function qt(e,t,n){return`import { createToken } from '@forinda/kickjs'
564
- import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
565
- import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
566
- import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
567
- import type { ParsedQuery } from '@forinda/kickjs'
568
-
569
- export interface I${e}Repository {
570
- findById(id: string): Promise<${e}ResponseDTO | null>
571
- findAll(): Promise<${e}ResponseDTO[]>
572
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
573
- create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
574
- update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
575
- delete(id: string): Promise<void>
576
- }
577
-
578
- /**
579
- * Collision-safe DI token bound to \`I${e}Repository\`.
580
- * \`container.resolve(${e.toUpperCase()}_REPOSITORY)\` and
581
- * \`@Inject(${e.toUpperCase()}_REPOSITORY)\` both return the typed
582
- * interface — no manual generic, no \`any\` cast.
583
- *
584
- * The \`'${n}/'\` prefix matches the project scope so
585
- * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
586
- * adopters must NOT use the reserved \`'kick/'\` namespace.
587
- */
588
- export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
589
- `}function Jt(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
590
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
591
-
592
- @Service()
593
- export class ${e}DomainService {
594
- constructor(
595
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
596
- ) {}
597
-
598
- async ensureExists(id: string): Promise<void> {
599
- const entity = await this.repo.findById(id)
600
- if (!entity) throw HttpException.notFound('${e} not found')
601
- }
602
- }
603
- `}function Yt(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
604
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
605
- import type { Create${e}DTO } from '../dtos/create-${t}.dto'
606
-
607
- @Service()
608
- export class Create${e}UseCase {
609
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
610
- async execute(dto: Create${e}DTO) { return this.repo.create(dto) }
611
- }
612
- `},{file:`get-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
613
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
614
-
615
- @Service()
616
- export class Get${e}UseCase {
617
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
618
- async execute(id: string) { return this.repo.findById(id) }
619
- }
620
- `},{file:`list-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
621
- import type { ParsedQuery } from '@forinda/kickjs'
622
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
623
-
624
- @Service()
625
- export class List${r}UseCase {
626
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
627
- async execute(parsed: ParsedQuery) { return this.repo.findPaginated(parsed) }
628
- }
629
- `},{file:`update-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
630
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
631
- import type { Update${e}DTO } from '../dtos/update-${t}.dto'
632
-
633
- @Service()
634
- export class Update${e}UseCase {
635
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
636
- async execute(id: string, dto: Update${e}DTO) { return this.repo.update(id, dto) }
637
- }
638
- `},{file:`delete-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
639
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
640
-
641
- @Service()
642
- export class Delete${e}UseCase {
643
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
644
- async execute(id: string) { return this.repo.delete(id) }
645
- }
646
- `}]}async function Xt(e){let{name:n,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=x(n),s=g(n),c=[],l;if(e.outDir)l=A(e.outDir);else if(r){let e=x(r),t=a?de(e):e;l=A(O(i??`src/modules`,t,`__tests__`))}else l=A(`src/__tests__`);let u=O(l,`${o}.test.ts`);return await t(u,`import { describe, it, expect, beforeEach } from 'vitest'
647
- import { Container } from '@forinda/kickjs'
648
-
649
- describe('${s}', () => {
650
- beforeEach(() => {
651
- Container.reset()
652
- })
653
-
654
- it('should be defined', () => {
655
- // TODO: Import and test your class/function here
656
- expect(true).toBe(true)
657
- })
658
-
659
- it('should handle the happy path', async () => {
660
- // TODO: Set up test data and assertions
661
- expect(true).toBe(true)
662
- })
663
-
664
- it('should handle edge cases', async () => {
665
- // TODO: Test error handling, empty inputs, etc.
666
- expect(true).toBe(true)
667
- })
668
- })
669
- `),c.push(u),c}const Zt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function V(e){return e.parent?.opts()?.dryRun??!1}function H(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(`
670
- (dry run — no files were written)`),console.log()}async function Qt(e){if(!e)try{let e=await C(process.cwd());await T({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 $t=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`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`}];async function en(){console.log(`
671
- Built-in generators:
672
- `);let e=Math.max(...$t.map(e=>e.name.length));for(let t of $t)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await C(process.cwd()),n=_e(t?.plugins??[],t?.commands??[]),r=await ie(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
673
- Plugin generators:
674
- `);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(`
675
- Failed to load:
676
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function tn(e,t,n){let r=await C(process.cwd()),i=S(r),o=t.modulesDir??i.dir??`src/modules`,s=t.repo??fe(i.repo),c=t.pattern??r?.pattern??`ddd`,l=t.pluralize===!1?!1:i.pluralize??!0,u=pe(r,process.cwd()),d=i.style??`define`;if(!n&&d===`define`){let e=await Nt(A(o),`define`);if(e.length>0){console.error(`\n ${a.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${a.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${a.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 ${a.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${a.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${a.dim(`// kick.config.ts`)}\n ${a.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let f=[];for(let r of e){let e=await ue({name:r,modulesDir:A(o),noEntity:t.entity===!1,noTests:t.tests===!1,repo:s,minimal:t.minimal,force:t.force,pattern:c,dryRun:n,pluralize:l,prismaClientPath:i.prismaClientPath,tokenScope:u,style:i.style});f.push(...e)}H(f,n),await Qt(n)}function nn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await en();return}if(!e||e.length===0){n.help();return}let a=V(i);p(a);let[o,s,...c]=e;if(o){let e=await C(process.cwd()),n=_e(e?.plugins??[],e?.commands??[]),i=await v({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){H(i.files,a);return}}await tn(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 implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=V(n);p(r),await tn(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=V(n);p(r),H(await re({name:e,outDir:A(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=V(n);p(r),H(await vt({name:e,outDir:A(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
677
- 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=V(n);p(r);let i=await C(process.cwd()),a=S(i),o=a.dir??`src/modules`;H(await se({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.)
678
- 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=V(n);p(r);let i=await C(process.cwd()),a=S(i),o=a.dir??`src/modules`;H(await te({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)
679
- --type http (default, RequestContext) | bare (ExecutionContext)
680
- --params "source:string,region:number" → emits the withParams<T>() form
681
- 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=V(n);p(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 C(process.cwd()),o=S(a),s=o.dir??`src/modules`;H(await xt({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
682
- 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=V(n);p(r);let i=await C(process.cwd()),a=S(i),o=a.dir??`src/modules`;H(await ee({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
683
- 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=V(n);p(r);let i=await C(process.cwd()),a=S(i),o=a.dir??`src/modules`;H(await le({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Qt(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
684
- 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=V(n);p(r);let i=await C(process.cwd()),a=S(i),o=a.dir??`src/modules`;H(await ae({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
685
- 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=V(n);p(r);let i=S(await C(process.cwd())),a=i.dir??`src/modules`;H(await Xt({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=V(n);p(r),H(await Pt({name:e,outDir:A(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
686
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
687
- Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
688
- Optional: append :optional (shell-safe): description:text:optional
689
- 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=V(r);p(i),t.length===0&&(console.error(`
690
- Error: At least one field is required.
691
- Usage: kick g scaffold <name> <field:type> [field:type...]
692
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
693
- Optional: append :optional (shell-safe, no quoting needed)
694
- `),process.exit(1));let a=await C(process.cwd()),o=S(a),s=n.modulesDir??o.dir??`src/modules`,c=It(t),l=pe(a,process.cwd()),u=a?.pattern??`ddd`;u!==`ddd`&&(console.error(`\n Error: 'kick g scaffold' currently only supports the DDD pattern.\n Detected project pattern: '${u}'.\n Workarounds:\n - Run 'kick g module ${e}' for the ${u} layout (no fields), then add fields manually.\n - Override the pattern for this scaffold by setting kick.config.ts pattern: 'ddd'.\n`),process.exit(1));let d=await Lt({name:e,fields:c,modulesDir:A(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)`:``}`);H(d,i),await Qt(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=V(t);p(n),H(await St({outDir:A(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=V(t);p(n);let r=e.only??`all`;if(!Zt.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${Zt.join(` | `)}`),process.exitCode=1;return}H(await ge({outDir:A(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])rn(n,e,t?.projectRoot)}function rn(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=V(o);p(s);let c=await v({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&H(c.files,s)})}function an(e,t,n){let r=qe(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}async function on(e){let t=E.resolve(e.cwd,`.kickjs/types`);await Be(t,{recursive:!0});let n=new Map,r=e.scan??Se,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(I(e).href)},async writeFile(t,n){let r=E.resolve(e.cwd,t);await Be(E.dirname(r),{recursive:!0}),await F(r,n,`utf8`)},getScanResult:e=>{let t=sn(e),i=n.get(t);return i||(i=r(e),n.set(t,i)),i},log:console},a=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,o=E.join(t,`${n.id.replace(/\//g,`__`)}${r}`),s;try{s=await n.generate(i)}catch(e){let t=e instanceof Error?e.message:String(e);i.log.error(` ${n.id}: typegen failed (${t}) — keeping previous output`),a.push({id:n.id,status:`error`,outFile:o});continue}if(s===null){a.push({id:n.id,status:`skipped`});continue}let c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+s+`
695
- `,l=``;if(j(o)&&(l=await P(o,`utf8`)),l===c){a.push({id:n.id,status:`unchanged`,outFile:o});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${o})`);await F(o,c,`utf8`),a.push({id:n.id,status:`written`,outFile:o})}return a}function sn(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 cn(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))}}async function U(e){let{enabled:t,skipped:n,unknown:r}=cn(_e([...Hr,...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 on({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function ln(e,t){let{cwd:n,silent:r=!1}=t,i=t.distDir??e?.build?.outDir??`dist`,a=e?.assetMap;if(!a||Object.keys(a).length===0)return null;let o=r?()=>{}:console.log,s=A(n,i);M(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await un(e,t,n,s);c.push(r.entrySummary),Object.assign(l,r.manifestSlice),o(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let u={version:1,entries:l},d=O(s,`.kickjs-assets.json`);return Re(d,JSON.stringify(u,null,2)+`
696
- `,`utf-8`),o(` ✓ wrote manifest → ${k(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function un(e,t,n,r){let i=A(n,t.src),a=t.dest?A(n,t.dest):O(r,e);if(fn(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:k(n,a),filesCopied:0},manifestSlice:{}};if(!j(i)||!pn(i))return{entrySummary:{namespace:e,src:t.src,dest:k(n,a),filesCopied:0},manifestSlice:{}};let o=await Je(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});M(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=Ye(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=O(i,e),o=O(a,e);M(D(o),{recursive:!0}),Pe(n,o),s[t]=dn(r,o)}return l>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${l} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:k(n,a),filesCopied:o.length},manifestSlice:s}}function dn(e,t){return k(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function fn(e,t){let n=k(t,e);return n===``?!1:n.startsWith(`..`)||Me(n)}function pn(e){try{return Le(e).isDirectory()}catch{return!1}}function mn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function hn(e,t,n={}){t&&(process.env.PORT=t);let r=mn(n.polling),i=process.cwd(),a=await C(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await T({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=A(i,a?.typegen?.outDir??`.kickjs/types`);try{await Ce(c,await U({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(I(l(A(`package.json`)).resolve(`vite`)).href),d=await u({configFile:A(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),f=a?.assetMap?Object.values(a.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>A(i,e)):[],p=e=>f.some(t=>e===t||e.startsWith(`${t}/`)),m=null,h=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=p(e);!t&&!n||(m&&clearTimeout(m),m=setTimeout(()=>{T({cwd:i,silent:!0,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1}).catch(()=>{}),U({cwd:i,config:a,silent:!0}).then(e=>Ce(c,e,!0)).catch(()=>{})},100))};d.watcher.on(`add`,h),d.watcher.on(`unlink`,h),d.watcher.on(`change`,h),f.length>0&&d.watcher.add(f),await d.listen(),d.printUrls(),console.log(`
697
- KickJS dev server running (Vite + @forinda/kickjs-vite)
698
- `);let g=async()=>{m&&clearTimeout(m),await d.close(),process.exit(0)};process.on(`SIGINT`,g),process.on(`SIGTERM`,g)}function gn(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).action(async e=>{try{await hn(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
699
- Error: vite is not installed.
700
- Run: pnpm add -D vite unplugin-swc
701
- `):console.error(`
702
- Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
703
- Building for production...
704
- `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(I(e(A(`package.json`)).resolve(`vite`)).href);await t({configFile:A(`vite.config.ts`)});let n=await C(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
705
- Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?O(`dist`,e):e.dest??O(`dist`,t),r=A(t),i=A(n);if(!j(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}M(i,{recursive:!0}),Pe(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
706
- Building asset map...`);try{await ln(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
707
- Build complete.
708
- `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await C(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
709
- Building asset map...`);try{await ln(e,{cwd:process.cwd()}),console.log(`
710
- Asset build complete.
711
- `)}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)),an(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 hn(e.entry,e.port)}catch(e){console.error(`
712
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function _n(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
713
- KickJS CLI
714
-
715
- System:
716
- OS: ${Ze()} ${Qe()} (${Xe()})
717
- Node: ${process.version}
718
-
719
- Packages:
720
- @forinda/kickjs workspace
721
- @forinda/kickjs-vite workspace
722
- @forinda/kickjs-cli workspace
723
- `)})}const{bold:W,dim:G,green:vn,red:K,yellow:yn,blue:bn}=a;function xn(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 Sn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function q(e,t){try{return await Sn(`${e}${t}`)}catch{return null}}async function Cn(e){let[t,n,r,i,a]=await Promise.all([q(e,`/health`),q(e,`/metrics`),q(e,`/routes`),q(e,`/container`),q(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function wn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:s}=t,c=G(`─`.repeat(60));if(console.log(),console.log(W(` KickJS Inspector`)+G(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?vn(`● healthy`):K(`● `+n.status);console.log(` ${W(`Health:`)} ${e}`)}else console.log(` ${W(`Health:`)} ${K(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?K:r.errorRate>0?yn:vn;console.log(` ${W(`Uptime:`)} ${xn(r.uptimeSeconds)}`),console.log(` ${W(`Requests:`)} ${r.requests}`),console.log(` ${W(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${G(`(`)}${t(e+`%`)}${G(`)`)}`)}if(a&&console.log(` ${W(`DI:`)} ${a.count} bindings`),s&&s.enabled&&console.log(` ${W(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(W(` Routes`)),console.log(c),console.log(` ${G(`METHOD`)} ${G(`PATH`.padEnd(36))} ${G(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${o(e.method)} ${t} ${bn(e.controller)}.${G(e.handler)}`)}}console.log(c),console.log()}function Tn(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 Cn(r);t.json?console.log(JSON.stringify(e,null,2)):wn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(K(` ✖ Could not connect to ${n}`)),console.error(G(` ${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 En(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function J(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Dn=[{match(e,t){let n=En(e,[`config`,`get`])&&J(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&J(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
724
- registers the env schema with kickjs at module-load time. Without it,
725
- ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
726
- and every user-defined key reads as undefined. @Value() may *appear* to
727
- work via a raw process.env fallback, but Zod coercion and schema defaults
728
- are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
729
- import { bootstrap } from '@forinda/kickjs'
730
- import { modules } from './modules'
731
- `,codeAfter:`import 'reflect-metadata'
732
- import './config' // ← add this — registers env schema
733
- import { bootstrap } from '@forinda/kickjs'
734
- import { modules } from './modules'
735
- `,docs:`https://forinda.github.io/kick-js/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=J(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return J(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.
736
- When vitest re-imports your modules across tests, the same class can be
737
- registered twice and the container throws. The fix is to wipe the
738
- 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'
739
- import { Container } from '@forinda/kickjs'
740
-
741
- describe('UserController', () => {
742
- beforeEach(() => Container.reset())
743
-
744
- it('does the thing', async () => { /* ... */ })
745
- })`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||En(e,[`Module`,`is not a function`])||En(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
746
- pattern instead: a class implements AppModule and exposes routes() that
747
- returns the controller wiring. This was a deliberate choice — modules
748
- become explicit values rather than metadata, which makes them easier to
749
- compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
750
- import { UserController } from './user.controller'
751
-
752
- @Module({
753
- controllers: [UserController],
754
- })
755
- export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
756
- import { UserController } from './user.controller'
757
-
758
- export class UserModule implements AppModule {
759
- routes(): ModuleRoutes {
760
- return {
761
- path: '/users',
762
- router: buildRoutes(UserController),
763
- controller: UserController,
764
- }
765
- }
766
- }`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}},{match(e,t){return/KickRoutes\s*\[\s*['"](GET|POST|PUT|PATCH|DELETE)/i.test(e)?{confidence:95,diagnosis:{id:`legacy-kick-routes-bracket-syntax`,title:`KickRoutes['POST /users'] is the legacy v1 syntax`,explanation:`KickJS v2 changed the typegen output from a flat string-keyed map to a
767
- namespaced shape: KickRoutes.UserController["create"] instead of
768
- KickRoutes["POST /users"]. The new form is per-controller, per-method,
769
- and matches the actual class names so refactors propagate via
770
- rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
771
- create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
772
- create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://forinda.github.io/kick-js/guide/typegen.html`}}:null}},{match(e,t){let n=J(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=J(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
773
- cluster: { workers: N }, the framework forks N workers, each of which
774
- spins up its own Vite instance on a separate port. The fix landed in
775
- v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
776
- silently skips cluster, with a warning. If you see this on an older
777
- 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({
778
- modules,
779
- cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
780
- })`,docs:`https://forinda.github.io/kick-js/guide/cluster.html`}}}},{match(e,t){return J(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
781
- reflect-metadata polyfill. The polyfill must be imported once,
782
- before any decorator runs. Most projects do this at the top of
783
- src/index.ts; missing the import causes obscure "design:paramtypes"
784
- 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
785
- import './config'
786
- import { bootstrap } from '@forinda/kickjs'
787
- import { modules } from './modules'
788
-
789
- export const app = await bootstrap({ modules })`,docs:`https://forinda.github.io/kick-js/guide/dependency-injection.html`}}:null}},{match(e,t){return J(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
790
- generated a module via \`kick g module foo\` but the routes don't appear,
791
- the most likely cause is that the module is missing from the exported
792
- array. The CLI usually wires this automatically, but a hand-edit can
793
- drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleEntry } from '@forinda/kickjs'
794
- import { UserModule } from './users/user.module'
795
- import { TaskModule } from './tasks/task.module' // ← was this missing?
796
-
797
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function On(e,t){let n=null;for(let r of Dn){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 kn(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.
798
- export OPENAI_API_KEY="sk-..."
799
-
800
- 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:
801
- kick add ai
802
-
803
- Or manually:
804
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=An(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=jn((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 An(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
805
- `)}function jn(e){let t=[e,Mn(e),Nn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Pn(t))return t}catch{continue}return null}function Mn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Nn(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 Pn(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 Fn(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 Rn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
806
-
807
- Pass a message as a positional arg, --message flag, or pipe via stdin:
808
- kick explain "config.get returned undefined"
809
- pnpm test 2>&1 | kick explain
810
- `),process.exit(1));let r=Bn(),i=On(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
811
- `);return}if(i){Vn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
812
- `),process.exit(2)),Hn(n,!1),process.exit(2));let a=await kn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(In(a),null,2)+`
813
- `),process.exit(a.kind===`ok`?0:2)),Ln(n,a),process.exit(a.kind===`ok`?0:2)})}function In(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 Ln(e,t){if(t.kind===`ok`){Vn(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${X(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Y(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${X(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Rn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:zn()}function zn(){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 Bn(){let e=process.cwd();return{cwd:e,hasFile:t=>j(A(e,t))}}function Vn(e,t,n,r=!1){let i=X(e.trim(),200),a=r?`AI-generated — verify before applying`:Un(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${Y(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Y(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Y(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Y(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
814
- `)}function Hn(e,t){let n=X(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.
815
- When @forinda/kickjs-ai ships its provider implementations,
816
- this command will call the configured LLM with the error +
817
- project context and return a structured fix.
818
-
819
- `):process.stdout.write(` No known-issue matched. Things you can try:
820
-
821
- 1. Check the framework docs for the error keywords:
822
- https://forinda.github.io/kick-js/
823
-
824
- 2. Re-run with --ai to fall back to an LLM (requires
825
- @forinda/kickjs-ai with a configured provider):
826
- kick explain --ai "<your error>"
827
-
828
- 3. File an issue with the error text:
829
- https://github.com/forinda/kick-js/issues/new
830
-
831
- `)}function Y(e,t){return e.split(`
832
- `).map(e=>`${t}${e}`).join(`
833
- `)}function X(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Un(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Wn(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(Gn),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(Kn)}function Gn(e){let t=A(e.entry);j(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],r=Ke(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Kn(e){let t=process.cwd(),n=qn(t)??je(t),r=e.name??n,i=e.global?A(process.env.HOME??`.`,`.mcp.json`):A(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(j(i))try{let e=N(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,Re(i,JSON.stringify(o,null,2)+`
834
- `,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function qn(e){let t=A(e,`package.json`);if(!j(t))return null;try{let e=N(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Jn(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=A(t,e.entry);j(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Xn(t,`tsx`);r||(console.error(`
835
- Error: tsx not found. Install it: pnpm add -D tsx
836
- `),process.exit(1));let i=Yn(n,e.entry),a=O(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Ge(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Yn(e,t){return`
837
- import 'reflect-metadata'
838
-
839
- // Prevent bootstrap() from starting the HTTP server
840
- process.env.KICK_TINKER = '1'
841
-
842
- console.log('\\n 🔧 KickJS Tinker')
843
- console.log(' Loading: ${t}\\n')
844
-
845
- // Load core
846
- let Container, Logger, HttpException, HttpStatus
847
- try {
848
- const core = await import('@forinda/kickjs')
849
- Container = core.Container
850
- Logger = core.Logger
851
- HttpException = core.HttpException
852
- HttpStatus = core.HttpStatus
853
- } catch {
854
- console.error(' Error: @forinda/kickjs not found.')
855
- console.error(' Install it: pnpm add @forinda/kickjs\\n')
856
- process.exit(1)
857
- }
858
-
859
- // Load entry to trigger decorator registration
860
- try {
861
- await import('${I(e).href}')
862
- } catch (err) {
863
- console.warn(' Warning: ' + err.message)
864
- console.warn(' Container may be partially initialized.\\n')
865
- }
866
-
867
- const container = Container.getInstance()
868
-
869
- // Start REPL
870
- const repl = await import('node:repl')
871
- const server = repl.start({ prompt: 'kick> ', useGlobal: true })
872
-
873
- server.context.container = container
874
- server.context.Container = Container
875
- server.context.resolve = (token) => container.resolve(token)
876
- server.context.Logger = Logger
877
- server.context.HttpException = HttpException
878
- server.context.HttpStatus = HttpStatus
879
-
880
- console.log(' Available globals:')
881
- console.log(' container — DI container instance')
882
- console.log(' resolve(T) — shorthand for container.resolve(T)')
883
- console.log(' Container, Logger, HttpException, HttpStatus')
884
- console.log()
885
-
886
- server.on('exit', () => {
887
- console.log('\\n Goodbye!\\n')
888
- process.exit(0)
889
- })
890
- `}function Xn(e,t){let n=e;for(;;){let e=O(n,`node_modules`,`.bin`,t);if(j(e))return e;let r=A(n,`..`);if(r===n)break;n=r}return null}function Zn(e,t){let n=RegExp(`^\\s*${y(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]!==`
891
- `;)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]===`
892
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Qn(e,t){let n=_(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Zn(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${y(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 $n(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,o=x(t),s=g(t),c=i?de(o):o,l=O(n,c);if(!await f(l)){console.log(`\n Module not found: ${l}\n`);return}if(!r&&!await u({message:a.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
893
- Cancelled.
894
- `);return}await He(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let d=O(n,`index.ts`);if(await f(d)){let e=await P(d,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${y(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${y(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Qn(e,s),e=e.replace(/\n{3,}/g,`
895
-
896
- `),e!==t&&(await F(d,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${d}`))}console.log(`\n Module '${c}' removed.\n`)}function er(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=S(await C(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await $n({name:n,modulesDir:A(r),force:t.force,pluralize:i})})}function tr(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 nr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function rr(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=he(process.cwd()),n=await C(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-CcuuVb2P.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-DOQNq7JT.mjs`),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(`
897
- Registered typegen plugins:
898
- `);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=tr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=nr(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await Oe(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 T(a);let r=await U({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 Ce(A(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof ke?console.error(`
899
- `+e.message+`
900
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function ir(e){let t=[];if(!j(e))return t;let n=Fe(e,{withFileTypes:!0});for(let r of n){let n=O(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...ir(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function ar(e){try{return N(e,`utf-8`)}catch{return``}}const or=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function sr(e,t){let n=ar(O(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(or.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 cr(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 lr(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 ur(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function dr(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 fr(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 pr(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 mr(e){let t=ir(O(e,`src`)).map(e=>ar(e)),n=[],r=sr(e,t);r&&n.push(r);let i=cr(t);i&&n.push(i);let a=lr(t);a&&n.push(a);let o=ur();o&&n.push(o);let s=dr(t);return s&&n.push(s),n.push(fr(t)),n.push(pr(t)),n}function hr(t){t.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(t=>{if(!t.deploy){console.log(`
901
- Usage: kick check --deploy
902
-
903
- Available checks:
904
- --deploy Audit for production readiness (security, config, best practices)
905
- `);return}let i=process.cwd();n(`KickJS Deploy Check`);let o=l();o.start(`Scanning project...`);let c=mr(i);o.stop(`Scan complete`);let u={CRITICAL:0,WARNING:1,INFO:2};c.sort((e,t)=>u[e.severity]-u[t.severity]);for(let t of c)s.message(`${e(t.severity)} ${t.message}`);let d=c.filter(e=>e.severity===`CRITICAL`).length,f=c.filter(e=>e.severity===`WARNING`).length,p=c.filter(e=>e.severity===`INFO`).length,m=f===1?`warning`:`warnings`,h=[d>0?a.red(`${d} critical`):`${d} critical`,f>0?a.yellow(`${f} ${m}`):`${f} ${m}`,`${p} info`].join(`, `);d>0?(r(a.red(`${h} — fix critical issues before deploying`)),process.exit(1)):r(a.green(`${h} — looking good!`))})}async function Z(e){return st({configPath:E.resolve(process.cwd(),e.config)})}async function Q(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}async function gr(e){if(e.adapter||(e.dialect??`postgres`)!==`postgres`||!e.connectionString)return null;let t=new(await(import(`pg`))).default.Pool({connectionString:e.connectionString});return{runner:t,cleanup:async()=>{await t.end()}}}function _r(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function vr(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await Z(t),i=await gr(r),a=i?e=>$e(i.runner,e):void 0;try{let i=await et({name:e,config:r,cwd:n,empty:t.empty,detectCompositeRefs:a});if(i.status===`no-changes`){console.log(`No schema changes detected.`);return}if(i.empty){console.log(`Created empty migration ${i.migrationDir} (author up.sql + down.sql).`);return}let o=i.changeCount===1?``:`s`;console.log(`Created migration ${i.migrationDir} (${i.changeCount} change${o}).`)}finally{await i?.cleanup()}});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{let r=await nt({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{let r=await at({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{let e=await tt({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{let e=await rt({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{_r(await it({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Z(e),{adapter:n,cleanup:r}=await Q(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await F(i,ot(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}function yr(e){return e.optsWithGlobals().dryRun??!1}function br(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.
906
- Direction defaults to \`modules.style\` from kick.config (or "define").
907
- --target define|class Override the migration direction.
908
- --apply Apply the changes (default: dry-run preview).
909
- --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=yr(t)||!e.apply;p(n),e.experimental||(console.error(`
910
- `+a.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
911
- The regex-based rewrite handles the shapes our templates produce.
912
- Hand-rolled modules with non-standard structures may be skipped.
913
- Always commit before running with --apply.
914
- `),process.exit(1));let r=S(await C(process.cwd())),i=A(e.modulesDir??r.dir??`src/modules`),o;e.target===`define`||e.target===`class`?o=e.target:e.target===void 0?o=r.style??`define`:(console.error(`\n ${a.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=a.dim(`→ ${o}`),c=n?a.dim(`(dry-run)`):a.bold(`(applying)`);console.log(`\n ${a.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${a.dim(i)}\n`);let l=e.backup!==!1&&!n,u=await Mt(i,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${a.green(`✓`)} backup: ${a.dim(e)}\n ${a.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !n&&e.backup===!1&&console.log(` ${a.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${a.green(`✓`)} ${e.path}`);else{f++;let t=a.dim(`(${e.reason??`skipped`})`);console.log(` ${a.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${a.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=a.dim(`(${u.indexReason??`skipped`})`);console.log(` ${a.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${a.dim(`-`)} ${u.indexPath} ${a.dim(`(not found)`)}`);let m=n?a.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${a.bold(String(d))} migrated, ${a.bold(String(f))} skipped${m}\n`)})}const xr=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],Sr=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=Cr(e.cwd);if(!t)return null;let n=E.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${wr(E.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
915
- `)}});function Cr(e){for(let t of xr){let n=E.resolve(e,t);if(t.endsWith(`.ts`)){if(j(n))return n}else{let e=E.join(n,`index.ts`);if(j(e))return e}}return null}function wr(e){return e.replace(/\\/g,`/`)}const Tr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!j(E.resolve(e.cwd,`kick.config.ts`)))return null;let t=await C(e.cwd);if(!t?.assetMap)return null;let n=ve(t.assetMap,e.cwd);return n.count===0?null:Ee(n)}}),Er="/* 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 Dr(e,t,n){if(e.length===0)return`${Er}
916
- // (no routes discovered yet — annotate a controller method with
917
- // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
918
- declare global {
919
- // eslint-disable-next-line @typescript-eslint/no-namespace
920
- namespace KickRoutes {}
921
- }
922
-
923
- export {}
924
- `;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=Ar(e,r,t,n,i);return a?n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${a}>`:`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??Or(e),l=kr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
925
- `))}return`${Er}${jr(i)}
926
- declare global {
927
- // eslint-disable-next-line @typescript-eslint/no-namespace
928
- namespace KickRoutes {
929
- ${o.join(`
930
- `)}
931
- }
932
- }
933
-
934
- export {}
935
- `}function Or(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 kr(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 Ar(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Mr(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 jr(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(`
936
- `)+`
937
- `}function Mr(e,t,n){if(e===null)return`unknown`;let r=D(n);if(e===``){let e=k(r,t).split(Ne).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=k(r,A(D(t),e)).split(Ne).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const Nr=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Pr(e),cwd:e.cwd,envFile:Fr(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=E.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Dr(t.routes,r,n)}});function Pr(e){return E.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Fr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Ir(e,t,n=`zod`){if(!e)return null;let r=k(D(t),e.filePath).split(Ne).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
938
- // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
939
- // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
940
-
941
- // Importing the schema as a type lets us infer its shape without
942
- // pulling in any runtime code. \`Awaited<>\` strips an accidental
943
- // Promise wrap on dynamic-imported defaults.
944
- import type _envSchema from '${r}'
945
-
946
- ${n===`kickjs-schema`?`type _Raw = import('@forinda/kickjs-schema').InferSchemaOutput<typeof _envSchema>
947
- type _Resolved = { [K in keyof _Raw]: _Raw[K] }
948
- `:``}// Local type alias — interfaces can only \`extend\` an identifier,
949
- // not an inline import expression, so we resolve the schema's
950
- // inferred shape into a named type first.
951
- type _KickEnvShape = ${n===`kickjs-schema`?`_Resolved`:`import('zod').infer<typeof _envSchema>`}
952
-
953
- declare global {
954
- /**
955
- * Typed environment registry. Augmented from \`${e.relativePath}\`
956
- * so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
957
- * all type-safe and autocomplete.
958
- */
959
- interface KickEnv extends _KickEnvShape {}
960
-
961
- // eslint-disable-next-line @typescript-eslint/no-namespace
962
- namespace NodeJS {
963
- /**
964
- * Narrow \`process.env\` so known keys exist as \`string\` (the raw
965
- * pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
966
- * the schema's transforms internally; access \`process.env\` directly
967
- * only when you need the raw string. Unknown keys still resolve to
968
- * \`string | undefined\` via the base @types/node declaration.
969
- */
970
- interface ProcessEnv extends Record<keyof KickEnv, string> {}
971
- }
972
- }
973
-
974
- export {}
975
- `}const Lr=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=zr(e);if(t===!1)return null;let n=await e.getScanResult({root:Rr(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=E.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Ir(n.env,i,r)}});function Rr(e){return E.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function zr(e){return e.config?.typegen?.envFile}function Br(e){return E.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Vr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Br(e),cwd:e.cwd,envFile:Vr(e)}}const Hr=[w({name:`kick/init`,register:_t}),w({name:`kick/generate`,register:nn}),w({name:`kick/run`,register:gn}),w({name:`kick/info`,register:_n}),w({name:`kick/inspect`,register:Tn}),w({name:`kick/add`,register:ht}),w({name:`kick/list`,register:mt}),w({name:`kick/explain`,register:Fn}),w({name:`kick/mcp`,register:Wn}),w({name:`kick/tinker`,register:Jn}),w({name:`kick/remove`,register:er}),w({name:`kick/typegen`,register:rr}),w({name:`kick/check`,register:hr}),w({name:`kick/doctor`,register:ce}),w({name:`kick/db`,register:vr,typegens:[Sr()]}),w({name:`kick/codemod`,register:br}),w({name:`kick/registry`,typegens:[{id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=E.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return De(t.classes,n,r)}}]}),w({name:`kick/services`,typegens:[{id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className));return Te(`ServiceToken`,we(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}]}),w({name:`kick/modules`,typegens:[{id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return Te(`ModuleToken`,ye((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}]}),w({name:`kick/plugins`,typegens:[{id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return xe((await e.getScanResult($(e))).pluginsAndAdapters)}}]}),w({name:`kick/augmentations`,typegens:[{id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Ae((await e.getScanResult($(e))).augmentations)}}]}),w({name:`kick/context`,typegens:[{id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:be(t.contextKeys)}}]}),w({name:`kick/assets`,typegens:[Tr()]}),w({name:`kick/routes`,typegens:[Nr()]}),w({name:`kick/env`,typegens:[Lr()]})];export{cn as applyDisableFilter,U as runAllPluginTypegens,Hr as t};
976
- //# sourceMappingURL=run-plugins-fsoovaEF.mjs.map