@forinda/kickjs-cli 6.0.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-docs-Dmku65k2.mjs → agent-docs-DB5y-kvS.mjs} +3 -3
- package/dist/{agent-docs-Dmku65k2.mjs.map → agent-docs-DB5y-kvS.mjs.map} +1 -1
- package/dist/build-9YFC7Rd4.mjs +13 -0
- package/dist/build-9YFC7Rd4.mjs.map +1 -0
- package/dist/{builtins-G49e_Qsj.mjs → builtins-mr3TIDa8.mjs} +2 -2
- package/dist/cli.mjs +143 -151
- package/dist/{config-DdtRfl33.mjs → config-Dc4XuP2E.mjs} +3 -3
- package/dist/config-Dc4XuP2E.mjs.map +1 -0
- package/dist/{doctor-SUUDEI1J.mjs → doctor-shX-k8ju.mjs} +41 -41
- package/dist/doctor-shX-k8ju.mjs.map +1 -0
- package/dist/index.d.mts +279 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{plugin-Dg0Lk2Lp.mjs → plugin-DVOWYRqG.mjs} +3 -3
- package/dist/{plugin-Dg0Lk2Lp.mjs.map → plugin-DVOWYRqG.mjs.map} +1 -1
- package/dist/{project-docs-C-dA6-TO.mjs → project-docs-Cq_MswOY.mjs} +2 -2
- package/dist/{project-docs-C-dA6-TO.mjs.map → project-docs-Cq_MswOY.mjs.map} +1 -1
- package/dist/{project-root-so4F5DRN.mjs → project-root-C3u57Vec.mjs} +3 -3
- package/dist/{project-root-so4F5DRN.mjs.map → project-root-C3u57Vec.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DrKbExWn.mjs → rolldown-runtime-BMxBusPc.mjs} +1 -1
- package/dist/{run-plugins-B2_AT35s.mjs → run-plugins-COniKxrL.mjs} +73 -82
- package/dist/run-plugins-COniKxrL.mjs.map +1 -0
- package/dist/typegen-DPATg8Ix.mjs +114 -0
- package/dist/typegen-DPATg8Ix.mjs.map +1 -0
- package/dist/{types-C5PH0h7Z.mjs → types-B2r_OeIa.mjs} +1 -1
- package/package.json +7 -7
- package/dist/config-DdtRfl33.mjs.map +0 -1
- package/dist/doctor-SUUDEI1J.mjs.map +0 -1
- package/dist/run-plugins-B2_AT35s.mjs.map +0 -1
- package/dist/typegen-5MX2F5iL.mjs +0 -114
- package/dist/typegen-5MX2F5iL.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v6.
|
|
2
|
+
* @forinda/kickjs-cli v6.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,14 +8,14 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{_ as e,b as t,c as n,d as r,f as i,g as a,h as o,l as s,m as c,p as l,s as u,u as d,v as f,y as p}from"./project-docs-
|
|
11
|
+
import{_ as e,b as t,c as n,d as r,f as i,g as a,h as o,l as s,m as c,p as l,s as u,u as d,v as f,y as p}from"./project-docs-Cq_MswOY.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 x,a as S,b as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,j as ue,k as C,l as de,m as fe,p as pe,r as me,u as he,v as ge,w as _e,x as ve,y as ye}from"./doctor-shX-k8ju.mjs";import{a as w,i as T,o as be,s as xe,t as E}from"./config-Dc4XuP2E.mjs";import{t as Se}from"./project-root-C3u57Vec.mjs";import{n as D}from"./types-B2r_OeIa.mjs";import{t as Ce}from"./build-9YFC7Rd4.mjs";import{n as we}from"./agent-docs-DB5y-kvS.mjs";import{n as Te}from"./plugin-DVOWYRqG.mjs";import{a as Ee,c as De,d as Oe,f as ke,g as Ae,h as je,i as Me,l as Ne,m as Pe,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be}from"./typegen-DPATg8Ix.mjs";import O,{basename as Ve,dirname as k,join as A,relative as j,resolve as M,sep as N}from"node:path";import{cpSync as He,existsSync as P,mkdirSync as Ue,readFileSync as F,readdirSync as We,rmSync as Ge,writeFileSync as Ke}from"node:fs";import{copyFile as qe,mkdir as Je,readFile as I,readdir as Ye,rm as Xe,stat as Ze,writeFile as L}from"node:fs/promises";import{execSync as Qe,fork as $e,spawn as et,spawnSync as tt}from"node:child_process";import{fileURLToPath as nt,pathToFileURL as R}from"node:url";import{arch as rt,platform as it,release as at}from"node:os";const z={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},zod:{pkg:`zod`,peers:[],description:`Zod schema validation (env, DTOs, OpenAPI) — wrap with fromZod()`},valibot:{pkg:`valibot`,peers:[],description:`Valibot schema validation — wrap with fromValibot()`},yup:{pkg:`yup`,peers:[],description:`Yup schema validation — wrap with fromYup()`},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`JWT, API key, OAuth strategies, @Public, @Roles (+ optional argon2/bcryptjs)`,deprecated:`auth is moving to BYO — compose @LoadAuthUser/@RequireRole/@Public from defineContextDecorator (see the BYO Auth recipe in the docs)`},ai:{pkg:`@forinda/kickjs-ai`,peers:[`zod`],description:`AI toolkit — LLM providers, tool definitions from controllers`},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},pg:{pkg:`@forinda/kickjs-db`,peers:[`pg`],description:`kick/db + PostgreSQL driver (use @forinda/kickjs-db/pg)`},sqlite:{pkg:`@forinda/kickjs-db`,peers:[`better-sqlite3`],description:`kick/db + SQLite driver (use @forinda/kickjs-db/sqlite)`},mysql:{pkg:`@forinda/kickjs-db`,peers:[`mysql2`],description:`kick/db + MySQL driver (use @forinda/kickjs-db/mysql)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`,deprecated:"early-adoption adapter, no longer maintained — wire Drizzle directly (BYO), or use @forinda/kickjs-db, the built-in Kick ORM (`kick add db` / pg / sqlite / mysql)"},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`,deprecated:"early-adoption adapter, no longer maintained — wire Prisma directly (BYO), or use @forinda/kickjs-db, the built-in Kick ORM (`kick add db` / pg / sqlite / mysql)"},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},"queue:redis-pubsub":{pkg:`@forinda/kickjs-queue`,peers:[`ioredis`],description:`Lightweight pub/sub via Redis (no persistence)`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function B(e,t=process.cwd()){let n=t;for(;;){if(P(M(n,e)))return n;let t=k(n);if(t===n)return null;n=t}}function ot(){return B(`pnpm-lock.yaml`)?`pnpm`:B(`yarn.lock`)?`yarn`:B(`bun.lockb`)||B(`bun.lock`)?`bun`:B(`package-lock.json`)?`npm`:null}function st(){let e=process.cwd();for(;e;){let t=M(e,`package.json`);if(P(t))try{let e=JSON.parse(F(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(E.includes(t))return t}}catch{}let n=k(e);if(n===e)return null;e=n}return null}async function ct(e){if(e&&E.includes(e))return{pm:e,source:`flag`};let t=await T(process.cwd());if(t?.packageManager&&E.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=st();if(n)return{pm:n,source:`package.json`};let r=ot();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function lt(e){let{pm:t}=await ct(e);return t}function ut(e=!1){let t=Object.entries(z),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``,a=t.deprecated?` [DEPRECATED — ${t.deprecated}]`:``;return` ${r} ${t.description}${i}${a}`};console.log(`
|
|
12
12
|
Core packages (always installed by \`kick new\`):
|
|
13
13
|
`);for(let e of r)console.log(a(e));if(e){console.log(`
|
|
14
14
|
Optional packages (add as needed):
|
|
15
15
|
`);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
|
|
16
|
-
Usage: kick add
|
|
17
|
-
`),
|
|
18
|
-
`)}})}const mt=[{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 ht(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`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{n(`KickJS — Create a new project`);let o=!!(t.yes||t.nonInteractive);e||=o?`my-api`:await c({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let l;if(e===`.`?(l=
|
|
16
|
+
Usage: kick add ai db swagger`),console.log(` kick add queue:bullmq`),console.log()}function dt(e,t){let n=new Set,r=new Set,i=[],a=[];for(let o of e){let e=z[o];if(!e){i.push(o);continue}e.deprecated&&a.push(`'${o}' (${e.pkg}) is deprecated — ${e.deprecated}`);let s=t||e.dev?r:n;s.add(e.pkg);for(let t of e.peers)s.add(t)}return{prodDeps:[...n],devDeps:[...r],unknown:i,warnings:a}}function ft(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{ut(!!e.all)})}function pt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){ut(!!t.all);return}let{pm:n,source:r}=await ct(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let{prodDeps:i,devDeps:a,unknown:o,warnings:s}=dt(e,!!t.dev);for(let e of s)console.warn(`\n WARNING: ${e}`);if(!(o.length>0&&(console.log(`\n Unknown packages: ${o.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
|
|
17
|
+
`),i.length===0&&a.length===0))){if(i.length>0){let e=i,t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{Qe(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(a.length>0){let e=a,t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{Qe(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
|
|
18
|
+
`)}})}const mt=[{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 ht(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`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{n(`KickJS — Create a new project`);let o=!!(t.yes||t.nonInteractive);e||=o?`my-api`:await c({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let l;if(e===`.`?(l=M(`.`),e=Ve(l)):l=M(t.directory||e),P(l)){let n=We(l);if(n.length>0){if(t.force)s.warn(`Clearing existing files in ${l}`);else if(o){s.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{s.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)s.message(` - ${e}`);if(n.length>5&&s.message(` ... and ${n.length-5} more`),!await u({message:a.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of n)Ge(M(l,e),{recursive:!0,force:!0})}}let f=t.template;f||=o?`minimal`:await i({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let p=t.pm;p||=o?await lt(void 0):await i({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let m=t.repo;m||=o?`inmemory`:await c({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),xe(m);let h=t.schema;h||=o?`zod`:await i({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(h)||(s.warn(`Unknown --schema "${h}", falling back to zod.`),h=`zod`);let g;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();g=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else g=o?[]:await d({message:`Select packages to include`,options:[...mt],required:!1});let _;_=t.git===void 0?o?!0:await u({message:`Initialize git repository?`,initialValue:!0}):t.git;let v;v=t.install===void 0?o?!0:await u({message:`Install dependencies?`,initialValue:!0}):t.install,await he({name:e,directory:l,packageManager:p,initGit:_,installDeps:v,template:f,defaultRepo:m,packages:g,schemaLib:h}),r(`Done! Next steps: ${a.cyan(`cd ${e} && ${p} dev`)}`)})}async function gt(e){let{name:n,outDir:r}=e,i=y(n),a=b(n),o=[],s=A(r,`${i}.plugin.ts`);return await t(s,`import {
|
|
19
19
|
definePlugin,
|
|
20
20
|
type AppAdapter,
|
|
21
21
|
type AppModuleEntry,
|
|
@@ -159,9 +159,9 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
|
159
159
|
},
|
|
160
160
|
}),
|
|
161
161
|
})
|
|
162
|
-
`),o.push(s),o}function _t(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}function vt(e){switch(e){case`string`:return`''`;case`number`:return`0`;case`boolean`:return`false`;default:return null}}async function yt(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=
|
|
163
|
-
`)}\n}\n`:``,
|
|
164
|
-
`)}\n },\n`:``,
|
|
162
|
+
`),o.push(s),o}function _t(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}function vt(e){switch(e){case`string`:return`''`;case`number`:return`0`;case`boolean`:return`false`;default:return null}}async function yt(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:_t(e.params),d=se({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(`
|
|
163
|
+
`)}\n}\n`:``,h=u.length>0?`${f}.withParams<${c}Params>()({`:`${f}({`,g=u.map(e=>({name:e.name,def:vt(e.type)})).filter(e=>e.def!==null).map(e=>` ${e.name}: ${e.def},`),_=u.length>0?` paramDefaults: {\n${g.join(`
|
|
164
|
+
`)}\n },\n`:``,ee=u.length>0?`(ctx, _deps, params)`:`(ctx)`,te=u.length>0?` // \`params\` is typed as ${c}Params (call-site overrides merged onto paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,ne=`import { ${f} } from '@forinda/kickjs'
|
|
165
165
|
import type { ${p} } from '@forinda/kickjs'
|
|
166
166
|
|
|
167
167
|
/**
|
|
@@ -190,16 +190,16 @@ declare module '@forinda/kickjs' {
|
|
|
190
190
|
'${l}': unknown
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
|
-
${
|
|
194
|
-
export const ${c} = ${
|
|
193
|
+
${m}
|
|
194
|
+
export const ${c} = ${h}
|
|
195
195
|
key: '${l}',
|
|
196
|
-
${
|
|
197
|
-
${
|
|
196
|
+
${_} resolve: ${ee} => {
|
|
197
|
+
${te}
|
|
198
198
|
// TODO: compute and return the value written to ctx.set('${l}', …)
|
|
199
199
|
throw new Error("${c} contributor: resolve() not implemented")
|
|
200
200
|
},
|
|
201
201
|
})
|
|
202
|
-
`,
|
|
202
|
+
`,x=A(d,`${s}.contributor.ts`);return await t(x,ne),[x]}async function bt(e){let n=A(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return P(n)&&!e.force&&!await u({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
203
203
|
Skipped — existing kick.config.ts preserved.`),[]):(await t(n,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
204
204
|
|
|
205
205
|
export default defineConfig({
|
|
@@ -237,18 +237,18 @@ export default defineConfig({
|
|
|
237
237
|
},
|
|
238
238
|
],
|
|
239
239
|
})
|
|
240
|
-
`),[n])}function
|
|
240
|
+
`),[n])}function V(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function H(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=V(e,r);return i===-1?null:e.slice(r+1,i)}function U(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
241
241
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`);return r+e.replace(n,``)}).join(`
|
|
242
|
-
`)}function xt(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 St(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 Ct(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=
|
|
242
|
+
`)}function xt(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 St(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 Ct(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=V(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=H(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=H(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=H(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=xt(s),p=``;return l&&(p+=` register(container) {${U(l,4,6)} },\n\n`),u&&(p+=` contributors() {${U(u,4,6)} },\n\n`),p+=` routes() {${U(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
243
243
|
name: '${r}',
|
|
244
244
|
build: () => ({
|
|
245
245
|
${p}
|
|
246
246
|
}),
|
|
247
|
-
})`}${c}`}}function wt(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=
|
|
248
|
-
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=
|
|
247
|
+
})`}${c}`}}function wt(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=V(e,i);if(a===-1)return{migrated:null,reason:`unbalanced defineModule braces`};let o=e.indexOf(`)`,a);if(o===-1)return{migrated:null,reason:`unbalanced defineModule call parens`};let s=e.slice(i+1,a),c=e.slice(0,n.index),l=o+1;for(;l<e.length&&(e[l]===`
|
|
248
|
+
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=V(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=St(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${U(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${U(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${U(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
249
249
|
${y}
|
|
250
250
|
}
|
|
251
|
-
`}${u}`}}function Tt(e,t){return t===`class`?wt(e):Ct(e)}function Et(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 Dt(e){let t=[];return await n(
|
|
251
|
+
`}${u}`}}function Tt(e,t){return t===`class`?wt(e):Ct(e)}function Et(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 Dt(e){let t=[];return await n(M(e),0),t;async function n(e,r){let i;try{i=await Ye(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o;try{o=await Ze(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Ot(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Ye(e)}catch{return}await Je(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o=A(t,a),s;try{s=await Ze(i)}catch{continue}s.isDirectory()?await r(i,o):(await qe(i,o),n++)}}}function kt(e){return A(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function At(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Dt(e),s=await I(A(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=kt(r),await Ot(e,c));let l=[];for(let e of o){let t=Tt(await I(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await L(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=A(e,`index.ts`),d=null;try{d=await I(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Et(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await L(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function jt(e,t){let n=await Dt(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 I(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Mt(e){let{name:n,outDir:r}=e,i=b(n),a=y(n),o=v(n),s=e.queue??`${a}-queue`,c=[];return await(async(e,n)=>{let i=A(r,e);await t(i,n),c.push(i)})(`${a}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
252
252
|
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
253
253
|
|
|
254
254
|
/**
|
|
@@ -281,7 +281,7 @@ export class ${i}Job {
|
|
|
281
281
|
// Handle high-priority variant of this job
|
|
282
282
|
}
|
|
283
283
|
}
|
|
284
|
-
`),c}const Nt={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 Pt(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=Nt[a];if(!o){let e=[...Object.keys(Nt),`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 Ft(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=
|
|
284
|
+
`),c}const Nt={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 Pt(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=Nt[a];if(!o){let e=[...Object.keys(Nt),`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 Ft(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?ue(u):u,p=A(i,d),v=[],x=async(e,n)=>{let r=A(p,e);await t(r,n),v.push(r)};await x(`${l}.module.ts`,ee({pascal:u,kebab:l,plural:d,repo:a,style:s})),await x(`${l}.constants.ts`,te({pascal:u,kebab:l})),await x(`${l}.controller.ts`,g({pascal:u,kebab:l,plural:d,pluralPascal:f})),await x(`${l}.service.ts`,h({pascal:u,kebab:l})),await x(`dtos/create-${l}.dto.ts`,It(u,r)),await x(`dtos/update-${l}.dto.ts`,Lt(u,r)),await x(`dtos/${l}-response.dto.ts`,Rt(u,r)),await x(`${l}.repository.ts`,_({pascal:u,kebab:l,dtoPrefix:`./dtos`,tokenScope:o}));let S=a===`inmemory`,re=S?`in-memory-${l}`:`${y(a)}-${l}`,ie=S?ne({pascal:u,kebab:l,repoPrefix:`.`,dtoPrefix:`./dtos`}):_e({pascal:u,kebab:l,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});return await x(`${re}.repository.ts`,ie),await ge(i,u,d,l,s),v}function It(e,t){return`import { z } from 'zod'
|
|
285
285
|
|
|
286
286
|
export const create${e}Schema = z.object({
|
|
287
287
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -304,7 +304,7 @@ ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
|
304
304
|
createdAt: string
|
|
305
305
|
updatedAt: string
|
|
306
306
|
}
|
|
307
|
-
`}async function zt(e){let{name:n,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=
|
|
307
|
+
`}async function zt(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=M(e.outDir);else if(r){let e=y(r),t=a?m(e):e;l=M(A(i??`src/modules`,t,`__tests__`))}else l=M(`src/__tests__`);let u=A(l,`${o}.test.ts`);return await t(u,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
308
308
|
import { Container } from '@forinda/kickjs'
|
|
309
309
|
|
|
310
310
|
describe('${s}', () => {
|
|
@@ -327,61 +327,52 @@ describe('${s}', () => {
|
|
|
327
327
|
expect(true).toBe(true)
|
|
328
328
|
})
|
|
329
329
|
})
|
|
330
|
-
`),c.push(u),c}const Bt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function
|
|
331
|
-
(dry run — no files were written)`),console.log()}async function Vt(e){if(!e)try{let e=await
|
|
330
|
+
`),c.push(u),c}const Bt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function W(e){return e.parent?.opts()?.dryRun??!1}function G(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(`
|
|
331
|
+
(dry run — no files were written)`),console.log()}async function Vt(e){if(!e)try{let e=await T(process.cwd());await ze({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 Ht=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}],Ut=new Set(Ht.map(e=>e.name.split(` `)[0]));async function Wt(){console.log(`
|
|
332
332
|
Built-in generators:
|
|
333
|
-
`);let e=Math.max(...Ht.map(e=>e.name.length));for(let t of Ht)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await
|
|
333
|
+
`);let e=Math.max(...Ht.map(e=>e.name.length));for(let t of Ht)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await T(process.cwd()),n=Te(t?.plugins??[],t?.commands??[]),r=await le(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
334
334
|
Plugin generators:
|
|
335
335
|
`);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(`
|
|
336
336
|
Failed to load:
|
|
337
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Gt(e,t,n){let r=await
|
|
338
|
-
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
339
|
-
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
337
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Gt(e,t,n){let r=await T(process.cwd()),i=w(r),o=t.modulesDir??i.dir??`src/modules`,s=t.repo??ve(i.repo);t.repo&&xe(t.repo);let c=t.pattern??r?.pattern??`rest`,l=t.pluralize===!1?!1:i.pluralize??!0,u=be(r,process.cwd()),d=i.style??`define`;if(!n&&d===`define`){let e=await jt(M(o),`define`);if(e.length>0){console.error(`\n ${a.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${a.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${a.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${a.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${a.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${a.dim(`// kick.config.ts`)}\n ${a.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let f=[];for(let r of e){let e=await re({name:r,modulesDir:M(o),noEntity:t.entity===!1,noTests:t.tests===!1,repo:s,minimal:t.minimal,force:t.force,pattern:c,dryRun:n,pluralize:l,prismaClientPath:i.prismaClientPath,tokenScope:u,style:i.style});f.push(...e)}G(f,n),await Vt(n)}function Kt(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await Wt();return}if(!e||e.length===0){n.help();return}let a=W(i);p(a);let[o,s,...c]=e;if(o){let e=await T(process.cwd()),n=Te(e?.plugins??[],e?.commands??[]),i=await S({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){G(i.files,a);return}if(o!==`module`&&Ut.has(o)){console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`),process.exitCode=1;return}}await Gt(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=W(n);p(r),await Gt(e,{...n.optsWithGlobals(),...t},r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=W(n);p(r),G(await x({name:e,outDir:M(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=W(n);p(r),G(await gt({name:e,outDir:M(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
|
|
338
|
+
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=await T(process.cwd()),a=w(i),o=a.dir??`src/modules`;G(await ce({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
339
|
+
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=await T(process.cwd()),a=w(i),o=a.dir??`src/modules`;G(await fe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
340
340
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
341
341
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
342
|
-
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=
|
|
343
|
-
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
344
|
-
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
345
|
-
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
346
|
-
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=
|
|
342
|
+
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=W(n);p(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await T(process.cwd()),o=w(a),s=o.dir??`src/modules`;G(await yt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
343
|
+
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=await T(process.cwd()),a=w(i),o=a.dir??`src/modules`;G(await pe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
344
|
+
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=await T(process.cwd()),a=w(i),o=a.dir??`src/modules`;G(await oe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Vt(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
345
|
+
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=await T(process.cwd()),a=w(i),o=a.dir??`src/modules`;G(await ae({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
346
|
+
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=W(n);p(r);let i=w(await T(process.cwd())),a=i.dir??`src/modules`;G(await zt({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=W(n);p(r),G(await Mt({name:e,outDir:M(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
347
347
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
348
348
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
349
349
|
Optional: append :optional (shell-safe): description:text:optional
|
|
350
|
-
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=
|
|
350
|
+
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=W(r);p(i),t.length===0&&(console.error(`
|
|
351
351
|
Error: At least one field is required.
|
|
352
352
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
353
353
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
354
354
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
355
|
-
`),process.exit(1));let a=await
|
|
356
|
-
`,l=``;if(P(i)&&(l=await I(i,`utf8`)),l===c){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${i})`);await L(i,c,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}return s}function Xt(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 Zt(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))}}function Qt(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function
|
|
357
|
-
|
|
355
|
+
`),process.exit(1));let a=await T(process.cwd()),o=w(a),s=n.modulesDir??o.dir??`src/modules`,c=Pt(t),l=be(a,process.cwd()),u=await Ft({name:e,fields:c,modulesDir:M(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:l,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(u,i),await Vt(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=W(t);p(n),G(await bt({outDir:M(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=W(t);p(n);let r=e.only??`all`;if(!Bt.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${Bt.join(` | `)}`),process.exitCode=1;return}G(await we({outDir:M(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])qt(n,e,t?.projectRoot)}function qt(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=W(o);p(s);let c=await S({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&G(c.files,s)})}function Jt(e,t,n){let r=tt(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}async function Yt(e){let t=O.resolve(e.cwd,`.kickjs/types`);await Je(t,{recursive:!0});let n=new Map,r=e.scan??je,i=O.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(R(e).href)},async writeFile(t,n){let r=O.resolve(e.cwd,t);await Je(O.dirname(r),{recursive:!0}),await L(r,n,`utf8`)},getScanResult:e=>{let t=Xt(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Ae(s,a):r(s),n.set(t,o)}return o},log:console},s=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=O.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(e){let t=e instanceof Error?e.message:String(e);o.log.error(` ${n.id}: typegen failed (${t}) — 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 c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+a+`
|
|
356
|
+
`,l=``;if(P(i)&&(l=await I(i,`utf8`)),l===c){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${i})`);await L(i,c,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}return s}function Xt(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 Zt(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))}}function Qt(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function $t(e){let{enabled:t,skipped:n,unknown:r}=Zt(Te([...kr,...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 Yt({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Qt())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function en(e){let t=A(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=A(t,i);if(P(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function tn(e){let t=e.spawnFn??et,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(`
|
|
357
|
+
`):`${n.slice(0,t).join(`
|
|
358
|
+
`)}\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,n={}){t&&(process.env.PORT=t);let r=rn(n.polling),i=process.cwd(),a=await T(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await ze({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{await Me(c,await $t({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(R(l(M(`package.json`)).resolve(`vite`)).href);globalThis[ie]=`kick-dev`;let d=await u({configFile:M(`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=de({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(`
|
|
358
359
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
359
|
-
`);let
|
|
360
|
+
`),p?.schedule();let g=!1,_=async()=>{if(!g){g=!0,h.dispose(),p?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,_),process.on(`SIGTERM`,_),process.on(`SIGBREAK`,_)}function on(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 an(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
360
361
|
Error: vite is not installed.
|
|
361
362
|
Run: pnpm add -D vite unplugin-swc
|
|
362
363
|
`):console.error(`
|
|
363
364
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
364
365
|
Building for production...
|
|
365
|
-
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(R(e(
|
|
366
|
-
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
367
|
-
Building asset map...`);try{await
|
|
366
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(R(e(M(`package.json`)).resolve(`vite`)).href);await t({configFile:M(`vite.config.ts`)});let n=await T(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
367
|
+
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?A(`dist`,e):e.dest??A(`dist`,t),r=M(t),i=M(n);if(!P(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Ue(i,{recursive:!0}),He(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
368
|
+
Building asset map...`);try{await Ce(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
368
369
|
Build complete.
|
|
369
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
370
|
-
Building asset map...`);try{await
|
|
370
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await T(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
371
|
+
Building asset map...`);try{await Ce(e,{cwd:process.cwd()}),console.log(`
|
|
371
372
|
Asset build complete.
|
|
372
|
-
`)}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)),Jt(e.entry,t)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await
|
|
373
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function ln(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
|
|
374
|
-
KickJS
|
|
375
|
-
|
|
376
|
-
System:
|
|
377
|
-
OS: ${it()} ${at()} (${rt()})
|
|
378
|
-
Node: ${process.version}
|
|
379
|
-
|
|
380
|
-
Packages:
|
|
381
|
-
@forinda/kickjs workspace
|
|
382
|
-
@forinda/kickjs-vite workspace
|
|
383
|
-
@forinda/kickjs-cli workspace
|
|
384
|
-
`)})}const{bold:K,dim:q,green:un,red:J,yellow:dn,blue:fn}=a;function pn(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 mn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Y(e,t){try{return await mn(`${e}${t}`)}catch{return null}}async function hn(e){let[t,n,r,i,a]=await Promise.all([Y(e,`/health`),Y(e,`/metrics`),Y(e,`/routes`),Y(e,`/container`),Y(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function gn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:s}=t,c=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?un(`● healthy`):J(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${J(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?J:r.errorRate>0?dn:un;console.log(` ${K(`Uptime:`)} ${pn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),s&&s.enabled&&console.log(` ${K(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(c),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${o(e.method)} ${t} ${fn(e.controller)}.${q(e.handler)}`)}}console.log(c),console.log()}function _n(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 hn(r);t.json?console.log(JSON.stringify(e,null,2)):gn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(J(` ✖ Could not connect to ${n}`)),console.error(q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function vn(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 yn=[{match(e,t){let n=vn(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
|
|
373
|
+
`)}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)),Jt(e.entry,t)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await an(e.entry,e.port)}catch(e){console.error(`
|
|
374
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function sn(){try{let e=k(nt(import.meta.url));return JSON.parse(F(A(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const cn=new Set(Object.values(z).filter(e=>e.deprecated).map(e=>e.pkg));function ln(e){let t=A(e,`package.json`);if(!P(t))return[];let n;try{n=JSON.parse(F(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=A(e,`node_modules`,...t.split(`/`),`package.json`);if(P(i))try{n=JSON.parse(F(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:cn.has(t)}})}function un(e){let t=e;for(;;){if(P(A(t,`package.json`)))return t;let e=k(t);if(e===t)return null;t=e}}function dn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${sn()}`,``,` System:`,` OS: ${it()} ${at()} (${rt()})`,` Node: ${process.version}`],t=un(process.cwd()),n=t?ln(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(`
|
|
375
|
+
`))})}const{bold:K,dim:q,green:fn,red:J,yellow:pn,blue:mn}=a;function hn(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 gn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Y(e,t){try{return await gn(`${e}${t}`)}catch{return null}}async function _n(e){let[t,n,r,i,a]=await Promise.all([Y(e,`/health`),Y(e,`/metrics`),Y(e,`/routes`),Y(e,`/container`),Y(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function vn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:s}=t,c=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?fn(`● healthy`):J(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${J(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?J:r.errorRate>0?pn:fn;console.log(` ${K(`Uptime:`)} ${hn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),s&&s.enabled&&console.log(` ${K(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(c),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${o(e.method)} ${t} ${mn(e.controller)}.${q(e.handler)}`)}}console.log(c),console.log()}function yn(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 _n(r);t.json?console.log(JSON.stringify(e,null,2)):vn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(J(` ✖ Could not connect to ${n}`)),console.error(q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function bn(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 xn=[{match(e,t){let n=bn(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
|
|
385
376
|
registers the env schema with kickjs at module-load time. Without it,
|
|
386
377
|
ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
|
|
387
378
|
and every user-defined key reads as undefined. @Value() may *appear* to
|
|
@@ -403,7 +394,7 @@ describe('UserController', () => {
|
|
|
403
394
|
beforeEach(() => Container.reset())
|
|
404
395
|
|
|
405
396
|
it('does the thing', async () => { /* ... */ })
|
|
406
|
-
})`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
397
|
+
})`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||bn(e,[`Module`,`is not a function`])||bn(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
|
|
407
398
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
408
399
|
returns the controller wiring. This was a deliberate choice — modules
|
|
409
400
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -455,24 +446,24 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
455
446
|
import { UserModule } from './users/user.module'
|
|
456
447
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
457
448
|
|
|
458
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function
|
|
449
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function Sn(e,t){let n=null;for(let r of xn){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 Cn(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.
|
|
459
450
|
export OPENAI_API_KEY="sk-..."
|
|
460
451
|
|
|
461
452
|
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:
|
|
462
453
|
kick add ai
|
|
463
454
|
|
|
464
455
|
Or manually:
|
|
465
|
-
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=
|
|
466
|
-
`)}function
|
|
456
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=wn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Tn((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 wn(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
457
|
+
`)}function Tn(e){let t=[e,En(e),Dn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(On(t))return t}catch{continue}return null}function En(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Dn(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 On(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 kn(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 Mn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
467
458
|
|
|
468
459
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
469
460
|
kick explain "config.get returned undefined"
|
|
470
461
|
pnpm test 2>&1 | kick explain
|
|
471
|
-
`),process.exit(1));let r=
|
|
472
|
-
`);return}if(i){
|
|
473
|
-
`),process.exit(2)),
|
|
474
|
-
`),process.exit(a.kind===`ok`?0:2)),
|
|
475
|
-
`)}function
|
|
462
|
+
`),process.exit(1));let r=Pn(),i=Sn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
463
|
+
`);return}if(i){Fn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
464
|
+
`),process.exit(2)),In(n,!1),process.exit(2));let a=await Cn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(An(a),null,2)+`
|
|
465
|
+
`),process.exit(a.kind===`ok`?0:2)),jn(n,a),process.exit(a.kind===`ok`?0:2)})}function An(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 jn(e,t){if(t.kind===`ok`){Fn(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Q(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: ${Q(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Mn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Nn()}function Nn(){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 Pn(){let e=process.cwd();return{cwd:e,hasFile:t=>P(M(e,t))}}function Fn(e,t,n,r=!1){let i=Q(e.trim(),200),a=r?`AI-generated — verify before applying`:Ln(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(`
|
|
466
|
+
`)}function In(e,t){let n=Q(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.
|
|
476
467
|
When @forinda/kickjs-ai ships its provider implementations,
|
|
477
468
|
this command will call the configured LLM with the error +
|
|
478
469
|
project context and return a structured fix.
|
|
@@ -491,10 +482,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
491
482
|
|
|
492
483
|
`)}function Z(e,t){return e.split(`
|
|
493
484
|
`).map(e=>`${t}${e}`).join(`
|
|
494
|
-
`)}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function
|
|
495
|
-
`,`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
|
|
485
|
+
`)}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Ln(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Rn(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(Bn)}function zn(e){let t=M(e.entry);P(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=et(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 Bn(e){let t=process.cwd(),n=Vn(t)??Ve(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(P(i))try{let e=F(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,Ke(i,JSON.stringify(o,null,2)+`
|
|
486
|
+
`,`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 Vn(e){let t=M(e,`package.json`);if(!P(t))return null;try{let e=F(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Hn(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);P(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Wn(t,`tsx`);r||(console.error(`
|
|
496
487
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
497
|
-
`),process.exit(1));let i=
|
|
488
|
+
`),process.exit(1));let i=Un(n,e.entry),a=A(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=$e(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Un(e,t){return`
|
|
498
489
|
import 'reflect-metadata'
|
|
499
490
|
|
|
500
491
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -548,31 +539,31 @@ server.on('exit', () => {
|
|
|
548
539
|
console.log('\\n Goodbye!\\n')
|
|
549
540
|
process.exit(0)
|
|
550
541
|
})
|
|
551
|
-
`}function
|
|
542
|
+
`}function Wn(e,t){let n=e;for(;;){let e=A(n,`node_modules`,`.bin`,t);if(P(e))return e;let r=M(n,`..`);if(r===n)break;n=r}return null}function Gn(e,t){let n=RegExp(`^\\s*${C(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]!==`
|
|
552
543
|
`;)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]===`
|
|
553
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function
|
|
544
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Kn(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=Gn(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${C(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 qn(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,o=y(t),s=b(t),c=i?m(o):o,l=A(n,c);if(!await f(l)){console.log(`\n Module not found: ${l}\n`);return}if(!r&&!await u({message:a.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
554
545
|
Cancelled.
|
|
555
|
-
`);return}await
|
|
546
|
+
`);return}await Xe(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let d=A(n,`index.ts`);if(await f(d)){let e=await I(d,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${C(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${C(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Kn(e,s),e=e.replace(/\n{3,}/g,`
|
|
556
547
|
|
|
557
|
-
`),e!==t&&(await L(d,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${d}`))}console.log(`\n Module '${c}' removed.\n`)}function
|
|
548
|
+
`),e!==t&&(await L(d,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${d}`))}console.log(`\n Module '${c}' removed.\n`)}function Jn(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=w(await T(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await qn({name:n,modulesDir:M(r),force:t.force,pluralize:i})})}function Yn(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 Xn(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Zn(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=Se(process.cwd()),n=await T(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DVOWYRqG.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-mr3TIDa8.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(`
|
|
558
549
|
Registered typegen plugins:
|
|
559
|
-
`);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let r=
|
|
550
|
+
`);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let r=Yn(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Xn(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await Le(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 ze(a);let r=await $t({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 Me(M(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof Re?console.error(`
|
|
560
551
|
`+e.message+`
|
|
561
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function
|
|
552
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Qn(e){let t=[];if(!P(e))return t;let n=We(e,{withFileTypes:!0});for(let r of n){let n=A(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Qn(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function $n(e){try{return F(e,`utf-8`)}catch{return``}}const er=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function tr(e,t){let n=$n(A(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(er.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 nr(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 rr(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 ir(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function ar(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 or(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 sr(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 cr(e){let t=Qn(A(e,`src`)).map(e=>$n(e)),n=[],r=tr(e,t);r&&n.push(r);let i=nr(t);i&&n.push(i);let a=rr(t);a&&n.push(a);let o=ir();o&&n.push(o);let s=ar(t);return s&&n.push(s),n.push(or(t)),n.push(sr(t)),n}function lr(t){t.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(t=>{if(!t.deploy){console.log(`
|
|
562
553
|
Usage: kick check --deploy
|
|
563
554
|
|
|
564
555
|
Available checks:
|
|
565
556
|
--deploy Audit for production readiness (security, config, best practices)
|
|
566
|
-
`);return}let i=process.cwd();n(`KickJS Deploy Check`);let o=l();o.start(`Scanning project...`);let c=
|
|
557
|
+
`);return}let i=process.cwd();n(`KickJS Deploy Check`);let o=l();o.start(`Scanning project...`);let c=cr(i);o.stop(`Scan complete`);let u={CRITICAL:0,WARNING:1,INFO:2};c.sort((e,t)=>u[e.severity]-u[t.severity]);for(let t of c)s.message(`${e(t.severity)} ${t.message}`);let d=c.filter(e=>e.severity===`CRITICAL`).length,f=c.filter(e=>e.severity===`WARNING`).length,p=c.filter(e=>e.severity===`INFO`).length,m=f===1?`warning`:`warnings`,h=[d>0?a.red(`${d} critical`):`${d} critical`,f>0?a.yellow(`${f} ${m}`):`${f} ${m}`,`${p} info`].join(`, `);d>0?(r(a.red(`${h} — fix critical issues before deploying`)),process.exit(1)):r(a.green(`${h} — looking good!`))})}function ur(e){return e.optsWithGlobals().dryRun??!1}function dr(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.
|
|
567
558
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
568
559
|
--target define|class Override the migration direction.
|
|
569
560
|
--apply Apply the changes (default: dry-run preview).
|
|
570
|
-
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=
|
|
561
|
+
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=ur(t)||!e.apply;p(n),e.experimental||(console.error(`
|
|
571
562
|
`+a.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
572
563
|
The regex-based rewrite handles the shapes our templates produce.
|
|
573
564
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
574
565
|
Always commit before running with --apply.
|
|
575
|
-
`),process.exit(1));let r=
|
|
566
|
+
`),process.exit(1));let r=w(await T(process.cwd())),i=M(e.modulesDir??r.dir??`src/modules`),o;e.target===`define`||e.target===`class`?o=e.target:e.target===void 0?o=r.style??`define`:(console.error(`\n ${a.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=a.dim(`→ ${o}`),c=n?a.dim(`(dry-run)`):a.bold(`(applying)`);console.log(`\n ${a.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${a.dim(i)}\n`);let l=e.backup!==!1&&!n,u=await At(i,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${a.green(`✓`)} backup: ${a.dim(e)}\n ${a.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !n&&e.backup===!1&&console.log(` ${a.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${a.green(`✓`)} ${e.path}`);else{f++;let t=a.dim(`(${e.reason??`skipped`})`);console.log(` ${a.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${a.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=a.dim(`(${u.indexReason??`skipped`})`);console.log(` ${a.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${a.dim(`-`)} ${u.indexPath} ${a.dim(`(not found)`)}`);let m=n?a.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${a.bold(String(d))} migrated, ${a.bold(String(f))} skipped${m}\n`)})}const fr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!P(O.resolve(e.cwd,`kick.config.ts`)))return null;let t=await T(e.cwd);if(!t?.assetMap)return null;let n=Ee(t.assetMap,e.cwd);return n.count===0?null:Fe(n)}}),pr="/* 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 mr(e,t,n,r={}){if(e.length===0)return`${pr}
|
|
576
567
|
// (no routes discovered yet — annotate a controller method with
|
|
577
568
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
578
569
|
declare global {
|
|
@@ -581,20 +572,20 @@ declare global {
|
|
|
581
572
|
}
|
|
582
573
|
|
|
583
574
|
export {}
|
|
584
|
-
`;let
|
|
585
|
-
`))}return`${
|
|
575
|
+
`;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=(e,i,o)=>{let s=_r(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}>`},s=[];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=o(e.bodySchema,e,`body`),i=o(e.querySchema,e,`query`),a=o(e.paramsSchema,e,`params`)??t,s=r??`unknown`,c=i??hr(e),l=gr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),s.push(n.join(`
|
|
576
|
+
`))}return`${pr}${vr(a)}
|
|
586
577
|
declare global {
|
|
587
578
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
588
579
|
namespace KickRoutes {
|
|
589
|
-
${
|
|
580
|
+
${s.join(`
|
|
590
581
|
`)}
|
|
591
582
|
}
|
|
592
583
|
}
|
|
593
584
|
|
|
594
585
|
export {}
|
|
595
|
-
`}function
|
|
586
|
+
`}function hr(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 gr(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 _r(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=yr(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 vr(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(`
|
|
596
587
|
`)+`
|
|
597
|
-
`}function
|
|
588
|
+
`}function yr(e,t,n){if(e===null)return`unknown`;let r=k(n);if(e===``){let e=j(r,t).split(N).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=j(r,M(k(t),e)).split(N).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const br=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:xr(e),cwd:e.cwd,envFile:Sr(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return mr(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function xr(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Sr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Cr(e,t,n=`zod`){if(!e)return null;let r=j(k(t),e.filePath).split(N).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
|
|
598
589
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
599
590
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
600
591
|
|
|
@@ -632,5 +623,5 @@ declare global {
|
|
|
632
623
|
}
|
|
633
624
|
|
|
634
625
|
export {}
|
|
635
|
-
`}const
|
|
636
|
-
//# sourceMappingURL=run-plugins-
|
|
626
|
+
`}const wr=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Er(e);if(t===!1)return null;let n=await e.getScanResult({root:Tr(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=O.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Cr(n.env,i,r)}});function Tr(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Er(e){return e.config?.typegen?.envFile}function Dr(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Or(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Dr(e),cwd:e.cwd,envFile:Or(e)}}const kr=[D({name:`kick/init`,register:ht}),D({name:`kick/generate`,register:Kt}),D({name:`kick/run`,register:on}),D({name:`kick/info`,register:dn}),D({name:`kick/inspect`,register:yn}),D({name:`kick/add`,register:pt}),D({name:`kick/list`,register:ft}),D({name:`kick/explain`,register:kn}),D({name:`kick/mcp`,register:Rn}),D({name:`kick/tinker`,register:Hn}),D({name:`kick/remove`,register:Jn}),D({name:`kick/typegen`,register:Zn}),D({name:`kick/check`,register:lr}),D({name:`kick/doctor`,register:me}),D({name:`kick/codemod`,register:dr}),D({name:`kick/registry`,typegens:[{id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=O.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ie(t.classes,n,r)}}]}),D({name:`kick/services`,typegens:[{id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className));return Pe(`ServiceToken`,Ne(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}]}),D({name:`kick/modules`,typegens:[{id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return Pe(`ModuleToken`,De((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}]}),D({name:`kick/plugins`,typegens:[{id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ke((await e.getScanResult($(e))).pluginsAndAdapters)}}]}),D({name:`kick/augmentations`,typegens:[{id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Be((await e.getScanResult($(e))).augmentations)}}]}),D({name:`kick/context`,typegens:[{id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:Oe(t.contextKeys)}}]}),D({name:`kick/assets`,typegens:[fr()]}),D({name:`kick/routes`,typegens:[br()]}),D({name:`kick/env`,typegens:[wr()]})];export{Zt as applyDisableFilter,$t as runAllPluginTypegens,kr as t};
|
|
627
|
+
//# sourceMappingURL=run-plugins-COniKxrL.mjs.map
|