@forinda/kickjs-cli 8.1.6 → 8.2.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 (51) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-docs-BBlVl1tY.mjs → agent-docs-BkVcT3-P.mjs} +2 -2
  3. package/dist/{agent-docs-CW5TQHti.mjs → agent-docs-ZLJrf4le.mjs} +3 -3
  4. package/dist/{agent-docs-CW5TQHti.mjs.map → agent-docs-ZLJrf4le.mjs.map} +1 -1
  5. package/dist/{build-htBdOg51.mjs → build-B6sHvVo7.mjs} +3 -3
  6. package/dist/{build-DOI_zYDS.mjs → build-DYS28yQZ.mjs} +4 -4
  7. package/dist/{build-DOI_zYDS.mjs.map → build-DYS28yQZ.mjs.map} +1 -1
  8. package/dist/{builtins-Cj4BWpIe.mjs → builtins-Clx2eHtk.mjs} +2 -2
  9. package/dist/{builtins-SMK1mtlk.mjs → builtins-CxkMpt5m.mjs} +117 -115
  10. package/dist/cli.mjs +2 -2
  11. package/dist/{config-BYSNxf_t.mjs → config-C5NMS8wI.mjs} +3 -3
  12. package/dist/{config-DST3ilXt.mjs → config-DS1zxYJ1.mjs} +4 -4
  13. package/dist/config-DS1zxYJ1.mjs.map +1 -0
  14. package/dist/{doctor-CJYTXARe.mjs → doctor-Dq9eTYcX.mjs} +8 -7
  15. package/dist/doctor-Dq9eTYcX.mjs.map +1 -0
  16. package/dist/{fullstack-Mkw3lkF1.mjs → fullstack-2OdmYOvH.mjs} +4 -4
  17. package/dist/{fullstack-Mkw3lkF1.mjs.map → fullstack-2OdmYOvH.mjs.map} +1 -1
  18. package/dist/{fullstack-19gafr4U.mjs → fullstack-BQWhqUFG.mjs} +3 -3
  19. package/dist/index.d.mts +26 -27
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +2 -2
  22. package/dist/plugin-DKzw-J38.mjs +11 -0
  23. package/dist/{plugin-IEDGa0ny.mjs → plugin-DymfD_WC.mjs} +2 -2
  24. package/dist/{project-docs-CYCi7cHt.mjs → project-docs-2agWZ5Kj.mjs} +1 -1
  25. package/dist/{project-docs-at2gZlUE.mjs → project-docs-B1P0P1tS.mjs} +2 -2
  26. package/dist/{project-docs-at2gZlUE.mjs.map → project-docs-B1P0P1tS.mjs.map} +1 -1
  27. package/dist/{project-CAamSqrL.mjs → project-e2qx-MiB.mjs} +26 -24
  28. package/dist/project-e2qx-MiB.mjs.map +1 -0
  29. package/dist/{project-root-BhBKSGeK.mjs → project-root-C77GmtLr.mjs} +2 -2
  30. package/dist/{project-root-PMRCA_2T.mjs → project-root-D9DZhB77.mjs} +3 -3
  31. package/dist/{project-root-PMRCA_2T.mjs.map → project-root-D9DZhB77.mjs.map} +1 -1
  32. package/dist/{project-5ljMCm0U.mjs → project-zPKiG2Q_.mjs} +28 -26
  33. package/dist/{prompts-BxPTyuY3.mjs → prompts-DZjyJbKm.mjs} +2 -2
  34. package/dist/{prompts-BxPTyuY3.mjs.map → prompts-DZjyJbKm.mjs.map} +1 -1
  35. package/dist/{rolldown-runtime-D-i_dFAb.mjs → rolldown-runtime-CXm-vk54.mjs} +1 -1
  36. package/dist/{run-plugins-GxEtP9WR.mjs → run-plugins-D5xbaQib.mjs} +102 -101
  37. package/dist/run-plugins-D5xbaQib.mjs.map +1 -0
  38. package/dist/typegen-DTkfAt0T.mjs +131 -0
  39. package/dist/typegen-v-DVwTp8.mjs +132 -0
  40. package/dist/typegen-v-DVwTp8.mjs.map +1 -0
  41. package/dist/{types-PxKCj-JF.mjs → types-CPp_aWkS.mjs} +1 -1
  42. package/package.json +6 -6
  43. package/dist/config-DST3ilXt.mjs.map +0 -1
  44. package/dist/doctor-CJYTXARe.mjs.map +0 -1
  45. package/dist/plugin-Cfiz2G3K.mjs +0 -12
  46. package/dist/plugin-Cfiz2G3K.mjs.map +0 -1
  47. package/dist/project-CAamSqrL.mjs.map +0 -1
  48. package/dist/run-plugins-GxEtP9WR.mjs.map +0 -1
  49. package/dist/typegen-CJvd5MEz.mjs +0 -132
  50. package/dist/typegen-CJvd5MEz.mjs.map +0 -1
  51. package/dist/typegen-D7aeVM0D.mjs +0 -131
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.1.6
2
+ * @forinda/kickjs-cli v8.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{c as e,l as t,s as n}from"./project-docs-at2gZlUE.mjs";import{a as r,c as i,d as a,i as o,l as s,n as c,o as l,r as u,s as d,t as f,u as p}from"./prompts-BxPTyuY3.mjs";import{A as m,C as h,D as g,E as _,M as v,N as y,O as ee,P as b,S as te,T as ne,_ as re,a as ie,b as ae,c as oe,f as se,g as ce,h as le,i as ue,j as de,k as x,l as fe,m as pe,p as me,r as he,u as ge,v as _e,w as ve,x as ye,y as be}from"./doctor-CJYTXARe.mjs";import{a as xe,c as Se,o as Ce,r as we,t as Te,u as Ee}from"./project-CAamSqrL.mjs";import{a as De,c as Oe,i as ke,l as Ae,o as S,s as C,u as je}from"./config-DST3ilXt.mjs";import{t as w}from"./project-root-PMRCA_2T.mjs";import{n as T}from"./types-PxKCj-JF.mjs";import{t as Me}from"./build-DOI_zYDS.mjs";import{n as Ne}from"./agent-docs-CW5TQHti.mjs";import{n as Pe}from"./plugin-Cfiz2G3K.mjs";import{_ as Fe,a as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,l as Ue,m as We,o as Ge,p as Ke,r as qe,s as Je,t as E,u as Ye}from"./typegen-CJvd5MEz.mjs";import{createRequire as Xe}from"node:module";import D,{basename as Ze,dirname as O,join as k,relative as Qe,resolve as A,sep as $e}from"node:path";import{cpSync as et,existsSync as j,mkdirSync as tt,readFileSync as M,readdirSync as nt,rmSync as rt,writeFileSync as it}from"node:fs";import{copyFile as at,mkdir as N,readFile as P,readdir as ot,rm as st,stat as ct,writeFile as F}from"node:fs/promises";import{fork as lt,spawn as ut,spawnSync as dt}from"node:child_process";import{fileURLToPath as ft,pathToFileURL as I}from"node:url";import{arch as pt,platform as mt,release as ht}from"node:os";import{createHash as gt}from"node:crypto";const _t=[{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 vt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).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)=>{c(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await i({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let a;if(e===`.`?(a=A(`.`),e=Ze(a)):a=A(t.directory||e),j(a)){let i=nt(a);if(i.length>0){if(t.force)u.warn(`Clearing existing files in ${a}`);else if(n){u.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{u.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)u.message(` - ${e}`);if(i.length>5&&u.message(` ... and ${i.length-5} more`),!await f({message:p.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of i)rt(A(a,e),{recursive:!0,force:!0})}}let s=t.template;s||=n?`minimal`:await l({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let d=t.runtime;d||=n?`express`:await l({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let m=t.pm;m||=n?await Se(void 0):await l({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let h=t.repo;h||=n?`inmemory`:await i({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),je(h);let g=t.schema;g||=n?`zod`:await l({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(g)||(u.warn(`Unknown --schema "${g}", falling back to zod.`),g=`zod`);let _;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();_=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else _=n?[]:await o({message:`Select packages to include`,options:[..._t],required:!1});let v;v=t.git===void 0?n?!0:await f({message:`Initialize git repository?`,initialValue:!0}):t.git;let y;if(y=t.install===void 0?n?!0:await f({message:`Install dependencies?`,initialValue:!0}):t.install,s===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-Mkw3lkF1.mjs`);await t({name:e,directory:a,packageManager:m,initGit:v,installDeps:y,schemaLib:g,runtime:d}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${m}${m===`pnpm`?` dev`:` run dev:server`}`)}`);return}await Te({name:e,directory:a,packageManager:m,initGit:v,installDeps:y,template:s,defaultRepo:h,packages:_,schemaLib:g,runtime:d}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${m} dev`)}`)})}async function yt(e){let{name:n,outDir:r}=e,i=y(n),a=b(n),o=[],s=k(r,`${i}.plugin.ts`);return await t(s,`import {
11
+ import{t as e}from"./rolldown-runtime-CXm-vk54.mjs";import{c as t,l as n,s as r}from"./project-docs-B1P0P1tS.mjs";import{a as i,c as a,d as o,i as s,l as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./prompts-DZjyJbKm.mjs";import{A as h,C as g,D as _,E as v,M as y,N as b,O as ee,P as x,S as te,T as ne,_ as re,a as ie,b as ae,c as oe,f as se,g as ce,h as le,i as ue,j as de,k as fe,l as pe,m as me,p as he,r as ge,u as _e,v as ve,w as ye,x as be,y as xe}from"./doctor-Dq9eTYcX.mjs";import{a as Se,c as Ce,o as we,r as Te,t as Ee,u as De}from"./project-e2qx-MiB.mjs";import{a as Oe,c as ke,i as Ae,l as je,o as S,s as C,u as Me}from"./config-DS1zxYJ1.mjs";import{t as w}from"./project-root-D9DZhB77.mjs";import{n as T,t as E}from"./types-CPp_aWkS.mjs";import{t as Ne}from"./build-DYS28yQZ.mjs";import{n as Pe}from"./agent-docs-ZLJrf4le.mjs";import{C as Fe,S as D,T as Ie,_ as Le,a as Re,b as ze,c as Be,d as Ve,f as He,g as Ue,h as We,i as Ge,l as Ke,m as qe,o as Je,p as Ye,r as Xe,s as Ze,t as O,u as Qe,v as $e,w as et,x as tt,y as nt}from"./typegen-v-DVwTp8.mjs";import{createRequire as rt}from"node:module";import k,{basename as it,dirname as A,join as j,relative as at,resolve as M,sep as ot}from"node:path";import{cpSync as st,existsSync as N,mkdirSync as ct,readFileSync as P,readdirSync as lt,rmSync as ut,writeFileSync as dt}from"node:fs";import{copyFile as ft,mkdir as pt,readFile as F,readdir as mt,rm as ht,stat as gt,writeFile as I}from"node:fs/promises";import{fork as _t,spawn as vt,spawnSync as yt}from"node:child_process";import{fileURLToPath as bt,pathToFileURL as L}from"node:url";import{parseSync as xt}from"oxc-parser";import{arch as St,platform as Ct,release as wt}from"node:os";import{createHash as Tt}from"node:crypto";const Et=[{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 Dt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).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)=>{l(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await a({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=M(`.`),e=it(r)):r=M(t.directory||e),N(r)){let a=lt(r);if(a.length>0){if(t.force)d.warn(`Clearing existing files in ${r}`);else if(n){d.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),i(`Aborted.`);return}else{d.warn(`Directory "${e}" is not empty:`);let t=a.slice(0,5);for(let e of t)d.message(` - ${e}`);if(a.length>5&&d.message(` ... and ${a.length-5} more`),!await p({message:m.red(`Remove all existing files and proceed?`),initialValue:!1})){i(`Aborted.`);return}}for(let e of a)ut(M(r,e),{recursive:!0,force:!0})}}let o=t.template;o||=n?`minimal`:await u({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let c=t.runtime;c||=n?`express`:await u({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let f=t.pm;f||=n?await Ce(void 0):await u({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let h=t.repo;h||=n?`inmemory`:await a({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Me(h);let g=t.schema;g||=n?`zod`:await u({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(g)||(d.warn(`Unknown --schema "${g}", falling back to zod.`),g=`zod`);let _;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();_=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else _=n?[]:await s({message:`Select packages to include`,options:[...Et],required:!1});let v;v=t.git===void 0?n?!0:await p({message:`Initialize git repository?`,initialValue:!0}):t.git;let y;if(y=t.install===void 0?n?!0:await p({message:`Install dependencies?`,initialValue:!0}):t.install,o===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-2OdmYOvH.mjs`);await t({name:e,directory:r,packageManager:f,initGit:v,installDeps:y,schemaLib:g,runtime:c}),i(`Done! Next steps: ${m.cyan(`cd ${e} && ${f}${f===`pnpm`?` dev`:` run dev:server`}`)}`);return}await Ee({name:e,directory:r,packageManager:f,initGit:v,installDeps:y,template:o,defaultRepo:h,packages:_,schemaLib:g,runtime:c}),i(`Done! Next steps: ${m.cyan(`cd ${e} && ${f} dev`)}`)})}function R(e,t=[]){let n=new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new E(`plugin`,t.name,[t.name,t.name])}let r=new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new E(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new E(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new E(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await import(`./project-root-D9DZhB77.mjs`).then(e=>e.n),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}async function Ot(e){let{name:t,outDir:r}=e,i=b(t),a=x(t),o=[],s=j(r,`${i}.plugin.ts`);return await n(s,`import {
12
12
  definePlugin,
13
13
  type AppAdapter,
14
14
  type AppModuleEntry,
@@ -166,11 +166,11 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
166
166
  },
167
167
  }),
168
168
  })
169
- `),o.push(s),o}function bt(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function xt(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=y(n),c=b(n),l=e.key??v(n),u=Array.isArray(e.params)?e.params:bt(e.params),d=_e({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`,m=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
169
+ `),o.push(s),o}function kt(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function At(e){let{name:t,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=b(t),c=x(t),l=e.key??y(t),u=Array.isArray(e.params)?e.params:kt(e.params),d=ve({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`,m=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
170
170
  `)}\n}\n`:``,h=u.length>0?`${f}.withParams<${c}Params>()({`:`${f}({`,g=u.length>0?` // Every call site must supply these — no placeholder defaults.
171
171
  // Add \`paramDefaults: { … }\` for any field whose default is
172
172
  // genuinely correct for an undecorated route, and drop it from here.
173
- requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,ee=u.length>0?` // \`params\` is typed as ${c}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,te=`import { ${f} } from '@forinda/kickjs'
173
+ requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,v=u.length>0?` // \`params\` is typed as ${c}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,ee=`import { ${f} } from '@forinda/kickjs'
174
174
  import type { ${p} } from '@forinda/kickjs'
175
175
 
176
176
  /**
@@ -212,13 +212,13 @@ ${m}
212
212
  export const ${c} = ${h}
213
213
  key: '${l}',
214
214
  ${g} resolve: ${_} => {
215
- ${ee}
215
+ ${v}
216
216
  // TODO: compute and return the value written to ctx.set('${l}', …)
217
217
  throw new Error("${c} contributor: resolve() not implemented")
218
218
  },
219
219
  })
220
- `,ne=k(d,`${s}.contributor.ts`);return await t(ne,te),[ne]}async function St(e){let n=k(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return j(n)&&!e.force&&!await f({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
221
- Skipped — existing kick.config.ts preserved.`),[]):(await t(n,`import { defineConfig } from '@forinda/kickjs-cli'
220
+ `,te=j(d,`${s}.contributor.ts`);return await n(te,ee),[te]}async function jt(e){let t=j(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return N(t)&&!e.force&&!await p({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
221
+ Skipped — existing kick.config.ts preserved.`),[]):(await n(t,`import { defineConfig } from '@forinda/kickjs-cli'
222
222
 
223
223
  export default defineConfig({
224
224
  modules: {
@@ -260,18 +260,18 @@ export default defineConfig({
260
260
  },
261
261
  ],
262
262
  })
263
- `),[n])}function L(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 R(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=L(e,r);return i===-1?null:e.slice(r+1,i)}function z(e,t,n){let r=` `.repeat(n);return e.split(`
263
+ `),[t])}function z(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 B(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=z(e,r);return i===-1?null:e.slice(r+1,i)}function V(e,t,n){let r=` `.repeat(n);return e.split(`
264
264
  `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
265
- `)}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=L(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=R(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=R(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=R(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) {${z(l,4,6)} },\n\n`),u&&(p+=` contributors() {${z(u,4,6)} },\n\n`),p+=` routes() {${z(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
265
+ `)}function Mt(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 Nt(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 Pt(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=z(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=B(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=B(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=B(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Mt(s),p=``;return l&&(p+=` register(container) {${V(l,4,6)} },\n\n`),u&&(p+=` contributors() {${V(u,4,6)} },\n\n`),p+=` routes() {${V(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
266
266
  name: '${r}',
267
267
  build: () => ({
268
268
  ${p}
269
269
  }),
270
- })`}${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=L(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]===`
271
- `||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=L(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=R(m,/register\s*\(([^)]*)\)\s*\{/),g=R(m,/contributors\s*\(\s*\)\s*\{/),_=R(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 {${z(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${z(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${z(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
270
+ })`}${c}`}}function Ft(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=z(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]===`
271
+ `||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=z(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=B(m,/register\s*\(([^)]*)\)\s*\{/),g=B(m,/contributors\s*\(\s*\)\s*\{/),_=B(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Nt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${V(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${V(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${V(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
272
272
  ${y}
273
273
  }
274
- `}${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 ot(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o;try{o=await ct(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 ot(e)}catch{return}await N(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o=k(t,a),s;try{s=await ct(i)}catch{continue}s.isDirectory()?await r(i,o):(await at(i,o),n++)}}}function jt(e){return k(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(k(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=k(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}const Pt={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 Ft(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=Pt[a];if(!o){let e=[...Object.keys(Pt),`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 It(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=y(n),u=b(n),d=c?m(l):l,f=c?de(u):u,p=k(i,d),h=[],v=async(e,n)=>{let r=k(p,e);await t(r,n),h.push(r)};return await v(`${l}.module.ts`,ee({pascal:u,kebab:l,plural:d,repo:a,style:s})),await v(`${l}.constants.ts`,ve({pascal:u,kebab:l})),await v(`${l}.controller.ts`,g({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await v(`${l}.service.ts`,ne({pascal:u,kebab:l})),await v(`dtos/create-${l}.dto.ts`,Lt(u,r)),await v(`dtos/update-${l}.dto.ts`,Rt(u,r)),await v(`dtos/${l}-response.dto.ts`,zt(u,r)),await v(`${l}.repository.ts`,_({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await ae(i,u,d,l,s),h}function Lt(e,t){return`import { z } from 'zod'
274
+ `}${u}`}}function It(e,t){return t===`class`?Ft(e):Pt(e)}function Lt(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 Rt(e){let t=[];return await n(M(e),0),t;async function n(e,r){let i;try{i=await mt(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=j(e,a),o;try{o=await gt(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function zt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await mt(e)}catch{return}await pt(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=j(e,a),o=j(t,a),s;try{s=await gt(i)}catch{continue}s.isDirectory()?await r(i,o):(await ft(i,o),n++)}}}function Bt(e){let t=new Date().toISOString().replaceAll(/[:.]/g,`-`);return j(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function Vt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Rt(e),s=await F(j(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Bt(r),await zt(e,c));let l=[];for(let e of o){let t=It(await F(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await I(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=j(e,`index.ts`),d=null;try{d=await F(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Lt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await I(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Ht(e,t){let n=await Rt(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 F(e,`utf-8`);i.test(t)&&r.push(e)}return r}const Ut={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 Wt(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=Ut[a];if(!o){let e=[...Object.keys(Ut),`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 Gt(e){let{name:t,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=b(t),u=x(t),d=c?h(l):l,f=c?de(u):u,p=j(i,d),m=[],g=async(e,t)=>{let r=j(p,e);await n(r,t),m.push(r)};return await g(`${l}.module.ts`,ee({pascal:u,kebab:l,plural:d,repo:a,style:s})),await g(`${l}.constants.ts`,ye({pascal:u,kebab:l})),await g(`${l}.controller.ts`,_({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await g(`${l}.service.ts`,ne({pascal:u,kebab:l})),await g(`dtos/create-${l}.dto.ts`,Kt(u,r)),await g(`dtos/update-${l}.dto.ts`,qt(u,r)),await g(`dtos/${l}-response.dto.ts`,Jt(u,r)),await g(`${l}.repository.ts`,v({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await ae(i,u,d,l,s),m}function Kt(e,t){return`import { z } from 'zod'
275
275
 
276
276
  export const create${e}Schema = z.object({
277
277
  ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
@@ -279,7 +279,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
279
279
  })
280
280
 
281
281
  export type Create${e}DTO = z.infer<typeof create${e}Schema>
282
- `}function Rt(e,t){return`import { z } from 'zod'
282
+ `}function qt(e,t){return`import { z } from 'zod'
283
283
 
284
284
  export const update${e}Schema = z.object({
285
285
  ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
@@ -287,14 +287,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
287
287
  })
288
288
 
289
289
  export type Update${e}DTO = z.infer<typeof update${e}Schema>
290
- `}function zt(e,t){return`export interface ${e}ResponseDTO {
290
+ `}function Jt(e,t){return`export interface ${e}ResponseDTO {
291
291
  id: string
292
292
  ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
293
293
  `)}
294
294
  createdAt: string
295
295
  updatedAt: string
296
296
  }
297
- `}async function Bt(e){let{name:n,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=y(n),s=b(n),c=[],l;if(e.outDir)l=A(e.outDir);else if(r){let e=y(r),t=a?m(e):e;l=A(k(i??`src/modules`,t,`__tests__`))}else l=A(`src/__tests__`);let u=k(l,`${o}.test.ts`);return await t(u,`import { describe, it, expect, beforeEach } from 'vitest'
297
+ `}async function Yt(e){let{name:t,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=b(t),s=x(t),c=[],l;if(e.outDir)l=M(e.outDir);else if(r){let e=b(r),t=a?h(e):e;l=M(j(i??`src/modules`,t,`__tests__`))}else l=M(`src/__tests__`);let u=j(l,`${o}.test.ts`);return await n(u,`import { describe, it, expect, beforeEach } from 'vitest'
298
298
  import { Container } from '@forinda/kickjs'
299
299
 
300
300
  describe('${s}', () => {
@@ -317,57 +317,57 @@ describe('${s}', () => {
317
317
  expect(true).toBe(true)
318
318
  })
319
319
  })
320
- `),c.push(u),c}const Vt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function B(e){return e.parent?.opts()?.dryRun??!1}function V(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(`
321
- (dry run — no files were written)`),console.log()}async function Ht(e){if(!e)try{let e=await S(process.cwd());await E({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 Ut=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`}],Wt=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
322
- Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),Gt=new Set([...Ut.map(e=>e.name.split(` `)[0]),...Wt.keys()]);async function Kt(){console.log(`
320
+ `),c.push(u),c}const Xt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function H(e){return e.parent?.opts()?.dryRun??!1}function U(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(`
321
+ (dry run — no files were written)`),console.log()}async function Zt(e){if(!e)try{let e=await S(process.cwd());await O({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 Qt=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`}],$t=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
322
+ Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),en=new Set([...Qt.map(e=>e.name.split(` `)[0]),...$t.keys()]);async function tn(){console.log(`
323
323
  Built-in generators:
324
- `);let e=Math.max(...Ut.map(e=>e.name.length));for(let t of Ut)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await S(process.cwd()),n=Pe(t?.plugins??[],t?.commands??[]),r=await ue(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
324
+ `);let e=Math.max(...Qt.map(e=>e.name.length));for(let t of Qt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await S(process.cwd()),n=R(t?.plugins??[],t?.commands??[]),r=await ue(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
325
325
  Plugin generators:
326
326
  `);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(`
327
327
  Failed to load:
328
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function qt(e,t,n){let r=await S(process.cwd()),i=C(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??h(i.repo);t.repo&&je(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=Ae(r,process.cwd()),u=De(w()),d=Oe(w()),f=w(),m=ke(f,`@forinda/kickjs-testing`,`any`)&&ke(f,`supertest`,`any`),g=i.style??`define`;if(!n&&g===`define`){let e=await Nt(A(a),`define`);if(e.length>0){console.error(`\n ${p.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${p.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${p.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 ${p.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${p.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${p.dim(`// kick.config.ts`)}\n ${p.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await te({name:r,modulesDir:A(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:m,dryRun:n,pluralize:c,tokenScope:l,swagger:u,schemaLib:d,style:i.style});_.push(...e)}V(_,n),await Ht(n)}function Jt(t,n){let r=t.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,i,a)=>{if(i.list){await Kt();return}if(!t||t.length===0){r.help();return}let o=B(a);e(o);let[s,c,...l]=t;if(s){let e=await S(process.cwd()),t=Pe(e?.plugins??[],e?.commands??[]),r=await ie({generatorName:s,itemName:c??``,args:l,flags:i,cwd:process.cwd(),projectRoot:n?.projectRoot},t.generators);if(r){V(r.files,o);return}if(s!==`module`&&Gt.has(s)){let e=Wt.get(s);e?(console.error(`\n 'kick g ${s}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${s}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${s} ${c??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${s}' generator — upgrade it.\n`)),process.exitCode=1;return}}await qt(t,i,o)});r.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,n,r)=>{let i=B(r);e(i),await qt(t,{...r.optsWithGlobals(),...n},i)}),r.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(t,n,r)=>{let i=B(r);e(i),V(await be({name:t,outDir:A(n.out)}),i)}),r.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(t,n,r)=>{let i=B(r);e(i),V(await yt({name:t,outDir:A(n.out)}),i)}),r.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
329
- 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(t,n,r)=>{let i=B(r);e(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;V(await re({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,runtime:a?.runtime}),i)}),r.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
330
- 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(t,n,r)=>{let i=B(r);e(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;V(await ce({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
328
+ `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function nn(e,t,n){let r=await S(process.cwd()),i=C(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??g(i.repo);t.repo&&Me(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=je(r,process.cwd()),u=Oe(w()),d=ke(w()),f=w(),p=Ae(f,`@forinda/kickjs-testing`,`any`)&&Ae(f,`supertest`,`any`),h=i.style??`define`;if(!n&&h===`define`){let e=await Ht(M(a),`define`);if(e.length>0){console.error(`\n ${m.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${m.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${m.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 ${m.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${m.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${m.dim(`// kick.config.ts`)}\n ${m.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await te({name:r,modulesDir:M(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:p,dryRun:n,pluralize:c,tokenScope:l,swagger:u,schemaLib:d,style:i.style});_.push(...e)}U(_,n),await Zt(n)}function rn(e,n){let r=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,i,a)=>{if(i.list){await tn();return}if(!e||e.length===0){r.help();return}let o=H(a);t(o);let[s,c,...l]=e;if(s){let e=await S(process.cwd()),t=R(e?.plugins??[],e?.commands??[]),r=await ie({generatorName:s,itemName:c??``,args:l,flags:i,cwd:process.cwd(),projectRoot:n?.projectRoot},t.generators);if(r){U(r.files,o);return}if(s!==`module`&&en.has(s)){let e=$t.get(s);e?(console.error(`\n 'kick g ${s}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${s}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${s} ${c??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${s}' generator — upgrade it.\n`)),process.exitCode=1;return}}await nn(e,i,o)});r.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n,r)=>{let i=H(r);t(i),await nn(e,{...r.optsWithGlobals(),...n},i)}),r.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,n,r)=>{let i=H(r);t(i),U(await xe({name:e,outDir:M(n.out)}),i)}),r.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,n,r)=>{let i=H(r);t(i),U(await Ot({name:e,outDir:M(n.out)}),i)}),r.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
329
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await re({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,runtime:a?.runtime}),i)}),r.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
330
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await ce({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
331
331
  --type http (default, RequestContext) | bare (ExecutionContext)
332
332
  --params "source:string,region:number" → emits the withParams<T>() form
333
- 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(t,n,r)=>{let i=B(r);e(i);let a=(n.type??`http`).toLowerCase();a!==`http`&&a!==`bare`&&(console.warn(` kick g contributor: unknown --type '${n.type}', using 'http'.`),a=`http`);let o=await S(process.cwd()),s=C(o),c=s.dir??`src/modules`;V(await xt({name:t,type:a,key:n.key,params:n.params,outDir:n.out,moduleName:n.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),i)}),r.command(`service <name>`).description(`Generate a @Service() class
334
- 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(t,n,r)=>{let i=B(r);e(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;V(await le({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
335
- 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(t,n,r)=>{let i=B(r);e(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;V(await pe({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i),await Ht(i)}),r.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
336
- 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(t,n,r)=>{let i=B(r);e(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;V(await me({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,schemaLib:Oe(w())}),i)}),r.command(`test <name>`).description(`Generate a Vitest test scaffold
337
- 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(t,n,r)=>{let i=B(r);e(i);let a=C(await S(process.cwd())),o=a.dir??`src/modules`;V(await Bt({name:t,outDir:n.out,moduleName:n.module,modulesDir:o,pluralize:a.pluralize??!0}),i)}),r.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
333
+ 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,n,r)=>{let i=H(r);t(i);let a=(n.type??`http`).toLowerCase();a!==`http`&&a!==`bare`&&(console.warn(` kick g contributor: unknown --type '${n.type}', using 'http'.`),a=`http`);let o=await S(process.cwd()),s=C(o),c=s.dir??`src/modules`;U(await At({name:e,type:a,key:n.key,params:n.params,outDir:n.out,moduleName:n.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),i)}),r.command(`service <name>`).description(`Generate a @Service() class
334
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await le({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
335
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await me({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i),await Zt(i)}),r.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
336
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await he({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,schemaLib:ke(w())}),i)}),r.command(`test <name>`).description(`Generate a Vitest test scaffold
337
+ 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,n,r)=>{let i=H(r);t(i);let a=await S(process.cwd()),o=C(a),s=o.dir??`src/modules`;U(await Yt({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pluralize:o.pluralize??!0}),i)}),r.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
338
338
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
339
339
  Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
340
340
  Optional: append :optional (shell-safe): description:text:optional
341
- 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(t,n,r,i)=>{let a=B(i);e(a),n.length===0&&(console.error(`
341
+ 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,n,r,i)=>{let a=H(i);t(a),n.length===0&&(console.error(`
342
342
  Error: At least one field is required.
343
343
  Usage: kick g scaffold <name> <field:type> [field:type...]
344
344
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
345
345
  Optional: append :optional (shell-safe, no quoting needed)
346
- `),process.exit(1));let o=await S(process.cwd()),s=C(o),c=r.modulesDir??s.dir??`src/modules`,l=Ft(n),u=Ae(o,process.cwd()),d=De(w()),f=await It({name:t,fields:l,modulesDir:A(c),noEntity:r.entity===!1,noTests:r.tests===!1,pluralize:r.pluralize===!1?!1:s.pluralize??!0,tokenScope:u,swagger:d,style:s.style});console.log(`\n Scaffolded ${t} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);V(f,a),await Ht(a)}),r.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(t,n)=>{let r=B(n);e(r),V(await St({outDir:A(`.`),modulesDir:t.modulesDir,defaultRepo:t.repo,force:t.force}),r)}),r.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal | fullstack`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,n)=>{let r=B(n);e(r);let i=t.only??`all`;if(!Vt.includes(i)){console.error(` Invalid --only value: ${i}. Expected: ${Vt.join(` | `)}`),process.exitCode=1;return}V(await Ne({outDir:A(`.`),only:i,name:t.name,pm:t.pm,template:t.template,force:t.force}),r)});for(let e of n?.generators??[])Yt(r,e,n?.projectRoot)}function Yt(t,n,r){let{source:i,spec:a}=n,o=a.args?.[0],s=o?.name??`itemName`,c=o?.required?`<${s}>`:`[${s}]`,l=`${a.name} ${c} [extraArgs...]`,u=t.command(l).description(`${a.description} [${i}]`);for(let e of a.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;u.option(n,e.description??``)}u.action(async(t,i,o,s)=>{let c=B(s);e(c);let l=await ie({generatorName:a.name,itemName:t??``,args:i??[],flags:o,cwd:process.cwd(),projectRoot:r},[n]);l&&V(l.files,c)})}const Xt=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Zt(e){let t=D.resolve(e.cwd,`.kickjs/types`);e.check||await N(t,{recursive:!0});let n=new Map,r=e.scan??Be,i=D.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(I(e).href)},async writeFile(t,n){let r=D.resolve(e.cwd,t);await N(D.dirname(r),{recursive:!0}),await F(r,n,`utf8`)},getScanResult:e=>{let t=Qt(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Fe(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=D.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});o.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),s.push({id:n.id,status:`error`,outFile:i});continue}if(a===null){s.push({id:n.id,status:`skipped`});continue}let l=`${Xt}${n.id} */\n\n`+a+`
347
- `,u=``;if(j(i)&&(u=await P(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await F(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new ge(c);return s}function Qt(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 $t(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 H(e){let{enabled:t,skipped:n,unknown:r}=$t(Pe([...gi,...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 Zt({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&se())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof ge||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function en(e){let t=k(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=k(t,i);if(j(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function tn(e){let t=e.spawnFn??ut,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function nn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
346
+ `),process.exit(1));let o=await S(process.cwd()),s=C(o),c=r.modulesDir??s.dir??`src/modules`,l=Wt(n),u=je(o,process.cwd()),d=Oe(w()),f=await Gt({name:e,fields:l,modulesDir:M(c),noEntity:r.entity===!1,noTests:r.tests===!1,pluralize:r.pluralize===!1?!1:s.pluralize??!0,tokenScope:u,swagger:d,style:s.style});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);U(f,a),await Zt(a)}),r.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,n)=>{let r=H(n);t(r),U(await jt({outDir:M(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),r)}),r.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal | fullstack`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n)=>{let r=H(n);t(r);let i=e.only??`all`;if(!Xt.includes(i)){console.error(` Invalid --only value: ${i}. Expected: ${Xt.join(` | `)}`),process.exitCode=1;return}U(await Pe({outDir:M(`.`),only:i,name:e.name,pm:e.pm,template:e.template,force:e.force}),r)});for(let e of n?.generators??[])an(r,e,n?.projectRoot)}function an(e,n,r){let{source:i,spec:a}=n,o=a.args?.[0],s=o?.name??`itemName`,c=o?.required?`<${s}>`:`[${s}]`,l=`${a.name} ${c} [extraArgs...]`,u=e.command(l).description(`${a.description} [${i}]`);for(let e of a.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;u.option(n,e.description??``)}u.action(async(e,i,o,s)=>{let c=H(s);t(c);let l=await ie({generatorName:a.name,itemName:e??``,args:i??[],flags:o,cwd:process.cwd(),projectRoot:r},[n]);l&&U(l.files,c)})}const on=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function sn(e){let t=k.resolve(e.cwd,`.kickjs/types`);e.check||await pt(t,{recursive:!0});let n=new Map,r=e.scan??Ue,i=k.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(L(e).href)},async writeFile(t,n){let r=k.resolve(e.cwd,t);await pt(k.dirname(r),{recursive:!0}),await I(r,n,`utf8`)},getScanResult:e=>{let t=cn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Le(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=k.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});o.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),s.push({id:n.id,status:`error`,outFile:i});continue}if(a===null){s.push({id:n.id,status:`skipped`});continue}let l=`${on}${n.id} */\n\n`+a+`
347
+ `,u=``;if(N(i)&&(u=await F(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await I(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new _e(c);return s}function cn(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 ln(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var un=e({applyDisableFilter:()=>ln,runAllPluginTypegens:()=>W});async function W(e){let{enabled:t,skipped:n,unknown:r}=ln(R([...Fi,...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 sn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&se())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof _e||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function dn(e){let t=j(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=j(t,i);if(N(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function fn(e){let t=e.spawnFn??vt,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function pn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
348
348
  `):`${n.slice(0,t).join(`
349
- `)}\n… ${n.length-t} more line(s)`}function rn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function an(e,t=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function on(e,t,n={}){t&&(process.env.PORT=t);let r=rn(n.polling),i=process.cwd(),a=await S(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await E({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 He(c,await H({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);globalThis[oe]=`kick-dev`;let d=await u({configFile:A(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),f=n.typecheck??a?.dev?.typecheck??!1,p=null,m=!0;if(f){let e=en(i);e?p=tn({cwd:i,bin:e,onResult:e=>{d.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?m||(m=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(m=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(nn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let h=fe({cwd:i,config:a,emitWarning:e=>{console.warn(e),d.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>p?.schedule()});d.watcher.on(`add`,e=>h.handleWatchEvent(`add`,e)),d.watcher.on(`unlink`,e=>h.handleWatchEvent(`unlink`,e)),d.watcher.on(`change`,e=>h.handleWatchEvent(`change`,e)),d.watcher.on(`unlinkDir`,e=>h.handleWatchEvent(`unlinkDir`,e)),h.assetSrcRoots.length>0&&d.watcher.add([...h.assetSrcRoots]),await d.listen(),d.printUrls(),console.log(`
349
+ `)}\n… ${n.length-t} more line(s)`}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=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function gn(e,t,n={}){t&&(process.env.PORT=t);let r=mn(n.polling),i=process.cwd(),a=await S(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await O({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=M(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await W({cwd:i,config:a});await Ge(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(M(`package.json`)).resolve(`vite`),{createServer:d}=await import(L(u).href);globalThis[oe]=`kick-dev`;let f=await d({configFile:M(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=dn(i);e?m=fn({cwd:i,bin:e,onResult:e=>{f.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?h||(h=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(h=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(pn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let g=pe({cwd:i,config:a,emitWarning:e=>{console.warn(e),f.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>m?.schedule()});f.watcher.on(`add`,e=>g.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>g.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>g.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>g.handleWatchEvent(`unlinkDir`,e)),g.assetSrcRoots.length>0&&f.watcher.add([...g.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
350
350
  KickJS dev server running (Vite + @forinda/kickjs-vite)
351
- `),p?.schedule();let g=!1,_=async()=>{if(!g){g=!0,h.dispose(),p?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,_),process.on(`SIGTERM`,_),process.on(`SIGBREAK`,_)}async function sn(e){let t=await S(e);try{await E({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1}),await He(A(e,t?.typegen?.outDir??`.kickjs/types`),await H({cwd:e,config:t}),!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function cn(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await on(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
351
+ `),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await f.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}async function _n(e){let t=await S(e);try{await O({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1});let n=M(e,t?.typegen?.outDir??`.kickjs/types`),r=await W({cwd:e,config:t});await Ge(n,r,!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function vn(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await gn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
352
352
  Error: vite is not installed.
353
353
  Run: pnpm add -D vite unplugin-swc
354
354
  `):console.error(`
355
355
  Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
356
356
  Building for production...
357
- `);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 S(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
358
- Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?k(`dist`,e):e.dest??k(`dist`,t),r=A(t),i=A(n);if(!j(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}tt(i,{recursive:!0}),et(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
359
- Building asset map...`);try{await Me(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
357
+ `);let{createRequire:e}=await import(`node:module`),t=e(M(`package.json`)).resolve(`vite`),{build:n}=await import(L(t).href);await n({configFile:M(`vite.config.ts`)});let r=await S(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
358
+ Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?j(`dist`,e):e.dest??j(`dist`,t),r=M(t),i=M(n);if(!N(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}ct(i,{recursive:!0}),st(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
359
+ Building asset map...`);try{await Ne(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
360
360
  Build complete.
361
361
  `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await S(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
362
- Building asset map...`);try{await Me(e,{cwd:process.cwd()}),console.log(`
362
+ Building asset map...`);try{await Ne(e,{cwd:process.cwd()}),console.log(`
363
363
  Asset build complete.
364
- `)}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)),Ee(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=A(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await sn(t);let n=en(t);if(!n){console.error(`
364
+ `)}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)),De(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=M(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await _n(t);let n=dn(t);if(!n){console.error(`
365
365
  No type-checker found. Install one in this project:
366
366
  pnpm add -D typescript (tsc)
367
367
  pnpm add -D @typescript/native-preview (tsgo, faster)
368
- `),process.exit(1);return}let r=dt(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),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`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await an(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await on(e.entry,e.port)}catch(e){console.error(`
369
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function ln(){try{let e=O(ft(import.meta.url));return JSON.parse(M(k(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const un=new Set(Object.values(we).filter(e=>e.deprecated).map(e=>e.pkg));function dn(e){let t=k(e,`package.json`);if(!j(t))return[];let n;try{n=JSON.parse(M(t,`utf-8`))}catch{return[]}let r={...n.dependencies,...n.devDependencies};return Object.keys(r).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,i=k(e,`node_modules`,...t.split(`/`),`package.json`);if(j(i))try{n=JSON.parse(M(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:un.has(t)}})}function fn(e){let t=e;for(;;){if(j(k(t,`package.json`)))return t;let e=O(t);if(e===t)return null;t=e}}function pn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${ln()}`,``,` System:`,` OS: ${mt()} ${ht()} (${pt()})`,` Node: ${process.version}`],t=fn(process.cwd()),n=t?dn(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
370
- `))})}const{bold:U,dim:W,green:mn,red:G,yellow:hn,blue:gn}=p;function _n(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 vn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function K(e,t){try{return await vn(`${e}${t}`)}catch{return null}}async function yn(e){let[t,n,r,i,a]=await Promise.all([K(e,`/health`),K(e,`/metrics`),K(e,`/routes`),K(e,`/container`),K(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function bn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,c=W(`─`.repeat(60));if(console.log(),console.log(U(` KickJS Inspector`)+W(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?mn(`● healthy`):G(`● `+n.status);console.log(` ${U(`Health:`)} ${e}`)}else console.log(` ${U(`Health:`)} ${G(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?G:r.errorRate>0?hn:mn;console.log(` ${U(`Uptime:`)} ${_n(r.uptimeSeconds)}`),console.log(` ${U(`Requests:`)} ${r.requests}`),console.log(` ${U(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${W(`(`)}${t(e+`%`)}${W(`)`)}`)}if(a&&console.log(` ${U(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${U(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(U(` Routes`)),console.log(c),console.log(` ${W(`METHOD`)} ${W(`PATH`.padEnd(36))} ${W(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${s(e.method)} ${t} ${gn(e.controller)}.${W(e.handler)}`)}}console.log(c),console.log()}function xn(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 yn(r);t.json?console.log(JSON.stringify(e,null,2)):bn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(G(` ✖ Could not connect to ${n}`)),console.error(W(` ${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 q(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 Sn=[{match(e,t){let n=q(e,[`config`,`get`])&&J(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&J(e,[`undefined`,`is not defined`]);return!n&&!r?null:J(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
368
+ `),process.exit(1);return}let r=yt(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),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`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await hn(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await gn(e.entry,e.port)}catch(e){console.error(`
369
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function yn(){try{let e=A(bt(import.meta.url));return JSON.parse(P(j(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const bn=new Set(Object.values(Te).filter(e=>e.deprecated).map(e=>e.pkg));function xn(e){let t=j(e,`package.json`);if(!N(t))return[];let n;try{n=JSON.parse(P(t,`utf-8`))}catch{return[]}let r={...n.dependencies,...n.devDependencies};return Object.keys(r).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,i=j(e,`node_modules`,...t.split(`/`),`package.json`);if(N(i))try{n=JSON.parse(P(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:bn.has(t)}})}function Sn(e){let t=e;for(;;){if(N(j(t,`package.json`)))return t;let e=A(t);if(e===t)return null;t=e}}function Cn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${yn()}`,``,` System:`,` OS: ${Ct()} ${wt()} (${St()})`,` Node: ${process.version}`],t=Sn(process.cwd()),n=t?xn(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
370
+ `))})}const{bold:G,dim:K,green:wn,red:q,yellow:Tn,blue:En}=m;function Dn(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 On(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await On(`${e}${t}`)}catch{return null}}async function kn(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function An(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=K(`─`.repeat(60));if(console.log(),console.log(G(` KickJS Inspector`)+K(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?wn(`● healthy`):q(`● `+n.status);console.log(` ${G(`Health:`)} ${e}`)}else console.log(` ${G(`Health:`)} ${q(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?q:r.errorRate>0?Tn:wn;console.log(` ${G(`Uptime:`)} ${Dn(r.uptimeSeconds)}`),console.log(` ${G(`Requests:`)} ${r.requests}`),console.log(` ${G(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${K(`(`)}${t(e+`%`)}${K(`)`)}`)}if(a&&console.log(` ${G(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${G(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(G(` Routes`)),console.log(s),console.log(` ${K(`METHOD`)} ${K(`PATH`.padEnd(36))} ${K(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${c(e.method)} ${t} ${En(e.controller)}.${K(e.handler)}`)}}console.log(s),console.log()}function jn(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 kn(r);t.json?console.log(JSON.stringify(e,null,2)):An(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(q(` ✖ Could not connect to ${n}`)),console.error(K(` ${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 Y(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function X(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Mn=[{match(e,t){let n=Y(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
371
371
  src/config/index.ts, and src/index.ts imports it before bootstrap().
372
372
  Tests never load src/index.ts — \`createTestApp\` builds the app
373
373
  directly — so that import does not run and ConfigService falls back to
@@ -391,7 +391,7 @@ import { modules } from './modules'
391
391
  import './config' // ← add this — registers env schema
392
392
  import { bootstrap } from '@forinda/kickjs'
393
393
  import { modules } from './modules'
394
- `,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=J(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);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.
394
+ `,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return X(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.
395
395
  When vitest re-imports your modules across tests, the same class can be
396
396
  registered twice and the container throws. The fix is to wipe the
397
397
  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'
@@ -401,7 +401,7 @@ describe('UserController', () => {
401
401
  beforeEach(() => Container.reset())
402
402
 
403
403
  it('does the thing', async () => { /* ... */ })
404
- })`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||q(e,[`Module`,`is not a function`])||q(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
404
+ })`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Y(e,[`Module`,`is not a function`])||Y(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
405
405
  pattern instead: a class implements AppModule and exposes routes() that
406
406
  returns the controller wiring. This was a deliberate choice — modules
407
407
  become explicit values rather than metadata, which makes them easier to
@@ -428,7 +428,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
428
428
  and matches the actual class names so refactors propagate via
429
429
  rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
430
430
  create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
431
- create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/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
431
+ create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=X(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=X(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
432
432
  cluster: { workers: N }, the framework forks N workers, each of which
433
433
  spins up its own Vite instance on a separate port. The fix landed in
434
434
  v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
@@ -436,7 +436,7 @@ silently skips cluster, with a warning. If you see this on an older
436
436
  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({
437
437
  modules,
438
438
  cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
439
- })`,docs:`https://kickjs.app/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
439
+ })`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return X(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
440
440
  reflect-metadata polyfill. The polyfill must be imported once,
441
441
  before any decorator runs. Most projects do this at the top of
442
442
  src/index.ts; missing the import causes obscure "design:paramtypes"
@@ -445,7 +445,7 @@ import './config'
445
445
  import { bootstrap } from '@forinda/kickjs'
446
446
  import { modules } from './modules'
447
447
 
448
- export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/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
448
+ export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return X(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
449
449
  generated a module via \`kick g module foo\` but the routes don't appear,
450
450
  the most likely cause is that the module is missing from the exported
451
451
  array. The CLI usually wires this automatically, but a hand-edit can
@@ -453,7 +453,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
453
453
  import { UserModule } from './users/user.module'
454
454
  import { TaskModule } from './tasks/task.module' // ← was this missing?
455
455
 
456
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!J(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=J(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=J(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&J(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
456
+ export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!X(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=X(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=X(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&X(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
457
457
  That protects the vars your test runner pinned — but every var it did NOT
458
458
  pin is silently backfilled from your \`.env\`. So a suite can pin its database
459
459
  URL and still reach live development services through the vars it forgot,
@@ -487,7 +487,7 @@ beforeAll(() => {
487
487
  vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
488
488
  resetEnvCache()
489
489
  loadEnv(envSchema)
490
- })`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=q(e,[`cannot inject`,`request-scoped`,`singleton`]),r=q(e,[`request-scoped`,`singleton`]);return!n&&!r?null:{confidence:n?100:70,diagnosis:{id:`di-request-scope-into-singleton`,title:`A SINGLETON cannot hold a REQUEST-scoped dependency`,explanation:`Controllers are SINGLETON by default: one instance for the process, built
490
+ })`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=Y(e,[`cannot inject`,`request-scoped`,`singleton`]),r=Y(e,[`request-scoped`,`singleton`]);return!n&&!r?null:{confidence:n?100:70,diagnosis:{id:`di-request-scope-into-singleton`,title:`A SINGLETON cannot hold a REQUEST-scoped dependency`,explanation:`Controllers are SINGLETON by default: one instance for the process, built
491
491
  the first time the container resolves it. A REQUEST-scoped binding is the
492
492
  opposite — one instance per request, discarded when the response ends.
493
493
 
@@ -497,19 +497,18 @@ later request, so the container refuses at resolve time instead.
497
497
 
498
498
  This surfaces on the first request that reaches the controller, not at
499
499
  boot, because the container builds lazily. The route mounts fine and then
500
- answers 500.`,fix:`The error says "use TRANSIENT or REQUEST scope for the parent", and that
501
- is the fix when the parent is a @Service / @Repository / @Component —
502
- each takes \`{ scope }\`.
500
+ answers 500.`,fix:`When the parent is a @Service / @Repository / @Component, give it
501
+ TRANSIENT or REQUEST scope — each takes \`{ scope }\`.
503
502
 
504
503
  @Controller() does NOT. It takes no options and always registers as a
505
- SINGLETON, so for a controller the advice in the message is not
506
- available. Switch that one dependency to @Autowired instead: property
504
+ SINGLETON (older versions of the error still advised changing its scope,
505
+ which is not available). Switch that one dependency to @Autowired instead: property
507
506
  injection re-resolves per access, so each request reads its own instance
508
507
  and the singleton never captures one.
509
508
 
510
509
  If the dependency did not need request scope in the first place, the
511
510
  other direction also works — make it SINGLETON and pass the per-request
512
- values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=q(e,[`circular`,`dependency`]);return!n&&!r?null:{confidence:n?100:65,diagnosis:{id:`di-circular-dependency`,title:`Two services depend on each other, directly or through a chain`,explanation:`The container resolves constructor dependencies depth-first. When a token
511
+ values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=Y(e,[`circular`,`dependency`]);return!n&&!r?null:{confidence:n?100:65,diagnosis:{id:`di-circular-dependency`,title:`Two services depend on each other, directly or through a chain`,explanation:`The container resolves constructor dependencies depth-first. When a token
513
512
  is requested while it is already being resolved further up the stack, the
514
513
  graph has a cycle and there is no order that satisfies both ends.
515
514
 
@@ -541,7 +540,7 @@ export class OrderService {
541
540
  @Service()
542
541
  export class BillingService {
543
542
  @Autowired() private readonly orders!: OrderService // ← resolved after construction
544
- }`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=J(e,[`no provider for`,`no provider found for`,`no binding is registered`]);return!n&&!r?null:{confidence:n?100:85,diagnosis:{id:`di-no-provider-for-token`,title:`A token was requested but nothing registers it`,explanation:`Decorators register bindings as a side effect of the class being LOADED —
543
+ }`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=X(e,[`no provider for`,`no provider found for`,`no binding is registered`]);return!n&&!r?null:{confidence:n?100:85,diagnosis:{id:`di-no-provider-for-token`,title:`A token was requested but nothing registers it`,explanation:`Decorators register bindings as a side effect of the class being LOADED —
545
544
  and a class is only loaded if something imports it. A module that is not
546
545
  in the bootstrap array is never imported, so none of its @Service /
547
546
  @Repository / @Controller classes ever register, and the first thing that
@@ -567,7 +566,7 @@ export const TenantModule = defineModule({
567
566
  },
568
567
  routes: () => null,
569
568
  }),
570
- })`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!J(e,[`vite`,`kick dev`,`dev server`,`localhost:5173`,`:5173`])||!J(e,[`404`,`not found`,`cannot get`,`cannot post`,`no route`]))return null;let n=q(e,[`app`,`export`]),r=J(e,[`every route`,`all routes`,`every endpoint`,`all endpoints`,`none of the routes`]);return!n&&!r?null:{confidence:n&&r?85:n?80:70,diagnosis:{id:`vite-dev-app-not-exported`,title:"Every route 404s in dev because the entry file exports no `app`",explanation:`The Vite plugin does not start your server. It imports the entry module
569
+ })`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!X(e,[`vite`,`kick dev`,`dev server`,`localhost:5173`,`:5173`])||!X(e,[`404`,`not found`,`cannot get`,`cannot post`,`no route`]))return null;let n=Y(e,[`app`,`export`]),r=X(e,[`every route`,`all routes`,`every endpoint`,`all endpoints`,`none of the routes`]);return!n&&!r?null:{confidence:n&&r?85:n?80:70,diagnosis:{id:`vite-dev-app-not-exported`,title:"Every route 404s in dev because the entry file exports no `app`",explanation:`The Vite plugin does not start your server. It imports the entry module
571
570
  and reads \`app\` off it, then hands each request to that instance.
572
571
 
573
572
  When the entry runs \`await bootstrap(...)\` without assigning the result to
@@ -583,24 +582,24 @@ import { bootstrap } from '@forinda/kickjs'
583
582
  await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
584
583
  import { bootstrap } from '@forinda/kickjs'
585
584
 
586
- export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Cn(e,t){let n=null;for(let r of Sn){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 wn(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.
585
+ export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Nn(e,t){let n=null;for(let r of Mn){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 Pn(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.
587
586
  export OPENAI_API_KEY="sk-..."
588
587
 
589
588
  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:
590
589
  kick add ai
591
590
 
592
591
  Or manually:
593
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Tn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=En((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 Tn(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
594
- `)}function En(e){let t=[e,Dn(e),On(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(kn(t))return t}catch{continue}return null}function Dn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function On(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 kn(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 An(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 Nn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
592
+ pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Fn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=In((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 Fn(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
593
+ `)}function In(e){let t=[e,Ln(e),Rn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(zn(t))return t}catch{continue}return null}function Ln(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Rn(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 zn(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 Bn(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 Un(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
595
594
 
596
595
  Pass a message as a positional arg, --message flag, or pipe via stdin:
597
596
  kick explain "config.get returned undefined"
598
597
  pnpm test 2>&1 | kick explain
599
- `),process.exit(1));let r=Fn(),i=Cn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
600
- `);return}if(i){In(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
601
- `),process.exit(2)),Ln(n,!1),process.exit(2));let a=await wn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(jn(a),null,2)+`
602
- `),process.exit(a.kind===`ok`?0:2)),Mn(n,a),process.exit(a.kind===`ok`?0:2)})}function jn(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 Mn(e,t){if(t.kind===`ok`){In(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 Nn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Pn()}function Pn(){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 Fn(){let e=process.cwd();return{cwd:e,hasFile:t=>j(A(e,t))}}function In(e,t,n,r=!1){let i=X(e.trim(),200),a=r?`AI-generated — verify before applying`:Rn(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(`
603
- `)}function Ln(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.
598
+ `),process.exit(1));let r=Gn(),i=Nn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
599
+ `);return}if(i){Kn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
600
+ `),process.exit(2)),qn(n,!1),process.exit(2));let a=await Pn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Vn(a),null,2)+`
601
+ `),process.exit(a.kind===`ok`?0:2)),Hn(n,a),process.exit(a.kind===`ok`?0:2)})}function Vn(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 Hn(e,t){if(t.kind===`ok`){Kn(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Jn(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Jn(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Un(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Wn()}function Wn(){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 Gn(){let e=process.cwd();return{cwd:e,hasFile:t=>N(M(e,t))}}function Kn(e,t,n,r=!1){let i=Jn(e.trim(),200),a=r?`AI-generated — verify before applying`:Yn(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${Z(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Z(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Z(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Z(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
602
+ `)}function qn(e,t){let n=Jn(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.
604
603
  When @forinda/kickjs-ai ships its provider implementations,
605
604
  this command will call the configured LLM with the error +
606
605
  project context and return a structured fix.
@@ -617,12 +616,12 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
617
616
  3. File an issue with the error text:
618
617
  https://github.com/forinda/kick-js/issues/new
619
618
 
620
- `)}function Y(e,t){return e.split(`
619
+ `)}function Z(e,t){return e.split(`
621
620
  `).map(e=>`${t}${e}`).join(`
622
- `)}function X(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Rn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function zn(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(Bn),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(Vn)}function Bn(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=ut(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 Vn(e){let t=process.cwd(),n=Hn(t)??Ze(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=M(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,it(i,JSON.stringify(o,null,2)+`
623
- `,`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 Hn(e){let t=A(e,`package.json`);if(!j(t))return null;try{let e=M(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Un(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=Gn(t,`tsx`);r||(console.error(`
621
+ `)}function Jn(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Yn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Xn(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(Zn),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(Qn)}function Zn(e){let t=M(e.entry);N(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=vt(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 Qn(e){let t=process.cwd(),n=$n(t)??it(t),r=e.name??n,i=e.global?M(process.env.HOME??`.`,`.mcp.json`):M(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(N(i))try{let e=P(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,dt(i,JSON.stringify(o,null,2)+`
622
+ `,`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 $n(e){let t=M(e,`package.json`);if(!N(t))return null;try{let e=P(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function er(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=M(t,e.entry);N(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=nr(t,`tsx`);r||(console.error(`
624
623
  Error: tsx not found. Install it: pnpm add -D tsx
625
- `),process.exit(1));let i=Wn(n,e.entry),a=k(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=lt(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Wn(e,t){return`
624
+ `),process.exit(1));let i=tr(n,e.entry),a=j(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=_t(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function tr(e,t){return`
626
625
  import 'reflect-metadata'
627
626
 
628
627
  // Prevent bootstrap() from starting the HTTP server
@@ -647,7 +646,7 @@ try {
647
646
 
648
647
  // Load entry to trigger decorator registration
649
648
  try {
650
- await import('${I(e).href}')
649
+ await import('${L(e).href}')
651
650
  } catch (err) {
652
651
  console.warn(' Warning: ' + err.message)
653
652
  console.warn(' Container may be partially initialized.\\n')
@@ -676,36 +675,38 @@ server.on('exit', () => {
676
675
  console.log('\\n Goodbye!\\n')
677
676
  process.exit(0)
678
677
  })
679
- `}function Gn(e,t){let n=e;for(;;){let e=k(n,`node_modules`,`.bin`,t);if(j(e))return e;let r=A(n,`..`);if(r===n)break;n=r}return null}function Kn(e,t){let n=RegExp(`^\\s*${x(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]!==`
678
+ `}function nr(e,t){let n=e;for(;;){let e=j(n,`node_modules`,`.bin`,t);if(N(e))return e;let r=M(n,`..`);if(r===n)break;n=r}return null}function rr(e,t){let n=RegExp(`^\\s*${fe(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]!==`
680
679
  `;)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]===`
681
- `);)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=ye(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Kn(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${x(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 Jn(e){let{name:t,modulesDir:r,force:i}=e,a=e.pluralize!==!1,o=y(t),s=b(t),c=a?m(o):o,l=k(r,c);if(!await n(l)){console.log(`\n Module not found: ${l}\n`);return}if(!i&&!await f({message:p.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
680
+ `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function ir(e,t){let n=be(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=rr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${fe(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 ar(e){let{name:t,modulesDir:n,force:i}=e,a=e.pluralize!==!1,o=b(t),s=x(t),c=a?h(o):o,l=j(n,c);if(!await r(l)){console.log(`\n Module not found: ${l}\n`);return}if(!i&&!await p({message:m.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
682
681
  Cancelled.
683
- `);return}await st(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let u=k(r,`index.ts`);if(await n(u)){let e=await P(u,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${x(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${x(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=qn(e,s),e=e.replace(/\n{3,}/g,`
682
+ `);return}await ht(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let u=j(n,`index.ts`);if(await r(u)){let e=await F(u,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${fe(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${fe(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=ir(e,s),e=e.replace(/\n{3,}/g,`
684
683
 
685
- `),e!==t&&(await F(u,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${u}`))}console.log(`\n Module '${c}' removed.\n`)}function Yn(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=C(await S(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Jn({name:n,modulesDir:A(r),force:t.force,pluralize:i})})}function Xn(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 Zn(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Qn(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=w(process.cwd()),n=await S(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-Cfiz2G3K.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-Cj4BWpIe.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(`
684
+ `),e!==t&&(await I(u,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${u}`))}console.log(`\n Module '${c}' removed.\n`)}function or(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=await S(process.cwd()),r=C(n),i=t.modulesDir??r.dir??`src/modules`,a=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await ar({name:n,modulesDir:M(i),force:t.force,pluralize:a})})}function sr(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 cr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function lr(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=w(process.cwd()),n=await S(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DKzw-J38.mjs`),{builtinCliPlugins:t}=await import(`./builtins-Clx2eHtk.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(`
686
685
  Registered typegen plugins:
687
686
  `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``,n=`${e.id.replace(/\//g,`__`)}${e.outExtension??`.d.ts`}`;console.log(` ${e.id.padEnd(a+2)}→ .kickjs/types/${n}${t}`),console.log(` ${` `.repeat(a+2)} watches: ${e.inputs.join(`, `)||`(none)`}`)}console.log(`
688
687
  Disable one in kick.config.ts:
689
688
  `),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
690
- `);return}let r=Xn(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Zn(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await qe(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 E(a);let r=await H({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 He(A(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof Je?console.error(`
689
+ `);return}let r=sr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=cr(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await Xe(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 O(a);let r=await W({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=M(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await Ge(i,r,e.silent??!1)}}}catch(e){e instanceof Ze?console.error(`
691
690
  `+e.message+`
692
- `):e instanceof ge?console.error(`
691
+ `):e instanceof _e?console.error(`
693
692
  `+e.message+`
694
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function $n(e){let t=[];if(!j(e))return t;let n=nt(e,{withFileTypes:!0});for(let r of n){let n=k(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...$n(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function er(e){try{return M(e,`utf-8`)}catch{return``}}const tr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function nr(e,t){let n=er(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(tr.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 rr(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 ir(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 ar(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function or(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 sr(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 cr(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 lr(e){let t=$n(k(e,`src`)).map(e=>er(e)),n=[],r=nr(e,t);r&&n.push(r);let i=rr(t);i&&n.push(i);let a=ir(t);a&&n.push(a);let o=ar();o&&n.push(o);let s=or(t);return s&&n.push(s),n.push(sr(t)),n.push(cr(t)),n}function ur(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
695
- Usage: kick check --deploy
693
+ `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const ur=new Set([`Service`,`Injectable`,`Component`,`Repository`]);function dr(e,t){return typeof t==`number`?e.slice(0,t).split(`
694
+ `).length:1}function fr(e){let t=et(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(Fe(e)&&e.type===`MemberExpression`&&D(e.object)===`Scope`){let t=D(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function pr(e){let t=D(e);if(t)return{key:`id:${t}`,label:t};let n=et(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function mr(e,t){let n=(e.body?.body??[]).find(e=>e.type===`MethodDefinition`&&e.kind===`constructor`)?.value?.params??[],r=[];for(let e of n){let n=e.type===`TSParameterProperty`?e.parameter:e,i=nt(e).map($e).find(e=>e?.name===`Inject`),a=null;if(i)a=pr(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=pr(e.typeName))}a&&r.push({...a,line:dr(t,e.start)})}return r}function hr(e){let t=new Map,n=new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=xt(t,n);if(r.errors.length>0)continue;e=r.program}catch{continue}for(let n of e.body??[]){let e=(n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`)&&Fe(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(D(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(D(n.id),t)}Ie(e,e=>{if(e.type===`ClassDeclaration`){let a=D(e.id);if(!a)return;for(let o of nt(e)){let s=$e(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:mr(e,n)});return}if(ur.has(s.name)){let o=tt(ze(s.call),`scope`),c=o?fr(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:mr(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!Fe(a)||a.type!==`MemberExpression`)return;let o=D(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=pr(s[0]);c&&i(c.key,s.length>=3?fr(s[2]):`singleton`)})}let o=e=>(n.get(e)?.size??0)<=1,s=(e,n)=>{let r=t.get(e);return r?.size===1&&r.has(n)},c=[];for(let e of r)if(o(e.name)&&s(`id:${e.name}`,`singleton`))for(let t of e.params){if(t.key.startsWith(`id:`)&&!o(t.label)||!s(t.key,`request`))continue;let n=e.kind===`controller`?`@Controller() is always SINGLETON, so inject ${t.label} with @Autowired() instead of the constructor.`:`Give ${e.name} TRANSIENT or REQUEST scope, or inject ${t.label} with @Autowired() instead of the constructor.`;c.push({file:e.file,line:t.line,parent:e.name,dependency:t.label,message:`${e.name} (SINGLETON) injects REQUEST-scoped ${t.label} through its constructor — the first request that resolves it answers 500. ${n}`})}return c}function gr(e){let t=[];if(!N(e))return t;let n=lt(e,{withFileTypes:!0});for(let r of n){let n=j(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...gr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function _r(e){try{return P(e,`utf-8`)}catch{return``}}const vr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function yr(e,t){let n=_r(j(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(vr.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 br(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 xr(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 Sr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Cr(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 wr(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 Tr(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 Er(e){let t=gr(j(e,`src`)).map(e=>_r(e)),n=[],r=yr(e,t);r&&n.push(r);let i=br(t);i&&n.push(i);let a=xr(t);a&&n.push(a);let o=Sr();o&&n.push(o);let s=Cr(t);return s&&n.push(s),n.push(wr(t)),n.push(Tr(t)),n}function Dr(e){let t=hr(gr(j(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:at(e,t).split(`\\`).join(`/`),source:_r(t)})));return t.length===0?[{severity:`INFO`,message:`No REQUEST-scoped dependency injected into a singleton`}]:t.map(e=>({severity:`CRITICAL`,message:`${e.file}:${e.line} ${e.message}`}))}function Or(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).option(`--di`,`Find REQUEST-scoped dependencies injected into singletons`).action(e=>{if(!e.deploy&&!e.di){console.log(`
695
+ Usage: kick check [--deploy] [--di]
696
696
 
697
697
  Available checks:
698
698
  --deploy Audit for production readiness (security, config, best practices)
699
- `);return}let t=process.cwd();c(`KickJS Deploy Check`);let n=d();n.start(`Scanning project...`);let i=lr(t);n.stop(`Scan complete`);let o={CRITICAL:0,WARNING:1,INFO:2};i.sort((e,t)=>o[e.severity]-o[t.severity]);for(let e of i)u.message(`${a(e.severity)} ${e.message}`);let s=i.filter(e=>e.severity===`CRITICAL`).length,l=i.filter(e=>e.severity===`WARNING`).length,f=i.filter(e=>e.severity===`INFO`).length,m=l===1?`warning`:`warnings`,h=[s>0?p.red(`${s} critical`):`${s} critical`,l>0?p.yellow(`${l} ${m}`):`${l} ${m}`,`${f} info`].join(`, `);s>0?(r(p.red(`${h} — fix critical issues before deploying`)),process.exit(1)):r(p.green(`${h} — looking good!`))})}function dr(e){return e.optsWithGlobals().dryRun??!1}function fr(t){t.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.
699
+ --di Find REQUEST-scoped dependencies injected into singleton constructors
700
+ `);return}let t=process.cwd();l(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=f();n.start(`Scanning project...`);let r=[...e.deploy?Er(t):[],...e.di?Dr(t):[]];n.stop(`Scan complete`);let a={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>a[e.severity]-a[t.severity]);for(let e of r)d.message(`${o(e.severity)} ${e.message}`);let s=r.filter(e=>e.severity===`CRITICAL`).length,c=r.filter(e=>e.severity===`WARNING`).length,u=r.filter(e=>e.severity===`INFO`).length,p=c===1?`warning`:`warnings`,h=[s>0?m.red(`${s} critical`):`${s} critical`,c>0?m.yellow(`${c} ${p}`):`${c} ${p}`,`${u} info`].join(`, `);s>0?(i(m.red(`${h} — fix critical issues before deploying`)),process.exit(1)):i(m.green(`${h} — looking good!`))})}function kr(e){return e.optsWithGlobals().dryRun??!1}function Ar(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.
700
701
  Direction defaults to \`modules.style\` from kick.config (or "define").
701
702
  --target define|class Override the migration direction.
702
703
  --apply Apply the changes (default: dry-run preview).
703
- --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(t,n)=>{let r=dr(n)||!t.apply;e(r),t.experimental||(console.error(`
704
- `+p.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
704
+ --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,n)=>{let r=kr(n)||!e.apply;t(r),e.experimental||(console.error(`
705
+ `+m.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
705
706
  The regex-based rewrite handles the shapes our templates produce.
706
707
  Hand-rolled modules with non-standard structures may be skipped.
707
708
  Always commit before running with --apply.
708
- `),process.exit(1));let i=C(await S(process.cwd())),a=A(t.modulesDir??i.dir??`src/modules`),o;t.target===`define`||t.target===`class`?o=t.target:t.target===void 0?o=i.style??`define`:(console.error(`\n ${p.red(`Error:`)} --target must be 'define' or 'class' (got '${t.target}').\n`),process.exit(1));let s=p.dim(`→ ${o}`),c=r?p.dim(`(dry-run)`):p.bold(`(applying)`);console.log(`\n ${p.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${p.dim(a)}\n`);let l=t.backup!==!1&&!r,u=await Mt(a,{dryRun:r,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${p.green(`✓`)} backup: ${p.dim(e)}\n ${p.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&t.backup===!1&&console.log(` ${p.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${p.green(`✓`)} ${e.path}`);else{f++;let t=p.dim(`(${e.reason??`skipped`})`);console.log(` ${p.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${p.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=p.dim(`(${u.indexReason??`skipped`})`);console.log(` ${p.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${p.dim(`-`)} ${u.indexPath} ${p.dim(`(not found)`)}`);let m=r?p.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${p.bold(String(d))} migrated, ${p.bold(String(f))} skipped${m}\n`)})}const pr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!j(D.resolve(e.cwd,`kick.config.ts`)))return null;let t=await S(e.cwd);if(!t?.assetMap)return null;let n=Ie(t.assetMap,e.cwd);return n.count===0?null:Ge(n)}}),mr="/* 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 hr(e,t,n,r={}){if(e.length===0)return`${mr}
709
+ `),process.exit(1));let i=await S(process.cwd()),a=C(i),o=M(e.modulesDir??a.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=a.style??`define`:(console.error(`\n ${m.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=m.dim(`→ ${s}`),l=r?m.dim(`(dry-run)`):m.bold(`(applying)`);console.log(`\n ${m.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${m.dim(o)}\n`);let u=e.backup!==!1&&!r,d=await Vt(o,{dryRun:r,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${m.green(`✓`)} backup: ${m.dim(e)}\n ${m.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&e.backup===!1&&console.log(` ${m.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${m.green(`✓`)} ${e.path}`);else{p++;let t=m.dim(`(${e.reason??`skipped`})`);console.log(` ${m.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${m.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=m.dim(`(${d.indexReason??`skipped`})`);console.log(` ${m.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${m.dim(`-`)} ${d.indexPath} ${m.dim(`(not found)`)}`);let h=r?m.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${m.bold(String(f))} migrated, ${m.bold(String(p))} skipped${h}\n`)})}const jr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=k.resolve(e.cwd,`kick.config.ts`);if(!N(t))return null;let n=await S(e.cwd);if(!n?.assetMap)return null;let r=Re(n.assetMap,e.cwd);return r.count===0?null:Je(r)}}),Mr="/* 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 Nr(e,t,n,r={}){if(e.length===0)return`${Mr}
709
710
  // (no routes discovered yet — annotate a controller method with
710
711
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
711
712
  declare global {
@@ -722,18 +723,18 @@ declare global {
722
723
 
723
724
  /** Empty until the first route exists — see kick typegen. */
724
725
  export const kickRpc = {} as const
725
- `;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=yr(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??_r(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=vr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${gr(e)}`,` }`)}n.push(` }`),l.push(n.join(`
726
+ `;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=Lr(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??Fr(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=Ir(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${Pr(e)}`,` }`)}n.push(` }`),l.push(n.join(`
726
727
  `))}let u=[],d=new Set,f=new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;if(d.has(t)){r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`);continue}d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`)}let p=[` interface Api {`,...u,` }`].join(`
727
- `);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=Sr(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
728
+ `);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=Br(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
728
729
  `)}\n },`)}let g=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...m,`} as const`].join(`
729
- `),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=xr(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
730
+ `),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=zr(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
730
731
  `)+`
731
- `:``,ee=br(a)+y,b=l.join(`
732
- `);return`${mr}${ee}
732
+ `:``,b=Rr(a)+y,ee=l.join(`
733
+ `);return`${Mr}${b}
733
734
  declare global {
734
735
  // eslint-disable-next-line @typescript-eslint/no-namespace
735
736
  namespace KickRoutes {
736
- ${b}
737
+ ${ee}
737
738
  }
738
739
 
739
740
  /** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
@@ -741,18 +742,18 @@ ${b}
741
742
  }
742
743
 
743
744
  ${g}
744
- `}function gr(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function _r(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 vr(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 yr(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=xr(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 br(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(`
745
+ `}function Pr(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Fr(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 Ir(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 Lr(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=zr(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 Rr(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(`
745
746
  `)+`
746
- `}function xr(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=Qe(r,t).split($e).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=Qe(r,A(O(t),e)).split($e).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Sr(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const Cr=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:wr(e),cwd:e.cwd,envFile:Tr(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return hr(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function wr(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Tr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Z=`@typescript/typescript6`;function Er(e){return typeof e?.createProgram==`function`}function Dr(e){if(Er(e.typescript))return{api:e.typescript,source:`typescript`};if(Er(e.ts6))return{api:e.ts6,source:Z};let t=`Install it in the project:\n pnpm add -D ${Z}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
747
- TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${Z}' resolved from this project.\n ${t}`)}async function Or(e){let t=Xe(k(e,`package.json`)),n=async e=>{try{return await import(I(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Z)]);return Dr({typescript:kr(r),ts6:kr(i)}).api}function kr(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Ar=Symbol(`kick/client: expansion budget exhausted`);var jr=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==Ar)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw Ar;return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`}if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
747
+ `}function zr(e,t,n){if(e===null)return`unknown`;let r=A(n);if(e===``){let e=at(r,t).split(ot).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=A(t),a=M(i,e),o=at(r,a).split(ot).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function Br(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const Vr=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Hr(e),cwd:e.cwd,envFile:Ur(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=k.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Nr(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Hr(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ur(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Wr=`@typescript/typescript6`;function Gr(e){return typeof e?.createProgram==`function`}function Kr(e){if(Gr(e.typescript))return{api:e.typescript,source:`typescript`};if(Gr(e.ts6))return{api:e.ts6,source:Wr};let t=`Install it in the project:\n pnpm add -D ${Wr}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
748
+ TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${Wr}' resolved from this project.\n ${t}`)}async function qr(e){let t=rt(j(e,`package.json`)),n=async e=>{try{return await import(L(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Wr)]);return Kr({typescript:Jr(r),ts6:Jr(i)}).api}function Jr(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Yr=Symbol(`kick/client: expansion budget exhausted`);var Xr=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==Yr)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw Yr;return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`}if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
748
749
  `){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType,void 0,this.printFlags);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=this.typeOfProperty(r);if(this.isCallable(e)||r.getName().startsWith(`__@`))continue;let a=(r.flags&this.ts.SymbolFlags.Optional)!==0,o=this.renderPropertyType(e,a,r,t+1),s=this.isReadonlyProp(r)?`readonly `:``;i.push(`${n}${s}${this.propName(r.getName())}${a?`?`:``}: ${o}`)}return i.join(r===`
749
750
  `?`
750
- `:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const Mr=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Nr=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Pr(e){return gt(`sha1`).update(e).digest(`hex`)}function Fr(e){let t=gt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
751
- `));for(let n of Mr){let r=k(e.projectDir,n);if(j(r))try{t.update(M(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Nr.test(n)){t.update(n);try{t.update(M(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Ir(e){try{let t=await Or(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(k(e.projectDir,`tsconfig.json`),{},n);return r?Fr({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function Lr(e){let t=await Or(e.compilerFrom??e.projectDir),n=k(O(e.routesFile),`__kick_client_probe__.ts`),r=Br(e.routesFile,e.keys),i=Ur(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);Rr(t,i,e.routesFile);let s=Vr(t,i,o,e.keys),c=null,l=new jr(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===zr(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function Rr(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
752
- `);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function zr(e){return`_K${e}`}function Br(e,t){let n=`./`+Ze(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${zr(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
751
+ `:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const Zr=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Qr=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function $r(e){return Tt(`sha1`).update(e).digest(`hex`)}function ei(e){let t=Tt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
752
+ `));for(let n of Zr){let r=j(e.projectDir,n);if(N(r))try{t.update(P(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Qr.test(n)){t.update(n);try{t.update(P(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function ti(e){try{let t=await qr(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(j(e.projectDir,`tsconfig.json`),{},n);return r?ei({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function ni(e){let t=await qr(e.compilerFrom??e.projectDir),n=j(A(e.routesFile),`__kick_client_probe__.ts`),r=ai(e.routesFile,e.keys),i=ci(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);ri(t,i,e.routesFile);let s=oi(t,i,o,e.keys),c=null,l=new Xr(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===ii(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function ri(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
753
+ `);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function ii(e){return`_K${e}`}function ai(e,t){let n=`./`+it(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${ii(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
753
754
  `)+`
754
- `}function Vr(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(zr(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Hr(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=nt(t).filter(e=>e.endsWith(`.ts`)).map(e=>k(t,e))}catch{}return[...new Set([...n,...r])]}function Ur(e,t,n,r){let i=k(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
755
- `))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...Hr(o.fileNames,O(n)),n],options:o.options,host:s})}const Wr=`/* eslint-disable */
755
+ `}function oi(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(ii(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function si(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=lt(t).filter(e=>e.endsWith(`.ts`)).map(e=>j(t,e))}catch{}return[...new Set([...n,...r])]}function ci(e,t,n,r){let i=j(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
756
+ `))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...si(o.fileNames,A(n)),n],options:o.options,host:s})}const li=`/* eslint-disable */
756
757
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
757
758
  //
758
759
  // Self-contained: this file has no imports, so a frontend consumes it without
@@ -766,7 +767,7 @@ ${g}
766
767
  //
767
768
  // Not refreshed by \`kick dev\` — resolving these types builds a full
768
769
  // TypeScript program over the server. Re-run \`kick typegen\`.
769
- `;function Gr(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Wr}
770
+ `;function ui(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${li}
770
771
  // (no routes discovered yet — annotate a controller method with
771
772
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
772
773
  interface Api {}
@@ -783,7 +784,7 @@ export type { Api }
783
784
 
784
785
  `)+`
785
786
 
786
- `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Wr}
787
+ `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${li}
787
788
  ${r}interface Api {
788
789
  ${i.join(`
789
790
  `)}
@@ -797,14 +798,14 @@ declare global {
797
798
  }
798
799
 
799
800
  export type { Api }
800
- `}const Kr=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,qr=`.kickjs/cache/client-map.sha1`,Jr=(()=>{try{return Xe(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Yr(e){try{if(!j(e))return null;let[t,n]=M(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Xr(e){return`${Xt}${Kr} */\n\n${e}\n`}function Zr(e){try{return j(e)?M(e,`utf-8`):null}catch{return null}}async function Qr(e){let t=D.resolve(e.cwd,Q);if(!j(t))return!1;try{await st(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function $r(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function ei(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(j(D.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const ti=()=>({id:Kr,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!ei(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=$r(e.config),a=await Ir({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Jr}),o=Yr(D.resolve(e.cwd,qr)),s=Zr(D.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Pr(s))return se()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=Gr(await Lr({projectDir:e.cwd,routesFile:D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(qr,`${a} ${Pr(Xr(t))}`),t}catch(t){let n=j(D.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):se()&&e.log.info?.(r),n&&await Qr(e),null}}});function ni(e,t,n=`zod`){if(!e)return null;let r=Qe(O(t),e.filePath).split($e).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
801
+ `}const di=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,fi=`.kickjs/cache/client-map.sha1`,pi=(()=>{try{return rt(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function mi(e){try{if(!N(e))return null;let[t,n]=P(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function hi(e){return`${on}${di} */\n\n${e}\n`}function gi(e){try{return N(e)?P(e,`utf-8`):null}catch{return null}}async function _i(e){let t=k.resolve(e.cwd,Q);if(!N(t))return!1;try{await ht(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function vi(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function yi(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(N(k.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const bi=()=>({id:di,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!yi(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=vi(e.config),a=await ti({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:pi}),o=mi(k.resolve(e.cwd,fi)),s=gi(k.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===$r(s))return se()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=ui(await ni({projectDir:e.cwd,routesFile:k.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(fi,`${a} ${$r(hi(t))}`),t}catch(t){let n=N(k.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):se()&&e.log.info?.(r),n&&await _i(e),null}}});function xi(e,t,n=`zod`){if(!e)return null;let r=A(t),i=at(r,e.filePath).split(ot).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
801
802
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
802
803
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
803
804
 
804
805
  // Importing the schema as a type lets us infer its shape without
805
806
  // pulling in any runtime code. \`Awaited<>\` strips an accidental
806
807
  // Promise wrap on dynamic-imported defaults.
807
- import type _envSchema from '${r}'
808
+ import type _envSchema from '${i}'
808
809
 
809
810
  ${n===`kickjs-schema`?`type _Raw = import('@forinda/kickjs-schema').InferSchemaOutput<typeof _envSchema>
810
811
  type _Resolved = { [K in keyof _Raw]: _Raw[K] }
@@ -835,6 +836,6 @@ declare global {
835
836
  }
836
837
 
837
838
  export {}
838
- `}const ri=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ai(e);if(t===!1)return null;let n=await e.getScanResult({root:ii(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=D.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return ni(n.env,i,r)}});function ii(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ai(e){return e.config?.typegen?.envFile}function oi(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function si(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:oi(e),cwd:e.cwd,envFile:si(e)}}const ci=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=D.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ke(t.classes,n,r)}}),li=()=>({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 Ve(`ServiceToken`,Ue(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),ui=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return Ve(`ModuleToken`,Le((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),di=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ze((await e.getScanResult($(e))).pluginsAndAdapters)}}),fi=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Ye((await e.getScanResult($(e))).augmentations)}}),pi=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:Re(t.contextKeys)}}),mi=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){return We((await e.getScanResult($(e))).routeFlags)}}),hi={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},gi=[T({name:`kick/init`,register:vt}),T({name:`kick/generate`,register:Jt}),T({name:`kick/run`,register:cn}),T({name:`kick/info`,register:pn}),T({name:`kick/inspect`,register:xn}),T({name:`kick/add`,register:xe}),T({name:`kick/list`,register:Ce}),T({name:`kick/explain`,register:An}),T({name:`kick/mcp`,register:zn}),T({name:`kick/tinker`,register:Un}),T({name:`kick/remove`,register:Yn}),T({name:`kick/typegen`,register:Qn}),T({name:`kick/check`,register:ur}),T({name:`kick/doctor`,register:he}),T({name:`kick/codemod`,register:fr}),T({name:`kick/registry`,typegens:[ci()]}),T({name:`kick/services`,typegens:[li()]}),T({name:`kick/modules`,typegens:[ui()]}),T({name:`kick/plugins`,typegens:[di()]}),T({name:`kick/augmentations`,typegens:[fi()]}),T({name:`kick/context`,typegens:[pi()]}),T({name:`kick/route-flags`,typegens:[mi()]}),T({name:`kick/assets`,typegens:[pr()]}),T({name:`kick/routes`,typegens:[Cr()]}),T({name:`kick/client`,typegens:[ti()]}),T({name:`kick/env`,typegens:[ri()]}),T({name:`kick/runtime`,typegens:[{id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=hi[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
839
- `)}}]})];export{$t as applyDisableFilter,H as runAllPluginTypegens,gi as t};
840
- //# sourceMappingURL=run-plugins-GxEtP9WR.mjs.map
839
+ `}const Si=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=wi(e);if(t===!1)return null;let n=await e.getScanResult({root:Ci(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=k.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return xi(n.env,i,r)}});function Ci(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function wi(e){return e.config?.typegen?.envFile}function Ti(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ei(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ti(e),cwd:e.cwd,envFile:Ei(e)}}const Di=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=k.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ye(t.classes,n,r)}}),Oi=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className)),r=Ke(t.classes,t.tokens,t.injects,n);return We(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),ki=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return We(`ModuleToken`,Be(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Ai=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return He(t.pluginsAndAdapters)}}),ji=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Qe(t.augmentations)}}),Mi=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:Ve(t.contextKeys)}}),Ni=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return qe(t.routeFlags)}}),Pi={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Fi=[T({name:`kick/init`,register:Dt}),T({name:`kick/generate`,register:rn}),T({name:`kick/run`,register:vn}),T({name:`kick/info`,register:Cn}),T({name:`kick/inspect`,register:jn}),T({name:`kick/add`,register:Se}),T({name:`kick/list`,register:we}),T({name:`kick/explain`,register:Bn}),T({name:`kick/mcp`,register:Xn}),T({name:`kick/tinker`,register:er}),T({name:`kick/remove`,register:or}),T({name:`kick/typegen`,register:lr}),T({name:`kick/check`,register:Or}),T({name:`kick/doctor`,register:ge}),T({name:`kick/codemod`,register:Ar}),T({name:`kick/registry`,typegens:[Di()]}),T({name:`kick/services`,typegens:[Oi()]}),T({name:`kick/modules`,typegens:[ki()]}),T({name:`kick/plugins`,typegens:[Ai()]}),T({name:`kick/augmentations`,typegens:[ji()]}),T({name:`kick/context`,typegens:[Mi()]}),T({name:`kick/route-flags`,typegens:[Ni()]}),T({name:`kick/assets`,typegens:[jr()]}),T({name:`kick/routes`,typegens:[Vr()]}),T({name:`kick/client`,typegens:[bi()]}),T({name:`kick/env`,typegens:[Si()]}),T({name:`kick/runtime`,typegens:[{id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=Pi[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
840
+ `)}}]})];export{ln as applyDisableFilter,un as n,R as r,W as runAllPluginTypegens,Fi as t};
841
+ //# sourceMappingURL=run-plugins-D5xbaQib.mjs.map