@forinda/kickjs-cli 8.9.0 → 8.10.1
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/README.md +2 -0
- package/dist/{agent-docs-DUB-1Z6Q.mjs → agent-docs-TdQs75ND.mjs} +70 -21
- package/dist/agent-docs-TdQs75ND.mjs.map +1 -0
- package/dist/{agent-docs-bVMPt2m5.mjs → agent-docs-uEhHT_Tq.mjs} +72 -23
- package/dist/{build-C30mBgw6.mjs → build-D90mecBH.mjs} +3 -3
- package/dist/{build-C30mBgw6.mjs.map → build-D90mecBH.mjs.map} +1 -1
- package/dist/{build-xQXbdDpw.mjs → build-xfLqm9dd.mjs} +2 -2
- package/dist/{builtins-CtpLZ4FY.mjs → builtins-C3BQ79nW.mjs} +2 -2
- package/dist/{builtins-DiWfXc-D.mjs → builtins-CNJXXYW-.mjs} +149 -153
- package/dist/cli.mjs +2 -2
- package/dist/config-BV6rXylg.mjs +13 -0
- package/dist/config-BV6rXylg.mjs.map +1 -0
- package/dist/config-CVuSVUvw.mjs +12 -0
- package/dist/{doctor-CnsnRW7T.mjs → doctor-a-UkOZYd.mjs} +35 -40
- package/dist/doctor-a-UkOZYd.mjs.map +1 -0
- package/dist/fullstack-BlNhq-tI.mjs +100 -0
- package/dist/fullstack-BlNhq-tI.mjs.map +1 -0
- package/dist/fullstack-Zk31eUT1.mjs +99 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/package-manager-BUDLqU4F.mjs +12 -0
- package/dist/package-manager-BUDLqU4F.mjs.map +1 -0
- package/dist/package-manager-Bk2uiXkV.mjs +11 -0
- package/dist/{plugin-Bs0soxrU.mjs → plugin-DDENlsHw.mjs} +2 -2
- package/dist/{plugin-BfdvW6_r.mjs → plugin-FOqPjQ0u.mjs} +2 -2
- package/dist/project-BBiJ64ya.mjs +114 -0
- package/dist/project-fa9FRWXx.mjs +115 -0
- package/dist/project-fa9FRWXx.mjs.map +1 -0
- package/dist/{project-root-LYOxQHXp.mjs → project-root-BMpUTIbO.mjs} +2 -2
- package/dist/{project-root-B9BrO1na.mjs → project-root-BZ1wVwrr.mjs} +3 -3
- package/dist/{project-root-B9BrO1na.mjs.map → project-root-BZ1wVwrr.mjs.map} +1 -1
- package/dist/{prompts-BEAqcbPT.mjs → prompts-C4g1xbsv.mjs} +2 -2
- package/dist/{prompts-BEAqcbPT.mjs.map → prompts-C4g1xbsv.mjs.map} +1 -1
- package/dist/{rolldown-runtime-Da-NDvKz.mjs → rolldown-runtime-D8pytGn4.mjs} +1 -1
- package/dist/{run-plugins-0AfIgIsZ.mjs → run-plugins-CeZS2Opt.mjs} +107 -106
- package/dist/run-plugins-CeZS2Opt.mjs.map +1 -0
- package/dist/{typegen-BzgWveE_.mjs → typegen-Cj5lp0gl.mjs} +5 -5
- package/dist/{typegen-BzgWveE_.mjs.map → typegen-Cj5lp0gl.mjs.map} +1 -1
- package/dist/{typegen-up-UkaNc.mjs → typegen-D9opCn2d.mjs} +4 -4
- package/dist/{types-ChFFRT8E.mjs → types-BqvSIAQz.mjs} +1 -1
- package/package.json +6 -6
- package/templates/base/files/README.md +17 -15
- package/templates/base/files/kick.config.ts +1 -1
- package/templates/feature-storage/feature.json +13 -0
- package/templates/feature-storage/files/_dot_env.example.append +6 -0
- package/templates/feature-storage/files/_dot_gitignore.append +2 -0
- package/templates/feature-storage/files/src/storage.ts +16 -0
- package/templates/template-inertia/files/src/client/app.css +1 -1
- package/templates/template-inertia/files/vite.client.config.ts +1 -1
- package/dist/agent-docs-DUB-1Z6Q.mjs.map +0 -1
- package/dist/config-YvIngROH.mjs +0 -12
- package/dist/config-ZHuFjsKI.mjs +0 -13
- package/dist/config-ZHuFjsKI.mjs.map +0 -1
- package/dist/doctor-CnsnRW7T.mjs.map +0 -1
- package/dist/fs-Bm2St4gk.mjs +0 -11
- package/dist/fs-BvGbbHY0.mjs +0 -12
- package/dist/fs-BvGbbHY0.mjs.map +0 -1
- package/dist/fullstack-B0g06sSQ.mjs +0 -96
- package/dist/fullstack-B0g06sSQ.mjs.map +0 -1
- package/dist/fullstack-CZ9XQYk-.mjs +0 -95
- package/dist/project-B_qDdkYQ.mjs +0 -113
- package/dist/project-B_qDdkYQ.mjs.map +0 -1
- package/dist/project-Bp-KfBNb.mjs +0 -112
- package/dist/run-plugins-0AfIgIsZ.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v8.
|
|
2
|
+
* @forinda/kickjs-cli v8.10.1
|
|
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-Da-NDvKz.mjs";import{c as t,g as n,i as r,l as i,o as a,r as o,s,t as c}from"./project-Bp-KfBNb.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-YvIngROH.mjs";import{n as g,r as _}from"./plugin-BfdvW6_r.mjs";import{n as v,r as y,t as b}from"./fs-Bm2St4gk.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 oe,s as w,u as se}from"./agent-docs-bVMPt2m5.mjs";import{t as T}from"./project-root-LYOxQHXp.mjs";import{C as ce,S as le,_ as ue,a as de,b as fe,c as pe,d as me,f as he,g as ge,h as _e,i as ve,l as ye,m as be,o as xe,p as Se,r as Ce,s as we,t as Te,u as Ee,v as De,w as Oe,x as E,y as ke}from"./typegen-up-UkaNc.mjs";import{t as Ae}from"./build-xQXbdDpw.mjs";import{createRequire as je}from"node:module";import{cpSync as Me,existsSync as D,mkdirSync as Ne,readFileSync as O,readdirSync as k,rmSync as Pe,statSync as Fe,writeFileSync as A}from"node:fs";import j,{basename as Ie,dirname as M,join as N,relative as P,resolve as F,sep as I}from"node:path";import{fileURLToPath as Le,pathToFileURL as L}from"node:url";import{fork as Re,spawn as ze,spawnSync as Be}from"node:child_process";import{copyFile as Ve,mkdir as He,readFile as R,readdir as Ue,rm as We,stat as Ge,writeFile as z}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as Ke}from"node:crypto";import{parseSync as qe}from"oxc-parser";import Je from"pluralize";import{arch as Ye,platform as Xe,release as Ze}from"node:os";const Qe=[{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 $e(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-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 se({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=F(`.`),e=Ie(r)):r=F(t.directory||e),D(r)){let i=k(r);if(i.length>0){if(t.force)x.warn(`Clearing existing files in ${r}`);else if(n){x.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),w(`Aborted.`);return}else{x.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)x.message(` - ${e}`);if(i.length>5&&x.message(` ... and ${i.length-5} more`),!await oe({message:C.red(`Remove all existing files and proceed?`),initialValue:!1})){w(`Aborted.`);return}}for(let e of i)Pe(F(r,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`},{value:`inertia`,label:`Inertia`,hint:`server-driven React pages, one app, SSR`}]});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 i(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 se({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),f(l);let u=t.schema;a===`inertia`&&(u&&u!==`zod`&&x.warn(`The inertia template uses zod — ignoring --schema ${u}.`),u=`zod`),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:[...Qe],required:!1});let p;p=t.git===void 0?n?!0:await oe({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?n?!0:await oe({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).`),w(`Aborted.`);return}let{VITE_TEMPLATES:h,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-CZ9XQYk-.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(`, `)}.`),w(`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-CZ9XQYk-.mjs`);await t({name:e,directory:r,packageManager:s,initGit:p,installDeps:m,schemaLib:u,runtime:o,packages:d,frontend:_,viteTemplate:v}),w(`Done! Next steps: ${C.cyan(`cd ${e} && ${s}${s===`pnpm`?` dev`:` run dev:server`}`)}`)}else await c({name:e,directory:r,packageManager:s,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:d,schemaLib:u,runtime:o}),w(`Done! Next steps: ${C.cyan(`cd ${e} && ${s} dev`)}`)})}function B(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function V(e){let t=B(e);return t.charAt(0).toLowerCase()+t.slice(1)}function H(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function U(e){return Je.plural(e)}function et(e){return Je.plural(e)}function tt(e){return H(e).replace(/-/g,`_`)}function nt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??T(t),r=e.pluralize??!0,i=B(e.name),a=V(e.name),o=H(e.name),s=tt(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=U(o);c.pluralKebab=e,c.pluralPascal=B(e),c.pluralCamel=V(e)}return c}function rt(e,t){return F(e.cwd,t)}async function it(e){return import(L(e).href)}const at=/* @__PURE__ */ new Map;async function ot(e){let t=at.get(e);if(t)return t;let n=st(e);return at.set(e,n),n}async function st(e){let t=F(e,`package.json`);if(!D(t))return{generators:[],loaded:[],failed:[]};let n=ct(JSON.parse(await R(t,`utf-8`))),r=je(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 R(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(!D(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await it(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`});else{for(let t of u)lt(t)?i.push({source:e,spec:t}):o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});a.push(e)}}return{generators:i,loaded:a,failed:o}}function ct(e){let t=/* @__PURE__ */ 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 lt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function ut(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return pt(r.spec,r.source,e,n);let i=ft(await ot(n),e.generatorName);return i?pt(i.spec,i.source,e,n):null}async function dt(e,t=[]){let n=await ot(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 ft(e,t){return e.generators.find(e=>e.spec.name===t)}async function pt(e,t,n,r){let i=nt({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=rt(i,e.path);await y(t,e.content),o.push(t)}return{files:o,source:t}}function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const mt={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function ht(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function gt(e){return mt[e]??ht(e)}function _t(e){return`create${e}Repository`}function vt(e){return e??`define`}function yt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=_t(t),s=vt(a),c=`/**
|
|
11
|
+
import{t as e}from"./rolldown-runtime-D8pytGn4.mjs";import{c as t,g as n,i as r,o as i,r as a,s as o,t as s}from"./project-BBiJ64ya.mjs";import{a as c,c as l,d as u,i as d,l as f,o as p,s as m,u as h}from"./config-CVuSVUvw.mjs";import{n as g,r as _}from"./plugin-FOqPjQ0u.mjs";import{a as v,i as y,n as ee,o as b,t as x}from"./package-manager-Bk2uiXkV.mjs";import{a as S,c as C,d as te,f as w,i as ne,l as re,n as ie,o as ae,p as oe,r as se,s as T,u as ce}from"./agent-docs-uEhHT_Tq.mjs";import{t as E}from"./project-root-BMpUTIbO.mjs";import{C as le,S as ue,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,i as ye,l as be,m as xe,o as Se,p as Ce,r as we,s as Te,t as Ee,u as De,v as Oe,w as ke,x as D,y as Ae}from"./typegen-D9opCn2d.mjs";import{t as je}from"./build-xfLqm9dd.mjs";import{createRequire as Me}from"node:module";import{cpSync as Ne,existsSync as O,mkdirSync as Pe,readFileSync as k,readdirSync as A,rmSync as Fe,statSync as Ie,writeFileSync as j}from"node:fs";import M,{basename as Le,dirname as N,join as P,relative as F,resolve as I,sep as L}from"node:path";import{fileURLToPath as Re,pathToFileURL as R}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 z,readdir as We,rm as Ge,stat as Ke,writeFile as B}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as qe}from"node:crypto";import{parseSync as Je}from"oxc-parser";import Ye from"pluralize";import{arch as Xe,platform as Ze,release as Qe}from"node:os";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`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`}];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 | inertia`).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)=>{ne(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await ce({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=I(`.`),e=Le(r)):r=I(t.directory||e),O(r)){let i=A(r);if(i.length>0){if(t.force)S.warn(`Clearing existing files in ${r}`);else if(n){S.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),T(`Aborted.`);return}else{S.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)S.message(` - ${e}`);if(i.length>5&&S.message(` ... and ${i.length-5} more`),!await se({message:w.red(`Remove all existing files and proceed?`),initialValue:!1})){T(`Aborted.`);return}}for(let e of i)Fe(I(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await C({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`},{value:`inertia`,label:`Inertia`,hint:`server-driven React pages, one app, SSR`}]});let a=t.runtime;a||=n?`express`:await C({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 o=t.pm;o||=n?await ee(void 0):await C({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let c=t.repo;c||=n?`inmemory`:await ce({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),u(c);let l=t.schema;i===`inertia`&&(l&&l!==`zod`&&S.warn(`The inertia template uses zod — ignoring --schema ${l}.`),l=`zod`),l||=n?`zod`:await C({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(l)||(S.warn(`Unknown --schema "${l}", falling back to zod.`),l=`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 ae({message:`Select packages to include`,options:[...$e],required:!1});let f;f=t.git===void 0?n?!0:await se({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;if(p=t.install===void 0?n?!0:await se({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){S.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),T(`Aborted.`);return}let{VITE_TEMPLATES:m,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-Zk31eUT1.mjs`);if(t.viteTemplate!==void 0&&!m.some(e=>e.value===t.viteTemplate)){S.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${m.map(e=>e.value).join(`, `)}.`),T(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(i===`fullstack`&&!t.frontend&&!n&&(_=await C({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 C({message:`create-vite template`,options:m.map(e=>({value:e.value,label:e.label})),initialValue:g})),i===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-Zk31eUT1.mjs`);await t({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,schemaLib:l,runtime:a,packages:d,frontend:_,viteTemplate:v}),T(`Done! Next steps: ${w.cyan(`cd ${e} && ${o}${o===`pnpm`?` dev`:` run dev:server`}`)}`)}else await s({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,template:i,defaultRepo:c,packages:d,schemaLib:l,runtime:a}),T(`Done! Next steps: ${w.cyan(`cd ${e} && ${h(o,`dev`)}`)}`)})}function V(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function H(e){let t=V(e);return t.charAt(0).toLowerCase()+t.slice(1)}function U(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function W(e){return Ye.plural(e)}function tt(e){return Ye.plural(e)}function nt(e){return U(e).replace(/-/g,`_`)}function rt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??E(t),r=e.pluralize??!0,i=V(e.name),a=H(e.name),o=U(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=W(o);c.pluralKebab=e,c.pluralPascal=V(e),c.pluralCamel=H(e)}return c}function it(e,t){return I(e.cwd,t)}async function at(e){return import(R(e).href)}const ot=/* @__PURE__ */ 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=I(e,`package.json`);if(!O(t))return{generators:[],loaded:[],failed:[]};let n=lt(JSON.parse(await z(t,`utf-8`))),r=Me(I(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 z(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=I(N(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`});else{for(let t of u)ut(t)?i.push({source:e,spec:t}):o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});a.push(e)}}return{generators:i,loaded:a,failed:o}}function lt(e){let t=/* @__PURE__ */ 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 b(t,e.content),o.push(t)}return{files:o,source:t}}function G(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-Da-NDvKz.mjs";import{c as t,g as n,i 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 ${i===`inmemory`?`a database`:
|
|
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, { error: '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=U(t),d=V(t),f=c?W(u):u,p=c?tt(d):d,m=P(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=P(m,e);s?h.push(n):!g&&await y(n)&&!await se({message:`File exists: ${w.dim(e)}. Overwrite?`,initialValue:!1})?S.warn(`Skipped: ${e}`):(await b(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=P(e,`index.ts`),o=await y(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,11 @@ export const modules: AppModuleEntry[] = [${c}]
|
|
|
548
548
|
import { ${t}Module } from '${s}'
|
|
549
549
|
|
|
550
550
|
export const modules = defineModules().mount(${c})
|
|
551
|
-
`;await
|
|
551
|
+
`;await b(a,e);return}let l=await z(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=G(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${G(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${G(t)}Module\\b`).test(e)||(l=Rt(l,c))}else l=Rt(l,c);await B(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++}else{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++}else{if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}}return-1}function Wt(e,t,n,r){return`/**
|
|
556
556
|
* Snapshot for the DevTools topology view (\`/_debug\`).
|
|
557
557
|
*
|
|
558
558
|
* Must be CHEAP — the topology endpoint polls on a short interval, so
|
|
@@ -578,7 +578,7 @@ export const modules = defineModules().mount(${c})
|
|
|
578
578
|
* an iframe, buttons that run server code, or a browser module.
|
|
579
579
|
*
|
|
580
580
|
* Uncomment with: import { defineDevtoolsTab } from '@forinda/kickjs-devtools-kit'
|
|
581
|
-
* and add
|
|
581
|
+
* and add \`@forinda/kickjs-devtools-kit\` to the dependencies.
|
|
582
582
|
* (\`@forinda/kickjs\` deliberately does not depend on it.)
|
|
583
583
|
* Delete this hook unless the ${n} ships a panel.
|
|
584
584
|
*/
|
|
@@ -592,7 +592,7 @@ export const modules = defineModules().mount(${c})
|
|
|
592
592
|
// ]
|
|
593
593
|
// },`.split(`
|
|
594
594
|
`).map(e=>r+e).join(`
|
|
595
|
-
`)}async function
|
|
595
|
+
`)}async function Gt(e){let{name:t,outDir:n}=e,r=U(t),i=V(t),a=[],o=P(n,`${r}.adapter.ts`);return await b(o,`import {
|
|
596
596
|
defineAdapter,
|
|
597
597
|
type AdapterContext,
|
|
598
598
|
type AdapterMiddleware,
|
|
@@ -797,11 +797,11 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
|
797
797
|
return { name: '${r}', status: 'up' }
|
|
798
798
|
},
|
|
799
799
|
|
|
800
|
-
${
|
|
800
|
+
${Wt(r,i,`adapter`,` `)}
|
|
801
801
|
}
|
|
802
802
|
},
|
|
803
803
|
})
|
|
804
|
-
`),a.push(o),a}async function
|
|
804
|
+
`),a.push(o),a}async function Kt(e){let{name:t,outDir:n}=e,r=U(t),i=V(t),a=[],o=P(n,`${r}.plugin.ts`);return await b(o,`import {
|
|
805
805
|
definePlugin,
|
|
806
806
|
type AppAdapter,
|
|
807
807
|
type AppModuleEntry,
|
|
@@ -958,13 +958,13 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
958
958
|
// Example: await this.connection?.close()
|
|
959
959
|
},
|
|
960
960
|
|
|
961
|
-
${
|
|
961
|
+
${Wt(r,i,`plugin`,` `)}
|
|
962
962
|
}),
|
|
963
963
|
})
|
|
964
|
-
`),a.push(o),a}const
|
|
965
|
-
// \`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 Jt(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return I(n);if(r){let e=qt,n=U(r),a=o?W(n):n,s=e[t]??``,c=P(i,a);return I(s?P(c,s):c)}return I(a)}async function Yt(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=Jt({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),c=U(t),l=H(t),u=[],d=P(s,`${c}.middleware.ts`);return await b(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
|
|
966
966
|
|
|
967
|
-
export interface ${
|
|
967
|
+
export interface ${V(t)}Options {
|
|
968
968
|
// Add configuration options here. The factory below closes over the
|
|
969
969
|
// resolved options object; pass them at the call site —
|
|
970
970
|
// \`${l}({ foo: 'bar' })\` — and the closure preserves them across
|
|
@@ -972,7 +972,7 @@ export interface ${B(t)}Options {
|
|
|
972
972
|
}
|
|
973
973
|
|
|
974
974
|
/**
|
|
975
|
-
* ${
|
|
975
|
+
* ${V(t)} middleware.
|
|
976
976
|
*
|
|
977
977
|
* Usage in bootstrap (fires on every request):
|
|
978
978
|
* middlewares: [${l}()]
|
|
@@ -1008,7 +1008,7 @@ export interface ${B(t)}Options {
|
|
|
1008
1008
|
* first \`next()\` throws \`TypeError: next is not a function\`. Generate a
|
|
1009
1009
|
* guard instead (\`kick g guard\`) for the per-route, ctx-style shape.
|
|
1010
1010
|
*/
|
|
1011
|
-
export function ${l}(options: ${
|
|
1011
|
+
export function ${l}(options: ${V(t)}Options = {}) {
|
|
1012
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
|
|
1013
1013
|
// on every engine, but ${o} dependency to import types from. Under Fastify the handler
|
|
1014
1014
|
// receives \`request.raw\` / a reply driver, and under h3 the node objects, so
|
|
@@ -1021,7 +1021,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
|
|
|
1021
1021
|
next()
|
|
1022
1022
|
}
|
|
1023
1023
|
}
|
|
1024
|
-
`),u.push(d),u}async function
|
|
1024
|
+
`),u.push(d),u}async function Xt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Jt({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=U(t),s=H(t),c=V(t),l=[],u=P(a,`${o}.guard.ts`);return await b(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
1025
1025
|
import type { RequestContext } from '@forinda/kickjs'
|
|
1026
1026
|
|
|
1027
1027
|
/**
|
|
@@ -1061,7 +1061,7 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
1061
1061
|
ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
|
|
1062
1062
|
}
|
|
1063
1063
|
}
|
|
1064
|
-
`),l.push(u),l}function
|
|
1064
|
+
`),l.push(u),l}function Zt(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 Qt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=U(t),s=V(t),c=e.key??H(t),l=Array.isArray(e.params)?e.params:Zt(e.params),u=Jt({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(`
|
|
1065
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.
|
|
1066
1066
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
1067
1067
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
@@ -1112,7 +1112,7 @@ ${_}
|
|
|
1112
1112
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1113
1113
|
},
|
|
1114
1114
|
})
|
|
1115
|
-
`,
|
|
1115
|
+
`,y=P(u,`${o}.contributor.ts`);return await b(y,v),[y]}async function $t(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Jt({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=U(t),s=V(t),c=[],l=P(a,`${o}.service.ts`);return await b(l,`import { Service } from '@forinda/kickjs'
|
|
1116
1116
|
|
|
1117
1117
|
@Service()
|
|
1118
1118
|
export class ${s}Service {
|
|
@@ -1121,7 +1121,7 @@ export class ${s}Service {
|
|
|
1121
1121
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1122
1122
|
// ) {}
|
|
1123
1123
|
}
|
|
1124
|
-
`),c.push(l),c}async function
|
|
1124
|
+
`),c.push(l),c}async function en(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Jt({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=U(t),s=V(t),c=[],l=P(a,`${o}.controller.ts`);return await b(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
1125
1125
|
|
|
1126
1126
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1127
1127
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
@@ -1163,13 +1163,13 @@ export class ${s}Controller {
|
|
|
1163
1163
|
return reply.noContent()
|
|
1164
1164
|
}
|
|
1165
1165
|
}
|
|
1166
|
-
`),c.push(l),c}async function
|
|
1166
|
+
`),c.push(l),c}async function tn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Jt({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=U(t),s=V(t),c=H(t),l=e.schemaLib??`zod`,u=Ct[l],d=[],f=P(a,`${o}.dto.ts`);return await b(f,`${u.import}
|
|
1167
1167
|
|
|
1168
|
-
export const ${c}Schema = ${
|
|
1168
|
+
export const ${c}Schema = ${wt(l,`// Define your schema fields here\n name: ${u.required}`)}
|
|
1169
1169
|
|
|
1170
1170
|
export type ${s}DTO = ${u.infer(`${c}Schema`)}
|
|
1171
|
-
`),d.push(f),d}async function
|
|
1172
|
-
Skipped — existing kick.config.ts preserved.`),[]):(await
|
|
1171
|
+
`),d.push(f),d}async function nn(e){let t=P(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return O(t)&&!e.force&&!await se({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
1172
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await b(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1173
1173
|
|
|
1174
1174
|
export default defineConfig({
|
|
1175
1175
|
modules: {
|
|
@@ -1187,7 +1187,7 @@ export default defineConfig({
|
|
|
1187
1187
|
{
|
|
1188
1188
|
name: 'test',
|
|
1189
1189
|
description: 'Run tests with Vitest',
|
|
1190
|
-
steps: 'vitest run',
|
|
1190
|
+
steps: 'vitest run --passWithNoTests',
|
|
1191
1191
|
},
|
|
1192
1192
|
{
|
|
1193
1193
|
name: 'lint',
|
|
@@ -1212,18 +1212,18 @@ export default defineConfig({
|
|
|
1212
1212
|
},
|
|
1213
1213
|
],
|
|
1214
1214
|
})
|
|
1215
|
-
`),[t])}function
|
|
1215
|
+
`),[t])}function rn(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 an(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=rn(e,r);return i===-1?null:e.slice(r+1,i)}function on(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
1216
1216
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1217
|
-
`)}function
|
|
1217
|
+
`)}function sn(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 cn(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 ln(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=rn(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=an(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=an(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=an(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=sn(s),p=``;return l&&(p+=` register(container) {${on(l,4,6)} },\n\n`),u&&(p+=` contributors() {${on(u,4,6)} },\n\n`),p+=` routes() {${on(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
1218
1218
|
name: '${r}',
|
|
1219
1219
|
build: () => ({
|
|
1220
1220
|
${p}
|
|
1221
1221
|
}),
|
|
1222
|
-
})`}${c}`}}function
|
|
1223
|
-
`||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=
|
|
1222
|
+
})`}${c}`}}function un(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=rn(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]===`
|
|
1223
|
+
`||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=rn(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=an(m,/register\s*\(([^)]*)\)\s*\{/),g=an(m,/contributors\s*\(\s*\)\s*\{/),_=an(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=cn(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${on(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${on(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${on(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
1224
1224
|
${y}
|
|
1225
1225
|
}
|
|
1226
|
-
`}${u}`}}function
|
|
1226
|
+
`}${u}`}}function dn(e,t){return t===`class`?un(e):ln(e)}function fn(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 pn(e){let t=[];return await n(I(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=P(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 mn(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=P(e,a),o=P(t,a),s;try{s=await Ke(i)}catch{continue}s.isDirectory()?await r(i,o):(await He(i,o),n++)}}}function hn(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return P(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function gn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await pn(e),s=await z(P(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=hn(r),await mn(e,c));let l=[];for(let e of o){let t=dn(await z(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await B(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=P(e,`index.ts`),d=null;try{d=await z(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=fn(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await B(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function _n(e,t){let n=await pn(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 z(e,`utf-8`);i.test(t)&&r.push(e)}return r}const vn={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.iso.datetime()`},email:{ts:`string`,zod:`z.email()`},url:{ts:`string`,zod:`z.url()`},uuid:{ts:`string`,zod:`z.uuid()`},json:{ts:`any`,zod:`z.any()`}};function yn(e){let t=e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=vn[a];if(!o){let e=[...Object.keys(vn),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}}),n=/* @__PURE__ */ new Set;for(let{name:e}of t){if(n.has(e))throw Error(`Duplicate field: "${e}". Each field name may appear once.`);n.add(e)}return t}async function bn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=U(t),l=V(t),u=s?W(c):c,d=s?tt(l):l,f=P(r,u),p=[],m=async(e,t)=>{let n=P(f,e);await b(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`,xn(l,n)),await m(`dtos/update-${c}.dto.ts`,Sn(l,n)),await m(`dtos/${c}-response.dto.ts`,Cn(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 xn(e,t){return`import { z } from 'zod'
|
|
1227
1227
|
|
|
1228
1228
|
export const create${e}Schema = z.object({
|
|
1229
1229
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1231,7 +1231,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
1231
1231
|
})
|
|
1232
1232
|
|
|
1233
1233
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
1234
|
-
`}function
|
|
1234
|
+
`}function Sn(e,t){return`import { z } from 'zod'
|
|
1235
1235
|
|
|
1236
1236
|
export const update${e}Schema = z.object({
|
|
1237
1237
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -1239,14 +1239,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
1239
1239
|
})
|
|
1240
1240
|
|
|
1241
1241
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
1242
|
-
`}function
|
|
1242
|
+
`}function Cn(e,t){return`export interface ${e}ResponseDTO {
|
|
1243
1243
|
id: string
|
|
1244
1244
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
1245
1245
|
`)}
|
|
1246
1246
|
createdAt: string
|
|
1247
1247
|
updatedAt: string
|
|
1248
1248
|
}
|
|
1249
|
-
`}async function
|
|
1249
|
+
`}async function wn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=U(t),o=V(t),s=[],c;if(e.outDir)c=I(e.outDir);else if(n){let e=U(n),t=i?W(e):e;c=I(P(r??`src/modules`,t,`__tests__`))}else c=I(`src/__tests__`);let l=P(c,`${a}.test.ts`);return await b(l,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
1250
1250
|
import { Container } from '@forinda/kickjs'
|
|
1251
1251
|
|
|
1252
1252
|
describe('${o}', () => {
|
|
@@ -1269,58 +1269,53 @@ describe('${o}', () => {
|
|
|
1269
1269
|
expect(true).toBe(true)
|
|
1270
1270
|
})
|
|
1271
1271
|
})
|
|
1272
|
-
`),s.push(l),s}function
|
|
1273
|
-
`);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
|
|
1274
|
-
(dry run — no files were written)`),console.log()}async function
|
|
1275
|
-
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),
|
|
1272
|
+
`),s.push(l),s}function Tn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var En=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
1273
|
+
`);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 Dn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function K(e){return e.parent?.opts()?.dryRun??!1}function q(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(`
|
|
1274
|
+
(dry run — no files were written)`),console.log()}async function On(e){if(!e)try{let e=await p(process.cwd());await Ee({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 kn=[{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`}],An=/* @__PURE__ */ new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
1275
|
+
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),jn=/* @__PURE__ */ new Set([...kn.map(e=>e.name.split(` `)[0]),...An.keys()]);async function Mn(){console.log(`
|
|
1276
1276
|
Built-in generators:
|
|
1277
|
-
`);let e=Math.max(...
|
|
1277
|
+
`);let e=Math.max(...kn.map(e=>e.name.length));for(let t of kn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await p(process.cwd()),n=g(t?.plugins??[],t?.commands??[]),r=await ft(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1278
1278
|
Plugin generators:
|
|
1279
1279
|
`);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(`
|
|
1280
1280
|
Failed to load:
|
|
1281
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function
|
|
1282
|
-
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=
|
|
1283
|
-
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=
|
|
1281
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function Nn(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 Pn(e,t,n){let r=await p(process.cwd()),i=m(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Ft(i.repo);t.repo&&u(t.repo);let s=t.pattern??r?.pattern??`rest`,h=t.pluralize===!1?!1:i.pluralize??!0,g=f(r,process.cwd()),_=c(E()),v=l(E()),y=E(),ee=d(y,`@forinda/kickjs-testing`,`any`)&&d(y,`supertest`,`any`),b=i.style??`define`;if(!n&&b===`define`){let e=await _n(I(a),`define`);if(e.length>0){console.error(`\n ${w.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${w.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${w.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 ${w.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${w.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${w.dim(`// kick.config.ts`)}\n ${w.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let x=[];for(let r of e){let e=await It({name:r,modulesDir:I(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:ee,dryRun:n,pluralize:h,tokenScope:g,swagger:_,schemaLib:v,style:i.style});x.push(...e)}q(x,n),await On(n)}function Fn(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 Mn();return}if(!e||e.length===0){n.help();return}let a=K(i);v(a);let[o,s,...c]=e;if(o){let e=await p(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){q(i.files,a);return}if(o!==`module`&&jn.has(o)){let e=An.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 Pn(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=K(n);v(r),await Pn(e,Nn(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=K(n);v(r),q(await Gt({name:e,outDir:I(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=K(n);v(r),q(await Kt({name:e,outDir:I(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
1282
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await Yt({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.)
|
|
1283
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await Xt({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)
|
|
1284
1284
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1285
1285
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1286
|
-
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=
|
|
1287
|
-
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=
|
|
1288
|
-
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=
|
|
1289
|
-
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=
|
|
1290
|
-
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=
|
|
1286
|
+
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=K(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 p(process.cwd()),o=m(a),s=o.dir??`src/modules`;q(await Qt({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
|
|
1287
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await $t({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
|
|
1288
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await en({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await On(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
|
|
1289
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await tn({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,schemaLib:l(E())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
1290
|
+
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=K(n);v(r);let i=await p(process.cwd()),a=m(i),o=a.dir??`src/modules`;q(await wn({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
|
|
1291
1291
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1292
1292
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1293
1293
|
Optional: append :optional (shell-safe): description:text:optional
|
|
1294
|
-
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=
|
|
1294
|
+
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=Nn(r,n),a=K(r);v(a),t.length===0&&(console.error(`
|
|
1295
1295
|
Error: At least one field is required.
|
|
1296
1296
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1297
1297
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1298
1298
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1299
|
-
`),process.exit(1));let o=await
|
|
1300
|
-
`,u=``;
|
|
1299
|
+
`),process.exit(1));let o=await p(process.cwd()),s=m(o),l=i.modulesDir??s.dir??`src/modules`,u=yn(t),d=f(o,process.cwd()),h=c(E()),g=await bn({name:e,fields:u,modulesDir:I(l),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:i.pluralize===!1?!1:s.pluralize??!0,tokenScope:d,swagger:h,style:s.style});console.log(`\n Scaffolded ${e} with ${u.length} field(s):`);for(let e of u)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);q(g,a),await On(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=K(t);v(n),q(await nn({outDir:I(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (default: detected from kick.config, packageManager, or the lockfile)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=K(t);v(n);let r=e.only??`all`;Dn.includes(r)?q(await ie({outDir:I(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${Dn.join(` | `)}`),process.exitCode=1)});for(let e of t?.generators??[])In(n,e,t?.projectRoot)}function In(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=K(o);v(s);let c=await dt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&q(c.files,s)})}const Ln=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Rn(e){let t=M.resolve(e.cwd,`.kickjs/types`);e.check||await Ue(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??ve,i=M.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(R(e).href)},async writeFile(t,n){let r=M.resolve(e.cwd,t);await Ue(M.dirname(r),{recursive:!0}),await B(r,n,`utf8`)},getScanResult:e=>{let t=zn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?_e(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=M.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=`${Ln}${n.id} */\n\n`+a+`
|
|
1300
|
+
`,u=``;O(i)&&(u=await z(i,`utf8`)),u===l?s.push({id:n.id,status:`unchanged`,outFile:i}):e.check?(c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i})):(await B(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new En(c);return s}function zn(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 Bn(e,t){let n=new Set(t),r=[],i=[],a=/* @__PURE__ */ new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var Vn=/* @__PURE__ */ e({applyDisableFilter:()=>Bn,runAllPluginTypegens:()=>Hn});async function Hn(e){let t=[...Po,...e.config?.plugins??[]],{enabled:n,skipped:r,unknown:i}=Bn(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 Rn({cwd:e.cwd,config:e.config??{},plugins:n,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Tn())for(let e of t)console.log(` ${e.id}: ${e.status}`);return t}catch(t){if(t instanceof En||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 Un(e){let t=/* @__PURE__ */ 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)}}}const Wn=`__kickjs_typegen_owner`;function Gn(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-D9opCn2d.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Vn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-D9opCn2d.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-xfLqm9dd.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=M.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=>M.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=Un(e.emitWarning),m=null,h=!1,g=/* @__PURE__ */ new Set,_=/* @__PURE__ */ new Set,v=!1,y=!1;function ee(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 b(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,ee(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(b,r)}},runOnce(){h||ee(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function Kn(e){let t=process.platform===`win32`;for(let n of qn(e))for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=t?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=P(n,i);if(O(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function qn(e){let t=I(e),n=Jn(t);return(n?[t,n]:[t]).map(e=>P(e,`node_modules`,`.bin`))}function Jn(e){for(let t=N(e);t!==N(t);t=N(t)){let n=P(t,`pnpm-workspace.yaml`),r=P(t,`package.json`);if(O(n)||O(r))return Yn(n,r).some(n=>Xn(n,F(t,e)))?t:void 0}}function Yn(e,t){try{if(O(e)){let t=k(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
|
|
1301
|
+
`)){if(!e.trim()||e.trim().startsWith(`#`))continue;let t=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*$/.exec(e);if(!t)break;n.push(t[1])}return n}let{workspaces:n}=JSON.parse(k(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function Xn(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(L).join(`/`))}function Zn(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 Qn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1301
1302
|
`):`${n.slice(0,t).join(`
|
|
1302
|
-
`)}\n… ${n.length-t} more line(s)`}function
|
|
1303
|
+
`)}\n… ${n.length-t} more line(s)`}function $n(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function er(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 tr(e,t,n={}){t&&(process.env.PORT=t);let r=$n(n.polling),i=process.cwd(),a=await p(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ee({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=I(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await Hn({cwd:i,config:a});await ye(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(I(`package.json`)).resolve(`vite`),{createServer:d}=await import(R(u).href);globalThis[Wn]=`kick-dev`;let f=await d({configFile:I(`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=Kn(i);e?h=Zn({cwd:i,bin:e,onResult:e=>{f.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?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(Qn(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 _=Gn({cwd:i,config:a,emitWarning:e=>{console.warn(e),f.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>h?.schedule()});f.watcher.on(`add`,e=>_.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>_.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>_.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>_.handleWatchEvent(`unlinkDir`,e)),_.assetSrcRoots.length>0&&f.watcher.add([..._.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
|
|
1303
1304
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1304
|
-
`),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
|
|
1305
|
-
Error: vite is not installed.
|
|
1306
|
-
Run: pnpm add -D vite unplugin-swc
|
|
1307
|
-
`):console.error(`
|
|
1305
|
+
`),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 f.close(),process.exit(0)}};process.on(`SIGINT`,y),process.on(`SIGTERM`,y),process.on(`SIGBREAK`,y)}async function nr(e){let t=await p(e);try{await Ee({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=I(e,t?.typegen?.outDir??`.kickjs/types`),r=await Hn({cwd:e,config:t});await ye(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 rr(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 tr(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`\n Error: vite is not installed.\n Run: ${x()} add -D vite unplugin-swc\n`):console.error(`
|
|
1308
1306
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1309
1307
|
Building for production...
|
|
1310
|
-
`);let{createRequire:e}=await import(`node:module`),t=e(
|
|
1311
|
-
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
1312
|
-
Building asset map...`);try{await
|
|
1308
|
+
`);let{createRequire:e}=await import(`node:module`),t=e(I(`package.json`)).resolve(`vite`),{build:n}=await import(R(t).href);await n({configFile:I(`vite.config.ts`)});let r=await p(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
|
|
1309
|
+
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?P(`dist`,e):e.dest??P(`dist`,t),r=I(t),i=I(n);O(r)?(Pe(i,{recursive:!0}),Ne(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)):console.log(` ⚠ Skipped ${t} (not found)`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
|
|
1310
|
+
Building asset map...`);try{await je(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1313
1311
|
Build complete.
|
|
1314
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
1315
|
-
Building asset map...`);try{await
|
|
1312
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await p(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0)console.log(` No assetMap entries — nothing to build.`);else{console.log(`
|
|
1313
|
+
Building asset map...`);try{await je(e,{cwd:process.cwd()}),console.log(`
|
|
1316
1314
|
Asset build complete.
|
|
1317
|
-
`)}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)),n(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=
|
|
1318
|
-
No type-checker found. Install one in this project:
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
`),process.exit(1);return}let r=Be(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(`
|
|
1322
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Xn(){try{let e=M(Le(import.meta.url));return JSON.parse(O(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(!D(t))return[];let n;try{n=JSON.parse(O(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(D(i))try{n=JSON.parse(O(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(D(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(`
|
|
1323
|
-
`))})}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
|
|
1315
|
+
`)}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)),n(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=I(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await nr(t);let n=Kn(t);if(!n){console.error(`
|
|
1316
|
+
No type-checker found. Install one in this project:\n ${x(t)} add -D typescript (tsc)\n ${x(t)} add -D @typescript/native-preview (tsgo, faster)\n`),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 er(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 tr(e.entry,e.port)}catch(e){console.error(`
|
|
1317
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function ir(){try{let e=N(Re(import.meta.url));return JSON.parse(k(P(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const ar=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function or(e){let t=P(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=P(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:ar.has(t)}})}function sr(e){let t=e;for(;;){if(O(P(t,`package.json`)))return t;let e=N(t);if(e===t)return null;t=e}}function cr(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${ir()}`,``,` System:`,` OS: ${Ze()} ${Qe()} (${Xe()})`,` Node: ${process.version}`],t=sr(process.cwd()),n=t?or(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(`
|
|
1318
|
+
`))})}const{bold:J,dim:Y,green:lr,red:ur,yellow:dr,blue:fr}=w;function pr(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 mr(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function hr(e,t){try{return await mr(`${e}${t}`)}catch{return null}}async function gr(e){let[t,n,r,i,a]=await Promise.all([hr(e,`/health`),hr(e,`/metrics`),hr(e,`/routes`),hr(e,`/container`),hr(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function _r(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=Y(`─`.repeat(60));if(console.log(),console.log(J(` KickJS Inspector`)+Y(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?lr(`● healthy`):ur(`● `+n.status);console.log(` ${J(`Health:`)} ${e}`)}else console.log(` ${J(`Health:`)} ${ur(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?ur:r.errorRate>0?dr:lr;console.log(` ${J(`Uptime:`)} ${pr(r.uptimeSeconds)}`),console.log(` ${J(`Requests:`)} ${r.requests}`),console.log(` ${J(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${Y(`(`)}${t(e+`%`)}${Y(`)`)}`)}if(a&&console.log(` ${J(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${J(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(J(` Routes`)),console.log(s),console.log(` ${Y(`METHOD`)} ${Y(`PATH`.padEnd(36))} ${Y(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${te(e.method)} ${t} ${fr(e.controller)}.${Y(e.handler)}`)}}console.log(s),console.log()}function vr(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 gr(r);t.json?console.log(JSON.stringify(e,null,2)):_r(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(ur(` ✖ Could not connect to ${n}`)),console.error(Y(` ${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 X(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Z(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const yr=[{match(e,t){let n=X(e,[`config`,`get`])&&Z(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Z(e,[`undefined`,`is not defined`]);return!n&&!r?null:Z(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
|
|
1324
1319
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
1325
1320
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
1326
1321
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -1344,7 +1339,7 @@ import { modules } from './modules'
|
|
|
1344
1339
|
import './config' // ← add this — registers env schema
|
|
1345
1340
|
import { bootstrap } from '@forinda/kickjs'
|
|
1346
1341
|
import { modules } from './modules'
|
|
1347
|
-
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=
|
|
1342
|
+
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Z(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return Z(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.
|
|
1348
1343
|
When vitest re-imports your modules across tests, the same class can be
|
|
1349
1344
|
registered twice and the container throws. The fix is to wipe the
|
|
1350
1345
|
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'
|
|
@@ -1354,7 +1349,7 @@ describe('UserController', () => {
|
|
|
1354
1349
|
beforeEach(() => Container.reset())
|
|
1355
1350
|
|
|
1356
1351
|
it('does the thing', async () => { /* ... */ })
|
|
1357
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
1352
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||X(e,[`Module`,`is not a function`])||X(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
|
|
1358
1353
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
1359
1354
|
returns the controller wiring. This was a deliberate choice — modules
|
|
1360
1355
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -1381,7 +1376,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
1381
1376
|
and matches the actual class names so refactors propagate via
|
|
1382
1377
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
1383
1378
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
1384
|
-
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=
|
|
1379
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=Z(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Z(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
|
|
1385
1380
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
1386
1381
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
1387
1382
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -1389,7 +1384,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
1389
1384
|
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({
|
|
1390
1385
|
modules,
|
|
1391
1386
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
1392
|
-
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return
|
|
1387
|
+
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return Z(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
|
|
1393
1388
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
1394
1389
|
before any decorator runs. Most projects do this at the top of
|
|
1395
1390
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -1398,7 +1393,7 @@ import './config'
|
|
|
1398
1393
|
import { bootstrap } from '@forinda/kickjs'
|
|
1399
1394
|
import { modules } from './modules'
|
|
1400
1395
|
|
|
1401
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return
|
|
1396
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return Z(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
|
|
1402
1397
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
1403
1398
|
the most likely cause is that the module is missing from the exported
|
|
1404
1399
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -1406,7 +1401,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
1406
1401
|
import { UserModule } from './users/user.module'
|
|
1407
1402
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1408
1403
|
|
|
1409
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!
|
|
1404
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!Z(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=Z(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=Z(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&Z(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\`.
|
|
1410
1405
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
1411
1406
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
1412
1407
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -1440,7 +1435,7 @@ beforeAll(() => {
|
|
|
1440
1435
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
1441
1436
|
resetEnvCache()
|
|
1442
1437
|
loadEnv(envSchema)
|
|
1443
|
-
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=
|
|
1438
|
+
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=X(e,[`cannot inject`,`request-scoped`,`singleton`]),r=X(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
|
|
1444
1439
|
the first time the container resolves it. A REQUEST-scoped binding is the
|
|
1445
1440
|
opposite — one instance per request, discarded when the response ends.
|
|
1446
1441
|
|
|
@@ -1461,7 +1456,7 @@ and the singleton never captures one.
|
|
|
1461
1456
|
|
|
1462
1457
|
If the dependency did not need request scope in the first place, the
|
|
1463
1458
|
other direction also works — make it SINGLETON and pass the per-request
|
|
1464
|
-
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=
|
|
1459
|
+
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=X(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
|
|
1465
1460
|
is requested while it is already being resolved further up the stack, the
|
|
1466
1461
|
graph has a cycle and there is no order that satisfies both ends.
|
|
1467
1462
|
|
|
@@ -1493,7 +1488,7 @@ export class OrderService {
|
|
|
1493
1488
|
@Service()
|
|
1494
1489
|
export class BillingService {
|
|
1495
1490
|
@Autowired() private readonly orders!: OrderService // ← resolved after construction
|
|
1496
|
-
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=
|
|
1491
|
+
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=Z(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 —
|
|
1497
1492
|
and a class is only loaded if something imports it. A module that is not
|
|
1498
1493
|
in the bootstrap array is never imported, so none of its @Service /
|
|
1499
1494
|
@Repository / @Controller classes ever register, and the first thing that
|
|
@@ -1519,7 +1514,7 @@ export const TenantModule = defineModule({
|
|
|
1519
1514
|
},
|
|
1520
1515
|
routes: () => null,
|
|
1521
1516
|
}),
|
|
1522
|
-
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!
|
|
1517
|
+
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!Z(e,[`vite`,`kick dev`,`dev server`,`localhost:5173`,`:5173`])||!Z(e,[`404`,`not found`,`cannot get`,`cannot post`,`no route`]))return null;let n=X(e,[`app`,`export`]),r=Z(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
|
|
1523
1518
|
and reads \`app\` off it, then hands each request to that instance.
|
|
1524
1519
|
|
|
1525
1520
|
When the entry runs \`await bootstrap(...)\` without assigning the result to
|
|
@@ -1535,24 +1530,23 @@ import { bootstrap } from '@forinda/kickjs'
|
|
|
1535
1530
|
await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
|
|
1536
1531
|
import { bootstrap } from '@forinda/kickjs'
|
|
1537
1532
|
|
|
1538
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function
|
|
1533
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function br(e,t){let n=null;for(let r of yr){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function xr(e){let t=e.provider??`openai`,n=process.env.OPENAI_API_KEY;if(t===`openai`&&!n)return{kind:`unavailable`,reason:`OPENAI_API_KEY environment variable is not set`,suggestion:`Set OPENAI_API_KEY in your shell, e.g.
|
|
1539
1534
|
export OPENAI_API_KEY="sk-..."
|
|
1540
1535
|
|
|
1541
1536
|
Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@forinda/kickjs-ai`)}catch{return{kind:`unavailable`,reason:`@forinda/kickjs-ai is not installed`,suggestion:`Install the AI package to enable the LLM fallback:
|
|
1542
1537
|
kick add ai
|
|
1543
1538
|
|
|
1544
1539
|
Or manually:
|
|
1545
|
-
|
|
1546
|
-
`)}function
|
|
1540
|
+
${x()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Sr(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Cr((await a.chat({messages:[{role:`system`,content:o},{role:`user`,content:s}]})).content);return e?{kind:`ok`,diagnosis:e}:{kind:`error`,message:`The LLM responded but the payload was not valid JSON in the expected shape. Try again, or file an issue with the error text.`}}catch(e){return{kind:`error`,message:`LLM request failed: ${e instanceof Error?e.message:String(e)}`}}}function Sr(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
1541
|
+
`)}function Cr(e){let t=[e,wr(e),Tr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Er(t))return t}catch{continue}return null}function wr(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Tr(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i)i=!1;else if(o===`\\`&&r)i=!0;else if(o===`"`)r=!r;else if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Er(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function Dr(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await Ar(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
1547
1542
|
|
|
1548
1543
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
1549
1544
|
kick explain "config.get returned undefined"
|
|
1550
|
-
|
|
1551
|
-
`)
|
|
1552
|
-
`)
|
|
1553
|
-
`),process.exit(2)),
|
|
1554
|
-
`)
|
|
1555
|
-
`)}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:
|
|
1545
|
+
${h(x(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=Mr(),i=br(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1546
|
+
`);return}if(i){Nr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1547
|
+
`),process.exit(2)),Pr(n),process.exit(2));let a=await xr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Or(a),null,2)+`
|
|
1548
|
+
`),process.exit(a.kind===`ok`?0:2)),kr(n,a),process.exit(a.kind===`ok`?0:2)})}function Or(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 kr(e,t){t.kind===`ok`?Nr(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${Ir(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Fr(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${Ir(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Ar(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:jr()}function jr(){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 Mr(){let e=process.cwd();return{cwd:e,hasFile:t=>O(I(e,t))}}function Nr(e,t,n,r=!1){let i=Ir(e.trim(),200),a=r?`AI-generated — verify before applying`:Lr(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${Fr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Fr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Fr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Fr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
1549
|
+
`)}function Pr(e){let t=Ir(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
|
|
1556
1550
|
|
|
1557
1551
|
1. Check the framework docs for the error keywords:
|
|
1558
1552
|
https://kickjs.app/
|
|
@@ -1564,12 +1558,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1564
1558
|
3. File an issue with the error text:
|
|
1565
1559
|
https://github.com/forinda/kick-js/issues/new
|
|
1566
1560
|
|
|
1567
|
-
`)}function
|
|
1561
|
+
`)}function Fr(e,t){return e.split(`
|
|
1568
1562
|
`).map(e=>`${t}${e}`).join(`
|
|
1569
|
-
`)}function
|
|
1570
|
-
`,`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
|
|
1571
|
-
Error: tsx not found. Install it: pnpm add -D tsx
|
|
1572
|
-
`),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=Re(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`
|
|
1563
|
+
`)}function Ir(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Lr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Rr(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(zr),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(Br)}function zr(e){let t=I(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)=>{t?process.kill(process.pid,t):process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Br(e){let t=process.cwd(),n=Vr(t)??Le(t),r=e.name??n,i=e.global?I(process.env.HOME??`.`,`.mcp.json`):I(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,j(i,JSON.stringify(o,null,2)+`
|
|
1564
|
+
`,`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 Vr(e){let t=I(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 Hr(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=I(t,e.entry);O(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Wr(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${x(t)} add -D tsx\n`),process.exit(1));let i=Ur(n,e.entry),a=P(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 Ur(e,t){return`
|
|
1573
1565
|
import 'reflect-metadata'
|
|
1574
1566
|
|
|
1575
1567
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1588,13 +1580,13 @@ try {
|
|
|
1588
1580
|
HttpStatus = core.HttpStatus
|
|
1589
1581
|
} catch {
|
|
1590
1582
|
console.error(' Error: @forinda/kickjs not found.')
|
|
1591
|
-
console.error(' Install
|
|
1583
|
+
console.error(' Install @forinda/kickjs in this project.\\n')
|
|
1592
1584
|
process.exit(1)
|
|
1593
1585
|
}
|
|
1594
1586
|
|
|
1595
1587
|
// Load entry to trigger decorator registration
|
|
1596
1588
|
try {
|
|
1597
|
-
await import('${
|
|
1589
|
+
await import('${R(e).href}')
|
|
1598
1590
|
} catch (err) {
|
|
1599
1591
|
console.warn(' Warning: ' + err.message)
|
|
1600
1592
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -1623,53 +1615,56 @@ server.on('exit', () => {
|
|
|
1623
1615
|
console.log('\\n Goodbye!\\n')
|
|
1624
1616
|
process.exit(0)
|
|
1625
1617
|
})
|
|
1626
|
-
`}function
|
|
1618
|
+
`}function Wr(e,t){for(let n of qn(e)){let e=P(n,t);if(O(e))return e}return null}function Gr(e,t){let n=RegExp(`^\\s*${G(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]!==`
|
|
1627
1619
|
`;)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]===`
|
|
1628
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function
|
|
1620
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function Kr(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=Gr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${G(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 qr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=U(t),o=V(t),s=i?W(a):a;s!==a&&!await y(P(n,s))&&await y(P(n,a))&&(s=a);let c=P(n,s);if(!await y(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await se({message:w.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1629
1621
|
Cancelled.
|
|
1630
|
-
`);return}await
|
|
1622
|
+
`);return}await Ge(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=P(n,`index.ts`);if(await y(l)){let e=await z(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${G(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${G(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Kr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1631
1623
|
|
|
1632
|
-
`),e!==t&&(await
|
|
1624
|
+
`),e!==t&&(await B(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Jr(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 p(process.cwd()),r=m(n),i=t.modulesDir??r.dir??`src/modules`,a=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await qr({name:n,modulesDir:I(i),force:t.force,pluralize:a})})}function Yr(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 Xr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Zr(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 p(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-FOqPjQ0u.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>No),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(`
|
|
1633
1625
|
Registered typegen plugins:
|
|
1634
1626
|
`);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(`
|
|
1635
1627
|
Disable one in kick.config.ts:
|
|
1636
1628
|
`),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
|
|
1637
|
-
`);return}let r=
|
|
1629
|
+
`);return}let r=Yr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Xr(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 we(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 Ee(a);let r=await Hn({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=I(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await ye(i,r,e.silent??!1)}}}catch(e){e instanceof Te?console.error(`
|
|
1638
1630
|
`+e.message+`
|
|
1639
|
-
`):e instanceof
|
|
1631
|
+
`):e instanceof En?console.error(`
|
|
1640
1632
|
`+e.message+`
|
|
1641
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const
|
|
1642
|
-
`).length:1}function
|
|
1633
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const Qr=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function $r(e,t){return typeof t==`number`?e.slice(0,t).split(`
|
|
1634
|
+
`).length:1}function ei(e){let t=le(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(ue(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 ti(e){let t=D(e);if(t)return{key:`id:${t}`,label:t};let n=le(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function ni(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=Oe(e).map(de).find(e=>e?.name===`Inject`),a=null;if(i)a=ti(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=ti(e.typeName))}a&&r.push({...a,line:$r(t,e.start)})}return r}function ri(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,/* @__PURE__ */ new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,/* @__PURE__ */ new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=Je(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`)&&ue(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)}ke(e,e=>{if(e.type===`ClassDeclaration`){let a=D(e.id);if(!a)return;for(let o of Oe(e)){let s=de(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:ni(e,n)});return}if(Qr.has(s.name)){let o=pe(Ae(s.call),`scope`),c=o?ei(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:ni(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!ue(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=ti(s[0]);c&&i(c.key,s.length>=3?ei(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 ii(e){let t=[];if(!O(e))return t;let n=A(e,{withFileTypes:!0});for(let r of n){let n=P(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...ii(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function ai(e){try{return k(e,`utf-8`)}catch{return``}}const oi=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function si(e,t){let n=ai(P(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(oi.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 ci(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 li(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 ui(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function di(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 fi(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 pi(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 mi(e){let t=ii(P(e,`src`)).map(e=>ai(e)),n=[],r=si(e,t);r&&n.push(r);let i=ci(t);i&&n.push(i);let a=li(t);a&&n.push(a);let o=ui();o&&n.push(o);let s=di(t);return s&&n.push(s),n.push(fi(t)),n.push(pi(t)),n}function hi(e){let t=ri(ii(P(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:F(e,t).split(`\\`).join(`/`),source:ai(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 gi(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(`
|
|
1643
1635
|
Usage: kick check [--deploy] [--di]
|
|
1644
1636
|
|
|
1645
1637
|
Available checks:
|
|
1646
1638
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1647
1639
|
--di Find REQUEST-scoped dependencies injected into singleton constructors
|
|
1648
|
-
`);return}let t=process.cwd();
|
|
1649
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function
|
|
1650
|
-
Install it: pnpm add reflect-metadata
|
|
1651
|
-
Then import it at the top of src/index.ts:
|
|
1652
|
-
|
|
1653
|
-
import 'reflect-metadata'
|
|
1654
|
-
// ... rest of bootstrap`}}function Di(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 Oi(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=>D(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=>D(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 ki(e,t=Ai){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=k(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);else try{let e=Fe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const Ai=2e3;function ji(e){let t=N(e.cwd,`.kickjs`,`types`);if(!D(t))return null;let n=ki(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 Mi=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Ni=[`.env.test`,`.env.test.local`],Pi=[`.env`,`.env.local`];function Fi(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 Ii(e){if(!Mi.some(t=>D(N(e.cwd,t))))return null;let t=Pi.filter(t=>D(N(e.cwd,t)));if(t.length===0)return null;let n=Ni.filter(t=>D(N(e.cwd,t)));if(n.length>0){let t=Fi(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
|
|
1640
|
+
`);return}let t=process.cwd();ne(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=re();n.start(`Scanning project...`);let r=[...e.deploy?mi(t):[],...e.di?hi(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)S.message(`${oe(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?w.red(`${a} critical`):`${a} critical`,o>0?w.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(T(w.red(`${l} — fix critical issues before deploying`)),process.exit(1)):T(w.green(`${l} — looking good!`))})}function _i(e){try{return JSON.parse(k(e,`utf-8`))}catch{return null}}function vi(e){try{return k(e,`utf-8`)}catch{return null}}function yi(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function bi(e){let t=P(e,`tsconfig.json`);if(O(t))return xi(t,/* @__PURE__ */ new Set)}function xi(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=vi(e);if(n===null)return null;let r=yi(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=Si(N(e),n);if(!r)continue;let i=xi(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Si(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Ci(I(e,t));let n=e;for(;;){let e=Ci(P(n,`node_modules`,t));if(e)return e;let r=N(n);if(r===n)break;n=r}return null}function Ci(e){if(O(e)){try{if(Ie(e).isDirectory()){let t=P(e,`tsconfig.json`);return O(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return O(t)?t:null}function wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ti(){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.
|
|
1641
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Ei(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 Di(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: ${x(e.cwd)} add express`}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const Oi={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ki(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=Oi[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: ${x(e.cwd)} add ${n.join(` `)}`}:e.runtime===`h3`&&Ai(e.cwd,t.h3)===1?{name:r,status:`fail`,message:`h3 v1`,fix:`This version of @forinda/kickjs runs on h3 v2 only. Upgrade: ${x(e.cwd)} add h3@^2 — no code change for apps that only use KickJS APIs.`}:{name:r,status:`pass`}}function Ai(e,t){let n=t;for(let t=I(e);;t=N(t)){try{n=JSON.parse(k(P(t,`node_modules`,`h3`,`package.json`),`utf8`)).version;break}catch{}if(N(t)===t)break}let r=/(\d+)/.exec(n)?.[1];return r===void 0?void 0:Number(r)}function ji(e){if(!e.pkg||!Ni(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or ${x(e.cwd)} add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const Mi=2e3;function Ni(e){let t=P(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<Mi;){let e=r.pop(),t;try{t=A(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=Mi)break;let t=P(e,a.name);if(a.isDirectory())a.name!==`node_modules`&&r.push(t);else if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(vi(t)??``)))return!0}}return!1}function Pi(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.\nInstall it: ${x(e.cwd)} add reflect-metadata\nThen import it at the top of src/index.ts:\n\n import 'reflect-metadata'\n // ... rest of bootstrap`}}function Fi(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 Ii(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>P(e.cwd,t)).filter(e=>O(e)).filter(e=>/\bloadEnv\s*\(/.test(vi(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>P(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=vi(n)??``,i=N(n),a=[];for(let e of t){let t=F(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+)?['"]${wi(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=>F(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 \`${F(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 ${F(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 Li(e,t=Ri){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=P(e,o.name);if(o.isDirectory())i.push(a);else try{let e=Ie(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const Ri=2e3;function zi(e){let t=P(e.cwd,`.kickjs`,`types`);if(!O(t))return null;let n=Li(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 Bi=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Vi=[`.env.test`,`.env.test.local`],Hi=[`.env`,`.env.local`];function Ui(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 Wi(e){if(!Bi.some(t=>O(P(e.cwd,t))))return null;let t=Hi.filter(t=>O(P(e.cwd,t)));if(t.length===0)return null;let n=Vi.filter(t=>O(P(e.cwd,t)));if(n.length>0){let t=Ui(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
|
|
1655
1642
|
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
|
|
1656
1643
|
development env — including DATABASE_URL and any third-party credentials.
|
|
1657
1644
|
|
|
1658
1645
|
Create .env.test (cp .env.test.example .env.test, if the project has one)
|
|
1659
1646
|
holding the whole environment the suite should run against
|
|
1660
1647
|
(a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
|
|
1661
|
-
and supply env from the test runner.`}}const
|
|
1662
|
-
`).map(e=>` ${
|
|
1663
|
-
`)}function
|
|
1648
|
+
and supply env from the test runner.`}}const Gi=[()=>Ti(),Ei,Di,ki,ji,Pi,Fi,Ii,Wi,zi];async function Ki(e,t={}){let n={cwd:e,pkg:_i(P(e,`package.json`)),tsconfig:bi(e),runtime:t.runtime??`express`},r=[...Gi,...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 qi(e){switch(e){case`pass`:return w.green(`✔`);case`warn`:return w.yellow(`⚠`);case`fail`:return w.red(`✖`)}}function Ji(e){let t=qi(e.status),n=e.message?` ${w.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function Yi(e){return e.split(`
|
|
1649
|
+
`).map(e=>` ${w.dim(`→`)} ${e}`).join(`
|
|
1650
|
+
`)}function Xi(e){return e?.doctor?.checks??[]}function Zi(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),n=Xi(await p(e)),r=await t(e);ne(`KickJS Doctor`);let i=await Ki(e,{extraChecks:n,runtime:r});for(let e of i)S.message(Ji(e)),e.fix&&e.status!==`pass`&&S.message(Yi(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=[w.green(`${a} passed`),o>0?w.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?w.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`:w.green(`${c} — your environment looks good`))})}const Qi=Symbol.for(`kickjs.handler.entryCapture`),$i=Symbol.for(`kickjs.config.describe`);function ea(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function ta(e){let t=[];for(let n of e){let e=[n.description,n.list?`comma-separated list`:void 0].filter(Boolean);for(let n of e.length>0?e.join(` — `).split(/\r?\n/):[])t.push(`# ${n}`);n.required?t.push(`${n.name}=`):t.push(`# ${n.name}=${n.default===void 0?``:ea(n.default)}`)}return t}function na(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
|
|
1651
|
+
# sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
|
|
1652
|
+
#
|
|
1653
|
+
# Uncommented variables are required. Commented ones are optional; the value shown
|
|
1654
|
+
# is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...ta(e.env)].join(`
|
|
1655
|
+
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...ta(n.vars)].join(`
|
|
1656
|
+
`));return`${t.join(`
|
|
1657
|
+
|
|
1658
|
+
`)}\n`}async function ra(e,t){let n=I(e,t);if(!O(n))throw Error(`${t} not found`);let r=I(e,`vite.config.ts`);if(!O(r))throw Error(`vite.config.ts not found — kick env example loads the app through it`);let{createRequire:i}=await import(`node:module`),a=i(I(e,`package.json`)),{createServer:o}=await import(R(a.resolve(`vite`)).href),s=globalThis,c;s[Qi]=e=>{c??=e},s[$i]=!0,s[Wn]=`kick-env`;let l=await o({configFile:r,root:e,logLevel:`error`,appType:`custom`,server:{middlewareMode:!0,hmr:!1,watch:null}});try{await l.ssrLoadModule(n)}finally{delete s[Qi],delete s[$i],delete s[Wn],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function ia(e){e.command(`env`).description(`Work with the environment the app reads`).command(`example`).description(`Write .env.example from the env schema and declared settings sections`).option(`-e, --entry <file>`,`App entry that calls bootstrap()`,`src/index.ts`).option(`-o, --out <file>`,`File to write`,`.env.example`).option(`--check`,`Exit 1 if the file is missing or out of date, instead of writing it`).action(async e=>{let t=process.cwd(),n=I(t,e.out),r;try{r=na(await ra(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((O(n)?k(n,`utf8`):void 0)!==r&&(console.error(`\n ${e.out} is out of date — run \`kick env example\`.\n`),process.exit(1)),console.log(` ${e.out} is up to date.`)):(j(n,r),console.log(` Wrote ${e.out}`))})}function aa(e){return e.optsWithGlobals().dryRun??!1}function oa(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.
|
|
1664
1659
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
1665
1660
|
--target define|class Override the migration direction.
|
|
1666
1661
|
--apply Apply the changes (default: dry-run preview).
|
|
1667
|
-
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=
|
|
1668
|
-
`+
|
|
1662
|
+
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=aa(t)||!e.apply;v(n),e.experimental||(console.error(`
|
|
1663
|
+
`+w.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
1669
1664
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1670
1665
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1671
1666
|
Always commit before running with --apply.
|
|
1672
|
-
`),process.exit(1));let r=await
|
|
1667
|
+
`),process.exit(1));let r=await p(process.cwd()),i=m(r),a=I(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 ${w.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=w.dim(`→ ${o}`),c=n?w.dim(`(dry-run)`):w.bold(`(applying)`);console.log(`\n ${w.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${w.dim(a)}\n`);let l=e.backup!==!1&&!n,u=await gn(a,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${w.green(`✓`)} backup: ${w.dim(e)}\n ${w.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${w.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${w.green(`✓`)} ${e.path}`);else{f++;let t=w.dim(`(${e.reason??`skipped`})`);console.log(` ${w.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${w.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=w.dim(`(${u.indexReason??`skipped`})`);console.log(` ${w.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${w.dim(`-`)} ${u.indexPath} ${w.dim(`(not found)`)}`);let h=n?w.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${w.bold(String(d))} migrated, ${w.bold(String(f))} skipped${h}\n`)})}function sa(e){try{let t=JSON.parse(k(I(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function ca(e,t=O,n=sa(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=N(e);return(t(I(r,`pnpm-workspace.yaml`))||t(I(r,`package.json`)))&&t(I(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function la(e,t,n,r){let i=ca(t,n,r),a=e?.staticDir===!1?void 0:e?.staticDir??i.staticDir;return{entry:e?.entry??`src/serverless.ts`,outDir:e?.outDir??`dist/serverless`,staticDir:a,siteRoot:e?.siteRoot??i.siteRoot,publishDir:e?.publishDir??`dist/public`,apiPath:e?.apiPath??i.apiPath,external:e?.external??[`valibot`,`yup`],vercelRuntime:e?.vercelRuntime??`nodejs22.x`,include:e?.include??i.include??[]}}function ua(e,t,n={projectDir:`.`}){let r=[` path: '${t}/*',`,...n.preferStatic?[` preferStatic: true,`]:[],...n.includedFiles?.length?[` includedFiles: ${JSON.stringify(n.includedFiles)},`]:[]];return`import { fileURLToPath } from 'node:url'
|
|
1673
1668
|
import { handler } from '${e}'
|
|
1674
1669
|
|
|
1675
1670
|
// Where the app's build files were packaged; the platform starts this
|
|
@@ -1683,7 +1678,7 @@ export const config = {
|
|
|
1683
1678
|
${r.join(`
|
|
1684
1679
|
`)}
|
|
1685
1680
|
}
|
|
1686
|
-
`}function
|
|
1681
|
+
`}function da(){return`import { fileURLToPath } from 'node:url'
|
|
1687
1682
|
import { handler } from './server.mjs'
|
|
1688
1683
|
|
|
1689
1684
|
// The app's build files are copied into this function at their project
|
|
@@ -1693,11 +1688,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
|
|
|
1693
1688
|
const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
|
|
1694
1689
|
|
|
1695
1690
|
export default (req, res) => handler.node(req, res, requestContext())
|
|
1696
|
-
`}function
|
|
1697
|
-
`).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
|
|
1691
|
+
`}function fa(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function pa(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&e!==``&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function ma(e,t){let n;try{n=Je(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
|
|
1692
|
+
`).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 ha(e){let t=I(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(I(t,e),`utf-8`);return n.includes(`@Cron`)?ma(n,`src/${e}`):[]}):[]}function ga(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 _a(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=`${r.file}:${r.line}`;if(r.expression===void 0){t.push(`${e}: @Cron expression is not a string literal, so it has no Vercel cron entry`);continue}r.timezone&&t.push(`${e}: Vercel crons run in UTC — the timezone option is ignored there`);let i=r.expression.trim().replace(/\s+/g,` `);i.split(` `).length===5?n.set(ga(i),i):t.push(`${e}: Vercel crons need a five-field expression, so it has no Vercel cron entry`)}return{crons:[...n].map(([e,t])=>({path:`/_kick/cron/${e}`,schedule:t})),warnings:t}}function va(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 ya(e,t){let{createRequire:n}=await import(`node:module`),r=n(I(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=I(e,`node_modules`,t,`package.json`)}if(!O(i))throw Error(`${t} is not installed in this project. Run: ${x(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=va(JSON.parse(k(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(R(I(N(i),a)).href)}async function ba(e,t,n){let r=I(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 ya(e,`vite`),{default:a}=await ya(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await ya(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":I(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:I(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>Sa(n,r?N(r):e)||t.external.includes(n)&&Sa(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=I(e,t.outDir,`server.mjs`);return n(`bundled ${F(process.cwd(),c)}`),c}function xa(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function Sa(e,t,n=O){let r=xa(e);if(!r)return!1;for(let e=t;;e=N(e)){if(n(I(e,`node_modules`,r,`package.json`)))return!1;if(N(e)===e)return!0}}function Ca(e,t){let n=F(e,t).split(L)[0];return n!==void 0&&n.startsWith(`.`)}function wa(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function Ta(e){try{return Ie(e)}catch{return}}function Ea(e,t){let n=t.filter(t=>!O(I(e,t)));if(n.length>0)throw Error(`${n.join(`, `)} not found — the function reads ${n.length===1?`it`:`them`} at runtime. Run the full build first (\`${h(x(e),`build`)}\`), or fix \`deploy.include\`.`)}function Da(e,t){let n=t.projectRoot,r=()=>la(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();Ea(n,e.include);let i=await ba(n,e,t.log),a=I(n,e.siteRoot),o=ha(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=I(a,`.netlify/v1/functions`);Pe(s,{recursive:!0});let c=F(s,i).split(L).join(`/`),l=e=>e.split(L).join(`/`);j(I(s,`api.mjs`),ua(c,e.apiPath,{projectDir:l(F(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(F(s,I(n,e)));return Ta(I(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${F(process.cwd(),I(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)Pe(I(n,u),{recursive:!0}),t.log(`publish directory ready at ${F(process.cwd(),I(n,u))}`);else if(O(I(n,u))){let e=A(I(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=I(n,u,`_redirects`),r=O(t)?k(t,`utf-8`):``,i=wa(e).filter(e=>!r.includes(e));i.length>0&&j(t,`${r}${r&&!r.endsWith(`
|
|
1698
1693
|
`)?`
|
|
1699
1694
|
`:``}${i.join(`
|
|
1700
|
-
`)}\n`)}}let d=
|
|
1695
|
+
`)}\n`)}}let d=I(a,`netlify.toml`);if(O(d)){let e=fa(k(d,`utf-8`)),r=F(a,I(n,u)).split(L).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();Ea(n,e.include);let i=await ba(n,e,t.log),a=I(n,e.siteRoot),o=e.staticDir?I(n,e.staticDir):void 0,s=I(a,`.vercel/output`),c=I(s,`functions/api.func`);Fe(s,{recursive:!0,force:!0}),Pe(c,{recursive:!0}),Ne(i,I(c,`server.mjs`)),j(I(c,`index.mjs`),da());for(let t of e.include)Ne(I(n,t),I(c,t),{recursive:!0});if(j(I(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`);Ne(o,I(s,`static`),{recursive:!0,filter:e=>!Ca(o,e)})}let{crons:l,warnings:u}=_a(ha(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:pa(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};j(I(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${F(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 Oa=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=M.resolve(e.cwd,`kick.config.ts`);if(!O(t))return null;let n=await p(e.cwd);if(!n?.assetMap)return null;let r=fe(n.assetMap,e.cwd);return r.count===0?null:Se(r)}}),ka="/* 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 Aa(e,t,n,r={}){if(e.length===0)return`${ka}
|
|
1701
1696
|
// (no routes discovered yet — annotate a controller method with
|
|
1702
1697
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1703
1698
|
declare global {
|
|
@@ -1714,14 +1709,15 @@ declare global {
|
|
|
1714
1709
|
|
|
1715
1710
|
/** Empty until the first route exists — see kick typegen. */
|
|
1716
1711
|
export const kickRpc = {} as const
|
|
1717
|
-
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=
|
|
1718
|
-
`))}let u=[],d=/* @__PURE__ */ new Set,f=/* @__PURE__ */ new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;d.has(t)?r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`):(d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`))}let p=[` interface Api {`,...u,` }`].join(`
|
|
1719
|
-
`);l.push(p);let m=[]
|
|
1720
|
-
`)
|
|
1721
|
-
`)
|
|
1712
|
+
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=Pa(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??Ma(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=Na(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${ja(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
1713
|
+
`))}let u=[],d=/* @__PURE__ */ new Set,f=/* @__PURE__ */ new Set;i.has(`Named`)&&r.onWarn?.(`controller class 'Named' collides with the reserved KickRoutes.Named route-name map — its interface declaration-merges into it. Rename the controller.`),i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;d.has(t)?r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`):(d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`))}let p=[` interface Api {`,...u,` }`].join(`
|
|
1714
|
+
`);l.push(p);let m=[];for(let[e,t]of i)for(let n of t)f.has(`${e}.${n.method}`)&&m.push(` '${e}.${n.method}': ${e}['${n.method}']`);l.push([` interface Named {`,...m,` }`].join(`
|
|
1715
|
+
`));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=La(e);if(g.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}g.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&h.push(` ${n}: {\n${i.join(`
|
|
1716
|
+
`)}\n },`)}let _=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...h,`} as const`].join(`
|
|
1717
|
+
`),v=[],y=/* @__PURE__ */ new Map;for(let t of e)y.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=y.get(e),i=Ia(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;v.push(`import type { ${a} } from '${i}'`)}let ee=v.length>0?v.join(`
|
|
1722
1718
|
`)+`
|
|
1723
|
-
`:``,b=
|
|
1724
|
-
`);return`${
|
|
1719
|
+
`:``,b=Fa(a)+ee,x=l.join(`
|
|
1720
|
+
`);return`${ka}${b}
|
|
1725
1721
|
declare global {
|
|
1726
1722
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1727
1723
|
namespace KickRoutes {
|
|
@@ -1732,19 +1728,19 @@ ${x}
|
|
|
1732
1728
|
type KickApi = KickRoutes.Api
|
|
1733
1729
|
}
|
|
1734
1730
|
|
|
1735
|
-
${
|
|
1736
|
-
`}function
|
|
1731
|
+
${_}
|
|
1732
|
+
`}function ja(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Ma(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 Na(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 Pa(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Ia(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(`
|
|
1737
1733
|
`)+`
|
|
1738
|
-
`}function
|
|
1739
|
-
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 '${
|
|
1734
|
+
`}function Ia(e,t,n){if(e===null)return`unknown`;let r=N(n);if(e===``){let e=F(r,t).split(L).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=N(t),a=I(i,e),o=F(r,a).split(L).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function La(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const Ra=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:za(e),cwd:e.cwd,envFile:Ba(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=M.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Aa(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function za(e){return M.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ba(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Va=`@typescript/typescript6`;function Ha(e){return typeof e?.createProgram==`function`}function Ua(e){if(Ha(e.typescript))return{api:e.typescript,source:`typescript`};if(Ha(e.ts6))return{api:e.ts6,source:Va};let t=`Install it in the project:\n ${x()} add -D ${Va}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
1735
|
+
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 Wa(e){let t=Me(P(e,`package.json`)),n=async e=>{try{return await import(R(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Va)]);return Ua({typescript:Ga(r),ts6:Ga(i)}).api}function Ga(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Ka=Symbol(`kick/client: expansion budget exhausted`);var qa=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=/* @__PURE__ */ new Map;inProgress=/* @__PURE__ */ new Map;jsonInProgress=/* @__PURE__ */ new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;let t=this.blocks.length,n=this.nextName,r=new Set(this.hoistedByType.keys());try{return this.render(e,0)}catch(e){if(e!==Ka)throw e;this.blocks.length=t,this.nextName=n;for(let e of this.hoistedByType.keys())r.has(e)||this.hoistedByType.delete(e);return this.opts.onWarn?.(`expansion abandoned after ${this.budget} depth hoists — emitting 'unknown'. Either the response type never repeats (a generic that grows at every level) or it nests more distinct types than the budget allows; raising maxDepth hoists fewer of them. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t,n=!0){let r=this.ts.TypeFlags;if(n){let t=this.hoistedByType.get(e);if(t)return t}if(t>this.maxDepth&&!this.isLeaf(e))return this.hoistDeep(e);if(e.flags&(r.String|r.Number|r.Boolean|r.BigInt|r.ESSymbol)||e.flags&(r.Any|r.Unknown|r.Never|r.Void|r.Undefined|r.Null)||e.isLiteral()||e.flags&r.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let i=this.arrayElement(e);if(i){let e=this.render(i.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return i.readonly?`readonly ${n}`:n}let a=this.toJsonType(e);if(a){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(a,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&r.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}isLeaf(e){let t=this.ts.TypeFlags;return(e.flags&(t.String|t.Number|t.Boolean|t.BigInt|t.ESSymbol|t.Any|t.Unknown|t.Never|t.Void|t.Undefined|t.Null|t.BooleanLiteral))!==0||e.isLiteral()}hoistDeep(e){if(++this.truncations>this.budget)throw Ka;let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=this.isPlainObject(e)?`interface ${t} {\n${this.members(e,0,` `)}\n}`:`type ${t} = ${this.render(e,0,!1)}`,t}isPlainObject(e){return(e.flags&this.ts.TypeFlags.Object)!==0&&!e.isUnionOrIntersection()&&!this.isTuple(e)&&!this.arrayElement(e)&&!this.toJsonType(e)&&!this.isLibType(e)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
|
|
1740
1736
|
`){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===`
|
|
1741
1737
|
`?`
|
|
1742
|
-
`: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
|
|
1743
|
-
`));for(let n of
|
|
1744
|
-
`);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
|
|
1738
|
+
`: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 Ja=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Ya=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Xa(e){return qe(`sha1`).update(e).digest(`hex`)}function Za(e){let t=qe(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
|
|
1739
|
+
`));for(let n of Ja){let r=P(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(!Ya.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 Qa(e){try{let t=await Wa(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(P(e.projectDir,`tsconfig.json`),{},n);return r?Za({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 $a(e){let t=await Wa(e.compilerFrom??e.projectDir),n=P(N(e.routesFile),`__kick_client_probe__.ts`),r=no(e.routesFile,e.keys),i=ao(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.`);eo(t,i,e.routesFile);let s=ro(t,i,o,e.keys),c=null,l=new qa(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=/* @__PURE__ */ new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===to(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);d.flags&t.TypeFlags.Any?e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`):(c=r,u.set(r,l.expand(d)),c=null)}return{entries:u,hoisted:l.hoisted()}}function eo(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(`
|
|
1740
|
+
`);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 to(e){return`_K${e}`}function no(e,t){let n=`./`+Le(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${to(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
1745
1741
|
`)+`
|
|
1746
|
-
`}function
|
|
1747
|
-
`))}},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:[...
|
|
1742
|
+
`}function ro(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(to(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function io(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=>P(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function ao(e,t,n,r){let i=P(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
1743
|
+
`))}},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:[...io(o.fileNames,N(n)),n],options:o.options,host:s})}const oo=`/* eslint-disable */
|
|
1748
1744
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1749
1745
|
//
|
|
1750
1746
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -1758,7 +1754,7 @@ ${g}
|
|
|
1758
1754
|
//
|
|
1759
1755
|
// Written when \`kick dev\` starts, not on save — resolving these types builds a
|
|
1760
1756
|
// full TypeScript program over the server. Re-run \`kick typegen\`.
|
|
1761
|
-
`;function
|
|
1757
|
+
`;function so(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${oo}
|
|
1762
1758
|
// (no routes discovered yet — annotate a controller method with
|
|
1763
1759
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1764
1760
|
interface Api {}
|
|
@@ -1775,7 +1771,7 @@ export type { Api }
|
|
|
1775
1771
|
|
|
1776
1772
|
`)+`
|
|
1777
1773
|
|
|
1778
|
-
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${
|
|
1774
|
+
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${oo}
|
|
1779
1775
|
${r}interface Api {
|
|
1780
1776
|
${i.join(`
|
|
1781
1777
|
`)}
|
|
@@ -1789,7 +1785,7 @@ declare global {
|
|
|
1789
1785
|
}
|
|
1790
1786
|
|
|
1791
1787
|
export type { Api }
|
|
1792
|
-
`}const
|
|
1788
|
+
`}const co=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,lo=`.kickjs/cache/client-map.sha1`,uo=(()=>{try{return Me(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function fo(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 po(e){return`${Ln}${co} */\n\n${e}\n`}function mo(e){try{return O(e)?k(e,`utf-8`):null}catch{return null}}async function ho(e){let t=M.resolve(e.cwd,Q);if(!O(t))return!1;try{await Ge(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function go(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function _o(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(O(M.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const vo=()=>({id:co,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!_o(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:M.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=/* @__PURE__ */ new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=go(e.config),a=await Qa({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:uo}),o=fo(M.resolve(e.cwd,lo)),s=mo(M.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Xa(s))return Tn()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=so(await $a({projectDir:e.cwd,routesFile:M.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(lo,`${a} ${Xa(po(t))}`),t}catch(t){let n=O(M.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):Tn()&&e.log.info?.(r),n&&await ho(e),null}}});function yo(e,t,n=`zod`){if(!e)return null;let r=N(t),i=F(r,e.filePath).split(L).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
|
|
1793
1789
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1794
1790
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1795
1791
|
|
|
@@ -1827,5 +1823,5 @@ declare global {
|
|
|
1827
1823
|
}
|
|
1828
1824
|
|
|
1829
1825
|
export {}
|
|
1830
|
-
`}const
|
|
1831
|
-
`)}});var
|
|
1826
|
+
`}const bo=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=So(e);if(t===!1)return null;let n=await e.getScanResult({root:xo(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=M.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return yo(n.env,i,r)}});function xo(e){return M.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function So(e){return e.config?.typegen?.envFile}function Co(e){return M.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function wo(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Co(e),cwd:e.cwd,envFile:wo(e)}}const To=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=M.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return ge(t.classes,n,r)}}),Eo=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className)),r=be(t.classes,t.tokens,t.injects,n);return xe(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Do=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return xe(`ModuleToken`,me(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Oo=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return he(t.pluginsAndAdapters)}}),ko=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:De(t.contextKeys)}}),Ao=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Ce(t.routeFlags)}}),jo={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Mo=()=>({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}=jo[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(`
|
|
1827
|
+
`)}});var No=/* @__PURE__ */ e({builtinCliPlugins:()=>Po});const Po=[_({name:`kick/init`,register:et}),_({name:`kick/generate`,register:Fn}),_({name:`kick/run`,register:rr}),_({name:`kick/info`,register:cr}),_({name:`kick/inspect`,register:vr}),_({name:`kick/add`,register:i}),_({name:`kick/list`,register:o}),_({name:`kick/explain`,register:Dr}),_({name:`kick/mcp`,register:Rr}),_({name:`kick/tinker`,register:Hr}),_({name:`kick/remove`,register:Jr}),_({name:`kick/typegen`,register:Zr}),_({name:`kick/check`,register:gi}),_({name:`kick/doctor`,register:Zi}),_({name:`kick/env-command`,register:ia}),_({name:`kick/codemod`,register:oa}),_({name:`kick/deploy`,register:Da}),_({name:`kick/registry`,typegens:[To()]}),_({name:`kick/services`,typegens:[Eo()]}),_({name:`kick/modules`,typegens:[Do()]}),_({name:`kick/plugins`,typegens:[Oo()]}),_({name:`kick/context`,typegens:[ko()]}),_({name:`kick/route-flags`,typegens:[Ao()]}),_({name:`kick/assets`,typegens:[Oa()]}),_({name:`kick/routes`,typegens:[Ra()]}),_({name:`kick/client`,typegens:[vo()]}),_({name:`kick/env`,typegens:[bo()]}),_({name:`kick/runtime`,typegens:[Mo()]})];export{Vn as n,Po as t};
|