@forinda/kickjs-cli 8.17.3 → 8.18.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-BxHRHi1r.mjs → agent-docs-CbVUB2eN.mjs} +11 -11
- package/dist/{agent-docs-BkQx62G6.mjs → agent-docs-xZISEduq.mjs} +16 -16
- package/dist/{agent-docs-BkQx62G6.mjs.map → agent-docs-xZISEduq.mjs.map} +1 -1
- package/dist/build-BLQQMQtM.mjs +13 -0
- package/dist/{build-CARdsp9F.mjs.map → build-BLQQMQtM.mjs.map} +1 -1
- package/dist/build-CKmAKaJ1.mjs +12 -0
- package/dist/{builtins-BOWp16P2.mjs → builtins-4IV5eliu.mjs} +80 -80
- package/dist/{builtins-Cb02IU36.mjs → builtins-4OFjCWYj.mjs} +2 -2
- package/dist/cli.mjs +2 -2
- package/dist/{config-DoZ1J2Kh.mjs → config-B3kSZiSh.mjs} +3 -3
- package/dist/{config-DoZ1J2Kh.mjs.map → config-B3kSZiSh.mjs.map} +1 -1
- package/dist/{config-CadmyiYh.mjs → config-v0mtdiYe.mjs} +2 -2
- package/dist/{doctor-C4bdYrM6.mjs → doctor-DJxEocJ5.mjs} +8 -8
- package/dist/{doctor-C4bdYrM6.mjs.map → doctor-DJxEocJ5.mjs.map} +1 -1
- package/dist/{fullstack-DjV35qtY.mjs → fullstack-DM0a3A8G.mjs} +4 -4
- package/dist/{fullstack-DjV35qtY.mjs.map → fullstack-DM0a3A8G.mjs.map} +1 -1
- package/dist/{fullstack-CiPh1wb_.mjs → fullstack-iWO7BFX6.mjs} +10 -10
- package/dist/index.d.mts +3 -50
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-BAlAQlkw.mjs → plugin-BCMbxzi5.mjs} +2 -2
- package/dist/{plugin-D8VpKAVP.mjs → plugin-P1F0k7kH.mjs} +2 -2
- package/dist/{project-CzMPptXL.mjs → project-6h_j0VK0.mjs} +25 -12
- package/dist/project-6h_j0VK0.mjs.map +1 -0
- package/dist/project-9QfIRkON.mjs +152 -0
- package/dist/{project-root-BHqLKyr9.mjs → project-root-DcfsBtCw.mjs} +3 -3
- package/dist/{project-root-BHqLKyr9.mjs.map → project-root-DcfsBtCw.mjs.map} +1 -1
- package/dist/{project-root-Ck8UKRHG.mjs → project-root-rs5vJCt5.mjs} +2 -2
- package/dist/{rolldown-runtime-BjnQdm0J.mjs → rolldown-runtime-CQE1JsWD.mjs} +1 -1
- package/dist/{run-plugins-BrI7b2Y5.mjs → run-plugins-BONtomzM.mjs} +147 -147
- package/dist/run-plugins-BONtomzM.mjs.map +1 -0
- package/dist/{typegen-D17TQ6Uy.mjs → typegen-FLvIFR3i.mjs} +5 -5
- package/dist/{typegen-D17TQ6Uy.mjs.map → typegen-FLvIFR3i.mjs.map} +1 -1
- package/dist/{typegen-0Ffq-YuL.mjs → typegen-ZG4nzOUN.mjs} +4 -4
- package/dist/{types-Bp0MoCVq.mjs → types-Doudtd8d.mjs} +1 -1
- package/package.json +12 -12
- package/templates/feature-storage/files/_dot_env.example.append +6 -0
- package/templates/feature-storage/files/src/adapters/storage.ts +2 -2
- package/templates/inertia-react/feature.json +13 -0
- package/templates/inertia-svelte/feature.json +13 -0
- package/templates/inertia-svelte/files/src/client/Layout.svelte +19 -0
- package/templates/inertia-svelte/files/src/client/Seo.svelte +47 -0
- package/templates/inertia-svelte/files/src/client/main.ts +16 -0
- package/templates/inertia-svelte/files/src/client/pages/Error.svelte +14 -0
- package/templates/inertia-svelte/files/src/client/pages/Home.svelte +13 -0
- package/templates/inertia-svelte/files/src/client/pages/Posts/Index.svelte +33 -0
- package/templates/inertia-svelte/files/src/client/ssr.ts +16 -0
- package/templates/inertia-svelte/files/src/client/svelte.d.ts +7 -0
- package/templates/inertia-svelte/files/vite.client.config.ts +32 -0
- package/templates/inertia-svelte/files/vite.config.ts +42 -0
- package/templates/inertia-vue/feature.json +13 -0
- package/templates/inertia-vue/files/src/client/Layout.vue +21 -0
- package/templates/inertia-vue/files/src/client/Seo.ts +49 -0
- package/templates/inertia-vue/files/src/client/main.ts +17 -0
- package/templates/inertia-vue/files/src/client/pages/Error.vue +16 -0
- package/templates/inertia-vue/files/src/client/pages/Home.vue +15 -0
- package/templates/inertia-vue/files/src/client/pages/Posts/Index.vue +31 -0
- package/templates/inertia-vue/files/src/client/ssr.ts +21 -0
- package/templates/inertia-vue/files/src/client/vue.d.ts +7 -0
- package/templates/inertia-vue/files/vite.client.config.ts +32 -0
- package/templates/inertia-vue/files/vite.config.ts +42 -0
- package/templates/template-inertia/feature.json +3 -13
- package/templates/template-inertia/files/src/client/app.css +1 -1
- package/templates/template-inertia/files/src/index.ts +4 -4
- package/templates/template-inertia/files/src/modules/pages/pages.controller.ts +1 -1
- package/dist/build-CARdsp9F.mjs +0 -13
- package/dist/build-I3pY30S2.mjs +0 -12
- package/dist/project-Bjk2dJc2.mjs +0 -139
- package/dist/project-CzMPptXL.mjs.map +0 -1
- package/dist/run-plugins-BrI7b2Y5.mjs.map +0 -1
- /package/templates/{template-inertia → inertia-react}/files/src/client/Layout.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/Seo.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/main.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/pages/Error.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/pages/Home.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/pages/Posts/Index.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/src/client/ssr.tsx +0 -0
- /package/templates/{template-inertia → inertia-react}/files/vite.client.config.ts +0 -0
- /package/templates/{template-inertia → inertia-react}/files/vite.config.ts +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v8.
|
|
2
|
+
* @forinda/kickjs-cli v8.18.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-
|
|
11
|
+
import{t as e}from"./rolldown-runtime-CQE1JsWD.mjs";import{n as t,t as n}from"./types-Doudtd8d.mjs";import{_ as r,a as i,b as a,d as o,g as s,h as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v,x as y,y as b}from"./project-6h_j0VK0.mjs";import{C as x,S,_ as ee,a as te,b as C,d as ne,f as w,g as re,h as T,i as E,m as D,n as ie,o as ae,p as oe,u as se,v as ce,x as le,y as O}from"./agent-docs-xZISEduq.mjs";import{a as ue,c as k,d as de,f as fe,h as pe,l as A,m as me,o as he,p as ge,s as j,u as _e}from"./config-B3kSZiSh.mjs";import{A as ve,C as ye,D as be,E as xe,F as Se,M as Ce,N as we,O as Te,P as M,S as Ee,T as De,_ as Oe,a as ke,b as Ae,c as je,f as Me,g as Ne,h as Pe,i as Fe,j as Ie,k as Le,l as Re,m as ze,p as Be,r as Ve,u as He,v as Ue,w as We,x as Ge,y as Ke}from"./doctor-DJxEocJ5.mjs";import{t as N}from"./project-root-DcfsBtCw.mjs";import{C as qe,S as Je,_ as Ye,a as Xe,b as Ze,c as Qe,d as $e,f as et,g as tt,h as nt,i as rt,l as it,m as at,o as ot,p as st,r as ct,s as lt,t as ut,u as dt,v as ft,w as pt,x as P,y as mt}from"./typegen-FLvIFR3i.mjs";import{t as ht}from"./build-BLQQMQtM.mjs";import{createRequire as gt}from"node:module";import F,{basename as _t,dirname as I,join as L,relative as R,resolve as z,sep as B}from"node:path";import{cpSync as vt,existsSync as V,mkdirSync as yt,readFileSync as H,readdirSync as bt,rmSync as xt,statSync as St,writeFileSync as U}from"node:fs";import{copyFile as Ct,mkdir as wt,readFile as W,readdir as Tt,rm as Et,stat as Dt,writeFile as Ot}from"node:fs/promises";import{fork as kt,spawn as At,spawnSync as jt}from"node:child_process";import{createHash as Mt}from"node:crypto";import{fileURLToPath as Nt,pathToFileURL as G}from"node:url";import{parseSync as Pt}from"oxc-parser";import{arch as Ft,platform as It,release as Lt}from"node:os";const Rt=[{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`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`},{value:`views`,label:`Views`,hint:`server-rendered .kick templates`}];function zt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`--client <framework>`,`Inertia template pages: react | vue | svelte (default react)`).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(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`--deploy <targets>`,`Comma-separated deploy targets to write files for: netlify, vercel, docker (later: kick g deploy)`).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)=>{ne(`KickJS — Create a new project`);let n=m(),r=e=>{e&&w.warn(`kick ${g} is behind the latest release, ${e} — templates and options added since are missing. Upgrade: npm i -g @forinda/kickjs-cli@latest`)},i=[];try{i=t.deploy?y(t.deploy):[]}catch(e){w.error(e.message),D(`Aborted.`),process.exitCode=1;return}let a=[`react`,`vue`,`svelte`],o=t.client;if(o!==void 0&&!a.includes(o)){w.error(`Unknown --client '${String(o)}'. Use ${a.join(`, `)}.`),D(`Aborted.`),process.exitCode=1;return}let s=!!(t.yes||t.nonInteractive);e||=s?`my-api`:await ee({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let c;if(e===`.`?(c=z(`.`),e=_t(c)):c=z(t.directory||e),V(c)){let n=bt(c);if(n.length>0){if(t.force)w.warn(`Clearing existing files in ${c}`);else if(s){w.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),D(`Aborted.`);return}else{w.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)w.message(` - ${e}`);if(n.length>5&&w.message(` ... and ${n.length-5} more`),!await se({message:O.red(`Remove all existing files and proceed?`),initialValue:!1})){D(`Aborted.`);return}}for(let e of n)xt(z(c,e),{recursive:!0,force:!0})}}s||r(await Promise.race([n,new Promise(e=>setTimeout(e,3e3,null).unref())]));let l=t.template;l||=s?`minimal`:await T({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`},{value:`inertia`,label:`Inertia`,hint:`server-driven React, Vue or Svelte pages, one app, SSR`}]}),l===`inertia`&&o===void 0?o=s?`react`:await T({message:`Pages written in`,options:[{value:`react`,label:`React`},{value:`vue`,label:`Vue`},{value:`svelte`,label:`Svelte`}]}):l!==`inertia`&&o!==void 0&&w.warn(`--client applies to the inertia template only; ignoring it.`);let u=t.runtime;u||=s?`express`:await T({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let f=t.pm;f||=s?await te(void 0):await T({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let p=t.repo;p||=s?`inmemory`:await ee({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),pe(p);let h=t.schema;l===`inertia`&&(h&&h!==`zod`&&w.warn(`The inertia template uses zod — ignoring --schema ${h}.`),h=`zod`),h||=s?`zod`:await T({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)||(w.warn(`Unknown --schema "${h}", falling back to zod.`),h=`zod`);let _;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();_=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else _=s?[]:await oe({message:`Select packages to include`,options:[...Rt],required:!1});let v;v=t.git===void 0?s?!0:await se({message:`Initialize git repository?`,initialValue:!0}):t.git;let b;if(b=t.install===void 0?s?!0:await se({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){w.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),D(`Aborted.`);return}let{VITE_TEMPLATES:x,DEFAULT_VITE_TEMPLATE:S}=await import(`./fullstack-DM0a3A8G.mjs`);if(t.viteTemplate!==void 0&&!x.some(e=>e.value===t.viteTemplate)){w.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${x.map(e=>e.value).join(`, `)}.`),D(`Aborted.`);return}let C=t.frontend===`vite`?`vite`:`kick`,re=t.viteTemplate??S;if(l===`fullstack`&&!t.frontend&&!s&&(C=await T({message:`Frontend for web/`,options:[{value:`kick`,label:`KickJS React app`,hint:`typed client, /api proxy, route types — wired`},{value:`vite`,label:`Delegate to create-vite`,hint:`pick any framework; wiring is manual (guide printed after)`}]})),C===`vite`&&!t.viteTemplate&&!s&&(re=await T({message:`create-vite template`,options:x.map(e=>({value:e.value,label:e.label})),initialValue:S})),l===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DM0a3A8G.mjs`);await t({name:e,directory:c,packageManager:f,initGit:v,installDeps:b,schemaLib:h,runtime:u,packages:_,frontend:C,viteTemplate:re,deploy:i}),s&&r(await n),D(`Done! Next steps: ${O.cyan(`cd ${e} && ${f}${f===`pnpm`?` dev`:` run dev:server`}`)}`)}else await d({name:e,directory:c,packageManager:f,initGit:v,installDeps:b,template:l,client:o,defaultRepo:p,packages:_,schemaLib:h,runtime:u,deploy:i}),s&&r(await n),D(`Done! Next steps: ${O.cyan(`cd ${e} && ${ge(f,`dev`)}`)}`)})}function Bt(e,t=[]){let r=/* @__PURE__ */ new Map;for(let t of e){let e=(r.get(t.name)??0)+1;if(r.set(t.name,e),e===2)throw new n(`plugin`,t.name,[t.name,t.name])}let i=/* @__PURE__ */ new Map,a=[];for(let t of e)for(let e of t.commands??[]){let r=i.get(e.name);if(r)throw new n(`command`,e.name,[r,t.name]);i.set(e.name,t.name),a.push(e)}let o=new Set(t.map(e=>e.name)),s=[...a.filter(e=>!o.has(e.name)),...t],c=/* @__PURE__ */ new Map,l=[];for(let t of e)for(let e of t.typegens??[]){let r=c.get(e.id);if(r)throw new n(`typegen`,e.id,[r,t.name]);c.set(e.id,t.name),l.push(e)}let u=/* @__PURE__ */ new Map,d=[];for(let t of e)for(let e of t.generators??[]){let r=u.get(e.name);if(r)throw new n(`generator`,e.name,[r,t.name]);u.set(e.name,t.name),d.push({source:t.name,spec:e})}return{commands:s,typegens:l,generators:d,register:async(t,n)=>{let r;if(n)r={generators:d,...n};else{let{findProjectRoot:e}=await import(`./project-root-DcfsBtCw.mjs`).then(e=>e.n),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:d}}for(let n of e)n.register&&await n.register(t,r)}}}async function Vt(e){let{name:t,outDir:n}=e,r=M(t),i=Se(t),a=[],o=L(n,`${r}.plugin.ts`);return await x(o,`import {
|
|
12
12
|
definePlugin,
|
|
13
13
|
type AppAdapter,
|
|
14
14
|
type AppModuleEntry,
|
|
@@ -17,21 +17,21 @@ import{t as e}from"./rolldown-runtime-BjnQdm0J.mjs";import{C as t,S as n,_ as r,
|
|
|
17
17
|
} from '@forinda/kickjs'
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
|
-
* Configuration for the ${
|
|
20
|
+
* Configuration for the ${i} plugin.
|
|
21
21
|
*
|
|
22
22
|
* Plugins typically take a small config object so callers can tune
|
|
23
23
|
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
24
24
|
* derived from the environment should be read inside the build
|
|
25
25
|
* function via getEnv(), not forced onto the caller.
|
|
26
26
|
*/
|
|
27
|
-
export interface ${
|
|
27
|
+
export interface ${i}PluginConfig {
|
|
28
28
|
// Add your plugin config here, e.g.:
|
|
29
29
|
// enabled?: boolean
|
|
30
30
|
// apiKey?: string
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
|
-
* ${
|
|
34
|
+
* ${i} plugin — built via \`definePlugin()\` so callers get the
|
|
35
35
|
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
36
36
|
*
|
|
37
37
|
* A plugin bundles DI bindings, modules, adapters, and middleware
|
|
@@ -61,16 +61,16 @@ export interface ${a}PluginConfig {
|
|
|
61
61
|
* @example
|
|
62
62
|
* \`\`\`ts
|
|
63
63
|
* import { bootstrap } from '@forinda/kickjs'
|
|
64
|
-
* import { ${
|
|
64
|
+
* import { ${i}Plugin } from './plugins/${r}.plugin'
|
|
65
65
|
*
|
|
66
66
|
* export const app = await bootstrap({
|
|
67
67
|
* modules,
|
|
68
|
-
* plugins: [${
|
|
68
|
+
* plugins: [${i}Plugin({ /* config overrides *\\/ })],
|
|
69
69
|
* })
|
|
70
70
|
* \`\`\`
|
|
71
71
|
*/
|
|
72
|
-
export const ${
|
|
73
|
-
name: '${
|
|
72
|
+
export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
73
|
+
name: '${i}Plugin',
|
|
74
74
|
defaults: {
|
|
75
75
|
// Default config values go here
|
|
76
76
|
},
|
|
@@ -136,12 +136,12 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
|
136
136
|
return [
|
|
137
137
|
// Example:
|
|
138
138
|
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
139
|
-
// declare module '@forinda/kickjs' { interface ContextMeta { ${
|
|
140
|
-
// const Load${
|
|
141
|
-
// key: '${
|
|
142
|
-
// resolve: (ctx) => ({ foo: ctx.req.headers['x-${
|
|
139
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
|
|
140
|
+
// const Load${i} = defineHttpContextDecorator({
|
|
141
|
+
// key: '${r}',
|
|
142
|
+
// resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
|
|
143
143
|
// })
|
|
144
|
-
// return [Load${
|
|
144
|
+
// return [Load${i}.registration]
|
|
145
145
|
]
|
|
146
146
|
},
|
|
147
147
|
|
|
@@ -152,7 +152,7 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
|
152
152
|
*/
|
|
153
153
|
async onReady(_container: Container): Promise<void> {
|
|
154
154
|
// const log = _container.resolve(Logger)
|
|
155
|
-
// log.info('${
|
|
155
|
+
// log.info('${i} plugin ready')
|
|
156
156
|
},
|
|
157
157
|
|
|
158
158
|
/**
|
|
@@ -165,67 +165,67 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
|
165
165
|
// Example: await this.connection?.close()
|
|
166
166
|
},
|
|
167
167
|
|
|
168
|
-
${
|
|
168
|
+
${Ae(r,i,`plugin`,` `)}
|
|
169
169
|
}),
|
|
170
170
|
})
|
|
171
|
-
`),
|
|
172
|
-
`)}\n}\n`:``,
|
|
171
|
+
`),a.push(o),a}function Ht(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function Ut(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=M(t),s=Se(t),c=e.key??we(t),l=Array.isArray(e.params)?e.params:Ht(e.params),u=Ue({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!1}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
172
|
+
`)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
173
173
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
174
174
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
175
|
-
requiredParams: [${
|
|
176
|
-
import type { ${
|
|
175
|
+
requiredParams: [${l.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,g=l.length>0?`(ctx, _deps, params)`:`(ctx)`,_=l.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${f} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,v=`import { ${d} } from '@forinda/kickjs'
|
|
176
|
+
import type { ${f} } from '@forinda/kickjs'
|
|
177
177
|
|
|
178
178
|
/**
|
|
179
|
-
* ${
|
|
179
|
+
* ${s} context contributor (${a}).
|
|
180
180
|
*
|
|
181
|
-
* Computes a value and writes it to \`ctx.set('${
|
|
181
|
+
* Computes a value and writes it to \`ctx.set('${c}', …)\` before a
|
|
182
182
|
* matched handler runs — the typed, ordered alternative to
|
|
183
183
|
* \`@Middleware()\` when the only job is to populate \`ctx\`.
|
|
184
184
|
*
|
|
185
185
|
* Apply per method/class:
|
|
186
186
|
*
|
|
187
|
-
${
|
|
187
|
+
${a===`http`?` * @${s}${l.length>0?`({ ${l[0]?.name}: … })`:``}
|
|
188
188
|
* @Get('/')
|
|
189
|
-
* handler(ctx: ${
|
|
190
|
-
* return ctx.require('${
|
|
189
|
+
* handler(ctx: ${f}) {
|
|
190
|
+
* return ctx.require('${c}')
|
|
191
191
|
* }`:` * // Any transport whose handler receives an ExecutionContext
|
|
192
192
|
* // (WebSocket, queue, cron). Attach via that transport's decorator,
|
|
193
193
|
* // or register the contributor at a module / bootstrap site below.
|
|
194
|
-
* handler(ctx: ${
|
|
195
|
-
* const value = ctx.require('${
|
|
194
|
+
* handler(ctx: ${f}) {
|
|
195
|
+
* const value = ctx.require('${c}')
|
|
196
196
|
* }`}
|
|
197
197
|
*
|
|
198
198
|
* Or register at a module / adapter / bootstrap site — those take a
|
|
199
199
|
* \`ContributorRegistration\`, not the decorator itself:
|
|
200
200
|
*
|
|
201
|
-
* bootstrap({ contributors: [${
|
|
201
|
+
* bootstrap({ contributors: [${s}${l.length>0?`.with({ ${l[0]?.name}: … })`:``}.registration] })
|
|
202
202
|
*/
|
|
203
203
|
|
|
204
|
-
// Register '${
|
|
204
|
+
// Register '${c}' so \`ctx.require('${c}')\` is typed and \`dependsOn: ['${c}']\`
|
|
205
205
|
// is checked. Replace \`unknown\` with the resolved value's real type.
|
|
206
206
|
// (For a key you only depend on — no value type needed — declare it in
|
|
207
207
|
// \`interface ContextKeys\` instead.)
|
|
208
208
|
declare module '@forinda/kickjs' {
|
|
209
209
|
interface ContextMeta {
|
|
210
|
-
'${
|
|
210
|
+
'${c}': unknown
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
-
${
|
|
214
|
-
export const ${
|
|
215
|
-
key: '${
|
|
216
|
-
${
|
|
217
|
-
${
|
|
218
|
-
// TODO: compute and return the value written to ctx.set('${
|
|
219
|
-
throw new Error("${
|
|
213
|
+
${p}
|
|
214
|
+
export const ${s} = ${m}
|
|
215
|
+
key: '${c}',
|
|
216
|
+
${h} resolve: ${g} => {
|
|
217
|
+
${_}
|
|
218
|
+
// TODO: compute and return the value written to ctx.set('${c}', …)
|
|
219
|
+
throw new Error("${s} contributor: resolve() not implemented")
|
|
220
220
|
},
|
|
221
221
|
})
|
|
222
|
-
`,
|
|
223
|
-
Skipped — existing kick.config.ts preserved.`),[]):(await t
|
|
222
|
+
`,y=L(u,`${o}.contributor.ts`);return await x(y,v),[y]}async function Wt(e){let t=L(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return V(t)&&!e.force&&!await se({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
223
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await x(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
224
224
|
|
|
225
225
|
export default defineConfig({
|
|
226
226
|
modules: {
|
|
227
|
-
dir: '${
|
|
228
|
-
repo: '${
|
|
227
|
+
dir: '${n}',
|
|
228
|
+
repo: '${r}',
|
|
229
229
|
pluralize: false,
|
|
230
230
|
},
|
|
231
231
|
|
|
@@ -263,18 +263,18 @@ export default defineConfig({
|
|
|
263
263
|
},
|
|
264
264
|
],
|
|
265
265
|
})
|
|
266
|
-
`),[
|
|
266
|
+
`),[t])}function Gt(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 K(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Gt(e,r);return i===-1?null:e.slice(r+1,i)}function Kt(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
267
267
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
268
|
-
`)}function
|
|
268
|
+
`)}function qt(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 Jt(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 Yt(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=Gt(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=K(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=K(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=K(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=qt(s),p=``;return l&&(p+=` register(container) {${Kt(l,4,6)} },\n\n`),u&&(p+=` contributors() {${Kt(u,4,6)} },\n\n`),p+=` routes() {${Kt(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
269
269
|
name: '${r}',
|
|
270
270
|
build: () => ({
|
|
271
271
|
${p}
|
|
272
272
|
}),
|
|
273
|
-
})`}${c}`}}function
|
|
274
|
-
`||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=
|
|
273
|
+
})`}${c}`}}function Xt(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=Gt(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]===`
|
|
274
|
+
`||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=Gt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=K(m,/register\s*\(([^)]*)\)\s*\{/),g=K(m,/contributors\s*\(\s*\)\s*\{/),_=K(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Jt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${Kt(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${Kt(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${Kt(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
275
275
|
${y}
|
|
276
276
|
}
|
|
277
|
-
`}${u}`}}function
|
|
277
|
+
`}${u}`}}function Zt(e,t){return t===`class`?Xt(e):Yt(e)}function Qt(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 $t(e){let t=[];return await n(z(e),0),t;async function n(e,r){let i;try{i=await Tt(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=L(e,a),o;try{o=await Dt(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function en(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Tt(e)}catch{return}await wt(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=L(e,a),o=L(t,a),s;try{s=await Dt(i)}catch{continue}s.isDirectory()?await r(i,o):(await Ct(i,o),n++)}}}function tn(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return L(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function nn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await $t(e),s=await W(L(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=tn(r),await en(e,c));let l=[];for(let e of o){let t=Zt(await W(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await Ot(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=L(e,`index.ts`),d=null;try{d=await W(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Qt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await Ot(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function rn(e,t){let n=await $t(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await W(e,`utf-8`);i.test(t)&&r.push(e)}return r}const an={string:{ts:`string`,zod:`z.string().min(1).max(200)`},text:{ts:`string`,zod:`z.string().min(1)`},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.iso.datetime()`},email:{ts:`string`,zod:`z.email()`},url:{ts:`string`,zod:`z.url()`},uuid:{ts:`string`,zod:`z.uuid()`},json:{ts:`any`,zod:`z.any()`}};function on(e){let t=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=an[a];if(!o){let e=[...Object.keys(an),`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}}),n=/* @__PURE__ */ new Set;for(let{name:e}of t){if(n.has(e))throw Error(`Duplicate field: "${e}". Each field name may appear once.`);n.add(e)}return t}async function sn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize===!0,c=M(t),l=Se(t),u=s?Ie(c):c,d=s?Ce(l):l,f=e.pluralizeRoutes===!1?c:Ie(c),p=L(r,u),m=[],h=async(e,t)=>{let n=L(p,e);await x(n,t),m.push(n)};return await h(`${c}.module.ts`,Le({pascal:l,kebab:c,plural:u,routePath:f,repo:i,style:o})),await h(`${c}.constants.ts`,De({pascal:l,kebab:c,fields:n})),await h(`${c}.controller.ts`,Te({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await h(`${c}.service.ts`,xe({pascal:l,kebab:c})),await h(`dtos/create-${c}.dto.ts`,cn(l,n)),await h(`dtos/update-${c}.dto.ts`,ln(l,n)),await h(`dtos/${c}-response.dto.ts`,un(l,n)),await h(`${c}.repository.ts`,be({pascal:l,kebab:c,repoType:i,dtoPrefix:`./dtos`,tokenScope:a})),await Ge(r,l,u,c,o),m}function cn(e,t){return`import { z } from 'zod'
|
|
278
278
|
|
|
279
279
|
export const create${e}Schema = z.object({
|
|
280
280
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -282,7 +282,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
282
282
|
})
|
|
283
283
|
|
|
284
284
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
285
|
-
`}function
|
|
285
|
+
`}function ln(e,t){return`import { z } from 'zod'
|
|
286
286
|
|
|
287
287
|
export const update${e}Schema = z.object({
|
|
288
288
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -290,17 +290,17 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
290
290
|
})
|
|
291
291
|
|
|
292
292
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
293
|
-
`}function
|
|
293
|
+
`}function un(e,t){return`export interface ${e}ResponseDTO {
|
|
294
294
|
id: string
|
|
295
295
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
296
296
|
`)}
|
|
297
297
|
createdAt: string
|
|
298
298
|
updatedAt: string
|
|
299
299
|
}
|
|
300
|
-
`}async function
|
|
300
|
+
`}async function dn(e){let{name:t,moduleName:n,modulesDir:r,testImport:i=`vitest`}=e,a=e.pluralize??!1,o=M(t),s=Se(t),c=[],l;if(e.outDir)l=z(e.outDir);else if(n){let e=M(n),t=a?Ie(e):e;l=z(L(r??`src/modules`,t,`__tests__`))}else l=z(`src/__tests__`);let u=L(l,`${o}.test.ts`);return await x(u,`import { describe, it, expect, beforeEach } from '${i}'
|
|
301
301
|
import { Container } from '@forinda/kickjs'
|
|
302
302
|
|
|
303
|
-
describe('${
|
|
303
|
+
describe('${s}', () => {
|
|
304
304
|
beforeEach(() => {
|
|
305
305
|
Container.reset()
|
|
306
306
|
})
|
|
@@ -320,63 +320,63 @@ describe('${c}', () => {
|
|
|
320
320
|
expect(true).toBe(true)
|
|
321
321
|
})
|
|
322
322
|
})
|
|
323
|
-
`),
|
|
324
|
-
(dry run — no files were written)`),console.log()}async function
|
|
325
|
-
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),
|
|
323
|
+
`),c.push(u),c}const fn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function q(e){return e.parent?.opts()?.dryRun??!1}function J(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
|
|
324
|
+
(dry run — no files were written)`),console.log()}async function pn(e){if(!e)try{let e=await j(process.cwd());await ut({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 mn=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`},{name:`deploy <targets...>`,description:`Deploy files: netlify | vercel | docker (config, entry, build script)`}],hn=/* @__PURE__ */ new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
325
|
+
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),gn=/* @__PURE__ */ new Set([...mn.map(e=>e.name.split(` `)[0]),...hn.keys()]);async function _n(){console.log(`
|
|
326
326
|
Built-in generators:
|
|
327
|
-
`);let e=Math.max(...
|
|
327
|
+
`);let e=Math.max(...mn.map(e=>e.name.length));for(let t of mn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await j(process.cwd()),n=Bt(t?.plugins??[],t?.commands??[]),r=await Fe(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
328
328
|
Plugin generators:
|
|
329
329
|
`);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(`
|
|
330
330
|
Failed to load:
|
|
331
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function
|
|
332
|
-
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,
|
|
333
|
-
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,
|
|
331
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function vn(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`])n[e]===!1&&(r[e]=!1);for(let e of[`pluralize`,`pluralizeRoutes`])r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return r}async function yn(e,t,n){let r=await j(process.cwd()),i=k(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??We(i.repo);t.repo&&pe(t.repo);let s=t.pattern??r?.pattern??`rest`,c=A(t.pluralize,i),l=_e(t.pluralizeRoutes,i),u=fe(r,process.cwd()),d=he(N()),f=de(N()),p=N(),m=ue(p,`@forinda/kickjs-testing`,`any`)&&ue(p,`supertest`,`any`),h=i.style??`define`;if(!n&&h===`define`){let e=await rn(z(a),`define`);if(e.length>0){console.error(`\n ${O.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${O.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${O.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${O.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${O.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${O.dim(`// kick.config.ts`)}\n ${O.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let g=[];for(let r of e){let e=await ye({name:r,modulesDir:z(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:m,testImport:me(p),dryRun:n,pluralize:c,pluralizeRoutes:l,tokenScope:u,swagger:d,schemaLib:f,style:i.style});g.push(...e)}J(g,n),await pn(n)}function bn(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await _n();return}if(!e||e.length===0){n.help();return}let a=q(i);S(a);let[o,s,...c]=e;if(o){let e=await j(process.cwd()),n=Bt(e?.plugins??[],e?.commands??[]),i=await ke({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){J(i.files,a);return}if(o!==`module`&&gn.has(o)){let e=hn.get(o);e?(console.error(`\n 'kick g ${o}' has been removed.`),console.error(` ${e}\n`)):(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 yn(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);S(r),await yn(e,vn(n,t),r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=q(n);S(r),J(await Ke({name:e,outDir:z(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=q(n);S(r),J(await Vt({name:e,outDir:z(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
332
|
+
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await Oe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:A(void 0,a),runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
333
|
+
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await Ne({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:A(void 0,a)}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
334
334
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
335
335
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
336
|
-
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,
|
|
337
|
-
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,
|
|
338
|
-
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,
|
|
339
|
-
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,
|
|
340
|
-
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,
|
|
336
|
+
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=q(n);S(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await j(process.cwd()),o=k(a),s=o.dir??`src/modules`;J(await Ut({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:A(void 0,o)}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
337
|
+
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await Pe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:A(void 0,a)}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
338
|
+
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await ze({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:A(void 0,a)}),r),await pn(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
|
|
339
|
+
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await Be({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:A(void 0,a),schemaLib:de(N())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
340
|
+
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=q(n);S(r);let i=await j(process.cwd()),a=k(i),o=a.dir??`src/modules`;J(await dn({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pluralize:A(void 0,a),testImport:me(N())}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
341
341
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
342
342
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
343
343
|
Optional: append :optional (shell-safe): description:text:optional
|
|
344
|
-
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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,r
|
|
344
|
+
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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=vn(r,n),a=q(r);S(a),t.length===0&&(console.error(`
|
|
345
345
|
Error: At least one field is required.
|
|
346
346
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
347
347
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
348
348
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
349
|
-
`),process.exit(1));let
|
|
350
|
-
`,u=``;
|
|
351
|
-
`)){if(!e.trim()||e.trim().startsWith(`#`))continue;let t=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*$/.exec(e);if(!t)break;n.push(t[1])}return n}let{workspaces:n}=JSON.parse(
|
|
349
|
+
`),process.exit(1));let o=await j(process.cwd()),s=k(o),c=i.modulesDir??s.dir??`src/modules`,l=on(t),u=fe(o,process.cwd()),d=he(N()),f=await sn({name:e,fields:l,modulesDir:z(c),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:A(i.pluralize,s),pluralizeRoutes:_e(i.pluralizeRoutes,s),tokenScope:u,swagger:d,style:s.style});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);J(f,a),await pn(a)}),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=q(t);S(n),J(await Wt({outDir:z(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (default: detected from kick.config, packageManager, or the lockfile)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=q(t);S(n);let r=e.only??`all`;fn.includes(r)?J(await ie({outDir:z(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${fn.join(` | `)}`),process.exitCode=1)}),n.command(`deploy <targets...>`).description(`Add deploy files: netlify | vercel | docker (config, serverless entry, build script)`).option(`--pm <pm>`,`Package manager (default: detected)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);S(r);let i;try{i=y(e.flatMap(e=>e.split(`,`))),J(await a({dir:z(`.`),targets:i,pm:t.pm,force:t.force}),r)}catch(e){console.error(` ${e.message}`),process.exitCode=1}});for(let e of t?.generators??[])xn(n,e,t?.projectRoot)}function xn(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=q(o);S(s);let c=await ke({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&J(c.files,s)})}const Sn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Cn(e){let t=F.resolve(e.cwd,`.kickjs/types`);e.check||await wt(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??nt,i=F.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(G(e).href)},async writeFile(t,n){let r=F.resolve(e.cwd,t);await wt(F.dirname(r),{recursive:!0}),await Ot(r,n,`utf8`)},getScanResult:e=>{let t=wn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?tt(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=F.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});o.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),s.push({id:n.id,status:`error`,outFile:i});continue}if(a===null){s.push({id:n.id,status:`skipped`});continue}let l=`${Sn}${n.id} */\n\n`+a+`
|
|
350
|
+
`,u=``;V(i)&&(u=await W(i,`utf8`)),u===l?s.push({id:n.id,status:`unchanged`,outFile:i}):e.check?(c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i})):(await Ot(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new He(c);return s}function wn(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 Tn(e,t){let n=new Set(t),r=[],i=[],a=/* @__PURE__ */ new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var En=/* @__PURE__ */ e({applyDisableFilter:()=>Tn,runAllPluginTypegens:()=>Dn});async function Dn(e){let{enabled:t,skipped:n,unknown:r}=Tn(Bt([...io,...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 Cn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Me())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof He||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function On(e){let t=process.platform===`win32`;for(let n of kn(e))for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=t?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=L(n,i);if(V(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function kn(e){let t=z(e),n=An(t);return(n?[t,n]:[t]).map(e=>L(e,`node_modules`,`.bin`))}function An(e){for(let t=I(e);t!==I(t);t=I(t)){let n=L(t,`pnpm-workspace.yaml`),r=L(t,`package.json`);if(V(n)||V(r))return jn(n,r).some(n=>Mn(n,R(t,e)))?t:void 0}}function jn(e,t){try{if(V(e)){let t=H(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
|
|
351
|
+
`)){if(!e.trim()||e.trim().startsWith(`#`))continue;let t=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*$/.exec(e);if(!t)break;n.push(t[1])}return n}let{workspaces:n}=JSON.parse(H(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function Mn(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(B).join(`/`))}function Nn(e){let t=e.spawnFn??At,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function Pn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
352
352
|
`):`${n.slice(0,t).join(`
|
|
353
|
-
`)}\n… ${n.length-t} more line(s)`}function
|
|
353
|
+
`)}\n… ${n.length-t} more line(s)`}function Fn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function In(e,t=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function Ln(e,t,n={}){t&&(process.env.PORT=t);let r=Fn(n.polling),i=process.cwd(),a=await j(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await ut({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=z(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await Dn({cwd:i,config:a});await rt(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(z(`package.json`)).resolve(`vite`),{createServer:d}=await import(G(u).href);globalThis[je]=`kick-dev`;let f=await d({configFile:z(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=On(i);e?m=Nn({cwd:i,bin:e,onResult:e=>{f.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?h||(h=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(h=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(Pn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let g=Re({cwd:i,config:a,emitWarning:e=>{console.warn(e),f.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>m?.schedule()});f.watcher.on(`add`,e=>g.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>g.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>g.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>g.handleWatchEvent(`unlinkDir`,e)),g.assetSrcRoots.length>0&&f.watcher.add([...g.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
|
|
354
354
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
355
|
-
`),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await f.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}async function
|
|
355
|
+
`),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await f.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}async function Rn(e){let t=await j(e);try{await ut({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1});let n=z(e,t?.typegen?.outDir??`.kickjs/types`),r=await Dn({cwd:e,config:t});await rt(n,r,!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function zn(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 Ln(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`\n Error: vite is not installed.\n Run: ${E()} add -D vite unplugin-swc\n`):console.error(`
|
|
356
356
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
357
357
|
Building for production...
|
|
358
|
-
`);let{createRequire:e}=await import(`node:module`),t=e(
|
|
359
|
-
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
360
|
-
Building asset map...`);try{await
|
|
358
|
+
`);let{createRequire:e}=await import(`node:module`),t=e(z(`package.json`)).resolve(`vite`),{build:n}=await import(G(t).href);await n({configFile:z(`vite.config.ts`)});let r=await j(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
|
|
359
|
+
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?L(`dist`,e):e.dest??L(`dist`,t),r=z(t),i=z(n);V(r)?(yt(i,{recursive:!0}),vt(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)):console.log(` ⚠ Skipped ${t} (not found)`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
|
|
360
|
+
Building asset map...`);try{await ht(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
361
361
|
Build complete.
|
|
362
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
363
|
-
Building asset map...`);try{await
|
|
362
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await j(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0)console.log(` No assetMap entries — nothing to build.`);else{console.log(`
|
|
363
|
+
Building asset map...`);try{await ht(e,{cwd:process.cwd()}),console.log(`
|
|
364
364
|
Asset build complete.
|
|
365
|
-
`)}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)),
|
|
366
|
-
No type-checker found. Install one in this project:\n ${
|
|
367
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function
|
|
368
|
-
`))})}const{bold:
|
|
369
|
-
`,r.start)+1,a=e.slice(i,r.start);return/^\s*$/.test(a)?`${e.slice(0,r.start)}${n},\n${a}${e.slice(r.start)}`:`${e.slice(0,r.start)}${n}, ${e.slice(r.start)}`}function
|
|
365
|
+
`)}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)),b(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=z(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await Rn(t);let n=On(t);if(!n){console.error(`
|
|
366
|
+
No type-checker found. Install one in this project:\n ${E(t)} add -D typescript (tsc)\n ${E(t)} add -D @typescript/native-preview (tsgo, faster)\n`),process.exit(1);return}let r=jt(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await In(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await Ln(e.entry,e.port)}catch(e){console.error(`
|
|
367
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Bn(){try{let e=I(Nt(import.meta.url));return JSON.parse(H(L(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Vn=new Set(Object.values(f).filter(e=>e.deprecated).map(e=>e.pkg));function Hn(e){let t=L(e,`package.json`);if(!V(t))return[];let n;try{n=JSON.parse(H(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=L(e,`node_modules`,...t.split(`/`),`package.json`);if(V(i))try{n=JSON.parse(H(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Vn.has(t)}})}function Un(e){let t=e;for(;;){if(V(L(t,`package.json`)))return t;let e=I(t);if(e===t)return null;t=e}}function Wn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Bn()}`,``,` System:`,` OS: ${It()} ${Lt()} (${Ft()})`,` Node: ${process.version}`],t=Un(process.cwd()),n=t?Hn(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(`
|
|
368
|
+
`))})}const{bold:Y,dim:X,green:Gn,red:Kn,yellow:qn,blue:Jn}=O;function Yn(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 Xn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Zn(e,t){try{return await Xn(`${e}${t}`)}catch{return null}}async function Qn(e){let[t,n,r,i,a]=await Promise.all([Zn(e,`/health`),Zn(e,`/metrics`),Zn(e,`/routes`),Zn(e,`/container`),Zn(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function $n(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=X(`─`.repeat(60));if(console.log(),console.log(Y(` KickJS Inspector`)+X(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Gn(`● healthy`):Kn(`● `+n.status);console.log(` ${Y(`Health:`)} ${e}`)}else console.log(` ${Y(`Health:`)} ${Kn(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Kn:r.errorRate>0?qn:Gn;console.log(` ${Y(`Uptime:`)} ${Yn(r.uptimeSeconds)}`),console.log(` ${Y(`Requests:`)} ${r.requests}`),console.log(` ${Y(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${X(`(`)}${t(e+`%`)}${X(`)`)}`)}if(a&&console.log(` ${Y(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${Y(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(Y(` Routes`)),console.log(s),console.log(` ${X(`METHOD`)} ${X(`PATH`.padEnd(36))} ${X(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${ce(e.method)} ${t} ${Jn(e.controller)}.${X(e.handler)}`)}}console.log(s),console.log()}function er(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 Qn(r);t.json?console.log(JSON.stringify(e,null,2)):$n(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Kn(` ✖ Could not connect to ${n}`)),console.error(X(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}const tr={express:{name:`expressRuntime`,from:`@forinda/kickjs`},fastify:{name:`fastifyRuntime`,from:`@forinda/kickjs/fastify`},h3:{name:`h3Runtime`,from:`@forinda/kickjs/h3`}},nr=`// Express needs a body parser; Fastify and h3 parse bodies natively.`;function rr(e,t,n,i=`src/index.ts`){let a={source:e,changes:[],manual:[],blocked:!1},o=tr[t],c=tr[n],l=or(ar(i,a.source));if(!l)return a.manual.push(`No bootstrap({ ... }) call in ${i}: set \`runtime: ${c.name}()\` (import { ${c.name} } from '${c.from}') yourself.`),a;let u=sr(l,`runtime`),d=`${c.name}()`;if(u){let e=u.value,r=ur(ar(i,a.source),o.from,o.name);if(u.shorthand||e.type!==`CallExpression`||e.callee?.type!==`Identifier`||r===void 0||e.callee.name!==r){let e=a.source.slice(u.start,u.end);return a.manual.push(`\`${e}\` in ${i} isn't a call to ${o.name}(): set it to ${d} (import { ${c.name} } from '${c.from}') yourself.`),a.blocked=!0,a}let s=e.arguments;if(s.length>0){let e=a.source.slice(s[0].start,s.at(-1).end);a.manual.push(`The ${t} runtime had options (${e}); ${n} takes its own — see guide/http-runtimes.`)}a.source=a.source.slice(0,e.start)+d+a.source.slice(e.end)}else a.source=cr(a.source,l,`runtime: ${d}`);if(a.changes.push(`runtime: ${d}`),a.source=s(a.source,{from:c.from,names:[c.name]},i),a.source=dr(a.source,o.from,o.name,i),t===`express`&&n!==`express`){let e=lr(a.source,i);e!==a.source&&(a.source=fr(e,`express`,i),a.changes.push(`removed express.json() — ${n} parses bodies itself`))}else if(n===`express`&&t!==`express`){let e=r(a.source,[{import:{from:`express`,default:`express`},slot:`middleware`,code:`${nr}\nexpress.json()`}],void 0,i);a.source=e.source,e.added.length>0&&a.changes.push(`added express.json() to middlewares`),e.manual.length>0&&a.manual.push(`Add express.json() to bootstrap({ middlewares }) yourself.`)}return a}function ir(e,t,n=`kick.config.ts`){let r=ar(n,e).body.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration;for(;r&&(r.type===`TSSatisfiesExpression`||r.type===`TSAsExpression`);)r=r.expression;if(r?.type===`CallExpression`&&(r=r.arguments?.[0]),r?.type!==`ObjectExpression`)return null;let i=sr(r,`runtime`);if(!i)return cr(e,r,`runtime: '${t}'`);let a=i.value;if(a.type!==`Literal`||typeof a.value!=`string`)return null;let o=e[a.start]===`"`?`"`:`'`;return`${e.slice(0,a.start)}${o}${t}${o}${e.slice(a.end)}`}function ar(e,t){return Pt(e,t).program}function or(e){let t,n=e=>{if(t||!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(n);let r=e;if(r.type===`CallExpression`&&r.callee?.type===`Identifier`&&r.callee.name===`bootstrap`&&r.arguments?.[0]?.type===`ObjectExpression`)t=r.arguments[0];else for(let e in r)n(r[e])};return n(e),t}function sr(e,t){return e.properties.find(e=>e.type===`Property`&&(e.key?.name??e.key?.value)===t)}function cr(e,t,n){let r=t.properties[0];if(!r)return`${e.slice(0,t.start)}{ ${n} }${e.slice(t.end)}`;let i=e.lastIndexOf(`
|
|
369
|
+
`,r.start)+1,a=e.slice(i,r.start);return/^\s*$/.test(a)?`${e.slice(0,r.start)}${n},\n${a}${e.slice(r.start)}`:`${e.slice(0,r.start)}${n}, ${e.slice(r.start)}`}function lr(e,t){let n=or(ar(t,e)),r=n&&sr(n,`middlewares`);if(!r||r.value.type!==`ArrayExpression`)return e;let i=r.value.elements.find(e=>e?.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.name===`express`&&e.callee.property?.name===`json`);if(!i)return e;let a=i.start,o=i.end,s=e.slice(o).match(/^\s*,/);s&&(o+=s[0].length);let c=e.lastIndexOf(`
|
|
370
370
|
`,a)+1;if(/^\s*$/.test(e.slice(c,a))){a=c;let t=e.lastIndexOf(`
|
|
371
|
-
`,a-2)+1;e.slice(t,a-1).trim()===
|
|
372
|
-
`,o);n!==-1&&/^\s*$/.test(e.slice(o,n))&&(o=n+1)}return e.slice(0,a)+e.slice(o)}function
|
|
373
|
-
`?t.end+1:t.end;return e.slice(0,t.start)+e.slice(n)}let i=r.filter(e=>e.type===`ImportSpecifier`);if(n.type===`ImportSpecifier`&&i.length===1){let t=e.lastIndexOf(`,`,n.start),r=e.indexOf(`}`,n.end)+1;return e.slice(0,t)+e.slice(r)}if(n.type===`ImportDefaultSpecifier`){let t=e.indexOf(`,`,n.end)+1,r=e.slice(t).match(/^\s*/)[0].length;return e.slice(0,n.start)+e.slice(t+r)}let a=i.indexOf(n),o=a===0?n.start:i[a-1].end,s=a===0?i[1].start:n.end;return e.slice(0,o)+e.slice(s)}const
|
|
374
|
-
`);return}let i;try{i=
|
|
375
|
-
`),process.exitCode=1;return}let
|
|
376
|
-
`).forEach((t,r)=>{(
|
|
371
|
+
`,a-2)+1;e.slice(t,a-1).trim()===nr&&(a=t);let n=e.indexOf(`
|
|
372
|
+
`,o);n!==-1&&/^\s*$/.test(e.slice(o,n))&&(o=n+1)}return e.slice(0,a)+e.slice(o)}function ur(e,t,n){for(let r of e.body)if(r.type===`ImportDeclaration`&&r.source.value===t)for(let e of r.specifiers){let t=e.imported?.name??e.imported?.value;if(e.type===`ImportSpecifier`&&t===n)return e.local.name}}function dr(e,t,n,r){let i=ar(r,e);for(let r of i.body){if(r.type!==`ImportDeclaration`||r.source.value!==t)continue;let a=r.specifiers.find(e=>e.type===`ImportSpecifier`&&(e.imported?.name??e.imported?.value)===n);if(a)return pr(i,a.local.name)?e:mr(e,r,a)}return e}function fr(e,t,n){let r=ar(n,e);for(let n of r.body){if(n.type!==`ImportDeclaration`||n.source.value!==t)continue;let i=n.specifiers.find(e=>e.type===`ImportDefaultSpecifier`);if(i)return pr(r,i.local.name)?e:mr(e,n,i)}return e}function pr(e,t){let n=!1,r=e=>{if(n||!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(r);let i=e;if(i.type!==`ImportDeclaration`){if((i.type===`Identifier`||i.type===`IdentifierReference`)&&i.name===t)n=!0;else for(let e in i)e!==`parent`&&r(i[e])}};return r(e.body),n}function mr(e,t,n){let r=t.specifiers;if(r.length===1){let n=e[t.end]===`
|
|
373
|
+
`?t.end+1:t.end;return e.slice(0,t.start)+e.slice(n)}let i=r.filter(e=>e.type===`ImportSpecifier`);if(n.type===`ImportSpecifier`&&i.length===1){let t=e.lastIndexOf(`,`,n.start),r=e.indexOf(`}`,n.end)+1;return e.slice(0,t)+e.slice(r)}if(n.type===`ImportDefaultSpecifier`){let t=e.indexOf(`,`,n.end)+1,r=e.slice(t).match(/^\s*/)[0].length;return e.slice(0,n.start)+e.slice(t+r)}let a=i.indexOf(n),o=a===0?n.start:i[a-1].end,s=a===0?i[1].start:n.end;return e.slice(0,o)+e.slice(s)}const hr={express:/from ['"](express|@types\/express)['"]/,fastify:/from ['"](fastify|@fastify\/[^'"]+)['"]/,h3:/from ['"]h3['"]/},gr=e=>e.replace(/(?<=.)@[^/]*$/,``);function _r(e){e.command(`runtime [engine]`).description(`Show the HTTP engine, or move the app to another: express | fastify | h3`).option(`--dry-run`,`Print what would change, and change nothing`).option(`--no-install`,`Edit the files only; leave packages to you`).option(`--pm <manager>`,`Package manager override`).option(`--entry <file>`,`Entry file (default: src/index.ts, then src/main.ts)`).option(`-f, --force`,`Edit files with uncommitted changes`).action(async(e,t)=>{let n=process.cwd(),r=await p(n);if(!e){let e=r.fromConfig?`kick.config.ts`:`guessed from package.json`;console.log(`\n HTTP runtime: ${r.runtime} (${e})`),r.ambiguous&&console.log(` Several engines are installed: ${r.candidates.join(`, `)}.`),console.log(` Move to another with: kick runtime <express|fastify|h3>
|
|
374
|
+
`);return}let i;try{i=l(e)}catch{console.error(`\n Unknown engine '${e}'. Expected express, fastify or h3.\n`),process.exitCode=1;return}if(r.ambiguous&&!r.fromConfig){console.error(`\n Cannot tell which engine this app boots on now: found ${r.candidates.join(`, `)} in package.json.\n Set \`runtime: '<engine>'\` in kick.config.ts, then rerun.\n`),process.exitCode=1;return}let a=r.runtime;if(a===i){console.log(`\n Already on ${i}.\n`);return}let o=c(n,t.entry);if(!o){console.error(`\n No entry file (${t.entry??`src/index.ts or src/main.ts`}).\n`),process.exitCode=1;return}let s=[`kick.config.ts`,`kick.config.mts`,`kick.config.js`].find(e=>V(L(n,e))),d=u(n,[o,...s?[s]:[]]);if(d.length>0&&!t.force&&!t.dryRun){console.error(`\n ${d.join(`, `)} ${d.length===1?`has`:`have`} uncommitted changes. Commit or stage them first, so this change is its own diff, or rerun with --force.
|
|
375
|
+
`),process.exitCode=1;return}let f=rr(H(L(n,o),`utf-8`),a,i,o);if(f.blocked){for(let e of f.manual)console.error(`\n ${e}`);console.error(`\n Nothing changed. Fix that, then rerun kick runtime ${i}.\n`),process.exitCode=1;return}let m=s?H(L(n,s),`utf-8`):void 0,h=m===void 0?null:ir(m,i,s);h===null&&f.manual.push(`Set \`runtime: '${i}'\` in ${s??`kick.config.ts`} so kick commands know the engine.`);let g=xr(L(n,`src`)).map(e=>({file:e,text:e===L(n,o)?f.source:H(e,`utf-8`)})),_=g.some(({text:e})=>/@FileUpload\(|upload\.(single|array|none)\(/.test(e)),y=br(n),{toAdd:b,toAddDev:x,toRemove:S,stillImported:ee}=vr({from:a,to:i,installed:/* @__PURE__ */ new Set([...Object.keys(y.dependencies),...Object.keys(y.devDependencies)]),uploads:_,imported:e=>g.some(({text:t})=>RegExp(`from ['"]${e}(/[^'"]*)?['"]`).test(t))}),te=[];for(let{file:e,text:t}of g)t.split(`
|
|
376
|
+
`).forEach((t,r)=>{(hr[a].test(t)||/\bctx\.res\./.test(t))&&te.push(`${R(n,e)}:${r+1} ${t.trim()}`)});console.log(`\n ${a} → ${i}\n`);for(let e of f.changes)console.log(` ${o}: ${e}`);if(h&&console.log(` ${s}: runtime: '${i}'`),b.length&&console.log(` + ${b.join(`, `)}`),x.length&&console.log(` + ${x.join(`, `)} (dev)`),S.length&&console.log(` - ${S.join(`, `)}`),ee.length&&console.log(` kept ${ee.join(`, `)}: still imported in src/`),t.dryRun){console.log(`
|
|
377
377
|
Dry run: nothing changed.
|
|
378
|
-
`),
|
|
379
|
-
`),
|
|
378
|
+
`),yr(f.manual,te,a);return}U(L(n,o),f.source),h!==null&&U(L(n,s),h);let C=!0;if(t.install!==!1){let{pm:e}=await ae(t.pm),r=t=>{let r=[e,...t].join(` `);console.log(`\n ${r}`);try{v(e,t,{cwd:n})}catch{C=!1,console.log(` Failed. Run it yourself:\n ${r}`)}};b.length&&r([`add`,...b]),x.length&&r([`add`,`-D`,...x]),S.length&&r([e===`npm`?`uninstall`:`remove`,...S])}yr(f.manual,te,a),console.log(C?" Done. Run `kick typegen` and your typecheck to see the rest.\n":` Files changed; the package step above did not finish.
|
|
379
|
+
`),C||(process.exitCode=1)})}function vr(e){let{from:t,to:n,installed:r,uploads:a,imported:o}=e,s=[...i[n],...a&&h[n].prod?[h[n].prod]:[]],c=[...n===`express`?[`@types/express`]:[],...a&&h[n].dev?[h[n].dev]:[]],l=new Set([...s,...c].map(gr)),u=[...i[t],...t===`express`?[`@types/express`]:[],...h[t].prod?[h[t].prod]:[],...h[t].dev?[h[t].dev]:[]].map(gr).filter(e=>r.has(e)&&!l.has(e)),d=u.filter(e=>o(e.replace(/^@types\//,``)));return{toAdd:s.filter(e=>!r.has(gr(e))),toAddDev:c.filter(e=>!r.has(gr(e))),toRemove:u.filter(e=>!d.includes(e)),stillImported:d}}function yr(e,t,n){for(let t of e)console.log(`\n ! ${t}`);if(t.length>0){console.log(`\n Review — code that uses ${n} or the engine's response (ctx.res) directly:`);for(let e of t)console.log(` ${e}`)}console.log()}function br(e){try{let t=JSON.parse(H(L(e,`package.json`),`utf-8`));return{dependencies:t.dependencies??{},devDependencies:t.devDependencies??{}}}catch{return{dependencies:{},devDependencies:{}}}}function xr(e){return V(e)?bt(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&/\.(ts|tsx|mts)$/.test(e.name)).map(e=>L(e.parentPath,e.name)):[]}function Z(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Q(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Sr=[{match(e,t){let n=Z(e,[`config`,`get`])&&Q(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Q(e,[`undefined`,`is not defined`]);return!n&&!r?null:Q(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
|
|
380
380
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
381
381
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
382
382
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -400,7 +400,7 @@ import { modules } from './modules'
|
|
|
400
400
|
import './config' // ← add this — registers env schema
|
|
401
401
|
import { bootstrap } from '@forinda/kickjs'
|
|
402
402
|
import { modules } from './modules'
|
|
403
|
-
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=
|
|
403
|
+
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Q(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return Q(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
|
|
404
404
|
When vitest re-imports your modules across tests, the same class can be
|
|
405
405
|
registered twice and the container throws. The fix is to wipe the
|
|
406
406
|
container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
|
|
@@ -410,7 +410,7 @@ describe('UserController', () => {
|
|
|
410
410
|
beforeEach(() => Container.reset())
|
|
411
411
|
|
|
412
412
|
it('does the thing', async () => { /* ... */ })
|
|
413
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
413
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Z(e,[`Module`,`is not a function`])||Z(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
|
|
414
414
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
415
415
|
returns the controller wiring. This was a deliberate choice — modules
|
|
416
416
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -437,7 +437,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
437
437
|
and matches the actual class names so refactors propagate via
|
|
438
438
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
439
439
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
440
|
-
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=
|
|
440
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=Q(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Q(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
|
|
441
441
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
442
442
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
443
443
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -445,7 +445,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
445
445
|
version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
|
|
446
446
|
modules,
|
|
447
447
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
448
|
-
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return
|
|
448
|
+
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return Q(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
|
|
449
449
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
450
450
|
before any decorator runs. Most projects do this at the top of
|
|
451
451
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -454,7 +454,7 @@ import './config'
|
|
|
454
454
|
import { bootstrap } from '@forinda/kickjs'
|
|
455
455
|
import { modules } from './modules'
|
|
456
456
|
|
|
457
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return
|
|
457
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return Q(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
|
|
458
458
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
459
459
|
the most likely cause is that the module is missing from the exported
|
|
460
460
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -462,7 +462,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
462
462
|
import { UserModule } from './users/user.module'
|
|
463
463
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
464
464
|
|
|
465
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!
|
|
465
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!Q(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=Q(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=Q(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&Q(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
|
|
466
466
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
467
467
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
468
468
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -496,7 +496,7 @@ beforeAll(() => {
|
|
|
496
496
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
497
497
|
resetEnvCache()
|
|
498
498
|
loadEnv(envSchema)
|
|
499
|
-
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=
|
|
499
|
+
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=Z(e,[`cannot inject`,`request-scoped`,`singleton`]),r=Z(e,[`request-scoped`,`singleton`]);return!n&&!r?null:{confidence:n?100:70,diagnosis:{id:`di-request-scope-into-singleton`,title:`A SINGLETON cannot hold a REQUEST-scoped dependency`,explanation:`Controllers are SINGLETON by default: one instance for the process, built
|
|
500
500
|
the first time the container resolves it. A REQUEST-scoped binding is the
|
|
501
501
|
opposite — one instance per request, discarded when the response ends.
|
|
502
502
|
|
|
@@ -517,7 +517,7 @@ and the singleton never captures one.
|
|
|
517
517
|
|
|
518
518
|
If the dependency did not need request scope in the first place, the
|
|
519
519
|
other direction also works — make it SINGLETON and pass the per-request
|
|
520
|
-
values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=
|
|
520
|
+
values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=Z(e,[`circular`,`dependency`]);return!n&&!r?null:{confidence:n?100:65,diagnosis:{id:`di-circular-dependency`,title:`Two services depend on each other, directly or through a chain`,explanation:`The container resolves constructor dependencies depth-first. When a token
|
|
521
521
|
is requested while it is already being resolved further up the stack, the
|
|
522
522
|
graph has a cycle and there is no order that satisfies both ends.
|
|
523
523
|
|
|
@@ -549,7 +549,7 @@ export class OrderService {
|
|
|
549
549
|
@Service()
|
|
550
550
|
export class BillingService {
|
|
551
551
|
@Autowired() private readonly orders!: OrderService // ← resolved after construction
|
|
552
|
-
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=
|
|
552
|
+
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=Q(e,[`no provider for`,`no provider found for`,`no binding is registered`]);return!n&&!r?null:{confidence:n?100:85,diagnosis:{id:`di-no-provider-for-token`,title:`A token was requested but nothing registers it`,explanation:`Decorators register bindings as a side effect of the class being LOADED —
|
|
553
553
|
and a class is only loaded if something imports it. A module that is not
|
|
554
554
|
in the bootstrap array is never imported, so none of its @Service /
|
|
555
555
|
@Repository / @Controller classes ever register, and the first thing that
|
|
@@ -575,7 +575,7 @@ export const TenantModule = defineModule({
|
|
|
575
575
|
},
|
|
576
576
|
routes: () => null,
|
|
577
577
|
}),
|
|
578
|
-
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!
|
|
578
|
+
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!Q(e,[`vite`,`kick dev`,`dev server`,`localhost:5173`,`:5173`])||!Q(e,[`404`,`not found`,`cannot get`,`cannot post`,`no route`]))return null;let n=Z(e,[`app`,`export`]),r=Q(e,[`every route`,`all routes`,`every endpoint`,`all endpoints`,`none of the routes`]);return!n&&!r?null:{confidence:n&&r?85:n?80:70,diagnosis:{id:`vite-dev-app-not-exported`,title:"Every route 404s in dev because the entry file exports no `app`",explanation:`The Vite plugin does not start your server. It imports the entry module
|
|
579
579
|
and reads \`app\` off it, then hands each request to that instance.
|
|
580
580
|
|
|
581
581
|
When the entry runs \`await bootstrap(...)\` without assigning the result to
|
|
@@ -591,23 +591,23 @@ import { bootstrap } from '@forinda/kickjs'
|
|
|
591
591
|
await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
|
|
592
592
|
import { bootstrap } from '@forinda/kickjs'
|
|
593
593
|
|
|
594
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function
|
|
594
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Cr(e,t){let n=null;for(let r of Sr){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 wr(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.
|
|
595
595
|
export OPENAI_API_KEY="sk-..."
|
|
596
596
|
|
|
597
597
|
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:
|
|
598
598
|
kick add ai
|
|
599
599
|
|
|
600
600
|
Or manually:
|
|
601
|
-
${
|
|
602
|
-
`)}function
|
|
601
|
+
${E()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Tr(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Er((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 Tr(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
602
|
+
`)}function Er(e){let t=[e,Dr(e),Or(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(kr(t))return t}catch{continue}return null}function Dr(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Or(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;else if(o===`\\`&&r)i=!0;else if(o===`"`)r=!r;else if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function kr(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 Ar(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 Nr(e,t.message);n&&n.trim().length!==0||(process.stderr.write(`Error: no input provided.
|
|
603
603
|
|
|
604
604
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
605
605
|
kick explain "config.get returned undefined"
|
|
606
|
-
${
|
|
607
|
-
`);return}if(i){
|
|
608
|
-
`),process.exit(2)),
|
|
609
|
-
`),process.exit(a.kind===`ok`?0:2)),
|
|
610
|
-
`)}function
|
|
606
|
+
${ge(E(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=Fr(),i=Cr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
607
|
+
`);return}if(i){Ir(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
608
|
+
`),process.exit(2)),Lr(n),process.exit(2));let a=await wr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(jr(a),null,2)+`
|
|
609
|
+
`),process.exit(a.kind===`ok`?0:2)),Mr(n,a),process.exit(a.kind===`ok`?0:2)})}function jr(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 Mr(e,t){t.kind===`ok`?Ir(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${zr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Rr(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${zr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Nr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Pr()}function Pr(){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 Fr(){let e=process.cwd();return{cwd:e,hasFile:t=>V(z(e,t))}}function Ir(e,t,n,r=!1){let i=zr(e.trim(),200),a=r?`AI-generated — verify before applying`:Br(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${Rr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Rr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Rr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Rr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
610
|
+
`)}function Lr(e){let t=zr(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
|
|
611
611
|
|
|
612
612
|
1. Check the framework docs for the error keywords:
|
|
613
613
|
https://kickjs.app/
|
|
@@ -619,10 +619,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
619
619
|
3. File an issue with the error text:
|
|
620
620
|
https://github.com/forinda/kick-js/issues/new
|
|
621
621
|
|
|
622
|
-
`)}function
|
|
622
|
+
`)}function Rr(e,t){return e.split(`
|
|
623
623
|
`).map(e=>`${t}${e}`).join(`
|
|
624
|
-
`)}function
|
|
625
|
-
`,`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
|
|
624
|
+
`)}function zr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Br(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Vr(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(Hr),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(Ur)}function Hr(e){let t=z(e.entry);V(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=At(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)=>{t?process.kill(process.pid,t):process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Ur(e){let t=process.cwd(),n=Wr(t)??_t(t),r=e.name??n,i=e.global?z(process.env.HOME??`.`,`.mcp.json`):z(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(V(i))try{let e=H(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,U(i,JSON.stringify(o,null,2)+`
|
|
625
|
+
`,`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 Wr(e){let t=z(e,`package.json`);if(!V(t))return null;try{let e=H(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Gr(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=z(t,e.entry);V(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=qr(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${E(t)} add -D tsx\n`),process.exit(1));let i=Kr(n,e.entry),a=L(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=kt(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Kr(e,t){return`
|
|
626
626
|
import 'reflect-metadata'
|
|
627
627
|
|
|
628
628
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -647,7 +647,7 @@ try {
|
|
|
647
647
|
|
|
648
648
|
// Load entry to trigger decorator registration
|
|
649
649
|
try {
|
|
650
|
-
await import('${
|
|
650
|
+
await import('${G(e).href}')
|
|
651
651
|
} catch (err) {
|
|
652
652
|
console.warn(' Warning: ' + err.message)
|
|
653
653
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -676,46 +676,46 @@ server.on('exit', () => {
|
|
|
676
676
|
console.log('\\n Goodbye!\\n')
|
|
677
677
|
process.exit(0)
|
|
678
678
|
})
|
|
679
|
-
`}function
|
|
679
|
+
`}function qr(e,t){for(let n of kn(e)){let e=L(n,t);if(V(e))return e}return null}function Jr(e,t){let n=RegExp(`^\\s*${ve(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
|
|
680
680
|
`;)s++;else{for(s+=2;s+1<a.length&&(a[s]!==`*`||a[s+1]!==`/`);)s++;s+=2}continue}let t=a[s]??``;if(t===`'`||t===`"`||t==="`"){let e=t;for(s++;s<a.length&&a[s]!==e;)a[s]===`\\`&&s++,s++}else if(t===`(`)o++;else if(t===`)`&&(o--,o===0))break;s++}if(o!==0)break;let c=a.slice(t,s);if(n.test(c)){let t=e;for(;t>0&&(a[t-1]===` `||a[t-1]===` `||a[t-1]===`
|
|
681
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function
|
|
681
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function Yr(e,t){let n=Ee(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Jr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${ve(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 Xr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize===!0,a=M(t),o=Se(t),s=i?Ie(a):a;s!==a&&!await le(L(n,s))&&await le(L(n,a))&&(s=a);let c=L(n,s);if(!await le(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await se({message:O.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
682
682
|
Cancelled.
|
|
683
|
-
`);return}await
|
|
683
|
+
`);return}await Et(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=L(n,`index.ts`);if(await le(l)){let e=await W(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${ve(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${ve(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Yr(e,o),e=e.replace(/\n{3,}/g,`
|
|
684
684
|
|
|
685
|
-
`),e!==
|
|
685
|
+
`),e!==t&&(await x(l,e),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Zr(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(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await j(process.cwd()),r=k(n),i=t.modulesDir??r.dir??`src/modules`,a=A(t.pluralize,r);for(let n of e)await Xr({name:n,modulesDir:z(i),force:t.force,pluralize:a})})}function Qr(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 $r(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function ei(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=N(process.cwd()),n=await j(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-BCMbxzi5.mjs`),{builtinCliPlugins:t}=await import(`./builtins-4OFjCWYj.mjs`),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
|
|
686
686
|
Registered typegen plugins:
|
|
687
687
|
`);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``,n=`${e.id.replace(/\//g,`__`)}${e.outExtension??`.d.ts`}`;console.log(` ${e.id.padEnd(a+2)}→ .kickjs/types/${n}${t}`),console.log(` ${` `.repeat(a+2)} watches: ${e.inputs.join(`, `)||`(none)`}`)}console.log(`
|
|
688
688
|
Disable one in kick.config.ts:
|
|
689
689
|
`),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
|
|
690
|
-
`);return}let r
|
|
690
|
+
`);return}let r=Qr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=$r(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ct(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 ut(a);let r=await Dn({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=z(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await rt(i,r,e.silent??!1)}}}catch(e){e instanceof lt?console.error(`
|
|
691
691
|
`+e.message+`
|
|
692
|
-
`):e instanceof
|
|
692
|
+
`):e instanceof He?console.error(`
|
|
693
693
|
`+e.message+`
|
|
694
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const
|
|
695
|
-
`).length:1}function
|
|
694
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const ti=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function ni(e,t){return typeof t==`number`?e.slice(0,t).split(`
|
|
695
|
+
`).length:1}function ri(e){let t=qe(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(Je(e)&&e.type===`MemberExpression`&&P(e.object)===`Scope`){let t=P(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function ii(e){let t=P(e);if(t)return{key:`id:${t}`,label:t};let n=qe(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function ai(e,t){let n=(e.body?.body??[]).find(e=>e.type===`MethodDefinition`&&e.kind===`constructor`)?.value?.params??[],r=[];for(let e of n){let n=e.type===`TSParameterProperty`?e.parameter:e,i=ft(e).map(Ye).find(e=>e?.name===`Inject`),a=null;if(i)a=ii(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=ii(e.typeName))}a&&r.push({...a,line:ni(t,e.start)})}return r}function oi(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,/* @__PURE__ */ new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,/* @__PURE__ */ new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=Pt(t,n);if(r.errors.length>0)continue;e=r.program}catch{continue}for(let n of e.body??[]){let e=(n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`)&&Je(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(P(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(P(n.id),t)}pt(e,e=>{if(e.type===`ClassDeclaration`){let a=P(e.id);if(!a)return;for(let o of ft(e)){let s=Ye(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:ai(e,n)});return}if(ti.has(s.name)){let o=Ze(mt(s.call),`scope`),c=o?ri(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:ai(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!Je(a)||a.type!==`MemberExpression`)return;let o=P(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=ii(s[0]);c&&i(c.key,s.length>=3?ri(s[2]):`singleton`)})}let o=e=>(n.get(e)?.size??0)<=1,s=(e,n)=>{let r=t.get(e);return r?.size===1&&r.has(n)},c=[];for(let e of r)if(o(e.name)&&s(`id:${e.name}`,`singleton`))for(let t of e.params){if(t.key.startsWith(`id:`)&&!o(t.label)||!s(t.key,`request`))continue;let n=e.kind===`controller`?`@Controller() is always SINGLETON, so inject ${t.label} with @Autowired() instead of the constructor.`:`Give ${e.name} TRANSIENT or REQUEST scope, or inject ${t.label} with @Autowired() instead of the constructor.`;c.push({file:e.file,line:t.line,parent:e.name,dependency:t.label,message:`${e.name} (SINGLETON) injects REQUEST-scoped ${t.label} through its constructor — the first request that resolves it answers 500. ${n}`})}return c}function si(e){let t=[];if(!V(e))return t;let n=bt(e,{withFileTypes:!0});for(let r of n){let n=L(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...si(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function ci(e){try{return H(e,`utf-8`)}catch{return``}}const li=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function ui(e,t){let n=ci(L(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(li.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 di(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 fi(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 pi(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function mi(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 hi(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 gi(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 _i(e){let t=si(L(e,`src`)).map(e=>ci(e)),n=[],r=ui(e,t);r&&n.push(r);let i=di(t);i&&n.push(i);let a=fi(t);a&&n.push(a);let o=pi();o&&n.push(o);let s=mi(t);return s&&n.push(s),n.push(hi(t)),n.push(gi(t)),n}function vi(e){let t=oi(si(L(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:R(e,t).split(`\\`).join(`/`),source:ci(t)})));return t.length===0?[{severity:`INFO`,message:`No REQUEST-scoped dependency injected into a singleton`}]:t.map(e=>({severity:`CRITICAL`,message:`${e.file}:${e.line} ${e.message}`}))}function yi(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).option(`--di`,`Find REQUEST-scoped dependencies injected into singletons`).action(e=>{if(!e.deploy&&!e.di){console.log(`
|
|
696
696
|
Usage: kick check [--deploy] [--di]
|
|
697
697
|
|
|
698
698
|
Available checks:
|
|
699
699
|
--deploy Audit for production readiness (security, config, best practices)
|
|
700
700
|
--di Find REQUEST-scoped dependencies injected into singleton constructors
|
|
701
|
-
`);return}let t=process.cwd();
|
|
701
|
+
`);return}let t=process.cwd();ne(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=re();n.start(`Scanning project...`);let r=[...e.deploy?_i(t):[],...e.di?vi(t):[]];n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)w.message(`${C(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?O.red(`${a} critical`):`${a} critical`,o>0?O.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(D(O.red(`${l} — fix critical issues before deploying`)),process.exit(1)):D(O.green(`${l} — looking good!`))})}const bi=Symbol.for(`kickjs.handler.entryCapture`),xi=Symbol.for(`kickjs.config.describe`);function Si(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}const Ci=e=>e.split(/\r?\n/).map(e=>`# ${e}`);function wi(e,t=!1){let n=[];for(let r of e){let e=[r.description,r.list?`comma-separated list`:void 0,t&&r.required?`required when used`:void 0].filter(Boolean);e.length>0&&n.push(...Ci(e.join(` — `))),r.required&&!t?n.push(`${r.name}=`):n.push(`# ${r.name}=${r.default===void 0?``:Si(r.default)}`)}return n}function Ti(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
|
|
702
702
|
# sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
|
|
703
703
|
#
|
|
704
704
|
# Uncommented variables are required. Commented ones are optional; the value shown
|
|
705
|
-
# is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...
|
|
706
|
-
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (${n.optional?`optional, `:``}declared by ${n.declaredBy}) ──`,...n.description?
|
|
705
|
+
# is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...wi(e.env)].join(`
|
|
706
|
+
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (${n.optional?`optional, `:``}declared by ${n.declaredBy}) ──`,...n.description?Ci(n.description):[],...wi(n.vars,n.optional)].join(`
|
|
707
707
|
`));return`${t.join(`
|
|
708
708
|
|
|
709
|
-
`)}\n`}async function
|
|
709
|
+
`)}\n`}async function Ei(e,t){let n=z(e,t);if(!V(n))throw Error(`${t} not found`);let r=z(e,`vite.config.ts`);if(!V(r))throw Error(`vite.config.ts not found — kick env example loads the app through it`);let{createRequire:i}=await import(`node:module`),a=i(z(e,`package.json`)),{createServer:o}=await import(G(a.resolve(`vite`)).href),s=globalThis,c;s[bi]=e=>{c??=e},s[xi]=!0,s[je]=`kick-env`;let l=await o({configFile:r,root:e,logLevel:`error`,appType:`custom`,server:{middlewareMode:!0,hmr:!1,watch:null}});try{await l.ssrLoadModule(n)}finally{delete s[bi],delete s[xi],delete s[je],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Di(e){e.command(`env`).description(`Work with the environment the app reads`).command(`example`).description(`Write .env.example from the env schema and declared settings sections`).option(`-e, --entry <file>`,`App entry that calls bootstrap()`,`src/index.ts`).option(`-o, --out <file>`,`File to write`,`.env.example`).option(`--check`,`Exit 1 if the file is missing or out of date, instead of writing it`).action(async e=>{let t=process.cwd(),n=z(t,e.out),r;try{r=Ti(await Ei(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((V(n)?H(n,`utf8`):void 0)!==r&&(console.error(`\n ${e.out} is out of date — run \`kick env example\`.\n`),process.exit(1)),console.log(` ${e.out} is up to date.`)):(U(n,r),console.log(` Wrote ${e.out}`))})}function Oi(e){return e.optsWithGlobals().dryRun??!1}function ki(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.
|
|
710
710
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
711
711
|
--target define|class Override the migration direction.
|
|
712
712
|
--apply Apply the changes (default: dry-run preview).
|
|
713
|
-
--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
|
|
714
|
-
`+
|
|
713
|
+
--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=Oi(t)||!e.apply;S(n),e.experimental||(console.error(`
|
|
714
|
+
`+O.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
715
715
|
The regex-based rewrite handles the shapes our templates produce.
|
|
716
716
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
717
717
|
Always commit before running with --apply.
|
|
718
|
-
`),process.exit(1));let
|
|
718
|
+
`),process.exit(1));let r=await j(process.cwd()),i=k(r),a=z(e.modulesDir??i.dir??`src/modules`),o;e.target===`define`||e.target===`class`?o=e.target:e.target===void 0?o=i.style??`define`:(console.error(`\n ${O.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=O.dim(`→ ${o}`),c=n?O.dim(`(dry-run)`):O.bold(`(applying)`);console.log(`\n ${O.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${O.dim(a)}\n`);let l=e.backup!==!1&&!n,u=await nn(a,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${O.green(`✓`)} backup: ${O.dim(e)}\n ${O.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${O.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${O.green(`✓`)} ${e.path}`);else{f++;let t=O.dim(`(${e.reason??`skipped`})`);console.log(` ${O.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${O.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=O.dim(`(${u.indexReason??`skipped`})`);console.log(` ${O.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${O.dim(`-`)} ${u.indexPath} ${O.dim(`(not found)`)}`);let p=n?O.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${O.bold(String(d))} migrated, ${O.bold(String(f))} skipped${p}\n`)})}function Ai(e){try{let t=JSON.parse(H(z(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function ji(e,t=V,n=Ai(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=I(e);return(t(z(r,`pnpm-workspace.yaml`))||t(z(r,`package.json`)))&&t(z(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:n[`@forinda/kickjs-view`]?{staticDir:`dist/public`,siteRoot:`.`,apiPath:``}:{siteRoot:`.`,apiPath:``}}function Mi(e,t,n,r){let i=ji(t,n,r),a=e?.staticDir===!1?void 0:e?.staticDir??i.staticDir;return{entry:e?.entry??`src/serverless.ts`,outDir:e?.outDir??`dist/serverless`,staticDir:a,siteRoot:e?.siteRoot??i.siteRoot,publishDir:e?.publishDir??`dist/public`,apiPath:e?.apiPath??i.apiPath,external:e?.external??[`valibot`,`yup`],vercelRuntime:e?.vercelRuntime??`nodejs22.x`,include:e?.include??i.include??[]}}function Ni(e,t,n={projectDir:`.`}){let r=[` path: '${t}/*',`,...n.preferStatic?[` preferStatic: true,`]:[],...n.includedFiles?.length?[` includedFiles: ${JSON.stringify(n.includedFiles)},`]:[]];return`import { fileURLToPath } from 'node:url'
|
|
719
719
|
import { handler } from '${e}'
|
|
720
720
|
|
|
721
721
|
// Where the app's build files were packaged; the platform starts this
|
|
@@ -729,7 +729,7 @@ export const config = {
|
|
|
729
729
|
${r.join(`
|
|
730
730
|
`)}
|
|
731
731
|
}
|
|
732
|
-
`}function
|
|
732
|
+
`}function Pi(){return`import { fileURLToPath } from 'node:url'
|
|
733
733
|
import { handler } from './server.mjs'
|
|
734
734
|
|
|
735
735
|
// The app's build files are copied into this function at their project
|
|
@@ -739,11 +739,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
|
|
|
739
739
|
const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
|
|
740
740
|
|
|
741
741
|
export default (req, res) => handler.node(req, res, requestContext())
|
|
742
|
-
`}function
|
|
743
|
-
`).length,a=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(a);let n=e,o=n.expression;if(n.type===`Decorator`&&o?.type===`CallExpression`&&o.callee?.type===`Identifier`&&o.callee.name===`Cron`){let[e,a]=o.arguments??[],s=e?.type===`Literal`&&typeof e.value==`string`?e.value:e?.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value?.cooked:void 0;r.push({file:t,line:i(n.start??0),expression:s,timezone:a?.type===`ObjectExpression`&&a.properties.some(e=>(e.key?.name??e.key?.value)===`timezone`)})}for(let e in n)e!==`parent`&&a(n[e])};return a(n),r}function
|
|
742
|
+
`}function Fi(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Ii(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&e!==``&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function Li(e,t){let n;try{n=Pt(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
|
|
743
|
+
`).length,a=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(a);let n=e,o=n.expression;if(n.type===`Decorator`&&o?.type===`CallExpression`&&o.callee?.type===`Identifier`&&o.callee.name===`Cron`){let[e,a]=o.arguments??[],s=e?.type===`Literal`&&typeof e.value==`string`?e.value:e?.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value?.cooked:void 0;r.push({file:t,line:i(n.start??0),expression:s,timezone:a?.type===`ObjectExpression`&&a.properties.some(e=>(e.key?.name??e.key?.value)===`timezone`)})}for(let e in n)e!==`parent`&&a(n[e])};return a(n),r}function Ri(e){let t=z(e,`src`);return V(t)?bt(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=H(z(t,e),`utf-8`);return n.includes(`@Cron`)?Li(n,`src/${e}`):[]}):[]}function zi(e){let t=2166136261;for(let n of e.trim().replace(/\s+/g,` `))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(36)}function Bi(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=`${r.file}:${r.line}`;if(r.expression===void 0){t.push(`${e}: @Cron expression is not a string literal, so it has no Vercel cron entry`);continue}r.timezone&&t.push(`${e}: Vercel crons run in UTC — the timezone option is ignored there`);let i=r.expression.trim().replace(/\s+/g,` `);i.split(` `).length===5?n.set(zi(i),i):t.push(`${e}: Vercel crons need a five-field expression, so it has no Vercel cron entry`)}return{crons:[...n].map(([e,t])=>({path:`/_kick/cron/${e}`,schedule:t})),warnings:t}}function Vi(e){let t=e=>{if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let n=e;for(let e of[`import`,`module`,`node`,`default`]){let r=t(n[e]);if(r)return r}},n=e.exports;return t(typeof n==`string`||Array.isArray(n)?n:n?.[`.`]??n)??e.module??e.main}async function Hi(e,t){let{createRequire:n}=await import(`node:module`),r=n(z(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=z(e,`node_modules`,t,`package.json`)}if(!V(i))throw Error(`${t} is not installed in this project. Run: ${E(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=Vi(JSON.parse(H(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(G(z(I(i),a)).href)}function Ui(e,t){if(!t.staticDir)return{clientFiles:`bundle`};let n=z(e,t.outDir);return{publicDir:R(n,z(e,t.staticDir)).split(B).join(`/`)}}function Wi(e,t){let n=t?.resolve?.alias,r=Array.isArray(n)?n:Object.entries(n??{}).map(([e,t])=>({find:e,replacement:t}));return{define:t?.define??{},resolve:{alias:[...r,{find:`@`,replacement:z(e,`src`)}]}}}async function Gi(e,t){return(await t({command:`build`,mode:`production`,isSsrBuild:!0},void 0,e))?.config}async function Ki(e,t,n){let r=z(e,t.entry);if(!V(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i,loadConfigFromFile:a}=await Hi(e,`vite`),o=await Gi(e,(e,t,n)=>a(e,t,n,`silent`)),{default:s}=await Hi(e,`unplugin-swc`),{devtoolsFlagPlugin:c,devtoolsStripPlugin:l,kickViewsPlugin:u}=await Hi(e,`@forinda/kickjs-vite`),d=Ai(e)[`@forinda/kickjs-view`]?[u(Ui(e,t))]:[];await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[s.vite(),c(),l(),...d],...Wi(e,o),ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:z(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>Ji(n,r?I(r):e)||t.external.includes(n)&&Ji(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}}),d.length&&t.staticDir&&yt(z(e,t.staticDir),{recursive:!0});let f=z(e,t.outDir,`server.mjs`);return n(`bundled ${R(process.cwd(),f)}`),f}function qi(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function Ji(e,t,n=V){let r=qi(e);if(!r)return!1;for(let e=t;;e=I(e)){if(n(z(e,`node_modules`,r,`package.json`)))return!1;if(I(e)===e)return!0}}function Yi(e,t){let n=R(e,t).split(B)[0];return n!==void 0&&n.startsWith(`.`)}function Xi(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function Zi(e){try{return St(e)}catch{return}}function Qi(e,t){let n=t.filter(t=>!V(z(e,t)));if(n.length>0)throw Error(`${n.join(`, `)} not found — the function reads ${n.length===1?`it`:`them`} at runtime. Run the full build first (\`${ge(E(e),`build`)}\`), or fix \`deploy.include\`.`)}function $i(e,t){let n=t.projectRoot,r=()=>Mi(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();Qi(n,e.include);let i=await Ki(n,e,t.log),a=z(n,e.siteRoot),o=Ri(n);o.length>0&&t.log(`warning: ${o.length} @Cron job(s) found — Netlify has no cron trigger for them, so they will not run. Use Netlify scheduled functions, or deploy to Vercel or Workers.`);let s=z(a,`.netlify/v1/functions`);yt(s,{recursive:!0});let c=R(s,i).split(B).join(`/`),l=e=>e.split(B).join(`/`);U(z(s,`api.mjs`),Ni(c,e.apiPath,{projectDir:l(R(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(R(s,z(n,e)));return Zi(z(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${R(process.cwd(),z(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)yt(z(n,u),{recursive:!0}),t.log(`publish directory ready at ${R(process.cwd(),z(n,u))}`);else if(V(z(n,u))){let e=bt(z(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=z(n,u,`_redirects`),r=V(t)?H(t,`utf-8`):``,i=Xi(e).filter(e=>!r.includes(e));i.length>0&&U(t,`${r}${r&&!r.endsWith(`
|
|
744
744
|
`)?`
|
|
745
745
|
`:``}${i.join(`
|
|
746
|
-
`)}\n`)}}let d=
|
|
746
|
+
`)}\n`)}}let d=z(a,`netlify.toml`);if(V(d)){let e=Fi(H(d,`utf-8`)),r=R(a,z(n,u)).split(B).join(`/`);e!==void 0&&e!==r&&t.log(`warning: netlify.toml publishes "${e}", but this build fills "${r}". Update netlify.toml, or set \`deploy.publishDir\` / \`deploy.staticDir\` to match.`)}}),e.command(`build:vercel`).description(`Bundle the serverless entry and write .vercel/output (Build Output API v3)`).action(async()=>{let e=r();Qi(n,e.include);let i=await Ki(n,e,t.log),a=z(n,e.siteRoot),o=e.staticDir?z(n,e.staticDir):void 0,s=z(a,`.vercel/output`),c=z(s,`functions/api.func`);xt(s,{recursive:!0,force:!0}),yt(c,{recursive:!0}),vt(i,z(c,`server.mjs`)),U(z(c,`index.mjs`),Pi());for(let t of e.include)vt(z(n,t),z(c,t),{recursive:!0});if(U(z(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!V(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);vt(o,z(s,`static`),{recursive:!0,filter:e=>!Yi(o,e)})}let{crons:l,warnings:u}=Bi(Ri(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:Ii(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};U(z(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${R(process.cwd(),s)}`),l.length>0&&t.log(`${l.length} cron schedule(s) written. Set CRON_SECRET in the Vercel project — the trigger is not mounted without it.`)})}const ea=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=F.resolve(e.cwd,`kick.config.ts`);if(!V(t))return null;let n=await j(e.cwd);if(!n?.assetMap)return null;let r=Xe(n.assetMap,e.cwd);return r.count===0?null:ot(r)}}),ta="/* 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 na(e,t,n,r={}){if(e.length===0)return`${ta}
|
|
747
747
|
// (no routes discovered yet — annotate a controller method with
|
|
748
748
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
749
749
|
declare global {
|
|
@@ -760,19 +760,19 @@ declare global {
|
|
|
760
760
|
|
|
761
761
|
/** Empty until the first route exists — see kick typegen. */
|
|
762
762
|
export const kickRpc = {} as const
|
|
763
|
-
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=
|
|
763
|
+
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=oa(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'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${R(process.cwd(),i.filePath)} but not exported, so the generated types can't import it — ${o} is typed as ${t}. Export it (\`export const ${e.identifier} = ...\`) to type ctx.${o}.`:`${n}: ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??ia(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=aa(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${ra(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
764
764
|
`))}let u=[],d=/* @__PURE__ */ new Set,f=/* @__PURE__ */ new Set;i.has(`Named`)&&r.onWarn?.(`controller class 'Named' collides with the reserved KickRoutes.Named route-name map — its interface declaration-merges into it. Rename the controller.`),i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;d.has(t)?r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`):(d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`))}let p=[` interface Api {`,...u,` }`].join(`
|
|
765
765
|
`);l.push(p);let m=[];for(let[e,t]of i)for(let n of t)f.has(`${e}.${n.method}`)&&m.push(` '${e}.${n.method}': ${e}['${n.method}']`);l.push([` interface Named {`,...m,` }`].join(`
|
|
766
|
-
`));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=
|
|
766
|
+
`));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=la(e);if(g.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}g.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&h.push(` ${n}: {\n${i.join(`
|
|
767
767
|
`)}\n },`)}let _=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...h,`} as const`].join(`
|
|
768
|
-
`),v=[],y=/* @__PURE__ */ new Map;for(let t of e)y.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=y.get(e),i=
|
|
768
|
+
`),v=[],y=/* @__PURE__ */ new Map;for(let t of e)y.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=y.get(e),i=ca(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;v.push(`import type { ${a} } from '${i}'`)}let b=v.length>0?v.join(`
|
|
769
769
|
`)+`
|
|
770
|
-
`:``,x=
|
|
771
|
-
`);return`${
|
|
770
|
+
`:``,x=sa(a)+b,S=l.join(`
|
|
771
|
+
`);return`${ta}${x}
|
|
772
772
|
declare global {
|
|
773
773
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
774
774
|
namespace KickRoutes {
|
|
775
|
-
${
|
|
775
|
+
${S}
|
|
776
776
|
}
|
|
777
777
|
|
|
778
778
|
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
@@ -780,18 +780,18 @@ ${ee}
|
|
|
780
780
|
}
|
|
781
781
|
|
|
782
782
|
${_}
|
|
783
|
-
`}function
|
|
783
|
+
`}function ra(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function ia(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; cursor?: string }`}function aa(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 oa(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=ca(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 sa(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(`
|
|
784
784
|
`)+`
|
|
785
|
-
`}function
|
|
786
|
-
TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${
|
|
785
|
+
`}function ca(e,t,n){if(e===null)return`unknown`;let r=I(n);if(e===``){let e=R(r,t).split(B).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=I(t),a=z(i,e),o=R(r,a).split(B).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function la(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const ua=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:da(e),cwd:e.cwd,envFile:fa(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=F.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return na(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function da(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function fa(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const pa=`@typescript/typescript6`;function ma(e){return typeof e?.createProgram==`function`}function ha(e){if(ma(e.typescript))return{api:e.typescript,source:`typescript`};if(ma(e.ts6))return{api:e.ts6,source:pa};let t=`Install it in the project:\n ${E()} add -D ${pa}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
786
|
+
TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${pa}' resolved from this project.\n ${t}`)}async function ga(e){let t=gt(L(e,`package.json`)),n=async e=>{try{return await import(G(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(pa)]);return ha({typescript:_a(r),ts6:_a(i)}).api}function _a(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const va=Symbol(`kick/client: expansion budget exhausted`);var ya=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=/* @__PURE__ */ new Map;inProgress=/* @__PURE__ */ new Map;jsonInProgress=/* @__PURE__ */ new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;let t=this.blocks.length,n=this.nextName,r=new Set(this.hoistedByType.keys());try{return this.render(e,0)}catch(e){if(e!==va)throw e;this.blocks.length=t,this.nextName=n;for(let e of this.hoistedByType.keys())r.has(e)||this.hoistedByType.delete(e);return this.opts.onWarn?.(`expansion abandoned after ${this.budget} depth hoists — emitting 'unknown'. Either the response type never repeats (a generic that grows at every level) or it nests more distinct types than the budget allows; raising maxDepth hoists fewer of them. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t,n=!0){let r=this.ts.TypeFlags;if(n){let t=this.hoistedByType.get(e);if(t)return t}if(t>this.maxDepth&&!this.isLeaf(e))return this.hoistDeep(e);if(e.flags&(r.String|r.Number|r.Boolean|r.BigInt|r.ESSymbol)||e.flags&(r.Any|r.Unknown|r.Never|r.Void|r.Undefined|r.Null)||e.isLiteral()||e.flags&r.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let i=this.arrayElement(e);if(i){let e=this.render(i.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return i.readonly?`readonly ${n}`:n}let a=this.toJsonType(e);if(a){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(a,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&r.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}isLeaf(e){let t=this.ts.TypeFlags;return(e.flags&(t.String|t.Number|t.Boolean|t.BigInt|t.ESSymbol|t.Any|t.Unknown|t.Never|t.Void|t.Undefined|t.Null|t.BooleanLiteral))!==0||e.isLiteral()}hoistDeep(e){if(++this.truncations>this.budget)throw va;let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=this.isPlainObject(e)?`interface ${t} {\n${this.members(e,0,` `)}\n}`:`type ${t} = ${this.render(e,0,!1)}`,t}isPlainObject(e){return(e.flags&this.ts.TypeFlags.Object)!==0&&!e.isUnionOrIntersection()&&!this.isTuple(e)&&!this.arrayElement(e)&&!this.toJsonType(e)&&!this.isLibType(e)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
|
|
787
787
|
`){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType,void 0,this.printFlags);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=this.typeOfProperty(r);if(this.isCallable(e)||r.getName().startsWith(`__@`))continue;let a=(r.flags&this.ts.SymbolFlags.Optional)!==0,o=this.renderPropertyType(e,a,r,t+1),s=this.isReadonlyProp(r)?`readonly `:``;i.push(`${n}${s}${this.propName(r.getName())}${a?`?`:``}: ${o}`)}return i.join(r===`
|
|
788
788
|
`?`
|
|
789
|
-
`:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const
|
|
790
|
-
`));for(let n of
|
|
791
|
-
`);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function
|
|
789
|
+
`:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const ba=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],xa=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Sa(e){return Mt(`sha1`).update(e).digest(`hex`)}function Ca(e){let t=Mt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
|
|
790
|
+
`));for(let n of ba){let r=L(e.projectDir,n);if(V(r))try{t.update(H(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!xa.test(n)){t.update(n);try{t.update(H(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function wa(e){try{let t=await ga(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(L(e.projectDir,`tsconfig.json`),{},n);return r?Ca({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function Ta(e){let t=await ga(e.compilerFrom??e.projectDir),n=L(I(e.routesFile),`__kick_client_probe__.ts`),r=Oa(e.routesFile,e.keys),i=ja(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);Ea(t,i,e.routesFile);let s=ka(t,i,o,e.keys),c=null,l=new ya(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=/* @__PURE__ */ new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===Da(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);d.flags&t.TypeFlags.Any?e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`):(c=r,u.set(r,l.expand(d)),c=null)}return{entries:u,hoisted:l.hoisted()}}function Ea(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
|
|
791
|
+
`);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function Da(e){return`_K${e}`}function Oa(e,t){let n=`./`+_t(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Da(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
792
792
|
`)+`
|
|
793
|
-
`}function
|
|
794
|
-
`))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...
|
|
793
|
+
`}function ka(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(Da(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Aa(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=bt(t).filter(e=>e.endsWith(`.ts`)).map(e=>L(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function ja(e,t,n,r){let i=L(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
794
|
+
`))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...Aa(o.fileNames,I(n)),n],options:o.options,host:s})}const Ma=`/* eslint-disable */
|
|
795
795
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
796
796
|
//
|
|
797
797
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -805,7 +805,7 @@ ${_}
|
|
|
805
805
|
//
|
|
806
806
|
// Written when \`kick dev\` starts, not on save — resolving these types builds a
|
|
807
807
|
// full TypeScript program over the server. Re-run \`kick typegen\`.
|
|
808
|
-
`;function
|
|
808
|
+
`;function Na(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Ma}
|
|
809
809
|
// (no routes discovered yet — annotate a controller method with
|
|
810
810
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
811
811
|
interface Api {}
|
|
@@ -822,7 +822,7 @@ export type { Api }
|
|
|
822
822
|
|
|
823
823
|
`)+`
|
|
824
824
|
|
|
825
|
-
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${
|
|
825
|
+
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Ma}
|
|
826
826
|
${r}interface Api {
|
|
827
827
|
${i.join(`
|
|
828
828
|
`)}
|
|
@@ -836,7 +836,7 @@ declare global {
|
|
|
836
836
|
}
|
|
837
837
|
|
|
838
838
|
export type { Api }
|
|
839
|
-
`}const
|
|
839
|
+
`}const Pa=`kick/client`,$=`.kickjs/types/kick__client.d.ts`,Fa=`.kickjs/cache/client-map.sha1`,Ia=(()=>{try{return gt(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function La(e){try{if(!V(e))return null;let[t,n]=H(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Ra(e){return`${Sn}${Pa} */\n\n${e}\n`}function za(e){try{return V(e)?H(e,`utf-8`):null}catch{return null}}async function Ba(e){let t=F.resolve(e.cwd,$);if(!V(t))return!1;try{await Et(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${$} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${$} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function Va(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function Ha(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(V(F.resolve(e.cwd,$))&&e.log.warn(` kick/client: ${$} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const Ua=()=>({id:Pa,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!Ha(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=/* @__PURE__ */ new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=Va(e.config),a=await wa({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Ia}),o=La(F.resolve(e.cwd,Fa)),s=za(F.resolve(e.cwd,$));if(a&&o&&s!==null&&o.inputs===a&&o.output===Sa(s))return Me()&&e.log.info?.(` kick/client: unchanged, keeping ${$}`),null;try{let t=Na(await Ta({projectDir:e.cwd,routesFile:F.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(Fa,`${a} ${Sa(Ra(t))}`),t}catch(t){let n=V(F.resolve(e.cwd,$)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):Me()&&e.log.info?.(r),n&&await Ba(e),null}}});function Wa(e,t,n=`zod`){if(!e)return null;let r=I(t),i=R(r,e.filePath).split(B).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
|
|
840
840
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
841
841
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
842
842
|
|
|
@@ -874,6 +874,6 @@ declare global {
|
|
|
874
874
|
}
|
|
875
875
|
|
|
876
876
|
export {}
|
|
877
|
-
`}const
|
|
878
|
-
`)}}]})];export{
|
|
879
|
-
//# sourceMappingURL=run-plugins-
|
|
877
|
+
`}const Ga=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=qa(e);if(t===!1)return null;let n=await e.getScanResult({root:Ka(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=F.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Wa(n.env,i,r)}});function Ka(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function qa(e){return e.config?.typegen?.envFile}function Ja(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ya(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Xa(e){return{root:Ja(e),cwd:e.cwd,envFile:Ya(e)}}const Za=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e)),n=F.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return et(t.classes,n,r)}}),Qa=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e)),n=new Set(t.collisions.map(e=>e.className)),r=it(t.classes,t.tokens,t.injects,n);return at(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),$a=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e));return at(`ModuleToken`,Qe(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),eo=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e));return $e(t.pluginsAndAdapters)}}),to=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e));return t.contextKeys.length===0?null:dt(t.contextKeys)}}),no=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(Xa(e));return st(t.routeFlags)}}),ro={express:{subpath:`@forinda/kickjs/express`,typeName:`ExpressRuntimeTypes`},fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},io=[t({name:`kick/init`,register:zt}),t({name:`kick/generate`,register:bn}),t({name:`kick/run`,register:zn}),t({name:`kick/info`,register:Wn}),t({name:`kick/inspect`,register:er}),t({name:`kick/add`,register:_}),t({name:`kick/runtime-swap`,register:_r}),t({name:`kick/list`,register:o}),t({name:`kick/explain`,register:Ar}),t({name:`kick/mcp`,register:Vr}),t({name:`kick/tinker`,register:Gr}),t({name:`kick/remove`,register:Zr}),t({name:`kick/typegen`,register:ei}),t({name:`kick/check`,register:yi}),t({name:`kick/doctor`,register:Ve}),t({name:`kick/env-command`,register:Di}),t({name:`kick/codemod`,register:ki}),t({name:`kick/deploy`,register:$i}),t({name:`kick/registry`,typegens:[Za()]}),t({name:`kick/services`,typegens:[Qa()]}),t({name:`kick/modules`,typegens:[$a()]}),t({name:`kick/plugins`,typegens:[eo()]}),t({name:`kick/context`,typegens:[to()]}),t({name:`kick/route-flags`,typegens:[no()]}),t({name:`kick/assets`,typegens:[ea()]}),t({name:`kick/routes`,typegens:[ua()]}),t({name:`kick/client`,typegens:[Ua()]}),t({name:`kick/env`,typegens:[Ga()]}),t({name:`kick/runtime`,typegens:[{id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime??`express`;if(t!==`express`&&t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=ro[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
|
|
878
|
+
`)}}]})];export{Tn as applyDisableFilter,En as n,Bt as r,Dn as runAllPluginTypegens,io as t};
|
|
879
|
+
//# sourceMappingURL=run-plugins-BONtomzM.mjs.map
|