@forinda/kickjs-devtools 7.2.0 → 7.3.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/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
 
2
2
  import "reflect-metadata";
3
+ import * as kick from "@forinda/kickjs";
3
4
  import { ComputedRef, Ref } from "@forinda/kickjs";
4
5
  import { MemoryAnalyzer, RuntimeSampler } from "@forinda/kickjs-devtools-kit";
5
6
  //#region src/adapter.d.ts
@@ -118,7 +119,7 @@ interface DevToolsAdapterExtensions {
118
119
  * })
119
120
  * ```
120
121
  */
121
- declare const DevToolsAdapter: import("@forinda/kickjs").AdapterFactory<DevToolsOptions, DevToolsAdapterExtensions>;
122
+ export declare const DevToolsAdapter: kick.AdapterFactory<DevToolsOptions, DevToolsAdapterExtensions>;
122
123
  //#endregion
123
- export { DevToolsAdapter, type DevToolsOptions };
124
+ export type { DevToolsOptions };
124
125
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;UAqDU;EACR;EACA;EACA;EACA;;EAEA;;UAoFe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,uBAAuB;;EAEvB;;EAEA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA;;IAEE;;IAEA;;IAEA;;;;;;;;UASa;;WAEN,cAAc;;WAEd,YAAY;;WAEZ,kBAAkB;;WAElB,WAAW;;WAEX,WAAW;;WAEX,eAAe;;WAEf,cAAc,eAAe;;;;;;WAM7B,gBAAgB;;;;;;WAMhB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8Bd,2CAAe,eAAA,iBAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;;UA2EU;EACR;EACA;EACA;EACA;;EAEA;;UA4Ee;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,uBAAuB;;EAEvB;;EAEA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA;;IAEE;;IAEA;;IAEA;;;;;;;;UASa;;WAEN,cAAc;;WAEd,YAAY;;WAEZ,kBAAkB;;WAElB,WAAW;;WAEX,WAAW;;WAEX,eAAe;;WAEf,cAAc,eAAe;;;;;;WAM7B,gBAAgB;;;;;;WAMhB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8Bd,iBAAe,KAAA,eAAA,iBAAA"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-devtools v7.2.0
2
+ * @forinda/kickjs-devtools v7.3.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,13 +8,8 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"reflect-metadata";import{static as static$1}from"express";import{dirname,join}from"node:path";import{tmpdir}from"node:os";import{fileURLToPath}from"node:url";import{createReadStream,existsSync,readFileSync,statSync,unlink}from"node:fs";import{randomBytes}from"node:crypto";import{writeHeapSnapshot}from"node:v8";import{METADATA,computed,createLogger,defineAdapter,getClassMeta,getMethodMeta,getRouteFlags,reactive,ref,watch}from"@forinda/kickjs";import{MemoryAnalyzer,PROTOCOL_VERSION,RuntimeSampler}from"@forinda/kickjs-devtools-kit";import{DEVTOOLS_BUS}from"@forinda/kickjs-devtools-kit/bus/token";import{createBusCore}from"@forinda/kickjs-devtools-kit/bus";import{WebSocketServer}from"ws";async function collectTopologySnapshot(opts){let{app,container,introspectTimeoutMs=100}=opts,errors=[],plugins=await Promise.all(app.getPlugins().map(p=>snapshotFor(p,`plugin`,introspectTimeoutMs,errors))),adapters=await Promise.all(app.getAdapters().map(a=>snapshotFor(a,`adapter`,introspectTimeoutMs,errors)));return{protocolVersion:PROTOCOL_VERSION,timestamp:Date.now(),plugins,adapters,contributors:collectContributors(app),diTokens:collectTokens(container),errors}}async function snapshotFor(primitive,kind,timeoutMs,errors){let name=primitive.name??`(unnamed)`,stub={protocolVersion:PROTOCOL_VERSION,name,kind};if(typeof primitive.introspect!=`function`)return stub;try{let result=await Promise.race([Promise.resolve(primitive.introspect()),new Promise((_,reject)=>setTimeout(()=>reject(Error(`introspect() timed out after ${timeoutMs}ms`)),timeoutMs))]);if(result&&typeof result==`object`){let snap=result;return{protocolVersion:PROTOCOL_VERSION,name:snap.name??name,kind:snap.kind??kind,version:snap.version,state:snap.state,tokens:snap.tokens,metrics:snap.metrics,memoryBytes:snap.memoryBytes}}return stub}catch(err){return errors.push({name,kind,message:err instanceof Error?err.message:String(err)}),stub}}function collectTokens(container){return container.getRegistrations().filter(r=>!r.token.startsWith(`__hmr__`)).map(r=>({token:r.token,scope:r.scope,kind:r.kind,instantiated:r.instantiated}))}function collectContributors(app){let seen=new Map;if(typeof app.getContributors==`function`){for(let c of app.getContributors())seen.has(c.key)||seen.set(c.key,{key:c.key,source:c.source,dependsOn:c.dependsOn});return[...seen.values()]}let ingest=(list,source)=>{if(list)for(let reg of list){let r=reg,key=typeof r.key==`string`?r.key:null;!key||seen.has(key)||seen.set(key,{key,source,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let plugin of app.getPlugins())ingest(plugin.contributors?.(),`adapter`);for(let adapter of app.getAdapters())ingest(adapter.contributors?.(),`adapter`);return[...seen.values()]}const VALID_VIEW_TYPES=new Set([`iframe`,`launch`,`html`]);function collectDevtoolsTabs(app){let tabs=[],seen=new Map,errors=[],ingest=(sourceName,raw)=>{if(!Array.isArray(raw)){errors.push({source:sourceName,reason:`devtoolsTabs() did not return an array`});return}for(let entry of raw){let validation=validateTab(entry);if(!validation.ok){errors.push({source:sourceName,reason:validation.reason});continue}let tab=validation.tab,owner=seen.get(tab.id);if(owner){errors.push({source:sourceName,reason:`tab id '${tab.id}' already registered by ${owner} — first-source wins`});continue}seen.set(tab.id,sourceName),tabs.push(tab)}};for(let plugin of app.getPlugins())if(typeof plugin.devtoolsTabs==`function`)try{ingest(plugin.name??`(unnamed plugin)`,plugin.devtoolsTabs())}catch(err){errors.push({source:plugin.name??`(unnamed plugin)`,reason:err instanceof Error?err.message:String(err)})}for(let adapter of app.getAdapters())if(typeof adapter.devtoolsTabs==`function`)try{ingest(adapter.name??`(unnamed adapter)`,adapter.devtoolsTabs())}catch(err){errors.push({source:adapter.name??`(unnamed adapter)`,reason:err instanceof Error?err.message:String(err)})}return{tabs,errors}}function validateTab(raw){if(!raw||typeof raw!=`object`)return{ok:!1,reason:`tab entry is not an object`};let obj=raw;if(typeof obj.id!=`string`||obj.id.length===0)return{ok:!1,reason:`tab.id must be a non-empty string`};if(typeof obj.title!=`string`||obj.title.length===0)return{ok:!1,reason:`tab '${obj.id}': title must be a non-empty string`};let view=obj.view;if(!view||typeof view!=`object`)return{ok:!1,reason:`tab '${obj.id}': view object is required`};if(typeof view.type!=`string`||!VALID_VIEW_TYPES.has(view.type))return{ok:!1,reason:`tab '${obj.id}': view.type must be one of iframe / launch / html`};switch(view.type){case`iframe`:if(typeof view.src!=`string`||view.src.length===0)return{ok:!1,reason:`tab '${obj.id}': iframe view requires a non-empty src`};break;case`html`:if(typeof view.html!=`string`)return{ok:!1,reason:`tab '${obj.id}': html view requires html string`};break;case`launch`:if(!Array.isArray(view.actions))return{ok:!1,reason:`tab '${obj.id}': launch view requires actions array`};break}return{ok:!0,tab:obj}}function createServerBus(opts={}){let wsPath=opts.wsPath??`/_debug/_bus`,secret=opts.secret??!1,core=createBusCore(),wss=new WebSocketServer({noServer:!0}),clients=new Set,attachedServer=null,upgradeHandler=null;wss.on(`connection`,ws=>{clients.add(ws),ws.on(`message`,data=>{try{let text=typeof data==`string`?data:data.toString(`utf-8`),parsed=JSON.parse(text);if(!parsed||typeof parsed.type!=`string`||typeof parsed.ts!=`number`)return;core.dispatch({...parsed,__kick_origin:`ws`})}catch{}}),ws.on(`close`,()=>{clients.delete(ws)}),ws.on(`error`,()=>{clients.delete(ws)})});let fanOut=envelope=>{if(clients.size===0)return;let text=JSON.stringify(envelope);for(let client of clients)if(client.readyState===client.OPEN)try{client.send(text)}catch{}},checkAuth=req=>{if(secret===!1)return!0;let header=req.headers[`x-devtools-token`];if(typeof header==`string`&&header===secret)return!0;let url=req.url??``,queryIdx=url.indexOf(`?`);return queryIdx!==-1&&new URLSearchParams(url.slice(queryIdx+1)).get(`token`)===secret};return{on(type,handler){return core.on(type,handler)},onAny(handler){return core.onAny(handler)},emit(type,payload){let envelope={type,payload,ts:Date.now(),__kick_origin:`local`};core.dispatch(envelope),fanOut(envelope)},attachUpgrade:httpServer=>{attachedServer||(attachedServer=httpServer,upgradeHandler=(req,socket,head)=>{if((req.url??``).split(`?`)[0]===wsPath){if(!checkAuth(req)){socket.write(`HTTP/1.1 401 Unauthorized\r
11
+ import"reflect-metadata";import{dirname,join,relative,sep}from"node:path";import{tmpdir}from"node:os";import{fileURLToPath}from"node:url";import{createReadStream,existsSync,readFileSync,readdirSync,statSync,unlink}from"node:fs";import{Readable}from"node:stream";import{randomBytes}from"node:crypto";import{writeHeapSnapshot}from"node:v8";import*as kick from"@forinda/kickjs";import{METADATA,computed,createLogger,defineAdapter,getClassMeta,getMethodMeta,getRouteFlags,reactive,ref,watch}from"@forinda/kickjs";import{MemoryAnalyzer,PROTOCOL_VERSION,RuntimeSampler}from"@forinda/kickjs-devtools-kit";import{DEVTOOLS_BUS}from"@forinda/kickjs-devtools-kit/bus/token";import{createBusCore}from"@forinda/kickjs-devtools-kit/bus";import{WebSocketServer}from"ws";async function collectTopologySnapshot(opts){let{app,container,introspectTimeoutMs=100}=opts,errors=[],plugins=await Promise.all(app.getPlugins().map(p=>snapshotFor(p,`plugin`,introspectTimeoutMs,errors))),adapters=await Promise.all(app.getAdapters().map(a=>snapshotFor(a,`adapter`,introspectTimeoutMs,errors)));return{protocolVersion:PROTOCOL_VERSION,timestamp:Date.now(),plugins,adapters,contributors:collectContributors(app),diTokens:collectTokens(container),errors}}async function snapshotFor(primitive,kind,timeoutMs,errors){let name=primitive.name??`(unnamed)`,stub={protocolVersion:PROTOCOL_VERSION,name,kind};if(typeof primitive.introspect!=`function`)return stub;try{let result=await Promise.race([Promise.resolve(primitive.introspect()),new Promise((_,reject)=>setTimeout(()=>reject(Error(`introspect() timed out after ${timeoutMs}ms`)),timeoutMs))]);if(result&&typeof result==`object`){let snap=result;return{protocolVersion:PROTOCOL_VERSION,name:snap.name??name,kind:snap.kind??kind,version:snap.version,state:snap.state,tokens:snap.tokens,metrics:snap.metrics,memoryBytes:snap.memoryBytes}}return stub}catch(err){return errors.push({name,kind,message:err instanceof Error?err.message:String(err)}),stub}}function collectTokens(container){return container.getRegistrations().filter(r=>!r.token.startsWith(`__hmr__`)).map(r=>({token:r.token,scope:r.scope,kind:r.kind,instantiated:r.instantiated}))}function collectContributors(app){let seen=new Map;if(typeof app.getContributors==`function`){for(let c of app.getContributors())seen.has(c.key)||seen.set(c.key,{key:c.key,source:c.source,dependsOn:c.dependsOn});return[...seen.values()]}let ingest=(list,source)=>{if(list)for(let reg of list){let r=reg,key=typeof r.key==`string`?r.key:null;key&&!seen.has(key)&&seen.set(key,{key,source,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let plugin of app.getPlugins())ingest(plugin.contributors?.(),`adapter`);for(let adapter of app.getAdapters())ingest(adapter.contributors?.(),`adapter`);return[...seen.values()]}const VALID_VIEW_TYPES=new Set([`iframe`,`launch`,`html`]);function collectDevtoolsTabs(app){let tabs=[],seen=new Map,errors=[],ingest=(sourceName,raw)=>{if(!Array.isArray(raw)){errors.push({source:sourceName,reason:`devtoolsTabs() did not return an array`});return}for(let entry of raw){let validation=validateTab(entry);if(!validation.ok){errors.push({source:sourceName,reason:validation.reason});continue}let tab=validation.tab,owner=seen.get(tab.id);if(owner){errors.push({source:sourceName,reason:`tab id '${tab.id}' already registered by ${owner} — first-source wins`});continue}seen.set(tab.id,sourceName),tabs.push(tab)}};for(let plugin of app.getPlugins())if(typeof plugin.devtoolsTabs==`function`)try{ingest(plugin.name??`(unnamed plugin)`,plugin.devtoolsTabs())}catch(err){errors.push({source:plugin.name??`(unnamed plugin)`,reason:err instanceof Error?err.message:String(err)})}for(let adapter of app.getAdapters())if(typeof adapter.devtoolsTabs==`function`)try{ingest(adapter.name??`(unnamed adapter)`,adapter.devtoolsTabs())}catch(err){errors.push({source:adapter.name??`(unnamed adapter)`,reason:err instanceof Error?err.message:String(err)})}return{tabs,errors}}function validateTab(raw){if(!raw||typeof raw!=`object`)return{ok:!1,reason:`tab entry is not an object`};let obj=raw;if(typeof obj.id!=`string`||obj.id.length===0)return{ok:!1,reason:`tab.id must be a non-empty string`};if(typeof obj.title!=`string`||obj.title.length===0)return{ok:!1,reason:`tab '${obj.id}': title must be a non-empty string`};let view=obj.view;if(!view||typeof view!=`object`)return{ok:!1,reason:`tab '${obj.id}': view object is required`};if(typeof view.type!=`string`||!VALID_VIEW_TYPES.has(view.type))return{ok:!1,reason:`tab '${obj.id}': view.type must be one of iframe / launch / html`};switch(view.type){case`iframe`:if(typeof view.src!=`string`||view.src.length===0)return{ok:!1,reason:`tab '${obj.id}': iframe view requires a non-empty src`};break;case`html`:if(typeof view.html!=`string`)return{ok:!1,reason:`tab '${obj.id}': html view requires html string`};break;case`launch`:if(!Array.isArray(view.actions))return{ok:!1,reason:`tab '${obj.id}': launch view requires actions array`}}return{ok:!0,tab:obj}}const escape=name=>name.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function findHandlerLine(source,controller,handler){let cls=RegExp(`\\bclass\\s+${escape(controller)}\\b`).exec(source);if(!cls)return;let lineAt=offset=>source.slice(0,offset).split(`
12
+ `).length,start=cls.index+cls[0].length,rest=source.slice(start),next=rest.search(/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s/m),body=next===-1?rest:rest.slice(0,next),method=RegExp(`^[ \\t]*(?:(?:public|private|protected|static|async|override)\\s+)*${escape(handler)}\\s*[(<]`,`m`).exec(body);return lineAt(method?start+method.index+method[0].search(/\S/):cls.index)}function locateHandler(root,controller,handler){let dir=existsSync(join(root,`src`))?join(root,`src`):root,files=readdirSync(dir,{recursive:!0,encoding:`utf-8`}).filter(f=>/\.[mc]?tsx?$/.test(f)&&!/\.d\.[mc]?ts$/.test(f)&&!f.split(sep).includes(`node_modules`)&&!f.split(sep).includes(`dist`));for(let f of files){let file=join(dir,f),source;try{source=readFileSync(file,`utf-8`)}catch{continue}if(!source.includes(controller))continue;let line=findHandlerLine(source,controller,handler);if(line!==void 0)return{file,relative:relative(root,file).split(sep).join(`/`),line}}}function createServerBus(opts={}){let wsPath=opts.wsPath??`/_debug/_bus`,secret=opts.secret??!1,core=createBusCore(),wss=new WebSocketServer({noServer:!0}),clients=new Set,attachedServer=null,upgradeHandler=null;wss.on(`connection`,ws=>{clients.add(ws),ws.on(`message`,data=>{try{let text=typeof data==`string`?data:data.toString(`utf-8`),parsed=JSON.parse(text);if(!parsed||typeof parsed.type!=`string`||typeof parsed.ts!=`number`)return;core.dispatch({...parsed,__kick_origin:`ws`})}catch{}}),ws.on(`close`,()=>{clients.delete(ws)}),ws.on(`error`,()=>{clients.delete(ws)})});let fanOut=envelope=>{if(clients.size===0)return;let text=JSON.stringify(envelope);for(let client of clients)if(client.readyState===client.OPEN)try{client.send(text)}catch{}},checkAuth=req=>{if(secret===!1)return!0;let header=req.headers[`x-devtools-token`];if(typeof header==`string`&&header===secret)return!0;let url=req.url??``,queryIdx=url.indexOf(`?`);return queryIdx!==-1&&new URLSearchParams(url.slice(queryIdx+1)).get(`token`)===secret};return{on(type,handler){return core.on(type,handler)},onAny(handler){return core.onAny(handler)},emit(type,payload){let envelope={type,payload,ts:Date.now(),__kick_origin:`local`};core.dispatch(envelope),fanOut(envelope)},attachUpgrade:httpServer=>{attachedServer||(attachedServer=httpServer,upgradeHandler=(req,socket,head)=>{if((req.url??``).split(`?`)[0]===wsPath){if(!checkAuth(req)){socket.write(`HTTP/1.1 401 Unauthorized\r
12
13
  \r
13
- `),socket.destroy();return}wss.handleUpgrade(req,socket,head,ws=>{wss.emit(`connection`,ws,req)})}},httpServer.on(`upgrade`,upgradeHandler))},close:()=>{attachedServer&&upgradeHandler&&attachedServer.off(`upgrade`,upgradeHandler),attachedServer=null,upgradeHandler=null;for(let client of clients)try{client.close()}catch{}clients.clear(),wss.close()},clientCount:()=>clients.size}}const log=createLogger(`DevTools`);function percentile(sorted,p){if(sorted.length===0)return 0;let idx=Math.ceil(p*sorted.length)-1;return sorted[Math.max(0,idx)]}function computePercentiles(stats){let sorted=[...stats.samples].toSorted((a,b)=>a-b);return{p50:percentile(sorted,.5),p95:percentile(sorted,.95),p99:percentile(sorted,.99)}}function openSseStream(req,res){res.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),res.flushHeaders?.()}function writeSseEvent(res,payload){res.write(`data: ${JSON.stringify(payload)}\n\n`)}function raceWithTimeout(promise,ms,label){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms)});return Promise.race([promise,timeout]).finally(()=>{timer&&clearTimeout(timer)})}let snapshotInProgress=!1;const DevToolsAdapter=defineAdapter({name:`DevToolsAdapter`,defaults:{basePath:`/_debug`,errorRateThreshold:.5,exposeConfig:!1,configPrefixes:[`APP_`,`NODE_ENV`]},build:options=>{let basePath=options.basePath,enabled=options.enabled??process.env.NODE_ENV!==`production`,exposeConfig=options.exposeConfig,configPrefixes=options.configPrefixes,errorRateThreshold=options.errorRateThreshold,peerAdapters=options.adapters??[],secret;secret=options.secret===!1?!1:options.secret?options.secret:randomBytes(16).toString(`hex`);let runtimeEnabled=options.runtime?.enabled??!0,runtimeSampler=runtimeEnabled?new RuntimeSampler({intervalMs:options.runtime?.intervalMs??1e3,bufferSize:options.runtime?.bufferSize??60}):null,memoryAnalyzer=runtimeEnabled?new MemoryAnalyzer:null,bus=null,ensureBus=container=>container.has(DEVTOOLS_BUS)?(bus=container.resolve(DEVTOOLS_BUS),bus):(bus=enabled?createServerBus({wsPath:`${basePath}/_bus`,secret:secret!==!1&&secret}):{on:()=>()=>{},onAny:()=>()=>{},emit:()=>{},attachUpgrade:()=>{},close:()=>{},clientCount:()=>0},container.registerInstance(DEVTOOLS_BUS,bus),bus),requestCount=ref(0),errorCount=ref(0),clientErrorCount=ref(0),startedAt=ref(Date.now()),routeLatency=reactive({}),errorRate=computed(()=>requestCount.value>0?errorCount.value/requestCount.value:0),uptimeSeconds=computed(()=>(startedAt.value,Math.floor(process.uptime()))),routes=[],container=null,appRef=null,adapterStatuses={},stopErrorWatch=null;if(options.onErrorRateExceeded){let callback=options.onErrorRateExceeded;stopErrorWatch=watch(errorRate,rate=>{rate>errorRateThreshold&&callback(rate)})}else stopErrorWatch=watch(errorRate,rate=>{rate>errorRateThreshold&&log.warn(`Error rate elevated: ${(rate*100).toFixed(1)}%`)});let resolvePublicDir=()=>{let thisDir=dirname(fileURLToPath(import.meta.url)),candidates=[join(thisDir,`..`,`public`,`spa`),join(thisDir,`..`,`..`,`public`,`spa`),join(thisDir,`..`,`public`,`devtools`),join(thisDir,`..`,`..`,`public`,`devtools`)];for(let dir of candidates)if(existsSync(join(dir,`index.html`)))return dir;return null},getPeerAdapters=()=>{let kickApp=appRef?.__kickApp;return kickApp&&typeof kickApp.getAdapters==`function`?kickApp.getAdapters():peerAdapters},readActiveRuntime=()=>{let kickApp=appRef?.__kickApp;if(kickApp&&typeof kickApp.getActiveRuntime==`function`)try{return kickApp.getActiveRuntime()}catch{return null}return null};return{requestCount,errorCount,clientErrorCount,startedAt,errorRate,uptimeSeconds,routeLatency,runtimeSampler,memoryAnalyzer,introspect(){return{protocolVersion:PROTOCOL_VERSION,name:`DevToolsAdapter`,kind:`adapter`,state:{basePath,enabled,runtimeEnabled,secret:secret!==!1&&`present`},metrics:{requestCount:requestCount.value,serverErrors:errorCount.value,clientErrors:clientErrorCount.value,uptimeSeconds:uptimeSeconds.value,routesTracked:routes.length}}},beforeMount({app,http,container:containerArg}){if(!enabled)return;appRef=app,container=containerArg,ensureBus(containerArg),startedAt.value=Date.now(),routes=[],adapterStatuses.DevToolsAdapter=`running`,runtimeSampler?.start(),memoryAnalyzer?.start();let joinBase=p=>p===`/`?basePath:`${basePath}${p}`,router={use:mw=>http.use(mw,{path:basePath}),get:(path,handler)=>http.route(`GET`,joinBase(path),ctx=>handler(ctx.req,ctx.res)),post:(path,handler)=>http.route(`POST`,joinBase(path),ctx=>handler(ctx.req,ctx.res))};if(secret!==!1){let token=secret;router.use((req,res,next)=>{if((req.headers[`x-devtools-token`]??req.query?.token)===token||req.path===`/`&&req.method===`GET`&&!req.query?.token||req.path.endsWith(`.js`)||req.path.endsWith(`.css`))return next();res.status(403).json({error:`Forbidden — invalid or missing devtools token`})})}router.get(`/routes`,(_req,res)=>{res.json({routes})}),router.get(`/container`,(_req,res)=>{let registrations=container?.getRegistrations()??[];res.json({registrations,count:registrations.length})}),router.get(`/metrics`,(_req,res)=>{let latency={};for(let[key,stats]of Object.entries(routeLatency)){let{samples:_,...rest}=stats;latency[key]={...rest,...computePercentiles(stats)}}res.json({requests:requestCount.value,serverErrors:errorCount.value,clientErrors:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value,startedAt:new Date(startedAt.value).toISOString(),routeLatency:latency})}),router.get(`/health`,async(_req,res)=>{let healthy=errorRate.value<errorRateThreshold,status=healthy?`healthy`:`degraded`,live={...adapterStatuses};await Promise.all(getPeerAdapters().map(async peer=>{if(typeof peer?.onHealthCheck!=`function`)return;let name=peer?.name;if(typeof name==`string`&&name!==`DevToolsAdapter`)try{let result=await raceWithTimeout(Promise.resolve(peer.onHealthCheck()),1500,`onHealthCheck(${name})`);result&&typeof result.status==`string`&&(live[name]=result.status)}catch{live[name]=`down`}})),res.status(healthy?200:503).json({status,errorRate:errorRate.value,uptime:uptimeSeconds.value,runtime:readActiveRuntime(),adapters:live})}),router.get(`/state`,(_req,res)=>{let wsAdapter=getPeerAdapters().find(a=>a.name===`WsAdapter`&&typeof a.getStats==`function`);res.json({reactive:{requestCount:requestCount.value,errorCount:errorCount.value,clientErrorCount:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value,startedAt:new Date(startedAt.value).toISOString()},routes:routes.length,container:container?.getRegistrations().length??0,routeLatency,...wsAdapter?{ws:wsAdapter.getStats()}:{}})}),router.get(`/runtime`,(_req,res)=>{if(!runtimeSampler||!memoryAnalyzer){res.status(404).json({error:`runtime sampler disabled — set runtime.enabled = true`});return}let latest=runtimeSampler.latest(),history=runtimeSampler.history(),health=memoryAnalyzer.health(history);res.json({protocolVersion:PROTOCOL_VERSION,process:{nodeVersion:process.version,pid:process.pid,platform:process.platform,arch:process.arch,runtime:readActiveRuntime()},latest,history,health})}),router.get(`/runtime/stream`,(req,res)=>{if(!runtimeSampler){res.status(404).json({error:`runtime sampler disabled`});return}openSseStream(req,res);let intervalMs=options.runtime?.intervalMs??1e3,tick=()=>{let snap=runtimeSampler.latest();snap&&writeSseEvent(res,snap)};tick();let interval=setInterval(tick,intervalMs),heartbeat=setInterval(()=>res.write(`: heartbeat
14
-
15
- `),3e4);req.on(`close`,()=>{clearInterval(interval),clearInterval(heartbeat)})}),router.get(`/memory/stream`,(req,res)=>{if(!runtimeSampler||!memoryAnalyzer){res.status(404).json({error:`runtime sampler disabled`});return}openSseStream(req,res);let intervalMs=options.runtime?.intervalMs??1e3,tick=()=>{let snap=runtimeSampler.latest();snap&&writeSseEvent(res,{snapshot:snap,health:memoryAnalyzer.health(runtimeSampler.history())})};tick();let interval=setInterval(tick,intervalMs),heartbeat=setInterval(()=>res.write(`: heartbeat
16
-
17
- `),3e4);req.on(`close`,()=>{clearInterval(interval),clearInterval(heartbeat)})}),router.post(`/memory/snapshot`,(_req,res)=>{if(snapshotInProgress){res.status(503).json({error:`heap snapshot already in progress — wait for it to complete`});return}snapshotInProgress=!0;let startedAt=Date.now(),filename=`kickjs-heap-${new Date().toISOString().replace(/[:.]/g,`-`)}.heapsnapshot`,targetPath=join(tmpdir(),filename),written;try{written=writeHeapSnapshot(targetPath)}catch(err){snapshotInProgress=!1,log.error({err},`heap snapshot capture failed`),res.status(500).json({error:`snapshot capture failed`,message:err.message});return}let size=0;try{size=statSync(written).size}catch{}let elapsedMs=Date.now()-startedAt;log.info(`Heap snapshot captured: ${written} (${(size/1024/1024).toFixed(1)} MiB in ${elapsedMs}ms)`),res.setHeader(`Content-Type`,`application/json`),res.setHeader(`Content-Disposition`,`attachment; filename="${filename}"`),size>0&&res.setHeader(`Content-Length`,String(size)),res.setHeader(`X-Snapshot-Capture-Ms`,String(elapsedMs));let cleanup=()=>{unlink(written,err=>{err&&log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`),snapshotInProgress=!1})},stream=createReadStream(written);stream.on(`end`,cleanup),stream.on(`error`,err=>{log.error({err},`heap snapshot stream failed`),res.headersSent||res.status(500).end(),cleanup()}),res.on(`close`,()=>{stream.destroy()}),stream.pipe(res)}),router.post(`/memory/gc`,(_req,res)=>{let gc=globalThis.gc;if(typeof gc!=`function`){res.status(412).json({error:`global.gc unavailable — start Node with --expose-gc to enable this endpoint`});return}let before=process.memoryUsage().heapUsed,startedAt=Date.now();try{gc()}catch(err){res.status(500).json({error:`forced GC failed`,message:err instanceof Error?err.message:String(err)});return}let after=process.memoryUsage().heapUsed,reclaimedBytes=Math.max(0,before-after),elapsedMs=Date.now()-startedAt;log.info(`Forced GC reclaimed ${(reclaimedBytes/1024/1024).toFixed(2)} MiB in ${elapsedMs}ms`),res.json({before,after,reclaimedBytes,elapsedMs})}),router.get(`/tabs`,(_req,res)=>{let kickApp=appRef?.__kickApp;if(!kickApp){res.status(503).json({error:`tabs unavailable — application surface not exposed`});return}res.json(collectDevtoolsTabs(kickApp))}),router.get(`/topology`,async(_req,res)=>{if(!container){res.status(503).json({error:`topology unavailable — container not bound yet`});return}let kickApp=appRef?.__kickApp;if(!kickApp){res.status(503).json({error:`topology unavailable — application surface not exposed`});return}try{let snapshot=await collectTopologySnapshot({app:kickApp,container});res.json(snapshot)}catch(err){let message=err instanceof Error?err.message:String(err);res.status(500).json({error:`topology collection failed`,message})}}),router.get(`/ws`,(_req,res)=>{let wsAdapter=getPeerAdapters().find(a=>a.name===`WsAdapter`&&typeof a.getStats==`function`);if(!wsAdapter){res.json({enabled:!1,message:`WsAdapter not found`});return}res.json({enabled:!0,...wsAdapter.getStats()})}),router.get(`/queues`,async(_req,res)=>{let queueAdapter=getPeerAdapters().find(a=>a.name===`QueueAdapter`&&typeof a.getQueueNames==`function`);if(!queueAdapter){res.json({enabled:!1,message:`QueueAdapter not found`});return}try{let names=queueAdapter.getQueueNames?.()??[],queues=[];for(let name of names){let stats=await queueAdapter.getQueueStats?.(name);queues.push({name,...stats})}res.json({enabled:!0,queues})}catch{res.json({enabled:!0,queues:[],error:`Failed to fetch queue stats`})}}),router.get(`/graph`,(_req,res)=>{let registrations=container?.getRegistrations()??[],nodes=registrations.filter(r=>!r.token.startsWith(`__hmr__`)).map(r=>({id:r.token,kind:r.kind,scope:r.scope,resolveCount:r.resolveCount})),nodeIds=new Set(nodes.map(n=>n.id)),edges=[];for(let r of registrations)if(!r.token.startsWith(`__hmr__`))for(let dep of r.dependencies)nodeIds.has(dep)&&edges.push({from:r.token,to:dep});res.json({nodes,edges})}),router.get(`/stream`,(req,res)=>{res.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`});let sendMetrics=()=>{let data={type:`metrics`,requestCount:requestCount.value,errorCount:errorCount.value,clientErrorCount:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value};res.write(`data: ${JSON.stringify(data)}\n\n`)};sendMetrics();let unsubContainer=container?.onChange?.(changes=>{res.write(`data: ${JSON.stringify({type:`container`,changes,timestamp:Date.now()})}\n\n`),sendMetrics()}),stopRequestWatch=watch(requestCount,()=>sendMetrics()),stopErrWatch=watch(errorCount,()=>sendMetrics()),heartbeat=setInterval(()=>{res.write(`: heartbeat
18
-
19
- `)},3e4);req.on(`close`,()=>{unsubContainer?.(),stopRequestWatch(),stopErrWatch(),clearInterval(heartbeat)})}),exposeConfig&&router.get(`/config`,(_req,res)=>{let config={};for(let[key,value]of Object.entries(process.env))value!==void 0&&(config[key]=configPrefixes.some(prefix=>key.startsWith(prefix))?value:`[REDACTED]`);res.json({config})});let publicDir=resolvePublicDir();if(publicDir){router.use(static$1(publicDir));let indexHtml=readFileSync(join(publicDir,`index.html`),`utf-8`);router.get(`/`,(_req,res)=>{let html=indexHtml.replace(`<body`,`<body data-base="${basePath}"`);res.type(`html`).send(html)})}else router.get(`/`,(_req,res)=>{res.type(`html`).send(`<h1>DevTools: public directory not found</h1>`)});secret?(log.info(`DevTools mounted at ${basePath} [token: ${secret}]`),log.info(`Access: ${basePath}?token=${secret}`)):log.info(`DevTools mounted at ${basePath} [no guard]`)},middleware(){return enabled?[{handler:(req,res,next)=>{let start=Date.now();requestCount.value++,res.on(`finish`,()=>{res.statusCode>=500?errorCount.value++:res.statusCode>=400&&clientErrorCount.value++;let routeKey=req.route?.path?`${req.method} ${req.route.path}`:`${req.method} <unmatched>`,elapsed=Date.now()-start;routeLatency[routeKey]||(routeLatency[routeKey]={count:0,totalMs:0,minMs:1/0,maxMs:0,samples:[]});let stats=routeLatency[routeKey];stats.count++,stats.totalMs+=elapsed,stats.minMs=Math.min(stats.minMs,elapsed),stats.maxMs=Math.max(stats.maxMs,elapsed),stats.samples.push(elapsed),stats.samples.length>1e3&&stats.samples.shift()}),next()},phase:`beforeGlobal`}]:[]},onRouteMount(controllerClass,mountPath){if(!enabled)return;let collectedRoutes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddleware=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]);for(let route of collectedRoutes){let methodMiddleware=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass.prototype,route.handlerName,[]);routes.push({method:route.method.toUpperCase(),path:`${mountPath}${route.path===`/`?``:route.path}`,controller:controllerClass.name,handler:route.handlerName,middleware:[...classMiddleware.map(m=>m.name||`anonymous`),...methodMiddleware.map(m=>m.name||`anonymous`)],flags:Object.fromEntries(getRouteFlags(controllerClass,route.handlerName))})}},afterStart({server}){if(enabled){server&&bus?.attachUpgrade(server);for(let peer of getPeerAdapters()){let name=peer?.name;typeof name==`string`&&name!==`DevToolsAdapter`&&(adapterStatuses[name]=`running`)}log.info(`DevTools ready — ${routes.length} routes tracked, ${container?.getRegistrations().length??0} DI bindings, event bus on ${basePath}/_bus`)}},shutdown(){stopErrorWatch?.(),runtimeSampler?.stop(),memoryAnalyzer?.stop(),bus?.close(),adapterStatuses.DevToolsAdapter=`stopped`}}}});export{DevToolsAdapter};
14
+ `),socket.destroy();return}wss.handleUpgrade(req,socket,head,ws=>{wss.emit(`connection`,ws,req)})}},httpServer.on(`upgrade`,upgradeHandler))},close:()=>{attachedServer&&upgradeHandler&&attachedServer.off(`upgrade`,upgradeHandler),attachedServer=null,upgradeHandler=null;for(let client of clients)try{client.close()}catch{}clients.clear(),wss.close()},clientCount:()=>clients.size}}const log=createLogger(`DevTools`);function uploadInfo(controllerClass,handlerName){let config=getMethodMeta(METADATA.FILE_UPLOAD,controllerClass,handlerName,void 0);if(!config)return{};let{mode,fieldName,maxCount}=config;return{upload:{mode,...fieldName?{fieldName}:{},...maxCount?{maxCount}:{}}}}const MATCHED_ROUTE_SLOT=Symbol.for(`kick.route`),FRAMEWORK_REPORTS_RESPONSES=typeof kick.reportResponse==`function`;function percentile(sorted,p){if(sorted.length===0)return 0;let idx=Math.ceil(p*sorted.length)-1;return sorted[Math.max(0,idx)]}function computePercentiles(stats){let sorted=[...stats.samples].toSorted((a,b)=>a-b);return{p50:percentile(sorted,.5),p95:percentile(sorted,.95),p99:percentile(sorted,.99)}}function raceWithTimeout(promise,ms,label){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms)});return Promise.race([promise,timeout]).finally(()=>{timer&&clearTimeout(timer)})}let snapshotInProgress=!1;const DevToolsAdapter=defineAdapter({name:`DevToolsAdapter`,defaults:{basePath:`/_debug`,errorRateThreshold:.5,exposeConfig:!1,configPrefixes:[`APP_`,`NODE_ENV`]},build:options=>{let basePath=options.basePath,enabled=options.enabled??process.env.NODE_ENV!==`production`,exposeConfig=options.exposeConfig,configPrefixes=options.configPrefixes,errorRateThreshold=options.errorRateThreshold,peerAdapters=options.adapters??[],secret;secret=options.secret===!1?!1:options.secret?options.secret:randomBytes(16).toString(`hex`);let runtimeEnabled=options.runtime?.enabled??!0,runtimeSampler=runtimeEnabled?new RuntimeSampler({intervalMs:options.runtime?.intervalMs??1e3,bufferSize:options.runtime?.bufferSize??60}):null,memoryAnalyzer=runtimeEnabled?new MemoryAnalyzer:null,bus=null,ensureBus=container=>container.has(DEVTOOLS_BUS)?(bus=container.resolve(DEVTOOLS_BUS),bus):(bus=enabled?createServerBus({wsPath:`${basePath}/_bus`,secret:secret!==!1&&secret}):{on:()=>()=>{},onAny:()=>()=>{},emit:()=>{},attachUpgrade:()=>{},close:()=>{},clientCount:()=>0},container.registerInstance(DEVTOOLS_BUS,bus),bus),requestCount=ref(0),errorCount=ref(0),clientErrorCount=ref(0),startedAt=ref(Date.now()),routeLatency=reactive({}),errorRate=computed(()=>requestCount.value>0?errorCount.value/requestCount.value:0),uptimeSeconds=computed(()=>(startedAt.value,Math.floor(process.uptime()))),routes=[],container=null,appRef=null,recordResponse=(method,route,status,elapsedMs)=>{requestCount.value++,status>=500?errorCount.value++:status>=400&&clientErrorCount.value++;let routeKey=`${method} ${route??`<unmatched>`}`;routeLatency[routeKey]||(routeLatency[routeKey]={count:0,totalMs:0,minMs:1/0,maxMs:0,samples:[]});let stats=routeLatency[routeKey];stats.count++,stats.totalMs+=elapsedMs,stats.minMs=Math.min(stats.minMs,elapsedMs),stats.maxMs=Math.max(stats.maxMs,elapsedMs),stats.samples.push(elapsedMs),stats.samples.length>1e3&&stats.samples.shift()},adapterStatuses={},stopErrorWatch=null;if(options.onErrorRateExceeded){let callback=options.onErrorRateExceeded;stopErrorWatch=watch(errorRate,rate=>{rate>errorRateThreshold&&callback(rate)})}else stopErrorWatch=watch(errorRate,rate=>{rate>errorRateThreshold&&log.warn(`Error rate elevated: ${(rate*100).toFixed(1)}%`)});let resolvePublicDir=()=>{let thisDir=dirname(fileURLToPath(import.meta.url)),candidates=[join(thisDir,`..`,`public`,`spa`),join(thisDir,`..`,`..`,`public`,`spa`),join(thisDir,`..`,`public`,`devtools`),join(thisDir,`..`,`..`,`public`,`devtools`)];for(let dir of candidates)if(existsSync(join(dir,`index.html`)))return dir;return null},getPeerAdapters=()=>{let kickApp=appRef?.__kickApp;return kickApp&&typeof kickApp.getAdapters==`function`?kickApp.getAdapters():peerAdapters},readActiveRuntime=()=>{let kickApp=appRef?.__kickApp;if(kickApp&&typeof kickApp.getActiveRuntime==`function`)try{return kickApp.getActiveRuntime()}catch{return null}return null};return{requestCount,errorCount,clientErrorCount,startedAt,errorRate,uptimeSeconds,routeLatency,runtimeSampler,memoryAnalyzer,introspect(){return{protocolVersion:PROTOCOL_VERSION,name:`DevToolsAdapter`,kind:`adapter`,state:{basePath,enabled,runtimeEnabled,secret:secret!==!1&&`present`},metrics:{requestCount:requestCount.value,serverErrors:errorCount.value,clientErrors:clientErrorCount.value,uptimeSeconds:uptimeSeconds.value,routesTracked:routes.length}}},beforeMount({app,http,container:containerArg}){if(!enabled)return;appRef=app,container=containerArg,ensureBus(containerArg),startedAt.value=Date.now(),routes=[],adapterStatuses.DevToolsAdapter=`running`,runtimeSampler?.start(),memoryAnalyzer?.start();let joinBase=p=>p===`/`?basePath:`${basePath}${p}`,authorized=ctx=>secret===!1||(ctx.headers[`x-devtools-token`]??ctx.query?.token)===secret||(ctx.json({error:`Forbidden — invalid or missing devtools token`},403),!1),guarded=handler=>ctx=>authorized(ctx)?handler(ctx):void 0,router={get:(path,handler)=>http.route(`GET`,joinBase(path),guarded(handler)),post:(path,handler)=>http.route(`POST`,joinBase(path),guarded(handler))};router.get(`/routes`,ctx=>{ctx.json({routes})}),router.get(`/source`,ctx=>{let{controller,handler}=ctx.query,found=routes.some(r=>r.controller===controller&&r.handler===handler)&&controller&&handler?locateHandler(process.cwd(),controller,handler):void 0;if(!found){ctx.json({error:`Handler source not found`},404);return}ctx.json(found)}),router.get(`/container`,ctx=>{let registrations=container?.getRegistrations()??[];ctx.json({registrations,count:registrations.length})}),router.get(`/metrics`,ctx=>{let latency={};for(let[key,stats]of Object.entries(routeLatency)){let{samples:_,...rest}=stats;latency[key]={...rest,...computePercentiles(stats)}}ctx.json({requests:requestCount.value,serverErrors:errorCount.value,clientErrors:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value,startedAt:new Date(startedAt.value).toISOString(),routeLatency:latency})}),router.get(`/health`,async ctx=>{let healthy=errorRate.value<errorRateThreshold,status=healthy?`healthy`:`degraded`,live={...adapterStatuses};await Promise.all(getPeerAdapters().map(async peer=>{if(typeof peer?.onHealthCheck!=`function`)return;let name=peer?.name;if(typeof name==`string`&&name!==`DevToolsAdapter`)try{let result=await raceWithTimeout(Promise.resolve(peer.onHealthCheck()),1500,`onHealthCheck(${name})`);result&&typeof result.status==`string`&&(live[name]=result.status)}catch{live[name]=`down`}})),ctx.json({status,errorRate:errorRate.value,uptime:uptimeSeconds.value,runtime:readActiveRuntime(),adapters:live},healthy?200:503)}),router.get(`/state`,ctx=>{let wsAdapter=getPeerAdapters().find(a=>a.name===`WsAdapter`&&typeof a.getStats==`function`);ctx.json({reactive:{requestCount:requestCount.value,errorCount:errorCount.value,clientErrorCount:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value,startedAt:new Date(startedAt.value).toISOString()},routes:routes.length,container:container?.getRegistrations().length??0,routeLatency,...wsAdapter?{ws:wsAdapter.getStats()}:{}})}),router.get(`/runtime`,ctx=>{if(!runtimeSampler||!memoryAnalyzer){ctx.json({error:`runtime sampler disabled — set runtime.enabled = true`},404);return}let latest=runtimeSampler.latest(),history=runtimeSampler.history(),health=memoryAnalyzer.health(history);ctx.json({protocolVersion:PROTOCOL_VERSION,process:{nodeVersion:process.version,pid:process.pid,platform:process.platform,arch:process.arch,runtime:readActiveRuntime()},latest,history,health})}),router.get(`/runtime/stream`,ctx=>{if(!runtimeSampler){ctx.json({error:`runtime sampler disabled`},404);return}let sse=ctx.sse(),intervalMs=options.runtime?.intervalMs??1e3,tick=()=>{let snap=runtimeSampler.latest();snap&&sse.send(snap)};tick();let interval=setInterval(tick,intervalMs),heartbeat=setInterval(()=>sse.comment(`heartbeat`),3e4);sse.onClose(()=>{clearInterval(interval),clearInterval(heartbeat)})}),router.get(`/memory/stream`,ctx=>{if(!runtimeSampler||!memoryAnalyzer){ctx.json({error:`runtime sampler disabled`},404);return}let sse=ctx.sse(),intervalMs=options.runtime?.intervalMs??1e3,tick=()=>{let snap=runtimeSampler.latest();if(!snap)return;let health=memoryAnalyzer.health(runtimeSampler.history());sse.send({snapshot:snap,health})};tick();let interval=setInterval(tick,intervalMs),heartbeat=setInterval(()=>sse.comment(`heartbeat`),3e4);sse.onClose(()=>{clearInterval(interval),clearInterval(heartbeat)})}),router.post(`/memory/snapshot`,async ctx=>{if(snapshotInProgress){ctx.json({error:`heap snapshot already in progress — wait for it to complete`},503);return}snapshotInProgress=!0;let startedAt=Date.now(),filename=`kickjs-heap-${new Date().toISOString().replace(/[:.]/g,`-`)}.heapsnapshot`,targetPath=join(tmpdir(),filename),written;try{written=writeHeapSnapshot(targetPath)}catch(err){snapshotInProgress=!1,log.error({err},`heap snapshot capture failed`),ctx.json({error:`snapshot capture failed`,message:err.message},500);return}let size=0;try{size=statSync(written).size}catch{}let elapsedMs=Date.now()-startedAt;log.info(`Heap snapshot captured: ${written} (${(size/1024/1024).toFixed(1)} MiB in ${elapsedMs}ms)`);let headers={"Content-Type":`application/json`,"Content-Disposition":`attachment; filename="${filename}"`,"X-Snapshot-Capture-Ms":String(elapsedMs)};size>0&&(headers[`Content-Length`]=String(size));let stream=createReadStream(written);try{await ctx.sendResponse(new Response(Readable.toWeb(stream),{headers}))}catch(err){log.error({err},`heap snapshot stream failed`)}finally{stream.destroy(),unlink(written,err=>{err&&log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`),snapshotInProgress=!1})}}),router.post(`/memory/gc`,ctx=>{let gc=globalThis.gc;if(typeof gc!=`function`){ctx.json({error:`global.gc unavailable — start Node with --expose-gc to enable this endpoint`},412);return}let before=process.memoryUsage().heapUsed,startedAt=Date.now();try{gc()}catch(err){ctx.json({error:`forced GC failed`,message:err instanceof Error?err.message:String(err)},500);return}let after=process.memoryUsage().heapUsed,reclaimedBytes=Math.max(0,before-after),elapsedMs=Date.now()-startedAt;log.info(`Forced GC reclaimed ${(reclaimedBytes/1024/1024).toFixed(2)} MiB in ${elapsedMs}ms`),ctx.json({before,after,reclaimedBytes,elapsedMs})}),router.get(`/tabs`,ctx=>{let kickApp=appRef?.__kickApp;if(!kickApp){ctx.json({error:`tabs unavailable — application surface not exposed`},503);return}ctx.json(collectDevtoolsTabs(kickApp))}),router.get(`/topology`,async ctx=>{if(!container){ctx.json({error:`topology unavailable — container not bound yet`},503);return}let kickApp=appRef?.__kickApp;if(!kickApp){ctx.json({error:`topology unavailable — application surface not exposed`},503);return}try{let snapshot=await collectTopologySnapshot({app:kickApp,container});ctx.json(snapshot)}catch(err){let message=err instanceof Error?err.message:String(err);ctx.json({error:`topology collection failed`,message},500)}}),router.get(`/ws`,ctx=>{let wsAdapter=getPeerAdapters().find(a=>a.name===`WsAdapter`&&typeof a.getStats==`function`);if(!wsAdapter){ctx.json({enabled:!1,message:`WsAdapter not found`});return}ctx.json({enabled:!0,...wsAdapter.getStats()})}),router.get(`/queues`,async ctx=>{let queueAdapter=getPeerAdapters().find(a=>a.name===`QueueAdapter`&&typeof a.getQueueNames==`function`);if(!queueAdapter){ctx.json({enabled:!1,message:`QueueAdapter not found`});return}try{let names=queueAdapter.getQueueNames?.()??[],queues=[];for(let name of names){let stats=await queueAdapter.getQueueStats?.(name);queues.push({name,...stats})}ctx.json({enabled:!0,queues})}catch{ctx.json({enabled:!0,queues:[],error:`Failed to fetch queue stats`})}}),router.get(`/graph`,ctx=>{let registrations=container?.getRegistrations()??[],nodes=registrations.filter(r=>!r.token.startsWith(`__hmr__`)).map(r=>({id:r.token,kind:r.kind,scope:r.scope,resolveCount:r.resolveCount})),nodeIds=new Set(nodes.map(n=>n.id)),edges=[];for(let r of registrations)if(!r.token.startsWith(`__hmr__`))for(let dep of r.dependencies)nodeIds.has(dep)&&edges.push({from:r.token,to:dep});ctx.json({nodes,edges})}),router.get(`/stream`,ctx=>{let sse=ctx.sse(),sendMetrics=()=>{sse.send({type:`metrics`,requestCount:requestCount.value,errorCount:errorCount.value,clientErrorCount:clientErrorCount.value,errorRate:errorRate.value,uptimeSeconds:uptimeSeconds.value})};sendMetrics();let unsubContainer=container?.onChange?.(changes=>{sse.send({type:`container`,changes,timestamp:Date.now()}),sendMetrics()}),stopRequestWatch=watch(requestCount,()=>sendMetrics()),stopErrWatch=watch(errorCount,()=>sendMetrics()),heartbeat=setInterval(()=>sse.comment(`heartbeat`),3e4);sse.onClose(()=>{unsubContainer?.(),stopRequestWatch(),stopErrWatch(),clearInterval(heartbeat)})}),exposeConfig&&router.get(`/config`,ctx=>{let config={};for(let[key,value]of Object.entries(process.env))value!==void 0&&(config[key]=configPrefixes.some(prefix=>key.startsWith(prefix))?value:`[REDACTED]`);ctx.json({config})});let publicDir=resolvePublicDir(),dashboard=html=>ctx=>ctx.query?.token===void 0||authorized(ctx)?ctx.html(html):void 0;if(publicDir){let assetsDir=join(publicDir,`assets`);existsSync(assetsDir)?http.serveStatic(`${basePath}/assets`,assetsDir):http.serveStatic(basePath,publicDir);let indexHtml=readFileSync(join(publicDir,`index.html`),`utf-8`);http.route(`GET`,basePath,dashboard(indexHtml.replace(`<body`,`<body data-base="${basePath}"`)))}else http.route(`GET`,basePath,dashboard(`<h1>DevTools: public directory not found</h1>`));secret?(log.info(`DevTools mounted at ${basePath} [token: ${secret}]`),log.info(`Access: ${basePath}?token=${secret}`)):log.info(`DevTools mounted at ${basePath} [no guard]`)},onResponse(info){enabled&&recordResponse(info.method,info.route,info.status,info.durationMs)},middleware(){return!enabled||FRAMEWORK_REPORTS_RESPONSES?[]:[{handler:(req,res,next)=>{let start=Date.now();res.on(`finish`,()=>{let matched=req[MATCHED_ROUTE_SLOT];recordResponse(req.method??`GET`,matched?.pattern??matched?.path,res.statusCode,Date.now()-start)}),next()},phase:`beforeGlobal`}]},onRouteMount(controllerClass,mountPath){if(!enabled)return;let collectedRoutes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddleware=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]);for(let route of collectedRoutes){let methodMiddleware=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass.prototype,route.handlerName,[]);routes.push({method:route.method.toUpperCase(),path:`${mountPath}${route.path===`/`?``:route.path}`,controller:controllerClass.name,handler:route.handlerName,middleware:[...classMiddleware.map(m=>m.name||`anonymous`),...methodMiddleware.map(m=>m.name||`anonymous`)],flags:Object.fromEntries(getRouteFlags(controllerClass,route.handlerName)),...uploadInfo(controllerClass,route.handlerName)})}},afterStart({server}){if(enabled){server&&bus?.attachUpgrade(server);for(let peer of getPeerAdapters()){let name=peer?.name;typeof name==`string`&&name!==`DevToolsAdapter`&&(adapterStatuses[name]=`running`)}log.info(`DevTools ready — ${routes.length} routes tracked, ${container?.getRegistrations().length??0} DI bindings, event bus on ${basePath}/_bus`)}},shutdown(){stopErrorWatch?.(),runtimeSampler?.stop(),memoryAnalyzer?.stop(),bus?.close(),adapterStatuses.DevToolsAdapter=`stopped`}}}});export{DevToolsAdapter};
20
15
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["serveStatic"],"sources":["../src/topology.ts","../src/devtools-tabs.ts","../src/bus/server.ts","../src/adapter.ts"],"sourcesContent":["/**\n * Topology aggregator — walks the running KickJS application + DI\n * container and produces a JSON-serialisable {@link TopologySnapshot}.\n *\n * Calls `introspect()` on every plugin and adapter that implements it\n * (architecture.md §23.3); falls back to a minimal `{ protocolVersion,\n * name, kind }` stub for primitives that don't. Per-primitive\n * introspection failures are caught + collected into the snapshot's\n * `errors` field rather than failing the entire endpoint.\n *\n * @module @forinda/kickjs-devtools/topology\n */\n\nimport type { AppAdapter, Container, KickPlugin } from '@forinda/kickjs'\nimport {\n PROTOCOL_VERSION,\n type IntrospectionSnapshot,\n type TopologyContributorEntry,\n type TopologyError,\n type TopologySnapshot,\n type TopologyTokenEntry,\n} from '@forinda/kickjs-devtools-kit'\n\n/** Minimal Application surface the aggregator needs — keeps coupling thin. */\nexport interface TopologyApplicationLike {\n getAdapters(): AppAdapter[]\n getPlugins(): readonly KickPlugin[]\n /**\n * Optional in older Application implementations — when present, returns\n * the union of contributors across adapters/plugins/global with proper\n * source labels. The topology aggregator prefers this over walking\n * `adapter.contributors()` + `plugin.contributors()` directly because\n * the application-level walk preserves source provenance.\n */\n getContributors?(): ReadonlyArray<{\n key: string\n source: 'adapter' | 'plugin' | 'module' | 'global'\n label: string\n dependsOn: readonly string[]\n }>\n}\n\n/** Inputs to {@link collectTopologySnapshot}. */\nexport interface CollectTopologyOptions {\n /** The running KickJS application (or anything that exposes its surface). */\n app: TopologyApplicationLike\n /** The DI container — used to enumerate registered tokens. */\n container: Container\n /**\n * Optional per-call introspect timeout in milliseconds. An adapter\n * whose `introspect()` doesn't settle within the budget gets a stub\n * snapshot + an entry in `errors`. Default: 100ms — keeps the\n * topology endpoint snappy even if one adapter misbehaves.\n */\n introspectTimeoutMs?: number\n}\n\nconst DEFAULT_INTROSPECT_TIMEOUT_MS = 100\n\n/**\n * Collect a {@link TopologySnapshot} for the given application.\n *\n * Async because plugin/adapter `introspect()` may be async; the work\n * is parallelised across all primitives so wall-clock time scales\n * with the slowest introspector, not their sum.\n */\nexport async function collectTopologySnapshot(\n opts: CollectTopologyOptions,\n): Promise<TopologySnapshot> {\n const { app, container, introspectTimeoutMs = DEFAULT_INTROSPECT_TIMEOUT_MS } = opts\n const errors: TopologyError[] = []\n\n const plugins = await Promise.all(\n app.getPlugins().map((p) => snapshotFor(p, 'plugin', introspectTimeoutMs, errors)),\n )\n const adapters = await Promise.all(\n app.getAdapters().map((a) => snapshotFor(a, 'adapter', introspectTimeoutMs, errors)),\n )\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n timestamp: Date.now(),\n plugins,\n adapters,\n contributors: collectContributors(app),\n diTokens: collectTokens(container),\n errors,\n }\n}\n\n/**\n * Coerce one primitive into an {@link IntrospectionSnapshot}. Tries\n * the primitive's own `introspect()` first; falls back to a stub on\n * any of: missing implementation, throw, timeout, or non-object return.\n */\nasync function snapshotFor(\n primitive: AppAdapter | KickPlugin,\n kind: 'plugin' | 'adapter',\n timeoutMs: number,\n errors: TopologyError[],\n): Promise<IntrospectionSnapshot> {\n const name = primitive.name ?? '(unnamed)'\n const stub: IntrospectionSnapshot = {\n protocolVersion: PROTOCOL_VERSION,\n name,\n kind,\n }\n if (typeof primitive.introspect !== 'function') return stub\n\n try {\n const result = await Promise.race([\n Promise.resolve(primitive.introspect()),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`introspect() timed out after ${timeoutMs}ms`)),\n timeoutMs,\n ),\n ),\n ])\n if (result && typeof result === 'object') {\n // Accept whatever the primitive returned; the kit's\n // IntrospectionSnapshot is opt-in typed via the kit, not enforced\n // at this layer (see plugin.ts / adapter.ts comment about avoiding\n // a runtime dep on the kit).\n const snap = result as Partial<IntrospectionSnapshot>\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: snap.name ?? name,\n kind: snap.kind ?? kind,\n version: snap.version,\n state: snap.state,\n tokens: snap.tokens,\n metrics: snap.metrics,\n memoryBytes: snap.memoryBytes,\n }\n }\n return stub\n } catch (err) {\n errors.push({\n name,\n kind,\n message: err instanceof Error ? err.message : String(err),\n })\n return stub\n }\n}\n\n/** Read DI registrations into the topology shape — drops noisy HMR tokens. */\nfunction collectTokens(container: Container): TopologyTokenEntry[] {\n return container\n .getRegistrations()\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n token: r.token,\n scope: r.scope,\n kind: r.kind,\n instantiated: r.instantiated,\n }))\n}\n\n/**\n * Contributor enumeration. Prefers `app.getContributors()` (the\n * Application-level walk that preserves adapter / plugin / global\n * source labels) when present; falls back to walking\n * `adapter.contributors()` + `plugin.contributors()` directly for\n * older Application implementations that don't expose the helper.\n *\n * Module-level contributors are still not surfaced here — module\n * instances aren't retained post-bootstrap. Per-route enumeration\n * lands in a later iteration alongside the route detail panel.\n */\nfunction collectContributors(app: TopologyApplicationLike): TopologyContributorEntry[] {\n const seen = new Map<string, TopologyContributorEntry>()\n\n if (typeof app.getContributors === 'function') {\n for (const c of app.getContributors()) {\n if (seen.has(c.key)) continue\n // Pass `source` through unchanged — the kit's\n // `TopologyContributorSource` union accepts every value the\n // framework's `getContributors()` returns. Earlier versions\n // collapsed `'plugin' | 'global'` → `'adapter'` because the kit\n // type was narrower; that's no longer needed.\n seen.set(c.key, {\n key: c.key,\n source: c.source as TopologyContributorEntry['source'],\n dependsOn: c.dependsOn as string[],\n })\n }\n return [...seen.values()]\n }\n\n // Legacy path — direct walk.\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: TopologyContributorEntry['source'],\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: string; dependsOn?: readonly string[] }\n const key = typeof r.key === 'string' ? r.key : null\n if (!key || seen.has(key)) continue\n seen.set(key, {\n key,\n source,\n dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : [],\n })\n }\n }\n\n for (const plugin of app.getPlugins()) {\n ingest(plugin.contributors?.(), 'adapter')\n }\n for (const adapter of app.getAdapters()) {\n ingest(adapter.contributors?.(), 'adapter')\n }\n\n return [...seen.values()]\n}\n","/**\n * Custom-tab aggregator — collects every plugin/adapter's\n * `devtoolsTabs()` contribution into a single deduped list for the\n * panel's `/_debug/tabs` endpoint.\n *\n * Validation is permissive: anything that doesn't look like a\n * {@link DevtoolsTabDescriptor} is dropped with a console warning\n * rather than throwing — a misconfigured adapter shouldn't break the\n * whole DevTools panel.\n *\n * @module @forinda/kickjs-devtools/devtools-tabs\n */\n\nimport type { DevtoolsTabDescriptor } from '@forinda/kickjs-devtools-kit'\nimport type { TopologyApplicationLike } from './topology'\n\n/** Result of {@link collectDevtoolsTabs}. */\nexport interface DevtoolsTabsResult {\n /** Deduped, validated tabs in registration order. */\n tabs: DevtoolsTabDescriptor[]\n /** Per-source collection errors (drop reason, source name). */\n errors: ReadonlyArray<{ source: string; reason: string }>\n}\n\nconst VALID_VIEW_TYPES = new Set(['iframe', 'launch', 'html'])\n\n/**\n * Walk every plugin + adapter, call `devtoolsTabs?()`, validate each\n * entry, and dedupe by `id`. Last-source-wins on collision is too\n * surprising — first-source-wins + a warning entry instead.\n */\nexport function collectDevtoolsTabs(app: TopologyApplicationLike): DevtoolsTabsResult {\n const tabs: DevtoolsTabDescriptor[] = []\n const seen = new Map<string, string>() // id → source name (for collision warnings)\n const errors: Array<{ source: string; reason: string }> = []\n\n const ingest = (sourceName: string, raw: unknown): void => {\n if (!Array.isArray(raw)) {\n errors.push({ source: sourceName, reason: 'devtoolsTabs() did not return an array' })\n return\n }\n for (const entry of raw) {\n const validation = validateTab(entry)\n if (!validation.ok) {\n errors.push({ source: sourceName, reason: validation.reason })\n continue\n }\n const tab = validation.tab\n const owner = seen.get(tab.id)\n if (owner) {\n errors.push({\n source: sourceName,\n reason: `tab id '${tab.id}' already registered by ${owner} — first-source wins`,\n })\n continue\n }\n seen.set(tab.id, sourceName)\n tabs.push(tab)\n }\n }\n\n for (const plugin of app.getPlugins()) {\n if (typeof plugin.devtoolsTabs !== 'function') continue\n try {\n ingest(plugin.name ?? '(unnamed plugin)', plugin.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: plugin.name ?? '(unnamed plugin)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n for (const adapter of app.getAdapters()) {\n if (typeof adapter.devtoolsTabs !== 'function') continue\n try {\n ingest(adapter.name ?? '(unnamed adapter)', adapter.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: adapter.name ?? '(unnamed adapter)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return { tabs, errors }\n}\n\ninterface ValidationOk {\n ok: true\n tab: DevtoolsTabDescriptor\n}\n\ninterface ValidationFail {\n ok: false\n reason: string\n}\n\n/**\n * Coerce + validate a tab descriptor. Returns the typed object on\n * success; a structured reason on failure. Uses a permissive checker\n * so a partially-correct entry from a third-party adapter doesn't\n * break the whole panel.\n */\nfunction validateTab(raw: unknown): ValidationOk | ValidationFail {\n if (!raw || typeof raw !== 'object') {\n return { ok: false, reason: 'tab entry is not an object' }\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.id !== 'string' || obj.id.length === 0) {\n return { ok: false, reason: 'tab.id must be a non-empty string' }\n }\n if (typeof obj.title !== 'string' || obj.title.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': title must be a non-empty string` }\n }\n const view = obj.view as Record<string, unknown> | undefined\n if (!view || typeof view !== 'object') {\n return { ok: false, reason: `tab '${obj.id}': view object is required` }\n }\n if (typeof view.type !== 'string' || !VALID_VIEW_TYPES.has(view.type)) {\n return {\n ok: false,\n reason: `tab '${obj.id}': view.type must be one of iframe / launch / html`,\n }\n }\n switch (view.type) {\n case 'iframe':\n if (typeof view.src !== 'string' || view.src.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': iframe view requires a non-empty src` }\n }\n break\n case 'html':\n if (typeof view.html !== 'string') {\n return { ok: false, reason: `tab '${obj.id}': html view requires html string` }\n }\n break\n case 'launch':\n if (!Array.isArray(view.actions)) {\n return { ok: false, reason: `tab '${obj.id}': launch view requires actions array` }\n }\n break\n }\n return { ok: true, tab: obj as unknown as DevtoolsTabDescriptor }\n}\n","// Server-side KickEventBus implementation.\n//\n// Wraps the bus core from `@forinda/kickjs-devtools-kit/bus` with a\n// `ws` server bound to a path on the framework's existing\n// `http.Server`. Architecture:\n//\n// server.on('upgrade') ─┐\n// ├──► WebSocketServer.handleUpgrade()\n// │ └─► ws clients: receive emits as JSON\n// bus.emit(type, payload) ─┴──► serialize → fan out to clients +\n// dispatch locally to in-process subs\n//\n// Why piggyback on the framework's http.Server instead of starting a\n// dedicated WS server: the framework already owns the listener, the\n// upgrade event is the canonical hook, and reusing it means devtools\n// inherits whatever TLS / proxy / port config the application provides.\n//\n// Lifecycle:\n// - createServerBus() builds the WebSocketServer in `noServer: true`\n// mode (no listener of its own) and returns the bus + attach/close\n// handles.\n// - attachUpgrade(httpServer) wires server.on('upgrade') so upgrades\n// matching `wsPath` route into the WebSocketServer. Other upgrade\n// paths (kickjs-ws, etc.) ignore us by virtue of path matching.\n// - close() drops every client and detaches from the http server so\n// repeated dev-mode restarts don't leak listener handles.\n//\n// Authentication:\n// - The optional `secret` matches the devtools panel's existing\n// `x-devtools-token` / `?token=` access guard. When set, upgrades\n// without the right token get rejected at HTTP-handshake time —\n// never reaching the bus.\n//\n// Loop avoidance:\n// - Server emits fan out to every connected client. Client-side\n// emits sent UP the socket dispatch into the local core (so\n// server tabs can react) but are NOT re-broadcast to other\n// clients. This keeps the same \"no echo\" contract the browser\n// bus enforces; without it a tab's emit would round-trip through\n// the server and back to itself.\n\nimport type { IncomingMessage } from 'node:http'\nimport type http from 'node:http'\nimport type { Socket } from 'node:net'\n\nimport { createBusCore } from '@forinda/kickjs-devtools-kit/bus'\nimport type { KickDevtoolsEvent, KickEventBus, Unsubscribe } from '@forinda/kickjs-devtools-kit/bus'\nimport { WebSocketServer, type WebSocket } from 'ws'\n\nexport interface ServerBusOptions {\n /** Path the WebSocket upgrade listens on. Default `/_debug/_bus`. */\n wsPath?: string\n /**\n * Optional shared secret. When set, clients must include either\n * `?token=<secret>` on the upgrade URL or an\n * `x-devtools-token: <secret>` header. Unauthorized upgrades return\n * 401 and never reach the bus. Pass `false` (or omit) to disable.\n */\n secret?: string | false\n}\n\ninterface TaggedEnvelope extends KickDevtoolsEvent {\n __kick_origin?: 'local' | 'broadcast' | 'ws'\n}\n\nexport interface ServerBus extends KickEventBus {\n /** Hook into an existing http.Server's `upgrade` event. */\n attachUpgrade(httpServer: http.Server): void\n /** Drop all clients + detach. Idempotent. */\n close(): void\n /** Currently connected client count. Useful for the devtools health card. */\n clientCount(): number\n}\n\nexport function createServerBus(opts: ServerBusOptions = {}): ServerBus {\n const wsPath = opts.wsPath ?? '/_debug/_bus'\n const secret = opts.secret ?? false\n const core = createBusCore()\n const wss = new WebSocketServer({ noServer: true })\n const clients = new Set<WebSocket>()\n let attachedServer: http.Server | null = null\n let upgradeHandler: ((req: IncomingMessage, socket: Socket, head: Buffer) => void) | null = null\n\n wss.on('connection', (ws: WebSocket) => {\n clients.add(ws)\n ws.on('message', (data: Buffer | string) => {\n try {\n const text = typeof data === 'string' ? data : data.toString('utf-8')\n const parsed = JSON.parse(text) as TaggedEnvelope\n if (!parsed || typeof parsed.type !== 'string' || typeof parsed.ts !== 'number') return\n // Dispatch locally only — never echo back to other clients.\n // (Tabs that need cross-tab fan-out use BroadcastChannel; the\n // server is point-to-point per client.)\n core.dispatch({ ...parsed, __kick_origin: 'ws' } as KickDevtoolsEvent)\n } catch {\n // Malformed — drop silently. A misbehaving tab shouldn't\n // crash the server bus.\n }\n })\n ws.on('close', () => {\n clients.delete(ws)\n })\n ws.on('error', () => {\n clients.delete(ws)\n })\n })\n\n const fanOut = (envelope: TaggedEnvelope): void => {\n if (clients.size === 0) return\n const text = JSON.stringify(envelope)\n for (const client of clients) {\n // OPEN === 1 in the ws spec; reusing the import for the type\n // guard keeps this readable without pulling in WebSocket consts.\n if (client.readyState === client.OPEN) {\n try {\n client.send(text)\n } catch {\n // Network error mid-fan-out — clean removal happens via the\n // 'close' / 'error' handlers; nothing to do here.\n }\n }\n }\n }\n\n const checkAuth = (req: IncomingMessage): boolean => {\n if (secret === false) return true\n const header = req.headers['x-devtools-token']\n if (typeof header === 'string' && header === secret) return true\n // Parse query — `req.url` is path + ?query for upgrade requests.\n const url = req.url ?? ''\n const queryIdx = url.indexOf('?')\n if (queryIdx === -1) return false\n const params = new URLSearchParams(url.slice(queryIdx + 1))\n return params.get('token') === secret\n }\n\n const attachUpgrade = (httpServer: http.Server): void => {\n if (attachedServer) return // idempotent\n attachedServer = httpServer\n upgradeHandler = (req, socket, head) => {\n // Path match — ignore upgrades destined for other adapters\n // (kickjs-ws, custom adapters, etc.). They register their own\n // upgrade handlers; ours just no-ops on non-matching URLs.\n const url = req.url ?? ''\n const pathOnly = url.split('?')[0]\n if (pathOnly !== wsPath) return\n\n if (!checkAuth(req)) {\n socket.write('HTTP/1.1 401 Unauthorized\\r\\n\\r\\n')\n socket.destroy()\n return\n }\n\n wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {\n wss.emit('connection', ws, req)\n })\n }\n httpServer.on('upgrade', upgradeHandler)\n }\n\n const close = (): void => {\n if (attachedServer && upgradeHandler) {\n attachedServer.off('upgrade', upgradeHandler)\n }\n attachedServer = null\n upgradeHandler = null\n for (const client of clients) {\n try {\n client.close()\n } catch {\n // ignore\n }\n }\n clients.clear()\n wss.close()\n }\n\n return {\n on(type: string, handler: (payload: unknown) => void): Unsubscribe {\n return core.on(type, handler)\n },\n onAny(handler: (event: KickDevtoolsEvent) => void): Unsubscribe {\n return core.onAny(handler)\n },\n emit(type: string, payload: unknown): void {\n const envelope: TaggedEnvelope = {\n type,\n payload,\n ts: Date.now(),\n __kick_origin: 'local',\n }\n core.dispatch(envelope)\n fanOut(envelope)\n },\n attachUpgrade,\n close,\n clientCount: () => clients.size,\n } as ServerBus\n}\n","import type { Request, Response, NextFunction, RequestHandler } from 'express'\nimport { static as serveStatic } from 'express'\nimport { dirname, join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { createReadStream, existsSync, readFileSync, statSync, unlink } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { writeHeapSnapshot } from 'node:v8'\nimport {\n type AdapterMiddleware,\n type Container,\n METADATA,\n defineAdapter,\n ref,\n computed,\n reactive,\n watch,\n createLogger,\n type Ref,\n type ComputedRef,\n getClassMeta,\n getMethodMeta,\n getRouteFlags,\n} from '@forinda/kickjs'\nimport {\n MemoryAnalyzer,\n PROTOCOL_VERSION,\n RuntimeSampler,\n type IntrospectionSnapshot,\n} from '@forinda/kickjs-devtools-kit'\nimport { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\nimport { collectTopologySnapshot, type TopologyApplicationLike } from './topology'\nimport { collectDevtoolsTabs } from './devtools-tabs'\nimport { createServerBus, type ServerBus } from './bus/server'\n\nconst log = createLogger('DevTools')\n\n/** Route metadata collected during mount */\ninterface RouteInfo {\n method: string\n path: string\n controller: string\n handler: string\n middleware: string[]\n /**\n * Route flags in force, resolved method-over-class. Present so the dashboard\n * can answer \"why is this endpoint not requiring auth\" from the route list\n * itself, rather than by reading the controller.\n */\n flags: Record<string, unknown>\n}\n\n/** Per-route latency stats with percentile tracking */\ninterface RouteStats {\n count: number\n totalMs: number\n minMs: number\n maxMs: number\n /** Ring buffer of last N samples for percentile computation */\n samples: number[]\n}\n\nconst MAX_SAMPLES = 1000\n\n/** Compute a percentile from a sorted array of numbers */\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.ceil(p * sorted.length) - 1\n return sorted[Math.max(0, idx)]\n}\n\n/** Compute p50, p95, p99 from a RouteStats samples buffer */\nfunction computePercentiles(stats: RouteStats): { p50: number; p95: number; p99: number } {\n const sorted = [...stats.samples].toSorted((a, b) => a - b)\n return {\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n }\n}\n\n/**\n * Open an SSE response — sets the headers, flushes them, and disables\n * any compression middleware that may have been registered upstream\n * (compression buffers SSE chunks indefinitely; we need flush-on-write).\n */\nfunction openSseStream(req: Request, res: Response): void {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n res.flushHeaders?.()\n // Defensive: the compression middleware checks this header. Some\n // setups also wrap res.write — calling res.flush after each write\n // is safe even when no compression is in play.\n void req\n}\n\n/** Write a single SSE `data:` event with a JSON payload + double newline. */\nfunction writeSseEvent(res: Response, payload: unknown): void {\n res.write(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\n/**\n * Race a promise against a timeout. Clears the timer when the inner\n * promise wins so we don't leak handles every time a peer responds\n * quickly. Used to bound peer `onHealthCheck()` calls inside the\n * `/_debug/health` handler — one slow peer must not be able to stall\n * the dashboard request.\n */\nfunction raceWithTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)\n })\n return Promise.race([promise, timeout]).finally(() => {\n if (timer) clearTimeout(timer)\n })\n}\n\n/**\n * Per-peer budget for `onHealthCheck()` inside `/_debug/health`.\n * Long enough for a typical DB ping or remote check, short enough that\n * one misbehaving adapter can't stall the dashboard endpoint.\n */\nconst PEER_HEALTHCHECK_TIMEOUT_MS = 1500\n\n/**\n * Module-scoped guard for `POST /_debug/memory/snapshot`. `writeHeapSnapshot()`\n * blocks the event loop for the duration of the capture (multi-second\n * for large heaps); two concurrent captures would compound the pause.\n * The endpoint returns 503 + a hint message when this flag is set so\n * the SPA can surface a \"snapshot already running\" warning rather than\n * silently queueing.\n *\n * Module-scoped (not per-adapter-instance) because writeHeapSnapshot\n * acts on the V8 process — multiple DevToolsAdapter instances would\n * still race at the v8 layer.\n */\nlet snapshotInProgress = false\n\nexport interface DevToolsOptions {\n /** Base path for debug endpoints (default: '/_debug') */\n basePath?: string\n /** Only enable when this is true (default: process.env.NODE_ENV !== 'production') */\n enabled?: boolean\n /** Include environment variables (sanitized) at /_debug/config (default: false) */\n exposeConfig?: boolean\n /** Env var prefixes to expose (default: ['APP_', 'NODE_ENV']). Others are redacted. */\n configPrefixes?: string[]\n /** Callback when error rate exceeds threshold */\n onErrorRateExceeded?: (rate: number) => void\n /** Error rate threshold (default: 0.5 = 50%) */\n errorRateThreshold?: number\n /** Other adapters to discover stats from (e.g., WsAdapter) */\n adapters?: any[]\n\n /**\n * Secret token to guard DevTools access. When set, all requests must\n * include this token as `x-devtools-token` header or `?token=` query param.\n *\n * Auto-generated on startup if not provided. The token is logged to the console.\n * Set to `false` to disable the guard entirely (not recommended).\n *\n * @example\n * ```ts\n * DevToolsAdapter({ secret: getEnv('DEVTOOLS_SECRET') })\n * ```\n */\n secret?: string | false\n\n /**\n * Tuning for the runtime sampler that powers `/_debug/runtime` and\n * the upcoming Memory tab (architecture.md §23). Defaults to\n * 1-second polling with a 60-sample (~1 minute) ring buffer.\n *\n * Set `runtime.enabled = false` to skip starting the sampler — the\n * `/_debug/runtime` endpoint then returns 404 instead of an empty\n * snapshot, signalling deliberate opt-out rather than a startup race.\n */\n runtime?: {\n /** Whether to start the runtime sampler at all. Default: true. */\n enabled?: boolean\n /** Polling interval in milliseconds. Default: 1000. */\n intervalMs?: number\n /** Ring-buffer size — number of past samples retained. Default: 60. */\n bufferSize?: number\n }\n}\n\n/**\n * Public reactive surface exposed by a DevToolsAdapter instance —\n * counters, computed metrics, and the route latency map. Tests and\n * peer adapters consume these directly to drive their own behavior.\n */\nexport interface DevToolsAdapterExtensions {\n /** Total requests received. */\n readonly requestCount: Ref<number>\n /** Total responses with status >= 500. */\n readonly errorCount: Ref<number>\n /** Total responses with status >= 400 and < 500. */\n readonly clientErrorCount: Ref<number>\n /** Server start time. */\n readonly startedAt: Ref<number>\n /** Computed error rate (server errors / total requests). */\n readonly errorRate: ComputedRef<number>\n /** Computed uptime in seconds. */\n readonly uptimeSeconds: ComputedRef<number>\n /** Per-route latency tracking. */\n readonly routeLatency: Record<string, RouteStats>\n /**\n * Tier-1 runtime sampler from `@forinda/kickjs-devtools-kit`. `null`\n * when `runtime.enabled` is `false`. Tests can `latest()` and\n * `history()` directly without going through the HTTP endpoint.\n */\n readonly runtimeSampler: RuntimeSampler | null\n /**\n * Memory analyzer fed by the runtime sampler. `null` when the\n * sampler is disabled. Use `analyzer.health(sampler.history())` to\n * compose a composite memory-health snapshot.\n */\n readonly memoryAnalyzer: MemoryAnalyzer | null\n}\n\n/**\n * DevToolsAdapter — Vue-style reactive introspection for KickJS applications.\n *\n * Exposes debug endpoints powered by reactive state (ref, computed, watch):\n * - `GET /_debug/routes` — all registered routes with middleware\n * - `GET /_debug/container` — DI registry with scopes and instantiation status\n * - `GET /_debug/metrics` — live request/error counts, error rate, uptime\n * - `GET /_debug/health` — deep health check with adapter status\n * - `GET /_debug/config` — sanitized environment variables (opt-in)\n * - `GET /_debug/state` — full reactive state snapshot\n *\n * @example\n * ```ts\n * import { DevToolsAdapter } from '@forinda/kickjs-devtools'\n *\n * bootstrap({\n * modules: [UserModule],\n * adapters: [\n * DevToolsAdapter({\n * enabled: process.env.NODE_ENV !== 'production',\n * exposeConfig: true,\n * configPrefixes: ['APP_', 'DATABASE_'],\n * }),\n * ],\n * })\n * ```\n */\nexport const DevToolsAdapter = defineAdapter<DevToolsOptions, DevToolsAdapterExtensions>({\n name: 'DevToolsAdapter',\n defaults: {\n basePath: '/_debug',\n errorRateThreshold: 0.5,\n exposeConfig: false,\n configPrefixes: ['APP_', 'NODE_ENV'],\n },\n build: (options) => {\n const basePath = options.basePath!\n const enabled = options.enabled ?? process.env.NODE_ENV !== 'production'\n const exposeConfig = options.exposeConfig!\n const configPrefixes = options.configPrefixes!\n const errorRateThreshold = options.errorRateThreshold!\n const peerAdapters = options.adapters ?? []\n\n // Secret token guard\n let secret: string | false\n if (options.secret === false) {\n secret = false\n } else if (options.secret) {\n secret = options.secret\n } else {\n secret = randomBytes(16).toString('hex')\n }\n\n // ── Runtime sampler + memory analyzer (kit) ────────────────────\n // Lazily instantiated so an adopter that disables runtime monitoring\n // doesn't pay the perf_hooks histogram cost. Lifecycle: start in\n // `beforeMount`, stop in `shutdown`.\n const runtimeEnabled = options.runtime?.enabled ?? true\n const runtimeSampler = runtimeEnabled\n ? new RuntimeSampler({\n intervalMs: options.runtime?.intervalMs ?? 1000,\n bufferSize: options.runtime?.bufferSize ?? 60,\n })\n : null\n const memoryAnalyzer = runtimeEnabled ? new MemoryAnalyzer() : null\n\n // ── Server-side event bus ──────────────────────────────────────\n // Lazily resolved in `beforeMount` — when the devtools adapter is\n // rebuilt during HMR, the same `Container` may already hold a bus\n // from a previous mount with live WebSocket clients + in-flight\n // subscriptions. Creating a fresh bus on every rebuild would\n // silently swap the registered instance, leaving plugins that\n // already captured the old reference publishing into a dead bus.\n // Using `container.has(DEVTOOLS_BUS)` to reuse instead keeps event\n // delivery stable across rebuilds.\n //\n // When the devtools adapter is disabled (`enabled === false`) we\n // register a no-op stub instead so adopters who Inject(DEVTOOLS_BUS)\n // under @Optional() get a callable instance rather than undefined.\n let bus: ServerBus | null = null\n\n const ensureBus = (container: Container): ServerBus => {\n if (container.has(DEVTOOLS_BUS)) {\n // The token is typed `KickEventBus` but the registered instance\n // is the wider `ServerBus` (KickEventBus + attachUpgrade /\n // close / clientCount). Explicit generic on resolve avoids the\n // structural-cast — Container.resolve's last overload accepts\n // an explicit T and returns it.\n bus = container.resolve<ServerBus>(DEVTOOLS_BUS)\n return bus\n }\n bus = enabled\n ? createServerBus({\n wsPath: `${basePath}/_bus`,\n secret: secret === false ? false : secret,\n })\n : ({\n on: () => () => {},\n onAny: () => () => {},\n emit: () => {},\n attachUpgrade: () => {},\n close: () => {},\n clientCount: () => 0,\n } as ServerBus)\n container.registerInstance(DEVTOOLS_BUS, bus)\n return bus\n }\n\n // ── Reactive state ─────────────────────────────────────────────\n const requestCount = ref(0)\n const errorCount = ref(0)\n const clientErrorCount = ref(0)\n // App mount timestamp — kept for reference, but uptime is derived from the\n // node process (see below) so it survives HMR rebuilds.\n const startedAt = ref(Date.now())\n const routeLatency = reactive<Record<string, RouteStats>>({})\n\n const errorRate = computed(() =>\n requestCount.value > 0 ? errorCount.value / requestCount.value : 0,\n )\n\n // Uptime is the NODE PROCESS uptime, not \"time since beforeMount\". In dev,\n // `beforeMount` re-runs on every HMR rebuild / SSR re-bootstrap, which used\n // to reset `startedAt` and pin uptime near 0s. `process.uptime()` is\n // monotonic from process start, so it reports the real server uptime across\n // reloads. `tick` makes the computed re-evaluate when the reactive graph\n // refreshes; the value itself comes from the live process clock.\n const uptimeSeconds = computed(() => {\n void startedAt.value // keep the dependency so DevTools polls re-read it\n return Math.floor(process.uptime())\n })\n\n // ── Internal mutable state ─────────────────────────────────────\n let routes: RouteInfo[] = []\n let container: Container | null = null\n let appRef: any = null\n const adapterStatuses: Record<string, string> = {}\n let stopErrorWatch: (() => void) | null = null\n\n // Watch error rate — log warnings when elevated\n if (options.onErrorRateExceeded) {\n const callback = options.onErrorRateExceeded\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n callback(rate)\n }\n })\n } else {\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n log.warn(`Error rate elevated: ${(rate * 100).toFixed(1)}%`)\n }\n })\n }\n\n /**\n * Find the dashboard's public directory. Prefers the new Solid SPA\n * (public/spa/, shipped from PR 4 of §23); falls back to the legacy\n * Vue+Tailwind dashboard (public/devtools/) for environments that\n * haven't run `pnpm --filter @forinda/kickjs-devtools build:spa`.\n */\n const resolvePublicDir = (): string | null => {\n const thisDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(thisDir, '..', 'public', 'spa'), // dist/ -> public/spa\n join(thisDir, '..', '..', 'public', 'spa'), // src/ -> public/spa\n join(thisDir, '..', 'public', 'devtools'), // legacy Vue dashboard\n join(thisDir, '..', '..', 'public', 'devtools'), // legacy from src/\n ]\n for (const dir of candidates) {\n if (existsSync(join(dir, 'index.html'))) return dir\n }\n return null\n }\n\n /**\n * Resolve peer adapters at request time. Prefers live adapters from the\n * Application registry (survives HMR rebuild) and falls back to the\n * constructor-provided refs.\n */\n const getPeerAdapters = (): any[] => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getAdapters === 'function') {\n return kickApp.getAdapters()\n }\n return peerAdapters\n }\n\n /**\n * Active HTTP runtime identity + capabilities (`express` | `fastify` | `h3`),\n * read from the Application via `getActiveRuntime()`. Returns `null` when the\n * framework is older than the getter (graceful for mixed versions). Lets the\n * dashboard show which engine the app is running on.\n */\n const readActiveRuntime = (): {\n name: string\n capabilities: Record<string, boolean>\n } | null => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getActiveRuntime === 'function') {\n try {\n return kickApp.getActiveRuntime()\n } catch {\n return null\n }\n }\n return null\n }\n\n return {\n // ── Extensions (TExtra) ───────────────────────────────────────\n requestCount,\n errorCount,\n clientErrorCount,\n startedAt,\n errorRate,\n uptimeSeconds,\n routeLatency,\n runtimeSampler,\n memoryAnalyzer,\n\n // ── DevTools introspection (architecture.md §23) ─────────────\n // Cheap snapshot — counters + flags only. Anything that requires\n // a container walk or DB hit belongs in the per-endpoint RPCs\n // (`/_debug/container`, `/_debug/graph`), not here.\n introspect(): IntrospectionSnapshot {\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: 'DevToolsAdapter',\n kind: 'adapter',\n state: {\n basePath,\n enabled,\n runtimeEnabled,\n secret: secret === false ? false : 'present',\n },\n metrics: {\n requestCount: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n uptimeSeconds: uptimeSeconds.value,\n routesTracked: routes.length,\n },\n }\n },\n\n // ── Lifecycle ─────────────────────────────────────────────────\n\n beforeMount({ app, http, container: containerArg }) {\n if (!enabled) return\n\n appRef = app\n container = containerArg\n // Lazy resolve — reuses the existing bus when the same\n // container is reused across HMR rebuilds, otherwise creates\n // and registers a fresh instance. See `ensureBus` for why.\n ensureBus(containerArg)\n startedAt.value = Date.now()\n // Clear routes on rebuild/restart to prevent HMR duplication\n routes = []\n adapterStatuses['DevToolsAdapter'] = 'running'\n\n // Start the runtime sampler + memory analyzer here (rather than\n // at construction) so test harnesses that build the adapter but\n // never mount it don't leak interval timers.\n runtimeSampler?.start()\n memoryAnalyzer?.start()\n\n // Register dashboard routes through the engine-agnostic HTTP facade\n // (`ctx.http`) instead of an Express Router, so devtools no longer\n // depends on the raw Express app for mounting. The `router` shim keeps\n // every existing `(req, res)` handler verbatim — `req` / `res` are the\n // engine-native request/response under the default runtime.\n //\n // `use()` scopes the middleware to `basePath` (Express strips the\n // prefix, so the guard still sees router-relative `req.path`). `get` /\n // `post` register the prefixed path; the dashboard root (`'/'`) maps to\n // `basePath` itself, matching the old `router.get('/')` at the mount.\n const joinBase = (p: string): string => (p === '/' ? basePath : `${basePath}${p}`)\n const router = {\n use: (mw: RequestHandler): void => http.use(mw, { path: basePath }),\n get: (path: string, handler: (req: Request, res: Response) => unknown): void =>\n http.route('GET', joinBase(path), (ctx) => handler(ctx.req, ctx.res)),\n post: (path: string, handler: (req: Request, res: Response) => unknown): void =>\n http.route('POST', joinBase(path), (ctx) => handler(ctx.req, ctx.res)),\n }\n\n // ── Access guard — require secret token ──────────────────\n if (secret !== false) {\n const token = secret\n router.use((req: Request, res: Response, next: NextFunction) => {\n const provided = req.headers['x-devtools-token'] ?? req.query?.token\n if (provided === token) return next()\n // Allow the dashboard HTML itself (it will include the token in API calls)\n if (req.path === '/' && req.method === 'GET' && !req.query?.token) {\n return next() // serve dashboard, it handles auth via token\n }\n // Serve static assets for the dashboard (js files)\n if (req.path.endsWith('.js') || req.path.endsWith('.css')) {\n return next()\n }\n res.status(403).json({ error: 'Forbidden — invalid or missing devtools token' })\n })\n }\n\n router.get('/routes', (_req: Request, res: Response) => {\n res.json({ routes })\n })\n\n router.get('/container', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n res.json({ registrations, count: registrations.length })\n })\n\n router.get('/metrics', (_req: Request, res: Response) => {\n // Build latency with percentiles, omitting raw samples from response\n const latency: Record<string, any> = {}\n for (const [key, stats] of Object.entries(routeLatency)) {\n const { samples: _, ...rest } = stats\n latency[key] = { ...rest, ...computePercentiles(stats) }\n }\n res.json({\n requests: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n routeLatency: latency,\n })\n })\n\n router.get('/health', async (_req: Request, res: Response) => {\n const healthy = errorRate.value < errorRateThreshold\n const status = healthy ? 'healthy' : 'degraded'\n\n // Refresh peer statuses from `onHealthCheck()` when present.\n // The static `adapterStatuses` dict (seeded in `afterStart`)\n // proves a peer was mounted; calling `onHealthCheck()` here\n // upgrades that to a live `up`/`down`/`degraded` reading so\n // the Overview > Health card reflects actual adapter state,\n // not just \"registered at boot\".\n //\n // Each peer call is bounded by `PEER_HEALTHCHECK_TIMEOUT_MS` —\n // an adapter whose check hangs (network DB ping, remote\n // service, etc.) must not be able to stall the entire\n // dashboard request. Timed-out peers fall through to the\n // catch arm and are reported as `down`.\n const live: Record<string, string> = { ...adapterStatuses }\n await Promise.all(\n getPeerAdapters().map(async (peer) => {\n if (typeof peer?.onHealthCheck !== 'function') return\n const name: unknown = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') return\n try {\n const result = await raceWithTimeout(\n Promise.resolve(peer.onHealthCheck()),\n PEER_HEALTHCHECK_TIMEOUT_MS,\n `onHealthCheck(${name})`,\n )\n if (result && typeof result.status === 'string') {\n live[name] = result.status\n }\n } catch {\n live[name] = 'down'\n }\n }),\n )\n\n res.status(healthy ? 200 : 503).json({\n status,\n errorRate: errorRate.value,\n uptime: uptimeSeconds.value,\n runtime: readActiveRuntime(),\n adapters: live,\n })\n })\n\n router.get('/state', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n res.json({\n reactive: {\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n },\n routes: routes.length,\n container: container?.getRegistrations().length ?? 0,\n routeLatency,\n ...(wsAdapter ? { ws: wsAdapter.getStats() } : {}),\n })\n })\n\n // ── Tier-1 runtime monitoring (architecture.md §23) ─────────\n // Returns the latest RuntimeSnapshot + a composite MemoryHealth\n // computed from the sampler's ring buffer. Returns 404 when the\n // sampler is disabled so adopters can distinguish \"off\" from\n // \"starting up\".\n router.get('/runtime', (_req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled — set runtime.enabled = true' })\n return\n }\n const latest = runtimeSampler.latest()\n const history = runtimeSampler.history()\n const health = memoryAnalyzer.health(history)\n res.json({\n protocolVersion: PROTOCOL_VERSION,\n // Identity of the process these stats describe — every memory / CPU /\n // event-loop number below is for THIS Node process (the one running\n // your KickJS app), not the OS or any child. Lets the panel label it\n // unambiguously (\"Node v22 · pid 12345 · linux/x64 · engine: fastify\").\n process: {\n nodeVersion: process.version,\n pid: process.pid,\n platform: process.platform,\n arch: process.arch,\n runtime: readActiveRuntime(),\n },\n latest,\n history,\n health,\n })\n })\n\n // ── SSE: live runtime snapshots (architecture.md §23) ───────\n // Pushes the latest RuntimeSnapshot every `intervalMs`. SSE\n // (not WebSocket) avoids the http.Server `upgrade`-event\n // coordination cost — see devtools-flows.md §3 for rationale.\n router.get('/runtime/stream', (req: Request, res: Response) => {\n if (!runtimeSampler) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (snap) writeSseEvent(res, snap)\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── SSE: memory health composite (architecture.md §23) ──────\n router.get('/memory/stream', (req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (!snap) return\n const health = memoryAnalyzer.health(runtimeSampler.history())\n writeSseEvent(res, { snapshot: snap, health })\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── Heap snapshot — Tier 3 monitoring (architecture.md §23) ─\n // POST /_debug/memory/snapshot — captures a V8 heap snapshot\n // and streams the resulting .heapsnapshot file back as\n // application/json with Content-Disposition. Snapshot capture\n // blocks the event loop while writing (multi-second pause for\n // large heaps), so the endpoint enforces single-flight via a\n // module-scoped flag — concurrent calls return 503.\n //\n // The temp file is deleted as soon as the response stream\n // completes (success or error). Worst case if the process\n // dies mid-snapshot is a stranded file in `os.tmpdir()`,\n // which the OS cleans up on next boot.\n router.post('/memory/snapshot', (_req: Request, res: Response) => {\n if (snapshotInProgress) {\n res\n .status(503)\n .json({ error: 'heap snapshot already in progress — wait for it to complete' })\n return\n }\n snapshotInProgress = true\n const startedAt = Date.now()\n const filename = `kickjs-heap-${new Date().toISOString().replace(/[:.]/g, '-')}.heapsnapshot`\n const targetPath = join(tmpdir(), filename)\n\n let written: string\n try {\n // writeHeapSnapshot is synchronous — the event loop is\n // blocked for the duration. There's no async variant in\n // the v8 module today; if one ships, swap here.\n written = writeHeapSnapshot(targetPath)\n } catch (err) {\n snapshotInProgress = false\n log.error({ err }, 'heap snapshot capture failed')\n res\n .status(500)\n .json({ error: 'snapshot capture failed', message: (err as Error).message })\n return\n }\n\n let size = 0\n try {\n size = statSync(written).size\n } catch {\n /* size header is best-effort */\n }\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Heap snapshot captured: ${written} (${(size / 1024 / 1024).toFixed(1)} MiB in ${elapsedMs}ms)`,\n )\n\n res.setHeader('Content-Type', 'application/json')\n res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n if (size > 0) res.setHeader('Content-Length', String(size))\n res.setHeader('X-Snapshot-Capture-Ms', String(elapsedMs))\n\n const cleanup = (): void => {\n unlink(written, (err) => {\n if (err) log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`)\n snapshotInProgress = false\n })\n }\n const stream = createReadStream(written)\n stream.on('end', cleanup)\n stream.on('error', (err) => {\n log.error({ err }, 'heap snapshot stream failed')\n if (!res.headersSent) res.status(500).end()\n cleanup()\n })\n // Defensive: if the client disconnects mid-download, abort\n // the stream + run cleanup so the temp file doesn't linger.\n res.on('close', () => {\n stream.destroy()\n // If the stream already fired 'end', cleanup already ran\n // — the unlink is idempotent enough that running twice\n // just yields ENOENT which we ignore in cleanup.\n })\n stream.pipe(res)\n })\n\n // ── Force GC — Tier 3 monitoring (architecture.md §23) ──────\n // POST /_debug/memory/gc — calls `global.gc()` if Node was\n // started with --expose-gc, returning before/after heap size\n // so the panel can show how much was reclaimed. Useful for\n // confirming \"is this growth real or just delayed GC?\".\n //\n // Returns 412 Precondition Failed (with hint) when the flag\n // wasn't set, so the SPA can show \"Run with --expose-gc to\n // enable this button\" instead of a generic 5xx.\n router.post('/memory/gc', (_req: Request, res: Response) => {\n const gc = (globalThis as { gc?: () => void }).gc\n if (typeof gc !== 'function') {\n res.status(412).json({\n error: 'global.gc unavailable — start Node with --expose-gc to enable this endpoint',\n })\n return\n }\n const before = process.memoryUsage().heapUsed\n const startedAt = Date.now()\n try {\n gc()\n } catch (err) {\n res.status(500).json({\n error: 'forced GC failed',\n message: err instanceof Error ? err.message : String(err),\n })\n return\n }\n const after = process.memoryUsage().heapUsed\n const reclaimedBytes = Math.max(0, before - after)\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Forced GC reclaimed ${(reclaimedBytes / 1024 / 1024).toFixed(2)} MiB in ${elapsedMs}ms`,\n )\n res.json({ before, after, reclaimedBytes, elapsedMs })\n })\n\n // ── Custom-tab discovery (architecture.md §23) ──────────────\n // Walks every plugin/adapter `devtoolsTabs?()` contribution\n // and serves the deduped + validated list. The SPA fetches\n // this once at boot to render dynamic tabs after the four\n // built-ins.\n router.get('/tabs', (_req: Request, res: Response) => {\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res.status(503).json({ error: 'tabs unavailable — application surface not exposed' })\n return\n }\n res.json(collectDevtoolsTabs(kickApp))\n })\n\n // ── Topology RPC (architecture.md §23) ──────────────────────\n // Aggregates plugins + adapters + contributors + DI tokens\n // into one snapshot; calls each primitive's introspect() in\n // parallel with a per-call timeout so a misbehaving adapter\n // can't block the endpoint. Errors are collected, not thrown.\n router.get('/topology', async (_req: Request, res: Response) => {\n if (!container) {\n res.status(503).json({ error: 'topology unavailable — container not bound yet' })\n return\n }\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res\n .status(503)\n .json({ error: 'topology unavailable — application surface not exposed' })\n return\n }\n try {\n const snapshot = await collectTopologySnapshot({ app: kickApp, container })\n res.json(snapshot)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({ error: 'topology collection failed', message })\n }\n })\n\n router.get('/ws', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n if (!wsAdapter) {\n res.json({ enabled: false, message: 'WsAdapter not found' })\n return\n }\n res.json({ enabled: true, ...wsAdapter.getStats() })\n })\n\n router.get('/queues', async (_req: Request, res: Response) => {\n const queueAdapter = getPeerAdapters().find(\n (a) => a.name === 'QueueAdapter' && typeof a.getQueueNames === 'function',\n )\n if (!queueAdapter) {\n res.json({ enabled: false, message: 'QueueAdapter not found' })\n return\n }\n try {\n const names: string[] = queueAdapter.getQueueNames?.() ?? []\n const queues: any[] = []\n for (const name of names) {\n const stats = await queueAdapter.getQueueStats?.(name)\n queues.push({ name, ...stats })\n }\n res.json({ enabled: true, queues })\n } catch {\n res.json({ enabled: true, queues: [], error: 'Failed to fetch queue stats' })\n }\n })\n\n // ── Dependency graph ────────────────────────────────────────\n router.get('/graph', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n const nodes = registrations\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n id: r.token,\n kind: r.kind,\n scope: r.scope,\n resolveCount: r.resolveCount,\n }))\n const nodeIds = new Set(nodes.map((n) => n.id))\n const edges: Array<{ from: string; to: string }> = []\n for (const r of registrations) {\n if (r.token.startsWith('__hmr__')) continue\n for (const dep of r.dependencies) {\n if (nodeIds.has(dep)) {\n edges.push({ from: r.token, to: dep })\n }\n }\n }\n res.json({ nodes, edges })\n })\n\n // ── SSE stream for real-time updates ────────────────────────\n router.get('/stream', (req: Request, res: Response) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n\n const sendMetrics = () => {\n const data = {\n type: 'metrics',\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n }\n res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n }\n sendMetrics()\n\n const unsubContainer = container?.onChange?.((changes) => {\n res.write(\n `data: ${JSON.stringify({ type: 'container', changes, timestamp: Date.now() })}\\n\\n`,\n )\n sendMetrics()\n })\n\n const stopRequestWatch = watch(requestCount, () => sendMetrics())\n const stopErrWatch = watch(errorCount, () => sendMetrics())\n\n const heartbeat = setInterval(() => {\n res.write(`: heartbeat\\n\\n`)\n }, 30000)\n\n req.on('close', () => {\n unsubContainer?.()\n stopRequestWatch()\n stopErrWatch()\n clearInterval(heartbeat)\n })\n })\n\n if (exposeConfig) {\n router.get('/config', (_req: Request, res: Response) => {\n const config: Record<string, string> = {}\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) continue\n const allowed = configPrefixes.some((prefix) => key.startsWith(prefix))\n config[key] = allowed ? value : '[REDACTED]'\n }\n res.json({ config })\n })\n }\n\n // Dashboard UI — Vue + Tailwind from public/devtools directory\n const publicDir = resolvePublicDir()\n if (publicDir) {\n router.use(serveStatic(publicDir))\n\n const indexHtml = readFileSync(join(publicDir, 'index.html'), 'utf-8')\n router.get('/', (_req: Request, res: Response) => {\n const html = indexHtml.replace('<body', `<body data-base=\"${basePath}\"`)\n res.type('html').send(html)\n })\n } else {\n router.get('/', (_req: Request, res: Response) => {\n res.type('html').send('<h1>DevTools: public directory not found</h1>')\n })\n }\n\n // Routes self-register through the facade as they're declared above —\n // no Router to mount here.\n\n if (secret) {\n log.info(`DevTools mounted at ${basePath} [token: ${secret}]`)\n log.info(`Access: ${basePath}?token=${secret}`)\n } else {\n log.info(`DevTools mounted at ${basePath} [no guard]`)\n }\n },\n\n middleware(): AdapterMiddleware[] {\n if (!enabled) return []\n\n return [\n {\n handler: (req: Request, res: Response, next: NextFunction) => {\n const start = Date.now()\n requestCount.value++\n\n res.on('finish', () => {\n if (res.statusCode >= 500) errorCount.value++\n else if (res.statusCode >= 400) clientErrorCount.value++\n\n // Bucket unmatched paths (404s) under a single key. The\n // previous `?? req.path` fallback used the raw URL, which\n // grows the reactive map unboundedly under 404 probing —\n // each random path became its own entry, bloating\n // `/_debug/metrics` and leaking memory.\n const routeKey = req.route?.path\n ? `${req.method} ${req.route.path}`\n : `${req.method} <unmatched>`\n const elapsed = Date.now() - start\n\n if (!routeLatency[routeKey]) {\n routeLatency[routeKey] = {\n count: 0,\n totalMs: 0,\n minMs: Infinity,\n maxMs: 0,\n samples: [],\n }\n }\n const stats = routeLatency[routeKey]\n stats.count++\n stats.totalMs += elapsed\n stats.minMs = Math.min(stats.minMs, elapsed)\n stats.maxMs = Math.max(stats.maxMs, elapsed)\n stats.samples.push(elapsed)\n if (stats.samples.length > MAX_SAMPLES) stats.samples.shift()\n })\n\n next()\n },\n phase: 'beforeGlobal',\n },\n ]\n },\n\n onRouteMount(controllerClass, mountPath) {\n if (!enabled) return\n\n const collectedRoutes = getClassMeta<\n Array<{ method: string; path: string; handlerName: string }>\n >(METADATA.ROUTES, controllerClass, [])\n\n const classMiddleware = getClassMeta<any[]>(METADATA.CLASS_MIDDLEWARES, controllerClass, [])\n\n for (const route of collectedRoutes) {\n const methodMiddleware = getMethodMeta<any[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass.prototype,\n route.handlerName,\n [],\n )\n\n routes.push({\n method: route.method.toUpperCase(),\n path: `${mountPath}${route.path === '/' ? '' : route.path}`,\n controller: controllerClass.name,\n handler: route.handlerName,\n middleware: [\n ...classMiddleware.map((m: any) => m.name || 'anonymous'),\n ...methodMiddleware.map((m: any) => m.name || 'anonymous'),\n ],\n flags: Object.fromEntries(getRouteFlags(controllerClass, route.handlerName)),\n })\n }\n },\n\n afterStart({ server }) {\n if (!enabled) return\n // Wire the bus's WS upgrade to the framework's http.Server.\n // Path-based routing inside attachUpgrade means kickjs-ws or\n // any other adapter sharing the same listener stays\n // unaffected — only `${basePath}/_bus` is claimed.\n if (server) bus?.attachUpgrade(server)\n\n // Seed `/_debug/health.adapters` with every peer the framework\n // mounted alongside us. Before this, only `DevToolsAdapter`\n // appeared in the Overview > Health card because the dict was\n // only ever written in `beforeMount` (self) and `shutdown`\n // (self). Peers with `onHealthCheck` get their live status;\n // anything else is reported as `running` since reaching\n // `afterStart` means the framework already mounted them.\n for (const peer of getPeerAdapters()) {\n const name = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') continue\n adapterStatuses[name] = 'running'\n }\n\n log.info(\n `DevTools ready — ${routes.length} routes tracked, ` +\n `${container?.getRegistrations().length ?? 0} DI bindings, ` +\n `event bus on ${basePath}/_bus`,\n )\n },\n\n shutdown() {\n stopErrorWatch?.()\n runtimeSampler?.stop()\n memoryAnalyzer?.stop()\n bus?.close()\n adapterStatuses['DevToolsAdapter'] = 'stopped'\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;2rBAkEA,eAAsB,wBACpB,KAC2B,CAC3B,GAAM,CAAE,IAAK,UAAW,oBAAsB,KAAkC,KAC1E,OAA0B,CAAC,EAE3B,QAAU,MAAM,QAAQ,IAC5B,IAAI,WAAW,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,SAAU,oBAAqB,MAAM,CAAC,CACnF,EACM,SAAW,MAAM,QAAQ,IAC7B,IAAI,YAAY,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,UAAW,oBAAqB,MAAM,CAAC,CACrF,EAEA,MAAO,CACL,gBAAiB,iBACjB,UAAW,KAAK,IAAI,EACpB,QACA,SACA,aAAc,oBAAoB,GAAG,EACrC,SAAU,cAAc,SAAS,EACjC,MACF,CACF,CAOA,eAAe,YACb,UACA,KACA,UACA,OACgC,CAChC,IAAM,KAAO,UAAU,MAAQ,YACzB,KAA8B,CAClC,gBAAiB,iBACjB,KACA,IACF,EACA,GAAI,OAAO,UAAU,YAAe,WAAY,OAAO,KAEvD,GAAI,CACF,IAAM,OAAS,MAAM,QAAQ,KAAK,CAChC,QAAQ,QAAQ,UAAU,WAAW,CAAC,EACtC,IAAI,SAAgB,EAAG,SACrB,eACQ,OAAW,MAAM,gCAAgC,UAAU,GAAG,CAAC,EACrE,SACF,CACF,CACF,CAAC,EACD,GAAI,QAAU,OAAO,QAAW,SAAU,CAKxC,IAAM,KAAO,OACb,MAAO,CACL,gBAAiB,iBACjB,KAAM,KAAK,MAAQ,KACnB,KAAM,KAAK,MAAQ,KACnB,QAAS,KAAK,QACd,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,QAAS,KAAK,QACd,YAAa,KAAK,WACpB,CACF,CACA,OAAO,IACT,OAAS,IAAK,CAMZ,OALA,OAAO,KAAK,CAC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vC,GAAI,CAAC,QAAS,OAEd,IAAM,gBAAkB,aAEtB,SAAS,OAAQ,gBAAiB,CAAC,CAAC,EAEhC,gBAAkB,aAAoB,SAAS,kBAAmB,gBAAiB,CAAC,CAAC,EAE3F,IAAK,IAAM,SAAS,gBAAiB,CACnC,IAAM,iBAAmB,cACvB,SAAS,mBACT,gBAAgB,UAChB,MAAM,YACN,CAAC,CACH,EAEA,OAAO,KAAK,CACV,OAAQ,MAAM,OAAO,YAAY,EACjC,KAAM,GAAG,YAAY,MAAM,OAAS,IAAM,GAAK,MAAM,OACrD,WAAY,gBAAgB,KAC5B,QAAS,MAAM,YACf,WAAY,CACV,GAAG,gBAAgB,IAAK,GAAW,EAAE,MAAQ,WAAW,EACxD,GAAG,iBAAiB,IAAK,GAAW,EAAE,MAAQ,WAAW,CAC3D,EACA,MAAO,OAAO,YAAY,cAAc,gBAAiB,MAAM,WAAW,CAAC,CAC7E,CAAC,CACH,CACF,EAEA,WAAW,CAAE,QAAU,CAChB,WAKL,CAAI,QAAQ,KAAK,cAAc,MAAM,EASrC,IAAK,IAAM,QAAQ,gBAAgB,EAAG,CACpC,IAAM,KAAO,MAAM,KACf,OAAO,MAAS,UAAY,OAAS,oBACzC,gBAAgB,MAAQ,UAC1B,CAEA,IAAI,KACF,oBAAoB,OAAO,OAAO,mBAC7B,WAAW,iBAAiB,CAAC,CAAC,QAAU,EAAE,6BAC7B,SAAS,MAC7B,CAnBqC,CAoBvC,EAEA,UAAW,CACT,iBAAiB,EACjB,gBAAgB,KAAK,EACrB,gBAAgB,KAAK,EACrB,KAAK,MAAM,EACX,gBAAgB,gBAAqB,SACvC,CACF,CACF,CACF,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/topology.ts","../src/devtools-tabs.ts","../src/source-locator.ts","../src/bus/server.ts","../src/adapter.ts"],"sourcesContent":["/**\n * Topology aggregator — walks the running KickJS application + DI\n * container and produces a JSON-serialisable {@link TopologySnapshot}.\n *\n * Calls `introspect()` on every plugin and adapter that implements it\n * (architecture.md §23.3); falls back to a minimal `{ protocolVersion,\n * name, kind }` stub for primitives that don't. Per-primitive\n * introspection failures are caught + collected into the snapshot's\n * `errors` field rather than failing the entire endpoint.\n *\n * @module @forinda/kickjs-devtools/topology\n */\n\nimport type { AppAdapter, Container, KickPlugin } from '@forinda/kickjs'\nimport {\n PROTOCOL_VERSION,\n type IntrospectionSnapshot,\n type TopologyContributorEntry,\n type TopologyError,\n type TopologySnapshot,\n type TopologyTokenEntry,\n} from '@forinda/kickjs-devtools-kit'\n\n/** Minimal Application surface the aggregator needs — keeps coupling thin. */\nexport interface TopologyApplicationLike {\n getAdapters(): AppAdapter[]\n getPlugins(): readonly KickPlugin[]\n /**\n * Optional in older Application implementations — when present, returns\n * the union of contributors across adapters/plugins/global with proper\n * source labels. The topology aggregator prefers this over walking\n * `adapter.contributors()` + `plugin.contributors()` directly because\n * the application-level walk preserves source provenance.\n */\n getContributors?(): ReadonlyArray<{\n key: string\n source: 'adapter' | 'plugin' | 'module' | 'global'\n label: string\n dependsOn: readonly string[]\n }>\n}\n\n/** Inputs to {@link collectTopologySnapshot}. */\nexport interface CollectTopologyOptions {\n /** The running KickJS application (or anything that exposes its surface). */\n app: TopologyApplicationLike\n /** The DI container — used to enumerate registered tokens. */\n container: Container\n /**\n * Optional per-call introspect timeout in milliseconds. An adapter\n * whose `introspect()` doesn't settle within the budget gets a stub\n * snapshot + an entry in `errors`. Default: 100ms — keeps the\n * topology endpoint snappy even if one adapter misbehaves.\n */\n introspectTimeoutMs?: number\n}\n\nconst DEFAULT_INTROSPECT_TIMEOUT_MS = 100\n\n/**\n * Collect a {@link TopologySnapshot} for the given application.\n *\n * Async because plugin/adapter `introspect()` may be async; the work\n * is parallelised across all primitives so wall-clock time scales\n * with the slowest introspector, not their sum.\n */\nexport async function collectTopologySnapshot(\n opts: CollectTopologyOptions,\n): Promise<TopologySnapshot> {\n const { app, container, introspectTimeoutMs = DEFAULT_INTROSPECT_TIMEOUT_MS } = opts\n const errors: TopologyError[] = []\n\n const plugins = await Promise.all(\n app.getPlugins().map((p) => snapshotFor(p, 'plugin', introspectTimeoutMs, errors)),\n )\n const adapters = await Promise.all(\n app.getAdapters().map((a) => snapshotFor(a, 'adapter', introspectTimeoutMs, errors)),\n )\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n timestamp: Date.now(),\n plugins,\n adapters,\n contributors: collectContributors(app),\n diTokens: collectTokens(container),\n errors,\n }\n}\n\n/**\n * Coerce one primitive into an {@link IntrospectionSnapshot}. Tries\n * the primitive's own `introspect()` first; falls back to a stub on\n * any of: missing implementation, throw, timeout, or non-object return.\n */\nasync function snapshotFor(\n primitive: AppAdapter | KickPlugin,\n kind: 'plugin' | 'adapter',\n timeoutMs: number,\n errors: TopologyError[],\n): Promise<IntrospectionSnapshot> {\n const name = primitive.name ?? '(unnamed)'\n const stub: IntrospectionSnapshot = {\n protocolVersion: PROTOCOL_VERSION,\n name,\n kind,\n }\n if (typeof primitive.introspect !== 'function') return stub\n\n try {\n const result = await Promise.race([\n Promise.resolve(primitive.introspect()),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`introspect() timed out after ${timeoutMs}ms`)),\n timeoutMs,\n ),\n ),\n ])\n if (result && typeof result === 'object') {\n // Accept whatever the primitive returned; the kit's\n // IntrospectionSnapshot is opt-in typed via the kit, not enforced\n // at this layer (see plugin.ts / adapter.ts comment about avoiding\n // a runtime dep on the kit).\n const snap = result as Partial<IntrospectionSnapshot>\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: snap.name ?? name,\n kind: snap.kind ?? kind,\n version: snap.version,\n state: snap.state,\n tokens: snap.tokens,\n metrics: snap.metrics,\n memoryBytes: snap.memoryBytes,\n }\n }\n return stub\n } catch (err) {\n errors.push({\n name,\n kind,\n message: err instanceof Error ? err.message : String(err),\n })\n return stub\n }\n}\n\n/** Read DI registrations into the topology shape — drops noisy HMR tokens. */\nfunction collectTokens(container: Container): TopologyTokenEntry[] {\n return container\n .getRegistrations()\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n token: r.token,\n scope: r.scope,\n kind: r.kind,\n instantiated: r.instantiated,\n }))\n}\n\n/**\n * Contributor enumeration. Prefers `app.getContributors()` (the\n * Application-level walk that preserves adapter / plugin / global\n * source labels) when present; falls back to walking\n * `adapter.contributors()` + `plugin.contributors()` directly for\n * older Application implementations that don't expose the helper.\n *\n * Module-level contributors are still not surfaced here — module\n * instances aren't retained post-bootstrap. Per-route enumeration\n * lands in a later iteration alongside the route detail panel.\n */\nfunction collectContributors(app: TopologyApplicationLike): TopologyContributorEntry[] {\n const seen = new Map<string, TopologyContributorEntry>()\n\n if (typeof app.getContributors === 'function') {\n for (const c of app.getContributors()) {\n if (seen.has(c.key)) continue\n // Pass `source` through unchanged — the kit's\n // `TopologyContributorSource` union accepts every value the\n // framework's `getContributors()` returns. Earlier versions\n // collapsed `'plugin' | 'global'` → `'adapter'` because the kit\n // type was narrower; that's no longer needed.\n seen.set(c.key, {\n key: c.key,\n source: c.source as TopologyContributorEntry['source'],\n dependsOn: c.dependsOn as string[],\n })\n }\n return [...seen.values()]\n }\n\n // Legacy path — direct walk.\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: TopologyContributorEntry['source'],\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: string; dependsOn?: readonly string[] }\n const key = typeof r.key === 'string' ? r.key : null\n if (!key || seen.has(key)) continue\n seen.set(key, {\n key,\n source,\n dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : [],\n })\n }\n }\n\n for (const plugin of app.getPlugins()) {\n ingest(plugin.contributors?.(), 'adapter')\n }\n for (const adapter of app.getAdapters()) {\n ingest(adapter.contributors?.(), 'adapter')\n }\n\n return [...seen.values()]\n}\n","/**\n * Custom-tab aggregator — collects every plugin/adapter's\n * `devtoolsTabs()` contribution into a single deduped list for the\n * panel's `/_debug/tabs` endpoint.\n *\n * Validation is permissive: anything that doesn't look like a\n * {@link DevtoolsTabDescriptor} is dropped with a console warning\n * rather than throwing — a misconfigured adapter shouldn't break the\n * whole DevTools panel.\n *\n * @module @forinda/kickjs-devtools/devtools-tabs\n */\n\nimport type { DevtoolsTabDescriptor } from '@forinda/kickjs-devtools-kit'\nimport type { TopologyApplicationLike } from './topology'\n\n/** Result of {@link collectDevtoolsTabs}. */\nexport interface DevtoolsTabsResult {\n /** Deduped, validated tabs in registration order. */\n tabs: DevtoolsTabDescriptor[]\n /** Per-source collection errors (drop reason, source name). */\n errors: ReadonlyArray<{ source: string; reason: string }>\n}\n\nconst VALID_VIEW_TYPES = new Set(['iframe', 'launch', 'html'])\n\n/**\n * Walk every plugin + adapter, call `devtoolsTabs?()`, validate each\n * entry, and dedupe by `id`. Last-source-wins on collision is too\n * surprising — first-source-wins + a warning entry instead.\n */\nexport function collectDevtoolsTabs(app: TopologyApplicationLike): DevtoolsTabsResult {\n const tabs: DevtoolsTabDescriptor[] = []\n const seen = new Map<string, string>() // id → source name (for collision warnings)\n const errors: Array<{ source: string; reason: string }> = []\n\n const ingest = (sourceName: string, raw: unknown): void => {\n if (!Array.isArray(raw)) {\n errors.push({ source: sourceName, reason: 'devtoolsTabs() did not return an array' })\n return\n }\n for (const entry of raw) {\n const validation = validateTab(entry)\n if (!validation.ok) {\n errors.push({ source: sourceName, reason: validation.reason })\n continue\n }\n const tab = validation.tab\n const owner = seen.get(tab.id)\n if (owner) {\n errors.push({\n source: sourceName,\n reason: `tab id '${tab.id}' already registered by ${owner} — first-source wins`,\n })\n continue\n }\n seen.set(tab.id, sourceName)\n tabs.push(tab)\n }\n }\n\n for (const plugin of app.getPlugins()) {\n if (typeof plugin.devtoolsTabs !== 'function') continue\n try {\n ingest(plugin.name ?? '(unnamed plugin)', plugin.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: plugin.name ?? '(unnamed plugin)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n for (const adapter of app.getAdapters()) {\n if (typeof adapter.devtoolsTabs !== 'function') continue\n try {\n ingest(adapter.name ?? '(unnamed adapter)', adapter.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: adapter.name ?? '(unnamed adapter)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return { tabs, errors }\n}\n\ninterface ValidationOk {\n ok: true\n tab: DevtoolsTabDescriptor\n}\n\ninterface ValidationFail {\n ok: false\n reason: string\n}\n\n/**\n * Coerce + validate a tab descriptor. Returns the typed object on\n * success; a structured reason on failure. Uses a permissive checker\n * so a partially-correct entry from a third-party adapter doesn't\n * break the whole panel.\n */\nfunction validateTab(raw: unknown): ValidationOk | ValidationFail {\n if (!raw || typeof raw !== 'object') {\n return { ok: false, reason: 'tab entry is not an object' }\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.id !== 'string' || obj.id.length === 0) {\n return { ok: false, reason: 'tab.id must be a non-empty string' }\n }\n if (typeof obj.title !== 'string' || obj.title.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': title must be a non-empty string` }\n }\n const view = obj.view as Record<string, unknown> | undefined\n if (!view || typeof view !== 'object') {\n return { ok: false, reason: `tab '${obj.id}': view object is required` }\n }\n if (typeof view.type !== 'string' || !VALID_VIEW_TYPES.has(view.type)) {\n return {\n ok: false,\n reason: `tab '${obj.id}': view.type must be one of iframe / launch / html`,\n }\n }\n switch (view.type) {\n case 'iframe':\n if (typeof view.src !== 'string' || view.src.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': iframe view requires a non-empty src` }\n }\n break\n case 'html':\n if (typeof view.html !== 'string') {\n return { ok: false, reason: `tab '${obj.id}': html view requires html string` }\n }\n break\n case 'launch':\n if (!Array.isArray(view.actions)) {\n return { ok: false, reason: `tab '${obj.id}': launch view requires actions array` }\n }\n break\n }\n return { ok: true, tab: obj as unknown as DevtoolsTabDescriptor }\n}\n","/**\n * Find a controller method in the project's source — what \"open handler in\n * editor\" needs. The running app knows the class and method names but not the\n * file (the dev server may have transformed it), so this reads `src/` for the\n * class declaration, then the method inside it.\n *\n * Read on each lookup rather than cached: it runs on a click, in development,\n * and files move under HMR.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, relative, sep } from 'node:path'\n\nexport interface HandlerSource {\n /** Absolute path. */\n file: string\n /** Path relative to the project root, `/`-separated — for mapping into another checkout. */\n relative: string\n /** 1-based line of the method (or of the class, when the method isn't found). */\n line: number\n}\n\nconst escape = (name: string) => name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/** 1-based line of the handler inside `controller`, or `undefined` when the class isn't declared here. */\nexport function findHandlerLine(\n source: string,\n controller: string,\n handler: string,\n): number | undefined {\n const cls = new RegExp(`\\\\bclass\\\\s+${escape(controller)}\\\\b`).exec(source)\n if (!cls) return undefined\n const lineAt = (offset: number) => source.slice(0, offset).split('\\n').length\n // Only this class's body: up to the next top-level class declaration, so a\n // same-named method of a later class is never picked.\n const start = cls.index + cls[0].length\n const rest = source.slice(start)\n const next = rest.search(/^(?:export\\s+)?(?:default\\s+)?(?:abstract\\s+)?class\\s/m)\n const body = next === -1 ? rest : rest.slice(0, next)\n const method = new RegExp(\n `^[ \\\\t]*(?:(?:public|private|protected|static|async|override)\\\\s+)*${escape(handler)}\\\\s*[(<]`,\n 'm',\n ).exec(body)\n return lineAt(method ? start + method.index + method[0].search(/\\S/) : cls.index)\n}\n\n/** Locate `controller.handler` under `<root>/src` (or `<root>` when there is no `src/`). */\nexport function locateHandler(\n root: string,\n controller: string,\n handler: string,\n): HandlerSource | undefined {\n const dir = existsSync(join(root, 'src')) ? join(root, 'src') : root\n const files = readdirSync(dir, { recursive: true, encoding: 'utf-8' }).filter(\n (f) =>\n /\\.[mc]?tsx?$/.test(f) &&\n !/\\.d\\.[mc]?ts$/.test(f) &&\n !f.split(sep).includes('node_modules') &&\n !f.split(sep).includes('dist'),\n )\n for (const f of files) {\n const file = join(dir, f)\n let source: string\n try {\n source = readFileSync(file, 'utf-8')\n } catch {\n continue\n }\n if (!source.includes(controller)) continue\n const line = findHandlerLine(source, controller, handler)\n if (line !== undefined) {\n return { file, relative: relative(root, file).split(sep).join('/'), line }\n }\n }\n return undefined\n}\n","// Server-side KickEventBus implementation.\n//\n// Wraps the bus core from `@forinda/kickjs-devtools-kit/bus` with a\n// `ws` server bound to a path on the framework's existing\n// `http.Server`. Architecture:\n//\n// server.on('upgrade') ─┐\n// ├──► WebSocketServer.handleUpgrade()\n// │ └─► ws clients: receive emits as JSON\n// bus.emit(type, payload) ─┴──► serialize → fan out to clients +\n// dispatch locally to in-process subs\n//\n// Why piggyback on the framework's http.Server instead of starting a\n// dedicated WS server: the framework already owns the listener, the\n// upgrade event is the canonical hook, and reusing it means devtools\n// inherits whatever TLS / proxy / port config the application provides.\n//\n// Lifecycle:\n// - createServerBus() builds the WebSocketServer in `noServer: true`\n// mode (no listener of its own) and returns the bus + attach/close\n// handles.\n// - attachUpgrade(httpServer) wires server.on('upgrade') so upgrades\n// matching `wsPath` route into the WebSocketServer. Other upgrade\n// paths (kickjs-ws, etc.) ignore us by virtue of path matching.\n// - close() drops every client and detaches from the http server so\n// repeated dev-mode restarts don't leak listener handles.\n//\n// Authentication:\n// - The optional `secret` matches the devtools panel's existing\n// `x-devtools-token` / `?token=` access guard. When set, upgrades\n// without the right token get rejected at HTTP-handshake time —\n// never reaching the bus.\n//\n// Loop avoidance:\n// - Server emits fan out to every connected client. Client-side\n// emits sent UP the socket dispatch into the local core (so\n// server tabs can react) but are NOT re-broadcast to other\n// clients. This keeps the same \"no echo\" contract the browser\n// bus enforces; without it a tab's emit would round-trip through\n// the server and back to itself.\n\nimport type { IncomingMessage } from 'node:http'\nimport type { KickServer } from '@forinda/kickjs'\nimport type { Socket } from 'node:net'\n\nimport { createBusCore } from '@forinda/kickjs-devtools-kit/bus'\nimport type { KickDevtoolsEvent, KickEventBus, Unsubscribe } from '@forinda/kickjs-devtools-kit/bus'\nimport { WebSocketServer, type WebSocket } from 'ws'\n\nexport interface ServerBusOptions {\n /** Path the WebSocket upgrade listens on. Default `/_debug/_bus`. */\n wsPath?: string\n /**\n * Optional shared secret. When set, clients must include either\n * `?token=<secret>` on the upgrade URL or an\n * `x-devtools-token: <secret>` header. Unauthorized upgrades return\n * 401 and never reach the bus. Pass `false` (or omit) to disable.\n */\n secret?: string | false\n}\n\ninterface TaggedEnvelope extends KickDevtoolsEvent {\n __kick_origin?: 'local' | 'broadcast' | 'ws'\n}\n\nexport interface ServerBus extends KickEventBus {\n /**\n * Hook into the app server's `upgrade` event — `http`, `https`, or HTTP/2\n * with HTTP/1.1 fallback all emit it for WebSocket handshakes.\n */\n attachUpgrade(httpServer: KickServer): void\n /** Drop all clients + detach. Idempotent. */\n close(): void\n /** Currently connected client count. Useful for the devtools health card. */\n clientCount(): number\n}\n\nexport function createServerBus(opts: ServerBusOptions = {}): ServerBus {\n const wsPath = opts.wsPath ?? '/_debug/_bus'\n const secret = opts.secret ?? false\n const core = createBusCore()\n const wss = new WebSocketServer({ noServer: true })\n const clients = new Set<WebSocket>()\n let attachedServer: KickServer | null = null\n let upgradeHandler: ((req: IncomingMessage, socket: Socket, head: Buffer) => void) | null = null\n\n wss.on('connection', (ws: WebSocket) => {\n clients.add(ws)\n ws.on('message', (data: Buffer | string) => {\n try {\n const text = typeof data === 'string' ? data : data.toString('utf-8')\n const parsed = JSON.parse(text) as TaggedEnvelope\n if (!parsed || typeof parsed.type !== 'string' || typeof parsed.ts !== 'number') return\n // Dispatch locally only — never echo back to other clients.\n // (Tabs that need cross-tab fan-out use BroadcastChannel; the\n // server is point-to-point per client.)\n core.dispatch({ ...parsed, __kick_origin: 'ws' } as KickDevtoolsEvent)\n } catch {\n // Malformed — drop silently. A misbehaving tab shouldn't\n // crash the server bus.\n }\n })\n ws.on('close', () => {\n clients.delete(ws)\n })\n ws.on('error', () => {\n clients.delete(ws)\n })\n })\n\n const fanOut = (envelope: TaggedEnvelope): void => {\n if (clients.size === 0) return\n const text = JSON.stringify(envelope)\n for (const client of clients) {\n // OPEN === 1 in the ws spec; reusing the import for the type\n // guard keeps this readable without pulling in WebSocket consts.\n if (client.readyState === client.OPEN) {\n try {\n client.send(text)\n } catch {\n // Network error mid-fan-out — clean removal happens via the\n // 'close' / 'error' handlers; nothing to do here.\n }\n }\n }\n }\n\n const checkAuth = (req: IncomingMessage): boolean => {\n if (secret === false) return true\n const header = req.headers['x-devtools-token']\n if (typeof header === 'string' && header === secret) return true\n // Parse query — `req.url` is path + ?query for upgrade requests.\n const url = req.url ?? ''\n const queryIdx = url.indexOf('?')\n if (queryIdx === -1) return false\n const params = new URLSearchParams(url.slice(queryIdx + 1))\n return params.get('token') === secret\n }\n\n const attachUpgrade = (httpServer: KickServer): void => {\n if (attachedServer) return // idempotent\n attachedServer = httpServer\n upgradeHandler = (req, socket, head) => {\n // Path match — ignore upgrades destined for other adapters\n // (kickjs-ws, custom adapters, etc.). They register their own\n // upgrade handlers; ours just no-ops on non-matching URLs.\n const url = req.url ?? ''\n const pathOnly = url.split('?')[0]\n if (pathOnly !== wsPath) return\n\n if (!checkAuth(req)) {\n socket.write('HTTP/1.1 401 Unauthorized\\r\\n\\r\\n')\n socket.destroy()\n return\n }\n\n wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {\n wss.emit('connection', ws, req)\n })\n }\n httpServer.on('upgrade', upgradeHandler)\n }\n\n const close = (): void => {\n if (attachedServer && upgradeHandler) {\n attachedServer.off('upgrade', upgradeHandler)\n }\n attachedServer = null\n upgradeHandler = null\n for (const client of clients) {\n try {\n client.close()\n } catch {\n // ignore\n }\n }\n clients.clear()\n wss.close()\n }\n\n return {\n on(type: string, handler: (payload: unknown) => void): Unsubscribe {\n return core.on(type, handler)\n },\n onAny(handler: (event: KickDevtoolsEvent) => void): Unsubscribe {\n return core.onAny(handler)\n },\n emit(type: string, payload: unknown): void {\n const envelope: TaggedEnvelope = {\n type,\n payload,\n ts: Date.now(),\n __kick_origin: 'local',\n }\n core.dispatch(envelope)\n fanOut(envelope)\n },\n attachUpgrade,\n close,\n clientCount: () => clients.size,\n } as ServerBus\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { dirname, join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { createReadStream, existsSync, readFileSync, statSync, unlink } from 'node:fs'\nimport { Readable } from 'node:stream'\nimport { randomBytes } from 'node:crypto'\nimport { writeHeapSnapshot } from 'node:v8'\nimport {\n type AdapterMiddleware,\n type Container,\n METADATA,\n defineAdapter,\n ref,\n computed,\n reactive,\n watch,\n createLogger,\n type Ref,\n type ComputedRef,\n getClassMeta,\n getMethodMeta,\n getRouteFlags,\n type MatchedRoute,\n type RequestContext,\n} from '@forinda/kickjs'\nimport * as kick from '@forinda/kickjs'\nimport {\n MemoryAnalyzer,\n PROTOCOL_VERSION,\n RuntimeSampler,\n type IntrospectionSnapshot,\n} from '@forinda/kickjs-devtools-kit'\nimport { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\nimport { collectTopologySnapshot, type TopologyApplicationLike } from './topology'\nimport { collectDevtoolsTabs } from './devtools-tabs'\nimport { locateHandler } from './source-locator'\nimport { createServerBus, type ServerBus } from './bus/server'\n\nconst log = createLogger('DevTools')\n\n/** The serialisable part of a handler's `@FileUpload` config, if it has one. */\nfunction uploadInfo(controllerClass: any, handlerName: string): Pick<RouteInfo, 'upload'> {\n const config = getMethodMeta<\n { mode: 'single' | 'array' | 'none'; fieldName?: string; maxCount?: number } | undefined\n >(METADATA.FILE_UPLOAD, controllerClass, handlerName, undefined)\n if (!config) return {}\n const { mode, fieldName, maxCount } = config\n return {\n upload: { mode, ...(fieldName ? { fieldName } : {}), ...(maxCount ? { maxCount } : {}) },\n }\n}\n\n/** Route metadata collected during mount */\ninterface RouteInfo {\n method: string\n path: string\n controller: string\n handler: string\n middleware: string[]\n /**\n * Route flags in force, resolved method-over-class. Present so the dashboard\n * can answer \"why is this endpoint not requiring auth\" from the route list\n * itself, rather than by reading the controller.\n */\n flags: Record<string, unknown>\n /**\n * `@FileUpload` config, when the handler declares one — the dashboard's API\n * runner starts such routes in multipart mode with this field. Only the\n * plain fields: `allowedTypes` may be a function and isn't serialisable.\n */\n upload?: { mode: 'single' | 'array' | 'none'; fieldName?: string; maxCount?: number }\n}\n\n/** Per-route latency stats with percentile tracking */\ninterface RouteStats {\n count: number\n totalMs: number\n minMs: number\n maxMs: number\n /** Ring buffer of last N samples for percentile computation */\n samples: number[]\n}\n\nconst MAX_SAMPLES = 1000\n\n/**\n * Where every runtime publishes the matched route on the raw request — the\n * same `Symbol.for` slot `ctx.route` reads in `@forinda/kickjs`. Registry\n * symbol, so it is shared across module copies.\n */\nconst MATCHED_ROUTE_SLOT = Symbol.for('kick.route')\n\n/**\n * Whether the installed `@forinda/kickjs` reports every response to adapter\n * `onResponse` hooks. When it does, the dashboard's counters are fed from\n * there; on older releases (still supported peers) the adapter falls back to\n * its own middleware. Looked up, not imported by name, so older releases load.\n */\nconst FRAMEWORK_REPORTS_RESPONSES =\n typeof (kick as { reportResponse?: unknown }).reportResponse === 'function'\n\n/** Compute a percentile from a sorted array of numbers */\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.ceil(p * sorted.length) - 1\n return sorted[Math.max(0, idx)]\n}\n\n/** Compute p50, p95, p99 from a RouteStats samples buffer */\nfunction computePercentiles(stats: RouteStats): { p50: number; p95: number; p99: number } {\n const sorted = [...stats.samples].toSorted((a, b) => a - b)\n return {\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n }\n}\n\n/**\n * Race a promise against a timeout. Clears the timer when the inner\n * promise wins so we don't leak handles every time a peer responds\n * quickly. Used to bound peer `onHealthCheck()` calls inside the\n * `/_debug/health` handler — one slow peer must not be able to stall\n * the dashboard request.\n */\nfunction raceWithTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)\n })\n return Promise.race([promise, timeout]).finally(() => {\n if (timer) clearTimeout(timer)\n })\n}\n\n/**\n * Per-peer budget for `onHealthCheck()` inside `/_debug/health`.\n * Long enough for a typical DB ping or remote check, short enough that\n * one misbehaving adapter can't stall the dashboard endpoint.\n */\nconst PEER_HEALTHCHECK_TIMEOUT_MS = 1500\n\n/**\n * Module-scoped guard for `POST /_debug/memory/snapshot`. `writeHeapSnapshot()`\n * blocks the event loop for the duration of the capture (multi-second\n * for large heaps); two concurrent captures would compound the pause.\n * The endpoint returns 503 + a hint message when this flag is set so\n * the SPA can surface a \"snapshot already running\" warning rather than\n * silently queueing.\n *\n * Module-scoped (not per-adapter-instance) because writeHeapSnapshot\n * acts on the V8 process — multiple DevToolsAdapter instances would\n * still race at the v8 layer.\n */\nlet snapshotInProgress = false\n\nexport interface DevToolsOptions {\n /** Base path for debug endpoints (default: '/_debug') */\n basePath?: string\n /** Only enable when this is true (default: process.env.NODE_ENV !== 'production') */\n enabled?: boolean\n /** Include environment variables (sanitized) at /_debug/config (default: false) */\n exposeConfig?: boolean\n /** Env var prefixes to expose (default: ['APP_', 'NODE_ENV']). Others are redacted. */\n configPrefixes?: string[]\n /** Callback when error rate exceeds threshold */\n onErrorRateExceeded?: (rate: number) => void\n /** Error rate threshold (default: 0.5 = 50%) */\n errorRateThreshold?: number\n /** Other adapters to discover stats from (e.g., WsAdapter) */\n adapters?: any[]\n\n /**\n * Secret token to guard DevTools access. When set, all requests must\n * include this token as `x-devtools-token` header or `?token=` query param.\n *\n * Auto-generated on startup if not provided. The token is logged to the console.\n * Set to `false` to disable the guard entirely (not recommended).\n *\n * @example\n * ```ts\n * DevToolsAdapter({ secret: getEnv('DEVTOOLS_SECRET') })\n * ```\n */\n secret?: string | false\n\n /**\n * Tuning for the runtime sampler that powers `/_debug/runtime` and\n * the upcoming Memory tab (architecture.md §23). Defaults to\n * 1-second polling with a 60-sample (~1 minute) ring buffer.\n *\n * Set `runtime.enabled = false` to skip starting the sampler — the\n * `/_debug/runtime` endpoint then returns 404 instead of an empty\n * snapshot, signalling deliberate opt-out rather than a startup race.\n */\n runtime?: {\n /** Whether to start the runtime sampler at all. Default: true. */\n enabled?: boolean\n /** Polling interval in milliseconds. Default: 1000. */\n intervalMs?: number\n /** Ring-buffer size — number of past samples retained. Default: 60. */\n bufferSize?: number\n }\n}\n\n/**\n * Public reactive surface exposed by a DevToolsAdapter instance —\n * counters, computed metrics, and the route latency map. Tests and\n * peer adapters consume these directly to drive their own behavior.\n */\nexport interface DevToolsAdapterExtensions {\n /** Total requests received. */\n readonly requestCount: Ref<number>\n /** Total responses with status >= 500. */\n readonly errorCount: Ref<number>\n /** Total responses with status >= 400 and < 500. */\n readonly clientErrorCount: Ref<number>\n /** Server start time. */\n readonly startedAt: Ref<number>\n /** Computed error rate (server errors / total requests). */\n readonly errorRate: ComputedRef<number>\n /** Computed uptime in seconds. */\n readonly uptimeSeconds: ComputedRef<number>\n /** Per-route latency tracking. */\n readonly routeLatency: Record<string, RouteStats>\n /**\n * Tier-1 runtime sampler from `@forinda/kickjs-devtools-kit`. `null`\n * when `runtime.enabled` is `false`. Tests can `latest()` and\n * `history()` directly without going through the HTTP endpoint.\n */\n readonly runtimeSampler: RuntimeSampler | null\n /**\n * Memory analyzer fed by the runtime sampler. `null` when the\n * sampler is disabled. Use `analyzer.health(sampler.history())` to\n * compose a composite memory-health snapshot.\n */\n readonly memoryAnalyzer: MemoryAnalyzer | null\n}\n\n/**\n * DevToolsAdapter — Vue-style reactive introspection for KickJS applications.\n *\n * Exposes debug endpoints powered by reactive state (ref, computed, watch):\n * - `GET /_debug/routes` — all registered routes with middleware\n * - `GET /_debug/container` — DI registry with scopes and instantiation status\n * - `GET /_debug/metrics` — live request/error counts, error rate, uptime\n * - `GET /_debug/health` — deep health check with adapter status\n * - `GET /_debug/config` — sanitized environment variables (opt-in)\n * - `GET /_debug/state` — full reactive state snapshot\n *\n * @example\n * ```ts\n * import { DevToolsAdapter } from '@forinda/kickjs-devtools'\n *\n * bootstrap({\n * modules: [UserModule],\n * adapters: [\n * DevToolsAdapter({\n * enabled: process.env.NODE_ENV !== 'production',\n * exposeConfig: true,\n * configPrefixes: ['APP_', 'DATABASE_'],\n * }),\n * ],\n * })\n * ```\n */\nexport const DevToolsAdapter = defineAdapter<DevToolsOptions, DevToolsAdapterExtensions>({\n name: 'DevToolsAdapter',\n defaults: {\n basePath: '/_debug',\n errorRateThreshold: 0.5,\n exposeConfig: false,\n configPrefixes: ['APP_', 'NODE_ENV'],\n },\n build: (options) => {\n const basePath = options.basePath!\n const enabled = options.enabled ?? process.env.NODE_ENV !== 'production'\n const exposeConfig = options.exposeConfig!\n const configPrefixes = options.configPrefixes!\n const errorRateThreshold = options.errorRateThreshold!\n const peerAdapters = options.adapters ?? []\n\n // Secret token guard\n let secret: string | false\n if (options.secret === false) {\n secret = false\n } else if (options.secret) {\n secret = options.secret\n } else {\n secret = randomBytes(16).toString('hex')\n }\n\n // ── Runtime sampler + memory analyzer (kit) ────────────────────\n // Lazily instantiated so an adopter that disables runtime monitoring\n // doesn't pay the perf_hooks histogram cost. Lifecycle: start in\n // `beforeMount`, stop in `shutdown`.\n const runtimeEnabled = options.runtime?.enabled ?? true\n const runtimeSampler = runtimeEnabled\n ? new RuntimeSampler({\n intervalMs: options.runtime?.intervalMs ?? 1000,\n bufferSize: options.runtime?.bufferSize ?? 60,\n })\n : null\n const memoryAnalyzer = runtimeEnabled ? new MemoryAnalyzer() : null\n\n // ── Server-side event bus ──────────────────────────────────────\n // Lazily resolved in `beforeMount` — when the devtools adapter is\n // rebuilt during HMR, the same `Container` may already hold a bus\n // from a previous mount with live WebSocket clients + in-flight\n // subscriptions. Creating a fresh bus on every rebuild would\n // silently swap the registered instance, leaving plugins that\n // already captured the old reference publishing into a dead bus.\n // Using `container.has(DEVTOOLS_BUS)` to reuse instead keeps event\n // delivery stable across rebuilds.\n //\n // When the devtools adapter is disabled (`enabled === false`) we\n // register a no-op stub instead so adopters who Inject(DEVTOOLS_BUS)\n // under @Optional() get a callable instance rather than undefined.\n let bus: ServerBus | null = null\n\n const ensureBus = (container: Container): ServerBus => {\n if (container.has(DEVTOOLS_BUS)) {\n // The token is typed `KickEventBus` but the registered instance\n // is the wider `ServerBus` (KickEventBus + attachUpgrade /\n // close / clientCount). Explicit generic on resolve avoids the\n // structural-cast — Container.resolve's last overload accepts\n // an explicit T and returns it.\n bus = container.resolve<ServerBus>(DEVTOOLS_BUS)\n return bus\n }\n bus = enabled\n ? createServerBus({\n wsPath: `${basePath}/_bus`,\n secret: secret === false ? false : secret,\n })\n : ({\n on: () => () => {},\n onAny: () => () => {},\n emit: () => {},\n attachUpgrade: () => {},\n close: () => {},\n clientCount: () => 0,\n } as ServerBus)\n container.registerInstance(DEVTOOLS_BUS, bus)\n return bus\n }\n\n // ── Reactive state ─────────────────────────────────────────────\n const requestCount = ref(0)\n const errorCount = ref(0)\n const clientErrorCount = ref(0)\n // App mount timestamp — kept for reference, but uptime is derived from the\n // node process (see below) so it survives HMR rebuilds.\n const startedAt = ref(Date.now())\n const routeLatency = reactive<Record<string, RouteStats>>({})\n\n const errorRate = computed(() =>\n requestCount.value > 0 ? errorCount.value / requestCount.value : 0,\n )\n\n // Uptime is the NODE PROCESS uptime, not \"time since beforeMount\". In dev,\n // `beforeMount` re-runs on every HMR rebuild / SSR re-bootstrap, which used\n // to reset `startedAt` and pin uptime near 0s. `process.uptime()` is\n // monotonic from process start, so it reports the real server uptime across\n // reloads. `tick` makes the computed re-evaluate when the reactive graph\n // refreshes; the value itself comes from the live process clock.\n const uptimeSeconds = computed(() => {\n void startedAt.value // keep the dependency so DevTools polls re-read it\n return Math.floor(process.uptime())\n })\n\n // ── Internal mutable state ─────────────────────────────────────\n let routes: RouteInfo[] = []\n let container: Container | null = null\n let appRef: any = null\n\n /**\n * One finished response into the reactive state. Latency is keyed by the\n * full route pattern (`GET /api/v1/users/:id`), so two modules' `/:id`\n * routes no longer share a bucket; unmatched requests (404 probing)\n * collapse into one `<unmatched>` bucket per method instead of one entry\n * per raw URL, which grew the map without bound.\n */\n const recordResponse = (\n method: string,\n route: string | undefined,\n status: number,\n elapsedMs: number,\n ): void => {\n requestCount.value++\n if (status >= 500) errorCount.value++\n else if (status >= 400) clientErrorCount.value++\n\n const routeKey = `${method} ${route ?? '<unmatched>'}`\n if (!routeLatency[routeKey]) {\n routeLatency[routeKey] = { count: 0, totalMs: 0, minMs: Infinity, maxMs: 0, samples: [] }\n }\n const stats = routeLatency[routeKey]\n stats.count++\n stats.totalMs += elapsedMs\n stats.minMs = Math.min(stats.minMs, elapsedMs)\n stats.maxMs = Math.max(stats.maxMs, elapsedMs)\n stats.samples.push(elapsedMs)\n if (stats.samples.length > MAX_SAMPLES) stats.samples.shift()\n }\n const adapterStatuses: Record<string, string> = {}\n let stopErrorWatch: (() => void) | null = null\n\n // Watch error rate — log warnings when elevated\n if (options.onErrorRateExceeded) {\n const callback = options.onErrorRateExceeded\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n callback(rate)\n }\n })\n } else {\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n log.warn(`Error rate elevated: ${(rate * 100).toFixed(1)}%`)\n }\n })\n }\n\n /**\n * Find the dashboard's public directory. Prefers the new Solid SPA\n * (public/spa/, shipped from PR 4 of §23); falls back to the legacy\n * Vue+Tailwind dashboard (public/devtools/) for environments that\n * haven't run `pnpm --filter @forinda/kickjs-devtools build:spa`.\n */\n const resolvePublicDir = (): string | null => {\n const thisDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(thisDir, '..', 'public', 'spa'), // dist/ -> public/spa\n join(thisDir, '..', '..', 'public', 'spa'), // src/ -> public/spa\n join(thisDir, '..', 'public', 'devtools'), // legacy Vue dashboard\n join(thisDir, '..', '..', 'public', 'devtools'), // legacy from src/\n ]\n for (const dir of candidates) {\n if (existsSync(join(dir, 'index.html'))) return dir\n }\n return null\n }\n\n /**\n * Resolve peer adapters at request time. Prefers live adapters from the\n * Application registry (survives HMR rebuild) and falls back to the\n * constructor-provided refs.\n */\n const getPeerAdapters = (): any[] => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getAdapters === 'function') {\n return kickApp.getAdapters()\n }\n return peerAdapters\n }\n\n /**\n * Active HTTP runtime identity + capabilities (`express` | `fastify` | `h3`),\n * read from the Application via `getActiveRuntime()`. Returns `null` when the\n * framework is older than the getter (graceful for mixed versions). Lets the\n * dashboard show which engine the app is running on.\n */\n const readActiveRuntime = (): {\n name: string\n capabilities: Record<string, boolean>\n } | null => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getActiveRuntime === 'function') {\n try {\n return kickApp.getActiveRuntime()\n } catch {\n return null\n }\n }\n return null\n }\n\n return {\n // ── Extensions (TExtra) ───────────────────────────────────────\n requestCount,\n errorCount,\n clientErrorCount,\n startedAt,\n errorRate,\n uptimeSeconds,\n routeLatency,\n runtimeSampler,\n memoryAnalyzer,\n\n // ── DevTools introspection (architecture.md §23) ─────────────\n // Cheap snapshot — counters + flags only. Anything that requires\n // a container walk or DB hit belongs in the per-endpoint RPCs\n // (`/_debug/container`, `/_debug/graph`), not here.\n introspect(): IntrospectionSnapshot {\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: 'DevToolsAdapter',\n kind: 'adapter',\n state: {\n basePath,\n enabled,\n runtimeEnabled,\n secret: secret === false ? false : 'present',\n },\n metrics: {\n requestCount: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n uptimeSeconds: uptimeSeconds.value,\n routesTracked: routes.length,\n },\n }\n },\n\n // ── Lifecycle ─────────────────────────────────────────────────\n\n beforeMount({ app, http, container: containerArg }) {\n if (!enabled) return\n\n appRef = app\n container = containerArg\n // Lazy resolve — reuses the existing bus when the same\n // container is reused across HMR rebuilds, otherwise creates\n // and registers a fresh instance. See `ensureBus` for why.\n ensureBus(containerArg)\n startedAt.value = Date.now()\n // Clear routes on rebuild/restart to prevent HMR duplication\n routes = []\n adapterStatuses['DevToolsAdapter'] = 'running'\n\n // Start the runtime sampler + memory analyzer here (rather than\n // at construction) so test harnesses that build the adapter but\n // never mount it don't leak interval timers.\n runtimeSampler?.start()\n memoryAnalyzer?.start()\n\n // Every dashboard route registers through the engine-agnostic HTTP\n // facade (`ctx.http`) and answers through `RequestContext`, so the\n // dashboard runs under Express, Fastify, and h3 alike. The dashboard\n // root (`'/'`) maps to `basePath` itself.\n //\n // The token guard runs inside each route rather than as a path-scoped\n // connect middleware: connect middleware sees the engine's raw\n // request, whose `path` / `query` differ per engine (and Express\n // strips the mount prefix while the others don't).\n const joinBase = (p: string): string => (p === '/' ? basePath : `${basePath}${p}`)\n const authorized = (ctx: RequestContext): boolean => {\n if (secret === false) return true\n const provided = ctx.headers['x-devtools-token'] ?? ctx.query?.token\n if (provided === secret) return true\n ctx.json({ error: 'Forbidden — invalid or missing devtools token' }, 403)\n return false\n }\n const guarded =\n (handler: (ctx: RequestContext) => unknown) =>\n (ctx: RequestContext): unknown =>\n authorized(ctx) ? handler(ctx) : undefined\n const router = {\n get: (path: string, handler: (ctx: RequestContext) => unknown): void =>\n http.route('GET', joinBase(path), guarded(handler)),\n post: (path: string, handler: (ctx: RequestContext) => unknown): void =>\n http.route('POST', joinBase(path), guarded(handler)),\n }\n\n router.get('/routes', (ctx: RequestContext) => {\n ctx.json({ routes })\n })\n\n // Where a route's handler lives — \"open in editor\" in the dashboard\n // and the VS Code extension.\n router.get('/source', (ctx: RequestContext) => {\n const { controller, handler } = ctx.query as Record<string, string | undefined>\n const known = routes.some((r) => r.controller === controller && r.handler === handler)\n const found =\n known && controller && handler\n ? locateHandler(process.cwd(), controller, handler)\n : undefined\n if (!found) {\n ctx.json({ error: 'Handler source not found' }, 404)\n return\n }\n ctx.json(found)\n })\n\n router.get('/container', (ctx: RequestContext) => {\n const registrations = container?.getRegistrations() ?? []\n ctx.json({ registrations, count: registrations.length })\n })\n\n router.get('/metrics', (ctx: RequestContext) => {\n // Build latency with percentiles, omitting raw samples from response\n const latency: Record<string, any> = {}\n for (const [key, stats] of Object.entries(routeLatency)) {\n const { samples: _, ...rest } = stats\n latency[key] = { ...rest, ...computePercentiles(stats) }\n }\n ctx.json({\n requests: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n routeLatency: latency,\n })\n })\n\n router.get('/health', async (ctx: RequestContext) => {\n const healthy = errorRate.value < errorRateThreshold\n const status = healthy ? 'healthy' : 'degraded'\n\n // Refresh peer statuses from `onHealthCheck()` when present.\n // The static `adapterStatuses` dict (seeded in `afterStart`)\n // proves a peer was mounted; calling `onHealthCheck()` here\n // upgrades that to a live `up`/`down`/`degraded` reading so\n // the Overview > Health card reflects actual adapter state,\n // not just \"registered at boot\".\n //\n // Each peer call is bounded by `PEER_HEALTHCHECK_TIMEOUT_MS` —\n // an adapter whose check hangs (network DB ping, remote\n // service, etc.) must not be able to stall the entire\n // dashboard request. Timed-out peers fall through to the\n // catch arm and are reported as `down`.\n const live: Record<string, string> = { ...adapterStatuses }\n await Promise.all(\n getPeerAdapters().map(async (peer) => {\n if (typeof peer?.onHealthCheck !== 'function') return\n const name: unknown = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') return\n try {\n const result = await raceWithTimeout(\n Promise.resolve(peer.onHealthCheck()),\n PEER_HEALTHCHECK_TIMEOUT_MS,\n `onHealthCheck(${name})`,\n )\n if (result && typeof result.status === 'string') {\n live[name] = result.status\n }\n } catch {\n live[name] = 'down'\n }\n }),\n )\n\n ctx.json(\n {\n status,\n errorRate: errorRate.value,\n uptime: uptimeSeconds.value,\n runtime: readActiveRuntime(),\n adapters: live,\n },\n healthy ? 200 : 503,\n )\n })\n\n router.get('/state', (ctx: RequestContext) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n ctx.json({\n reactive: {\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n },\n routes: routes.length,\n container: container?.getRegistrations().length ?? 0,\n routeLatency,\n ...(wsAdapter ? { ws: wsAdapter.getStats() } : {}),\n })\n })\n\n // ── Tier-1 runtime monitoring (architecture.md §23) ─────────\n // Returns the latest RuntimeSnapshot + a composite MemoryHealth\n // computed from the sampler's ring buffer. Returns 404 when the\n // sampler is disabled so adopters can distinguish \"off\" from\n // \"starting up\".\n router.get('/runtime', (ctx: RequestContext) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n ctx.json({ error: 'runtime sampler disabled — set runtime.enabled = true' }, 404)\n return\n }\n const latest = runtimeSampler.latest()\n const history = runtimeSampler.history()\n const health = memoryAnalyzer.health(history)\n ctx.json({\n protocolVersion: PROTOCOL_VERSION,\n // Identity of the process these stats describe — every memory / CPU /\n // event-loop number below is for THIS Node process (the one running\n // your KickJS app), not the OS or any child. Lets the panel label it\n // unambiguously (\"Node v22 · pid 12345 · linux/x64 · engine: fastify\").\n process: {\n nodeVersion: process.version,\n pid: process.pid,\n platform: process.platform,\n arch: process.arch,\n runtime: readActiveRuntime(),\n },\n latest,\n history,\n health,\n })\n })\n\n // ── SSE: live runtime snapshots (architecture.md §23) ───────\n // Pushes the latest RuntimeSnapshot every `intervalMs`. SSE\n // (not WebSocket) avoids the http.Server `upgrade`-event\n // coordination cost — see devtools-flows.md §3 for rationale.\n router.get('/runtime/stream', (ctx: RequestContext) => {\n if (!runtimeSampler) {\n ctx.json({ error: 'runtime sampler disabled' }, 404)\n return\n }\n const sse = ctx.sse()\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (snap) sse.send(snap)\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => sse.comment('heartbeat'), 30_000)\n sse.onClose(() => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── SSE: memory health composite (architecture.md §23) ──────\n router.get('/memory/stream', (ctx: RequestContext) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n ctx.json({ error: 'runtime sampler disabled' }, 404)\n return\n }\n const sse = ctx.sse()\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (!snap) return\n const health = memoryAnalyzer.health(runtimeSampler.history())\n sse.send({ snapshot: snap, health })\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => sse.comment('heartbeat'), 30_000)\n sse.onClose(() => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── Heap snapshot — Tier 3 monitoring (architecture.md §23) ─\n // POST /_debug/memory/snapshot — captures a V8 heap snapshot\n // and streams the resulting .heapsnapshot file back as\n // application/json with Content-Disposition. Snapshot capture\n // blocks the event loop while writing (multi-second pause for\n // large heaps), so the endpoint enforces single-flight via a\n // module-scoped flag — concurrent calls return 503.\n //\n // The file streams through `ctx.sendResponse` (engine-neutral, with\n // backpressure — never buffered whole) and the temp file is deleted\n // once the response completes, fails, or the client disconnects.\n // Worst case if the process dies mid-snapshot is a stranded file in\n // `os.tmpdir()`, which the OS cleans up on next boot.\n router.post('/memory/snapshot', async (ctx: RequestContext) => {\n if (snapshotInProgress) {\n ctx.json({ error: 'heap snapshot already in progress — wait for it to complete' }, 503)\n return\n }\n snapshotInProgress = true\n const startedAt = Date.now()\n const filename = `kickjs-heap-${new Date().toISOString().replace(/[:.]/g, '-')}.heapsnapshot`\n const targetPath = join(tmpdir(), filename)\n\n let written: string\n try {\n // writeHeapSnapshot is synchronous — the event loop is\n // blocked for the duration. There's no async variant in\n // the v8 module today; if one ships, swap here.\n written = writeHeapSnapshot(targetPath)\n } catch (err) {\n snapshotInProgress = false\n log.error({ err }, 'heap snapshot capture failed')\n ctx.json({ error: 'snapshot capture failed', message: (err as Error).message }, 500)\n return\n }\n\n let size = 0\n try {\n size = statSync(written).size\n } catch {\n /* size header is best-effort */\n }\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Heap snapshot captured: ${written} (${(size / 1024 / 1024).toFixed(1)} MiB in ${elapsedMs}ms)`,\n )\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'X-Snapshot-Capture-Ms': String(elapsedMs),\n }\n if (size > 0) headers['Content-Length'] = String(size)\n\n const stream = createReadStream(written)\n try {\n await ctx.sendResponse(\n new Response(Readable.toWeb(stream) as ReadableStream, { headers }),\n )\n } catch (err) {\n log.error({ err }, 'heap snapshot stream failed')\n } finally {\n // Also covers a client that disconnected mid-download:\n // sendResponse stops reading, so close the file here.\n stream.destroy()\n unlink(written, (err) => {\n if (err) log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`)\n snapshotInProgress = false\n })\n }\n })\n\n // ── Force GC — Tier 3 monitoring (architecture.md §23) ──────\n // POST /_debug/memory/gc — calls `global.gc()` if Node was\n // started with --expose-gc, returning before/after heap size\n // so the panel can show how much was reclaimed. Useful for\n // confirming \"is this growth real or just delayed GC?\".\n //\n // Returns 412 Precondition Failed (with hint) when the flag\n // wasn't set, so the SPA can show \"Run with --expose-gc to\n // enable this button\" instead of a generic 5xx.\n router.post('/memory/gc', (ctx: RequestContext) => {\n const gc = (globalThis as { gc?: () => void }).gc\n if (typeof gc !== 'function') {\n ctx.json(\n {\n error:\n 'global.gc unavailable — start Node with --expose-gc to enable this endpoint',\n },\n 412,\n )\n return\n }\n const before = process.memoryUsage().heapUsed\n const startedAt = Date.now()\n try {\n gc()\n } catch (err) {\n ctx.json(\n {\n error: 'forced GC failed',\n message: err instanceof Error ? err.message : String(err),\n },\n 500,\n )\n return\n }\n const after = process.memoryUsage().heapUsed\n const reclaimedBytes = Math.max(0, before - after)\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Forced GC reclaimed ${(reclaimedBytes / 1024 / 1024).toFixed(2)} MiB in ${elapsedMs}ms`,\n )\n ctx.json({ before, after, reclaimedBytes, elapsedMs })\n })\n\n // ── Custom-tab discovery (architecture.md §23) ──────────────\n // Walks every plugin/adapter `devtoolsTabs?()` contribution\n // and serves the deduped + validated list. The SPA fetches\n // this once at boot to render dynamic tabs after the four\n // built-ins.\n router.get('/tabs', (ctx: RequestContext) => {\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n ctx.json({ error: 'tabs unavailable — application surface not exposed' }, 503)\n return\n }\n ctx.json(collectDevtoolsTabs(kickApp))\n })\n\n // ── Topology RPC (architecture.md §23) ──────────────────────\n // Aggregates plugins + adapters + contributors + DI tokens\n // into one snapshot; calls each primitive's introspect() in\n // parallel with a per-call timeout so a misbehaving adapter\n // can't block the endpoint. Errors are collected, not thrown.\n router.get('/topology', async (ctx: RequestContext) => {\n if (!container) {\n ctx.json({ error: 'topology unavailable — container not bound yet' }, 503)\n return\n }\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n ctx.json({ error: 'topology unavailable — application surface not exposed' }, 503)\n return\n }\n try {\n const snapshot = await collectTopologySnapshot({ app: kickApp, container })\n ctx.json(snapshot)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n ctx.json({ error: 'topology collection failed', message }, 500)\n }\n })\n\n router.get('/ws', (ctx: RequestContext) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n if (!wsAdapter) {\n ctx.json({ enabled: false, message: 'WsAdapter not found' })\n return\n }\n ctx.json({ enabled: true, ...wsAdapter.getStats() })\n })\n\n router.get('/queues', async (ctx: RequestContext) => {\n const queueAdapter = getPeerAdapters().find(\n (a) => a.name === 'QueueAdapter' && typeof a.getQueueNames === 'function',\n )\n if (!queueAdapter) {\n ctx.json({ enabled: false, message: 'QueueAdapter not found' })\n return\n }\n try {\n const names: string[] = queueAdapter.getQueueNames?.() ?? []\n const queues: any[] = []\n for (const name of names) {\n const stats = await queueAdapter.getQueueStats?.(name)\n queues.push({ name, ...stats })\n }\n ctx.json({ enabled: true, queues })\n } catch {\n ctx.json({ enabled: true, queues: [], error: 'Failed to fetch queue stats' })\n }\n })\n\n // ── Dependency graph ────────────────────────────────────────\n router.get('/graph', (ctx: RequestContext) => {\n const registrations = container?.getRegistrations() ?? []\n const nodes = registrations\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n id: r.token,\n kind: r.kind,\n scope: r.scope,\n resolveCount: r.resolveCount,\n }))\n const nodeIds = new Set(nodes.map((n) => n.id))\n const edges: Array<{ from: string; to: string }> = []\n for (const r of registrations) {\n if (r.token.startsWith('__hmr__')) continue\n for (const dep of r.dependencies) {\n if (nodeIds.has(dep)) {\n edges.push({ from: r.token, to: dep })\n }\n }\n }\n ctx.json({ nodes, edges })\n })\n\n // ── SSE stream for real-time updates ────────────────────────\n router.get('/stream', (ctx: RequestContext) => {\n const sse = ctx.sse()\n\n const sendMetrics = () => {\n sse.send({\n type: 'metrics',\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n })\n }\n sendMetrics()\n\n const unsubContainer = container?.onChange?.((changes) => {\n sse.send({ type: 'container', changes, timestamp: Date.now() })\n sendMetrics()\n })\n\n const stopRequestWatch = watch(requestCount, () => sendMetrics())\n const stopErrWatch = watch(errorCount, () => sendMetrics())\n\n const heartbeat = setInterval(() => sse.comment('heartbeat'), 30000)\n\n sse.onClose(() => {\n unsubContainer?.()\n stopRequestWatch()\n stopErrWatch()\n clearInterval(heartbeat)\n })\n })\n\n if (exposeConfig) {\n router.get('/config', (ctx: RequestContext) => {\n const config: Record<string, string> = {}\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) continue\n const allowed = configPrefixes.some((prefix) => key.startsWith(prefix))\n config[key] = allowed ? value : '[REDACTED]'\n }\n ctx.json({ config })\n })\n }\n\n // Dashboard UI — Vue + Tailwind from public/devtools directory\n const publicDir = resolvePublicDir()\n // The page itself is not token-guarded — it loads first and sends the\n // token on its API calls — unless a `?token=` is given, which must match.\n const dashboard =\n (html: string) =>\n (ctx: RequestContext): unknown =>\n ctx.query?.token === undefined || authorized(ctx) ? ctx.html(html) : undefined\n if (publicDir) {\n // Serve only the SPA's `assets/` statically, so the static server can\n // never answer the dashboard root with the raw `index.html` — the\n // route below owns it and injects `data-base`. The legacy Vue\n // dashboard keeps its files at the top level.\n const assetsDir = join(publicDir, 'assets')\n if (existsSync(assetsDir)) http.serveStatic(`${basePath}/assets`, assetsDir)\n else http.serveStatic(basePath, publicDir)\n\n const indexHtml = readFileSync(join(publicDir, 'index.html'), 'utf-8')\n http.route(\n 'GET',\n basePath,\n dashboard(indexHtml.replace('<body', `<body data-base=\"${basePath}\"`)),\n )\n } else {\n http.route('GET', basePath, dashboard('<h1>DevTools: public directory not found</h1>'))\n }\n\n if (secret) {\n log.info(`DevTools mounted at ${basePath} [token: ${secret}]`)\n log.info(`Access: ${basePath}?token=${secret}`)\n } else {\n log.info(`DevTools mounted at ${basePath} [no guard]`)\n }\n },\n\n /**\n * Feeds the reactive counters (`requestCount`, `errorCount`,\n * `routeLatency`, …) from the framework's response funnel — one\n * listener for every observer instead of one middleware per adapter.\n */\n onResponse(info) {\n if (!enabled) return\n recordResponse(info.method, info.route, info.status, info.durationMs)\n },\n\n middleware(): AdapterMiddleware[] {\n // The framework already reports every response to `onResponse`.\n if (!enabled || FRAMEWORK_REPORTS_RESPONSES) return []\n\n return [\n {\n // Older kickjs: time the response ourselves. Connect-style, so it\n // sees the engine's raw Node request/response on every runtime.\n handler: (req: IncomingMessage, res: ServerResponse, next: () => void) => {\n const start = Date.now()\n res.on('finish', () => {\n const matched = (req as unknown as Record<symbol, MatchedRoute | undefined>)[\n MATCHED_ROUTE_SLOT\n ]\n recordResponse(\n req.method ?? 'GET',\n matched?.pattern ?? matched?.path,\n res.statusCode,\n Date.now() - start,\n )\n })\n next()\n },\n phase: 'beforeGlobal',\n },\n ]\n },\n\n onRouteMount(controllerClass, mountPath) {\n if (!enabled) return\n\n const collectedRoutes = getClassMeta<\n Array<{ method: string; path: string; handlerName: string }>\n >(METADATA.ROUTES, controllerClass, [])\n\n const classMiddleware = getClassMeta<any[]>(METADATA.CLASS_MIDDLEWARES, controllerClass, [])\n\n for (const route of collectedRoutes) {\n const methodMiddleware = getMethodMeta<any[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass.prototype,\n route.handlerName,\n [],\n )\n\n routes.push({\n method: route.method.toUpperCase(),\n path: `${mountPath}${route.path === '/' ? '' : route.path}`,\n controller: controllerClass.name,\n handler: route.handlerName,\n middleware: [\n ...classMiddleware.map((m: any) => m.name || 'anonymous'),\n ...methodMiddleware.map((m: any) => m.name || 'anonymous'),\n ],\n flags: Object.fromEntries(getRouteFlags(controllerClass, route.handlerName)),\n ...uploadInfo(controllerClass, route.handlerName),\n })\n }\n },\n\n afterStart({ server }) {\n if (!enabled) return\n // Wire the bus's WS upgrade to the framework's http.Server.\n // Path-based routing inside attachUpgrade means kickjs-ws or\n // any other adapter sharing the same listener stays\n // unaffected — only `${basePath}/_bus` is claimed.\n if (server) bus?.attachUpgrade(server)\n\n // Seed `/_debug/health.adapters` with every peer the framework\n // mounted alongside us. Before this, only `DevToolsAdapter`\n // appeared in the Overview > Health card because the dict was\n // only ever written in `beforeMount` (self) and `shutdown`\n // (self). Peers with `onHealthCheck` get their live status;\n // anything else is reported as `running` since reaching\n // `afterStart` means the framework already mounted them.\n for (const peer of getPeerAdapters()) {\n const name = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') continue\n adapterStatuses[name] = 'running'\n }\n\n log.info(\n `DevTools ready — ${routes.length} routes tracked, ` +\n `${container?.getRegistrations().length ?? 0} DI bindings, ` +\n `event bus on ${basePath}/_bus`,\n )\n },\n\n shutdown() {\n stopErrorWatch?.()\n runtimeSampler?.stop()\n memoryAnalyzer?.stop()\n bus?.close()\n adapterStatuses['DevToolsAdapter'] = 'stopped'\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;mvBAkEA,eAAsB,wBACpB,KAC2B,CAC3B,GAAM,CAAE,IAAK,UAAW,oBAAsB,KAAkC,KAC1E,OAA0B,CAAC,EAE3B,QAAU,MAAM,QAAQ,IAC5B,IAAI,WAAW,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,SAAU,oBAAqB,MAAM,CAAC,CACnF,EACM,SAAW,MAAM,QAAQ,IAC7B,IAAI,YAAY,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,UAAW,oBAAqB,MAAM,CAAC,CACrF,EAEA,MAAO,CACL,gBAAiB,iBACjB,UAAW,KAAK,IAAI,EACpB,QACA,SACA,aAAc,oBAAoB,GAAG,EACrC,SAAU,cAAc,SAAS,EACjC,MACF,CACF,CAOA,eAAe,YACb,UACA,KACA,UACA,OACgC,CAChC,IAAM,KAAO,UAAU,MAAQ,YACzB,KAA8B,CAClC,gBAAiB,iBACjB,KACA,IACF,EACA,GAAI,OAAO,UAAU,YAAe,WAAY,OAAO,KAEvD,GAAI,CACF,IAAM,OAAS,MAAM,QAAQ,KAAK,CAChC,QAAQ,QAAQ,UAAU,WAAW,CAAC,EACtC,IAAI,SAAgB,EAAG,SACrB,eACQ,OAAW,MAAM,gCAAgC,UAAU,GAAG,CAAC,EACrE,SACF,CACF,CACF,CAAC,EACD,GAAI,QAAU,OAAO,QAAW,SAAU,CAKxC,IAAM,KAAO,OACb,MAAO,CACL,gBAAiB,iBACjB,KAAM,KAAK,MAAQ,KACnB,KAAM,KAAK,MAAQ,KACnB,QAAS,KAAK,QACd,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,QAAS,KAAK,QACd,YAAa,KAAK,WACpB,CACF,CACA,OAAO,IACT,OAAS,IAAK,CAMZ,OALA,OAAO,KAAK,CACV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