@warlock.js/devtools 5.54.0 → 5.56.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 +36 -0
- package/README.md +26 -13
- package/cjs/{ai-source-CSPh1HqJ.cjs → ai-source-DTpxumMA.cjs} +54 -3
- package/cjs/{ai-source-CSPh1HqJ.cjs.map → ai-source-DTpxumMA.cjs.map} +1 -1
- package/cjs/auth-DzU0gHDG.cjs +1655 -0
- package/cjs/auth-DzU0gHDG.cjs.map +1 -0
- package/cjs/boot-BQi0Etor.cjs +138 -0
- package/cjs/boot-BQi0Etor.cjs.map +1 -0
- package/cjs/capture-CqIiaznN.cjs +1342 -0
- package/cjs/capture-CqIiaznN.cjs.map +1 -0
- package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
- package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
- package/cjs/collector-CJbQbzzK.cjs +271 -0
- package/cjs/collector-CJbQbzzK.cjs.map +1 -0
- package/cjs/contracts-CVmplkNb.cjs +112 -0
- package/cjs/contracts-CVmplkNb.cjs.map +1 -0
- package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
- package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
- package/cjs/errors-CyZp5yS-.cjs +177 -0
- package/cjs/errors-CyZp5yS-.cjs.map +1 -0
- package/cjs/histogram-BaI-PnCv.cjs +102 -0
- package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
- package/cjs/http-CabcUwBx.cjs +870 -0
- package/cjs/http-CabcUwBx.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/insights-BKtqxdnP.cjs +811 -0
- package/cjs/insights-BKtqxdnP.cjs.map +1 -0
- package/cjs/ip-DbNhPOzi.cjs +153 -0
- package/cjs/ip-DbNhPOzi.cjs.map +1 -0
- package/cjs/migrations-w7GMsrQw.cjs +297 -0
- package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
- package/cjs/openapi-CC7OAUc6.cjs +52 -0
- package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
- package/cjs/options-CWqFC5__.cjs +181 -0
- package/cjs/options-CWqFC5__.cjs.map +1 -0
- package/cjs/panels-B0dAfGbJ.cjs +298 -0
- package/cjs/panels-B0dAfGbJ.cjs.map +1 -0
- package/cjs/process-panel-DEOnLxoT.cjs +48 -0
- package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
- package/cjs/production/index.cjs +238 -0
- package/cjs/production/index.cjs.map +1 -0
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
- package/cjs/server-B6xdeKS8.cjs +184 -0
- package/cjs/server-B6xdeKS8.cjs.map +1 -0
- package/cjs/{src-BzuntLcd.cjs → src-Ce-3Lniv.cjs} +171 -308
- package/cjs/src-Ce-3Lniv.cjs.map +1 -0
- package/cjs/store-aq207T8v.cjs +9 -0
- package/cjs/stream-route-BGJa-zQu.cjs +875 -0
- package/cjs/stream-route-BGJa-zQu.cjs.map +1 -0
- package/esm/devtools-connector.d.mts +16 -12
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +137 -18
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +3 -1
- package/esm/options.mjs.map +1 -1
- package/esm/panels.mjs +267 -0
- package/esm/panels.mjs.map +1 -0
- package/esm/process-panel.mjs +20 -1
- package/esm/process-panel.mjs.map +1 -1
- package/esm/production/auth/common-passwords.mjs +303 -0
- package/esm/production/auth/common-passwords.mjs.map +1 -0
- package/esm/production/auth/default-crypto.mjs +19 -0
- package/esm/production/auth/default-crypto.mjs.map +1 -0
- package/esm/production/auth/helpers.mjs +77 -0
- package/esm/production/auth/helpers.mjs.map +1 -0
- package/esm/production/auth/index.mjs +6 -0
- package/esm/production/auth/passkeys.mjs +96 -0
- package/esm/production/auth/passkeys.mjs.map +1 -0
- package/esm/production/auth/service.mjs +1166 -0
- package/esm/production/auth/service.mjs.map +1 -0
- package/esm/production/boot.mjs +138 -0
- package/esm/production/boot.mjs.map +1 -0
- package/esm/production/capture/dev-stats.mjs +83 -0
- package/esm/production/capture/dev-stats.mjs.map +1 -0
- package/esm/production/capture/engine.mjs +442 -0
- package/esm/production/capture/engine.mjs.map +1 -0
- package/esm/production/capture/explain.mjs +271 -0
- package/esm/production/capture/explain.mjs.map +1 -0
- package/esm/production/capture/filter.mjs +24 -0
- package/esm/production/capture/filter.mjs.map +1 -0
- package/esm/production/capture/index.mjs +7 -0
- package/esm/production/capture/production-capture.mjs +134 -0
- package/esm/production/capture/production-capture.mjs.map +1 -0
- package/esm/production/capture/redact.mjs +109 -0
- package/esm/production/capture/redact.mjs.map +1 -0
- package/esm/production/capture/stats-stores.mjs +300 -0
- package/esm/production/capture/stats-stores.mjs.map +1 -0
- package/esm/production/cli/actions.mjs +151 -0
- package/esm/production/cli/actions.mjs.map +1 -0
- package/esm/production/cli/index.d.mts +17 -0
- package/esm/production/cli/index.d.mts.map +1 -0
- package/esm/production/cli/index.mjs +86 -0
- package/esm/production/cli/index.mjs.map +1 -0
- package/esm/production/contracts.d.mts +592 -0
- package/esm/production/contracts.d.mts.map +1 -0
- package/esm/production/contracts.mjs +95 -0
- package/esm/production/contracts.mjs.map +1 -0
- package/esm/production/errors.d.mts +31 -0
- package/esm/production/errors.d.mts.map +1 -0
- package/esm/production/errors.mjs +142 -0
- package/esm/production/errors.mjs.map +1 -0
- package/esm/production/http/access.mjs +124 -0
- package/esm/production/http/access.mjs.map +1 -0
- package/esm/production/http/auth-routes.mjs +280 -0
- package/esm/production/http/auth-routes.mjs.map +1 -0
- package/esm/production/http/client.mjs +57 -0
- package/esm/production/http/client.mjs.map +1 -0
- package/esm/production/http/constants.mjs +11 -0
- package/esm/production/http/constants.mjs.map +1 -0
- package/esm/production/http/context.mjs +14 -0
- package/esm/production/http/context.mjs.map +1 -0
- package/esm/production/http/cookie.mjs +39 -0
- package/esm/production/http/cookie.mjs.map +1 -0
- package/esm/production/http/headers.mjs +25 -0
- package/esm/production/http/headers.mjs.map +1 -0
- package/esm/production/http/index.mjs +10 -0
- package/esm/production/http/ip.mjs +130 -0
- package/esm/production/http/ip.mjs.map +1 -0
- package/esm/production/http/mount.mjs +300 -0
- package/esm/production/http/mount.mjs.map +1 -0
- package/esm/production/http/state.mjs +54 -0
- package/esm/production/http/state.mjs.map +1 -0
- package/esm/production/index.d.mts +6 -0
- package/esm/production/index.mjs +5 -0
- package/esm/production/insights/cap-report.mjs +67 -0
- package/esm/production/insights/cap-report.mjs.map +1 -0
- package/esm/production/insights/health.mjs +88 -0
- package/esm/production/insights/health.mjs.map +1 -0
- package/esm/production/insights/index.mjs +10 -0
- package/esm/production/insights/insights.mjs +167 -0
- package/esm/production/insights/insights.mjs.map +1 -0
- package/esm/production/insights/instance.mjs +24 -0
- package/esm/production/insights/instance.mjs.map +1 -0
- package/esm/production/insights/jobs.mjs +100 -0
- package/esm/production/insights/jobs.mjs.map +1 -0
- package/esm/production/insights/reporter.mjs +59 -0
- package/esm/production/insights/reporter.mjs.map +1 -0
- package/esm/production/insights/resources.mjs +139 -0
- package/esm/production/insights/resources.mjs.map +1 -0
- package/esm/production/insights/writer.mjs +72 -0
- package/esm/production/insights/writer.mjs.map +1 -0
- package/esm/production/openapi.mjs +52 -0
- package/esm/production/openapi.mjs.map +1 -0
- package/esm/production/options.d.mts +60 -0
- package/esm/production/options.d.mts.map +1 -0
- package/esm/production/options.mjs +170 -0
- package/esm/production/options.mjs.map +1 -0
- package/esm/production/stats/histogram.mjs +67 -0
- package/esm/production/stats/histogram.mjs.map +1 -0
- package/esm/production/stats/merge.mjs +106 -0
- package/esm/production/stats/merge.mjs.map +1 -0
- package/esm/production/store/cascade-store.mjs +322 -0
- package/esm/production/store/cascade-store.mjs.map +1 -0
- package/esm/production/store/index.mjs +5 -0
- package/esm/production/store/mapping.mjs +258 -0
- package/esm/production/store/mapping.mjs.map +1 -0
- package/esm/production/store/memory-store.mjs +291 -0
- package/esm/production/store/memory-store.mjs.map +1 -0
- package/esm/production/store/migrations.d.mts +11 -0
- package/esm/production/store/migrations.d.mts.map +1 -0
- package/esm/production/store/migrations.mjs +29 -0
- package/esm/production/store/migrations.mjs.map +1 -0
- package/esm/production/store/models/account.migration.mjs +34 -0
- package/esm/production/store/models/account.migration.mjs.map +1 -0
- package/esm/production/store/models/account.model.mjs +13 -0
- package/esm/production/store/models/account.model.mjs.map +1 -0
- package/esm/production/store/models/audit.migration.mjs +30 -0
- package/esm/production/store/models/audit.migration.mjs.map +1 -0
- package/esm/production/store/models/audit.model.mjs +13 -0
- package/esm/production/store/models/audit.model.mjs.map +1 -0
- package/esm/production/store/models/base.mjs +27 -0
- package/esm/production/store/models/base.mjs.map +1 -0
- package/esm/production/store/models/index.mjs +17 -0
- package/esm/production/store/models/invite.migration.mjs +26 -0
- package/esm/production/store/models/invite.migration.mjs.map +1 -0
- package/esm/production/store/models/invite.model.mjs +13 -0
- package/esm/production/store/models/invite.model.mjs.map +1 -0
- package/esm/production/store/models/report.migration.mjs +20 -0
- package/esm/production/store/models/report.migration.mjs.map +1 -0
- package/esm/production/store/models/report.model.mjs +13 -0
- package/esm/production/store/models/report.model.mjs.map +1 -0
- package/esm/production/store/models/sample.migration.mjs +25 -0
- package/esm/production/store/models/sample.migration.mjs.map +1 -0
- package/esm/production/store/models/sample.model.mjs +13 -0
- package/esm/production/store/models/sample.model.mjs.map +1 -0
- package/esm/production/store/models/session.migration.mjs +31 -0
- package/esm/production/store/models/session.migration.mjs.map +1 -0
- package/esm/production/store/models/session.model.mjs +13 -0
- package/esm/production/store/models/session.model.mjs.map +1 -0
- package/esm/production/store/models/state.migration.mjs +26 -0
- package/esm/production/store/models/state.migration.mjs.map +1 -0
- package/esm/production/store/models/state.model.mjs +13 -0
- package/esm/production/store/models/state.model.mjs.map +1 -0
- package/esm/query-shape.mjs +14 -1
- package/esm/query-shape.mjs.map +1 -1
- package/esm/server/explain-route.mjs +26 -1
- package/esm/server/explain-route.mjs.map +1 -1
- package/esm/server/index.mjs +16 -6
- package/esm/server/index.mjs.map +1 -1
- package/esm/server/insights-routes.mjs +62 -0
- package/esm/server/insights-routes.mjs.map +1 -0
- package/esm/server/log-routes.mjs +32 -5
- package/esm/server/log-routes.mjs.map +1 -1
- package/esm/server/openapi-routes.mjs +3 -2
- package/esm/server/openapi-routes.mjs.map +1 -1
- package/esm/server/panel-routes.mjs +44 -0
- package/esm/server/panel-routes.mjs.map +1 -0
- package/esm/server/requests-routes.mjs +125 -0
- package/esm/server/requests-routes.mjs.map +1 -1
- package/esm/server/session-routes.mjs +42 -0
- package/esm/server/session-routes.mjs.map +1 -0
- package/esm/server/stream-route.mjs +81 -11
- package/esm/server/stream-route.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +34 -12
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/sources/log-source.mjs +14 -1
- package/esm/sources/log-source.mjs.map +1 -1
- package/esm/types.d.mts +271 -1
- package/esm/types.d.mts.map +1 -1
- package/esm/ui-root.mjs +11 -6
- package/esm/ui-root.mjs.map +1 -1
- package/llms-full.txt +208 -19
- package/llms.txt +2 -2
- package/package.json +32 -8
- package/skills/SKILL.md +208 -19
- package/ui/dashboard/assets/app.css +3 -0
- package/ui/dashboard/assets/app.js +50 -0
- package/ui/dashboard/build-info.json +21 -0
- package/ui/dashboard/index.html +15 -0
- package/ui/panels/processes.js +15 -0
- package/cjs/server-BlQshJLE.cjs +0 -658
- package/cjs/server-BlQshJLE.cjs.map +0 -1
- package/cjs/src-BzuntLcd.cjs.map +0 -1
- package/esm/server/process-routes.mjs +0 -11
- package/esm/server/process-routes.mjs.map +0 -1
- package/ui/app.css +0 -376
- package/ui/app.js +0 -1054
- package/ui/index.html +0 -28
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cascade-store-pHjKeSFm.cjs","names":["rateLimitClient","DevtoolsStoreConflictError","randomUUID","rateLimitClient","DevtoolsProductionConfigError","randomUUID","DevtoolsStoreConflictError","rateLimitClient"],"sources":["../../../../../../../packages/devtools/src/production/store/mapping.ts","../../../../../../../packages/devtools/src/production/store/memory-store.ts","../../../../../../../packages/devtools/src/production/store/cascade-store.ts"],"sourcesContent":["import type { DevtoolsAuditEntry, DevtoolsInstanceReport } from \"../contracts\";\nimport { rateLimitClient } from \"../http/ip\";\nimport type {\n DevtoolsAccountPatch,\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsPasskeyRecord,\n DevtoolsSessionPatch,\n DevtoolsSessionRecord,\n DevtoolsStatePatch,\n DevtoolsStateRecord,\n DevtoolsStoredSample,\n} from \"./types\";\n\n/**\n * The record <-> row mapping of the cascade store. Rows use snake_case column\n * names; times are epoch milliseconds in integer columns on every driver.\n * Pure functions, so they are tested without a database.\n */\nexport type Row = Record<string, unknown>;\n\n/** A number from a column that a driver may return as a string (PostgreSQL `bigint`). */\nexport function toNumber(value: unknown): number {\n if (typeof value === \"number\") return value;\n\n const parsed = Number(value);\n\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\n/** Like `toNumber`, keeping `null` for a missing value. */\nexport function toNumberOrNull(value: unknown): number | null {\n return value === null || value === undefined ? null : toNumber(value);\n}\n\nexport function toStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nexport function toBoolean(value: unknown): boolean {\n return value === true || value === 1 || value === \"true\" || value === \"t\";\n}\n\n/** Parses JSON text; a value a driver already parsed passes through. */\nexport function parseJson<T>(value: unknown, fallback: T): T {\n if (typeof value === \"string\") {\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n }\n\n return value === null || value === undefined ? fallback : (value as T);\n}\n\nfunction toArray<T>(value: unknown): T[] {\n const parsed = parseJson<unknown>(value, []);\n\n return Array.isArray(parsed) ? (parsed as T[]) : [];\n}\n\n// ---------------------------------------------------------------------------\n// Accounts\n// ---------------------------------------------------------------------------\n\nconst ACCOUNT_COLUMNS = {\n email: \"email\",\n role: \"role\",\n passwordHash: \"password_hash\",\n passwordSource: \"password_source\",\n mustChangePassword: \"must_change_password\",\n totpSecret: \"totp_secret\",\n totpEnabledAt: \"totp_enabled_at\",\n totpLastStep: \"totp_last_step\",\n recoveryCodes: \"recovery_codes\",\n passkeys: \"passkeys\",\n failuresResetAt: \"failures_reset_at\",\n createdAt: \"created_at\",\n updatedAt: \"updated_at\",\n lastLoginAt: \"last_login_at\",\n createdBy: \"created_by\",\n version: \"version\",\n} as const satisfies Record<keyof Omit<DevtoolsAccountRecord, \"id\">, string>;\n\nexport function accountToRow(record: DevtoolsAccountRecord): Row {\n return { id: record.id, ...fieldsToRow(ACCOUNT_COLUMNS, record) };\n}\n\nexport function accountPatchToRow(patch: DevtoolsAccountPatch): Row {\n return fieldsToRow(ACCOUNT_COLUMNS, patch);\n}\n\nexport function rowToAccount(row: Row): DevtoolsAccountRecord {\n return {\n id: String(row.id),\n email: String(row.email),\n role: row.role as DevtoolsAccountRecord[\"role\"],\n passwordHash: String(row.password_hash),\n passwordSource: row.password_source as DevtoolsAccountRecord[\"passwordSource\"],\n mustChangePassword: toBoolean(row.must_change_password),\n totpSecret: toStringOrNull(row.totp_secret),\n totpEnabledAt: toNumberOrNull(row.totp_enabled_at),\n totpLastStep: toNumberOrNull(row.totp_last_step),\n recoveryCodes: toArray<string>(row.recovery_codes),\n passkeys: toArray<DevtoolsPasskeyRecord>(row.passkeys),\n failuresResetAt: toNumberOrNull(row.failures_reset_at),\n createdAt: toNumber(row.created_at),\n updatedAt: toNumber(row.updated_at),\n lastLoginAt: toNumberOrNull(row.last_login_at),\n createdBy: toStringOrNull(row.created_by),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nconst SESSION_COLUMNS = {\n tokenHash: \"token_hash\",\n accountId: \"account_id\",\n stage: \"stage\",\n csrfSecret: \"csrf_secret\",\n createdAt: \"created_at\",\n lastSeenAt: \"last_seen_at\",\n expiresAt: \"expires_at\",\n ip: \"ip\",\n userAgent: \"user_agent\",\n pendingTotpSecret: \"pending_totp_secret\",\n challenge: \"challenge\",\n challengeExpiresAt: \"challenge_expires_at\",\n version: \"version\",\n} as const satisfies Record<keyof Omit<DevtoolsSessionRecord, \"id\">, string>;\n\nexport function sessionToRow(record: DevtoolsSessionRecord): Row {\n return { id: record.id, ...fieldsToRow(SESSION_COLUMNS, record) };\n}\n\nexport function sessionPatchToRow(patch: DevtoolsSessionPatch): Row {\n return fieldsToRow(SESSION_COLUMNS, patch);\n}\n\nexport function rowToSession(row: Row): DevtoolsSessionRecord {\n return {\n id: String(row.id),\n tokenHash: String(row.token_hash),\n accountId: String(row.account_id),\n stage: row.stage as DevtoolsSessionRecord[\"stage\"],\n csrfSecret: String(row.csrf_secret),\n createdAt: toNumber(row.created_at),\n lastSeenAt: toNumber(row.last_seen_at),\n expiresAt: toNumber(row.expires_at),\n ip: toStringOrNull(row.ip),\n userAgent: toStringOrNull(row.user_agent),\n pendingTotpSecret: toStringOrNull(row.pending_totp_secret),\n challenge: toStringOrNull(row.challenge),\n challengeExpiresAt: toNumberOrNull(row.challenge_expires_at),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Invites\n// ---------------------------------------------------------------------------\n\nexport function inviteToRow(record: DevtoolsInviteRecord): Row {\n return {\n id: record.id,\n token_hash: record.tokenHash,\n email: record.email,\n role: record.role,\n created_by: record.createdBy,\n created_at: record.createdAt,\n expires_at: record.expiresAt,\n used_at: record.usedAt,\n account_id: record.accountId,\n };\n}\n\nexport function rowToInvite(row: Row): DevtoolsInviteRecord {\n return {\n id: String(row.id),\n tokenHash: String(row.token_hash),\n email: String(row.email),\n role: row.role as DevtoolsInviteRecord[\"role\"],\n createdBy: toStringOrNull(row.created_by),\n createdAt: toNumber(row.created_at),\n expiresAt: toNumber(row.expires_at),\n usedAt: toNumberOrNull(row.used_at),\n accountId: toStringOrNull(row.account_id),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Audit\n// ---------------------------------------------------------------------------\n\nexport function auditToRow(entry: DevtoolsAuditEntry): Row {\n return {\n id: entry.id,\n type: entry.type,\n occurred_at: entry.at,\n account_id: entry.accountId,\n email: entry.email,\n ip: entry.ip,\n // What the per-IP limit counts by: the address, or its /64 for IPv6.\n ip_bucket: entry.ip === null ? null : rateLimitClient(entry.ip),\n user_agent: entry.userAgent,\n detail: entry.detail,\n ref: entry.ref,\n };\n}\n\nexport function rowToAudit(row: Row): DevtoolsAuditEntry {\n return {\n id: String(row.id),\n at: toNumber(row.occurred_at),\n type: row.type as DevtoolsAuditEntry[\"type\"],\n accountId: toStringOrNull(row.account_id),\n email: toStringOrNull(row.email),\n ip: toStringOrNull(row.ip),\n userAgent: toStringOrNull(row.user_agent),\n detail: parseJson<DevtoolsAuditEntry[\"detail\"]>(row.detail, {}),\n ref: String(row.ref),\n };\n}\n\n// ---------------------------------------------------------------------------\n// State\n// ---------------------------------------------------------------------------\n\nconst STATE_COLUMNS = {\n disabled: \"disabled\",\n disabledPathHash: \"disabled_path_hash\",\n disabledAt: \"disabled_at\",\n disabledBy: \"disabled_by\",\n lockedUntil: \"locked_until\",\n failuresResetAt: \"failures_reset_at\",\n updatedAt: \"updated_at\",\n version: \"version\",\n} as const satisfies Record<keyof DevtoolsStateRecord, string>;\n\nexport function stateToRow(record: DevtoolsStateRecord): Row {\n return fieldsToRow(STATE_COLUMNS, record);\n}\n\nexport function statePatchToRow(patch: DevtoolsStatePatch): Row {\n return fieldsToRow(STATE_COLUMNS, patch);\n}\n\nexport function rowToState(row: Row): DevtoolsStateRecord {\n return {\n disabled: toBoolean(row.disabled),\n disabledPathHash: toStringOrNull(row.disabled_path_hash),\n disabledAt: toNumberOrNull(row.disabled_at),\n disabledBy: toStringOrNull(row.disabled_by),\n lockedUntil: toNumberOrNull(row.locked_until),\n failuresResetAt: toNumberOrNull(row.failures_reset_at),\n updatedAt: toNumber(row.updated_at),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Samples and reports\n// ---------------------------------------------------------------------------\n\n/**\n * `detail` is JSON text, not a JSON column: a sample holds keys from request\n * data (headers, query names) and MongoDB rejects or misreads field names\n * that start with `$` or contain dots.\n */\nexport function sampleToRow(sample: DevtoolsStoredSample): Row {\n return {\n id: sample.id,\n instance: sample.instance,\n started_at: sample.startedAt,\n status: sample.summary.status ?? null,\n method: sample.summary.method.toUpperCase(),\n path: sample.summary.path,\n summary: sample.summary,\n detail: sample.detail === null ? null : JSON.stringify(sample.detail),\n };\n}\n\nexport function rowToSampleSummary(row: Row): DevtoolsStoredSample[\"summary\"] {\n return parseJson<DevtoolsStoredSample[\"summary\"]>(row.summary, {} as never);\n}\n\nexport function rowToSample(row: Row): DevtoolsStoredSample {\n const detail = row.detail;\n\n return {\n id: String(row.id),\n instance: String(row.instance),\n startedAt: toNumber(row.started_at),\n summary: parseJson<DevtoolsStoredSample[\"summary\"]>(row.summary, {} as never),\n detail:\n detail === null || detail === undefined\n ? null\n : parseJson<DevtoolsStoredSample[\"detail\"]>(detail, null),\n };\n}\n\n/** `data` is JSON text for the same reason as a sample's `detail`. */\nexport function reportToRow(report: DevtoolsInstanceReport): Row {\n return {\n id: report.instance.id,\n seen_at: report.at,\n data: JSON.stringify(report),\n };\n}\n\nexport function rowToReport(row: Row): DevtoolsInstanceReport {\n return parseJson<DevtoolsInstanceReport>(row.data, {} as never);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Maps the defined fields of `source` to their columns. */\nfunction fieldsToRow(columns: Record<string, string>, source: object): Row {\n const row: Row = {};\n const values = source as Record<string, unknown>;\n\n for (const [field, column] of Object.entries(columns)) {\n const value = values[field];\n\n if (value !== undefined) row[column] = value;\n }\n\n return row;\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n DevtoolsAuditEntry,\n DevtoolsInstanceReport,\n DevtoolsSampleSummary,\n} from \"../contracts\";\nimport { DevtoolsStoreConflictError } from \"../errors\";\nimport { rateLimitClient } from \"../http/ip\";\nimport type {\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsSampleFilter,\n DevtoolsSessionRecord,\n DevtoolsStateRecord,\n DevtoolsStore,\n DevtoolsStoredSample,\n} from \"./types\";\n\n/** A structural copy, so callers never hold the store's own objects. */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n\n/** The state row before anything was written. */\nexport function defaultStateRecord(now = 0): DevtoolsStateRecord {\n return {\n disabled: false,\n disabledPathHash: null,\n disabledAt: null,\n disabledBy: null,\n lockedUntil: null,\n failuresResetAt: null,\n updatedAt: now,\n version: 0,\n };\n}\n\n/** Whether `status` matches a sample filter value: `\"5xx\"`, `\"4xx\"`, `\"404\"`. */\nexport function sampleStatusMatches(filter: string, status: number | undefined): boolean {\n if (status === undefined) return false;\n\n const value = filter.trim().toLowerCase();\n\n if (/^[1-5]xx$/.test(value)) return Math.floor(status / 100) === Number(value[0]);\n\n return String(status) === value;\n}\n\n/** Whether a sample summary passes `filter` (everything but `limit`). */\nexport function sampleMatches(\n summary: DevtoolsSampleSummary,\n filter: DevtoolsSampleFilter,\n): boolean {\n if (filter.status !== undefined && !sampleStatusMatches(filter.status, summary.status))\n return false;\n if (filter.method !== undefined && summary.method.toUpperCase() !== filter.method.toUpperCase()) {\n return false;\n }\n\n if (filter.route !== undefined) {\n const needle = filter.route.toLowerCase();\n const haystack = `${summary.route ?? \"\"} ${summary.path}`.toLowerCase();\n\n if (!haystack.includes(needle)) return false;\n }\n\n if (filter.q !== undefined && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) {\n return false;\n }\n\n if (filter.since !== undefined && summary.startedAt < filter.since) return false;\n if (filter.until !== undefined && summary.startedAt > filter.until) return false;\n if (filter.instance !== undefined && summary.instance !== filter.instance) return false;\n\n return true;\n}\n\n/**\n * An in-process `DevtoolsStore` for specs (and nothing else: it is neither\n * shared between processes nor kept across restarts). It follows the store\n * contract exactly, compare-and-set included, so a spec written against it\n * holds for the database store too.\n *\n * `now` is read for `updatedAt` stamps; pass a fake clock in specs.\n */\nexport function createMemoryStore(options: { now?: () => number } = {}): DevtoolsStore {\n const now = options.now ?? Date.now;\n const accounts = new Map<string, DevtoolsAccountRecord>();\n const sessions = new Map<string, DevtoolsSessionRecord>();\n const invites = new Map<string, DevtoolsInviteRecord>();\n const audit: DevtoolsAuditEntry[] = [];\n const samples = new Map<string, DevtoolsStoredSample>();\n const reports = new Map<string, DevtoolsInstanceReport>();\n let state: DevtoolsStateRecord | null = null;\n\n return {\n async verify() {},\n\n accounts: {\n async findByEmail(email) {\n for (const account of accounts.values()) {\n if (account.email === email) return copy(account);\n }\n\n return null;\n },\n async findById(id) {\n const account = accounts.get(id);\n\n return account ? copy(account) : null;\n },\n async list() {\n return [...accounts.values()].sort((a, b) => a.createdAt - b.createdAt).map(copy);\n },\n async countAdmins() {\n return [...accounts.values()].filter((account) => account.role === \"admin\").length;\n },\n async create(input) {\n for (const account of accounts.values()) {\n if (account.email === input.email) throw new DevtoolsStoreConflictError(\"email\");\n }\n\n const at = now();\n const record: DevtoolsAccountRecord = {\n ...copy(input),\n id: randomUUID(),\n createdAt: at,\n updatedAt: at,\n version: 1,\n };\n\n accounts.set(record.id, record);\n\n return copy(record);\n },\n async update(id, expectedVersion, patch) {\n const current = accounts.get(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n if (patch.email !== undefined && patch.email !== current.email) {\n for (const account of accounts.values()) {\n if (account.email === patch.email) throw new DevtoolsStoreConflictError(\"email\");\n }\n }\n\n const next: DevtoolsAccountRecord = {\n ...current,\n ...copy(patch),\n id,\n createdAt: current.createdAt,\n updatedAt: now(),\n version: current.version + 1,\n };\n\n accounts.set(id, next);\n\n return copy(next);\n },\n async remove(id) {\n return accounts.delete(id);\n },\n },\n\n sessions: {\n async create(input) {\n const record: DevtoolsSessionRecord = { ...copy(input), id: randomUUID(), version: 1 };\n\n sessions.set(record.id, record);\n\n return copy(record);\n },\n async findByTokenHash(tokenHash) {\n for (const session of sessions.values()) {\n if (session.tokenHash === tokenHash) return copy(session);\n }\n\n return null;\n },\n async listForAccount(accountId) {\n return [...sessions.values()]\n .filter((session) => session.accountId === accountId)\n .sort((a, b) => b.createdAt - a.createdAt)\n .map(copy);\n },\n async update(id, expectedVersion, patch) {\n const current = sessions.get(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n const next: DevtoolsSessionRecord = {\n ...current,\n ...copy(patch),\n id,\n accountId: current.accountId,\n version: current.version + 1,\n };\n\n sessions.set(id, next);\n\n return copy(next);\n },\n async remove(id) {\n return sessions.delete(id);\n },\n async removeForAccount(accountId, exceptId) {\n let removed = 0;\n\n for (const session of [...sessions.values()]) {\n if (session.accountId === accountId && session.id !== exceptId) {\n sessions.delete(session.id);\n removed++;\n }\n }\n\n return removed;\n },\n async removeExpired(at) {\n let removed = 0;\n\n for (const session of [...sessions.values()]) {\n if (session.expiresAt < at) {\n sessions.delete(session.id);\n removed++;\n }\n }\n\n return removed;\n },\n },\n\n invites: {\n async create(input) {\n const record: DevtoolsInviteRecord = {\n ...copy(input),\n id: randomUUID(),\n usedAt: null,\n accountId: null,\n };\n\n invites.set(record.id, record);\n\n return copy(record);\n },\n async findByTokenHash(tokenHash) {\n for (const invite of invites.values()) {\n if (invite.tokenHash === tokenHash) return copy(invite);\n }\n\n return null;\n },\n async list(listOptions = {}) {\n return [...invites.values()]\n .filter((invite) => listOptions.includeUsed === true || invite.usedAt === null)\n .sort((a, b) => b.createdAt - a.createdAt)\n .map(copy);\n },\n async markUsed(id, at, accountId) {\n const invite = invites.get(id);\n\n if (!invite || invite.usedAt !== null || at >= invite.expiresAt) return false;\n\n invites.set(id, { ...invite, usedAt: at, accountId });\n\n return true;\n },\n async remove(id) {\n return invites.delete(id);\n },\n async removeExpired(at) {\n let removed = 0;\n\n for (const invite of [...invites.values()]) {\n if (invite.usedAt === null && invite.expiresAt < at) {\n invites.delete(invite.id);\n removed++;\n }\n }\n\n return removed;\n },\n },\n\n audit: {\n async append(entry) {\n const record: DevtoolsAuditEntry = { ...copy(entry), id: randomUUID() };\n\n audit.push(record);\n\n return copy(record);\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(500, filter.limit));\n\n return audit\n .filter(\n (entry) =>\n (filter.types === undefined || filter.types.includes(entry.type)) &&\n (filter.accountId === undefined || entry.accountId === filter.accountId) &&\n (filter.before === undefined || entry.at < filter.before),\n )\n .sort((a, b) => b.at - a.at)\n .slice(0, limit)\n .map(copy);\n },\n async count(filter) {\n return audit.filter(\n (entry) =>\n filter.types.includes(entry.type) &&\n entry.at >= filter.since &&\n (filter.accountId === undefined || entry.accountId === filter.accountId) &&\n (filter.ip === undefined ||\n (entry.ip !== null && rateLimitClient(entry.ip) === rateLimitClient(filter.ip))),\n ).length;\n },\n async prune(before) {\n const kept = audit.filter((entry) => entry.at >= before);\n const removed = audit.length - kept.length;\n\n audit.splice(0, audit.length, ...kept);\n\n return removed;\n },\n },\n\n state: {\n async read() {\n return copy(state ?? defaultStateRecord(now()));\n },\n async update(expectedVersion, patch) {\n const current = state ?? defaultStateRecord(now());\n\n if (current.version !== expectedVersion) return null;\n\n state = { ...current, ...copy(patch), updatedAt: now(), version: current.version + 1 };\n\n return copy(state);\n },\n },\n\n samples: {\n async insert(list) {\n for (const sample of list) samples.set(sample.id, copy(sample));\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(1000, filter.limit));\n\n return [...samples.values()]\n .map((sample) => sample.summary)\n .filter((summary) => sampleMatches(summary, filter))\n .sort((a, b) => b.startedAt - a.startedAt)\n .slice(0, limit)\n .map(copy);\n },\n async get(id) {\n const sample = samples.get(id);\n\n return sample ? copy(sample) : null;\n },\n async prune(before) {\n let removed = 0;\n\n for (const sample of [...samples.values()]) {\n if (sample.startedAt < before) {\n samples.delete(sample.id);\n removed++;\n }\n }\n\n return removed;\n },\n async clear() {\n const removed = samples.size;\n\n samples.clear();\n\n return removed;\n },\n },\n\n reports: {\n async write(report) {\n reports.set(report.instance.id, copy(report));\n },\n async list(seenSince) {\n return [...reports.values()]\n .filter((report) => report.at >= seenSince)\n .sort((a, b) => b.at - a.at)\n .map(copy);\n },\n async prune(seenBefore) {\n let removed = 0;\n\n for (const report of [...reports.values()]) {\n if (report.at < seenBefore) {\n reports.delete(report.instance.id);\n removed++;\n }\n }\n\n return removed;\n },\n async remove(instanceId) {\n return reports.delete(instanceId);\n },\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { DevtoolsAuditEntry, DevtoolsInstanceReport } from \"../contracts\";\nimport { DevtoolsProductionConfigError, DevtoolsStoreConflictError } from \"../errors\";\nimport { rateLimitClient } from \"../http/ip\";\nimport {\n accountPatchToRow,\n accountToRow,\n auditToRow,\n inviteToRow,\n reportToRow,\n rowToAccount,\n rowToAudit,\n rowToInvite,\n rowToReport,\n rowToSample,\n rowToSampleSummary,\n rowToSession,\n rowToState,\n sampleToRow,\n sessionPatchToRow,\n sessionToRow,\n statePatchToRow,\n stateToRow,\n type Row,\n} from \"./mapping\";\nimport { defaultStateRecord, sampleMatches } from \"./memory-store\";\nimport type {\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsSessionRecord,\n DevtoolsStore,\n} from \"./types\";\n\ntype ModelsModule = typeof import(\"./models\");\n\n/** The part of cascade's query builder this store uses. */\ninterface RowQuery {\n where(field: string, operator: string, value: unknown): RowQuery;\n whereIn(field: string, values: unknown[]): RowQuery;\n whereNull(field: string): RowQuery;\n orderBy(field: string, direction: \"asc\" | \"desc\"): RowQuery;\n limit(value: number): RowQuery;\n select(fields: string[]): RowQuery;\n get(): Promise<Row[]>;\n first(): Promise<Row | null>;\n delete(): Promise<number>;\n count(): Promise<number>;\n}\n\n/** The part of a cascade model class this store uses (every table class has this shape). */\ntype RowClass = ModelsModule[\"DevtoolsAccountRow\"];\n\nexport type CascadeStoreOptions = {\n /** The clock for `updatedAt` stamps; defaults to `Date.now`. */\n now?: () => number;\n};\n\n/** The most rows scanned for a sample filter the database cannot apply (route, text). */\nconst SAMPLE_SCAN_LIMIT = 5000;\n\n/** A plain-row query (no model instances). */\nfunction rows(table: RowClass): RowQuery {\n return table.query().lean() as unknown as RowQuery;\n}\n\n/** A query for counting and deleting. */\nfunction query(table: RowClass): RowQuery {\n return table.query() as unknown as RowQuery;\n}\n\nfunction byId(table: RowClass, id: string): Promise<Row | null> {\n return rows(table).where(\"id\", \"=\", id).first();\n}\n\nasync function insert(table: RowClass, row: Row): Promise<void> {\n await table.create(row as never);\n}\n\nasync function removeWhere(table: RowClass, field: string, value: unknown): Promise<boolean> {\n return (await query(table).where(field, \"=\", value).delete()) > 0;\n}\n\n/** Applies `$set` to the row only while its `version` still equals `expected`. */\nasync function compareAndSet(\n table: RowClass,\n id: string,\n expected: number,\n set: Row,\n): Promise<boolean> {\n const updated = await table.atomic({ id, version: expected }, { $set: set });\n\n return updated > 0;\n}\n\n/**\n * The production `DevtoolsStore`: the app's database through\n * `@warlock.js/cascade` (MongoDB or SQL), using the models in `./models` and\n * the tables `devtoolsMigrations` creates. Imports cascade lazily so loading\n * this module never requires it.\n *\n * Throws `DevtoolsProductionConfigError(\"DT005\")` when cascade is not\n * installed or has no connection.\n */\nexport async function createCascadeStore(\n options: CascadeStoreOptions = {},\n): Promise<DevtoolsStore> {\n const now = options.now ?? Date.now;\n let models: ModelsModule;\n\n try {\n models = await import(\"./models\");\n // Throws when the app has no data source.\n models.DevtoolsAccountRow.getDataSource();\n } catch (error) {\n throw new DevtoolsProductionConfigError(\n \"DT005\",\n error instanceof Error ? `(${error.message})` : undefined,\n );\n }\n\n const {\n DevtoolsAccountRow: Accounts,\n DevtoolsSessionRow: Sessions,\n DevtoolsInviteRow: Invites,\n DevtoolsAuditRow: Audit,\n DevtoolsStateRow: State,\n DevtoolsSampleRow: Samples,\n DevtoolsReportRow: Reports,\n } = models;\n const tables: RowClass[] = [Accounts, Sessions, Invites, Audit, State, Samples, Reports];\n\n const accountById = async (id: string): Promise<DevtoolsAccountRecord | null> => {\n const row = await byId(Accounts, id);\n\n return row ? rowToAccount(row) : null;\n };\n const sessionById = async (id: string): Promise<DevtoolsSessionRecord | null> => {\n const row = await byId(Sessions, id);\n\n return row ? rowToSession(row) : null;\n };\n\n return {\n async verify() {\n const blueprint = Accounts.getDriver().blueprint;\n const missing: string[] = [];\n\n for (const table of tables) {\n if (!(await blueprint.tableExists(table.table))) missing.push(table.table);\n }\n\n if (missing.length > 0) {\n throw new DevtoolsProductionConfigError(\"DT008\", `(missing: ${missing.join(\", \")})`);\n }\n },\n\n accounts: {\n async findByEmail(email) {\n const row = await rows(Accounts).where(\"email\", \"=\", email).first();\n\n return row ? rowToAccount(row) : null;\n },\n findById: accountById,\n async list() {\n const found = await rows(Accounts).orderBy(\"created_at\", \"asc\").get();\n\n return found.map(rowToAccount);\n },\n async countAdmins() {\n return query(Accounts).where(\"role\", \"=\", \"admin\").count();\n },\n async create(input) {\n const at = now();\n const record: DevtoolsAccountRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n createdAt: at,\n updatedAt: at,\n version: 1,\n };\n\n if (await rows(Accounts).where(\"email\", \"=\", record.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n try {\n await insert(Accounts, accountToRow(record));\n } catch (error) {\n // A concurrent request took the email between the check and the insert.\n if (await rows(Accounts).where(\"email\", \"=\", record.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n throw error;\n }\n\n return record;\n },\n async update(id, expectedVersion, patch) {\n const current = await accountById(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n if (patch.email !== undefined && patch.email !== current.email) {\n if (await rows(Accounts).where(\"email\", \"=\", patch.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n }\n\n const set = {\n ...accountPatchToRow(structuredClone(patch)),\n updated_at: now(),\n version: expectedVersion + 1,\n };\n let won: boolean;\n\n try {\n won = await compareAndSet(Accounts, id, expectedVersion, set);\n } catch (error) {\n if (\n patch.email !== undefined &&\n (await rows(Accounts).where(\"email\", \"=\", patch.email).first())\n ) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n throw error;\n }\n\n return won ? accountById(id) : null;\n },\n async remove(id) {\n return removeWhere(Accounts, \"id\", id);\n },\n },\n\n sessions: {\n async create(input) {\n const record: DevtoolsSessionRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n version: 1,\n };\n\n await insert(Sessions, sessionToRow(record));\n\n return record;\n },\n async findByTokenHash(tokenHash) {\n const row = await rows(Sessions).where(\"token_hash\", \"=\", tokenHash).first();\n\n return row ? rowToSession(row) : null;\n },\n async listForAccount(accountId) {\n const found = await rows(Sessions)\n .where(\"account_id\", \"=\", accountId)\n .orderBy(\"created_at\", \"desc\")\n .get();\n\n return found.map(rowToSession);\n },\n async update(id, expectedVersion, patch) {\n const set = { ...sessionPatchToRow(structuredClone(patch)), version: expectedVersion + 1 };\n\n if (!(await compareAndSet(Sessions, id, expectedVersion, set))) return null;\n\n return sessionById(id);\n },\n async remove(id) {\n return removeWhere(Sessions, \"id\", id);\n },\n async removeForAccount(accountId, exceptId) {\n const target = query(Sessions).where(\"account_id\", \"=\", accountId);\n\n if (exceptId !== undefined) target.where(\"id\", \"!=\", exceptId);\n\n return target.delete();\n },\n async removeExpired(at) {\n return query(Sessions).where(\"expires_at\", \"<\", at).delete();\n },\n },\n\n invites: {\n async create(input) {\n const record: DevtoolsInviteRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n usedAt: null,\n accountId: null,\n };\n\n await insert(Invites, inviteToRow(record));\n\n return record;\n },\n async findByTokenHash(tokenHash) {\n const row = await rows(Invites).where(\"token_hash\", \"=\", tokenHash).first();\n\n return row ? rowToInvite(row) : null;\n },\n async list(listOptions = {}) {\n const target = rows(Invites);\n\n if (listOptions.includeUsed !== true) target.whereNull(\"used_at\");\n\n return (await target.orderBy(\"created_at\", \"desc\").get()).map(rowToInvite);\n },\n async markUsed(id, at, accountId) {\n const updated = await Invites.atomic(\n { id, used_at: null, expires_at: { $gt: at } },\n { $set: { used_at: at, account_id: accountId } },\n // Code-authored filter; nothing here comes from a request.\n { trustedFilter: true },\n );\n\n return updated > 0;\n },\n async remove(id) {\n return removeWhere(Invites, \"id\", id);\n },\n async removeExpired(at) {\n return query(Invites).whereNull(\"used_at\").where(\"expires_at\", \"<\", at).delete();\n },\n },\n\n audit: {\n async append(entry) {\n const record: DevtoolsAuditEntry = { ...structuredClone(entry), id: randomUUID() };\n\n await insert(Audit, auditToRow(record));\n\n return record;\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(500, filter.limit));\n const target = rows(Audit);\n\n if (filter.types !== undefined) target.whereIn(\"type\", [...filter.types]);\n if (filter.accountId !== undefined) target.where(\"account_id\", \"=\", filter.accountId);\n if (filter.before !== undefined) target.where(\"occurred_at\", \"<\", filter.before);\n\n const found = await target.orderBy(\"occurred_at\", \"desc\").limit(limit).get();\n\n return found.map(rowToAudit);\n },\n async count(filter) {\n const target = query(Audit)\n .whereIn(\"type\", [...filter.types])\n .where(\"occurred_at\", \">=\", filter.since);\n\n if (filter.accountId !== undefined) target.where(\"account_id\", \"=\", filter.accountId);\n if (filter.ip !== undefined) target.where(\"ip_bucket\", \"=\", rateLimitClient(filter.ip));\n\n return target.count();\n },\n async prune(before) {\n return query(Audit).where(\"occurred_at\", \"<\", before).delete();\n },\n },\n\n state: {\n async read() {\n const row = await byId(State, \"state\");\n\n return row ? rowToState(row) : defaultStateRecord(now());\n },\n async update(expectedVersion, patch) {\n const row = await byId(State, \"state\");\n\n if (!row) {\n if (expectedVersion !== 0) return null;\n\n const record = {\n ...defaultStateRecord(now()),\n ...structuredClone(patch),\n updatedAt: now(),\n version: 1,\n };\n\n try {\n await insert(State, { id: \"state\", ...stateToRow(record) });\n } catch {\n // Another process wrote the first row; this write lost the race.\n return null;\n }\n\n return record;\n }\n\n const set = {\n ...statePatchToRow(structuredClone(patch)),\n updated_at: now(),\n version: expectedVersion + 1,\n };\n\n if (!(await compareAndSet(State, \"state\", expectedVersion, set))) return null;\n\n const next = await byId(State, \"state\");\n\n return next ? rowToState(next) : null;\n },\n },\n\n samples: {\n async insert(list) {\n for (const sample of list) {\n const { id, ...data } = sampleToRow(structuredClone(sample));\n\n await Samples.upsert({ id } as never, data as never);\n }\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(1000, filter.limit));\n const target = rows(Samples).select([\"summary\"]);\n const exact = !(filter.route !== undefined || filter.q !== undefined);\n\n if (filter.status !== undefined) {\n const status = filter.status.trim().toLowerCase();\n\n if (/^[1-5]xx$/.test(status)) {\n const base = Number(status[0]) * 100;\n\n target.where(\"status\", \">=\", base).where(\"status\", \"<\", base + 100);\n } else if (/^\\d+$/.test(status) && String(Number(status)) === status) {\n target.where(\"status\", \"=\", Number(status));\n } else {\n return [];\n }\n }\n\n if (filter.method !== undefined) target.where(\"method\", \"=\", filter.method.toUpperCase());\n if (filter.since !== undefined) target.where(\"started_at\", \">=\", filter.since);\n if (filter.until !== undefined) target.where(\"started_at\", \"<=\", filter.until);\n if (filter.instance !== undefined) target.where(\"instance\", \"=\", filter.instance);\n\n const found = await target\n .orderBy(\"started_at\", \"desc\")\n .limit(exact ? limit : SAMPLE_SCAN_LIMIT)\n .get();\n\n // Route and text filters are substring matches the databases do not\n // share, so they run here, with the same rules as the memory store.\n return found\n .map(rowToSampleSummary)\n .filter((summary) => sampleMatches(summary, filter))\n .slice(0, limit);\n },\n async get(id) {\n const row = await byId(Samples, id);\n\n return row ? rowToSample(row) : null;\n },\n async prune(before) {\n return query(Samples).where(\"started_at\", \"<\", before).delete();\n },\n async clear() {\n return query(Samples).where(\"started_at\", \">=\", 0).delete();\n },\n },\n\n reports: {\n async write(report: DevtoolsInstanceReport) {\n const { id, ...data } = reportToRow(report);\n\n await Reports.upsert({ id } as never, data as never);\n },\n async list(seenSince) {\n const found = await rows(Reports)\n .where(\"seen_at\", \">=\", seenSince)\n .orderBy(\"seen_at\", \"desc\")\n .get();\n\n return found.map(rowToReport);\n },\n async prune(seenBefore) {\n return query(Reports).where(\"seen_at\", \"<\", seenBefore).delete();\n },\n async remove(instanceId) {\n return removeWhere(Reports, \"id\", instanceId);\n },\n },\n };\n}\n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QAAQ,WAAW,MAAM,CAAC,CAC1B,IAAI,EAEK,CAAC,IAAI,WAAW;GAC9B;GACA,MAAM,MAAM,YAAY;IACtB,OAAO,MAAM,OAAO,CAAC,CAAC,MAAM,WAAW,KAAK,UAAU,CAAC,CAAC,OAAO;GACjE;GACA,MAAM,OAAO,YAAY;IACvB,OAAO,YAAY,SAAS,MAAM,UAAU;GAC9C;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
//#region ../../packages/devtools/src/n-plus-one.ts
|
|
2
|
+
/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */
|
|
3
|
+
function detectNPlusOne(queries, threshold) {
|
|
4
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5
|
+
for (const query of queries) groups.set(query.shape, [...groups.get(query.shape) ?? [], query]);
|
|
6
|
+
return [...groups.entries()].filter(([, grouped]) => grouped.length >= threshold).sort(([, left], [, right]) => right.length - left.length).map(([shape, grouped]) => ({
|
|
7
|
+
type: "n+1",
|
|
8
|
+
shape,
|
|
9
|
+
count: grouped.length,
|
|
10
|
+
message: `N+1: ${grouped.length}× "${truncate(shape, 120)}"`,
|
|
11
|
+
...mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}
|
|
12
|
+
}));
|
|
13
|
+
}
|
|
14
|
+
function truncate(value, maximum) {
|
|
15
|
+
return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;
|
|
16
|
+
}
|
|
17
|
+
function mostFrequentCaller(queries) {
|
|
18
|
+
const callers = /* @__PURE__ */ new Map();
|
|
19
|
+
for (const query of queries) {
|
|
20
|
+
if (!query.caller) continue;
|
|
21
|
+
const key = `${query.caller.file}:${query.caller.line}`;
|
|
22
|
+
const found = callers.get(key);
|
|
23
|
+
callers.set(key, found ? {
|
|
24
|
+
...found,
|
|
25
|
+
count: found.count + 1
|
|
26
|
+
} : {
|
|
27
|
+
caller: query.caller,
|
|
28
|
+
count: 1
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region ../../packages/devtools/src/query-shape.ts
|
|
36
|
+
const numericLiteral = /(?<![\w$])[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?![\w$])/g;
|
|
37
|
+
const quotedLiteral = /'(?:''|[^'])*'/g;
|
|
38
|
+
const dollarQuotedLiteral = /(\$[A-Za-z_]*\$)[\s\S]*?\1/g;
|
|
39
|
+
const postgresShapes = /* @__PURE__ */ new Map();
|
|
40
|
+
const POSTGRES_SHAPE_CACHE = 1e3;
|
|
41
|
+
/** Returns a binding-independent shape for a database query. */
|
|
42
|
+
function queryShape(query) {
|
|
43
|
+
if (query.driver === "postgres") {
|
|
44
|
+
const sql = query.sql ?? "";
|
|
45
|
+
const known = postgresShapes.get(sql);
|
|
46
|
+
if (known !== void 0) return known;
|
|
47
|
+
const shape = sql.replace(quotedLiteral, "?").replace(dollarQuotedLiteral, "?").replace(numericLiteral, "?").replace(/\s+/g, " ").trim();
|
|
48
|
+
if (sql.length <= 4e3) {
|
|
49
|
+
if (postgresShapes.size >= POSTGRES_SHAPE_CACHE) postgresShapes.clear();
|
|
50
|
+
postgresShapes.set(sql, shape);
|
|
51
|
+
}
|
|
52
|
+
return shape;
|
|
53
|
+
}
|
|
54
|
+
return `${query.collection ?? ""}.${query.command ?? ""} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;
|
|
55
|
+
}
|
|
56
|
+
function normalizeMongoValue(value) {
|
|
57
|
+
if (isMongoLeaf(value)) return "?";
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
if (value.every(isMongoLeaf)) return ["?"];
|
|
60
|
+
return value.map(normalizeMongoValue);
|
|
61
|
+
}
|
|
62
|
+
const record = value;
|
|
63
|
+
return Object.fromEntries(Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]));
|
|
64
|
+
}
|
|
65
|
+
function isMongoLeaf(value) {
|
|
66
|
+
if (value === null || typeof value !== "object") return true;
|
|
67
|
+
if (value instanceof Date) return true;
|
|
68
|
+
const record = value;
|
|
69
|
+
return typeof record.toHexString === "function" || typeof record.$oid === "string";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region ../../packages/devtools/src/collector.ts
|
|
74
|
+
const mailLimit = 100;
|
|
75
|
+
const logLimit = 1e3;
|
|
76
|
+
const backgroundLimit = 500;
|
|
77
|
+
/**
|
|
78
|
+
* Creates the in-memory devtools store.
|
|
79
|
+
*
|
|
80
|
+
* Read methods return shallow structural copies, including copied arrays, so consumers
|
|
81
|
+
* cannot mutate collector-owned arrays. The individual nested entries are retained.
|
|
82
|
+
*/
|
|
83
|
+
function createCollector(options) {
|
|
84
|
+
const requests = /* @__PURE__ */ new Map();
|
|
85
|
+
const mails = /* @__PURE__ */ new Map();
|
|
86
|
+
const logs = [];
|
|
87
|
+
const background = {
|
|
88
|
+
queries: [],
|
|
89
|
+
cache: [],
|
|
90
|
+
logs: []
|
|
91
|
+
};
|
|
92
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
93
|
+
let querySequence = 0;
|
|
94
|
+
const emit = (event) => {
|
|
95
|
+
for (const listener of listeners) try {
|
|
96
|
+
listener(event);
|
|
97
|
+
} catch {}
|
|
98
|
+
};
|
|
99
|
+
const addBackground = (list, value) => {
|
|
100
|
+
list.push(value);
|
|
101
|
+
if (list.length > backgroundLimit) list.shift();
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
startRequest(request) {
|
|
105
|
+
requests.delete(request.id);
|
|
106
|
+
requests.set(request.id, {
|
|
107
|
+
...request,
|
|
108
|
+
phases: [],
|
|
109
|
+
queries: [],
|
|
110
|
+
cache: [],
|
|
111
|
+
logs: [],
|
|
112
|
+
mails: [],
|
|
113
|
+
warnings: []
|
|
114
|
+
});
|
|
115
|
+
while (requests.size > options.maxRequests) requests.delete(requests.keys().next().value);
|
|
116
|
+
},
|
|
117
|
+
endRequest(id, result) {
|
|
118
|
+
const request = requests.get(id);
|
|
119
|
+
if (!request) return;
|
|
120
|
+
request.status = result.status;
|
|
121
|
+
request.durationMs = result.durationMs;
|
|
122
|
+
request.error = result.error;
|
|
123
|
+
if (result.route !== void 0) request.route = result.route;
|
|
124
|
+
request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);
|
|
125
|
+
emit({
|
|
126
|
+
type: "request",
|
|
127
|
+
data: summary(request)
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
addPhase(requestId, phase) {
|
|
131
|
+
requests.get(requestId)?.phases.push(phase);
|
|
132
|
+
},
|
|
133
|
+
addQuery(requestId, query) {
|
|
134
|
+
const stored = {
|
|
135
|
+
...query,
|
|
136
|
+
id: `q${++querySequence}`,
|
|
137
|
+
shape: queryShape(query)
|
|
138
|
+
};
|
|
139
|
+
const request = requestId ? requests.get(requestId) : void 0;
|
|
140
|
+
if (request) request.queries.push(stored);
|
|
141
|
+
else addBackground(background.queries, stored);
|
|
142
|
+
return stored;
|
|
143
|
+
},
|
|
144
|
+
addCacheOperation(requestId, operation) {
|
|
145
|
+
const request = requestId ? requests.get(requestId) : void 0;
|
|
146
|
+
if (request) request.cache.push(operation);
|
|
147
|
+
else addBackground(background.cache, operation);
|
|
148
|
+
},
|
|
149
|
+
addLog(requestId, entry) {
|
|
150
|
+
const request = requestId ? requests.get(requestId) : void 0;
|
|
151
|
+
if (request) request.logs.push(entry);
|
|
152
|
+
else addBackground(background.logs, entry);
|
|
153
|
+
logs.unshift(entry);
|
|
154
|
+
if (logs.length > logLimit) logs.pop();
|
|
155
|
+
emit({
|
|
156
|
+
type: "log",
|
|
157
|
+
data: entry
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
addMail(mail) {
|
|
161
|
+
mails.delete(mail.id);
|
|
162
|
+
mails.set(mail.id, mail);
|
|
163
|
+
while (mails.size > mailLimit) mails.delete(mails.keys().next().value);
|
|
164
|
+
if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);
|
|
165
|
+
emit({
|
|
166
|
+
type: "mail",
|
|
167
|
+
data: mailSummary(mail)
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
listRequests() {
|
|
171
|
+
return [...requests.values()].reverse().map(summary);
|
|
172
|
+
},
|
|
173
|
+
getRequest(id) {
|
|
174
|
+
const request = requests.get(id);
|
|
175
|
+
return request && copyRequest(request);
|
|
176
|
+
},
|
|
177
|
+
listMails() {
|
|
178
|
+
return [...mails.values()].reverse().map(mailSummary);
|
|
179
|
+
},
|
|
180
|
+
getMail(id) {
|
|
181
|
+
const mail = mails.get(id);
|
|
182
|
+
return mail && {
|
|
183
|
+
...mail,
|
|
184
|
+
to: [...mail.to],
|
|
185
|
+
cc: [...mail.cc],
|
|
186
|
+
bcc: [...mail.bcc],
|
|
187
|
+
headers: { ...mail.headers },
|
|
188
|
+
attachments: [...mail.attachments]
|
|
189
|
+
};
|
|
190
|
+
},
|
|
191
|
+
listLogs(filter = {}) {
|
|
192
|
+
const module = filter.module?.toLowerCase();
|
|
193
|
+
return logs.filter((entry) => (!filter.level || entry.level === filter.level) && (!module || entry.module.toLowerCase().includes(module))).map((entry) => ({ ...entry }));
|
|
194
|
+
},
|
|
195
|
+
getBackground() {
|
|
196
|
+
return {
|
|
197
|
+
queries: [...background.queries],
|
|
198
|
+
cache: [...background.cache],
|
|
199
|
+
logs: [...background.logs]
|
|
200
|
+
};
|
|
201
|
+
},
|
|
202
|
+
subscribe(listener) {
|
|
203
|
+
listeners.add(listener);
|
|
204
|
+
return () => listeners.delete(listener);
|
|
205
|
+
},
|
|
206
|
+
clear() {
|
|
207
|
+
requests.clear();
|
|
208
|
+
mails.clear();
|
|
209
|
+
logs.length = 0;
|
|
210
|
+
background.queries.length = 0;
|
|
211
|
+
background.cache.length = 0;
|
|
212
|
+
background.logs.length = 0;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function summary(request) {
|
|
217
|
+
const { id, method, path, route, status, startedAt, durationMs } = request;
|
|
218
|
+
return {
|
|
219
|
+
id,
|
|
220
|
+
method,
|
|
221
|
+
path,
|
|
222
|
+
route,
|
|
223
|
+
status,
|
|
224
|
+
startedAt,
|
|
225
|
+
durationMs,
|
|
226
|
+
queryCount: request.queries.length,
|
|
227
|
+
warningCount: request.warnings.length
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function mailSummary(mail) {
|
|
231
|
+
const { id, requestId, capturedAt, to, subject } = mail;
|
|
232
|
+
return {
|
|
233
|
+
id,
|
|
234
|
+
requestId,
|
|
235
|
+
capturedAt,
|
|
236
|
+
to: [...to],
|
|
237
|
+
subject
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function copyRequest(request) {
|
|
241
|
+
return {
|
|
242
|
+
...request,
|
|
243
|
+
phases: [...request.phases],
|
|
244
|
+
queries: [...request.queries],
|
|
245
|
+
cache: [...request.cache],
|
|
246
|
+
logs: [...request.logs],
|
|
247
|
+
mails: [...request.mails],
|
|
248
|
+
warnings: [...request.warnings]
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
//#endregion
|
|
253
|
+
Object.defineProperty(exports, "createCollector", {
|
|
254
|
+
enumerable: true,
|
|
255
|
+
get: function () {
|
|
256
|
+
return createCollector;
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
Object.defineProperty(exports, "detectNPlusOne", {
|
|
260
|
+
enumerable: true,
|
|
261
|
+
get: function () {
|
|
262
|
+
return detectNPlusOne;
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
Object.defineProperty(exports, "queryShape", {
|
|
266
|
+
enumerable: true,
|
|
267
|
+
get: function () {
|
|
268
|
+
return queryShape;
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
//# sourceMappingURL=collector-CJbQbzzK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collector-CJbQbzzK.cjs","names":[],"sources":["../../../../../../../packages/devtools/src/n-plus-one.ts","../../../../../../../packages/devtools/src/query-shape.ts","../../../../../../../packages/devtools/src/collector.ts"],"sourcesContent":["import type { DevtoolsCallerLocation, DevtoolsQuery, DevtoolsWarning } from \"./types\";\n\n/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */\nexport function detectNPlusOne(queries: DevtoolsQuery[], threshold: number): DevtoolsWarning[] {\n const groups = new Map<string, DevtoolsQuery[]>();\n for (const query of queries) groups.set(query.shape, [...(groups.get(query.shape) ?? []), query]);\n\n return [...groups.entries()]\n .filter(([, grouped]) => grouped.length >= threshold)\n .sort(([, left], [, right]) => right.length - left.length)\n .map(([shape, grouped]) => ({\n type: \"n+1\" as const,\n shape,\n count: grouped.length,\n message: `N+1: ${grouped.length}× \"${truncate(shape, 120)}\"`,\n ...(mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}),\n }));\n}\n\nfunction truncate(value: string, maximum: number): string {\n return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;\n}\n\nfunction mostFrequentCaller(queries: DevtoolsQuery[]): DevtoolsCallerLocation | undefined {\n const callers = new Map<string, { caller: DevtoolsCallerLocation; count: number }>();\n for (const query of queries) {\n if (!query.caller) continue;\n const key = `${query.caller.file}:${query.caller.line}`;\n const found = callers.get(key);\n callers.set(\n key,\n found ? { ...found, count: found.count + 1 } : { caller: query.caller, count: 1 },\n );\n }\n return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;\n}\n","import type { DevtoolsQuery } from \"./types\";\n\ntype QueryShapeInput = Pick<\n DevtoolsQuery,\n \"driver\" | \"sql\" | \"collection\" | \"command\" | \"pipeline\"\n>;\n\nconst numericLiteral = /(?<![\\w$])[-+]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?![\\w$])/g;\nconst quotedLiteral = /'(?:''|[^'])*'/g;\nconst dollarQuotedLiteral = /(\\$[A-Za-z_]*\\$)[\\s\\S]*?\\1/g;\n\nconst postgresShapes = new Map<string, string>();\nconst POSTGRES_SHAPE_CACHE = 1000;\n\n/** Returns a binding-independent shape for a database query. */\nexport function queryShape(query: QueryShapeInput): string {\n if (query.driver === \"postgres\") {\n const sql = query.sql ?? \"\";\n // An app runs the same few statements over and over; the shape of a statement never changes.\n const known = postgresShapes.get(sql);\n\n if (known !== undefined) return known;\n\n const shape = sql\n .replace(quotedLiteral, \"?\")\n .replace(dollarQuotedLiteral, \"?\")\n .replace(numericLiteral, \"?\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n // Statements with inlined values are mostly one-off: only short ones are worth remembering.\n if (sql.length <= 4000) {\n if (postgresShapes.size >= POSTGRES_SHAPE_CACHE) postgresShapes.clear();\n\n postgresShapes.set(sql, shape);\n }\n\n return shape;\n }\n\n return `${query.collection ?? \"\"}.${query.command ?? \"\"} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;\n}\n\nfunction normalizeMongoValue(value: unknown): unknown {\n if (isMongoLeaf(value)) return \"?\";\n\n if (Array.isArray(value)) {\n if (value.every(isMongoLeaf)) return [\"?\"];\n return value.map(normalizeMongoValue);\n }\n\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]),\n );\n}\n\nfunction isMongoLeaf(value: unknown): boolean {\n if (value === null || typeof value !== \"object\") return true;\n if (value instanceof Date) return true;\n const record = value as Record<string, unknown>;\n return typeof record.toHexString === \"function\" || typeof record.$oid === \"string\";\n}\n","import type {\n DevtoolsBackground,\n DevtoolsCollector,\n DevtoolsDisposer,\n DevtoolsLogEntry,\n DevtoolsMail,\n DevtoolsMailSummary,\n DevtoolsQuery,\n DevtoolsRequest,\n DevtoolsRequestSummary,\n DevtoolsStreamEvent,\n ResolvedDevtoolsOptions,\n} from \"./types\";\nimport { detectNPlusOne } from \"./n-plus-one\";\nimport { queryShape } from \"./query-shape\";\n\nconst mailLimit = 100;\nconst logLimit = 1000;\nconst backgroundLimit = 500;\n\n/**\n * Creates the in-memory devtools store.\n *\n * Read methods return shallow structural copies, including copied arrays, so consumers\n * cannot mutate collector-owned arrays. The individual nested entries are retained.\n */\nexport function createCollector(options: ResolvedDevtoolsOptions): DevtoolsCollector {\n const requests = new Map<string, DevtoolsRequest>();\n const mails = new Map<string, DevtoolsMail>();\n const logs: DevtoolsLogEntry[] = [];\n const background: DevtoolsBackground = { queries: [], cache: [], logs: [] };\n const listeners = new Set<(event: DevtoolsStreamEvent) => void>();\n let querySequence = 0;\n\n const emit = (event: DevtoolsStreamEvent) => {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch {\n /* Subscribers must not affect collection. */\n }\n }\n };\n\n const addBackground = <T>(list: T[], value: T) => {\n list.push(value);\n if (list.length > backgroundLimit) list.shift();\n };\n\n return {\n startRequest(request) {\n requests.delete(request.id);\n requests.set(request.id, {\n ...request,\n phases: [],\n queries: [],\n cache: [],\n logs: [],\n mails: [],\n warnings: [],\n });\n while (requests.size > options.maxRequests)\n requests.delete(requests.keys().next().value as string);\n },\n endRequest(id, result) {\n const request = requests.get(id);\n if (!request) return;\n request.status = result.status;\n request.durationMs = result.durationMs;\n request.error = result.error;\n if (result.route !== undefined) request.route = result.route;\n request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);\n emit({ type: \"request\", data: summary(request) });\n },\n addPhase(requestId, phase) {\n requests.get(requestId)?.phases.push(phase);\n },\n addQuery(requestId, query) {\n const stored: DevtoolsQuery = {\n ...query,\n id: `q${++querySequence}`,\n shape: queryShape(query),\n };\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.queries.push(stored);\n else addBackground(background.queries, stored);\n return stored;\n },\n addCacheOperation(requestId, operation) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.cache.push(operation);\n else addBackground(background.cache, operation);\n },\n addLog(requestId, entry) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.logs.push(entry);\n else addBackground(background.logs, entry);\n logs.unshift(entry);\n if (logs.length > logLimit) logs.pop();\n emit({ type: \"log\", data: entry });\n },\n addMail(mail) {\n mails.delete(mail.id);\n mails.set(mail.id, mail);\n while (mails.size > mailLimit) mails.delete(mails.keys().next().value as string);\n if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);\n emit({ type: \"mail\", data: mailSummary(mail) });\n },\n listRequests() {\n return [...requests.values()].reverse().map(summary);\n },\n getRequest(id) {\n const request = requests.get(id);\n return request && copyRequest(request);\n },\n listMails() {\n return [...mails.values()].reverse().map(mailSummary);\n },\n getMail(id) {\n const mail = mails.get(id);\n return (\n mail && {\n ...mail,\n to: [...mail.to],\n cc: [...mail.cc],\n bcc: [...mail.bcc],\n headers: { ...mail.headers },\n attachments: [...mail.attachments],\n }\n );\n },\n listLogs(filter = {}) {\n const module = filter.module?.toLowerCase();\n return logs\n .filter(\n (entry) =>\n (!filter.level || entry.level === filter.level) &&\n (!module || entry.module.toLowerCase().includes(module)),\n )\n .map((entry) => ({ ...entry }));\n },\n getBackground() {\n return {\n queries: [...background.queries],\n cache: [...background.cache],\n logs: [...background.logs],\n };\n },\n subscribe(listener): DevtoolsDisposer {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n requests.clear();\n mails.clear();\n logs.length = 0;\n background.queries.length = 0;\n background.cache.length = 0;\n background.logs.length = 0;\n },\n };\n}\n\nfunction summary(request: DevtoolsRequest): DevtoolsRequestSummary {\n const { id, method, path, route, status, startedAt, durationMs } = request;\n return {\n id,\n method,\n path,\n route,\n status,\n startedAt,\n durationMs,\n queryCount: request.queries.length,\n warningCount: request.warnings.length,\n };\n}\n\nfunction mailSummary(mail: DevtoolsMail): DevtoolsMailSummary {\n const { id, requestId, capturedAt, to, subject } = mail;\n return { id, requestId, capturedAt, to: [...to], subject };\n}\n\nfunction copyRequest(request: DevtoolsRequest): DevtoolsRequest {\n return {\n ...request,\n phases: [...request.phases],\n queries: [...request.queries],\n cache: [...request.cache],\n logs: [...request.logs],\n mails: [...request.mails],\n warnings: [...request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;CACnD,OAAO;EAAE;EAAI;EAAW;EAAY,IAAI,CAAC,GAAG,EAAE;EAAG;CAAQ;AAC3D;AAEA,SAAS,YAAY,SAA2C;CAC9D,OAAO;EACL,GAAG;EACH,QAAQ,CAAC,GAAG,QAAQ,MAAM;EAC1B,SAAS,CAAC,GAAG,QAAQ,OAAO;EAC5B,OAAO,CAAC,GAAG,QAAQ,KAAK;EACxB,MAAM,CAAC,GAAG,QAAQ,IAAI;EACtB,OAAO,CAAC,GAAG,QAAQ,KAAK;EACxB,UAAU,CAAC,GAAG,QAAQ,QAAQ;CAChC;AACF"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
//#region ../../packages/devtools/src/production/contracts.ts
|
|
2
|
+
/**
|
|
3
|
+
* Upper bounds (inclusive, ms) of the latency buckets every histogram uses.
|
|
4
|
+
* A histogram's `counts` has one more entry than this list: the last entry
|
|
5
|
+
* counts everything above the highest bound. Fixed bounds make histograms
|
|
6
|
+
* from several instances merge exactly.
|
|
7
|
+
*/
|
|
8
|
+
const DEVTOOLS_LATENCY_BUCKETS_MS = [
|
|
9
|
+
1,
|
|
10
|
+
2,
|
|
11
|
+
5,
|
|
12
|
+
10,
|
|
13
|
+
25,
|
|
14
|
+
50,
|
|
15
|
+
100,
|
|
16
|
+
250,
|
|
17
|
+
500,
|
|
18
|
+
1e3,
|
|
19
|
+
2500,
|
|
20
|
+
5e3,
|
|
21
|
+
1e4,
|
|
22
|
+
3e4
|
|
23
|
+
];
|
|
24
|
+
/**
|
|
25
|
+
* The built-in tabs, in display order, with whether production shows them
|
|
26
|
+
* when the project says nothing (`production.panels` overrides per id).
|
|
27
|
+
*/
|
|
28
|
+
const DEVTOOLS_BUILT_IN_PANELS = [
|
|
29
|
+
{
|
|
30
|
+
id: "requests",
|
|
31
|
+
title: "Requests",
|
|
32
|
+
production: true
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: "queries",
|
|
36
|
+
title: "Queries",
|
|
37
|
+
production: true
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
id: "routes",
|
|
41
|
+
title: "Routes",
|
|
42
|
+
production: true
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
id: "resources",
|
|
46
|
+
title: "Resources",
|
|
47
|
+
production: true
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
id: "health",
|
|
51
|
+
title: "Health",
|
|
52
|
+
production: true
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "errors",
|
|
56
|
+
title: "Errors",
|
|
57
|
+
production: true
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: "logs",
|
|
61
|
+
title: "Logs",
|
|
62
|
+
production: true
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
id: "jobs",
|
|
66
|
+
title: "Jobs",
|
|
67
|
+
production: true
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
id: "mail",
|
|
71
|
+
title: "Mail",
|
|
72
|
+
production: false
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: "ai",
|
|
76
|
+
title: "AI",
|
|
77
|
+
production: false
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: "agents",
|
|
81
|
+
title: "Agents",
|
|
82
|
+
production: false
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
id: "api",
|
|
86
|
+
title: "API",
|
|
87
|
+
production: false
|
|
88
|
+
}
|
|
89
|
+
];
|
|
90
|
+
/** The audit types that count toward the account, IP and global failure limits. */
|
|
91
|
+
const DEVTOOLS_FAILURE_AUDIT_TYPES = ["login.failed", "mfa.failed"];
|
|
92
|
+
|
|
93
|
+
//#endregion
|
|
94
|
+
Object.defineProperty(exports, "DEVTOOLS_BUILT_IN_PANELS", {
|
|
95
|
+
enumerable: true,
|
|
96
|
+
get: function () {
|
|
97
|
+
return DEVTOOLS_BUILT_IN_PANELS;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
Object.defineProperty(exports, "DEVTOOLS_FAILURE_AUDIT_TYPES", {
|
|
101
|
+
enumerable: true,
|
|
102
|
+
get: function () {
|
|
103
|
+
return DEVTOOLS_FAILURE_AUDIT_TYPES;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
Object.defineProperty(exports, "DEVTOOLS_LATENCY_BUCKETS_MS", {
|
|
107
|
+
enumerable: true,
|
|
108
|
+
get: function () {
|
|
109
|
+
return DEVTOOLS_LATENCY_BUCKETS_MS;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
//# sourceMappingURL=contracts-CVmplkNb.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contracts-CVmplkNb.cjs","names":[],"sources":["../../../../../../../packages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai\", title: \"AI\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"stream.too-many\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n"],"mappings":";;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;AA8WA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAM,OAAO;EAAM,YAAY;CAAM;CAC3C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAkIA,MAAa,+BAA6D,CACxE,gBACA,YACF"}
|