@forinda/kickjs-cli 8.6.0 → 8.7.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-BFOgLbXq.mjs → agent-docs-BWnHJdm8.mjs} +5 -5
- package/dist/agent-docs-BWnHJdm8.mjs.map +1 -0
- package/dist/{agent-docs-BU1rORKA.mjs → agent-docs-BpcruhI0.mjs} +4 -4
- package/dist/{build-DlfIkjcw.mjs → build-CkO4WI5N.mjs} +2 -2
- package/dist/{build-CdIpRyfy.mjs → build-CmmbAJ-6.mjs} +3 -3
- package/dist/{build-CdIpRyfy.mjs.map → build-CmmbAJ-6.mjs.map} +1 -1
- package/dist/{builtins-CfAXBoIM.mjs → builtins-C_zzIKuU.mjs} +2 -2
- package/dist/{builtins-CmuUgcIq.mjs → builtins-CrQekXun.mjs} +150 -144
- package/dist/cli.mjs +2 -2
- package/dist/{config-ndsVdO8u.mjs → config-CKtUkFnR.mjs} +3 -3
- package/dist/config-CKtUkFnR.mjs.map +1 -0
- package/dist/{config-SvlcF3Ls.mjs → config-Po20hhzt.mjs} +2 -2
- package/dist/{doctor-D3RMXkxE.mjs → doctor-DOuVk9cj.mjs} +74 -70
- package/dist/doctor-DOuVk9cj.mjs.map +1 -0
- package/dist/{fs-DdNMcW_P.mjs → fs-BdI6OJqD.mjs} +2 -2
- package/dist/{fs-DdNMcW_P.mjs.map → fs-BdI6OJqD.mjs.map} +1 -1
- package/dist/{fs-v57MCgpH.mjs → fs-Cj6xpMO3.mjs} +1 -1
- package/dist/{fullstack-DOufUeMv.mjs → fullstack-CYWi1UG7.mjs} +3 -3
- package/dist/{fullstack-LJwhodT-.mjs → fullstack-CjwAefj4.mjs} +4 -4
- package/dist/{fullstack-LJwhodT-.mjs.map → fullstack-CjwAefj4.mjs.map} +1 -1
- package/dist/index.d.mts +2 -21
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-Dighdqh-.mjs → plugin-BWaA0gd6.mjs} +2 -2
- package/dist/{plugin-Dn67elEZ.mjs → plugin-rEXrK-TD.mjs} +2 -2
- package/dist/{project-Cb_NLUWI.mjs → project-16gsHLs5.mjs} +10 -9
- package/dist/project-16gsHLs5.mjs.map +1 -0
- package/dist/{project-AXCA1hD9.mjs → project-Coim2UNJ.mjs} +9 -8
- package/dist/{project-root-Dgvy5kYG.mjs → project-root-Bab7F0mt.mjs} +2 -2
- package/dist/{project-root-C7TrLJlZ.mjs → project-root-DebxcXwp.mjs} +3 -3
- package/dist/{project-root-C7TrLJlZ.mjs.map → project-root-DebxcXwp.mjs.map} +1 -1
- package/dist/{prompts-CSATvwXw.mjs → prompts-XSHQCmzs.mjs} +2 -2
- package/dist/{prompts-CSATvwXw.mjs.map → prompts-XSHQCmzs.mjs.map} +1 -1
- package/dist/{rolldown-runtime-BhxEEqxa.mjs → rolldown-runtime-DyiVSlN6.mjs} +1 -1
- package/dist/{run-plugins-Cf_6BgGZ.mjs → run-plugins-CEomWccT.mjs} +79 -77
- package/dist/run-plugins-CEomWccT.mjs.map +1 -0
- package/dist/typegen-CEcjoYli.mjs +106 -0
- package/dist/typegen-Cs40J3ar.mjs +107 -0
- package/dist/typegen-Cs40J3ar.mjs.map +1 -0
- package/dist/{types-lHwt_SNI.mjs → types-BtMrQ7AM.mjs} +1 -1
- package/package.json +4 -4
- package/templates/base/files/src/modules/index.ts +2 -3
- package/templates/base/files/tsconfig.json +0 -1
- package/dist/agent-docs-BFOgLbXq.mjs.map +0 -1
- package/dist/config-ndsVdO8u.mjs.map +0 -1
- package/dist/doctor-D3RMXkxE.mjs.map +0 -1
- package/dist/project-Cb_NLUWI.mjs.map +0 -1
- package/dist/run-plugins-Cf_6BgGZ.mjs.map +0 -1
- package/dist/typegen-97E_RYNp.mjs +0 -131
- package/dist/typegen-CYhFNfIu.mjs +0 -132
- package/dist/typegen-CYhFNfIu.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v8.
|
|
2
|
+
* @forinda/kickjs-cli v8.7.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-BhxEEqxa.mjs";import{c as t,i as n,l as r,o as i,p as a,r as o,s,t as c}from"./project-AXCA1hD9.mjs";import{a as l,c as u,i as d,l as f,o as p,r as m,s as h}from"./config-SvlcF3Ls.mjs";import{n as g,r as _}from"./plugin-Dn67elEZ.mjs";import{n as v,r as y,t as b}from"./fs-v57MCgpH.mjs";import{a as x,c as S,d as ee,f as C,i as te,l as ne,n as re,o as ie,p as ae,r as w,s as T,u as oe}from"./agent-docs-BU1rORKA.mjs";import{t as E}from"./project-root-Dgvy5kYG.mjs";import{C as se,S as D,T as ce,_ as le,a as ue,b as de,c as fe,d as pe,f as me,g as he,h as ge,i as _e,l as ve,m as ye,o as be,p as xe,r as Se,s as Ce,t as we,u as Te,v as Ee,w as De,x as Oe,y as ke}from"./typegen-97E_RYNp.mjs";import{t as Ae}from"./build-DlfIkjcw.mjs";import{createRequire as je}from"node:module";import{cpSync as Me,existsSync as O,mkdirSync as Ne,readFileSync as k,readdirSync as Pe,rmSync as Fe,statSync as Ie,writeFileSync as Le}from"node:fs";import A,{basename as Re,dirname as j,join as M,relative as N,resolve as P,sep as ze}from"node:path";import{fileURLToPath as Be,pathToFileURL as F}from"node:url";import{fork as Ve,spawn as He,spawnSync as Ue}from"node:child_process";import{copyFile as We,mkdir as Ge,readFile as I,readdir as Ke,rm as qe,stat as Je,writeFile as L}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{parseSync as Ye}from"oxc-parser";import Xe from"pluralize";import{arch as Ze,platform as Qe,release as $e}from"node:os";import{createHash as et}from"node:crypto";const tt=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function nt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--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(`-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)=>{te(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await oe({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=P(`.`),e=Re(i)):i=P(t.directory||e),O(i)){let r=Pe(i);if(r.length>0){if(t.force)x.warn(`Clearing existing files in ${i}`);else if(n){x.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),T(`Aborted.`);return}else{x.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)x.message(` - ${e}`);if(r.length>5&&x.message(` ... and ${r.length-5} more`),!await w({message:C.red(`Remove all existing files and proceed?`),initialValue:!1})){T(`Aborted.`);return}}for(let e of r)Fe(P(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await S({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let o=t.runtime;o||=n?`express`:await S({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 s=t.pm;s||=n?await r(void 0):await S({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=n?`inmemory`:await oe({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),f(l);let u=t.schema;u||=n?`zod`:await S({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(u)||(x.warn(`Unknown --schema "${u}", falling back to zod.`),u=`zod`);let d;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();d=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else d=n?[]:await ie({message:`Select packages to include`,options:[...tt],required:!1});let p;p=t.git===void 0?n?!0:await w({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?n?!0:await w({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){x.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),T(`Aborted.`);return}let{VITE_TEMPLATES:h,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-DOufUeMv.mjs`);if(t.viteTemplate!==void 0&&!h.some(e=>e.value===t.viteTemplate)){x.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${h.map(e=>e.value).join(`, `)}.`),T(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(a===`fullstack`&&!t.frontend&&!n&&(_=await S({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)`}]})),_===`vite`&&!t.viteTemplate&&!n&&(v=await S({message:`create-vite template`,options:h.map(e=>({value:e.value,label:e.label})),initialValue:g})),a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DOufUeMv.mjs`);await t({name:e,directory:i,packageManager:s,initGit:p,installDeps:m,schemaLib:u,runtime:o,packages:d,frontend:_,viteTemplate:v}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${s}${s===`pnpm`?` dev`:` run dev:server`}`)}`);return}await c({name:e,directory:i,packageManager:s,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:d,schemaLib:u,runtime:o}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${s} dev`)}`)})}function R(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function z(e){let t=R(e);return t.charAt(0).toLowerCase()+t.slice(1)}function B(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function V(e){return Xe.plural(e)}function rt(e){return Xe.plural(e)}function it(e){return B(e).replace(/-/g,`_`)}function at(e){let t=e.cwd??process.cwd(),n=e.projectRoot??E(t),r=e.pluralize??!0,i=R(e.name),a=z(e.name),o=B(e.name),s=it(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=V(o);c.pluralKebab=e,c.pluralPascal=R(e),c.pluralCamel=z(e)}return c}function ot(e,t){return P(e.cwd,t)}async function st(e){return import(F(e).href)}const ct=new Map;async function lt(e){let t=ct.get(e);if(t)return t;let n=ut(e);return ct.set(e,n),n}async function ut(e){let t=P(e,`package.json`);if(!O(t))return{generators:[],loaded:[],failed:[]};let n=dt(JSON.parse(await I(t,`utf-8`))),r=je(P(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await I(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=P(j(t),s);if(!O(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await st(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!ft(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function dt(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function pt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return gt(r.spec,r.source,e,n);let i=ht(await lt(n),e.generatorName);return i?gt(i.spec,i.source,e,n):null}async function mt(e,t=[]){let n=await lt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function ht(e,t){return e.generators.find(e=>e.spec.name===t)}async function gt(e,t,n,r){let i=at({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=ot(i,e.path);await y(t,e.content),o.push(t)}return{files:o,source:t}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const _t={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function vt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yt(e){return _t[e]??vt(e)}function bt(e){return`create${e}Repository`}function xt(e){return e??`define`}function St(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=bt(t),s=xt(a),c=`/**
|
|
11
|
+
import{t as e}from"./rolldown-runtime-DyiVSlN6.mjs";import{c as t,i as n,l as r,o as i,p as a,r as o,s,t as c}from"./project-Coim2UNJ.mjs";import{a as l,c as u,i as d,l as f,o as p,r as m,s as h}from"./config-Po20hhzt.mjs";import{n as g,r as _}from"./plugin-rEXrK-TD.mjs";import{n as v,r as y,t as b}from"./fs-Cj6xpMO3.mjs";import{a as x,c as S,d as ee,f as C,i as te,l as ne,n as re,o as ie,p as ae,r as w,s as T,u as oe}from"./agent-docs-BpcruhI0.mjs";import{t as E}from"./project-root-Bab7F0mt.mjs";import{C as se,S as ce,_ as le,a as ue,b as de,c as fe,d as pe,f as me,g as he,h as ge,i as _e,l as ve,m as ye,o as be,p as xe,r as Se,s as Ce,t as we,u as Te,v as Ee,w as De,x as D,y as Oe}from"./typegen-CEcjoYli.mjs";import{t as ke}from"./build-CkO4WI5N.mjs";import{createRequire as Ae}from"node:module";import{cpSync as je,existsSync as O,mkdirSync as Me,readFileSync as k,readdirSync as A,rmSync as Ne,statSync as Pe,writeFileSync as Fe}from"node:fs";import j,{basename as Ie,dirname as M,join as N,relative as P,resolve as F,sep as Le}from"node:path";import{fileURLToPath as Re,pathToFileURL as I}from"node:url";import{fork as ze,spawn as Be,spawnSync as Ve}from"node:child_process";import{copyFile as He,mkdir as Ue,readFile as L,readdir as We,rm as Ge,stat as Ke,writeFile as R}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{parseSync as qe}from"oxc-parser";import Je from"pluralize";import{arch as Ye,platform as Xe,release as Ze}from"node:os";import{createHash as Qe}from"node:crypto";const $e=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function et(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--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(`-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)=>{te(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await oe({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=F(`.`),e=Ie(i)):i=F(t.directory||e),O(i)){let r=A(i);if(r.length>0){if(t.force)x.warn(`Clearing existing files in ${i}`);else if(n){x.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),T(`Aborted.`);return}else{x.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)x.message(` - ${e}`);if(r.length>5&&x.message(` ... and ${r.length-5} more`),!await w({message:C.red(`Remove all existing files and proceed?`),initialValue:!1})){T(`Aborted.`);return}}for(let e of r)Ne(F(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await S({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let o=t.runtime;o||=n?`express`:await S({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 s=t.pm;s||=n?await r(void 0):await S({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=n?`inmemory`:await oe({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),f(l);let u=t.schema;u||=n?`zod`:await S({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(u)||(x.warn(`Unknown --schema "${u}", falling back to zod.`),u=`zod`);let d;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();d=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else d=n?[]:await ie({message:`Select packages to include`,options:[...$e],required:!1});let p;p=t.git===void 0?n?!0:await w({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?n?!0:await w({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){x.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),T(`Aborted.`);return}let{VITE_TEMPLATES:h,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-CYWi1UG7.mjs`);if(t.viteTemplate!==void 0&&!h.some(e=>e.value===t.viteTemplate)){x.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${h.map(e=>e.value).join(`, `)}.`),T(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(a===`fullstack`&&!t.frontend&&!n&&(_=await S({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)`}]})),_===`vite`&&!t.viteTemplate&&!n&&(v=await S({message:`create-vite template`,options:h.map(e=>({value:e.value,label:e.label})),initialValue:g})),a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-CYWi1UG7.mjs`);await t({name:e,directory:i,packageManager:s,initGit:p,installDeps:m,schemaLib:u,runtime:o,packages:d,frontend:_,viteTemplate:v}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${s}${s===`pnpm`?` dev`:` run dev:server`}`)}`);return}await c({name:e,directory:i,packageManager:s,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:d,schemaLib:u,runtime:o}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${s} dev`)}`)})}function z(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function B(e){let t=z(e);return t.charAt(0).toLowerCase()+t.slice(1)}function V(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function H(e){return Je.plural(e)}function tt(e){return Je.plural(e)}function nt(e){return V(e).replace(/-/g,`_`)}function rt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??E(t),r=e.pluralize??!0,i=z(e.name),a=B(e.name),o=V(e.name),s=nt(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=H(o);c.pluralKebab=e,c.pluralPascal=z(e),c.pluralCamel=B(e)}return c}function it(e,t){return F(e.cwd,t)}async function at(e){return import(I(e).href)}const ot=new Map;async function st(e){let t=ot.get(e);if(t)return t;let n=ct(e);return ot.set(e,n),n}async function ct(e){let t=F(e,`package.json`);if(!O(t))return{generators:[],loaded:[],failed:[]};let n=lt(JSON.parse(await L(t,`utf-8`))),r=Ae(F(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await L(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=F(M(t),s);if(!O(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await at(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!ut(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function lt(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function ut(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function dt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return mt(r.spec,r.source,e,n);let i=pt(await st(n),e.generatorName);return i?mt(i.spec,i.source,e,n):null}async function ft(e,t=[]){let n=await st(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function pt(e,t){return e.generators.find(e=>e.spec.name===t)}async function mt(e,t,n,r){let i=rt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=it(i,e.path);await y(t,e.content),o.push(t)}return{files:o,source:t}}function U(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const ht={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function gt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function _t(e){return ht[e]??gt(e)}function vt(e){return`create${e}Repository`}function yt(e){return e??`define`}function bt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=vt(t),s=yt(a),c=`/**
|
|
12
12
|
* ${t} Module
|
|
13
13
|
*
|
|
14
14
|
* REST module with a flat folder structure.
|
|
@@ -21,7 +21,7 @@ import{t as e}from"./rolldown-runtime-BhxEEqxa.mjs";import{c as t,i as n,l as r,
|
|
|
21
21
|
* dtos/ — Request/response schemas
|
|
22
22
|
*
|
|
23
23
|
* The repository is backed by an in-memory Map so this module works as
|
|
24
|
-
* generated. Swap in ${
|
|
24
|
+
* generated. Swap in ${i===`inmemory`?`a database`:_t(i)} by replacing the factory body in
|
|
25
25
|
* ${n}.repository.ts — the contract is whatever that factory returns, so
|
|
26
26
|
* nothing else has to change.
|
|
27
27
|
*/`,l=`import { ${t.toUpperCase()}_REPOSITORY, ${o} } from './${n}.repository'
|
|
@@ -86,7 +86,7 @@ ${u}
|
|
|
86
86
|
},
|
|
87
87
|
}),
|
|
88
88
|
})
|
|
89
|
-
`}function
|
|
89
|
+
`}function xt(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=yt(i),o=` /**
|
|
90
90
|
* Declare HTTP routes. Return value shape:
|
|
91
91
|
*
|
|
92
92
|
* - \`path\` — URL prefix for this route set.
|
|
@@ -126,7 +126,7 @@ ${o}
|
|
|
126
126
|
},
|
|
127
127
|
}),
|
|
128
128
|
})
|
|
129
|
-
`}function
|
|
129
|
+
`}function St(e){let{pascal:t,kebab:n}=e,r=e.swagger?`import { ApiTags } from '@forinda/kickjs-swagger'
|
|
130
130
|
`:``,i=e.swagger?` @ApiTags('${e.pascal}')\n`:``,a=t.charAt(0).toLowerCase()+t.slice(1);return`import {
|
|
131
131
|
Controller,
|
|
132
132
|
Get,
|
|
@@ -198,10 +198,10 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
|
198
198
|
return reply.noContent()
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
|
-
`}const
|
|
201
|
+
`}const Ct={zod:{import:`import { z } from 'zod'`,required:`z.string().min(1, 'Name is required').max(200)`,optional:`z.string().min(1).max(200).optional()`,infer:e=>`z.infer<typeof ${e}>`,hint:[` * z.string(), z.number(), z.boolean(), z.enum([...]),`,` * z.array(), z.object(), .optional(), .default(), .transform()`].join(`
|
|
202
202
|
`)},valibot:{import:`import * as v from 'valibot'`,required:`v.pipe(v.string(), v.minLength(1, 'Name is required'), v.maxLength(200))`,optional:`v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200)))`,infer:e=>`v.InferOutput<typeof ${e}>`,hint:[` * v.string(), v.number(), v.boolean(), v.picklist([...]),`,` * v.array(), v.object(), v.optional(), and v.pipe(...) to chain checks`].join(`
|
|
203
203
|
`)},yup:{import:`import * as yup from 'yup'`,required:`yup.string().required('Name is required').min(1).max(200)`,optional:`yup.string().min(1).max(200).optional()`,infer:e=>`yup.InferType<typeof ${e}>`,hint:[` * yup.string(), yup.number(), yup.boolean(), .oneOf([...]),`,` * yup.array(), yup.object(), .required(), .optional(), .default()`].join(`
|
|
204
|
-
`)}};function
|
|
204
|
+
`)}};function wt(e,t){return`${e===`zod`?`z.object`:e===`valibot`?`v.object`:`yup.object`}({\n ${t},\n})`}function Tt(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=Ct[n],i=`create${t}Schema`,a=n===`zod`?`Zod`:n===`valibot`?`Valibot`:`Yup`;return`${r.import}
|
|
205
205
|
|
|
206
206
|
/**
|
|
207
207
|
* Create ${t} DTO — ${a} schema for validating POST request bodies.
|
|
@@ -211,21 +211,21 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
|
211
211
|
* Add more fields as needed. Supported ${a} types:
|
|
212
212
|
${r.hint}
|
|
213
213
|
*/
|
|
214
|
-
export const ${i} = ${
|
|
214
|
+
export const ${i} = ${wt(n,`name: ${r.required}`)}
|
|
215
215
|
|
|
216
216
|
export type Create${t}DTO = ${r.infer(i)}
|
|
217
|
-
`}function
|
|
217
|
+
`}function Et(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=Ct[n],i=`update${t}Schema`;return`${r.import}
|
|
218
218
|
|
|
219
|
-
export const ${i} = ${
|
|
219
|
+
export const ${i} = ${wt(n,`name: ${r.optional}`)}
|
|
220
220
|
|
|
221
221
|
export type Update${t}DTO = ${r.infer(i)}
|
|
222
|
-
`}function
|
|
222
|
+
`}function Dt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
223
223
|
id: string
|
|
224
224
|
name: string
|
|
225
225
|
createdAt: string
|
|
226
226
|
updatedAt: string
|
|
227
227
|
}
|
|
228
|
-
`}function
|
|
228
|
+
`}function Ot(e){let{pascal:t,kebab:n,repoType:r,dtoPrefix:i=`./dtos`,tokenScope:a=`app`}=e,o=r&&r!==`inmemory`?r:``,s=`create${t}Repository`,c=` const store = new Map<string, ${t}ResponseDTO>()
|
|
229
229
|
|
|
230
230
|
return {
|
|
231
231
|
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
@@ -300,7 +300,7 @@ export type ${t}Repository = ReturnType<typeof ${s}>
|
|
|
300
300
|
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
301
301
|
*/
|
|
302
302
|
export const ${t.toUpperCase()}_REPOSITORY = createToken<${t}Repository>('${a}/${t}/repository')
|
|
303
|
-
`}function
|
|
303
|
+
`}function kt(e){let{pascal:t,kebab:n,plural:r=``,style:i=`define`,testHarness:a=!1}=e,o=i===`define`?`${t}Module()`:`${t}Module`;return`${a?`import { describe, it, expect, beforeEach } from 'vitest'
|
|
304
304
|
import request from 'supertest'
|
|
305
305
|
import { Container } from '@forinda/kickjs'
|
|
306
306
|
import { createTestApp } from '@forinda/kickjs-testing'
|
|
@@ -394,7 +394,7 @@ ${a?` /**
|
|
|
394
394
|
it.todo('deletes a ${n}')
|
|
395
395
|
})
|
|
396
396
|
})
|
|
397
|
-
`}function
|
|
397
|
+
`}function At(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../${n}.repository`}=e,a=`create${t}Repository`;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
398
398
|
import { ${a}, type ${t}Repository } from '${i}'
|
|
399
399
|
|
|
400
400
|
describe('${t} repository', () => {
|
|
@@ -456,7 +456,7 @@ describe('${t} repository', () => {
|
|
|
456
456
|
expect(found).toBeNull()
|
|
457
457
|
})
|
|
458
458
|
})
|
|
459
|
-
`}function
|
|
459
|
+
`}function jt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
460
460
|
import type { ParsedQuery } from '@forinda/kickjs'
|
|
461
461
|
import { ${t.toUpperCase()}_REPOSITORY, type ${t}Repository } from './${n}.repository'
|
|
462
462
|
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
@@ -493,14 +493,14 @@ export class ${t}Service {
|
|
|
493
493
|
await this.repo.delete(id)
|
|
494
494
|
}
|
|
495
495
|
}
|
|
496
|
-
`}function
|
|
496
|
+
`}function Mt(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
497
497
|
|
|
498
498
|
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
499
499
|
filterable: ['name'],
|
|
500
500
|
sortable: ['name', 'createdAt'],
|
|
501
501
|
searchable: ['name'],
|
|
502
502
|
}
|
|
503
|
-
`}async function
|
|
503
|
+
`}async function Nt(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,xt({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
504
504
|
|
|
505
505
|
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
506
506
|
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
@@ -540,7 +540,7 @@ export class ${t}Controller {
|
|
|
540
540
|
return reply.noContent()
|
|
541
541
|
}
|
|
542
542
|
}
|
|
543
|
-
`)}async function
|
|
543
|
+
`)}async function Pt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,testHarness:l,write:u}=e,d=e.swagger??!1,f=e.schemaLib??`zod`;await u(`${n}.module.ts`,bt({pascal:t,kebab:n,plural:r,repo:a,style:c})),await u(`${n}.constants.ts`,Mt({pascal:t,kebab:n})),await u(`${n}.controller.ts`,St({pascal:t,kebab:n,plural:r,pluralPascal:i,swagger:d})),await u(`${n}.service.ts`,jt({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,Tt({pascal:t,kebab:n,schemaLib:f})),await u(`dtos/update-${n}.dto.ts`,Et({pascal:t,kebab:n,schemaLib:f})),await u(`dtos/${n}-response.dto.ts`,Dt({pascal:t,kebab:n})),await u(`${n}.repository.ts`,Ot({pascal:t,kebab:n,repoType:a,dtoPrefix:`./dtos`,tokenScope:s})),o||(await u(`__tests__/${n}.controller.test.ts`,kt({pascal:t,kebab:n,plural:r,style:c,testHarness:l})),await u(`__tests__/${n}.repository.test.ts`,At({pascal:t,kebab:n,plural:r,repoPrefix:`../${n}.repository`})))}function Ft(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function It(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=V(t),d=z(t),f=c?H(u):u,p=c?tt(d):d,m=N(n,f),h=[],g=o??!1,_={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,tokenScope:e.tokenScope??`app`,swagger:e.swagger??!1,schemaLib:e.schemaLib??`zod`,testHarness:e.testHarness??!1,style:e.style??`define`,write:async(e,t)=>{let n=N(m,e);if(s){h.push(n);return}if(!g&&await b(n)&&!await w({message:`File exists: ${C.dim(e)}. Overwrite?`,initialValue:!1})){x.warn(`Skipped: ${e}`);return}await y(n,t),h.push(n)},files:h};switch(l){case`minimal`:await Nt(_);break;default:await Pt(_)}return s||await Lt(n,d,f,u,_.style),h}async function Lt(e,t,n,r,i=`define`){let a=N(e,`index.ts`),o=await b(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){let e=i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
544
544
|
import { ${t}Module } from '${s}'
|
|
545
545
|
|
|
546
546
|
export const modules: AppModuleEntry[] = [${c}]
|
|
@@ -548,11 +548,51 @@ export const modules: AppModuleEntry[] = [${c}]
|
|
|
548
548
|
import { ${t}Module } from '${s}'
|
|
549
549
|
|
|
550
550
|
export const modules = defineModules().mount(${c})
|
|
551
|
-
`;await y(a,e);return}let l=await
|
|
551
|
+
`;await y(a,e);return}let l=await L(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=U(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${U(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
552
552
|
`,e);l=l.slice(0,t+1)+u+`
|
|
553
553
|
`+l.slice(t+1)}else l=u+`
|
|
554
|
-
`+l}let f=
|
|
555
|
-
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function
|
|
554
|
+
`+l}let f=zt(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${U(t)}Module\\b`).test(e)||(l=Rt(l,c))}else l=Rt(l,c);await R(a,l,`utf-8`)}function Rt(e,t){let n=zt(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function zt(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Ht(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Bt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Bt(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Ut(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Ut(e,t);if(n===-1)break;i=n+1}return i}function Vt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
555
|
+
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function Ht(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Vt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Ut(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Vt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}function Wt(e,t,n,r){return`/**
|
|
556
|
+
* Snapshot for the DevTools topology view (\`/_debug\`).
|
|
557
|
+
*
|
|
558
|
+
* Must be CHEAP — the topology endpoint polls on a short interval, so
|
|
559
|
+
* \`state\` and \`metrics\` should be counters and flags already in memory,
|
|
560
|
+
* never a database round trip.
|
|
561
|
+
*
|
|
562
|
+
* Uncomment with: import type { IntrospectionSnapshot } from '@forinda/kickjs'
|
|
563
|
+
* Delete this hook if the ${n} has nothing worth showing.
|
|
564
|
+
*/
|
|
565
|
+
// introspect(): IntrospectionSnapshot {
|
|
566
|
+
// return {
|
|
567
|
+
// protocolVersion: 1,
|
|
568
|
+
// name: '${e}',
|
|
569
|
+
// kind: '${n}',
|
|
570
|
+
// state: { connected: true },
|
|
571
|
+
// metrics: { handled: 0 },
|
|
572
|
+
// tokens: { provides: [], requires: [] },
|
|
573
|
+
// }
|
|
574
|
+
// },
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* DevTools panels this ${n} contributes — a sidebar tab showing HTML,
|
|
578
|
+
* an iframe, buttons that run server code, or a browser module.
|
|
579
|
+
*
|
|
580
|
+
* Uncomment with: import { defineDevtoolsTab } from '@forinda/kickjs-devtools-kit'
|
|
581
|
+
* and add the kit as a dependency: \`pnpm add @forinda/kickjs-devtools-kit\`.
|
|
582
|
+
* (\`@forinda/kickjs\` deliberately does not depend on it.)
|
|
583
|
+
* Delete this hook unless the ${n} ships a panel.
|
|
584
|
+
*/
|
|
585
|
+
// devtoolsTabs() {
|
|
586
|
+
// return [
|
|
587
|
+
// defineDevtoolsTab({
|
|
588
|
+
// id: '${e}',
|
|
589
|
+
// title: '${t}',
|
|
590
|
+
// view: { type: 'html', html: '<p>${t} ${n}</p>' },
|
|
591
|
+
// }),
|
|
592
|
+
// ]
|
|
593
|
+
// },`.split(`
|
|
594
|
+
`).map(e=>r+e).join(`
|
|
595
|
+
`)}async function Gt(e){let{name:t,outDir:n}=e,r=V(t),i=z(t),a=[],o=N(n,`${r}.adapter.ts`);return await y(o,`import {
|
|
556
596
|
defineAdapter,
|
|
557
597
|
type AdapterContext,
|
|
558
598
|
type AdapterMiddleware,
|
|
@@ -757,47 +797,11 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
|
757
797
|
return { name: '${r}', status: 'up' }
|
|
758
798
|
},
|
|
759
799
|
|
|
760
|
-
|
|
761
|
-
* Snapshot for the DevTools topology view (\`/_debug\`).
|
|
762
|
-
*
|
|
763
|
-
* Must be CHEAP — the topology endpoint polls on a short interval, so
|
|
764
|
-
* \`state\` and \`metrics\` should be counters and flags already in memory,
|
|
765
|
-
* never a database round trip. Async is allowed for that reason, not as
|
|
766
|
-
* an invitation to do work.
|
|
767
|
-
*
|
|
768
|
-
* Delete this hook if the adapter has nothing worth showing.
|
|
769
|
-
*/
|
|
770
|
-
// introspect(): IntrospectionSnapshot {
|
|
771
|
-
// return {
|
|
772
|
-
// protocolVersion: 1,
|
|
773
|
-
// state: { connected: true },
|
|
774
|
-
// metrics: { handled: 0 },
|
|
775
|
-
// tokens: [],
|
|
776
|
-
// }
|
|
777
|
-
// },
|
|
778
|
-
|
|
779
|
-
/**
|
|
780
|
-
* DevTools panels this adapter contributes.
|
|
781
|
-
*
|
|
782
|
-
* Import \`defineDevtoolsTab\` from \`@forinda/kickjs-devtools-kit\`;
|
|
783
|
-
* \`@forinda/kickjs\` deliberately does not depend on the kit at runtime.
|
|
784
|
-
*
|
|
785
|
-
* Delete this hook unless the adapter ships a panel.
|
|
786
|
-
*/
|
|
787
|
-
// devtoolsTabs() {
|
|
788
|
-
// return [
|
|
789
|
-
// defineDevtoolsTab({
|
|
790
|
-
// id: '${r}',
|
|
791
|
-
// title: '${i}',
|
|
792
|
-
// kind: 'html',
|
|
793
|
-
// render: () => '<p>${i} adapter</p>',
|
|
794
|
-
// }),
|
|
795
|
-
// ]
|
|
796
|
-
// },
|
|
800
|
+
${Wt(r,i,`adapter`,` `)}
|
|
797
801
|
}
|
|
798
802
|
},
|
|
799
803
|
})
|
|
800
|
-
`),a.push(o),a}async function
|
|
804
|
+
`),a.push(o),a}async function Kt(e){let{name:t,outDir:n}=e,r=V(t),i=z(t),a=[],o=N(n,`${r}.plugin.ts`);return await y(o,`import {
|
|
801
805
|
definePlugin,
|
|
802
806
|
type AppAdapter,
|
|
803
807
|
type AppModuleEntry,
|
|
@@ -953,12 +957,14 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
953
957
|
async shutdown(): Promise<void> {
|
|
954
958
|
// Example: await this.connection?.close()
|
|
955
959
|
},
|
|
960
|
+
|
|
961
|
+
${Wt(r,i,`plugin`,` `)}
|
|
956
962
|
}),
|
|
957
963
|
})
|
|
958
|
-
`),a.push(o),a}const
|
|
959
|
-
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=
|
|
964
|
+
`),a.push(o),a}const qt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function W(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return F(n);if(r){let e=qt,n=V(r),a=o?H(n):n,s=e[t]??``,c=N(i,a);return F(s?N(c,s):c)}return F(a)}async function Jt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.runtime===`express`,o=e.runtime?`this project runs on ${e.runtime} and has no
|
|
965
|
+
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=W({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),c=V(t),l=B(t),u=[],d=N(s,`${c}.middleware.ts`);return await y(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
|
|
960
966
|
|
|
961
|
-
export interface ${
|
|
967
|
+
export interface ${z(t)}Options {
|
|
962
968
|
// Add configuration options here. The factory below closes over the
|
|
963
969
|
// resolved options object; pass them at the call site —
|
|
964
970
|
// \`${l}({ foo: 'bar' })\` — and the closure preserves them across
|
|
@@ -966,7 +972,7 @@ export interface ${R(t)}Options {
|
|
|
966
972
|
}
|
|
967
973
|
|
|
968
974
|
/**
|
|
969
|
-
* ${
|
|
975
|
+
* ${z(t)} middleware.
|
|
970
976
|
*
|
|
971
977
|
* Usage in bootstrap (fires on every request):
|
|
972
978
|
* middlewares: [${l}()]
|
|
@@ -1002,7 +1008,7 @@ export interface ${R(t)}Options {
|
|
|
1002
1008
|
* first \`next()\` throws \`TypeError: next is not a function\`. Generate a
|
|
1003
1009
|
* guard instead (\`kick g guard\`) for the per-route, ctx-style shape.
|
|
1004
1010
|
*/
|
|
1005
|
-
export function ${l}(options: ${
|
|
1011
|
+
export function ${l}(options: ${z(t)}Options = {}) {
|
|
1006
1012
|
${a?" // Typed from `express` because that is this project's runtime\n // (`runtime: 'express'` in kick.config.ts). Global middleware is\n // connect-style on every engine, but only Express hands the handler its own\n // request / response objects — so `req.originalUrl`, `req.query` and\n // `res.json()` are all available here. Switching `runtime` later means\n // re-typing this signature from `node:http`.\n return (req: Request, res: Response, next: NextFunction) => {":` // Typed from \`node:http\`, not \`express\`. Global middleware is connect-style
|
|
1007
1013
|
// on every engine, but ${o} dependency to import types from. Under Fastify the handler
|
|
1008
1014
|
// receives \`request.raw\` / a reply driver, and under h3 the node objects, so
|
|
@@ -1015,7 +1021,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
|
|
|
1015
1021
|
next()
|
|
1016
1022
|
}
|
|
1017
1023
|
}
|
|
1018
|
-
`),u.push(d),u}async function
|
|
1024
|
+
`),u.push(d),u}async function Yt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=V(t),s=B(t),c=z(t),l=[],u=N(a,`${o}.guard.ts`);return await y(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
1019
1025
|
import type { RequestContext } from '@forinda/kickjs'
|
|
1020
1026
|
|
|
1021
1027
|
/**
|
|
@@ -1055,7 +1061,7 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
1055
1061
|
ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
|
|
1056
1062
|
}
|
|
1057
1063
|
}
|
|
1058
|
-
`),l.push(u),l}function
|
|
1064
|
+
`),l.push(u),l}function Xt(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 Zt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=V(t),s=z(t),c=e.key??B(t),l=Array.isArray(e.params)?e.params:Xt(e.params),u=W({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
1059
1065
|
`)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
1060
1066
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
1061
1067
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
@@ -1106,7 +1112,7 @@ ${_}
|
|
|
1106
1112
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1107
1113
|
},
|
|
1108
1114
|
})
|
|
1109
|
-
`,b=
|
|
1115
|
+
`,b=N(u,`${o}.contributor.ts`);return await y(b,v),[b]}async function Qt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=V(t),s=z(t),c=[],l=N(a,`${o}.service.ts`);return await y(l,`import { Service } from '@forinda/kickjs'
|
|
1110
1116
|
|
|
1111
1117
|
@Service()
|
|
1112
1118
|
export class ${s}Service {
|
|
@@ -1115,7 +1121,7 @@ export class ${s}Service {
|
|
|
1115
1121
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1116
1122
|
// ) {}
|
|
1117
1123
|
}
|
|
1118
|
-
`),c.push(l),c}async function
|
|
1124
|
+
`),c.push(l),c}async function $t(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=V(t),s=z(t),c=[],l=N(a,`${o}.controller.ts`);return await y(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
1119
1125
|
|
|
1120
1126
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1121
1127
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
@@ -1157,12 +1163,12 @@ export class ${s}Controller {
|
|
|
1157
1163
|
return reply.noContent()
|
|
1158
1164
|
}
|
|
1159
1165
|
}
|
|
1160
|
-
`),c.push(l),c}async function
|
|
1166
|
+
`),c.push(l),c}async function en(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=V(t),s=z(t),c=B(t),l=e.schemaLib??`zod`,u=Ct[l],d=[],f=N(a,`${o}.dto.ts`);return await y(f,`${u.import}
|
|
1161
1167
|
|
|
1162
|
-
export const ${c}Schema = ${
|
|
1168
|
+
export const ${c}Schema = ${wt(l,`// Define your schema fields here\n name: ${u.required}`)}
|
|
1163
1169
|
|
|
1164
1170
|
export type ${s}DTO = ${u.infer(`${c}Schema`)}
|
|
1165
|
-
`),d.push(f),d}async function
|
|
1171
|
+
`),d.push(f),d}async function tn(e){let t=N(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return O(t)&&!e.force&&!await w({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
1166
1172
|
Skipped — existing kick.config.ts preserved.`),[]):(await y(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1167
1173
|
|
|
1168
1174
|
export default defineConfig({
|
|
@@ -1205,18 +1211,18 @@ export default defineConfig({
|
|
|
1205
1211
|
},
|
|
1206
1212
|
],
|
|
1207
1213
|
})
|
|
1208
|
-
`),[t])}function
|
|
1214
|
+
`),[t])}function nn(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 G(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=nn(e,r);return i===-1?null:e.slice(r+1,i)}function K(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
1209
1215
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1210
|
-
`)}function
|
|
1216
|
+
`)}function rn(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 an(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 on(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=nn(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=G(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=G(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=G(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=rn(s),p=``;return l&&(p+=` register(container) {${K(l,4,6)} },\n\n`),u&&(p+=` contributors() {${K(u,4,6)} },\n\n`),p+=` routes() {${K(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
1211
1217
|
name: '${r}',
|
|
1212
1218
|
build: () => ({
|
|
1213
1219
|
${p}
|
|
1214
1220
|
}),
|
|
1215
|
-
})`}${c}`}}function
|
|
1216
|
-
`||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=
|
|
1221
|
+
})`}${c}`}}function sn(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=nn(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]===`
|
|
1222
|
+
`||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=nn(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=G(m,/register\s*\(([^)]*)\)\s*\{/),g=G(m,/contributors\s*\(\s*\)\s*\{/),_=G(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=an(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${K(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${K(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${K(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
1217
1223
|
${y}
|
|
1218
1224
|
}
|
|
1219
|
-
`}${u}`}}function
|
|
1225
|
+
`}${u}`}}function cn(e,t){return t===`class`?sn(e):on(e)}function ln(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 un(e){let t=[];return await n(F(e),0),t;async function n(e,r){let i;try{i=await We(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=N(e,a),o;try{o=await Ke(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function dn(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await We(e)}catch{return}await Ue(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=N(e,a),o=N(t,a),s;try{s=await Ke(i)}catch{continue}s.isDirectory()?await r(i,o):(await He(i,o),n++)}}}function fn(e){let t=new Date().toISOString().replaceAll(/[:.]/g,`-`);return N(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function pn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await un(e),s=await L(N(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=fn(r),await dn(e,c));let l=[];for(let e of o){let t=cn(await L(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await R(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=N(e,`index.ts`),d=null;try{d=await L(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=ln(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await R(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function mn(e,t){let n=await un(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 L(e,`utf-8`);i.test(t)&&r.push(e)}return r}const hn={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function gn(e){return e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=hn[a];if(!o){let e=[...Object.keys(hn),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}})}async function _n(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=V(t),l=z(t),u=s?H(c):c,d=s?tt(l):l,f=N(r,u),p=[],m=async(e,t)=>{let n=N(f,e);await y(n,t),p.push(n)};return await m(`${c}.module.ts`,bt({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,Mt({pascal:l,kebab:c})),await m(`${c}.controller.ts`,St({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await m(`${c}.service.ts`,jt({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,vn(l,n)),await m(`dtos/update-${c}.dto.ts`,yn(l,n)),await m(`dtos/${c}-response.dto.ts`,bn(l,n)),await m(`${c}.repository.ts`,Ot({pascal:l,kebab:c,repoType:i,dtoPrefix:`./dtos`,tokenScope:a})),await Lt(r,l,u,c,o),p}function vn(e,t){return`import { z } from 'zod'
|
|
1220
1226
|
|
|
1221
1227
|
export const create${e}Schema = z.object({
|
|
1222
1228
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1224,7 +1230,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
1224
1230
|
})
|
|
1225
1231
|
|
|
1226
1232
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
1227
|
-
`}function
|
|
1233
|
+
`}function yn(e,t){return`import { z } from 'zod'
|
|
1228
1234
|
|
|
1229
1235
|
export const update${e}Schema = z.object({
|
|
1230
1236
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -1232,14 +1238,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
1232
1238
|
})
|
|
1233
1239
|
|
|
1234
1240
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
1235
|
-
`}function
|
|
1241
|
+
`}function bn(e,t){return`export interface ${e}ResponseDTO {
|
|
1236
1242
|
id: string
|
|
1237
1243
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
1238
1244
|
`)}
|
|
1239
1245
|
createdAt: string
|
|
1240
1246
|
updatedAt: string
|
|
1241
1247
|
}
|
|
1242
|
-
`}async function
|
|
1248
|
+
`}async function xn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=V(t),o=z(t),s=[],c;if(e.outDir)c=F(e.outDir);else if(n){let e=V(n),t=i?H(e):e;c=F(N(r??`src/modules`,t,`__tests__`))}else c=F(`src/__tests__`);let l=N(c,`${a}.test.ts`);return await y(l,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
1243
1249
|
import { Container } from '@forinda/kickjs'
|
|
1244
1250
|
|
|
1245
1251
|
describe('${o}', () => {
|
|
@@ -1262,58 +1268,58 @@ describe('${o}', () => {
|
|
|
1262
1268
|
expect(true).toBe(true)
|
|
1263
1269
|
})
|
|
1264
1270
|
})
|
|
1265
|
-
`),s.push(l),s}function
|
|
1266
|
-
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const
|
|
1267
|
-
(dry run — no files were written)`),console.log()}async function
|
|
1268
|
-
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),
|
|
1271
|
+
`),s.push(l),s}function Sn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var Cn=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
1272
|
+
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const wn=[`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(`
|
|
1273
|
+
(dry run — no files were written)`),console.log()}async function Tn(e){if(!e)try{let e=await l(process.cwd());await we({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 En=[{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`}],Dn=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
1274
|
+
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),On=new Set([...En.map(e=>e.name.split(` `)[0]),...Dn.keys()]);async function kn(){console.log(`
|
|
1269
1275
|
Built-in generators:
|
|
1270
|
-
`);let e=Math.max(...
|
|
1276
|
+
`);let e=Math.max(...En.map(e=>e.name.length));for(let t of En)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await l(process.cwd()),n=g(t?.plugins??[],t?.commands??[]),r=await ft(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1271
1277
|
Plugin generators:
|
|
1272
1278
|
`);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(`
|
|
1273
1279
|
Failed to load:
|
|
1274
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function jn(e,t,n){let r=await l(process.cwd()),i=p(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??
|
|
1275
|
-
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=
|
|
1276
|
-
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=
|
|
1280
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function An(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`,`pluralize`])n[e]===!1&&(r[e]=!1);return r}async function jn(e,t,n){let r=await l(process.cwd()),i=p(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Ft(i.repo);t.repo&&f(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,g=u(r,process.cwd()),_=d(E()),v=h(E()),y=E(),b=m(y,`@forinda/kickjs-testing`,`any`)&&m(y,`supertest`,`any`),x=i.style??`define`;if(!n&&x===`define`){let e=await mn(F(a),`define`);if(e.length>0){console.error(`\n ${C.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${C.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${C.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 ${C.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${C.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${C.dim(`// kick.config.ts`)}\n ${C.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let S=[];for(let r of e){let e=await It({name:r,modulesDir:F(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:b,dryRun:n,pluralize:c,tokenScope:g,swagger:_,schemaLib:v,style:i.style});S.push(...e)}J(S,n),await Tn(n)}function Mn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await kn();return}if(!e||e.length===0){n.help();return}let a=q(i);v(a);let[o,s,...c]=e;if(o){let e=await l(process.cwd()),n=g(e?.plugins??[],e?.commands??[]),i=await dt({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`&&On.has(o)){let e=Dn.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 jn(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);v(r),await jn(e,An(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);v(r),J(await Gt({name:e,outDir:F(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);v(r),J(await Kt({name:e,outDir:F(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
1281
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await Jt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
1282
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await Yt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
1277
1283
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1278
1284
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1279
|
-
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=
|
|
1280
|
-
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=
|
|
1281
|
-
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=
|
|
1282
|
-
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=
|
|
1283
|
-
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=
|
|
1285
|
+
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);v(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 l(process.cwd()),o=p(a),s=o.dir??`src/modules`;J(await Zt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
1286
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await Qt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
1287
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await $t({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Tn(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
|
|
1288
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await en({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,schemaLib:h(E())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
1289
|
+
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);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;J(await xn({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pluralize:a.pluralize??!0}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
1284
1290
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1285
1291
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1286
1292
|
Optional: append :optional (shell-safe): description:text:optional
|
|
1287
|
-
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=
|
|
1293
|
+
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=An(r,n),a=q(r);v(a),t.length===0&&(console.error(`
|
|
1288
1294
|
Error: At least one field is required.
|
|
1289
1295
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1290
1296
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1291
1297
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1292
|
-
`),process.exit(1));let
|
|
1293
|
-
`,u=``;if(O(i)&&(u=await
|
|
1298
|
+
`),process.exit(1));let o=await l(process.cwd()),s=p(o),c=i.modulesDir??s.dir??`src/modules`,f=gn(t),m=u(o,process.cwd()),h=d(E()),g=await _n({name:e,fields:f,modulesDir:F(c),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:i.pluralize===!1?!1:s.pluralize??!0,tokenScope:m,swagger:h,style:s.style});console.log(`\n Scaffolded ${e} with ${f.length} field(s):`);for(let e of f)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);J(g,a),await Tn(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);v(n),J(await tn({outDir:F(`.`),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 (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal | fullstack`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=q(t);v(n);let r=e.only??`all`;if(!wn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${wn.join(` | `)}`),process.exitCode=1;return}J(await re({outDir:F(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])Nn(n,e,t?.projectRoot)}function Nn(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);v(s);let c=await dt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&J(c.files,s)})}const Pn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Fn(e){let t=j.resolve(e.cwd,`.kickjs/types`);e.check||await Ue(t,{recursive:!0});let n=new Map,r=e.scan??ge,i=j.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(I(e).href)},async writeFile(t,n){let r=j.resolve(e.cwd,t);await Ue(j.dirname(r),{recursive:!0}),await R(r,n,`utf8`)},getScanResult:e=>{let t=In(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?he(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=j.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=`${Pn}${n.id} */\n\n`+a+`
|
|
1299
|
+
`,u=``;if(O(i)&&(u=await L(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await R(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new Cn(c);return s}function In(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function Ln(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var Rn=e({applyDisableFilter:()=>Ln,runAllPluginTypegens:()=>zn});async function zn(e){let t=[...fo,...e.config?.plugins??[]],{enabled:n,skipped:r,unknown:i}=Ln(g(t,e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&r.length>0)for(let e of r)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&i.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${i.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),n.length===0)return[];try{let t=await Fn({cwd:e.cwd,config:e.config??{},plugins:n,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Sn())for(let e of t)console.log(` ${e.id}: ${e.status}`);return t}catch(t){if(t instanceof Cn||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 Bn(e){let t=new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}function Vn(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-CEcjoYli.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Rn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-CEcjoYli.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-CkO4WI5N.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=j.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>j.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,u=e=>e.replaceAll(`\\`,`/`),d=c.map(u),f=e=>{let t=u(e);return d.some(e=>t===e||t.startsWith(`${e}/`))},p=Bn(e.emitWarning),m=null,h=!1,g=new Set,_=new Set,v=!1,y=!1;function b(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>p.clear(`scan`)).catch(e=>p.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r,watch:!0}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>p.clear(`plugins`)).catch(e=>p.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function x(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,b(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!h&&!u(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)v=!0,l&&(y=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=f(t);if(!n&&!r)return;r&&l&&(y=!0),n&&(e===`unlink`?(_.add(t),g.delete(t)):(g.add(t),_.delete(t)))}m&&clearTimeout(m),m=setTimeout(x,r)}},runOnce(){h||b(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function Hn(e){let t=N(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=N(t,i);if(O(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function Un(e){let t=e.spawnFn??Be,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 Wn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1294
1300
|
`):`${n.slice(0,t).join(`
|
|
1295
|
-
`)}\n… ${n.length-t} more line(s)`}function Gn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Kn(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 qn(e,t,n={}){t&&(process.env.PORT=t);let r=Gn(n.polling),i=process.cwd(),a=await l(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await we({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=
|
|
1301
|
+
`)}\n… ${n.length-t} more line(s)`}function Gn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Kn(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 qn(e,t,n={}){t&&(process.env.PORT=t);let r=Gn(n.polling),i=process.cwd(),a=await l(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await we({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=F(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await zn({cwd:i,config:a});await _e(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:u}=await import(`node:module`),d=u(F(`package.json`)).resolve(`vite`),{createServer:f}=await import(I(d).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let p=await f({configFile:F(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),m=n.typecheck??a?.dev?.typecheck??!1,h=null,g=!0;if(m){let e=Hn(i);e?h=Un({cwd:i,bin:e,onResult:e=>{p.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?g||(g=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(g=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(Wn(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 _=Vn({cwd:i,config:a,emitWarning:e=>{console.warn(e),p.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>h?.schedule()});p.watcher.on(`add`,e=>_.handleWatchEvent(`add`,e)),p.watcher.on(`unlink`,e=>_.handleWatchEvent(`unlink`,e)),p.watcher.on(`change`,e=>_.handleWatchEvent(`change`,e)),p.watcher.on(`unlinkDir`,e=>_.handleWatchEvent(`unlinkDir`,e)),_.assetSrcRoots.length>0&&p.watcher.add([..._.assetSrcRoots]),await p.listen(),p.printUrls(),console.log(`
|
|
1296
1302
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1297
|
-
`),h?.schedule();let v=!1,y=async()=>{if(!v){v=!0,_.dispose(),h?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await p.close(),process.exit(0)}};process.on(`SIGINT`,y),process.on(`SIGTERM`,y),process.on(`SIGBREAK`,y)}async function Jn(e){let t=await l(e);try{await we({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=
|
|
1303
|
+
`),h?.schedule();let v=!1,y=async()=>{if(!v){v=!0,_.dispose(),h?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await p.close(),process.exit(0)}};process.on(`SIGINT`,y),process.on(`SIGTERM`,y),process.on(`SIGBREAK`,y)}async function Jn(e){let t=await l(e);try{await we({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=F(e,t?.typegen?.outDir??`.kickjs/types`),r=await zn({cwd:e,config:t});await _e(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 Yn(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 qn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
1298
1304
|
Error: vite is not installed.
|
|
1299
1305
|
Run: pnpm add -D vite unplugin-swc
|
|
1300
1306
|
`):console.error(`
|
|
1301
1307
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1302
1308
|
Building for production...
|
|
1303
|
-
`);let{createRequire:e}=await import(`node:module`),t=e(
|
|
1304
|
-
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
1305
|
-
Building asset map...`);try{await
|
|
1309
|
+
`);let{createRequire:e}=await import(`node:module`),t=e(F(`package.json`)).resolve(`vite`),{build:n}=await import(I(t).href);await n({configFile:F(`vite.config.ts`)});let r=await l(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
|
|
1310
|
+
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?N(`dist`,e):e.dest??N(`dist`,t),r=F(t),i=F(n);if(!O(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Me(i,{recursive:!0}),je(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
|
|
1311
|
+
Building asset map...`);try{await ke(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1306
1312
|
Build complete.
|
|
1307
1313
|
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await l(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
1308
|
-
Building asset map...`);try{await
|
|
1314
|
+
Building asset map...`);try{await ke(e,{cwd:process.cwd()}),console.log(`
|
|
1309
1315
|
Asset build complete.
|
|
1310
|
-
`)}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)),a(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=
|
|
1316
|
+
`)}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)),a(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=F(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await Jn(t);let n=Hn(t);if(!n){console.error(`
|
|
1311
1317
|
No type-checker found. Install one in this project:
|
|
1312
1318
|
pnpm add -D typescript (tsc)
|
|
1313
1319
|
pnpm add -D @typescript/native-preview (tsgo, faster)
|
|
1314
|
-
`),process.exit(1);return}let r=
|
|
1315
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Xn(){try{let e=
|
|
1316
|
-
`))})}const{bold:
|
|
1320
|
+
`),process.exit(1);return}let r=Ve(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 Kn(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 qn(e.entry,e.port)}catch(e){console.error(`
|
|
1321
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Xn(){try{let e=M(Re(import.meta.url));return JSON.parse(k(N(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Zn=new Set(Object.values(o).filter(e=>e.deprecated).map(e=>e.pkg));function Qn(e){let t=N(e,`package.json`);if(!O(t))return[];let n;try{n=JSON.parse(k(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=N(e,`node_modules`,...t.split(`/`),`package.json`);if(O(i))try{n=JSON.parse(k(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Zn.has(t)}})}function $n(e){let t=e;for(;;){if(O(N(t,`package.json`)))return t;let e=M(t);if(e===t)return null;t=e}}function er(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Xn()}`,``,` System:`,` OS: ${Xe()} ${Ze()} (${Ye()})`,` Node: ${process.version}`],t=$n(process.cwd()),n=t?Qn(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(`
|
|
1322
|
+
`))})}const{bold:Y,dim:X,green:tr,red:nr,yellow:rr,blue:ir}=C;function ar(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 or(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function sr(e,t){try{return await or(`${e}${t}`)}catch{return null}}async function cr(e){let[t,n,r,i,a]=await Promise.all([sr(e,`/health`),sr(e,`/metrics`),sr(e,`/routes`),sr(e,`/container`),sr(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function lr(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`?tr(`● healthy`):nr(`● `+n.status);console.log(` ${Y(`Health:`)} ${e}`)}else console.log(` ${Y(`Health:`)} ${nr(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?nr:r.errorRate>0?rr:tr;console.log(` ${Y(`Uptime:`)} ${ar(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(` ${ee(e.method)} ${t} ${ir(e.controller)}.${X(e.handler)}`)}}console.log(s),console.log()}function ur(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 cr(r);t.json?console.log(JSON.stringify(e,null,2)):lr(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(nr(` ✖ 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()})}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 dr=[{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
|
|
1317
1323
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
1318
1324
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
1319
1325
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -1337,7 +1343,7 @@ import { modules } from './modules'
|
|
|
1337
1343
|
import './config' // ← add this — registers env schema
|
|
1338
1344
|
import { bootstrap } from '@forinda/kickjs'
|
|
1339
1345
|
import { modules } from './modules'
|
|
1340
|
-
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=
|
|
1346
|
+
`,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.
|
|
1341
1347
|
When vitest re-imports your modules across tests, the same class can be
|
|
1342
1348
|
registered twice and the container throws. The fix is to wipe the
|
|
1343
1349
|
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'
|
|
@@ -1347,7 +1353,7 @@ describe('UserController', () => {
|
|
|
1347
1353
|
beforeEach(() => Container.reset())
|
|
1348
1354
|
|
|
1349
1355
|
it('does the thing', async () => { /* ... */ })
|
|
1350
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
1356
|
+
})`,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
|
|
1351
1357
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
1352
1358
|
returns the controller wiring. This was a deliberate choice — modules
|
|
1353
1359
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -1374,7 +1380,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
1374
1380
|
and matches the actual class names so refactors propagate via
|
|
1375
1381
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
1376
1382
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
1377
|
-
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=
|
|
1383
|
+
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
|
|
1378
1384
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
1379
1385
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
1380
1386
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -1382,7 +1388,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
1382
1388
|
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({
|
|
1383
1389
|
modules,
|
|
1384
1390
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
1385
|
-
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return
|
|
1391
|
+
})`,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
|
|
1386
1392
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
1387
1393
|
before any decorator runs. Most projects do this at the top of
|
|
1388
1394
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -1391,7 +1397,7 @@ import './config'
|
|
|
1391
1397
|
import { bootstrap } from '@forinda/kickjs'
|
|
1392
1398
|
import { modules } from './modules'
|
|
1393
1399
|
|
|
1394
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return
|
|
1400
|
+
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
|
|
1395
1401
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
1396
1402
|
the most likely cause is that the module is missing from the exported
|
|
1397
1403
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -1399,7 +1405,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
1399
1405
|
import { UserModule } from './users/user.module'
|
|
1400
1406
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1401
1407
|
|
|
1402
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!
|
|
1408
|
+
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\`.
|
|
1403
1409
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
1404
1410
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
1405
1411
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -1433,7 +1439,7 @@ beforeAll(() => {
|
|
|
1433
1439
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
1434
1440
|
resetEnvCache()
|
|
1435
1441
|
loadEnv(envSchema)
|
|
1436
|
-
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=
|
|
1442
|
+
})`,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
|
|
1437
1443
|
the first time the container resolves it. A REQUEST-scoped binding is the
|
|
1438
1444
|
opposite — one instance per request, discarded when the response ends.
|
|
1439
1445
|
|
|
@@ -1454,7 +1460,7 @@ and the singleton never captures one.
|
|
|
1454
1460
|
|
|
1455
1461
|
If the dependency did not need request scope in the first place, the
|
|
1456
1462
|
other direction also works — make it SINGLETON and pass the per-request
|
|
1457
|
-
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=
|
|
1463
|
+
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
|
|
1458
1464
|
is requested while it is already being resolved further up the stack, the
|
|
1459
1465
|
graph has a cycle and there is no order that satisfies both ends.
|
|
1460
1466
|
|
|
@@ -1486,7 +1492,7 @@ export class OrderService {
|
|
|
1486
1492
|
@Service()
|
|
1487
1493
|
export class BillingService {
|
|
1488
1494
|
@Autowired() private readonly orders!: OrderService // ← resolved after construction
|
|
1489
|
-
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=
|
|
1495
|
+
}`,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 —
|
|
1490
1496
|
and a class is only loaded if something imports it. A module that is not
|
|
1491
1497
|
in the bootstrap array is never imported, so none of its @Service /
|
|
1492
1498
|
@Repository / @Controller classes ever register, and the first thing that
|
|
@@ -1512,7 +1518,7 @@ export const TenantModule = defineModule({
|
|
|
1512
1518
|
},
|
|
1513
1519
|
routes: () => null,
|
|
1514
1520
|
}),
|
|
1515
|
-
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!
|
|
1521
|
+
})`,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
|
|
1516
1522
|
and reads \`app\` off it, then hands each request to that instance.
|
|
1517
1523
|
|
|
1518
1524
|
When the entry runs \`await bootstrap(...)\` without assigning the result to
|
|
@@ -1544,7 +1550,7 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1544
1550
|
`),process.exit(1));let r=wr(),i=fr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1545
1551
|
`);return}if(i){Tr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1546
1552
|
`),process.exit(2)),Er(n),process.exit(2));let a=await pr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(br(a),null,2)+`
|
|
1547
|
-
`),process.exit(a.kind===`ok`?0:2)),xr(n,a),process.exit(a.kind===`ok`?0:2)})}function br(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 xr(e,t){if(t.kind===`ok`){Tr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Or(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Dr(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Or(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Sr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Cr()}function Cr(){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 wr(){let e=process.cwd();return{cwd:e,hasFile:t=>O(
|
|
1553
|
+
`),process.exit(a.kind===`ok`?0:2)),xr(n,a),process.exit(a.kind===`ok`?0:2)})}function br(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 xr(e,t){if(t.kind===`ok`){Tr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Or(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Dr(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Or(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Sr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Cr()}function Cr(){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 wr(){let e=process.cwd();return{cwd:e,hasFile:t=>O(F(e,t))}}function Tr(e,t,n,r=!1){let i=Or(e.trim(),200),a=r?`AI-generated — verify before applying`:kr(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${Dr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Dr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Dr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Dr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
1548
1554
|
`)}function Er(e){let t=Or(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
|
|
1549
1555
|
|
|
1550
1556
|
1. Check the framework docs for the error keywords:
|
|
@@ -1559,10 +1565,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1559
1565
|
|
|
1560
1566
|
`)}function Dr(e,t){return e.split(`
|
|
1561
1567
|
`).map(e=>`${t}${e}`).join(`
|
|
1562
|
-
`)}function Or(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function kr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Ar(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(jr),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(Mr)}function jr(e){let t=
|
|
1563
|
-
`,`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 Nr(e){let t=
|
|
1568
|
+
`)}function Or(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function kr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Ar(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(jr),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(Mr)}function jr(e){let t=F(e.entry);O(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=Be(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Mr(e){let t=process.cwd(),n=Nr(t)??Ie(t),r=e.name??n,i=e.global?F(process.env.HOME??`.`,`.mcp.json`):F(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(O(i))try{let e=k(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,Fe(i,JSON.stringify(o,null,2)+`
|
|
1569
|
+
`,`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 Nr(e){let t=F(e,`package.json`);if(!O(t))return null;try{let e=k(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Pr(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=F(t,e.entry);O(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Ir(t,`tsx`);r||(console.error(`
|
|
1564
1570
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
1565
|
-
`),process.exit(1));let i=Fr(n,e.entry),a=
|
|
1571
|
+
`),process.exit(1));let i=Fr(n,e.entry),a=N(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=ze(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Fr(e,t){return`
|
|
1566
1572
|
import 'reflect-metadata'
|
|
1567
1573
|
|
|
1568
1574
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1587,7 +1593,7 @@ try {
|
|
|
1587
1593
|
|
|
1588
1594
|
// Load entry to trigger decorator registration
|
|
1589
1595
|
try {
|
|
1590
|
-
await import('${
|
|
1596
|
+
await import('${I(e).href}')
|
|
1591
1597
|
} catch (err) {
|
|
1592
1598
|
console.warn(' Warning: ' + err.message)
|
|
1593
1599
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -1616,42 +1622,42 @@ server.on('exit', () => {
|
|
|
1616
1622
|
console.log('\\n Goodbye!\\n')
|
|
1617
1623
|
process.exit(0)
|
|
1618
1624
|
})
|
|
1619
|
-
`}function Ir(e,t){let n=e;for(;;){let e=
|
|
1625
|
+
`}function Ir(e,t){let n=e;for(;;){let e=N(n,`node_modules`,`.bin`,t);if(O(e))return e;let r=F(n,`..`);if(r===n)break;n=r}return null}function Lr(e,t){let n=RegExp(`^\\s*${U(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]!==`
|
|
1620
1626
|
`;)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]===`
|
|
1621
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Rr(e,t){let n=
|
|
1627
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Rr(e,t){let n=zt(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Lr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${U(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 zr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=V(t),o=z(t),s=i?H(a):a;s!==a&&!await b(N(n,s))&&await b(N(n,a))&&(s=a);let c=N(n,s);if(!await b(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await w({message:C.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1622
1628
|
Cancelled.
|
|
1623
|
-
`);return}await
|
|
1629
|
+
`);return}await Ge(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=N(n,`index.ts`);if(await b(l)){let e=await L(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${U(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${U(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Rr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1624
1630
|
|
|
1625
|
-
`),e!==t&&(await
|
|
1631
|
+
`),e!==t&&(await R(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Br(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await l(process.cwd()),r=p(n),i=t.modulesDir??r.dir??`src/modules`,a=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await zr({name:n,modulesDir:F(i),force:t.force,pluralize:a})})}function Vr(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 Hr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Ur(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=E(process.cwd()),n=await l(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-rEXrK-TD.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>uo),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(`
|
|
1626
1632
|
Registered typegen plugins:
|
|
1627
1633
|
`);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(`
|
|
1628
1634
|
Disable one in kick.config.ts:
|
|
1629
1635
|
`),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
|
|
1630
|
-
`);return}let r=Vr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Hr(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 Se(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 we(a);let r=await zn({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=
|
|
1636
|
+
`);return}let r=Vr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Hr(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 Se(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 we(a);let r=await zn({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=F(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await _e(i,r,e.silent??!1)}}}catch(e){e instanceof Ce?console.error(`
|
|
1631
1637
|
`+e.message+`
|
|
1632
|
-
`):e instanceof
|
|
1638
|
+
`):e instanceof Cn?console.error(`
|
|
1633
1639
|
`+e.message+`
|
|
1634
1640
|
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const Wr=new Set([`Service`,`Injectable`,`Component`,`Repository`]);function Gr(e,t){return typeof t==`number`?e.slice(0,t).split(`
|
|
1635
|
-
`).length:1}function Kr(e){let t=
|
|
1641
|
+
`).length:1}function Kr(e){let t=se(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(ce(e)&&e.type===`MemberExpression`&&D(e.object)===`Scope`){let t=D(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function qr(e){let t=D(e);if(t)return{key:`id:${t}`,label:t};let n=se(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function Jr(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=Ee(e).map(le).find(e=>e?.name===`Inject`),a=null;if(i)a=qr(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=qr(e.typeName))}a&&r.push({...a,line:Gr(t,e.start)})}return r}function Yr(e){let t=new Map,n=new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=qe(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`)&&ce(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(D(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(D(n.id),t)}De(e,e=>{if(e.type===`ClassDeclaration`){let a=D(e.id);if(!a)return;for(let o of Ee(e)){let s=le(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:Jr(e,n)});return}if(Wr.has(s.name)){let o=de(Oe(s.call),`scope`),c=o?Kr(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:Jr(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!ce(a)||a.type!==`MemberExpression`)return;let o=D(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=qr(s[0]);c&&i(c.key,s.length>=3?Kr(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 Xr(e){let t=[];if(!O(e))return t;let n=A(e,{withFileTypes:!0});for(let r of n){let n=N(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Xr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Zr(e){try{return k(e,`utf-8`)}catch{return``}}const Qr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function $r(e,t){let n=Zr(N(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Qr.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 ei(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 ti(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 ni(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function ri(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 ii(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 ai(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 oi(e){let t=Xr(N(e,`src`)).map(e=>Zr(e)),n=[],r=$r(e,t);r&&n.push(r);let i=ei(t);i&&n.push(i);let a=ti(t);a&&n.push(a);let o=ni();o&&n.push(o);let s=ri(t);return s&&n.push(s),n.push(ii(t)),n.push(ai(t)),n}function si(e){let t=Yr(Xr(N(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:P(e,t).split(`\\`).join(`/`),source:Zr(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 ci(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(`
|
|
1636
1642
|
Usage: kick check [--deploy] [--di]
|
|
1637
1643
|
|
|
1638
1644
|
Available checks:
|
|
1639
1645
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1640
1646
|
--di Find REQUEST-scoped dependencies injected into singleton constructors
|
|
1641
|
-
`);return}let t=process.cwd();te(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=ne();n.start(`Scanning project...`);let r=[...e.deploy?oi(t):[],...e.di?si(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)x.message(`${ae(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?C.red(`${a} critical`):`${a} critical`,o>0?C.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(T(C.red(`${l} — fix critical issues before deploying`)),process.exit(1)):T(C.green(`${l} — looking good!`))})}function li(e){try{return JSON.parse(k(e,`utf-8`))}catch{return null}}function ui(e){try{return k(e,`utf-8`)}catch{return null}}function di(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function fi(e){let t=
|
|
1642
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function vi(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function yi(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const bi={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function xi(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=bi[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function Si(e){if(!e.pkg||!wi(e.cwd))return null;let t=n[e.runtime],r=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:r,status:`pass`,message:t.prod}:{name:r,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:r,status:`pass`,message:`native multipart`}}const Ci=2e3;function wi(e){let t=
|
|
1647
|
+
`);return}let t=process.cwd();te(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=ne();n.start(`Scanning project...`);let r=[...e.deploy?oi(t):[],...e.di?si(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)x.message(`${ae(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?C.red(`${a} critical`):`${a} critical`,o>0?C.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(T(C.red(`${l} — fix critical issues before deploying`)),process.exit(1)):T(C.green(`${l} — looking good!`))})}function li(e){try{return JSON.parse(k(e,`utf-8`))}catch{return null}}function ui(e){try{return k(e,`utf-8`)}catch{return null}}function di(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function fi(e){let t=N(e,`tsconfig.json`);if(O(t))return pi(t,new Set)}function pi(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=ui(e);if(n===null)return null;let r=di(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={};for(let n of i){if(typeof n!=`string`)continue;let r=mi(M(e),n);if(!r)continue;let i=pi(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function mi(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return hi(F(e,t));let n=e;for(;;){let e=hi(N(n,`node_modules`,t));if(e)return e;let r=M(n);if(r===n)break;n=r}return null}function hi(e){if(O(e)){try{if(Pe(e).isDirectory()){let t=N(e,`tsconfig.json`);return O(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return O(t)?t:null}function gi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function _i(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
|
|
1648
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function vi(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function yi(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const bi={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function xi(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=bi[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function Si(e){if(!e.pkg||!wi(e.cwd))return null;let t=n[e.runtime],r=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:r,status:`pass`,message:t.prod}:{name:r,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:r,status:`pass`,message:`native multipart`}}const Ci=2e3;function wi(e){let t=N(e,`src`);if(!O(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<Ci;){let e=r.pop(),t;try{t=A(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=Ci)break;let t=N(e,a.name);if(a.isDirectory()){a.name!==`node_modules`&&r.push(t);continue}if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(ui(t)??``)))return!0}}return!1}function Ti(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.
|
|
1643
1649
|
Install it: pnpm add reflect-metadata
|
|
1644
1650
|
Then import it at the top of src/index.ts:
|
|
1645
1651
|
|
|
1646
1652
|
import 'reflect-metadata'
|
|
1647
|
-
// ... rest of bootstrap`}}function Ei(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function Di(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>
|
|
1653
|
+
// ... rest of bootstrap`}}function Ei(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function Di(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>N(e.cwd,t)).filter(e=>O(e)).filter(e=>/\bloadEnv\s*\(/.test(ui(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>N(e.cwd,t)).find(e=>O(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let r=ui(n)??``,i=M(n),a=[];for(let e of t){let t=P(i,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);a.push(n,r);let o=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(o){let e=`@/`+o[1],t=e.replace(/\/index$/,``);a.push(e,t)}}let o=-1;for(let e of new Set(a)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${gi(e)}['"]`,`m`),n=r.match(t);n&&n.index!==void 0&&(o===-1||n.index<o)&&(o=n.index)}let s=r.search(/\bbootstrap\s*\(/),c=t.map(t=>P(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return o===-1?{name:`env wiring`,status:`fail`,message:c,fix:`An env-init file (${c}) calls \`loadEnv(...)\` but \`${P(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${P(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:s!==-1&&o>s?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function Oi(e,t=ki){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=A(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=N(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=Pe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const ki=2e3;function Ai(e){let t=N(e.cwd,`.kickjs`,`types`);if(!O(t))return null;let n=Oi(t);if(n===0)return null;let r=Date.now()-n,i=Math.floor(r/6e4);return i>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${i} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:i===0?`just now`:`${i}m ago`}}const ji=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Mi=[`.env.test`,`.env.test.local`],Ni=[`.env`,`.env.local`];function Pi(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function Fi(e){if(!ji.some(t=>O(N(e.cwd,t))))return null;let t=Ni.filter(t=>O(N(e.cwd,t)));if(t.length===0)return null;let n=Mi.filter(t=>O(N(e.cwd,t)));if(n.length>0){let t=Pi(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
|
|
1648
1654
|
INSTEAD of ${t.join(` and `)} — no layering, no fallback. Without one of\nthose files, every var your test config does not pin resolves from your
|
|
1649
1655
|
development env — including DATABASE_URL and any third-party credentials.
|
|
1650
1656
|
|
|
1651
1657
|
Create .env.test (cp .env.test.example .env.test, if the project has one)
|
|
1652
1658
|
holding the whole environment the suite should run against
|
|
1653
1659
|
(a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
|
|
1654
|
-
and supply env from the test runner.`}}const Ii=[()=>_i(),vi,yi,xi,Si,Ti,Ei,Di,Fi,Ai];async function Li(e,t={}){let n={cwd:e,pkg:li(
|
|
1660
|
+
and supply env from the test runner.`}}const Ii=[()=>_i(),vi,yi,xi,Si,Ti,Ei,Di,Fi,Ai];async function Li(e,t={}){let n={cwd:e,pkg:li(N(e,`package.json`)),tsconfig:fi(e),runtime:t.runtime??`express`},r=[...Ii,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function Ri(e){switch(e){case`pass`:return C.green(`✔`);case`warn`:return C.yellow(`⚠`);case`fail`:return C.red(`✖`)}}function zi(e){let t=Ri(e.status),n=e.message?` ${C.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function Bi(e){return e.split(`
|
|
1655
1661
|
`).map(e=>` ${C.dim(`→`)} ${e}`).join(`
|
|
1656
1662
|
`)}function Vi(e){return e?.doctor?.checks??[]}function Hi(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),n=Vi(await l(e)),r=await t(e);te(`KickJS Doctor`);let i=await Li(e,{extraChecks:n,runtime:r});for(let e of i)x.message(zi(e)),e.fix&&e.status!==`pass`&&x.message(Bi(e.fix));let a=i.filter(e=>e.status===`pass`).length,o=i.filter(e=>e.status===`warn`).length,s=i.filter(e=>e.status===`fail`).length,c=[C.green(`${a} passed`),o>0?C.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?C.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(T(`${c} — fix the errors above before running the app`),process.exit(1)):T(o>0?`${c} — review the warnings`:C.green(`${c} — your environment looks good`))})}function Ui(e){return e.optsWithGlobals().dryRun??!1}function Wi(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.
|
|
1657
1663
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
@@ -1662,7 +1668,7 @@ and supply env from the test runner.`}}const Ii=[()=>_i(),vi,yi,xi,Si,Ti,Ei,Di,F
|
|
|
1662
1668
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1663
1669
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1664
1670
|
Always commit before running with --apply.
|
|
1665
|
-
`),process.exit(1));let r=await l(process.cwd()),i=p(r),a=
|
|
1671
|
+
`),process.exit(1));let r=await l(process.cwd()),i=p(r),a=F(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 ${C.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=C.dim(`→ ${o}`),c=n?C.dim(`(dry-run)`):C.bold(`(applying)`);console.log(`\n ${C.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${C.dim(a)}\n`);let u=e.backup!==!1&&!n,d=await pn(a,{dryRun:n,target:o,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${C.green(`✓`)} backup: ${C.dim(e)}\n ${C.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${C.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,m=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${C.green(`✓`)} ${e.path}`);else{m++;let t=C.dim(`(${e.reason??`skipped`})`);console.log(` ${C.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${C.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=C.dim(`(${d.indexReason??`skipped`})`);console.log(` ${C.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${C.dim(`-`)} ${d.indexPath} ${C.dim(`(not found)`)}`);let h=n?C.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${C.bold(String(f))} migrated, ${C.bold(String(m))} skipped${h}\n`)})}function Gi(e,t=O){let n=M(e);return(t(F(n,`pnpm-workspace.yaml`))||t(F(n,`package.json`)))&&t(F(n,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function Ki(e,t,n){let r=Gi(t,n),i=e?.staticDir===!1?void 0:e?.staticDir??r.staticDir;return{entry:e?.entry??`src/serverless.ts`,outDir:e?.outDir??`dist/serverless`,staticDir:i,siteRoot:e?.siteRoot??r.siteRoot,publishDir:e?.publishDir??`dist/public`,apiPath:e?.apiPath??r.apiPath,external:e?.external??[`valibot`,`yup`],vercelRuntime:e?.vercelRuntime??`nodejs22.x`}}function qi(e,t){return`import { handler } from '${e}'
|
|
1666
1672
|
|
|
1667
1673
|
// Netlify's context carries waitUntil, so ctx.waitUntil() work finishes after the response.
|
|
1668
1674
|
export default (request, context) => handler.fetch(request, context)
|
|
@@ -1675,8 +1681,8 @@ export const config = {
|
|
|
1675
1681
|
const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
|
|
1676
1682
|
|
|
1677
1683
|
export default (req, res) => handler.node(req, res, requestContext())
|
|
1678
|
-
`}function Yi(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Xi(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function Zi(e,t){let n;try{n=
|
|
1679
|
-
`).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 Qi(e){let t=
|
|
1684
|
+
`}function Yi(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Xi(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function Zi(e,t){let n;try{n=qe(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
|
|
1685
|
+
`).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 Qi(e){let t=F(e,`src`);return O(t)?A(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=k(F(t,e),`utf-8`);return n.includes(`@Cron`)?Zi(n,`src/${e}`):[]}):[]}function $i(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 ea(e){let t=[],n=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,` `);if(i.split(` `).length!==5){t.push(`${e}: Vercel crons need a five-field expression, so it has no Vercel cron entry`);continue}n.set($i(i),i)}return{crons:[...n].map(([e,t])=>({path:`/_kick/cron/${e}`,schedule:t})),warnings:t}}function ta(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 na(e,t){let{createRequire:n}=await import(`node:module`),r=n(F(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=F(e,`node_modules`,t,`package.json`)}if(!O(i))throw Error(`${t} is not installed in this project. Run: pnpm add -D vite unplugin-swc @forinda/kickjs-vite`);let a=ta(JSON.parse(k(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(I(F(M(i),a)).href)}async function ra(e,t,n){let r=F(e,t.entry);if(!O(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await na(e,`vite`),{default:a}=await na(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await na(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":F(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:F(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:t.external.filter(t=>!O(F(e,`node_modules`,t))),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=F(e,t.outDir,`server.mjs`);return n(`bundled ${P(process.cwd(),c)}`),c}function ia(e,t){let n=t.projectRoot,r=()=>Ki(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r(),i=await ra(n,e,t.log),a=F(n,e.siteRoot),o=Qi(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=F(a,`.netlify/v1/functions`);Me(s,{recursive:!0});let c=P(s,i).split(Le).join(`/`);Fe(F(s,`api.mjs`),qi(c,e.apiPath)),t.log(`wrote ${P(process.cwd(),F(s,`api.mjs`))}`);let l=e.staticDir??e.publishDir;e.staticDir||(Me(F(n,l),{recursive:!0}),t.log(`publish directory ready at ${P(process.cwd(),F(n,l))}`));let u=F(a,`netlify.toml`);if(O(u)){let e=Yi(k(u,`utf-8`)),r=P(a,F(n,l)).split(Le).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(),i=await ra(n,e,t.log),a=F(n,e.siteRoot),o=e.staticDir?F(n,e.staticDir):void 0,s=F(a,`.vercel/output`),c=F(s,`functions/api.func`);if(Ne(s,{recursive:!0,force:!0}),Me(c,{recursive:!0}),je(i,F(c,`server.mjs`)),Fe(F(c,`index.mjs`),Ji()),Fe(F(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!O(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);je(o,F(s,`static`),{recursive:!0})}let{crons:l,warnings:u}=ea(Qi(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:Xi(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};Fe(F(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${P(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 aa=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=j.resolve(e.cwd,`kick.config.ts`);if(!O(t))return null;let n=await l(e.cwd);if(!n?.assetMap)return null;let r=ue(n.assetMap,e.cwd);return r.count===0?null:be(r)}}),oa="/* 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 sa(e,t,n,r={}){if(e.length===0)return`${oa}
|
|
1680
1686
|
// (no routes discovered yet — annotate a controller method with
|
|
1681
1687
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1682
1688
|
declare global {
|
|
@@ -1714,16 +1720,16 @@ ${x}
|
|
|
1714
1720
|
${g}
|
|
1715
1721
|
`}function ca(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function la(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function ua(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 da(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=pa(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 fa(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(`
|
|
1716
1722
|
`)+`
|
|
1717
|
-
`}function pa(e,t,n){if(e===null)return`unknown`;let r=
|
|
1718
|
-
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 '${va}' resolved from this project.\n ${t}`)}async function xa(e){let t=
|
|
1723
|
+
`}function pa(e,t,n){if(e===null)return`unknown`;let r=M(n);if(e===``){let e=P(r,t).split(Le).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=M(t),a=F(i,e),o=P(r,a).split(Le).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function ma(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 ha=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:ga(e),cwd:e.cwd,envFile:_a(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=j.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return sa(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function ga(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function _a(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const va=`@typescript/typescript6`;function ya(e){return typeof e?.createProgram==`function`}function ba(e){if(ya(e.typescript))return{api:e.typescript,source:`typescript`};if(ya(e.ts6))return{api:e.ts6,source:va};let t=`Install it in the project:\n pnpm add -D ${va}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
1724
|
+
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 '${va}' resolved from this project.\n ${t}`)}async function xa(e){let t=Ae(N(e,`package.json`)),n=async e=>{try{return await import(I(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(va)]);return ba({typescript:Sa(r),ts6:Sa(i)}).api}function Sa(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Ca=Symbol(`kick/client: expansion budget exhausted`);var wa=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==Ca)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw Ca;return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`}if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
|
|
1719
1725
|
`){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===`
|
|
1720
1726
|
`?`
|
|
1721
|
-
`: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 Ta=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Ea=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Da(e){return
|
|
1722
|
-
`));for(let n of Ta){let r=
|
|
1723
|
-
`);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 Ma(e){return`_K${e}`}function Na(e,t){let n=`./`+
|
|
1727
|
+
`: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 Ta=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Ea=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Da(e){return Qe(`sha1`).update(e).digest(`hex`)}function Oa(e){let t=Qe(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
|
|
1728
|
+
`));for(let n of Ta){let r=N(e.projectDir,n);if(O(r))try{t.update(k(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Ea.test(n)){t.update(n);try{t.update(k(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function ka(e){try{let t=await xa(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(N(e.projectDir,`tsconfig.json`),{},n);return r?Oa({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 Aa(e){let t=await xa(e.compilerFrom??e.projectDir),n=N(M(e.routesFile),`__kick_client_probe__.ts`),r=Na(e.routesFile,e.keys),i=Ia(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.`);ja(t,i,e.routesFile);let s=Pa(t,i,o,e.keys),c=null,l=new wa(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===Ma(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function ja(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(`
|
|
1729
|
+
`);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 Ma(e){return`_K${e}`}function Na(e,t){let n=`./`+Ie(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Ma(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
1724
1730
|
`)+`
|
|
1725
|
-
`}function Pa(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(Ma(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Fa(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=
|
|
1726
|
-
`))}},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:[...Fa(o.fileNames,
|
|
1731
|
+
`}function Pa(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(Ma(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Fa(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=A(t).filter(e=>e.endsWith(`.ts`)).map(e=>N(t,e))}catch{}return[...new Set([...n,...r])]}function Ia(e,t,n,r){let i=N(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
1732
|
+
`))}},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:[...Fa(o.fileNames,M(n)),n],options:o.options,host:s})}const La=`/* eslint-disable */
|
|
1727
1733
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1728
1734
|
//
|
|
1729
1735
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -1768,7 +1774,7 @@ declare global {
|
|
|
1768
1774
|
}
|
|
1769
1775
|
|
|
1770
1776
|
export type { Api }
|
|
1771
|
-
`}const za=`kick/client
|
|
1777
|
+
`}const za=`kick/client`,$=`.kickjs/types/kick__client.d.ts`,Ba=`.kickjs/cache/client-map.sha1`,Va=(()=>{try{return Ae(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Ha(e){try{if(!O(e))return null;let[t,n]=k(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Ua(e){return`${Pn}${za} */\n\n${e}\n`}function Wa(e){try{return O(e)?k(e,`utf-8`):null}catch{return null}}async function Ga(e){let t=j.resolve(e.cwd,$);if(!O(t))return!1;try{await Ge(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 Ka(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function qa(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(O(j.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 Ja=()=>({id:za,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!qa(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:j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=Ka(e.config),a=await ka({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Va}),o=Ha(j.resolve(e.cwd,Ba)),s=Wa(j.resolve(e.cwd,$));if(a&&o&&s!==null&&o.inputs===a&&o.output===Da(s))return Sn()&&e.log.info?.(` kick/client: unchanged, keeping ${$}`),null;try{let t=Ra(await Aa({projectDir:e.cwd,routesFile:j.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(Ba,`${a} ${Da(Ua(t))}`),t}catch(t){let n=O(j.resolve(e.cwd,$)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):Sn()&&e.log.info?.(r),n&&await Ga(e),null}}});function Ya(e,t,n=`zod`){if(!e)return null;let r=M(t),i=P(r,e.filePath).split(Le).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
|
|
1772
1778
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1773
1779
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1774
1780
|
|
|
@@ -1806,5 +1812,5 @@ declare global {
|
|
|
1806
1812
|
}
|
|
1807
1813
|
|
|
1808
1814
|
export {}
|
|
1809
|
-
`}const Xa=()=>({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:Za(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=
|
|
1810
|
-
`)}});var uo=e({builtinCliPlugins:()=>fo});const fo=[_({name:`kick/init`,register:
|
|
1815
|
+
`}const Xa=()=>({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:Za(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=j.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Ya(n.env,i,r)}});function Za(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Qa(e){return e.config?.typegen?.envFile}function $a(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function eo(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function to(e){return{root:$a(e),cwd:e.cwd,envFile:eo(e)}}const no=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e)),n=j.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return me(t.classes,n,r)}}),ro=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e)),n=new Set(t.collisions.map(e=>e.className)),r=ve(t.classes,t.tokens,t.injects,n);return ye(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),io=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e));return ye(`ModuleToken`,fe(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),ao=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e));return pe(t.pluginsAndAdapters)}}),oo=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e));return t.contextKeys.length===0?null:Te(t.contextKeys)}}),so=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(to(e));return xe(t.routeFlags)}}),co={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},lo=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=co[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(`
|
|
1816
|
+
`)}});var uo=e({builtinCliPlugins:()=>fo});const fo=[_({name:`kick/init`,register:et}),_({name:`kick/generate`,register:Mn}),_({name:`kick/run`,register:Yn}),_({name:`kick/info`,register:er}),_({name:`kick/inspect`,register:ur}),_({name:`kick/add`,register:i}),_({name:`kick/list`,register:s}),_({name:`kick/explain`,register:yr}),_({name:`kick/mcp`,register:Ar}),_({name:`kick/tinker`,register:Pr}),_({name:`kick/remove`,register:Br}),_({name:`kick/typegen`,register:Ur}),_({name:`kick/check`,register:ci}),_({name:`kick/doctor`,register:Hi}),_({name:`kick/codemod`,register:Wi}),_({name:`kick/deploy`,register:ia}),_({name:`kick/registry`,typegens:[no()]}),_({name:`kick/services`,typegens:[ro()]}),_({name:`kick/modules`,typegens:[io()]}),_({name:`kick/plugins`,typegens:[ao()]}),_({name:`kick/context`,typegens:[oo()]}),_({name:`kick/route-flags`,typegens:[so()]}),_({name:`kick/assets`,typegens:[aa()]}),_({name:`kick/routes`,typegens:[ha()]}),_({name:`kick/client`,typegens:[Ja()]}),_({name:`kick/env`,typegens:[Xa()]}),_({name:`kick/runtime`,typegens:[lo()]})];export{Rn as n,fo as t};
|