@stacksjs/debugbar 0.75.755 → 0.75.764
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.ts +0 -2
- package/dist/index.js +7 -7
- package/dist/views.d.ts +0 -4
- package/package.json +13 -13
- package/dist/peer.d.ts +0 -23
package/dist/index.d.ts
CHANGED
|
@@ -6,7 +6,6 @@ export type { Collector, CollectorContext, ResponseSnapshot } from './collectors
|
|
|
6
6
|
export type { EndpointContext, SignInAuth } from './endpoints';
|
|
7
7
|
export type { InjectOptions } from './inject';
|
|
8
8
|
export type { DebugbarMiddleware } from './middleware';
|
|
9
|
-
export type { PeerServer, SocketPeer } from './peer';
|
|
10
9
|
export type { BootOptions, DebugbarRuntime } from './runtime';
|
|
11
10
|
export type { EnvironmentInputs } from './state';
|
|
12
11
|
export type { DebugbarStore } from './storage';
|
|
@@ -37,7 +36,6 @@ export { isLocalHostname, isLocalRequest, isLoopbackAddress, isSameOriginRequest
|
|
|
37
36
|
export { DEBUGBAR_ASSET_PATH, DEBUGBAR_ID_HEADER, debugbarScriptTag, extractCspScriptNonce, injectDebugbar, injectDebugbarResponse, isInjectableDocument, withRecordId } from './inject';
|
|
38
37
|
export { createApiDebugbarMiddleware, installApiDebugbar } from './middleware';
|
|
39
38
|
export { isSensitiveName, redact, redactBindings, redactHeaders, redactQuery, redactUrl, REDACTED } from './redact';
|
|
40
|
-
export { capturedSocketPeer, captureSocketPeers, peerAwareServer } from './peer';
|
|
41
39
|
export { bootDebugbar, debugbarEnabled, debugbarRuntime, shutdownDebugbar } from './runtime';
|
|
42
40
|
export { analyzeQueries, normalizeSql } from './sql';
|
|
43
41
|
export { isDebugbarEnabled, isProductionEnvironment, resolveDebugbarConfig } from './state';
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{AsyncLocalStorage as xr}from"async_hooks";var kr=Symbol.for("stacks.debugbar.collection"),Y=globalThis[kr]??=new xr,Rr=1000,be=0;function at(e=Date.now()){be=(be+1)%1296;let t=crypto.getRandomValues(new Uint32Array(2));return e.toString(36).padStart(9,"0")+be.toString(36).padStart(2,"0")+t[0].toString(36).padStart(7,"0").slice(-7)+t[1].toString(36).padStart(7,"0").slice(-6)}var Cr=/^[0-9a-z]{20,32}$/;function I(e){return typeof e==="string"&&Cr.test(e)}class ee{id;process;request;url;config;startedAt;startedMs;kind;finished=!1;duration;bags=new Map;overflow=new Map;values=new Map;constructor(e,t,r){this.id=at(),this.process=t,this.request=e,this.url=new URL(e.url),this.config=r,this.startedAt=Date.now(),this.startedMs=performance.now(),this.kind=t==="api"?"api":"page"}elapsed(){return this.duration??performance.now()-this.startedMs}push(e,t,r=Rr){if(this.finished)return;let n=this.bags.get(e);if(!n)n=[],this.bags.set(e,n);if(n.length>=r){this.overflow.set(e,(this.overflow.get(e)??0)+1);return}n.push(t)}list(e){return this.bags.get(e)??[]}dropped(e){return this.overflow.get(e)??0}set(e,t){if(!this.finished)this.values.set(e,t)}get(e){return this.values.get(e)}}function x(){let e=Y.getStore();return e&&!e.finished?e:void 0}function he(e,t){return Y.run(e,t)}function ut(e){Y.enterWith(e)}function R(e){return Y.run(void 0,e)}var Sr="[redacted]",Er=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-csrf-token","x-xsrf-token","x-api-key","x-auth-token","x-debugbar-token"]),vr=new Set(["password","passwd","passphrase","pwd","secret","secrets","token","tokens","key","keys","apikey","authorization","auth","credential","credentials","signature","cookie","cookies","session","csrf","xsrf","dsn","otp","pin","cvv","cvc","ssn"]),ye=new Map;function _(e){let t=ye.get(e);if(t!==void 0)return t;let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((o)=>vr.has(o))||/password|secret|token|apikey/i.test(e);if(ye.size<2000)ye.set(e,n);return n}function te(e){if(e.length<20)return!1;if(/^\$(?:2[aby]|argon2(?:id|i|d)|scrypt|pbkdf2)[$-]/.test(e))return!0;if(/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*$/.test(e))return!0;if(/^(?:sk|pk|rk|whsec|ghp|gho|xox[abp])[-_][\w-]{16,}$/.test(e))return!0;return e.length>=40&&/^[a-f0-9]+$/i.test(e)}function re(e){let t={};if(!e)return t;return e.forEach((r,n)=>{let o=n.toLowerCase();t[o]=Er.has(o)||_(o)?"[redacted]":U(r,2000)}),t}function lt(e){if(!e)return[];let t=[];for(let r of e.split(";")){let n=r.split("=",1)[0]?.trim();if(n)t.push(n)}return t}function we(e){let t={};for(let r of new Set(e.keys())){let n=_(r)?["[redacted]"]:e.getAll(r).map((o)=>te(o)?"[redacted]":U(o,500));t[r]=n.length===1?n[0]:n}return t}function q(e){if(!e.search)return e.pathname;let t=[];for(let[r,n]of e.searchParams){let o=_(r)||te(n)?"[redacted]":n;t.push(`${encodeURIComponent(r)}=${o==="[redacted]"?"[redacted]":encodeURIComponent(o)}`)}return`${e.pathname}?${t.join("&")}`}function U(e,t){return e.length>t?`${e.slice(0,t)}... (${e.length} chars)`:e}function m(e,t={}){let r={maxDepth:t.maxDepth??6,maxKeys:t.maxKeys??60,maxItems:t.maxItems??60,maxString:t.maxString??2000};return D(e,r,0,new WeakSet)}function D(e,t,r,n){if(e===null||e===void 0)return e??null;switch(typeof e){case"string":return te(e)?"[redacted]":U(e,t.maxString);case"number":return Number.isFinite(e)?e:String(e);case"boolean":return e;case"bigint":return`${e}n`;case"symbol":return e.toString();case"function":return`[function ${e.name||"anonymous"}]`}let o=e;if(n.has(o))return"[circular]";if(r>=t.maxDepth)return Array.isArray(o)?`[array(${o.length})]`:"[object]";if(o instanceof Date)return Number.isNaN(o.getTime())?"Invalid Date":o.toISOString();if(o instanceof Error)return{name:o.name,message:U(o.message,t.maxString)};if(o instanceof URL)return q(o);if(typeof Request<"u"&&o instanceof Request)return`[Request ${o.method} ${Dr(o.url)}]`;if(typeof Response<"u"&&o instanceof Response)return`[Response ${o.status}]`;if(ArrayBuffer.isView(o)||o instanceof ArrayBuffer)return`[binary ${o.byteLength} bytes]`;n.add(o);try{if(Array.isArray(o)){let u=o.slice(0,t.maxItems).map((c)=>D(c,t,r+1,n));if(o.length>t.maxItems)u.push(`... ${o.length-t.maxItems} more`);return u}if(o instanceof Map)return D(Object.fromEntries([...o.entries()].slice(0,t.maxKeys).map(([u,c])=>[String(u),c])),t,r,n);if(o instanceof Set)return D([...o],t,r,n);let s=typeof o.toJSON==="function"?ct(()=>o.toJSON()):o;if(s===null||typeof s!=="object")return D(s,t,r+1,n);if(s!==o&&Array.isArray(s))return D(s,t,r,n);let i={},a=0;for(let u of Object.keys(s)){if(a++>=t.maxKeys){i["..."]=`${Object.keys(s).length-t.maxKeys} more keys`;break}i[u]=_(u)?"[redacted]":D(ct(()=>s[u]),t,r+1,n)}return i}finally{n.delete(o)}}function ct(e){try{return e()}catch{return"[unreadable]"}}function Dr(e){try{return new URL(e).pathname}catch{return""}}function xe(e){if(!e)return[];return e.slice(0,100).map((t)=>{if(typeof t==="string")return te(t)?"[redacted]":U(t,500);if(t===null||typeof t==="number"||typeof t==="boolean")return t;if(typeof t==="bigint")return`${t}n`;if(t instanceof Date)return Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)return`[binary ${t.byteLength} bytes]`;return m(t,{maxDepth:3,maxString:500})})}function Ar(e){if(typeof e==="string")return e;if(e instanceof Error)return`${e.name}: ${e.message}`;try{return JSON.stringify(m(e))??String(e)}catch{return String(e)}}function A(e,t,r="info",n){let o=x();if(!o)return;o.push("messages",{level:r,label:t,message:Ar(e).slice(0,4000),context:n===void 0?void 0:m(n),at:o.elapsed()})}function ke(e,t){A(e,void 0,"debug",t)}function Re(e,t){A(e,void 0,"info",t)}function Ce(e,t){A(e,void 0,"warning",t)}function Se(e,t){A(e,void 0,"error",t)}function Ee(e,t){let r=x();if(!r)return;let n=r.get("measures:open");if(!n)n=new Map,r.set("measures:open",n);n.set(e,{label:t??e,start:r.elapsed()})}function ve(e){let t=x(),r=t?.get("measures:open"),n=r?.get(e);if(!t||!r||!n)return;r.delete(e),t.push("measures",{label:n.label,start:n.start,duration:t.elapsed()-n.start,group:"measure"})}function De(e,t,r,n="measure"){x()?.push("measures",{label:e,start:t,duration:r,group:n})}function Ae(e,t){let r=x();if(!r)return t();let n=r.elapsed(),o=()=>{r.push("measures",{label:e,start:n,duration:r.elapsed()-n,group:"measure"})},s;try{s=t()}catch(i){throw o(),i}if(s instanceof Promise)return s.finally(o);return o(),s}var C=new Map,ne=new Map,S;function dt(e,t){if(!e.install)return;try{let r=e.install(t),n=(o)=>{if(typeof o!=="function")return;if(S!==t||C.get(e.name)!==e)o();else ne.set(e.name,o)};if(r instanceof Promise)r.then(n,()=>{});else n(r)}catch{}}function Pe(e){let t=ne.get(e);ne.delete(e);try{t?.()}catch{}}function Q(e){if(!e||typeof e.name!=="string"||!/^[\w-]{1,40}$/.test(e.name))throw TypeError("A debugbar collector needs a name of letters, digits, dashes or underscores.");if(Pe(e.name),C.set(e.name,e),S)dt(e,S);return()=>{if(C.get(e.name)!==e)return;Pe(e.name),C.delete(e.name)}}function Me(){return[...C.values()]}function ft(e,t){if(S)return;S={config:e,process:t,current:x};for(let r of C.values())dt(r,S)}function pt(){S=void 0;for(let e of[...ne.keys()])Pe(e)}function mt(e){if(!S)return;for(let t of C.values()){if(!t.begin)continue;try{t.begin(e)}catch{}}}async function gt(e,t){let r={},n={};for(let o of C.values()){if(!o.collect)continue;try{let s=await o.collect(e,t);if(s===void 0||s===null)continue;if(r[o.name]=s,o.label)n[o.name]=o.label}catch(s){r[o.name]={error:s instanceof Error?s.message:String(s)}}}return{sections:r,labels:n}}import{randomBytes as nr}from"crypto";import{chmodSync as Sn,existsSync as En,readFileSync as vn,writeFileSync as Dn}from"fs";import{join as or}from"path";import An from"process";import{config as Ke}from"@stacksjs/config";import{projectPath as Pn,storagePath as Mn}from"@stacksjs/path";var H=new Map,Pr=3000;function oe(e){if(!e||typeof e!=="object")return null;let t=(i)=>{try{return e[i]}catch{return}},r=t("id");if(typeof r!=="number"&&typeof r!=="string")return null;let n=(i)=>{let a=t(i);return typeof a==="string"&&a.trim()?a.trim():void 0},o=n("email"),s=n("name")??([n("first_name")??n("firstName"),n("last_name")??n("lastName")].filter(Boolean).join(" ")||void 0)??n("username")??o??`User #${r}`;return{id:r,name:s,...o&&{email:o}}}function Mr(e,t){let r=e.headers.get("authorization");if(r&&/^bearer\s+\S/i.test(r))return{token:r.replace(/^bearer\s+/i,"").trim(),via:"bearer"};let n=t?.(e);return n?{token:n,via:"cookie"}:void 0}async function se(e){try{let t=await import("@stacksjs/auth"),r=Mr(e,t.authCookieToken);if(!r)return{user:null,via:"none"};let n=H.get(r.token);if(n&&Date.now()-n.at<Pr)return{user:n.user,via:r.via};let o=await R(()=>t.Auth.getUserFromToken(r.token)),s=oe(o);if(H.size>100)H.clear();return H.set(r.token,{user:s,at:Date.now()}),{user:s,via:r.via}}catch{return{user:null,via:"none"}}}function Te(){H.clear()}var bt={name:"auth",label:"Auth",async collect(e){let{user:t,via:r}=await se(e.request);return{authenticated:t!==null,guard:r==="none"?"guest":r==="bearer"?"token":"cookie",user:t}}};import{subscribe as Tr,unsubscribe as jr}from"diagnostics_channel";var ht="stacks:cache:operation",yt={name:"cache",label:"Cache",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||typeof o?.key!=="string")return;n.push("cache",{type:o.type,key:o.key.slice(0,500),ttl:o.ttl,duration:o.durationMs,at:n.elapsed()})};return Tr(ht,t),()=>{jr(ht,t)}},collect(e){let t=e.list("cache");if(t.length===0)return;let r=(n)=>t.filter((o)=>o.type===n).length;return{hits:r("hit"),misses:r("miss"),writes:r("write"),forgets:r("forget"),operations:t}}};import{existsSync as ie,readFileSync as W,statSync as Lr}from"fs";import{join as z,resolve as Rt}from"path";import ae from"process";import{config as Ct}from"@stacksjs/config";var wt={name:"@stacksjs/debugbar",type:"module",sideEffects:!1,version:"0.75.755",description:"The Stacks debugbar: a request inspector for development.",author:"Chris Breuer",contributors:["Chris Breuer <chris@stacksjs.com>"],license:"MIT",funding:"https://github.com/sponsors/chrisbbreuer",homepage:"https://github.com/stacksjs/stacks/tree/main/storage/framework/core/debugbar#readme",repository:{type:"git",url:"git+https://github.com/stacksjs/stacks.git",directory:"./storage/framework/core/debugbar"},bugs:{url:"https://github.com/stacksjs/stacks/issues"},keywords:["debugbar","debug","profiler","queries","stacks"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js",default:"./dist/index.js"},"./*":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"},"./*.js":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"}},module:"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],scripts:{build:"bun build.ts",typecheck:"bun tsc --noEmit",prepublishOnly:"bun run build"},devDependencies:{"better-dx":"^0.2.41"},dependencies:{"@stacksjs/auth":"workspace:*","@stacksjs/config":"workspace:*","@stacksjs/database":"workspace:*","@stacksjs/error-handling":"workspace:*","@stacksjs/events":"workspace:*","@stacksjs/logging":"workspace:*","@stacksjs/path":"workspace:*","@stacksjs/query-builder":"workspace:*","@stacksjs/queue":"workspace:*","@stacksjs/router":"workspace:*","@stacksjs/types":"workspace:*"}};import qe from"process";var je=new Set(["production","prod","live"]),qr=new Set(["local","development","dev"]);function P(e){return typeof e==="string"?e.trim().toLowerCase():""}function xt(e={}){let t=e.env??qe.env,r=P(t.APP_ENV);if(je.has(r)||je.has(P(e.appEnv)))return!0;return!r&&je.has(P(t.NODE_ENV))}function Oe(e={}){let t=e.env??qe.env;return P(t.APP_ENV)||P(e.appEnv)||P(t.NODE_ENV)}function Or(e){let t=P((e.env??qe.env).APP_DEBUG);return t==="false"||t==="0"||t==="off"||t==="no"}function $e(e,t={}){if(xt(t))return!1;if(e?.enabled===!1)return!1;if(e?.enabled===!0)return!0;return qr.has(Oe(t))&&!Or(t)}function Ne(e,t){let r=e?.queries??{};return{...e,storage:{path:e?.storage?.path||t,maxRequests:Ie(e?.storage?.maxRequests,200)},except:Array.isArray(e?.except)?e.except.filter((n)=>typeof n==="string"):[],queries:{slowThresholdMs:$r(r.slowThresholdMs,100),nPlusOneThreshold:Math.max(2,Ie(r.nPlusOneThreshold,5)),backtrace:r.backtrace!==!1,maxQueries:Ie(r.maxQueries,500)}}}function Ie(e,t){let r=Number(e);return Number.isFinite(r)&&r>=1?Math.floor(r):t}function $r(e,t){let r=Number(e);return Number.isFinite(r)&&r>=0?r:t}var Nr=/^\/(?:__debugbar|_stx|__deps|__hmr|__stx|@|node_modules)(?:\/|$)|^\/favicon\.|\.(?:js|mjs|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|eot|mp4|webm|mp3|wasm|txt|xml|webmanifest)$/i;function kt(e,t){if(Nr.test(e))return!0;for(let r of t)if(r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r)return!0;return!1}function Br(e){try{let t=z(e,".git");if(!ie(t))return{};if(Lr(t).isFile()){let u=/^gitdir:\s*(.+)$/m.exec(W(t,"utf8"));if(!u)return{};t=Rt(e,u[1].trim())}let r=W(z(t,"HEAD"),"utf8").trim(),n=/^ref:\s*(.+)$/.exec(r);if(!n)return{sha:r.slice(0,12)};let o=n[1].replace(/^refs\/heads\//,""),s=z(t,"commondir"),i=ie(s)?Rt(t,W(s,"utf8").trim()):t;for(let u of[t,i]){let c=z(u,n[1]);if(ie(c))return{branch:o,sha:W(c,"utf8").trim().slice(0,12)}}let a=z(i,"packed-refs");if(ie(a)){let u=W(a,"utf8").split(`
|
|
3
|
-
`).find((c)=>c.endsWith(` ${n[1]}`));if(u)return{branch:o,sha:u.slice(0,12)}}return{branch:o}}catch{return{}}}var V;function
|
|
4
|
-
`)){let o=
|
|
5
|
-
`)){let n=
|
|
6
|
-
`);if(t<1||t>o.length)return;let s=Math.max(1,t-r),i=Math.min(o.length,t+r);return{file:Le(n),line:t,start:s,lines:o.slice(s-1,i).map((a)=>a.length>400?`${a.slice(0,400)}...`:a)}}catch{return}}var jt=new WeakMap;function Be(e,t,r){let n=t instanceof Error?t:Error(typeof t==="string"?t:"Non-error value thrown"),o=jt.get(e);if(!o)o=new WeakSet,jt.set(e,o);if(o.has(n))return;o.add(n),e.push("exceptions",{name:n.name||"Error",message:String(n.message??"").slice(0,4000),at:e.elapsed(),frames:Mt(n.stack),context:r===void 0?void 0:m(r,{maxDepth:4})},50)}var It={name:"exceptions",label:"Exceptions",async install({current:e}){let{registerErrorReporter:t}=await import("@stacksjs/error-handling");return t({name:"debugbar",report({error:r,context:n}){let o=e();if(o)Be(o,r,n)}})},async collect(e){let t=e.list("exceptions");if(t.length===0)return;for(let r of t){let n=r.frames.find((o)=>o.app&&o.line);if(n)r.excerpt=await Tt(n.file,n.line)}return t}};var qt={name:"jobs",label:"Jobs",async install({current:e}){let{onQueueEvent:t}=await import("@stacksjs/queue");return t("*",(r,n)=>{let o=e();if(!o||!r.startsWith("job:")&&!r.startsWith("batch:"))return;o.push("jobs",{event:r,name:n?.jobName??n?.jobId??"unknown",queue:n?.queueName??"default",at:o.elapsed(),payload:n?.data===void 0?void 0:m(n.data,{maxDepth:4,maxKeys:30}),error:n?.error?String(n.error.message??n.error):void 0},200)})},collect(e){let t=e.list("jobs");return t.length>0?t:void 0}};var Vr=/\u001B\[[0-9;]*[A-Za-z]/g,Ot={name:"logs",label:"Logs",async install({current:e}){let{registerTransport:t}=await import("@stacksjs/logging");return t({name:"debugbar",log(r){let n=e();if(!n)return;n.push("logs",{level:r.level,message:String(r.message??"").replace(Vr,"").slice(0,4000),at:n.elapsed(),context:r.args.length>1?m(r.args.slice(1),{maxDepth:4}):void 0})}})},collect(e){let t=e.list("logs");return t.length>0?t:void 0}};import{subscribe as Fr,unsubscribe as Kr}from"diagnostics_channel";var $t="stacks:mail:sent";function Nt(e){return(Array.isArray(e)?e:e?[e]:[]).map((r)=>typeof r==="string"?r:r?.address??"").filter(Boolean).slice(0,50)}var Lt={name:"mail",label:"Mail",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||!o?.message)return;n.push("mail",{to:Nt(o.message.to),from:Nt(o.message.from)[0],subject:String(o.message.subject??"").slice(0,500),driver:String(o.driver??""),success:o.result?.success===!0,message:typeof o.result?.message==="string"?o.result.message.slice(0,500):void 0,duration:Number(o.durationMs)||0,at:n.elapsed()},200)};return Fr($t,t),()=>{Kr($t,t)}},collect(e){let t=e.list("mail");return t.length>0?t:void 0}};var Bt={name:"messages",label:"Messages",collect(e){let t=e.list("messages");return t.length>0?t:void 0}};function Gr({current:e}){return(t)=>{let r=e();if(!r||typeof t?.model!=="string"||!t.model)return;let n=r.get("models:counts");if(!n)n=new Map,r.set("models:counts",n);let o=n.get(t.model);if(o){if(o.count++,!o.table&&t.table)o.table=t.table}else n.set(t.model,{model:t.model,...t.table?{table:t.table}:{},count:1})}}var Ut={name:"models",label:"Models",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=Gr(e);return t({onModelHydrate:r})},collect(e){let t=e.get("models:counts");if(!t||t.size===0)return;let r=[...t.values()].sort((o,s)=>s.count-o.count||o.model.localeCompare(s.model));return{total:r.reduce((o,s)=>o+s.count,0),models:r}}};function _t(e){return e.replace(/'(?:[^']|'')*'/g,"?").replace(/\$\d+/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/\bIN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toLowerCase()}function Jr(e){return e.startsWith("select")||e.startsWith("with")}function Ue(e){return/^\s*(?:explain\b|pragma\b)/i.test(e)||/\b(?:from|into|update|join)\s+[`"']?query_logs\b/i.test(e)}function _e(e,t){let r=new Map,n=new Map,o=[];for(let l of e){let p=_t(l.sql),h=`${l.sql}\x00${Xr(l.params)}`;o.push({exact:h,shape:p}),r.set(h,(r.get(h)??0)+1);let b=n.get(p);if(b)b.count++;else n.set(p,{count:1,sample:l.sql,source:l.source})}let s=0,i=0,a=0,u=0;e.forEach((l,p)=>{let{exact:h,shape:b}=o[p],d=r.get(h)??1,f=n.get(b)?.count??1;if(s+=l.duration,d>1)l.duplicates=d;if(f>1)l.similar=f;if(l.duration>=t.slowThresholdMs)l.slow=!0,a++;if(l.error)u++});for(let l of r.values())i+=l-1;let c=[...n.entries()].filter(([l,p])=>p.count>=t.nPlusOneThreshold&&Jr(l)).map(([l,p])=>({shape:l,count:p.count,sample:p.sample,source:p.source})).sort((l,p)=>p.count-l.count);return{count:e.length+(t.dropped??0),duration:s,dropped:t.dropped??0,duplicates:i,slow:a,failed:u,slowThresholdMs:t.slowThresholdMs,nPlusOne:c,statements:e}}function Xr(e){try{return JSON.stringify(e)??""}catch{return""}}function Zr(e,t){let r=e.get("queries:pending");if(!r)r=[],e.set("queries:pending",r);if(r.length<200)r.push({sql:t,source:ce()})}function Yr(e,t){let r=e.get("queries:pending");if(!r)return;for(let n=r.length-1;n>=0;n--)if(r[n].sql===t)return r.splice(n,1)[0].source;return}function en({current:e,config:t}){let r=t.queries.maxQueries,n=(o,s,i)=>{let a=e();if(!a||typeof o?.sql!=="string"||Ue(o.sql))return;let u=typeof o.durationMs==="number"?o.durationMs:0;a.push("queries",{sql:o.sql.length>8000?`${o.sql.slice(0,8000)} ...`:o.sql,params:xe(o.params),start:Math.max(0,a.elapsed()-u),duration:u,rows:typeof o.rowCount==="number"?o.rowCount:void 0,kind:o.kind,source:i?i():Yr(a,o.sql),error:s?o.error instanceof Error?o.error.message:String(o.error??"failed"):void 0},r)};return{...t.queries.backtrace&&{onQueryStart(o){let s=e();if(s&&typeof o?.sql==="string"&&!Ue(o.sql))Zr(s,o.sql)}},onQueryEnd(o){n(o,!1)},onQueryError(o){n(o,!0)},onModelQuery(o){n(o,o.error!==void 0,t.queries.backtrace?ce:void 0)}}}var Qt={name:"queries",label:"Queries",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=en(e);return t({...r.onQueryStart?{onQueryStart:r.onQueryStart}:{},onQueryEnd:r.onQueryEnd,onQueryError:r.onQueryError})},collect(e){return _e(e.list("queries"),{slowThresholdMs:e.config.queries.slowThresholdMs,nPlusOneThreshold:e.config.queries.nPlusOneThreshold,dropped:e.dropped("queries")})}};function tn(e){let t=e,r=t.jsonBody??t.formBody;return r&&typeof r==="object"?m(r,{maxDepth:5}):void 0}var Ht={name:"request",label:"Request",collect(e,t){let{request:r,url:n}=e,o=t.headers.get("content-length");return{method:r.method,url:q(n),path:n.pathname,host:n.host,query:we(n.searchParams),headers:re(r.headers),cookies:lt(r.headers.get("cookie")),contentType:r.headers.get("content-type")??void 0,input:tn(r),response:{status:t.status,headers:re(t.headers),contentType:t.headers.get("content-type")??void 0,size:o&&/^\d+$/.test(o)?Number(o):void 0}}}};import{subscribe as rn,unsubscribe as nn}from"diagnostics_channel";var Wt="stacks:router:route-matched",zt={name:"route",label:"Route",install({current:e}){let t=(r)=>{let n=r;e()?.set("route",{method:n.method,path:n.path,handler:n.handler,middleware:Array.isArray(n.middleware)?n.middleware:[]})};return rn(Wt,t),()=>{nn(Wt,t)}},collect(e){return e.get("route")}};import on from"process";function sn(e){if(!e)return[];let t=[];for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=o.map((a)=>a.trim()).find((a)=>a.startsWith("dur=")),i=s?Number(s.slice(4)):Number.NaN;if(n&&Number.isFinite(i))t.push({name:n.trim(),duration:i})}return t}var Vt={name:"timeline",label:"Timeline",collect(e,t){let r=e.elapsed(),n=[],o=sn(t.headers.get("server-timing")),s=o.find((u)=>u.name==="total"),i=s?Math.max(0,r-s.duration):0;for(let u of o){if(!u.name.startsWith("mw_"))continue;n.push({label:u.name.slice(3),start:i,duration:u.duration,group:"middleware"}),i+=u.duration}if(s&&n.length>0)n.push({label:"handler",start:i,duration:Math.max(0,r-i),group:"handler"});if(e.process==="views")n.push({label:t.kind==="fragment"?"render fragment":"render page",start:0,duration:r,group:"render"});n.push(...e.list("measures")),n.sort((u,c)=>u.start-c.start);let a=on.memoryUsage();return{duration:r,measures:n,memory:{rss:a.rss,heapUsed:a.heapUsed}}}};import{existsSync as an}from"fs";import{join as Ft}from"path";import un from"process";var O=new Map,Kt;function Gt(e){Kt=e,O.clear()}function cn(e){if(O.has(e))return O.get(e);let t=Kt??Ft(un.cwd(),"resources/views"),r=e.replace(/\/+$/,"").replace(/^\/+/,""),n=r?[`${r}.stx`,`${r}/index.stx`]:["index.stx"],o;if(!r.split("/").includes("..")){for(let s of n)if(an(Ft(t,s))){o=`resources/views/${s}`;break}}if(O.size>500)O.clear();return O.set(e,o),o}var Jt={name:"views",label:"Views",collect(e,t){if(e.process!=="views")return;return{template:cn(e.url.pathname),layout:t.headers.get("x-stx-layout")??void 0,fragment:t.kind==="fragment",renderMs:e.elapsed()}}};var Qe={messages:Bt,timeline:Vt,queries:Qt,models:Ut,exceptions:It,logs:Ot,views:Jt,route:zt,events:Et,cache:yt,mail:Lt,jobs:qt,auth:bt,request:Ht,environment:St};function Xt(e){return Object.keys(Qe).filter((t)=>e.collectors?.[t]!==!1).map((t)=>Qe[t])}var ln=Object.keys(Qe);import{AsyncLocalStorage as dn}from"async_hooks";var fn=Symbol.for("stacks.debugbar.socketPeer"),Yt=globalThis[fn]??=new dn,le=!1,He;function er(){return Yt.getStore()??null}function We(){if(le||typeof Bun>"u"||typeof Bun.serve!=="function")return;le=!0;let e=Bun.serve,t=()=>{if(Bun.serve===r)Bun.serve=e;le=!1,He=void 0};He=t;let r=function(o,...s){let i=o?.fetch;if(typeof i!=="function")return Reflect.apply(e,Bun,[o,...s]);let a=Reflect.apply(e,Bun,[{...o,fetch(u,c,...l){let p=null;try{p=c?.requestIP?.(u)??null}catch{}return Yt.run(p,()=>Reflect.apply(i,this,[u,c,...l]))}},...s]);return t(),a};try{Bun.serve=r}catch{le=!1}}function tr(){He?.()}var Zt=new WeakMap;function ze(e){let t=e,r=t&&typeof t==="object"?Zt.get(t):void 0;if(r)return r;let n={requestIP(o){let s=null;try{s=t?.requestIP?.(o)??null}catch{}return s??er()}};if(t&&typeof t==="object")Zt.set(t,n);return n}import{existsSync as pn,mkdirSync as mn,writeFileSync as gn}from"fs";import{mkdir as bn,readdir as hn,readFile as yn,rename as wn,rm as xn,unlink as kn,writeFile as rr}from"fs/promises";import{join as N}from"path";import Rn from"process";function Ve(e){try{mn(e,{recursive:!0});let t=N(e,".gitignore");if(!pn(t))gn(t,`*
|
|
2
|
+
import{AsyncLocalStorage as fr}from"async_hooks";var pr=Symbol.for("stacks.debugbar.collection"),Y=globalThis[pr]??=new fr,mr=1000,ge=0;function nt(e=Date.now()){ge=(ge+1)%1296;let t=crypto.getRandomValues(new Uint32Array(2));return e.toString(36).padStart(9,"0")+ge.toString(36).padStart(2,"0")+t[0].toString(36).padStart(7,"0").slice(-7)+t[1].toString(36).padStart(7,"0").slice(-6)}var gr=/^[0-9a-z]{20,32}$/;function I(e){return typeof e==="string"&&gr.test(e)}class ee{id;process;request;url;config;startedAt;startedMs;kind;finished=!1;duration;bags=new Map;overflow=new Map;values=new Map;constructor(e,t,r){this.id=nt(),this.process=t,this.request=e,this.url=new URL(e.url),this.config=r,this.startedAt=Date.now(),this.startedMs=performance.now(),this.kind=t==="api"?"api":"page"}elapsed(){return this.duration??performance.now()-this.startedMs}push(e,t,r=mr){if(this.finished)return;let n=this.bags.get(e);if(!n)n=[],this.bags.set(e,n);if(n.length>=r){this.overflow.set(e,(this.overflow.get(e)??0)+1);return}n.push(t)}list(e){return this.bags.get(e)??[]}dropped(e){return this.overflow.get(e)??0}set(e,t){if(!this.finished)this.values.set(e,t)}get(e){return this.values.get(e)}}function x(){let e=Y.getStore();return e&&!e.finished?e:void 0}function be(e,t){return Y.run(e,t)}function ot(e){Y.enterWith(e)}function R(e){return Y.run(void 0,e)}var br="[redacted]",hr=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-csrf-token","x-xsrf-token","x-api-key","x-auth-token","x-debugbar-token"]),yr=new Set(["password","passwd","passphrase","pwd","secret","secrets","token","tokens","key","keys","apikey","authorization","auth","credential","credentials","signature","cookie","cookies","session","csrf","xsrf","dsn","otp","pin","cvv","cvc","ssn"]),he=new Map;function _(e){let t=he.get(e);if(t!==void 0)return t;let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((o)=>yr.has(o))||/password|secret|token|apikey/i.test(e);if(he.size<2000)he.set(e,n);return n}function te(e){if(e.length<20)return!1;if(/^\$(?:2[aby]|argon2(?:id|i|d)|scrypt|pbkdf2)[$-]/.test(e))return!0;if(/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*$/.test(e))return!0;if(/^(?:sk|pk|rk|whsec|ghp|gho|xox[abp])[-_][\w-]{16,}$/.test(e))return!0;return e.length>=40&&/^[a-f0-9]+$/i.test(e)}function re(e){let t={};if(!e)return t;return e.forEach((r,n)=>{let o=n.toLowerCase();t[o]=hr.has(o)||_(o)?"[redacted]":B(r,2000)}),t}function it(e){if(!e)return[];let t=[];for(let r of e.split(";")){let n=r.split("=",1)[0]?.trim();if(n)t.push(n)}return t}function ye(e){let t={};for(let r of new Set(e.keys())){let n=_(r)?["[redacted]"]:e.getAll(r).map((o)=>te(o)?"[redacted]":B(o,500));t[r]=n.length===1?n[0]:n}return t}function q(e){if(!e.search)return e.pathname;let t=[];for(let[r,n]of e.searchParams){let o=_(r)||te(n)?"[redacted]":n;t.push(`${encodeURIComponent(r)}=${o==="[redacted]"?"[redacted]":encodeURIComponent(o)}`)}return`${e.pathname}?${t.join("&")}`}function B(e,t){return e.length>t?`${e.slice(0,t)}... (${e.length} chars)`:e}function m(e,t={}){let r={maxDepth:t.maxDepth??6,maxKeys:t.maxKeys??60,maxItems:t.maxItems??60,maxString:t.maxString??2000};return v(e,r,0,new WeakSet)}function v(e,t,r,n){if(e===null||e===void 0)return e??null;switch(typeof e){case"string":return te(e)?"[redacted]":B(e,t.maxString);case"number":return Number.isFinite(e)?e:String(e);case"boolean":return e;case"bigint":return`${e}n`;case"symbol":return e.toString();case"function":return`[function ${e.name||"anonymous"}]`}let o=e;if(n.has(o))return"[circular]";if(r>=t.maxDepth)return Array.isArray(o)?`[array(${o.length})]`:"[object]";if(o instanceof Date)return Number.isNaN(o.getTime())?"Invalid Date":o.toISOString();if(o instanceof Error)return{name:o.name,message:B(o.message,t.maxString)};if(o instanceof URL)return q(o);if(typeof Request<"u"&&o instanceof Request)return`[Request ${o.method} ${wr(o.url)}]`;if(typeof Response<"u"&&o instanceof Response)return`[Response ${o.status}]`;if(ArrayBuffer.isView(o)||o instanceof ArrayBuffer)return`[binary ${o.byteLength} bytes]`;n.add(o);try{if(Array.isArray(o)){let u=o.slice(0,t.maxItems).map((c)=>v(c,t,r+1,n));if(o.length>t.maxItems)u.push(`... ${o.length-t.maxItems} more`);return u}if(o instanceof Map)return v(Object.fromEntries([...o.entries()].slice(0,t.maxKeys).map(([u,c])=>[String(u),c])),t,r,n);if(o instanceof Set)return v([...o],t,r,n);let s=typeof o.toJSON==="function"?st(()=>o.toJSON()):o;if(s===null||typeof s!=="object")return v(s,t,r+1,n);if(s!==o&&Array.isArray(s))return v(s,t,r,n);let i={},a=0;for(let u of Object.keys(s)){if(a++>=t.maxKeys){i["..."]=`${Object.keys(s).length-t.maxKeys} more keys`;break}i[u]=_(u)?"[redacted]":v(st(()=>s[u]),t,r+1,n)}return i}finally{n.delete(o)}}function st(e){try{return e()}catch{return"[unreadable]"}}function wr(e){try{return new URL(e).pathname}catch{return""}}function we(e){if(!e)return[];return e.slice(0,100).map((t)=>{if(typeof t==="string")return te(t)?"[redacted]":B(t,500);if(t===null||typeof t==="number"||typeof t==="boolean")return t;if(typeof t==="bigint")return`${t}n`;if(t instanceof Date)return Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)return`[binary ${t.byteLength} bytes]`;return m(t,{maxDepth:3,maxString:500})})}function xr(e){if(typeof e==="string")return e;if(e instanceof Error)return`${e.name}: ${e.message}`;try{return JSON.stringify(m(e))??String(e)}catch{return String(e)}}function A(e,t,r="info",n){let o=x();if(!o)return;o.push("messages",{level:r,label:t,message:xr(e).slice(0,4000),context:n===void 0?void 0:m(n),at:o.elapsed()})}function xe(e,t){A(e,void 0,"debug",t)}function Ce(e,t){A(e,void 0,"info",t)}function Re(e,t){A(e,void 0,"warning",t)}function ke(e,t){A(e,void 0,"error",t)}function Ee(e,t){let r=x();if(!r)return;let n=r.get("measures:open");if(!n)n=new Map,r.set("measures:open",n);n.set(e,{label:t??e,start:r.elapsed()})}function Se(e){let t=x(),r=t?.get("measures:open"),n=r?.get(e);if(!t||!r||!n)return;r.delete(e),t.push("measures",{label:n.label,start:n.start,duration:t.elapsed()-n.start,group:"measure"})}function De(e,t,r,n="measure"){x()?.push("measures",{label:e,start:t,duration:r,group:n})}function ve(e,t){let r=x();if(!r)return t();let n=r.elapsed(),o=()=>{r.push("measures",{label:e,start:n,duration:r.elapsed()-n,group:"measure"})},s;try{s=t()}catch(i){throw o(),i}if(s instanceof Promise)return s.finally(o);return o(),s}var k=new Map,ne=new Map,E;function at(e,t){if(!e.install)return;try{let r=e.install(t),n=(o)=>{if(typeof o!=="function")return;if(E!==t||k.get(e.name)!==e)o();else ne.set(e.name,o)};if(r instanceof Promise)r.then(n,()=>{});else n(r)}catch{}}function Ae(e){let t=ne.get(e);ne.delete(e);try{t?.()}catch{}}function Q(e){if(!e||typeof e.name!=="string"||!/^[\w-]{1,40}$/.test(e.name))throw TypeError("A debugbar collector needs a name of letters, digits, dashes or underscores.");if(Ae(e.name),k.set(e.name,e),E)at(e,E);return()=>{if(k.get(e.name)!==e)return;Ae(e.name),k.delete(e.name)}}function Me(){return[...k.values()]}function ut(e,t){if(E)return;E={config:e,process:t,current:x};for(let r of k.values())at(r,E)}function ct(){E=void 0;for(let e of[...ne.keys()])Ae(e)}function lt(e){if(!E)return;for(let t of k.values()){if(!t.begin)continue;try{t.begin(e)}catch{}}}async function dt(e,t){let r={},n={};for(let o of k.values()){if(!o.collect)continue;try{let s=await o.collect(e,t);if(s===void 0||s===null)continue;if(r[o.name]=s,o.label)n[o.name]=o.label}catch(s){r[o.name]={error:s instanceof Error?s.message:String(s)}}}return{sections:r,labels:n}}import{randomBytes as Gt}from"crypto";import{chmodSync as mn,existsSync as gn,readFileSync as bn,writeFileSync as hn}from"fs";import{join as Jt}from"path";import yn from"process";import{config as ze}from"@stacksjs/config";import{projectPath as wn,storagePath as xn}from"@stacksjs/path";var H=new Map,Cr=3000;function oe(e){if(!e||typeof e!=="object")return null;let t=(i)=>{try{return e[i]}catch{return}},r=t("id");if(typeof r!=="number"&&typeof r!=="string")return null;let n=(i)=>{let a=t(i);return typeof a==="string"&&a.trim()?a.trim():void 0},o=n("email"),s=n("name")??([n("first_name")??n("firstName"),n("last_name")??n("lastName")].filter(Boolean).join(" ")||void 0)??n("username")??o??`User #${r}`;return{id:r,name:s,...o&&{email:o}}}function Rr(e,t){let r=e.headers.get("authorization");if(r&&/^bearer\s+\S/i.test(r))return{token:r.replace(/^bearer\s+/i,"").trim(),via:"bearer"};let n=t?.(e);return n?{token:n,via:"cookie"}:void 0}async function se(e){try{let t=await import("@stacksjs/auth"),r=Rr(e,t.authCookieToken);if(!r)return{user:null,via:"none"};let n=H.get(r.token);if(n&&Date.now()-n.at<Cr)return{user:n.user,via:r.via};let o=await R(()=>t.Auth.getUserFromToken(r.token)),s=oe(o);if(H.size>100)H.clear();return H.set(r.token,{user:s,at:Date.now()}),{user:s,via:r.via}}catch{return{user:null,via:"none"}}}function Te(){H.clear()}var ft={name:"auth",label:"Auth",async collect(e){let{user:t,via:r}=await se(e.request);return{authenticated:t!==null,guard:r==="none"?"guest":r==="bearer"?"token":"cookie",user:t}}};import{subscribe as kr,unsubscribe as Er}from"diagnostics_channel";var pt="stacks:cache:operation",mt={name:"cache",label:"Cache",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||typeof o?.key!=="string")return;n.push("cache",{type:o.type,key:o.key.slice(0,500),ttl:o.ttl,duration:o.durationMs,at:n.elapsed()})};return kr(pt,t),()=>{Er(pt,t)}},collect(e){let t=e.list("cache");if(t.length===0)return;let r=(n)=>t.filter((o)=>o.type===n).length;return{hits:r("hit"),misses:r("miss"),writes:r("write"),forgets:r("forget"),operations:t}}};import{existsSync as ie,readFileSync as z,statSync as Tr}from"fs";import{join as W,resolve as yt}from"path";import ae from"process";import{config as wt}from"@stacksjs/config";var gt={name:"@stacksjs/debugbar",type:"module",sideEffects:!1,version:"0.75.764",description:"The Stacks debugbar: a request inspector for development.",author:"Chris Breuer",contributors:["Chris Breuer <chris@stacksjs.com>"],license:"MIT",funding:"https://github.com/sponsors/chrisbbreuer",homepage:"https://github.com/stacksjs/stacks/tree/main/storage/framework/core/debugbar#readme",repository:{type:"git",url:"git+https://github.com/stacksjs/stacks.git",directory:"./storage/framework/core/debugbar"},bugs:{url:"https://github.com/stacksjs/stacks/issues"},keywords:["debugbar","debug","profiler","queries","stacks"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js",default:"./dist/index.js"},"./*":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"},"./*.js":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"}},module:"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],scripts:{build:"bun build.ts",typecheck:"bun tsc --noEmit",prepublishOnly:"bun run build"},devDependencies:{"better-dx":"^0.2.42"},dependencies:{"@stacksjs/auth":"workspace:*","@stacksjs/config":"workspace:*","@stacksjs/database":"workspace:*","@stacksjs/error-handling":"workspace:*","@stacksjs/events":"workspace:*","@stacksjs/logging":"workspace:*","@stacksjs/path":"workspace:*","@stacksjs/query-builder":"workspace:*","@stacksjs/queue":"workspace:*","@stacksjs/router":"workspace:*","@stacksjs/types":"workspace:*"}};import Ie from"process";var Pe=new Set(["production","prod","live"]),Dr=new Set(["local","development","dev"]);function M(e){return typeof e==="string"?e.trim().toLowerCase():""}function bt(e={}){let t=e.env??Ie.env,r=M(t.APP_ENV);if(Pe.has(r)||Pe.has(M(e.appEnv)))return!0;return!r&&Pe.has(M(t.NODE_ENV))}function qe(e={}){let t=e.env??Ie.env;return M(t.APP_ENV)||M(e.appEnv)||M(t.NODE_ENV)}function vr(e){let t=M((e.env??Ie.env).APP_DEBUG);return t==="false"||t==="0"||t==="off"||t==="no"}function Oe(e,t={}){if(bt(t))return!1;if(e?.enabled===!1)return!1;if(e?.enabled===!0)return!0;return Dr.has(qe(t))&&!vr(t)}function $e(e,t){let r=e?.queries??{};return{...e,storage:{path:e?.storage?.path||t,maxRequests:je(e?.storage?.maxRequests,200)},except:Array.isArray(e?.except)?e.except.filter((n)=>typeof n==="string"):[],queries:{slowThresholdMs:Ar(r.slowThresholdMs,100),nPlusOneThreshold:Math.max(2,je(r.nPlusOneThreshold,5)),backtrace:r.backtrace!==!1,maxQueries:je(r.maxQueries,500)}}}function je(e,t){let r=Number(e);return Number.isFinite(r)&&r>=1?Math.floor(r):t}function Ar(e,t){let r=Number(e);return Number.isFinite(r)&&r>=0?r:t}var Mr=/^\/(?:__debugbar|_stx|__deps|__hmr|__stx|@|node_modules)(?:\/|$)|^\/favicon\.|\.(?:js|mjs|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|eot|mp4|webm|mp3|wasm|txt|xml|webmanifest)$/i;function ht(e,t){if(Mr.test(e))return!0;for(let r of t)if(r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r)return!0;return!1}function Pr(e){try{let t=W(e,".git");if(!ie(t))return{};if(Tr(t).isFile()){let u=/^gitdir:\s*(.+)$/m.exec(z(t,"utf8"));if(!u)return{};t=yt(e,u[1].trim())}let r=z(W(t,"HEAD"),"utf8").trim(),n=/^ref:\s*(.+)$/.exec(r);if(!n)return{sha:r.slice(0,12)};let o=n[1].replace(/^refs\/heads\//,""),s=W(t,"commondir"),i=ie(s)?yt(t,z(s,"utf8").trim()):t;for(let u of[t,i]){let c=W(u,n[1]);if(ie(c))return{branch:o,sha:z(c,"utf8").trim().slice(0,12)}}let a=W(i,"packed-refs");if(ie(a)){let u=z(a,"utf8").split(`
|
|
3
|
+
`).find((c)=>c.endsWith(` ${n[1]}`));if(u)return{branch:o,sha:u.slice(0,12)}}return{branch:o}}catch{return{}}}var V;function jr(){if(!V||Date.now()-V.at>5000)V={...Pr(ae.cwd()),at:Date.now()};return{branch:V.branch,sha:V.sha}}function Ir(){let e=(r)=>{try{return r()}catch{return}},t=wt;return m({app:e(()=>({name:t.app?.name,env:t.app?.env,url:t.app?.url,debug:t.app?.debug,timezone:t.app?.timezone,locale:t.app?.locale})),database:e(()=>({default:t.database?.default})),cache:e(()=>({driver:t.cache?.driver})),queue:e(()=>({default:t.queue?.default})),email:e(()=>({default:t.email?.default,from:t.email?.from})),searchEngine:e(()=>({driver:t.searchEngine?.driver})),ports:e(()=>t.ports)},{maxDepth:4})}var xt={name:"environment",label:"Environment",collect(e){return{environment:qe({appEnv:wt.app?.env})||"unknown",process:e.process,pid:ae.pid,stacks:gt.version,bun:typeof Bun<"u"?Bun.version:void 0,platform:`${ae.platform} ${ae.arch}`,git:jr(),config:Ir()}}};var Ct={name:"events",label:"Events",async install({current:e}){let{listen:t,off:r}=await import("@stacksjs/events"),n=(o,s)=>{let i=e();if(!i)return;i.push("events",{name:String(o),at:i.elapsed(),payload:s===void 0?void 0:m(s,{maxDepth:4,maxKeys:30})})};return t("*",n),()=>{r("*",n)}},collect(e){let t=e.list("events");return t.length>0?t:void 0}};import{readFile as qr}from"fs/promises";import{relative as Or,sep as g}from"path";import $r from"process";var Rt;function kt(e){Rt=e.endsWith(g)?e.slice(0,-1):e}function ue(){return Rt??=$r.cwd()}var Nr=[`${g}node_modules${g}`,`${g}storage${g}framework${g}`,`${g}pantry${g}`];function Et(e){let t=ue();if(!e.startsWith(t+g))return!1;let r=e.slice(t.length);return!Nr.some((n)=>r.includes(n))}function Ne(e){let t=ue();return e.startsWith(t+g)?Or(t,e):e}var St=/^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?((?:\/|[A-Za-z]:\\|file:\/\/)[^)]*?):(\d+)(?::(\d+))?\)?\s*$/;function Dt(e,t=30){if(!e)return[];let r=[];for(let n of e.split(`
|
|
4
|
+
`)){let o=St.exec(n);if(!o)continue;let s=o[2].replace(/^file:\/\//,"");if(r.push({function:o[1]&&o[1]!=="<anonymous>"?o[1]:void 0,file:Ne(s),line:Number(o[3]),column:o[4]?Number(o[4]):void 0,app:Et(s)}),r.length>=t)break}return r}function ce(){let e={},t=Error.stackTraceLimit;Error.stackTraceLimit=40;try{Error.captureStackTrace(e,ce)}finally{Error.stackTraceLimit=t}if(!e.stack)return;for(let r of e.stack.split(`
|
|
5
|
+
`)){let n=St.exec(r);if(!n)continue;let o=n[2].replace(/^file:\/\//,"");if(Et(o))return`${Ne(o)}:${n[3]}`}return}async function vt(e,t,r=5){let n=e.startsWith(g)?e:`${ue()}${g}${e}`;if(!n.startsWith(ue()+g)||n.includes(`${g}..${g}`))return;try{let o=(await qr(n,"utf8")).split(`
|
|
6
|
+
`);if(t<1||t>o.length)return;let s=Math.max(1,t-r),i=Math.min(o.length,t+r);return{file:Ne(n),line:t,start:s,lines:o.slice(s-1,i).map((a)=>a.length>400?`${a.slice(0,400)}...`:a)}}catch{return}}var At=new WeakMap;function Le(e,t,r){let n=t instanceof Error?t:Error(typeof t==="string"?t:"Non-error value thrown"),o=At.get(e);if(!o)o=new WeakSet,At.set(e,o);if(o.has(n))return;o.add(n),e.push("exceptions",{name:n.name||"Error",message:String(n.message??"").slice(0,4000),at:e.elapsed(),frames:Dt(n.stack),context:r===void 0?void 0:m(r,{maxDepth:4})},50)}var Mt={name:"exceptions",label:"Exceptions",async install({current:e}){let{registerErrorReporter:t}=await import("@stacksjs/error-handling");return t({name:"debugbar",report({error:r,context:n}){let o=e();if(o)Le(o,r,n)}})},async collect(e){let t=e.list("exceptions");if(t.length===0)return;for(let r of t){let n=r.frames.find((o)=>o.app&&o.line);if(n)r.excerpt=await vt(n.file,n.line)}return t}};var Tt={name:"jobs",label:"Jobs",async install({current:e}){let{onQueueEvent:t}=await import("@stacksjs/queue");return t("*",(r,n)=>{let o=e();if(!o||!r.startsWith("job:")&&!r.startsWith("batch:"))return;o.push("jobs",{event:r,name:n?.jobName??n?.jobId??"unknown",queue:n?.queueName??"default",at:o.elapsed(),payload:n?.data===void 0?void 0:m(n.data,{maxDepth:4,maxKeys:30}),error:n?.error?String(n.error.message??n.error):void 0},200)})},collect(e){let t=e.list("jobs");return t.length>0?t:void 0}};var Lr=/\u001B\[[0-9;]*[A-Za-z]/g,Pt={name:"logs",label:"Logs",async install({current:e}){let{registerTransport:t}=await import("@stacksjs/logging");return t({name:"debugbar",log(r){let n=e();if(!n)return;n.push("logs",{level:r.level,message:String(r.message??"").replace(Lr,"").slice(0,4000),at:n.elapsed(),context:r.args.length>1?m(r.args.slice(1),{maxDepth:4}):void 0})}})},collect(e){let t=e.list("logs");return t.length>0?t:void 0}};import{subscribe as Ur,unsubscribe as Br}from"diagnostics_channel";var jt="stacks:mail:sent";function It(e){return(Array.isArray(e)?e:e?[e]:[]).map((r)=>typeof r==="string"?r:r?.address??"").filter(Boolean).slice(0,50)}var qt={name:"mail",label:"Mail",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||!o?.message)return;n.push("mail",{to:It(o.message.to),from:It(o.message.from)[0],subject:String(o.message.subject??"").slice(0,500),driver:String(o.driver??""),success:o.result?.success===!0,message:typeof o.result?.message==="string"?o.result.message.slice(0,500):void 0,duration:Number(o.durationMs)||0,at:n.elapsed()},200)};return Ur(jt,t),()=>{Br(jt,t)}},collect(e){let t=e.list("mail");return t.length>0?t:void 0}};var Ot={name:"messages",label:"Messages",collect(e){let t=e.list("messages");return t.length>0?t:void 0}};function _r({current:e}){return(t)=>{let r=e();if(!r||typeof t?.model!=="string"||!t.model)return;let n=r.get("models:counts");if(!n)n=new Map,r.set("models:counts",n);let o=n.get(t.model);if(o){if(o.count++,!o.table&&t.table)o.table=t.table}else n.set(t.model,{model:t.model,...t.table?{table:t.table}:{},count:1})}}var $t={name:"models",label:"Models",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=_r(e);return t({onModelHydrate:r})},collect(e){let t=e.get("models:counts");if(!t||t.size===0)return;let r=[...t.values()].sort((o,s)=>s.count-o.count||o.model.localeCompare(s.model));return{total:r.reduce((o,s)=>o+s.count,0),models:r}}};function Nt(e){return e.replace(/'(?:[^']|'')*'/g,"?").replace(/\$\d+/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/\bIN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toLowerCase()}function Qr(e){return e.startsWith("select")||e.startsWith("with")}function Ue(e){return/^\s*(?:explain\b|pragma\b)/i.test(e)||/\b(?:from|into|update|join)\s+[`"']?query_logs\b/i.test(e)}function Be(e,t){let r=new Map,n=new Map,o=[];for(let l of e){let p=Nt(l.sql),h=`${l.sql}\x00${Hr(l.params)}`;o.push({exact:h,shape:p}),r.set(h,(r.get(h)??0)+1);let b=n.get(p);if(b)b.count++;else n.set(p,{count:1,sample:l.sql,source:l.source})}let s=0,i=0,a=0,u=0;e.forEach((l,p)=>{let{exact:h,shape:b}=o[p],d=r.get(h)??1,f=n.get(b)?.count??1;if(s+=l.duration,d>1)l.duplicates=d;if(f>1)l.similar=f;if(l.duration>=t.slowThresholdMs)l.slow=!0,a++;if(l.error)u++});for(let l of r.values())i+=l-1;let c=[...n.entries()].filter(([l,p])=>p.count>=t.nPlusOneThreshold&&Qr(l)).map(([l,p])=>({shape:l,count:p.count,sample:p.sample,source:p.source})).sort((l,p)=>p.count-l.count);return{count:e.length+(t.dropped??0),duration:s,dropped:t.dropped??0,duplicates:i,slow:a,failed:u,slowThresholdMs:t.slowThresholdMs,nPlusOne:c,statements:e}}function Hr(e){try{return JSON.stringify(e)??""}catch{return""}}function zr(e,t){let r=e.get("queries:pending");if(!r)r=[],e.set("queries:pending",r);if(r.length<200)r.push({sql:t,source:ce()})}function Wr(e,t){let r=e.get("queries:pending");if(!r)return;for(let n=r.length-1;n>=0;n--)if(r[n].sql===t)return r.splice(n,1)[0].source;return}function Vr({current:e,config:t}){let r=t.queries.maxQueries,n=(o,s,i)=>{let a=e();if(!a||typeof o?.sql!=="string"||Ue(o.sql))return;let u=typeof o.durationMs==="number"?o.durationMs:0;a.push("queries",{sql:o.sql.length>8000?`${o.sql.slice(0,8000)} ...`:o.sql,params:we(o.params),start:Math.max(0,a.elapsed()-u),duration:u,rows:typeof o.rowCount==="number"?o.rowCount:void 0,kind:o.kind,source:i?i():Wr(a,o.sql),error:s?o.error instanceof Error?o.error.message:String(o.error??"failed"):void 0},r)};return{...t.queries.backtrace&&{onQueryStart(o){let s=e();if(s&&typeof o?.sql==="string"&&!Ue(o.sql))zr(s,o.sql)}},onQueryEnd(o){n(o,!1)},onQueryError(o){n(o,!0)},onModelQuery(o){n(o,o.error!==void 0,t.queries.backtrace?ce:void 0)}}}var Lt={name:"queries",label:"Queries",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=Vr(e);return t({...r.onQueryStart?{onQueryStart:r.onQueryStart}:{},onQueryEnd:r.onQueryEnd,onQueryError:r.onQueryError})},collect(e){return Be(e.list("queries"),{slowThresholdMs:e.config.queries.slowThresholdMs,nPlusOneThreshold:e.config.queries.nPlusOneThreshold,dropped:e.dropped("queries")})}};function Fr(e){let t=e,r=t.jsonBody??t.formBody;return r&&typeof r==="object"?m(r,{maxDepth:5}):void 0}var Ut={name:"request",label:"Request",collect(e,t){let{request:r,url:n}=e,o=t.headers.get("content-length");return{method:r.method,url:q(n),path:n.pathname,host:n.host,query:ye(n.searchParams),headers:re(r.headers),cookies:it(r.headers.get("cookie")),contentType:r.headers.get("content-type")??void 0,input:Fr(r),response:{status:t.status,headers:re(t.headers),contentType:t.headers.get("content-type")??void 0,size:o&&/^\d+$/.test(o)?Number(o):void 0}}}};import{subscribe as Kr,unsubscribe as Gr}from"diagnostics_channel";var Bt="stacks:router:route-matched",_t={name:"route",label:"Route",install({current:e}){let t=(r)=>{let n=r;e()?.set("route",{method:n.method,path:n.path,handler:n.handler,middleware:Array.isArray(n.middleware)?n.middleware:[]})};return Kr(Bt,t),()=>{Gr(Bt,t)}},collect(e){return e.get("route")}};import Jr from"process";function Xr(e){if(!e)return[];let t=[];for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=o.map((a)=>a.trim()).find((a)=>a.startsWith("dur=")),i=s?Number(s.slice(4)):Number.NaN;if(n&&Number.isFinite(i))t.push({name:n.trim(),duration:i})}return t}var Qt={name:"timeline",label:"Timeline",collect(e,t){let r=e.elapsed(),n=[],o=Xr(t.headers.get("server-timing")),s=o.find((u)=>u.name==="total"),i=s?Math.max(0,r-s.duration):0;for(let u of o){if(!u.name.startsWith("mw_"))continue;n.push({label:u.name.slice(3),start:i,duration:u.duration,group:"middleware"}),i+=u.duration}if(s&&n.length>0)n.push({label:"handler",start:i,duration:Math.max(0,r-i),group:"handler"});if(e.process==="views")n.push({label:t.kind==="fragment"?"render fragment":"render page",start:0,duration:r,group:"render"});n.push(...e.list("measures")),n.sort((u,c)=>u.start-c.start);let a=Jr.memoryUsage();return{duration:r,measures:n,memory:{rss:a.rss,heapUsed:a.heapUsed}}}};import{existsSync as Zr}from"fs";import{join as Ht}from"path";import Yr from"process";var O=new Map,zt;function Wt(e){zt=e,O.clear()}function en(e){if(O.has(e))return O.get(e);let t=zt??Ht(Yr.cwd(),"resources/views"),r=e.replace(/\/+$/,"").replace(/^\/+/,""),n=r?[`${r}.stx`,`${r}/index.stx`]:["index.stx"],o;if(!r.split("/").includes("..")){for(let s of n)if(Zr(Ht(t,s))){o=`resources/views/${s}`;break}}if(O.size>500)O.clear();return O.set(e,o),o}var Vt={name:"views",label:"Views",collect(e,t){if(e.process!=="views")return;return{template:en(e.url.pathname),layout:t.headers.get("x-stx-layout")??void 0,fragment:t.kind==="fragment",renderMs:e.elapsed()}}};var _e={messages:Ot,timeline:Qt,queries:Lt,models:$t,exceptions:Mt,logs:Pt,views:Vt,route:_t,events:Ct,cache:mt,mail:qt,jobs:Tt,auth:ft,request:Ut,environment:xt};function Ft(e){return Object.keys(_e).filter((t)=>e.collectors?.[t]!==!1).map((t)=>_e[t])}var tn=Object.keys(_e);import{existsSync as rn,mkdirSync as nn,writeFileSync as on}from"fs";import{mkdir as sn,readdir as an,readFile as un,rename as cn,rm as ln,unlink as dn,writeFile as Kt}from"fs/promises";import{join as N}from"path";import fn from"process";function Qe(e){try{nn(e,{recursive:!0});let t=N(e,".gitignore");if(!rn(t))on(t,`*
|
|
7
7
|
!.gitignore
|
|
8
|
-
`)}catch{}}var
|
|
8
|
+
`)}catch{}}var pn=/^([0-9a-z]{20,32})\.json$/;function He(e){let{directory:t}=e,r=Math.max(1,e.maxRequests),n=new Map,o,s=0,i=new Set;function a(){return o??=(async()=>{await sn(t,{recursive:!0}),await Kt(N(t,".gitignore"),`*
|
|
9
9
|
!.gitignore
|
|
10
|
-
`,{flag:"wx"}).catch(()=>{})})().catch(()=>{o=void 0})}async function u(){try{let d=[];for(let f of await hn(t)){let y=Cn.exec(f);if(y)d.push(y[1])}return d.sort()}catch{return[]}}async function c(){let d=await u(),f=d.slice(0,Math.max(0,d.length-r));await Promise.all(f.map((y)=>kn(N(t,`${y}.json`)).catch(()=>{})));for(let y of f)n.delete(y);return f.length}async function l(d){if(!I(d.id))return;let f=(async()=>{try{await a();let y=N(t,`${d.id}.json`),k=`${y}.${Rn.pid}.tmp`;if(await rr(k,JSON.stringify(d)),await wn(k,y),n.set(d.id,{startedAt:d.startedAt,summary:d.summary}),++s>=20||n.size>r)s=0,await c()}catch{}})();return i.add(f),f.finally(()=>{i.delete(f)}),f}async function p(d){if(!I(d))return null;try{let f=JSON.parse(await yn(N(t,`${d}.json`),"utf8"));return f&&f.id===d?f:null}catch{return null}}async function h(d=50){let f=(await u()).reverse().slice(0,Math.max(1,Math.min(d,r))),y=[];for(let k of f){let v=n.get(k);if(!v){let ge=await p(k);if(!ge)continue;v={startedAt:ge.startedAt,summary:ge.summary},n.set(k,v)}y.push({id:k,...v})}if(n.size>r*2){let k=new Set(f);for(let v of n.keys())if(!k.has(v))n.delete(v)}return y}async function b(){n.clear();let d=await u();await Promise.all(d.map((f)=>xn(N(t,`${f}.json`),{force:!0}).catch(()=>{})))}return{directory:t,write:l,read:p,list:h,clear:b,prune:c,async flush(){while(i.size>0)await Promise.allSettled([...i])}}}var B,Ge=new Set,sr=[];function ir(){try{let e=Ke.app;return{env:e?.env,url:e?.url}}catch{return{}}}function de(e={}){let t=ir();return $e(e.config??Ke.debugbar,{env:e.env,appEnv:e.appEnv??t.env})}function F(e,t={}){if(B)return B;if(!de(t))return;let r=t.root??Pn(),n=Ne(t.config??Ke.debugbar,Mn("framework/debugbar"));Dt(r),Gt(or(r,"resources/views"));let o=new Set(Me().map((s)=>s.name));for(let s of Xt(n)){if(o.has(s.name))continue;sr.push(Q(s)),Ge.add(s.name)}return ft(n,e),Ve(n.storage.path),B={config:n,store:Fe({directory:n.storage.path,maxRequests:n.storage.maxRequests}),process:e,appUrl:ir().url},B}function Tn(){return B}function jn(){pt();for(let e of sr.splice(0))e();Ge.clear(),tr(),B=void 0,L=void 0}function fe(e,t){return!kt(t,e.config.except)}function pe(e,t){let r=new ee(t,e.process,e.config);return mt(r),r}function In(e,t,r){let{queries:n,models:o,route:s,views:i,auth:a}=r,u=(c)=>Array.isArray(r[c])?r[c].length:0;return{method:e.request.method,url:q(e.url),path:e.url.pathname,status:t.status,kind:t.kind,process:e.process,duration:e.elapsed(),memory:Math.round(An.memoryUsage().rss/1048576*10)/10,queries:n?.count??0,queryDuration:n?.duration??0,...o?.total?{models:o.total}:{},logs:u("logs")+u("messages"),exceptions:u("exceptions"),route:s?`${s.method} ${s.path}`:i?.template,user:a?.user??void 0}}function K(e,t,r,n=t.kind){if(t.finished)return Promise.resolve();t.duration=performance.now()-t.startedMs,t.kind=n,t.finished=!0;let o={status:r.status,headers:new Headers(r.headers),kind:n};return R(async()=>{try{let{sections:s,labels:i}=await gt(t,o),a=Object.fromEntries(Object.entries(i).filter(([c])=>!Ge.has(c))),u={id:t.id,version:1,startedAt:new Date(t.startedAt).toISOString(),summary:In(t,o,s),collectors:s,...Object.keys(a).length>0&&{labels:a}};await e.store.write(u)}catch{}})}var L;function me(e){if(L)return L;let t=or(e.config.storage.path,".token");try{if(En(t)){let n=vn(t,"utf8").trim();if(/^[a-f0-9]{48}$/.test(n))return L=n}let r=nr(24).toString("hex");return Ve(e.config.storage.path),Dn(t,r,{mode:384}),Sn(t,384),L=r}catch{return L=nr(24).toString("hex")}}import{existsSync as qn}from"fs";import{join as ar}from"path";var Je,Xe="0";async function On(){let e=ar(import.meta.dir,"client","debugbar.js"),t;if(qn(e))t=await Bun.file(e).text();else{let r=await Bun.build({entrypoints:[ar(import.meta.dir,"client","index.ts")],target:"browser",format:"iife",minify:!0}),n=r.outputs[0];if(!r.success||!n)throw Error("The debugbar client could not be bundled.");t=await n.text()}return Xe=Bun.hash(t).toString(36).slice(0,10),{body:t,version:Xe}}function ur(){return Xe}function G(){return Je??=On().catch((e)=>{throw Je=void 0,e})}function $n(){Je=void 0}var Nn=new RegExp("^127(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$");function M(e){if(!e)return!1;let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(t==="::1"||t==="localhost")return!0;let r=t.startsWith("::ffff:")?t.slice(7):t;return Nn.test(r)}function J(e,t){if(!e)return!1;let r=e.trim().toLowerCase();if(r.startsWith("[")){let n=r.indexOf("]");if(n===-1)return!1;r=r.slice(1,n)}else r=r.replace(/:\d+$/,"");if(M(r)||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".test"))return!0;if(t)try{let n=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`).hostname.toLowerCase();if(r===n&&(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".test")||M(n)))return!0}catch{}return!1}function T(e,t={}){if(t.allowRemote===!0)return!0;if(t.peer!==void 0&&!M(t.peer))return!1;let r=e.headers.get("x-forwarded-for");if(r&&!r.split(",").every((i)=>M(i)))return!1;for(let i of["x-real-ip","cf-connecting-ip","true-client-ip"]){let a=e.headers.get(i);if(a&&!M(a))return!1}let n=e.headers.get("forwarded");if(n)for(let i of n.split(",")){let a=/\bfor=(?:"([^"]+)"|([^;\s]+))/i.exec(i),u=(a?.[1]??a?.[2])?.replace(/^\[|\]$/g,"").replace(/:\d+$/,"");if(u&&!M(u))return!1;let c=/\bhost=(?:"([^"]+)"|([^;\s]+))/i.exec(i),l=c?.[1]??c?.[2];if(l&&!J(l,t.appUrl))return!1}let o=e.headers.get("x-forwarded-host");if(o&&!o.split(",").every((i)=>J(i,t.appUrl)))return!1;let s=e.headers.get("host");if(!s)try{s=new URL(e.url).host}catch{return!1}return J(s,t.appUrl)}function Ze(e){let t=e.headers.get("sec-fetch-site");if(t&&t!=="same-origin")return!1;let r=e.headers.get("origin");if(r){let n;try{n=new URL(r).host.toLowerCase()}catch{return!1}let o=e.headers.get("host")?.trim().toLowerCase(),s=[];if(o)s.push(o);let i=e.headers.get("x-forwarded-host");if(i)for(let a of i.split(",")){let u=a.trim().toLowerCase();if(u&&J(u))s.push(u)}try{s.push(new URL(e.url).host.toLowerCase())}catch{}if(!s.includes(n))return!1}return!0}function cr(e,t){if(typeof e!=="string"||e.length!==t.length||t.length===0)return!1;let r=0;for(let n=0;n<t.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var Ye="/__debugbar/",Ln="x-debugbar-token";function lr(e){return e.auth?e.auth():import("@stacksjs/auth")}var dr={"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin","X-Robots-Tag":"noindex"};function j(e,t=200,r={}){return new Response(JSON.stringify(e),{status:t,headers:{...dr,"Content-Type":"application/json; charset=utf-8",...r}})}function w(e,t){return j({error:t},e)}function et(e){return e.startsWith(Ye)}async function Bn(){let{db:e}=await import("@stacksjs/database/runtime");return(await e.selectFrom("users").selectAll().limit(25).execute()).map(oe).filter((r)=>r!==null)}async function tt(e){let t=e.config.signInAs?.users,r=await R(async()=>typeof t==="function"?await t():await Bn());if(!Array.isArray(r))return[];let n=[];for(let o of r.slice(0,500)){if(!o||typeof o.id!=="number"&&typeof o.id!=="string")continue;let s=(i)=>typeof i==="string"&&i?i.slice(0,200):void 0;n.push({id:o.id,name:s(o.name)??`User #${o.id}`,...s(o.email)&&{email:s(o.email)},...s(o.badge)&&{badge:s(o.badge)},...s(o.description)&&{description:s(o.description)}})}return n}function fr(e){if(e.config.allowRemote===!0)return e.config.signInAs?.enabled===!0;return e.config.signInAs?.enabled!==!1}function rt(e,t){if(!Ze(e))return w(403,"Cross-origin requests are not accepted.");if(!cr(e.headers.get(Ln),me(t)))return w(403,"Missing or invalid debugbar token. Reload the page.");return}function pr(e){return(e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()??new URL(e.url).protocol.replace(":",""))==="https"}async function Un(e,t,r){if(!fr(t))return w(404,"Sign in as is disabled.");let n=rt(e,t);if(n)return n;let o;try{o=(await e.json())?.id}catch{return w(400,"Expected a JSON body with an id.")}if(typeof o!=="number"&&typeof o!=="string")return w(400,"Expected a JSON body with an id.");let s=(await tt(t)).find((c)=>String(c.id)===String(o));if(!s)return w(404,"That user is not offered for sign in.");let i=await lr(r),a=await R(()=>i.Auth.loginUsingId(s.id));if(!a)return w(404,"That user no longer exists.");Te();let u=String(a.token);return j({token:u,user:oe(a.user)??s,tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":i.authCookie(u,{secure:pr(e)})})}async function _n(e,t,r){let n=rt(e,t);if(n)return n;let o=await lr(r);return Te(),j({tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":o.clearAuthCookie({secure:pr(e)})})}async function Qn(e,t){let r=fr(t),[n,o]=await Promise.all([r?tt(t).catch(()=>[]):Promise.resolve([]),se(e)]);return j({enabled:r,users:n,current:o.user,tokenStorageKey:t.config.signInAs?.tokenStorageKey})}async function Hn(e){let t=await G(),r=`"${t.version}"`,n={...dr,"Content-Type":"text/javascript; charset=utf-8",ETag:r,"Cache-Control":new URL(e.url).searchParams.get("v")===t.version?"private, max-age=31536000, immutable":"no-cache"};if(e.headers.get("if-none-match")===r)return new Response(null,{status:304,headers:n});return new Response(t.body,{headers:n})}async function nt(e,t,r={}){if(!t)return new Response("Not Found",{status:404});if(!T(e,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:r.peer}))return w(403,"The debugbar only answers requests from this machine. Set debugbar.allowRemote to change that.");let n=new URL(e.url),o=n.pathname.slice(Ye.length).replace(/\/+$/,""),s=e.method.toUpperCase();try{if(o==="assets/debugbar.js"&&(s==="GET"||s==="HEAD"))return await Hn(e);if(o==="requests"){if(s==="GET")return j({requests:await t.store.list(Number(n.searchParams.get("limit"))||50)});if(s==="DELETE"){let i=rt(e,t);if(i)return i;return await t.store.clear(),j({cleared:!0})}return w(405,"Method not allowed.")}if(o.startsWith("requests/")&&s==="GET"){let i=o.slice(9),a=I(i)?await t.store.read(i):null;return a?j(a):w(404,"No record with that id.")}if(o==="users"&&s==="GET")return await Qn(e,t);if(o==="sign-in-as"&&s==="POST")return await Un(e,t,r);if(o==="sign-out"&&s==="POST")return await _n(e,t,r)}catch(i){return w(500,i instanceof Error?i.message:"The debugbar failed to answer.")}return w(404,"Not found.")}import{brotliCompressSync as Wn,brotliDecompressSync as zn,deflateSync as Vn,gunzipSync as Fn,gzipSync as Kn,inflateSync as Gn}from"zlib";var E="X-Debugbar-Id",gr="/__debugbar/assets/debugbar.js";function X(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ot(e){let t=e.get("content-security-policy");if(!t)return;let r=new Map;for(let s of t.split(";")){let i=s.trim();if(!i)continue;let a=i.search(/\s/);if(a<0)continue;let u=i.slice(0,a).toLowerCase(),c=i.slice(a+1).trim();if(!r.has(u))r.set(u,c)}let n=r.get("script-src")??r.get("default-src");if(!n)return;return n.match(/'nonce-([^'\s]+)'/i)?.[1]||void 0}function st(e){let t=e.nonce?` nonce="${X(e.nonce)}"`:"";return`<script src="${gr}?v=${X(e.version)}" defer${t} data-stacks-debugbar data-id="${X(e.id)}" data-token="${X(e.token)}" data-options="${X(JSON.stringify(e.client??{}))}"></script>`}function br(e){if(!e.body||e.status===204||e.status===304)return!1;if(e.headers.has("content-encoding"))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function hr(e){let t=e.headers.get("content-encoding")?.trim().toLowerCase();if(t==="gzip"||t==="br"||t==="deflate")return t;return}function Jn(e){if(!e.body||e.status===204||e.status===304)return!1;if(!hr(e))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function yr(e,t){if(!br(e))return;let r=t.nonce??ot(e.headers),n=st(r?{...t,nonce:r}:t),o=!1,s=new HTMLRewriter().on("body",{element(i){if(o)return;o=!0,i.append(n,{html:!0})}}).transform(e);return s.headers.delete("content-length"),s}function it(e,t){let r=yr(e,t);if(r)return r;if(!Jn(e))return;let n=hr(e),o=t.nonce??ot(e.headers),s=st(o?{...t,nonce:o}:t);return(async()=>{let i=new Uint8Array(await e.arrayBuffer()),a;try{let b=n==="gzip"?Fn(i):n==="br"?zn(i):Gn(i);a=new TextDecoder().decode(b)}catch{return new Response(i,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}let u=/<\/body>/i,c=u.test(a)?a.replace(u,(b)=>`${s}${b}`):a,l=new TextEncoder().encode(c),p=n==="gzip"?Kn(l):n==="br"?Wn(l):Vn(l),h=new Headers(e.headers);return h.delete("content-length"),new Response(p,{status:e.status,statusText:e.statusText,headers:h})})()}function Z(e,t){let r=mr(e,E,t),n=r.headers.get("server-timing"),o=`debugbar;desc="${t}"`;return mr(r,"Server-Timing",n?`${n}, ${o}`:o)}function mr(e,t,r){try{return e.headers.set(t,r),e}catch{let n=new Headers(e.headers);return n.set(t,r),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}import Xn from"process";import{peerAddress as Zn}from"@stacksjs/router";function Yn(e){if(!e.headers.has("access-control-allow-origin"))return;let t=e.headers.get("access-control-expose-headers");if(t&&t.toLowerCase().split(",").map((r)=>r.trim()).includes(E.toLowerCase()))return;try{e.headers.set("Access-Control-Expose-Headers",t?`${t}, ${E}`:E)}catch{}}function wr(e){let t={allowRemote:e.config.allowRemote,appUrl:e.appUrl};return async(r,n)=>{let o;try{o=new URL(r.url).pathname}catch{return n()}let s=Zn(r);if(r.method==="OPTIONS"||!fe(e,o)||!T(r,s?{...t,peer:s}:t))return n();let i=pe(e,r),a=r;if(a._startNs==null)a._startNs=Xn.hrtime.bigint();let u;try{u=await he(i,n)}catch(l){throw Be(i,l),K(e,i,{status:500,headers:new Headers}),l}if(!(u instanceof Response))return u;let c=Z(u,i.id);return Yn(c),K(e,i,c),c}}function eo(e,t={}){let r=F("api",t);if(!r)return!1;return e.use(wr(r)),!0}function to(e={}){let t=F("views",e);if(!t)return;let r=new WeakMap,n={shortcut:t.config.shortcut??"alt+shift+d",signInAs:t.config.signInAs?.enabled!==!1,tokenStorageKey:t.config.signInAs?.tokenStorageKey,slowQueryMs:t.config.queries.slowThresholdMs};G().catch(()=>{}),We();let o=(s,i)=>{let a=ze(i),u;try{u=e.clientAddress?.(s,a)}catch{}if(u)return u;return a.requestIP(s)?.address||null};return{runtime:t,onRequest(s,i){let a;try{a=new URL(s.url).pathname}catch{return}if(et(a))return nt(s,t,{peer:o(s,i)});if(!fe(t,a))return;if(!T(s,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:o(s,i)}))return;let u=pe(t,s);r.set(s,u),ut(u);return},onResponse(s,i){let a=r.get(s);if(!a)return;if(r.delete(s),i.headers.has(E)){a.finished=!0;return}let u=i.headers.get("content-type")?.toLowerCase()??"",c=u.startsWith("text/html"),l=i.status>=300&&i.status<400&&i.headers.has("location");if(!c&&!u.includes("json")&&!l){a.finished=!0;return}let h=i.headers.get("x-stx-fragment")==="true"?"fragment":c||l?"page":"api",b=(d)=>{let f=Z(d,a.id);return K(t,a,f,h),f};if(h==="page"&&c){let d=it(i,{id:a.id,token:me(t),version:ur(),client:n});if(d instanceof Promise)return d.then(b);return b(d??i)}return b(i)}}}var ro={enabled:()=>de(),collecting:()=>x()!==void 0,addMessage:A,debug:ke,info:Re,warn:Ce,error:Se,measure:Ae,startMeasure:Ee,stopMeasure:ve,addMeasure:De,registerCollector:Q},Qi=ro;export{ln as BUILT_IN_COLLECTOR_NAMES,ee as Collection,gr as DEBUGBAR_ASSET_PATH,E as DEBUGBAR_ID_HEADER,Ye as DEBUGBAR_PREFIX,Sr as REDACTED,De as addMeasure,A as addMessage,_e as analyzeQueries,F as bootDebugbar,We as captureSocketPeers,er as capturedSocketPeer,G as clientBundle,Me as collectors,wr as createApiDebugbarMiddleware,at as createRecordId,Fe as createStore,to as createViewsDebugbar,x as currentCollection,ke as debug,ro as debugbar,de as debugbarEnabled,Tn as debugbarRuntime,st as debugbarScriptTag,Qi as default,Se as error,ot as extractCspScriptNonce,nt as handleDebugbarRequest,Re as info,yr as injectDebugbar,it as injectDebugbarResponse,eo as installApiDebugbar,$e as isDebugbarEnabled,et as isDebugbarPath,br as isInjectableDocument,J as isLocalHostname,T as isLocalRequest,M as isLoopbackAddress,xt as isProductionEnvironment,I as isRecordId,Ze as isSameOriginRequest,_ as isSensitiveName,Ae as measure,_t as normalizeSql,ze as peerAwareServer,m as redact,xe as redactBindings,re as redactHeaders,we as redactQuery,q as redactUrl,Q as registerCollector,$n as resetClientBundle,Ne as resolveDebugbarConfig,he as runWithCollection,jn as shutdownDebugbar,tt as signInAsUsers,Ee as startMeasure,ve as stopMeasure,Ce as warn,Z as withRecordId,R as withoutCollection};
|
|
10
|
+
`,{flag:"wx"}).catch(()=>{})})().catch(()=>{o=void 0})}async function u(){try{let d=[];for(let f of await an(t)){let y=pn.exec(f);if(y)d.push(y[1])}return d.sort()}catch{return[]}}async function c(){let d=await u(),f=d.slice(0,Math.max(0,d.length-r));await Promise.all(f.map((y)=>dn(N(t,`${y}.json`)).catch(()=>{})));for(let y of f)n.delete(y);return f.length}async function l(d){if(!I(d.id))return;let f=(async()=>{try{await a();let y=N(t,`${d.id}.json`),C=`${y}.${fn.pid}.tmp`;if(await Kt(C,JSON.stringify(d)),await cn(C,y),n.set(d.id,{startedAt:d.startedAt,summary:d.summary}),++s>=20||n.size>r)s=0,await c()}catch{}})();return i.add(f),f.finally(()=>{i.delete(f)}),f}async function p(d){if(!I(d))return null;try{let f=JSON.parse(await un(N(t,`${d}.json`),"utf8"));return f&&f.id===d?f:null}catch{return null}}async function h(d=50){let f=(await u()).reverse().slice(0,Math.max(1,Math.min(d,r))),y=[];for(let C of f){let D=n.get(C);if(!D){let me=await p(C);if(!me)continue;D={startedAt:me.startedAt,summary:me.summary},n.set(C,D)}y.push({id:C,...D})}if(n.size>r*2){let C=new Set(f);for(let D of n.keys())if(!C.has(D))n.delete(D)}return y}async function b(){n.clear();let d=await u();await Promise.all(d.map((f)=>ln(N(t,`${f}.json`),{force:!0}).catch(()=>{})))}return{directory:t,write:l,read:p,list:h,clear:b,prune:c,async flush(){while(i.size>0)await Promise.allSettled([...i])}}}var U,We=new Set,Xt=[];function Zt(){try{let e=ze.app;return{env:e?.env,url:e?.url}}catch{return{}}}function le(e={}){let t=Zt();return Oe(e.config??ze.debugbar,{env:e.env,appEnv:e.appEnv??t.env})}function F(e,t={}){if(U)return U;if(!le(t))return;let r=t.root??wn(),n=$e(t.config??ze.debugbar,xn("framework/debugbar"));kt(r),Wt(Jt(r,"resources/views"));let o=new Set(Me().map((s)=>s.name));for(let s of Ft(n)){if(o.has(s.name))continue;Xt.push(Q(s)),We.add(s.name)}return ut(n,e),Qe(n.storage.path),U={config:n,store:He({directory:n.storage.path,maxRequests:n.storage.maxRequests}),process:e,appUrl:Zt().url},U}function Cn(){return U}function Rn(){ct();for(let e of Xt.splice(0))e();We.clear(),U=void 0,L=void 0}function de(e,t){return!ht(t,e.config.except)}function fe(e,t){let r=new ee(t,e.process,e.config);return lt(r),r}function kn(e,t,r){let{queries:n,models:o,route:s,views:i,auth:a}=r,u=(c)=>Array.isArray(r[c])?r[c].length:0;return{method:e.request.method,url:q(e.url),path:e.url.pathname,status:t.status,kind:t.kind,process:e.process,duration:e.elapsed(),memory:Math.round(yn.memoryUsage().rss/1048576*10)/10,queries:n?.count??0,queryDuration:n?.duration??0,...o?.total?{models:o.total}:{},logs:u("logs")+u("messages"),exceptions:u("exceptions"),route:s?`${s.method} ${s.path}`:i?.template,user:a?.user??void 0}}function K(e,t,r,n=t.kind){if(t.finished)return Promise.resolve();t.duration=performance.now()-t.startedMs,t.kind=n,t.finished=!0;let o={status:r.status,headers:new Headers(r.headers),kind:n};return R(async()=>{try{let{sections:s,labels:i}=await dt(t,o),a=Object.fromEntries(Object.entries(i).filter(([c])=>!We.has(c))),u={id:t.id,version:1,startedAt:new Date(t.startedAt).toISOString(),summary:kn(t,o,s),collectors:s,...Object.keys(a).length>0&&{labels:a}};await e.store.write(u)}catch{}})}var L;function pe(e){if(L)return L;let t=Jt(e.config.storage.path,".token");try{if(gn(t)){let n=bn(t,"utf8").trim();if(/^[a-f0-9]{48}$/.test(n))return L=n}let r=Gt(24).toString("hex");return Qe(e.config.storage.path),hn(t,r,{mode:384}),mn(t,384),L=r}catch{return L=Gt(24).toString("hex")}}import{existsSync as En}from"fs";import{join as Yt}from"path";var Ve,Fe="0";async function Sn(){let e=Yt(import.meta.dir,"client","debugbar.js"),t;if(En(e))t=await Bun.file(e).text();else{let r=await Bun.build({entrypoints:[Yt(import.meta.dir,"client","index.ts")],target:"browser",format:"iife",minify:!0}),n=r.outputs[0];if(!r.success||!n)throw Error("The debugbar client could not be bundled.");t=await n.text()}return Fe=Bun.hash(t).toString(36).slice(0,10),{body:t,version:Fe}}function er(){return Fe}function G(){return Ve??=Sn().catch((e)=>{throw Ve=void 0,e})}function Dn(){Ve=void 0}var vn=new RegExp("^127(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$");function T(e){if(!e)return!1;let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(t==="::1"||t==="localhost")return!0;let r=t.startsWith("::ffff:")?t.slice(7):t;return vn.test(r)}function J(e,t){if(!e)return!1;let r=e.trim().toLowerCase();if(r.startsWith("[")){let n=r.indexOf("]");if(n===-1)return!1;r=r.slice(1,n)}else r=r.replace(/:\d+$/,"");if(T(r)||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".test"))return!0;if(t)try{let n=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`).hostname.toLowerCase();if(r===n&&(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".test")||T(n)))return!0}catch{}return!1}function P(e,t={}){if(t.allowRemote===!0)return!0;if(t.peer!==void 0&&!T(t.peer))return!1;let r=e.headers.get("x-forwarded-for");if(r&&!r.split(",").every((i)=>T(i)))return!1;for(let i of["x-real-ip","cf-connecting-ip","true-client-ip"]){let a=e.headers.get(i);if(a&&!T(a))return!1}let n=e.headers.get("forwarded");if(n)for(let i of n.split(",")){let a=/\bfor=(?:"([^"]+)"|([^;\s]+))/i.exec(i),u=(a?.[1]??a?.[2])?.replace(/^\[|\]$/g,"").replace(/:\d+$/,"");if(u&&!T(u))return!1;let c=/\bhost=(?:"([^"]+)"|([^;\s]+))/i.exec(i),l=c?.[1]??c?.[2];if(l&&!J(l,t.appUrl))return!1}let o=e.headers.get("x-forwarded-host");if(o&&!o.split(",").every((i)=>J(i,t.appUrl)))return!1;let s=e.headers.get("host");if(!s)try{s=new URL(e.url).host}catch{return!1}return J(s,t.appUrl)}function Ke(e){let t=e.headers.get("sec-fetch-site");if(t&&t!=="same-origin")return!1;let r=e.headers.get("origin");if(r){let n;try{n=new URL(r).host.toLowerCase()}catch{return!1}let o=e.headers.get("host")?.trim().toLowerCase(),s=[];if(o)s.push(o);let i=e.headers.get("x-forwarded-host");if(i)for(let a of i.split(",")){let u=a.trim().toLowerCase();if(u&&J(u))s.push(u)}try{s.push(new URL(e.url).host.toLowerCase())}catch{}if(!s.includes(n))return!1}return!0}function tr(e,t){if(typeof e!=="string"||e.length!==t.length||t.length===0)return!1;let r=0;for(let n=0;n<t.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var Ge="/__debugbar/",An="x-debugbar-token";function rr(e){return e.auth?e.auth():import("@stacksjs/auth")}var nr={"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin","X-Robots-Tag":"noindex"};function j(e,t=200,r={}){return new Response(JSON.stringify(e),{status:t,headers:{...nr,"Content-Type":"application/json; charset=utf-8",...r}})}function w(e,t){return j({error:t},e)}function Je(e){return e.startsWith(Ge)}async function Mn(){let{db:e}=await import("@stacksjs/database/runtime");return(await e.selectFrom("users").selectAll().limit(25).execute()).map(oe).filter((r)=>r!==null)}async function Xe(e){let t=e.config.signInAs?.users,r=await R(async()=>typeof t==="function"?await t():await Mn());if(!Array.isArray(r))return[];let n=[];for(let o of r.slice(0,500)){if(!o||typeof o.id!=="number"&&typeof o.id!=="string")continue;let s=(i)=>typeof i==="string"&&i?i.slice(0,200):void 0;n.push({id:o.id,name:s(o.name)??`User #${o.id}`,...s(o.email)&&{email:s(o.email)},...s(o.badge)&&{badge:s(o.badge)},...s(o.description)&&{description:s(o.description)}})}return n}function or(e){if(e.config.allowRemote===!0)return e.config.signInAs?.enabled===!0;return e.config.signInAs?.enabled!==!1}function Ze(e,t){if(!Ke(e))return w(403,"Cross-origin requests are not accepted.");if(!tr(e.headers.get(An),pe(t)))return w(403,"Missing or invalid debugbar token. Reload the page.");return}function sr(e){return(e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()??new URL(e.url).protocol.replace(":",""))==="https"}async function Tn(e,t,r){if(!or(t))return w(404,"Sign in as is disabled.");let n=Ze(e,t);if(n)return n;let o;try{o=(await e.json())?.id}catch{return w(400,"Expected a JSON body with an id.")}if(typeof o!=="number"&&typeof o!=="string")return w(400,"Expected a JSON body with an id.");let s=(await Xe(t)).find((c)=>String(c.id)===String(o));if(!s)return w(404,"That user is not offered for sign in.");let i=await rr(r),a=await R(()=>i.Auth.loginUsingId(s.id));if(!a)return w(404,"That user no longer exists.");Te();let u=String(a.token);return j({token:u,user:oe(a.user)??s,tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":i.authCookie(u,{secure:sr(e)})})}async function Pn(e,t,r){let n=Ze(e,t);if(n)return n;let o=await rr(r);return Te(),j({tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":o.clearAuthCookie({secure:sr(e)})})}async function jn(e,t){let r=or(t),[n,o]=await Promise.all([r?Xe(t).catch(()=>[]):Promise.resolve([]),se(e)]);return j({enabled:r,users:n,current:o.user,tokenStorageKey:t.config.signInAs?.tokenStorageKey})}async function In(e){let t=await G(),r=`"${t.version}"`,n={...nr,"Content-Type":"text/javascript; charset=utf-8",ETag:r,"Cache-Control":new URL(e.url).searchParams.get("v")===t.version?"private, max-age=31536000, immutable":"no-cache"};if(e.headers.get("if-none-match")===r)return new Response(null,{status:304,headers:n});return new Response(t.body,{headers:n})}async function Ye(e,t,r={}){if(!t)return new Response("Not Found",{status:404});if(!P(e,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:r.peer}))return w(403,"The debugbar only answers requests from this machine. Set debugbar.allowRemote to change that.");let n=new URL(e.url),o=n.pathname.slice(Ge.length).replace(/\/+$/,""),s=e.method.toUpperCase();try{if(o==="assets/debugbar.js"&&(s==="GET"||s==="HEAD"))return await In(e);if(o==="requests"){if(s==="GET")return j({requests:await t.store.list(Number(n.searchParams.get("limit"))||50)});if(s==="DELETE"){let i=Ze(e,t);if(i)return i;return await t.store.clear(),j({cleared:!0})}return w(405,"Method not allowed.")}if(o.startsWith("requests/")&&s==="GET"){let i=o.slice(9),a=I(i)?await t.store.read(i):null;return a?j(a):w(404,"No record with that id.")}if(o==="users"&&s==="GET")return await jn(e,t);if(o==="sign-in-as"&&s==="POST")return await Tn(e,t,r);if(o==="sign-out"&&s==="POST")return await Pn(e,t,r)}catch(i){return w(500,i instanceof Error?i.message:"The debugbar failed to answer.")}return w(404,"Not found.")}import{brotliCompressSync as qn,brotliDecompressSync as On,deflateSync as $n,gunzipSync as Nn,gzipSync as Ln,inflateSync as Un}from"zlib";var S="X-Debugbar-Id",ar="/__debugbar/assets/debugbar.js";function X(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function et(e){let t=e.get("content-security-policy");if(!t)return;let r=new Map;for(let s of t.split(";")){let i=s.trim();if(!i)continue;let a=i.search(/\s/);if(a<0)continue;let u=i.slice(0,a).toLowerCase(),c=i.slice(a+1).trim();if(!r.has(u))r.set(u,c)}let n=r.get("script-src")??r.get("default-src");if(!n)return;return n.match(/'nonce-([^'\s]+)'/i)?.[1]||void 0}function tt(e){let t=e.nonce?` nonce="${X(e.nonce)}"`:"";return`<script src="${ar}?v=${X(e.version)}" defer${t} data-stacks-debugbar data-id="${X(e.id)}" data-token="${X(e.token)}" data-options="${X(JSON.stringify(e.client??{}))}"></script>`}function ur(e){if(!e.body||e.status===204||e.status===304)return!1;if(e.headers.has("content-encoding"))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function cr(e){let t=e.headers.get("content-encoding")?.trim().toLowerCase();if(t==="gzip"||t==="br"||t==="deflate")return t;return}function Bn(e){if(!e.body||e.status===204||e.status===304)return!1;if(!cr(e))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function lr(e,t){if(!ur(e))return;let r=t.nonce??et(e.headers),n=tt(r?{...t,nonce:r}:t),o=!1,s=new HTMLRewriter().on("body",{element(i){if(o)return;o=!0,i.append(n,{html:!0})}}).transform(e);return s.headers.delete("content-length"),s}function rt(e,t){let r=lr(e,t);if(r)return r;if(!Bn(e))return;let n=cr(e),o=t.nonce??et(e.headers),s=tt(o?{...t,nonce:o}:t);return(async()=>{let i=new Uint8Array(await e.arrayBuffer()),a;try{let b=n==="gzip"?Nn(i):n==="br"?On(i):Un(i);a=new TextDecoder().decode(b)}catch{return new Response(i,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}let u=/<\/body>/i,c=u.test(a)?a.replace(u,(b)=>`${s}${b}`):a,l=new TextEncoder().encode(c),p=n==="gzip"?Ln(l):n==="br"?qn(l):$n(l),h=new Headers(e.headers);return h.delete("content-length"),new Response(p,{status:e.status,statusText:e.statusText,headers:h})})()}function Z(e,t){let r=ir(e,S,t),n=r.headers.get("server-timing"),o=`debugbar;desc="${t}"`;return ir(r,"Server-Timing",n?`${n}, ${o}`:o)}function ir(e,t,r){try{return e.headers.set(t,r),e}catch{let n=new Headers(e.headers);return n.set(t,r),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}import _n from"process";import{peerAddress as Qn}from"@stacksjs/router";function Hn(e){if(!e.headers.has("access-control-allow-origin"))return;let t=e.headers.get("access-control-expose-headers");if(t&&t.toLowerCase().split(",").map((r)=>r.trim()).includes(S.toLowerCase()))return;try{e.headers.set("Access-Control-Expose-Headers",t?`${t}, ${S}`:S)}catch{}}function dr(e){let t={allowRemote:e.config.allowRemote,appUrl:e.appUrl};return async(r,n)=>{let o;try{o=new URL(r.url).pathname}catch{return n()}let s=Qn(r);if(r.method==="OPTIONS"||!de(e,o)||!P(r,s?{...t,peer:s}:t))return n();let i=fe(e,r),a=r;if(a._startNs==null)a._startNs=_n.hrtime.bigint();let u;try{u=await be(i,n)}catch(l){throw Le(i,l),K(e,i,{status:500,headers:new Headers}),l}if(!(u instanceof Response))return u;let c=Z(u,i.id);return Hn(c),K(e,i,c),c}}function zn(e,t={}){let r=F("api",t);if(!r)return!1;return e.use(dr(r)),!0}function Wn(e={}){let t=F("views",e);if(!t)return;let r=new WeakMap,n={shortcut:t.config.shortcut??"alt+shift+d",signInAs:t.config.signInAs?.enabled!==!1,tokenStorageKey:t.config.signInAs?.tokenStorageKey,slowQueryMs:t.config.queries.slowThresholdMs};G().catch(()=>{});let o=(s,i)=>{let a;try{a=e.clientAddress?.(s,i)}catch{}if(a)return a;try{return i?.requestIP?.(s)?.address||null}catch{return null}};return{runtime:t,onRequest(s,i){let a;try{a=new URL(s.url).pathname}catch{return}if(Je(a))return Ye(s,t,{peer:o(s,i)});if(!de(t,a))return;if(!P(s,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:o(s,i)}))return;let u=fe(t,s);r.set(s,u),ot(u);return},onResponse(s,i){let a=r.get(s);if(!a)return;if(r.delete(s),i.headers.has(S)){a.finished=!0;return}let u=i.headers.get("content-type")?.toLowerCase()??"",c=u.startsWith("text/html"),l=i.status>=300&&i.status<400&&i.headers.has("location");if(!c&&!u.includes("json")&&!l){a.finished=!0;return}let h=i.headers.get("x-stx-fragment")==="true"?"fragment":c||l?"page":"api",b=(d)=>{let f=Z(d,a.id);return K(t,a,f,h),f};if(h==="page"&&c){let d=rt(i,{id:a.id,token:pe(t),version:er(),client:n});if(d instanceof Promise)return d.then(b);return b(d??i)}return b(i)}}}var Vn={enabled:()=>le(),collecting:()=>x()!==void 0,addMessage:A,debug:xe,info:Ce,warn:Re,error:ke,measure:ve,startMeasure:Ee,stopMeasure:Se,addMeasure:De,registerCollector:Q},vi=Vn;export{tn as BUILT_IN_COLLECTOR_NAMES,ee as Collection,ar as DEBUGBAR_ASSET_PATH,S as DEBUGBAR_ID_HEADER,Ge as DEBUGBAR_PREFIX,br as REDACTED,De as addMeasure,A as addMessage,Be as analyzeQueries,F as bootDebugbar,G as clientBundle,Me as collectors,dr as createApiDebugbarMiddleware,nt as createRecordId,He as createStore,Wn as createViewsDebugbar,x as currentCollection,xe as debug,Vn as debugbar,le as debugbarEnabled,Cn as debugbarRuntime,tt as debugbarScriptTag,vi as default,ke as error,et as extractCspScriptNonce,Ye as handleDebugbarRequest,Ce as info,lr as injectDebugbar,rt as injectDebugbarResponse,zn as installApiDebugbar,Oe as isDebugbarEnabled,Je as isDebugbarPath,ur as isInjectableDocument,J as isLocalHostname,P as isLocalRequest,T as isLoopbackAddress,bt as isProductionEnvironment,I as isRecordId,Ke as isSameOriginRequest,_ as isSensitiveName,ve as measure,Nt as normalizeSql,m as redact,we as redactBindings,re as redactHeaders,ye as redactQuery,q as redactUrl,Q as registerCollector,Dn as resetClientBundle,$e as resolveDebugbarConfig,be as runWithCollection,Rn as shutdownDebugbar,Xe as signInAsUsers,Ee as startMeasure,Se as stopMeasure,Re as warn,Z as withRecordId,R as withoutCollection};
|
package/dist/views.d.ts
CHANGED
|
@@ -2,10 +2,6 @@ import type { BootOptions, DebugbarRuntime } from './runtime';
|
|
|
2
2
|
/**
|
|
3
3
|
* The debugbar for a server that renders pages, or undefined when it is not
|
|
4
4
|
* enabled in this process. A caller that gets undefined mounts nothing.
|
|
5
|
-
*
|
|
6
|
-
* Create it before the page server's module is imported (see peer.ts): on
|
|
7
|
-
* an app with i18n the client's address cannot be told otherwise, and every
|
|
8
|
-
* request under `/__debugbar/` is then refused.
|
|
9
5
|
*/
|
|
10
6
|
export declare function createViewsDebugbar(options?: ViewsDebugbarOptions): ViewsDebugbar | undefined;
|
|
11
7
|
export declare interface ViewsDebugbarOptions extends BootOptions {
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/debugbar",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.764",
|
|
6
6
|
"description": "The Stacks debugbar: a request inspector for development.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,19 +58,19 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
|
-
"better-dx": "^0.2.
|
|
61
|
+
"better-dx": "^0.2.42"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@stacksjs/auth": "0.75.
|
|
65
|
-
"@stacksjs/config": "0.75.
|
|
66
|
-
"@stacksjs/database": "0.75.
|
|
67
|
-
"@stacksjs/error-handling": "0.75.
|
|
68
|
-
"@stacksjs/events": "0.75.
|
|
69
|
-
"@stacksjs/logging": "0.75.
|
|
70
|
-
"@stacksjs/path": "0.75.
|
|
71
|
-
"@stacksjs/query-builder": "0.75.
|
|
72
|
-
"@stacksjs/queue": "0.75.
|
|
73
|
-
"@stacksjs/router": "0.75.
|
|
74
|
-
"@stacksjs/types": "0.75.
|
|
64
|
+
"@stacksjs/auth": "0.75.764",
|
|
65
|
+
"@stacksjs/config": "0.75.764",
|
|
66
|
+
"@stacksjs/database": "0.75.764",
|
|
67
|
+
"@stacksjs/error-handling": "0.75.764",
|
|
68
|
+
"@stacksjs/events": "0.75.764",
|
|
69
|
+
"@stacksjs/logging": "0.75.764",
|
|
70
|
+
"@stacksjs/path": "0.75.764",
|
|
71
|
+
"@stacksjs/query-builder": "0.75.764",
|
|
72
|
+
"@stacksjs/queue": "0.75.764",
|
|
73
|
+
"@stacksjs/router": "0.75.764",
|
|
74
|
+
"@stacksjs/types": "0.75.764"
|
|
75
75
|
}
|
|
76
76
|
}
|
package/dist/peer.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/** The socket peer of the request the caller is handling, when it was captured. */
|
|
2
|
-
export declare function capturedSocketPeer(): SocketPeer | null;
|
|
3
|
-
/**
|
|
4
|
-
* Start capturing the socket peer of each request to the next server this
|
|
5
|
-
* process starts. Idempotent, and it puts `Bun.serve` back as soon as that
|
|
6
|
-
* server is listening.
|
|
7
|
-
*/
|
|
8
|
-
export declare function captureSocketPeers(): void;
|
|
9
|
-
/** Put `Bun.serve` back without waiting for a server to start. */
|
|
10
|
-
export declare function releaseSocketPeerCapture(): void;
|
|
11
|
-
/**
|
|
12
|
-
* `server`, answering `requestIP` from the captured peer when it cannot
|
|
13
|
-
* answer for the request it is given.
|
|
14
|
-
*/
|
|
15
|
-
export declare function peerAwareServer(server: unknown): PeerServer;
|
|
16
|
-
export declare interface SocketPeer {
|
|
17
|
-
address: string
|
|
18
|
-
port: number
|
|
19
|
-
family?: string
|
|
20
|
-
}
|
|
21
|
-
export declare interface PeerServer {
|
|
22
|
-
requestIP: (request: Request) => SocketPeer | null
|
|
23
|
-
}
|