@forinda/kickjs-devtools 7.1.2 → 7.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/public/spa/assets/index.js +1 -1
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;UAqDU;EACR;EACA;EACA;EACA;;EAEA;;UAoFe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,uBAAuB;;EAEvB;;EAEA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA;;IAEE;;IAEA;;IAEA;;;;;;;;UASa;;WAEN,cAAc;;WAEd,YAAY;;WAEZ,kBAAkB;;WAElB,WAAW;;WAEX,WAAW;;WAEX,eAAe;;WAEf,cAAc,eAAe;;;;;;WAM7B,gBAAgB;;;;;;WAMhB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8Bd,2CAAe,eAAA,iBAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-devtools v7.
|
|
2
|
+
* @forinda/kickjs-devtools v7.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import"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
|
|
11
|
+
import"reflect-metadata";import{static as static$1}from"express";import{dirname,join}from"node:path";import{tmpdir}from"node:os";import{fileURLToPath}from"node:url";import{createReadStream,existsSync,readFileSync,statSync,unlink}from"node:fs";import{randomBytes}from"node:crypto";import{writeHeapSnapshot}from"node:v8";import{METADATA,computed,createLogger,defineAdapter,getClassMeta,getMethodMeta,getRouteFlags,reactive,ref,watch}from"@forinda/kickjs";import{MemoryAnalyzer,PROTOCOL_VERSION,RuntimeSampler}from"@forinda/kickjs-devtools-kit";import{DEVTOOLS_BUS}from"@forinda/kickjs-devtools-kit/bus/token";import{createBusCore}from"@forinda/kickjs-devtools-kit/bus";import{WebSocketServer}from"ws";async function collectTopologySnapshot(opts){let{app,container,introspectTimeoutMs=100}=opts,errors=[],plugins=await Promise.all(app.getPlugins().map(p=>snapshotFor(p,`plugin`,introspectTimeoutMs,errors))),adapters=await Promise.all(app.getAdapters().map(a=>snapshotFor(a,`adapter`,introspectTimeoutMs,errors)));return{protocolVersion:PROTOCOL_VERSION,timestamp:Date.now(),plugins,adapters,contributors:collectContributors(app),diTokens:collectTokens(container),errors}}async function snapshotFor(primitive,kind,timeoutMs,errors){let name=primitive.name??`(unnamed)`,stub={protocolVersion:PROTOCOL_VERSION,name,kind};if(typeof primitive.introspect!=`function`)return stub;try{let result=await Promise.race([Promise.resolve(primitive.introspect()),new Promise((_,reject)=>setTimeout(()=>reject(Error(`introspect() timed out after ${timeoutMs}ms`)),timeoutMs))]);if(result&&typeof result==`object`){let snap=result;return{protocolVersion:PROTOCOL_VERSION,name:snap.name??name,kind:snap.kind??kind,version:snap.version,state:snap.state,tokens:snap.tokens,metrics:snap.metrics,memoryBytes:snap.memoryBytes}}return stub}catch(err){return errors.push({name,kind,message:err instanceof Error?err.message:String(err)}),stub}}function collectTokens(container){return container.getRegistrations().filter(r=>!r.token.startsWith(`__hmr__`)).map(r=>({token:r.token,scope:r.scope,kind:r.kind,instantiated:r.instantiated}))}function collectContributors(app){let seen=new Map;if(typeof app.getContributors==`function`){for(let c of app.getContributors())seen.has(c.key)||seen.set(c.key,{key:c.key,source:c.source,dependsOn:c.dependsOn});return[...seen.values()]}let ingest=(list,source)=>{if(list)for(let reg of list){let r=reg,key=typeof r.key==`string`?r.key:null;!key||seen.has(key)||seen.set(key,{key,source,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let plugin of app.getPlugins())ingest(plugin.contributors?.(),`adapter`);for(let adapter of app.getAdapters())ingest(adapter.contributors?.(),`adapter`);return[...seen.values()]}const VALID_VIEW_TYPES=new Set([`iframe`,`launch`,`html`]);function collectDevtoolsTabs(app){let tabs=[],seen=new Map,errors=[],ingest=(sourceName,raw)=>{if(!Array.isArray(raw)){errors.push({source:sourceName,reason:`devtoolsTabs() did not return an array`});return}for(let entry of raw){let validation=validateTab(entry);if(!validation.ok){errors.push({source:sourceName,reason:validation.reason});continue}let tab=validation.tab,owner=seen.get(tab.id);if(owner){errors.push({source:sourceName,reason:`tab id '${tab.id}' already registered by ${owner} — first-source wins`});continue}seen.set(tab.id,sourceName),tabs.push(tab)}};for(let plugin of app.getPlugins())if(typeof plugin.devtoolsTabs==`function`)try{ingest(plugin.name??`(unnamed plugin)`,plugin.devtoolsTabs())}catch(err){errors.push({source:plugin.name??`(unnamed plugin)`,reason:err instanceof Error?err.message:String(err)})}for(let adapter of app.getAdapters())if(typeof adapter.devtoolsTabs==`function`)try{ingest(adapter.name??`(unnamed adapter)`,adapter.devtoolsTabs())}catch(err){errors.push({source:adapter.name??`(unnamed adapter)`,reason:err instanceof Error?err.message:String(err)})}return{tabs,errors}}function validateTab(raw){if(!raw||typeof raw!=`object`)return{ok:!1,reason:`tab entry is not an object`};let obj=raw;if(typeof obj.id!=`string`||obj.id.length===0)return{ok:!1,reason:`tab.id must be a non-empty string`};if(typeof obj.title!=`string`||obj.title.length===0)return{ok:!1,reason:`tab '${obj.id}': title must be a non-empty string`};let view=obj.view;if(!view||typeof view!=`object`)return{ok:!1,reason:`tab '${obj.id}': view object is required`};if(typeof view.type!=`string`||!VALID_VIEW_TYPES.has(view.type))return{ok:!1,reason:`tab '${obj.id}': view.type must be one of iframe / launch / html`};switch(view.type){case`iframe`:if(typeof view.src!=`string`||view.src.length===0)return{ok:!1,reason:`tab '${obj.id}': iframe view requires a non-empty src`};break;case`html`:if(typeof view.html!=`string`)return{ok:!1,reason:`tab '${obj.id}': html view requires html string`};break;case`launch`:if(!Array.isArray(view.actions))return{ok:!1,reason:`tab '${obj.id}': launch view requires actions array`};break}return{ok:!0,tab:obj}}function createServerBus(opts={}){let wsPath=opts.wsPath??`/_debug/_bus`,secret=opts.secret??!1,core=createBusCore(),wss=new WebSocketServer({noServer:!0}),clients=new Set,attachedServer=null,upgradeHandler=null;wss.on(`connection`,ws=>{clients.add(ws),ws.on(`message`,data=>{try{let text=typeof data==`string`?data:data.toString(`utf-8`),parsed=JSON.parse(text);if(!parsed||typeof parsed.type!=`string`||typeof parsed.ts!=`number`)return;core.dispatch({...parsed,__kick_origin:`ws`})}catch{}}),ws.on(`close`,()=>{clients.delete(ws)}),ws.on(`error`,()=>{clients.delete(ws)})});let fanOut=envelope=>{if(clients.size===0)return;let text=JSON.stringify(envelope);for(let client of clients)if(client.readyState===client.OPEN)try{client.send(text)}catch{}},checkAuth=req=>{if(secret===!1)return!0;let header=req.headers[`x-devtools-token`];if(typeof header==`string`&&header===secret)return!0;let url=req.url??``,queryIdx=url.indexOf(`?`);return queryIdx!==-1&&new URLSearchParams(url.slice(queryIdx+1)).get(`token`)===secret};return{on(type,handler){return core.on(type,handler)},onAny(handler){return core.onAny(handler)},emit(type,payload){let envelope={type,payload,ts:Date.now(),__kick_origin:`local`};core.dispatch(envelope),fanOut(envelope)},attachUpgrade:httpServer=>{attachedServer||(attachedServer=httpServer,upgradeHandler=(req,socket,head)=>{if((req.url??``).split(`?`)[0]===wsPath){if(!checkAuth(req)){socket.write(`HTTP/1.1 401 Unauthorized\r
|
|
12
12
|
\r
|
|
13
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
|
|
|
@@ -16,5 +16,5 @@ import"reflect-metadata";import{static as static$1}from"express";import{dirname,
|
|
|
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`)],flags:Object.fromEntries(getRouteFlags(controllerClass,route.handlerName))})}},afterStart({server}){if(enabled){server&&bus?.attachUpgrade(server);for(let peer of getPeerAdapters()){let name=peer?.name;typeof name==`string`&&name!==`DevToolsAdapter`&&(adapterStatuses[name]=`running`)}log.info(`DevTools ready — ${routes.length} routes tracked, ${container?.getRegistrations().length??0} DI bindings, event bus on ${basePath}/_bus`)}},shutdown(){stopErrorWatch?.(),runtimeSampler?.stop(),memoryAnalyzer?.stop(),bus?.close(),adapterStatuses.DevToolsAdapter=`stopped`}}}});export{DevToolsAdapter};
|
|
20
20
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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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B,WAAW,iBAAiB,CAAC,CAAC,QAAU,EAAE,6BAC7B,SAAS,MAC7B,CAnBqC,CAoBvC,EAEA,UAAW,CACT,iBAAiB,EACjB,gBAAgB,KAAK,EACrB,gBAAgB,KAAK,EACrB,KAAK,MAAM,EACX,gBAAgB,gBAAqB,SACvC,CACF,CACF,CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["serveStatic"],"sources":["../src/topology.ts","../src/devtools-tabs.ts","../src/bus/server.ts","../src/adapter.ts"],"sourcesContent":["/**\n * Topology aggregator — walks the running KickJS application + DI\n * container and produces a JSON-serialisable {@link TopologySnapshot}.\n *\n * Calls `introspect()` on every plugin and adapter that implements it\n * (architecture.md §23.3); falls back to a minimal `{ protocolVersion,\n * name, kind }` stub for primitives that don't. Per-primitive\n * introspection failures are caught + collected into the snapshot's\n * `errors` field rather than failing the entire endpoint.\n *\n * @module @forinda/kickjs-devtools/topology\n */\n\nimport type { AppAdapter, Container, KickPlugin } from '@forinda/kickjs'\nimport {\n PROTOCOL_VERSION,\n type IntrospectionSnapshot,\n type TopologyContributorEntry,\n type TopologyError,\n type TopologySnapshot,\n type TopologyTokenEntry,\n} from '@forinda/kickjs-devtools-kit'\n\n/** Minimal Application surface the aggregator needs — keeps coupling thin. */\nexport interface TopologyApplicationLike {\n getAdapters(): AppAdapter[]\n getPlugins(): readonly KickPlugin[]\n /**\n * Optional in older Application implementations — when present, returns\n * the union of contributors across adapters/plugins/global with proper\n * source labels. The topology aggregator prefers this over walking\n * `adapter.contributors()` + `plugin.contributors()` directly because\n * the application-level walk preserves source provenance.\n */\n getContributors?(): ReadonlyArray<{\n key: string\n source: 'adapter' | 'plugin' | 'module' | 'global'\n label: string\n dependsOn: readonly string[]\n }>\n}\n\n/** Inputs to {@link collectTopologySnapshot}. */\nexport interface CollectTopologyOptions {\n /** The running KickJS application (or anything that exposes its surface). */\n app: TopologyApplicationLike\n /** The DI container — used to enumerate registered tokens. */\n container: Container\n /**\n * Optional per-call introspect timeout in milliseconds. An adapter\n * whose `introspect()` doesn't settle within the budget gets a stub\n * snapshot + an entry in `errors`. Default: 100ms — keeps the\n * topology endpoint snappy even if one adapter misbehaves.\n */\n introspectTimeoutMs?: number\n}\n\nconst DEFAULT_INTROSPECT_TIMEOUT_MS = 100\n\n/**\n * Collect a {@link TopologySnapshot} for the given application.\n *\n * Async because plugin/adapter `introspect()` may be async; the work\n * is parallelised across all primitives so wall-clock time scales\n * with the slowest introspector, not their sum.\n */\nexport async function collectTopologySnapshot(\n opts: CollectTopologyOptions,\n): Promise<TopologySnapshot> {\n const { app, container, introspectTimeoutMs = DEFAULT_INTROSPECT_TIMEOUT_MS } = opts\n const errors: TopologyError[] = []\n\n const plugins = await Promise.all(\n app.getPlugins().map((p) => snapshotFor(p, 'plugin', introspectTimeoutMs, errors)),\n )\n const adapters = await Promise.all(\n app.getAdapters().map((a) => snapshotFor(a, 'adapter', introspectTimeoutMs, errors)),\n )\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n timestamp: Date.now(),\n plugins,\n adapters,\n contributors: collectContributors(app),\n diTokens: collectTokens(container),\n errors,\n }\n}\n\n/**\n * Coerce one primitive into an {@link IntrospectionSnapshot}. Tries\n * the primitive's own `introspect()` first; falls back to a stub on\n * any of: missing implementation, throw, timeout, or non-object return.\n */\nasync function snapshotFor(\n primitive: AppAdapter | KickPlugin,\n kind: 'plugin' | 'adapter',\n timeoutMs: number,\n errors: TopologyError[],\n): Promise<IntrospectionSnapshot> {\n const name = primitive.name ?? '(unnamed)'\n const stub: IntrospectionSnapshot = {\n protocolVersion: PROTOCOL_VERSION,\n name,\n kind,\n }\n if (typeof primitive.introspect !== 'function') return stub\n\n try {\n const result = await Promise.race([\n Promise.resolve(primitive.introspect()),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`introspect() timed out after ${timeoutMs}ms`)),\n timeoutMs,\n ),\n ),\n ])\n if (result && typeof result === 'object') {\n // Accept whatever the primitive returned; the kit's\n // IntrospectionSnapshot is opt-in typed via the kit, not enforced\n // at this layer (see plugin.ts / adapter.ts comment about avoiding\n // a runtime dep on the kit).\n const snap = result as Partial<IntrospectionSnapshot>\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: snap.name ?? name,\n kind: snap.kind ?? kind,\n version: snap.version,\n state: snap.state,\n tokens: snap.tokens,\n metrics: snap.metrics,\n memoryBytes: snap.memoryBytes,\n }\n }\n return stub\n } catch (err) {\n errors.push({\n name,\n kind,\n message: err instanceof Error ? err.message : String(err),\n })\n return stub\n }\n}\n\n/** Read DI registrations into the topology shape — drops noisy HMR tokens. */\nfunction collectTokens(container: Container): TopologyTokenEntry[] {\n return container\n .getRegistrations()\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n token: r.token,\n scope: r.scope,\n kind: r.kind,\n instantiated: r.instantiated,\n }))\n}\n\n/**\n * Contributor enumeration. Prefers `app.getContributors()` (the\n * Application-level walk that preserves adapter / plugin / global\n * source labels) when present; falls back to walking\n * `adapter.contributors()` + `plugin.contributors()` directly for\n * older Application implementations that don't expose the helper.\n *\n * Module-level contributors are still not surfaced here — module\n * instances aren't retained post-bootstrap. Per-route enumeration\n * lands in a later iteration alongside the route detail panel.\n */\nfunction collectContributors(app: TopologyApplicationLike): TopologyContributorEntry[] {\n const seen = new Map<string, TopologyContributorEntry>()\n\n if (typeof app.getContributors === 'function') {\n for (const c of app.getContributors()) {\n if (seen.has(c.key)) continue\n // Pass `source` through unchanged — the kit's\n // `TopologyContributorSource` union accepts every value the\n // framework's `getContributors()` returns. Earlier versions\n // collapsed `'plugin' | 'global'` → `'adapter'` because the kit\n // type was narrower; that's no longer needed.\n seen.set(c.key, {\n key: c.key,\n source: c.source as TopologyContributorEntry['source'],\n dependsOn: c.dependsOn as string[],\n })\n }\n return [...seen.values()]\n }\n\n // Legacy path — direct walk.\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: TopologyContributorEntry['source'],\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: string; dependsOn?: readonly string[] }\n const key = typeof r.key === 'string' ? r.key : null\n if (!key || seen.has(key)) continue\n seen.set(key, {\n key,\n source,\n dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : [],\n })\n }\n }\n\n for (const plugin of app.getPlugins()) {\n ingest(plugin.contributors?.(), 'adapter')\n }\n for (const adapter of app.getAdapters()) {\n ingest(adapter.contributors?.(), 'adapter')\n }\n\n return [...seen.values()]\n}\n","/**\n * Custom-tab aggregator — collects every plugin/adapter's\n * `devtoolsTabs()` contribution into a single deduped list for the\n * panel's `/_debug/tabs` endpoint.\n *\n * Validation is permissive: anything that doesn't look like a\n * {@link DevtoolsTabDescriptor} is dropped with a console warning\n * rather than throwing — a misconfigured adapter shouldn't break the\n * whole DevTools panel.\n *\n * @module @forinda/kickjs-devtools/devtools-tabs\n */\n\nimport type { DevtoolsTabDescriptor } from '@forinda/kickjs-devtools-kit'\nimport type { TopologyApplicationLike } from './topology'\n\n/** Result of {@link collectDevtoolsTabs}. */\nexport interface DevtoolsTabsResult {\n /** Deduped, validated tabs in registration order. */\n tabs: DevtoolsTabDescriptor[]\n /** Per-source collection errors (drop reason, source name). */\n errors: ReadonlyArray<{ source: string; reason: string }>\n}\n\nconst VALID_VIEW_TYPES = new Set(['iframe', 'launch', 'html'])\n\n/**\n * Walk every plugin + adapter, call `devtoolsTabs?()`, validate each\n * entry, and dedupe by `id`. Last-source-wins on collision is too\n * surprising — first-source-wins + a warning entry instead.\n */\nexport function collectDevtoolsTabs(app: TopologyApplicationLike): DevtoolsTabsResult {\n const tabs: DevtoolsTabDescriptor[] = []\n const seen = new Map<string, string>() // id → source name (for collision warnings)\n const errors: Array<{ source: string; reason: string }> = []\n\n const ingest = (sourceName: string, raw: unknown): void => {\n if (!Array.isArray(raw)) {\n errors.push({ source: sourceName, reason: 'devtoolsTabs() did not return an array' })\n return\n }\n for (const entry of raw) {\n const validation = validateTab(entry)\n if (!validation.ok) {\n errors.push({ source: sourceName, reason: validation.reason })\n continue\n }\n const tab = validation.tab\n const owner = seen.get(tab.id)\n if (owner) {\n errors.push({\n source: sourceName,\n reason: `tab id '${tab.id}' already registered by ${owner} — first-source wins`,\n })\n continue\n }\n seen.set(tab.id, sourceName)\n tabs.push(tab)\n }\n }\n\n for (const plugin of app.getPlugins()) {\n if (typeof plugin.devtoolsTabs !== 'function') continue\n try {\n ingest(plugin.name ?? '(unnamed plugin)', plugin.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: plugin.name ?? '(unnamed plugin)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n for (const adapter of app.getAdapters()) {\n if (typeof adapter.devtoolsTabs !== 'function') continue\n try {\n ingest(adapter.name ?? '(unnamed adapter)', adapter.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: adapter.name ?? '(unnamed adapter)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return { tabs, errors }\n}\n\ninterface ValidationOk {\n ok: true\n tab: DevtoolsTabDescriptor\n}\n\ninterface ValidationFail {\n ok: false\n reason: string\n}\n\n/**\n * Coerce + validate a tab descriptor. Returns the typed object on\n * success; a structured reason on failure. Uses a permissive checker\n * so a partially-correct entry from a third-party adapter doesn't\n * break the whole panel.\n */\nfunction validateTab(raw: unknown): ValidationOk | ValidationFail {\n if (!raw || typeof raw !== 'object') {\n return { ok: false, reason: 'tab entry is not an object' }\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.id !== 'string' || obj.id.length === 0) {\n return { ok: false, reason: 'tab.id must be a non-empty string' }\n }\n if (typeof obj.title !== 'string' || obj.title.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': title must be a non-empty string` }\n }\n const view = obj.view as Record<string, unknown> | undefined\n if (!view || typeof view !== 'object') {\n return { ok: false, reason: `tab '${obj.id}': view object is required` }\n }\n if (typeof view.type !== 'string' || !VALID_VIEW_TYPES.has(view.type)) {\n return {\n ok: false,\n reason: `tab '${obj.id}': view.type must be one of iframe / launch / html`,\n }\n }\n switch (view.type) {\n case 'iframe':\n if (typeof view.src !== 'string' || view.src.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': iframe view requires a non-empty src` }\n }\n break\n case 'html':\n if (typeof view.html !== 'string') {\n return { ok: false, reason: `tab '${obj.id}': html view requires html string` }\n }\n break\n case 'launch':\n if (!Array.isArray(view.actions)) {\n return { ok: false, reason: `tab '${obj.id}': launch view requires actions array` }\n }\n break\n }\n return { ok: true, tab: obj as unknown as DevtoolsTabDescriptor }\n}\n","// Server-side KickEventBus implementation.\n//\n// Wraps the bus core from `@forinda/kickjs-devtools-kit/bus` with a\n// `ws` server bound to a path on the framework's existing\n// `http.Server`. Architecture:\n//\n// server.on('upgrade') ─┐\n// ├──► WebSocketServer.handleUpgrade()\n// │ └─► ws clients: receive emits as JSON\n// bus.emit(type, payload) ─┴──► serialize → fan out to clients +\n// dispatch locally to in-process subs\n//\n// Why piggyback on the framework's http.Server instead of starting a\n// dedicated WS server: the framework already owns the listener, the\n// upgrade event is the canonical hook, and reusing it means devtools\n// inherits whatever TLS / proxy / port config the application provides.\n//\n// Lifecycle:\n// - createServerBus() builds the WebSocketServer in `noServer: true`\n// mode (no listener of its own) and returns the bus + attach/close\n// handles.\n// - attachUpgrade(httpServer) wires server.on('upgrade') so upgrades\n// matching `wsPath` route into the WebSocketServer. Other upgrade\n// paths (kickjs-ws, etc.) ignore us by virtue of path matching.\n// - close() drops every client and detaches from the http server so\n// repeated dev-mode restarts don't leak listener handles.\n//\n// Authentication:\n// - The optional `secret` matches the devtools panel's existing\n// `x-devtools-token` / `?token=` access guard. When set, upgrades\n// without the right token get rejected at HTTP-handshake time —\n// never reaching the bus.\n//\n// Loop avoidance:\n// - Server emits fan out to every connected client. Client-side\n// emits sent UP the socket dispatch into the local core (so\n// server tabs can react) but are NOT re-broadcast to other\n// clients. This keeps the same \"no echo\" contract the browser\n// bus enforces; without it a tab's emit would round-trip through\n// the server and back to itself.\n\nimport type { IncomingMessage } from 'node:http'\nimport type http from 'node:http'\nimport type { Socket } from 'node:net'\n\nimport { createBusCore } from '@forinda/kickjs-devtools-kit/bus'\nimport type { KickDevtoolsEvent, KickEventBus, Unsubscribe } from '@forinda/kickjs-devtools-kit/bus'\nimport { WebSocketServer, type WebSocket } from 'ws'\n\nexport interface ServerBusOptions {\n /** Path the WebSocket upgrade listens on. Default `/_debug/_bus`. */\n wsPath?: string\n /**\n * Optional shared secret. When set, clients must include either\n * `?token=<secret>` on the upgrade URL or an\n * `x-devtools-token: <secret>` header. Unauthorized upgrades return\n * 401 and never reach the bus. Pass `false` (or omit) to disable.\n */\n secret?: string | false\n}\n\ninterface TaggedEnvelope extends KickDevtoolsEvent {\n __kick_origin?: 'local' | 'broadcast' | 'ws'\n}\n\nexport interface ServerBus extends KickEventBus {\n /** Hook into an existing http.Server's `upgrade` event. */\n attachUpgrade(httpServer: http.Server): void\n /** Drop all clients + detach. Idempotent. */\n close(): void\n /** Currently connected client count. Useful for the devtools health card. */\n clientCount(): number\n}\n\nexport function createServerBus(opts: ServerBusOptions = {}): ServerBus {\n const wsPath = opts.wsPath ?? '/_debug/_bus'\n const secret = opts.secret ?? false\n const core = createBusCore()\n const wss = new WebSocketServer({ noServer: true })\n const clients = new Set<WebSocket>()\n let attachedServer: http.Server | null = null\n let upgradeHandler: ((req: IncomingMessage, socket: Socket, head: Buffer) => void) | null = null\n\n wss.on('connection', (ws: WebSocket) => {\n clients.add(ws)\n ws.on('message', (data: Buffer | string) => {\n try {\n const text = typeof data === 'string' ? data : data.toString('utf-8')\n const parsed = JSON.parse(text) as TaggedEnvelope\n if (!parsed || typeof parsed.type !== 'string' || typeof parsed.ts !== 'number') return\n // Dispatch locally only — never echo back to other clients.\n // (Tabs that need cross-tab fan-out use BroadcastChannel; the\n // server is point-to-point per client.)\n core.dispatch({ ...parsed, __kick_origin: 'ws' } as KickDevtoolsEvent)\n } catch {\n // Malformed — drop silently. A misbehaving tab shouldn't\n // crash the server bus.\n }\n })\n ws.on('close', () => {\n clients.delete(ws)\n })\n ws.on('error', () => {\n clients.delete(ws)\n })\n })\n\n const fanOut = (envelope: TaggedEnvelope): void => {\n if (clients.size === 0) return\n const text = JSON.stringify(envelope)\n for (const client of clients) {\n // OPEN === 1 in the ws spec; reusing the import for the type\n // guard keeps this readable without pulling in WebSocket consts.\n if (client.readyState === client.OPEN) {\n try {\n client.send(text)\n } catch {\n // Network error mid-fan-out — clean removal happens via the\n // 'close' / 'error' handlers; nothing to do here.\n }\n }\n }\n }\n\n const checkAuth = (req: IncomingMessage): boolean => {\n if (secret === false) return true\n const header = req.headers['x-devtools-token']\n if (typeof header === 'string' && header === secret) return true\n // Parse query — `req.url` is path + ?query for upgrade requests.\n const url = req.url ?? ''\n const queryIdx = url.indexOf('?')\n if (queryIdx === -1) return false\n const params = new URLSearchParams(url.slice(queryIdx + 1))\n return params.get('token') === secret\n }\n\n const attachUpgrade = (httpServer: http.Server): void => {\n if (attachedServer) return // idempotent\n attachedServer = httpServer\n upgradeHandler = (req, socket, head) => {\n // Path match — ignore upgrades destined for other adapters\n // (kickjs-ws, custom adapters, etc.). They register their own\n // upgrade handlers; ours just no-ops on non-matching URLs.\n const url = req.url ?? ''\n const pathOnly = url.split('?')[0]\n if (pathOnly !== wsPath) return\n\n if (!checkAuth(req)) {\n socket.write('HTTP/1.1 401 Unauthorized\\r\\n\\r\\n')\n socket.destroy()\n return\n }\n\n wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {\n wss.emit('connection', ws, req)\n })\n }\n httpServer.on('upgrade', upgradeHandler)\n }\n\n const close = (): void => {\n if (attachedServer && upgradeHandler) {\n attachedServer.off('upgrade', upgradeHandler)\n }\n attachedServer = null\n upgradeHandler = null\n for (const client of clients) {\n try {\n client.close()\n } catch {\n // ignore\n }\n }\n clients.clear()\n wss.close()\n }\n\n return {\n on(type: string, handler: (payload: unknown) => void): Unsubscribe {\n return core.on(type, handler)\n },\n onAny(handler: (event: KickDevtoolsEvent) => void): Unsubscribe {\n return core.onAny(handler)\n },\n emit(type: string, payload: unknown): void {\n const envelope: TaggedEnvelope = {\n type,\n payload,\n ts: Date.now(),\n __kick_origin: 'local',\n }\n core.dispatch(envelope)\n fanOut(envelope)\n },\n attachUpgrade,\n close,\n clientCount: () => clients.size,\n } as ServerBus\n}\n","import type { Request, Response, NextFunction, RequestHandler } from 'express'\nimport { static as serveStatic } from 'express'\nimport { dirname, join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { createReadStream, existsSync, readFileSync, statSync, unlink } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { writeHeapSnapshot } from 'node:v8'\nimport {\n type AdapterMiddleware,\n type Container,\n METADATA,\n defineAdapter,\n ref,\n computed,\n reactive,\n watch,\n createLogger,\n type Ref,\n type ComputedRef,\n getClassMeta,\n getMethodMeta,\n getRouteFlags,\n} from '@forinda/kickjs'\nimport {\n MemoryAnalyzer,\n PROTOCOL_VERSION,\n RuntimeSampler,\n type IntrospectionSnapshot,\n} from '@forinda/kickjs-devtools-kit'\nimport { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\nimport { collectTopologySnapshot, type TopologyApplicationLike } from './topology'\nimport { collectDevtoolsTabs } from './devtools-tabs'\nimport { createServerBus, type ServerBus } from './bus/server'\n\nconst log = createLogger('DevTools')\n\n/** Route metadata collected during mount */\ninterface RouteInfo {\n method: string\n path: string\n controller: string\n handler: string\n middleware: string[]\n /**\n * Route flags in force, resolved method-over-class. Present so the dashboard\n * can answer \"why is this endpoint not requiring auth\" from the route list\n * itself, rather than by reading the controller.\n */\n flags: Record<string, unknown>\n}\n\n/** Per-route latency stats with percentile tracking */\ninterface RouteStats {\n count: number\n totalMs: number\n minMs: number\n maxMs: number\n /** Ring buffer of last N samples for percentile computation */\n samples: number[]\n}\n\nconst MAX_SAMPLES = 1000\n\n/** Compute a percentile from a sorted array of numbers */\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.ceil(p * sorted.length) - 1\n return sorted[Math.max(0, idx)]\n}\n\n/** Compute p50, p95, p99 from a RouteStats samples buffer */\nfunction computePercentiles(stats: RouteStats): { p50: number; p95: number; p99: number } {\n const sorted = [...stats.samples].toSorted((a, b) => a - b)\n return {\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n }\n}\n\n/**\n * Open an SSE response — sets the headers, flushes them, and disables\n * any compression middleware that may have been registered upstream\n * (compression buffers SSE chunks indefinitely; we need flush-on-write).\n */\nfunction openSseStream(req: Request, res: Response): void {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n res.flushHeaders?.()\n // Defensive: the compression middleware checks this header. Some\n // setups also wrap res.write — calling res.flush after each write\n // is safe even when no compression is in play.\n void req\n}\n\n/** Write a single SSE `data:` event with a JSON payload + double newline. */\nfunction writeSseEvent(res: Response, payload: unknown): void {\n res.write(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\n/**\n * Race a promise against a timeout. Clears the timer when the inner\n * promise wins so we don't leak handles every time a peer responds\n * quickly. Used to bound peer `onHealthCheck()` calls inside the\n * `/_debug/health` handler — one slow peer must not be able to stall\n * the dashboard request.\n */\nfunction raceWithTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)\n })\n return Promise.race([promise, timeout]).finally(() => {\n if (timer) clearTimeout(timer)\n })\n}\n\n/**\n * Per-peer budget for `onHealthCheck()` inside `/_debug/health`.\n * Long enough for a typical DB ping or remote check, short enough that\n * one misbehaving adapter can't stall the dashboard endpoint.\n */\nconst PEER_HEALTHCHECK_TIMEOUT_MS = 1500\n\n/**\n * Module-scoped guard for `POST /_debug/memory/snapshot`. `writeHeapSnapshot()`\n * blocks the event loop for the duration of the capture (multi-second\n * for large heaps); two concurrent captures would compound the pause.\n * The endpoint returns 503 + a hint message when this flag is set so\n * the SPA can surface a \"snapshot already running\" warning rather than\n * silently queueing.\n *\n * Module-scoped (not per-adapter-instance) because writeHeapSnapshot\n * acts on the V8 process — multiple DevToolsAdapter instances would\n * still race at the v8 layer.\n */\nlet snapshotInProgress = false\n\nexport interface DevToolsOptions {\n /** Base path for debug endpoints (default: '/_debug') */\n basePath?: string\n /** Only enable when this is true (default: process.env.NODE_ENV !== 'production') */\n enabled?: boolean\n /** Include environment variables (sanitized) at /_debug/config (default: false) */\n exposeConfig?: boolean\n /** Env var prefixes to expose (default: ['APP_', 'NODE_ENV']). Others are redacted. */\n configPrefixes?: string[]\n /** Callback when error rate exceeds threshold */\n onErrorRateExceeded?: (rate: number) => void\n /** Error rate threshold (default: 0.5 = 50%) */\n errorRateThreshold?: number\n /** Other adapters to discover stats from (e.g., WsAdapter) */\n adapters?: any[]\n\n /**\n * Secret token to guard DevTools access. When set, all requests must\n * include this token as `x-devtools-token` header or `?token=` query param.\n *\n * Auto-generated on startup if not provided. The token is logged to the console.\n * Set to `false` to disable the guard entirely (not recommended).\n *\n * @example\n * ```ts\n * DevToolsAdapter({ secret: getEnv('DEVTOOLS_SECRET') })\n * ```\n */\n secret?: string | false\n\n /**\n * Tuning for the runtime sampler that powers `/_debug/runtime` and\n * the upcoming Memory tab (architecture.md §23). Defaults to\n * 1-second polling with a 60-sample (~1 minute) ring buffer.\n *\n * Set `runtime.enabled = false` to skip starting the sampler — the\n * `/_debug/runtime` endpoint then returns 404 instead of an empty\n * snapshot, signalling deliberate opt-out rather than a startup race.\n */\n runtime?: {\n /** Whether to start the runtime sampler at all. Default: true. */\n enabled?: boolean\n /** Polling interval in milliseconds. Default: 1000. */\n intervalMs?: number\n /** Ring-buffer size — number of past samples retained. Default: 60. */\n bufferSize?: number\n }\n}\n\n/**\n * Public reactive surface exposed by a DevToolsAdapter instance —\n * counters, computed metrics, and the route latency map. Tests and\n * peer adapters consume these directly to drive their own behavior.\n */\nexport interface DevToolsAdapterExtensions {\n /** Total requests received. */\n readonly requestCount: Ref<number>\n /** Total responses with status >= 500. */\n readonly errorCount: Ref<number>\n /** Total responses with status >= 400 and < 500. */\n readonly clientErrorCount: Ref<number>\n /** Server start time. */\n readonly startedAt: Ref<number>\n /** Computed error rate (server errors / total requests). */\n readonly errorRate: ComputedRef<number>\n /** Computed uptime in seconds. */\n readonly uptimeSeconds: ComputedRef<number>\n /** Per-route latency tracking. */\n readonly routeLatency: Record<string, RouteStats>\n /**\n * Tier-1 runtime sampler from `@forinda/kickjs-devtools-kit`. `null`\n * when `runtime.enabled` is `false`. Tests can `latest()` and\n * `history()` directly without going through the HTTP endpoint.\n */\n readonly runtimeSampler: RuntimeSampler | null\n /**\n * Memory analyzer fed by the runtime sampler. `null` when the\n * sampler is disabled. Use `analyzer.health(sampler.history())` to\n * compose a composite memory-health snapshot.\n */\n readonly memoryAnalyzer: MemoryAnalyzer | null\n}\n\n/**\n * DevToolsAdapter — Vue-style reactive introspection for KickJS applications.\n *\n * Exposes debug endpoints powered by reactive state (ref, computed, watch):\n * - `GET /_debug/routes` — all registered routes with middleware\n * - `GET /_debug/container` — DI registry with scopes and instantiation status\n * - `GET /_debug/metrics` — live request/error counts, error rate, uptime\n * - `GET /_debug/health` — deep health check with adapter status\n * - `GET /_debug/config` — sanitized environment variables (opt-in)\n * - `GET /_debug/state` — full reactive state snapshot\n *\n * @example\n * ```ts\n * import { DevToolsAdapter } from '@forinda/kickjs-devtools'\n *\n * bootstrap({\n * modules: [UserModule],\n * adapters: [\n * DevToolsAdapter({\n * enabled: process.env.NODE_ENV !== 'production',\n * exposeConfig: true,\n * configPrefixes: ['APP_', 'DATABASE_'],\n * }),\n * ],\n * })\n * ```\n */\nexport const DevToolsAdapter = defineAdapter<DevToolsOptions, DevToolsAdapterExtensions>({\n name: 'DevToolsAdapter',\n defaults: {\n basePath: '/_debug',\n errorRateThreshold: 0.5,\n exposeConfig: false,\n configPrefixes: ['APP_', 'NODE_ENV'],\n },\n build: (options) => {\n const basePath = options.basePath!\n const enabled = options.enabled ?? process.env.NODE_ENV !== 'production'\n const exposeConfig = options.exposeConfig!\n const configPrefixes = options.configPrefixes!\n const errorRateThreshold = options.errorRateThreshold!\n const peerAdapters = options.adapters ?? []\n\n // Secret token guard\n let secret: string | false\n if (options.secret === false) {\n secret = false\n } else if (options.secret) {\n secret = options.secret\n } else {\n secret = randomBytes(16).toString('hex')\n }\n\n // ── Runtime sampler + memory analyzer (kit) ────────────────────\n // Lazily instantiated so an adopter that disables runtime monitoring\n // doesn't pay the perf_hooks histogram cost. Lifecycle: start in\n // `beforeMount`, stop in `shutdown`.\n const runtimeEnabled = options.runtime?.enabled ?? true\n const runtimeSampler = runtimeEnabled\n ? new RuntimeSampler({\n intervalMs: options.runtime?.intervalMs ?? 1000,\n bufferSize: options.runtime?.bufferSize ?? 60,\n })\n : null\n const memoryAnalyzer = runtimeEnabled ? new MemoryAnalyzer() : null\n\n // ── Server-side event bus ──────────────────────────────────────\n // Lazily resolved in `beforeMount` — when the devtools adapter is\n // rebuilt during HMR, the same `Container` may already hold a bus\n // from a previous mount with live WebSocket clients + in-flight\n // subscriptions. Creating a fresh bus on every rebuild would\n // silently swap the registered instance, leaving plugins that\n // already captured the old reference publishing into a dead bus.\n // Using `container.has(DEVTOOLS_BUS)` to reuse instead keeps event\n // delivery stable across rebuilds.\n //\n // When the devtools adapter is disabled (`enabled === false`) we\n // register a no-op stub instead so adopters who Inject(DEVTOOLS_BUS)\n // under @Optional() get a callable instance rather than undefined.\n let bus: ServerBus | null = null\n\n const ensureBus = (container: Container): ServerBus => {\n if (container.has(DEVTOOLS_BUS)) {\n // The token is typed `KickEventBus` but the registered instance\n // is the wider `ServerBus` (KickEventBus + attachUpgrade /\n // close / clientCount). Explicit generic on resolve avoids the\n // structural-cast — Container.resolve's last overload accepts\n // an explicit T and returns it.\n bus = container.resolve<ServerBus>(DEVTOOLS_BUS)\n return bus\n }\n bus = enabled\n ? createServerBus({\n wsPath: `${basePath}/_bus`,\n secret: secret === false ? false : secret,\n })\n : ({\n on: () => () => {},\n onAny: () => () => {},\n emit: () => {},\n attachUpgrade: () => {},\n close: () => {},\n clientCount: () => 0,\n } as ServerBus)\n container.registerInstance(DEVTOOLS_BUS, bus)\n return bus\n }\n\n // ── Reactive state ─────────────────────────────────────────────\n const requestCount = ref(0)\n const errorCount = ref(0)\n const clientErrorCount = ref(0)\n // App mount timestamp — kept for reference, but uptime is derived from the\n // node process (see below) so it survives HMR rebuilds.\n const startedAt = ref(Date.now())\n const routeLatency = reactive<Record<string, RouteStats>>({})\n\n const errorRate = computed(() =>\n requestCount.value > 0 ? errorCount.value / requestCount.value : 0,\n )\n\n // Uptime is the NODE PROCESS uptime, not \"time since beforeMount\". In dev,\n // `beforeMount` re-runs on every HMR rebuild / SSR re-bootstrap, which used\n // to reset `startedAt` and pin uptime near 0s. `process.uptime()` is\n // monotonic from process start, so it reports the real server uptime across\n // reloads. `tick` makes the computed re-evaluate when the reactive graph\n // refreshes; the value itself comes from the live process clock.\n const uptimeSeconds = computed(() => {\n void startedAt.value // keep the dependency so DevTools polls re-read it\n return Math.floor(process.uptime())\n })\n\n // ── Internal mutable state ─────────────────────────────────────\n let routes: RouteInfo[] = []\n let container: Container | null = null\n let appRef: any = null\n const adapterStatuses: Record<string, string> = {}\n let stopErrorWatch: (() => void) | null = null\n\n // Watch error rate — log warnings when elevated\n if (options.onErrorRateExceeded) {\n const callback = options.onErrorRateExceeded\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n callback(rate)\n }\n })\n } else {\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n log.warn(`Error rate elevated: ${(rate * 100).toFixed(1)}%`)\n }\n })\n }\n\n /**\n * Find the dashboard's public directory. Prefers the new Solid SPA\n * (public/spa/, shipped from PR 4 of §23); falls back to the legacy\n * Vue+Tailwind dashboard (public/devtools/) for environments that\n * haven't run `pnpm --filter @forinda/kickjs-devtools build:spa`.\n */\n const resolvePublicDir = (): string | null => {\n const thisDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(thisDir, '..', 'public', 'spa'), // dist/ -> public/spa\n join(thisDir, '..', '..', 'public', 'spa'), // src/ -> public/spa\n join(thisDir, '..', 'public', 'devtools'), // legacy Vue dashboard\n join(thisDir, '..', '..', 'public', 'devtools'), // legacy from src/\n ]\n for (const dir of candidates) {\n if (existsSync(join(dir, 'index.html'))) return dir\n }\n return null\n }\n\n /**\n * Resolve peer adapters at request time. Prefers live adapters from the\n * Application registry (survives HMR rebuild) and falls back to the\n * constructor-provided refs.\n */\n const getPeerAdapters = (): any[] => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getAdapters === 'function') {\n return kickApp.getAdapters()\n }\n return peerAdapters\n }\n\n /**\n * Active HTTP runtime identity + capabilities (`express` | `fastify` | `h3`),\n * read from the Application via `getActiveRuntime()`. Returns `null` when the\n * framework is older than the getter (graceful for mixed versions). Lets the\n * dashboard show which engine the app is running on.\n */\n const readActiveRuntime = (): {\n name: string\n capabilities: Record<string, boolean>\n } | null => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getActiveRuntime === 'function') {\n try {\n return kickApp.getActiveRuntime()\n } catch {\n return null\n }\n }\n return null\n }\n\n return {\n // ── Extensions (TExtra) ───────────────────────────────────────\n requestCount,\n errorCount,\n clientErrorCount,\n startedAt,\n errorRate,\n uptimeSeconds,\n routeLatency,\n runtimeSampler,\n memoryAnalyzer,\n\n // ── DevTools introspection (architecture.md §23) ─────────────\n // Cheap snapshot — counters + flags only. Anything that requires\n // a container walk or DB hit belongs in the per-endpoint RPCs\n // (`/_debug/container`, `/_debug/graph`), not here.\n introspect(): IntrospectionSnapshot {\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: 'DevToolsAdapter',\n kind: 'adapter',\n state: {\n basePath,\n enabled,\n runtimeEnabled,\n secret: secret === false ? false : 'present',\n },\n metrics: {\n requestCount: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n uptimeSeconds: uptimeSeconds.value,\n routesTracked: routes.length,\n },\n }\n },\n\n // ── Lifecycle ─────────────────────────────────────────────────\n\n beforeMount({ app, http, container: containerArg }) {\n if (!enabled) return\n\n appRef = app\n container = containerArg\n // Lazy resolve — reuses the existing bus when the same\n // container is reused across HMR rebuilds, otherwise creates\n // and registers a fresh instance. See `ensureBus` for why.\n ensureBus(containerArg)\n startedAt.value = Date.now()\n // Clear routes on rebuild/restart to prevent HMR duplication\n routes = []\n adapterStatuses['DevToolsAdapter'] = 'running'\n\n // Start the runtime sampler + memory analyzer here (rather than\n // at construction) so test harnesses that build the adapter but\n // never mount it don't leak interval timers.\n runtimeSampler?.start()\n memoryAnalyzer?.start()\n\n // Register dashboard routes through the engine-agnostic HTTP facade\n // (`ctx.http`) instead of an Express Router, so devtools no longer\n // depends on the raw Express app for mounting. The `router` shim keeps\n // every existing `(req, res)` handler verbatim — `req` / `res` are the\n // engine-native request/response under the default runtime.\n //\n // `use()` scopes the middleware to `basePath` (Express strips the\n // prefix, so the guard still sees router-relative `req.path`). `get` /\n // `post` register the prefixed path; the dashboard root (`'/'`) maps to\n // `basePath` itself, matching the old `router.get('/')` at the mount.\n const joinBase = (p: string): string => (p === '/' ? basePath : `${basePath}${p}`)\n const router = {\n use: (mw: RequestHandler): void => http.use(mw, { path: basePath }),\n get: (path: string, handler: (req: Request, res: Response) => unknown): void =>\n http.route('GET', joinBase(path), (ctx) => handler(ctx.req, ctx.res)),\n post: (path: string, handler: (req: Request, res: Response) => unknown): void =>\n http.route('POST', joinBase(path), (ctx) => handler(ctx.req, ctx.res)),\n }\n\n // ── Access guard — require secret token ──────────────────\n if (secret !== false) {\n const token = secret\n router.use((req: Request, res: Response, next: NextFunction) => {\n const provided = req.headers['x-devtools-token'] ?? req.query?.token\n if (provided === token) return next()\n // Allow the dashboard HTML itself (it will include the token in API calls)\n if (req.path === '/' && req.method === 'GET' && !req.query?.token) {\n return next() // serve dashboard, it handles auth via token\n }\n // Serve static assets for the dashboard (js files)\n if (req.path.endsWith('.js') || req.path.endsWith('.css')) {\n return next()\n }\n res.status(403).json({ error: 'Forbidden — invalid or missing devtools token' })\n })\n }\n\n router.get('/routes', (_req: Request, res: Response) => {\n res.json({ routes })\n })\n\n router.get('/container', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n res.json({ registrations, count: registrations.length })\n })\n\n router.get('/metrics', (_req: Request, res: Response) => {\n // Build latency with percentiles, omitting raw samples from response\n const latency: Record<string, any> = {}\n for (const [key, stats] of Object.entries(routeLatency)) {\n const { samples: _, ...rest } = stats\n latency[key] = { ...rest, ...computePercentiles(stats) }\n }\n res.json({\n requests: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n routeLatency: latency,\n })\n })\n\n router.get('/health', async (_req: Request, res: Response) => {\n const healthy = errorRate.value < errorRateThreshold\n const status = healthy ? 'healthy' : 'degraded'\n\n // Refresh peer statuses from `onHealthCheck()` when present.\n // The static `adapterStatuses` dict (seeded in `afterStart`)\n // proves a peer was mounted; calling `onHealthCheck()` here\n // upgrades that to a live `up`/`down`/`degraded` reading so\n // the Overview > Health card reflects actual adapter state,\n // not just \"registered at boot\".\n //\n // Each peer call is bounded by `PEER_HEALTHCHECK_TIMEOUT_MS` —\n // an adapter whose check hangs (network DB ping, remote\n // service, etc.) must not be able to stall the entire\n // dashboard request. Timed-out peers fall through to the\n // catch arm and are reported as `down`.\n const live: Record<string, string> = { ...adapterStatuses }\n await Promise.all(\n getPeerAdapters().map(async (peer) => {\n if (typeof peer?.onHealthCheck !== 'function') return\n const name: unknown = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') return\n try {\n const result = await raceWithTimeout(\n Promise.resolve(peer.onHealthCheck()),\n PEER_HEALTHCHECK_TIMEOUT_MS,\n `onHealthCheck(${name})`,\n )\n if (result && typeof result.status === 'string') {\n live[name] = result.status\n }\n } catch {\n live[name] = 'down'\n }\n }),\n )\n\n res.status(healthy ? 200 : 503).json({\n status,\n errorRate: errorRate.value,\n uptime: uptimeSeconds.value,\n runtime: readActiveRuntime(),\n adapters: live,\n })\n })\n\n router.get('/state', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n res.json({\n reactive: {\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n },\n routes: routes.length,\n container: container?.getRegistrations().length ?? 0,\n routeLatency,\n ...(wsAdapter ? { ws: wsAdapter.getStats() } : {}),\n })\n })\n\n // ── Tier-1 runtime monitoring (architecture.md §23) ─────────\n // Returns the latest RuntimeSnapshot + a composite MemoryHealth\n // computed from the sampler's ring buffer. Returns 404 when the\n // sampler is disabled so adopters can distinguish \"off\" from\n // \"starting up\".\n router.get('/runtime', (_req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled — set runtime.enabled = true' })\n return\n }\n const latest = runtimeSampler.latest()\n const history = runtimeSampler.history()\n const health = memoryAnalyzer.health(history)\n res.json({\n protocolVersion: PROTOCOL_VERSION,\n // Identity of the process these stats describe — every memory / CPU /\n // event-loop number below is for THIS Node process (the one running\n // your KickJS app), not the OS or any child. Lets the panel label it\n // unambiguously (\"Node v22 · pid 12345 · linux/x64 · engine: fastify\").\n process: {\n nodeVersion: process.version,\n pid: process.pid,\n platform: process.platform,\n arch: process.arch,\n runtime: readActiveRuntime(),\n },\n latest,\n history,\n health,\n })\n })\n\n // ── SSE: live runtime snapshots (architecture.md §23) ───────\n // Pushes the latest RuntimeSnapshot every `intervalMs`. SSE\n // (not WebSocket) avoids the http.Server `upgrade`-event\n // coordination cost — see devtools-flows.md §3 for rationale.\n router.get('/runtime/stream', (req: Request, res: Response) => {\n if (!runtimeSampler) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (snap) writeSseEvent(res, snap)\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── SSE: memory health composite (architecture.md §23) ──────\n router.get('/memory/stream', (req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (!snap) return\n const health = memoryAnalyzer.health(runtimeSampler.history())\n writeSseEvent(res, { snapshot: snap, health })\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── Heap snapshot — Tier 3 monitoring (architecture.md §23) ─\n // POST /_debug/memory/snapshot — captures a V8 heap snapshot\n // and streams the resulting .heapsnapshot file back as\n // application/json with Content-Disposition. Snapshot capture\n // blocks the event loop while writing (multi-second pause for\n // large heaps), so the endpoint enforces single-flight via a\n // module-scoped flag — concurrent calls return 503.\n //\n // The temp file is deleted as soon as the response stream\n // completes (success or error). Worst case if the process\n // dies mid-snapshot is a stranded file in `os.tmpdir()`,\n // which the OS cleans up on next boot.\n router.post('/memory/snapshot', (_req: Request, res: Response) => {\n if (snapshotInProgress) {\n res\n .status(503)\n .json({ error: 'heap snapshot already in progress — wait for it to complete' })\n return\n }\n snapshotInProgress = true\n const startedAt = Date.now()\n const filename = `kickjs-heap-${new Date().toISOString().replace(/[:.]/g, '-')}.heapsnapshot`\n const targetPath = join(tmpdir(), filename)\n\n let written: string\n try {\n // writeHeapSnapshot is synchronous — the event loop is\n // blocked for the duration. There's no async variant in\n // the v8 module today; if one ships, swap here.\n written = writeHeapSnapshot(targetPath)\n } catch (err) {\n snapshotInProgress = false\n log.error({ err }, 'heap snapshot capture failed')\n res\n .status(500)\n .json({ error: 'snapshot capture failed', message: (err as Error).message })\n return\n }\n\n let size = 0\n try {\n size = statSync(written).size\n } catch {\n /* size header is best-effort */\n }\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Heap snapshot captured: ${written} (${(size / 1024 / 1024).toFixed(1)} MiB in ${elapsedMs}ms)`,\n )\n\n res.setHeader('Content-Type', 'application/json')\n res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n if (size > 0) res.setHeader('Content-Length', String(size))\n res.setHeader('X-Snapshot-Capture-Ms', String(elapsedMs))\n\n const cleanup = (): void => {\n unlink(written, (err) => {\n if (err) log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`)\n snapshotInProgress = false\n })\n }\n const stream = createReadStream(written)\n stream.on('end', cleanup)\n stream.on('error', (err) => {\n log.error({ err }, 'heap snapshot stream failed')\n if (!res.headersSent) res.status(500).end()\n cleanup()\n })\n // Defensive: if the client disconnects mid-download, abort\n // the stream + run cleanup so the temp file doesn't linger.\n res.on('close', () => {\n stream.destroy()\n // If the stream already fired 'end', cleanup already ran\n // — the unlink is idempotent enough that running twice\n // just yields ENOENT which we ignore in cleanup.\n })\n stream.pipe(res)\n })\n\n // ── Force GC — Tier 3 monitoring (architecture.md §23) ──────\n // POST /_debug/memory/gc — calls `global.gc()` if Node was\n // started with --expose-gc, returning before/after heap size\n // so the panel can show how much was reclaimed. Useful for\n // confirming \"is this growth real or just delayed GC?\".\n //\n // Returns 412 Precondition Failed (with hint) when the flag\n // wasn't set, so the SPA can show \"Run with --expose-gc to\n // enable this button\" instead of a generic 5xx.\n router.post('/memory/gc', (_req: Request, res: Response) => {\n const gc = (globalThis as { gc?: () => void }).gc\n if (typeof gc !== 'function') {\n res.status(412).json({\n error: 'global.gc unavailable — start Node with --expose-gc to enable this endpoint',\n })\n return\n }\n const before = process.memoryUsage().heapUsed\n const startedAt = Date.now()\n try {\n gc()\n } catch (err) {\n res.status(500).json({\n error: 'forced GC failed',\n message: err instanceof Error ? err.message : String(err),\n })\n return\n }\n const after = process.memoryUsage().heapUsed\n const reclaimedBytes = Math.max(0, before - after)\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Forced GC reclaimed ${(reclaimedBytes / 1024 / 1024).toFixed(2)} MiB in ${elapsedMs}ms`,\n )\n res.json({ before, after, reclaimedBytes, elapsedMs })\n })\n\n // ── Custom-tab discovery (architecture.md §23) ──────────────\n // Walks every plugin/adapter `devtoolsTabs?()` contribution\n // and serves the deduped + validated list. The SPA fetches\n // this once at boot to render dynamic tabs after the four\n // built-ins.\n router.get('/tabs', (_req: Request, res: Response) => {\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res.status(503).json({ error: 'tabs unavailable — application surface not exposed' })\n return\n }\n res.json(collectDevtoolsTabs(kickApp))\n })\n\n // ── Topology RPC (architecture.md §23) ──────────────────────\n // Aggregates plugins + adapters + contributors + DI tokens\n // into one snapshot; calls each primitive's introspect() in\n // parallel with a per-call timeout so a misbehaving adapter\n // can't block the endpoint. Errors are collected, not thrown.\n router.get('/topology', async (_req: Request, res: Response) => {\n if (!container) {\n res.status(503).json({ error: 'topology unavailable — container not bound yet' })\n return\n }\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res\n .status(503)\n .json({ error: 'topology unavailable — application surface not exposed' })\n return\n }\n try {\n const snapshot = await collectTopologySnapshot({ app: kickApp, container })\n res.json(snapshot)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({ error: 'topology collection failed', message })\n }\n })\n\n router.get('/ws', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n if (!wsAdapter) {\n res.json({ enabled: false, message: 'WsAdapter not found' })\n return\n }\n res.json({ enabled: true, ...wsAdapter.getStats() })\n })\n\n router.get('/queues', async (_req: Request, res: Response) => {\n const queueAdapter = getPeerAdapters().find(\n (a) => a.name === 'QueueAdapter' && typeof a.getQueueNames === 'function',\n )\n if (!queueAdapter) {\n res.json({ enabled: false, message: 'QueueAdapter not found' })\n return\n }\n try {\n const names: string[] = queueAdapter.getQueueNames?.() ?? []\n const queues: any[] = []\n for (const name of names) {\n const stats = await queueAdapter.getQueueStats?.(name)\n queues.push({ name, ...stats })\n }\n res.json({ enabled: true, queues })\n } catch {\n res.json({ enabled: true, queues: [], error: 'Failed to fetch queue stats' })\n }\n })\n\n // ── Dependency graph ────────────────────────────────────────\n router.get('/graph', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n const nodes = registrations\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n id: r.token,\n kind: r.kind,\n scope: r.scope,\n resolveCount: r.resolveCount,\n }))\n const nodeIds = new Set(nodes.map((n) => n.id))\n const edges: Array<{ from: string; to: string }> = []\n for (const r of registrations) {\n if (r.token.startsWith('__hmr__')) continue\n for (const dep of r.dependencies) {\n if (nodeIds.has(dep)) {\n edges.push({ from: r.token, to: dep })\n }\n }\n }\n res.json({ nodes, edges })\n })\n\n // ── SSE stream for real-time updates ────────────────────────\n router.get('/stream', (req: Request, res: Response) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n\n const sendMetrics = () => {\n const data = {\n type: 'metrics',\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n }\n res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n }\n sendMetrics()\n\n const unsubContainer = container?.onChange?.((changes) => {\n res.write(\n `data: ${JSON.stringify({ type: 'container', changes, timestamp: Date.now() })}\\n\\n`,\n )\n sendMetrics()\n })\n\n const stopRequestWatch = watch(requestCount, () => sendMetrics())\n const stopErrWatch = watch(errorCount, () => sendMetrics())\n\n const heartbeat = setInterval(() => {\n res.write(`: heartbeat\\n\\n`)\n }, 30000)\n\n req.on('close', () => {\n unsubContainer?.()\n stopRequestWatch()\n stopErrWatch()\n clearInterval(heartbeat)\n })\n })\n\n if (exposeConfig) {\n router.get('/config', (_req: Request, res: Response) => {\n const config: Record<string, string> = {}\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) continue\n const allowed = configPrefixes.some((prefix) => key.startsWith(prefix))\n config[key] = allowed ? value : '[REDACTED]'\n }\n res.json({ config })\n })\n }\n\n // Dashboard UI — Vue + Tailwind from public/devtools directory\n const publicDir = resolvePublicDir()\n if (publicDir) {\n router.use(serveStatic(publicDir))\n\n const indexHtml = readFileSync(join(publicDir, 'index.html'), 'utf-8')\n router.get('/', (_req: Request, res: Response) => {\n const html = indexHtml.replace('<body', `<body data-base=\"${basePath}\"`)\n res.type('html').send(html)\n })\n } else {\n router.get('/', (_req: Request, res: Response) => {\n res.type('html').send('<h1>DevTools: public directory not found</h1>')\n })\n }\n\n // Routes self-register through the facade as they're declared above —\n // no Router to mount here.\n\n if (secret) {\n log.info(`DevTools mounted at ${basePath} [token: ${secret}]`)\n log.info(`Access: ${basePath}?token=${secret}`)\n } else {\n log.info(`DevTools mounted at ${basePath} [no guard]`)\n }\n },\n\n middleware(): AdapterMiddleware[] {\n if (!enabled) return []\n\n return [\n {\n handler: (req: Request, res: Response, next: NextFunction) => {\n const start = Date.now()\n requestCount.value++\n\n res.on('finish', () => {\n if (res.statusCode >= 500) errorCount.value++\n else if (res.statusCode >= 400) clientErrorCount.value++\n\n // Bucket unmatched paths (404s) under a single key. The\n // previous `?? req.path` fallback used the raw URL, which\n // grows the reactive map unboundedly under 404 probing —\n // each random path became its own entry, bloating\n // `/_debug/metrics` and leaking memory.\n const routeKey = req.route?.path\n ? `${req.method} ${req.route.path}`\n : `${req.method} <unmatched>`\n const elapsed = Date.now() - start\n\n if (!routeLatency[routeKey]) {\n routeLatency[routeKey] = {\n count: 0,\n totalMs: 0,\n minMs: Infinity,\n maxMs: 0,\n samples: [],\n }\n }\n const stats = routeLatency[routeKey]\n stats.count++\n stats.totalMs += elapsed\n stats.minMs = Math.min(stats.minMs, elapsed)\n stats.maxMs = Math.max(stats.maxMs, elapsed)\n stats.samples.push(elapsed)\n if (stats.samples.length > MAX_SAMPLES) stats.samples.shift()\n })\n\n next()\n },\n phase: 'beforeGlobal',\n },\n ]\n },\n\n onRouteMount(controllerClass, mountPath) {\n if (!enabled) return\n\n const collectedRoutes = getClassMeta<\n Array<{ method: string; path: string; handlerName: string }>\n >(METADATA.ROUTES, controllerClass, [])\n\n const classMiddleware = getClassMeta<any[]>(METADATA.CLASS_MIDDLEWARES, controllerClass, [])\n\n for (const route of collectedRoutes) {\n const methodMiddleware = getMethodMeta<any[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass.prototype,\n route.handlerName,\n [],\n )\n\n routes.push({\n method: route.method.toUpperCase(),\n path: `${mountPath}${route.path === '/' ? '' : route.path}`,\n controller: controllerClass.name,\n handler: route.handlerName,\n middleware: [\n ...classMiddleware.map((m: any) => m.name || 'anonymous'),\n ...methodMiddleware.map((m: any) => m.name || 'anonymous'),\n ],\n flags: Object.fromEntries(getRouteFlags(controllerClass, route.handlerName)),\n })\n }\n },\n\n afterStart({ server }) {\n if (!enabled) return\n // Wire the bus's WS upgrade to the framework's http.Server.\n // Path-based routing inside attachUpgrade means kickjs-ws or\n // any other adapter sharing the same listener stays\n // unaffected — only `${basePath}/_bus` is claimed.\n if (server) bus?.attachUpgrade(server)\n\n // Seed `/_debug/health.adapters` with every peer the framework\n // mounted alongside us. Before this, only `DevToolsAdapter`\n // appeared in the Overview > Health card because the dict was\n // only ever written in `beforeMount` (self) and `shutdown`\n // (self). Peers with `onHealthCheck` get their live status;\n // anything else is reported as `running` since reaching\n // `afterStart` means the framework already mounted them.\n for (const peer of getPeerAdapters()) {\n const name = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') continue\n adapterStatuses[name] = 'running'\n }\n\n log.info(\n `DevTools ready — ${routes.length} routes tracked, ` +\n `${container?.getRegistrations().length ?? 0} DI bindings, ` +\n `event bus on ${basePath}/_bus`,\n )\n },\n\n shutdown() {\n stopErrorWatch?.()\n runtimeSampler?.stop()\n memoryAnalyzer?.stop()\n bus?.close()\n adapterStatuses['DevToolsAdapter'] = 'stopped'\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;2rBAkEA,eAAsB,wBACpB,KAC2B,CAC3B,GAAM,CAAE,IAAK,UAAW,oBAAsB,KAAkC,KAC1E,OAA0B,CAAC,EAE3B,QAAU,MAAM,QAAQ,IAC5B,IAAI,WAAW,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,SAAU,oBAAqB,MAAM,CAAC,CACnF,EACM,SAAW,MAAM,QAAQ,IAC7B,IAAI,YAAY,CAAC,CAAC,IAAK,GAAM,YAAY,EAAG,UAAW,oBAAqB,MAAM,CAAC,CACrF,EAEA,MAAO,CACL,gBAAiB,iBACjB,UAAW,KAAK,IAAI,EACpB,QACA,SACA,aAAc,oBAAoB,GAAG,EACrC,SAAU,cAAc,SAAS,EACjC,MACF,CACF,CAOA,eAAe,YACb,UACA,KACA,UACA,OACgC,CAChC,IAAM,KAAO,UAAU,MAAQ,YACzB,KAA8B,CAClC,gBAAiB,iBACjB,KACA,IACF,EACA,GAAI,OAAO,UAAU,YAAe,WAAY,OAAO,KAEvD,GAAI,CACF,IAAM,OAAS,MAAM,QAAQ,KAAK,CAChC,QAAQ,QAAQ,UAAU,WAAW,CAAC,EACtC,IAAI,SAAgB,EAAG,SACrB,e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AC7B,CAnBqC,CAoBvC,EAEA,UAAW,CACT,iBAAiB,EACjB,gBAAgB,KAAK,EACrB,gBAAgB,KAAK,EACrB,KAAK,MAAM,EACX,gBAAgB,gBAAqB,SACvC,CACF,CACF,CACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forinda/kickjs-devtools",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.2.0",
|
|
4
4
|
"description": "Development introspection dashboard for KickJS — routes, DI container, metrics, health",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"vite-plugin-solid": "^2.11.14",
|
|
49
49
|
"vitest": "^4.1.11",
|
|
50
50
|
"ws": "^8.21.3",
|
|
51
|
-
"@forinda/kickjs": "8.
|
|
51
|
+
"@forinda/kickjs": "8.2.0"
|
|
52
52
|
},
|
|
53
53
|
"publishConfig": {
|
|
54
54
|
"access": "public"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&n(u)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var j={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return gt(this.context.count)},getNextContextId(){return gt(this.context.count++)}};function gt(e){const t=String(e),r=t.length-1;return j.context.id+(r?String.fromCharCode(96+r):"")+t}function Ze(e){j.context=e}function cr(){return{...j.context,id:j.getNextContextId(),count:0}}var ur=(e,t)=>e===t,dr=Symbol("solid-track"),De={equals:ur},ft=null,qt=Nt,te=1,Ee=2,Ot={owned:null,cleanups:null,context:null,owner:null},L=null,$=null,Ae=null,be=null,O=null,G=null,W=null,Ke=0;function je(e,t){const r=O,n=L,s=e.length===0,i=t===void 0?n:t,u=s?Ot:{owned:null,cleanups:null,context:i?i.context:null,owner:i},a=s?e:()=>e(()=>se(()=>he(u)));L=u,O=null;try{return ce(a,!0)}finally{O=r,L=n}}function x(e,t){t=t?Object.assign({},De,t):De;const r={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},n=s=>(typeof s=="function"&&($&&$.running&&$.sources.has(r)?s=s(r.tValue):s=s(r.value)),jt(r,s));return[Pt.bind(r),n]}function k(e,t,r){const n=at(e,t,!1,te);Ae&&$&&$.running?G.push(n):Le(n)}function it(e,t,r){qt=pr;const n=at(e,t,!1,te),s=et&&gr(et);s&&(n.suspense=s),(!r||!r.render)&&(n.user=!0),W?W.push(n):Le(n)}function P(e,t,r){r=r?Object.assign({},De,r):De;const n=at(e,t,!0,0);return n.observers=null,n.observerSlots=null,n.comparator=r.equals||void 0,Ae&&$&&$.running?(n.tState=te,G.push(n)):Le(n),Pt.bind(n)}function se(e){if(!be&&O===null)return e();const t=O;O=null;try{return be?be.untrack(e):e()}finally{O=t}}function xe(e){it(()=>se(e))}function ie(e){return L===null||(L.cleanups===null?L.cleanups=[e]:L.cleanups.push(e)),e}function hr(e){if($&&$.running)return e(),$.done;const t=O,r=L;return Promise.resolve().then(()=>{O=t,L=r;let n;return(Ae||et)&&(n=$||($={sources:new Set,effects:[],promises:new Set,disposed:new Set,queue:new Set,running:!0}),n.done||(n.done=new Promise(s=>n.resolve=s)),n.running=!0),ce(e,!1),O=L=null,n?n.done:void 0})}var[pa,vt]=x(!1);function gr(e){let t;return L&&L.context&&(t=L.context[e.id])!==void 0?t:e.defaultValue}var et;function Pt(){const e=$&&$.running;if(this.sources&&(e?this.tState:this.state))if((e?this.tState:this.state)===te)Le(this);else{const t=G;G=null,ce(()=>Ue(this),!1),G=t}if(O){const t=this.observers;if(!t||t[t.length-1]!==O){const r=t?t.length:0;O.sources?(O.sources.push(this),O.sourceSlots.push(r)):(O.sources=[this],O.sourceSlots=[r]),t?(t.push(O),this.observerSlots.push(O.sources.length-1)):(this.observers=[O],this.observerSlots=[O.sources.length-1])}}return e&&$.sources.has(this)?this.tValue:this.value}function jt(e,t,r){let n=$&&$.running&&$.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(n,t)){if($){const s=$.running;(s||!r&&$.sources.has(e))&&($.sources.add(e),e.tValue=t),s||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&ce(()=>{for(let s=0;s<e.observers.length;s+=1){const i=e.observers[s],u=$&&$.running;u&&$.disposed.has(i)||((u?!i.tState:!i.state)&&(i.pure?G.push(i):W.push(i),i.observers&&It(i)),u?i.tState=te:i.state=te)}if(G.length>1e6)throw G=[],new Error},!1)}return t}function Le(e){if(!e.fn)return;he(e);const t=Ke;pt(e,$&&$.running&&$.sources.has(e)?e.tValue:e.value,t),$&&!$.running&&$.sources.has(e)&&queueMicrotask(()=>{ce(()=>{$&&($.running=!0),O=L=e,pt(e,e.tValue,t),O=L=null},!1)})}function pt(e,t,r){let n;const s=L,i=O;O=L=e;try{n=e.fn(t)}catch(u){return e.pure&&($&&$.running?(e.tState=te,e.tOwned&&e.tOwned.forEach(he),e.tOwned=void 0):(e.state=te,e.owned&&e.owned.forEach(he),e.owned=null)),e.updatedAt=r+1,ot(u)}finally{O=i,L=s}(!e.updatedAt||e.updatedAt<=r)&&(e.updatedAt!=null&&"observers"in e?jt(e,n,!0):$&&$.running&&e.pure?($.sources.has(e)||(e.value=n),$.sources.add(e),e.tValue=n):e.value=n,e.updatedAt=r)}function at(e,t,r,n=te,s){const i={fn:e,state:n,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:L,context:L?L.context:null,pure:r};if($&&$.running&&(i.state=0,i.tState=n),L===null||L!==Ot&&($&&$.running&&L.pure?L.tOwned?L.tOwned.push(i):L.tOwned=[i]:L.owned?L.owned.push(i):L.owned=[i]),be&&i.fn){const u=i.fn,[a,c]=x(void 0,{equals:!1}),g=be.factory(u,c);ie(()=>g.dispose());let d,h=!1;const f=()=>hr(c).then(()=>{d&&(d.dispose(),d=void 0,h||c())});i.fn=p=>(a(),$&&$.running?(d||(d=be.factory(u,f)),d.track(p)):(h=!0,g.track(p)))}return i}function Te(e){const t=$&&$.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===Ee)return Ue(e);if(e.suspense&&se(e.suspense.inFallback))return e.suspense.effects.push(e);const r=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Ke);){if(t&&$.disposed.has(e))return;(t?e.tState:e.state)&&r.push(e)}for(let n=r.length-1;n>=0;n--){if(e=r[n],t){let s=e,i=r[n+1];for(;(s=s.owner)&&s!==i;)if($.disposed.has(s))return}if((t?e.tState:e.state)===te)Le(e);else if((t?e.tState:e.state)===Ee){const s=G;G=null,ce(()=>Ue(e,r[0]),!1),G=s}}}function ce(e,t){if(G)return e();let r=!1;t||(G=[]),W?r=!0:W=[],Ke++;try{const n=e();return fr(r),n}catch(n){r||(W=null),G=null,ot(n)}}function fr(e){if(G&&(Ae&&$&&$.running?vr(G):Nt(G),G=null),e)return;let t;if($){if(!$.promises.size&&!$.queue.size){const n=$.sources,s=$.disposed;W.push.apply(W,$.effects),t=$.resolve;for(const i of W)"tState"in i&&(i.state=i.tState),delete i.tState;$=null,ce(()=>{for(const i of s)he(i);for(const i of n){if(i.value=i.tValue,i.owned)for(let u=0,a=i.owned.length;u<a;u++)he(i.owned[u]);i.tOwned&&(i.owned=i.tOwned),delete i.tValue,delete i.tOwned,i.tState=0}vt(!1)},!1)}else if($.running){$.running=!1,$.effects.push.apply($.effects,W),W=null,vt(!0);return}}const r=W;W=null,r.length&&ce(()=>qt(r),!1),t&&t()}function Nt(e){for(let t=0;t<e.length;t++)Te(e[t])}function vr(e){for(let t=0;t<e.length;t++){const r=e[t],n=$.queue;n.has(r)||(n.add(r),Ae(()=>{n.delete(r),ce(()=>{$.running=!0,Te(r)},!1),$&&($.running=!1)}))}}function pr(e){let t,r=0;for(t=0;t<e.length;t++){const n=e[t];n.user?e[r++]=n:Te(n)}if(j.context){if(j.count){j.effects||(j.effects=[]),j.effects.push(...e.slice(0,r));return}Ze()}for(j.effects&&(j.done||!j.count)&&(e=[...j.effects,...e],r+=j.effects.length,delete j.effects),t=0;t<r;t++)Te(e[t])}function Ue(e,t){const r=$&&$.running;r?e.tState=0:e.state=0;for(let n=0;n<e.sources.length;n+=1){const s=e.sources[n];if(s.sources){const i=r?s.tState:s.state;i===te?s!==t&&(!s.updatedAt||s.updatedAt<Ke)&&Te(s):i===Ee&&Ue(s,t)}}}function It(e){const t=$&&$.running;for(let r=0;r<e.observers.length;r+=1){const n=e.observers[r];(t?!n.tState:!n.state)&&(t?n.tState=Ee:n.state=Ee,n.pure?G.push(n):W.push(n),n.observers&&It(n))}}function he(e){let t;if(e.sources)for(;e.sources.length;){const r=e.sources.pop(),n=e.sourceSlots.pop(),s=r.observers;if(s&&s.length){const i=s.pop(),u=r.observerSlots.pop();n<s.length&&(i.sourceSlots[u]=n,s[n]=i,r.observerSlots[n]=u)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)he(e.tOwned[t]);delete e.tOwned}if($&&$.running&&e.pure)Dt(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)he(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}$&&$.running?e.tState=0:e.state=0}function Dt(e,t){if(t||(e.tState=0,$.disposed.add(e)),e.owned)for(let r=0;r<e.owned.length;r++)Dt(e.owned[r])}function mr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function mt(e,t,r){try{for(const n of t)n(e)}catch(n){ot(n,r&&r.owner||null)}}function ot(e,t=L){const r=ft&&t&&t.context&&t.context[ft],n=mr(e);if(!r)throw n;W?W.push({fn(){mt(n,r,t)},state:te}):mt(n,r,t)}var br=Symbol("fallback");function bt(e){for(let t=0;t<e.length;t++)e[t]()}function $r(e,t,r={}){let n=[],s=[],i=[],u=0,a=t.length>1?[]:null;return ie(()=>bt(i)),()=>{let c=e()||[],g=c.length,d,h;return c[dr],se(()=>{let p,m,y,_,C,w,E,S,T;if(g===0)u!==0&&(bt(i),i=[],n=[],s=[],u=0,a&&(a=[])),r.fallback&&(n=[br],s[0]=je(F=>(i[0]=F,r.fallback())),u=1);else if(u===0){for(s=new Array(g),h=0;h<g;h++)n[h]=c[h],s[h]=je(f);u=g}else{for(y=new Array(g),_=new Array(g),a&&(C=new Array(g)),w=0,E=Math.min(u,g);w<E&&n[w]===c[w];w++);for(E=u-1,S=g-1;E>=w&&S>=w&&n[E]===c[S];E--,S--)y[S]=s[E],_[S]=i[E],a&&(C[S]=a[E]);for(p=new Map,m=new Array(S+1),h=S;h>=w;h--)T=c[h],d=p.get(T),m[h]=d===void 0?-1:d,p.set(T,h);for(d=w;d<=E;d++)T=n[d],h=p.get(T),h!==void 0&&h!==-1?(y[h]=s[d],_[h]=i[d],a&&(C[h]=a[d]),h=m[h],p.set(T,h)):i[d]();for(h=w;h<g;h++)h in y?(s[h]=y[h],i[h]=_[h],a&&(a[h]=C[h],a[h](h))):s[h]=je(f);s=s.slice(0,u=g),n=c.slice(0)}return s});function f(p){if(i[h]=p,a){const[m,y]=x(h);return a[h]=y,t(c[h],m)}return t(c[h])}}}var xr=!1;function o(e,t){if(xr&&j.context){const r=j.context;Ze(cr());const n=se(()=>e(t||{}));return Ze(r),n}return se(()=>e(t||{}))}var yr=e=>`Stale read from <${e}>.`;function A(e){const t="fallback"in e&&{fallback:()=>e.fallback};return P($r(()=>e.each,e.children,t||void 0))}function b(e){const t=e.keyed,r=P(()=>e.when,void 0,void 0),n=t?r:P(r,void 0,{equals:(s,i)=>!s==!i});return P(()=>{const s=n();if(s){const i=e.children;return typeof i=="function"&&i.length>0?se(()=>i(t?s:()=>{if(!se(n))throw yr("Show");return r()})):i}return e.fallback},void 0,void 0)}var Re=e=>P(()=>e());function _r(e,t,r){let n=r.length,s=t.length,i=n,u=0,a=0,c=t[s-1].nextSibling,g=null;for(;u<s||a<i;){if(t[u]===r[a]){u++,a++;continue}for(;t[s-1]===r[i-1];)s--,i--;if(s===u){const d=i<n?a?r[a-1].nextSibling:r[i-a]:c;for(;a<i;)e.insertBefore(r[a++],d)}else if(i===a)for(;u<s;)(!g||!g.has(t[u]))&&t[u].remove(),u++;else if(t[u]===r[i-1]&&r[a]===t[s-1]){const d=t[--s].nextSibling;e.insertBefore(r[a++],t[u++].nextSibling),e.insertBefore(r[--i],d),t[s]=r[i]}else{if(!g){g=new Map;let h=a;for(;h<i;)g.set(r[h],h++)}const d=g.get(t[u]);if(d!=null)if(a<d&&d<i){let h=u,f=1,p;for(;++h<s&&h<i&&!((p=g.get(t[h]))==null||p!==d+f);)f++;if(f>d-a){const m=t[u];for(;a<d;)e.insertBefore(r[a++],m)}else e.replaceChild(r[a++],t[u++])}else u++;else t[u++].remove()}}}var $t="_$DX_DELEGATE";function wr(e,t,r,n={}){let s;return je(i=>{s=i,t===document?e():l(t,e(),t.firstChild?null:void 0,r)},n.owner),()=>{s(),t.textContent=""}}function v(e,t,r,n){let s;const i=()=>{const a=n?document.createElementNS("http://www.w3.org/1998/Math/MathML","template"):document.createElement("template");return a.innerHTML=e,r?a.content.firstChild.firstChild:n?a.firstChild:a.content.firstChild},u=t?()=>se(()=>document.importNode(s||(s=i()),!0)):()=>(s||(s=i())).cloneNode(!0);return u.cloneNode=u,u}function J(e,t=window.document){const r=t[$t]||(t[$t]=new Set);for(let n=0,s=e.length;n<s;n++){const i=e[n];r.has(i)||(r.add(i),t.addEventListener(i,kr))}}function N(e,t,r){ut(e)||(r==null?e.removeAttribute(t):e.setAttribute(t,r))}function B(e,t){ut(e)||(t==null?e.removeAttribute("class"):e.className=t)}function ct(e,t,r){if(!t)return r?N(e,"style"):t;const n=e.style;if(typeof t=="string")return n.cssText=t;typeof r=="string"&&(n.cssText=r=void 0),r||(r={}),t||(t={});let s,i;for(i in r)t[i]??n.removeProperty(i),delete r[i];for(i in t)s=t[i],s!==r[i]&&(n.setProperty(i,s),r[i]=s);return r}function Sr(e,t,r){return se(()=>e(t,r))}function l(e,t,r,n){if(r!==void 0&&!n&&(n=[]),typeof t!="function")return ze(e,t,n,r);k(s=>ze(e,t(),s,r),n)}function ut(e){return!!j.context&&!j.done&&(!e||e.isConnected)}function kr(e){if(j.registry&&j.events&&j.events.find(([c,g])=>g===e))return;let t=e.target;const r=`$$${e.type}`,n=e.target,s=e.currentTarget,i=c=>Object.defineProperty(e,"target",{configurable:!0,value:c}),u=()=>{const c=t[r];if(c&&!t.disabled){const g=t[`${r}Data`];if(g!==void 0?c.call(t,g,e):c.call(t,e),e.cancelBubble)return}return t.host&&typeof t.host!="string"&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;u()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return t||document}}),j.registry&&!j.done&&(j.done=_$HY.done=!0),e.composedPath){const c=e.composedPath();i(c[0]);for(let g=0;g<c.length-2&&(t=c[g],!!u());g++){if(t._$host){t=t._$host,a();break}if(t.parentNode===s)break}}else a();i(n)}function ze(e,t,r,n,s){const i=ut(e);if(i){!r&&(r=[...e.childNodes]);let c=[];for(let g=0;g<r.length;g++){const d=r[g];d.nodeType===8&&d.data.slice(0,2)==="!$"?d.remove():c.push(d)}r=c}for(;typeof r=="function";)r=r();if(t===r)return r;const u=typeof t,a=n!==void 0;if(e=a&&r[0]&&r[0].parentNode||e,u==="string"||u==="number"){if(i||u==="number"&&(t=t.toString(),t===r))return r;if(a){let c=r[0];c&&c.nodeType===3?c.data!==t&&(c.data=t):c=document.createTextNode(t),r=pe(e,r,n,c)}else r!==""&&typeof r=="string"?r=e.firstChild.data=t:r=e.textContent=t}else if(t==null||u==="boolean"){if(i)return r;r=pe(e,r,n)}else{if(u==="function")return k(()=>{let c=t();for(;typeof c=="function";)c=c();r=ze(e,c,r,n)}),()=>r;if(Array.isArray(t)){const c=[],g=r&&Array.isArray(r);if(tt(c,t,r,s))return k(()=>r=ze(e,c,r,n,!0)),()=>r;if(i){if(!c.length)return r;if(n===void 0)return r=[...e.childNodes];let d=c[0];if(d.parentNode!==e)return r;const h=[d];for(;(d=d.nextSibling)!==n;)h.push(d);return r=h}if(c.length===0){if(r=pe(e,r,n),a)return r}else g?r.length===0?xt(e,c,n):_r(e,r,c):(r&&pe(e),xt(e,c));r=c}else if(t.nodeType){if(i&&t.parentNode)return r=a?[t]:t;if(Array.isArray(r)){if(a)return r=pe(e,r,n,t);pe(e,r,null,t)}else r==null||r===""||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);r=t}}return r}function tt(e,t,r,n){let s=!1;for(let i=0,u=t.length;i<u;i++){let a=t[i],c=r&&r[e.length],g;if(!(a==null||a===!0||a===!1))if((g=typeof a)=="object"&&a.nodeType)e.push(a);else if(Array.isArray(a))s=tt(e,a,c)||s;else if(g==="function")if(n){for(;typeof a=="function";)a=a();s=tt(e,Array.isArray(a)?a:[a],Array.isArray(c)?c:[c])||s}else e.push(a),s=!0;else{const d=String(a);c&&c.nodeType===3&&c.data===d?e.push(c):e.push(document.createTextNode(d))}}return s}function xt(e,t,r=null){for(let n=0,s=t.length;n<s;n++)e.insertBefore(t[n],r)}function pe(e,t,r,n){if(r===void 0)return e.textContent="";const s=n||document.createTextNode("");if(t.length){let i=!1;for(let u=t.length-1;u>=0;u--){const a=t[u];if(s!==a){const c=a.parentNode===e;!i&&!u?c?e.replaceChild(s,a):e.insertBefore(s,r):c&&a.remove()}else i=!0}}else e.insertBefore(s,r);return[s]}var Ut="kickjs-devtools-theme";function Cr(){try{const e=localStorage.getItem(Ut);if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Er(){return typeof window>"u"||!window.matchMedia?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}var[zt,Tr]=x(Cr()),[Mr,Ar]=x(Er());if(typeof window<"u"&&window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: light)"),t=r=>Ar(r.matches?"light":"dark");e.addEventListener("change",t)}var Je=zt;function Ft(){const e=zt();return e==="system"?Mr():e}function Lr(e){Tr(e);try{localStorage.setItem(Ut,e)}catch{}}function Rr(){it(()=>{const e=Ft();document.documentElement.dataset.theme=e}),ie(()=>{delete document.documentElement.dataset.theme})}var Ht="kickjs-devtools-density";function Br(){try{const e=localStorage.getItem(Ht);if(e==="sm"||e==="md"||e==="lg")return e}catch{}return"sm"}var[Gt,qr]=x(Br()),yt=Gt;function Or(e){qr(e);try{localStorage.setItem(Ht,e)}catch{}}function Pr(){it(()=>{document.documentElement.dataset.density=Gt()}),ie(()=>{delete document.documentElement.dataset.density})}var[jr,Nr]=x("connecting"),[Ir,_t]=x(null),[Dr,Ur]=x(!1),[zr,Fr]=x(null),[Hr,Gr]=x(null),[Vr,Kr]=x(null),[Wr,Jr]=x([]),[Qr,Yr]=x([]),[Xr,Zr]=x({enabled:!1,queues:[]}),[en,tn]=x({enabled:!1}),M={connectionStatus:jr,lastUpdate:Ir,authRequired:Dr,authError:zr,health:Hr,metrics:Vr,routes:Wr,container:Qr,queues:Xr,ws:en},U={setConnectionStatus:Nr,setLastUpdate:_t,setAuthRequired:Ur,setAuthError:Fr,setHealth:Gr,setMetrics:Kr,setRoutes:Jr,setContainer:Yr,setQueues:Zr,setWs:tn,touch(){_t(new Date)}};function Q(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KiB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MiB`:`${(e/1024/1024/1024).toFixed(2)} GiB`}function rn(e){if(e===0)return"0";const t=e*60;return Math.abs(t)<1048576?`${(t/1024).toFixed(1)} KiB/min`:`${(t/1024/1024).toFixed(1)} MiB/min`}function oe(e){return e<1?`${e.toFixed(2)} ms`:e<100?`${e.toFixed(1)} ms`:`${Math.round(e)} ms`}function dt(e){const t=Math.floor(e);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m ${t%60}s`:`${Math.floor(t/3600)}h ${Math.floor(t%3600/60)}m ${t%60}s`}function Fe(e){return`${Math.round(e*100)}%`}var nn=v('<span class=dt-tip tabindex=0><svg class=dt-tip-icon viewBox="0 0 24 24"aria-hidden=true><circle cx=12 cy=12 r=9 fill=none stroke=currentColor stroke-width=1.5></circle><path d="M12 8h.01M12 11v6"stroke=currentColor stroke-width=2 stroke-linecap=round fill=none></path></svg><span role=tooltip>'),ln=v('<button type=button class="dt-tip dt-tip-clickable"><svg class=dt-tip-icon viewBox="0 0 24 24"aria-hidden=true><circle cx=12 cy=12 r=9 fill=none stroke=currentColor stroke-width=1.5></circle><path d="M12 8h.01M12 11v6"stroke=currentColor stroke-width=2 stroke-linecap=round fill=none>'),sn=v('<div class="fixed inset-0 z-50 bg-slate-950/80 flex items-center justify-center p-4"><div class="bg-slate-900 border border-slate-700 rounded-2xl p-6 max-w-lg w-full shadow-2xl max-h-[90vh] overflow-y-auto"><div class="flex items-start justify-between mb-4"><h2 class="text-lg font-semibold text-slate-200"></h2><button type=button class="text-slate-500 hover:text-slate-300 p-1"aria-label=Close><svg class="w-5 h-5"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M6 18L18 6M6 6l12 12"></path></svg></button></div><div class="text-sm text-slate-300 space-y-3">'),rt={"heap.used":{short:"V8-allocated memory currently used by JavaScript objects.",detail:"Grows as your code allocates objects, shrinks after GC frees them. A consistently rising heap-used line on the sparkline is the textbook leak signature."},"heap.total":{short:"V8-allocated memory the JS heap is currently sized to use.",detail:"Larger than heap-used; V8 reserves headroom so allocations don't pause to grow the heap. Bumps up in 1-8 MiB jumps as the heap expands."},rss:{short:"Total memory resident in physical RAM for this Node process.",detail:'Includes the JS heap, native buffers, V8 internal structures, and code. Always larger than heap-used; the gap is "everything the OS sees" minus "JS objects".'},external:{short:"Memory used by C++ objects bound to JS (Buffers, native bindings)."},"array-buffers":{short:"Memory used by ArrayBuffer / SharedArrayBuffer instances."},"event-loop.p99":{short:"99% of event-loop ticks completed within this time.",detail:"Sustained values above ~50ms mean some synchronous operation is blocking the loop. Common culprits: large JSON.parse, sync crypto, blocking DB drivers."},gc:{short:"Garbage-collector activity since process start.",detail:"Total run count and cumulative pause time. Frequent GC with low reclaim ratio = leak; rare GC with healthy reclaim = good citizen."},"leak.risk":{short:"Heap-growth slope over the recent window — stable / warn / critical.",detail:"Bucketed from heap-growth in MB/min: <5 = ok, <20 = warn, ≥20 = critical. Critical sustained for >5 minutes is the moment to capture a heap snapshot."},"gc.reclaim":{short:"Average ratio of memory freed by each GC pass.",detail:"Trending toward zero means GC can't free anything — strong leak indicator. Healthy apps reclaim 20-60% on each major GC."},"heap.utilization":{short:"Fraction of V8's hard heap-size limit currently in use.",detail:"Approaching 1 means the process is close to OOM. Use --max-old-space-size to raise the limit if your workload is memory-bound."},requests:{short:"Total HTTP requests handled since process start."},"server-errors":{short:"5xx responses — server-side failures."},"client-errors":{short:"4xx responses — bad client input, missing routes, auth denials."},"error-rate":{short:"Server errors as a percentage of total requests.",detail:"Computed across the lifetime of the process. Spikes typically signal upstream dependency failures; sustained elevation = code bug."},uptime:{short:"How long this Node process has been running."},"latency.avg":{short:"Mean response time per route (sum of all calls / call count)."},"latency.p50":{short:"Median — half the requests complete faster than this."},"latency.p95":{short:"95% of requests complete within this time."},"latency.p99":{short:"99% of requests complete within this time. Outlier-sensitive."},"latency.max":{short:"Slowest single response observed since process start."},"resolve.count":{short:"Number of times this token was resolved from the DI container."},"resolve.duration":{short:"How long the container took to resolve this token (ms)."},"post-construct":{short:"@PostConstruct lifecycle status: done / failed / none.",detail:'A failed PostConstruct means the service registered but its async init threw. The token is left in a "registered" state; resolve() will throw the original error.'}},Y=e=>{const t=()=>e.text??rt[e.metric??""]?.short??"",r=e.placement??"top";return(()=>{var n=nn(),s=n.firstChild.nextSibling;return B(s,`dt-tip-pop dt-tip-pop-${r}`),l(s,t),k(()=>N(n,"aria-label",t())),n})()},an=e=>{const[t,r]=x(!1);return[(()=>{var n=ln();return n.$$click=()=>r(!0),k(()=>N(n,"aria-label",`More info: ${e.title}`)),n})(),o(b,{get when(){return t()},get children(){return o(on,{get title(){return e.title},onClose:()=>r(!1),get children(){return e.children}})}})]},on=e=>(()=>{var t=sn(),r=t.firstChild.firstChild,n=r.firstChild,s=n.nextSibling,i=r.nextSibling;return t.$$click=u=>{u.target===u.currentTarget&&e.onClose()},l(n,()=>e.title),s.$$click=()=>e.onClose(),l(i,()=>e.children),t})();J(["click"]);var cn=v('<div class="grid grid-cols-1 md:grid-cols-3 gap-4">'),un=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">Health'),Vt=v('<p class="text-text-muted italic">Loading…'),dn=v("<span>"),$e=v('<span class="font-semibold tabular-nums">'),Kt=v("<div class=mt-1>"),hn=v('<div class="border-t border-border mt-2 pt-2"><button type=button class="text-xs text-text-muted hover:text-text-strong flex items-center gap-1"><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg>Adapters (<!>)'),gn=v('<div class="flex items-center justify-between py-1"><span class="text-text-secondary text-sm"></span><span>'),fn=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">Metrics'),vn=v('<span class="font-semibold tabular-nums text-red-400">'),pn=v('<span class="font-semibold tabular-nums text-amber-400">'),mn=v('<span class="font-semibold text-sm">'),bn=v('<span class="font-semibold tabular-nums text-emerald-400">'),$n=v('<div class="border-t border-border mt-2 pt-2"><button type=button class="text-xs text-text-muted hover:text-text-strong flex items-center gap-1"><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg>Namespaces (<!>)'),xn=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">WebSocket'),yn=v('<p class="text-text-muted italic">No WsAdapter detected'),_n=v('<div class="flex items-center justify-between py-1"><span class="text-text-secondary text-sm font-mono"></span><span class=text-sm> conn / <!> handlers'),wn=v('<div class="flex items-center justify-between mb-2"><span class=text-text-secondary>'),Sn=()=>(()=>{var e=cn();return l(e,o(kn,{}),null),l(e,o(Cn,{}),null),l(e,o(En,{}),null),e})(),kn=()=>{const[e,t]=x(!0);return(()=>{var r=un();return r.firstChild,l(r,o(b,{get when(){return M.health()},get fallback(){return Vt()},children:n=>[o(re,{label:"Status",get children(){var s=dn();return l(s,()=>n().status),k(()=>B(s,`badge ${Tn(n().status)}`)),s}}),o(re,{label:"Uptime",get children(){var s=$e();return l(s,()=>dt(n().uptime)),s}}),o(re,{label:"Error rate",get children(){var s=$e();return l(s,()=>Fe(n().errorRate),null),l(s,o(Y,{metric:"error-rate"}),null),s}}),o(b,{get when(){return Object.keys(n().adapters).length>0},get children(){var s=hn(),i=s.firstChild,u=i.firstChild,a=u.nextSibling.nextSibling;return a.nextSibling,i.$$click=()=>t(c=>!c),l(i,()=>Object.keys(n().adapters).length,a),l(s,o(b,{get when(){return e()},get children(){var c=Kt();return l(c,o(A,{get each(){return Object.entries(n().adapters)},children:([g,d])=>(()=>{var h=gn(),f=h.firstChild,p=f.nextSibling;return l(f,g),B(p,`badge ${d==="running"?"badge-ok":"badge-warn"}`),l(p,d),h})()})),c}}),null),k(()=>N(u,"class",`w-3 h-3 transition-transform ${e()?"rotate-90":""}`)),s}})]}),null),r})()},Cn=()=>(()=>{var e=fn();return e.firstChild,l(e,o(b,{get when(){return M.metrics()},get fallback(){return Vt()},children:t=>[o(re,{label:"Total requests",get children(){var r=$e();return l(r,()=>t().requests.toLocaleString()),r}}),o(re,{label:"5xx errors",get children(){var r=vn();return l(r,()=>t().serverErrors),r}}),o(re,{label:"4xx errors",get children(){var r=pn();return l(r,()=>t().clientErrors),r}}),o(re,{label:"Started",get children(){var r=mn();return l(r,()=>new Date(t().startedAt).toLocaleTimeString()),r}})]}),null),e})(),En=()=>{const[e,t]=x(!1);return(()=>{var r=xn();return r.firstChild,l(r,o(b,{get when(){return M.ws().enabled},get fallback(){return yn()},get children(){return[o(re,{label:"Active",get children(){var n=bn();return l(n,()=>M.ws().activeConnections??0),n}}),o(re,{label:"Total",get children(){var n=$e();return l(n,()=>M.ws().totalConnections??0),n}}),o(re,{label:"Messages in",get children(){var n=$e();return l(n,()=>M.ws().messagesReceived??0),n}}),o(re,{label:"Messages out",get children(){var n=$e();return l(n,()=>M.ws().messagesSent??0),n}}),o(b,{get when(){return Re(()=>!!M.ws().namespaces)()&&Object.keys(M.ws().namespaces??{}).length>0},get children(){var n=$n(),s=n.firstChild,i=s.firstChild,u=i.nextSibling.nextSibling;return u.nextSibling,s.$$click=()=>t(a=>!a),l(s,()=>Object.keys(M.ws().namespaces??{}).length,u),l(n,o(b,{get when(){return e()},get children(){var a=Kt();return l(a,o(A,{get each(){return Object.entries(M.ws().namespaces??{})},children:([c,g])=>(()=>{var d=_n(),h=d.firstChild,f=h.nextSibling,p=f.firstChild,m=p.nextSibling;return m.nextSibling,l(h,c),l(f,()=>g.connections,p),l(f,()=>g.handlers,m),d})()})),a}}),null),k(()=>N(i,"class",`w-3 h-3 transition-transform ${e()?"rotate-90":""}`)),n}})]}}),null),r})()},re=e=>(()=>{var t=wn(),r=t.firstChild;return l(r,()=>e.label),l(t,()=>e.children,null),t})();function Tn(e){return e==="healthy"?"badge-ok":e==="degraded"?"badge-warn":"badge-critical"}J(["click"]);var Mn=v("<svg class=sparkline preserveAspectRatio=none aria-hidden=true><path fill=none stroke-width=1.5 stroke-linejoin=round stroke-linecap=round>"),Ne=e=>{const t=()=>e.width??200,n=P(()=>{const s=e.values;if(s.length<2)return"";const i=Math.min(...s),u=Math.max(...s)-i||1,a=t()/(s.length-1),c=d=>40-(d-i)/u*36-2;let g=`M0 ${c(s[0]).toFixed(2)}`;for(let d=1;d<s.length;d++)g+=` L${(d*a).toFixed(2)} ${c(s[d]).toFixed(2)}`;return g});return(()=>{var s=Mn(),i=s.firstChild;return k(u=>{var a=`0 0 ${t()} 40`,c=n(),g=e.stroke??"var(--color-accent)";return a!==u.e&&N(s,"viewBox",u.e=a),c!==u.t&&N(i,"d",u.t=c),g!==u.a&&N(i,"stroke",u.a=g),u},{e:void 0,t:void 0,a:void 0}),s})()};function ye(){return document.body.dataset.base??"/_debug"}var Wt="kickjs_devtools_token",An=30,Se=null;function ve(){if(Se)return Se;const e=new URLSearchParams(location.search).get("token");if(e){Jt(e);const r=new URL(location.href);return r.searchParams.delete("token"),history.replaceState({},"",r.toString()),e}const t=document.cookie.match(new RegExp(`${Wt}=([^;]+)`));return t?(Se=decodeURIComponent(t[1]),Se):null}function Jt(e){Se=e,document.cookie=`${Wt}=${encodeURIComponent(e)}; path=/; max-age=${86400*An}; SameSite=Lax`}function Qt(e){const t=ve();return t?`${e}${e.includes("?")?"&":"?"}token=${encodeURIComponent(t)}`:e}var Yt=class extends Error{constructor(){super("AUTH_REQUIRED"),this.name="AuthRequiredError"}};async function le(e){const t=Qt(`${ye()}${e}`),r=await fetch(t,{headers:Ln()});if(r.status===401||r.status===403)throw new Yt;if(!r.ok)throw new Error(`GET ${e} failed: ${r.status} ${r.statusText}`);return await r.json()}function Ln(){const e=ve();return e?{"x-devtools-token":e}:{}}var ee={runtime:()=>le("/runtime"),topology:()=>le("/topology"),metrics:()=>le("/metrics"),routes:()=>le("/metrics"),routeRegistry:()=>le("/routes"),container:()=>le("/container"),health:()=>le("/health"),queues:()=>le("/queues"),ws:()=>le("/ws"),tabs:()=>le("/tabs")};function ht(e,t,r){const n=Qt(`${ye()}${e}`),s=new EventSource(n);return s.addEventListener("message",i=>{try{t(JSON.parse(i.data))}catch(u){console.warn("SSE parse failed",u)}}),r&&s.addEventListener("error",r),()=>s.close()}var Rn=v("<div class=status><span><span></span></span><span> samples"),Bn=v("<div class=proc-strip><span class=proc-label>These stats are for <strong>this Node process</strong> — the one running your KickJS app.</span><span class=proc-meta><span class=proc-pill>Node </span><span class=proc-pill>/</span><span class=proc-pill>pid "),qn=v("<span>engine: "),On=v("<div class=empty>Loading runtime metrics…"),Pn=v("<div class=empty style=padding:0;text-align:left;font-size:11px>GC: <!> runs, <!> total"),wt=v("<div class=grid>"),jn=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),Nn=()=>{const[e,t]=x(null),[r,n]=x(null),[s,i]=x([]),[u,a]=x([]),[c,g]=x([]),[d,h]=x(!1),f=p=>{t(p),i(m=>[...m,p.memory.heapUsed].slice(-60)),a(m=>[...m,p.memory.rss].slice(-60)),g(m=>[...m,p.eventLoop.p99].slice(-60))};return xe(()=>{ee.runtime().then(m=>{m.process&&n(m.process);for(const y of m.history)f(y);h(!0)}).catch(()=>h(!1));const p=ht("/runtime/stream",m=>{h(!0),f(m)},()=>h(!1));ie(p)}),[o(b,{get when(){return r()},children:p=>(()=>{var m=Bn(),y=m.firstChild.nextSibling,_=y.firstChild;_.firstChild;var C=_.nextSibling,w=C.firstChild,E=C.nextSibling;return E.firstChild,l(y,o(b,{get when(){return p().runtime},children:S=>(()=>{var T=qn();return T.firstChild,l(T,()=>S().name,null),k(()=>B(T,`proc-pill rt-${S().name}`)),T})()}),_),l(_,()=>p().nodeVersion,null),l(C,()=>p().platform,w),l(C,()=>p().arch,null),l(E,()=>p().pid,null),m})()}),o(b,{get when(){return e()},get fallback(){return On()},children:p=>[(()=>{var m=wt();return l(m,o(de,{title:"Heap used",metric:"heap.used",get value(){return Q(p().memory.heapUsed)},get children(){return o(Ne,{get values(){return s()}})}}),null),l(m,o(de,{title:"RSS",metric:"rss",get value(){return Q(p().memory.rss)},get children(){return o(Ne,{get values(){return u()}})}}),null),l(m,o(de,{title:"Event loop p99",metric:"event-loop.p99",get value(){return oe(p().eventLoop.p99)},get children(){return o(Ne,{get values(){return c()}})}}),null),l(m,o(de,{title:"Uptime",metric:"uptime",get value(){return dt(p().uptimeSec)},get children(){var y=Pn(),_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling;return C.nextSibling,l(y,()=>p().gc.count,_),l(y,()=>oe(p().gc.totalPauseMs),C),y}}),null),m})(),(()=>{var m=wt();return l(m,o(de,{title:"External",metric:"external",get value(){return Q(p().memory.external)}}),null),l(m,o(de,{title:"Array buffers",metric:"array-buffers",get value(){return Q(p().memory.arrayBuffers)}}),null),l(m,o(de,{title:"Heap total",metric:"heap.total",get value(){return Q(p().memory.heapTotal)}}),null),l(m,o(de,{title:"CPU (last sample)",get value(){return`${(p().cpu.userMicros/1e3).toFixed(1)} ms u / ${(p().cpu.systemMicros/1e3).toFixed(1)} ms s`}}),null),m})()]}),(()=>{var p=Rn(),m=p.firstChild,y=m.firstChild,_=m.nextSibling,C=_.firstChild;return l(m,()=>d()?"streaming":"reconnecting…",null),l(_,()=>s().length,C),k(()=>B(y,`status-dot ${d()?"connected":"disconnected"}`)),p})()]},de=e=>(()=>{var t=jn(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),l(t,()=>e.children,null),t})(),In=v("<div class=status><span><span></span></span><span> samples"),Dn=v("<div class=empty>Loading memory metrics…"),St=v("<p>"),Un=v("<p><strong>Severity buckets</strong> (heap-growth in MB/min):"),zn=v('<ul class="list-disc pl-5 space-y-1"><li><span class="badge badge-ok">ok</span> < 5 MB/min — typical operation.</li><li><span class="badge badge-warn">warn</span> < 20 MB/min — investigate if sustained > 5 minutes.</li><li><span class="badge badge-critical">critical</span> ≥ 20 MB/min — capture a heap snapshot now.'),Fn=v("<div class=card><div class=card-header><div class=card-title>Leak risk</div><span></span></div><div style=display:flex;justify-content:space-between;align-items:baseline><div class=card-value> growth</div><div class=card-value style=font-size:13px;color:var(--text-dim)>GC reclaim<!> <!> • heap util<!> "),Hn=v("<div class=grid>"),Gn=v("<table><thead><tr><th>Type</th><th style=text-align:right>Count</th></tr></thead><tbody>"),Vn=v("<div class=card><div class=card-header><div class=card-title>Active handles</div><div class=card-value>"),Kn=v("<div class=empty>No handle inventory available on this runtime."),Wn=v("<tr><td></td><td style=text-align:right>"),Jn=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),Qn=v('<div class=card><div class=card-header><div class=card-title>Heap snapshot</div><div class=card-value style=font-size:13px;color:var(--text-dim)>~<!> estimate</div></div><p style="margin:0 0 12px;color:var(--text-dim);font-size:12px">Captures a V8 heap snapshot for retained-size analysis in Chrome DevTools (Memory tab, Load profile). Capture blocks the event loop for several seconds — avoid in production.</p><div style=display:flex;align-items:center;gap:12px><button type=button class=tab style="border:1px solid var(--accent);border-radius:4px;padding:6px 14px;border-bottom-color:var(--accent);color:var(--accent)">'),Yn=v("<span style=color:var(--text-dim);font-size:12px;font-family:var(--font-mono)>Last: <!> (<!>)"),Xt=v('<p style="margin:8px 0 0;color:var(--critical);font-size:12px;font-family:var(--font-mono)">'),Xn=v('<div class=card><div class=card-header><div class=card-title>Force GC</div></div><p style="margin:0 0 12px;color:var(--text-dim);font-size:12px">Triggers a synchronous V8 GC pass to confirm whether heap growth is real retention or just uncollected garbage. Requires <code>node --expose-gc</code>.</p><div style=display:flex;align-items:center;gap:12px;flex-wrap:wrap><button type=button class=tab style="border:1px solid var(--accent);border-radius:4px;padding:6px 14px;border-bottom-color:var(--accent);color:var(--accent)">'),Zn=v("<span style=color:var(--text-dim);font-size:12px;font-family:var(--font-mono)>Reclaimed <!> (<!> → <!>) in <!>ms"),el=()=>{const[e,t]=x(null),[r,n]=x([]),[s,i]=x(!1),u=c=>{t(c),n(g=>[...g,c.snapshot.memory.heapUsed].slice(-60))};xe(()=>{ee.runtime().then(g=>{g.latest&&(u({snapshot:g.latest,health:g.health}),n(g.history.map(d=>d.memory.heapUsed).slice(-60))),i(!0)}).catch(()=>i(!1));const c=ht("/memory/stream",g=>{i(!0),u(g)},()=>i(!1));ie(c)});const a=P(()=>{const c=e();return c?Object.entries(c.health.handlesByType).toSorted((g,d)=>d[1]-g[1]):[]});return[o(b,{get when(){return e()},get fallback(){return Dn()},children:c=>[(()=>{var g=Fn(),d=g.firstChild,h=d.firstChild;h.firstChild;var f=h.nextSibling,p=d.nextSibling.firstChild,m=p.firstChild,y=p.nextSibling,_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling,w=C.nextSibling.nextSibling;return w.nextSibling,l(h,o(an,{title:"What is leak risk?",get children(){return[(()=>{var E=St();return l(E,()=>rt["leak.risk"].short),E})(),(()=>{var E=St();return l(E,()=>rt["leak.risk"].detail),E})(),Un(),zn()]}}),null),l(f,()=>c().health.heapGrowthSeverity),l(p,()=>rn(c().health.heapGrowthBytesPerSec),m),l(y,o(Y,{metric:"gc.reclaim"}),_),l(y,()=>Fe(c().health.gcReclaimRatio),C),l(y,o(Y,{metric:"heap.utilization"}),w),l(y,()=>Fe(c().health.heapUtilization),null),l(g,o(Ne,{get values(){return r()}}),null),k(()=>B(f,`badge badge-${c().health.heapGrowthSeverity}`)),g})(),(()=>{var g=Hn();return l(g,o(Be,{title:"Heap used",metric:"heap.used",get value(){return Q(c().snapshot.memory.heapUsed)}}),null),l(g,o(Be,{title:"Heap total",metric:"heap.total",get value(){return Q(c().snapshot.memory.heapTotal)}}),null),l(g,o(Be,{title:"RSS",metric:"rss",get value(){return Q(c().snapshot.memory.rss)}}),null),l(g,o(Be,{title:"External",metric:"external",get value(){return Q(c().snapshot.memory.external)}}),null),g})(),(()=>{var g=Vn(),d=g.firstChild.firstChild.nextSibling;return l(d,()=>c().health.activeHandles),l(g,o(b,{get when(){return a().length>0},get fallback(){return Kn()},get children(){var h=Gn(),f=h.firstChild.nextSibling;return l(f,o(A,{get each(){return a()},children:([p,m])=>(()=>{var y=Wn(),_=y.firstChild,C=_.nextSibling;return l(_,p),l(C,m),y})()})),h}}),null),g})(),o(tl,{get heapTotal(){return c().snapshot.memory.heapTotal}}),o(ll,{})]}),(()=>{var c=In(),g=c.firstChild,d=g.firstChild,h=g.nextSibling,f=h.firstChild;return l(g,()=>s()?"streaming":"reconnecting…",null),l(h,()=>r().length,f),k(()=>B(d,`status-dot ${s()?"connected":"disconnected"}`)),c})()]},Be=e=>(()=>{var t=Jn(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),t})(),tl=e=>{const[t,r]=x(!1),[n,s]=x(null),[i,u]=x(null),a=async()=>{r(!0),s(null);try{const c=ve(),g=`${ye()}/memory/snapshot${c?`?token=${encodeURIComponent(c)}`:""}`,d=await fetch(g,{method:"POST",headers:c?{"x-devtools-token":c}:void 0});if(!d.ok){let p=`${d.status} ${d.statusText}`;try{const m=await d.json();m.error&&(p=m.error)}catch{}throw new Error(p)}const h=await d.blob(),f=rl(d.headers.get("content-disposition"))??`kickjs-heap-${Date.now()}.heapsnapshot`;nl(h,f),u({name:f,sizeBytes:h.size})}catch(c){s(c instanceof Error?c.message:String(c))}finally{r(!1)}};return(()=>{var c=Qn(),g=c.firstChild,d=g.firstChild.nextSibling,h=d.firstChild.nextSibling;h.nextSibling;var f=g.nextSibling.nextSibling,p=f.firstChild;return l(d,()=>Q(e.heapTotal),h),p.$$click=()=>{a()},l(p,()=>t()?"Capturing…":"Take snapshot"),l(f,o(b,{get when(){return i()},children:m=>(()=>{var y=Yn(),_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling;return C.nextSibling,l(y,()=>m().name,_),l(y,()=>Q(m().sizeBytes),C),y})()}),null),l(c,o(b,{get when(){return n()},children:m=>(()=>{var y=Xt();return l(y,m),y})()}),null),k(()=>p.disabled=t()),c})()};function rl(e){if(!e)return null;const t=/filename="?([^";]+)"?/.exec(e);return t?t[1]:null}function nl(e,t){const r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}var ll=()=>{const[e,t]=x(!1),[r,n]=x(null),[s,i]=x(null),u=async()=>{t(!0),i(null);try{const a=ve(),c=`${ye()}/memory/gc${a?`?token=${encodeURIComponent(a)}`:""}`,g=await fetch(c,{method:"POST",headers:a?{"x-devtools-token":a}:void 0});if(!g.ok){let d=`${g.status} ${g.statusText}`;try{const h=await g.json();h.error&&(d=h.error)}catch{}throw new Error(d)}n(await g.json())}catch(a){i(a instanceof Error?a.message:String(a))}finally{t(!1)}};return(()=>{var a=Xn(),c=a.firstChild.nextSibling.nextSibling,g=c.firstChild;return g.$$click=()=>{u()},l(g,()=>e()?"Collecting…":"Run GC"),l(c,o(b,{get when(){return r()},children:d=>(()=>{var h=Zn(),f=h.firstChild.nextSibling,p=f.nextSibling.nextSibling,m=p.nextSibling.nextSibling,y=m.nextSibling.nextSibling;return y.nextSibling,l(h,()=>Q(d().reclaimedBytes),f),l(h,()=>Q(d().before),p),l(h,()=>Q(d().after),m),l(h,()=>d().elapsedMs,y),h})()}),null),l(a,o(b,{get when(){return s()},children:d=>(()=>{var h=Xt();return l(h,d),h})()}),null),k(()=>g.disabled=e()),a})()};J(["click"]);var sl=v('<div class="flex items-center justify-between mt-4 pt-3 border-t border-slate-800 text-xs text-slate-500"><div class="flex items-center gap-3"><span>Showing <!>–<!> of </span><label class="flex items-center gap-1"><span class=text-slate-600>Per page</span><select class="bg-slate-800 border border-slate-700 rounded px-1.5 py-0.5 text-slate-200"></select></label></div><div class="flex items-center gap-1"><button type=button class="px-2.5 py-1 rounded border border-slate-700 bg-slate-800 hover:bg-slate-700 disabled:opacity-30">Prev</button><button type=button class="px-2.5 py-1 rounded border border-slate-700 bg-slate-800 hover:bg-slate-700 disabled:opacity-30">Next'),il=v("<option>"),al=v('<span class="px-1 text-slate-600">…'),ol=v("<button type=button>"),cl=[5,10,15,20,25,50,100];function ge(e,t={}){const r=t.pageSizeChoices??cl,n=t.pageSize??r[0]??5,[s,i]=x(n),[u,a]=x(1),c=P(()=>Math.max(1,Math.ceil(e().length/s()))),g=P(()=>Math.min(u(),c()));return{source:e,page:P(()=>{const d=(g()-1)*s();return e().slice(d,d+s())}),current:g,total:c,pageSize:s,pageSizeChoices:r,range:P(()=>{const d=e().length;return d===0?{start:0,end:0,total:0}:{start:(g()-1)*s()+1,end:Math.min(g()*s(),d),total:d}}),goto(d){a(Math.max(1,Math.min(d,c())))},next(){a(d=>Math.min(d+1,c()))},prev(){a(d=>Math.max(d-1,1))},setPageSize(d){i(d);const h=(g()-1)*s();a(Math.max(1,Math.floor(h/d)+1))}}}var fe=e=>{const t=P(()=>{const r=e.pager.total(),n=e.pager.current();if(r<=7)return Array.from({length:r},(a,c)=>c+1);const s=[1],i=Math.max(2,n-1),u=Math.min(r-1,n+1);i>2&&s.push("gap");for(let a=i;a<=u;a++)s.push(a);return u<r-1&&s.push("gap"),s.push(r),s});return o(b,{get when(){return e.pager.total()>1||e.pager.source().length>e.pager.pageSize()},get children(){var r=sl(),n=r.firstChild,s=n.firstChild,i=s.firstChild.nextSibling,u=i.nextSibling.nextSibling;u.nextSibling;var a=s.nextSibling.firstChild.nextSibling,c=n.nextSibling,g=c.firstChild,d=g.nextSibling;return l(s,()=>e.pager.range().start,i),l(s,()=>e.pager.range().end,u),l(s,()=>e.pager.range().total,null),a.addEventListener("change",h=>e.pager.setPageSize(Number(h.currentTarget.value))),l(a,o(A,{get each(){return e.pager.pageSizeChoices},children:h=>(()=>{var f=il();return f.value=h,l(f,h),f})()})),g.$$click=()=>e.pager.prev(),l(c,o(A,{get each(){return t()},children:h=>o(b,{when:h==="gap",get fallback(){return(()=>{var f=ol();return f.$$click=()=>e.pager.goto(h),l(f,h),k(()=>B(f,`px-2.5 py-1 rounded border ${h===e.pager.current()?"border-kick-500/30 bg-kick-500/20 text-kick-500":"border-slate-700 bg-slate-800 hover:bg-slate-700"}`)),f})()},get children(){return al()}})}),d),d.$$click=()=>e.pager.next(),k(h=>{var f=e.pager.current()===1,p=e.pager.current()===e.pager.total();return f!==h.e&&(g.disabled=h.e=f),p!==h.t&&(d.disabled=h.t=p),h},{e:void 0,t:void 0}),k(()=>a.value=e.pager.pageSize()),r}})};J(["click"]);var ul=v('<div style=display:flex;justify-content:space-between;align-items:center;margin-bottom:12px><h2 style=margin:0;font-size:16px>Topology</h2><button type=button class=tab style="border:1px solid var(--border);border-radius:4px;padding:4px 12px;border-bottom-color:var(--border)">'),dl=v("<div class=card style=border-color:var(--critical)><div class=card-title style=color:var(--critical)>Topology error</div><code>"),hl=v("<div class=empty>Loading topology…"),gl=v('<div class=card style=border-color:var(--warn)><div class=card-title style=color:var(--warn)> introspect failure(s)</div><ul style="margin:8px 0 0;padding-left:20px;font-family:var(--font-mono);font-size:12px">'),fl=v("<li>/<!>: "),vl=v("<table><thead><tr><th>Key</th><th>Source</th><th>Depends on</th></tr></thead><tbody>"),pl=v("<div class=card><div class=card-header><div class=card-title>Contributors (<!>)"),ml=v("<div class=empty>No contributors registered"),bl=v("<tr><td><span class=tree-key></span></td><td></td><td>"),$l=v("<table><thead><tr><th>Token</th><th>Scope</th><th>Kind</th><th>Resolved</th></tr></thead><tbody>"),xl=v("<div class=card><div class=card-header><div class=card-title>DI tokens (<!>)"),yl=v("<div class=empty>No DI tokens registered"),_l=v("<tr><td><span class=tree-key></span></td><td></td><td></td><td>"),wl=v("<div class=card><div class=card-header><div class=card-title>"),Sl=v("<div class=empty>"),kl=v("<span class=tree-meta>[<!>]"),Cl=v("<span class=tree-meta>v"),El=v("<span class=tree-meta>"),Tl=v("<div class=tree-meta>provides: "),Ml=v("<div class=tree-meta>requires: "),kt=v("<div class=tree-meta>"),Al=v("<div class=tree-node><span class=tree-key>"),Ct=v("<span style=margin-right:12px>: <strong style=color:var(--text)>"),Ll=()=>{const[e,t]=x(null),[r,n]=x(null),[s,i]=x(!1),u=async()=>{i(!0),n(null);try{t(await ee.topology())}catch(a){n(a instanceof Error?a.message:String(a))}finally{i(!1)}};return xe(()=>{u()}),[(()=>{var a=ul(),c=a.firstChild.nextSibling;return c.$$click=()=>{u()},l(c,()=>s()?"Refreshing…":"Refresh"),k(()=>c.disabled=s()),a})(),o(b,{get when(){return r()},children:a=>(()=>{var c=dl(),g=c.firstChild.nextSibling;return l(g,a),c})()}),o(b,{get when(){return e()},get fallback(){return hl()},children:a=>[o(b,{get when(){return a().errors.length>0},get children(){var c=gl(),g=c.firstChild,d=g.firstChild,h=g.nextSibling;return l(g,()=>a().errors.length,d),l(h,o(A,{get each(){return a().errors},children:f=>(()=>{var p=fl(),m=p.firstChild,y=m.nextSibling;return y.nextSibling,l(p,()=>f.kind,m),l(p,()=>f.name,y),l(p,()=>f.message,null),p})()})),c}}),o(Et,{get title(){return`Plugins (${a().plugins.length})`},get items(){return a().plugins},empty:"No plugins registered"}),o(Et,{get title(){return`Adapters (${a().adapters.length})`},get items(){return a().adapters},empty:"No adapters registered"}),o(Rl,{get rows(){return a().contributors}}),o(Bl,{get rows(){return a().diTokens}})]})]},Rl=e=>{const t=P(()=>e.rows??[]),r=ge(t);return(()=>{var n=pl(),s=n.firstChild.firstChild,i=s.firstChild.nextSibling;return i.nextSibling,l(s,()=>t().length,i),l(n,o(b,{get when(){return t().length>0},get fallback(){return ml()},get children(){return[(()=>{var u=vl(),a=u.firstChild.nextSibling;return l(a,o(A,{get each(){return r.page()},children:c=>(()=>{var g=bl(),d=g.firstChild,h=d.firstChild,f=d.nextSibling,p=f.nextSibling;return l(h,()=>c.key),l(f,()=>c.source),l(p,()=>c.dependsOn.join(", ")||"—"),g})()})),u})(),o(fe,{pager:r})]}}),null),n})()},Bl=e=>{const t=P(()=>e.rows??[]),r=ge(t);return(()=>{var n=xl(),s=n.firstChild.firstChild,i=s.firstChild.nextSibling;return i.nextSibling,l(s,()=>t().length,i),l(n,o(b,{get when(){return t().length>0},get fallback(){return yl()},get children(){return[(()=>{var u=$l(),a=u.firstChild.nextSibling;return l(a,o(A,{get each(){return r.page()},children:c=>(()=>{var g=_l(),d=g.firstChild,h=d.firstChild,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return l(h,()=>c.token),l(f,()=>c.scope),l(p,()=>c.kind),l(m,()=>c.instantiated?"yes":"no"),g})()})),u})(),o(fe,{pager:r})]}}),null),n})()},Et=e=>(()=>{var t=wl(),r=t.firstChild.firstChild;return l(r,()=>e.title),l(t,o(b,{get when(){return e.items.length>0},get fallback(){return(()=>{var n=Sl();return l(n,()=>e.empty),n})()},get children(){return o(A,{get each(){return e.items},children:n=>o(Pl,{item:n})})}}),null),t})();function ql(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(1)} GB`}function Ol(e){if(typeof e!="object"||e===null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}var Pl=e=>(()=>{var t=Al(),r=t.firstChild;return l(r,()=>e.item.name),l(t,o(b,{get when(){return e.item.kind},get children(){var n=kl(),s=n.firstChild.nextSibling;return s.nextSibling,l(n,()=>e.item.kind,s),n}}),null),l(t,o(b,{get when(){return e.item.version},get children(){var n=Cl();return n.firstChild,l(n,()=>e.item.version,null),n}}),null),l(t,o(b,{get when(){return typeof e.item.memoryBytes=="number"},get children(){var n=El();return l(n,()=>ql(e.item.memoryBytes)),n}}),null),l(t,o(b,{get when(){return e.item.tokens?.provides.length},get children(){var n=Tl();return n.firstChild,l(n,()=>e.item.tokens?.provides.join(", "),null),n}}),null),l(t,o(b,{get when(){return e.item.tokens?.requires.length},get children(){var n=Ml();return n.firstChild,l(n,()=>e.item.tokens?.requires.join(", "),null),n}}),null),l(t,o(b,{get when(){return Re(()=>!!e.item.state)()&&Object.keys(e.item.state).length>0},get children(){var n=kt();return l(n,o(A,{get each(){return Object.entries(e.item.state??{})},children:([s,i])=>(()=>{var u=Ct(),a=u.firstChild,c=a.nextSibling;return l(u,s,a),l(c,()=>Ol(i)),u})()})),n}}),null),l(t,o(b,{get when(){return e.item.metrics},children:n=>(()=>{var s=kt();return l(s,o(A,{get each(){return Object.entries(n())},children:([i,u])=>(()=>{var a=Ct(),c=a.firstChild,g=c.nextSibling;return l(a,i,c),l(g,u),a})()})),s})()}),null),t})();J(["click"]);var jl=v("<div class=overflow-x-auto><table><thead><tr><th>Method</th><th>Path</th><th>Controller</th><th>Handler</th><th>Middleware</th></tr></thead><tbody>"),Nl=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col sm:flex-row gap-3 mb-4"><div class="relative flex-1"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search routes (path, controller, handler)…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"></div><div class="flex gap-1">'),Il=v("<button type=button>"),Dl=v("<div class=empty>"),Ul=v('<tr><td><span></span></td><td class="font-mono text-sm"></td><td></td><td class=text-text-secondary></td><td class="text-text-muted text-xs">'),zl=["ALL","GET","POST","PUT","DELETE","PATCH"],Fl=()=>{const[e,t]=x(""),[r,n]=x("ALL"),s=P(()=>{let u=M.routes();r()!=="ALL"&&(u=u.filter(c=>c.method.toUpperCase()===r()));const a=e().trim().toLowerCase();return a&&(u=u.filter(c=>c.path.toLowerCase().includes(a)||c.controller.toLowerCase().includes(a)||c.handler.toLowerCase().includes(a))),u}),i=ge(()=>s());return(()=>{var u=Nl(),a=u.firstChild.firstChild,c=a.firstChild.nextSibling,g=a.nextSibling;return c.$$input=d=>t(d.currentTarget.value),l(g,o(A,{each:zl,children:d=>(()=>{var h=Il();return h.$$click=()=>n(d),l(h,d),k(()=>B(h,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${r()===d?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),h})()})),l(u,o(b,{get when(){return i.page().length>0},get fallback(){return(()=>{var d=Dl();return l(d,()=>e()||r()!=="ALL"?"No routes match the current filter":"No routes registered"),d})()},get children(){return[(()=>{var d=jl(),h=d.firstChild.firstChild.nextSibling;return l(h,o(A,{get each(){return i.page()},children:f=>(()=>{var p=Ul(),m=p.firstChild,y=m.firstChild,_=m.nextSibling,C=_.nextSibling,w=C.nextSibling,E=w.nextSibling;return l(y,()=>f.method),l(_,()=>f.path),l(C,()=>f.controller),l(w,()=>f.handler),l(E,(()=>{var S=Re(()=>!!f.middleware.length);return()=>S()?f.middleware.join(", "):"—"})()),k(()=>B(y,`text-xs font-bold ${Hl(f.method)}`)),p})()})),d})(),o(fe,{pager:i})]}}),null),k(()=>c.value=e()),u})()};function Hl(e){const t=e.toUpperCase();return t==="GET"?"text-emerald-400":t==="POST"?"text-cyan-400":t==="PUT"||t==="PATCH"?"text-amber-400":t==="DELETE"?"text-red-400":"text-text-secondary"}J(["input","click"]);var Gl=v("<div class=card style=border-color:var(--critical)><div class=card-title style=color:var(--critical)>Failed to load metrics</div><code>"),Vl=v("<div class=empty>Loading route metrics…"),Kl=v("<div class=grid>"),Wl=v("<table><thead><tr><th>Route</th><th style=text-align:right>Calls</th><th style=text-align:right>Avg</th><th style=text-align:right>p50</th><th style=text-align:right>p95</th><th style=text-align:right>p99</th><th style=text-align:right>Max</th></tr></thead><tbody>"),Jl=v("<div class=card><div class=card-header><div class=card-title>Per-route latency"),Ql=v("<div class=empty>No requests recorded yet"),Yl=v("<tr><td></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right>"),Xl=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),Zl=()=>{const[e,t]=x(null),[r,n]=x(null),s=async()=>{try{t(await ee.routes()),n(null)}catch(u){n(u instanceof Error?u.message:String(u))}};xe(()=>{s();const u=setInterval(()=>{s()},2e3);return()=>clearInterval(u)});const i=P(()=>{const u=e();return u?Object.entries(u.routeLatency).map(([a,c])=>Object.assign({key:a},c,{avg:c.count>0?c.totalMs/c.count:0})).toSorted((a,c)=>c.count-a.count):[]});return[o(b,{get when(){return r()},children:u=>(()=>{var a=Gl(),c=a.firstChild.nextSibling;return l(c,u),a})()}),o(b,{get when(){return e()},get fallback(){return Vl()},children:u=>[(()=>{var a=Kl();return l(a,o(we,{title:"Requests",metric:"requests",get value(){return u().requests.toString()}}),null),l(a,o(we,{title:"Server errors",metric:"server-errors",get value(){return u().serverErrors.toString()}}),null),l(a,o(we,{title:"Client errors",metric:"client-errors",get value(){return u().clientErrors.toString()}}),null),l(a,o(we,{title:"Error rate",metric:"error-rate",get value(){return Fe(u().errorRate)}}),null),l(a,o(we,{title:"Uptime",metric:"uptime",get value(){return dt(u().uptimeSeconds)}}),null),a})(),(()=>{var a=Jl();return a.firstChild,l(a,o(b,{get when(){return i().length>0},get fallback(){return Ql()},get children(){var c=Wl(),g=c.firstChild,d=g.firstChild.firstChild.nextSibling.nextSibling;d.firstChild;var h=d.nextSibling;h.firstChild;var f=h.nextSibling;f.firstChild;var p=f.nextSibling;p.firstChild;var m=p.nextSibling;m.firstChild;var y=g.nextSibling;return l(d,o(Y,{metric:"latency.avg",placement:"bottom"}),null),l(h,o(Y,{metric:"latency.p50",placement:"bottom"}),null),l(f,o(Y,{metric:"latency.p95",placement:"bottom"}),null),l(p,o(Y,{metric:"latency.p99",placement:"bottom"}),null),l(m,o(Y,{metric:"latency.max",placement:"bottom"}),null),l(y,o(A,{get each(){return i()},children:_=>(()=>{var C=Yl(),w=C.firstChild,E=w.nextSibling,S=E.nextSibling,T=S.nextSibling,F=T.nextSibling,I=F.nextSibling,q=I.nextSibling;return l(w,()=>_.key),l(E,()=>_.count),l(S,()=>oe(_.avg)),l(T,()=>oe(_.p50)),l(F,()=>oe(_.p95)),l(I,()=>oe(_.p99)),l(q,()=>oe(_.maxMs)),C})()})),c}}),null),a})()]})]},we=e=>(()=>{var t=Xl(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),t})(),es=v('<button type=button class="text-text-muted hover:text-text-strong p-1"aria-label=Back><svg class="w-4 h-4"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M15 19l-7-7 7-7">'),Tt=v('<div class="flex flex-wrap gap-1">'),ts=v('<div class="bg-surface-2/50 rounded-lg border border-border-strong p-3 space-y-2 text-sm">'),rs=v("<span>"),ns=v('<div class="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"><div class="bg-surface-1 border border-border-strong rounded-2xl p-6 max-w-2xl w-full shadow-2xl max-h-[90vh] overflow-y-auto"><div class="flex items-start justify-between mb-4"><div><div class="flex items-center gap-2 mb-1"><h2 class="text-base font-semibold font-mono text-text-body break-all"></h2></div><div class="flex flex-wrap gap-2 mt-2"><span></span><span class="bg-border-strong/50 text-text-strong px-2 py-0.5 rounded text-xs font-semibold"></span><span></span></div></div><button type=button class="text-slate-500 hover:text-slate-300 p-1"aria-label=Close><svg class="w-5 h-5"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M6 18L18 6M6 6l12 12">'),Mt=v('<span class="text-text-muted text-sm">None'),ls=v('<button type=button class="bg-surface-2 text-kick-500 hover:bg-border-strong px-2.5 py-1 rounded text-xs font-mono border border-border-strong transition-colors">'),ss=v('<button type=button class="bg-surface-2 text-amber-400 hover:bg-border-strong px-2.5 py-1 rounded text-xs font-mono border border-border-strong transition-colors">'),is=v('<div class=mb-4><h3 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">'),as=v('<div class="flex justify-between"><span class=text-text-secondary></span><span class=tabular-nums>'),[nt,Me]=x(null),[os,We]=x([]);function He(e){We([]),Me(e)}function At(e){const t=nt();t&&t!==e&&We(r=>[...r,t]),Me(e)}function cs(){We(e=>{if(e.length===0)return Me(null),e;const t=e.slice(0,-1);return Me(e[e.length-1]),t})}function Lt(){Me(null),We([])}var us=()=>{const e=P(()=>{const r=nt();if(!r)return null;const n=M.container().find(s=>s.token===r);return n||{token:r,kind:void 0,scope:void 0,dependencies:[]}}),t=P(()=>{const r=nt();return r?M.container().filter(n=>n.dependencies?.includes(r)).map(n=>n.token):[]});return o(b,{get when(){return e()},children:r=>(()=>{var n=ns(),s=n.firstChild,i=s.firstChild.firstChild,u=i.firstChild,a=u.firstChild,c=u.nextSibling.firstChild,g=c.nextSibling,d=g.nextSibling,h=i.nextSibling;return n.$$click=f=>{f.target===f.currentTarget&&Lt()},l(u,o(b,{get when(){return os().length>0},get children(){var f=es();return f.$$click=cs,f}}),a),l(a,()=>r().token),l(c,()=>r().kind??"unknown"),l(g,()=>r().scope??"singleton"),l(d,()=>gs(r())),h.$$click=Lt,l(s,o(qe,{title:"Dependencies",get children(){return o(b,{get when(){return(r().dependencies?.length??0)>0},get fallback(){return Mt()},get children(){var f=Tt();return l(f,o(A,{get each(){return r().dependencies},children:p=>(()=>{var m=ls();return m.$$click=()=>At(p),l(m,p),m})()})),f}})}}),null),l(s,o(qe,{title:"Dependents",get children(){return o(b,{get when(){return t().length>0},get fallback(){return Mt()},get children(){var f=Tt();return l(f,o(A,{get each(){return t()},children:p=>(()=>{var m=ss();return m.$$click=()=>At(p),l(m,p),m})()})),f}})}}),null),l(s,o(qe,{title:"Resolve stats",get children(){var f=ts();return l(f,o(Oe,{label:"Resolve count",get value(){return String(r().resolveCount??0)}}),null),l(f,o(b,{get when(){return r().firstResolved},children:p=>o(Oe,{label:"First resolved",get value(){return new Date(p()).toLocaleString()}})}),null),l(f,o(b,{get when(){return r().lastResolved},children:p=>o(Oe,{label:"Last resolved",get value(){return new Date(p()).toLocaleString()}})}),null),l(f,o(b,{get when(){return r().resolveDurationMs!=null},get children(){return o(Oe,{label:"Resolution duration",get value(){return`${(r().resolveDurationMs??0).toFixed(2)} ms`}})}}),null),f}}),null),l(s,o(qe,{title:"PostConstruct",get children(){var f=rs();return l(f,()=>r().postConstructStatus??"none"),k(()=>B(f,`px-2 py-0.5 rounded text-xs font-semibold ${fs(r().postConstructStatus)}`)),f}}),null),k(f=>{var p=`px-2 py-0.5 rounded text-xs font-semibold ${ds(r().kind)}`,m=`px-2 py-0.5 rounded text-xs font-semibold ${hs(r())}`;return p!==f.e&&B(c,f.e=p),m!==f.t&&B(d,f.t=m),f},{e:void 0,t:void 0}),n})()})},qe=e=>(()=>{var t=is(),r=t.firstChild;return l(r,()=>e.title),l(t,()=>e.children,null),t})(),Oe=e=>(()=>{var t=as(),r=t.firstChild,n=r.nextSibling;return l(r,()=>e.label),l(n,()=>e.value),t})();function ds(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function hs(e){return e.postConstructStatus==="failed"?"bg-red-900/50 text-red-300":e.instantiated?"bg-emerald-900/50 text-emerald-300":"bg-amber-900/50 text-amber-300"}function gs(e){return e.postConstructStatus==="failed"?"failed":e.instantiated?"active":"registered"}function fs(e){return e==="done"?"bg-emerald-900/50 text-emerald-300":e==="failed"?"bg-red-900/50 text-red-300":"bg-border-strong/50 text-text-secondary"}J(["click"]);var vs=v("<div class=overflow-x-auto><table><thead><tr><th class=w-6 aria-label=expand></th><th>Token</th><th>Kind</th><th>Scope</th><th>Status</th><th class=text-right>Resolves</th><th class=text-right>Deps</th></tr></thead><tbody>"),ps=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col gap-3 mb-4"><div class=relative><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search tokens…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"></div><div class="flex flex-col sm:flex-row gap-3"><div class="flex gap-1 items-center"><span class="text-xs text-text-muted mr-1">Kind:</span></div><div class="flex gap-1 items-center"><span class="text-xs text-text-muted mr-1">Scope:'),Rt=v("<button type=button>"),ms=v("<div class=empty>"),bs=v('<tr class="cursor-pointer select-none"><td><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg></td><td class="font-mono text-sm"></td><td><span></span></td><td><span class="bg-border-strong/50 text-text-strong px-2 py-0.5 rounded text-xs font-semibold"></span></td><td><span></span></td><td class="text-right tabular-nums"></td><td class="text-right text-text-muted text-xs">'),$s=v('<tr><td colspan=7 class="bg-surface-2/30 px-6 py-4 border-b border-border">'),xs=v('<div class="flex flex-wrap gap-1">'),ys=v('<div class="flex justify-between"><span class=text-text-secondary>Duration</span><span class=tabular-nums>ms'),_s=v('<div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">Dependencies</h4></div><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">Resolve Stats</h4><div class="space-y-1 text-sm"><div class="flex justify-between"><span class=text-text-secondary>Resolve count</span><span class=tabular-nums></span></div></div></div><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">PostConstruct</h4><span></span></div><div class="md:col-span-2 flex justify-end"><button type=button class="px-3 py-1.5 text-xs font-semibold rounded-lg bg-kick-500/20 text-kick-500 border border-kick-500/30 hover:bg-kick-500/30 transition-colors">View full details'),ws=v('<span class="text-text-muted text-sm">None'),Ss=v('<button type=button class="bg-border-strong/50 text-kick-500 hover:bg-border-strong px-2 py-0.5 rounded text-xs font-mono transition-colors">'),ks=v('<div class="flex justify-between"><span class=text-text-secondary>First resolved</span><span class=text-xs>'),Cs=v('<div class="flex justify-between"><span class=text-text-secondary>Last resolved</span><span class=text-xs>'),Es=["ALL","controller","service","repository","other"],Ts=["ALL","singleton","transient","request"],Ms=()=>{const[e,t]=x(""),[r,n]=x("ALL"),[s,i]=x("ALL"),[u,a]=x(new Set),c=P(()=>{let h=M.container();if(r()!=="ALL"){const p=r();h=h.filter(m=>p==="other"?!["controller","service","repository"].includes(m.kind??""):m.kind===p)}s()!=="ALL"&&(h=h.filter(p=>p.scope===s()));const f=e().trim().toLowerCase();return f&&(h=h.filter(p=>p.token.toLowerCase().includes(f))),h}),g=ge(()=>c()),d=h=>{a(f=>{const p=new Set(f);return p.has(h)?p.delete(h):p.add(h),p})};return(()=>{var h=ps(),f=h.firstChild.firstChild,p=f.firstChild.nextSibling,m=f.nextSibling.firstChild;m.firstChild;var y=m.nextSibling;return y.firstChild,p.$$input=_=>t(_.currentTarget.value),l(m,o(A,{each:Es,children:_=>(()=>{var C=Rt();return C.$$click=()=>n(_),l(C,_),k(()=>B(C,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${r()===_?Rs(_):"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),C})()}),null),l(y,o(A,{each:Ts,children:_=>(()=>{var C=Rt();return C.$$click=()=>i(_),l(C,_),k(()=>B(C,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${s()===_?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),C})()}),null),l(h,o(b,{get when(){return g.page().length>0},get fallback(){return(()=>{var _=ms();return l(_,()=>e()||r()!=="ALL"||s()!=="ALL"?"No tokens match the current filter":"No DI registrations"),_})()},get children(){return[(()=>{var _=vs(),C=_.firstChild.firstChild,w=C.firstChild.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;w.firstChild;var E=C.nextSibling;return l(w,o(Y,{metric:"resolve.count",placement:"bottom"}),null),l(E,o(A,{get each(){return g.page()},children:S=>[(()=>{var T=bs(),F=T.firstChild,I=F.firstChild,q=F.nextSibling,R=q.nextSibling,X=R.firstChild,z=R.nextSibling,V=z.firstChild,D=z.nextSibling,H=D.firstChild,K=D.nextSibling,Z=K.nextSibling;return T.$$click=()=>d(S.token),l(q,()=>S.token),l(X,()=>S.kind??"unknown"),l(V,()=>S.scope??"—"),l(H,()=>qs(S)),l(K,()=>S.resolveCount??0),l(Z,()=>S.dependencies?.length??0),k(ae=>{var ne=`w-3 h-3 text-text-muted transition-transform ${u().has(S.token)?"rotate-90":""}`,ue=`px-2 py-0.5 rounded text-xs font-semibold ${Ls(S.kind)}`,_e=`px-2 py-0.5 rounded text-xs font-semibold ${Bs(S)}`;return ne!==ae.e&&N(I,"class",ae.e=ne),ue!==ae.t&&B(X,ae.t=ue),_e!==ae.a&&B(H,ae.a=_e),ae},{e:void 0,t:void 0,a:void 0}),T})(),o(b,{get when(){return u().has(S.token)},get children(){var T=$s(),F=T.firstChild;return l(F,o(As,{registration:S})),T}})]})),_})(),o(fe,{pager:g})]}}),null),k(()=>p.value=e()),h})()},As=e=>(()=>{var t=_s(),r=t.firstChild;r.firstChild;var n=r.nextSibling,s=n.firstChild.nextSibling,i=s.firstChild.firstChild.nextSibling,u=n.nextSibling,a=u.firstChild;a.firstChild;var c=a.nextSibling,g=u.nextSibling.firstChild;return l(r,o(b,{get when(){return(e.registration.dependencies?.length??0)>0},get fallback(){return ws()},get children(){var d=xs();return l(d,o(A,{get each(){return e.registration.dependencies},children:h=>(()=>{var f=Ss();return f.$$click=p=>{p.stopPropagation(),He(h)},N(f,"title",`Open detail for ${h}`),l(f,h),f})()})),d}}),null),l(i,()=>e.registration.resolveCount??0),l(s,o(b,{get when(){return e.registration.firstResolved},children:d=>(()=>{var h=ks(),f=h.firstChild.nextSibling;return l(f,()=>new Date(d()).toLocaleTimeString()),h})()}),null),l(s,o(b,{get when(){return e.registration.lastResolved},children:d=>(()=>{var h=Cs(),f=h.firstChild.nextSibling;return l(f,()=>new Date(d()).toLocaleTimeString()),h})()}),null),l(s,o(b,{get when(){return e.registration.resolveDurationMs!=null},get children(){var d=ys(),h=d.firstChild.nextSibling,f=h.firstChild;return l(h,()=>(e.registration.resolveDurationMs??0).toFixed(2),f),d}}),null),l(a,o(Y,{metric:"post-construct"}),null),l(c,()=>e.registration.postConstructStatus??"none"),g.$$click=d=>{d.stopPropagation(),He(e.registration.token)},k(()=>B(c,`px-2 py-0.5 rounded text-xs font-semibold ${Os(e.registration.postConstructStatus)}`)),t})();function Ls(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function Rs(e){return e==="controller"?"bg-violet-900/50 text-violet-300 border-violet-700/50":e==="service"?"bg-blue-900/50 text-blue-300 border-blue-700/50":e==="repository"?"bg-teal-900/50 text-teal-300 border-teal-700/50":e==="other"?"bg-border-strong/50 text-text-strong border-border-strong/50":"bg-kick-500/20 text-kick-500 border-kick-500/30"}function Bs(e){return e.postConstructStatus==="failed"?"bg-red-900/50 text-red-300":e.instantiated?"bg-emerald-900/50 text-emerald-300":"bg-amber-900/50 text-amber-300"}function qs(e){return e.postConstructStatus==="failed"?"failed":e.instantiated?"active":"registered"}function Os(e){return e==="done"?"bg-emerald-900/50 text-emerald-300":e==="failed"?"bg-red-900/50 text-red-300":"bg-border-strong/50 text-text-secondary"}J(["input","click"]);var Ps=v('<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">'),js=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="relative mb-4"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search queues by name…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500">'),Ns=v('<div class=card><div class=card-title>Queues</div><p class="text-text-muted text-sm mt-2">QueueAdapter not detected. Install <code class="font-mono text-kick-500">@forinda/kickjs-queue</code> and register the adapter in your bootstrap to see queue stats here.'),Is=v("<div class=empty>No queues registered"),Ds=v("<div class=empty>No queues match the search"),Us=v('<div class="grid grid-cols-2 gap-2 text-sm">'),zs=v('<div class="bg-surface-2/50 rounded-lg border border-border-strong p-4"><h3 class="font-mono text-sm font-semibold text-kick-500 mb-3 break-all">'),Fs=v('<div class="text-red-400 text-sm">'),Hs=v('<div class="flex justify-between"><span class=text-text-secondary></span><span>'),Gs=()=>{const[e,t]=x(""),r=P(()=>{const s=M.queues().queues,i=e().trim().toLowerCase();return i?s.filter(u=>u.name.toLowerCase().includes(i)):s}),n=ge(()=>r());return o(b,{get when(){return M.queues().enabled},get fallback(){return Ns()},get children(){return o(b,{get when(){return M.queues().queues.length>0},get fallback(){return Is()},get children(){var s=js(),i=s.firstChild.firstChild.nextSibling;return i.$$input=u=>t(u.currentTarget.value),l(s,o(b,{get when(){return n.page().length>0},get fallback(){return Ds()},get children(){return[(()=>{var u=Ps();return l(u,o(A,{get each(){return n.page()},children:a=>o(Vs,{queue:a})})),u})(),o(fe,{pager:n})]}}),null),k(()=>i.value=e()),s}})}})},Vs=e=>(()=>{var t=zs(),r=t.firstChild;return l(r,()=>e.queue.name),l(t,o(b,{get when(){return!e.queue.error},get fallback(){return(()=>{var n=Fs();return l(n,()=>e.queue.error),n})()},get children(){var n=Us();return l(n,o(me,{label:"Waiting",get value(){return e.queue.waiting??0},colour:"text-amber-400"}),null),l(n,o(me,{label:"Active",get value(){return e.queue.active??0},colour:"text-blue-400"}),null),l(n,o(me,{label:"Completed",get value(){return e.queue.completed??0},colour:"text-emerald-400"}),null),l(n,o(me,{label:"Failed",get value(){return e.queue.failed??0},colour:"text-red-400"}),null),l(n,o(me,{label:"Delayed",get value(){return e.queue.delayed??0},colour:"text-violet-400"}),null),l(n,o(me,{label:"Paused",get value(){return e.queue.paused??0},colour:"text-text-secondary"}),null),n}}),null),t})(),me=e=>(()=>{var t=Hs(),r=t.firstChild,n=r.nextSibling;return l(r,()=>e.label),l(n,()=>e.value),k(()=>B(n,`font-semibold tabular-nums ${e.colour}`)),t})();J(["input"]);function Ks(){let e=new Map,t=new Set;return{on:(r,n)=>{let s=e.get(r);return s||(s=new Set,e.set(r,s)),s.add(n),()=>{let i=e.get(r);i?.delete(n),i&&i.size===0&&e.delete(r)}},onAny:r=>(t.add(r),()=>{t.delete(r)}),dispatch:r=>{let n=e.get(r.type);if(n&&n.size>0)for(let s of[...n])try{s(r.payload)}catch(i){console.error(`[kick:devtools-bus] handler for "${r.type}" threw`,i)}if(t.size>0)for(let s of[...t])try{s(r)}catch(i){console.error("[kick:devtools-bus] onAny handler threw",i)}}}}function Ws(e={}){let t=Ks(),r=e.channel===!1?null:e.channel??"kick-devtools",n=r!=null&&typeof BroadcastChannel<"u"?new BroadcastChannel(r):null;n?.addEventListener("message",f=>{let p=f.data;!p||typeof p.type!="string"||typeof p.ts!="number"||t.dispatch({...p,__kick_origin:"broadcast"})});let s=null,i=0,u=null,a=e.reconnectMs??500,c=e.reconnectMaxMs??5e3,g=()=>{e.wsUrl&&(typeof WebSocket>"u"||s&&(s.readyState===WebSocket.OPEN||s.readyState===WebSocket.CONNECTING)||(s=new WebSocket(e.wsUrl),s.addEventListener("open",()=>{i=0}),s.addEventListener("message",f=>{try{let p=JSON.parse(String(f.data));if(!p||typeof p.type!="string"||typeof p.ts!="number")return;t.dispatch({...p,__kick_origin:"ws"})}catch{}}),s.addEventListener("close",()=>{s=null,d()}),s.addEventListener("error",()=>{d()})))},d=()=>{if(!e.wsUrl||u!=null)return;i+=1;let f=Math.min(i*a,c);u=setTimeout(()=>{u=null,g()},f)},h=f=>{n?.postMessage(f),s&&s.readyState===WebSocket.OPEN?s.send(JSON.stringify(f)):e.wsUrl&&g()};return{on(f,p){return g(),t.on(f,p)},onAny(f){return g(),t.onAny(f)},emit(f,p){let m={type:f,payload:p,ts:Date.now(),__kick_origin:"local"};t.dispatch(m),h(m)}}}var ke=null,[Js,lt]=x([]);function Qs(){if(ke)return()=>{};const e=`${ye()}/_bus`,t=location.protocol==="https:"?"wss:":"ws:",r=ve(),n=r?`?token=${encodeURIComponent(r)}`:"",s=`${t}//${location.host}${e}${n}`;ke=Ws({channel:"kick-devtools",wsUrl:s});const i=ke.onAny(u=>{lt(a=>{const c=a.length>=500?a.slice(1):a.slice();return c.push(u),c})});return()=>{i(),ke=null,lt([])}}function Ge(){return Js}function Ys(){lt([])}function Xs(){return ke}var Qe=200;function Zs(e){if(e==null)return String(e);if(typeof e=="bigint")return`${e.toString()}n`;if(typeof e!="object")return String(e);const t=new WeakSet,r=(s,i)=>{if(typeof i=="bigint")return`${i.toString()}n`;if(i instanceof Error)return{name:i.name,message:i.message};if(i&&typeof i=="object"){if(t.has(i))return"[Circular]";t.add(i)}return i};let n;try{n=JSON.stringify(e,r)}catch{n="[unserialisable]"}return n===void 0&&(n=String(e)),n.length>Qe?`${n.slice(0,Qe)}… (+${n.length-Qe} chars)`:n}function Zt(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}.${String(t.getMilliseconds()).padStart(3,"0")}`}var ei=v("<table><thead><tr><th>Time</th><th>Dialect</th><th class=text-right>Duration</th><th>SQL</th></tr></thead><tbody>"),ti=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="grid mb-4"></div><input type=text placeholder="Filter by SQL (substring)…"class="w-full bg-surface-2 border border-border-strong rounded-lg px-3 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500 mb-4">'),ri=v("<div class=empty>No queries yet. <code>kick/db</code> emits a <code>db:query</code> event per statement when DevTools is installed — run a query to see it here."),ni=v("<code class=break-all>"),li=v("<tr><td class=dimmed></td><td></td><td class=text-right></td><td>"),si=v("<span style=color:var(--color-red-400)>"),ii=v("<div class=card><div class=card-header><div class=card-title></div></div><div class=card-value>"),Ye=50,ai=300,oi=()=>{const[e,t]=x([]),[r,n]=x(""),s=g=>{t(d=>{const h=d.length>=ai?d.slice(1):d.slice();return h.push(g),h})},i=(g,d)=>{const h=g,f=h.error;return{sql:h.sql,parameters:h.parameters,durationMs:0,dialect:h.dialect,error:f instanceof Error?f.message:String(f??"query error"),ts:d}};xe(()=>{for(const f of Ge()())f.type==="db:query"?s({...f.payload,ts:f.ts}):f.type==="db:query-error"&&s(i(f.payload,f.ts));const g=Xs(),d=g?.on("db:query",f=>{const p=f;s({...p,ts:p.ts??Date.now()})}),h=g?.on("db:query-error",f=>s(i(f,Date.now())));ie(()=>{d?.(),h?.()})});const u=P(()=>{const g=e(),d=g.filter(p=>p.error).length,h=g.filter(p=>p.durationMs>=Ye).length,f=g.length;return{total:f,errors:d,slow:h,avg:f?g.reduce((p,m)=>p+m.durationMs,0)/f:0}}),a=P(()=>{const g=r().trim().toLowerCase();return[...g?e().filter(d=>d.sql.toLowerCase().includes(g)):e()].toReversed()}),c=ge(()=>a());return(()=>{var g=ti(),d=g.firstChild,h=d.nextSibling;return l(d,o(Pe,{label:"Queries",get value(){return String(u().total)}}),null),l(d,o(Pe,{label:"Errors",get value(){return String(u().errors)},get tone(){return u().errors?"err":void 0}}),null),l(d,o(Pe,{label:`Slow (≥${Ye}ms)`,get value(){return String(u().slow)},get tone(){return u().slow?"warn":void 0}}),null),l(d,o(Pe,{label:"Avg duration",get value(){return oe(u().avg)}}),null),h.$$input=f=>n(f.currentTarget.value),l(g,o(b,{get when(){return e().length},get fallback(){return ri()},get children(){return[(()=>{var f=ei(),p=f.firstChild.nextSibling;return l(p,o(A,{get each(){return c.page()},children:m=>(()=>{var y=li(),_=y.firstChild,C=_.nextSibling,w=C.nextSibling,E=w.nextSibling;return l(_,()=>Zt(m.ts)),l(C,()=>m.dialect??"—"),l(w,()=>oe(m.durationMs)),l(E,o(b,{get when(){return!m.error},get fallback(){return(()=>{var S=si();return l(S,()=>m.error),S})()},get children(){var S=ni();return l(S,()=>m.sql),S}})),k(S=>ct(w,m.durationMs>=Ye?"color:var(--color-amber-400);font-weight:600":"",S)),y})()})),f})(),o(fe,{pager:c})]}}),null),k(()=>h.value=r()),g})()},Pe=e=>(()=>{var t=ii(),r=t.firstChild,n=r.firstChild,s=r.nextSibling;return l(n,()=>e.label),l(s,()=>e.value),k(i=>ct(s,e.tone==="err"?"color:var(--color-red-400)":e.tone==="warn"?"color:var(--color-amber-400)":"",i)),t})();J(["input"]);var ci=v("<div class=space-y-6>"),ui=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="relative mb-4"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Filter graph (token or kind)…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500">'),di=v("<div class=empty>"),hi=v("<div class=space-y-1>"),gi=v('<div><button type=button><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2.5 d="M9 5l7 7-7 7"></path></svg><span></span><span class="ml-2 text-text-muted font-normal normal-case">(<!>)'),fi=v('<span class="bg-border-strong/50 text-text-secondary px-1.5 py-0.5 rounded text-xs">'),vi=v('<span class="text-text-muted text-xs ml-auto tabular-nums"> resolves'),pi=v('<div class="ml-8 mt-1 space-y-0.5">'),mi=v('<button type=button class="w-full text-left px-3 py-2 rounded-lg hover:bg-surface-2/50 transition-colors group"><div class="flex items-center gap-2"><span></span><span class="font-mono text-sm text-text-body break-all">'),bi=v('<div class="flex items-center gap-2 text-xs text-text-muted hover:text-text-strong"><svg class="w-3 h-3 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M13 7l5 5-5 5M6 12h12"></path></svg><span></span><span class=font-mono>'),$i=[{id:"controllers",label:"Controllers",match:e=>e==="controller"},{id:"services",label:"Services",match:e=>e==="service"},{id:"repositories",label:"Repositories",match:e=>e==="repository"},{id:"other",label:"Other",match:e=>!["controller","service","repository"].includes(e??"")}],xi=()=>{const[e,t]=x(""),r=P(()=>{const s=M.container(),i=e().trim().toLowerCase();return i?s.filter(u=>u.token.toLowerCase().includes(i)||(u.kind??"").toLowerCase().includes(i)):s}),n=P(()=>$i.map(s=>Object.assign(s,{nodes:r().filter(i=>s.match(i.kind))})));return(()=>{var s=ui(),i=s.firstChild.firstChild.nextSibling;return i.$$input=u=>t(u.currentTarget.value),l(s,o(b,{get when(){return r().length>0},get fallback(){return(()=>{var u=di();return l(u,()=>e()?"No nodes match the filter":"No DI registrations to graph"),u})()},get children(){var u=ci();return l(u,o(A,{get each(){return n()},children:a=>o(b,{get when(){return a.nodes.length>0},get children(){return o(yi,{get label(){return a.label},get nodes(){return a.nodes}})}})})),u}}),null),k(()=>i.value=e()),s})()},yi=e=>{const t=P(()=>e.nodes??[]),r=ge(t),n=`kickjs-devtools-graph-collapsed-${e.label}`,s=()=>{try{return localStorage.getItem(n)==="1"}catch{return!1}},[i,u]=x(s()),a=()=>{const c=!i();u(c);try{c?localStorage.setItem(n,"1"):localStorage.removeItem(n)}catch{}};return(()=>{var c=gi(),g=c.firstChild,d=g.firstChild,h=d.nextSibling,f=h.nextSibling,p=f.firstChild.nextSibling;return p.nextSibling,g.$$click=a,l(h,()=>e.label),l(f,()=>t().length,p),l(c,o(b,{get when(){return!i()},get children(){return[(()=>{var m=hi();return l(m,o(A,{get each(){return r.page()},children:y=>o(_i,{node:y})})),m})(),o(b,{get when(){return r.total()>1},get children(){return o(fe,{pager:r})}})]}}),null),k(m=>{var y=!i(),_=`w-full flex items-center text-left text-xs font-semibold uppercase tracking-wider mb-2 ${wi(e.label)} cursor-pointer hover:opacity-80 transition-opacity`,C=`w-3 h-3 mr-1.5 transition-transform ${i()?"":"rotate-90"}`;return y!==m.e&&N(g,"aria-expanded",m.e=y),_!==m.t&&B(g,m.t=_),C!==m.a&&N(d,"class",m.a=C),m},{e:void 0,t:void 0,a:void 0}),c})()},_i=e=>{const t=()=>e.node.dependencies??[];return(()=>{var r=mi(),n=r.firstChild,s=n.firstChild,i=s.nextSibling;return r.$$click=()=>He(e.node.token),l(s,()=>er(e.node.kind)),l(i,()=>e.node.token),l(n,o(b,{get when(){return e.node.scope},get children(){var u=fi();return l(u,()=>e.node.scope),u}}),null),l(n,o(b,{get when(){return(e.node.resolveCount??0)>0},get children(){var u=vi(),a=u.firstChild;return l(u,()=>e.node.resolveCount,a),u}}),null),l(r,o(b,{get when(){return t().length>0},get children(){var u=pi();return l(u,o(A,{get each(){return t()},children:a=>(()=>{var c=bi(),g=c.firstChild.nextSibling,d=g.nextSibling;return c.$$click=h=>{h.stopPropagation(),He(a)},l(g,()=>Si(a)),l(d,a),k(()=>B(g,`px-1.5 py-0.5 rounded text-xs font-semibold ${ki(a)}`)),c})()})),u}}),null),k(()=>B(s,`px-2 py-0.5 rounded text-xs font-semibold ${tr(e.node.kind)}`)),r})()};function er(e){return e==="controller"?"ctrl":e==="service"?"svc":e==="repository"?"repo":"other"}function tr(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function wi(e){return e==="Controllers"?"text-violet-400":e==="Services"?"text-blue-400":e==="Repositories"?"text-teal-400":"text-text-secondary"}function Si(e){return er(M.container().find(t=>t.token===e)?.kind)}function ki(e){return tr(M.container().find(t=>t.token===e)?.kind)}J(["input","click"]);var Ci=v("<div class=overflow-x-auto><table><thead><tr><th style=width:140px>Time</th><th style=width:200px>Type</th><th style=width:120px>Source</th><th>Payload</th></tr></thead><tbody>"),Ei=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col sm:flex-row gap-3 mb-4 items-stretch sm:items-center"><input type=text placeholder="Filter by event type (substring)…"class="flex-1 bg-surface-2 border border-border-strong rounded-lg px-3 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"><div class="flex gap-2"><button type=button></button><button type=button class="px-3 py-1.5 text-xs font-semibold rounded-lg bg-surface-2 text-text-secondary border border-border-strong hover:text-text-body transition-colors">Clear</button></div></div><div class="text-xs text-text-muted mb-3 font-mono">/<!> buffered'),Ti=v("<div class=empty>"),Mi=v('<tr><td class="font-mono text-xs text-text-muted"></td><td class="font-mono text-xs"></td><td class="font-mono text-xs text-text-secondary"></td><td class="font-mono text-xs"><code class="text-text-body break-all">'),Ai=()=>{const e=Ge(),[t,r]=x(""),[n,s]=x(!1),[i,u]=x(null),a=()=>{s(d=>{const h=!d;return u(h?e():null),h})},c=P(()=>{const d=i()??e(),h=t().trim().toLowerCase();return[...h?d.filter(f=>f.type.toLowerCase().includes(h)):d].toReversed()}),g=ge(()=>c());return(()=>{var d=Ei(),h=d.firstChild,f=h.firstChild,p=f.nextSibling.firstChild,m=p.nextSibling,y=h.nextSibling,_=y.firstChild,C=_.nextSibling;return C.nextSibling,f.$$input=w=>r(w.currentTarget.value),p.$$click=a,l(p,()=>n()?"▶ Resume":"⏸ Pause"),m.$$click=()=>Ys(),l(y,()=>e().length,_),l(y,500,C),l(y,o(b,{get when(){return n()},children:" · paused"}),null),l(y,o(b,{get when(){return t().trim()},get children(){return[' · filter: "',Re(()=>t().trim()),'"']}}),null),l(d,o(b,{get when(){return g.page().length>0},get fallback(){return(()=>{var w=Ti();return l(w,o(b,{get when(){return e().length===0},fallback:"No events match the current filter",children:"No events yet — emits from kickjs-db, plugins, or the panel itself land here."})),w})()},get children(){return[(()=>{var w=Ci(),E=w.firstChild.firstChild.nextSibling;return l(E,o(A,{get each(){return g.page()},children:S=>(()=>{var T=Mi(),F=T.firstChild,I=F.nextSibling,q=I.nextSibling,R=q.nextSibling.firstChild;return l(F,()=>Zt(S.ts)),l(I,()=>S.type),l(q,()=>S.pluginId??"—"),l(R,()=>Zs(S.payload)),T})()})),w})(),o(fe,{pager:g})]}}),null),k(()=>B(p,`px-3 py-1.5 text-xs font-semibold rounded-lg border transition-colors ${n()?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),k(()=>f.value=t()),d})()};J(["input","click"]);var Li=v("<div style=display:flex;flex-direction:column;height:100%>"),Ri=v('<iframe title="custom devtools tab"sandbox="allow-scripts allow-same-origin allow-forms"style=flex:1;width:100%;border:none;background:var(--bg)>'),Bi=v("<div style=padding:16px><div class=card>"),qi=v("<div style=color:var(--text-dim);font-size:12px>"),Oi=v('<div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)"><div><div style=font-weight:600></div></div><button type=button class=tab style="border:1px solid var(--border);border-radius:4px;padding:6px 14px;border-bottom-color:var(--border)">'),Pi=v("<div class=card><div class=card-title>Last response</div><code>"),ji=v("<div style=padding:16px;flex:1;overflow:auto>"),Ni=e=>(()=>{var t=Li();return l(t,o(b,{get when(){return e.tab.view.type==="iframe"},get children(){return o(Ii,{get view(){return e.tab.view}})}}),null),l(t,o(b,{get when(){return e.tab.view.type==="launch"},get children(){return o(Di,{get view(){return e.tab.view},get tabId(){return e.tab.id}})}}),null),l(t,o(b,{get when(){return e.tab.view.type==="html"},get children(){return o(Ui,{get view(){return e.tab.view}})}}),null),t})(),Ii=e=>{const t=()=>{const r=e.view.src,n=(r.startsWith("http")||r.startsWith("//"),r),s=ve();return s?`${n}${n.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:n};return(()=>{var r=Ri();return k(()=>N(r,"src",t())),r})()},Di=e=>{const[t,r]=x(null),[n,s]=x(null),i=async u=>{r(u),s(null);try{const a=`${ye()}/tabs/${encodeURIComponent(e.tabId)}/actions/${encodeURIComponent(u)}`,c=ve(),g=await fetch(c?`${a}?token=${encodeURIComponent(c)}`:a,{method:"POST",headers:c?{"x-devtools-token":c}:void 0});s(`${g.status} ${g.statusText}`)}catch(a){s(a instanceof Error?a.message:String(a))}finally{r(null)}};return(()=>{var u=Bi(),a=u.firstChild;return l(a,o(A,{get each(){return e.view.actions},children:c=>(()=>{var g=Oi(),d=g.firstChild,h=d.firstChild,f=d.nextSibling;return l(h,()=>c.label),l(d,o(b,{get when(){return c.description},get children(){var p=qi();return l(p,()=>c.description),p}}),null),f.$$click=()=>{i(c.id)},l(f,()=>t()===c.id?"Running…":"Run"),k(()=>f.disabled=t()===c.id),g})()})),l(u,o(b,{get when(){return n()},children:c=>(()=>{var g=Pi(),d=g.firstChild.nextSibling;return l(d,c),g})()}),null),u})()},Ui=e=>(()=>{var t=ji();return k(()=>t.innerHTML=e.view.html),t})();J(["click"]);var Ve=!1,Ce=null,Ie=null;async function zi(){return U.setConnectionStatus("connecting"),await st(),Ie=ht("/stream",e=>{if(!Ve){if(U.setConnectionStatus("live"),rr(),e.type==="metrics"){Fi(e),U.touch();return}if(e.type==="container"){st();return}}},()=>{Ve||(U.setConnectionStatus("polling"),Hi())}),Gi}async function st(){const e=await Promise.allSettled([ee.health(),ee.metrics(),ee.routeRegistry(),ee.container(),ee.queues(),ee.ws()]);if(e.every(a=>a.status==="rejected"&&a.reason instanceof Yt)){U.setAuthRequired(!0),U.setConnectionStatus("disconnected");return}M.authRequired()&&(U.setAuthRequired(!1),U.setAuthError(null));const[t,r,n,s,i,u]=e;t.status==="fulfilled"&&U.setHealth({status:t.value.status,errorRate:t.value.errorRate,uptime:t.value.uptime,adapters:t.value.adapters??{}}),r.status==="fulfilled"&&U.setMetrics({requests:r.value.requests,serverErrors:r.value.serverErrors,clientErrors:r.value.clientErrors,errorRate:r.value.errorRate,uptimeSeconds:r.value.uptimeSeconds,startedAt:r.value.startedAt}),n.status==="fulfilled"&&U.setRoutes(n.value.routes??[]),s.status==="fulfilled"&&U.setContainer(s.value.registrations??[]),i.status==="fulfilled"&&U.setQueues({enabled:i.value.enabled,queues:i.value.queues??[]}),u.status==="fulfilled"&&U.setWs(u.value),U.touch()}function Fi(e){const t=M.metrics();if(!t)return;U.setMetrics({...t,requests:e.requestCount,serverErrors:e.errorCount,clientErrors:e.clientErrorCount,errorRate:e.errorRate,uptimeSeconds:e.uptimeSeconds});const r=M.health();r&&U.setHealth({...r,uptime:e.uptimeSeconds,errorRate:e.errorRate})}function Hi(){Ce||(Ce=setInterval(()=>{Ve||st()},5e3))}function rr(){Ce&&(clearInterval(Ce),Ce=null)}function Gi(){Ve=!0,rr(),Ie&&(Ie(),Ie=null),U.setConnectionStatus("disconnected")}var Vi=v('<div class="fixed inset-0 z-[60] bg-slate-950/90 flex items-center justify-center p-4"><div class="bg-slate-900 border border-slate-700 rounded-2xl p-8 max-w-md w-full shadow-2xl"><div class="text-center mb-6"><h2 class="text-xl font-bold text-kick-500 mb-2">⚡ KickJS DevTools</h2><p class="text-sm text-slate-400">Enter your DevTools token to continue.</p><p class="text-xs text-slate-600 mt-1">The token is printed in the server console on startup, e.g. <code class="font-mono text-slate-500">[token: abc123…]</code></p></div><form><input type=text autofocus placeholder="Paste your token here…"class="w-full bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-sm text-slate-200 placeholder-slate-500 focus:outline-none focus:border-kick-500 font-mono mb-3"><button type=submit class="w-full bg-kick-500 hover:bg-kick-600 text-white font-semibold py-2.5 rounded-lg transition-colors disabled:opacity-50">'),Ki=v('<p class="text-red-400 text-sm mb-3">'),Wi=()=>{const[e,t]=x(""),[r,n]=x(!1),s=async()=>{const i=e().trim();if(!i){U.setAuthError("Token is required");return}n(!0),U.setAuthError(null);try{Jt(i),await ee.health(),U.setAuthRequired(!1),U.setAuthError(null),t("")}catch{U.setAuthError("Invalid token — request was rejected.")}finally{n(!1)}};return o(b,{get when(){return M.authRequired()},get children(){var i=Vi(),u=i.firstChild.firstChild.nextSibling,a=u.firstChild,c=a.nextSibling;return u.addEventListener("submit",g=>{g.preventDefault(),s()}),a.$$input=g=>t(g.currentTarget.value),l(u,o(b,{get when(){return M.authError()},children:g=>(()=>{var d=Ki();return l(d,g),d})()}),c),l(c,()=>r()?"Verifying…":"Authenticate"),k(()=>c.disabled=r()),k(()=>a.value=e()),i}})};J(["input"]);var Ji=v("<div class=dt-nav-sep>"),Qi=v('<div class=card style=border-color:var(--warn);margin-top:16px><div class=card-title style=color:var(--warn)> custom-tab issue(s)</div><ul style="margin:8px 0 0;padding-left:20px;font-family:var(--font-mono);font-size:12px">'),Yi=v("<div class=app><header class=dt-header><div class=dt-header-brand><span class=dt-bolt aria-hidden=true>⚡</span><h1>KickJS DevTools</h1></div><div style=display:flex;align-items:center;gap:12px></div></header><div class=dt-shell><aside class=dt-sidebar role=tablist></aside><div class=dt-resizer role=separator aria-orientation=vertical></div><main class=dt-main role=tabpanel>"),Xe=v("<button type=button role=tab><span class=dt-nav-label>"),Bt=v("<span class=tab-badge>"),Xi=v("<div class=dt-nav-group><button type=button class=dt-nav-group-header><span>▾"),Zi=v("<li>: "),ea=v("<div class=dt-conn><span aria-hidden=true></span><span class=dt-conn-label></span><span class=dt-conn-sep>·</span><span class=dt-conn-ts>Updated "),ta=v("<div class=dt-settings-pop role=menu><div class=dt-settings-section><div class=dt-settings-label>Density</div><div class=dt-seg></div><div class=dt-settings-hint>Controls spacing & font scale. Default: Small."),ra=v('<div class=dt-settings><button type=button aria-label=Settings aria-haspopup=true title=Settings><svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><circle cx=12 cy=12 r=3></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z">'),na=v("<button type=button>"),la=v('<svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z">'),sa=v("<button type=button class=dt-theme-toggle>"),ia=v('<svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><circle cx=12 cy=12 r=4></circle><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41">');function nr(){return[{id:"overview",label:"Overview"},{id:"runtime",label:"Runtime"},{id:"memory",label:"Memory"},{id:"topology",label:"Topology"},{id:"routes",label:"Routes",count:()=>M.routes().length||void 0},{id:"metrics",label:"Metrics"},{id:"container",label:"Container",count:()=>M.container().length||void 0},{id:"queues",label:"Queues",count:()=>M.queues().queues.length||void 0},{id:"database",label:"Database",count:()=>Ge()().filter(e=>e.type==="db:query"||e.type==="db:query-error").length||void 0},{id:"graph",label:"Graph",count:()=>M.container().length||void 0},{id:"activity",label:"Activity",count:()=>Ge()().length||void 0}]}var aa=new Set(nr().map(e=>e.id)),oa=[{label:null,ids:["overview"]},{label:"Runtime",ids:["runtime","memory","topology","metrics"]},{label:"Architecture",ids:["routes","container","graph"]},{label:"Data & Jobs",ids:["database","queues"]},{label:null,ids:["activity"]}],lr="kickjs-devtools-sidebar-w",sr="kickjs-devtools-sidebar-collapsed",ir=150,ar=360;function ca(){try{const e=Number(localStorage.getItem(lr));if(e>=ir&&e<=ar)return e}catch{}return 200}function ua(){try{const e=localStorage.getItem(sr);if(e)return JSON.parse(e)}catch{}return[]}var da=()=>{const e=(()=>{try{const w=localStorage.getItem("kickjs-devtools-tab");if(w)return w}catch{}return"overview"})(),[t,r]=x(e),[n,s]=x([]),[i,u]=x([]),a=nr(),c=new Map(a.map(w=>[w.id,w])),[g,d]=x(ca()),[h,f]=x(ua()),p=w=>{f(E=>{const S=E.includes(w)?E.filter(T=>T!==w):[...E,w];try{localStorage.setItem(sr,JSON.stringify(S))}catch{}return S})};let m=null;ie(()=>m?.());const y=w=>{w.preventDefault();const E=w.clientX,S=g();document.body.style.cursor="col-resize";const T=q=>{const R=Math.min(ar,Math.max(ir,S+(q.clientX-E)));d(R)},F=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",I),document.body.style.cursor="",m=null},I=()=>{F();try{localStorage.setItem(lr,String(g()))}catch{}};m=F,document.addEventListener("mousemove",T),document.addEventListener("mouseup",I)};xe(()=>{ee.tabs().then(({tabs:S,errors:T})=>{s(S.filter(F=>!aa.has(F.id))),u(T)}).catch(()=>{});let w=null;zi().then(S=>{w=S});const E=Qs();ie(()=>{w?.(),E()}),Rr(),Pr()});const _=w=>{r(w);try{localStorage.setItem("kickjs-devtools-tab",w)}catch{}queueMicrotask(()=>{document.querySelector(`[role="tab"][data-tab-id="${w}"]`)?.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"})})},C=()=>n().find(w=>w.id===t());return(()=>{var w=Yi(),E=w.firstChild,S=E.firstChild.nextSibling,T=E.nextSibling.firstChild,F=T.nextSibling,I=F.nextSibling;return l(S,o(ha,{}),null),l(S,o(va,{}),null),l(S,o(fa,{}),null),l(T,o(A,{each:oa,children:q=>o(b,{get when(){return q.label},get fallback(){return o(A,{get each(){return q.ids},children:R=>{const X=c.get(R);return o(b,{when:X,children:z=>(()=>{var V=Xe(),D=V.firstChild;return V.$$click=()=>_(R),N(V,"data-tab-id",R),l(D,()=>z().label),l(V,o(b,{get when(){return z().count?.()},children:H=>(()=>{var K=Bt();return l(K,H),K})()}),null),k(H=>{var K=`dt-nav-item ${t()===R?"active":""}`,Z=t()===R;return K!==H.e&&B(V,H.e=K),Z!==H.t&&N(V,"aria-selected",H.t=Z),H},{e:void 0,t:void 0}),V})()})}})},children:R=>(()=>{var X=Xi(),z=X.firstChild,V=z.firstChild;return z.$$click=()=>p(R()),l(z,R,null),l(X,o(b,{get when(){return!h().includes(R())},get children(){return o(A,{get each(){return q.ids},children:D=>{const H=c.get(D);return o(b,{when:H,children:K=>(()=>{var Z=Xe(),ae=Z.firstChild;return Z.$$click=()=>_(D),N(Z,"data-tab-id",D),l(ae,()=>K().label),l(Z,o(b,{get when(){return K().count?.()},children:ne=>(()=>{var ue=Bt();return l(ue,ne),ue})()}),null),k(ne=>{var ue=`dt-nav-item nested ${t()===D?"active":""}`,_e=t()===D;return ue!==ne.e&&B(Z,ne.e=ue),_e!==ne.t&&N(Z,"aria-selected",ne.t=_e),ne},{e:void 0,t:void 0}),Z})()})}})}}),null),k(D=>{var H=!h().includes(R()),K=`dt-nav-caret ${h().includes(R())?"closed":""}`;return H!==D.e&&N(z,"aria-expanded",D.e=H),K!==D.t&&B(V,D.t=K),D},{e:void 0,t:void 0}),X})()})}),null),l(T,o(b,{get when(){return n().length>0},get children(){return[Ji(),o(A,{get each(){return n()},children:q=>(()=>{var R=Xe(),X=R.firstChild;return R.$$click=()=>_(q.id),l(X,()=>q.title),k(z=>{var V=q.id,D=`dt-nav-item ${t()===q.id?"active":""}`,H=t()===q.id,K=q.title;return V!==z.e&&N(R,"data-tab-id",z.e=V),D!==z.t&&B(R,z.t=D),H!==z.a&&N(R,"aria-selected",z.a=H),K!==z.o&&N(R,"title",z.o=K),z},{e:void 0,t:void 0,a:void 0,o:void 0}),R})()})]}}),null),F.$$mousedown=y,l(I,o(b,{get when(){return t()==="overview"},get children(){return o(Sn,{})}}),null),l(I,o(b,{get when(){return t()==="runtime"},get children(){return o(Nn,{})}}),null),l(I,o(b,{get when(){return t()==="memory"},get children(){return o(el,{})}}),null),l(I,o(b,{get when(){return t()==="topology"},get children(){return o(Ll,{})}}),null),l(I,o(b,{get when(){return t()==="routes"},get children(){return o(Fl,{})}}),null),l(I,o(b,{get when(){return t()==="metrics"},get children(){return o(Zl,{})}}),null),l(I,o(b,{get when(){return t()==="container"},get children(){return o(Ms,{})}}),null),l(I,o(b,{get when(){return t()==="queues"},get children(){return o(Gs,{})}}),null),l(I,o(b,{get when(){return t()==="database"},get children(){return o(oi,{})}}),null),l(I,o(b,{get when(){return t()==="graph"},get children(){return o(xi,{})}}),null),l(I,o(b,{get when(){return t()==="activity"},get children(){return o(Ai,{})}}),null),l(I,o(b,{get when(){return C()},children:q=>o(Ni,{get tab(){return q()}})}),null),l(I,o(b,{get when(){return Re(()=>i().length>0)()&&t()==="overview"},get children(){var q=Qi(),R=q.firstChild,X=R.firstChild,z=R.nextSibling;return l(R,()=>i().length,X),l(z,o(A,{get each(){return i()},children:V=>(()=>{var D=Zi(),H=D.firstChild;return l(D,()=>V.source,H),l(D,()=>V.reason,null),D})()})),q}}),null),l(w,o(us,{}),null),l(w,o(Wi,{}),null),k(q=>ct(T,`width:${g()}px`,q)),w})()},ha=()=>{const e=r=>r==="live"?"Live":r==="polling"?"Polling":r==="disconnected"?"Disconnected":"Connecting…",t=r=>r?r.toLocaleTimeString():"never";return(()=>{var r=ea(),n=r.firstChild,s=n.nextSibling,i=s.nextSibling.nextSibling;return i.firstChild,l(s,()=>e(M.connectionStatus())),l(i,()=>t(M.lastUpdate()),null),k(()=>B(n,`dt-pulse dt-pulse-${M.connectionStatus()}`)),r})()},ga=[{id:"sm",label:"Small"},{id:"md",label:"Medium"},{id:"lg",label:"Large"}],fa=()=>{const[e,t]=x(!1);let r;const n=i=>{e()&&r&&!r.contains(i.target)&&t(!1)},s=i=>{i.key==="Escape"&&t(!1)};return document.addEventListener("click",n),document.addEventListener("keydown",s),ie(()=>{document.removeEventListener("click",n),document.removeEventListener("keydown",s)}),(()=>{var i=ra(),u=i.firstChild;return Sr(a=>r=a,i),u.$$click=()=>t(a=>!a),l(i,o(b,{get when(){return e()},get children(){var a=ta(),c=a.firstChild.firstChild.nextSibling;return l(c,o(A,{each:ga,children:g=>(()=>{var d=na();return d.$$click=()=>Or(g.id),l(d,()=>g.label),k(h=>{var f=`dt-seg-item ${yt()===g.id?"active":""}`,p=yt()===g.id;return f!==h.e&&B(d,h.e=f),p!==h.t&&N(d,"aria-pressed",h.t=p),h},{e:void 0,t:void 0}),d})()})),a}}),null),k(a=>{var c=`dt-settings-btn ${e()?"open":""}`,g=e();return c!==a.e&&B(u,a.e=c),g!==a.t&&N(u,"aria-expanded",a.t=g),a},{e:void 0,t:void 0}),i})()},va=()=>{const e=()=>{const r=Je()==="system"?"light":Je()==="light"?"dark":"system";Lr(r)},t=()=>{const r=Je();return`Theme: ${r==="system"?"follow system":r} (click to cycle)`};return(()=>{var r=sa();return r.$$click=e,l(r,o(b,{get when(){return Ft()==="dark"},get fallback(){return ia()},get children(){return la()}})),k(n=>{var s=t(),i=t();return s!==n.e&&N(r,"aria-label",n.e=s),i!==n.t&&N(r,"title",n.t=i),n},{e:void 0,t:void 0}),r})()};J(["mousedown","click"]);var or=document.getElementById("root");if(!or)throw new Error("#root not found");wr(()=>o(da,{}),or);
|
|
1
|
+
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&n(u)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var P={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return gt(this.context.count)},getNextContextId(){return gt(this.context.count++)}};function gt(e){const t=String(e),r=t.length-1;return P.context.id+(r?String.fromCharCode(96+r):"")+t}function Ze(e){P.context=e}function cr(){return{...P.context,id:P.getNextContextId(),count:0}}var ur=(e,t)=>e===t,dr=Symbol("solid-track"),De={equals:ur},ft=null,Ot=Nt,te=1,Ee=2,qt={owned:null,cleanups:null,context:null,owner:null},L=null,$=null,Ae=null,be=null,q=null,G=null,W=null,Ke=0;function Pe(e,t){const r=q,n=L,s=e.length===0,i=t===void 0?n:t,u=s?qt:{owned:null,cleanups:null,context:i?i.context:null,owner:i},a=s?e:()=>e(()=>se(()=>he(u)));L=u,q=null;try{return ce(a,!0)}finally{q=r,L=n}}function x(e,t){t=t?Object.assign({},De,t):De;const r={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},n=s=>(typeof s=="function"&&($&&$.running&&$.sources.has(r)?s=s(r.tValue):s=s(r.value)),Pt(r,s));return[jt.bind(r),n]}function k(e,t,r){const n=at(e,t,!1,te);Ae&&$&&$.running?G.push(n):Le(n)}function it(e,t,r){Ot=pr;const n=at(e,t,!1,te),s=et&&gr(et);s&&(n.suspense=s),(!r||!r.render)&&(n.user=!0),W?W.push(n):Le(n)}function j(e,t,r){r=r?Object.assign({},De,r):De;const n=at(e,t,!0,0);return n.observers=null,n.observerSlots=null,n.comparator=r.equals||void 0,Ae&&$&&$.running?(n.tState=te,G.push(n)):Le(n),jt.bind(n)}function se(e){if(!be&&q===null)return e();const t=q;q=null;try{return be?be.untrack(e):e()}finally{q=t}}function xe(e){it(()=>se(e))}function ie(e){return L===null||(L.cleanups===null?L.cleanups=[e]:L.cleanups.push(e)),e}function hr(e){if($&&$.running)return e(),$.done;const t=q,r=L;return Promise.resolve().then(()=>{q=t,L=r;let n;return(Ae||et)&&(n=$||($={sources:new Set,effects:[],promises:new Set,disposed:new Set,queue:new Set,running:!0}),n.done||(n.done=new Promise(s=>n.resolve=s)),n.running=!0),ce(e,!1),q=L=null,n?n.done:void 0})}var[ma,vt]=x(!1);function gr(e){let t;return L&&L.context&&(t=L.context[e.id])!==void 0?t:e.defaultValue}var et;function jt(){const e=$&&$.running;if(this.sources&&(e?this.tState:this.state))if((e?this.tState:this.state)===te)Le(this);else{const t=G;G=null,ce(()=>Ue(this),!1),G=t}if(q){const t=this.observers;if(!t||t[t.length-1]!==q){const r=t?t.length:0;q.sources?(q.sources.push(this),q.sourceSlots.push(r)):(q.sources=[this],q.sourceSlots=[r]),t?(t.push(q),this.observerSlots.push(q.sources.length-1)):(this.observers=[q],this.observerSlots=[q.sources.length-1])}}return e&&$.sources.has(this)?this.tValue:this.value}function Pt(e,t,r){let n=$&&$.running&&$.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(n,t)){if($){const s=$.running;(s||!r&&$.sources.has(e))&&($.sources.add(e),e.tValue=t),s||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&ce(()=>{for(let s=0;s<e.observers.length;s+=1){const i=e.observers[s],u=$&&$.running;u&&$.disposed.has(i)||((u?!i.tState:!i.state)&&(i.pure?G.push(i):W.push(i),i.observers&&It(i)),u?i.tState=te:i.state=te)}if(G.length>1e6)throw G=[],new Error},!1)}return t}function Le(e){if(!e.fn)return;he(e);const t=Ke;pt(e,$&&$.running&&$.sources.has(e)?e.tValue:e.value,t),$&&!$.running&&$.sources.has(e)&&queueMicrotask(()=>{ce(()=>{$&&($.running=!0),q=L=e,pt(e,e.tValue,t),q=L=null},!1)})}function pt(e,t,r){let n;const s=L,i=q;q=L=e;try{n=e.fn(t)}catch(u){return e.pure&&($&&$.running?(e.tState=te,e.tOwned&&e.tOwned.forEach(he),e.tOwned=void 0):(e.state=te,e.owned&&e.owned.forEach(he),e.owned=null)),e.updatedAt=r+1,ot(u)}finally{q=i,L=s}(!e.updatedAt||e.updatedAt<=r)&&(e.updatedAt!=null&&"observers"in e?Pt(e,n,!0):$&&$.running&&e.pure?($.sources.has(e)||(e.value=n),$.sources.add(e),e.tValue=n):e.value=n,e.updatedAt=r)}function at(e,t,r,n=te,s){const i={fn:e,state:n,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:L,context:L?L.context:null,pure:r};if($&&$.running&&(i.state=0,i.tState=n),L===null||L!==qt&&($&&$.running&&L.pure?L.tOwned?L.tOwned.push(i):L.tOwned=[i]:L.owned?L.owned.push(i):L.owned=[i]),be&&i.fn){const u=i.fn,[a,c]=x(void 0,{equals:!1}),g=be.factory(u,c);ie(()=>g.dispose());let d,h=!1;const f=()=>hr(c).then(()=>{d&&(d.dispose(),d=void 0,h||c())});i.fn=p=>(a(),$&&$.running?(d||(d=be.factory(u,f)),d.track(p)):(h=!0,g.track(p)))}return i}function Te(e){const t=$&&$.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===Ee)return Ue(e);if(e.suspense&&se(e.suspense.inFallback))return e.suspense.effects.push(e);const r=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Ke);){if(t&&$.disposed.has(e))return;(t?e.tState:e.state)&&r.push(e)}for(let n=r.length-1;n>=0;n--){if(e=r[n],t){let s=e,i=r[n+1];for(;(s=s.owner)&&s!==i;)if($.disposed.has(s))return}if((t?e.tState:e.state)===te)Le(e);else if((t?e.tState:e.state)===Ee){const s=G;G=null,ce(()=>Ue(e,r[0]),!1),G=s}}}function ce(e,t){if(G)return e();let r=!1;t||(G=[]),W?r=!0:W=[],Ke++;try{const n=e();return fr(r),n}catch(n){r||(W=null),G=null,ot(n)}}function fr(e){if(G&&(Ae&&$&&$.running?vr(G):Nt(G),G=null),e)return;let t;if($){if(!$.promises.size&&!$.queue.size){const n=$.sources,s=$.disposed;W.push.apply(W,$.effects),t=$.resolve;for(const i of W)"tState"in i&&(i.state=i.tState),delete i.tState;$=null,ce(()=>{for(const i of s)he(i);for(const i of n){if(i.value=i.tValue,i.owned)for(let u=0,a=i.owned.length;u<a;u++)he(i.owned[u]);i.tOwned&&(i.owned=i.tOwned),delete i.tValue,delete i.tOwned,i.tState=0}vt(!1)},!1)}else if($.running){$.running=!1,$.effects.push.apply($.effects,W),W=null,vt(!0);return}}const r=W;W=null,r.length&&ce(()=>Ot(r),!1),t&&t()}function Nt(e){for(let t=0;t<e.length;t++)Te(e[t])}function vr(e){for(let t=0;t<e.length;t++){const r=e[t],n=$.queue;n.has(r)||(n.add(r),Ae(()=>{n.delete(r),ce(()=>{$.running=!0,Te(r)},!1),$&&($.running=!1)}))}}function pr(e){let t,r=0;for(t=0;t<e.length;t++){const n=e[t];n.user?e[r++]=n:Te(n)}if(P.context){if(P.count){P.effects||(P.effects=[]),P.effects.push(...e.slice(0,r));return}Ze()}for(P.effects&&(P.done||!P.count)&&(e=[...P.effects,...e],r+=P.effects.length,delete P.effects),t=0;t<r;t++)Te(e[t])}function Ue(e,t){const r=$&&$.running;r?e.tState=0:e.state=0;for(let n=0;n<e.sources.length;n+=1){const s=e.sources[n];if(s.sources){const i=r?s.tState:s.state;i===te?s!==t&&(!s.updatedAt||s.updatedAt<Ke)&&Te(s):i===Ee&&Ue(s,t)}}}function It(e){const t=$&&$.running;for(let r=0;r<e.observers.length;r+=1){const n=e.observers[r];(t?!n.tState:!n.state)&&(t?n.tState=Ee:n.state=Ee,n.pure?G.push(n):W.push(n),n.observers&&It(n))}}function he(e){let t;if(e.sources)for(;e.sources.length;){const r=e.sources.pop(),n=e.sourceSlots.pop(),s=r.observers;if(s&&s.length){const i=s.pop(),u=r.observerSlots.pop();n<s.length&&(i.sourceSlots[u]=n,s[n]=i,r.observerSlots[n]=u)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)he(e.tOwned[t]);delete e.tOwned}if($&&$.running&&e.pure)Dt(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)he(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}$&&$.running?e.tState=0:e.state=0}function Dt(e,t){if(t||(e.tState=0,$.disposed.add(e)),e.owned)for(let r=0;r<e.owned.length;r++)Dt(e.owned[r])}function mr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function mt(e,t,r){try{for(const n of t)n(e)}catch(n){ot(n,r&&r.owner||null)}}function ot(e,t=L){const r=ft&&t&&t.context&&t.context[ft],n=mr(e);if(!r)throw n;W?W.push({fn(){mt(n,r,t)},state:te}):mt(n,r,t)}var br=Symbol("fallback");function bt(e){for(let t=0;t<e.length;t++)e[t]()}function $r(e,t,r={}){let n=[],s=[],i=[],u=0,a=t.length>1?[]:null;return ie(()=>bt(i)),()=>{let c=e()||[],g=c.length,d,h;return c[dr],se(()=>{let p,m,y,_,C,w,E,S,T;if(g===0)u!==0&&(bt(i),i=[],n=[],s=[],u=0,a&&(a=[])),r.fallback&&(n=[br],s[0]=Pe(F=>(i[0]=F,r.fallback())),u=1);else if(u===0){for(s=new Array(g),h=0;h<g;h++)n[h]=c[h],s[h]=Pe(f);u=g}else{for(y=new Array(g),_=new Array(g),a&&(C=new Array(g)),w=0,E=Math.min(u,g);w<E&&n[w]===c[w];w++);for(E=u-1,S=g-1;E>=w&&S>=w&&n[E]===c[S];E--,S--)y[S]=s[E],_[S]=i[E],a&&(C[S]=a[E]);for(p=new Map,m=new Array(S+1),h=S;h>=w;h--)T=c[h],d=p.get(T),m[h]=d===void 0?-1:d,p.set(T,h);for(d=w;d<=E;d++)T=n[d],h=p.get(T),h!==void 0&&h!==-1?(y[h]=s[d],_[h]=i[d],a&&(C[h]=a[d]),h=m[h],p.set(T,h)):i[d]();for(h=w;h<g;h++)h in y?(s[h]=y[h],i[h]=_[h],a&&(a[h]=C[h],a[h](h))):s[h]=Pe(f);s=s.slice(0,u=g),n=c.slice(0)}return s});function f(p){if(i[h]=p,a){const[m,y]=x(h);return a[h]=y,t(c[h],m)}return t(c[h])}}}var xr=!1;function o(e,t){if(xr&&P.context){const r=P.context;Ze(cr());const n=se(()=>e(t||{}));return Ze(r),n}return se(()=>e(t||{}))}var yr=e=>`Stale read from <${e}>.`;function A(e){const t="fallback"in e&&{fallback:()=>e.fallback};return j($r(()=>e.each,e.children,t||void 0))}function b(e){const t=e.keyed,r=j(()=>e.when,void 0,void 0),n=t?r:j(r,void 0,{equals:(s,i)=>!s==!i});return j(()=>{const s=n();if(s){const i=e.children;return typeof i=="function"&&i.length>0?se(()=>i(t?s:()=>{if(!se(n))throw yr("Show");return r()})):i}return e.fallback},void 0,void 0)}var Re=e=>j(()=>e());function _r(e,t,r){let n=r.length,s=t.length,i=n,u=0,a=0,c=t[s-1].nextSibling,g=null;for(;u<s||a<i;){if(t[u]===r[a]){u++,a++;continue}for(;t[s-1]===r[i-1];)s--,i--;if(s===u){const d=i<n?a?r[a-1].nextSibling:r[i-a]:c;for(;a<i;)e.insertBefore(r[a++],d)}else if(i===a)for(;u<s;)(!g||!g.has(t[u]))&&t[u].remove(),u++;else if(t[u]===r[i-1]&&r[a]===t[s-1]){const d=t[--s].nextSibling;e.insertBefore(r[a++],t[u++].nextSibling),e.insertBefore(r[--i],d),t[s]=r[i]}else{if(!g){g=new Map;let h=a;for(;h<i;)g.set(r[h],h++)}const d=g.get(t[u]);if(d!=null)if(a<d&&d<i){let h=u,f=1,p;for(;++h<s&&h<i&&!((p=g.get(t[h]))==null||p!==d+f);)f++;if(f>d-a){const m=t[u];for(;a<d;)e.insertBefore(r[a++],m)}else e.replaceChild(r[a++],t[u++])}else u++;else t[u++].remove()}}}var $t="_$DX_DELEGATE";function wr(e,t,r,n={}){let s;return Pe(i=>{s=i,t===document?e():l(t,e(),t.firstChild?null:void 0,r)},n.owner),()=>{s(),t.textContent=""}}function v(e,t,r,n){let s;const i=()=>{const a=n?document.createElementNS("http://www.w3.org/1998/Math/MathML","template"):document.createElement("template");return a.innerHTML=e,r?a.content.firstChild.firstChild:n?a.firstChild:a.content.firstChild},u=t?()=>se(()=>document.importNode(s||(s=i()),!0)):()=>(s||(s=i())).cloneNode(!0);return u.cloneNode=u,u}function J(e,t=window.document){const r=t[$t]||(t[$t]=new Set);for(let n=0,s=e.length;n<s;n++){const i=e[n];r.has(i)||(r.add(i),t.addEventListener(i,kr))}}function N(e,t,r){ut(e)||(r==null?e.removeAttribute(t):e.setAttribute(t,r))}function B(e,t){ut(e)||(t==null?e.removeAttribute("class"):e.className=t)}function ct(e,t,r){if(!t)return r?N(e,"style"):t;const n=e.style;if(typeof t=="string")return n.cssText=t;typeof r=="string"&&(n.cssText=r=void 0),r||(r={}),t||(t={});let s,i;for(i in r)t[i]??n.removeProperty(i),delete r[i];for(i in t)s=t[i],s!==r[i]&&(n.setProperty(i,s),r[i]=s);return r}function Sr(e,t,r){return se(()=>e(t,r))}function l(e,t,r,n){if(r!==void 0&&!n&&(n=[]),typeof t!="function")return ze(e,t,n,r);k(s=>ze(e,t(),s,r),n)}function ut(e){return!!P.context&&!P.done&&(!e||e.isConnected)}function kr(e){if(P.registry&&P.events&&P.events.find(([c,g])=>g===e))return;let t=e.target;const r=`$$${e.type}`,n=e.target,s=e.currentTarget,i=c=>Object.defineProperty(e,"target",{configurable:!0,value:c}),u=()=>{const c=t[r];if(c&&!t.disabled){const g=t[`${r}Data`];if(g!==void 0?c.call(t,g,e):c.call(t,e),e.cancelBubble)return}return t.host&&typeof t.host!="string"&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;u()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return t||document}}),P.registry&&!P.done&&(P.done=_$HY.done=!0),e.composedPath){const c=e.composedPath();i(c[0]);for(let g=0;g<c.length-2&&(t=c[g],!!u());g++){if(t._$host){t=t._$host,a();break}if(t.parentNode===s)break}}else a();i(n)}function ze(e,t,r,n,s){const i=ut(e);if(i){!r&&(r=[...e.childNodes]);let c=[];for(let g=0;g<r.length;g++){const d=r[g];d.nodeType===8&&d.data.slice(0,2)==="!$"?d.remove():c.push(d)}r=c}for(;typeof r=="function";)r=r();if(t===r)return r;const u=typeof t,a=n!==void 0;if(e=a&&r[0]&&r[0].parentNode||e,u==="string"||u==="number"){if(i||u==="number"&&(t=t.toString(),t===r))return r;if(a){let c=r[0];c&&c.nodeType===3?c.data!==t&&(c.data=t):c=document.createTextNode(t),r=pe(e,r,n,c)}else r!==""&&typeof r=="string"?r=e.firstChild.data=t:r=e.textContent=t}else if(t==null||u==="boolean"){if(i)return r;r=pe(e,r,n)}else{if(u==="function")return k(()=>{let c=t();for(;typeof c=="function";)c=c();r=ze(e,c,r,n)}),()=>r;if(Array.isArray(t)){const c=[],g=r&&Array.isArray(r);if(tt(c,t,r,s))return k(()=>r=ze(e,c,r,n,!0)),()=>r;if(i){if(!c.length)return r;if(n===void 0)return r=[...e.childNodes];let d=c[0];if(d.parentNode!==e)return r;const h=[d];for(;(d=d.nextSibling)!==n;)h.push(d);return r=h}if(c.length===0){if(r=pe(e,r,n),a)return r}else g?r.length===0?xt(e,c,n):_r(e,r,c):(r&&pe(e),xt(e,c));r=c}else if(t.nodeType){if(i&&t.parentNode)return r=a?[t]:t;if(Array.isArray(r)){if(a)return r=pe(e,r,n,t);pe(e,r,null,t)}else r==null||r===""||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);r=t}}return r}function tt(e,t,r,n){let s=!1;for(let i=0,u=t.length;i<u;i++){let a=t[i],c=r&&r[e.length],g;if(!(a==null||a===!0||a===!1))if((g=typeof a)=="object"&&a.nodeType)e.push(a);else if(Array.isArray(a))s=tt(e,a,c)||s;else if(g==="function")if(n){for(;typeof a=="function";)a=a();s=tt(e,Array.isArray(a)?a:[a],Array.isArray(c)?c:[c])||s}else e.push(a),s=!0;else{const d=String(a);c&&c.nodeType===3&&c.data===d?e.push(c):e.push(document.createTextNode(d))}}return s}function xt(e,t,r=null){for(let n=0,s=t.length;n<s;n++)e.insertBefore(t[n],r)}function pe(e,t,r,n){if(r===void 0)return e.textContent="";const s=n||document.createTextNode("");if(t.length){let i=!1;for(let u=t.length-1;u>=0;u--){const a=t[u];if(s!==a){const c=a.parentNode===e;!i&&!u?c?e.replaceChild(s,a):e.insertBefore(s,r):c&&a.remove()}else i=!0}}else e.insertBefore(s,r);return[s]}var Ut="kickjs-devtools-theme";function Cr(){try{const e=localStorage.getItem(Ut);if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Er(){return typeof window>"u"||!window.matchMedia?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}var[zt,Tr]=x(Cr()),[Mr,Ar]=x(Er());if(typeof window<"u"&&window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: light)"),t=r=>Ar(r.matches?"light":"dark");e.addEventListener("change",t)}var Je=zt;function Ft(){const e=zt();return e==="system"?Mr():e}function Lr(e){Tr(e);try{localStorage.setItem(Ut,e)}catch{}}function Rr(){it(()=>{const e=Ft();document.documentElement.dataset.theme=e}),ie(()=>{delete document.documentElement.dataset.theme})}var Ht="kickjs-devtools-density";function Br(){try{const e=localStorage.getItem(Ht);if(e==="sm"||e==="md"||e==="lg")return e}catch{}return"sm"}var[Gt,Or]=x(Br()),yt=Gt;function qr(e){Or(e);try{localStorage.setItem(Ht,e)}catch{}}function jr(){it(()=>{document.documentElement.dataset.density=Gt()}),ie(()=>{delete document.documentElement.dataset.density})}var[Pr,Nr]=x("connecting"),[Ir,_t]=x(null),[Dr,Ur]=x(!1),[zr,Fr]=x(null),[Hr,Gr]=x(null),[Vr,Kr]=x(null),[Wr,Jr]=x([]),[Qr,Yr]=x([]),[Xr,Zr]=x({enabled:!1,queues:[]}),[en,tn]=x({enabled:!1}),M={connectionStatus:Pr,lastUpdate:Ir,authRequired:Dr,authError:zr,health:Hr,metrics:Vr,routes:Wr,container:Qr,queues:Xr,ws:en},U={setConnectionStatus:Nr,setLastUpdate:_t,setAuthRequired:Ur,setAuthError:Fr,setHealth:Gr,setMetrics:Kr,setRoutes:Jr,setContainer:Yr,setQueues:Zr,setWs:tn,touch(){_t(new Date)}};function Q(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KiB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MiB`:`${(e/1024/1024/1024).toFixed(2)} GiB`}function rn(e){if(e===0)return"0";const t=e*60;return Math.abs(t)<1048576?`${(t/1024).toFixed(1)} KiB/min`:`${(t/1024/1024).toFixed(1)} MiB/min`}function oe(e){return e<1?`${e.toFixed(2)} ms`:e<100?`${e.toFixed(1)} ms`:`${Math.round(e)} ms`}function dt(e){const t=Math.floor(e);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m ${t%60}s`:`${Math.floor(t/3600)}h ${Math.floor(t%3600/60)}m ${t%60}s`}function Fe(e){return`${Math.round(e*100)}%`}var nn=v('<span class=dt-tip tabindex=0><svg class=dt-tip-icon viewBox="0 0 24 24"aria-hidden=true><circle cx=12 cy=12 r=9 fill=none stroke=currentColor stroke-width=1.5></circle><path d="M12 8h.01M12 11v6"stroke=currentColor stroke-width=2 stroke-linecap=round fill=none></path></svg><span role=tooltip>'),ln=v('<button type=button class="dt-tip dt-tip-clickable"><svg class=dt-tip-icon viewBox="0 0 24 24"aria-hidden=true><circle cx=12 cy=12 r=9 fill=none stroke=currentColor stroke-width=1.5></circle><path d="M12 8h.01M12 11v6"stroke=currentColor stroke-width=2 stroke-linecap=round fill=none>'),sn=v('<div class="fixed inset-0 z-50 bg-slate-950/80 flex items-center justify-center p-4"><div class="bg-slate-900 border border-slate-700 rounded-2xl p-6 max-w-lg w-full shadow-2xl max-h-[90vh] overflow-y-auto"><div class="flex items-start justify-between mb-4"><h2 class="text-lg font-semibold text-slate-200"></h2><button type=button class="text-slate-500 hover:text-slate-300 p-1"aria-label=Close><svg class="w-5 h-5"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M6 18L18 6M6 6l12 12"></path></svg></button></div><div class="text-sm text-slate-300 space-y-3">'),rt={"heap.used":{short:"V8-allocated memory currently used by JavaScript objects.",detail:"Grows as your code allocates objects, shrinks after GC frees them. A consistently rising heap-used line on the sparkline is the textbook leak signature."},"heap.total":{short:"V8-allocated memory the JS heap is currently sized to use.",detail:"Larger than heap-used; V8 reserves headroom so allocations don't pause to grow the heap. Bumps up in 1-8 MiB jumps as the heap expands."},rss:{short:"Total memory resident in physical RAM for this Node process.",detail:'Includes the JS heap, native buffers, V8 internal structures, and code. Always larger than heap-used; the gap is "everything the OS sees" minus "JS objects".'},external:{short:"Memory used by C++ objects bound to JS (Buffers, native bindings)."},"array-buffers":{short:"Memory used by ArrayBuffer / SharedArrayBuffer instances."},"event-loop.p99":{short:"99% of event-loop ticks completed within this time.",detail:"Sustained values above ~50ms mean some synchronous operation is blocking the loop. Common culprits: large JSON.parse, sync crypto, blocking DB drivers."},gc:{short:"Garbage-collector activity since process start.",detail:"Total run count and cumulative pause time. Frequent GC with low reclaim ratio = leak; rare GC with healthy reclaim = good citizen."},"leak.risk":{short:"Heap-growth slope over the recent window — stable / warn / critical.",detail:"Bucketed from heap-growth in MB/min: <5 = ok, <20 = warn, ≥20 = critical. Critical sustained for >5 minutes is the moment to capture a heap snapshot."},"gc.reclaim":{short:"Average ratio of memory freed by each GC pass.",detail:"Trending toward zero means GC can't free anything — strong leak indicator. Healthy apps reclaim 20-60% on each major GC."},"heap.utilization":{short:"Fraction of V8's hard heap-size limit currently in use.",detail:"Approaching 1 means the process is close to OOM. Use --max-old-space-size to raise the limit if your workload is memory-bound."},requests:{short:"Total HTTP requests handled since process start."},"server-errors":{short:"5xx responses — server-side failures."},"client-errors":{short:"4xx responses — bad client input, missing routes, auth denials."},"error-rate":{short:"Server errors as a percentage of total requests.",detail:"Computed across the lifetime of the process. Spikes typically signal upstream dependency failures; sustained elevation = code bug."},uptime:{short:"How long this Node process has been running."},"latency.avg":{short:"Mean response time per route (sum of all calls / call count)."},"latency.p50":{short:"Median — half the requests complete faster than this."},"latency.p95":{short:"95% of requests complete within this time."},"latency.p99":{short:"99% of requests complete within this time. Outlier-sensitive."},"latency.max":{short:"Slowest single response observed since process start."},"resolve.count":{short:"Number of times this token was resolved from the DI container."},"resolve.duration":{short:"How long the container took to resolve this token (ms)."},"post-construct":{short:"@PostConstruct lifecycle status: done / failed / none.",detail:'A failed PostConstruct means the service registered but its async init threw. The token is left in a "registered" state; resolve() will throw the original error.'}},Y=e=>{const t=()=>e.text??rt[e.metric??""]?.short??"",r=e.placement??"top";return(()=>{var n=nn(),s=n.firstChild.nextSibling;return B(s,`dt-tip-pop dt-tip-pop-${r}`),l(s,t),k(()=>N(n,"aria-label",t())),n})()},an=e=>{const[t,r]=x(!1);return[(()=>{var n=ln();return n.$$click=()=>r(!0),k(()=>N(n,"aria-label",`More info: ${e.title}`)),n})(),o(b,{get when(){return t()},get children(){return o(on,{get title(){return e.title},onClose:()=>r(!1),get children(){return e.children}})}})]},on=e=>(()=>{var t=sn(),r=t.firstChild.firstChild,n=r.firstChild,s=n.nextSibling,i=r.nextSibling;return t.$$click=u=>{u.target===u.currentTarget&&e.onClose()},l(n,()=>e.title),s.$$click=()=>e.onClose(),l(i,()=>e.children),t})();J(["click"]);var cn=v('<div class="grid grid-cols-1 md:grid-cols-3 gap-4">'),un=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">Health'),Vt=v('<p class="text-text-muted italic">Loading…'),dn=v("<span>"),$e=v('<span class="font-semibold tabular-nums">'),Kt=v("<div class=mt-1>"),hn=v('<div class="border-t border-border mt-2 pt-2"><button type=button class="text-xs text-text-muted hover:text-text-strong flex items-center gap-1"><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg>Adapters (<!>)'),gn=v('<div class="flex items-center justify-between py-1"><span class="text-text-secondary text-sm"></span><span>'),fn=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">Metrics'),vn=v('<span class="font-semibold tabular-nums text-red-400">'),pn=v('<span class="font-semibold tabular-nums text-amber-400">'),mn=v('<span class="font-semibold text-sm">'),bn=v('<span class="font-semibold tabular-nums text-emerald-400">'),$n=v('<div class="border-t border-border mt-2 pt-2"><button type=button class="text-xs text-text-muted hover:text-text-strong flex items-center gap-1"><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg>Namespaces (<!>)'),xn=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><h2 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">WebSocket'),yn=v('<p class="text-text-muted italic">No WsAdapter detected'),_n=v('<div class="flex items-center justify-between py-1"><span class="text-text-secondary text-sm font-mono"></span><span class=text-sm> conn / <!> handlers'),wn=v('<div class="flex items-center justify-between mb-2"><span class=text-text-secondary>'),Sn=()=>(()=>{var e=cn();return l(e,o(kn,{}),null),l(e,o(Cn,{}),null),l(e,o(En,{}),null),e})(),kn=()=>{const[e,t]=x(!0);return(()=>{var r=un();return r.firstChild,l(r,o(b,{get when(){return M.health()},get fallback(){return Vt()},children:n=>[o(re,{label:"Status",get children(){var s=dn();return l(s,()=>n().status),k(()=>B(s,`badge ${Tn(n().status)}`)),s}}),o(re,{label:"Uptime",get children(){var s=$e();return l(s,()=>dt(n().uptime)),s}}),o(re,{label:"Error rate",get children(){var s=$e();return l(s,()=>Fe(n().errorRate),null),l(s,o(Y,{metric:"error-rate"}),null),s}}),o(b,{get when(){return Object.keys(n().adapters).length>0},get children(){var s=hn(),i=s.firstChild,u=i.firstChild,a=u.nextSibling.nextSibling;return a.nextSibling,i.$$click=()=>t(c=>!c),l(i,()=>Object.keys(n().adapters).length,a),l(s,o(b,{get when(){return e()},get children(){var c=Kt();return l(c,o(A,{get each(){return Object.entries(n().adapters)},children:([g,d])=>(()=>{var h=gn(),f=h.firstChild,p=f.nextSibling;return l(f,g),B(p,`badge ${d==="running"?"badge-ok":"badge-warn"}`),l(p,d),h})()})),c}}),null),k(()=>N(u,"class",`w-3 h-3 transition-transform ${e()?"rotate-90":""}`)),s}})]}),null),r})()},Cn=()=>(()=>{var e=fn();return e.firstChild,l(e,o(b,{get when(){return M.metrics()},get fallback(){return Vt()},children:t=>[o(re,{label:"Total requests",get children(){var r=$e();return l(r,()=>t().requests.toLocaleString()),r}}),o(re,{label:"5xx errors",get children(){var r=vn();return l(r,()=>t().serverErrors),r}}),o(re,{label:"4xx errors",get children(){var r=pn();return l(r,()=>t().clientErrors),r}}),o(re,{label:"Started",get children(){var r=mn();return l(r,()=>new Date(t().startedAt).toLocaleTimeString()),r}})]}),null),e})(),En=()=>{const[e,t]=x(!1);return(()=>{var r=xn();return r.firstChild,l(r,o(b,{get when(){return M.ws().enabled},get fallback(){return yn()},get children(){return[o(re,{label:"Active",get children(){var n=bn();return l(n,()=>M.ws().activeConnections??0),n}}),o(re,{label:"Total",get children(){var n=$e();return l(n,()=>M.ws().totalConnections??0),n}}),o(re,{label:"Messages in",get children(){var n=$e();return l(n,()=>M.ws().messagesReceived??0),n}}),o(re,{label:"Messages out",get children(){var n=$e();return l(n,()=>M.ws().messagesSent??0),n}}),o(b,{get when(){return Re(()=>!!M.ws().namespaces)()&&Object.keys(M.ws().namespaces??{}).length>0},get children(){var n=$n(),s=n.firstChild,i=s.firstChild,u=i.nextSibling.nextSibling;return u.nextSibling,s.$$click=()=>t(a=>!a),l(s,()=>Object.keys(M.ws().namespaces??{}).length,u),l(n,o(b,{get when(){return e()},get children(){var a=Kt();return l(a,o(A,{get each(){return Object.entries(M.ws().namespaces??{})},children:([c,g])=>(()=>{var d=_n(),h=d.firstChild,f=h.nextSibling,p=f.firstChild,m=p.nextSibling;return m.nextSibling,l(h,c),l(f,()=>g.connections,p),l(f,()=>g.handlers,m),d})()})),a}}),null),k(()=>N(i,"class",`w-3 h-3 transition-transform ${e()?"rotate-90":""}`)),n}})]}}),null),r})()},re=e=>(()=>{var t=wn(),r=t.firstChild;return l(r,()=>e.label),l(t,()=>e.children,null),t})();function Tn(e){return e==="healthy"?"badge-ok":e==="degraded"?"badge-warn":"badge-critical"}J(["click"]);var Mn=v("<svg class=sparkline preserveAspectRatio=none aria-hidden=true><path fill=none stroke-width=1.5 stroke-linejoin=round stroke-linecap=round>"),Ne=e=>{const t=()=>e.width??200,n=j(()=>{const s=e.values;if(s.length<2)return"";const i=Math.min(...s),u=Math.max(...s)-i||1,a=t()/(s.length-1),c=d=>40-(d-i)/u*36-2;let g=`M0 ${c(s[0]).toFixed(2)}`;for(let d=1;d<s.length;d++)g+=` L${(d*a).toFixed(2)} ${c(s[d]).toFixed(2)}`;return g});return(()=>{var s=Mn(),i=s.firstChild;return k(u=>{var a=`0 0 ${t()} 40`,c=n(),g=e.stroke??"var(--color-accent)";return a!==u.e&&N(s,"viewBox",u.e=a),c!==u.t&&N(i,"d",u.t=c),g!==u.a&&N(i,"stroke",u.a=g),u},{e:void 0,t:void 0,a:void 0}),s})()};function ye(){return document.body.dataset.base??"/_debug"}var Wt="kickjs_devtools_token",An=30,Se=null;function ve(){if(Se)return Se;const e=new URLSearchParams(location.search).get("token");if(e){Jt(e);const r=new URL(location.href);return r.searchParams.delete("token"),history.replaceState({},"",r.toString()),e}const t=document.cookie.match(new RegExp(`${Wt}=([^;]+)`));return t?(Se=decodeURIComponent(t[1]),Se):null}function Jt(e){Se=e,document.cookie=`${Wt}=${encodeURIComponent(e)}; path=/; max-age=${86400*An}; SameSite=Lax`}function Qt(e){const t=ve();return t?`${e}${e.includes("?")?"&":"?"}token=${encodeURIComponent(t)}`:e}var Yt=class extends Error{constructor(){super("AUTH_REQUIRED"),this.name="AuthRequiredError"}};async function le(e){const t=Qt(`${ye()}${e}`),r=await fetch(t,{headers:Ln()});if(r.status===401||r.status===403)throw new Yt;if(!r.ok)throw new Error(`GET ${e} failed: ${r.status} ${r.statusText}`);return await r.json()}function Ln(){const e=ve();return e?{"x-devtools-token":e}:{}}var ee={runtime:()=>le("/runtime"),topology:()=>le("/topology"),metrics:()=>le("/metrics"),routes:()=>le("/metrics"),routeRegistry:()=>le("/routes"),container:()=>le("/container"),health:()=>le("/health"),queues:()=>le("/queues"),ws:()=>le("/ws"),tabs:()=>le("/tabs")};function ht(e,t,r){const n=Qt(`${ye()}${e}`),s=new EventSource(n);return s.addEventListener("message",i=>{try{t(JSON.parse(i.data))}catch(u){console.warn("SSE parse failed",u)}}),r&&s.addEventListener("error",r),()=>s.close()}var Rn=v("<div class=status><span><span></span></span><span> samples"),Bn=v("<div class=proc-strip><span class=proc-label>These stats are for <strong>this Node process</strong> — the one running your KickJS app.</span><span class=proc-meta><span class=proc-pill>Node </span><span class=proc-pill>/</span><span class=proc-pill>pid "),On=v("<span>engine: "),qn=v("<div class=empty>Loading runtime metrics…"),jn=v("<div class=empty style=padding:0;text-align:left;font-size:11px>GC: <!> runs, <!> total"),wt=v("<div class=grid>"),Pn=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),Nn=()=>{const[e,t]=x(null),[r,n]=x(null),[s,i]=x([]),[u,a]=x([]),[c,g]=x([]),[d,h]=x(!1),f=p=>{t(p),i(m=>[...m,p.memory.heapUsed].slice(-60)),a(m=>[...m,p.memory.rss].slice(-60)),g(m=>[...m,p.eventLoop.p99].slice(-60))};return xe(()=>{ee.runtime().then(m=>{m.process&&n(m.process);for(const y of m.history)f(y);h(!0)}).catch(()=>h(!1));const p=ht("/runtime/stream",m=>{h(!0),f(m)},()=>h(!1));ie(p)}),[o(b,{get when(){return r()},children:p=>(()=>{var m=Bn(),y=m.firstChild.nextSibling,_=y.firstChild;_.firstChild;var C=_.nextSibling,w=C.firstChild,E=C.nextSibling;return E.firstChild,l(y,o(b,{get when(){return p().runtime},children:S=>(()=>{var T=On();return T.firstChild,l(T,()=>S().name,null),k(()=>B(T,`proc-pill rt-${S().name}`)),T})()}),_),l(_,()=>p().nodeVersion,null),l(C,()=>p().platform,w),l(C,()=>p().arch,null),l(E,()=>p().pid,null),m})()}),o(b,{get when(){return e()},get fallback(){return qn()},children:p=>[(()=>{var m=wt();return l(m,o(de,{title:"Heap used",metric:"heap.used",get value(){return Q(p().memory.heapUsed)},get children(){return o(Ne,{get values(){return s()}})}}),null),l(m,o(de,{title:"RSS",metric:"rss",get value(){return Q(p().memory.rss)},get children(){return o(Ne,{get values(){return u()}})}}),null),l(m,o(de,{title:"Event loop p99",metric:"event-loop.p99",get value(){return oe(p().eventLoop.p99)},get children(){return o(Ne,{get values(){return c()}})}}),null),l(m,o(de,{title:"Uptime",metric:"uptime",get value(){return dt(p().uptimeSec)},get children(){var y=jn(),_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling;return C.nextSibling,l(y,()=>p().gc.count,_),l(y,()=>oe(p().gc.totalPauseMs),C),y}}),null),m})(),(()=>{var m=wt();return l(m,o(de,{title:"External",metric:"external",get value(){return Q(p().memory.external)}}),null),l(m,o(de,{title:"Array buffers",metric:"array-buffers",get value(){return Q(p().memory.arrayBuffers)}}),null),l(m,o(de,{title:"Heap total",metric:"heap.total",get value(){return Q(p().memory.heapTotal)}}),null),l(m,o(de,{title:"CPU (last sample)",get value(){return`${(p().cpu.userMicros/1e3).toFixed(1)} ms u / ${(p().cpu.systemMicros/1e3).toFixed(1)} ms s`}}),null),m})()]}),(()=>{var p=Rn(),m=p.firstChild,y=m.firstChild,_=m.nextSibling,C=_.firstChild;return l(m,()=>d()?"streaming":"reconnecting…",null),l(_,()=>s().length,C),k(()=>B(y,`status-dot ${d()?"connected":"disconnected"}`)),p})()]},de=e=>(()=>{var t=Pn(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),l(t,()=>e.children,null),t})(),In=v("<div class=status><span><span></span></span><span> samples"),Dn=v("<div class=empty>Loading memory metrics…"),St=v("<p>"),Un=v("<p><strong>Severity buckets</strong> (heap-growth in MB/min):"),zn=v('<ul class="list-disc pl-5 space-y-1"><li><span class="badge badge-ok">ok</span> < 5 MB/min — typical operation.</li><li><span class="badge badge-warn">warn</span> < 20 MB/min — investigate if sustained > 5 minutes.</li><li><span class="badge badge-critical">critical</span> ≥ 20 MB/min — capture a heap snapshot now.'),Fn=v("<div class=card><div class=card-header><div class=card-title>Leak risk</div><span></span></div><div style=display:flex;justify-content:space-between;align-items:baseline><div class=card-value> growth</div><div class=card-value style=font-size:13px;color:var(--text-dim)>GC reclaim<!> <!> • heap util<!> "),Hn=v("<div class=grid>"),Gn=v("<table><thead><tr><th>Type</th><th style=text-align:right>Count</th></tr></thead><tbody>"),Vn=v("<div class=card><div class=card-header><div class=card-title>Active handles</div><div class=card-value>"),Kn=v("<div class=empty>No handle inventory available on this runtime."),Wn=v("<tr><td></td><td style=text-align:right>"),Jn=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),Qn=v('<div class=card><div class=card-header><div class=card-title>Heap snapshot</div><div class=card-value style=font-size:13px;color:var(--text-dim)>~<!> estimate</div></div><p style="margin:0 0 12px;color:var(--text-dim);font-size:12px">Captures a V8 heap snapshot for retained-size analysis in Chrome DevTools (Memory tab, Load profile). Capture blocks the event loop for several seconds — avoid in production.</p><div style=display:flex;align-items:center;gap:12px><button type=button class=tab style="border:1px solid var(--accent);border-radius:4px;padding:6px 14px;border-bottom-color:var(--accent);color:var(--accent)">'),Yn=v("<span style=color:var(--text-dim);font-size:12px;font-family:var(--font-mono)>Last: <!> (<!>)"),Xt=v('<p style="margin:8px 0 0;color:var(--critical);font-size:12px;font-family:var(--font-mono)">'),Xn=v('<div class=card><div class=card-header><div class=card-title>Force GC</div></div><p style="margin:0 0 12px;color:var(--text-dim);font-size:12px">Triggers a synchronous V8 GC pass to confirm whether heap growth is real retention or just uncollected garbage. Requires <code>node --expose-gc</code>.</p><div style=display:flex;align-items:center;gap:12px;flex-wrap:wrap><button type=button class=tab style="border:1px solid var(--accent);border-radius:4px;padding:6px 14px;border-bottom-color:var(--accent);color:var(--accent)">'),Zn=v("<span style=color:var(--text-dim);font-size:12px;font-family:var(--font-mono)>Reclaimed <!> (<!> → <!>) in <!>ms"),el=()=>{const[e,t]=x(null),[r,n]=x([]),[s,i]=x(!1),u=c=>{t(c),n(g=>[...g,c.snapshot.memory.heapUsed].slice(-60))};xe(()=>{ee.runtime().then(g=>{g.latest&&(u({snapshot:g.latest,health:g.health}),n(g.history.map(d=>d.memory.heapUsed).slice(-60))),i(!0)}).catch(()=>i(!1));const c=ht("/memory/stream",g=>{i(!0),u(g)},()=>i(!1));ie(c)});const a=j(()=>{const c=e();return c?Object.entries(c.health.handlesByType).toSorted((g,d)=>d[1]-g[1]):[]});return[o(b,{get when(){return e()},get fallback(){return Dn()},children:c=>[(()=>{var g=Fn(),d=g.firstChild,h=d.firstChild;h.firstChild;var f=h.nextSibling,p=d.nextSibling.firstChild,m=p.firstChild,y=p.nextSibling,_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling,w=C.nextSibling.nextSibling;return w.nextSibling,l(h,o(an,{title:"What is leak risk?",get children(){return[(()=>{var E=St();return l(E,()=>rt["leak.risk"].short),E})(),(()=>{var E=St();return l(E,()=>rt["leak.risk"].detail),E})(),Un(),zn()]}}),null),l(f,()=>c().health.heapGrowthSeverity),l(p,()=>rn(c().health.heapGrowthBytesPerSec),m),l(y,o(Y,{metric:"gc.reclaim"}),_),l(y,()=>Fe(c().health.gcReclaimRatio),C),l(y,o(Y,{metric:"heap.utilization"}),w),l(y,()=>Fe(c().health.heapUtilization),null),l(g,o(Ne,{get values(){return r()}}),null),k(()=>B(f,`badge badge-${c().health.heapGrowthSeverity}`)),g})(),(()=>{var g=Hn();return l(g,o(Be,{title:"Heap used",metric:"heap.used",get value(){return Q(c().snapshot.memory.heapUsed)}}),null),l(g,o(Be,{title:"Heap total",metric:"heap.total",get value(){return Q(c().snapshot.memory.heapTotal)}}),null),l(g,o(Be,{title:"RSS",metric:"rss",get value(){return Q(c().snapshot.memory.rss)}}),null),l(g,o(Be,{title:"External",metric:"external",get value(){return Q(c().snapshot.memory.external)}}),null),g})(),(()=>{var g=Vn(),d=g.firstChild.firstChild.nextSibling;return l(d,()=>c().health.activeHandles),l(g,o(b,{get when(){return a().length>0},get fallback(){return Kn()},get children(){var h=Gn(),f=h.firstChild.nextSibling;return l(f,o(A,{get each(){return a()},children:([p,m])=>(()=>{var y=Wn(),_=y.firstChild,C=_.nextSibling;return l(_,p),l(C,m),y})()})),h}}),null),g})(),o(tl,{get heapTotal(){return c().snapshot.memory.heapTotal}}),o(ll,{})]}),(()=>{var c=In(),g=c.firstChild,d=g.firstChild,h=g.nextSibling,f=h.firstChild;return l(g,()=>s()?"streaming":"reconnecting…",null),l(h,()=>r().length,f),k(()=>B(d,`status-dot ${s()?"connected":"disconnected"}`)),c})()]},Be=e=>(()=>{var t=Jn(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),t})(),tl=e=>{const[t,r]=x(!1),[n,s]=x(null),[i,u]=x(null),a=async()=>{r(!0),s(null);try{const c=ve(),g=`${ye()}/memory/snapshot${c?`?token=${encodeURIComponent(c)}`:""}`,d=await fetch(g,{method:"POST",headers:c?{"x-devtools-token":c}:void 0});if(!d.ok){let p=`${d.status} ${d.statusText}`;try{const m=await d.json();m.error&&(p=m.error)}catch{}throw new Error(p)}const h=await d.blob(),f=rl(d.headers.get("content-disposition"))??`kickjs-heap-${Date.now()}.heapsnapshot`;nl(h,f),u({name:f,sizeBytes:h.size})}catch(c){s(c instanceof Error?c.message:String(c))}finally{r(!1)}};return(()=>{var c=Qn(),g=c.firstChild,d=g.firstChild.nextSibling,h=d.firstChild.nextSibling;h.nextSibling;var f=g.nextSibling.nextSibling,p=f.firstChild;return l(d,()=>Q(e.heapTotal),h),p.$$click=()=>{a()},l(p,()=>t()?"Capturing…":"Take snapshot"),l(f,o(b,{get when(){return i()},children:m=>(()=>{var y=Yn(),_=y.firstChild.nextSibling,C=_.nextSibling.nextSibling;return C.nextSibling,l(y,()=>m().name,_),l(y,()=>Q(m().sizeBytes),C),y})()}),null),l(c,o(b,{get when(){return n()},children:m=>(()=>{var y=Xt();return l(y,m),y})()}),null),k(()=>p.disabled=t()),c})()};function rl(e){if(!e)return null;const t=/filename="?([^";]+)"?/.exec(e);return t?t[1]:null}function nl(e,t){const r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}var ll=()=>{const[e,t]=x(!1),[r,n]=x(null),[s,i]=x(null),u=async()=>{t(!0),i(null);try{const a=ve(),c=`${ye()}/memory/gc${a?`?token=${encodeURIComponent(a)}`:""}`,g=await fetch(c,{method:"POST",headers:a?{"x-devtools-token":a}:void 0});if(!g.ok){let d=`${g.status} ${g.statusText}`;try{const h=await g.json();h.error&&(d=h.error)}catch{}throw new Error(d)}n(await g.json())}catch(a){i(a instanceof Error?a.message:String(a))}finally{t(!1)}};return(()=>{var a=Xn(),c=a.firstChild.nextSibling.nextSibling,g=c.firstChild;return g.$$click=()=>{u()},l(g,()=>e()?"Collecting…":"Run GC"),l(c,o(b,{get when(){return r()},children:d=>(()=>{var h=Zn(),f=h.firstChild.nextSibling,p=f.nextSibling.nextSibling,m=p.nextSibling.nextSibling,y=m.nextSibling.nextSibling;return y.nextSibling,l(h,()=>Q(d().reclaimedBytes),f),l(h,()=>Q(d().before),p),l(h,()=>Q(d().after),m),l(h,()=>d().elapsedMs,y),h})()}),null),l(a,o(b,{get when(){return s()},children:d=>(()=>{var h=Xt();return l(h,d),h})()}),null),k(()=>g.disabled=e()),a})()};J(["click"]);var sl=v('<div class="flex items-center justify-between mt-4 pt-3 border-t border-slate-800 text-xs text-slate-500"><div class="flex items-center gap-3"><span>Showing <!>–<!> of </span><label class="flex items-center gap-1"><span class=text-slate-600>Per page</span><select class="bg-slate-800 border border-slate-700 rounded px-1.5 py-0.5 text-slate-200"></select></label></div><div class="flex items-center gap-1"><button type=button class="px-2.5 py-1 rounded border border-slate-700 bg-slate-800 hover:bg-slate-700 disabled:opacity-30">Prev</button><button type=button class="px-2.5 py-1 rounded border border-slate-700 bg-slate-800 hover:bg-slate-700 disabled:opacity-30">Next'),il=v("<option>"),al=v('<span class="px-1 text-slate-600">…'),ol=v("<button type=button>"),cl=[5,10,15,20,25,50,100];function ge(e,t={}){const r=t.pageSizeChoices??cl,n=t.pageSize??r[0]??5,[s,i]=x(n),[u,a]=x(1),c=j(()=>Math.max(1,Math.ceil(e().length/s()))),g=j(()=>Math.min(u(),c()));return{source:e,page:j(()=>{const d=(g()-1)*s();return e().slice(d,d+s())}),current:g,total:c,pageSize:s,pageSizeChoices:r,range:j(()=>{const d=e().length;return d===0?{start:0,end:0,total:0}:{start:(g()-1)*s()+1,end:Math.min(g()*s(),d),total:d}}),goto(d){a(Math.max(1,Math.min(d,c())))},next(){a(d=>Math.min(d+1,c()))},prev(){a(d=>Math.max(d-1,1))},setPageSize(d){i(d);const h=(g()-1)*s();a(Math.max(1,Math.floor(h/d)+1))}}}var fe=e=>{const t=j(()=>{const r=e.pager.total(),n=e.pager.current();if(r<=7)return Array.from({length:r},(a,c)=>c+1);const s=[1],i=Math.max(2,n-1),u=Math.min(r-1,n+1);i>2&&s.push("gap");for(let a=i;a<=u;a++)s.push(a);return u<r-1&&s.push("gap"),s.push(r),s});return o(b,{get when(){return e.pager.total()>1||e.pager.source().length>e.pager.pageSize()},get children(){var r=sl(),n=r.firstChild,s=n.firstChild,i=s.firstChild.nextSibling,u=i.nextSibling.nextSibling;u.nextSibling;var a=s.nextSibling.firstChild.nextSibling,c=n.nextSibling,g=c.firstChild,d=g.nextSibling;return l(s,()=>e.pager.range().start,i),l(s,()=>e.pager.range().end,u),l(s,()=>e.pager.range().total,null),a.addEventListener("change",h=>e.pager.setPageSize(Number(h.currentTarget.value))),l(a,o(A,{get each(){return e.pager.pageSizeChoices},children:h=>(()=>{var f=il();return f.value=h,l(f,h),f})()})),g.$$click=()=>e.pager.prev(),l(c,o(A,{get each(){return t()},children:h=>o(b,{when:h==="gap",get fallback(){return(()=>{var f=ol();return f.$$click=()=>e.pager.goto(h),l(f,h),k(()=>B(f,`px-2.5 py-1 rounded border ${h===e.pager.current()?"border-kick-500/30 bg-kick-500/20 text-kick-500":"border-slate-700 bg-slate-800 hover:bg-slate-700"}`)),f})()},get children(){return al()}})}),d),d.$$click=()=>e.pager.next(),k(h=>{var f=e.pager.current()===1,p=e.pager.current()===e.pager.total();return f!==h.e&&(g.disabled=h.e=f),p!==h.t&&(d.disabled=h.t=p),h},{e:void 0,t:void 0}),k(()=>a.value=e.pager.pageSize()),r}})};J(["click"]);var ul=v('<div style=display:flex;justify-content:space-between;align-items:center;margin-bottom:12px><h2 style=margin:0;font-size:16px>Topology</h2><button type=button class=tab style="border:1px solid var(--border);border-radius:4px;padding:4px 12px;border-bottom-color:var(--border)">'),dl=v("<div class=card style=border-color:var(--critical)><div class=card-title style=color:var(--critical)>Topology error</div><code>"),hl=v("<div class=empty>Loading topology…"),gl=v('<div class=card style=border-color:var(--warn)><div class=card-title style=color:var(--warn)> introspect failure(s)</div><ul style="margin:8px 0 0;padding-left:20px;font-family:var(--font-mono);font-size:12px">'),fl=v("<li>/<!>: "),vl=v("<table><thead><tr><th>Key</th><th>Source</th><th>Depends on</th></tr></thead><tbody>"),pl=v("<div class=card><div class=card-header><div class=card-title>Contributors (<!>)"),ml=v("<div class=empty>No contributors registered"),bl=v("<tr><td><span class=tree-key></span></td><td></td><td>"),$l=v("<table><thead><tr><th>Token</th><th>Scope</th><th>Kind</th><th>Resolved</th></tr></thead><tbody>"),xl=v("<div class=card><div class=card-header><div class=card-title>DI tokens (<!>)"),yl=v("<div class=empty>No DI tokens registered"),_l=v("<tr><td><span class=tree-key></span></td><td></td><td></td><td>"),wl=v("<div class=card><div class=card-header><div class=card-title>"),Sl=v("<div class=empty>"),kl=v("<span class=tree-meta>[<!>]"),Cl=v("<span class=tree-meta>v"),El=v("<span class=tree-meta>"),Tl=v("<div class=tree-meta>provides: "),Ml=v("<div class=tree-meta>requires: "),kt=v("<div class=tree-meta>"),Al=v("<div class=tree-node><span class=tree-key>"),Ct=v("<span style=margin-right:12px>: <strong style=color:var(--text)>"),Ll=()=>{const[e,t]=x(null),[r,n]=x(null),[s,i]=x(!1),u=async()=>{i(!0),n(null);try{t(await ee.topology())}catch(a){n(a instanceof Error?a.message:String(a))}finally{i(!1)}};return xe(()=>{u()}),[(()=>{var a=ul(),c=a.firstChild.nextSibling;return c.$$click=()=>{u()},l(c,()=>s()?"Refreshing…":"Refresh"),k(()=>c.disabled=s()),a})(),o(b,{get when(){return r()},children:a=>(()=>{var c=dl(),g=c.firstChild.nextSibling;return l(g,a),c})()}),o(b,{get when(){return e()},get fallback(){return hl()},children:a=>[o(b,{get when(){return a().errors.length>0},get children(){var c=gl(),g=c.firstChild,d=g.firstChild,h=g.nextSibling;return l(g,()=>a().errors.length,d),l(h,o(A,{get each(){return a().errors},children:f=>(()=>{var p=fl(),m=p.firstChild,y=m.nextSibling;return y.nextSibling,l(p,()=>f.kind,m),l(p,()=>f.name,y),l(p,()=>f.message,null),p})()})),c}}),o(Et,{get title(){return`Plugins (${a().plugins.length})`},get items(){return a().plugins},empty:"No plugins registered"}),o(Et,{get title(){return`Adapters (${a().adapters.length})`},get items(){return a().adapters},empty:"No adapters registered"}),o(Rl,{get rows(){return a().contributors}}),o(Bl,{get rows(){return a().diTokens}})]})]},Rl=e=>{const t=j(()=>e.rows??[]),r=ge(t);return(()=>{var n=pl(),s=n.firstChild.firstChild,i=s.firstChild.nextSibling;return i.nextSibling,l(s,()=>t().length,i),l(n,o(b,{get when(){return t().length>0},get fallback(){return ml()},get children(){return[(()=>{var u=vl(),a=u.firstChild.nextSibling;return l(a,o(A,{get each(){return r.page()},children:c=>(()=>{var g=bl(),d=g.firstChild,h=d.firstChild,f=d.nextSibling,p=f.nextSibling;return l(h,()=>c.key),l(f,()=>c.source),l(p,()=>c.dependsOn.join(", ")||"—"),g})()})),u})(),o(fe,{pager:r})]}}),null),n})()},Bl=e=>{const t=j(()=>e.rows??[]),r=ge(t);return(()=>{var n=xl(),s=n.firstChild.firstChild,i=s.firstChild.nextSibling;return i.nextSibling,l(s,()=>t().length,i),l(n,o(b,{get when(){return t().length>0},get fallback(){return yl()},get children(){return[(()=>{var u=$l(),a=u.firstChild.nextSibling;return l(a,o(A,{get each(){return r.page()},children:c=>(()=>{var g=_l(),d=g.firstChild,h=d.firstChild,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return l(h,()=>c.token),l(f,()=>c.scope),l(p,()=>c.kind),l(m,()=>c.instantiated?"yes":"no"),g})()})),u})(),o(fe,{pager:r})]}}),null),n})()},Et=e=>(()=>{var t=wl(),r=t.firstChild.firstChild;return l(r,()=>e.title),l(t,o(b,{get when(){return e.items.length>0},get fallback(){return(()=>{var n=Sl();return l(n,()=>e.empty),n})()},get children(){return o(A,{get each(){return e.items},children:n=>o(jl,{item:n})})}}),null),t})();function Ol(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(1)} GB`}function ql(e){if(typeof e!="object"||e===null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}var jl=e=>(()=>{var t=Al(),r=t.firstChild;return l(r,()=>e.item.name),l(t,o(b,{get when(){return e.item.kind},get children(){var n=kl(),s=n.firstChild.nextSibling;return s.nextSibling,l(n,()=>e.item.kind,s),n}}),null),l(t,o(b,{get when(){return e.item.version},get children(){var n=Cl();return n.firstChild,l(n,()=>e.item.version,null),n}}),null),l(t,o(b,{get when(){return typeof e.item.memoryBytes=="number"},get children(){var n=El();return l(n,()=>Ol(e.item.memoryBytes)),n}}),null),l(t,o(b,{get when(){return e.item.tokens?.provides.length},get children(){var n=Tl();return n.firstChild,l(n,()=>e.item.tokens?.provides.join(", "),null),n}}),null),l(t,o(b,{get when(){return e.item.tokens?.requires.length},get children(){var n=Ml();return n.firstChild,l(n,()=>e.item.tokens?.requires.join(", "),null),n}}),null),l(t,o(b,{get when(){return Re(()=>!!e.item.state)()&&Object.keys(e.item.state).length>0},get children(){var n=kt();return l(n,o(A,{get each(){return Object.entries(e.item.state??{})},children:([s,i])=>(()=>{var u=Ct(),a=u.firstChild,c=a.nextSibling;return l(u,s,a),l(c,()=>ql(i)),u})()})),n}}),null),l(t,o(b,{get when(){return e.item.metrics},children:n=>(()=>{var s=kt();return l(s,o(A,{get each(){return Object.entries(n())},children:([i,u])=>(()=>{var a=Ct(),c=a.firstChild,g=c.nextSibling;return l(a,i,c),l(g,u),a})()})),s})()}),null),t})();J(["click"]);var Pl=v("<div class=overflow-x-auto><table><thead><tr><th>Method</th><th>Path</th><th>Controller</th><th>Handler</th><th>Middleware</th><th>Flags</th></tr></thead><tbody>"),Nl=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col sm:flex-row gap-3 mb-4"><div class="relative flex-1"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search routes (path, controller, handler)…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"></div><div class="flex gap-1">'),Il=v("<button type=button>"),Dl=v("<div class=empty>"),Ul=v('<tr><td><span></span></td><td class="font-mono text-sm"></td><td></td><td class=text-text-secondary></td><td class="text-text-muted text-xs"></td><td class="text-text-muted text-xs">'),zl=["ALL","GET","POST","PUT","DELETE","PATCH"];function Fl(e){const t=Object.entries(e??{});return t.length?t.map(([r,n])=>n===!0?r:`${r}=${JSON.stringify(n)}`).join(", "):"—"}var Hl=()=>{const[e,t]=x(""),[r,n]=x("ALL"),s=j(()=>{let u=M.routes();r()!=="ALL"&&(u=u.filter(c=>c.method.toUpperCase()===r()));const a=e().trim().toLowerCase();return a&&(u=u.filter(c=>c.path.toLowerCase().includes(a)||c.controller.toLowerCase().includes(a)||c.handler.toLowerCase().includes(a))),u}),i=ge(()=>s());return(()=>{var u=Nl(),a=u.firstChild.firstChild,c=a.firstChild.nextSibling,g=a.nextSibling;return c.$$input=d=>t(d.currentTarget.value),l(g,o(A,{each:zl,children:d=>(()=>{var h=Il();return h.$$click=()=>n(d),l(h,d),k(()=>B(h,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${r()===d?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),h})()})),l(u,o(b,{get when(){return i.page().length>0},get fallback(){return(()=>{var d=Dl();return l(d,()=>e()||r()!=="ALL"?"No routes match the current filter":"No routes registered"),d})()},get children(){return[(()=>{var d=Pl(),h=d.firstChild.firstChild.nextSibling;return l(h,o(A,{get each(){return i.page()},children:f=>(()=>{var p=Ul(),m=p.firstChild,y=m.firstChild,_=m.nextSibling,C=_.nextSibling,w=C.nextSibling,E=w.nextSibling,S=E.nextSibling;return l(y,()=>f.method),l(_,()=>f.path),l(C,()=>f.controller),l(w,()=>f.handler),l(E,(()=>{var T=Re(()=>!!f.middleware.length);return()=>T()?f.middleware.join(", "):"—"})()),l(S,()=>Fl(f.flags)),k(()=>B(y,`text-xs font-bold ${Gl(f.method)}`)),p})()})),d})(),o(fe,{pager:i})]}}),null),k(()=>c.value=e()),u})()};function Gl(e){const t=e.toUpperCase();return t==="GET"?"text-emerald-400":t==="POST"?"text-cyan-400":t==="PUT"||t==="PATCH"?"text-amber-400":t==="DELETE"?"text-red-400":"text-text-secondary"}J(["input","click"]);var Vl=v("<div class=card style=border-color:var(--critical)><div class=card-title style=color:var(--critical)>Failed to load metrics</div><code>"),Kl=v("<div class=empty>Loading route metrics…"),Wl=v("<div class=grid>"),Jl=v("<table><thead><tr><th>Route</th><th style=text-align:right>Calls</th><th style=text-align:right>Avg</th><th style=text-align:right>p50</th><th style=text-align:right>p95</th><th style=text-align:right>p99</th><th style=text-align:right>Max</th></tr></thead><tbody>"),Ql=v("<div class=card><div class=card-header><div class=card-title>Per-route latency"),Yl=v("<div class=empty>No requests recorded yet"),Xl=v("<tr><td></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right></td><td style=text-align:right>"),Zl=v("<div class=card><div class=card-header><div class=card-title></div><div class=card-value>"),es=()=>{const[e,t]=x(null),[r,n]=x(null),s=async()=>{try{t(await ee.routes()),n(null)}catch(u){n(u instanceof Error?u.message:String(u))}};xe(()=>{s();const u=setInterval(()=>{s()},2e3);return()=>clearInterval(u)});const i=j(()=>{const u=e();return u?Object.entries(u.routeLatency).map(([a,c])=>Object.assign({key:a},c,{avg:c.count>0?c.totalMs/c.count:0})).toSorted((a,c)=>c.count-a.count):[]});return[o(b,{get when(){return r()},children:u=>(()=>{var a=Vl(),c=a.firstChild.nextSibling;return l(c,u),a})()}),o(b,{get when(){return e()},get fallback(){return Kl()},children:u=>[(()=>{var a=Wl();return l(a,o(we,{title:"Requests",metric:"requests",get value(){return u().requests.toString()}}),null),l(a,o(we,{title:"Server errors",metric:"server-errors",get value(){return u().serverErrors.toString()}}),null),l(a,o(we,{title:"Client errors",metric:"client-errors",get value(){return u().clientErrors.toString()}}),null),l(a,o(we,{title:"Error rate",metric:"error-rate",get value(){return Fe(u().errorRate)}}),null),l(a,o(we,{title:"Uptime",metric:"uptime",get value(){return dt(u().uptimeSeconds)}}),null),a})(),(()=>{var a=Ql();return a.firstChild,l(a,o(b,{get when(){return i().length>0},get fallback(){return Yl()},get children(){var c=Jl(),g=c.firstChild,d=g.firstChild.firstChild.nextSibling.nextSibling;d.firstChild;var h=d.nextSibling;h.firstChild;var f=h.nextSibling;f.firstChild;var p=f.nextSibling;p.firstChild;var m=p.nextSibling;m.firstChild;var y=g.nextSibling;return l(d,o(Y,{metric:"latency.avg",placement:"bottom"}),null),l(h,o(Y,{metric:"latency.p50",placement:"bottom"}),null),l(f,o(Y,{metric:"latency.p95",placement:"bottom"}),null),l(p,o(Y,{metric:"latency.p99",placement:"bottom"}),null),l(m,o(Y,{metric:"latency.max",placement:"bottom"}),null),l(y,o(A,{get each(){return i()},children:_=>(()=>{var C=Xl(),w=C.firstChild,E=w.nextSibling,S=E.nextSibling,T=S.nextSibling,F=T.nextSibling,I=F.nextSibling,O=I.nextSibling;return l(w,()=>_.key),l(E,()=>_.count),l(S,()=>oe(_.avg)),l(T,()=>oe(_.p50)),l(F,()=>oe(_.p95)),l(I,()=>oe(_.p99)),l(O,()=>oe(_.maxMs)),C})()})),c}}),null),a})()]})]},we=e=>(()=>{var t=Zl(),r=t.firstChild.firstChild,n=r.nextSibling;return l(r,()=>e.title,null),l(r,o(b,{get when(){return e.metric},children:s=>o(Y,{get metric(){return s()}})}),null),l(n,()=>e.value),t})(),ts=v('<button type=button class="text-text-muted hover:text-text-strong p-1"aria-label=Back><svg class="w-4 h-4"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M15 19l-7-7 7-7">'),Tt=v('<div class="flex flex-wrap gap-1">'),rs=v('<div class="bg-surface-2/50 rounded-lg border border-border-strong p-3 space-y-2 text-sm">'),ns=v("<span>"),ls=v('<div class="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"><div class="bg-surface-1 border border-border-strong rounded-2xl p-6 max-w-2xl w-full shadow-2xl max-h-[90vh] overflow-y-auto"><div class="flex items-start justify-between mb-4"><div><div class="flex items-center gap-2 mb-1"><h2 class="text-base font-semibold font-mono text-text-body break-all"></h2></div><div class="flex flex-wrap gap-2 mt-2"><span></span><span class="bg-border-strong/50 text-text-strong px-2 py-0.5 rounded text-xs font-semibold"></span><span></span></div></div><button type=button class="text-slate-500 hover:text-slate-300 p-1"aria-label=Close><svg class="w-5 h-5"fill=none stroke=currentColor viewBox="0 0 24 24"><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M6 18L18 6M6 6l12 12">'),Mt=v('<span class="text-text-muted text-sm">None'),ss=v('<button type=button class="bg-surface-2 text-kick-500 hover:bg-border-strong px-2.5 py-1 rounded text-xs font-mono border border-border-strong transition-colors">'),is=v('<button type=button class="bg-surface-2 text-amber-400 hover:bg-border-strong px-2.5 py-1 rounded text-xs font-mono border border-border-strong transition-colors">'),as=v('<div class=mb-4><h3 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">'),os=v('<div class="flex justify-between"><span class=text-text-secondary></span><span class=tabular-nums>'),[nt,Me]=x(null),[cs,We]=x([]);function He(e){We([]),Me(e)}function At(e){const t=nt();t&&t!==e&&We(r=>[...r,t]),Me(e)}function us(){We(e=>{if(e.length===0)return Me(null),e;const t=e.slice(0,-1);return Me(e[e.length-1]),t})}function Lt(){Me(null),We([])}var ds=()=>{const e=j(()=>{const r=nt();if(!r)return null;const n=M.container().find(s=>s.token===r);return n||{token:r,kind:void 0,scope:void 0,dependencies:[]}}),t=j(()=>{const r=nt();return r?M.container().filter(n=>n.dependencies?.includes(r)).map(n=>n.token):[]});return o(b,{get when(){return e()},children:r=>(()=>{var n=ls(),s=n.firstChild,i=s.firstChild.firstChild,u=i.firstChild,a=u.firstChild,c=u.nextSibling.firstChild,g=c.nextSibling,d=g.nextSibling,h=i.nextSibling;return n.$$click=f=>{f.target===f.currentTarget&&Lt()},l(u,o(b,{get when(){return cs().length>0},get children(){var f=ts();return f.$$click=us,f}}),a),l(a,()=>r().token),l(c,()=>r().kind??"unknown"),l(g,()=>r().scope??"singleton"),l(d,()=>fs(r())),h.$$click=Lt,l(s,o(Oe,{title:"Dependencies",get children(){return o(b,{get when(){return(r().dependencies?.length??0)>0},get fallback(){return Mt()},get children(){var f=Tt();return l(f,o(A,{get each(){return r().dependencies},children:p=>(()=>{var m=ss();return m.$$click=()=>At(p),l(m,p),m})()})),f}})}}),null),l(s,o(Oe,{title:"Dependents",get children(){return o(b,{get when(){return t().length>0},get fallback(){return Mt()},get children(){var f=Tt();return l(f,o(A,{get each(){return t()},children:p=>(()=>{var m=is();return m.$$click=()=>At(p),l(m,p),m})()})),f}})}}),null),l(s,o(Oe,{title:"Resolve stats",get children(){var f=rs();return l(f,o(qe,{label:"Resolve count",get value(){return String(r().resolveCount??0)}}),null),l(f,o(b,{get when(){return r().firstResolved},children:p=>o(qe,{label:"First resolved",get value(){return new Date(p()).toLocaleString()}})}),null),l(f,o(b,{get when(){return r().lastResolved},children:p=>o(qe,{label:"Last resolved",get value(){return new Date(p()).toLocaleString()}})}),null),l(f,o(b,{get when(){return r().resolveDurationMs!=null},get children(){return o(qe,{label:"Resolution duration",get value(){return`${(r().resolveDurationMs??0).toFixed(2)} ms`}})}}),null),f}}),null),l(s,o(Oe,{title:"PostConstruct",get children(){var f=ns();return l(f,()=>r().postConstructStatus??"none"),k(()=>B(f,`px-2 py-0.5 rounded text-xs font-semibold ${vs(r().postConstructStatus)}`)),f}}),null),k(f=>{var p=`px-2 py-0.5 rounded text-xs font-semibold ${hs(r().kind)}`,m=`px-2 py-0.5 rounded text-xs font-semibold ${gs(r())}`;return p!==f.e&&B(c,f.e=p),m!==f.t&&B(d,f.t=m),f},{e:void 0,t:void 0}),n})()})},Oe=e=>(()=>{var t=as(),r=t.firstChild;return l(r,()=>e.title),l(t,()=>e.children,null),t})(),qe=e=>(()=>{var t=os(),r=t.firstChild,n=r.nextSibling;return l(r,()=>e.label),l(n,()=>e.value),t})();function hs(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function gs(e){return e.postConstructStatus==="failed"?"bg-red-900/50 text-red-300":e.instantiated?"bg-emerald-900/50 text-emerald-300":"bg-amber-900/50 text-amber-300"}function fs(e){return e.postConstructStatus==="failed"?"failed":e.instantiated?"active":"registered"}function vs(e){return e==="done"?"bg-emerald-900/50 text-emerald-300":e==="failed"?"bg-red-900/50 text-red-300":"bg-border-strong/50 text-text-secondary"}J(["click"]);var ps=v("<div class=overflow-x-auto><table><thead><tr><th class=w-6 aria-label=expand></th><th>Token</th><th>Kind</th><th>Scope</th><th>Status</th><th class=text-right>Resolves</th><th class=text-right>Deps</th></tr></thead><tbody>"),ms=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col gap-3 mb-4"><div class=relative><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search tokens…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"></div><div class="flex flex-col sm:flex-row gap-3"><div class="flex gap-1 items-center"><span class="text-xs text-text-muted mr-1">Kind:</span></div><div class="flex gap-1 items-center"><span class="text-xs text-text-muted mr-1">Scope:'),Rt=v("<button type=button>"),bs=v("<div class=empty>"),$s=v('<tr class="cursor-pointer select-none"><td><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M9 5l7 7-7 7"></path></svg></td><td class="font-mono text-sm"></td><td><span></span></td><td><span class="bg-border-strong/50 text-text-strong px-2 py-0.5 rounded text-xs font-semibold"></span></td><td><span></span></td><td class="text-right tabular-nums"></td><td class="text-right text-text-muted text-xs">'),xs=v('<tr><td colspan=7 class="bg-surface-2/30 px-6 py-4 border-b border-border">'),ys=v('<div class="flex flex-wrap gap-1">'),_s=v('<div class="flex justify-between"><span class=text-text-secondary>Duration</span><span class=tabular-nums>ms'),ws=v('<div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">Dependencies</h4></div><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">Resolve Stats</h4><div class="space-y-1 text-sm"><div class="flex justify-between"><span class=text-text-secondary>Resolve count</span><span class=tabular-nums></span></div></div></div><div><h4 class="text-xs font-semibold uppercase tracking-wider text-text-muted mb-2">PostConstruct</h4><span></span></div><div class="md:col-span-2 flex justify-end"><button type=button class="px-3 py-1.5 text-xs font-semibold rounded-lg bg-kick-500/20 text-kick-500 border border-kick-500/30 hover:bg-kick-500/30 transition-colors">View full details'),Ss=v('<span class="text-text-muted text-sm">None'),ks=v('<button type=button class="bg-border-strong/50 text-kick-500 hover:bg-border-strong px-2 py-0.5 rounded text-xs font-mono transition-colors">'),Cs=v('<div class="flex justify-between"><span class=text-text-secondary>First resolved</span><span class=text-xs>'),Es=v('<div class="flex justify-between"><span class=text-text-secondary>Last resolved</span><span class=text-xs>'),Ts=["ALL","controller","service","repository","other"],Ms=["ALL","singleton","transient","request"],As=()=>{const[e,t]=x(""),[r,n]=x("ALL"),[s,i]=x("ALL"),[u,a]=x(new Set),c=j(()=>{let h=M.container();if(r()!=="ALL"){const p=r();h=h.filter(m=>p==="other"?!["controller","service","repository"].includes(m.kind??""):m.kind===p)}s()!=="ALL"&&(h=h.filter(p=>p.scope===s()));const f=e().trim().toLowerCase();return f&&(h=h.filter(p=>p.token.toLowerCase().includes(f))),h}),g=ge(()=>c()),d=h=>{a(f=>{const p=new Set(f);return p.has(h)?p.delete(h):p.add(h),p})};return(()=>{var h=ms(),f=h.firstChild.firstChild,p=f.firstChild.nextSibling,m=f.nextSibling.firstChild;m.firstChild;var y=m.nextSibling;return y.firstChild,p.$$input=_=>t(_.currentTarget.value),l(m,o(A,{each:Ts,children:_=>(()=>{var C=Rt();return C.$$click=()=>n(_),l(C,_),k(()=>B(C,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${r()===_?Bs(_):"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),C})()}),null),l(y,o(A,{each:Ms,children:_=>(()=>{var C=Rt();return C.$$click=()=>i(_),l(C,_),k(()=>B(C,`px-3 py-1.5 text-xs font-semibold rounded-lg transition-colors border ${s()===_?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),C})()}),null),l(h,o(b,{get when(){return g.page().length>0},get fallback(){return(()=>{var _=bs();return l(_,()=>e()||r()!=="ALL"||s()!=="ALL"?"No tokens match the current filter":"No DI registrations"),_})()},get children(){return[(()=>{var _=ps(),C=_.firstChild.firstChild,w=C.firstChild.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;w.firstChild;var E=C.nextSibling;return l(w,o(Y,{metric:"resolve.count",placement:"bottom"}),null),l(E,o(A,{get each(){return g.page()},children:S=>[(()=>{var T=$s(),F=T.firstChild,I=F.firstChild,O=F.nextSibling,R=O.nextSibling,X=R.firstChild,z=R.nextSibling,V=z.firstChild,D=z.nextSibling,H=D.firstChild,K=D.nextSibling,Z=K.nextSibling;return T.$$click=()=>d(S.token),l(O,()=>S.token),l(X,()=>S.kind??"unknown"),l(V,()=>S.scope??"—"),l(H,()=>qs(S)),l(K,()=>S.resolveCount??0),l(Z,()=>S.dependencies?.length??0),k(ae=>{var ne=`w-3 h-3 text-text-muted transition-transform ${u().has(S.token)?"rotate-90":""}`,ue=`px-2 py-0.5 rounded text-xs font-semibold ${Rs(S.kind)}`,_e=`px-2 py-0.5 rounded text-xs font-semibold ${Os(S)}`;return ne!==ae.e&&N(I,"class",ae.e=ne),ue!==ae.t&&B(X,ae.t=ue),_e!==ae.a&&B(H,ae.a=_e),ae},{e:void 0,t:void 0,a:void 0}),T})(),o(b,{get when(){return u().has(S.token)},get children(){var T=xs(),F=T.firstChild;return l(F,o(Ls,{registration:S})),T}})]})),_})(),o(fe,{pager:g})]}}),null),k(()=>p.value=e()),h})()},Ls=e=>(()=>{var t=ws(),r=t.firstChild;r.firstChild;var n=r.nextSibling,s=n.firstChild.nextSibling,i=s.firstChild.firstChild.nextSibling,u=n.nextSibling,a=u.firstChild;a.firstChild;var c=a.nextSibling,g=u.nextSibling.firstChild;return l(r,o(b,{get when(){return(e.registration.dependencies?.length??0)>0},get fallback(){return Ss()},get children(){var d=ys();return l(d,o(A,{get each(){return e.registration.dependencies},children:h=>(()=>{var f=ks();return f.$$click=p=>{p.stopPropagation(),He(h)},N(f,"title",`Open detail for ${h}`),l(f,h),f})()})),d}}),null),l(i,()=>e.registration.resolveCount??0),l(s,o(b,{get when(){return e.registration.firstResolved},children:d=>(()=>{var h=Cs(),f=h.firstChild.nextSibling;return l(f,()=>new Date(d()).toLocaleTimeString()),h})()}),null),l(s,o(b,{get when(){return e.registration.lastResolved},children:d=>(()=>{var h=Es(),f=h.firstChild.nextSibling;return l(f,()=>new Date(d()).toLocaleTimeString()),h})()}),null),l(s,o(b,{get when(){return e.registration.resolveDurationMs!=null},get children(){var d=_s(),h=d.firstChild.nextSibling,f=h.firstChild;return l(h,()=>(e.registration.resolveDurationMs??0).toFixed(2),f),d}}),null),l(a,o(Y,{metric:"post-construct"}),null),l(c,()=>e.registration.postConstructStatus??"none"),g.$$click=d=>{d.stopPropagation(),He(e.registration.token)},k(()=>B(c,`px-2 py-0.5 rounded text-xs font-semibold ${js(e.registration.postConstructStatus)}`)),t})();function Rs(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function Bs(e){return e==="controller"?"bg-violet-900/50 text-violet-300 border-violet-700/50":e==="service"?"bg-blue-900/50 text-blue-300 border-blue-700/50":e==="repository"?"bg-teal-900/50 text-teal-300 border-teal-700/50":e==="other"?"bg-border-strong/50 text-text-strong border-border-strong/50":"bg-kick-500/20 text-kick-500 border-kick-500/30"}function Os(e){return e.postConstructStatus==="failed"?"bg-red-900/50 text-red-300":e.instantiated?"bg-emerald-900/50 text-emerald-300":"bg-amber-900/50 text-amber-300"}function qs(e){return e.postConstructStatus==="failed"?"failed":e.instantiated?"active":"registered"}function js(e){return e==="done"?"bg-emerald-900/50 text-emerald-300":e==="failed"?"bg-red-900/50 text-red-300":"bg-border-strong/50 text-text-secondary"}J(["input","click"]);var Ps=v('<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">'),Ns=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="relative mb-4"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Search queues by name…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500">'),Is=v('<div class=card><div class=card-title>Queues</div><p class="text-text-muted text-sm mt-2">QueueAdapter not detected. Install <code class="font-mono text-kick-500">@forinda/kickjs-queue</code> and register the adapter in your bootstrap to see queue stats here.'),Ds=v("<div class=empty>No queues registered"),Us=v("<div class=empty>No queues match the search"),zs=v('<div class="grid grid-cols-2 gap-2 text-sm">'),Fs=v('<div class="bg-surface-2/50 rounded-lg border border-border-strong p-4"><h3 class="font-mono text-sm font-semibold text-kick-500 mb-3 break-all">'),Hs=v('<div class="text-red-400 text-sm">'),Gs=v('<div class="flex justify-between"><span class=text-text-secondary></span><span>'),Vs=()=>{const[e,t]=x(""),r=j(()=>{const s=M.queues().queues,i=e().trim().toLowerCase();return i?s.filter(u=>u.name.toLowerCase().includes(i)):s}),n=ge(()=>r());return o(b,{get when(){return M.queues().enabled},get fallback(){return Is()},get children(){return o(b,{get when(){return M.queues().queues.length>0},get fallback(){return Ds()},get children(){var s=Ns(),i=s.firstChild.firstChild.nextSibling;return i.$$input=u=>t(u.currentTarget.value),l(s,o(b,{get when(){return n.page().length>0},get fallback(){return Us()},get children(){return[(()=>{var u=Ps();return l(u,o(A,{get each(){return n.page()},children:a=>o(Ks,{queue:a})})),u})(),o(fe,{pager:n})]}}),null),k(()=>i.value=e()),s}})}})},Ks=e=>(()=>{var t=Fs(),r=t.firstChild;return l(r,()=>e.queue.name),l(t,o(b,{get when(){return!e.queue.error},get fallback(){return(()=>{var n=Hs();return l(n,()=>e.queue.error),n})()},get children(){var n=zs();return l(n,o(me,{label:"Waiting",get value(){return e.queue.waiting??0},colour:"text-amber-400"}),null),l(n,o(me,{label:"Active",get value(){return e.queue.active??0},colour:"text-blue-400"}),null),l(n,o(me,{label:"Completed",get value(){return e.queue.completed??0},colour:"text-emerald-400"}),null),l(n,o(me,{label:"Failed",get value(){return e.queue.failed??0},colour:"text-red-400"}),null),l(n,o(me,{label:"Delayed",get value(){return e.queue.delayed??0},colour:"text-violet-400"}),null),l(n,o(me,{label:"Paused",get value(){return e.queue.paused??0},colour:"text-text-secondary"}),null),n}}),null),t})(),me=e=>(()=>{var t=Gs(),r=t.firstChild,n=r.nextSibling;return l(r,()=>e.label),l(n,()=>e.value),k(()=>B(n,`font-semibold tabular-nums ${e.colour}`)),t})();J(["input"]);function Ws(){let e=new Map,t=new Set;return{on:(r,n)=>{let s=e.get(r);return s||(s=new Set,e.set(r,s)),s.add(n),()=>{let i=e.get(r);i?.delete(n),i&&i.size===0&&e.delete(r)}},onAny:r=>(t.add(r),()=>{t.delete(r)}),dispatch:r=>{let n=e.get(r.type);if(n&&n.size>0)for(let s of[...n])try{s(r.payload)}catch(i){console.error(`[kick:devtools-bus] handler for "${r.type}" threw`,i)}if(t.size>0)for(let s of[...t])try{s(r)}catch(i){console.error("[kick:devtools-bus] onAny handler threw",i)}}}}function Js(e={}){let t=Ws(),r=e.channel===!1?null:e.channel??"kick-devtools",n=r!=null&&typeof BroadcastChannel<"u"?new BroadcastChannel(r):null;n?.addEventListener("message",f=>{let p=f.data;!p||typeof p.type!="string"||typeof p.ts!="number"||t.dispatch({...p,__kick_origin:"broadcast"})});let s=null,i=0,u=null,a=e.reconnectMs??500,c=e.reconnectMaxMs??5e3,g=()=>{e.wsUrl&&(typeof WebSocket>"u"||s&&(s.readyState===WebSocket.OPEN||s.readyState===WebSocket.CONNECTING)||(s=new WebSocket(e.wsUrl),s.addEventListener("open",()=>{i=0}),s.addEventListener("message",f=>{try{let p=JSON.parse(String(f.data));if(!p||typeof p.type!="string"||typeof p.ts!="number")return;t.dispatch({...p,__kick_origin:"ws"})}catch{}}),s.addEventListener("close",()=>{s=null,d()}),s.addEventListener("error",()=>{d()})))},d=()=>{if(!e.wsUrl||u!=null)return;i+=1;let f=Math.min(i*a,c);u=setTimeout(()=>{u=null,g()},f)},h=f=>{n?.postMessage(f),s&&s.readyState===WebSocket.OPEN?s.send(JSON.stringify(f)):e.wsUrl&&g()};return{on(f,p){return g(),t.on(f,p)},onAny(f){return g(),t.onAny(f)},emit(f,p){let m={type:f,payload:p,ts:Date.now(),__kick_origin:"local"};t.dispatch(m),h(m)}}}var ke=null,[Qs,lt]=x([]);function Ys(){if(ke)return()=>{};const e=`${ye()}/_bus`,t=location.protocol==="https:"?"wss:":"ws:",r=ve(),n=r?`?token=${encodeURIComponent(r)}`:"",s=`${t}//${location.host}${e}${n}`;ke=Js({channel:"kick-devtools",wsUrl:s});const i=ke.onAny(u=>{lt(a=>{const c=a.length>=500?a.slice(1):a.slice();return c.push(u),c})});return()=>{i(),ke=null,lt([])}}function Ge(){return Qs}function Xs(){lt([])}function Zs(){return ke}var Qe=200;function ei(e){if(e==null)return String(e);if(typeof e=="bigint")return`${e.toString()}n`;if(typeof e!="object")return String(e);const t=new WeakSet,r=(s,i)=>{if(typeof i=="bigint")return`${i.toString()}n`;if(i instanceof Error)return{name:i.name,message:i.message};if(i&&typeof i=="object"){if(t.has(i))return"[Circular]";t.add(i)}return i};let n;try{n=JSON.stringify(e,r)}catch{n="[unserialisable]"}return n===void 0&&(n=String(e)),n.length>Qe?`${n.slice(0,Qe)}… (+${n.length-Qe} chars)`:n}function Zt(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}.${String(t.getMilliseconds()).padStart(3,"0")}`}var ti=v("<table><thead><tr><th>Time</th><th>Dialect</th><th class=text-right>Duration</th><th>SQL</th></tr></thead><tbody>"),ri=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="grid mb-4"></div><input type=text placeholder="Filter by SQL (substring)…"class="w-full bg-surface-2 border border-border-strong rounded-lg px-3 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500 mb-4">'),ni=v("<div class=empty>No queries yet. <code>kick/db</code> emits a <code>db:query</code> event per statement when DevTools is installed — run a query to see it here."),li=v("<code class=break-all>"),si=v("<tr><td class=dimmed></td><td></td><td class=text-right></td><td>"),ii=v("<span style=color:var(--color-red-400)>"),ai=v("<div class=card><div class=card-header><div class=card-title></div></div><div class=card-value>"),Ye=50,oi=300,ci=()=>{const[e,t]=x([]),[r,n]=x(""),s=g=>{t(d=>{const h=d.length>=oi?d.slice(1):d.slice();return h.push(g),h})},i=(g,d)=>{const h=g,f=h.error;return{sql:h.sql,parameters:h.parameters,durationMs:0,dialect:h.dialect,error:f instanceof Error?f.message:String(f??"query error"),ts:d}};xe(()=>{for(const f of Ge()())f.type==="db:query"?s({...f.payload,ts:f.ts}):f.type==="db:query-error"&&s(i(f.payload,f.ts));const g=Zs(),d=g?.on("db:query",f=>{const p=f;s({...p,ts:p.ts??Date.now()})}),h=g?.on("db:query-error",f=>s(i(f,Date.now())));ie(()=>{d?.(),h?.()})});const u=j(()=>{const g=e(),d=g.filter(p=>p.error).length,h=g.filter(p=>p.durationMs>=Ye).length,f=g.length;return{total:f,errors:d,slow:h,avg:f?g.reduce((p,m)=>p+m.durationMs,0)/f:0}}),a=j(()=>{const g=r().trim().toLowerCase();return[...g?e().filter(d=>d.sql.toLowerCase().includes(g)):e()].toReversed()}),c=ge(()=>a());return(()=>{var g=ri(),d=g.firstChild,h=d.nextSibling;return l(d,o(je,{label:"Queries",get value(){return String(u().total)}}),null),l(d,o(je,{label:"Errors",get value(){return String(u().errors)},get tone(){return u().errors?"err":void 0}}),null),l(d,o(je,{label:`Slow (≥${Ye}ms)`,get value(){return String(u().slow)},get tone(){return u().slow?"warn":void 0}}),null),l(d,o(je,{label:"Avg duration",get value(){return oe(u().avg)}}),null),h.$$input=f=>n(f.currentTarget.value),l(g,o(b,{get when(){return e().length},get fallback(){return ni()},get children(){return[(()=>{var f=ti(),p=f.firstChild.nextSibling;return l(p,o(A,{get each(){return c.page()},children:m=>(()=>{var y=si(),_=y.firstChild,C=_.nextSibling,w=C.nextSibling,E=w.nextSibling;return l(_,()=>Zt(m.ts)),l(C,()=>m.dialect??"—"),l(w,()=>oe(m.durationMs)),l(E,o(b,{get when(){return!m.error},get fallback(){return(()=>{var S=ii();return l(S,()=>m.error),S})()},get children(){var S=li();return l(S,()=>m.sql),S}})),k(S=>ct(w,m.durationMs>=Ye?"color:var(--color-amber-400);font-weight:600":"",S)),y})()})),f})(),o(fe,{pager:c})]}}),null),k(()=>h.value=r()),g})()},je=e=>(()=>{var t=ai(),r=t.firstChild,n=r.firstChild,s=r.nextSibling;return l(n,()=>e.label),l(s,()=>e.value),k(i=>ct(s,e.tone==="err"?"color:var(--color-red-400)":e.tone==="warn"?"color:var(--color-amber-400)":"",i)),t})();J(["input"]);var ui=v("<div class=space-y-6>"),di=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="relative mb-4"><svg class="absolute left-3 top-2.5 w-4 h-4 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg><input type=text placeholder="Filter graph (token or kind)…"class="w-full bg-surface-2 border border-border-strong rounded-lg pl-10 pr-4 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500">'),hi=v("<div class=empty>"),gi=v("<div class=space-y-1>"),fi=v('<div><button type=button><svg fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2.5 d="M9 5l7 7-7 7"></path></svg><span></span><span class="ml-2 text-text-muted font-normal normal-case">(<!>)'),vi=v('<span class="bg-border-strong/50 text-text-secondary px-1.5 py-0.5 rounded text-xs">'),pi=v('<span class="text-text-muted text-xs ml-auto tabular-nums"> resolves'),mi=v('<div class="ml-8 mt-1 space-y-0.5">'),bi=v('<button type=button class="w-full text-left px-3 py-2 rounded-lg hover:bg-surface-2/50 transition-colors group"><div class="flex items-center gap-2"><span></span><span class="font-mono text-sm text-text-body break-all">'),$i=v('<div class="flex items-center gap-2 text-xs text-text-muted hover:text-text-strong"><svg class="w-3 h-3 text-text-muted"fill=none stroke=currentColor viewBox="0 0 24 24"aria-hidden=true><path stroke-linecap=round stroke-linejoin=round stroke-width=2 d="M13 7l5 5-5 5M6 12h12"></path></svg><span></span><span class=font-mono>'),xi=[{id:"controllers",label:"Controllers",match:e=>e==="controller"},{id:"services",label:"Services",match:e=>e==="service"},{id:"repositories",label:"Repositories",match:e=>e==="repository"},{id:"other",label:"Other",match:e=>!["controller","service","repository"].includes(e??"")}],yi=()=>{const[e,t]=x(""),r=j(()=>{const s=M.container(),i=e().trim().toLowerCase();return i?s.filter(u=>u.token.toLowerCase().includes(i)||(u.kind??"").toLowerCase().includes(i)):s}),n=j(()=>xi.map(s=>Object.assign(s,{nodes:r().filter(i=>s.match(i.kind))})));return(()=>{var s=di(),i=s.firstChild.firstChild.nextSibling;return i.$$input=u=>t(u.currentTarget.value),l(s,o(b,{get when(){return r().length>0},get fallback(){return(()=>{var u=hi();return l(u,()=>e()?"No nodes match the filter":"No DI registrations to graph"),u})()},get children(){var u=ui();return l(u,o(A,{get each(){return n()},children:a=>o(b,{get when(){return a.nodes.length>0},get children(){return o(_i,{get label(){return a.label},get nodes(){return a.nodes}})}})})),u}}),null),k(()=>i.value=e()),s})()},_i=e=>{const t=j(()=>e.nodes??[]),r=ge(t),n=`kickjs-devtools-graph-collapsed-${e.label}`,s=()=>{try{return localStorage.getItem(n)==="1"}catch{return!1}},[i,u]=x(s()),a=()=>{const c=!i();u(c);try{c?localStorage.setItem(n,"1"):localStorage.removeItem(n)}catch{}};return(()=>{var c=fi(),g=c.firstChild,d=g.firstChild,h=d.nextSibling,f=h.nextSibling,p=f.firstChild.nextSibling;return p.nextSibling,g.$$click=a,l(h,()=>e.label),l(f,()=>t().length,p),l(c,o(b,{get when(){return!i()},get children(){return[(()=>{var m=gi();return l(m,o(A,{get each(){return r.page()},children:y=>o(wi,{node:y})})),m})(),o(b,{get when(){return r.total()>1},get children(){return o(fe,{pager:r})}})]}}),null),k(m=>{var y=!i(),_=`w-full flex items-center text-left text-xs font-semibold uppercase tracking-wider mb-2 ${Si(e.label)} cursor-pointer hover:opacity-80 transition-opacity`,C=`w-3 h-3 mr-1.5 transition-transform ${i()?"":"rotate-90"}`;return y!==m.e&&N(g,"aria-expanded",m.e=y),_!==m.t&&B(g,m.t=_),C!==m.a&&N(d,"class",m.a=C),m},{e:void 0,t:void 0,a:void 0}),c})()},wi=e=>{const t=()=>e.node.dependencies??[];return(()=>{var r=bi(),n=r.firstChild,s=n.firstChild,i=s.nextSibling;return r.$$click=()=>He(e.node.token),l(s,()=>er(e.node.kind)),l(i,()=>e.node.token),l(n,o(b,{get when(){return e.node.scope},get children(){var u=vi();return l(u,()=>e.node.scope),u}}),null),l(n,o(b,{get when(){return(e.node.resolveCount??0)>0},get children(){var u=pi(),a=u.firstChild;return l(u,()=>e.node.resolveCount,a),u}}),null),l(r,o(b,{get when(){return t().length>0},get children(){var u=mi();return l(u,o(A,{get each(){return t()},children:a=>(()=>{var c=$i(),g=c.firstChild.nextSibling,d=g.nextSibling;return c.$$click=h=>{h.stopPropagation(),He(a)},l(g,()=>ki(a)),l(d,a),k(()=>B(g,`px-1.5 py-0.5 rounded text-xs font-semibold ${Ci(a)}`)),c})()})),u}}),null),k(()=>B(s,`px-2 py-0.5 rounded text-xs font-semibold ${tr(e.node.kind)}`)),r})()};function er(e){return e==="controller"?"ctrl":e==="service"?"svc":e==="repository"?"repo":"other"}function tr(e){return e==="controller"?"bg-violet-900/50 text-violet-300":e==="service"?"bg-blue-900/50 text-blue-300":e==="repository"?"bg-teal-900/50 text-teal-300":"bg-border-strong/50 text-text-strong"}function Si(e){return e==="Controllers"?"text-violet-400":e==="Services"?"text-blue-400":e==="Repositories"?"text-teal-400":"text-text-secondary"}function ki(e){return er(M.container().find(t=>t.token===e)?.kind)}function Ci(e){return tr(M.container().find(t=>t.token===e)?.kind)}J(["input","click"]);var Ei=v("<div class=overflow-x-auto><table><thead><tr><th style=width:140px>Time</th><th style=width:200px>Type</th><th style=width:120px>Source</th><th>Payload</th></tr></thead><tbody>"),Ti=v('<div class="bg-surface-1 rounded-xl border border-border p-5"><div class="flex flex-col sm:flex-row gap-3 mb-4 items-stretch sm:items-center"><input type=text placeholder="Filter by event type (substring)…"class="flex-1 bg-surface-2 border border-border-strong rounded-lg px-3 py-2 text-sm text-text-body placeholder:text-text-muted focus:outline-none focus:border-kick-500"><div class="flex gap-2"><button type=button></button><button type=button class="px-3 py-1.5 text-xs font-semibold rounded-lg bg-surface-2 text-text-secondary border border-border-strong hover:text-text-body transition-colors">Clear</button></div></div><div class="text-xs text-text-muted mb-3 font-mono">/<!> buffered'),Mi=v("<div class=empty>"),Ai=v('<tr><td class="font-mono text-xs text-text-muted"></td><td class="font-mono text-xs"></td><td class="font-mono text-xs text-text-secondary"></td><td class="font-mono text-xs"><code class="text-text-body break-all">'),Li=()=>{const e=Ge(),[t,r]=x(""),[n,s]=x(!1),[i,u]=x(null),a=()=>{s(d=>{const h=!d;return u(h?e():null),h})},c=j(()=>{const d=i()??e(),h=t().trim().toLowerCase();return[...h?d.filter(f=>f.type.toLowerCase().includes(h)):d].toReversed()}),g=ge(()=>c());return(()=>{var d=Ti(),h=d.firstChild,f=h.firstChild,p=f.nextSibling.firstChild,m=p.nextSibling,y=h.nextSibling,_=y.firstChild,C=_.nextSibling;return C.nextSibling,f.$$input=w=>r(w.currentTarget.value),p.$$click=a,l(p,()=>n()?"▶ Resume":"⏸ Pause"),m.$$click=()=>Xs(),l(y,()=>e().length,_),l(y,500,C),l(y,o(b,{get when(){return n()},children:" · paused"}),null),l(y,o(b,{get when(){return t().trim()},get children(){return[' · filter: "',Re(()=>t().trim()),'"']}}),null),l(d,o(b,{get when(){return g.page().length>0},get fallback(){return(()=>{var w=Mi();return l(w,o(b,{get when(){return e().length===0},fallback:"No events match the current filter",children:"No events yet — emits from kickjs-db, plugins, or the panel itself land here."})),w})()},get children(){return[(()=>{var w=Ei(),E=w.firstChild.firstChild.nextSibling;return l(E,o(A,{get each(){return g.page()},children:S=>(()=>{var T=Ai(),F=T.firstChild,I=F.nextSibling,O=I.nextSibling,R=O.nextSibling.firstChild;return l(F,()=>Zt(S.ts)),l(I,()=>S.type),l(O,()=>S.pluginId??"—"),l(R,()=>ei(S.payload)),T})()})),w})(),o(fe,{pager:g})]}}),null),k(()=>B(p,`px-3 py-1.5 text-xs font-semibold rounded-lg border transition-colors ${n()?"bg-kick-500/20 text-kick-500 border-kick-500/30":"bg-surface-2 text-text-secondary border-border-strong hover:text-text-body"}`)),k(()=>f.value=t()),d})()};J(["input","click"]);var Ri=v("<div style=display:flex;flex-direction:column;height:100%>"),Bi=v('<iframe title="custom devtools tab"sandbox="allow-scripts allow-same-origin allow-forms"style=flex:1;width:100%;border:none;background:var(--bg)>'),Oi=v("<div style=padding:16px><div class=card>"),qi=v("<div style=color:var(--text-dim);font-size:12px>"),ji=v('<div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)"><div><div style=font-weight:600></div></div><button type=button class=tab style="border:1px solid var(--border);border-radius:4px;padding:6px 14px;border-bottom-color:var(--border)">'),Pi=v("<div class=card><div class=card-title>Last response</div><code>"),Ni=v("<div style=padding:16px;flex:1;overflow:auto>"),Ii=e=>(()=>{var t=Ri();return l(t,o(b,{get when(){return e.tab.view.type==="iframe"},get children(){return o(Di,{get view(){return e.tab.view}})}}),null),l(t,o(b,{get when(){return e.tab.view.type==="launch"},get children(){return o(Ui,{get view(){return e.tab.view},get tabId(){return e.tab.id}})}}),null),l(t,o(b,{get when(){return e.tab.view.type==="html"},get children(){return o(zi,{get view(){return e.tab.view}})}}),null),t})(),Di=e=>{const t=()=>{const r=e.view.src,n=(r.startsWith("http")||r.startsWith("//"),r),s=ve();return s?`${n}${n.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:n};return(()=>{var r=Bi();return k(()=>N(r,"src",t())),r})()},Ui=e=>{const[t,r]=x(null),[n,s]=x(null),i=async u=>{r(u),s(null);try{const a=`${ye()}/tabs/${encodeURIComponent(e.tabId)}/actions/${encodeURIComponent(u)}`,c=ve(),g=await fetch(c?`${a}?token=${encodeURIComponent(c)}`:a,{method:"POST",headers:c?{"x-devtools-token":c}:void 0});s(`${g.status} ${g.statusText}`)}catch(a){s(a instanceof Error?a.message:String(a))}finally{r(null)}};return(()=>{var u=Oi(),a=u.firstChild;return l(a,o(A,{get each(){return e.view.actions},children:c=>(()=>{var g=ji(),d=g.firstChild,h=d.firstChild,f=d.nextSibling;return l(h,()=>c.label),l(d,o(b,{get when(){return c.description},get children(){var p=qi();return l(p,()=>c.description),p}}),null),f.$$click=()=>{i(c.id)},l(f,()=>t()===c.id?"Running…":"Run"),k(()=>f.disabled=t()===c.id),g})()})),l(u,o(b,{get when(){return n()},children:c=>(()=>{var g=Pi(),d=g.firstChild.nextSibling;return l(d,c),g})()}),null),u})()},zi=e=>(()=>{var t=Ni();return k(()=>t.innerHTML=e.view.html),t})();J(["click"]);var Ve=!1,Ce=null,Ie=null;async function Fi(){return U.setConnectionStatus("connecting"),await st(),Ie=ht("/stream",e=>{if(!Ve){if(U.setConnectionStatus("live"),rr(),e.type==="metrics"){Hi(e),U.touch();return}if(e.type==="container"){st();return}}},()=>{Ve||(U.setConnectionStatus("polling"),Gi())}),Vi}async function st(){const e=await Promise.allSettled([ee.health(),ee.metrics(),ee.routeRegistry(),ee.container(),ee.queues(),ee.ws()]);if(e.every(a=>a.status==="rejected"&&a.reason instanceof Yt)){U.setAuthRequired(!0),U.setConnectionStatus("disconnected");return}M.authRequired()&&(U.setAuthRequired(!1),U.setAuthError(null));const[t,r,n,s,i,u]=e;t.status==="fulfilled"&&U.setHealth({status:t.value.status,errorRate:t.value.errorRate,uptime:t.value.uptime,adapters:t.value.adapters??{}}),r.status==="fulfilled"&&U.setMetrics({requests:r.value.requests,serverErrors:r.value.serverErrors,clientErrors:r.value.clientErrors,errorRate:r.value.errorRate,uptimeSeconds:r.value.uptimeSeconds,startedAt:r.value.startedAt}),n.status==="fulfilled"&&U.setRoutes(n.value.routes??[]),s.status==="fulfilled"&&U.setContainer(s.value.registrations??[]),i.status==="fulfilled"&&U.setQueues({enabled:i.value.enabled,queues:i.value.queues??[]}),u.status==="fulfilled"&&U.setWs(u.value),U.touch()}function Hi(e){const t=M.metrics();if(!t)return;U.setMetrics({...t,requests:e.requestCount,serverErrors:e.errorCount,clientErrors:e.clientErrorCount,errorRate:e.errorRate,uptimeSeconds:e.uptimeSeconds});const r=M.health();r&&U.setHealth({...r,uptime:e.uptimeSeconds,errorRate:e.errorRate})}function Gi(){Ce||(Ce=setInterval(()=>{Ve||st()},5e3))}function rr(){Ce&&(clearInterval(Ce),Ce=null)}function Vi(){Ve=!0,rr(),Ie&&(Ie(),Ie=null),U.setConnectionStatus("disconnected")}var Ki=v('<div class="fixed inset-0 z-[60] bg-slate-950/90 flex items-center justify-center p-4"><div class="bg-slate-900 border border-slate-700 rounded-2xl p-8 max-w-md w-full shadow-2xl"><div class="text-center mb-6"><h2 class="text-xl font-bold text-kick-500 mb-2">⚡ KickJS DevTools</h2><p class="text-sm text-slate-400">Enter your DevTools token to continue.</p><p class="text-xs text-slate-600 mt-1">The token is printed in the server console on startup, e.g. <code class="font-mono text-slate-500">[token: abc123…]</code></p></div><form><input type=text autofocus placeholder="Paste your token here…"class="w-full bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-sm text-slate-200 placeholder-slate-500 focus:outline-none focus:border-kick-500 font-mono mb-3"><button type=submit class="w-full bg-kick-500 hover:bg-kick-600 text-white font-semibold py-2.5 rounded-lg transition-colors disabled:opacity-50">'),Wi=v('<p class="text-red-400 text-sm mb-3">'),Ji=()=>{const[e,t]=x(""),[r,n]=x(!1),s=async()=>{const i=e().trim();if(!i){U.setAuthError("Token is required");return}n(!0),U.setAuthError(null);try{Jt(i),await ee.health(),U.setAuthRequired(!1),U.setAuthError(null),t("")}catch{U.setAuthError("Invalid token — request was rejected.")}finally{n(!1)}};return o(b,{get when(){return M.authRequired()},get children(){var i=Ki(),u=i.firstChild.firstChild.nextSibling,a=u.firstChild,c=a.nextSibling;return u.addEventListener("submit",g=>{g.preventDefault(),s()}),a.$$input=g=>t(g.currentTarget.value),l(u,o(b,{get when(){return M.authError()},children:g=>(()=>{var d=Wi();return l(d,g),d})()}),c),l(c,()=>r()?"Verifying…":"Authenticate"),k(()=>c.disabled=r()),k(()=>a.value=e()),i}})};J(["input"]);var Qi=v("<div class=dt-nav-sep>"),Yi=v('<div class=card style=border-color:var(--warn);margin-top:16px><div class=card-title style=color:var(--warn)> custom-tab issue(s)</div><ul style="margin:8px 0 0;padding-left:20px;font-family:var(--font-mono);font-size:12px">'),Xi=v("<div class=app><header class=dt-header><div class=dt-header-brand><span class=dt-bolt aria-hidden=true>⚡</span><h1>KickJS DevTools</h1></div><div style=display:flex;align-items:center;gap:12px></div></header><div class=dt-shell><aside class=dt-sidebar role=tablist></aside><div class=dt-resizer role=separator aria-orientation=vertical></div><main class=dt-main role=tabpanel>"),Xe=v("<button type=button role=tab><span class=dt-nav-label>"),Bt=v("<span class=tab-badge>"),Zi=v("<div class=dt-nav-group><button type=button class=dt-nav-group-header><span>▾"),ea=v("<li>: "),ta=v("<div class=dt-conn><span aria-hidden=true></span><span class=dt-conn-label></span><span class=dt-conn-sep>·</span><span class=dt-conn-ts>Updated "),ra=v("<div class=dt-settings-pop role=menu><div class=dt-settings-section><div class=dt-settings-label>Density</div><div class=dt-seg></div><div class=dt-settings-hint>Controls spacing & font scale. Default: Small."),na=v('<div class=dt-settings><button type=button aria-label=Settings aria-haspopup=true title=Settings><svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><circle cx=12 cy=12 r=3></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z">'),la=v("<button type=button>"),sa=v('<svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z">'),ia=v("<button type=button class=dt-theme-toggle>"),aa=v('<svg viewBox="0 0 24 24"fill=none stroke=currentColor stroke-width=2><circle cx=12 cy=12 r=4></circle><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41">');function nr(){return[{id:"overview",label:"Overview"},{id:"runtime",label:"Runtime"},{id:"memory",label:"Memory"},{id:"topology",label:"Topology"},{id:"routes",label:"Routes",count:()=>M.routes().length||void 0},{id:"metrics",label:"Metrics"},{id:"container",label:"Container",count:()=>M.container().length||void 0},{id:"queues",label:"Queues",count:()=>M.queues().queues.length||void 0},{id:"database",label:"Database",count:()=>Ge()().filter(e=>e.type==="db:query"||e.type==="db:query-error").length||void 0},{id:"graph",label:"Graph",count:()=>M.container().length||void 0},{id:"activity",label:"Activity",count:()=>Ge()().length||void 0}]}var oa=new Set(nr().map(e=>e.id)),ca=[{label:null,ids:["overview"]},{label:"Runtime",ids:["runtime","memory","topology","metrics"]},{label:"Architecture",ids:["routes","container","graph"]},{label:"Data & Jobs",ids:["database","queues"]},{label:null,ids:["activity"]}],lr="kickjs-devtools-sidebar-w",sr="kickjs-devtools-sidebar-collapsed",ir=150,ar=360;function ua(){try{const e=Number(localStorage.getItem(lr));if(e>=ir&&e<=ar)return e}catch{}return 200}function da(){try{const e=localStorage.getItem(sr);if(e)return JSON.parse(e)}catch{}return[]}var ha=()=>{const e=(()=>{try{const w=localStorage.getItem("kickjs-devtools-tab");if(w)return w}catch{}return"overview"})(),[t,r]=x(e),[n,s]=x([]),[i,u]=x([]),a=nr(),c=new Map(a.map(w=>[w.id,w])),[g,d]=x(ua()),[h,f]=x(da()),p=w=>{f(E=>{const S=E.includes(w)?E.filter(T=>T!==w):[...E,w];try{localStorage.setItem(sr,JSON.stringify(S))}catch{}return S})};let m=null;ie(()=>m?.());const y=w=>{w.preventDefault();const E=w.clientX,S=g();document.body.style.cursor="col-resize";const T=O=>{const R=Math.min(ar,Math.max(ir,S+(O.clientX-E)));d(R)},F=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",I),document.body.style.cursor="",m=null},I=()=>{F();try{localStorage.setItem(lr,String(g()))}catch{}};m=F,document.addEventListener("mousemove",T),document.addEventListener("mouseup",I)};xe(()=>{ee.tabs().then(({tabs:S,errors:T})=>{s(S.filter(F=>!oa.has(F.id))),u(T)}).catch(()=>{});let w=null;Fi().then(S=>{w=S});const E=Ys();ie(()=>{w?.(),E()}),Rr(),jr()});const _=w=>{r(w);try{localStorage.setItem("kickjs-devtools-tab",w)}catch{}queueMicrotask(()=>{document.querySelector(`[role="tab"][data-tab-id="${w}"]`)?.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"})})},C=()=>n().find(w=>w.id===t());return(()=>{var w=Xi(),E=w.firstChild,S=E.firstChild.nextSibling,T=E.nextSibling.firstChild,F=T.nextSibling,I=F.nextSibling;return l(S,o(ga,{}),null),l(S,o(pa,{}),null),l(S,o(va,{}),null),l(T,o(A,{each:ca,children:O=>o(b,{get when(){return O.label},get fallback(){return o(A,{get each(){return O.ids},children:R=>{const X=c.get(R);return o(b,{when:X,children:z=>(()=>{var V=Xe(),D=V.firstChild;return V.$$click=()=>_(R),N(V,"data-tab-id",R),l(D,()=>z().label),l(V,o(b,{get when(){return z().count?.()},children:H=>(()=>{var K=Bt();return l(K,H),K})()}),null),k(H=>{var K=`dt-nav-item ${t()===R?"active":""}`,Z=t()===R;return K!==H.e&&B(V,H.e=K),Z!==H.t&&N(V,"aria-selected",H.t=Z),H},{e:void 0,t:void 0}),V})()})}})},children:R=>(()=>{var X=Zi(),z=X.firstChild,V=z.firstChild;return z.$$click=()=>p(R()),l(z,R,null),l(X,o(b,{get when(){return!h().includes(R())},get children(){return o(A,{get each(){return O.ids},children:D=>{const H=c.get(D);return o(b,{when:H,children:K=>(()=>{var Z=Xe(),ae=Z.firstChild;return Z.$$click=()=>_(D),N(Z,"data-tab-id",D),l(ae,()=>K().label),l(Z,o(b,{get when(){return K().count?.()},children:ne=>(()=>{var ue=Bt();return l(ue,ne),ue})()}),null),k(ne=>{var ue=`dt-nav-item nested ${t()===D?"active":""}`,_e=t()===D;return ue!==ne.e&&B(Z,ne.e=ue),_e!==ne.t&&N(Z,"aria-selected",ne.t=_e),ne},{e:void 0,t:void 0}),Z})()})}})}}),null),k(D=>{var H=!h().includes(R()),K=`dt-nav-caret ${h().includes(R())?"closed":""}`;return H!==D.e&&N(z,"aria-expanded",D.e=H),K!==D.t&&B(V,D.t=K),D},{e:void 0,t:void 0}),X})()})}),null),l(T,o(b,{get when(){return n().length>0},get children(){return[Qi(),o(A,{get each(){return n()},children:O=>(()=>{var R=Xe(),X=R.firstChild;return R.$$click=()=>_(O.id),l(X,()=>O.title),k(z=>{var V=O.id,D=`dt-nav-item ${t()===O.id?"active":""}`,H=t()===O.id,K=O.title;return V!==z.e&&N(R,"data-tab-id",z.e=V),D!==z.t&&B(R,z.t=D),H!==z.a&&N(R,"aria-selected",z.a=H),K!==z.o&&N(R,"title",z.o=K),z},{e:void 0,t:void 0,a:void 0,o:void 0}),R})()})]}}),null),F.$$mousedown=y,l(I,o(b,{get when(){return t()==="overview"},get children(){return o(Sn,{})}}),null),l(I,o(b,{get when(){return t()==="runtime"},get children(){return o(Nn,{})}}),null),l(I,o(b,{get when(){return t()==="memory"},get children(){return o(el,{})}}),null),l(I,o(b,{get when(){return t()==="topology"},get children(){return o(Ll,{})}}),null),l(I,o(b,{get when(){return t()==="routes"},get children(){return o(Hl,{})}}),null),l(I,o(b,{get when(){return t()==="metrics"},get children(){return o(es,{})}}),null),l(I,o(b,{get when(){return t()==="container"},get children(){return o(As,{})}}),null),l(I,o(b,{get when(){return t()==="queues"},get children(){return o(Vs,{})}}),null),l(I,o(b,{get when(){return t()==="database"},get children(){return o(ci,{})}}),null),l(I,o(b,{get when(){return t()==="graph"},get children(){return o(yi,{})}}),null),l(I,o(b,{get when(){return t()==="activity"},get children(){return o(Li,{})}}),null),l(I,o(b,{get when(){return C()},children:O=>o(Ii,{get tab(){return O()}})}),null),l(I,o(b,{get when(){return Re(()=>i().length>0)()&&t()==="overview"},get children(){var O=Yi(),R=O.firstChild,X=R.firstChild,z=R.nextSibling;return l(R,()=>i().length,X),l(z,o(A,{get each(){return i()},children:V=>(()=>{var D=ea(),H=D.firstChild;return l(D,()=>V.source,H),l(D,()=>V.reason,null),D})()})),O}}),null),l(w,o(ds,{}),null),l(w,o(Ji,{}),null),k(O=>ct(T,`width:${g()}px`,O)),w})()},ga=()=>{const e=r=>r==="live"?"Live":r==="polling"?"Polling":r==="disconnected"?"Disconnected":"Connecting…",t=r=>r?r.toLocaleTimeString():"never";return(()=>{var r=ta(),n=r.firstChild,s=n.nextSibling,i=s.nextSibling.nextSibling;return i.firstChild,l(s,()=>e(M.connectionStatus())),l(i,()=>t(M.lastUpdate()),null),k(()=>B(n,`dt-pulse dt-pulse-${M.connectionStatus()}`)),r})()},fa=[{id:"sm",label:"Small"},{id:"md",label:"Medium"},{id:"lg",label:"Large"}],va=()=>{const[e,t]=x(!1);let r;const n=i=>{e()&&r&&!r.contains(i.target)&&t(!1)},s=i=>{i.key==="Escape"&&t(!1)};return document.addEventListener("click",n),document.addEventListener("keydown",s),ie(()=>{document.removeEventListener("click",n),document.removeEventListener("keydown",s)}),(()=>{var i=na(),u=i.firstChild;return Sr(a=>r=a,i),u.$$click=()=>t(a=>!a),l(i,o(b,{get when(){return e()},get children(){var a=ra(),c=a.firstChild.firstChild.nextSibling;return l(c,o(A,{each:fa,children:g=>(()=>{var d=la();return d.$$click=()=>qr(g.id),l(d,()=>g.label),k(h=>{var f=`dt-seg-item ${yt()===g.id?"active":""}`,p=yt()===g.id;return f!==h.e&&B(d,h.e=f),p!==h.t&&N(d,"aria-pressed",h.t=p),h},{e:void 0,t:void 0}),d})()})),a}}),null),k(a=>{var c=`dt-settings-btn ${e()?"open":""}`,g=e();return c!==a.e&&B(u,a.e=c),g!==a.t&&N(u,"aria-expanded",a.t=g),a},{e:void 0,t:void 0}),i})()},pa=()=>{const e=()=>{const r=Je()==="system"?"light":Je()==="light"?"dark":"system";Lr(r)},t=()=>{const r=Je();return`Theme: ${r==="system"?"follow system":r} (click to cycle)`};return(()=>{var r=ia();return r.$$click=e,l(r,o(b,{get when(){return Ft()==="dark"},get fallback(){return aa()},get children(){return sa()}})),k(n=>{var s=t(),i=t();return s!==n.e&&N(r,"aria-label",n.e=s),i!==n.t&&N(r,"title",n.t=i),n},{e:void 0,t:void 0}),r})()};J(["mousedown","click"]);var or=document.getElementById("root");if(!or)throw new Error("#root not found");wr(()=>o(ha,{}),or);
|