@stacksjs/debugbar 0.0.1-stage → 0.75.733
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/LICENSE.md +21 -0
- package/README.md +43 -0
- package/dist/api.d.ts +30 -0
- package/dist/assets.d.ts +9 -0
- package/dist/client/debugbar.js +234 -0
- package/dist/collectors/auth.d.ts +2 -0
- package/dist/collectors/cache.d.ts +2 -0
- package/dist/collectors/environment.d.ts +4 -0
- package/dist/collectors/events.d.ts +2 -0
- package/dist/collectors/exceptions.d.ts +5 -0
- package/dist/collectors/index.d.ts +5 -0
- package/dist/collectors/jobs.d.ts +2 -0
- package/dist/collectors/logs.d.ts +2 -0
- package/dist/collectors/mail.d.ts +4 -0
- package/dist/collectors/messages.d.ts +2 -0
- package/dist/collectors/queries.d.ts +18 -0
- package/dist/collectors/request.d.ts +2 -0
- package/dist/collectors/route.d.ts +2 -0
- package/dist/collectors/timeline.d.ts +4 -0
- package/dist/collectors/views.d.ts +11 -0
- package/dist/collectors.d.ts +47 -0
- package/dist/context.d.ts +44 -0
- package/dist/endpoints.d.ts +24 -0
- package/dist/frames.d.ts +13 -0
- package/dist/guard.d.ts +37 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +10 -0
- package/dist/inject.d.ts +40 -0
- package/dist/middleware.d.ts +14 -0
- package/dist/peer.d.ts +23 -0
- package/dist/redact.d.ts +36 -0
- package/dist/runtime.d.ts +47 -0
- package/dist/sql.d.ts +15 -0
- package/dist/state.d.ts +28 -0
- package/dist/storage.d.ts +18 -0
- package/dist/tsconfig.json +5 -0
- package/dist/types.d.ts +145 -0
- package/dist/user.d.ts +7 -0
- package/dist/views.d.ts +18 -0
- package/package.json +63 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { DebugbarProcess, DebugbarRequestKind, ResolvedDebugbarConfig } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* A record id: when it was made, then randomness.
|
|
4
|
+
*
|
|
5
|
+
* Time first, in fixed-width base 36, so ids sort by age as plain strings.
|
|
6
|
+
* That ordering is the store's index: the newest records are the last file
|
|
7
|
+
* names, with no index file to keep in step between two processes.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createRecordId(now?: number): string;
|
|
10
|
+
export declare function isRecordId(value: unknown): value is string;
|
|
11
|
+
/** The collection the caller is running inside, or undefined. */
|
|
12
|
+
export declare function currentCollection(): Collection | undefined;
|
|
13
|
+
/** Run `fn` with `collection` as the one in flight. */
|
|
14
|
+
export declare function runWithCollection<T>(collection: Collection, fn: () => T): T;
|
|
15
|
+
/**
|
|
16
|
+
* Make `collection` the one in flight for the rest of the current async
|
|
17
|
+
* context. For a server whose request hook returns before the work it starts,
|
|
18
|
+
* where there is no function to wrap. Call it before the hook's first `await`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function enterCollection(collection: Collection): void;
|
|
21
|
+
/** Run `fn` outside any collection, so the debugbar's own work is not recorded. */
|
|
22
|
+
export declare function withoutCollection<T>(fn: () => T): T;
|
|
23
|
+
export declare class Collection {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly process: DebugbarProcess;
|
|
26
|
+
readonly request: Request;
|
|
27
|
+
readonly url: URL;
|
|
28
|
+
readonly config: ResolvedDebugbarConfig;
|
|
29
|
+
readonly startedAt: number;
|
|
30
|
+
readonly startedMs: number;
|
|
31
|
+
kind: DebugbarRequestKind;
|
|
32
|
+
finished: boolean;
|
|
33
|
+
duration: number | undefined;
|
|
34
|
+
private bags;
|
|
35
|
+
private overflow;
|
|
36
|
+
private values;
|
|
37
|
+
constructor(request: Request, process: DebugbarProcess, config: ResolvedDebugbarConfig);
|
|
38
|
+
elapsed(): number;
|
|
39
|
+
push<T>(name: string, entry: T, limit?: number): void;
|
|
40
|
+
list<T>(name: string): T[];
|
|
41
|
+
dropped(name: string): number;
|
|
42
|
+
set(name: string, value: unknown): void;
|
|
43
|
+
get<T>(name: string): T | undefined;
|
|
44
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { DebugbarRuntime } from './runtime';
|
|
2
|
+
import type { DebugbarUser } from '@stacksjs/types';
|
|
3
|
+
export declare function isDebugbarPath(path: string): boolean;
|
|
4
|
+
/** The users "Sign in as" offers, from the app's resolver or the users table. */
|
|
5
|
+
export declare function signInAsUsers(runtime: DebugbarRuntime): Promise<DebugbarUser[]>;
|
|
6
|
+
/**
|
|
7
|
+
* Answer a request under `/__debugbar/`.
|
|
8
|
+
*
|
|
9
|
+
* `runtime` is what `bootDebugbar` returned. Without one there is no
|
|
10
|
+
* debugbar, and every path answers 404 exactly as an unknown path would.
|
|
11
|
+
*/
|
|
12
|
+
export declare function handleDebugbarRequest(request: Request, runtime: DebugbarRuntime | undefined, context?: EndpointContext): Promise<Response>;
|
|
13
|
+
export declare const DEBUGBAR_PREFIX: '/__debugbar/';
|
|
14
|
+
export declare const DEBUGBAR_TOKEN_HEADER: 'x-debugbar-token';
|
|
15
|
+
/** The three things "Sign in as" needs from `@stacksjs/auth`. */
|
|
16
|
+
export declare interface SignInAuth {
|
|
17
|
+
Auth: { loginUsingId: (id: number) => Promise<{ user: unknown, token: unknown } | null> }
|
|
18
|
+
authCookie: (token: string, options?: { secure?: boolean }) => string
|
|
19
|
+
clearAuthCookie: (options?: { secure?: boolean }) => string
|
|
20
|
+
}
|
|
21
|
+
export declare interface EndpointContext {
|
|
22
|
+
peer?: string | null
|
|
23
|
+
auth?: () => Promise<SignInAuth>
|
|
24
|
+
}
|
package/dist/frames.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { StackFrame } from './types';
|
|
2
|
+
export declare function setProjectRoot(root: string): void;
|
|
3
|
+
/** A file inside the project that is not the framework or a dependency. */
|
|
4
|
+
export declare function isAppFile(file: string): boolean;
|
|
5
|
+
export declare function displayPath(file: string): string;
|
|
6
|
+
export declare function parseStack(stack: string | undefined, limit?: number): StackFrame[];
|
|
7
|
+
/**
|
|
8
|
+
* `app/Actions/CarIndexAction.ts:14` for the first application frame of the
|
|
9
|
+
* current stack, or undefined when the caller is not application code.
|
|
10
|
+
*/
|
|
11
|
+
export declare function callerSource(): string | undefined;
|
|
12
|
+
/** The source lines around `line` of a project file, for an exception. */
|
|
13
|
+
export declare function sourceExcerpt(file: string, line: number, radius?: number): Promise<{ file: string, line: number, start: number, lines: string[] } | undefined>;
|
package/dist/guard.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may talk to the debugbar.
|
|
3
|
+
*
|
|
4
|
+
* A dev server is often reachable from more than the machine it runs on: a
|
|
5
|
+
* `0.0.0.0` bind, a tunnel, a phone on the same network. The records hold
|
|
6
|
+
* request data and one endpoint issues sign-in tokens, so by default
|
|
7
|
+
* everything under `/__debugbar/` answers only a client on this machine,
|
|
8
|
+
* asking for this machine by a local name.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isLoopbackAddress(address: string | null | undefined): boolean;
|
|
11
|
+
/** A hostname that can only resolve to this machine, or the app's own dev host. */
|
|
12
|
+
export declare function isLocalHostname(host: string | null | undefined, appUrl?: string): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Whether a request comes from this machine and asks for it by a local name.
|
|
15
|
+
*
|
|
16
|
+
* The forwarding headers are checked as well as the peer because a tunnel or
|
|
17
|
+
* a reverse proxy connects from loopback on behalf of somebody who is not.
|
|
18
|
+
* The Host check closes DNS rebinding: a page on another origin can point a
|
|
19
|
+
* name it controls at 127.0.0.1, and its requests then arrive from loopback
|
|
20
|
+
* carrying that name.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isLocalRequest(request: Request, options?: LocalRequestOptions): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Whether a state-changing request was made by a page of this same origin.
|
|
25
|
+
*
|
|
26
|
+
* A browser says so itself: `Sec-Fetch-Site` on every request, `Origin` on
|
|
27
|
+
* every cross-origin or non-GET one. A request carrying neither did not come
|
|
28
|
+
* from a browser page, and is judged by the token check alone.
|
|
29
|
+
*/
|
|
30
|
+
export declare function isSameOriginRequest(request: Request): boolean;
|
|
31
|
+
/** Compare two secrets without leaking where they differ. */
|
|
32
|
+
export declare function tokensMatch(given: string | null | undefined, expected: string): boolean;
|
|
33
|
+
export declare interface LocalRequestOptions {
|
|
34
|
+
allowRemote?: boolean
|
|
35
|
+
appUrl?: string
|
|
36
|
+
peer?: string | null
|
|
37
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { addMeasure, addMessage, debug, error, info, measure, startMeasure, stopMeasure, warn } from './api';
|
|
2
|
+
import { currentCollection } from './context';
|
|
3
|
+
import { debugbarEnabled } from './runtime';
|
|
4
|
+
import { registerCollector } from './collectors';
|
|
5
|
+
export type { Collector, CollectorContext, ResponseSnapshot } from './collectors';
|
|
6
|
+
export type { EndpointContext, SignInAuth } from './endpoints';
|
|
7
|
+
export type { InjectOptions } from './inject';
|
|
8
|
+
export type { DebugbarMiddleware } from './middleware';
|
|
9
|
+
export type { PeerServer, SocketPeer } from './peer';
|
|
10
|
+
export type { BootOptions, DebugbarRuntime } from './runtime';
|
|
11
|
+
export type { EnvironmentInputs } from './state';
|
|
12
|
+
export type { DebugbarStore } from './storage';
|
|
13
|
+
export type * from './types';
|
|
14
|
+
export type { ViewsDebugbar, ViewsDebugbarOptions } from './views';
|
|
15
|
+
export declare const debugbar: Debugbar;
|
|
16
|
+
export declare interface Debugbar {
|
|
17
|
+
enabled: () => boolean
|
|
18
|
+
collecting: () => boolean
|
|
19
|
+
addMessage: typeof addMessage
|
|
20
|
+
debug: typeof debug
|
|
21
|
+
info: typeof info
|
|
22
|
+
warn: typeof warn
|
|
23
|
+
error: typeof error
|
|
24
|
+
measure: typeof measure
|
|
25
|
+
startMeasure: typeof startMeasure
|
|
26
|
+
stopMeasure: typeof stopMeasure
|
|
27
|
+
addMeasure: typeof addMeasure
|
|
28
|
+
registerCollector: typeof registerCollector
|
|
29
|
+
}
|
|
30
|
+
export { addMeasure, addMessage, debug, error, info, measure, startMeasure, stopMeasure, warn } from './api';
|
|
31
|
+
export { clientBundle, resetClientBundle } from './assets';
|
|
32
|
+
export { collectors, registerCollector } from './collectors';
|
|
33
|
+
export { BUILT_IN_COLLECTOR_NAMES } from './collectors/index';
|
|
34
|
+
export { Collection, createRecordId, currentCollection, isRecordId, runWithCollection, withoutCollection } from './context';
|
|
35
|
+
export { DEBUGBAR_PREFIX, handleDebugbarRequest, isDebugbarPath, signInAsUsers } from './endpoints';
|
|
36
|
+
export { isLocalHostname, isLocalRequest, isLoopbackAddress, isSameOriginRequest } from './guard';
|
|
37
|
+
export { DEBUGBAR_ASSET_PATH, DEBUGBAR_ID_HEADER, debugbarScriptTag, injectDebugbar, isInjectableDocument, withRecordId } from './inject';
|
|
38
|
+
export { createApiDebugbarMiddleware, installApiDebugbar } from './middleware';
|
|
39
|
+
export { isSensitiveName, redact, redactBindings, redactHeaders, redactQuery, redactUrl, REDACTED } from './redact';
|
|
40
|
+
export { capturedSocketPeer, captureSocketPeers, peerAwareServer } from './peer';
|
|
41
|
+
export { bootDebugbar, debugbarEnabled, debugbarRuntime, shutdownDebugbar } from './runtime';
|
|
42
|
+
export { analyzeQueries, normalizeSql } from './sql';
|
|
43
|
+
export { isDebugbarEnabled, isProductionEnvironment, resolveDebugbarConfig } from './state';
|
|
44
|
+
export { createStore } from './storage';
|
|
45
|
+
export { createViewsDebugbar } from './views';
|
|
46
|
+
export default debugbar;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{AsyncLocalStorage as br}from"async_hooks";var hr=Symbol.for("stacks.debugbar.collection"),X=globalThis[hr]??=new br,yr=1000,me=0;function it(e=Date.now()){me=(me+1)%1296;let t=crypto.getRandomValues(new Uint32Array(2));return e.toString(36).padStart(9,"0")+me.toString(36).padStart(2,"0")+t[0].toString(36).padStart(7,"0").slice(-7)+t[1].toString(36).padStart(7,"0").slice(-6)}var wr=/^[0-9a-z]{20,32}$/;function q(e){return typeof e==="string"&&wr.test(e)}class Z{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=it(),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=yr){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 w(){let e=X.getStore();return e&&!e.finished?e:void 0}function ge(e,t){return X.run(e,t)}function at(e){X.enterWith(e)}function k(e){return X.run(void 0,e)}var xr="[redacted]",kr=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-csrf-token","x-xsrf-token","x-api-key","x-auth-token","x-debugbar-token"]),Rr=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"]),be=new Map;function L(e){let t=be.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)=>Rr.has(o))||/password|secret|token|apikey/i.test(e);if(be.size<2000)be.set(e,n);return n}function he(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 Y(e){let t={};if(!e)return t;return e.forEach((r,n)=>{let o=n.toLowerCase();t[o]=kr.has(o)||L(o)?"[redacted]":U(r,2000)}),t}function ct(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=L(r)?["[redacted]"]:e.getAll(r).map((o)=>he(o)?"[redacted]":U(o,500));t[r]=n.length===1?n[0]:n}return t}function j(e){if(!e.search)return e.pathname;let t=[];for(let[r,n]of e.searchParams){let o=L(r)||he(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 S(e,r,0,new WeakSet)}function S(e,t,r,n){if(e===null||e===void 0)return e??null;switch(typeof e){case"string":return 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 j(o);if(typeof Request<"u"&&o instanceof Request)return`[Request ${o.method} ${Cr(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)=>S(c,t,r+1,n));if(o.length>t.maxItems)u.push(`... ${o.length-t.maxItems} more`);return u}if(o instanceof Map)return S(Object.fromEntries([...o.entries()].slice(0,t.maxKeys).map(([u,c])=>[String(u),c])),t,r,n);if(o instanceof Set)return S([...o],t,r,n);let s=typeof o.toJSON==="function"?ut(()=>o.toJSON()):o;if(s===null||typeof s!=="object")return S(s,t,r+1,n);if(s!==o&&Array.isArray(s))return S(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]=L(u)?"[redacted]":S(ut(()=>s[u]),t,r+1,n)}return i}finally{n.delete(o)}}function ut(e){try{return e()}catch{return"[unreadable]"}}function Cr(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 he(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 Er(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 v(e,t,r="info",n){let o=w();if(!o)return;o.push("messages",{level:r,label:t,message:Er(e).slice(0,4000),context:n===void 0?void 0:m(n),at:o.elapsed()})}function xe(e,t){v(e,void 0,"debug",t)}function ke(e,t){v(e,void 0,"info",t)}function Re(e,t){v(e,void 0,"warning",t)}function Ce(e,t){v(e,void 0,"error",t)}function Ee(e,t){let r=w();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=w(),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 ve(e,t,r,n="measure"){w()?.push("measures",{label:e,start:t,duration:r,group:n})}function De(e,t){let r=w();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 R=new Map,ee=new Map,C;function lt(e,t){if(!e.install)return;try{let r=e.install(t),n=(o)=>{if(typeof o!=="function")return;if(C!==t||R.get(e.name)!==e)o();else ee.set(e.name,o)};if(r instanceof Promise)r.then(n,()=>{});else n(r)}catch{}}function Ae(e){let t=ee.get(e);ee.delete(e);try{t?.()}catch{}}function _(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),R.set(e.name,e),C)lt(e,C);return()=>{if(R.get(e.name)!==e)return;Ae(e.name),R.delete(e.name)}}function Pe(){return[...R.values()]}function dt(e,t){if(C)return;C={config:e,process:t,current:w};for(let r of R.values())lt(r,C)}function ft(){C=void 0;for(let e of[...ee.keys()])Ae(e)}function pt(e){if(!C)return;for(let t of R.values()){if(!t.begin)continue;try{t.begin(e)}catch{}}}async function mt(e,t){let r={},n={};for(let o of R.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 tr}from"crypto";import{chmodSync as wn,existsSync as xn,readFileSync as kn,writeFileSync as Rn}from"fs";import{join as rr}from"path";import Cn from"process";import{config as Ke}from"@stacksjs/config";import{projectPath as En,storagePath as Sn}from"@stacksjs/path";var Q=new Map,Sr=3000;function te(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 vr(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 re(e){try{let t=await import("@stacksjs/auth"),r=vr(e,t.authCookieToken);if(!r)return{user:null,via:"none"};let n=Q.get(r.token);if(n&&Date.now()-n.at<Sr)return{user:n.user,via:r.via};let o=await k(()=>t.Auth.getUserFromToken(r.token)),s=te(o);if(Q.size>100)Q.clear();return Q.set(r.token,{user:s,at:Date.now()}),{user:s,via:r.via}}catch{return{user:null,via:"none"}}}function Me(){Q.clear()}var gt={name:"auth",label:"Auth",async collect(e){let{user:t,via:r}=await re(e.request);return{authenticated:t!==null,guard:r==="none"?"guest":r==="bearer"?"token":"cookie",user:t}}};import{subscribe as Dr,unsubscribe as Ar}from"diagnostics_channel";var bt="stacks:cache:operation",ht={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 Dr(bt,t),()=>{Ar(bt,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 ne,readFileSync as H,statSync as Ir}from"fs";import{join as W,resolve as kt}from"path";import oe from"process";import{config as Rt}from"@stacksjs/config";var yt={name:"@stacksjs/debugbar",type:"module",sideEffects:!1,version:"0.75.733",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.39"},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 je from"process";var Te=new Set(["production","prod","live"]),Mr=new Set(["local","development","dev"]);function D(e){return typeof e==="string"?e.trim().toLowerCase():""}function wt(e={}){let t=e.env??je.env,r=D(t.APP_ENV);if(Te.has(r)||Te.has(D(e.appEnv)))return!0;return!r&&Te.has(D(t.NODE_ENV))}function Ie(e={}){let t=e.env??je.env;return D(t.APP_ENV)||D(e.appEnv)||D(t.NODE_ENV)}function Tr(e){let t=D((e.env??je.env).APP_DEBUG);return t==="false"||t==="0"||t==="off"||t==="no"}function Ne(e,t={}){if(wt(t))return!1;if(e?.enabled===!1)return!1;if(e?.enabled===!0)return!0;return Mr.has(Ie(t))&&!Tr(t)}function Oe(e,t){let r=e?.queries??{};return{...e,storage:{path:e?.storage?.path||t,maxRequests:qe(e?.storage?.maxRequests,200)},except:Array.isArray(e?.except)?e.except.filter((n)=>typeof n==="string"):[],queries:{slowThresholdMs:qr(r.slowThresholdMs,100),nPlusOneThreshold:Math.max(2,qe(r.nPlusOneThreshold,5)),backtrace:r.backtrace!==!1,maxQueries:qe(r.maxQueries,500)}}}function qe(e,t){let r=Number(e);return Number.isFinite(r)&&r>=1?Math.floor(r):t}function qr(e,t){let r=Number(e);return Number.isFinite(r)&&r>=0?r:t}var jr=/^\/(?:__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 xt(e,t){if(jr.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 Nr(e){try{let t=W(e,".git");if(!ne(t))return{};if(Ir(t).isFile()){let u=/^gitdir:\s*(.+)$/m.exec(H(t,"utf8"));if(!u)return{};t=kt(e,u[1].trim())}let r=H(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=ne(s)?kt(t,H(s,"utf8").trim()):t;for(let u of[t,i]){let c=W(u,n[1]);if(ne(c))return{branch:o,sha:H(c,"utf8").trim().slice(0,12)}}let a=W(i,"packed-refs");if(ne(a)){let u=H(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 z;function Or(){if(!z||Date.now()-z.at>5000)z={...Nr(oe.cwd()),at:Date.now()};return{branch:z.branch,sha:z.sha}}function $r(){let e=(r)=>{try{return r()}catch{return}},t=Rt;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 Ct={name:"environment",label:"Environment",collect(e){return{environment:Ie({appEnv:Rt.app?.env})||"unknown",process:e.process,pid:oe.pid,stacks:yt.version,bun:typeof Bun<"u"?Bun.version:void 0,platform:`${oe.platform} ${oe.arch}`,git:Or(),config:$r()}}};var Et={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 Br}from"fs/promises";import{relative as Ur,sep as g}from"path";import Lr from"process";var St;function vt(e){St=e.endsWith(g)?e.slice(0,-1):e}function se(){return St??=Lr.cwd()}var _r=[`${g}node_modules${g}`,`${g}storage${g}framework${g}`,`${g}pantry${g}`];function Dt(e){let t=se();if(!e.startsWith(t+g))return!1;let r=e.slice(t.length);return!_r.some((n)=>r.includes(n))}function $e(e){let t=se();return e.startsWith(t+g)?Ur(t,e):e}var At=/^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?((?:\/|[A-Za-z]:\\|file:\/\/)[^)]*?):(\d+)(?::(\d+))?\)?\s*$/;function Pt(e,t=30){if(!e)return[];let r=[];for(let n of e.split(`
|
|
4
|
+
`)){let o=At.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:$e(s),line:Number(o[3]),column:o[4]?Number(o[4]):void 0,app:Dt(s)}),r.length>=t)break}return r}function ie(){let e={},t=Error.stackTraceLimit;Error.stackTraceLimit=40;try{Error.captureStackTrace(e,ie)}finally{Error.stackTraceLimit=t}if(!e.stack)return;for(let r of e.stack.split(`
|
|
5
|
+
`)){let n=At.exec(r);if(!n)continue;let o=n[2].replace(/^file:\/\//,"");if(Dt(o))return`${$e(o)}:${n[3]}`}return}async function Mt(e,t,r=5){let n=e.startsWith(g)?e:`${se()}${g}${e}`;if(!n.startsWith(se()+g)||n.includes(`${g}..${g}`))return;try{let o=(await Br(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:$e(n),line:t,start:s,lines:o.slice(s-1,i).map((a)=>a.length>400?`${a.slice(0,400)}...`:a)}}catch{return}}var Tt=new WeakMap;function Be(e,t,r){let n=t instanceof Error?t:Error(typeof t==="string"?t:"Non-error value thrown"),o=Tt.get(e);if(!o)o=new WeakSet,Tt.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:Pt(n.stack),context:r===void 0?void 0:m(r,{maxDepth:4})},50)}var qt={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 Mt(n.file,n.line)}return t}};var jt={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 Qr=/\u001B\[[0-9;]*[A-Za-z]/g,It={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(Qr,"").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 Hr,unsubscribe as Wr}from"diagnostics_channel";var Nt="stacks:mail:sent";function Ot(e){return(Array.isArray(e)?e:e?[e]:[]).map((r)=>typeof r==="string"?r:r?.address??"").filter(Boolean).slice(0,50)}var $t={name:"mail",label:"Mail",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||!o?.message)return;n.push("mail",{to:Ot(o.message.to),from:Ot(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 Hr(Nt,t),()=>{Wr(Nt,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 Ut(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 zr(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 Le(e,t){let r=new Map,n=new Map,o=[];for(let l of e){let f=Ut(l.sql),b=`${l.sql}\x00${Vr(l.params)}`;o.push({exact:b,shape:f}),r.set(b,(r.get(b)??0)+1);let T=n.get(f);if(T)T.count++;else n.set(f,{count:1,sample:l.sql,source:l.source})}let s=0,i=0,a=0,u=0;e.forEach((l,f)=>{let{exact:b,shape:T}=o[f],d=r.get(b)??1,p=n.get(T)?.count??1;if(s+=l.duration,d>1)l.duplicates=d;if(p>1)l.similar=p;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,f])=>f.count>=t.nPlusOneThreshold&&zr(l)).map(([l,f])=>({shape:l,count:f.count,sample:f.sample,source:f.source})).sort((l,f)=>f.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 Vr(e){try{return JSON.stringify(e)??""}catch{return""}}function Fr(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:ie()})}function Kr(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 Gr({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():Kr(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))Fr(s,o.sql)}},onQueryEnd(o){n(o,!1)},onQueryError(o){n(o,!0)},onModelQuery(o){n(o,o.error!==void 0,t.queries.backtrace?ie:void 0)}}}var _e,Lt={name:"queries",label:"Queries",async install(e){let{ensureModelQueryObservation:t,observeModelQueries:r,registerPersistentQueryHooks:n}=await import("@stacksjs/query-builder");_e=t;let{onModelQuery:o,...s}=Gr(e),i=n(s),a=r(o);return()=>{_e=void 0,i(),a()}},begin(){_e?.()},collect(e){return Le(e.list("queries"),{slowThresholdMs:e.config.queries.slowThresholdMs,nPlusOneThreshold:e.config.queries.nPlusOneThreshold,dropped:e.dropped("queries")})}};function Jr(e){let t=e,r=t.jsonBody??t.formBody;return r&&typeof r==="object"?m(r,{maxDepth:5}):void 0}var _t={name:"request",label:"Request",collect(e,t){let{request:r,url:n}=e,o=t.headers.get("content-length");return{method:r.method,url:j(n),path:n.pathname,host:n.host,query:ye(n.searchParams),headers:Y(r.headers),cookies:ct(r.headers.get("cookie")),contentType:r.headers.get("content-type")??void 0,input:Jr(r),response:{status:t.status,headers:Y(t.headers),contentType:t.headers.get("content-type")??void 0,size:o&&/^\d+$/.test(o)?Number(o):void 0}}}};import{subscribe as Xr,unsubscribe as Zr}from"diagnostics_channel";var Qt="stacks:router:route-matched",Ht={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 Xr(Qt,t),()=>{Zr(Qt,t)}},collect(e){return e.get("route")}};import Yr from"process";function en(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 Wt={name:"timeline",label:"Timeline",collect(e,t){let r=e.elapsed(),n=[],o=en(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=Yr.memoryUsage();return{duration:r,measures:n,memory:{rss:a.rss,heapUsed:a.heapUsed}}}};import{existsSync as tn}from"fs";import{join as zt}from"path";import rn from"process";var I=new Map,Vt;function Ft(e){Vt=e,I.clear()}function nn(e){if(I.has(e))return I.get(e);let t=Vt??zt(rn.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(tn(zt(t,s))){o=`resources/views/${s}`;break}}if(I.size>500)I.clear();return I.set(e,o),o}var Kt={name:"views",label:"Views",collect(e,t){if(e.process!=="views")return;return{template:nn(e.url.pathname),layout:t.headers.get("x-stx-layout")??void 0,fragment:t.kind==="fragment",renderMs:e.elapsed()}}};var Qe={messages:Bt,timeline:Wt,queries:Lt,exceptions:qt,logs:It,views:Kt,route:Ht,events:Et,cache:ht,mail:$t,jobs:jt,auth:gt,request:_t,environment:Ct};function Gt(e){return Object.keys(Qe).filter((t)=>e.collectors?.[t]!==!1).map((t)=>Qe[t])}var on=Object.keys(Qe);import{AsyncLocalStorage as sn}from"async_hooks";var an=Symbol.for("stacks.debugbar.socketPeer"),Xt=globalThis[an]??=new sn,ae=!1,He;function Zt(){return Xt.getStore()??null}function We(){if(ae||typeof Bun>"u"||typeof Bun.serve!=="function")return;ae=!0;let e=Bun.serve,t=()=>{if(Bun.serve===r)Bun.serve=e;ae=!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 f=null;try{f=c?.requestIP?.(u)??null}catch{}return Xt.run(f,()=>Reflect.apply(i,this,[u,c,...l]))}},...s]);return t(),a};try{Bun.serve=r}catch{ae=!1}}function Yt(){He?.()}var Jt=new WeakMap;function ze(e){let t=e,r=t&&typeof t==="object"?Jt.get(t):void 0;if(r)return r;let n={requestIP(o){let s=null;try{s=t?.requestIP?.(o)??null}catch{}return s??Zt()}};if(t&&typeof t==="object")Jt.set(t,n);return n}import{existsSync as un,mkdirSync as cn,writeFileSync as ln}from"fs";import{mkdir as dn,readdir as fn,readFile as pn,rename as mn,rm as gn,unlink as bn,writeFile as er}from"fs/promises";import{join as N}from"path";import hn from"process";function Ve(e){try{cn(e,{recursive:!0});let t=N(e,".gitignore");if(!un(t))ln(t,`*
|
|
7
|
+
!.gitignore
|
|
8
|
+
`)}catch{}}var yn=/^([0-9a-z]{20,32})\.json$/;function Fe(e){let{directory:t}=e,r=Math.max(1,e.maxRequests),n=new Map,o,s=0,i=Promise.resolve();function a(){return o??=(async()=>{await dn(t,{recursive:!0}),await er(N(t,".gitignore"),`*
|
|
9
|
+
!.gitignore
|
|
10
|
+
`,{flag:"wx"}).catch(()=>{})})().catch(()=>{o=void 0})}async function u(){try{let d=[];for(let p of await fn(t)){let h=yn.exec(p);if(h)d.push(h[1])}return d.sort()}catch{return[]}}async function c(){let d=await u(),p=d.slice(0,Math.max(0,d.length-r));await Promise.all(p.map((h)=>bn(N(t,`${h}.json`)).catch(()=>{})));for(let h of p)n.delete(h);return p.length}async function l(d){if(!q(d.id))return;let p=(async()=>{try{await a();let h=N(t,`${d.id}.json`),x=`${h}.${hn.pid}.tmp`;if(await er(x,JSON.stringify(d)),await mn(x,h),n.set(d.id,{startedAt:d.startedAt,summary:d.summary}),++s>=20||n.size>r)s=0,await c()}catch{}})();return i=Promise.allSettled([i,p]),p}async function f(d){if(!q(d))return null;try{let p=JSON.parse(await pn(N(t,`${d}.json`),"utf8"));return p&&p.id===d?p:null}catch{return null}}async function b(d=50){let p=(await u()).reverse().slice(0,Math.max(1,Math.min(d,r))),h=[];for(let x of p){let E=n.get(x);if(!E){let pe=await f(x);if(!pe)continue;E={startedAt:pe.startedAt,summary:pe.summary},n.set(x,E)}h.push({id:x,...E})}if(n.size>r*2){let x=new Set(p);for(let E of n.keys())if(!x.has(E))n.delete(E)}return h}async function T(){n.clear();let d=await u();await Promise.all(d.map((p)=>gn(N(t,`${p}.json`),{force:!0}).catch(()=>{})))}return{directory:t,write:l,read:f,list:b,clear:T,prune:c,async flush(){await i}}}var B,Ge=new Set,nr=[];function or(){try{let e=Ke.app;return{env:e?.env,url:e?.url}}catch{return{}}}function ue(e={}){let t=or();return Ne(e.config??Ke.debugbar,{env:e.env,appEnv:e.appEnv??t.env})}function V(e,t={}){if(B)return B;if(!ue(t))return;let r=t.root??En(),n=Oe(t.config??Ke.debugbar,Sn("framework/debugbar"));vt(r),Ft(rr(r,"resources/views"));let o=new Set(Pe().map((s)=>s.name));for(let s of Gt(n)){if(o.has(s.name))continue;nr.push(_(s)),Ge.add(s.name)}return dt(n,e),Ve(n.storage.path),B={config:n,store:Fe({directory:n.storage.path,maxRequests:n.storage.maxRequests}),process:e,appUrl:or().url},B}function vn(){return B}function Dn(){ft();for(let e of nr.splice(0))e();Ge.clear(),Yt(),B=void 0,O=void 0}function ce(e,t){return!xt(t,e.config.except)}function le(e,t){let r=new Z(t,e.process,e.config);return pt(r),r}function An(e,t,r){let{queries:n,route:o,views:s,auth:i}=r,a=(u)=>Array.isArray(r[u])?r[u].length:0;return{method:e.request.method,url:j(e.url),path:e.url.pathname,status:t.status,kind:t.kind,process:e.process,duration:e.elapsed(),memory:Math.round(Cn.memoryUsage().rss/1048576*10)/10,queries:n?.count??0,queryDuration:n?.duration??0,logs:a("logs")+a("messages"),exceptions:a("exceptions"),route:o?`${o.method} ${o.path}`:s?.template,user:i?.user??void 0}}function F(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 k(async()=>{try{let{sections:s,labels:i}=await mt(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:An(t,o,s),collectors:s,...Object.keys(a).length>0&&{labels:a}};await e.store.write(u)}catch{}})}var O;function de(e){if(O)return O;let t=rr(e.config.storage.path,".token");try{if(xn(t)){let n=kn(t,"utf8").trim();if(/^[a-f0-9]{48}$/.test(n))return O=n}let r=tr(24).toString("hex");return Ve(e.config.storage.path),Rn(t,r,{mode:384}),wn(t,384),O=r}catch{return O=tr(24).toString("hex")}}import{existsSync as Pn}from"fs";import{join as sr}from"path";var Je,Xe="0";async function Mn(){let e=sr(import.meta.dir,"client","debugbar.js"),t;if(Pn(e))t=await Bun.file(e).text();else{let r=await Bun.build({entrypoints:[sr(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 ir(){return Xe}function K(){return Je??=Mn().catch((e)=>{throw Je=void 0,e})}function Tn(){Je=void 0}function G(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/^127(?:\.\d{1,3}){3}$/.test(r)}function Ze(e,t){if(!e)return!1;let r=e.trim().toLowerCase();if(r=r.startsWith("[")?r.slice(1,r.indexOf("]")):r.replace(/:\d+$/,""),G(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")||G(n)))return!0}catch{}return!1}function A(e,t={}){if(t.allowRemote===!0)return!0;if(t.peer!==void 0&&!G(t.peer))return!1;let r=e.headers.get("x-forwarded-for");if(r&&!r.split(",").every((s)=>G(s)))return!1;let n=e.headers.get("x-forwarded-host");if(n&&!n.split(",").every((s)=>Ze(s,t.appUrl)))return!1;let o=e.headers.get("host");if(!o)try{o=new URL(e.url).host}catch{return!1}return Ze(o,t.appUrl)}function Ye(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("x-forwarded-host"),e.headers.get("host")].flatMap((s)=>s?s.split(","):[]).map((s)=>s.trim().toLowerCase());try{o.push(new URL(e.url).host.toLowerCase())}catch{}if(!o.includes(n))return!1}return!0}function ar(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 et="/__debugbar/",qn="x-debugbar-token";function ur(e){return e.auth?e.auth():import("@stacksjs/auth")}var cr={"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin","X-Robots-Tag":"noindex"};function P(e,t=200,r={}){return new Response(JSON.stringify(e),{status:t,headers:{...cr,"Content-Type":"application/json; charset=utf-8",...r}})}function y(e,t){return P({error:t},e)}function tt(e){return e.startsWith(et)}async function jn(){let{db:e}=await import("@stacksjs/database/runtime");return(await e.selectFrom("users").selectAll().limit(25).execute()).map(te).filter((r)=>r!==null)}async function rt(e){let t=e.config.signInAs?.users,r=await k(async()=>typeof t==="function"?await t():await jn());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 lr(e){return e.config.signInAs?.enabled!==!1}function nt(e,t){if(!Ye(e))return y(403,"Cross-origin requests are not accepted.");if(!ar(e.headers.get(qn),de(t)))return y(403,"Missing or invalid debugbar token. Reload the page.");return}function dr(e){return(e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()??new URL(e.url).protocol.replace(":",""))==="https"}async function In(e,t,r){if(!lr(t))return y(404,"Sign in as is disabled.");let n=nt(e,t);if(n)return n;let o;try{o=(await e.json())?.id}catch{return y(400,"Expected a JSON body with an id.")}if(typeof o!=="number"&&typeof o!=="string")return y(400,"Expected a JSON body with an id.");let s=(await rt(t)).find((c)=>String(c.id)===String(o));if(!s)return y(404,"That user is not offered for sign in.");let i=await ur(r),a=await k(()=>i.Auth.loginUsingId(s.id));if(!a)return y(404,"That user no longer exists.");Me();let u=String(a.token);return P({token:u,user:te(a.user)??s,tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":i.authCookie(u,{secure:dr(e)})})}async function Nn(e,t,r){let n=nt(e,t);if(n)return n;let o=await ur(r);return Me(),P({tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":o.clearAuthCookie({secure:dr(e)})})}async function On(e,t){let r=lr(t),[n,o]=await Promise.all([r?rt(t).catch(()=>[]):Promise.resolve([]),re(e)]);return P({enabled:r,users:n,current:o.user,tokenStorageKey:t.config.signInAs?.tokenStorageKey})}async function $n(e){let t=await K(),r=`"${t.version}"`,n={...cr,"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 ot(e,t,r={}){if(!t)return new Response("Not Found",{status:404});if(!A(e,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:r.peer}))return y(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(et.length).replace(/\/+$/,""),s=e.method.toUpperCase();try{if(o==="assets/debugbar.js"&&(s==="GET"||s==="HEAD"))return await $n(e);if(o==="requests"){if(s==="GET")return P({requests:await t.store.list(Number(n.searchParams.get("limit"))||50)});if(s==="DELETE"){let i=nt(e,t);if(i)return i;return await t.store.clear(),P({cleared:!0})}return y(405,"Method not allowed.")}if(o.startsWith("requests/")&&s==="GET"){let i=o.slice(9),a=q(i)?await t.store.read(i):null;return a?P(a):y(404,"No record with that id.")}if(o==="users"&&s==="GET")return await On(e,t);if(o==="sign-in-as"&&s==="POST")return await In(e,t,r);if(o==="sign-out"&&s==="POST")return await Nn(e,t,r)}catch(i){return y(500,i instanceof Error?i.message:"The debugbar failed to answer.")}return y(404,"Not found.")}var M="X-Debugbar-Id",Bn="/__debugbar/assets/debugbar.js";function fe(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function pr(e){return`<script src="/__debugbar/assets/debugbar.js?v=${fe(e.version)}" defer data-stacks-debugbar data-id="${fe(e.id)}" data-token="${fe(e.token)}" data-options="${fe(JSON.stringify(e.client??{}))}"></script>`}function mr(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 st(e,t){if(!mr(e))return;let r=pr(t),n=!1,o=new HTMLRewriter().on("body",{element(s){if(n)return;n=!0,s.append(r,{html:!0})}}).transform(e);return o.headers.delete("content-length"),o}function J(e,t){let r=fr(e,"X-Debugbar-Id",t),n=r.headers.get("server-timing"),o=`debugbar;desc="${t}"`;return fr(r,"Server-Timing",n?`${n}, ${o}`:o)}function fr(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 Un from"process";function Ln(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(M.toLowerCase()))return;try{e.headers.set("Access-Control-Expose-Headers",t?`${t}, ${M}`:M)}catch{}}function gr(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()}if(r.method==="OPTIONS"||!ce(e,o)||!A(r,t))return n();let s=le(e,r),i=r;if(i._startNs==null)i._startNs=Un.hrtime.bigint();let a;try{a=await ge(s,n)}catch(c){throw Be(s,c),F(e,s,{status:500,headers:new Headers}),c}if(!(a instanceof Response))return a;let u=J(a,s.id);return Ln(u),F(e,s,u),u}}function _n(e,t={}){let r=V("api",t);if(!r)return!1;return e.use(gr(r)),!0}function Qn(e={}){let t=V("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};K().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(tt(a))return ot(s,t,{peer:o(s,i)});if(!ce(t,a))return;if(!A(s,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:o(s,i)}))return;let u=le(t,s);r.set(s,u),at(u);return},onResponse(s,i){let a=r.get(s);if(!a)return;if(r.delete(s),i.headers.has(M)){a.finished=!0;return}let u=i.headers.get("content-type")?.toLowerCase()??"",c=u.startsWith("text/html");if(!c&&!u.includes("json")){a.finished=!0;return}let f=i.headers.get("x-stx-fragment")==="true"?"fragment":c?"page":"api",b=i;if(f==="page")b=st(i,{id:a.id,token:de(t),version:ir(),client:n})??i;return b=J(b,a.id),F(t,a,b,f),b}}}var Hn={enabled:()=>ue(),collecting:()=>w()!==void 0,addMessage:v,debug:xe,info:ke,warn:Re,error:Ce,measure:De,startMeasure:Ee,stopMeasure:Se,addMeasure:ve,registerCollector:_},Si=Hn;export{on as BUILT_IN_COLLECTOR_NAMES,Z as Collection,Bn as DEBUGBAR_ASSET_PATH,M as DEBUGBAR_ID_HEADER,et as DEBUGBAR_PREFIX,xr as REDACTED,ve as addMeasure,v as addMessage,Le as analyzeQueries,V as bootDebugbar,We as captureSocketPeers,Zt as capturedSocketPeer,K as clientBundle,Pe as collectors,gr as createApiDebugbarMiddleware,it as createRecordId,Fe as createStore,Qn as createViewsDebugbar,w as currentCollection,xe as debug,Hn as debugbar,ue as debugbarEnabled,vn as debugbarRuntime,pr as debugbarScriptTag,Si as default,Ce as error,ot as handleDebugbarRequest,ke as info,st as injectDebugbar,_n as installApiDebugbar,Ne as isDebugbarEnabled,tt as isDebugbarPath,mr as isInjectableDocument,Ze as isLocalHostname,A as isLocalRequest,G as isLoopbackAddress,wt as isProductionEnvironment,q as isRecordId,Ye as isSameOriginRequest,L as isSensitiveName,De as measure,Ut as normalizeSql,ze as peerAwareServer,m as redact,we as redactBindings,Y as redactHeaders,ye as redactQuery,j as redactUrl,_ as registerCollector,Tn as resetClientBundle,Oe as resolveDebugbarConfig,ge as runWithCollection,Dn as shutdownDebugbar,rt as signInAsUsers,Ee as startMeasure,Se as stopMeasure,Re as warn,J as withRecordId,k as withoutCollection};
|
package/dist/inject.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare function debugbarScriptTag(options: InjectOptions): string;
|
|
2
|
+
/** A full, uncompressed HTML document: the only response the script goes into. */
|
|
3
|
+
export declare function isInjectableDocument(response: Response): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* The response with the bar's script appended to its `<body>`, or undefined
|
|
6
|
+
* when it is not a document the script belongs in.
|
|
7
|
+
*
|
|
8
|
+
* Streamed through `HTMLRewriter`, so the page is not buffered, and an HTML
|
|
9
|
+
* response with no `<body>` (a partial some handler returned as `text/html`)
|
|
10
|
+
* passes through untouched.
|
|
11
|
+
*/
|
|
12
|
+
export declare function injectDebugbar(response: Response, options: InjectOptions): Response | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* `response` carrying the record id, as `X-Debugbar-Id` and as a
|
|
15
|
+
* `Server-Timing` entry.
|
|
16
|
+
*
|
|
17
|
+
* The second is for requests a page makes before the bar's script has run:
|
|
18
|
+
* the bar cannot have been watching them, but the browser keeps each
|
|
19
|
+
* response's `Server-Timing` on its resource timing entry, where the bar
|
|
20
|
+
* finds the id afterwards.
|
|
21
|
+
*/
|
|
22
|
+
export declare function withRecordId(response: Response, id: string): Response;
|
|
23
|
+
/** `response` carrying `name: value`, copied when its headers cannot be written. */
|
|
24
|
+
export declare function withHeader(response: Response, name: string, value: string): Response;
|
|
25
|
+
/**
|
|
26
|
+
* Putting the bar on a page.
|
|
27
|
+
*
|
|
28
|
+
* One `<script>` before `</body>`, on full HTML documents only. An stx router
|
|
29
|
+
* navigation answers with a fragment that is swapped into the page already
|
|
30
|
+
* showing the bar, so a fragment gets the record id as a header and nothing
|
|
31
|
+
* in its body.
|
|
32
|
+
*/
|
|
33
|
+
export declare const DEBUGBAR_ID_HEADER: 'X-Debugbar-Id';
|
|
34
|
+
export declare const DEBUGBAR_ASSET_PATH: '/__debugbar/assets/debugbar.js';
|
|
35
|
+
export declare interface InjectOptions {
|
|
36
|
+
id: string
|
|
37
|
+
token: string
|
|
38
|
+
version: string
|
|
39
|
+
client?: Record<string, unknown>
|
|
40
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { BootOptions, DebugbarRuntime } from './runtime';
|
|
2
|
+
export declare function createApiDebugbarMiddleware(runtime: DebugbarRuntime): DebugbarMiddleware;
|
|
3
|
+
/**
|
|
4
|
+
* Register the debugbar on an API router. Returns false, having registered
|
|
5
|
+
* nothing, when the debugbar is not enabled in this process.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* installApiDebugbar(route)
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function installApiDebugbar(router: { use: (handler: any) => unknown }, options?: BootOptions): boolean;
|
|
13
|
+
// eslint-disable-next-line pickier/no-unused-vars
|
|
14
|
+
export type DebugbarMiddleware = (request: Request, next: () => Response | Promise<Response>) => Promise<Response>;
|
package/dist/peer.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
}
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Whether a field, header or parameter name says its value is a secret. */
|
|
2
|
+
export declare function isSensitiveName(name: string): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Whether a bare value looks like a credential: a password hash, a JWT, or a
|
|
5
|
+
* long opaque token. For bound statement values, which carry no name.
|
|
6
|
+
*/
|
|
7
|
+
export declare function looksLikeSecret(value: string): boolean;
|
|
8
|
+
export declare function redactHeaders(headers: Headers | undefined | null): Record<string, string>;
|
|
9
|
+
/** The names of the cookies a request carried. Never their values. */
|
|
10
|
+
export declare function cookieNames(header: string | null | undefined): string[];
|
|
11
|
+
export declare function redactQuery(params: URLSearchParams): Record<string, string | string[]>;
|
|
12
|
+
/** `/reset?token=abc&page=2` to `/reset?token=[redacted]&page=2`. */
|
|
13
|
+
export declare function redactUrl(url: URL): string;
|
|
14
|
+
/**
|
|
15
|
+
* A JSON-safe copy of `value` with secrets replaced and size bounded.
|
|
16
|
+
*
|
|
17
|
+
* Bounded because the things passed in are arbitrary application data: an
|
|
18
|
+
* event payload holding a model with every relation loaded, a log call handed
|
|
19
|
+
* a request. A record must stay small enough to write and to read.
|
|
20
|
+
*/
|
|
21
|
+
export declare function redact(value: unknown, options?: RedactOptions): unknown;
|
|
22
|
+
/** Bound statement values: no names to go by, so judged by shape. */
|
|
23
|
+
export declare function redactBindings(params: readonly unknown[] | undefined): unknown[];
|
|
24
|
+
/**
|
|
25
|
+
* Everything the debugbar records passes through here before it is written,
|
|
26
|
+
* because a record sits on disk and is served to a browser. Redaction is by
|
|
27
|
+
* name where there is a name (a header, a field, a query parameter) and by
|
|
28
|
+
* shape where there is not (a bound value in a statement).
|
|
29
|
+
*/
|
|
30
|
+
export declare const REDACTED: '[redacted]';
|
|
31
|
+
export declare interface RedactOptions {
|
|
32
|
+
maxDepth?: number
|
|
33
|
+
maxKeys?: number
|
|
34
|
+
maxItems?: number
|
|
35
|
+
maxString?: number
|
|
36
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { config } from '@stacksjs/config';
|
|
2
|
+
import { Collection } from './context';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import type { DebugbarConfig } from '@stacksjs/types';
|
|
5
|
+
import type { DebugbarProcess, DebugbarRequestKind, ResolvedDebugbarConfig } from './types';
|
|
6
|
+
import type { DebugbarStore } from './storage';
|
|
7
|
+
import type { EnvironmentInputs } from './state';
|
|
8
|
+
/** Whether the debugbar would run in this process. Reads the environment and config, starts nothing. */
|
|
9
|
+
export declare function debugbarEnabled(options?: BootOptions): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Start the debugbar in this process, or do nothing and return undefined
|
|
12
|
+
* when it is not enabled. Idempotent.
|
|
13
|
+
*/
|
|
14
|
+
export declare function bootDebugbar(processName: DebugbarProcess, options?: BootOptions): DebugbarRuntime | undefined;
|
|
15
|
+
/** The running debugbar, or undefined when it is not running in this process. */
|
|
16
|
+
export declare function debugbarRuntime(): DebugbarRuntime | undefined;
|
|
17
|
+
/** Stop the debugbar and detach every hook. For tests and hot reload. */
|
|
18
|
+
export declare function shutdownDebugbar(): void;
|
|
19
|
+
/** Whether this request is one the debugbar records. */
|
|
20
|
+
export declare function shouldCollect(active: DebugbarRuntime, path: string): boolean;
|
|
21
|
+
export declare function beginCollection(active: DebugbarRuntime, request: Request): Collection;
|
|
22
|
+
/**
|
|
23
|
+
* Close a request and write its record.
|
|
24
|
+
*
|
|
25
|
+
* Synchronous up to the point the response is known, so it adds nothing a
|
|
26
|
+
* client waits on. The collectors that need I/O (who the token belongs to,
|
|
27
|
+
* the source lines around an exception) and the write itself happen after,
|
|
28
|
+
* and nothing they do can reach the response.
|
|
29
|
+
*/
|
|
30
|
+
export declare function finishCollection(active: DebugbarRuntime, collection: Collection, response: { status: number, headers: Headers }, kind?: DebugbarRequestKind): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* The secret a page must echo to use "Sign in as".
|
|
33
|
+
*
|
|
34
|
+
* Kept in the storage directory so it survives the dev server restarting
|
|
35
|
+
* under a page that is still open, and readable only by the user who runs it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function debugbarToken(active: DebugbarRuntime): string;
|
|
38
|
+
export declare interface DebugbarRuntime {
|
|
39
|
+
readonly config: ResolvedDebugbarConfig
|
|
40
|
+
readonly store: DebugbarStore
|
|
41
|
+
readonly process: DebugbarProcess
|
|
42
|
+
readonly appUrl?: string
|
|
43
|
+
}
|
|
44
|
+
export declare interface BootOptions extends EnvironmentInputs {
|
|
45
|
+
config?: DebugbarConfig
|
|
46
|
+
root?: string
|
|
47
|
+
}
|
package/dist/sql.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { QueriesSection, QueryEntry } from './types';
|
|
2
|
+
export declare function normalizeSql(sql: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Statements the framework runs about other statements, never the app's:
|
|
5
|
+
* connection pragmas, plans, and everything that touches its own query log
|
|
6
|
+
* (the write per logged statement, and the prune that follows).
|
|
7
|
+
*/
|
|
8
|
+
export declare function isBookkeepingSql(sql: string): boolean;
|
|
9
|
+
/** Mark duplicates, repeated shapes and slow statements, and total them. */
|
|
10
|
+
export declare function analyzeQueries(statements: QueryEntry[], options: QueryAnalysisOptions): QueriesSection;
|
|
11
|
+
export declare interface QueryAnalysisOptions {
|
|
12
|
+
slowThresholdMs: number
|
|
13
|
+
nPlusOneThreshold: number
|
|
14
|
+
dropped?: number
|
|
15
|
+
}
|
package/dist/state.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { DebugbarConfig } from '@stacksjs/types';
|
|
2
|
+
import type { ResolvedDebugbarConfig } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* True when anything says this process is production: `APP_ENV`, the loaded
|
|
5
|
+
* config, or `NODE_ENV` when `APP_ENV` says nothing.
|
|
6
|
+
*
|
|
7
|
+
* Any one of them is enough. A process whose environment variable and config
|
|
8
|
+
* disagree is treated as production, since being wrong in that direction
|
|
9
|
+
* costs a developer a toolbar and being wrong in the other costs an app its
|
|
10
|
+
* session tokens.
|
|
11
|
+
*/
|
|
12
|
+
export declare function isProductionEnvironment(inputs?: EnvironmentInputs): boolean;
|
|
13
|
+
/** The environment name the app reports, lowercased, or '' when it reports none. */
|
|
14
|
+
export declare function environmentName(inputs?: EnvironmentInputs): string;
|
|
15
|
+
/**
|
|
16
|
+
* Whether the debugbar should run in this process.
|
|
17
|
+
*
|
|
18
|
+
* Production: never. Otherwise `enabled: false` turns it off, `enabled: true`
|
|
19
|
+
* turns it on, and unset means on in `local` and `development` while
|
|
20
|
+
* `APP_DEBUG` is not false.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isDebugbarEnabled(config: DebugbarConfig | undefined, inputs?: EnvironmentInputs): boolean;
|
|
23
|
+
export declare function resolveDebugbarConfig(config: DebugbarConfig | undefined, defaultStoragePath: string): ResolvedDebugbarConfig;
|
|
24
|
+
export declare function isExcludedPath(path: string, except: readonly string[]): boolean;
|
|
25
|
+
export declare interface EnvironmentInputs {
|
|
26
|
+
env?: Record<string, string | undefined>
|
|
27
|
+
appEnv?: string
|
|
28
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DebugbarRecord, DebugbarSummary } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Create the directory and make it ignore itself.
|
|
4
|
+
*
|
|
5
|
+
* Records hold request data and the directory holds the sign-in token. An
|
|
6
|
+
* app whose `.gitignore` predates the debugbar must not commit either.
|
|
7
|
+
*/
|
|
8
|
+
export declare function ensureStorageDirectory(directory: string): void;
|
|
9
|
+
export declare function createStore(options: { directory: string, maxRequests: number }): DebugbarStore;
|
|
10
|
+
export declare interface DebugbarStore {
|
|
11
|
+
readonly directory: string
|
|
12
|
+
write: (record: DebugbarRecord) => Promise<void>
|
|
13
|
+
read: (id: string) => Promise<DebugbarRecord | null>
|
|
14
|
+
list: (limit?: number) => Promise<Array<{ id: string, startedAt: string, summary: DebugbarSummary }>>
|
|
15
|
+
clear: () => Promise<void>
|
|
16
|
+
prune: () => Promise<number>
|
|
17
|
+
flush: () => Promise<void>
|
|
18
|
+
}
|