@warlock.js/devtools 5.60.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/cjs/{boot-Dg5YZGGR.cjs → boot-D0nF-7w3.cjs} +6 -5
- package/cjs/{boot-Dg5YZGGR.cjs.map → boot-D0nF-7w3.cjs.map} +1 -1
- package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
- package/cjs/capture-D2k0GnBN.cjs.map +1 -0
- package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
- package/cjs/collector-BfC4v87v.cjs.map +1 -0
- package/cjs/errors-DNQ-g49I.cjs.map +1 -1
- package/cjs/{http-DCVCf44M.cjs → http-1nnpAoI7.cjs} +10 -4
- package/cjs/http-1nnpAoI7.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
- package/cjs/insights-COA3u37q.cjs.map +1 -0
- package/cjs/query-shape-DShKQa0x.cjs +45 -0
- package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
- package/cjs/redact-DQ28mDzr.cjs +533 -0
- package/cjs/redact-DQ28mDzr.cjs.map +1 -0
- package/cjs/{server-CC5DpObz.cjs → server-DLT3uPef.cjs} +2 -2
- package/cjs/{server-CC5DpObz.cjs.map → server-DLT3uPef.cjs.map} +1 -1
- package/cjs/{src-VyOjEEAo.cjs → src-BZiSv8A1.cjs} +9 -6
- package/cjs/src-BZiSv8A1.cjs.map +1 -0
- package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-B6WAjbPG.cjs} +5 -8
- package/cjs/stream-route-B6WAjbPG.cjs.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +4 -1
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/production/boot.mjs +1 -0
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +17 -4
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/http/mount.mjs +8 -2
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/jobs.mjs +45 -11
- package/esm/production/insights/jobs.mjs.map +1 -1
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +4 -7
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/types.d.mts +2 -2
- package/llms-full.txt +22 -22
- package/package.json +8 -8
- package/skills/SKILL.md +22 -22
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +2 -2
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/capture-CBgONYhk.cjs.map +0 -1
- package/cjs/collector-CJbQbzzK.cjs.map +0 -1
- package/cjs/histogram-CkoVizdf.cjs +0 -102
- package/cjs/histogram-CkoVizdf.cjs.map +0 -1
- package/cjs/http-DCVCf44M.cjs.map +0 -1
- package/cjs/insights-CFof59kF.cjs.map +0 -1
- package/cjs/src-VyOjEEAo.cjs.map +0 -1
- package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http-DCVCf44M.cjs","names":["normalizeIp","isIP","ipMatches","MAX_TOKEN","bodyOf","DevtoolsApiError","safeEqual","DevtoolsApiError","rateLimitClient","DEVTOOLS_FAILURE_AUDIT_TYPES","generateToken","hashToken","panelContentType","sendPanelFile","createHash","DevtoolsApiError","ipMatches","createErrorRef","DEVTOOLS_ERROR_MESSAGES","listPanelInfos","createHash"],"sources":["../../../../../../../packages/devtools/src/production/http/access.ts","../../../../../../../packages/devtools/src/production/http/client.ts","../../../../../../../packages/devtools/src/production/http/constants.ts","../../../../../../../packages/devtools/src/production/http/context.ts","../../../../../../../packages/devtools/src/production/http/cookie.ts","../../../../../../../packages/devtools/src/production/http/auth-routes.ts","../../../../../../../packages/devtools/src/production/http/headers.ts","../../../../../../../packages/devtools/src/production/http/share-session.ts","../../../../../../../packages/devtools/src/production/http/share.ts","../../../../../../../packages/devtools/src/production/http/mount.ts","../../../../../../../packages/devtools/src/production/http/state.ts"],"sourcesContent":["import type { DevtoolsRouteAccess, DevtoolsRouteAccessRule } from \"./types\";\n\ntype Method = DevtoolsRouteAccessRule[\"method\"];\n\nconst PUBLIC: DevtoolsRouteAccess = { type: \"public\" };\nconst VIEWER: DevtoolsRouteAccess = { type: \"viewer\" };\nconst ADMIN: DevtoolsRouteAccess = { type: \"admin\" };\nconst SHARE: DevtoolsRouteAccess = { type: \"share\" };\n\nconst pending = (...stages: Extract<DevtoolsRouteAccess, { type: \"pending\" }>[\"stages\"]) =>\n ({ type: \"pending\", stages }) satisfies DevtoolsRouteAccess;\n\nconst ALL_STEPS = [\"password-change\", \"mfa-enrol\", \"mfa-verify\"] as const;\n\n/**\n * The access table: every production route, its method and who may call it.\n * A route with no entry is `admin` (fail closed). A package panel `<id>`\n * gets `GET /api/<id>` and `GET /api/<id>/*` for viewers and every other\n * method there for admins, audited as `panel.action`; a url ending in `/*`\n * matches every pattern below it. The share routes exist only when\n * `options.share` is `true` (`production.share.enabled`).\n */\nexport function productionRouteAccess(\n panelIds: readonly string[],\n options: { share?: boolean } = {},\n): DevtoolsRouteAccessRule[] {\n const rule = (\n method: Method,\n url: string,\n access: DevtoolsRouteAccess,\n audit?: DevtoolsRouteAccessRule[\"audit\"],\n ): DevtoolsRouteAccessRule => ({ method, url, access, ...(audit ? { audit } : {}) });\n\n const rules: DevtoolsRouteAccessRule[] = [\n // The shell and its sign-in steps.\n rule(\"GET\", \"/\", PUBLIC),\n rule(\"GET\", \"/assets/:name\", PUBLIC),\n rule(\"GET\", \"/api/auth/session\", PUBLIC),\n rule(\"POST\", \"/api/auth/login\", PUBLIC),\n rule(\"POST\", \"/api/auth/setup\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/inspect\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/accept\", PUBLIC),\n rule(\"POST\", \"/api/auth/password\", pending(\"password-change\")),\n rule(\"POST\", \"/api/auth/totp/start\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/totp/confirm\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/passkey/options\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/passkey/verify\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/mfa\", pending(\"mfa-verify\")),\n rule(\"POST\", \"/api/auth/logout\", pending(...ALL_STEPS)),\n\n // The signed-in account.\n rule(\"GET\", \"/api/panels\", VIEWER),\n rule(\"GET\", \"/api/account\", VIEWER),\n rule(\"GET\", \"/api/account/sessions\", VIEWER),\n rule(\"DELETE\", \"/api/account/sessions/:id\", VIEWER),\n rule(\"POST\", \"/api/account/password\", VIEWER),\n rule(\"POST\", \"/api/account/totp/start\", VIEWER),\n rule(\"POST\", \"/api/account/totp/confirm\", VIEWER),\n rule(\"DELETE\", \"/api/account/totp\", VIEWER),\n rule(\"POST\", \"/api/account/recovery-codes\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/options\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/verify\", VIEWER),\n rule(\"DELETE\", \"/api/account/passkeys/:id\", VIEWER),\n\n // Administration.\n rule(\"GET\", \"/api/admin/users\", ADMIN),\n rule(\"POST\", \"/api/admin/invites\", ADMIN),\n rule(\"DELETE\", \"/api/admin/invites/:id\", ADMIN),\n rule(\"PATCH\", \"/api/admin/users/:id\", ADMIN),\n rule(\"DELETE\", \"/api/admin/users/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/reset-mfa\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/sign-out\", ADMIN),\n rule(\"GET\", \"/api/admin/audit\", ADMIN),\n rule(\"POST\", \"/api/admin/disable\", ADMIN),\n\n // Data.\n rule(\"GET\", \"/api/stream\", VIEWER),\n rule(\"GET\", \"/api/instances\", VIEWER),\n rule(\"GET\", \"/api/resources\", VIEWER),\n rule(\"GET\", \"/api/queries/stats\", VIEWER),\n rule(\"GET\", \"/api/routes/stats\", VIEWER),\n rule(\"GET\", \"/api/health\", VIEWER),\n rule(\"GET\", \"/api/errors\", VIEWER),\n rule(\"GET\", \"/api/jobs\", VIEWER),\n rule(\"GET\", \"/api/logs\", VIEWER),\n rule(\"GET\", \"/api/requests\", VIEWER),\n rule(\"GET\", \"/api/requests/:id\", VIEWER),\n rule(\"GET\", \"/api/requests/:id/curl\", VIEWER),\n rule(\"DELETE\", \"/api/requests\", ADMIN, \"requests.cleared\"),\n rule(\"POST\", \"/api/queries/:shapeId/explain\", ADMIN, \"explain.run\"),\n rule(\"GET\", \"/api/routes\", VIEWER),\n rule(\"GET\", \"/panels/:id/:name\", VIEWER),\n rule(\"GET\", \"/panels/:id/files/*\", VIEWER),\n\n // Tabs that are off unless the project turns them on.\n rule(\"GET\", \"/api/mails\", VIEWER),\n rule(\"GET\", \"/api/mails/:id\", VIEWER),\n rule(\"GET\", \"/api/mails/:id/html\", VIEWER),\n rule(\"GET\", \"/api/ai\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs\", VIEWER),\n rule(\"GET\", \"/api/ai/reports\", VIEWER),\n rule(\"GET\", \"/api/ai/models\", VIEWER),\n rule(\"GET\", \"/api/ai/errors\", VIEWER),\n rule(\"GET\", \"/api/ai/evaluate\", VIEWER),\n rule(\"POST\", \"/api/ai/evaluate\", ADMIN),\n rule(\"GET\", \"/api/openapi.json\", VIEWER),\n rule(\"GET\", \"/api/postman.json\", VIEWER),\n rule(\"GET\", \"/docs\", VIEWER),\n rule(\"GET\", \"/docs/swagger\", VIEWER),\n ];\n\n if (options.share === true) {\n rules.push(\n // The grant exchange: public, answered only for a valid token.\n rule(\"POST\", \"/api/share/open\", PUBLIC),\n // What a share grant may reach.\n rule(\"GET\", \"/api/share/info\", SHARE),\n rule(\"GET\", \"/api/share/view.js\", SHARE),\n rule(\"GET\", \"/api/share/assets/:name\", SHARE),\n rule(\"GET\", \"/api/share/files/*\", SHARE),\n rule(\"GET\", \"/api/share/panel\", SHARE),\n rule(\"GET\", \"/api/share/panel/*\", SHARE),\n // Managing the links.\n rule(\"GET\", \"/api/admin/shares\", ADMIN),\n rule(\"POST\", \"/api/admin/shares\", ADMIN),\n rule(\"DELETE\", \"/api/admin/shares/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/shares/revoke-all\", ADMIN),\n );\n }\n\n for (const id of panelIds) {\n rules.push(rule(\"GET\", `/api/${id}`, VIEWER), rule(\"GET\", `/api/${id}/*`, VIEWER));\n\n for (const method of [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const) {\n rules.push(\n rule(method, `/api/${id}`, ADMIN, \"panel.action\"),\n rule(method, `/api/${id}/*`, ADMIN, \"panel.action\"),\n );\n }\n }\n\n return rules;\n}\n\n/** Looks routes up by method and URL pattern: exact first, then the longest `/*` prefix. */\nexport function createAccessLookup(\n rules: readonly DevtoolsRouteAccessRule[],\n): (method: string, pattern: string) => DevtoolsRouteAccessRule | undefined {\n const exact = new Map<string, DevtoolsRouteAccessRule>();\n const wildcards: { method: Method; prefix: string; rule: DevtoolsRouteAccessRule }[] = [];\n\n for (const rule of rules) {\n if (rule.url.endsWith(\"/*\")) {\n wildcards.push({ method: rule.method, prefix: rule.url.slice(0, -1), rule });\n } else {\n exact.set(`${rule.method} ${rule.url}`, rule);\n }\n }\n\n wildcards.sort((a, b) => b.prefix.length - a.prefix.length);\n\n return (method, pattern) => {\n // A HEAD request is answered by the GET route.\n const verb = method === \"HEAD\" ? \"GET\" : method;\n const found = exact.get(`${verb} ${pattern}`);\n\n if (found) return found;\n\n return wildcards.find((item) => item.method === verb && pattern.startsWith(item.prefix))?.rule;\n };\n}\n","import { isIP } from \"node:net\";\nimport type { DevtoolsClientInfo, DevtoolsProxyRequest } from \"./types\";\nimport { ipMatches, normalizeIp } from \"./ip\";\n\n/** The first value of a header that may repeat or hold a comma list. */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n const text = Array.isArray(value) ? value[0] : value;\n const first = text?.split(\",\")[0]?.trim();\n\n return first === undefined || first === \"\" ? undefined : first;\n}\n\n/** The host name of a `Host` value: no port, lower case, brackets of an IPv6 literal kept. */\nfunction hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? value : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n\n return colon === -1 ? value : value.slice(0, colon);\n}\n\n/** The client address out of an `X-Forwarded-For` value, walking right to left past trusted hops. */\nfunction forwardedClient(\n header: string | string[] | undefined,\n trusted: readonly string[],\n): string | undefined {\n const text = Array.isArray(header) ? header.join(\",\") : header;\n const hops = (text ?? \"\")\n .split(\",\")\n .map((hop) => normalizeIp(hop.trim().replace(/^\\[|\\]$/g, \"\")))\n .filter((hop) => isIP(hop) !== 0);\n\n for (let index = hops.length - 1; index >= 0; index -= 1) {\n const hop = hops[index];\n\n if (hop !== undefined && !ipMatches(hop, trusted)) return hop;\n }\n\n // Every hop is a trusted proxy: the leftmost is the origin of the chain.\n return hops[0];\n}\n\n/**\n * The client IP, protocol and host. Forwarding headers are read only when the\n * socket peer is a trusted proxy; `X-Forwarded-For` is walked right to left,\n * skipping trusted addresses, and the first untrusted one is the client.\n */\nexport function resolveClient(\n request: DevtoolsProxyRequest,\n trustedProxies: readonly string[],\n): DevtoolsClientInfo {\n const peer = normalizeIp(request.socket.remoteAddress ?? \"\");\n const headers = request.headers;\n let ip = peer;\n let proto = request.socket.encrypted === true ? \"https\" : \"http\";\n let host = firstValue(headers.host) ?? \"\";\n\n if (peer !== \"\" && ipMatches(peer, trustedProxies)) {\n ip = forwardedClient(headers[\"x-forwarded-for\"], trustedProxies) ?? peer;\n\n const forwardedProto = firstValue(headers[\"x-forwarded-proto\"])?.toLowerCase();\n\n if (forwardedProto === \"http\" || forwardedProto === \"https\") proto = forwardedProto;\n\n host = firstValue(headers[\"x-forwarded-host\"]) ?? host;\n }\n\n host = host.toLowerCase();\n\n return { ip, proto, hostname: hostnameOf(host), host };\n}\n","/** The header the dashboard sends the CSRF token in. */\nexport const DEVTOOLS_CSRF_HEADER = \"x-devtools-csrf\";\n\n/** The session cookie name over HTTPS (`__Secure-` makes browsers refuse it over plain HTTP). */\nexport const DEVTOOLS_SESSION_COOKIE = \"__Secure-warlock-devtools\";\n\n/** The session cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SESSION_COOKIE_INSECURE = \"warlock-devtools\";\n\n/** The share cookie name over HTTPS. */\nexport const DEVTOOLS_SHARE_COOKIE = \"__Secure-warlock-devtools-share\";\n\n/** The share cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SHARE_COOKIE_INSECURE = \"warlock-devtools-share\";\n\n/** The longest a share cookie lives, whatever the link's expiry: 12 hours. */\nexport const DEVTOOLS_SHARE_COOKIE_MAX_SECONDS = 12 * 3600;\n","import type { FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsShareGrant } from \"./share-session\";\nimport type { DevtoolsClientInfo, DevtoolsRouteAccessRule } from \"./types\";\n\n/** What the gate learned about a dashboard request, for the handlers that follow. */\nexport type DevtoolsRequestContext = {\n client: DevtoolsClientInfo;\n meta: DevtoolsRequestMeta;\n /** The access rule the route matched; `undefined` for a route with no entry (treated as admin). */\n rule: DevtoolsRouteAccessRule | undefined;\n /** The route pattern relative to the dashboard path (`/api/requests/:id`). */\n pattern: string;\n /** The session, for every route that is not public. */\n authenticated: DevtoolsAuthenticated | null;\n /** The share grant, for a request that passed the `share` access check. */\n share?: DevtoolsShareGrant | null;\n};\n\nconst contexts = new WeakMap<FastifyRequest, DevtoolsRequestContext>();\n\n/** Stores the context of `request` (the gate calls this). */\nexport function setDevtoolsRequestContext(\n request: FastifyRequest,\n context: DevtoolsRequestContext,\n): void {\n contexts.set(request, context);\n}\n\n/** The context the gate stored for `request`, or `undefined` outside the production dashboard. */\nexport function devtoolsRequestContext(\n request: FastifyRequest,\n): DevtoolsRequestContext | undefined {\n return contexts.get(request);\n}\n","import {\n DEVTOOLS_SESSION_COOKIE,\n DEVTOOLS_SESSION_COOKIE_INSECURE,\n DEVTOOLS_SHARE_COOKIE,\n DEVTOOLS_SHARE_COOKIE_INSECURE,\n} from \"./constants\";\n\n/** The cookie name for the HTTPS mode. */\nexport function sessionCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SESSION_COOKIE : DEVTOOLS_SESSION_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a session token (or a clearing cookie when `token`\n * is `null`). The cookie is a browser-session cookie scoped to the dashboard\n * path, `HttpOnly` and `SameSite=Strict`, with no `Domain`.\n */\nexport function sessionCookie(\n token: string | null,\n options: { path: string; secure: boolean },\n): string {\n const parts = [\n `${sessionCookieName(options.secure)}=${token ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (token === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n\n return parts.join(\"; \");\n}\n\n/** The value of cookie `name` in a `Cookie` header, or `undefined`. */\nexport function readCookie(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n\n if (equals === -1) continue;\n\n if (pair.slice(0, equals).trim() === name) {\n const value = pair.slice(equals + 1).trim();\n\n return value === \"\" ? undefined : value;\n }\n }\n\n return undefined;\n}\n\n/** The share cookie name for the HTTPS mode. */\nexport function shareCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SHARE_COOKIE : DEVTOOLS_SHARE_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a share grant (or a clearing cookie when `value` is\n * `null`). Scoped to the dashboard path, `HttpOnly`, `SameSite=Strict`, no\n * `Domain`, and it ends after `maxAgeSeconds`.\n */\nexport function shareCookie(\n value: string | null,\n options: { path: string; secure: boolean; maxAgeSeconds?: number },\n): string {\n const parts = [\n `${shareCookieName(options.secure)}=${value ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (value === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n else parts.push(`Max-Age=${Math.max(1, Math.floor(options.maxAgeSeconds ?? 0))}`);\n\n return parts.join(\"; \");\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsAuthStep, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsRole } from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport { readCookie, sessionCookie, sessionCookieName } from \"./cookie\";\nimport { devtoolsRequestContext } from \"./context\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst MAX_TEXT = 1024;\nconst MAX_EMAIL = 320;\nconst MAX_CODE = 128;\nconst MAX_TOKEN = 512;\nconst ROLES: readonly DevtoolsRole[] = [\"admin\", \"viewer\"];\n\n/** A request body that is a plain JSON object, or `input.invalid`. */\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\n/** A non-empty string field no longer than `max`, or `input.invalid`. */\nfunction text(body: Record<string, unknown>, key: string, max = MAX_TEXT): string {\n const value = body[key];\n\n if (typeof value !== \"string\" || value === \"\" || value.length > max) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value;\n}\n\n/** An optional string field; `undefined` when absent, `input.invalid` when present but wrong. */\nfunction optionalText(\n body: Record<string, unknown>,\n key: string,\n max = MAX_TEXT,\n): string | undefined {\n return body[key] === undefined ? undefined : text(body, key, max);\n}\n\nfunction email(body: Record<string, unknown>): string {\n const value = text(body, \"email\", MAX_EMAIL).trim().toLowerCase();\n\n if (!/^[^\\s@]+@[^\\s@]+$/.test(value)) throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction role(body: Record<string, unknown>): DevtoolsRole {\n const value = body.role;\n\n if (typeof value !== \"string\" || !ROLES.includes(value as DevtoolsRole)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value as DevtoolsRole;\n}\n\nfunction purpose(body: Record<string, unknown>): \"register\" | \"login\" {\n const value = body.purpose;\n\n if (value !== \"register\" && value !== \"login\") throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction idParam(request: FastifyRequest): string {\n const { id } = (request.params ?? {}) as { id?: unknown };\n\n if (typeof id !== \"string\" || id === \"\" || id.length > MAX_CODE) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return id;\n}\n\n/** The `current` password of a request that may have no body (a DELETE). */\nfunction currentOf(request: FastifyRequest): string | undefined {\n return request.body === undefined || request.body === null\n ? undefined\n : optionalText(bodyOf(request), \"current\");\n}\n\n/** What the gate stored, for a route that is never reached without it. */\nfunction contextOf(request: FastifyRequest): {\n meta: DevtoolsRequestMeta;\n auth: DevtoolsAuthenticated;\n} {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { meta: context.meta, auth: context.authenticated };\n}\n\nfunction metaOf(request: FastifyRequest): DevtoolsRequestMeta {\n const context = devtoolsRequestContext(request);\n\n if (!context) throw new Error(\"A dashboard route ran without its request context.\");\n\n return context.meta;\n}\n\n/**\n * Registers the sign-in, account and admin routes. All decisions live in the\n * auth service; the handlers read the body, call it and answer. The gate\n * (`mountProductionDevtools`) has already checked the session, role, origin\n * and CSRF token by the time a handler runs.\n */\nexport function registerAuthRoutes(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { auth, store, state, production } = deps;\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n\n /** Sets the new session cookie when the step minted one; answers the step. */\n const answerStep = (\n reply: FastifyReply,\n step: DevtoolsAuthStep,\n recoveryCodes?: string[] | null,\n ): DevtoolsAuthStepResult & { recoveryCodes?: string[] } => {\n if (step.token !== null) reply.header(\"set-cookie\", sessionCookie(step.token, cookieOptions));\n\n return {\n stage: step.stage,\n csrf: step.csrf,\n ...(recoveryCodes ? { recoveryCodes } : {}),\n };\n };\n\n /** The stage and CSRF token of the session in force, for answers that do not change it. */\n const currentStep = (authenticated: DevtoolsAuthenticated): DevtoolsAuthStepResult => ({\n stage: authenticated.stage,\n csrf: auth.csrfToken(authenticated.session),\n });\n\n const clearCookie = (reply: FastifyReply): void => {\n reply.header(\"set-cookie\", sessionCookie(null, cookieOptions));\n };\n\n const requireAdmin = (authenticated: DevtoolsAuthenticated): void => {\n if (authenticated.account.role !== \"admin\" || authenticated.stage !== \"active\") {\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n };\n\n // ---- Public ------------------------------------------------------------\n\n server.get(\"/api/auth/session\", async (request, reply) => {\n const token = readCookie(request.headers.cookie, sessionCookieName(production.requireHttps));\n const authenticated = token === undefined ? null : await auth.authenticate(token);\n\n // A cookie that no longer matches a session is dead weight: clear it.\n if (token !== undefined && authenticated === null) clearCookie(reply);\n\n return auth.sessionView(authenticated);\n });\n\n server.post(\"/api/auth/login\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.login(\n { email: email(body), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/setup\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.setup(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/invite/inspect\", async (request) => {\n const body = bodyOf(request);\n\n return auth.inspectInvite(text(body, \"token\", MAX_TOKEN));\n });\n\n server.post(\"/api/auth/invite/accept\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.acceptInvite(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n // ---- Sign-in steps and the account (a session is required) --------------\n\n const changePassword = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const current = optionalText(body, \"current\");\n const step = await auth.changePassword(\n authenticated,\n { ...(current === undefined ? {} : { current }), password: text(body, \"password\") },\n meta,\n );\n\n return answerStep(reply, step);\n };\n\n const startTotp = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.startTotp(authenticated, meta);\n };\n\n const confirmTotp = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const result = await auth.confirmTotp(\n authenticated,\n text(body, \"code\", MAX_CODE),\n meta,\n optionalText(body, \"current\"),\n );\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n const passkeyOptions = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.passkeyOptions(authenticated, purpose(bodyOf(request)), meta);\n };\n\n const passkeyVerify = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n if (body.response === null || typeof body.response !== \"object\") {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const result = await auth.verifyPasskey(\n authenticated,\n purpose(body),\n body.response,\n meta,\n optionalText(body, \"current\"),\n );\n\n if (result.step === null) {\n return {\n ...currentStep(authenticated),\n ...(result.recoveryCodes ? { recoveryCodes: result.recoveryCodes } : {}),\n };\n }\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n server.post(\"/api/auth/password\", changePassword);\n server.post(\"/api/auth/totp/start\", startTotp);\n server.post(\"/api/auth/totp/confirm\", confirmTotp);\n server.post(\"/api/auth/passkey/options\", passkeyOptions);\n server.post(\"/api/auth/passkey/verify\", passkeyVerify);\n\n server.post(\"/api/auth/mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const code = optionalText(body, \"code\", MAX_CODE);\n const recoveryCode = optionalText(body, \"recoveryCode\", MAX_CODE);\n\n if ((code === undefined) === (recoveryCode === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const step = await auth.verifySecondFactor(\n authenticated,\n code === undefined ? { recoveryCode: recoveryCode as string } : { code },\n meta,\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/logout\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.logout(authenticated, meta);\n clearCookie(reply);\n\n return reply.code(204).send();\n });\n\n server.get(\"/api/account\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.accountView(authenticated.account);\n });\n\n server.get(\"/api/account/sessions\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listSessions(authenticated);\n });\n\n server.delete(\"/api/account/sessions/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeSession(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/password\", changePassword);\n server.post(\"/api/account/totp/start\", startTotp);\n server.post(\"/api/account/totp/confirm\", confirmTotp);\n\n server.delete(\"/api/account/totp\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeTotp(authenticated, meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/recovery-codes\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n // No code: a passkey step-up in this session stands in for it.\n const codes = await auth.regenerateRecoveryCodes(\n authenticated,\n optionalText(bodyOf(request), \"code\", MAX_CODE) ?? \"\",\n meta,\n );\n\n return { codes };\n });\n\n server.post(\"/api/account/passkey/options\", passkeyOptions);\n server.post(\"/api/account/passkey/verify\", passkeyVerify);\n\n server.delete(\"/api/account/passkeys/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removePasskey(authenticated, idParam(request), meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n // ---- Admin ---------------------------------------------------------------\n\n server.get(\"/api/admin/users\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listUsers(authenticated);\n });\n\n server.post(\"/api/admin/invites\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n return auth.createInvite(authenticated, { email: email(body), role: role(body) }, meta);\n });\n\n server.delete(\"/api/admin/invites/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeInvite(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.patch(\"/api/admin/users/:id\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.setRole(authenticated, idParam(request), role(bodyOf(request)), meta);\n });\n\n server.delete(\"/api/admin/users/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/reset-mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.resetSecondFactor(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/sign-out\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.signOutAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.get<{ Querystring: Record<string, string | undefined> }>(\n \"/api/admin/audit\",\n async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n requireAdmin(authenticated);\n\n const query = request.query;\n const types = query.type\n ?.split(\",\")\n .map((type) => type.trim())\n .filter((type) => type !== \"\");\n const before = query.before === undefined ? undefined : Number(query.before);\n const limit = query.limit === undefined ? 100 : Number(query.limit);\n\n if (\n (before !== undefined && !Number.isFinite(before)) ||\n !Number.isInteger(limit) ||\n limit < 1\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return store.audit.list({\n ...(types && types.length > 0 ? { types: types as DevtoolsAuditType[] } : {}),\n ...(query.account ? { accountId: query.account } : {}),\n ...(before === undefined ? {} : { before }),\n limit: Math.min(limit, 500),\n });\n },\n );\n\n server.post(\"/api/admin/disable\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n if (bodyOf(request).confirm !== \"disable\") throw new DevtoolsApiError(\"input.invalid\");\n\n await auth.disableDashboard(authenticated, meta);\n // This process closes at once; the others within the state cache time.\n state.invalidate();\n\n return reply.code(204).send();\n });\n}\n","/** Headers on every dashboard answer that is not the uniform 404. */\nexport const DASHBOARD_HEADERS: Readonly<Record<string, string>> = {\n \"Cache-Control\": \"no-store\",\n \"X-Robots-Tag\": \"noindex, nofollow, noarchive\",\n \"Referrer-Policy\": \"no-referrer\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"X-Frame-Options\": \"DENY\",\n \"Cross-Origin-Opener-Policy\": \"same-origin\",\n \"Cross-Origin-Resource-Policy\": \"same-origin\",\n \"Permissions-Policy\":\n \"camera=(), microphone=(), geolocation=(), publickey-credentials-get=(self), publickey-credentials-create=(self)\",\n};\n\n/** The policy of the dashboard's own HTML: scripts and styles from the bundle only. */\nexport const DASHBOARD_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n\n/**\n * The policy of the opt-in API documentation pages: scripts from the dashboard\n * only (Scalar and Swagger UI probe `Function` in a try/catch and work without\n * `'unsafe-eval'`), inline styles, and framing by the dashboard itself, whose\n * API tab shows them in a frame.\n */\nexport const DOCS_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n","import type { MountedDevtoolsPanel } from \"../../panels\";\nimport { safeEqual } from \"../auth/helpers\";\nimport type { DevtoolsShareRecord, DevtoolsStore } from \"../store/types\";\nimport { DEVTOOLS_SHARE_COOKIE_MAX_SECONDS } from \"./constants\";\n\n/** How long a read of a share record is reused. A revoke reaches every instance within this time. */\nexport const SHARE_CACHE_MS = 5000;\n\n/** Records kept in the cache of one process (oldest evicted). */\nconst SHARE_CACHE_SIZE = 500;\n\n/** A link's use is written at most this often per link and process. */\nconst TOUCH_INTERVAL_MS = 60_000;\n\n/** What a valid share cookie grants: the link and the panel it opens. */\nexport type DevtoolsShareGrant = {\n share: DevtoolsShareRecord;\n panel: MountedDevtoolsPanel;\n};\n\n/** Why a share cookie or token was refused (written to the audit log; never the value). */\nexport type DevtoolsShareRefusal = \"unknown\" | \"expired\" | \"revoked\" | \"panel\" | \"cookie\";\n\nexport type DevtoolsShareSessions = {\n /** The cookie value for `share`: `<id>.<exp>.<hmac>`, and its life in seconds. */\n issue(share: DevtoolsShareRecord): { value: string; maxAgeSeconds: number };\n /** The grant a `Cookie` value carries, or the reason it was refused. */\n verify(\n value: string | undefined,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** The record a token hash names, checked for life and panel; or the reason it is refused. */\n open(\n tokenHash: string,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** Counts one use of `share` (at most once a minute per link). */\n touch(shareId: string): void;\n /** Forgets cached records (after this process revoked or created a link). */\n invalidate(): void;\n};\n\n/**\n * The share grant: a cookie carrying `<shareId>.<exp>.<HMAC-SHA256(key,\n * \"share:<id>:<exp>\")>`. The signature proves this server issued it; the\n * link's record, read through a 5-second cache, proves it is still alive, so\n * a revoke takes effect everywhere within that time without a session table.\n */\nexport function createShareSessions(input: {\n store: DevtoolsStore;\n panels: readonly MountedDevtoolsPanel[];\n hmac: (value: string) => string;\n now?: () => number;\n warn?: (message: string) => void;\n}): DevtoolsShareSessions {\n const { store, hmac } = input;\n const now = input.now ?? (() => Date.now());\n const panels = new Map(\n input.panels.filter((panel) => panel.share !== null).map((panel) => [panel.id, panel]),\n );\n const cache = new Map<string, { record: DevtoolsShareRecord | null; at: number }>();\n const touched = new Map<string, number>();\n\n const sign = (id: string, exp: number): string => hmac(`share:${id}:${exp}`);\n\n async function record(id: string): Promise<DevtoolsShareRecord | null> {\n const cached = cache.get(id);\n\n if (cached && now() - cached.at < SHARE_CACHE_MS) return cached.record;\n\n const found = await store.shares.get(id);\n\n cache.delete(id);\n\n if (cache.size >= SHARE_CACHE_SIZE) {\n const oldest = cache.keys().next();\n\n if (!oldest.done) cache.delete(oldest.value);\n }\n\n cache.set(id, { record: found, at: now() });\n\n return found;\n }\n\n function grantFor(\n share: DevtoolsShareRecord,\n ): { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string } {\n if (share.revokedAt !== null) return { refused: \"revoked\", shareId: share.id };\n\n if (share.expiresAt <= now()) return { refused: \"expired\", shareId: share.id };\n\n const panel = panels.get(share.panel);\n\n return panel ? { grant: { share, panel } } : { refused: \"panel\", shareId: share.id };\n }\n\n return {\n issue(share) {\n const remaining = Math.floor((share.expiresAt - now()) / 1000);\n const maxAgeSeconds = Math.max(1, Math.min(remaining, DEVTOOLS_SHARE_COOKIE_MAX_SECONDS));\n const exp = now() + maxAgeSeconds * 1000;\n\n return { value: `${share.id}.${exp}.${sign(share.id, exp)}`, maxAgeSeconds };\n },\n\n async verify(value) {\n const parts = (value ?? \"\").split(\".\");\n const [id, expText, signature] = parts;\n\n if (parts.length !== 3 || !id || !expText || !signature || !/^\\d{1,16}$/.test(expText)) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const exp = Number(expText);\n\n if (!safeEqual(signature, sign(id, exp)) || exp <= now()) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const share = await record(id);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: id };\n },\n\n async open(tokenHash) {\n const share = await store.shares.findByTokenHash(tokenHash);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: null };\n },\n\n touch(shareId) {\n const at = now();\n const last = touched.get(shareId);\n\n if (last !== undefined && at - last < TOUCH_INTERVAL_MS) return;\n\n touched.delete(shareId);\n\n if (touched.size >= SHARE_CACHE_SIZE) {\n const oldest = touched.keys().next();\n\n if (!oldest.done) touched.delete(oldest.value);\n }\n\n touched.set(shareId, at);\n // A failed write is not worth failing the request for.\n void store.shares.touch(shareId, at).catch((error: unknown) => {\n input.warn?.(\n `devtools could not record a share link use: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n },\n\n invalidate() {\n cache.clear();\n },\n };\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { panelContentType, type MountedDevtoolsPanel } from \"../../panels\";\nimport { sendPanelFile } from \"../../server/panel-routes\";\nimport { sendFile } from \"../../server/ui-assets\";\nimport type { DevtoolsPanelRequest } from \"../../types\";\nimport { generateToken, hashToken } from \"../auth/helpers\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport {\n DEVTOOLS_FAILURE_AUDIT_TYPES,\n DEVTOOLS_SHARE_LABEL_MAX,\n type DevtoolsCreatedShare,\n type DevtoolsShareList,\n type DevtoolsShareOpenAnswer,\n type DevtoolsShareView,\n} from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsShareRecord } from \"../store/types\";\nimport { devtoolsRequestContext } from \"./context\";\nimport { readCookie, shareCookie, shareCookieName } from \"./cookie\";\nimport { rateLimitClient } from \"./ip\";\nimport { createShareSessions, type DevtoolsShareGrant } from \"./share-session\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst DAY_MS = 86_400_000;\nconst MAX_TOKEN = 512;\nconst MAX_PANEL_ID = 64;\n\n/** A failed token is not looked up again for this long once its client is over the limit. */\nconst BLOCK_CACHE_MS = 30_000;\nconst BLOCK_CACHE_SIZE = 1000;\n\n/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */\nconst COOKIE_AUDIT_INTERVAL_MS = 60_000;\n\ntype Notfound = (request: FastifyRequest, reply: FastifyReply) => FastifyReply;\n\n/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */\nexport function matchSharePath(pattern: string, path: string): Record<string, string> | null {\n if (/[\\0\\\\]/.test(path)) return null;\n\n const wanted = pattern.split(\"/\");\n const given = path.split(\"/\");\n\n if (wanted.length !== given.length) return null;\n\n const params: Record<string, string> = {};\n\n for (const [index, part] of wanted.entries()) {\n const actual = given[index];\n\n if (actual === undefined) return null;\n\n if (part.startsWith(\":\")) {\n if (actual === \"\") return null;\n\n params[part.slice(1)] = actual;\n } else if (part !== actual) {\n return null;\n }\n }\n\n return params;\n}\n\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\nfunction viewOf(\n record: DevtoolsShareRecord,\n createdBy: string | null,\n at: number,\n): DevtoolsShareView {\n return {\n id: record.id,\n panel: record.panel,\n label: record.label,\n createdBy,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n revokedAt: record.revokedAt,\n lastUsedAt: record.lastUsedAt,\n uses: record.uses,\n status: record.revokedAt !== null ? \"revoked\" : record.expiresAt <= at ? \"expired\" : \"active\",\n };\n}\n\nfunction openAnswer(grant: DevtoolsShareGrant): DevtoolsShareOpenAnswer {\n const { panel, share } = grant;\n\n return {\n panel: panel.id,\n title: panel.title,\n label: share.label,\n expiresAt: share.expiresAt,\n assets: [...(panel.share?.assets ?? [])],\n files: panel.share?.files === true,\n };\n}\n\n/** What `mountProductionDevtools` gets back when sharing is on. */\nexport type DevtoolsShareMount = {\n /** The grant of a request's share cookie, or `null` (the gate then answers the uniform 404). */\n authorize(request: FastifyRequest, meta: DevtoolsRequestMeta): Promise<DevtoolsShareGrant | null>;\n /** Registers the share routes and the admin routes that manage links. */\n register(server: FastifyInstance, notFound: Notfound): void;\n};\n\n/**\n * Read-only share links of the production monitor. An admin creates a link\n * for a panel that declares `share`; the token is shown once and only its\n * SHA-256 is stored. Opening a link exchanges the token for a scoped cookie\n * (`__Secure-warlock-devtools-share`) that reaches only that panel's shared\n * view. Every refusal answers the dashboard's uniform 404, is audited as\n * `share.failed` (which counts toward the per-IP failure limit) and never\n * records the token.\n */\nexport function createDevtoolsShare(\n deps: MountProductionDevtoolsDeps & { now?: () => number },\n): DevtoolsShareMount {\n const { production, store, auth } = deps;\n const now = deps.now ?? (() => Date.now());\n\n if (typeof deps.hmac !== \"function\") {\n throw new Error(\"Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).\");\n }\n\n const sessions = createShareSessions({\n store,\n panels: deps.panels,\n hmac: deps.hmac,\n now,\n ...(deps.warn ? { warn: deps.warn } : {}),\n });\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n const cookieName = shareCookieName(production.requireHttps);\n const sharePanels = deps.panels.filter((panel) => panel.share !== null);\n const blocked = new Map<string, number>();\n const cookieAudited = new Map<string, number>();\n\n const limits = production.rateLimits;\n const windowMs = limits.windowMinutes * 60_000;\n\n async function overLimit(ip: string): Promise<boolean> {\n const client = rateLimitClient(ip);\n const at = now();\n const until = blocked.get(client);\n\n if (until !== undefined && at < until) return true;\n\n const state = await store.state.read();\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since, ip });\n\n blocked.delete(client);\n\n if (count < limits.ip) return false;\n\n if (blocked.size >= BLOCK_CACHE_SIZE) {\n const oldest = blocked.keys().next();\n\n if (!oldest.done) blocked.delete(oldest.value);\n }\n\n blocked.set(client, at + BLOCK_CACHE_MS);\n\n return true;\n }\n\n /** Writes one `share.failed` entry (never the token). Never throws. */\n async function failed(\n meta: DevtoolsRequestMeta,\n reason: string,\n shareId: string | null,\n ): Promise<void> {\n await auth.audit(\"share.failed\", { meta, detail: { reason, share: shareId } });\n }\n\n /** The cookie check for a share request. */\n async function authorize(\n request: FastifyRequest,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsShareGrant | null> {\n const value = readCookie(request.headers.cookie, cookieName);\n\n if (value === undefined) return null;\n\n let result;\n\n try {\n result = await sessions.verify(value);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return null;\n }\n\n if (\"grant\" in result) {\n sessions.touch(result.grant.share.id);\n\n return result.grant;\n }\n\n const client = rateLimitClient(meta.ip);\n const last = cookieAudited.get(client);\n\n if (last === undefined || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {\n cookieAudited.delete(client);\n\n if (cookieAudited.size >= BLOCK_CACHE_SIZE) {\n const oldest = cookieAudited.keys().next();\n\n if (!oldest.done) cookieAudited.delete(oldest.value);\n }\n\n cookieAudited.set(client, now());\n\n try {\n if (!(await overLimit(meta.ip))) await failed(meta, result.refused, result.shareId);\n } catch {\n // The refusal stands even when the audit cannot be written.\n }\n }\n\n return null;\n }\n\n function grantOf(request: FastifyRequest): DevtoolsShareGrant {\n const grant = devtoolsRequestContext(request)?.share;\n\n if (!grant) throw new Error(\"A share route ran without its grant.\");\n\n return grant;\n }\n\n function createdByOf(\n accounts: readonly { id: string; email: string }[],\n id: string | null,\n ): string | null {\n return accounts.find((account) => account.id === id)?.email ?? null;\n }\n\n // ---- Admin ----------------------------------------------------------------\n\n async function list(): Promise<DevtoolsShareList> {\n const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);\n const at = now();\n\n return {\n enabled: true,\n maxDays: production.share.maxDays,\n panels: sharePanels.map((panel) => ({ id: panel.id, title: panel.title })),\n shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at)),\n };\n }\n\n async function create(\n authenticated: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n body: Record<string, unknown>,\n ): Promise<DevtoolsCreatedShare> {\n const panel = body.panel;\n const label = typeof body.label === \"string\" ? body.label.trim() : \"\";\n const days = body.days;\n\n if (\n typeof panel !== \"string\" ||\n panel.length > MAX_PANEL_ID ||\n !sharePanels.some((item) => item.id === panel) ||\n label === \"\" ||\n label.length > DEVTOOLS_SHARE_LABEL_MAX ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f]/.test(label) ||\n typeof days !== \"number\" ||\n !Number.isInteger(days) ||\n days < 1 ||\n days > production.share.maxDays\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const token = generateToken();\n const at = now();\n const record = await store.shares.create({\n tokenHash: hashToken(token),\n panel,\n label,\n createdBy: authenticated.account.id,\n createdAt: at,\n expiresAt: at + days * DAY_MS,\n });\n\n sessions.invalidate();\n await auth.audit(\"share.created\", {\n auth: authenticated,\n meta,\n detail: { share: record.id, panel, days },\n });\n\n return {\n share: viewOf(record, authenticated.account.email, at),\n // The token rides in the fragment: it never reaches an access log or a Referer header.\n url: `${meta.origin}${production.path}/#/share/${token}`,\n };\n }\n\n // ---- Registration -----------------------------------------------------------\n\n function register(server: FastifyInstance, notFound: Notfound): void {\n const requireAuth = (request: FastifyRequest) => {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { auth: context.authenticated, meta: context.meta };\n };\n\n // The grant exchange. Every failure answers the uniform 404.\n server.post(\"/api/share/open\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n\n if (!context) return notFound(request, reply);\n\n const { meta } = context;\n const token = (request.body as { token?: unknown } | null | undefined)?.token;\n\n if (typeof token !== \"string\" || token === \"\" || token.length > MAX_TOKEN) {\n return notFound(request, reply);\n }\n\n try {\n if (await overLimit(meta.ip)) return notFound(request, reply);\n\n const result = await sessions.open(hashToken(token));\n\n if (!(\"grant\" in result)) {\n await failed(meta, result.refused, result.shareId);\n\n return notFound(request, reply);\n }\n\n const { value, maxAgeSeconds } = sessions.issue(result.grant.share);\n\n sessions.touch(result.grant.share.id);\n reply.header(\"set-cookie\", shareCookie(value, { ...cookieOptions, maxAgeSeconds }));\n\n return openAnswer(result.grant);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n });\n\n server.get(\"/api/share/info\", async (request) => openAnswer(grantOf(request)));\n\n server.get(\"/api/share/view.js\", async (request, reply) => {\n const view = grantOf(request).panel.share?.view;\n\n if (view === undefined) return notFound(request, reply);\n\n sendFile(reply, view, \"text/javascript; charset=utf-8\");\n\n return reply;\n });\n\n server.get<{ Params: { name: string } }>(\"/api/share/assets/:name\", async (request, reply) => {\n const { panel } = grantOf(request);\n const name = request.params.name;\n const file =\n panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) return notFound(request, reply);\n\n sendFile(reply, file, panelContentType(name));\n\n return reply;\n });\n\n server.get<{ Params: { \"*\": string } }>(\"/api/share/files/*\", async (request, reply) => {\n const { panel } = grantOf(request);\n\n return sendPanelFile(\n { files: panel.share?.files === true ? panel.files : null },\n request.params[\"*\"],\n request,\n reply,\n notFound,\n );\n });\n\n const panelRoute = async (request: FastifyRequest, reply: FastifyReply) => {\n const { panel } = grantOf(request);\n const sub = (request.params as { \"*\"?: string })[\"*\"];\n const path = sub === undefined || sub === \"\" ? \"\" : `/${sub}`;\n let matched: {\n route: MountedDevtoolsPanel[\"routes\"][number];\n params: Record<string, string>;\n } | null = null;\n\n for (const pattern of panel.share?.routes ?? []) {\n const params = matchSharePath(pattern, path);\n const route = panel.routes.find(\n (candidate) => candidate.method === \"GET\" && candidate.path === pattern,\n );\n\n if (params !== null && route !== undefined) {\n matched = { route, params };\n break;\n }\n }\n\n if (matched === null) return notFound(request, reply);\n\n const input: DevtoolsPanelRequest = {\n params: matched.params,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: undefined,\n shared: true,\n };\n const result = await matched.route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n };\n\n server.get(\"/api/share/panel\", panelRoute);\n server.get(\"/api/share/panel/*\", panelRoute);\n\n server.get(\"/api/admin/shares\", async () => list());\n\n server.post(\"/api/admin/shares\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const created = await create(authenticated, meta, bodyOf(request));\n\n return reply.code(201).send(created);\n });\n\n server.delete<{ Params: { id: string } }>(\"/api/admin/shares/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const id = request.params.id;\n\n if (typeof id !== \"string\" || id === \"\" || id.length > 64) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const record = await store.shares.get(id);\n\n if (!record || !(await store.shares.revoke(id, now()))) {\n throw new DevtoolsApiError(\"share.not-found\");\n }\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { share: id, panel: record.panel },\n });\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/shares/revoke-all\", async (request) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const revoked = await store.shares.revokeAll(now());\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { all: true, count: revoked },\n });\n\n return { revoked };\n });\n }\n\n return { authorize, register };\n}\n","import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiReportRoutes } from \"../../server/ai-report-routes\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { createDevtoolsShare } from \"./share\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The grant exchange of a share link: every failure of it answers the uniform 404. */\nconst SHARE_OPEN_PATTERN = \"/api/share/open\";\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai/reports\", \"ai-reports\"],\n [\"/api/ai/models\", \"ai-models\"],\n [\"/api/ai/errors\", \"ai-errors\"],\n [\"/api/ai/evaluate\", \"ai-evaluate\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\n/** The tabs the AI report routes serve; the routes register when any of them is on. */\nconst AI_REPORT_TABS = [\"ai-reports\", \"ai-models\", \"ai-errors\", \"ai-evaluate\"] as const;\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const share = production.share.enabled ? createDevtoolsShare(deps) : null;\n const lookup = createAccessLookup(\n productionRouteAccess(\n deps.panels.map((panel) => panel.id),\n { share: share !== null },\n ),\n );\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n // A share link has no account: its cookie grants one panel's shared view and nothing else.\n if (access.type === \"share\") {\n const grant = share ? await share.authorize(request, meta) : null;\n\n if (grant === null) return notFound(request, reply);\n\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule,\n pattern,\n authenticated: null,\n share: grant,\n });\n\n return;\n }\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) {\n if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n // A malformed grant exchange (bad JSON, too large) answers like any unknown URL.\n if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) {\n return notFound(request, reply);\n }\n\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels, { notFound });\n\n share?.register(instance, notFound);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (AI_REPORT_TABS.some((tab) => enabledTabs.has(tab)))\n registerAiReportRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport type { DevtoolsDashboardState } from \"./types\";\n\n/** SHA-256 hex of a dashboard path: what `disabledPathHash` holds. */\nexport function hashDashboardPath(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\");\n}\n\n/**\n * The open/closed state with a `ttlMs` cache (default 5000). Open means the\n * dashboard is not disabled for this path and not locked. A failed read is\n * not cached and rejects, so the caller can fail closed.\n */\nexport function createDashboardState(\n store: DevtoolsStore,\n path: string,\n options: { ttlMs?: number; now?: () => number } = {},\n): DevtoolsDashboardState {\n const ttlMs = options.ttlMs ?? 5000;\n const now = options.now ?? Date.now;\n const pathHash = hashDashboardPath(path);\n let cached: { open: boolean; at: number } | null = null;\n let pending: Promise<boolean> | null = null;\n let generation = 0;\n\n const read = async (): Promise<boolean> => {\n const started = generation;\n const state = await store.state.read();\n const at = now();\n const disabled = state.disabled && state.disabledPathHash === pathHash;\n const locked = state.lockedUntil !== null && state.lockedUntil > at;\n const open = !disabled && !locked;\n\n if (started === generation) cached = { open, at };\n\n return open;\n };\n\n return {\n async isOpen() {\n if (cached !== null && now() - cached.at < ttlMs) return cached.open;\n\n if (pending === null) {\n const current = read().finally(() => {\n if (pending === current) pending = null;\n });\n\n pending = current;\n }\n\n return pending;\n },\n invalidate() {\n generation += 1;\n cached = null;\n pending = null;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAIA,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AACnD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AAEnD,MAAM,WAAW,GAAG,YACjB;CAAE,MAAM;CAAW;AAAO;AAE7B,MAAM,YAAY;CAAC;CAAmB;CAAa;AAAY;;;;;;;;;AAU/D,SAAgB,sBACd,UACA,UAA+B,CAAC,GACL;CAC3B,MAAM,QACJ,QACA,KACA,QACA,WAC6B;EAAE;EAAQ;EAAK;EAAQ,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CAAG;CAElF,MAAM,QAAmC;EAEvC,KAAK,OAAO,KAAK,MAAM;EACvB,KAAK,OAAO,iBAAiB,MAAM;EACnC,KAAK,OAAO,qBAAqB,MAAM;EACvC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,4BAA4B,MAAM;EAC/C,KAAK,QAAQ,2BAA2B,MAAM;EAC9C,KAAK,QAAQ,sBAAsB,QAAQ,iBAAiB,CAAC;EAC7D,KAAK,QAAQ,wBAAwB,QAAQ,WAAW,CAAC;EACzD,KAAK,QAAQ,0BAA0B,QAAQ,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M,WAAW,MAAM,YAAY,MAAM,qBAAqB;EAC9D,MAAM,SAAS,MAAM,gBAAgB,QAAQ,MAAM,cAAc;EACjE,MAAM,OAAO,CAAC,YAAY,CAAC;EAE3B,IAAI,YAAY,YAAY,SAAS;GAAE;GAAM;EAAG;EAEhD,OAAO;CACT;CAEA,OAAO;EACL,MAAM,SAAS;GACb,IAAI,WAAW,QAAQ,IAAI,IAAI,OAAO,KAAK,OAAO,OAAO,OAAO;GAEhE,IAAI,YAAY,MAAM;IACpB,MAAM,UAAU,KAAK,CAAC,CAAC,cAAc;KACnC,IAAI,YAAY,SAAS,UAAU;IACrC,CAAC;IAED,UAAU;GACZ;GAEA,OAAO;EACT;EACA,aAAa;GACX,cAAc;GACd,SAAS;GACT,UAAU;EACZ;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"insights-CFof59kF.cjs","names":["mergeHistograms","histogramQuantile","histogramMean","os","cluster","constants","v8","monitorEventLoopDelay","performance","PerformanceObserver"],"sources":["../../../../../../../packages/devtools/src/production/stats/merge.ts","../../../../../../../packages/devtools/src/production/insights/cap-report.ts","../../../../../../../packages/devtools/src/production/insights/health.ts","../../../../../../../packages/devtools/src/production/insights/insights.ts","../../../../../../../packages/devtools/src/production/insights/instance.ts","../../../../../../../packages/devtools/src/production/insights/jobs.ts","../../../../../../../packages/devtools/src/production/insights/reporter.ts","../../../../../../../packages/devtools/src/production/insights/resources.ts","../../../../../../../packages/devtools/src/production/insights/writer.ts"],"sourcesContent":["import type {\n DevtoolsErrorGroup,\n DevtoolsQueryShapeStats,\n DevtoolsRoutePhaseStats,\n DevtoolsRouteStats,\n} from \"../contracts\";\nimport { mergeHistograms } from \"./histogram\";\n\n/** The later of two \"slowest\" records. */\nfunction slower<T extends { durationMs: number }>(a: T | null, b: T | null): T | null {\n if (a === null) return b;\n if (b === null) return a;\n\n return b.durationMs > a.durationMs ? b : a;\n}\n\n/**\n * Merges the query statistics several instances reported: one row per shape\n * id, counts and histograms summed, the slowest example kept, `instances`\n * listing who reported it. Order: highest total time first.\n */\nexport function mergeQueryShapeStats(\n reports: readonly { instance: string; shapes: readonly DevtoolsQueryShapeStats[] }[],\n): (DevtoolsQueryShapeStats & { instances: string[] })[] {\n const merged = new Map<string, DevtoolsQueryShapeStats & { instances: string[] }>();\n\n for (const { instance, shapes } of reports) {\n for (const shape of shapes) {\n const current = merged.get(shape.id);\n\n if (!current) {\n merged.set(shape.id, { ...structuredClone(shape), instances: [instance] });\n continue;\n }\n\n current.count += shape.count;\n current.errors += shape.errors;\n current.histogram = mergeHistograms([current.histogram, shape.histogram]);\n current.nPlusOne = {\n requests: current.nPlusOne.requests + shape.nPlusOne.requests,\n maxPerRequest: Math.max(current.nPlusOne.maxPerRequest, shape.nPlusOne.maxPerRequest),\n };\n current.slowest = slower(current.slowest, shape.slowest);\n current.firstSeen = Math.min(current.firstSeen, shape.firstSeen);\n current.lastSeen = Math.max(current.lastSeen, shape.lastSeen);\n current.explainable = current.explainable || shape.explainable;\n\n if (!current.instances.includes(instance)) current.instances.push(instance);\n }\n }\n\n return [...merged.values()].sort((a, b) => b.histogram.sumMs - a.histogram.sumMs);\n}\n\n/** Merges phase lists by name (counts and sums added, max kept), slowest total first, at most 30. */\nfunction mergePhases(\n lists: readonly (readonly DevtoolsRoutePhaseStats[])[],\n): DevtoolsRoutePhaseStats[] {\n const merged = new Map<string, DevtoolsRoutePhaseStats>();\n\n for (const list of lists) {\n for (const phase of list) {\n const current = merged.get(phase.name);\n\n if (!current) {\n merged.set(phase.name, { ...phase });\n continue;\n }\n\n current.count += phase.count;\n current.sumMs += phase.sumMs;\n current.maxMs = Math.max(current.maxMs, phase.maxMs);\n }\n }\n\n return [...merged.values()].sort((a, b) => b.sumMs - a.sumMs).slice(0, 30);\n}\n\n/** Merges route statistics by key, like `mergeQueryShapeStats`. */\nexport function mergeRouteStats(\n reports: readonly { instance: string; routes: readonly DevtoolsRouteStats[] }[],\n): (DevtoolsRouteStats & { instances: string[] })[] {\n const merged = new Map<string, DevtoolsRouteStats & { instances: string[] }>();\n\n for (const { instance, routes } of reports) {\n for (const route of routes) {\n const current = merged.get(route.key);\n\n if (!current) {\n merged.set(route.key, { ...structuredClone(route), instances: [instance] });\n continue;\n }\n\n current.count += route.count;\n current.errors += route.errors;\n current.histogram = mergeHistograms([current.histogram, route.histogram]);\n current.phases = mergePhases([current.phases, route.phases]);\n current.slowest = slower(current.slowest, route.slowest);\n\n if (!current.instances.includes(instance)) current.instances.push(instance);\n }\n }\n\n return [...merged.values()].sort((a, b) => b.histogram.sumMs - a.histogram.sumMs);\n}\n\n/** Merges error groups by id: counts added, the newest message/stack kept. Newest first. */\nexport function mergeErrorGroups(\n reports: readonly { instance: string; errors: readonly DevtoolsErrorGroup[] }[],\n): (DevtoolsErrorGroup & { instances: string[] })[] {\n const merged = new Map<string, DevtoolsErrorGroup & { instances: string[] }>();\n\n for (const { instance, errors } of reports) {\n for (const group of errors) {\n const current = merged.get(group.id);\n\n if (!current) {\n merged.set(group.id, { ...structuredClone(group), instances: [instance] });\n continue;\n }\n\n const newer = group.lastSeen > current.lastSeen;\n\n current.count += group.count;\n current.firstSeen = Math.min(current.firstSeen, group.firstSeen);\n\n if (newer) {\n current.lastSeen = group.lastSeen;\n current.message = group.message;\n current.stack = group.stack;\n current.status = group.status;\n current.lastRequestId = group.lastRequestId;\n }\n\n if (!current.instances.includes(instance)) current.instances.push(instance);\n }\n }\n\n return [...merged.values()].sort((a, b) => b.lastSeen - a.lastSeen);\n}\n","import type { DevtoolsInstanceReport } from \"../contracts\";\n\ntype ListSetter = (report: DevtoolsInstanceReport, keep: number) => DevtoolsInstanceReport;\n\nconst sizeOf = (report: DevtoolsInstanceReport): number =>\n Buffer.byteLength(JSON.stringify(report), \"utf8\");\n\n/** The lists to trim, in order, with how to cut each one to its first `keep` entries. */\nconst LISTS: { length(report: DevtoolsInstanceReport): number; cut: ListSetter }[] = [\n { length: (r) => r.logs.length, cut: (r, keep) => ({ ...r, logs: r.logs.slice(0, keep) }) },\n { length: (r) => r.errors.length, cut: (r, keep) => ({ ...r, errors: r.errors.slice(0, keep) }) },\n { length: (r) => r.routes.length, cut: (r, keep) => ({ ...r, routes: r.routes.slice(0, keep) }) },\n {\n length: (r) => r.queries.length,\n cut: (r, keep) => ({ ...r, queries: r.queries.slice(0, keep) }),\n },\n {\n length: (r) => r.resources.history.length,\n cut: (r, keep) => ({\n ...r,\n resources: { ...r.resources, history: r.resources.history.slice(0, keep) },\n }),\n },\n];\n\n/**\n * Trims a report's lists from the end until its JSON is at most `maxBytes`\n * (default 256 KB): logs first, then errors, routes, queries and the\n * resource history. A report that already fits is returned unchanged.\n */\nexport function capReportSize(\n report: DevtoolsInstanceReport,\n maxBytes = 262_144,\n): DevtoolsInstanceReport {\n let current = report;\n\n for (const list of LISTS) {\n if (sizeOf(current) <= maxBytes) return current;\n\n // The largest number of entries to keep that fits (0 when none does).\n let low = 0;\n let high = list.length(current);\n\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n\n if (sizeOf(list.cut(current, middle)) <= maxBytes) low = middle;\n else high = middle - 1;\n }\n\n current = list.cut(current, low);\n }\n\n return current;\n}\n","import type { DevtoolsHealthReport } from \"../contracts\";\nimport type { DevtoolsHealthStatusReader } from \"./readiness\";\nimport type { DevtoolsHealthHistory } from \"./types\";\n\n/** While the app boots, the first check is tried again this often. */\nconst BOOT_RETRY_MS = 1000;\n\n/** Core's readiness, imported on first use so devtools never loads core at import time. */\nconst coreReadiness: DevtoolsHealthStatusReader = async () => {\n const { health, Application } = await import(\"@warlock.js/core\");\n\n // The monitor starts while the app boots, when readiness is `error` with no failed check.\n if (!Application.isBooted && !Application.isShuttingDown) return null;\n\n return health.readiness();\n};\n\n/** Readiness checks every `intervalMs` (default 30000), 60 history entries. */\nexport function createHealthHistory(\n options: { intervalMs?: number; size?: number; readiness?: DevtoolsHealthStatusReader } = {},\n): DevtoolsHealthHistory {\n const intervalMs = options.intervalMs ?? 30_000;\n const size = Math.max(1, options.size ?? 60);\n const readiness = options.readiness ?? coreReadiness;\n\n let status: DevtoolsHealthReport[\"status\"] = \"unknown\";\n let checkedAt: number | null = null;\n let checks: Record<string, boolean> = {};\n const history: DevtoolsHealthReport[\"history\"] = [];\n let timer: ReturnType<typeof setInterval> | undefined;\n let retry: ReturnType<typeof setTimeout> | undefined;\n let running: Promise<DevtoolsHealthReport> | undefined;\n\n function report(): DevtoolsHealthReport {\n return {\n status,\n checkedAt,\n checks: { ...checks },\n history: history.map((e) => ({ ...e, failed: [...e.failed] })),\n };\n }\n\n async function run(): Promise<DevtoolsHealthReport> {\n try {\n const result = await readiness();\n\n if (result === null) {\n // Still booting: nothing to record yet. Until the first answer, try again soon instead of a whole interval later.\n if (timer && checkedAt === null && retry === undefined) {\n retry = setTimeout(() => {\n retry = undefined;\n void check();\n }, BOOT_RETRY_MS);\n retry.unref();\n }\n\n return report();\n }\n\n const now = Date.now();\n const failed = Object.entries(result.checks ?? {})\n .filter(([, passed]) => !passed)\n .map(([name]) => name);\n\n status = result.status;\n checkedAt = now;\n checks = { ...(result.checks ?? {}) };\n history.push({ at: now, status: result.status, failed });\n\n if (history.length > size) history.splice(0, history.length - size);\n } catch {\n // Readiness could not be read (core not loaded yet): keep the last answer.\n if (checkedAt === null) status = \"unknown\";\n }\n\n return report();\n }\n\n function check(): Promise<DevtoolsHealthReport> {\n running ??= run().finally(() => {\n running = undefined;\n });\n\n return running;\n }\n\n return {\n start() {\n if (timer) return;\n\n void check();\n timer = setInterval(() => void check(), intervalMs);\n timer.unref();\n },\n\n stop() {\n if (timer) clearInterval(timer);\n if (retry) clearTimeout(retry);\n\n timer = undefined;\n retry = undefined;\n },\n\n check,\n report,\n };\n}\n","import type { DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsLogRow } from \"../contracts\";\nimport {\n histogramMean,\n histogramQuantile,\n mergeErrorGroups,\n mergeQueryShapeStats,\n mergeRouteStats,\n} from \"../stats\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport type { DevtoolsInsightQuery, DevtoolsInsights, DevtoolsLocalReporter } from \"./types\";\n\nexport const DEFAULT_INSIGHT_LIMIT = 100;\nexport const MAX_INSIGHT_LIMIT = 500;\n\n/** Reports fresher than this are merged into the views. */\nconst FRESH_MS = 60_000;\n/** The instances list reaches back this far. */\nconst INSTANCES_MS = 5 * 60_000;\n\ntype ReportLoader = (windowMs: number) => Promise<DevtoolsInstanceReport[]>;\n\nfunction limitOf(query: DevtoolsInsightQuery): number {\n const limit = query.limit ?? DEFAULT_INSIGHT_LIMIT;\n\n return Math.min(MAX_INSIGHT_LIMIT, Math.max(1, Math.floor(limit)));\n}\n\nfunction matches(value: string, needle: string | undefined): boolean {\n return !needle || value.toLowerCase().includes(needle.toLowerCase());\n}\n\nfunction infoOf(report: DevtoolsInstanceReport): DevtoolsInstanceInfo {\n return { ...report.instance, seenAt: report.at };\n}\n\nfunction build(load: ReportLoader, sampleRateOf: (reports: DevtoolsInstanceReport[]) => number) {\n /** The fresh reports of the selected instance(s). */\n async function select(\n query: DevtoolsInsightQuery,\n windowMs = FRESH_MS,\n ): Promise<DevtoolsInstanceReport[]> {\n const reports = await load(windowMs);\n\n return query.instance === \"all\"\n ? reports\n : reports.filter((report) => report.instance.id === query.instance);\n }\n\n const insights: DevtoolsInsights = {\n async instances() {\n const reports = await load(INSTANCES_MS);\n const infos = reports.map(infoOf).sort((a, b) => b.seenAt - a.seenAt);\n\n return { current: current(reports), instances: infos };\n },\n\n async resources(query) {\n const reports = await select(query);\n\n return {\n instances: reports.map((report) => ({\n instance: infoOf(report),\n snapshot: report.resources.snapshot,\n history: report.resources.history,\n })),\n };\n },\n\n async queryStats(query) {\n const reports = await select(query);\n const sort = query.sort ?? \"total\";\n const rows = mergeQueryShapeStats(\n reports.map((report) => ({ instance: report.instance.id, shapes: report.queries })),\n ).map((shape) => ({\n ...shape,\n p50Ms: histogramQuantile(shape.histogram, 0.5),\n p95Ms: histogramQuantile(shape.histogram, 0.95),\n meanMs: histogramMean(shape.histogram),\n }));\n\n const key: Record<string, (row: (typeof rows)[number]) => number> = {\n total: (row) => row.histogram.sumMs,\n p95: (row) => row.p95Ms,\n count: (row) => row.count,\n \"n+1\": (row) => row.nPlusOne.requests * 1e6 + row.nPlusOne.maxPerRequest,\n };\n const by = key[sort] ?? key.total!;\n\n return {\n shapes: rows.sort((a, b) => by(b) - by(a)).slice(0, limitOf(query)),\n sampleRate: sampleRateOf(reports),\n instanceCount: reports.length,\n evicted: reports.reduce((sum, report) => sum + report.capture.evictedShapes, 0),\n };\n },\n\n async routeStats(query) {\n const reports = await select(query);\n const sort = query.sort ?? \"total\";\n const rows = mergeRouteStats(\n reports.map((report) => ({ instance: report.instance.id, routes: report.routes })),\n ).map((route) => ({\n ...route,\n p50Ms: histogramQuantile(route.histogram, 0.5),\n p95Ms: histogramQuantile(route.histogram, 0.95),\n meanMs: histogramMean(route.histogram),\n }));\n\n const key: Record<string, (row: (typeof rows)[number]) => number> = {\n total: (row) => row.histogram.sumMs,\n p95: (row) => row.p95Ms,\n count: (row) => row.count,\n errors: (row) => row.errors,\n };\n const by = key[sort] ?? key.total!;\n\n return {\n routes: rows.sort((a, b) => by(b) - by(a)).slice(0, limitOf(query)),\n sampleRate: sampleRateOf(reports),\n instanceCount: reports.length,\n };\n },\n\n async health(query) {\n const reports = await select(query);\n\n return {\n instances: reports.map((report) => ({ instance: infoOf(report), report: report.health })),\n };\n },\n\n async errors(query) {\n const reports = await select(query);\n const groups = mergeErrorGroups(\n reports.map((report) => ({ instance: report.instance.id, errors: report.errors })),\n );\n\n return { groups: groups.slice(0, limitOf(query)) };\n },\n\n async logs(query) {\n const reports = await select(query);\n const rows: DevtoolsLogRow[] = [];\n\n for (const report of reports) {\n for (const entry of report.logs) {\n if (!matches(entry.level, query.level) || !matches(entry.module, query.module)) continue;\n\n rows.push({ ...entry, instance: report.instance.id });\n }\n }\n\n return rows.sort((a, b) => b.at - a.at).slice(0, limitOf(query));\n },\n\n async jobs(query) {\n const reports = await select(query);\n\n return {\n instances: reports.map((report) => ({ instance: infoOf(report), report: report.jobs })),\n };\n },\n };\n\n let currentId = \"\";\n\n function current(reports: DevtoolsInstanceReport[]): string {\n return currentId || reports[0]?.instance.id || \"\";\n }\n\n return {\n insights,\n setCurrent(id: string) {\n currentId = id;\n },\n };\n}\n\n/** The sample rate the counts come from: the lowest any selected instance used (1 when none). */\nfunction lowestRate(reports: DevtoolsInstanceReport[]): number {\n return reports.length === 0 ? 1 : Math.min(...reports.map((r) => r.capture.sampleRate));\n}\n\n/** Development insights: this process only. */\nexport function createLocalInsights(reporter: DevtoolsLocalReporter): DevtoolsInsights {\n const { insights, setCurrent } = build(async () => [await reporter.snapshot()], lowestRate);\n\n setCurrent(reporter.instance.id);\n\n return insights;\n}\n\n/** Production insights: merged instance reports from the store plus this process live. */\nexport function createSharedInsights(input: {\n store: DevtoolsStore;\n reporter: DevtoolsLocalReporter;\n sampleRate: number;\n}): DevtoolsInsights {\n const { store, reporter, sampleRate } = input;\n\n const { insights, setCurrent } = build(\n async (windowMs) => {\n const live = await reporter.snapshot();\n let stored: DevtoolsInstanceReport[] = [];\n\n try {\n stored = await store.reports.list(live.at - windowMs);\n } catch {\n // The database is unreachable: show this process alone rather than nothing.\n }\n\n // The answering instance is always taken live, never from its stored row.\n return [live, ...stored.filter((report) => report.instance.id !== live.instance.id)];\n },\n () => sampleRate,\n );\n\n setCurrent(reporter.instance.id);\n\n return insights;\n}\n","import cluster from \"node:cluster\";\nimport os from \"node:os\";\nimport type { DevtoolsInstanceInfo } from \"../contracts\";\n\n/** This process's identity (host, pid, pm2/cluster worker, start time). */\nexport function createInstanceInfo(now: number = Date.now()): DevtoolsInstanceInfo {\n const host = os.hostname();\n const pid = process.pid;\n const worker =\n process.env.NODE_APP_INSTANCE ||\n process.env.pm_id ||\n (cluster.worker ? String(cluster.worker.id) : null);\n\n return {\n id: `${host}:${pid}:${now.toString(36)}`,\n label: worker === null ? `${host} pid ${pid}` : `${host} #${worker}`,\n host,\n pid,\n worker,\n startedAt: now,\n seenAt: now,\n nodeVersion: process.version,\n };\n}\n","import type { DevtoolsJobsReport, DevtoolsScheduleInfo } from \"../contracts\";\nimport type { DevtoolsJobsReader } from \"./types\";\n\n/** The shape of a scheduler job this reader needs (duck-typed: the packages stay optional). */\ntype SchedulerJobLike = {\n name: string;\n cronExpression?: string | null;\n intervals?: { every?: { type?: string; value?: number } };\n isRunning?: boolean;\n lastRun?: { valueOf(): number } | null;\n nextRun?: { valueOf(): number } | null;\n};\n\n/** Where the jobs come from; replaced in specs. Each returns `null` when its package is absent. */\nexport type DevtoolsJobsLoaders = {\n scheduler(): Promise<readonly SchedulerJobLike[] | null>;\n queue(): Promise<{ name: string; counts: Record<string, number> }[] | null>;\n};\n\nconst SCHEDULER_KEY = Symbol.for(\"warlock.scheduler.running\");\n\n/** Imports an optional package by name; `null` when it is not installed. */\nasync function importOptional(name: string): Promise<Record<string, unknown> | null> {\n try {\n return (await import(/* @vite-ignore */ name)) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nconst defaultLoaders: DevtoolsJobsLoaders = {\n async scheduler() {\n if (!(await importOptional(\"@warlock.js/scheduler\"))) return null;\n\n const running = (globalThis as Record<symbol, unknown>)[SCHEDULER_KEY] as\n | Iterable<{ list?: () => readonly SchedulerJobLike[] }>\n | undefined;\n const jobs: SchedulerJobLike[] = [];\n\n for (const scheduler of running ?? []) {\n if (typeof scheduler.list === \"function\") jobs.push(...scheduler.list());\n }\n\n return jobs;\n },\n\n async queue() {\n const queue = await importOptional(\"@warlock.js/queue\");\n const current = queue?.currentQueueDriver as (() => unknown) | undefined;\n const driver = current?.() as\n | {\n running?: () => string[];\n counts?: (queue: string) => Promise<Record<string, number>>;\n }\n | undefined;\n\n if (!driver || typeof driver.counts !== \"function\" || typeof driver.running !== \"function\") {\n return null;\n }\n\n const queues: { name: string; counts: Record<string, number> }[] = [];\n\n for (const name of driver.running()) {\n queues.push({ name, counts: await driver.counts(name) });\n }\n\n return queues;\n },\n};\n\nfunction readableInterval(job: SchedulerJobLike): string | null {\n const every = job.intervals?.every;\n\n if (!every?.type) return null;\n\n const value = every.value ?? 1;\n const unit = every.type.replace(/s$/, \"\");\n\n return value === 1 ? `every ${unit}` : `every ${value} ${unit}s`;\n}\n\nfunction toSchedule(job: SchedulerJobLike): DevtoolsScheduleInfo {\n return {\n name: job.name,\n cron: job.cronExpression ?? null,\n interval: readableInterval(job),\n isRunning: job.isRunning === true,\n lastRunAt: job.lastRun ? Number(job.lastRun.valueOf()) : null,\n nextRunAt: job.nextRun ? Number(job.nextRun.valueOf()) : null,\n // The scheduler keeps no per-run history; these stay empty.\n lastDurationMs: null,\n lastError: null,\n runs: 0,\n failures: 0,\n };\n}\n\n/**\n * Reads the scheduler's jobs and the queue's counts when those packages are\n * installed. A part that is absent or fails reports `available: false` with\n * nothing else; the reader itself never throws.\n */\nexport function createJobsReader(loaders: Partial<DevtoolsJobsLoaders> = {}): DevtoolsJobsReader {\n const source = { ...defaultLoaders, ...loaders };\n\n return async () => {\n const report: DevtoolsJobsReport = {\n available: { scheduler: false, queue: false },\n schedules: [],\n queues: [],\n };\n\n try {\n const jobs = await source.scheduler();\n\n if (jobs) {\n report.available.scheduler = true;\n report.schedules = jobs.map(toSchedule);\n }\n } catch {\n report.available.scheduler = false;\n report.schedules = [];\n }\n\n try {\n const queues = await source.queue();\n\n if (queues) {\n report.available.queue = true;\n report.queues = queues;\n }\n } catch {\n report.available.queue = false;\n report.queues = [];\n }\n\n return report;\n };\n}\n","import type {\n DevtoolsCaptureCounters,\n DevtoolsInstanceInfo,\n DevtoolsInstanceReport,\n DevtoolsJobsReport,\n} from \"../contracts\";\nimport type {\n DevtoolsErrorGroups,\n DevtoolsProductionCapture,\n DevtoolsQueryStats,\n DevtoolsRecentLogs,\n DevtoolsRouteStatsStore,\n} from \"../capture/types\";\nimport type {\n DevtoolsHealthHistory,\n DevtoolsJobsReader,\n DevtoolsLocalReporter,\n DevtoolsResourceMonitor,\n} from \"./types\";\n\nconst emptyJobs = (): DevtoolsJobsReport => ({\n available: { scheduler: false, queue: false },\n schedules: [],\n queues: [],\n});\n\n/** This process's report from its parts (production: from the capture; development: from the dev stats). */\nexport function createLocalReporter(parts: {\n instance: DevtoolsInstanceInfo;\n resources: DevtoolsResourceMonitor;\n health: DevtoolsHealthHistory;\n jobs: DevtoolsJobsReader;\n queries: DevtoolsQueryStats;\n routes: DevtoolsRouteStatsStore;\n errors: DevtoolsErrorGroups;\n logs: DevtoolsRecentLogs;\n counters: DevtoolsProductionCapture[\"counters\"] | null;\n now?: () => number;\n}): DevtoolsLocalReporter {\n const now = parts.now ?? Date.now;\n\n return {\n instance: parts.instance,\n\n async snapshot() {\n const at = now();\n let jobs: DevtoolsJobsReport;\n\n try {\n jobs = await parts.jobs();\n } catch {\n jobs = emptyJobs();\n }\n\n const capture: DevtoolsCaptureCounters = parts.counters\n ? parts.counters()\n : {\n sampleRate: 1,\n requests: 0,\n sampled: 0,\n keptUnsampled: 0,\n stored: 0,\n droppedStored: 0,\n evictedShapes: parts.queries.evicted(),\n evictedRoutes: parts.routes.evicted(),\n evictedErrors: parts.errors.evicted(),\n droppedQueries: 0,\n };\n\n const report: DevtoolsInstanceReport = {\n instance: { ...parts.instance, seenAt: at },\n at,\n resources: { snapshot: parts.resources.snapshot(), history: parts.resources.history() },\n queries: parts.queries.snapshot(200),\n routes: parts.routes.snapshot(200),\n errors: parts.errors.snapshot(50),\n logs: parts.logs.snapshot(50),\n health: parts.health.report(),\n jobs,\n capture,\n };\n\n return report;\n },\n };\n}\n","import {\n constants,\n monitorEventLoopDelay,\n performance,\n PerformanceObserver,\n} from \"node:perf_hooks\";\nimport v8 from \"node:v8\";\nimport type { DevtoolsResourcePoint, DevtoolsResourceSnapshot } from \"../contracts\";\nimport type { DevtoolsResourceMonitor } from \"./types\";\n\ntype GcKind = keyof DevtoolsResourceSnapshot[\"gcByKind\"];\n\n/** The readings a monitor takes; replaced by fakes in specs. */\nexport type DevtoolsResourceSources = {\n now(): number;\n memoryUsage(): { rss: number; heapUsed: number; heapTotal: number; external: number };\n /** Microseconds, as `process.cpuUsage()`. */\n cpuUsage(): { user: number; system: number };\n heapLimit(): number;\n uptime(): number;\n /** Nanoseconds, as a `perf_hooks` interval histogram. */\n eventLoopDelay(): {\n enable(): unknown;\n disable(): unknown;\n reset(): void;\n percentile(percentile: number): number;\n readonly max: number;\n };\n eventLoopUtilization(): { idle: number; active: number };\n /** Calls `onGc` for every collection; returns the function that stops observing. */\n observeGc(onGc: (kind: GcKind, durationMs: number) => void): () => void;\n};\n\nfunction gcKindName(kind: number | undefined): GcKind {\n if (kind === constants.NODE_PERFORMANCE_GC_MAJOR) return \"major\";\n if (kind === constants.NODE_PERFORMANCE_GC_INCREMENTAL) return \"incremental\";\n if (kind === constants.NODE_PERFORMANCE_GC_WEAKCB) return \"weakcb\";\n\n return \"minor\";\n}\n\nconst defaultSources: DevtoolsResourceSources = {\n now: () => Date.now(),\n memoryUsage: () => process.memoryUsage(),\n cpuUsage: () => process.cpuUsage(),\n heapLimit: () => v8.getHeapStatistics().heap_size_limit,\n uptime: () => process.uptime(),\n eventLoopDelay: () => monitorEventLoopDelay({ resolution: 20 }),\n eventLoopUtilization: () => performance.eventLoopUtilization(),\n observeGc(onGc) {\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const detail = (entry as unknown as { detail?: { kind?: number }; kind?: number }).detail;\n const kind = detail?.kind ?? (entry as unknown as { kind?: number }).kind;\n\n onGc(gcKindName(kind), entry.duration);\n }\n });\n\n observer.observe({ entryTypes: [\"gc\"] });\n\n return () => observer.disconnect();\n },\n};\n\n/** Nanoseconds to milliseconds; a histogram with no samples reports 0. */\nfunction nsToMs(value: number): number {\n return Number.isFinite(value) && value > 0 && value < 1e15 ? value / 1e6 : 0;\n}\n\n/** Resource sampling every `intervalMs` (default 5000), `historySize` points (default 120). */\nexport function createResourceMonitor(\n options: {\n intervalMs?: number;\n historySize?: number;\n sources?: Partial<DevtoolsResourceSources>;\n } = {},\n): DevtoolsResourceMonitor {\n const intervalMs = options.intervalMs ?? 5000;\n const historySize = Math.max(1, options.historySize ?? 120);\n const sources: DevtoolsResourceSources = { ...defaultSources, ...options.sources };\n\n const loopDelay = sources.eventLoopDelay();\n const points: DevtoolsResourcePoint[] = [];\n const gcByKind: DevtoolsResourceSnapshot[\"gcByKind\"] = {\n minor: { count: 0, pauseMs: 0 },\n major: { count: 0, pauseMs: 0 },\n incremental: { count: 0, pauseMs: 0 },\n weakcb: { count: 0, pauseMs: 0 },\n };\n let gcCountSince = 0;\n let gcPauseSince = 0;\n let lastAt = sources.now();\n let lastCpu = sources.cpuUsage();\n let lastElu = sources.eventLoopUtilization();\n let timer: ReturnType<typeof setInterval> | undefined;\n let stopGc: (() => void) | undefined;\n\n function sample(): DevtoolsResourcePoint {\n const at = sources.now();\n const memory = sources.memoryUsage();\n const cpu = sources.cpuUsage();\n const elu = sources.eventLoopUtilization();\n const wallMs = at - lastAt;\n const cpuMs = (cpu.user + cpu.system - lastCpu.user - lastCpu.system) / 1000;\n const active = elu.active - lastElu.active;\n const idle = elu.idle - lastElu.idle;\n\n const point: DevtoolsResourcePoint = {\n at,\n rssBytes: memory.rss,\n heapUsedBytes: memory.heapUsed,\n heapTotalBytes: memory.heapTotal,\n externalBytes: memory.external,\n cpuPercent: wallMs > 0 ? Math.max(0, (cpuMs / wallMs) * 100) : 0,\n eventLoopDelayP50Ms: nsToMs(loopDelay.percentile(50)),\n eventLoopDelayP99Ms: nsToMs(loopDelay.percentile(99)),\n eventLoopDelayMaxMs: nsToMs(loopDelay.max),\n eventLoopUtilization: active + idle > 0 ? active / (active + idle) : 0,\n gcCount: gcCountSince,\n gcPauseMs: gcPauseSince,\n };\n\n loopDelay.reset();\n lastAt = at;\n lastCpu = cpu;\n lastElu = elu;\n gcCountSince = 0;\n gcPauseSince = 0;\n\n points.push(point);\n\n if (points.length > historySize) points.splice(0, points.length - historySize);\n\n return { ...point };\n }\n\n return {\n start() {\n if (timer) return;\n\n lastAt = sources.now();\n lastCpu = sources.cpuUsage();\n lastElu = sources.eventLoopUtilization();\n loopDelay.enable();\n stopGc = sources.observeGc((kind, durationMs) => {\n gcCountSince++;\n gcPauseSince += durationMs;\n gcByKind[kind].count++;\n gcByKind[kind].pauseMs += durationMs;\n });\n timer = setInterval(sample, intervalMs);\n timer.unref();\n },\n\n stop() {\n if (timer) clearInterval(timer);\n\n timer = undefined;\n stopGc?.();\n stopGc = undefined;\n loopDelay.disable();\n },\n\n sample,\n\n snapshot() {\n const latest = points[points.length - 1] ?? sample();\n\n return {\n ...latest,\n heapLimitBytes: sources.heapLimit(),\n uptimeSeconds: sources.uptime(),\n gcByKind: structuredClone(gcByKind),\n };\n },\n\n history() {\n return points.map((point) => ({ ...point }));\n },\n };\n}\n","import type { ResolvedDevtoolsProductionOptions } from \"../options\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport { capReportSize } from \"./cap-report\";\nimport type { DevtoolsLocalReporter, DevtoolsReportWriter } from \"./types\";\n\nconst HOUSEKEEPING_INTERVAL_MS = 10 * 60_000;\nconst REPORT_MAX_AGE_MS = 5 * 60_000;\nconst WARN_EVERY_MS = 60_000;\n\n/**\n * Writes the report every `production.reportIntervalMs`, and every 10\n * minutes prunes: reports unseen for 5 minutes, samples older than\n * `requestRetentionHours`, expired sessions and invites, share links that expired or were revoked more than 30 days ago, audit entries older\n * than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged\n * once per minute, never thrown.\n */\nexport function startReportWriter(input: {\n reporter: DevtoolsLocalReporter;\n store: DevtoolsStore;\n production: ResolvedDevtoolsProductionOptions;\n warn?: (message: string) => void;\n}): DevtoolsReportWriter {\n const { reporter, store, production, warn } = input;\n let stopped = false;\n let lastWarnAt = Number.NEGATIVE_INFINITY;\n let pending: Promise<void> = Promise.resolve();\n\n function fail(what: string, error: unknown): void {\n const now = Date.now();\n\n if (!warn || now - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = now;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${what}: ${reason}. It will try again.`);\n }\n\n async function write(): Promise<void> {\n if (stopped) return;\n\n try {\n await store.reports.write(capReportSize(await reporter.snapshot()));\n } catch (error) {\n fail(\"write this instance's report to the database\", error);\n }\n }\n\n async function housekeeping(): Promise<void> {\n if (stopped) return;\n\n const now = Date.now();\n const steps: [string, () => Promise<unknown>][] = [\n [\"remove old instance reports\", () => store.reports.prune(now - REPORT_MAX_AGE_MS)],\n [\n \"remove old request samples\",\n () => store.samples.prune(now - production.requestRetentionHours * 3_600_000),\n ],\n [\"remove expired sessions\", () => store.sessions.removeExpired(now)],\n [\"remove expired invites\", () => store.invites.removeExpired(now)],\n [\n \"remove old share links\",\n // Links that expired or were revoked more than 30 days ago; the table exists only when sharing is on.\n async () => (production.share.enabled ? store.shares.removeOld(now - 30 * 86_400_000) : 0),\n ],\n [\n \"remove old audit entries\",\n () => store.audit.prune(now - production.auditRetentionDays * 86_400_000),\n ],\n ];\n\n for (const [what, step] of steps) {\n try {\n await step();\n } catch (error) {\n fail(what, error);\n }\n }\n }\n\n function enqueue(task: () => Promise<void>): Promise<void> {\n pending = pending.then(task);\n\n return pending;\n }\n\n const writeTimer = setInterval(() => void enqueue(write), production.reportIntervalMs);\n const housekeepingTimer = setInterval(() => void enqueue(housekeeping), HOUSEKEEPING_INTERVAL_MS);\n\n writeTimer.unref();\n housekeepingTimer.unref();\n void enqueue(write);\n\n return {\n writeNow: () => enqueue(write),\n\n async stop() {\n stopped = true;\n clearInterval(writeTimer);\n clearInterval(housekeepingTimer);\n await pending;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAS,OAAyC,GAAa,GAAuB;CACpF,IAAI,MAAM,MAAM,OAAO;CACvB,IAAI,MAAM,MAAM,OAAO;CAEvB,OAAO,EAAE,aAAa,EAAE,aAAa,IAAI;AAC3C;;;;;;AAOA,SAAgB,qBACd,SACuD;CACvD,MAAM,yBAAS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,CACE,oCACM,MAAM,QAAQ,MAAM,MAAM,WAAW,wBAAwB,IAAS,CAC9E;GACA,CAAC,iCAAiC,MAAM,SAAS,cAAc,GAAG,CAAC;GACnE,CAAC,gCAAgC,MAAM,QAAQ,cAAc,GAAG,CAAC;GACjE,CACE,0BAEA,YAAa,WAAW,MAAM,UAAU,MAAM,OAAO,UAAU,MAAM,MAAe,IAAI,CAC1F;GACA,CACE,kCACM,MAAM,MAAM,MAAM,MAAM,WAAW,qBAAqB,KAAU,CAC1E;EACF;EAEA,KAAK,MAAM,CAAC,MAAM,SAAS,OACzB,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,KAAK,MAAM,KAAK;EAClB;CAEJ;CAEA,SAAS,QAAQ,MAA0C;EACzD,UAAU,QAAQ,KAAK,IAAI;EAE3B,OAAO;CACT;CAEA,MAAM,aAAa,kBAAkB,KAAK,QAAQ,KAAK,GAAG,WAAW,gBAAgB;CACrF,MAAM,oBAAoB,kBAAkB,KAAK,QAAQ,YAAY,GAAG,wBAAwB;CAEhG,WAAW,MAAM;CACjB,kBAAkB,MAAM;CACxB,AAAK,QAAQ,KAAK;CAElB,OAAO;EACL,gBAAgB,QAAQ,KAAK;EAE7B,MAAM,OAAO;GACX,UAAU;GACV,cAAc,UAAU;GACxB,cAAc,iBAAiB;GAC/B,MAAM;EACR;CACF;AACF"}
|
package/cjs/src-VyOjEEAo.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-VyOjEEAo.cjs","names":["DevtoolsApiError","createErrorRef","currentRequestId","LogChannel","toSafeValue","currentRequestId","currentRequestId","fileURLToPath","applyRedact","log","currentRequestId","toSafeValue","toSafeValue","createCollector","attachAiSource","attachAgentTraceSource","loadProcessPanel","processesDevtoolsPanel","loadDevtoolsPanels","DEVTOOLS_MOUNTED_KEY","DEVTOOLS_PRODUCTION_DEFAULTS","toAiUnavailableView","describeAiUnavailable","loadAiFeed","attachAiReports","resolveDevtoolsAiOptions","recentAiFailures","checkDevtoolsPanels"],"sources":["../../../../../../../packages/devtools/src/panel-errors.ts","../../../../../../../packages/devtools/src/options.ts","../../../../../../../packages/devtools/src/ai/reports/evaluate.ts","../../../../../../../packages/devtools/src/sources/cache-source.ts","../../../../../../../packages/devtools/src/sources/log-source.ts","../../../../../../../packages/devtools/src/sources/mail-source.ts","../../../../../../../packages/devtools/src/caller-location.ts","../../../../../../../packages/devtools/src/sources/query-source.ts","../../../../../../../packages/devtools/src/sources/tracing-source.ts","../../../../../../../packages/devtools/src/devtools-connector.ts","../../../../../../../packages/devtools/src/panel-tokens.ts"],"sourcesContent":["import type { DevtoolsErrorsView } from \"./production/contracts\";\nimport type { DevtoolsPanelErrorSummary } from \"./types\";\n\n/** Captured errors are offered to panels for the last hour. */\nconst WINDOW_MS = 3_600_000;\n\n/** The most error groups one read maps. */\nconst MAX_GROUPS = 500;\n\n/** The part of the insights a panel's error counts come from. */\ntype ErrorInsights = {\n errors(query: { instance: string; limit: number }): Promise<DevtoolsErrorsView>;\n};\n\n/**\n * What a panel factory receives as `context.errors`. Panels load before the\n * capture starts, so this reads through a source the connector binds once the\n * insights exist; until then (and when they never start) it answers an empty\n * list. Only counts, the route and the class name leave: no message, no stack.\n */\nexport type PanelErrorSource = {\n read: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n /** Binds the insights (development: this process; production: every instance). */\n bind(insights: ErrorInsights | null): void;\n};\n\nexport function createPanelErrorSource(now: () => number = Date.now): PanelErrorSource {\n let insights: ErrorInsights | null = null;\n\n return {\n bind(next) {\n insights = next;\n },\n async read() {\n if (insights === null) return [];\n\n const since = now() - WINDOW_MS;\n const view = await insights.errors({ instance: \"all\", limit: MAX_GROUPS });\n\n return view.groups\n .filter((group) => group.lastSeen >= since)\n .map((group) => ({\n route: group.route,\n status: group.status,\n name: group.name,\n source: group.source,\n count: group.count,\n firstSeen: group.firstSeen,\n lastSeen: group.lastSeen,\n }));\n },\n };\n}\n","import { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n // Validates the AI options; the mode defaults are applied where the mode is known.\n if (options.ai !== undefined) resolveDevtoolsAiOptions(options.ai, \"development\");\n\n return {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.ai === undefined ? {} : { ai: options.ai }),\n ...(options.production === undefined ? {} : { production: options.production }),\n };\n}\n","import type {\n DevtoolsAiEvaluateRequest,\n DevtoolsAiEvaluateResult,\n DevtoolsAiEvaluateView,\n} from \"../../production/contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../../production/errors\";\nimport type { DevtoolsAgentTraceSource } from \"../../sources/agent-trace-source\";\n\nconst MAX_PROMPTS = 50;\nconst MAX_RUNS_SCANNED = 300;\nconst MAX_SYSTEM_PROMPT = 100_000;\nconst MAX_INSTRUCTIONS = 4000;\nconst PREVIEW_LENGTH = 200;\n\ntype EvaluateModule = {\n getEvaluateConfig?: () => EvaluateConfigLike | undefined;\n evaluateSystemPrompt?: (\n systemPrompt: string,\n config: EvaluateConfigLike,\n instructions?: string,\n ) => Promise<{ score?: number; issues?: string[] }>;\n};\n\ntype ModelLike = { name?: string; provider?: string };\n\ntype EvaluateConfigLike = {\n model: ModelLike | (() => ModelLike | Promise<ModelLike>);\n instructions?: string;\n};\n\n/** What the Evaluate routes use; injected so specs need no model. */\nexport type DevtoolsAiEvaluator = {\n /** The page data: whether a judge is configured and the recent distinct system prompts. */\n view(): Promise<Extract<DevtoolsAiEvaluateView, { available: true }>>;\n /**\n * Grades a prompt with Panoptic's `evaluateSystemPrompt`. Throws\n * `DevtoolsApiError` `input.invalid` (both or neither of runId/systemPrompt,\n * sizes), `ai.evaluate-unavailable` (no judge configured),\n * `ai.prompt-not-found` (run gone or its text not kept) or\n * `ai.evaluate-failed` (the judge threw; logged with the reference).\n */\n evaluate(request: DevtoolsAiEvaluateRequest): Promise<DevtoolsAiEvaluateResult>;\n};\n\nfunction judgeLabel(model: ModelLike): string {\n return typeof model.provider === \"string\" && typeof model.name === \"string\"\n ? `${model.provider}/${model.name}`\n : (model.name ?? \"custom model\");\n}\n\n/** Builds the evaluator over the agent traces and Panoptic's evaluate helpers (loaded lazily). */\nexport function createAiEvaluator(input: {\n agentTraces: DevtoolsAgentTraceSource;\n load?: (name: string) => Promise<unknown>;\n warn?: (message: string) => void;\n}): DevtoolsAiEvaluator {\n const load = input.load ?? (() => import(\"@warlock.js/ai-panoptic\"));\n\n /** Panoptic's evaluate helpers, or `undefined` when Panoptic (or its evaluate support) is not there. */\n async function panoptic(): Promise<(EvaluateModule & Required<EvaluateModule>) | undefined> {\n try {\n const module = (await load(\"@warlock.js/ai-panoptic\")) as EvaluateModule;\n\n return typeof module.getEvaluateConfig === \"function\" &&\n typeof module.evaluateSystemPrompt === \"function\"\n ? (module as EvaluateModule & Required<EvaluateModule>)\n : undefined;\n } catch {\n return undefined;\n }\n }\n\n const unavailable = (): DevtoolsApiError => new DevtoolsApiError(\"ai.evaluate-unavailable\");\n\n return {\n async view() {\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n const byHash = new Map<\n string,\n { agents: string[]; runId: string; startedAt: string; text: string }\n >();\n const runs = input.agentTraces\n .list()\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0)\n .slice(0, MAX_RUNS_SCANNED);\n\n for (const run of runs) {\n const prompt = input.agentTraces.get(run.runId)?.systemPrompt;\n\n if (!prompt || typeof prompt.text !== \"string\" || prompt.text === \"\") continue;\n\n const known = byHash.get(prompt.hash);\n\n if (known) {\n if (!known.agents.includes(run.agent)) known.agents.push(run.agent);\n } else {\n byHash.set(prompt.hash, {\n agents: [run.agent],\n runId: run.runId,\n startedAt: run.startedAt,\n text: prompt.text,\n });\n }\n }\n\n return {\n available: true as const,\n configured: config !== undefined,\n judge:\n config === undefined\n ? null\n : typeof config.model === \"function\"\n ? \"custom model\"\n : judgeLabel(config.model),\n instructions: config?.instructions ?? \"\",\n prompts: [...byHash.entries()].slice(0, MAX_PROMPTS).map(([hash, item]) => ({\n hash,\n agents: item.agents,\n runId: item.runId,\n lastSeenAt: item.startedAt,\n preview: item.text.slice(0, PREVIEW_LENGTH),\n length: item.text.length,\n })),\n };\n },\n\n async evaluate(request) {\n const { runId, systemPrompt, instructions } = request;\n\n if ((runId === undefined) === (systemPrompt === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (\n (runId !== undefined && (typeof runId !== \"string\" || runId === \"\")) ||\n (systemPrompt !== undefined &&\n (typeof systemPrompt !== \"string\" ||\n systemPrompt.trim() === \"\" ||\n systemPrompt.length > MAX_SYSTEM_PROMPT)) ||\n (instructions !== undefined &&\n (typeof instructions !== \"string\" || instructions.length > MAX_INSTRUCTIONS))\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n if (!module || !config) throw unavailable();\n\n let text = systemPrompt;\n\n if (runId !== undefined) {\n text = input.agentTraces.get(runId)?.systemPrompt?.text;\n\n if (typeof text !== \"string\" || text === \"\")\n throw new DevtoolsApiError(\"ai.prompt-not-found\");\n }\n\n const started = Date.now();\n\n try {\n const model = typeof config.model === \"function\" ? await config.model() : config.model;\n const verdict = await module.evaluateSystemPrompt(\n text as string,\n { ...config, model },\n instructions,\n );\n\n return {\n score: typeof verdict.score === \"number\" ? verdict.score : null,\n issues: Array.isArray(verdict.issues) ? verdict.issues.map(String) : [],\n judge: judgeLabel(model),\n durationMs: Date.now() - started,\n };\n } catch (error) {\n const ref = createErrorRef();\n\n input.warn?.(\n `Devtools evaluate error ${ref}: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n throw new DevtoolsApiError(\"ai.evaluate-failed\", { ref, cause: error });\n }\n },\n };\n}\n","import { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCacheOperation, DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** Cache events the dashboard's waterfall and background bucket care about. */\nconst EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\n/** The shape `cache.on(event, handler)` hands the handler. */\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/**\n * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the\n * collector. A no-op when `@warlock.js/cache` isn't installed — it is an\n * optional peer.\n */\nexport async function attachCacheSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let cache: {\n on(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n off(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n };\n\n try {\n ({ cache } = await import(\"@warlock.js/cache\"));\n } catch {\n return () => {};\n }\n\n const handlers = EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) => {\n const operation: DevtoolsCacheOperation = {\n type,\n driver: data.driver,\n key: data.key,\n tags: data.tags,\n keys: data.keys,\n at: Date.now(),\n durationMs: data.durationMs,\n };\n\n collector.addCacheOperation(currentRequestId(), operation);\n };\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n return () => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n };\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry } from \"../types\";\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toDevtoolsLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\n/**\n * The entry's message as text. `request.log(error)` and friends log an Error\n * (or any value) as the message; kept as is, it reached the dashboard as `{}`.\n */\nfunction messageText(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (message instanceof Error) return `${message.name}: ${message.message}`;\n\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return String(message);\n }\n}\n\nclass DevtoolsLogChannel extends LogChannel {\n public override name = \"devtools\";\n public active = true;\n\n public constructor(private readonly collector: DevtoolsCollector) {\n super();\n }\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n // Already passed through the logger's redaction floor (`Logger.log`\n // applies it before invoking any channel). It is still app data, and can\n // hold live objects (a request, its socket), so a JSON-safe snapshot is\n // kept instead of the object itself.\n const entry: DevtoolsLogEntry = {\n level: toDevtoolsLevel(data.type),\n module: data.module,\n action: data.action,\n message: messageText(data.message),\n at: Date.now(),\n context: toSafeValue(data.context),\n };\n\n this.collector.addLog(currentRequestId(), entry);\n }\n}\n\n/**\n * Feeds every log entry, from `@warlock.js/logger`, into the collector by\n * registering an additional channel. `Logger` has no way to remove a\n * channel, so the disposer flag-ignores further entries instead — the\n * channel stays registered for the process's lifetime.\n */\nexport async function attachLogSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const channel = new DevtoolsLogChannel(collector);\n\n log.addChannel(channel);\n\n return () => {\n channel.active = false;\n };\n}\n","import type { CapturedMail, MailAddress, MailAttachment } from \"@warlock.js/core\";\nimport { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsMailAttachment } from \"../types\";\n\nfunction addressToString(address: MailAddress | undefined): string | undefined {\n if (!address) return undefined;\n\n return typeof address === \"string\" ? address : `${address.name} <${address.address}>`;\n}\n\nfunction attachmentSize(attachment: MailAttachment): number | undefined {\n if (typeof attachment.content === \"string\") return Buffer.byteLength(attachment.content);\n if (Buffer.isBuffer(attachment.content)) return attachment.content.length;\n\n return undefined;\n}\n\nfunction toDevtoolsAttachment(attachment: MailAttachment): DevtoolsMailAttachment {\n return {\n filename: attachment.filename,\n contentType: attachment.contentType,\n size: attachmentSize(attachment),\n };\n}\n\n/**\n * Feeds mails captured in development mode, from core's `mailEvents`, into\n * the collector. The captured attachments carry their content, but only\n * metadata is stored — the bytes are never kept.\n */\nexport async function attachMailSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const { mailEvents } = await import(\"@warlock.js/core\");\n\n const subscription = mailEvents.onCaptured((mail: CapturedMail) => {\n const { normalized } = mail;\n\n collector.addMail({\n id: mail.id,\n requestId: currentRequestId(),\n capturedAt: mail.timestamp.getTime(),\n from: addressToString(normalized.from),\n to: normalized.to,\n cc: normalized.cc,\n bcc: normalized.bcc,\n subject: normalized.subject,\n html: normalized.html,\n text: normalized.text,\n headers: normalized.headers,\n attachments: normalized.attachments.map(toDevtoolsAttachment),\n });\n });\n\n return () => subscription.unsubscribe();\n}\n","import { fileURLToPath } from \"node:url\";\n\nimport type { DevtoolsCallerLocation } from \"./types\";\n\nconst packageDirectory = normalizePath(fileURLToPath(new URL(\"../\", import.meta.url)));\n\n/** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */\nexport function captureCallerLocation(\n stack: string = new Error().stack ?? \"\",\n): DevtoolsCallerLocation | undefined {\n for (const line of stack.split(\"\\n\")) {\n const frame = parseFrame(line);\n if (!frame || shouldSkip(frame.file)) continue;\n return frame;\n }\n return undefined;\n}\n\nfunction parseFrame(frame: string): DevtoolsCallerLocation | undefined {\n const match = frame.match(/\\bat\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/);\n const [, rawFile, line, column] = match ?? [];\n if (!rawFile || !line || !column) return undefined;\n const file = normalizePath(rawFile);\n return { file, line: Number(line), column: Number(column) };\n}\n\n/** A drive-letter file URL names a Windows path on whichever host decodes it. */\nconst WINDOWS_DRIVE_FILE_URL = /^file:\\/\\/\\/[A-Za-z]:/;\n\nfunction normalizePath(path: string): string {\n const decoded = !path.startsWith(\"file:\")\n ? path\n : WINDOWS_DRIVE_FILE_URL.test(path)\n ? fileURLToPath(path, { windows: true })\n : fileURLToPath(path);\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction shouldSkip(file: string): boolean {\n return (\n file.startsWith(\"node:\") ||\n file.includes(\"/node_modules/\") ||\n // Node's own frames (`node:internal/…`, or bare `internal/…` on older\n // runtimes); an app folder named `internal` is still an app frame.\n file.startsWith(\"internal/\") ||\n file.startsWith(packageDirectory)\n );\n}\n","import { applyRedact, log } from \"@warlock.js/logger\";\nimport { captureCallerLocation } from \"../caller-location\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** The shape of the event `dataSourceRegistry` emits for `\"query\"`. */\ntype QueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** Redacts query bindings through the logger's redaction rules. */\nfunction redactBindings(bindings: unknown[] | undefined): unknown[] | undefined {\n if (!bindings) return bindings;\n\n const redacted = applyRedact(\n {\n type: \"debug\",\n module: \"devtools\",\n action: \"query\",\n message: undefined,\n context: { bindings },\n },\n log.getRedact(),\n );\n\n return (redacted.context as { bindings: unknown[] }).bindings;\n}\n\n/**\n * Feeds every settled database query, from cascade's data source registry,\n * into the collector. A no-op when `@warlock.js/cascade` isn't installed —\n * it is an optional peer.\n */\nexport async function attachQuerySource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: QueryEvent) => void): void;\n off(event: \"query\", listener: (event: QueryEvent) => void): void;\n };\n\n try {\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n } catch {\n return () => {};\n }\n\n const listener = (event: QueryEvent) => {\n collector.addQuery(currentRequestId(), {\n connection: event.connection,\n driver: event.driver,\n sql: event.sql,\n bindings: toSafeValue(redactBindings(event.bindings)) as unknown[] | undefined,\n collection: event.collection,\n command: event.command,\n pipeline: event.pipeline,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n rowCount: event.rowCount,\n error:\n event.error === undefined\n ? undefined\n : event.error instanceof Error\n ? event.error.message\n : String(event.error),\n caller: captureCallerLocation(),\n });\n };\n\n dataSourceRegistry.on(\"query\", listener);\n\n return () => dataSourceRegistry.off(\"query\", listener);\n}\n","import type { TracingContext, TracingPhaseInfo, TracingRequestEndInfo } from \"@warlock.js/core\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\n\n/**\n * Feeds request timelines from core's tracing hooks into the collector: one\n * `startRequest`/`endRequest` pair per HTTP request, with every named phase\n * in between. Requests to the dashboard's own path are never recorded, so\n * the dashboard never watches itself.\n */\nexport async function attachTracingSource(\n collector: DevtoolsCollector,\n options: ResolvedDevtoolsOptions,\n): Promise<DevtoolsDisposer> {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n const isDashboardPath = (path: string): boolean => path.startsWith(options.path);\n\n return registerTracingHooks({\n onRequestStart(ctx: TracingContext) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.startRequest({\n id: ctx.requestId,\n method: ctx.method,\n path: ctx.path,\n route: ctx.route,\n startedAt: performance.timeOrigin + performance.now(),\n });\n },\n onPhase(ctx: TracingContext, phase: TracingPhaseInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.addPhase(ctx.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,\n attrs:\n phase.attrs === undefined\n ? undefined\n : (toSafeValue(phase.attrs) as Record<string, unknown>),\n });\n },\n onRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.endRequest(ctx.requestId, {\n status: result.status,\n durationMs: result.durationMs,\n error:\n result.error === undefined\n ? undefined\n : result.error instanceof Error\n ? result.error.message\n : String(result.error),\n route: ctx.route,\n });\n },\n });\n}\n","/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createPanelErrorSource } from \"./panel-errors\";\nimport { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiReports, DEVTOOLS_MOUNTED_KEY, loadAiFeed } from \"./ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport { createAiEvaluator } from \"./ai/reports/evaluate\";\nimport { recentAiFailures } from \"./ai/reports/runs\";\nimport { attachAiSource, describeAiUnavailable, toAiUnavailableView } from \"./sources/ai-source\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const aiWiring = await wireDevelopmentAiReports(ai, resolved, core, log, disposers);\n const aiEvaluator = createAiEvaluator({\n agentTraces,\n warn: (message) => log.warn(\"devtools\", \"evaluate\", message),\n });\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panelErrors = createPanelErrorSource();\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n errors: panelErrors.read,\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n panelErrors.bind(insightsWiring.insights ?? null);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n aiReports: aiWiring,\n aiEvaluator,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = {\n path: resolved.path,\n mode: \"development\",\n };\n disposers.push(() => {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n });\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n // A disposer may return a promise (the AI totals' final flush): wait for it, never let one fail the rest.\n const finished: Promise<unknown>[] = [];\n\n for (const dispose of disposers.splice(0)) {\n try {\n finished.push(Promise.resolve(dispose()).catch(() => undefined));\n } catch {\n // The remaining disposers still run.\n }\n }\n\n await Promise.all(finished);\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts this process's AI totals in development: loads the Panoptic feed and\n * writes hourly rollups to `storage/devtools/ai-rollups`. Never throws; a\n * failure leaves the Reports, Models and Errors pages answering why.\n */\nasync function wireDevelopmentAiReports(\n ai: Awaited<ReturnType<typeof attachAiSource>>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<NonNullable<MountDevtoolsRoutesDeps[\"aiReports\"]>> {\n const none = (reason: \"ai-missing\" | \"reports-off\") => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n try {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, async dispose() {} };\n\n const reports = await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(resolved.ai, \"development\"),\n ...(typeof core.storagePath === \"function\"\n ? { directory: core.storagePath(\"devtools/ai-rollups\") }\n : {}),\n recentFailures: (filter) =>\n ai.available ? recentAiFailures(ai.store.query(), 50, filter) : [],\n warn: (message) => log.warn(\"devtools\", \"ai-reports\", message),\n });\n\n disposers.push(() => reports.dispose());\n\n return reports;\n } catch (error) {\n log.warn(\n \"devtools\",\n \"ai-reports\",\n `AI reports could not start: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return none(\"reports-off\");\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const panelErrors = createPanelErrorSource();\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n errors: panelErrors.read,\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n onInsights: (insights) => panelErrors.bind(insights),\n });\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n","/**\n * The CSS variables the dashboard defines for package panels, in both themes.\n *\n * A package panel's stylesheet may use only these variables, plus variables it\n * defines itself (in the same file). Anything else is undefined in the\n * dashboard and renders as the browser default, which is how a panel ends up\n * with unreadable text. The dashboard's own colours are checked for contrast\n * (4.5:1 for the text tokens on `--background` and `--card`) in both themes.\n */\nexport const DEVTOOLS_PANEL_TOKENS: readonly string[] = [\n \"--background\",\n \"--foreground\",\n \"--card\",\n \"--card-foreground\",\n \"--popover\",\n \"--popover-foreground\",\n \"--primary\",\n \"--primary-foreground\",\n \"--secondary\",\n \"--secondary-foreground\",\n \"--muted\",\n \"--muted-foreground\",\n \"--accent\",\n \"--accent-foreground\",\n \"--destructive\",\n \"--border\",\n \"--input\",\n \"--ring\",\n \"--radius\",\n \"--brand\",\n \"--brand-foreground\",\n \"--success\",\n \"--warning\",\n \"--info\",\n \"--chart-1\",\n \"--chart-2\",\n \"--chart-3\",\n \"--chart-4\",\n \"--chart-5\",\n];\n"],"mappings":";;;;;;;;;;;;;AAIA,MAAM,YAAY;;AAGlB,MAAM,aAAa;AAmBnB,SAAgB,uBAAuB,MAAoB,KAAK,KAAuB;CACrF,IAAI,WAAiC;CAErC,OAAO;EACL,KAAK,MAAM;GACT,WAAW;EACb;EACA,MAAM,OAAO;GACX,IAAI,aAAa,MAAM,OAAO,CAAC;GAE/B,MAAM,QAAQ,IAAI,IAAI;GAGtB,QAAO,MAFY,SAAS,OAAO;IAAE,UAAU;IAAO,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