@forinda/kickjs-devtools 7.1.0 → 7.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ Endpoints (token-gated unless `secret: false`): `/_debug/{routes,container,metri
31
31
 
32
32
  ## Documentation
33
33
 
34
- [forinda.github.io/kick-js/guide/devtools](https://forinda.github.io/kick-js/guide/devtools)
34
+ [kickjs.app/guide/devtools](https://kickjs.app/guide/devtools)
35
35
 
36
36
  ## License
37
37
 
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
+ import "reflect-metadata";
2
3
  import { ComputedRef, Ref } from "@forinda/kickjs";
3
4
  import { MemoryAnalyzer, RuntimeSampler } from "@forinda/kickjs-devtools-kit";
4
-
5
5
  //#region src/adapter.d.ts
6
6
  /** Per-route latency stats with percentile tracking */
7
7
  interface RouteStats {
@@ -50,8 +50,11 @@ interface DevToolsOptions {
50
50
  * snapshot, signalling deliberate opt-out rather than a startup race.
51
51
  */
52
52
  runtime?: {
53
- /** Whether to start the runtime sampler at all. Default: true. */enabled?: boolean; /** Polling interval in milliseconds. Default: 1000. */
54
- intervalMs?: number; /** Ring-buffer size — number of past samples retained. Default: 60. */
53
+ /** Whether to start the runtime sampler at all. Default: true. */
54
+ enabled?: boolean;
55
+ /** Polling interval in milliseconds. Default: 1000. */
56
+ intervalMs?: number;
57
+ /** Ring-buffer size — number of past samples retained. Default: 60. */
55
58
  bufferSize?: number;
56
59
  };
57
60
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;UA8CU,UAAA;EACR,KAAA;EACA,OAAA;EACA,KAAA;EACA,KAAA;EAJkB;EAMlB,OAAA;AAAA;AAAA,UAoFe,eAAA;EAtFf;EAwFA,QAAA;EAtFO;EAwFP,OAAA;EAJe;EAMf,YAAA;;EAEA,cAAA;EANA;EAQA,mBAAA,IAAu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  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,13 +8,13 @@
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,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?!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{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,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
12
12
  \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?!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?!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
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
14
 
15
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
16
 
17
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
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`)]})}},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};
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`)]})}},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
20
  //# 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} 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\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 })\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":";;;;;;;;;;6qBAkEA,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,CA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AgB,KAAK,EACrB,KAAK,MAAM,EACX,gBAAgB,gBAAqB,SACvC,CACF,CACF,CACF,CAAC"}
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} 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\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 })\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":";;;;;;;;;;6qBAkEA,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,OAA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