@forinda/kickjs-vite 8.4.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/compress.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-vite v8.4.0
2
+ * @forinda/kickjs-vite v8.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
package/dist/index.d.mts CHANGED
@@ -7,6 +7,8 @@ interface KickViewsPluginOptions {
7
7
  viewsDir?: string;
8
8
  /** Default `src/views/pipes.ts`. */
9
9
  pipesFile?: string;
10
+ /** The app's browser validators. Default `<viewsDir>/validators.ts`. */
11
+ validatorsFile?: string;
10
12
  /** Default `components`, inside the views folder. */
11
13
  componentsDir?: string;
12
14
  /** Where component scripts are served (the views' `clientScriptPath`). Default `'/_kick/c'`. */
@@ -18,7 +20,7 @@ interface KickViewsPluginOptions {
18
20
  * server bundle, for hosts with no static files.
19
21
  */
20
22
  clientFiles?: 'disk' | 'bundle';
21
- /** Default `'public'`, inside the build's `outDir`. */
23
+ /** Default `'public'`, relative to the build's `outDir` (or absolute). */
22
24
  publicDir?: string;
23
25
  /** Images and fonts up to this many bytes are inlined (`'disk'` mode). Default `4096`. */
24
26
  inlineLimit?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["_$__kick_views_plugin0.KickViewsPluginOptions"],"sources":["../src/kick-views-plugin.ts","../src/types.ts","../src/env-watch-plugin.ts","../src/typegen-plugin.ts","../src/devtools-flag-plugin.ts","../src/devtools-strip-plugin.ts","../src/babel-strip-devtools.ts","../src/index.ts"],"mappings":";;;;UAaiB;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;;wBAoBc,gBAAgB,UAAS,yBAA8B;;;;;;;;;;;;;;;;;;;;;;;;;UC7BtD;;;;;EAKf,QALeA;;;;;;;;;;;;;;EAoBf;;EAGA,MAAM;;;;;;;;;;;;;;;;;EAkBN,WAAW;;;;;;;UAQI;;EAEf;;EAEA;;;;;;;;;;;;UAae;;EAEf;;EAEA;;;;;;;;;;UAWe;;;;;;EAMf;;;;;;;;;;;;;;;;;EAkBA,kBAAkB,SAAS;;;;;;UAOZ;;EAEf;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBCpHc,kBAAkB;;;;UCIjB;EACf,eAAe,cAAc;EAC7B,wBAAwB;IACtB;IACA;IACA,cAAc;;IAEd,iBAAiB,kDAAkD;IACnE;IACA;IACA;;;UAkEa;;EAEf,WAAW,iBAAiB,QAAQ;;wBAGtB,oBAAoB,OAAM,uBAA4B;;;UC7ErD;;;;;;;;EAQf;;;;;;EAMA;;;;;;wBAOc,oBAAoB,OAAM,qBAA0B,MAAM;wBAY1D,mBAAmB,OAAM,sBAA2B;;;UC/CnD;;;;;;;EAOf;;;;;;;EAOA,UAAU;;;;;;EAMV,WAAW;;;;;;;wBAUG,oBAAoB,OAAM,uBAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCJrD;;;;;;;;;EASf;;UAGe;;EAEf;;EAEA;;;;;;;wBAQc,kBACd,gBACA,kBACA,OAAM,uBACL;;;wBCoCa,iBAAiB,UAAS,sBAA2B"}
1
+ {"version":3,"file":"index.d.mts","names":["_$__kick_views_plugin0.KickViewsPluginOptions"],"sources":["../src/kick-views-plugin.ts","../src/types.ts","../src/env-watch-plugin.ts","../src/typegen-plugin.ts","../src/devtools-flag-plugin.ts","../src/devtools-strip-plugin.ts","../src/babel-strip-devtools.ts","../src/index.ts"],"mappings":";;;;UAaiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;;wBAoBc,gBAAgB,UAAS,yBAA8B;;;;;;;;;;;;;;;;;;;;;;;;;UC/BtD;;;;;EAKf,QALeA;;;;;;;;;;;;;;EAoBf;;EAGA,MAAM;;;;;;;;;;;;;;;;;EAkBN,WAAW;;;;;;;UAQI;;EAEf;;EAEA;;;;;;;;;;;;UAae;;EAEf;;EAEA;;;;;;;;;;UAWe;;;;;;EAMf;;;;;;;;;;;;;;;;;EAkBA,kBAAkB,SAAS;;;;;;UAOZ;;EAEf;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBCpHc,kBAAkB;;;;UCIjB;EACf,eAAe,cAAc;EAC7B,wBAAwB;IACtB;IACA;IACA,cAAc;;IAEd,iBAAiB,kDAAkD;IACnE;IACA;IACA;;;UAkEa;;EAEf,WAAW,iBAAiB,QAAQ;;wBAGtB,oBAAoB,OAAM,uBAA4B;;;UC7ErD;;;;;;;;EAQf;;;;;;EAMA;;;;;;wBAOc,oBAAoB,OAAM,qBAA0B,MAAM;wBAY1D,mBAAmB,OAAM,sBAA2B;;;UC/CnD;;;;;;;EAOf;;;;;;;EAOA,UAAU;;;;;;EAMV,WAAW;;;;;;;wBAUG,oBAAoB,OAAM,uBAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCJrD;;;;;;;;;EASf;;UAGe;;EAEf;;EAEA;;;;;;;wBAQc,kBACd,gBACA,kBACA,OAAM,uBACL;;;wBCoCa,iBAAiB,UAAS,sBAA2B"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-vite v8.4.0
2
+ * @forinda/kickjs-vite v8.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,8 +8,8 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{compressAssets,compressDirectory}from"./compress.mjs";import fs,{existsSync,readFileSync}from"node:fs";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import path,{dirname,join,posix,relative,resolve,sep}from"node:path";import{normalizePath}from"vite";import*as babel from"@babel/core";import{pathToFileURL}from"node:url";import{reloadEnv}from"@forinda/kickjs";const RESOLVED=`\0virtual:kick-views`;async function kickFiles(dir){return existsSync(dir)?(await readdir(dir,{recursive:!0,withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(`.kick`)).map(e=>relative(dir,join(direntDir(e),e.name)).slice(0,-5).split(sep).join(`/`)).toSorted():[]}function kickViewsPlugin(options={}){let viewsDir=``,pipesFile=``,build=!0,checked,scriptPath=(options.clientScriptPath??`/_kick/c`).replace(/\/+$/,``),onDisk=options.clientFiles!==`bundle`,clientOut,clientFolder=posix.join(options.publicDir??`public`,scriptPath.slice(1)),root=``,shared={};async function checkTemplates(ctx){let hasPipes=existsSync(pipesFile),view=await import(`@forinda/kickjs-view`),names=await kickFiles(viewsDir),errors=[],pipeNames=[...view.BUILTIN_PIPES];if(hasPipes){let read=view.readPipeExports(await readFile(pipesFile,`utf8`),pipesFile);pipeNames.push(...read.names);for(let d of read.diagnostics)errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)}let templates=/* @__PURE__ */ new Map;for(let name of names){let file=join(viewsDir,`${name}.kick`);ctx.addWatchFile(file);let parsed=view.parse(await readFile(file,`utf8`),`${name}.kick`);templates.set(name,parsed.ast);for(let d of parsed.diagnostics)d.severity===`error`&&errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)}let project={templates,pipes:new Set(pipeNames),componentsDir:options.componentsDir??`components`},checked={};for(let name of names){let r=view.check(name,project);for(let d of r.diagnostics){let line=`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`;d.severity===`error`?errors.push(line):ctx.warn(line)}r.template&&(checked[name]=r.template)}let scripts=Object.entries(checked).filter(([,t])=>t.client).map(([name,t])=>({tag:view.componentTag(name,project.componentsDir),file:join(viewsDir,`${name}.kick`),code:t.client.code})),client;if(scripts.length&&onDisk&&!(`useClientFiles`in view))errors.push(`client files on disk need @forinda/kickjs-view 0.3 or later: upgrade it, or set views: { clientFiles: 'bundle' }`);else if(scripts.length)try{client=await bundleClientScripts(scripts,root,shared,scriptPath,onDisk?options.inlineLimit??4096:()=>!0)}catch(err){errors.push(`<script client> bundling failed: ${err.message}`)}for(let[name,t]of Object.entries(checked))if(t.client&&!t.client.js){if(client)t.client={code:``,js:!0};else try{t.client={code:await stripTs(t.client.code,`${name}.ts`),js:!0}}catch(err){errors.push(`${name}.kick — <script client>: ${err.message}`)}}errors.length&&ctx.error(`.kick templates have errors:\n ${[...new Set(errors)].join(`
12
- `)}`);let out;if(client&&onDisk)clientOut=new Map(Object.entries(client.files).map(([name,source])=>[posix.join(clientFolder,name),source])),out={entries:client.entries,css:client.css,disk:Object.keys(client.files)};else if(client){for(let[name,source]of Object.entries(client.files))typeof source!=`string`&&ctx.error(`client file ${name} isn't text: use clientFiles: 'disk' to serve it`);out=client}return JSON.stringify({v:view.AST_FORMAT_VERSION,templates:checked,client:out},null,1)}return{name:`kickjs:views`,configResolved(config){viewsDir=resolve(config.root,options.viewsDir??`src/views`),pipesFile=resolve(config.root,options.pipesFile??`src/views/pipes.ts`),build=config.command===`build`,root=config.root,shared={mode:config.mode,define:config.define,envDir:config.envDir,envPrefix:config.envPrefix,resolve:{alias:config.resolve?.alias??[]}}},resolveId(id){if(id===`virtual:kick-views`)return RESOLVED;if(clientModuleFile(id,viewsDir))return id},configureServer(server){let prefix=`${scriptPath}/`;server.watcher.on(`change`,file=>{let mod=server.moduleGraph.getModuleById(resolve(file)+CLIENT_SUFFIX);mod&&server.moduleGraph.invalidateModule(mod)}),server.middlewares.use(async(req,res,next)=>{let url=(req.url??``).split(`?`)[0];if(req.method!==`GET`&&req.method!==`HEAD`||!url.startsWith(prefix))return next();let m=/^([a-z][a-z0-9-]*)\.[A-Za-z0-9_-]{8}\.js$/.exec(url.slice(prefix.length));if(!m)return next();try{let view=await import(`@forinda/kickjs-view`),dir=options.componentsDir??`components`,name=(await kickFiles(viewsDir)).find(n=>n.startsWith(`${dir}/`)&&view.componentTag(n,dir)===m[1]);if(!name)return next();let file=join(viewsDir,`${name}.kick`);if(clientScriptOf(view,await readFile(file,`utf8`))===void 0)return next();let out=await server.transformRequest(file+CLIENT_SUFFIX);if(!out)return next();res.statusCode=200,res.setHeader(`content-type`,`text/javascript; charset=utf-8`),res.setHeader(`cache-control`,`no-cache`),res.end(req.method===`HEAD`?void 0:out.code)}catch(err){next(err)}})},async buildStart(){build&&(await kickFiles(viewsDir)).length&&(checked=await checkTemplates(this))},renderChunk(code,chunk){if(!code.includes(CLIENT_DIR))return null;let rel=posix.relative(posix.dirname(chunk.fileName),clientFolder);return{code:code.replaceAll(CLIENT_DIR,`./${rel}/`),map:null}},async writeBundle(out){if(clientOut&&out.dir)for(let[file,source]of clientOut){let to=join(out.dir,file);await mkdir(dirname(to),{recursive:!0}),await writeFile(to,source)}},async load(id){let kickFile=clientModuleFile(id,viewsDir);if(kickFile)return clientScriptOf(await import(`@forinda/kickjs-view`),await readFile(kickFile,`utf8`));if(id.endsWith(`.kick${CLIENT_SUFFIX}`)||id!==RESOLVED)return;let pipes=existsSync(pipesFile)?`import * as pipes from ${JSON.stringify(pipesFile)}`:`const pipes = {}`,bundle=`null`;return build&&(checked??=await checkTemplates(this),bundle=checked),[pipes,`const bundle = ${bundle};`,`const clientScriptPath = ${JSON.stringify(scriptPath)};`,clientOut?`const clientDir = (() => { try { return new URL(${JSON.stringify(CLIENT_DIR)}, import.meta.url).href } catch { return undefined } })();`:`const clientDir = undefined;`,`export { bundle, pipes, clientScriptPath, clientDir }`,`export default { bundle, pipes, clientScriptPath, clientDir }`].join(`
13
- `)}}}function clientModuleFile(id,viewsDir){if(!viewsDir||!id.endsWith(`.kick${CLIENT_SUFFIX}`))return;let file=resolve(id.slice(0,-CLIENT_SUFFIX.length));if(file.startsWith(viewsDir+sep)&&existsSync(file))return file}function clientScriptOf(view,src){for(let n of view.parse(src,`x.kick`).ast.body)if(n.k===`element`&&n.tag?.toLowerCase()===`script`&&n.attrs?.some(a=>a.name.toLowerCase()===`client`&&a.kind===`bare`))return(n.children??[]).map(c=>c.k===`text`?c.value:``).join(``)}const CLIENT_DIR=`__KICK_CLIENT_DIR__`,CLIENT_SUFFIX=`.client.ts`;async function bundleClientScripts(scripts,root,shared,scriptPath,inline){let vite=await import(`vite`),byId=new Map(scripts.map(s=>[s.file+CLIENT_SUFFIX,s.code])),out=await vite.build({...shared,configFile:!1,root,base:`${scriptPath}/`,logLevel:`silent`,plugins:[{name:`kickjs:client-scripts`,resolveId:id=>byId.has(id)?id:void 0,load:id=>byId.get(id)}],build:{write:!1,minify:!0,modulePreload:!1,copyPublicDir:!1,assetsDir:``,assetsInlineLimit:inline,rollupOptions:{input:Object.fromEntries(scripts.map(s=>[s.tag,s.file+CLIENT_SUFFIX])),output:{format:`es`,entryFileNames:`[name].[hash].js`,chunkFileNames:c=>`${servable(c.name)}.[hash].js`,assetFileNames:a=>{let name=a.names?.[0]??a.name??`asset`,ext=/\.[^.]*$/.exec(name)?.[0]??``;return`${servable(name.slice(0,name.length-ext.length))}.[hash]${ext.toLowerCase()}`}}}}}),output=(Array.isArray(out)?out[0]:out).output,entries={},css={},files={},byName=new Map(output.map(f=>[f.fileName,f])),cssOf=(name,seen=/* @__PURE__ */ new Set)=>{let c=byName.get(name);return!c||seen.has(name)?[]:(seen.add(name),[...(c.imports??[]).flatMap(i=>cssOf(i,seen)),...c.viteMetadata?.importedCss??[]])};for(let f of output)f.type===`chunk`?(files[f.fileName]=f.code,f.isEntry&&f.name&&(entries[f.name]=f.fileName)):f.fileName.endsWith(`.css`)?files[f.fileName]=typeof f.source==`string`?f.source:new TextDecoder().decode(f.source):files[f.fileName]=f.source;for(let[tag,file]of Object.entries(entries)){let list=[...new Set(cssOf(file))];list.length&&(css[tag]=list)}return{entries,css,files}}const servable=name=>name.replace(/[^A-Za-z0-9_-]/g,`_`);async function stripTs(code,file){let vite=await import(`vite`);return`transformWithOxc`in vite&&vite.transformWithOxc?(await vite.transformWithOxc(code,file,{lang:`ts`})).code:(await vite.transformWithEsbuild(code,file,{loader:`ts`})).code}function direntDir(e){return e.parentPath??e.path??``}function kickjsCorePlugin(ctx){return{name:`kickjs:core`,config(userConfig,_env){let explicitPort=userConfig.server?.port,envPort=process.env.PORT?parseInt(process.env.PORT,10):void 0;return{server:{port:explicitPort??envPort??3e3},appType:`custom`,clearScreen:!1,environments:{ssr:{dev:{warmup:[ctx.entry]}}},ssr:{external:[`@forinda/kickjs`,`express`,`reflect-metadata`]}}}}}const VIRTUAL_APP=`virtual:kickjs/app`,RESOLVED_APP=`${VIRTUAL_APP}`;function kickjsVirtualModulesPlugin(ctx){return{name:`kickjs:virtual-modules`,resolveId(id){if(id===`virtual:kickjs/app`)return RESOLVED_APP},load(id){if(id===RESOLVED_APP)return[`// Auto-generated by @forinda/kickjs-vite`,`// Imports the user's application entry and re-exports the app.`,`// Vite's module graph tracks this — file changes trigger re-evaluation.`,`export * from '${normalizePath(ctx.entry)}'`].join(`
11
+ import{compressAssets,compressDirectory}from"./compress.mjs";import fs,{existsSync,readFileSync}from"node:fs";import{mkdir,readFile,readdir,rm,writeFile}from"node:fs/promises";import path,{dirname,join,posix,relative,resolve,sep}from"node:path";import{normalizePath}from"vite";import*as babel from"@babel/core";import{pathToFileURL}from"node:url";import{reloadEnv}from"@forinda/kickjs";const RESOLVED=`\0virtual:kick-views`;async function kickFiles(dir){return existsSync(dir)?(await readdir(dir,{recursive:!0,withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(`.kick`)).map(e=>relative(dir,join(direntDir(e),e.name)).slice(0,-5).split(sep).join(`/`)).toSorted():[]}function kickViewsPlugin(options={}){let viewsDir=``,pipesFile=``,validatorsFile=``,validatorsEntry=()=>join(dirname(validatorsFile),VALIDATORS_TAG),isValidatorsEntry=id=>!!validatorsFile&&resolve(id)===resolve(validatorsEntry()+CLIENT_SUFFIX),build=!0,checked,scriptPath=(options.clientScriptPath??`/_kick/c`).replace(/\/+$/,``),onDisk=options.clientFiles!==`bundle`,clientOut,written=/* @__PURE__ */ new Set,clientFolder=posix.join(options.publicDir??`public`,scriptPath.slice(1)),root=``,shared={};async function checkTemplates(ctx){let hasPipes=existsSync(pipesFile);clientOut=onDisk?/* @__PURE__ */ new Map:void 0;let view=await import(`@forinda/kickjs-view`),names=await kickFiles(viewsDir),errors=[],pipeNames=[...view.BUILTIN_PIPES];if(hasPipes){let read=view.readPipeExports(await readFile(pipesFile,`utf8`),pipesFile);pipeNames.push(...read.names);for(let d of read.diagnostics)errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)}let validators=/* @__PURE__ */ new Set,hasValidators=existsSync(validatorsFile);if(hasValidators){if(ctx.addWatchFile(validatorsFile),!(`readValidatorExports`in view))errors.push(`custom validators need a newer @forinda/kickjs-view: upgrade it`);else{let read=view.readValidatorExports(await readFile(validatorsFile,`utf8`),validatorsFile);for(let n of read.names)validators.add(n);for(let d of read.diagnostics)errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)}}let templates=/* @__PURE__ */ new Map;for(let name of names){let file=join(viewsDir,`${name}.kick`);ctx.addWatchFile(file);let parsed=view.parse(await readFile(file,`utf8`),`${name}.kick`);templates.set(name,parsed.ast);for(let d of parsed.diagnostics)d.severity===`error`&&errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)}let project={templates,pipes:new Set(pipeNames),validators,componentsDir:options.componentsDir??`components`},checked={};for(let name of names){let r=view.check(name,project);for(let d of r.diagnostics){let line=`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`;d.severity===`error`?errors.push(line):ctx.warn(line)}r.template&&(checked[name]=r.template)}let scripts=Object.entries(checked).filter(([,t])=>t.client).map(([name,t])=>({tag:view.componentTag(name,project.componentsDir),file:join(viewsDir,`${name}.kick`),code:t.client.code}));hasValidators&&scripts.push({tag:VALIDATORS_TAG,file:validatorsEntry(),code:validatorsWrapper(validatorsFile)});let client;if(scripts.length&&onDisk&&!(`useClientFiles`in view))errors.push(`client files on disk need @forinda/kickjs-view 0.3 or later: upgrade it, or set views: { clientFiles: 'bundle' }`);else if(scripts.length)try{client=await bundleClientScripts(scripts,root,shared,scriptPath,onDisk?options.inlineLimit??4096:()=>!0)}catch(err){errors.push(`<script client> bundling failed: ${err.message}`)}for(let[name,t]of Object.entries(checked))if(t.client&&!t.client.js){if(client)t.client={code:``,js:!0};else try{t.client={code:await stripTs(t.client.code,`${name}.ts`),js:!0}}catch(err){errors.push(`${name}.kick — <script client>: ${err.message}`)}}errors.length&&ctx.error(`.kick templates have errors:\n ${[...new Set(errors)].join(`
12
+ `)}`);let out;if(client&&onDisk)clientOut=new Map(Object.entries(client.files).map(([name,source])=>[posix.join(clientFolder,name),source])),out={entries:client.entries,css:client.css,disk:Object.keys(client.files)};else if(client){for(let[name,source]of Object.entries(client.files))typeof source!=`string`&&ctx.error(`client file ${name} isn't text: use clientFiles: 'disk' to serve it`);out=client}return JSON.stringify({v:view.AST_FORMAT_VERSION,templates:checked,client:out},null,1)}return{name:`kickjs:views`,configResolved(config){viewsDir=resolve(config.root,options.viewsDir??`src/views`),pipesFile=resolve(config.root,options.pipesFile??`src/views/pipes.ts`),validatorsFile=options.validatorsFile?resolve(config.root,options.validatorsFile):join(viewsDir,`validators.ts`),build=config.command===`build`,root=config.root,shared={mode:config.mode,define:config.define,envDir:config.envDir,envPrefix:config.envPrefix,resolve:{alias:config.resolve?.alias??[]}}},resolveId(id){if(id===`virtual:kick-views`)return RESOLVED;if(clientModuleFile(id,viewsDir)||isValidatorsEntry(id))return id},configureServer(server){let prefix=`${scriptPath}/`;server.watcher.on(`change`,file=>{let mod=server.moduleGraph.getModuleById(resolve(file)+CLIENT_SUFFIX);mod&&server.moduleGraph.invalidateModule(mod)}),server.middlewares.use(async(req,res,next)=>{let url=(req.url??``).split(`?`)[0];if(req.method!==`GET`&&req.method!==`HEAD`||!url.startsWith(prefix))return next();let m=/^([a-z][a-z0-9-]*)\.[A-Za-z0-9_-]{8}\.js$/.exec(url.slice(prefix.length));if(!m)return next();if(m[1]===VALIDATORS_TAG){if(!existsSync(validatorsFile))return next();try{let out=await server.transformRequest(validatorsEntry()+CLIENT_SUFFIX);if(!out)return next();res.statusCode=200,res.setHeader(`content-type`,`text/javascript; charset=utf-8`),res.setHeader(`cache-control`,`no-cache`),res.end(req.method===`HEAD`?void 0:out.code)}catch(err){next(err)}}else try{let view=await import(`@forinda/kickjs-view`),dir=options.componentsDir??`components`,name=(await kickFiles(viewsDir)).find(n=>n.startsWith(`${dir}/`)&&view.componentTag(n,dir)===m[1]);if(!name)return next();let file=join(viewsDir,`${name}.kick`);if(clientScriptOf(view,await readFile(file,`utf8`))===void 0)return next();let out=await server.transformRequest(file+CLIENT_SUFFIX);if(!out)return next();res.statusCode=200,res.setHeader(`content-type`,`text/javascript; charset=utf-8`),res.setHeader(`cache-control`,`no-cache`),res.end(req.method===`HEAD`?void 0:out.code)}catch(err){next(err)}})},async buildStart(){!build||!(await kickFiles(viewsDir)).length?(checked=void 0,clientOut&&=/* @__PURE__ */ new Map):checked=await checkTemplates(this)},renderChunk(code,chunk,out){if(!code.includes(CLIENT_DIR))return null;let dir=out.dir??(out.file?dirname(out.file):``),rel=relative(resolve(dir,dirname(chunk.fileName)),resolve(dir,clientFolder));return{code:code.replaceAll(CLIENT_DIR,`./${rel.split(sep).join(`/`)}/`),map:null}},async writeBundle(out){if(!clientOut||!out.dir)return;let keep=new Set([...clientOut.keys()].map(f=>resolve(out.dir,f)));for(let file of written)keep.has(file)||await rm(file,{force:!0});written=keep;for(let[file,source]of clientOut){let to=resolve(out.dir,file);await mkdir(dirname(to),{recursive:!0}),await writeFile(to,source)}},async load(id){let kickFile=clientModuleFile(id,viewsDir);if(kickFile)return clientScriptOf(await import(`@forinda/kickjs-view`),await readFile(kickFile,`utf8`));if(isValidatorsEntry(id))return validatorsWrapper(validatorsFile);if(id.endsWith(`.kick${CLIENT_SUFFIX}`)||id!==RESOLVED)return;let pipes=existsSync(pipesFile)?`import * as pipes from ${JSON.stringify(pipesFile)}`:`const pipes = {}`,bundle=`null`;return build&&(checked??=await checkTemplates(this),bundle=checked),[pipes,`const bundle = ${bundle};`,`const clientScriptPath = ${JSON.stringify(scriptPath)};`,clientOut?`const clientDir = (() => { try { return new URL(${JSON.stringify(CLIENT_DIR)}, import.meta.url).href } catch { return undefined } })();`:`const clientDir = undefined;`,`export const validatorsFile = ${build?`undefined`:JSON.stringify(validatorsFile)};`,`export { bundle, pipes, clientScriptPath, clientDir }`,`export default { bundle, pipes, clientScriptPath, clientDir${build?``:`, validatorsFile`} }`].join(`
13
+ `)}}}function clientModuleFile(id,viewsDir){if(!viewsDir||!id.endsWith(`.kick${CLIENT_SUFFIX}`))return;let file=resolve(id.slice(0,-CLIENT_SUFFIX.length));if(file.startsWith(viewsDir+sep)&&existsSync(file))return file}function clientScriptOf(view,src){for(let n of view.parse(src,`x.kick`).ast.body)if(n.k===`element`&&n.tag?.toLowerCase()===`script`&&n.attrs?.some(a=>a.name.toLowerCase()===`client`&&a.kind===`bare`))return(n.children??[]).map(c=>c.k===`text`?c.value:``).join(``)}const CLIENT_DIR=`__KICK_CLIENT_DIR__`,CLIENT_SUFFIX=`.client.ts`,VALIDATORS_TAG=`kick-validators`;function validatorsWrapper(file){return`import * as v from ${JSON.stringify(file)}\nObject.assign((globalThis.__kickValidators ??= {}), v)\n`}async function bundleClientScripts(scripts,root,shared,scriptPath,inline){let vite=await import(`vite`),byId=new Map(scripts.map(s=>[s.file+CLIENT_SUFFIX,s.code])),out=await vite.build({...shared,configFile:!1,root,base:`${scriptPath}/`,logLevel:`silent`,plugins:[{name:`kickjs:client-scripts`,resolveId:id=>byId.has(id)?id:void 0,load:id=>byId.get(id)}],build:{write:!1,minify:!0,modulePreload:!1,copyPublicDir:!1,assetsDir:``,assetsInlineLimit:inline,rollupOptions:{input:Object.fromEntries(scripts.map(s=>[s.tag,s.file+CLIENT_SUFFIX])),output:{format:`es`,entryFileNames:`[name].[hash].js`,chunkFileNames:c=>`${servable(c.name)}.[hash].js`,assetFileNames:a=>{let name=a.names?.[0]??a.name??`asset`,ext=/\.[^.]*$/.exec(name)?.[0]??``;return`${servable(name.slice(0,name.length-ext.length))}.[hash]${ext.toLowerCase()}`}}}}}),output=(Array.isArray(out)?out[0]:out).output,entries={},css={},files={},byName=new Map(output.map(f=>[f.fileName,f])),cssOf=(name,seen=/* @__PURE__ */ new Set)=>{let c=byName.get(name);return!c||seen.has(name)?[]:(seen.add(name),[...(c.imports??[]).flatMap(i=>cssOf(i,seen)),...c.viteMetadata?.importedCss??[]])};for(let f of output)f.type===`chunk`?(files[f.fileName]=f.code,f.isEntry&&f.name&&(entries[f.name]=f.fileName)):f.fileName.endsWith(`.css`)?files[f.fileName]=typeof f.source==`string`?f.source:new TextDecoder().decode(f.source):files[f.fileName]=f.source;for(let[tag,file]of Object.entries(entries)){let list=[...new Set(cssOf(file))];list.length&&(css[tag]=list)}return{entries,css,files}}const servable=name=>name.replace(/[^A-Za-z0-9_-]/g,`_`);async function stripTs(code,file){let vite=await import(`vite`);return`transformWithOxc`in vite&&vite.transformWithOxc?(await vite.transformWithOxc(code,file,{lang:`ts`})).code:(await vite.transformWithEsbuild(code,file,{loader:`ts`})).code}function direntDir(e){return e.parentPath??e.path??``}function kickjsCorePlugin(ctx){return{name:`kickjs:core`,config(userConfig,_env){let explicitPort=userConfig.server?.port,envPort=process.env.PORT?parseInt(process.env.PORT,10):void 0;return{server:{port:explicitPort??envPort??3e3},appType:`custom`,clearScreen:!1,environments:{ssr:{dev:{warmup:[ctx.entry]}}},ssr:{external:[`@forinda/kickjs`,`express`,`reflect-metadata`]}}}}}const VIRTUAL_APP=`virtual:kickjs/app`,RESOLVED_APP=`${VIRTUAL_APP}`;function kickjsVirtualModulesPlugin(ctx){return{name:`kickjs:virtual-modules`,resolveId(id){if(id===`virtual:kickjs/app`)return RESOLVED_APP},load(id){if(id===RESOLVED_APP)return[`// Auto-generated by @forinda/kickjs-vite`,`// Imports the user's application entry and re-exports the app.`,`// Vite's module graph tracks this — file changes trigger re-evaluation.`,`export * from '${normalizePath(ctx.entry)}'`].join(`
14
14
  `)}}}function kickjsDevServerPlugin(_ctx){return{name:`kickjs:dev-server`,configureServer(viteServer){globalThis.__kickjs_httpServer=viteServer.httpServer??null,globalThis.__kickjs_viteServer=viteServer;let warm=()=>{viteServer.ssrLoadModule(VIRTUAL_APP).catch(err=>{err instanceof Error&&viteServer.ssrFixStacktrace(err),viteServer.config.logger.error(`[kickjs] failed to bootstrap app on startup: ${err instanceof Error?err.message:String(err)}`)})},httpServer=viteServer.httpServer;return httpServer&&(httpServer.listening?warm():httpServer.once(`listening`,warm)),()=>{viteServer.middlewares.use(async(req,res,next)=>{try{let kickApp=(await viteServer.ssrLoadModule(VIRTUAL_APP)).app;if(!kickApp?.handle)return next();kickApp.handle(req,res,err=>{if(err)return err instanceof Error&&viteServer.ssrFixStacktrace(err),next(err);next()})}catch(err){err instanceof Error&&viteServer.ssrFixStacktrace(err),next(err)}})}}}}function rewarmApp(server,reason){server.ssrLoadModule(VIRTUAL_APP).catch(err=>{err instanceof Error&&server.ssrFixStacktrace(err),server.config.logger.error(`[kickjs] app failed to reload after ${reason}: ${err instanceof Error?err.message:String(err)}`,{timestamp:!0})})}const MODULE_CLASS_REGEX=/export\s+(?:default\s+)?class\s+(\w+(?:Module))\s*(?:extends|implements|{)/,MODULE_FILE_PATTERN=/\.module\.[tj]sx?$/;function kickjsModuleDiscoveryPlugin(ctx){let discovered=/* @__PURE__ */ new Map,server=null;return ctx.discoveredModules=discovered,{name:`kickjs:module-discovery`,configureServer(viteServer){server=viteServer,viteServer.watcher.on(`add`,filePath=>{MODULE_FILE_PATTERN.test(filePath)&&invalidateVirtualApp(viteServer)}),viteServer.watcher.on(`unlink`,filePath=>{discovered.has(filePath)&&(discovered.delete(filePath),invalidateVirtualApp(viteServer))})},transform(code,id){if(!MODULE_FILE_PATTERN.test(id)||id.includes(`node_modules`))return null;let match=code.match(MODULE_CLASS_REGEX);if(match){let className=match[1],wasNew=!discovered.has(id);discovered.set(id,{filePath:id,className}),wasNew&&server&&invalidateVirtualApp(server)}else discovered.has(id)&&(discovered.delete(id),server&&invalidateVirtualApp(server));return null},handleHotUpdate({file,server:viteServer}){MODULE_FILE_PATTERN.test(file)&&invalidateVirtualApp(viteServer)}}}function invalidateVirtualApp(server){let mod=server.moduleGraph.getModuleById(RESOLVED_APP);mod&&server.moduleGraph.invalidateModule(mod),rewarmApp(server,`module discovery change`)}function isClientModule(server,file){return((server.environments?.client?.moduleGraph)?.getModulesByFile(file)?.size??0)>0}function isProjectSource(file){return!(!/\.(?:ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(file)||file.endsWith(`.d.ts`)||file.endsWith(`.d.mts`)||file.endsWith(`.d.cts`)||file.includes(`/node_modules/`)||file.includes(`/.kickjs/`)||file.includes(`/dist/`)||file.includes(`/.git/`)||file.includes(`/coverage/`))}function basename(file){let i=file.lastIndexOf(`/`);return i===-1?file:file.slice(i+1)}const DECORATOR_CLASS_REGEX=/@(?:Service|Controller|Repository|Injectable|Component)\s*\([^)]*\)\s*\n?\s*(?:export\s+)?class\s+(\w+)/g,FACTORY_DECL_REGEX=/(?:export\s+)?const\s+(\w+)\s*(?::[^=]+)?=\s*(defineAdapter|definePlugin|defineContextDecorator)\s*[<(]/g,FACTORY_KEYWORDS=[`defineAdapter`,`definePlugin`,`defineContextDecorator`],DECORATOR_KEYWORDS=[`@Service`,`@Controller`,`@Repository`,`@Injectable`,`@Component`];function kickjsHmrPlugin(ctx,hmrOptions={}){let fileTokenMap=/* @__PURE__ */ new Map,pendingTokens=/* @__PURE__ */ new Set,debounceTimer=null;return{name:`kickjs:hmr`,transform(code,id){if(!/\.[tj]sx?$/.test(id)||id.includes(`node_modules`))return null;let hasDecorator=DECORATOR_KEYWORDS.some(kw=>code.includes(kw)),hasFactory=FACTORY_KEYWORDS.some(kw=>code.includes(kw));if(!hasDecorator&&!hasFactory)return fileTokenMap.has(id)&&fileTokenMap.delete(id),null;let tokens=[];if(hasDecorator)for(let m of code.matchAll(DECORATOR_CLASS_REGEX))tokens.push(m[1]);if(hasFactory)for(let m of code.matchAll(FACTORY_DECL_REGEX))tokens.push(`${m[1]} (${m[2]})`);return tokens.length>0?fileTokenMap.set(id,tokens):fileTokenMap.has(id)&&fileTokenMap.delete(id),null},handleHotUpdate({file,server}){if(!isProjectSource(file))return;let tokens=fileTokenMap.get(file);if(tokens&&tokens.length>0)for(let t of tokens)pendingTokens.add(t);else pendingTokens.add(basename(file));if(debounceTimer&&clearTimeout(debounceTimer),debounceTimer=setTimeout(()=>{flushInvalidation(server,pendingTokens,hmrOptions),pendingTokens=/* @__PURE__ */ new Set},150),!isClientModule(server,file))return[]}}}function flushInvalidation(server,tokens,hmrOptions){let batch=[...tokens];if(batch.length===0)return;let timestamp=Date.now(),container=globalThis.__kickjs_container;if(container&&typeof container.invalidate==`function`)for(let token of batch)container.invalidate(token);let vmod=server.moduleGraph.getModuleById(RESOLVED_APP);if(vmod&&server.moduleGraph.invalidateModule(vmod),rewarmApp(server,`HMR invalidation (${batch.length} token${batch.length===1?``:`s`})`),server.hot.send({type:`custom`,event:`kickjs:hmr`,data:{tokens:batch,timestamp}}),hmrOptions.silent)return;if(hmrOptions.onInvalidation){let out=hmrOptions.onInvalidation({tokens:batch,timestamp});typeof out==`string`&&console.log(out);return}let names=batch.join(`, `),label=batch.length===1?`1 token`:`${batch.length} tokens`;console.log(` ${green(`HMR`)} invalidated ${label}: ${names}`)}function green(text){return`\x1b[32m${text}\x1b[0m`}function resolveDevtoolsFlag(opts={},env){if(typeof opts.enabled==`boolean`)return opts.enabled;let envOverride=process.env.KICKJS_DEVTOOLS;return envOverride===`1`||envOverride===`true`?!0:envOverride===`0`||envOverride===`false`?!1:env?env.command===`serve`:process.env.NODE_ENV===`development`||process.env.NODE_ENV===`test`}function devtoolsFlagPlugin(opts={}){let flagName=opts.flagName??`__KICKJS_DEVTOOLS__`;return{name:`kickjs:devtools-flag`,config(_userConfig,env){let enabled=resolveDevtoolsFlag(opts,env);return{define:{[flagName]:JSON.stringify(enabled)}}}}}const DEVTOOLS_KIT_RE=/^@forinda\/kickjs-devtools-kit(\/.*)?$/,DEVTOOLS_EVENTS_RE=/(^|\/)devtools-events(\.[a-z]+)?$/;function stripDevtoolsCode(source,filename,opts={}){if(opts.fastReject!==!1&&!source.includes(`@forinda/kickjs-devtools-kit`)&&!source.includes(`devtools-events`))return{code:source,changed:!1};let changed=!1,isJsx=/\.(?:tsx|jsx)$/i.test(filename),parserPlugins=[`typescript`,`decorators-legacy`,`classProperties`];isJsx&&parserPlugins.push(`jsx`);let result=babel.transformSync(source,{filename,babelrc:!1,configFile:!1,sourceType:`module`,parserOpts:{plugins:parserPlugins},generatorOpts:{retainLines:!0},plugins:[function(){return{name:`kickjs-strip-devtools`,visitor:{Program(path){let devtoolsBindings=/* @__PURE__ */ new Set;for(let stmt of path.get(`body`)){if(!stmt.isImportDeclaration())continue;let src=stmt.node.source.value;if(DEVTOOLS_KIT_RE.test(src)||DEVTOOLS_EVENTS_RE.test(src)){for(let spec of stmt.node.specifiers)spec.local?.name&&devtoolsBindings.add(spec.local.name);stmt.remove(),changed=!0}}if(devtoolsBindings.size!==0)for(let stmt of path.get(`body`)){if(!stmt.isExpressionStatement())continue;let root=rootIdentifier(stmt.node.expression);root&&devtoolsBindings.has(root)&&(stmt.remove(),changed=!0)}}}}}]});return!result||result.code==null||!changed?{code:source,changed:!1}:{code:result.code,changed:!0}}function rootIdentifier(expr){let node=expr;for(;;){if(node.type===`Identifier`)return node.name;if(node.type===`CallExpression`)node=node.callee;else if(node.type===`MemberExpression`)node=node.object;else if(node.type===`TSAsExpression`||node.type===`TSNonNullExpression`)node=node.expression;else return null}}const DEFAULT_INCLUDE=/\.(?:m|c)?[jt]sx?$/;function devtoolsStripPlugin(opts={}){let active=!1,include=opts.include??DEFAULT_INCLUDE;return{name:`kickjs:devtools-strip`,enforce:`pre`,apply:`build`,config(_userConfig,env){active=opts.enabled??(env.command===`build`&&!resolveDevtoolsFlag(opts.devtools,env))},transform(code,id){if(!active||id.includes(`node_modules`)||!include.test(id))return null;let result=stripDevtoolsCode(code,id);return result.changed?{code:result.code,map:null}:null}}}function resolveCliEntry(root){let dir=root;for(;;){let pkgDir=join(dir,`node_modules`,`@forinda`,`kickjs-cli`),manifestPath=join(pkgDir,`package.json`);if(existsSync(manifestPath))try{let pkg=JSON.parse(readFileSync(manifestPath,`utf8`)),dot=pkg.exports?.[`.`],entryRel=(typeof dot==`string`?dot:typeof dot?.import==`string`?dot.import:typeof dot?.import?.default==`string`?dot.import.default:typeof dot?.default==`string`?dot.default:void 0)??pkg.module??pkg.main;if(typeof entryRel==`string`)return join(pkgDir,entryRel)}catch{}let parent=dirname(dir);if(parent===dir)return null;dir=parent}}async function loadCliFromProject(root){try{let entry=resolveCliEntry(root);if(!entry||!existsSync(entry))return null;let mod=await import(pathToFileURL(entry).href);return typeof mod.createTypegenDevWatcher==`function`&&typeof mod.loadKickConfig==`function`?mod:null}catch{return null}}function kickjsTypegenPlugin(opts={}){let loadCli=opts.loadCli??loadCliFromProject;return{name:`kickjs:typegen`,apply:`serve`,async configureServer(server){if(globalThis.__kickjs_typegen_owner)return;let root=server.config.root,cli=await loadCli(root);if(!cli){server.config.logger.info("[kickjs] typegen-on-save disabled — @forinda/kickjs-cli not resolvable from the project (install it, or run `kick dev`).");return}let config=await cli.loadKickConfig(root).catch(()=>null),watcher=cli.createTypegenDevWatcher({cwd:root,config,emitWarning:message=>{server.config.logger.warn(message),server.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message,timestamp:Date.now()}})}});watcher.runOnce(),server.watcher.on(`add`,f=>watcher.handleWatchEvent(`add`,f)),server.watcher.on(`change`,f=>watcher.handleWatchEvent(`change`,f)),server.watcher.on(`unlink`,f=>watcher.handleWatchEvent(`unlink`,f)),server.watcher.on(`unlinkDir`,d=>watcher.handleWatchEvent(`unlinkDir`,d)),watcher.assetSrcRoots.length>0&&server.watcher.add([...watcher.assetSrcRoots]),server.httpServer?server.httpServer.once(`close`,()=>watcher.dispose()):server.watcher.once(`close`,()=>watcher.dispose())}}}function envWatchPlugin(){let envFiles=[`.env`,`.env.local`,`.env.development`,`.env.production`,`.env.test`];return{name:`kickjs-env-watch`,configureServer(server){let root=server.config.root;for(let file of envFiles){let filePath=path.resolve(root,file);fs.existsSync(filePath)&&server.watcher.add(filePath)}server.watcher.on(`change`,changedPath=>{let basename=path.basename(changedPath);if(envFiles.includes(basename)){server.config.logger.info(` .env changed (${basename}), triggering reload...`,{timestamp:!0});try{reloadEnv()}catch(err){server.config.logger.warn(` env reload failed: ${err?.message??err} — restart may be required`,{timestamp:!0})}let mods=server.moduleGraph.getModulesByFile(path.resolve(root,`src/index.ts`));if(mods)for(let mod of mods)server.moduleGraph.invalidateModule(mod);server.ws.send({type:`full-reload`})}})}}}function kickjsVitePlugin(options={}){let entry=options.entry??`src/index.ts`,ctx={entry,root:process.cwd()},plugins=[{name:`kickjs:root-resolver`,config(config){let root=config.root??process.cwd();ctx.root=root,ctx.entry=resolve(root,entry)}},kickjsCorePlugin(ctx),kickjsModuleDiscoveryPlugin(ctx),kickjsHmrPlugin(ctx,options.hmr),kickjsVirtualModulesPlugin(ctx),kickjsDevServerPlugin(ctx),kickjsTypegenPlugin(),...options.views===!1?[]:[kickViewsPlugin(options.views)]];return options.devtools!==!1&&(plugins.push(devtoolsFlagPlugin(options.devtools??{})),plugins.push(devtoolsStripPlugin({devtools:options.devtools??{}}))),plugins}export{compressAssets,compressDirectory,devtoolsFlagPlugin,devtoolsStripPlugin,envWatchPlugin,kickViewsPlugin,kickjsTypegenPlugin,kickjsVitePlugin,resolveDevtoolsFlag,stripDevtoolsCode};
15
15
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["OWNER_KEY"],"sources":["../src/kick-views-plugin.ts","../src/core-plugin.ts","../src/virtual-modules.ts","../src/dev-server.ts","../src/warm.ts","../src/module-discovery.ts","../src/hmr-plugin.ts","../src/devtools-flag-plugin.ts","../src/babel-strip-devtools.ts","../src/devtools-strip-plugin.ts","../src/typegen-plugin.ts","../src/env-watch-plugin.ts","../src/index.ts"],"sourcesContent":["/**\n * `virtual:kick-views` — the app's `.kick` templates, checked at build time\n * and shipped as data, plus its pipes file. A broken template fails the\n * build. Under `serve` the bundle is `null`: the app's file loader reads\n * templates and picks up edits on the next request.\n *\n * @module @forinda/kickjs-vite/kick-views-plugin\n */\nimport { existsSync } from 'node:fs'\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path'\nimport type { Plugin } from 'vite'\n\nexport interface KickViewsPluginOptions {\n /** Default `src/views`. */\n viewsDir?: string\n /** Default `src/views/pipes.ts`. */\n pipesFile?: string\n /** Default `components`, inside the views folder. */\n componentsDir?: string\n /** Where component scripts are served (the views' `clientScriptPath`). Default `'/_kick/c'`. */\n clientScriptPath?: string\n /**\n * Where `kick build` puts client files: `'disk'` (default) writes them to\n * `<outDir>/<publicDir><clientScriptPath>/`, served from disk on Node and by\n * the platform's static files on the edge; `'bundle'` keeps them in the\n * server bundle, for hosts with no static files.\n */\n clientFiles?: 'disk' | 'bundle'\n /** Default `'public'`, inside the build's `outDir`. */\n publicDir?: string\n /** Images and fonts up to this many bytes are inlined (`'disk'` mode). Default `4096`. */\n inlineLimit?: number\n}\n\nconst ID = 'virtual:kick-views'\nconst RESOLVED = '\\0virtual:kick-views'\n\nasync function kickFiles(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return []\n const entries = await readdir(dir, { recursive: true, withFileTypes: true })\n return entries\n .filter((e) => e.isFile() && e.name.endsWith('.kick'))\n .map((e) =>\n relative(dir, join(direntDir(e), e.name))\n .slice(0, -'.kick'.length)\n .split(sep)\n .join('/'),\n )\n .toSorted()\n}\n\nexport function kickViewsPlugin(options: KickViewsPluginOptions = {}): Plugin {\n let viewsDir = ''\n let pipesFile = ''\n let build = true\n let checked: string | undefined\n // Exported by the virtual module, so `createViews({ ...kickViews })` serves where this plugin does.\n const scriptPath = (options.clientScriptPath ?? '/_kick/c').replace(/\\/+$/, '')\n const onDisk = options.clientFiles !== 'bundle'\n /** Client files to write beside the server bundle, by path inside its `outDir`. */\n let clientOut: Map<string, string | Uint8Array> | undefined\n const clientFolder = posix.join(options.publicDir ?? 'public', scriptPath.slice(1))\n let root = ''\n // What the nested browser build takes from the app's config.\n let shared: ClientBuildConfig = {}\n\n /** Parse and check every template; the bundle as JSON, or a build error listing every problem. */\n async function checkTemplates(ctx: {\n addWatchFile(id: string): void\n warn(message: string): void\n error(message: string): never\n }): Promise<string> {\n const hasPipes = existsSync(pipesFile)\n // The view package is optional: only apps that import this module need it.\n const view = await import('@forinda/kickjs-view')\n const names = await kickFiles(viewsDir)\n const errors: string[] = []\n const pipeNames = [...view.BUILTIN_PIPES]\n if (hasPipes) {\n const read = view.readPipeExports(await readFile(pipesFile, 'utf8'), pipesFile)\n pipeNames.push(...read.names)\n for (const d of read.diagnostics) {\n errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)\n }\n }\n const templates = new Map()\n for (const name of names) {\n const file = join(viewsDir, `${name}.kick`)\n ctx.addWatchFile(file)\n const parsed = view.parse(await readFile(file, 'utf8'), `${name}.kick`)\n templates.set(name, parsed.ast)\n for (const d of parsed.diagnostics) {\n if (d.severity === 'error')\n errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)\n }\n }\n const project = {\n templates,\n pipes: new Set(pipeNames),\n componentsDir: options.componentsDir ?? 'components',\n }\n const checked: Record<string, unknown> = {}\n for (const name of names) {\n const r = view.check(name, project)\n for (const d of r.diagnostics) {\n const line = `${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`\n if (d.severity === 'error') errors.push(line)\n else ctx.warn(line)\n }\n if (r.template) checked[name] = r.template\n }\n // Client scripts bundled together: imports resolved, shared code in shared chunks.\n const scripts = Object.entries(checked as Record<string, { client?: { code: string } }>)\n .filter(([, t]) => t.client)\n .map(([name, t]) => ({\n tag: view.componentTag(name, project.componentsDir),\n file: join(viewsDir, `${name}.kick`),\n code: t.client!.code,\n }))\n let client: ClientBundle | undefined\n if (scripts.length && onDisk && !('useClientFiles' in view))\n errors.push(\n \"client files on disk need @forinda/kickjs-view 0.3 or later: upgrade it, or set views: { clientFiles: 'bundle' }\",\n )\n else if (scripts.length) {\n try {\n client = await bundleClientScripts(\n scripts,\n root,\n shared,\n scriptPath,\n onDisk ? (options.inlineLimit ?? 4096) : () => true,\n )\n } catch (err) {\n errors.push(`<script client> bundling failed: ${(err as Error).message}`)\n }\n }\n // `<script client>` ships as plain JS: the edge never strips types.\n for (const [name, t] of Object.entries(checked) as Array<\n [string, { client?: { code: string; js: boolean } }]\n >) {\n if (!t.client || t.client.js) continue\n // Bundled: the views serve the bundle's files, not this source.\n if (client) {\n t.client = { code: '', js: true }\n continue\n }\n try {\n t.client = { code: await stripTs(t.client.code, `${name}.ts`), js: true }\n } catch (err) {\n errors.push(`${name}.kick — <script client>: ${(err as Error).message}`)\n }\n }\n if (errors.length)\n ctx.error(`.kick templates have errors:\\n ${[...new Set(errors)].join('\\n ')}`)\n let out: Record<string, unknown> | undefined\n if (client && onDisk) {\n // Vite drops assets from server builds: written in `writeBundle` instead.\n clientOut = new Map(\n Object.entries(client.files).map(([name, source]) => [\n posix.join(clientFolder, name),\n source,\n ]),\n )\n out = { entries: client.entries, css: client.css, disk: Object.keys(client.files) }\n } else if (client) {\n for (const [name, source] of Object.entries(client.files))\n if (typeof source !== 'string')\n ctx.error(`client file ${name} isn't text: use clientFiles: 'disk' to serve it`)\n out = client\n }\n return JSON.stringify({ v: view.AST_FORMAT_VERSION, templates: checked, client: out }, null, 1)\n }\n\n return {\n name: 'kickjs:views',\n configResolved(config) {\n viewsDir = resolve(config.root, options.viewsDir ?? 'src/views')\n pipesFile = resolve(config.root, options.pipesFile ?? 'src/views/pipes.ts')\n build = config.command === 'build'\n root = config.root\n shared = {\n mode: config.mode,\n define: config.define,\n envDir: config.envDir,\n envPrefix: config.envPrefix,\n resolve: { alias: config.resolve?.alias ?? [] },\n }\n },\n resolveId(id) {\n if (id === ID) return RESOLVED\n // A component's client script, as a module next to its `.kick` file.\n if (clientModuleFile(id, viewsDir)) return id\n return undefined\n },\n // kick dev: component scripts through Vite's pipeline, so their imports\n // (relative, npm, aliases) resolve as they do in a build. Ahead of the app.\n configureServer(server) {\n const prefix = `${scriptPath}/`\n // An edited template's script is rebuilt on the next request.\n server.watcher.on('change', (file) => {\n const mod = server.moduleGraph.getModuleById(resolve(file) + CLIENT_SUFFIX)\n if (mod) server.moduleGraph.invalidateModule(mod)\n })\n server.middlewares.use(async (req, res, next) => {\n const url = (req.url ?? '').split('?')[0]!\n if ((req.method !== 'GET' && req.method !== 'HEAD') || !url.startsWith(prefix))\n return next()\n const m = /^([a-z][a-z0-9-]*)\\.[A-Za-z0-9_-]{8}\\.js$/.exec(url.slice(prefix.length))\n if (!m) return next()\n try {\n const view = await import('@forinda/kickjs-view')\n const dir = options.componentsDir ?? 'components'\n const name = (await kickFiles(viewsDir)).find(\n (n) => n.startsWith(`${dir}/`) && view.componentTag(n, dir) === m[1],\n )\n if (!name) return next()\n const file = join(viewsDir, `${name}.kick`)\n if (clientScriptOf(view, await readFile(file, 'utf8')) === undefined) return next()\n const out = await server.transformRequest(file + CLIENT_SUFFIX)\n if (!out) return next()\n res.statusCode = 200\n res.setHeader('content-type', 'text/javascript; charset=utf-8')\n res.setHeader('cache-control', 'no-cache')\n res.end(req.method === 'HEAD' ? undefined : out.code)\n } catch (err) {\n next(err)\n }\n })\n },\n // In a build the templates are checked up front, whether or not the app\n // imports the virtual module: a broken template always fails `kick build`.\n async buildStart() {\n // Apps without templates skip it, so they needn't install the view package.\n if (!build || !(await kickFiles(viewsDir)).length) return\n checked = await checkTemplates(this)\n },\n renderChunk(code, chunk) {\n if (!code.includes(CLIENT_DIR)) return null\n const rel = posix.relative(posix.dirname(chunk.fileName), clientFolder)\n return {\n code: code.replaceAll(CLIENT_DIR, `./${rel}/`),\n map: null,\n }\n },\n async writeBundle(out) {\n if (!clientOut || !out.dir) return\n for (const [file, source] of clientOut) {\n const to = join(out.dir, file)\n await mkdir(dirname(to), { recursive: true })\n await writeFile(to, source)\n }\n },\n async load(id) {\n const kickFile = clientModuleFile(id, viewsDir)\n if (kickFile) {\n const view = await import('@forinda/kickjs-view')\n return clientScriptOf(view, await readFile(kickFile, 'utf8'))\n }\n // Any other `.kick.client.ts`: not ours to load.\n if (id.endsWith(`.kick${CLIENT_SUFFIX}`)) return undefined\n if (id !== RESOLVED) return undefined\n const hasPipes = existsSync(pipesFile)\n const pipes = hasPipes\n ? `import * as pipes from ${JSON.stringify(pipesFile)}`\n : 'const pipes = {}'\n let bundle = 'null'\n if (build) {\n checked ??= await checkTemplates(this)\n bundle = checked\n }\n return [\n pipes,\n `const bundle = ${bundle};`,\n `const clientScriptPath = ${JSON.stringify(scriptPath)};`,\n // The folder beside this bundle; the edge may have no usable `import.meta.url`.\n // The folder beside this bundle (`renderChunk` fills the path); the\n // edge may have no usable `import.meta.url`.\n clientOut\n ? `const clientDir = (() => { try { return new URL(${JSON.stringify(CLIENT_DIR)}, import.meta.url).href } catch { return undefined } })();`\n : 'const clientDir = undefined;',\n 'export { bundle, pipes, clientScriptPath, clientDir }',\n 'export default { bundle, pipes, clientScriptPath, clientDir }',\n ].join('\\n')\n },\n }\n}\n\n/**\n * The `.kick` file behind a client-script module id — only inside the views\n * folder, so a crafted dev request can't load a template from elsewhere.\n */\nfunction clientModuleFile(id: string, viewsDir: string): string | undefined {\n if (!viewsDir || !id.endsWith(`.kick${CLIENT_SUFFIX}`)) return undefined\n const file = resolve(id.slice(0, -CLIENT_SUFFIX.length))\n if (!file.startsWith(viewsDir + sep) || !existsSync(file)) return undefined\n return file\n}\n\n/** A template's top-level `<script client>` text, as the checker lifts it. */\nfunction clientScriptOf(\n view: { parse(src: string, file: string): { ast: { body: unknown[] } } },\n src: string,\n): string | undefined {\n for (const n of view.parse(src, 'x.kick').ast.body as Array<{\n k: string\n tag?: string\n attrs?: Array<{ name: string; kind: string }>\n children?: Array<{ k: string; value?: string }>\n }>) {\n if (\n n.k === 'element' &&\n n.tag?.toLowerCase() === 'script' &&\n n.attrs?.some((a) => a.name.toLowerCase() === 'client' && a.kind === 'bare')\n )\n return (n.children ?? []).map((c) => (c.k === 'text' ? c.value : '')).join('')\n }\n return undefined\n}\n\n/** The app config the client build shares: mode, `define`, env files, aliases. */\ntype ClientBuildConfig = {\n mode?: string\n define?: Record<string, unknown>\n envDir?: string | false\n envPrefix?: string | string[]\n resolve?: { alias: unknown }\n}\n\n/** Replaced, per output chunk, with the relative path to the client files folder. */\nconst CLIENT_DIR = '__KICK_CLIENT_DIR__'\n\n/** The module id a component's client script builds from: next to its `.kick` file, so `./x` imports resolve there. */\nconst CLIENT_SUFFIX = '.client.ts'\n\n/**\n * One browser build of every component's `<script client>`: imports\n * (relative, npm, the app's aliases) resolved, code shared by several\n * components in shared chunks. Entries are named by component tag.\n */\nasync function bundleClientScripts(\n scripts: Array<{ tag: string; file: string; code: string }>,\n root: string,\n shared: ClientBuildConfig,\n scriptPath: string,\n inline: number | (() => boolean),\n): Promise<ClientBundle> {\n const vite = await import('vite')\n const byId = new Map(scripts.map((s) => [s.file + CLIENT_SUFFIX, s.code]))\n const out = (await vite.build({\n ...(shared as object),\n configFile: false,\n root,\n // CSS `url()`s and asset URLs point where the views serve files.\n base: `${scriptPath}/`,\n logLevel: 'silent',\n plugins: [\n {\n name: 'kickjs:client-scripts',\n resolveId: (id: string) => (byId.has(id) ? id : undefined),\n load: (id: string) => byId.get(id),\n },\n ],\n build: {\n write: false,\n minify: true,\n modulePreload: false,\n copyPublicDir: false,\n assetsDir: '',\n assetsInlineLimit: inline,\n rollupOptions: {\n input: Object.fromEntries(scripts.map((s) => [s.tag, s.file + CLIENT_SUFFIX])),\n output: {\n format: 'es',\n entryFileNames: '[name].[hash].js',\n chunkFileNames: (c: { name: string }) => `${servable(c.name)}.[hash].js`,\n // Served names take a lower-case extension: `Logo.PNG` becomes `Logo.<hash>.png`.\n assetFileNames: (a: { names?: string[]; name?: string }) => {\n const name = a.names?.[0] ?? a.name ?? 'asset'\n const ext = /\\.[^.]*$/.exec(name)?.[0] ?? ''\n return `${servable(name.slice(0, name.length - ext.length))}.[hash]${ext.toLowerCase()}`\n },\n },\n },\n },\n })) as { output: OutputFile[] } | Array<{ output: OutputFile[] }>\n const output = (Array.isArray(out) ? out[0]! : out).output\n const entries: Record<string, string> = {}\n const css: Record<string, string[]> = {}\n const files: Record<string, string | Uint8Array> = {}\n const byName = new Map(output.map((f) => [f.fileName, f]))\n /** The stylesheets a chunk and the chunks it imports bring in. */\n const cssOf = (name: string, seen = new Set<string>()): string[] => {\n const c = byName.get(name)\n if (!c || seen.has(name)) return []\n seen.add(name)\n return [\n ...(c.imports ?? []).flatMap((i) => cssOf(i, seen)),\n ...(c.viteMetadata?.importedCss ?? []),\n ]\n }\n for (const f of output) {\n if (f.type === 'chunk') {\n files[f.fileName] = f.code!\n if (f.isEntry && f.name) entries[f.name] = f.fileName\n } else if (f.fileName.endsWith('.css')) {\n files[f.fileName] =\n typeof f.source === 'string' ? f.source : new TextDecoder().decode(f.source)\n } else files[f.fileName] = f.source!\n }\n for (const [tag, file] of Object.entries(entries)) {\n const list = [...new Set(cssOf(file))]\n if (list.length) css[tag] = list\n }\n return { entries, css, files }\n}\n\n/** Served names allow no dots: `date.utils` becomes `date_utils`. */\nconst servable = (name: string) => name.replace(/[^A-Za-z0-9_-]/g, '_')\n\ntype OutputFile = {\n type: string\n fileName: string\n code?: string\n source?: string | Uint8Array\n isEntry?: boolean\n name?: string\n imports?: string[]\n viteMetadata?: { importedCss?: Set<string> }\n}\n\ntype ClientBundle = {\n entries: Record<string, string>\n css: Record<string, string[]>\n files: Record<string, string | Uint8Array>\n}\n\n/**\n * TypeScript to JS with the running Vite: `transformWithOxc` from Vite 8,\n * `transformWithEsbuild` before it (the plugin supports Vite 6 and up).\n */\nasync function stripTs(code: string, file: string): Promise<string> {\n const vite = (await import('vite')) as typeof import('vite') & {\n transformWithOxc?: typeof import('vite').transformWithOxc\n }\n if ('transformWithOxc' in vite && vite.transformWithOxc)\n return (await vite.transformWithOxc(code, file, { lang: 'ts' })).code\n return (await vite.transformWithEsbuild(code, file, { loader: 'ts' })).code\n}\n\n/** A dirent's folder: `parentPath` from Node 20.12, `path` before it. */\nfunction direntDir(e: { parentPath?: string; path?: string }): string {\n return e.parentPath ?? e.path ?? ''\n}\n","/**\n * Core Vite plugin for KickJS — configures the Vite server for backend\n * framework use: custom app type, SSR environment, and Node.js target.\n *\n * This plugin runs first in the array and sets up the environment that\n * the other sub-plugins (dev-server, virtual-modules, hmr) depend on.\n *\n * @module @forinda/kickjs-vite/core-plugin\n */\n\nimport type { Plugin } from 'vite'\nimport type { PluginContext } from './types'\n\n/**\n * Creates the core configuration plugin.\n *\n * Responsibilities:\n * - Sets `appType: 'custom'` so Vite doesn't serve index.html\n * - Configures the SSR environment for Node.js backend code\n * - Prevents Vite from clearing the terminal (KickJS logs route tables on startup)\n * - Externalizes Node.js built-ins and framework packages from the bundle\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsCorePlugin(ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:core',\n\n /**\n * Vite config hook — runs before config is resolved.\n * Sets the foundational configuration for a backend Node.js framework.\n */\n config(userConfig, _env) {\n // Respect explicit server.port from user's vite.config.ts.\n // Only inject .env PORT when the user hasn't set one.\n const explicitPort = userConfig.server?.port\n const envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined\n const port = explicitPort ?? envPort ?? 3000\n\n return {\n server: {\n port,\n },\n\n // 'custom' tells Vite this is not a SPA or MPA — we handle all requests\n appType: 'custom' as const,\n\n // Don't clear the terminal — KickJS logs route tables on startup\n clearScreen: false,\n\n // SSR environment configuration for backend code\n environments: {\n ssr: {\n // Warm up the entry file for faster first request\n dev: {\n warmup: [ctx.entry],\n },\n },\n },\n\n // SSR-specific settings\n ssr: {\n // Externalize Node.js built-ins and framework packages\n // These should NOT be bundled by Vite — they run natively in Node\n external: ['@forinda/kickjs', 'express', 'reflect-metadata'],\n },\n }\n },\n }\n}\n","/**\n * Virtual module plugin for KickJS — generates the `virtual:kickjs/app`\n * module that bridges Vite and the KickJS application.\n *\n * Virtual modules are Vite's mechanism for generating code at build/serve\n * time that doesn't exist on disk. When the dev server calls\n * `ssrLoadModule('virtual:kickjs/app')`, this plugin generates the code\n * that imports and re-exports the user's application entry.\n *\n * @see https://vite.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * @module @forinda/kickjs-vite/virtual-modules\n */\n\nimport { normalizePath, type Plugin } from 'vite'\nimport type { PluginContext } from './types'\n\n/** Prefix for resolved virtual module IDs (Vite convention) */\nconst VIRTUAL_PREFIX = '\\0'\n\n/** Virtual module ID for the KickJS application entry */\nconst VIRTUAL_APP = 'virtual:kickjs/app'\n\n/** Resolved virtual module ID (with \\0 prefix to mark as virtual) */\nconst RESOLVED_APP = `${VIRTUAL_PREFIX}${VIRTUAL_APP}`\n\n/**\n * Creates the virtual modules plugin.\n *\n * Currently provides one virtual module:\n * - `virtual:kickjs/app` — re-exports the user's application entry\n *\n * The dev server plugin imports this on every request via `ssrLoadModule()`.\n * When any source file changes, Vite invalidates the module graph and the\n * next import returns fresh code — this is how server-side HMR works.\n *\n * Future virtual modules (planned for Steps 4-5):\n * - `virtual:kickjs/modules` — auto-discovered `@Module` classes\n * - `virtual:kickjs/manifest` — container metadata for DevTools\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsVirtualModulesPlugin(ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:virtual-modules',\n\n /**\n * Resolve virtual module IDs.\n * Tells Vite that `virtual:kickjs/app` is a valid module ID\n * and maps it to our internal resolved ID.\n */\n resolveId(id: string) {\n if (id === VIRTUAL_APP) {\n return RESOLVED_APP\n }\n },\n\n /**\n * Load virtual module content.\n * Generates the code for `virtual:kickjs/app` that imports the user's\n * entry file and re-exports the app.\n *\n * The generated code:\n * 1. Imports the user's entry file (which calls `bootstrap()`)\n * 2. Re-exports everything from it (including the `app` export)\n *\n * The dev server plugin then does:\n * `const { app } = await ssrLoadModule('virtual:kickjs/app')`\n * and uses `app.handle(req, res, next)` to route requests through the app.\n */\n load(id: string) {\n if (id !== RESOLVED_APP) return\n\n // Generate code that imports and re-exports the user's entry\n // The entry file should: export const app = bootstrap({ modules: [...] })\n const normalizedEntry = normalizePath(ctx.entry)\n return [\n `// Auto-generated by @forinda/kickjs-vite`,\n `// Imports the user's application entry and re-exports the app.`,\n `// Vite's module graph tracks this — file changes trigger re-evaluation.`,\n `export * from '${normalizedEntry}'`,\n ].join('\\n')\n },\n }\n}\n\nexport { VIRTUAL_APP, RESOLVED_APP }\n","/**\n * Dev server plugin for KickJS — mounts the application on Vite's\n * HTTP server using the `configureServer` hook.\n *\n * ## Architecture\n *\n * In development, Vite owns the HTTP port and creates the `http.Server`.\n * This plugin:\n *\n * 1. **Stores `viteServer.httpServer` on `globalThis`** so KickJS adapters\n * (WsAdapter, Socket.IO, GraphQL subscriptions) can attach to the real\n * server via `server.on('upgrade', ...)`. This is the key to supporting\n * any library that needs the raw `http.Server`.\n *\n * 2. **Registers a post-middleware** that loads the KickJS app through\n * Vite's SSR transform pipeline on every request. When source files\n * change, Vite invalidates the module graph and the next request\n * gets fresh code — no process restart needed.\n *\n * 3. **Stores the Vite server reference** on `globalThis` so SSR\n * renderers can use `createViteRuntime()`.\n *\n * ## Why NOT middlewareMode\n *\n * The initial KickJS Vite plugin attempt used `middlewareMode: true`, which\n * makes `viteServer.httpServer = null`. This broke WsAdapter and any library\n * needing `server.on('upgrade', ...)`. By letting Vite create the server,\n * `httpServer` is the real `http.Server` — adapters attach to it seamlessly.\n *\n * ## Request Flow\n *\n * ```\n * HTTP Request → Vite static middleware (HMR, assets)\n * → If Vite handles it → done\n * → If not → KickJS post-middleware\n * → ssrLoadModule('virtual:kickjs/app') → fresh app\n * → the app handles the request on its runtime (Express, Fastify or h3)\n * ```\n *\n *\n * @module @forinda/kickjs-vite/dev-server\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { PluginContext } from './types'\nimport { VIRTUAL_APP } from './virtual-modules'\n\n/**\n * Declare the globalThis properties used for cross-module communication.\n * These persist across Vite's `ssrLoadModule()` re-evaluations.\n *\n * `__kickjs_httpServer` uses the same `HttpServer` type that Vite uses\n * internally (union of http.Server | https.Server | Http2SecureServer).\n * KickJS adapters receive it as `http.Server` via AdapterContext — the\n * cast is safe because the dev server is HTTP/1.1.\n */\ndeclare global {\n // eslint-disable-next-line no-var\n var __kickjs_httpServer: any\n // eslint-disable-next-line no-var\n var __kickjs_viteServer: ViteDevServer | null\n}\n\n/**\n * Creates the dev server plugin.\n *\n * This is the critical integration point between Vite and KickJS:\n * - Pipes `viteServer.httpServer` to adapters via `globalThis`\n * - Loads a fresh app on every request via `ssrLoadModule()`\n * - Fixes stack traces for SSR errors with `ssrFixStacktrace()`\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsDevServerPlugin(_ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:dev-server',\n\n /**\n * Configure the Vite dev server.\n *\n * The `configureServer` hook runs after Vite creates the HTTP server.\n * We use it to:\n * 1. Store the httpServer on globalThis (for WsAdapter, Socket.IO, etc.)\n * 2. Store the Vite server reference (for SSR rendering)\n * 3. Return a post-middleware that loads the KickJS app on each request\n *\n * Returning a function from `configureServer` registers it as a\n * **post-middleware** — it runs AFTER Vite's own middleware (static\n * files, HMR client, etc.), so Vite-handled requests never reach the app.\n */\n configureServer(viteServer: ViteDevServer) {\n // ━━━ Store the REAL http.Server on globalThis ━━━\n // This is the key to supporting Socket.IO, WsAdapter, GraphQL WS,\n // and any library that needs `server.on('upgrade', ...)`.\n //\n // Application.start() detects this and skips creating its own server:\n // if (globalThis.__kickjs_httpServer) → reuse Vite's server\n // else → create own http.Server (production mode)\n //\n // Adapters receive the server in afterStart({ server }) — same API\n // in both dev and prod. Zero adapter code changes needed.\n globalThis.__kickjs_httpServer = viteServer.httpServer ?? null\n globalThis.__kickjs_viteServer = viteServer\n\n // ━━━ Eagerly bootstrap the app once the server is listening ━━━\n // The post-middleware below only evaluates the entry on the FIRST\n // request (lazy SSR). That means `bootstrap()`, adapter\n // `afterStart`, and the app's startup logs don't run until someone\n // hits the URL — the app looks \"not started\" until then. Warm the\n // module once the HTTP server is listening so startup behaves like\n // `node`/`tsx` (logs + adapters + the in-dev shutdown hook ready\n // immediately). Errors surface with a fixed stacktrace.\n const warm = () => {\n viteServer.ssrLoadModule(VIRTUAL_APP).catch((err: unknown) => {\n if (err instanceof Error) viteServer.ssrFixStacktrace(err)\n viteServer.config.logger.error(\n `[kickjs] failed to bootstrap app on startup: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n })\n }\n const httpServer = viteServer.httpServer\n if (httpServer) {\n if (httpServer.listening) warm()\n else httpServer.once('listening', warm)\n }\n\n // Return post-middleware — runs after Vite's static/HMR middleware\n return () => {\n viteServer.middlewares.use(async (req, res, next) => {\n try {\n // Load the KickJS app through Vite's SSR transform pipeline.\n // On first request: evaluates the entry file and all imports.\n // On subsequent requests: returns cached modules (or re-evaluates\n // if source files changed since last request).\n //\n // This is the same pattern React Router and TanStack Start use.\n const mod = await viteServer.ssrLoadModule(VIRTUAL_APP)\n\n // The entry file exports: export const app = bootstrap({ modules })\n // `app` is the configured Application (not yet listening).\n const kickApp = mod.app\n\n if (!kickApp?.handle) {\n // Entry file doesn't export an app — fall through to Vite's 404\n return next()\n }\n\n // Let the app handle the request.\n // If no route matches, it calls next() and\n // Vite's default 404 handler takes over.\n kickApp.handle(req, res, (err?: any) => {\n if (err) {\n // Fix stack traces to point to original source (not compiled)\n if (err instanceof Error) {\n viteServer.ssrFixStacktrace(err)\n }\n return next(err)\n }\n next()\n })\n } catch (err) {\n // SSR load/evaluation error (syntax error, missing import, etc.)\n if (err instanceof Error) {\n viteServer.ssrFixStacktrace(err)\n }\n next(err)\n }\n })\n }\n },\n }\n}\n","/**\n * Eager app re-warm after an invalidation.\n *\n * The dev server evaluates `virtual:kickjs/app` lazily — after a save\n * invalidates it, re-evaluation waits for the NEXT HTTP request. A\n * broken file (syntax error, failed import, boot throw) was therefore\n * silent until something hit the server, even though startup surfaced\n * the same class of error eagerly. Re-warming right after invalidation\n * pushes transform/bootstrap errors into the dev console the moment\n * the save lands.\n *\n * Errors are logged (with fixed stacktraces) but never thrown — the\n * dev loop must survive a mid-edit broken state; the next successful\n * save heals it.\n */\nimport type { ViteDevServer } from 'vite'\n\nimport { VIRTUAL_APP } from './virtual-modules'\n\nexport function rewarmApp(server: ViteDevServer, reason: string): void {\n server.ssrLoadModule(VIRTUAL_APP).catch((err: unknown) => {\n if (err instanceof Error) server.ssrFixStacktrace(err)\n server.config.logger.error(\n `[kickjs] app failed to reload after ${reason}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { timestamp: true },\n )\n })\n}\n","/**\n * Module discovery plugin for KickJS — automatically detects `@Module` classes\n * by scanning source files during Vite's `transform()` hook.\n *\n * ## How It Works\n *\n * 1. Vite calls `transform(code, id)` for every file it processes\n * 2. This plugin checks if the file matches `*.module.ts` (or `.js`)\n * 3. If the file contains a class exported with `@Module` or extends `AppModule`,\n * it extracts the class name and records the file path\n * 4. The virtual module `virtual:kickjs/app` is invalidated so the next request\n * picks up the newly discovered module\n *\n * ## Why This Matters\n *\n * Without auto-discovery, users must manually maintain a barrel file\n * (`src/modules/index.ts`) that imports and re-exports all modules.\n * When `kick g module` creates a new module, it has to edit this barrel.\n * With auto-discovery, modules are detected automatically — no barrel needed.\n *\n * ## Interaction with HMR\n *\n * When a module file is added, renamed, or deleted:\n * - `handleHotUpdate()` detects the change\n * - The virtual module is invalidated\n * - The next `ssrLoadModule()` call regenerates the virtual module\n * with the updated module list\n *\n * @module @forinda/kickjs-vite/module-discovery\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { PluginContext } from './types'\nimport { RESOLVED_APP } from './virtual-modules'\nimport { rewarmApp } from './warm'\n\n/** Regex to detect exported module classes in source files */\nconst MODULE_CLASS_REGEX =\n /export\\s+(?:default\\s+)?class\\s+(\\w+(?:Module))\\s*(?:extends|implements|{)/\n\n/** File extensions to scan for modules */\nconst MODULE_FILE_PATTERN = /\\.module\\.[tj]sx?$/\n\n/**\n * Discovered module entry — maps a file path to its exported class name.\n *\n * @example\n * ```\n * {\n * filePath: '/src/modules/users/user.module.ts',\n * className: 'UserModule'\n * }\n * ```\n */\nexport interface DiscoveredModule {\n /** Absolute file path */\n filePath: string\n /** Exported class name (e.g., 'UserModule') */\n className: string\n}\n\n/**\n * Creates the module auto-discovery plugin.\n *\n * Scans `*.module.ts` files during Vite's transform phase to build a\n * registry of `@Module` classes. The registry is used by the virtual\n * modules plugin to generate auto-imports.\n *\n * @param ctx - Shared plugin context\n * @returns Vite plugin\n */\nexport function kickjsModuleDiscoveryPlugin(ctx: PluginContext): Plugin {\n /**\n * Registry of discovered modules.\n * Keyed by absolute file path to handle renames and deletions.\n * Stored on the plugin context so the virtual modules plugin can read it.\n */\n const discovered = new Map<string, DiscoveredModule>()\n let server: ViteDevServer | null = null\n\n // Expose discovered modules on the context for virtual-modules plugin\n ;(ctx as any).discoveredModules = discovered\n\n return {\n name: 'kickjs:module-discovery',\n\n configureServer(viteServer) {\n server = viteServer\n\n // Watch for new/deleted files in the modules directory\n viteServer.watcher.on('add', (filePath) => {\n if (MODULE_FILE_PATTERN.test(filePath)) {\n // File added — it will be processed in transform() when first imported.\n // Invalidate virtual module so it picks up the new file on next request.\n invalidateVirtualApp(viteServer)\n }\n })\n\n viteServer.watcher.on('unlink', (filePath) => {\n if (discovered.has(filePath)) {\n discovered.delete(filePath)\n invalidateVirtualApp(viteServer)\n }\n })\n },\n\n /**\n * Transform hook — called for every file Vite processes.\n *\n * We don't actually transform the code (return null), but we use this\n * hook to observe which files contain module classes. This is cheaper\n * than AST parsing — a regex match on the source is sufficient because\n * module files follow a consistent naming pattern (`*.module.ts`).\n */\n transform(code: string, id: string) {\n // Only scan files matching the module pattern\n if (!MODULE_FILE_PATTERN.test(id)) return null\n // Skip node_modules\n if (id.includes('node_modules')) return null\n\n const match = code.match(MODULE_CLASS_REGEX)\n if (match) {\n const className = match[1]\n const wasNew = !discovered.has(id)\n discovered.set(id, { filePath: id, className })\n\n if (wasNew && server) {\n // New module discovered — invalidate virtual module\n invalidateVirtualApp(server)\n }\n } else if (discovered.has(id)) {\n // File no longer exports a module class (user removed it)\n discovered.delete(id)\n if (server) {\n invalidateVirtualApp(server)\n }\n }\n\n // Return null — we don't transform the code, just observe it\n return null\n },\n\n /**\n * HMR hook — called when a file changes.\n *\n * If a module file changes, we re-scan it and invalidate the virtual\n * module so the next request picks up the changes.\n */\n handleHotUpdate({ file, server: viteServer }) {\n if (!MODULE_FILE_PATTERN.test(file)) return\n\n // The file will be re-processed in transform() on next import.\n // Invalidate the virtual module so it regenerates with fresh imports.\n invalidateVirtualApp(viteServer)\n },\n }\n}\n\n/**\n * Invalidate the virtual:kickjs/app module in Vite's module graph.\n * This forces the next `ssrLoadModule()` call to re-evaluate the\n * virtual module, picking up any new/removed modules.\n */\nfunction invalidateVirtualApp(server: ViteDevServer): void {\n const mod = server.moduleGraph.getModuleById(RESOLVED_APP)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n // Re-warm immediately so a broken module file surfaces its error on\n // save instead of on the next HTTP request (see warm.ts).\n rewarmApp(server, 'module discovery change')\n}\n\n/**\n * Get the current list of discovered modules.\n * Used by the virtual modules plugin to generate auto-imports.\n */\nexport function getDiscoveredModules(ctx: PluginContext): DiscoveredModule[] {\n const map = (ctx as any).discoveredModules as Map<string, DiscoveredModule> | undefined\n return map ? [...map.values()] : []\n}\n","/**\n * HMR plugin for KickJS — selective container invalidation when source\n * files change, with debounced batching for bulk operations.\n *\n * ## How It Works\n *\n * 1. During `transform()`, the plugin scans for decorator patterns\n * (`@Service`, `@Controller`, etc.) and maps file paths to DI token names\n * 2. When a file changes (`handleHotUpdate()`), the plugin:\n * - Looks up which DI tokens are defined in that file\n * - Calls `container.invalidate(token)` for each (which walks the dep graph)\n * - Invalidates the virtual module so `ssrLoadModule()` returns fresh code\n * - Sends a custom HMR event (`kickjs:hmr`) so DevTools/Swagger can react\n * 3. Changes are **debounced** (150ms) so `kick g module` creating 10+ files\n * emits ONE invalidation batch, not 10 separate events\n *\n * ## Interaction with Reactive Container\n *\n * `container.invalidate(token)` (from Step 3) does:\n * - Clears the cached instance for that token\n * - Walks the dependency graph to find dependents\n * - Invalidates all dependents recursively\n * - Emits batched `onChange()` events to all subscribers (Swagger, DevTools, etc.)\n *\n * ## Detection Strategy\n *\n * Uses regex patterns (not AST) for speed. This is the same approach\n * TanStack Start uses (`KindDetectionPatterns` in their compiler).\n * It's fast because:\n * - Only runs on files that actually contain decorator patterns\n * - No Babel/SWC parsing needed\n * - False positives are harmless (extra invalidation is safe)\n *\n * @module @forinda/kickjs-vite/hmr-plugin\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { HmrOptions, PluginContext } from './types'\nimport { RESOLVED_APP } from './virtual-modules'\nimport { rewarmApp } from './warm'\n\n/**\n * Test whether a watcher event refers to a file we should react to.\n *\n * Vite's chokidar fires for everything under the project root. We only\n * want code that the running app could realistically depend on:\n *\n * - **Source extensions only.** `.ts`, `.tsx`, `.js`, `.jsx`, `.mts`,\n * `.cts`, `.mjs`, `.cjs`. JSON / lockfiles / images / typegen\n * declaration files are noise.\n * - **Skip `.d.ts` declaration files.** They're regenerated by typegen\n * on every save and would create an invalidation loop with the\n * typegen watcher in `kick dev`.\n * - **Skip well-known noise directories.** `node_modules`, `dist`, the\n * `.kickjs` typegen output, `.git`, `coverage`, OS swap files.\n *\n * Errs on the inclusive side: a file that is genuinely unused but still\n * lives under `src/` causes a cheap virtual-app invalidation, no worse\n * than `kick dev`'s typegen sweep already does on the same event.\n */\n/** Whether the browser has loaded `file` through this dev server. */\nfunction isClientModule(server: ViteDevServer, file: string): boolean {\n const graph = server.environments?.client?.moduleGraph\n return (graph?.getModulesByFile(file)?.size ?? 0) > 0\n}\n\nfunction isProjectSource(file: string): boolean {\n if (!/\\.(?:ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(file)) return false\n if (file.endsWith('.d.ts') || file.endsWith('.d.mts') || file.endsWith('.d.cts')) return false\n if (\n file.includes('/node_modules/') ||\n file.includes('/.kickjs/') ||\n file.includes('/dist/') ||\n file.includes('/.git/') ||\n file.includes('/coverage/')\n ) {\n return false\n }\n return true\n}\n\n/** Strip directory components for a friendlier dev-console label. */\nfunction basename(file: string): string {\n const i = file.lastIndexOf('/')\n return i === -1 ? file : file.slice(i + 1)\n}\n\n/**\n * Regex patterns that detect KickJS decorator usage in source files.\n * Matches `@Service()`, `@Controller()`, `@Repository()`, etc.\n * followed by an exported class declaration.\n *\n * Pattern: decorator → optional whitespace → export? class ClassName\n */\nconst DECORATOR_CLASS_REGEX =\n /@(?:Service|Controller|Repository|Injectable|Component)\\s*\\([^)]*\\)\\s*\\n?\\s*(?:export\\s+)?class\\s+(\\w+)/g\n\n/**\n * Regex patterns that detect the v4 factory-style declarations:\n * `defineAdapter`, `definePlugin`, `defineContextDecorator`. These\n * produce values rather than decorated classes, so the class regex\n * above misses them and changes to plugin/adapter/contributor files\n * silently bypass kickjs HMR.\n *\n * Pattern: `export const Name = defineAdapter|definePlugin|defineContextDecorator(`\n * — captures the constant's name so it can be surfaced in the dev\n * console alongside the rest of the invalidation batch.\n */\nconst FACTORY_DECL_REGEX =\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::[^=]+)?=\\s*(defineAdapter|definePlugin|defineContextDecorator)\\s*[<(]/g\n\n/** Substrings that bail out the transform scanner before regex work. */\nconst FACTORY_KEYWORDS = ['defineAdapter', 'definePlugin', 'defineContextDecorator'] as const\nconst DECORATOR_KEYWORDS = [\n '@Service',\n '@Controller',\n '@Repository',\n '@Injectable',\n '@Component',\n] as const\n\n/** Debounce time for batching multiple file changes into one invalidation */\nconst DEBOUNCE_MS = 150\n\n/**\n * Creates the HMR selective invalidation plugin.\n *\n * Tracks which DI tokens are defined in which files, then selectively\n * invalidates only the affected tokens (and their dependents) when\n * those files change. Much faster than a full Container.reset().\n *\n * @param ctx - Shared plugin context\n * @returns Vite plugin\n */\nexport function kickjsHmrPlugin(ctx: PluginContext, hmrOptions: HmrOptions = {}): Plugin {\n /**\n * Maps file paths to the DI token names defined in them.\n * Built up during transform(), read during handleHotUpdate().\n *\n * @example\n * ```\n * '/src/modules/users/user.service.ts' → ['UserService']\n * '/src/modules/users/user.controller.ts' → ['UserController']\n * ```\n */\n const fileTokenMap = new Map<string, string[]>()\n\n /** Pending tokens to invalidate (accumulated during debounce window) */\n let pendingTokens = new Set<string>()\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n return {\n name: 'kickjs:hmr',\n\n /**\n * Transform hook — scans source files for decorator patterns.\n *\n * Doesn't modify the code (returns null), just records which\n * DI tokens are defined in each file. This mapping is used by\n * `handleHotUpdate()` to determine what to invalidate.\n */\n transform(code: string, id: string) {\n // Skip non-TypeScript/JavaScript files and node_modules\n if (!/\\.[tj]sx?$/.test(id)) return null\n if (id.includes('node_modules')) return null\n\n const hasDecorator = DECORATOR_KEYWORDS.some((kw) => code.includes(kw))\n const hasFactory = FACTORY_KEYWORDS.some((kw) => code.includes(kw))\n\n // Quick bail-out: nothing kickjs-relevant in the file\n if (!hasDecorator && !hasFactory) {\n if (fileTokenMap.has(id)) fileTokenMap.delete(id)\n return null\n }\n\n const tokens: string[] = []\n\n if (hasDecorator) {\n for (const m of code.matchAll(DECORATOR_CLASS_REGEX)) {\n tokens.push(m[1])\n }\n }\n\n if (hasFactory) {\n // Tag each entry with the factory kind so the HMR log line\n // distinguishes a controller-class invalidation from an adapter\n // / plugin / contributor reload — the second kind never maps\n // back to a DI token, but it still needs the virtual app\n // re-evaluated so bootstrap re-imports the new value.\n for (const m of code.matchAll(FACTORY_DECL_REGEX)) {\n tokens.push(`${m[1]} (${m[2]})`)\n }\n }\n\n if (tokens.length > 0) {\n fileTokenMap.set(id, tokens)\n } else if (fileTokenMap.has(id)) {\n fileTokenMap.delete(id)\n }\n\n return null\n },\n\n /**\n * HMR hook — called when a file changes in dev mode.\n *\n * If the changed file contains KickJS decorated classes:\n * 1. Accumulate the affected tokens in the debounce buffer\n * 2. After 150ms of quiet, flush: invalidate all tokens at once\n * 3. Invalidate the virtual module for fresh `ssrLoadModule()` response\n * 4. Send ONE `kickjs:hmr` event to the client (DevTools, Swagger UI)\n *\n * The 150ms debounce is critical for `kick g module` which creates\n * 10+ files in rapid succession. Without debouncing, each file would\n * trigger a separate invalidation cycle.\n *\n * Returns an empty array to tell Vite we handled the update\n * (prevents Vite's default full-page reload for these files).\n */\n handleHotUpdate({ file, server }) {\n // Reject anything outside the project's source surface — chokidar\n // also fires for `.kickjs/` typegen output, `dist/`, and editor\n // swap files that have nothing to do with the running app.\n if (!isProjectSource(file)) return\n\n const tokens = fileTokenMap.get(file)\n\n // Files with kickjs decorators / factories: accumulate their token\n // names so the dev console can name what changed. Files without a\n // tracked token (plain helpers, pure utilities, side-effect modules\n // like `hello.ts`) still trigger an invalidation — just labelled\n // by the file's basename so the user sees something happened.\n if (tokens && tokens.length > 0) {\n for (const t of tokens) pendingTokens.add(t)\n } else {\n pendingTokens.add(basename(file))\n }\n\n // Debounce: flush after 150ms of quiet\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n flushInvalidation(server, pendingTokens, hmrOptions)\n pendingTokens = new Set()\n }, DEBOUNCE_MS)\n\n // A module the browser imports (Inertia pages, a frontend served by\n // this dev server) keeps Vite's own HMR — React Fast Refresh, Vue and\n // Svelte hot updates. Answering `[]` for those swallowed the update,\n // so component edits only showed after a manual refresh.\n if (isClientModule(server, file)) return\n\n // Server-only: tell Vite we handled it — no full-page reload.\n // `flushInvalidation` always invalidates the virtual app module,\n // so the next ssrLoadModule re-imports the changed file via the\n // dev-server's middleware shim.\n return []\n },\n }\n}\n\n/**\n * Shape of the reactive-container handle the KickJS runtime publishes on\n * `globalThis` for dev-mode HMR. Optional all the way down — the container\n * only exists after the app has bootstrapped at least once, and older\n * runtime versions may not expose `invalidate`.\n */\ninterface KickHmrGlobal {\n __kickjs_container?: {\n invalidate?: (token: string) => void\n }\n}\n\n/**\n * Flush accumulated token invalidations.\n *\n * Called after the debounce window closes. Performs:\n * 1. Container invalidation (clears instances + walks dependency graph)\n * 2. Virtual module invalidation (forces ssrLoadModule to re-evaluate)\n * 3. HMR event broadcast (notifies DevTools, Swagger UI, etc.)\n *\n * @param server - Vite dev server\n * @param tokens - Set of DI token names to invalidate\n */\nfunction flushInvalidation(\n server: ViteDevServer,\n tokens: Set<string>,\n hmrOptions: HmrOptions,\n): void {\n const batch = [...tokens]\n if (batch.length === 0) return\n const timestamp = Date.now()\n\n // 1. Invalidate tokens in the reactive container (if available)\n // container.invalidate() walks the dependency graph and notifies subscribers\n const container = (globalThis as typeof globalThis & KickHmrGlobal).__kickjs_container\n if (container && typeof container.invalidate === 'function') {\n for (const token of batch) {\n container.invalidate(token)\n }\n }\n\n // 2. Invalidate the virtual module so next ssrLoadModule() re-evaluates\n const vmod = server.moduleGraph.getModuleById(RESOLVED_APP)\n if (vmod) {\n server.moduleGraph.invalidateModule(vmod)\n }\n // 2b. Re-warm immediately — without this, re-evaluation waits for the\n // next HTTP request, so a broken save (syntax error, boot throw)\n // stays SILENT until something hits the server. Mirrors the eager\n // startup warm in dev-server.ts.\n rewarmApp(server, `HMR invalidation (${batch.length} token${batch.length === 1 ? '' : 's'})`)\n\n // 3. Send ONE custom HMR event with the full batch\n // DevTools dashboard, Swagger UI, and other dev tools can listen:\n // import.meta.hot?.on('kickjs:hmr', (data) => { ... })\n server.hot.send({\n type: 'custom',\n event: 'kickjs:hmr',\n data: { tokens: batch, timestamp },\n })\n\n // 4. Dev-console log — three modes, in priority order:\n // a. `silent: true` → no log\n // b. `onInvalidation` provided → custom function controls the line\n // (returning a string emits one console.log, void/undefined =\n // suppresses, useful when piping to a structured logger or\n // overlay)\n // c. neither set → default `HMR invalidated N tokens: …` line\n if (hmrOptions.silent) return\n\n if (hmrOptions.onInvalidation) {\n const out = hmrOptions.onInvalidation({ tokens: batch, timestamp })\n if (typeof out === 'string') console.log(out)\n return\n }\n\n const names = batch.join(', ')\n const label = batch.length === 1 ? '1 token' : `${batch.length} tokens`\n console.log(` ${green('HMR')} invalidated ${label}: ${names}`)\n}\n\n/** ANSI green for terminal output */\nfunction green(text: string): string {\n return `\\x1b[32m${text}\\x1b[0m`\n}\n","// `devtoolsFlagPlugin()` — exposes `__KICKJS_DEVTOOLS__` as a build-time\n// constant adopters guard their devtools imports behind. Vite/Rollup's\n// existing dead-code-elimination strips the gated branch from production\n// bundles entirely (including any dynamic `import('@forinda/kickjs-devtools')`\n// inside the gate), giving \"devtools-in-dev, zero overhead in prod\"\n// without a babel pass.\n//\n// Adopter usage:\n//\n// const adapters = [/* prod adapters… */]\n// if (__KICKJS_DEVTOOLS__) {\n// const { DevToolsAdapter } = await import('@forinda/kickjs-devtools')\n// adapters.push(DevToolsAdapter({ basePath: '/_debug' }))\n// }\n//\n// bootstrap({ adapters, modules: [...] })\n//\n// Resolution order for the flag's value:\n// 1. explicit `enabled` option on the plugin → wins\n// 2. `KICKJS_DEVTOOLS=0|1` env var → operator-side override\n// 3. Vite `command` — `'serve'` (dev) → true, `'build'` → false.\n// `command` is cleaner than NODE_ENV: Vite passes it explicitly\n// to plugins regardless of how the user set their environment.\n//\n// The plugin returns a Vite `config` hook that adds the literal under\n// `define`. Vite's `define` is a verbatim-substitution map; stringifying\n// with JSON.stringify keeps the value a true / false token (no quotes\n// would break the parser).\n\nimport type { ConfigEnv, Plugin } from 'vite'\n\nexport interface DevtoolsFlagOptions {\n /**\n * Force the flag value. When set, environment-based detection is\n * bypassed entirely. Useful for explicit feature gates per build\n * profile.\n *\n * @default `vite command === 'serve'` (true in dev, false in build)\n */\n enabled?: boolean\n /**\n * Override the global name. Default `__KICKJS_DEVTOOLS__`.\n * Useful for adopters who want a project-specific flag name to\n * avoid colliding with another tooling's own globals.\n */\n flagName?: string\n}\n\n/**\n * Resolve the build-time devtools flag. Exposed for unit tests +\n * adopters who want to compute the same answer the plugin would.\n */\nexport function resolveDevtoolsFlag(opts: DevtoolsFlagOptions = {}, env?: ConfigEnv): boolean {\n if (typeof opts.enabled === 'boolean') return opts.enabled\n const envOverride = process.env.KICKJS_DEVTOOLS\n if (envOverride === '1' || envOverride === 'true') return true\n if (envOverride === '0' || envOverride === 'false') return false\n // env may be undefined when callers compute the flag outside a\n // Vite plugin invocation (tests). Fall back to NODE_ENV, failing\n // closed: an unset NODE_ENV leaves devtools out.\n if (env) return env.command === 'serve'\n return process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'\n}\n\nexport function devtoolsFlagPlugin(opts: DevtoolsFlagOptions = {}): Plugin {\n const flagName = opts.flagName ?? '__KICKJS_DEVTOOLS__'\n return {\n name: 'kickjs:devtools-flag',\n config(_userConfig, env) {\n const enabled = resolveDevtoolsFlag(opts, env)\n return {\n define: {\n [flagName]: JSON.stringify(enabled),\n },\n }\n },\n }\n}\n","/**\n * Babel-based devtools stripper for production builds.\n *\n * Built around a single rule: anything sourced from\n * `@forinda/kickjs-devtools-kit` (or any of its sub-paths) is dev-\n * only and must not ship in the prod bundle. The transform walks\n * each module and removes:\n *\n * 1. `import ... from '@forinda/kickjs-devtools-kit'` declarations\n * (named, default, namespace, side-effect — all forms).\n * 2. Top-level `ExpressionStatement`s whose call/expression root is\n * a binding imported from devtools-kit\n * (e.g., `defineDevtoolsRenderTab({...})`).\n * 3. Side-effect imports whose path ends in `/devtools-events`\n * (with any extension) — type-augmentation modules shipped by\n * adapter packages. Already side-effect-only, safe to drop in\n * prod.\n *\n * The transform is intentionally conservative. It will not:\n *\n * - Remove identifier *references* outside of the rules above. If\n * your code calls `defineDevtoolsRenderTab(...)` inside a regular\n * function body (i.e. not a top-level `ExpressionStatement`),\n * the reference stays. After we drop the import the build will\n * fail loud — that is the signal to gate the call behind\n * `__KICKJS_DEVTOOLS__` (see `devtools-flag-plugin.ts`).\n * - Touch files that don't import from devtools-kit at all.\n * - Touch files in `node_modules` (Vite's plugin chain handles\n * that already, but the transform short-circuits on a quick\n * string check too).\n *\n * The dev path is unchanged: this transform only runs when Vite's\n * `command === 'build'`. In dev, devtools-kit imports stay live.\n */\n\n// Namespace import, not a default import: Babel 8 ships as native ESM and\n// `@babel/core` exposes only named exports — `import babel from '@babel/core'`\n// fails at load with \"does not provide an export named 'default'\".\nimport * as babel from '@babel/core'\n\nconst DEVTOOLS_KIT_RE = /^@forinda\\/kickjs-devtools-kit(\\/.*)?$/\nconst DEVTOOLS_EVENTS_RE = /(^|\\/)devtools-events(\\.[a-z]+)?$/\n\nexport interface StripDevtoolsOptions {\n /**\n * When `false`, skips files that don't import devtools-kit. The\n * default short-circuit is a substring check on the source text;\n * disable it only for tests where you want the visitor to run\n * unconditionally.\n *\n * @default true\n */\n fastReject?: boolean\n}\n\nexport interface StripResult {\n /** Transformed source. Returns the original `code` when nothing was stripped. */\n code: string\n /** `true` if the visitor removed at least one node. */\n changed: boolean\n}\n\n/**\n * Strip devtools-kit imports and their dependent top-level calls\n * from a single TypeScript module. Pure — no I/O, no Vite, no\n * filesystem.\n */\nexport function stripDevtoolsCode(\n source: string,\n filename: string,\n opts: StripDevtoolsOptions = {},\n): StripResult {\n if (opts.fastReject !== false) {\n if (!source.includes('@forinda/kickjs-devtools-kit') && !source.includes('devtools-events')) {\n return { code: source, changed: false }\n }\n }\n\n let changed = false\n\n // Add the `jsx` plugin only for files that may contain JSX —\n // `.tsx` / `.jsx`. Mixing `jsx` + `typescript` on a `.ts` file\n // breaks the angle-bracket type-assertion syntax (`<T>x`); kept\n // off by default. `.tsx` files would otherwise fail to parse on\n // any embedded JSX.\n const isJsx = /\\.(?:tsx|jsx)$/i.test(filename)\n const parserPlugins: string[] = ['typescript', 'decorators-legacy', 'classProperties']\n if (isJsx) parserPlugins.push('jsx')\n\n const result = babel.transformSync(source, {\n filename,\n babelrc: false,\n configFile: false,\n sourceType: 'module',\n parserOpts: {\n plugins: parserPlugins as never,\n },\n generatorOpts: {\n retainLines: true,\n },\n plugins: [\n function devtoolsStripPlugin(): babel.PluginObject {\n return {\n name: 'kickjs-strip-devtools',\n visitor: {\n Program(path) {\n const devtoolsBindings = new Set<string>()\n\n // Pass 1 — drop devtools-kit imports + collect bound names.\n for (const stmt of path.get('body')) {\n if (!stmt.isImportDeclaration()) continue\n const src = stmt.node.source.value\n if (!DEVTOOLS_KIT_RE.test(src) && !DEVTOOLS_EVENTS_RE.test(src)) continue\n\n for (const spec of stmt.node.specifiers) {\n if (spec.local?.name) devtoolsBindings.add(spec.local.name)\n }\n stmt.remove()\n changed = true\n }\n\n if (devtoolsBindings.size === 0) return\n\n // Pass 2 — drop top-level expression statements rooted\n // in a stripped binding.\n for (const stmt of path.get('body')) {\n if (!stmt.isExpressionStatement()) continue\n const root = rootIdentifier(stmt.node.expression)\n if (root && devtoolsBindings.has(root)) {\n stmt.remove()\n changed = true\n }\n }\n },\n },\n }\n },\n ],\n })\n\n // Return the original source verbatim when nothing was stripped —\n // Babel's generator otherwise normalises whitespace + adds\n // semicolons, which would invalidate Vite's cache for files that\n // shouldn't have changed at all.\n if (!result || result.code == null || !changed) {\n return { code: source, changed: false }\n }\n return { code: result.code, changed: true }\n}\n\n/**\n * Walk a call/member expression tree to its root identifier. Returns\n * `null` for expressions we don't recognize (literals, sequence\n * expressions, etc.) — the caller skips those rather than guessing.\n */\nfunction rootIdentifier(expr: babel.types.Expression): string | null {\n let node: babel.types.Node = expr\n while (true) {\n if (node.type === 'Identifier') return node.name\n if (node.type === 'CallExpression') {\n node = node.callee\n continue\n }\n if (node.type === 'MemberExpression') {\n node = node.object\n continue\n }\n if (node.type === 'TSAsExpression' || node.type === 'TSNonNullExpression') {\n node = node.expression\n continue\n }\n return null\n }\n}\n","/**\n * Vite plugin wrapping `stripDevtoolsCode` for production builds.\n *\n * Runs only when Vite's `command === 'build'`. In dev the plugin is\n * a no-op so the devtools UI keeps working under `kick dev`.\n *\n * Pairs with `devtoolsFlagPlugin()` — that one constant-folds\n * `if (__KICKJS_DEVTOOLS__)` branches via Vite's existing DCE; this\n * one strips top-level devtools-kit imports + their `defineDevtoolsRenderTab(...)` /\n * `defineDevtoolsTab(...)` call sites without requiring adopters to\n * wrap them in the flag.\n */\n\nimport type { Plugin } from 'vite'\nimport { stripDevtoolsCode } from './babel-strip-devtools'\nimport { resolveDevtoolsFlag, type DevtoolsFlagOptions } from './devtools-flag-plugin'\n\nexport interface DevtoolsStripOptions {\n /**\n * Force enable / disable. Default: on for `vite build` when the devtools flag is off.\n * Adopters running a debug-prod build (`kick build` with the flag\n * forced on) can pass `false` to keep devtools-kit code in the\n * bundle.\n */\n enabled?: boolean\n /**\n * Glob-like include pattern. Default: any `.ts` / `.tsx` /\n * `.mts` / `.cts` file under the project root. The transform is\n * a no-op on files that don't import devtools-kit, so this is\n * normally fine to leave at the default.\n */\n include?: RegExp\n /**\n * The devtools flag options the build uses (`kickjsVitePlugin({ devtools })`).\n * Without an explicit `enabled`, the strip runs only when that flag is off —\n * a build that keeps DevTools keeps its tabs.\n */\n devtools?: DevtoolsFlagOptions\n}\n\nconst DEFAULT_INCLUDE = /\\.(?:m|c)?[jt]sx?$/\n\n/**\n * Strips devtools-kit imports + their top-level call sites from\n * production bundles. See `babel-strip-devtools.ts` for the exact\n * rule set.\n */\nexport function devtoolsStripPlugin(opts: DevtoolsStripOptions = {}): Plugin {\n let active = false\n const include = opts.include ?? DEFAULT_INCLUDE\n\n return {\n name: 'kickjs:devtools-strip',\n enforce: 'pre',\n apply: 'build',\n config(_userConfig, env) {\n active = opts.enabled ?? (env.command === 'build' && !resolveDevtoolsFlag(opts.devtools, env))\n },\n transform(code, id) {\n if (!active) return null\n if (id.includes('node_modules')) return null\n if (!include.test(id)) return null\n const result = stripDevtoolsCode(code, id)\n if (!result.changed) return null\n return { code: result.code, map: null }\n },\n }\n}\n","/**\n * kickjs:typegen — typegen-on-save for plain `vite` boots.\n *\n * `kick dev` owns the typegen watcher when it boots Vite (it claims\n * ownership on `globalThis` before `createServer`). But adopters who\n * run bare `vite` (the pre-fix scaffold default, or any Vite-embedding\n * tool) historically got working HMR with silently frozen\n * `.kickjs/types` — new routes lost their typing until a manual\n * `kick typegen`.\n *\n * This plugin closes that gap: when nothing has claimed ownership, it\n * dynamically loads the PROJECT's `@forinda/kickjs-cli` (optional peer\n * — resolved from the project root, never bundled) and wires the same\n * `createTypegenDevWatcher` engine `kick dev` uses, plus one startup\n * catch-up pass. No CLI installed → quiet no-op with a one-line notice.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\n/** Mirror of the CLI's TYPEGEN_OWNER_KEY — string-duplicated so this\n * module never needs the CLI at import time. */\nconst OWNER_KEY = '__kickjs_typegen_owner'\n\n/** Structural slice of the CLI surface this plugin consumes. */\nexport interface TypegenCliModule {\n loadKickConfig(cwd: string): Promise<unknown>\n createTypegenDevWatcher(opts: {\n cwd: string\n config: unknown\n emitWarning: (message: string) => void\n }): {\n handleWatchEvent(event: 'add' | 'change' | 'unlink' | 'unlinkDir', file: string): void\n runOnce(): void\n assetSrcRoots: readonly string[]\n dispose(): void\n }\n}\n\n/**\n * Resolve `@forinda/kickjs-cli` from the PROJECT root (not from this\n * package — under pnpm's strict layout the vite plugin can't see the\n * CLI through its own node_modules). Walks `node_modules` upward and\n * reads the manifest directly with fs: the CLI is ESM-only (no\n * `require` condition in its exports map), so `createRequire().resolve`\n * throws ERR_PACKAGE_PATH_NOT_EXPORTED and can't be used here.\n * Returns null when not installed or too old to export the watcher\n * engine.\n */\nfunction resolveCliEntry(root: string): string | null {\n let dir = root\n for (;;) {\n const pkgDir = join(dir, 'node_modules', '@forinda', 'kickjs-cli')\n const manifestPath = join(pkgDir, 'package.json')\n if (existsSync(manifestPath)) {\n try {\n const pkg = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n exports?: Record<string, unknown>\n module?: string\n main?: string\n }\n const dot = pkg.exports?.['.'] as string | Record<string, unknown> | undefined\n const fromExports =\n typeof dot === 'string'\n ? dot\n : typeof dot?.import === 'string'\n ? dot.import\n : typeof (dot?.import as Record<string, unknown> | undefined)?.default === 'string'\n ? ((dot!.import as Record<string, unknown>).default as string)\n : typeof dot?.default === 'string'\n ? (dot.default as string)\n : undefined\n const entryRel = fromExports ?? pkg.module ?? pkg.main\n if (typeof entryRel === 'string') return join(pkgDir, entryRel)\n } catch {\n // Unreadable manifest — keep walking up.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nasync function loadCliFromProject(root: string): Promise<TypegenCliModule | null> {\n try {\n const entry = resolveCliEntry(root)\n if (!entry || !existsSync(entry)) return null\n const mod = (await import(pathToFileURL(entry).href)) as Partial<TypegenCliModule>\n if (\n typeof mod.createTypegenDevWatcher === 'function' &&\n typeof mod.loadKickConfig === 'function'\n ) {\n return mod as TypegenCliModule\n }\n return null\n } catch {\n return null\n }\n}\n\nexport interface TypegenPluginOptions {\n /** Test seam — defaults to project-root resolution of the real CLI. */\n loadCli?: (root: string) => Promise<TypegenCliModule | null>\n}\n\nexport function kickjsTypegenPlugin(opts: TypegenPluginOptions = {}): Plugin {\n const loadCli = opts.loadCli ?? loadCliFromProject\n return {\n name: 'kickjs:typegen',\n apply: 'serve',\n\n async configureServer(server: ViteDevServer) {\n // `kick dev` boots Vite in-process and runs its own watcher —\n // stand down so the pipeline never double-runs.\n if ((globalThis as Record<string, unknown>)[OWNER_KEY]) return\n\n const root = server.config.root\n const cli = await loadCli(root)\n if (!cli) {\n server.config.logger.info(\n '[kickjs] typegen-on-save disabled — @forinda/kickjs-cli not resolvable from the ' +\n 'project (install it, or run `kick dev`).',\n )\n return\n }\n\n const config = await cli.loadKickConfig(root).catch(() => null)\n const watcher = cli.createTypegenDevWatcher({\n cwd: root,\n config,\n emitWarning: (message) => {\n server.config.logger.warn(message)\n server.hot.send({\n type: 'custom',\n event: 'kickjs:typegen-error',\n data: { message, timestamp: Date.now() },\n })\n },\n })\n\n // Startup catch-up — bare `vite` has no pre-server typegen pass\n // (kick dev runs one before createServer), so types may be stale\n // from edits made while no dev server was running.\n watcher.runOnce()\n\n server.watcher.on('add', (f: string) => watcher.handleWatchEvent('add', f))\n server.watcher.on('change', (f: string) => watcher.handleWatchEvent('change', f))\n server.watcher.on('unlink', (f: string) => watcher.handleWatchEvent('unlink', f))\n server.watcher.on('unlinkDir', (d: string) => watcher.handleWatchEvent('unlinkDir', d))\n if (watcher.assetSrcRoots.length > 0) {\n server.watcher.add([...watcher.assetSrcRoots])\n }\n if (server.httpServer) {\n server.httpServer.once('close', () => watcher.dispose())\n } else {\n // Middleware mode — no httpServer; tie disposal to the chokidar\n // watcher's own close so the debounce timer can't leak.\n server.watcher.once('close', () => watcher.dispose())\n }\n },\n }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { reloadEnv } from '@forinda/kickjs'\nimport type { Plugin } from 'vite'\n\n/**\n * Vite plugin that watches `.env` files and triggers a full reload\n * when they change. This ensures the dev server picks up environment\n * variable changes without a manual restart.\n *\n * Lives in `@forinda/kickjs-vite` so all Vite-only concerns are in one\n * place.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { envWatchPlugin } from '@forinda/kickjs-vite'\n *\n * export default defineConfig({\n * plugins: [swc.vite(), envWatchPlugin()],\n * })\n * ```\n */\nexport function envWatchPlugin(): Plugin {\n const envFiles = ['.env', '.env.local', '.env.development', '.env.production', '.env.test']\n\n return {\n name: 'kickjs-env-watch',\n\n configureServer(server) {\n const root = server.config.root\n\n for (const file of envFiles) {\n const filePath = path.resolve(root, file)\n if (fs.existsSync(filePath)) {\n server.watcher.add(filePath)\n }\n }\n\n server.watcher.on('change', (changedPath) => {\n const basename = path.basename(changedPath)\n if (envFiles.includes(basename)) {\n server.config.logger.info(` .env changed (${basename}), triggering reload...`, {\n timestamp: true,\n })\n\n // Re-read the .env file into process.env *before* invalidating\n // modules. Without this, the next SSR evaluation parses the\n // (stale) cached env snapshot — Zod throws on the missing key\n // and the user has to hard-restart the dev server.\n try {\n reloadEnv()\n } catch (err: any) {\n server.config.logger.warn(\n ` env reload failed: ${err?.message ?? err} — restart may be required`,\n { timestamp: true },\n )\n }\n\n // Invalidate all modules to trigger full HMR rebuild\n const mods = server.moduleGraph.getModulesByFile(path.resolve(root, 'src/index.ts'))\n if (mods) {\n for (const mod of mods) {\n server.moduleGraph.invalidateModule(mod)\n }\n }\n\n server.ws.send({ type: 'full-reload' })\n }\n })\n },\n }\n}\n","/**\n * @forinda/kickjs-vite — Vite plugin for the KickJS framework.\n *\n * Provides first-class Vite integration for KickJS backend applications:\n * - **Dev server**: Mounts the app on Vite's HTTP server (single port)\n * - **HMR**: Fresh server code on every request via `ssrLoadModule()`\n * - **httpServer piping**: Real `http.Server` available to all adapters\n * - **Virtual modules**: Auto-generated application entry\n *\n * ## Quick Start\n *\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import { kickjsVitePlugin } from '@forinda/kickjs-vite'\n * import swc from 'unplugin-swc'\n *\n * export default defineConfig({\n * plugins: [\n * swc.vite({ tsconfigFile: 'tsconfig.json' }),\n * kickjsVitePlugin({ entry: 'src/index.ts' }),\n * ],\n * })\n * ```\n *\n * ```ts\n * // src/index.ts\n * import { bootstrap } from '@forinda/kickjs'\n * import { UserModule } from './modules/users/user.module'\n *\n * // Export the app — Vite serves it in dev, you start it in prod\n * export const app = bootstrap({\n * modules: [UserModule],\n * middlewares: [express.json()],\n * })\n *\n * // Production: start the server directly\n * if (process.env.NODE_ENV === 'production') {\n * app.start()\n * }\n * ```\n *\n * ## Architecture\n *\n * The plugin returns an array of focused sub-plugins (React Router pattern):\n *\n * | Plugin | Responsibility |\n * |--------|---------------|\n * | `kickjs:core` | Vite config: appType, SSR environment, externals |\n * | `kickjs:module-discovery` | Auto-discover `@Module` classes via `transform()` |\n * | `kickjs:hmr` | Selective container invalidation via `handleHotUpdate()` |\n * | `kickjs:virtual-modules` | `virtual:kickjs/app` resolution and generation |\n * | `kickjs:dev-server` | `configureServer()` — mounts the app, pipes httpServer |\n *\n * ## httpServer Piping\n *\n * Vite creates the `http.Server` — this plugin stores it on\n * `globalThis.__kickjs_httpServer`. KickJS adapters (WsAdapter, Socket.IO,\n * GraphQL subscriptions) attach to this server via the standard\n * `afterStart({ server })` hook. Zero adapter code changes needed.\n *\n * @see https://kickjs.app/api/vite\n *\n * @module @forinda/kickjs-vite\n */\n\nimport { kickViewsPlugin } from './kick-views-plugin'\nimport { resolve } from 'node:path'\nimport type { Plugin } from 'vite'\nimport type { KickJSPluginOptions, PluginContext } from './types'\nimport { kickjsCorePlugin } from './core-plugin'\nimport { kickjsVirtualModulesPlugin } from './virtual-modules'\nimport { kickjsDevServerPlugin } from './dev-server'\nimport { kickjsModuleDiscoveryPlugin } from './module-discovery'\nimport { kickjsHmrPlugin } from './hmr-plugin'\nimport { devtoolsFlagPlugin } from './devtools-flag-plugin'\nimport { devtoolsStripPlugin } from './devtools-strip-plugin'\nimport { kickjsTypegenPlugin } from './typegen-plugin'\n\n/**\n * Create the KickJS Vite plugin array.\n *\n * Returns an array of focused sub-plugins that together provide full\n * Vite integration for KickJS backend applications. Each sub-plugin\n * has a single responsibility and runs at the appropriate Vite lifecycle stage.\n *\n * @param options - Plugin configuration\n * @param options.entry - Path to app entry file (default: 'src/index.ts')\n * @returns Array of Vite plugins\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import { kickjsVitePlugin } from '@forinda/kickjs-vite'\n * import swc from 'unplugin-swc'\n *\n * export default defineConfig({\n * plugins: [\n * swc.vite({ tsconfigFile: 'tsconfig.json' }),\n * kickjsVitePlugin(),\n * ],\n * })\n * ```\n */\nexport { kickViewsPlugin, type KickViewsPluginOptions } from './kick-views-plugin'\n\nexport function kickjsVitePlugin(options: KickJSPluginOptions = {}): Plugin[] {\n const entry = options.entry ?? 'src/index.ts'\n\n // Create shared context — resolved lazily in config hook since we\n // don't have the root directory until Vite resolves its config.\n const ctx: PluginContext = {\n entry,\n root: process.cwd(),\n }\n\n // Resolve root and entry as early as possible so sub-plugin config() hooks\n // (e.g., warmup) see the correct absolute entry path.\n const rootResolver: Plugin = {\n name: 'kickjs:root-resolver',\n config(config) {\n const root = config.root ?? process.cwd()\n ctx.root = root\n ctx.entry = resolve(root, entry)\n },\n }\n\n const plugins: Plugin[] = [\n rootResolver,\n kickjsCorePlugin(ctx),\n kickjsModuleDiscoveryPlugin(ctx),\n kickjsHmrPlugin(ctx, options.hmr),\n kickjsVirtualModulesPlugin(ctx),\n kickjsDevServerPlugin(ctx),\n // Typegen-on-save for bare `vite` boots — no-op under `kick dev`\n // (which claims ownership) or when @forinda/kickjs-cli is absent.\n kickjsTypegenPlugin(),\n // `virtual:kick-views` for .kick templates — inert unless the app imports it.\n ...(options.views === false ? [] : [kickViewsPlugin(options.views)]),\n ]\n // Register the devtools flag plugin by default. Adopters who don't\n // gate their devtools imports get a harmless no-op; adopters who do\n // get tree-shaking for free. Pass `devtools: false` to skip.\n if (options.devtools !== false) {\n plugins.push(devtoolsFlagPlugin(options.devtools ?? {}))\n // Babel-based strip — runs only on `vite build`, removes\n // devtools-kit imports + their top-level call sites without\n // requiring adopters to gate them behind the flag. See\n // `babel-strip-devtools.ts` for the rule set.\n plugins.push(devtoolsStripPlugin({ devtools: options.devtools ?? {} }))\n }\n return plugins\n}\n\n// Re-export types for consumers\nexport type {\n KickJSPluginOptions,\n PluginContext,\n HmrOptions,\n HmrInvalidationContext,\n DevtoolsOptions,\n} from './types'\n\n// Standalone plugins users can compose alongside `kickjsVitePlugin()`\nexport { envWatchPlugin } from './env-watch-plugin'\nexport {\n kickjsTypegenPlugin,\n type TypegenPluginOptions,\n type TypegenCliModule,\n} from './typegen-plugin'\nexport {\n devtoolsFlagPlugin,\n resolveDevtoolsFlag,\n type DevtoolsFlagOptions,\n} from './devtools-flag-plugin'\nexport { devtoolsStripPlugin, type DevtoolsStripOptions } from './devtools-strip-plugin'\nexport {\n stripDevtoolsCode,\n type StripDevtoolsOptions,\n type StripResult,\n} from './babel-strip-devtools'\nexport { compressAssets, compressDirectory, type CompressAssetsOptions } from './compress-plugin'\n"],"mappings":";;;;;;;;;;+XAmCA,MACM,SAAW,uBAEjB,eAAe,UAAU,IAAgC,CAGvD,OAFK,WAAW,GAAG,GAEZ,MADe,QAAQ,IAAK,CAAE,UAAW,GAAM,cAAe,EAAK,CAAC,EAAA,CAExE,OAAQ,GAAM,EAAE,OAAO,GAAK,EAAE,KAAK,SAAS,OAAO,CAAC,CAAC,CACrD,IAAK,GACJ,SAAS,IAAK,KAAK,UAAU,CAAC,EAAG,EAAE,IAAI,CAAC,CAAC,CACtC,MAAM,EAAG,EAAe,CAAC,CACzB,MAAM,GAAG,CAAC,CACV,KAAK,GAAG,CACb,CAAC,CACA,SAAS,EAViB,CAAC,CAWhC,CAEA,SAAgB,gBAAgB,QAAkC,CAAC,EAAW,CAC5E,IAAI,SAAW,GACX,UAAY,GACZ,MAAQ,GACR,QAEE,YAAc,QAAQ,kBAAoB,WAAA,CAAY,QAAQ,OAAQ,EAAE,EACxE,OAAS,QAAQ,cAAgB,SAEnC,UACE,aAAe,MAAM,KAAK,QAAQ,WAAa,SAAU,WAAW,MAAM,CAAC,CAAC,EAC9E,KAAO,GAEP,OAA4B,CAAC,EAGjC,eAAe,eAAe,IAIV,CAClB,IAAM,SAAW,WAAW,SAAS,EAE/B,KAAO,MAAM,OAAO,wBACpB,MAAQ,MAAM,UAAU,QAAQ,EAChC,OAAmB,CAAC,EACpB,UAAY,CAAC,GAAG,KAAK,aAAa,EACxC,GAAI,SAAU,CACZ,IAAM,KAAO,KAAK,gBAAgB,MAAM,SAAS,UAAW,MAAM,EAAG,SAAS,EAC9E,UAAU,KAAK,GAAG,KAAK,KAAK,EAC5B,IAAK,IAAM,KAAK,KAAK,YACnB,OAAO,KAAK,GAAG,E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s","names":["OWNER_KEY"],"sources":["../src/kick-views-plugin.ts","../src/core-plugin.ts","../src/virtual-modules.ts","../src/dev-server.ts","../src/warm.ts","../src/module-discovery.ts","../src/hmr-plugin.ts","../src/devtools-flag-plugin.ts","../src/babel-strip-devtools.ts","../src/devtools-strip-plugin.ts","../src/typegen-plugin.ts","../src/env-watch-plugin.ts","../src/index.ts"],"sourcesContent":["/**\n * `virtual:kick-views` — the app's `.kick` templates, checked at build time\n * and shipped as data, plus its pipes file. A broken template fails the\n * build. Under `serve` the bundle is `null`: the app's file loader reads\n * templates and picks up edits on the next request.\n *\n * @module @forinda/kickjs-vite/kick-views-plugin\n */\nimport { existsSync } from 'node:fs'\nimport { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path'\nimport type { Plugin } from 'vite'\n\nexport interface KickViewsPluginOptions {\n /** Default `src/views`. */\n viewsDir?: string\n /** Default `src/views/pipes.ts`. */\n pipesFile?: string\n /** The app's browser validators. Default `<viewsDir>/validators.ts`. */\n validatorsFile?: string\n /** Default `components`, inside the views folder. */\n componentsDir?: string\n /** Where component scripts are served (the views' `clientScriptPath`). Default `'/_kick/c'`. */\n clientScriptPath?: string\n /**\n * Where `kick build` puts client files: `'disk'` (default) writes them to\n * `<outDir>/<publicDir><clientScriptPath>/`, served from disk on Node and by\n * the platform's static files on the edge; `'bundle'` keeps them in the\n * server bundle, for hosts with no static files.\n */\n clientFiles?: 'disk' | 'bundle'\n /** Default `'public'`, relative to the build's `outDir` (or absolute). */\n publicDir?: string\n /** Images and fonts up to this many bytes are inlined (`'disk'` mode). Default `4096`. */\n inlineLimit?: number\n}\n\nconst ID = 'virtual:kick-views'\nconst RESOLVED = '\\0virtual:kick-views'\n\nasync function kickFiles(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return []\n const entries = await readdir(dir, { recursive: true, withFileTypes: true })\n return entries\n .filter((e) => e.isFile() && e.name.endsWith('.kick'))\n .map((e) =>\n relative(dir, join(direntDir(e), e.name))\n .slice(0, -'.kick'.length)\n .split(sep)\n .join('/'),\n )\n .toSorted()\n}\n\nexport function kickViewsPlugin(options: KickViewsPluginOptions = {}): Plugin {\n let viewsDir = ''\n let pipesFile = ''\n let validatorsFile = ''\n /** The module that registers validators.ts's exports: a namespace import keeps every one. */\n const validatorsEntry = () => join(dirname(validatorsFile), VALIDATORS_TAG)\n /** Compared resolved: Vite normalises ids (forward slashes on Windows) before `load`. */\n const isValidatorsEntry = (id: string) =>\n !!validatorsFile && resolve(id) === resolve(validatorsEntry() + CLIENT_SUFFIX)\n let build = true\n let checked: string | undefined\n // Exported by the virtual module, so `createViews({ ...kickViews })` serves where this plugin does.\n const scriptPath = (options.clientScriptPath ?? '/_kick/c').replace(/\\/+$/, '')\n const onDisk = options.clientFiles !== 'bundle'\n /** Client files to write beside the server bundle, by path inside its `outDir`. */\n let clientOut: Map<string, string | Uint8Array> | undefined\n /** The client files the last build wrote, by absolute path. */\n let written = new Set<string>()\n const clientFolder = posix.join(options.publicDir ?? 'public', scriptPath.slice(1))\n let root = ''\n // What the nested browser build takes from the app's config.\n let shared: ClientBuildConfig = {}\n\n /** Parse and check every template; the bundle as JSON, or a build error listing every problem. */\n async function checkTemplates(ctx: {\n addWatchFile(id: string): void\n warn(message: string): void\n error(message: string): never\n }): Promise<string> {\n const hasPipes = existsSync(pipesFile)\n // Empty, a rebuild with no client scripts left still clears the last build's files.\n clientOut = onDisk ? new Map() : undefined\n // The view package is optional: only apps that import this module need it.\n const view = await import('@forinda/kickjs-view')\n const names = await kickFiles(viewsDir)\n const errors: string[] = []\n const pipeNames = [...view.BUILTIN_PIPES]\n if (hasPipes) {\n const read = view.readPipeExports(await readFile(pipesFile, 'utf8'), pipesFile)\n pipeNames.push(...read.names)\n for (const d of read.diagnostics) {\n errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)\n }\n }\n const validators = new Set<string>()\n const hasValidators = existsSync(validatorsFile)\n if (hasValidators) {\n ctx.addWatchFile(validatorsFile)\n if (!('readValidatorExports' in view))\n errors.push('custom validators need a newer @forinda/kickjs-view: upgrade it')\n else {\n const read = view.readValidatorExports(\n await readFile(validatorsFile, 'utf8'),\n validatorsFile,\n )\n for (const n of read.names) validators.add(n)\n for (const d of read.diagnostics)\n errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)\n }\n }\n const templates = new Map()\n for (const name of names) {\n const file = join(viewsDir, `${name}.kick`)\n ctx.addWatchFile(file)\n const parsed = view.parse(await readFile(file, 'utf8'), `${name}.kick`)\n templates.set(name, parsed.ast)\n for (const d of parsed.diagnostics) {\n if (d.severity === 'error')\n errors.push(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`)\n }\n }\n const project = {\n templates,\n pipes: new Set(pipeNames),\n validators,\n componentsDir: options.componentsDir ?? 'components',\n }\n const checked: Record<string, unknown> = {}\n for (const name of names) {\n const r = view.check(name, project)\n for (const d of r.diagnostics) {\n const line = `${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`\n if (d.severity === 'error') errors.push(line)\n else ctx.warn(line)\n }\n if (r.template) checked[name] = r.template\n }\n // Client scripts bundled together: imports resolved, shared code in shared chunks.\n const scripts = Object.entries(checked as Record<string, { client?: { code: string } }>)\n .filter(([, t]) => t.client)\n .map(([name, t]) => ({\n tag: view.componentTag(name, project.componentsDir),\n file: join(viewsDir, `${name}.kick`),\n code: t.client!.code,\n }))\n // validators.ts: one more entry, so it's bundled even with no component scripts.\n if (hasValidators)\n scripts.push({\n tag: VALIDATORS_TAG,\n file: validatorsEntry(),\n code: validatorsWrapper(validatorsFile),\n })\n let client: ClientBundle | undefined\n if (scripts.length && onDisk && !('useClientFiles' in view))\n errors.push(\n \"client files on disk need @forinda/kickjs-view 0.3 or later: upgrade it, or set views: { clientFiles: 'bundle' }\",\n )\n else if (scripts.length) {\n try {\n client = await bundleClientScripts(\n scripts,\n root,\n shared,\n scriptPath,\n onDisk ? (options.inlineLimit ?? 4096) : () => true,\n )\n } catch (err) {\n errors.push(`<script client> bundling failed: ${(err as Error).message}`)\n }\n }\n // `<script client>` ships as plain JS: the edge never strips types.\n for (const [name, t] of Object.entries(checked) as Array<\n [string, { client?: { code: string; js: boolean } }]\n >) {\n if (!t.client || t.client.js) continue\n // Bundled: the views serve the bundle's files, not this source.\n if (client) {\n t.client = { code: '', js: true }\n continue\n }\n try {\n t.client = { code: await stripTs(t.client.code, `${name}.ts`), js: true }\n } catch (err) {\n errors.push(`${name}.kick — <script client>: ${(err as Error).message}`)\n }\n }\n if (errors.length)\n ctx.error(`.kick templates have errors:\\n ${[...new Set(errors)].join('\\n ')}`)\n let out: Record<string, unknown> | undefined\n if (client && onDisk) {\n // Vite drops assets from server builds: written in `writeBundle` instead.\n clientOut = new Map(\n Object.entries(client.files).map(([name, source]) => [\n posix.join(clientFolder, name),\n source,\n ]),\n )\n out = { entries: client.entries, css: client.css, disk: Object.keys(client.files) }\n } else if (client) {\n for (const [name, source] of Object.entries(client.files))\n if (typeof source !== 'string')\n ctx.error(`client file ${name} isn't text: use clientFiles: 'disk' to serve it`)\n out = client\n }\n return JSON.stringify({ v: view.AST_FORMAT_VERSION, templates: checked, client: out }, null, 1)\n }\n\n return {\n name: 'kickjs:views',\n configResolved(config) {\n viewsDir = resolve(config.root, options.viewsDir ?? 'src/views')\n pipesFile = resolve(config.root, options.pipesFile ?? 'src/views/pipes.ts')\n // Beside the views, as the editor and `kick check:views` look for it.\n validatorsFile = options.validatorsFile\n ? resolve(config.root, options.validatorsFile)\n : join(viewsDir, 'validators.ts')\n build = config.command === 'build'\n root = config.root\n shared = {\n mode: config.mode,\n define: config.define,\n envDir: config.envDir,\n envPrefix: config.envPrefix,\n resolve: { alias: config.resolve?.alias ?? [] },\n }\n },\n resolveId(id) {\n if (id === ID) return RESOLVED\n // A component's client script, as a module next to its `.kick` file.\n if (clientModuleFile(id, viewsDir)) return id\n if (isValidatorsEntry(id)) return id\n return undefined\n },\n // kick dev: component scripts through Vite's pipeline, so their imports\n // (relative, npm, aliases) resolve as they do in a build. Ahead of the app.\n configureServer(server) {\n const prefix = `${scriptPath}/`\n // An edited template's script is rebuilt on the next request.\n server.watcher.on('change', (file) => {\n const mod = server.moduleGraph.getModuleById(resolve(file) + CLIENT_SUFFIX)\n if (mod) server.moduleGraph.invalidateModule(mod)\n })\n server.middlewares.use(async (req, res, next) => {\n const url = (req.url ?? '').split('?')[0]!\n if ((req.method !== 'GET' && req.method !== 'HEAD') || !url.startsWith(prefix))\n return next()\n const m = /^([a-z][a-z0-9-]*)\\.[A-Za-z0-9_-]{8}\\.js$/.exec(url.slice(prefix.length))\n if (!m) return next()\n if (m[1] === VALIDATORS_TAG) {\n if (!existsSync(validatorsFile)) return next()\n try {\n const out = await server.transformRequest(validatorsEntry() + CLIENT_SUFFIX)\n if (!out) return next()\n res.statusCode = 200\n res.setHeader('content-type', 'text/javascript; charset=utf-8')\n res.setHeader('cache-control', 'no-cache')\n res.end(req.method === 'HEAD' ? undefined : out.code)\n } catch (err) {\n next(err)\n }\n return\n }\n try {\n const view = await import('@forinda/kickjs-view')\n const dir = options.componentsDir ?? 'components'\n const name = (await kickFiles(viewsDir)).find(\n (n) => n.startsWith(`${dir}/`) && view.componentTag(n, dir) === m[1],\n )\n if (!name) return next()\n const file = join(viewsDir, `${name}.kick`)\n if (clientScriptOf(view, await readFile(file, 'utf8')) === undefined) return next()\n const out = await server.transformRequest(file + CLIENT_SUFFIX)\n if (!out) return next()\n res.statusCode = 200\n res.setHeader('content-type', 'text/javascript; charset=utf-8')\n res.setHeader('cache-control', 'no-cache')\n res.end(req.method === 'HEAD' ? undefined : out.code)\n } catch (err) {\n next(err)\n }\n })\n },\n // In a build the templates are checked up front, whether or not the app\n // imports the virtual module: a broken template always fails `kick build`.\n async buildStart() {\n // Apps without templates skip it, so they needn't install the view package.\n if (!build || !(await kickFiles(viewsDir)).length) {\n // The last template removed between rebuilds: nothing of the last build is current.\n checked = undefined\n if (clientOut) clientOut = new Map()\n return\n }\n checked = await checkTemplates(this)\n },\n renderChunk(code, chunk, out) {\n if (!code.includes(CLIENT_DIR)) return null\n const dir = out.dir ?? (out.file ? dirname(out.file) : '')\n const rel = relative(resolve(dir, dirname(chunk.fileName)), resolve(dir, clientFolder))\n return {\n code: code.replaceAll(CLIENT_DIR, `./${rel.split(sep).join('/')}/`),\n map: null,\n }\n },\n async writeBundle(out) {\n if (!clientOut || !out.dir) return\n // A rebuild (`vite build --watch`) doesn't empty outDir: drop the files the\n // last build wrote that this one doesn't. Only ours: nothing else is touched.\n const keep = new Set([...clientOut.keys()].map((f) => resolve(out.dir!, f)))\n for (const file of written) if (!keep.has(file)) await rm(file, { force: true })\n written = keep\n for (const [file, source] of clientOut) {\n const to = resolve(out.dir, file)\n await mkdir(dirname(to), { recursive: true })\n await writeFile(to, source)\n }\n },\n async load(id) {\n const kickFile = clientModuleFile(id, viewsDir)\n if (kickFile) {\n const view = await import('@forinda/kickjs-view')\n return clientScriptOf(view, await readFile(kickFile, 'utf8'))\n }\n if (isValidatorsEntry(id)) return validatorsWrapper(validatorsFile)\n // Any other `.kick.client.ts`: not ours to load.\n if (id.endsWith(`.kick${CLIENT_SUFFIX}`)) return undefined\n if (id !== RESOLVED) return undefined\n const hasPipes = existsSync(pipesFile)\n const pipes = hasPipes\n ? `import * as pipes from ${JSON.stringify(pipesFile)}`\n : 'const pipes = {}'\n let bundle = 'null'\n if (build) {\n checked ??= await checkTemplates(this)\n bundle = checked\n }\n return [\n pipes,\n `const bundle = ${bundle};`,\n `const clientScriptPath = ${JSON.stringify(scriptPath)};`,\n // The folder beside this bundle; the edge may have no usable `import.meta.url`.\n // The folder beside this bundle (`renderChunk` fills the path); the\n // edge may have no usable `import.meta.url`.\n clientOut\n ? `const clientDir = (() => { try { return new URL(${JSON.stringify(CLIENT_DIR)}, import.meta.url).href } catch { return undefined } })();`\n : 'const clientDir = undefined;',\n // kick dev: the views read the validators file this plugin serves, wherever it's configured.\n `export const validatorsFile = ${build ? 'undefined' : JSON.stringify(validatorsFile)};`,\n 'export { bundle, pipes, clientScriptPath, clientDir }',\n `export default { bundle, pipes, clientScriptPath, clientDir${build ? '' : ', validatorsFile'} }`,\n ].join('\\n')\n },\n }\n}\n\n/**\n * The `.kick` file behind a client-script module id — only inside the views\n * folder, so a crafted dev request can't load a template from elsewhere.\n */\nfunction clientModuleFile(id: string, viewsDir: string): string | undefined {\n if (!viewsDir || !id.endsWith(`.kick${CLIENT_SUFFIX}`)) return undefined\n const file = resolve(id.slice(0, -CLIENT_SUFFIX.length))\n if (!file.startsWith(viewsDir + sep) || !existsSync(file)) return undefined\n return file\n}\n\n/** A template's top-level `<script client>` text, as the checker lifts it. */\nfunction clientScriptOf(\n view: { parse(src: string, file: string): { ast: { body: unknown[] } } },\n src: string,\n): string | undefined {\n for (const n of view.parse(src, 'x.kick').ast.body as Array<{\n k: string\n tag?: string\n attrs?: Array<{ name: string; kind: string }>\n children?: Array<{ k: string; value?: string }>\n }>) {\n if (\n n.k === 'element' &&\n n.tag?.toLowerCase() === 'script' &&\n n.attrs?.some((a) => a.name.toLowerCase() === 'client' && a.kind === 'bare')\n )\n return (n.children ?? []).map((c) => (c.k === 'text' ? c.value : '')).join('')\n }\n return undefined\n}\n\n/** The app config the client build shares: mode, `define`, env files, aliases. */\ntype ClientBuildConfig = {\n mode?: string\n define?: Record<string, unknown>\n envDir?: string | false\n envPrefix?: string | string[]\n resolve?: { alias: unknown }\n}\n\n/** Replaced, per output chunk, with the relative path to the client files folder. */\nconst CLIENT_DIR = '__KICK_CLIENT_DIR__'\n\n/** The module id a component's client script builds from: next to its `.kick` file, so `./x` imports resolve there. */\nconst CLIENT_SUFFIX = '.client.ts'\n\n/** The view package's tag for the app's validators script: `kick-validators.<hash>.js`. */\nconst VALIDATORS_TAG = 'kick-validators'\n\n/**\n * Registers every validators.ts export for the validator script. A namespace\n * import, not the module itself as the entry: app builds drop entry exports.\n */\nfunction validatorsWrapper(file: string): string {\n return `import * as v from ${JSON.stringify(file)}\\nObject.assign((globalThis.__kickValidators ??= {}), v)\\n`\n}\n\n/**\n * One browser build of every component's `<script client>`: imports\n * (relative, npm, the app's aliases) resolved, code shared by several\n * components in shared chunks. Entries are named by component tag.\n */\nasync function bundleClientScripts(\n scripts: Array<{ tag: string; file: string; code: string }>,\n root: string,\n shared: ClientBuildConfig,\n scriptPath: string,\n inline: number | (() => boolean),\n): Promise<ClientBundle> {\n const vite = await import('vite')\n const byId = new Map(scripts.map((s) => [s.file + CLIENT_SUFFIX, s.code]))\n const out = (await vite.build({\n ...(shared as object),\n configFile: false,\n root,\n // CSS `url()`s and asset URLs point where the views serve files.\n base: `${scriptPath}/`,\n logLevel: 'silent',\n plugins: [\n {\n name: 'kickjs:client-scripts',\n resolveId: (id: string) => (byId.has(id) ? id : undefined),\n load: (id: string) => byId.get(id),\n },\n ],\n build: {\n write: false,\n minify: true,\n modulePreload: false,\n copyPublicDir: false,\n assetsDir: '',\n assetsInlineLimit: inline,\n rollupOptions: {\n input: Object.fromEntries(scripts.map((s) => [s.tag, s.file + CLIENT_SUFFIX])),\n output: {\n format: 'es',\n entryFileNames: '[name].[hash].js',\n chunkFileNames: (c: { name: string }) => `${servable(c.name)}.[hash].js`,\n // Served names take a lower-case extension: `Logo.PNG` becomes `Logo.<hash>.png`.\n assetFileNames: (a: { names?: string[]; name?: string }) => {\n const name = a.names?.[0] ?? a.name ?? 'asset'\n const ext = /\\.[^.]*$/.exec(name)?.[0] ?? ''\n return `${servable(name.slice(0, name.length - ext.length))}.[hash]${ext.toLowerCase()}`\n },\n },\n },\n },\n })) as { output: OutputFile[] } | Array<{ output: OutputFile[] }>\n const output = (Array.isArray(out) ? out[0]! : out).output\n const entries: Record<string, string> = {}\n const css: Record<string, string[]> = {}\n const files: Record<string, string | Uint8Array> = {}\n const byName = new Map(output.map((f) => [f.fileName, f]))\n /** The stylesheets a chunk and the chunks it imports bring in. */\n const cssOf = (name: string, seen = new Set<string>()): string[] => {\n const c = byName.get(name)\n if (!c || seen.has(name)) return []\n seen.add(name)\n return [\n ...(c.imports ?? []).flatMap((i) => cssOf(i, seen)),\n ...(c.viteMetadata?.importedCss ?? []),\n ]\n }\n for (const f of output) {\n if (f.type === 'chunk') {\n files[f.fileName] = f.code!\n if (f.isEntry && f.name) entries[f.name] = f.fileName\n } else if (f.fileName.endsWith('.css')) {\n files[f.fileName] =\n typeof f.source === 'string' ? f.source : new TextDecoder().decode(f.source)\n } else files[f.fileName] = f.source!\n }\n for (const [tag, file] of Object.entries(entries)) {\n const list = [...new Set(cssOf(file))]\n if (list.length) css[tag] = list\n }\n return { entries, css, files }\n}\n\n/** Served names allow no dots: `date.utils` becomes `date_utils`. */\nconst servable = (name: string) => name.replace(/[^A-Za-z0-9_-]/g, '_')\n\ntype OutputFile = {\n type: string\n fileName: string\n code?: string\n source?: string | Uint8Array\n isEntry?: boolean\n name?: string\n imports?: string[]\n viteMetadata?: { importedCss?: Set<string> }\n}\n\ntype ClientBundle = {\n entries: Record<string, string>\n css: Record<string, string[]>\n files: Record<string, string | Uint8Array>\n}\n\n/**\n * TypeScript to JS with the running Vite: `transformWithOxc` from Vite 8,\n * `transformWithEsbuild` before it (the plugin supports Vite 6 and up).\n */\nasync function stripTs(code: string, file: string): Promise<string> {\n const vite = (await import('vite')) as typeof import('vite') & {\n transformWithOxc?: typeof import('vite').transformWithOxc\n }\n if ('transformWithOxc' in vite && vite.transformWithOxc)\n return (await vite.transformWithOxc(code, file, { lang: 'ts' })).code\n return (await vite.transformWithEsbuild(code, file, { loader: 'ts' })).code\n}\n\n/** A dirent's folder: `parentPath` from Node 20.12, `path` before it. */\nfunction direntDir(e: { parentPath?: string; path?: string }): string {\n return e.parentPath ?? e.path ?? ''\n}\n","/**\n * Core Vite plugin for KickJS — configures the Vite server for backend\n * framework use: custom app type, SSR environment, and Node.js target.\n *\n * This plugin runs first in the array and sets up the environment that\n * the other sub-plugins (dev-server, virtual-modules, hmr) depend on.\n *\n * @module @forinda/kickjs-vite/core-plugin\n */\n\nimport type { Plugin } from 'vite'\nimport type { PluginContext } from './types'\n\n/**\n * Creates the core configuration plugin.\n *\n * Responsibilities:\n * - Sets `appType: 'custom'` so Vite doesn't serve index.html\n * - Configures the SSR environment for Node.js backend code\n * - Prevents Vite from clearing the terminal (KickJS logs route tables on startup)\n * - Externalizes Node.js built-ins and framework packages from the bundle\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsCorePlugin(ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:core',\n\n /**\n * Vite config hook — runs before config is resolved.\n * Sets the foundational configuration for a backend Node.js framework.\n */\n config(userConfig, _env) {\n // Respect explicit server.port from user's vite.config.ts.\n // Only inject .env PORT when the user hasn't set one.\n const explicitPort = userConfig.server?.port\n const envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined\n const port = explicitPort ?? envPort ?? 3000\n\n return {\n server: {\n port,\n },\n\n // 'custom' tells Vite this is not a SPA or MPA — we handle all requests\n appType: 'custom' as const,\n\n // Don't clear the terminal — KickJS logs route tables on startup\n clearScreen: false,\n\n // SSR environment configuration for backend code\n environments: {\n ssr: {\n // Warm up the entry file for faster first request\n dev: {\n warmup: [ctx.entry],\n },\n },\n },\n\n // SSR-specific settings\n ssr: {\n // Externalize Node.js built-ins and framework packages\n // These should NOT be bundled by Vite — they run natively in Node\n external: ['@forinda/kickjs', 'express', 'reflect-metadata'],\n },\n }\n },\n }\n}\n","/**\n * Virtual module plugin for KickJS — generates the `virtual:kickjs/app`\n * module that bridges Vite and the KickJS application.\n *\n * Virtual modules are Vite's mechanism for generating code at build/serve\n * time that doesn't exist on disk. When the dev server calls\n * `ssrLoadModule('virtual:kickjs/app')`, this plugin generates the code\n * that imports and re-exports the user's application entry.\n *\n * @see https://vite.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * @module @forinda/kickjs-vite/virtual-modules\n */\n\nimport { normalizePath, type Plugin } from 'vite'\nimport type { PluginContext } from './types'\n\n/** Prefix for resolved virtual module IDs (Vite convention) */\nconst VIRTUAL_PREFIX = '\\0'\n\n/** Virtual module ID for the KickJS application entry */\nconst VIRTUAL_APP = 'virtual:kickjs/app'\n\n/** Resolved virtual module ID (with \\0 prefix to mark as virtual) */\nconst RESOLVED_APP = `${VIRTUAL_PREFIX}${VIRTUAL_APP}`\n\n/**\n * Creates the virtual modules plugin.\n *\n * Currently provides one virtual module:\n * - `virtual:kickjs/app` — re-exports the user's application entry\n *\n * The dev server plugin imports this on every request via `ssrLoadModule()`.\n * When any source file changes, Vite invalidates the module graph and the\n * next import returns fresh code — this is how server-side HMR works.\n *\n * Future virtual modules (planned for Steps 4-5):\n * - `virtual:kickjs/modules` — auto-discovered `@Module` classes\n * - `virtual:kickjs/manifest` — container metadata for DevTools\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsVirtualModulesPlugin(ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:virtual-modules',\n\n /**\n * Resolve virtual module IDs.\n * Tells Vite that `virtual:kickjs/app` is a valid module ID\n * and maps it to our internal resolved ID.\n */\n resolveId(id: string) {\n if (id === VIRTUAL_APP) {\n return RESOLVED_APP\n }\n },\n\n /**\n * Load virtual module content.\n * Generates the code for `virtual:kickjs/app` that imports the user's\n * entry file and re-exports the app.\n *\n * The generated code:\n * 1. Imports the user's entry file (which calls `bootstrap()`)\n * 2. Re-exports everything from it (including the `app` export)\n *\n * The dev server plugin then does:\n * `const { app } = await ssrLoadModule('virtual:kickjs/app')`\n * and uses `app.handle(req, res, next)` to route requests through the app.\n */\n load(id: string) {\n if (id !== RESOLVED_APP) return\n\n // Generate code that imports and re-exports the user's entry\n // The entry file should: export const app = bootstrap({ modules: [...] })\n const normalizedEntry = normalizePath(ctx.entry)\n return [\n `// Auto-generated by @forinda/kickjs-vite`,\n `// Imports the user's application entry and re-exports the app.`,\n `// Vite's module graph tracks this — file changes trigger re-evaluation.`,\n `export * from '${normalizedEntry}'`,\n ].join('\\n')\n },\n }\n}\n\nexport { VIRTUAL_APP, RESOLVED_APP }\n","/**\n * Dev server plugin for KickJS — mounts the application on Vite's\n * HTTP server using the `configureServer` hook.\n *\n * ## Architecture\n *\n * In development, Vite owns the HTTP port and creates the `http.Server`.\n * This plugin:\n *\n * 1. **Stores `viteServer.httpServer` on `globalThis`** so KickJS adapters\n * (WsAdapter, Socket.IO, GraphQL subscriptions) can attach to the real\n * server via `server.on('upgrade', ...)`. This is the key to supporting\n * any library that needs the raw `http.Server`.\n *\n * 2. **Registers a post-middleware** that loads the KickJS app through\n * Vite's SSR transform pipeline on every request. When source files\n * change, Vite invalidates the module graph and the next request\n * gets fresh code — no process restart needed.\n *\n * 3. **Stores the Vite server reference** on `globalThis` so SSR\n * renderers can use `createViteRuntime()`.\n *\n * ## Why NOT middlewareMode\n *\n * The initial KickJS Vite plugin attempt used `middlewareMode: true`, which\n * makes `viteServer.httpServer = null`. This broke WsAdapter and any library\n * needing `server.on('upgrade', ...)`. By letting Vite create the server,\n * `httpServer` is the real `http.Server` — adapters attach to it seamlessly.\n *\n * ## Request Flow\n *\n * ```\n * HTTP Request → Vite static middleware (HMR, assets)\n * → If Vite handles it → done\n * → If not → KickJS post-middleware\n * → ssrLoadModule('virtual:kickjs/app') → fresh app\n * → the app handles the request on its runtime (Express, Fastify or h3)\n * ```\n *\n *\n * @module @forinda/kickjs-vite/dev-server\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { PluginContext } from './types'\nimport { VIRTUAL_APP } from './virtual-modules'\n\n/**\n * Declare the globalThis properties used for cross-module communication.\n * These persist across Vite's `ssrLoadModule()` re-evaluations.\n *\n * `__kickjs_httpServer` uses the same `HttpServer` type that Vite uses\n * internally (union of http.Server | https.Server | Http2SecureServer).\n * KickJS adapters receive it as `http.Server` via AdapterContext — the\n * cast is safe because the dev server is HTTP/1.1.\n */\ndeclare global {\n // eslint-disable-next-line no-var\n var __kickjs_httpServer: any\n // eslint-disable-next-line no-var\n var __kickjs_viteServer: ViteDevServer | null\n}\n\n/**\n * Creates the dev server plugin.\n *\n * This is the critical integration point between Vite and KickJS:\n * - Pipes `viteServer.httpServer` to adapters via `globalThis`\n * - Loads a fresh app on every request via `ssrLoadModule()`\n * - Fixes stack traces for SSR errors with `ssrFixStacktrace()`\n *\n * @param ctx - Shared plugin context (entry file, root directory)\n * @returns Vite plugin\n */\nexport function kickjsDevServerPlugin(_ctx: PluginContext): Plugin {\n return {\n name: 'kickjs:dev-server',\n\n /**\n * Configure the Vite dev server.\n *\n * The `configureServer` hook runs after Vite creates the HTTP server.\n * We use it to:\n * 1. Store the httpServer on globalThis (for WsAdapter, Socket.IO, etc.)\n * 2. Store the Vite server reference (for SSR rendering)\n * 3. Return a post-middleware that loads the KickJS app on each request\n *\n * Returning a function from `configureServer` registers it as a\n * **post-middleware** — it runs AFTER Vite's own middleware (static\n * files, HMR client, etc.), so Vite-handled requests never reach the app.\n */\n configureServer(viteServer: ViteDevServer) {\n // ━━━ Store the REAL http.Server on globalThis ━━━\n // This is the key to supporting Socket.IO, WsAdapter, GraphQL WS,\n // and any library that needs `server.on('upgrade', ...)`.\n //\n // Application.start() detects this and skips creating its own server:\n // if (globalThis.__kickjs_httpServer) → reuse Vite's server\n // else → create own http.Server (production mode)\n //\n // Adapters receive the server in afterStart({ server }) — same API\n // in both dev and prod. Zero adapter code changes needed.\n globalThis.__kickjs_httpServer = viteServer.httpServer ?? null\n globalThis.__kickjs_viteServer = viteServer\n\n // ━━━ Eagerly bootstrap the app once the server is listening ━━━\n // The post-middleware below only evaluates the entry on the FIRST\n // request (lazy SSR). That means `bootstrap()`, adapter\n // `afterStart`, and the app's startup logs don't run until someone\n // hits the URL — the app looks \"not started\" until then. Warm the\n // module once the HTTP server is listening so startup behaves like\n // `node`/`tsx` (logs + adapters + the in-dev shutdown hook ready\n // immediately). Errors surface with a fixed stacktrace.\n const warm = () => {\n viteServer.ssrLoadModule(VIRTUAL_APP).catch((err: unknown) => {\n if (err instanceof Error) viteServer.ssrFixStacktrace(err)\n viteServer.config.logger.error(\n `[kickjs] failed to bootstrap app on startup: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n })\n }\n const httpServer = viteServer.httpServer\n if (httpServer) {\n if (httpServer.listening) warm()\n else httpServer.once('listening', warm)\n }\n\n // Return post-middleware — runs after Vite's static/HMR middleware\n return () => {\n viteServer.middlewares.use(async (req, res, next) => {\n try {\n // Load the KickJS app through Vite's SSR transform pipeline.\n // On first request: evaluates the entry file and all imports.\n // On subsequent requests: returns cached modules (or re-evaluates\n // if source files changed since last request).\n //\n // This is the same pattern React Router and TanStack Start use.\n const mod = await viteServer.ssrLoadModule(VIRTUAL_APP)\n\n // The entry file exports: export const app = bootstrap({ modules })\n // `app` is the configured Application (not yet listening).\n const kickApp = mod.app\n\n if (!kickApp?.handle) {\n // Entry file doesn't export an app — fall through to Vite's 404\n return next()\n }\n\n // Let the app handle the request.\n // If no route matches, it calls next() and\n // Vite's default 404 handler takes over.\n kickApp.handle(req, res, (err?: any) => {\n if (err) {\n // Fix stack traces to point to original source (not compiled)\n if (err instanceof Error) {\n viteServer.ssrFixStacktrace(err)\n }\n return next(err)\n }\n next()\n })\n } catch (err) {\n // SSR load/evaluation error (syntax error, missing import, etc.)\n if (err instanceof Error) {\n viteServer.ssrFixStacktrace(err)\n }\n next(err)\n }\n })\n }\n },\n }\n}\n","/**\n * Eager app re-warm after an invalidation.\n *\n * The dev server evaluates `virtual:kickjs/app` lazily — after a save\n * invalidates it, re-evaluation waits for the NEXT HTTP request. A\n * broken file (syntax error, failed import, boot throw) was therefore\n * silent until something hit the server, even though startup surfaced\n * the same class of error eagerly. Re-warming right after invalidation\n * pushes transform/bootstrap errors into the dev console the moment\n * the save lands.\n *\n * Errors are logged (with fixed stacktraces) but never thrown — the\n * dev loop must survive a mid-edit broken state; the next successful\n * save heals it.\n */\nimport type { ViteDevServer } from 'vite'\n\nimport { VIRTUAL_APP } from './virtual-modules'\n\nexport function rewarmApp(server: ViteDevServer, reason: string): void {\n server.ssrLoadModule(VIRTUAL_APP).catch((err: unknown) => {\n if (err instanceof Error) server.ssrFixStacktrace(err)\n server.config.logger.error(\n `[kickjs] app failed to reload after ${reason}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { timestamp: true },\n )\n })\n}\n","/**\n * Module discovery plugin for KickJS — automatically detects `@Module` classes\n * by scanning source files during Vite's `transform()` hook.\n *\n * ## How It Works\n *\n * 1. Vite calls `transform(code, id)` for every file it processes\n * 2. This plugin checks if the file matches `*.module.ts` (or `.js`)\n * 3. If the file contains a class exported with `@Module` or extends `AppModule`,\n * it extracts the class name and records the file path\n * 4. The virtual module `virtual:kickjs/app` is invalidated so the next request\n * picks up the newly discovered module\n *\n * ## Why This Matters\n *\n * Without auto-discovery, users must manually maintain a barrel file\n * (`src/modules/index.ts`) that imports and re-exports all modules.\n * When `kick g module` creates a new module, it has to edit this barrel.\n * With auto-discovery, modules are detected automatically — no barrel needed.\n *\n * ## Interaction with HMR\n *\n * When a module file is added, renamed, or deleted:\n * - `handleHotUpdate()` detects the change\n * - The virtual module is invalidated\n * - The next `ssrLoadModule()` call regenerates the virtual module\n * with the updated module list\n *\n * @module @forinda/kickjs-vite/module-discovery\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { PluginContext } from './types'\nimport { RESOLVED_APP } from './virtual-modules'\nimport { rewarmApp } from './warm'\n\n/** Regex to detect exported module classes in source files */\nconst MODULE_CLASS_REGEX =\n /export\\s+(?:default\\s+)?class\\s+(\\w+(?:Module))\\s*(?:extends|implements|{)/\n\n/** File extensions to scan for modules */\nconst MODULE_FILE_PATTERN = /\\.module\\.[tj]sx?$/\n\n/**\n * Discovered module entry — maps a file path to its exported class name.\n *\n * @example\n * ```\n * {\n * filePath: '/src/modules/users/user.module.ts',\n * className: 'UserModule'\n * }\n * ```\n */\nexport interface DiscoveredModule {\n /** Absolute file path */\n filePath: string\n /** Exported class name (e.g., 'UserModule') */\n className: string\n}\n\n/**\n * Creates the module auto-discovery plugin.\n *\n * Scans `*.module.ts` files during Vite's transform phase to build a\n * registry of `@Module` classes. The registry is used by the virtual\n * modules plugin to generate auto-imports.\n *\n * @param ctx - Shared plugin context\n * @returns Vite plugin\n */\nexport function kickjsModuleDiscoveryPlugin(ctx: PluginContext): Plugin {\n /**\n * Registry of discovered modules.\n * Keyed by absolute file path to handle renames and deletions.\n * Stored on the plugin context so the virtual modules plugin can read it.\n */\n const discovered = new Map<string, DiscoveredModule>()\n let server: ViteDevServer | null = null\n\n // Expose discovered modules on the context for virtual-modules plugin\n ;(ctx as any).discoveredModules = discovered\n\n return {\n name: 'kickjs:module-discovery',\n\n configureServer(viteServer) {\n server = viteServer\n\n // Watch for new/deleted files in the modules directory\n viteServer.watcher.on('add', (filePath) => {\n if (MODULE_FILE_PATTERN.test(filePath)) {\n // File added — it will be processed in transform() when first imported.\n // Invalidate virtual module so it picks up the new file on next request.\n invalidateVirtualApp(viteServer)\n }\n })\n\n viteServer.watcher.on('unlink', (filePath) => {\n if (discovered.has(filePath)) {\n discovered.delete(filePath)\n invalidateVirtualApp(viteServer)\n }\n })\n },\n\n /**\n * Transform hook — called for every file Vite processes.\n *\n * We don't actually transform the code (return null), but we use this\n * hook to observe which files contain module classes. This is cheaper\n * than AST parsing — a regex match on the source is sufficient because\n * module files follow a consistent naming pattern (`*.module.ts`).\n */\n transform(code: string, id: string) {\n // Only scan files matching the module pattern\n if (!MODULE_FILE_PATTERN.test(id)) return null\n // Skip node_modules\n if (id.includes('node_modules')) return null\n\n const match = code.match(MODULE_CLASS_REGEX)\n if (match) {\n const className = match[1]\n const wasNew = !discovered.has(id)\n discovered.set(id, { filePath: id, className })\n\n if (wasNew && server) {\n // New module discovered — invalidate virtual module\n invalidateVirtualApp(server)\n }\n } else if (discovered.has(id)) {\n // File no longer exports a module class (user removed it)\n discovered.delete(id)\n if (server) {\n invalidateVirtualApp(server)\n }\n }\n\n // Return null — we don't transform the code, just observe it\n return null\n },\n\n /**\n * HMR hook — called when a file changes.\n *\n * If a module file changes, we re-scan it and invalidate the virtual\n * module so the next request picks up the changes.\n */\n handleHotUpdate({ file, server: viteServer }) {\n if (!MODULE_FILE_PATTERN.test(file)) return\n\n // The file will be re-processed in transform() on next import.\n // Invalidate the virtual module so it regenerates with fresh imports.\n invalidateVirtualApp(viteServer)\n },\n }\n}\n\n/**\n * Invalidate the virtual:kickjs/app module in Vite's module graph.\n * This forces the next `ssrLoadModule()` call to re-evaluate the\n * virtual module, picking up any new/removed modules.\n */\nfunction invalidateVirtualApp(server: ViteDevServer): void {\n const mod = server.moduleGraph.getModuleById(RESOLVED_APP)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n // Re-warm immediately so a broken module file surfaces its error on\n // save instead of on the next HTTP request (see warm.ts).\n rewarmApp(server, 'module discovery change')\n}\n\n/**\n * Get the current list of discovered modules.\n * Used by the virtual modules plugin to generate auto-imports.\n */\nexport function getDiscoveredModules(ctx: PluginContext): DiscoveredModule[] {\n const map = (ctx as any).discoveredModules as Map<string, DiscoveredModule> | undefined\n return map ? [...map.values()] : []\n}\n","/**\n * HMR plugin for KickJS — selective container invalidation when source\n * files change, with debounced batching for bulk operations.\n *\n * ## How It Works\n *\n * 1. During `transform()`, the plugin scans for decorator patterns\n * (`@Service`, `@Controller`, etc.) and maps file paths to DI token names\n * 2. When a file changes (`handleHotUpdate()`), the plugin:\n * - Looks up which DI tokens are defined in that file\n * - Calls `container.invalidate(token)` for each (which walks the dep graph)\n * - Invalidates the virtual module so `ssrLoadModule()` returns fresh code\n * - Sends a custom HMR event (`kickjs:hmr`) so DevTools/Swagger can react\n * 3. Changes are **debounced** (150ms) so `kick g module` creating 10+ files\n * emits ONE invalidation batch, not 10 separate events\n *\n * ## Interaction with Reactive Container\n *\n * `container.invalidate(token)` (from Step 3) does:\n * - Clears the cached instance for that token\n * - Walks the dependency graph to find dependents\n * - Invalidates all dependents recursively\n * - Emits batched `onChange()` events to all subscribers (Swagger, DevTools, etc.)\n *\n * ## Detection Strategy\n *\n * Uses regex patterns (not AST) for speed. This is the same approach\n * TanStack Start uses (`KindDetectionPatterns` in their compiler).\n * It's fast because:\n * - Only runs on files that actually contain decorator patterns\n * - No Babel/SWC parsing needed\n * - False positives are harmless (extra invalidation is safe)\n *\n * @module @forinda/kickjs-vite/hmr-plugin\n */\n\nimport type { Plugin, ViteDevServer } from 'vite'\nimport type { HmrOptions, PluginContext } from './types'\nimport { RESOLVED_APP } from './virtual-modules'\nimport { rewarmApp } from './warm'\n\n/**\n * Test whether a watcher event refers to a file we should react to.\n *\n * Vite's chokidar fires for everything under the project root. We only\n * want code that the running app could realistically depend on:\n *\n * - **Source extensions only.** `.ts`, `.tsx`, `.js`, `.jsx`, `.mts`,\n * `.cts`, `.mjs`, `.cjs`. JSON / lockfiles / images / typegen\n * declaration files are noise.\n * - **Skip `.d.ts` declaration files.** They're regenerated by typegen\n * on every save and would create an invalidation loop with the\n * typegen watcher in `kick dev`.\n * - **Skip well-known noise directories.** `node_modules`, `dist`, the\n * `.kickjs` typegen output, `.git`, `coverage`, OS swap files.\n *\n * Errs on the inclusive side: a file that is genuinely unused but still\n * lives under `src/` causes a cheap virtual-app invalidation, no worse\n * than `kick dev`'s typegen sweep already does on the same event.\n */\n/** Whether the browser has loaded `file` through this dev server. */\nfunction isClientModule(server: ViteDevServer, file: string): boolean {\n const graph = server.environments?.client?.moduleGraph\n return (graph?.getModulesByFile(file)?.size ?? 0) > 0\n}\n\nfunction isProjectSource(file: string): boolean {\n if (!/\\.(?:ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(file)) return false\n if (file.endsWith('.d.ts') || file.endsWith('.d.mts') || file.endsWith('.d.cts')) return false\n if (\n file.includes('/node_modules/') ||\n file.includes('/.kickjs/') ||\n file.includes('/dist/') ||\n file.includes('/.git/') ||\n file.includes('/coverage/')\n ) {\n return false\n }\n return true\n}\n\n/** Strip directory components for a friendlier dev-console label. */\nfunction basename(file: string): string {\n const i = file.lastIndexOf('/')\n return i === -1 ? file : file.slice(i + 1)\n}\n\n/**\n * Regex patterns that detect KickJS decorator usage in source files.\n * Matches `@Service()`, `@Controller()`, `@Repository()`, etc.\n * followed by an exported class declaration.\n *\n * Pattern: decorator → optional whitespace → export? class ClassName\n */\nconst DECORATOR_CLASS_REGEX =\n /@(?:Service|Controller|Repository|Injectable|Component)\\s*\\([^)]*\\)\\s*\\n?\\s*(?:export\\s+)?class\\s+(\\w+)/g\n\n/**\n * Regex patterns that detect the v4 factory-style declarations:\n * `defineAdapter`, `definePlugin`, `defineContextDecorator`. These\n * produce values rather than decorated classes, so the class regex\n * above misses them and changes to plugin/adapter/contributor files\n * silently bypass kickjs HMR.\n *\n * Pattern: `export const Name = defineAdapter|definePlugin|defineContextDecorator(`\n * — captures the constant's name so it can be surfaced in the dev\n * console alongside the rest of the invalidation batch.\n */\nconst FACTORY_DECL_REGEX =\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::[^=]+)?=\\s*(defineAdapter|definePlugin|defineContextDecorator)\\s*[<(]/g\n\n/** Substrings that bail out the transform scanner before regex work. */\nconst FACTORY_KEYWORDS = ['defineAdapter', 'definePlugin', 'defineContextDecorator'] as const\nconst DECORATOR_KEYWORDS = [\n '@Service',\n '@Controller',\n '@Repository',\n '@Injectable',\n '@Component',\n] as const\n\n/** Debounce time for batching multiple file changes into one invalidation */\nconst DEBOUNCE_MS = 150\n\n/**\n * Creates the HMR selective invalidation plugin.\n *\n * Tracks which DI tokens are defined in which files, then selectively\n * invalidates only the affected tokens (and their dependents) when\n * those files change. Much faster than a full Container.reset().\n *\n * @param ctx - Shared plugin context\n * @returns Vite plugin\n */\nexport function kickjsHmrPlugin(ctx: PluginContext, hmrOptions: HmrOptions = {}): Plugin {\n /**\n * Maps file paths to the DI token names defined in them.\n * Built up during transform(), read during handleHotUpdate().\n *\n * @example\n * ```\n * '/src/modules/users/user.service.ts' → ['UserService']\n * '/src/modules/users/user.controller.ts' → ['UserController']\n * ```\n */\n const fileTokenMap = new Map<string, string[]>()\n\n /** Pending tokens to invalidate (accumulated during debounce window) */\n let pendingTokens = new Set<string>()\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n return {\n name: 'kickjs:hmr',\n\n /**\n * Transform hook — scans source files for decorator patterns.\n *\n * Doesn't modify the code (returns null), just records which\n * DI tokens are defined in each file. This mapping is used by\n * `handleHotUpdate()` to determine what to invalidate.\n */\n transform(code: string, id: string) {\n // Skip non-TypeScript/JavaScript files and node_modules\n if (!/\\.[tj]sx?$/.test(id)) return null\n if (id.includes('node_modules')) return null\n\n const hasDecorator = DECORATOR_KEYWORDS.some((kw) => code.includes(kw))\n const hasFactory = FACTORY_KEYWORDS.some((kw) => code.includes(kw))\n\n // Quick bail-out: nothing kickjs-relevant in the file\n if (!hasDecorator && !hasFactory) {\n if (fileTokenMap.has(id)) fileTokenMap.delete(id)\n return null\n }\n\n const tokens: string[] = []\n\n if (hasDecorator) {\n for (const m of code.matchAll(DECORATOR_CLASS_REGEX)) {\n tokens.push(m[1])\n }\n }\n\n if (hasFactory) {\n // Tag each entry with the factory kind so the HMR log line\n // distinguishes a controller-class invalidation from an adapter\n // / plugin / contributor reload — the second kind never maps\n // back to a DI token, but it still needs the virtual app\n // re-evaluated so bootstrap re-imports the new value.\n for (const m of code.matchAll(FACTORY_DECL_REGEX)) {\n tokens.push(`${m[1]} (${m[2]})`)\n }\n }\n\n if (tokens.length > 0) {\n fileTokenMap.set(id, tokens)\n } else if (fileTokenMap.has(id)) {\n fileTokenMap.delete(id)\n }\n\n return null\n },\n\n /**\n * HMR hook — called when a file changes in dev mode.\n *\n * If the changed file contains KickJS decorated classes:\n * 1. Accumulate the affected tokens in the debounce buffer\n * 2. After 150ms of quiet, flush: invalidate all tokens at once\n * 3. Invalidate the virtual module for fresh `ssrLoadModule()` response\n * 4. Send ONE `kickjs:hmr` event to the client (DevTools, Swagger UI)\n *\n * The 150ms debounce is critical for `kick g module` which creates\n * 10+ files in rapid succession. Without debouncing, each file would\n * trigger a separate invalidation cycle.\n *\n * Returns an empty array to tell Vite we handled the update\n * (prevents Vite's default full-page reload for these files).\n */\n handleHotUpdate({ file, server }) {\n // Reject anything outside the project's source surface — chokidar\n // also fires for `.kickjs/` typegen output, `dist/`, and editor\n // swap files that have nothing to do with the running app.\n if (!isProjectSource(file)) return\n\n const tokens = fileTokenMap.get(file)\n\n // Files with kickjs decorators / factories: accumulate their token\n // names so the dev console can name what changed. Files without a\n // tracked token (plain helpers, pure utilities, side-effect modules\n // like `hello.ts`) still trigger an invalidation — just labelled\n // by the file's basename so the user sees something happened.\n if (tokens && tokens.length > 0) {\n for (const t of tokens) pendingTokens.add(t)\n } else {\n pendingTokens.add(basename(file))\n }\n\n // Debounce: flush after 150ms of quiet\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n flushInvalidation(server, pendingTokens, hmrOptions)\n pendingTokens = new Set()\n }, DEBOUNCE_MS)\n\n // A module the browser imports (Inertia pages, a frontend served by\n // this dev server) keeps Vite's own HMR — React Fast Refresh, Vue and\n // Svelte hot updates. Answering `[]` for those swallowed the update,\n // so component edits only showed after a manual refresh.\n if (isClientModule(server, file)) return\n\n // Server-only: tell Vite we handled it — no full-page reload.\n // `flushInvalidation` always invalidates the virtual app module,\n // so the next ssrLoadModule re-imports the changed file via the\n // dev-server's middleware shim.\n return []\n },\n }\n}\n\n/**\n * Shape of the reactive-container handle the KickJS runtime publishes on\n * `globalThis` for dev-mode HMR. Optional all the way down — the container\n * only exists after the app has bootstrapped at least once, and older\n * runtime versions may not expose `invalidate`.\n */\ninterface KickHmrGlobal {\n __kickjs_container?: {\n invalidate?: (token: string) => void\n }\n}\n\n/**\n * Flush accumulated token invalidations.\n *\n * Called after the debounce window closes. Performs:\n * 1. Container invalidation (clears instances + walks dependency graph)\n * 2. Virtual module invalidation (forces ssrLoadModule to re-evaluate)\n * 3. HMR event broadcast (notifies DevTools, Swagger UI, etc.)\n *\n * @param server - Vite dev server\n * @param tokens - Set of DI token names to invalidate\n */\nfunction flushInvalidation(\n server: ViteDevServer,\n tokens: Set<string>,\n hmrOptions: HmrOptions,\n): void {\n const batch = [...tokens]\n if (batch.length === 0) return\n const timestamp = Date.now()\n\n // 1. Invalidate tokens in the reactive container (if available)\n // container.invalidate() walks the dependency graph and notifies subscribers\n const container = (globalThis as typeof globalThis & KickHmrGlobal).__kickjs_container\n if (container && typeof container.invalidate === 'function') {\n for (const token of batch) {\n container.invalidate(token)\n }\n }\n\n // 2. Invalidate the virtual module so next ssrLoadModule() re-evaluates\n const vmod = server.moduleGraph.getModuleById(RESOLVED_APP)\n if (vmod) {\n server.moduleGraph.invalidateModule(vmod)\n }\n // 2b. Re-warm immediately — without this, re-evaluation waits for the\n // next HTTP request, so a broken save (syntax error, boot throw)\n // stays SILENT until something hits the server. Mirrors the eager\n // startup warm in dev-server.ts.\n rewarmApp(server, `HMR invalidation (${batch.length} token${batch.length === 1 ? '' : 's'})`)\n\n // 3. Send ONE custom HMR event with the full batch\n // DevTools dashboard, Swagger UI, and other dev tools can listen:\n // import.meta.hot?.on('kickjs:hmr', (data) => { ... })\n server.hot.send({\n type: 'custom',\n event: 'kickjs:hmr',\n data: { tokens: batch, timestamp },\n })\n\n // 4. Dev-console log — three modes, in priority order:\n // a. `silent: true` → no log\n // b. `onInvalidation` provided → custom function controls the line\n // (returning a string emits one console.log, void/undefined =\n // suppresses, useful when piping to a structured logger or\n // overlay)\n // c. neither set → default `HMR invalidated N tokens: …` line\n if (hmrOptions.silent) return\n\n if (hmrOptions.onInvalidation) {\n const out = hmrOptions.onInvalidation({ tokens: batch, timestamp })\n if (typeof out === 'string') console.log(out)\n return\n }\n\n const names = batch.join(', ')\n const label = batch.length === 1 ? '1 token' : `${batch.length} tokens`\n console.log(` ${green('HMR')} invalidated ${label}: ${names}`)\n}\n\n/** ANSI green for terminal output */\nfunction green(text: string): string {\n return `\\x1b[32m${text}\\x1b[0m`\n}\n","// `devtoolsFlagPlugin()` — exposes `__KICKJS_DEVTOOLS__` as a build-time\n// constant adopters guard their devtools imports behind. Vite/Rollup's\n// existing dead-code-elimination strips the gated branch from production\n// bundles entirely (including any dynamic `import('@forinda/kickjs-devtools')`\n// inside the gate), giving \"devtools-in-dev, zero overhead in prod\"\n// without a babel pass.\n//\n// Adopter usage:\n//\n// const adapters = [/* prod adapters… */]\n// if (__KICKJS_DEVTOOLS__) {\n// const { DevToolsAdapter } = await import('@forinda/kickjs-devtools')\n// adapters.push(DevToolsAdapter({ basePath: '/_debug' }))\n// }\n//\n// bootstrap({ adapters, modules: [...] })\n//\n// Resolution order for the flag's value:\n// 1. explicit `enabled` option on the plugin → wins\n// 2. `KICKJS_DEVTOOLS=0|1` env var → operator-side override\n// 3. Vite `command` — `'serve'` (dev) → true, `'build'` → false.\n// `command` is cleaner than NODE_ENV: Vite passes it explicitly\n// to plugins regardless of how the user set their environment.\n//\n// The plugin returns a Vite `config` hook that adds the literal under\n// `define`. Vite's `define` is a verbatim-substitution map; stringifying\n// with JSON.stringify keeps the value a true / false token (no quotes\n// would break the parser).\n\nimport type { ConfigEnv, Plugin } from 'vite'\n\nexport interface DevtoolsFlagOptions {\n /**\n * Force the flag value. When set, environment-based detection is\n * bypassed entirely. Useful for explicit feature gates per build\n * profile.\n *\n * @default `vite command === 'serve'` (true in dev, false in build)\n */\n enabled?: boolean\n /**\n * Override the global name. Default `__KICKJS_DEVTOOLS__`.\n * Useful for adopters who want a project-specific flag name to\n * avoid colliding with another tooling's own globals.\n */\n flagName?: string\n}\n\n/**\n * Resolve the build-time devtools flag. Exposed for unit tests +\n * adopters who want to compute the same answer the plugin would.\n */\nexport function resolveDevtoolsFlag(opts: DevtoolsFlagOptions = {}, env?: ConfigEnv): boolean {\n if (typeof opts.enabled === 'boolean') return opts.enabled\n const envOverride = process.env.KICKJS_DEVTOOLS\n if (envOverride === '1' || envOverride === 'true') return true\n if (envOverride === '0' || envOverride === 'false') return false\n // env may be undefined when callers compute the flag outside a\n // Vite plugin invocation (tests). Fall back to NODE_ENV, failing\n // closed: an unset NODE_ENV leaves devtools out.\n if (env) return env.command === 'serve'\n return process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'\n}\n\nexport function devtoolsFlagPlugin(opts: DevtoolsFlagOptions = {}): Plugin {\n const flagName = opts.flagName ?? '__KICKJS_DEVTOOLS__'\n return {\n name: 'kickjs:devtools-flag',\n config(_userConfig, env) {\n const enabled = resolveDevtoolsFlag(opts, env)\n return {\n define: {\n [flagName]: JSON.stringify(enabled),\n },\n }\n },\n }\n}\n","/**\n * Babel-based devtools stripper for production builds.\n *\n * Built around a single rule: anything sourced from\n * `@forinda/kickjs-devtools-kit` (or any of its sub-paths) is dev-\n * only and must not ship in the prod bundle. The transform walks\n * each module and removes:\n *\n * 1. `import ... from '@forinda/kickjs-devtools-kit'` declarations\n * (named, default, namespace, side-effect — all forms).\n * 2. Top-level `ExpressionStatement`s whose call/expression root is\n * a binding imported from devtools-kit\n * (e.g., `defineDevtoolsRenderTab({...})`).\n * 3. Side-effect imports whose path ends in `/devtools-events`\n * (with any extension) — type-augmentation modules shipped by\n * adapter packages. Already side-effect-only, safe to drop in\n * prod.\n *\n * The transform is intentionally conservative. It will not:\n *\n * - Remove identifier *references* outside of the rules above. If\n * your code calls `defineDevtoolsRenderTab(...)` inside a regular\n * function body (i.e. not a top-level `ExpressionStatement`),\n * the reference stays. After we drop the import the build will\n * fail loud — that is the signal to gate the call behind\n * `__KICKJS_DEVTOOLS__` (see `devtools-flag-plugin.ts`).\n * - Touch files that don't import from devtools-kit at all.\n * - Touch files in `node_modules` (Vite's plugin chain handles\n * that already, but the transform short-circuits on a quick\n * string check too).\n *\n * The dev path is unchanged: this transform only runs when Vite's\n * `command === 'build'`. In dev, devtools-kit imports stay live.\n */\n\n// Namespace import, not a default import: Babel 8 ships as native ESM and\n// `@babel/core` exposes only named exports — `import babel from '@babel/core'`\n// fails at load with \"does not provide an export named 'default'\".\nimport * as babel from '@babel/core'\n\nconst DEVTOOLS_KIT_RE = /^@forinda\\/kickjs-devtools-kit(\\/.*)?$/\nconst DEVTOOLS_EVENTS_RE = /(^|\\/)devtools-events(\\.[a-z]+)?$/\n\nexport interface StripDevtoolsOptions {\n /**\n * When `false`, skips files that don't import devtools-kit. The\n * default short-circuit is a substring check on the source text;\n * disable it only for tests where you want the visitor to run\n * unconditionally.\n *\n * @default true\n */\n fastReject?: boolean\n}\n\nexport interface StripResult {\n /** Transformed source. Returns the original `code` when nothing was stripped. */\n code: string\n /** `true` if the visitor removed at least one node. */\n changed: boolean\n}\n\n/**\n * Strip devtools-kit imports and their dependent top-level calls\n * from a single TypeScript module. Pure — no I/O, no Vite, no\n * filesystem.\n */\nexport function stripDevtoolsCode(\n source: string,\n filename: string,\n opts: StripDevtoolsOptions = {},\n): StripResult {\n if (opts.fastReject !== false) {\n if (!source.includes('@forinda/kickjs-devtools-kit') && !source.includes('devtools-events')) {\n return { code: source, changed: false }\n }\n }\n\n let changed = false\n\n // Add the `jsx` plugin only for files that may contain JSX —\n // `.tsx` / `.jsx`. Mixing `jsx` + `typescript` on a `.ts` file\n // breaks the angle-bracket type-assertion syntax (`<T>x`); kept\n // off by default. `.tsx` files would otherwise fail to parse on\n // any embedded JSX.\n const isJsx = /\\.(?:tsx|jsx)$/i.test(filename)\n const parserPlugins: string[] = ['typescript', 'decorators-legacy', 'classProperties']\n if (isJsx) parserPlugins.push('jsx')\n\n const result = babel.transformSync(source, {\n filename,\n babelrc: false,\n configFile: false,\n sourceType: 'module',\n parserOpts: {\n plugins: parserPlugins as never,\n },\n generatorOpts: {\n retainLines: true,\n },\n plugins: [\n function devtoolsStripPlugin(): babel.PluginObject {\n return {\n name: 'kickjs-strip-devtools',\n visitor: {\n Program(path) {\n const devtoolsBindings = new Set<string>()\n\n // Pass 1 — drop devtools-kit imports + collect bound names.\n for (const stmt of path.get('body')) {\n if (!stmt.isImportDeclaration()) continue\n const src = stmt.node.source.value\n if (!DEVTOOLS_KIT_RE.test(src) && !DEVTOOLS_EVENTS_RE.test(src)) continue\n\n for (const spec of stmt.node.specifiers) {\n if (spec.local?.name) devtoolsBindings.add(spec.local.name)\n }\n stmt.remove()\n changed = true\n }\n\n if (devtoolsBindings.size === 0) return\n\n // Pass 2 — drop top-level expression statements rooted\n // in a stripped binding.\n for (const stmt of path.get('body')) {\n if (!stmt.isExpressionStatement()) continue\n const root = rootIdentifier(stmt.node.expression)\n if (root && devtoolsBindings.has(root)) {\n stmt.remove()\n changed = true\n }\n }\n },\n },\n }\n },\n ],\n })\n\n // Return the original source verbatim when nothing was stripped —\n // Babel's generator otherwise normalises whitespace + adds\n // semicolons, which would invalidate Vite's cache for files that\n // shouldn't have changed at all.\n if (!result || result.code == null || !changed) {\n return { code: source, changed: false }\n }\n return { code: result.code, changed: true }\n}\n\n/**\n * Walk a call/member expression tree to its root identifier. Returns\n * `null` for expressions we don't recognize (literals, sequence\n * expressions, etc.) — the caller skips those rather than guessing.\n */\nfunction rootIdentifier(expr: babel.types.Expression): string | null {\n let node: babel.types.Node = expr\n while (true) {\n if (node.type === 'Identifier') return node.name\n if (node.type === 'CallExpression') {\n node = node.callee\n continue\n }\n if (node.type === 'MemberExpression') {\n node = node.object\n continue\n }\n if (node.type === 'TSAsExpression' || node.type === 'TSNonNullExpression') {\n node = node.expression\n continue\n }\n return null\n }\n}\n","/**\n * Vite plugin wrapping `stripDevtoolsCode` for production builds.\n *\n * Runs only when Vite's `command === 'build'`. In dev the plugin is\n * a no-op so the devtools UI keeps working under `kick dev`.\n *\n * Pairs with `devtoolsFlagPlugin()` — that one constant-folds\n * `if (__KICKJS_DEVTOOLS__)` branches via Vite's existing DCE; this\n * one strips top-level devtools-kit imports + their `defineDevtoolsRenderTab(...)` /\n * `defineDevtoolsTab(...)` call sites without requiring adopters to\n * wrap them in the flag.\n */\n\nimport type { Plugin } from 'vite'\nimport { stripDevtoolsCode } from './babel-strip-devtools'\nimport { resolveDevtoolsFlag, type DevtoolsFlagOptions } from './devtools-flag-plugin'\n\nexport interface DevtoolsStripOptions {\n /**\n * Force enable / disable. Default: on for `vite build` when the devtools flag is off.\n * Adopters running a debug-prod build (`kick build` with the flag\n * forced on) can pass `false` to keep devtools-kit code in the\n * bundle.\n */\n enabled?: boolean\n /**\n * Glob-like include pattern. Default: any `.ts` / `.tsx` /\n * `.mts` / `.cts` file under the project root. The transform is\n * a no-op on files that don't import devtools-kit, so this is\n * normally fine to leave at the default.\n */\n include?: RegExp\n /**\n * The devtools flag options the build uses (`kickjsVitePlugin({ devtools })`).\n * Without an explicit `enabled`, the strip runs only when that flag is off —\n * a build that keeps DevTools keeps its tabs.\n */\n devtools?: DevtoolsFlagOptions\n}\n\nconst DEFAULT_INCLUDE = /\\.(?:m|c)?[jt]sx?$/\n\n/**\n * Strips devtools-kit imports + their top-level call sites from\n * production bundles. See `babel-strip-devtools.ts` for the exact\n * rule set.\n */\nexport function devtoolsStripPlugin(opts: DevtoolsStripOptions = {}): Plugin {\n let active = false\n const include = opts.include ?? DEFAULT_INCLUDE\n\n return {\n name: 'kickjs:devtools-strip',\n enforce: 'pre',\n apply: 'build',\n config(_userConfig, env) {\n active = opts.enabled ?? (env.command === 'build' && !resolveDevtoolsFlag(opts.devtools, env))\n },\n transform(code, id) {\n if (!active) return null\n if (id.includes('node_modules')) return null\n if (!include.test(id)) return null\n const result = stripDevtoolsCode(code, id)\n if (!result.changed) return null\n return { code: result.code, map: null }\n },\n }\n}\n","/**\n * kickjs:typegen — typegen-on-save for plain `vite` boots.\n *\n * `kick dev` owns the typegen watcher when it boots Vite (it claims\n * ownership on `globalThis` before `createServer`). But adopters who\n * run bare `vite` (the pre-fix scaffold default, or any Vite-embedding\n * tool) historically got working HMR with silently frozen\n * `.kickjs/types` — new routes lost their typing until a manual\n * `kick typegen`.\n *\n * This plugin closes that gap: when nothing has claimed ownership, it\n * dynamically loads the PROJECT's `@forinda/kickjs-cli` (optional peer\n * — resolved from the project root, never bundled) and wires the same\n * `createTypegenDevWatcher` engine `kick dev` uses, plus one startup\n * catch-up pass. No CLI installed → quiet no-op with a one-line notice.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\n/** Mirror of the CLI's TYPEGEN_OWNER_KEY — string-duplicated so this\n * module never needs the CLI at import time. */\nconst OWNER_KEY = '__kickjs_typegen_owner'\n\n/** Structural slice of the CLI surface this plugin consumes. */\nexport interface TypegenCliModule {\n loadKickConfig(cwd: string): Promise<unknown>\n createTypegenDevWatcher(opts: {\n cwd: string\n config: unknown\n emitWarning: (message: string) => void\n }): {\n handleWatchEvent(event: 'add' | 'change' | 'unlink' | 'unlinkDir', file: string): void\n runOnce(): void\n assetSrcRoots: readonly string[]\n dispose(): void\n }\n}\n\n/**\n * Resolve `@forinda/kickjs-cli` from the PROJECT root (not from this\n * package — under pnpm's strict layout the vite plugin can't see the\n * CLI through its own node_modules). Walks `node_modules` upward and\n * reads the manifest directly with fs: the CLI is ESM-only (no\n * `require` condition in its exports map), so `createRequire().resolve`\n * throws ERR_PACKAGE_PATH_NOT_EXPORTED and can't be used here.\n * Returns null when not installed or too old to export the watcher\n * engine.\n */\nfunction resolveCliEntry(root: string): string | null {\n let dir = root\n for (;;) {\n const pkgDir = join(dir, 'node_modules', '@forinda', 'kickjs-cli')\n const manifestPath = join(pkgDir, 'package.json')\n if (existsSync(manifestPath)) {\n try {\n const pkg = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n exports?: Record<string, unknown>\n module?: string\n main?: string\n }\n const dot = pkg.exports?.['.'] as string | Record<string, unknown> | undefined\n const fromExports =\n typeof dot === 'string'\n ? dot\n : typeof dot?.import === 'string'\n ? dot.import\n : typeof (dot?.import as Record<string, unknown> | undefined)?.default === 'string'\n ? ((dot!.import as Record<string, unknown>).default as string)\n : typeof dot?.default === 'string'\n ? (dot.default as string)\n : undefined\n const entryRel = fromExports ?? pkg.module ?? pkg.main\n if (typeof entryRel === 'string') return join(pkgDir, entryRel)\n } catch {\n // Unreadable manifest — keep walking up.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nasync function loadCliFromProject(root: string): Promise<TypegenCliModule | null> {\n try {\n const entry = resolveCliEntry(root)\n if (!entry || !existsSync(entry)) return null\n const mod = (await import(pathToFileURL(entry).href)) as Partial<TypegenCliModule>\n if (\n typeof mod.createTypegenDevWatcher === 'function' &&\n typeof mod.loadKickConfig === 'function'\n ) {\n return mod as TypegenCliModule\n }\n return null\n } catch {\n return null\n }\n}\n\nexport interface TypegenPluginOptions {\n /** Test seam — defaults to project-root resolution of the real CLI. */\n loadCli?: (root: string) => Promise<TypegenCliModule | null>\n}\n\nexport function kickjsTypegenPlugin(opts: TypegenPluginOptions = {}): Plugin {\n const loadCli = opts.loadCli ?? loadCliFromProject\n return {\n name: 'kickjs:typegen',\n apply: 'serve',\n\n async configureServer(server: ViteDevServer) {\n // `kick dev` boots Vite in-process and runs its own watcher —\n // stand down so the pipeline never double-runs.\n if ((globalThis as Record<string, unknown>)[OWNER_KEY]) return\n\n const root = server.config.root\n const cli = await loadCli(root)\n if (!cli) {\n server.config.logger.info(\n '[kickjs] typegen-on-save disabled — @forinda/kickjs-cli not resolvable from the ' +\n 'project (install it, or run `kick dev`).',\n )\n return\n }\n\n const config = await cli.loadKickConfig(root).catch(() => null)\n const watcher = cli.createTypegenDevWatcher({\n cwd: root,\n config,\n emitWarning: (message) => {\n server.config.logger.warn(message)\n server.hot.send({\n type: 'custom',\n event: 'kickjs:typegen-error',\n data: { message, timestamp: Date.now() },\n })\n },\n })\n\n // Startup catch-up — bare `vite` has no pre-server typegen pass\n // (kick dev runs one before createServer), so types may be stale\n // from edits made while no dev server was running.\n watcher.runOnce()\n\n server.watcher.on('add', (f: string) => watcher.handleWatchEvent('add', f))\n server.watcher.on('change', (f: string) => watcher.handleWatchEvent('change', f))\n server.watcher.on('unlink', (f: string) => watcher.handleWatchEvent('unlink', f))\n server.watcher.on('unlinkDir', (d: string) => watcher.handleWatchEvent('unlinkDir', d))\n if (watcher.assetSrcRoots.length > 0) {\n server.watcher.add([...watcher.assetSrcRoots])\n }\n if (server.httpServer) {\n server.httpServer.once('close', () => watcher.dispose())\n } else {\n // Middleware mode — no httpServer; tie disposal to the chokidar\n // watcher's own close so the debounce timer can't leak.\n server.watcher.once('close', () => watcher.dispose())\n }\n },\n }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { reloadEnv } from '@forinda/kickjs'\nimport type { Plugin } from 'vite'\n\n/**\n * Vite plugin that watches `.env` files and triggers a full reload\n * when they change. This ensures the dev server picks up environment\n * variable changes without a manual restart.\n *\n * Lives in `@forinda/kickjs-vite` so all Vite-only concerns are in one\n * place.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { envWatchPlugin } from '@forinda/kickjs-vite'\n *\n * export default defineConfig({\n * plugins: [swc.vite(), envWatchPlugin()],\n * })\n * ```\n */\nexport function envWatchPlugin(): Plugin {\n const envFiles = ['.env', '.env.local', '.env.development', '.env.production', '.env.test']\n\n return {\n name: 'kickjs-env-watch',\n\n configureServer(server) {\n const root = server.config.root\n\n for (const file of envFiles) {\n const filePath = path.resolve(root, file)\n if (fs.existsSync(filePath)) {\n server.watcher.add(filePath)\n }\n }\n\n server.watcher.on('change', (changedPath) => {\n const basename = path.basename(changedPath)\n if (envFiles.includes(basename)) {\n server.config.logger.info(` .env changed (${basename}), triggering reload...`, {\n timestamp: true,\n })\n\n // Re-read the .env file into process.env *before* invalidating\n // modules. Without this, the next SSR evaluation parses the\n // (stale) cached env snapshot — Zod throws on the missing key\n // and the user has to hard-restart the dev server.\n try {\n reloadEnv()\n } catch (err: any) {\n server.config.logger.warn(\n ` env reload failed: ${err?.message ?? err} — restart may be required`,\n { timestamp: true },\n )\n }\n\n // Invalidate all modules to trigger full HMR rebuild\n const mods = server.moduleGraph.getModulesByFile(path.resolve(root, 'src/index.ts'))\n if (mods) {\n for (const mod of mods) {\n server.moduleGraph.invalidateModule(mod)\n }\n }\n\n server.ws.send({ type: 'full-reload' })\n }\n })\n },\n }\n}\n","/**\n * @forinda/kickjs-vite — Vite plugin for the KickJS framework.\n *\n * Provides first-class Vite integration for KickJS backend applications:\n * - **Dev server**: Mounts the app on Vite's HTTP server (single port)\n * - **HMR**: Fresh server code on every request via `ssrLoadModule()`\n * - **httpServer piping**: Real `http.Server` available to all adapters\n * - **Virtual modules**: Auto-generated application entry\n *\n * ## Quick Start\n *\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import { kickjsVitePlugin } from '@forinda/kickjs-vite'\n * import swc from 'unplugin-swc'\n *\n * export default defineConfig({\n * plugins: [\n * swc.vite({ tsconfigFile: 'tsconfig.json' }),\n * kickjsVitePlugin({ entry: 'src/index.ts' }),\n * ],\n * })\n * ```\n *\n * ```ts\n * // src/index.ts\n * import { bootstrap } from '@forinda/kickjs'\n * import { UserModule } from './modules/users/user.module'\n *\n * // Export the app — Vite serves it in dev, you start it in prod\n * export const app = bootstrap({\n * modules: [UserModule],\n * middlewares: [express.json()],\n * })\n *\n * // Production: start the server directly\n * if (process.env.NODE_ENV === 'production') {\n * app.start()\n * }\n * ```\n *\n * ## Architecture\n *\n * The plugin returns an array of focused sub-plugins (React Router pattern):\n *\n * | Plugin | Responsibility |\n * |--------|---------------|\n * | `kickjs:core` | Vite config: appType, SSR environment, externals |\n * | `kickjs:module-discovery` | Auto-discover `@Module` classes via `transform()` |\n * | `kickjs:hmr` | Selective container invalidation via `handleHotUpdate()` |\n * | `kickjs:virtual-modules` | `virtual:kickjs/app` resolution and generation |\n * | `kickjs:dev-server` | `configureServer()` — mounts the app, pipes httpServer |\n *\n * ## httpServer Piping\n *\n * Vite creates the `http.Server` — this plugin stores it on\n * `globalThis.__kickjs_httpServer`. KickJS adapters (WsAdapter, Socket.IO,\n * GraphQL subscriptions) attach to this server via the standard\n * `afterStart({ server })` hook. Zero adapter code changes needed.\n *\n * @see https://kickjs.app/api/vite\n *\n * @module @forinda/kickjs-vite\n */\n\nimport { kickViewsPlugin } from './kick-views-plugin'\nimport { resolve } from 'node:path'\nimport type { Plugin } from 'vite'\nimport type { KickJSPluginOptions, PluginContext } from './types'\nimport { kickjsCorePlugin } from './core-plugin'\nimport { kickjsVirtualModulesPlugin } from './virtual-modules'\nimport { kickjsDevServerPlugin } from './dev-server'\nimport { kickjsModuleDiscoveryPlugin } from './module-discovery'\nimport { kickjsHmrPlugin } from './hmr-plugin'\nimport { devtoolsFlagPlugin } from './devtools-flag-plugin'\nimport { devtoolsStripPlugin } from './devtools-strip-plugin'\nimport { kickjsTypegenPlugin } from './typegen-plugin'\n\n/**\n * Create the KickJS Vite plugin array.\n *\n * Returns an array of focused sub-plugins that together provide full\n * Vite integration for KickJS backend applications. Each sub-plugin\n * has a single responsibility and runs at the appropriate Vite lifecycle stage.\n *\n * @param options - Plugin configuration\n * @param options.entry - Path to app entry file (default: 'src/index.ts')\n * @returns Array of Vite plugins\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import { kickjsVitePlugin } from '@forinda/kickjs-vite'\n * import swc from 'unplugin-swc'\n *\n * export default defineConfig({\n * plugins: [\n * swc.vite({ tsconfigFile: 'tsconfig.json' }),\n * kickjsVitePlugin(),\n * ],\n * })\n * ```\n */\nexport { kickViewsPlugin, type KickViewsPluginOptions } from './kick-views-plugin'\n\nexport function kickjsVitePlugin(options: KickJSPluginOptions = {}): Plugin[] {\n const entry = options.entry ?? 'src/index.ts'\n\n // Create shared context — resolved lazily in config hook since we\n // don't have the root directory until Vite resolves its config.\n const ctx: PluginContext = {\n entry,\n root: process.cwd(),\n }\n\n // Resolve root and entry as early as possible so sub-plugin config() hooks\n // (e.g., warmup) see the correct absolute entry path.\n const rootResolver: Plugin = {\n name: 'kickjs:root-resolver',\n config(config) {\n const root = config.root ?? process.cwd()\n ctx.root = root\n ctx.entry = resolve(root, entry)\n },\n }\n\n const plugins: Plugin[] = [\n rootResolver,\n kickjsCorePlugin(ctx),\n kickjsModuleDiscoveryPlugin(ctx),\n kickjsHmrPlugin(ctx, options.hmr),\n kickjsVirtualModulesPlugin(ctx),\n kickjsDevServerPlugin(ctx),\n // Typegen-on-save for bare `vite` boots — no-op under `kick dev`\n // (which claims ownership) or when @forinda/kickjs-cli is absent.\n kickjsTypegenPlugin(),\n // `virtual:kick-views` for .kick templates — inert unless the app imports it.\n ...(options.views === false ? [] : [kickViewsPlugin(options.views)]),\n ]\n // Register the devtools flag plugin by default. Adopters who don't\n // gate their devtools imports get a harmless no-op; adopters who do\n // get tree-shaking for free. Pass `devtools: false` to skip.\n if (options.devtools !== false) {\n plugins.push(devtoolsFlagPlugin(options.devtools ?? {}))\n // Babel-based strip — runs only on `vite build`, removes\n // devtools-kit imports + their top-level call sites without\n // requiring adopters to gate them behind the flag. See\n // `babel-strip-devtools.ts` for the rule set.\n plugins.push(devtoolsStripPlugin({ devtools: options.devtools ?? {} }))\n }\n return plugins\n}\n\n// Re-export types for consumers\nexport type {\n KickJSPluginOptions,\n PluginContext,\n HmrOptions,\n HmrInvalidationContext,\n DevtoolsOptions,\n} from './types'\n\n// Standalone plugins users can compose alongside `kickjsVitePlugin()`\nexport { envWatchPlugin } from './env-watch-plugin'\nexport {\n kickjsTypegenPlugin,\n type TypegenPluginOptions,\n type TypegenCliModule,\n} from './typegen-plugin'\nexport {\n devtoolsFlagPlugin,\n resolveDevtoolsFlag,\n type DevtoolsFlagOptions,\n} from './devtools-flag-plugin'\nexport { devtoolsStripPlugin, type DevtoolsStripOptions } from './devtools-strip-plugin'\nexport {\n stripDevtoolsCode,\n type StripDevtoolsOptions,\n type StripResult,\n} from './babel-strip-devtools'\nexport { compressAssets, compressDirectory, type CompressAssetsOptions } from './compress-plugin'\n"],"mappings":";;;;;;;;;;kYAqCA,MACM,SAAW,uBAEjB,eAAe,UAAU,IAAgC,CAGvD,OAFK,WAAW,GAAG,GAEZ,MADe,QAAQ,IAAK,CAAE,UAAW,GAAM,cAAe,EAAK,CAAC,EAAA,CAExE,OAAQ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2B,GAAG,EAC9B,sBAAsB,GAAG,EAGzB,oBAAoB,EAEpB,GAAI,QAAQ,QAAU,GAAQ,CAAC,EAAI,CAAC,gBAAgB,QAAQ,KAAK,CAAC,CACpE,EAYA,OARI,QAAQ,WAAa,KACvB,QAAQ,KAAK,mBAAmB,QAAQ,UAAY,CAAC,CAAC,CAAC,EAKvD,QAAQ,KAAK,oBAAoB,CAAE,SAAU,QAAQ,UAAY,CAAC,CAAE,CAAC,CAAC,GAEjE,OACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-vite",
3
- "version": "8.4.0",
3
+ "version": "8.5.0",
4
4
  "description": "Vite plugin for KickJS — dev server integration, HMR, virtual modules, httpServer piping",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -50,9 +50,9 @@
50
50
  "typescript": "^7.0.2",
51
51
  "vite": "^8.3.4",
52
52
  "vitest": "^5.0.5",
53
- "@forinda/kickjs": "10.12.0",
54
- "@forinda/kickjs-view": "0.3.0",
55
- "@forinda/kickjs-cli": "8.15.0"
53
+ "@forinda/kickjs-cli": "8.16.0",
54
+ "@forinda/kickjs-view": "0.4.0",
55
+ "@forinda/kickjs": "10.13.0"
56
56
  },
57
57
  "publishConfig": {
58
58
  "access": "public"