@mgamadeus/ddd-web 0.16.0 → 0.16.2

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.
@@ -459,13 +459,18 @@ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgam
459
459
 
460
460
  const serverIssuesReporter = createNodeIssuesReporter({
461
461
  app: 'web',
462
- apiBaseUrl: process.env.API_INTERNAL_URL, // + DDD_ISSUES_REPORT_PATH
462
+ apiBaseUrl: process.env.API_INTERNAL_URL, // + DDD_ISSUES_REPORT_PATH (reportPath)
463
+ // or: endpoint: 'https://api.internal/api/public/common/issues/report' | () => url — the FULL URL, wins over apiBaseUrl
463
464
  serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // → section WEB_SERVER
464
465
  release: () => process.env.WEB_RELEASE ?? null,
465
466
  });
466
467
  export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter); // Next.js instrumentation.ts
467
468
  ```
468
469
 
470
+ `endpoint` (string or function) is the full URL and wins when both are set; `apiBaseUrl` stays for compatibility —
471
+ as a function it, too, returns the full URL (kept from 0.16.0; prefer `endpoint`). The browser reporter has only
472
+ `endpoint` (full URL, or a path of the page's origin).
473
+
469
474
  `installNodeIssueCapture(reporter)` adds `uncaughtExceptionMonitor` (observes only) and a flush on `beforeExit`;
470
475
  `{ unhandledRejections: true }` also reports rejections — that listener stops Node from exiting on one.
471
476
 
@@ -502,7 +507,9 @@ Behaviour:
502
507
  it; on `flush({ unloading: true })` a beacon (`text/plain`, no preflight) unless the request carries `Authorization`
503
508
  or a server token (a beacon has no headers).
504
509
  - **Typed body from the app's own SDK:** pass `wire: { toWireEvent, toRequestBody }` built from the generated
505
- `ClientIssueEvent` / request DTO models; the default `dddIssuesWireAdapter` writes the same shape.
510
+ `ClientIssueEvent` / request DTO models; the default `dddIssuesWireAdapter` writes the same shape. Works with
511
+ `createIssuesReporter`, `createBrowserIssuesReporter` and `createNodeIssuesReporter` alike (all generic over the event
512
+ and body types, defaulting to the DDD ones; inferred from `wire`).
506
513
  - The reporter never throws into its caller and never reports its own failures.
507
514
 
508
515
  ## 6. Tokens (`/auth`)
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.2
4
+
5
+ ### Fixed
6
+ - `createIssuesRedactor` / `redactText` / `redactUrl`: a token after a token path segment (`/reset-password/…`) and a
7
+ `token` query value now end at the next `/`, `?`, `#`, `&`, whitespace, quote (`'` `"` `` ` ``), `<`, `>`, `)` or
8
+ `]`. Before, a token path segment in free text consumed the rest of the text up to the next `?` or `#`, so the text
9
+ after it was lost and the e-mail and additional rules never applied to it.
10
+
11
+ ## 0.16.1
12
+
13
+ ### Changed
14
+ - `createBrowserIssuesReporter` / `createNodeIssuesReporter` and `BrowserIssuesReporterOptions` /
15
+ `NodeIssuesReporterOptions` are generic over the wire event and request-body types, defaulting to the DDD ones: a
16
+ `wire` built from your generated models now type-checks with the adapters, not only with `createIssuesReporter`.
17
+ Existing calls compile unchanged.
18
+
19
+ ### Added
20
+ - `NodeIssuesReporterOptions.endpoint` (string or function): the full URL of the ingest endpoint; wins over
21
+ `apiBaseUrl` when both are set. `apiBaseUrl` keeps its behaviour (a function returns the full URL) for compatibility.
22
+ The browser reporter already takes `endpoint` and has no `apiBaseUrl`.
23
+
3
24
  ## 0.16.0
4
25
 
5
26
  ### Added
package/README.md CHANGED
@@ -183,12 +183,16 @@ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgam
183
183
 
184
184
  const serverIssuesReporter = createNodeIssuesReporter({
185
185
  app: 'web',
186
- apiBaseUrl: process.env.API_INTERNAL_URL,
186
+ apiBaseUrl: process.env.API_INTERNAL_URL, // + the default report path; or `endpoint` = the full URL (wins)
187
187
  serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // the backend files these as WEB_SERVER
188
188
  });
189
189
  export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter);
190
190
  ```
191
191
 
192
+ Both adapters are generic over the wire types like the core: a `wire` built from your generated models
193
+ (`createNodeIssuesReporter({ …, wire: appIssuesWire })`) types the event and the body with them; without it the
194
+ DDD defaults apply.
195
+
192
196
  React Native and other runtimes use `createIssuesReporter` from `/issues` with `createFetchIssuesTransport()`.
193
197
  Everything is redacted on the device (tokens in paths and queries, e-mails, bearer / JWT tokens, UUIDs, phone numbers),
194
198
  known noise is dropped, repeats are folded into `count`, and caps, batching, retry and backoff keep a broken page from
@@ -127,7 +127,8 @@ var DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS = Object.freeze([
127
127
  "verify-email",
128
128
  "reset-password"
129
129
  ]);
130
- var TOKEN_QUERY_PARAMETER = /([?&][^=&#]*token[^=&#]*)=[^&#]*/gi;
130
+ var TOKEN_TERMINATOR_CHARACTERS = "/?#&\\s'\"`<>)\\]";
131
+ var TOKEN_QUERY_PARAMETER = new RegExp(`([?&][^=&#\\s]*token[^=&#\\s]*)=(?!\\[redacted\\])[^${TOKEN_TERMINATOR_CHARACTERS}]*`, "gi");
131
132
  var ISSUES_REDACTION_RULES = Object.freeze([
132
133
  // An Authorization header value copied into a message.
133
134
  { pattern: /\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: "Bearer [redacted]" },
@@ -144,7 +145,7 @@ var LONG_HEX_PATH_SEGMENT = /\/[0-9a-f]{16,}(?=[/?#]|$)/gi;
144
145
  var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
145
146
  var createIssuesRedactor = (options = {}) => {
146
147
  const tokenPathSegments = (options.tokenPathSegments ?? DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS).map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter((segment) => segment !== "");
147
- const tokenRouteSegment = tokenPathSegments.length > 0 ? new RegExp(`/(${tokenPathSegments.map(escapeRegExp).join("|")})/[^/?#]+`, "g") : null;
148
+ const tokenRouteSegment = tokenPathSegments.length > 0 ? new RegExp(`/(${tokenPathSegments.map(escapeRegExp).join("|")})/(?!\\[redacted\\])[^${TOKEN_TERMINATOR_CHARACTERS}]+`, "g") : null;
148
149
  const valueRules = [...ISSUES_REDACTION_RULES, ...options.additionalRules ?? []];
149
150
  const redactTokens = (value) => {
150
151
  const withoutTokenSegments = tokenRouteSegment ? value.replace(tokenRouteSegment, "/$1/[redacted]") : value;
@@ -620,4 +621,4 @@ export {
620
621
  createIssuesRouteTracker,
621
622
  createFetchIssuesTransport
622
623
  };
623
- //# sourceMappingURL=chunk-GVRMHMNO.js.map
624
+ //# sourceMappingURL=chunk-4NBJXOD2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/issues/limits.ts","../src/issues/normalize.ts","../src/issues/redact.ts","../src/issues/breadcrumbs.ts","../src/issues/filters.ts","../src/issues/fingerprint.ts","../src/issues/reporter.ts","../src/issues/route-pattern.ts","../src/issues/transport.ts"],"sourcesContent":["/**\n * Every limit of the issues reporter in one place. The backend enforces its own caps again (mgamadeus/ddd\n * `ClientIssueReportNormalizer`); these keep a broken page from flooding the endpoint and keep requests small. The field\n * caps equal the backend's.\n */\n\n/** Caps of a reporter that lives for one page session: per session, a hard stop after repeated failed sends. */\nexport interface IssuesSessionLimits {\n sendsPerFingerprint: number;\n eventsPerSession: number;\n failedSendsBeforeStop: number;\n}\n\n/** Caps of a long-lived reporter (a server, a mobile app): windows and an exponential backoff instead of a stop. */\nexport interface IssuesWindowedLimits {\n sendsPerFingerprintPerWindow: number;\n fingerprintWindowMs: number;\n eventsPerMinute: number;\n backoffStartMs: number;\n backoffMaxMs: number;\n}\n\nexport interface IssuesLimits {\n /** Field caps per event (characters) */\n nameLength: number;\n messageLength: number;\n framesPerEvent: number;\n fileLength: number;\n functionLength: number;\n rawStackLength: number;\n urlLength: number;\n routePatternLength: number;\n breadcrumbsPerEvent: number;\n breadcrumbMessageLength: number;\n breadcrumbUrlLength: number;\n tagsPerEvent: number;\n tagLength: number;\n requestMethodLength: number;\n clientFingerprintLength: number;\n /** Batching */\n flushDelayMs: number;\n flushAtEvents: number;\n /** The backend drops every event beyond 10 per request (`too-many-events`). */\n eventsPerRequest: number;\n /** Serialized UTF-8 per request; under the browser's 64 KiB keepalive budget */\n requestBytes: number;\n /** Serialized UTF-8 per event, before it is queued (the backend's file sink takes 16 KB per client event) */\n eventBytes: number;\n /** One retry on a network error or a 5xx, never on a 4xx */\n retryDelayMs: number;\n /** Events waiting to be sent; the oldest go first beyond it (a backend that is down for long) */\n queuedEvents: number;\n session: IssuesSessionLimits;\n windowed: IssuesWindowedLimits;\n}\n\nexport type IssuesLimitsOverrides = Partial<Omit<IssuesLimits, 'session' | 'windowed'>> & {\n session?: Partial<IssuesSessionLimits>;\n windowed?: Partial<IssuesWindowedLimits>;\n};\n\nexport const ISSUES_LIMITS: Readonly<IssuesLimits> = Object.freeze({\n nameLength: 128,\n messageLength: 1024,\n framesPerEvent: 30,\n fileLength: 512,\n functionLength: 128,\n rawStackLength: 4096,\n urlLength: 1024,\n routePatternLength: 256,\n breadcrumbsPerEvent: 20,\n breadcrumbMessageLength: 256,\n breadcrumbUrlLength: 1024,\n tagsPerEvent: 10,\n tagLength: 64,\n requestMethodLength: 16,\n clientFingerprintLength: 128,\n\n flushDelayMs: 2_000,\n flushAtEvents: 5,\n eventsPerRequest: 10,\n requestBytes: 48 * 1024,\n eventBytes: 16 * 1024,\n retryDelayMs: 10_000,\n queuedEvents: 50,\n\n session: Object.freeze({\n sendsPerFingerprint: 3,\n eventsPerSession: 25,\n failedSendsBeforeStop: 3,\n }),\n\n windowed: Object.freeze({\n sendsPerFingerprintPerWindow: 3,\n fingerprintWindowMs: 5 * 60_000,\n eventsPerMinute: 60,\n backoffStartMs: 10_000,\n backoffMaxMs: 5 * 60_000,\n }),\n});\n\n/** The default limits with the given ones on top (the nested `session` / `windowed` caps merged field by field). */\nexport const mergeIssuesLimits = (overrides: IssuesLimitsOverrides = {}): IssuesLimits => ({\n ...ISSUES_LIMITS,\n ...overrides,\n session: { ...ISSUES_LIMITS.session, ...overrides.session },\n windowed: { ...ISSUES_LIMITS.windowed, ...overrides.windowed },\n});\n","import { ISSUES_LIMITS } from './limits';\nimport type { CapturedFrame } from './types';\n\n/** The error-like value a reporter received, reduced to what a report carries. */\nexport interface NormalizedError {\n name: string;\n message: string;\n /** Innermost first */\n frames: CapturedFrame[];\n /** Only when the stack had lines but none could be parsed */\n rawStack: string | null;\n}\n\n/** Decides whether a frame's file is the application's own code. */\nexport type InAppFileTest = (file: string) => boolean;\n\nexport const truncate = (value: string, maxLength: number): string =>\n value.length > maxLength ? value.slice(0, maxLength) : value;\n\n/** Files that are never the app's: extensions, the runtime, libraries. */\nconst FOREIGN_FILE =\n /^(chrome-extension|moz-extension|safari-extension|safari-web-extension):|^node:|node_modules|^<anonymous>$|^native$|^\\[native code\\]$/;\n\nexport const isForeignFile = (file: string): boolean => FOREIGN_FILE.test(file);\n\n/** V8 (Chrome, Edge, Node, Hermes): ` at fn (file:1:2)`, ` at file:1:2`, ` at async fn (file:1:2)` */\nconst V8_FRAME = /^\\s*at (?:(.+?) \\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/;\n/** V8 frame without a position: ` at fn (native)`, ` at fn (<anonymous>)` */\nconst V8_FRAME_WITHOUT_POSITION = /^\\s*at (?:(.+?) \\()?([^():]+)\\)?\\s*$/;\n/** SpiderMonkey / JavaScriptCore (Firefox, Safari): `fn@file:1:2`, `@file:1:2` */\nconst GECKO_FRAME = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/;\n\nconst toFrame = (\n functionName: string | undefined,\n file: string,\n line: string | undefined,\n column: string | undefined,\n isInAppFile: InAppFileTest,\n): CapturedFrame => {\n const cleanFunction = (functionName ?? '').replace(/^async /, '').replace(/^new /, '').trim();\n return {\n file: truncate(file, ISSUES_LIMITS.fileLength),\n line: line ? Number(line) : null,\n column: column ? Number(column) : null,\n function: cleanFunction ? truncate(cleanFunction, ISSUES_LIMITS.functionLength) : null,\n inApp: !isForeignFile(file) && isInAppFile(file),\n };\n};\n\n/** Parses a stack string into frames, innermost first. Lines that are not frames (the message) are skipped. */\nexport const parseStack = (\n stack: string,\n isInAppFile: InAppFileTest = () => true,\n maxFrames: number = ISSUES_LIMITS.framesPerEvent,\n): CapturedFrame[] => {\n const frames: CapturedFrame[] = [];\n for (const line of stack.split('\\n')) {\n if (frames.length >= maxFrames) break;\n const v8Match = V8_FRAME.exec(line);\n if (v8Match) {\n frames.push(toFrame(v8Match[1], v8Match[2] ?? '', v8Match[3], v8Match[4], isInAppFile));\n continue;\n }\n const v8MatchWithoutPosition = V8_FRAME_WITHOUT_POSITION.exec(line);\n if (v8MatchWithoutPosition) {\n frames.push(toFrame(v8MatchWithoutPosition[1], v8MatchWithoutPosition[2] ?? '', undefined, undefined, isInAppFile));\n continue;\n }\n const geckoMatch = GECKO_FRAME.exec(line);\n if (geckoMatch) {\n frames.push(toFrame(geckoMatch[1], geckoMatch[2] ?? '', geckoMatch[3], geckoMatch[4], isInAppFile));\n }\n }\n return frames;\n};\n\n/** `Minified React error #418; visit https://react.dev/errors/418…` → the code, so it survives grouping as a name. */\nconst MINIFIED_REACT_ERROR = /Minified React error #(\\d+)/;\n\nconst describeNonError = (value: unknown): string => {\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\ninterface ErrorLike {\n name?: unknown;\n message?: unknown;\n stack?: unknown;\n}\n\nconst isErrorLike = (value: unknown): value is ErrorLike =>\n typeof value === 'object' && value !== null && typeof (value as ErrorLike).message === 'string';\n\n/** Any thrown value (an Error, a string, a rejected object) → name, message, frames. */\nexport const normalizeError = (value: unknown, isInAppFile: InAppFileTest = () => true): NormalizedError => {\n if (!isErrorLike(value)) {\n const message = typeof value === 'string' ? value : describeNonError(value);\n return {\n name: typeof value === 'string' ? 'Error' : 'NonError',\n message: truncate(message, ISSUES_LIMITS.messageLength),\n frames: [],\n rawStack: null,\n };\n }\n\n const message = String(value.message);\n const reactErrorCode = MINIFIED_REACT_ERROR.exec(message)?.[1];\n const declaredName = typeof value.name === 'string' && value.name ? value.name : 'Error';\n const name = reactErrorCode ? `ReactError#${reactErrorCode}` : declaredName;\n const stack = typeof value.stack === 'string' ? value.stack : '';\n const frames = stack ? parseStack(stack, isInAppFile) : [];\n const hasStackLines = stack.split('\\n').length > 1;\n\n return {\n name: truncate(name, ISSUES_LIMITS.nameLength),\n message: truncate(message, ISSUES_LIMITS.messageLength),\n frames,\n rawStack: frames.length === 0 && hasStackLines ? truncate(stack, ISSUES_LIMITS.rawStackLength) : null,\n };\n};\n","/**\n * Client-side redaction of everything a report carries as free text: the page URL, breadcrumb URLs and messages, the\n * error message, the raw stack and tag values. The backend redacts again (mgamadeus/ddd `IssuesLogRedactor` and the\n * client rules of `logClientIssue`); this pass keeps credentials from leaving the device at all.\n */\n\n/** One rule by value, applied to text and URLs alike. */\nexport interface IssuesRedactionRule {\n pattern: RegExp;\n replacement: string;\n}\n\nexport interface IssuesRedactor {\n /** For a URL (page, request, navigation from / to). */\n redactUrl: (url: string) => string;\n /** For free text (error message, breadcrumb message); URLs inside it get the token rules too. */\n redactText: (text: string) => string;\n}\n\nexport interface IssuesRedactorOptions {\n /**\n * Path segments whose NEXT segment is the credential (an invitation, a password reset):\n * `/invitations/abc` → `/invitations/[redacted]`. A segment may contain `/` (`r/confirm`). Default\n * {@link DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS}, the backend's default `redactPathSegments`.\n */\n tokenPathSegments?: readonly string[];\n /** Applied after the built-in rules, e.g. a national phone-number format. */\n additionalRules?: readonly IssuesRedactionRule[];\n}\n\n/** The backend's default `redactPathSegments` (`Common.Issues`). */\nexport const DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS: readonly string[] = Object.freeze([\n 'invitations',\n 'claim-account',\n 'verify-email',\n 'reset-password',\n]);\n\n/**\n * Characters that end a token (a path segment or a query value): the URL delimiters `/ ? # &`, whitespace, quotes and\n * the brackets a URL is typically wrapped in inside free text, so the text after the token stays and keeps its rules.\n */\nconst TOKEN_TERMINATOR_CHARACTERS = '/?#&\\\\s\\'\"`<>)\\\\]';\n\n/** Any query parameter whose name contains `token`. */\nconst TOKEN_QUERY_PARAMETER = new RegExp(`([?&][^=&#\\\\s]*token[^=&#\\\\s]*)=(?!\\\\[redacted\\\\])[^${TOKEN_TERMINATOR_CHARACTERS}]*`, 'gi');\n\n/** Rules by value. Order matters: a bearer and a JWT go before the generic rules. */\nexport const ISSUES_REDACTION_RULES: readonly IssuesRedactionRule[] = Object.freeze([\n // An Authorization header value copied into a message.\n { pattern: /\\bBearer\\s+[A-Za-z0-9\\-._~+/]+=*/gi, replacement: 'Bearer [redacted]' },\n // A JWT anywhere (access tokens, custom tokens of an identity provider).\n { pattern: /\\beyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]+/g, replacement: '[jwt]' },\n // E-mail addresses.\n { pattern: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi, replacement: '[email]' },\n // UUIDs: a public link's id is often its credential (`/api/public/bookings/<uuid>/cancel`).\n { pattern: /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, replacement: '[uuid]' },\n // International phone numbers (+44 20 7946 0958).\n { pattern: /\\+\\d[\\d\\s().-]{6,}\\d/g, replacement: '[phone]' },\n]);\n\n/** Path segments that are long hex ids (signed links, opaque tokens); ids of 15 hex digits or fewer stay. */\nconst LONG_HEX_PATH_SEGMENT = /\\/[0-9a-f]{16,}(?=[/?#]|$)/gi;\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const createIssuesRedactor = (options: IssuesRedactorOptions = {}): IssuesRedactor => {\n const tokenPathSegments = (options.tokenPathSegments ?? DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS)\n .map((segment) => segment.replace(/^\\/+|\\/+$/g, ''))\n .filter((segment) => segment !== '');\n const tokenRouteSegment =\n tokenPathSegments.length > 0\n ? new RegExp(`/(${tokenPathSegments.map(escapeRegExp).join('|')})/(?!\\\\[redacted\\\\])[^${TOKEN_TERMINATOR_CHARACTERS}]+`, 'g')\n : null;\n const valueRules = [...ISSUES_REDACTION_RULES, ...(options.additionalRules ?? [])];\n\n const redactTokens = (value: string): string => {\n const withoutTokenSegments = tokenRouteSegment ? value.replace(tokenRouteSegment, '/$1/[redacted]') : value;\n return withoutTokenSegments.replace(TOKEN_QUERY_PARAMETER, '$1=[redacted]');\n };\n const applyValueRules = (value: string): string =>\n valueRules.reduce((redacted, rule) => redacted.replace(rule.pattern, rule.replacement), value);\n\n return {\n redactUrl: (url) => applyValueRules(redactTokens(url)).replace(LONG_HEX_PATH_SEGMENT, '/[id]'),\n redactText: (text) => applyValueRules(redactTokens(text)),\n };\n};\n\nconst defaultIssuesRedactor = createIssuesRedactor();\n\n/** {@link IssuesRedactor.redactUrl} with the default rules. */\nexport const redactUrl = (url: string): string => defaultIssuesRedactor.redactUrl(url);\n\n/** {@link IssuesRedactor.redactText} with the default rules. */\nexport const redactText = (text: string): string => defaultIssuesRedactor.redactText(text);\n","import { ISSUES_LIMITS } from './limits';\nimport { truncate } from './normalize';\nimport { type IssuesRedactor, redactText, redactUrl } from './redact';\nimport type { BreadcrumbCategory, CapturedBreadcrumb } from './types';\n\n/**\n * What happened before an error, newest last. Builders only: every string is capped and redacted here, so a caller\n * cannot add an unredacted URL (the reporter applies its own redactor again on add). Never bodies, never input values,\n * never the visible text of a clicked element.\n */\n\nexport interface BreadcrumbTrail {\n add: (breadcrumb: CapturedBreadcrumb) => void;\n /** A copy, oldest first */\n snapshot: () => CapturedBreadcrumb[];\n}\n\n/** Keeps the newest `limit` breadcrumbs. */\nexport const createBreadcrumbTrail = (limit: number = ISSUES_LIMITS.breadcrumbsPerEvent): BreadcrumbTrail => {\n const breadcrumbs: CapturedBreadcrumb[] = [];\n return {\n add: (breadcrumb) => {\n breadcrumbs.push(breadcrumb);\n while (breadcrumbs.length > limit) breadcrumbs.shift();\n },\n snapshot: () => breadcrumbs.slice(),\n };\n};\n\nconst DEFAULT_BREADCRUMB_REDACTOR: IssuesRedactor = { redactUrl, redactText };\n\n/** Caps and redacts every string of a breadcrumb. */\nexport const sanitizeBreadcrumb = (\n breadcrumb: CapturedBreadcrumb,\n redactor: IssuesRedactor = DEFAULT_BREADCRUMB_REDACTOR,\n): CapturedBreadcrumb => {\n const sanitizeUrl = (url: string | null | undefined): string | null =>\n url ? truncate(redactor.redactUrl(url), ISSUES_LIMITS.breadcrumbUrlLength) : null;\n return {\n at: breadcrumb.at,\n category: breadcrumb.category,\n message: truncate(redactor.redactText(breadcrumb.message), ISSUES_LIMITS.breadcrumbMessageLength),\n url: sanitizeUrl(breadcrumb.url),\n from: sanitizeUrl(breadcrumb.from),\n to: sanitizeUrl(breadcrumb.to),\n status: typeof breadcrumb.status === 'number' ? breadcrumb.status : null,\n };\n};\n\ntype BreadcrumbFields = Partial<Pick<CapturedBreadcrumb, 'url' | 'from' | 'to' | 'status'>>;\n\nconst buildBreadcrumb = (\n at: string,\n category: BreadcrumbCategory,\n message: string,\n fields: BreadcrumbFields = {},\n): CapturedBreadcrumb =>\n sanitizeBreadcrumb({\n at,\n category,\n message,\n url: fields.url ?? null,\n from: fields.from ?? null,\n to: fields.to ?? null,\n status: fields.status ?? null,\n });\n\n/** A route change; `from` / `to` are route patterns or paths. */\nexport const navigationBreadcrumb = (at: string, from: string | null, to: string): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'navigation', `${from ?? '(start)'} → ${to}`, { from, to });\n\n/** A failed request: status ≥ 400, or `network-error` when it never got an answer. */\nexport const fetchBreadcrumb = (\n at: string,\n method: string,\n url: string,\n outcome: number | 'network-error',\n): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'fetch', `${method.toUpperCase()} ${outcome}`, {\n url,\n status: outcome === 'network-error' ? null : outcome,\n });\n\n/** `console.error`: its first argument only. */\nexport const consoleBreadcrumb = (at: string, message: string): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'console', message);\n\n/**\n * A click: the element's `data-issues-action` id, else its tag and role. Never its text or `aria-label`, which can\n * hold an e-mail or a name.\n */\nexport const uiBreadcrumb = (at: string, action: string): CapturedBreadcrumb => buildBreadcrumb(at, 'ui', action);\n\n/** Anything else the app wants on the trail. */\nexport const customBreadcrumb = (at: string, message: string, fields: BreadcrumbFields = {}): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'custom', message, fields);\n","import type { CapturedFrame } from './types';\n\n/**\n * What the client never reports: noise that is not a failure of the app, or not actionable per event. The backend\n * drops the chunk-load, `Script error.` and `ResizeObserver loop` patterns again (`clientIgnorePatterns`); dropping\n * here saves the request.\n */\n\nexport interface IssueDropCandidate {\n name: string;\n message: string;\n frames: readonly CapturedFrame[];\n /** The page runs under automation (Playwright / WebDriver: `navigator.webdriver`) */\n automated: boolean;\n}\n\nexport interface IssueDropRule {\n id: string;\n matches: (candidate: IssueDropCandidate) => boolean;\n}\n\nconst messageMatches =\n (pattern: RegExp) =>\n (candidate: IssueDropCandidate): boolean =>\n pattern.test(candidate.message) || pattern.test(candidate.name);\n\nexport const ISSUE_DROP_RULES: readonly IssueDropRule[] = Object.freeze([\n // A tab opened before a deploy asks for chunks the new deploy no longer has.\n { id: 'chunk-load', matches: (candidate: IssueDropCandidate) => candidate.name === 'ChunkLoadError' },\n { id: 'chunk-load', matches: messageMatches(/Loading (CSS )?chunk [\\w-]+ failed/) },\n { id: 'chunk-load', matches: messageMatches(/Failed to fetch dynamically imported module/) },\n { id: 'chunk-load', matches: messageMatches(/Importing a module script failed/) },\n // Browser noise: the observer could not deliver every notification in one frame.\n { id: 'resize-observer', matches: messageMatches(/ResizeObserver loop/) },\n // An error in a cross-origin script: the browser hides everything, nothing to act on.\n { id: 'opaque-script-error', matches: (candidate: IssueDropCandidate) => /^Script error\\.?$/.test(candidate.message.trim()) },\n // Thrown by a browser extension injected into the page.\n {\n id: 'extension',\n matches: (candidate: IssueDropCandidate) =>\n /^(chrome-extension|moz-extension|safari-(web-)?extension):/.test(candidate.frames[0]?.file ?? ''),\n },\n // Wallet extensions and in-app wallet browsers touch `window.ethereum` on every page.\n { id: 'wallet-extension', matches: messageMatches(/\\bwindow\\.ethereum\\b/) },\n // A request the app cancelled itself (navigation, unmount, an aborted query).\n { id: 'aborted', matches: (candidate: IssueDropCandidate) => candidate.name === 'AbortError' },\n // End-to-end runs under automation stay silent.\n { id: 'automated-browser', matches: (candidate: IssueDropCandidate) => candidate.automated },\n]);\n\n/** The id of the first rule that drops the candidate, or null when it is reported. */\nexport const findIssueDropRule = (\n candidate: IssueDropCandidate,\n rules: readonly IssueDropRule[] = ISSUE_DROP_RULES,\n): string | null => rules.find((rule) => rule.matches(candidate))?.id ?? null;\n","import type { CapturedFrame } from './types';\n\n/**\n * The CLIENT's de-duplication key: `name | normalised message | top frame file:function`. Only for folding repeats on\n * one device (sent as `clientFingerprint`, informational); the backend builds the group and issue hashes itself\n * (mgamadeus/ddd `ClientIssuesFingerprintBuilder`) and never trusts this one.\n */\n\n/** URLs, UUIDs, hex ids and numbers become placeholders, so `order 41 failed` and `order 42 failed` are one key. */\nexport const normaliseIssueMessage = (message: string): string =>\n message\n .replace(/https?:\\/\\/\\S+/g, '{url}')\n .replace(/\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, '{uuid}')\n .replace(/\\b[0-9a-f]{8,}\\b/gi, '{hex}')\n .replace(/\\d+/g, '{n}');\n\n/** The top frame is the innermost in-app frame, else the innermost frame. */\nexport const buildClientFingerprint = (name: string, message: string, frames: readonly CapturedFrame[]): string => {\n const topFrame = frames.find((frame) => frame.inApp) ?? frames[0];\n const callSite = topFrame ? `${topFrame.file}:${topFrame.function ?? ''}` : '';\n return `${name}|${normaliseIssueMessage(message)}|${callSite}`;\n};\n","import { createBreadcrumbTrail, sanitizeBreadcrumb } from './breadcrumbs';\nimport { findIssueDropRule, ISSUE_DROP_RULES, type IssueDropRule } from './filters';\nimport { buildClientFingerprint } from './fingerprint';\nimport { type IssuesLimitsOverrides, mergeIssuesLimits } from './limits';\nimport { type InAppFileTest, normalizeError, truncate } from './normalize';\nimport { createIssuesRedactor, type IssuesRedactor } from './redact';\nimport type {\n CaptureExtra,\n CapturedBreadcrumb,\n CapturedIssueContext,\n CapturedIssueEvent,\n CapturedTag,\n IssueKind,\n IssuesRuntime,\n IssuesTransport,\n IssuesWireAdapter,\n} from './types';\nimport {\n type DddClientIssueEvent,\n type DddClientIssuesReportRequestBody,\n dddIssuesWireAdapter,\n} from './wire';\n\n/**\n * The issues reporter: collect → redact → de-duplicate → cap → batch → send. Platform-free: the caller supplies the\n * transport, the context and optionally the wire adapter. It never throws into its caller and never reports its own\n * failures.\n */\n\n/**\n * Header a client app's own server sends its shared secret in; the application's controller files such reports\n * under the section WEB_SERVER. The header name is the application's choice — `serverTokenHeader` overrides it.\n */\nexport const DDD_ISSUES_SERVER_TOKEN_HEADER = 'X-Issues-Server-Token';\n\n/** How the reporter caps what it sends. */\nexport type IssuesRateLimitMode =\n /** One page session: per-fingerprint and per-session caps, a hard stop after repeated failed sends. */\n | 'session'\n /** A long-lived process or app: windowed caps and an exponential backoff. */\n | 'windowed';\n\nexport interface IssuesClock {\n now: () => number;\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (handle: unknown) => void;\n}\n\ninterface TimerGlobals {\n setTimeout: (callback: () => void, delayMs: number) => { unref?: () => void } | number;\n clearTimeout: (handle: unknown) => void;\n}\n\n/** The running platform's timers, read when the reporter is created. On Node they are unref'd. */\nexport const createPlatformIssuesClock = (): IssuesClock => {\n const timers = globalThis as unknown as TimerGlobals;\n return {\n now: () => Date.now(),\n setTimeout: (callback, delayMs) => {\n const handle = timers.setTimeout(callback, delayMs);\n if (typeof handle === 'object' && handle !== null) handle.unref?.();\n return handle;\n },\n clearTimeout: (handle) => timers.clearTimeout(handle),\n };\n};\n\nexport type IssuesContextValues = Partial<Omit<CapturedIssueContext, 'runtime' | 'app'>>;\n\nexport interface IssuesReporterOptions<TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody> {\n runtime: IssuesRuntime;\n /** The client app, e.g. `web`, `admin`, `mobile` */\n app: string;\n /** Full URL of the ingest endpoint, read at send time; null = not configured, nothing is sent. */\n endpoint: () => string | null;\n transport: IssuesTransport;\n /** Read at send time (the release may only be known after the first render). Missing fields are null. */\n context?: () => IssuesContextValues;\n /** Read at capture time: tags every event carries (e.g. the deployed commit); a capture's own tags win on a clash. */\n commonTags?: () => CaptureExtra['tags'];\n /** Default: the DDD contract (`@mgamadeus/ddd-web/issues/wire`). Pass your own to type the body with your models. */\n wire?: IssuesWireAdapter<TWireEvent, TRequestBody>;\n /** A signed-in session's access token, so the backend attributes the error to the account. */\n getAuthorization?: () => string | null | undefined;\n /** The client app's own server only: the shared secret that makes the backend file reports as WEB_SERVER. */\n serverToken?: string;\n /** Default {@link DDD_ISSUES_SERVER_TOKEN_HEADER} */\n serverTokenHeader?: string;\n isInAppFile?: InAppFileTest;\n /** True under automation (`navigator.webdriver`): nothing is reported. */\n isAutomated?: () => boolean;\n /** Default: `session` for `browser`, `windowed` for `node` and `react-native`. */\n rateLimitMode?: IssuesRateLimitMode;\n /** Attach the breadcrumb trail to events. Default: every runtime but `node` (a server's trail mixes requests). */\n attachBreadcrumbs?: boolean;\n /** Default {@link ISSUE_DROP_RULES}; spread them to add your own. */\n dropRules?: readonly IssueDropRule[];\n /** Default {@link createIssuesRedactor}() */\n redactor?: IssuesRedactor;\n limits?: IssuesLimitsOverrides;\n clock?: IssuesClock;\n}\n\nexport interface IssuesReporter {\n /** Reports anything thrown. `kind` says how it was caught; `manual` (default) is the one the backend counts as handled. */\n captureError: (error: unknown, kind?: IssueKind, extra?: CaptureExtra) => void;\n addBreadcrumb: (breadcrumb: CapturedBreadcrumb) => void;\n /** The current route pattern (`/books/[bookId]`) and URL; both name every event captured after it. */\n setRoute: (routePattern: string | null, url: string | null) => void;\n /** Replaces `getAuthorization`, e.g. once the session store exists. */\n setAuthorizationReader: (reader: (() => string | null | undefined) | null) => void;\n /** Sends what is queued. `unloading`: the page is going away — keepalive, every batch at once, no awaiting. */\n flush: (options?: { unloading?: boolean }) => Promise<void>;\n /** Events waiting to be sent. */\n getQueuedEventCount: () => number;\n}\n\ninterface QueuedEvent {\n event: CapturedIssueEvent;\n attempts: number;\n}\n\n/** UTF-8 length of a string, without TextEncoder (not in every runtime this targets). */\nexport const utf8ByteLength = (value: string): number => {\n let bytes = 0;\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff) {\n bytes += 4;\n index++;\n } else bytes += 3;\n }\n return bytes;\n};\n\n/** Room left in a request for the context and the JSON around the events. */\nconst REQUEST_OVERHEAD_BYTES = 2048;\n/** Frames kept when an event is too large (the backend keeps the same number). */\nconst FRAMES_KEPT_WHEN_SHRINKING = 10;\n/** Message length kept when an event is still too large. */\nconst MESSAGE_LENGTH_KEPT_WHEN_SHRINKING = 256;\n\nconst NO_CONTEXT: Omit<CapturedIssueContext, 'runtime' | 'app'> = {\n release: null,\n tabId: null,\n userAgent: null,\n viewportWidth: null,\n viewportHeight: null,\n locale: null,\n};\n\nexport const createIssuesReporter = <TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody>(\n options: IssuesReporterOptions<TWireEvent, TRequestBody>,\n): IssuesReporter => {\n const limits = mergeIssuesLimits(options.limits);\n const clock = options.clock ?? createPlatformIssuesClock();\n const wire = options.wire ?? (dddIssuesWireAdapter as unknown as IssuesWireAdapter<TWireEvent, TRequestBody>);\n const redactor = options.redactor ?? createIssuesRedactor();\n const dropRules = options.dropRules ?? ISSUE_DROP_RULES;\n const isInAppFile = options.isInAppFile ?? (() => true);\n const rateLimitMode: IssuesRateLimitMode =\n options.rateLimitMode ?? (options.runtime === 'browser' ? 'session' : 'windowed');\n const attachBreadcrumbs = options.attachBreadcrumbs ?? options.runtime !== 'node';\n const isBrowser = options.runtime === 'browser';\n const trail = createBreadcrumbTrail(limits.breadcrumbsPerEvent);\n let readAuthorization = options.getAuthorization ?? null;\n\n let route: { routePattern: string | null; url: string | null } = { routePattern: null, url: null };\n let queue: QueuedEvent[] = [];\n let flushTimer: unknown = null;\n let isSending = false;\n let isKeepaliveInFlight = false;\n\n // Rate limit mode `session`\n const sendsByFingerprint = new Map<string, number>();\n let sessionEvents = 0;\n let failedSends = 0;\n let isStopped = false;\n\n // Rate limit mode `windowed`\n const sendTimesByFingerprint = new Map<string, number[]>();\n let sendTimesOfLastMinute: number[] = [];\n let backoffMs = 0;\n let backoffUntil = 0;\n\n const measureEvent = (event: CapturedIssueEvent): number => utf8ByteLength(JSON.stringify(wire.toWireEvent(event)));\n\n /** Breadcrumbs go first, then frames beyond 10, the raw stack, and the message beyond 256 characters. */\n const shrinkToFit = (event: CapturedIssueEvent): CapturedIssueEvent => {\n const steps: ((current: CapturedIssueEvent) => CapturedIssueEvent)[] = [\n (current) => ({ ...current, breadcrumbs: [] }),\n (current) => ({ ...current, frames: current.frames.slice(0, FRAMES_KEPT_WHEN_SHRINKING) }),\n (current) => ({ ...current, rawStack: null }),\n (current) => ({ ...current, message: truncate(current.message, MESSAGE_LENGTH_KEPT_WHEN_SHRINKING) }),\n ];\n let shrunk = event;\n for (const step of steps) {\n if (measureEvent(shrunk) <= limits.eventBytes) return shrunk;\n shrunk = step(shrunk);\n }\n return shrunk;\n };\n\n /** Whether the caps let one more event with this fingerprint through; records it when they do. */\n const admit = (fingerprint: string): boolean => {\n if (rateLimitMode === 'session') {\n if (isStopped) return false;\n const sends = sendsByFingerprint.get(fingerprint) ?? 0;\n if (sends >= limits.session.sendsPerFingerprint) return false;\n if (sessionEvents >= limits.session.eventsPerSession) return false;\n sendsByFingerprint.set(fingerprint, sends + 1);\n sessionEvents += 1;\n return true;\n }\n const now = clock.now();\n const windowStart = now - limits.windowed.fingerprintWindowMs;\n const fingerprintTimes = (sendTimesByFingerprint.get(fingerprint) ?? []).filter((time) => time > windowStart);\n sendTimesOfLastMinute = sendTimesOfLastMinute.filter((time) => time > now - 60_000);\n if (fingerprintTimes.length >= limits.windowed.sendsPerFingerprintPerWindow) return false;\n if (sendTimesOfLastMinute.length >= limits.windowed.eventsPerMinute) return false;\n fingerprintTimes.push(now);\n sendTimesByFingerprint.set(fingerprint, fingerprintTimes);\n sendTimesOfLastMinute.push(now);\n // A long-lived process sees many one-off fingerprints: forget the expired ones.\n if (sendTimesByFingerprint.size > 500) {\n for (const [key, times] of sendTimesByFingerprint) {\n if (times.every((time) => time <= windowStart)) sendTimesByFingerprint.delete(key);\n }\n }\n return true;\n };\n\n const scheduleFlush = (delayMs: number) => {\n if (flushTimer !== null) return;\n flushTimer = clock.setTimeout(() => {\n flushTimer = null;\n void flush();\n }, delayMs);\n };\n\n const recordFailure = () => {\n if (rateLimitMode === 'session') {\n failedSends += 1;\n if (failedSends >= limits.session.failedSendsBeforeStop) {\n isStopped = true;\n queue = [];\n }\n return;\n }\n backoffMs = backoffMs ? Math.min(backoffMs * 2, limits.windowed.backoffMaxMs) : limits.windowed.backoffStartMs;\n backoffUntil = clock.now() + backoffMs;\n };\n\n const recordSuccess = () => {\n backoffMs = 0;\n backoffUntil = 0;\n };\n\n /** Up to `eventsPerRequest` events and `requestBytes`, oldest first. */\n const takeBatch = (): QueuedEvent[] => {\n const batch: QueuedEvent[] = [];\n let bytes = REQUEST_OVERHEAD_BYTES;\n while (queue.length > 0 && batch.length < limits.eventsPerRequest) {\n const next = queue[0] as QueuedEvent;\n const eventBytes = measureEvent(next.event) + 1;\n if (batch.length > 0 && bytes + eventBytes > limits.requestBytes) break;\n bytes += eventBytes;\n batch.push(next);\n queue.shift();\n }\n return batch;\n };\n\n const buildHeaders = (): Record<string, string> => {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'application/json' };\n try {\n const accessToken = readAuthorization?.();\n if (accessToken) headers.Authorization = `Bearer ${accessToken}`;\n } catch {\n // No session to attribute: the report goes anonymous.\n }\n if (options.serverToken) headers[options.serverTokenHeader ?? DDD_ISSUES_SERVER_TOKEN_HEADER] = options.serverToken;\n return headers;\n };\n\n const buildContext = (): CapturedIssueContext => {\n let contextValues: IssuesContextValues = {};\n try {\n contextValues = options.context?.() ?? {};\n } catch {\n // A context that cannot be read leaves its fields null.\n }\n return { ...NO_CONTEXT, ...contextValues, runtime: options.runtime, app: options.app };\n };\n\n const sendBatch = async (batch: QueuedEvent[], unloading = false): Promise<void> => {\n if (batch.length === 0) return;\n let endpoint: string | null = null;\n try {\n endpoint = options.endpoint();\n } catch {\n endpoint = null;\n }\n if (!endpoint) return;\n const body = JSON.stringify(wire.toRequestBody(buildContext(), batch.map((queued) => wire.toWireEvent(queued.event))));\n const useKeepalive = isBrowser && !isKeepaliveInFlight;\n if (useKeepalive) isKeepaliveInFlight = true;\n\n let status: number | null = null;\n try {\n status = (await options.transport({ url: endpoint, headers: buildHeaders(), body, keepalive: useKeepalive, unloading })).status;\n } catch {\n status = null;\n } finally {\n if (useKeepalive) isKeepaliveInFlight = false;\n }\n\n if (status !== null && status < 400) {\n recordSuccess();\n return;\n }\n const isRetryable = status === null || status >= 500;\n const retryable = isRetryable ? batch.filter((queued) => queued.attempts === 0) : [];\n recordFailure();\n if (retryable.length > 0 && !isStopped) {\n queue = [...retryable.map((queued) => ({ ...queued, attempts: queued.attempts + 1 })), ...queue];\n scheduleFlush(Math.max(limits.retryDelayMs, backoffUntil - clock.now()));\n }\n };\n\n const flush = async (flushOptions?: { unloading?: boolean }): Promise<void> => {\n try {\n if (flushTimer !== null) {\n clock.clearTimeout(flushTimer);\n flushTimer = null;\n }\n if (queue.length === 0 || isStopped) return;\n if (rateLimitMode === 'windowed' && clock.now() < backoffUntil) {\n scheduleFlush(backoffUntil - clock.now());\n return;\n }\n if (flushOptions?.unloading) {\n // The page is going away: no awaiting, every batch now (only the first can ride keepalive).\n while (queue.length > 0) void sendBatch(takeBatch(), true);\n return;\n }\n if (isSending) return;\n isSending = true;\n try {\n await sendBatch(takeBatch());\n } finally {\n isSending = false;\n }\n if (queue.length > 0) scheduleFlush(limits.flushDelayMs);\n } catch {\n // Never into the caller.\n }\n };\n\n const toTags = (tags: CaptureExtra['tags']): CapturedTag[] =>\n Object.entries(tags ?? {})\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .slice(0, limits.tagsPerEvent)\n .map(([key, value]) => ({\n key: truncate(key, limits.tagLength),\n value: truncate(redactor.redactText(value), limits.tagLength),\n }));\n\n const captureError = (error: unknown, kind: IssueKind = 'manual', extra: CaptureExtra = {}) => {\n try {\n const normalized = normalizeError(error, isInAppFile);\n let isAutomated = false;\n try {\n isAutomated = options.isAutomated?.() ?? false;\n } catch {\n isAutomated = false;\n }\n if (findIssueDropRule({ ...normalized, automated: isAutomated }, dropRules)) return;\n\n const message = truncate(redactor.redactText(normalized.message), limits.messageLength);\n const frames = normalized.frames.slice(0, limits.framesPerEvent);\n const fingerprint = truncate(buildClientFingerprint(normalized.name, message, frames), limits.clientFingerprintLength);\n\n const alreadyQueued = queue.find((candidate) => candidate.event.clientFingerprint === fingerprint);\n if (alreadyQueued) {\n alreadyQueued.event.count += 1;\n return;\n }\n if (!admit(fingerprint)) return;\n\n const url = extra.url !== undefined ? extra.url : route.url;\n const routePattern = extra.routePattern !== undefined ? extra.routePattern : route.routePattern;\n let commonTags: CaptureExtra['tags'] = {};\n try {\n commonTags = options.commonTags?.() ?? {};\n } catch {\n commonTags = {};\n }\n const event = shrinkToFit({\n occurredAt: new Date(clock.now()).toISOString(),\n kind,\n level: extra.level ?? 'error',\n name: truncate(normalized.name, limits.nameLength),\n message,\n frames,\n rawStack: normalized.rawStack ? truncate(redactor.redactText(normalized.rawStack), limits.rawStackLength) : null,\n url: url ? truncate(redactor.redactUrl(url), limits.urlLength) : null,\n routePattern: routePattern ? truncate(routePattern, limits.routePatternLength) : null,\n requestMethod: extra.requestMethod ? truncate(extra.requestMethod.toUpperCase(), limits.requestMethodLength) : null,\n httpStatus: extra.httpStatus ?? null,\n breadcrumbs: attachBreadcrumbs ? trail.snapshot() : [],\n tags: toTags({ ...commonTags, ...extra.tags }),\n count: 1,\n clientFingerprint: fingerprint,\n });\n\n queue.push({ event, attempts: 0 });\n if (queue.length > limits.queuedEvents) queue.shift();\n if (queue.length >= limits.flushAtEvents) void flush();\n else scheduleFlush(limits.flushDelayMs);\n } catch {\n // Never into the caller.\n }\n };\n\n return {\n captureError,\n addBreadcrumb: (breadcrumb) => {\n try {\n trail.add(sanitizeBreadcrumb(breadcrumb, redactor));\n } catch {\n // Never into the caller.\n }\n },\n setRoute: (routePattern, url) => {\n route = { routePattern, url };\n },\n setAuthorizationReader: (reader) => {\n readAuthorization = reader;\n },\n flush,\n getQueuedEventCount: () => queue.length,\n };\n};\n","import { navigationBreadcrumb } from './breadcrumbs';\nimport type { CapturedBreadcrumb } from './types';\n\n/** Dynamic route params as routers hand them out (`string` per segment, `string[]` for a catch-all). */\nexport type IssuesRouteParams = Record<string, string | readonly string[] | undefined>;\n\n/**\n * The route PATTERN of a page, rebuilt from its path and its dynamic params: `/books/12/chapters/3` with\n * `{ bookId: '12', chapterId: '3' }` → `/books/[bookId]/chapters/[chapterId]`. The pattern names the issue (one bug on\n * every book's chapter page is one issue) and carries no slug, id or token.\n *\n * Params are matched left to right, each against the first unmatched segment equal to its value, so\n * `/books/3/chapters/3` with `{ bookId: '3', chapterId: '3' }` still comes out right. A catch-all (array value)\n * replaces the run of segments it spans with `[...key]`.\n */\nexport const buildRoutePattern = (pathname: string, params: IssuesRouteParams | null | undefined): string => {\n const segments = pathname.split('/');\n const decode = (segment: string): string => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n };\n const decodedSegments = segments.map(decode);\n let searchFrom = 1;\n\n for (const [key, rawValue] of Object.entries(params ?? {})) {\n if (rawValue === undefined) continue;\n const isCatchAll = typeof rawValue !== 'string';\n const values = (isCatchAll ? [...rawValue] : [rawValue]).map(decode);\n if (values.length === 0) continue;\n for (let start = searchFrom; start + values.length <= segments.length; start++) {\n const isRun = values.every((value, offset) => decodedSegments[start + offset] === value);\n if (!isRun) continue;\n const placeholder = isCatchAll ? `[...${key}]` : `[${key}]`;\n segments.splice(start, values.length, placeholder);\n decodedSegments.splice(start, values.length, placeholder);\n searchFrom = start + 1;\n break;\n }\n }\n return segments.join('/') || '/';\n};\n\n/** The part of a reporter a route tracker drives. */\nexport interface IssuesRouteTarget {\n setRoute: (routePattern: string | null, url: string | null) => void;\n addBreadcrumb: (breadcrumb: CapturedBreadcrumb) => void;\n}\n\nexport interface IssuesRouteTracker {\n /**\n * Call on every route change: sets the reporter's route pattern and URL (the URL defaults to the path) and adds a\n * navigation breadcrumb when the pattern changed. Returns the pattern.\n */\n trackRoute: (pathname: string, params?: IssuesRouteParams | null, url?: string | null) => string;\n}\n\n/** Platform-free: a web router, a React Native navigator or a test calls `trackRoute` itself. */\nexport const createIssuesRouteTracker = (\n target: IssuesRouteTarget,\n now: () => string = () => new Date().toISOString(),\n): IssuesRouteTracker => {\n let previousRoutePattern: string | null = null;\n return {\n trackRoute: (pathname, params, url) => {\n const routePattern = buildRoutePattern(pathname, params);\n target.setRoute(routePattern, url === undefined ? pathname : url);\n if (routePattern !== previousRoutePattern) {\n target.addBreadcrumb(navigationBreadcrumb(now(), previousRoutePattern, routePattern));\n previousRoutePattern = routePattern;\n }\n return routePattern;\n },\n };\n};\n","import type { IssuesTransport } from './types';\n\n/** The part of the Fetch API the transport uses (browser, Node 18+, React Native). */\nexport type IssuesFetchFunction = (\n url: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n keepalive?: boolean;\n credentials?: 'omit' | 'same-origin' | 'include';\n signal?: unknown;\n },\n) => Promise<{ status: number }>;\n\nexport interface FetchIssuesTransportOptions {\n /** Read at send time; default the global `fetch` as it is then. */\n fetch?: () => IssuesFetchFunction | undefined;\n /** Default `omit`: the report carries a bearer when there is a session, never cookies. */\n credentials?: 'omit' | 'same-origin' | 'include';\n /** Aborts a request that takes longer (where `AbortSignal.timeout` exists); default none. */\n timeoutMs?: number;\n}\n\ninterface AbortSignalWithTimeout {\n timeout?: (milliseconds: number) => unknown;\n}\n\n/** POSTs with `fetch`. Rejects on a network error, like `fetch` itself. Touches no global before the first send. */\nexport const createFetchIssuesTransport = (options: FetchIssuesTransportOptions = {}): IssuesTransport => {\n return async (request) => {\n const fetchFunction =\n options.fetch?.() ?? (globalThis as unknown as { fetch?: IssuesFetchFunction }).fetch;\n if (typeof fetchFunction !== 'function') throw new Error('No fetch function available for the issues transport');\n const abortSignalClass = (globalThis as unknown as { AbortSignal?: AbortSignalWithTimeout }).AbortSignal;\n const signal =\n options.timeoutMs !== undefined && typeof abortSignalClass?.timeout === 'function'\n ? abortSignalClass.timeout(options.timeoutMs)\n : undefined;\n const response = await fetchFunction(request.url, {\n method: 'POST',\n headers: request.headers,\n body: request.body,\n credentials: options.credentials ?? 'omit',\n ...(request.keepalive ? { keepalive: true } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n return { status: response.status };\n };\n};\n"],"mappings":";;;;;AA6DO,IAAM,gBAAwC,OAAO,OAAO;AAAA,EACjE,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EAEzB,cAAc;AAAA,EACd,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,cAAc,KAAK;AAAA,EACnB,YAAY,KAAK;AAAA,EACjB,cAAc;AAAA,EACd,c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iBAAiB,sBAAsB;AACzC,eAAO,cAAc,qBAAqB,IAAI,GAAG,sBAAsB,YAAY,CAAC;AACpF,+BAAuB;AAAA,MACzB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;AC/CO,IAAM,6BAA6B,CAAC,UAAuC,CAAC,MAAuB;AACxG,SAAO,OAAO,YAAY;AACxB,UAAM,gBACJ,QAAQ,QAAQ,KAAM,WAA0D;AAClF,QAAI,OAAO,kBAAkB,WAAY,OAAM,IAAI,MAAM,sDAAsD;AAC/G,UAAM,mBAAoB,WAAmE;AAC7F,UAAM,SACJ,QAAQ,cAAc,UAAa,OAAO,kBAAkB,YAAY,aACpE,iBAAiB,QAAQ,QAAQ,SAAS,IAC1C;AACN,UAAM,WAAW,MAAM,cAAc,QAAQ,KAAK;AAAA,MAChD,QAAQ;AAAA,MACR,SAAS,QAAQ;AAAA,MACjB,MAAM,QAAQ;AAAA,MACd,aAAa,QAAQ,eAAe;AAAA,MACpC,GAAI,QAAQ,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,MAC/C,GAAI,WAAW,SAAY,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3C,CAAC;AACD,WAAO,EAAE,QAAQ,SAAS,OAAO;AAAA,EACnC;AACF;","names":["message"]}
@@ -59,8 +59,12 @@ interface BeaconIssuesTransportOptions {
59
59
  * account attribution is never lost. A queued beacon answers 202.
60
60
  */
61
61
  declare const createBeaconIssuesTransport: (options?: BeaconIssuesTransportOptions) => IssuesTransport;
62
- type BrowserReporterBaseOptions = Omit<IssuesReporterOptions<DddClientIssueEvent, DddClientIssuesReportRequestBody>, 'runtime' | 'endpoint' | 'transport' | 'context' | 'serverToken' | 'serverTokenHeader'>;
63
- interface BrowserIssuesReporterOptions extends BrowserReporterBaseOptions {
62
+ type BrowserReporterBaseOptions<TWireEvent, TRequestBody> = Omit<IssuesReporterOptions<TWireEvent, TRequestBody>, 'runtime' | 'endpoint' | 'transport' | 'context' | 'serverToken' | 'serverTokenHeader'>;
63
+ /**
64
+ * Generic over the wire types like {@link IssuesReporterOptions}: the defaults are the DDD contract; a `wire` built
65
+ * from your generated models types the event and the body with them.
66
+ */
67
+ interface BrowserIssuesReporterOptions<TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody> extends BrowserReporterBaseOptions<TWireEvent, TRequestBody> {
64
68
  /**
65
69
  * The ingest endpoint: a full URL, a path of this origin, or a function read at send time. Default
66
70
  * {@link DDD_ISSUES_REPORT_PATH} on this origin.
@@ -80,7 +84,7 @@ interface BrowserIssuesReporterOptions extends BrowserReporterBaseOptions {
80
84
  * A reporter for the page: runtime `browser`, session caps, viewport / locale / tab id as context, in-app files =
81
85
  * this origin's scripts, nothing reported under automation (`navigator.webdriver`). Null outside a browser (SSR).
82
86
  */
83
- declare const createBrowserIssuesReporter: (options: BrowserIssuesReporterOptions) => IssuesReporter | null;
87
+ declare const createBrowserIssuesReporter: <TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody>(options: BrowserIssuesReporterOptions<TWireEvent, TRequestBody>) => IssuesReporter | null;
84
88
  interface BrowserIssueCaptureOptions {
85
89
  browserWindow?: IssuesBrowserWindow;
86
90
  /** Breadcrumb per failed request (status ≥ 400 or no answer). Default true. */
@@ -5,7 +5,7 @@ import {
5
5
  createIssuesRouteTracker,
6
6
  fetchBreadcrumb,
7
7
  uiBreadcrumb
8
- } from "../../chunk-GVRMHMNO.js";
8
+ } from "../../chunk-4NBJXOD2.js";
9
9
  import {
10
10
  DDD_ISSUES_REPORT_PATH
11
11
  } from "../../chunk-JAYJB2EF.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/issues/browser/index.ts"],"sourcesContent":["/**\n * `@mgamadeus/ddd-web/issues/browser` — the browser adapter of the issues reporter: a reporter with the page's\n * context and a keepalive / beacon transport, the global capture points (uncaught errors, unhandled rejections,\n * breadcrumbs from failed requests, `console.error` and clicks, flush on `pagehide`), a route tracker and render-error\n * reporting for error boundaries. No framework: a Next.js, Vite or any other app calls these from its own entry points.\n */\nimport {\n consoleBreadcrumb,\n createFetchIssuesTransport,\n createIssuesReporter,\n createIssuesRouteTracker,\n fetchBreadcrumb,\n uiBreadcrumb,\n type IssuesFetchFunction,\n type IssuesReporter,\n type IssuesReporterOptions,\n type IssuesRouteParams,\n type IssuesTransport,\n} from '../index';\nimport { DDD_ISSUES_REPORT_PATH, type DddClientIssueEvent, type DddClientIssuesReportRequestBody } from '../wire';\n\ntype BrowserEventListener = (event: Event) => void;\n\n/** The part of `window` the adapter uses; a test passes a fake (an `EventTarget` with `fetch`). */\nexport interface IssuesBrowserWindow {\n addEventListener: (type: string, listener: BrowserEventListener, options?: boolean | AddEventListenerOptions) => void;\n removeEventListener: (type: string, listener: BrowserEventListener, options?: boolean | EventListenerOptions) => void;\n fetch: typeof fetch;\n document?: {\n visibilityState: string;\n addEventListener: (type: string, listener: BrowserEventListener) => void;\n removeEventListener: (type: string, listener: BrowserEventListener) => void;\n };\n location?: { href: string; origin: string };\n navigator?: { webdriver?: boolean; language?: string; sendBeacon?: (url: string, data?: BodyInit | null) => boolean };\n innerWidth?: number;\n innerHeight?: number;\n sessionStorage?: Pick<Storage, 'getItem' | 'setItem'>;\n crypto?: { randomUUID?: () => string };\n console?: { error: (...args: unknown[]) => void };\n}\n\nconst readBrowserWindow = (): IssuesBrowserWindow | null => {\n const candidate = globalThis as unknown as Partial<IssuesBrowserWindow>;\n return typeof candidate.addEventListener === 'function' && typeof candidate.fetch === 'function'\n ? (candidate as IssuesBrowserWindow)\n : null;\n};\n\n/** The `fetch` from before {@link installBrowserIssueCapture} wrapped it, per window: the reporter's own requests leave no breadcrumbs. */\nconst unwrappedFetchByWindow = new WeakMap<object, typeof fetch>();\n\nconst readUnwrappedFetch = (browserWindow: IssuesBrowserWindow): typeof fetch =>\n unwrappedFetchByWindow.get(browserWindow) ?? browserWindow.fetch.bind(browserWindow);\n\n/** Default key of the per-tab id in `sessionStorage`. */\nexport const DDD_ISSUES_TAB_ID_STORAGE_KEY = 'ddd-issues-tab-id';\n\n/**\n * The id of this tab, kept in `sessionStorage`: tells one user's repeats from many users, never a person. Null when\n * storage is blocked (private mode, a sandboxed frame).\n */\nexport const readOrCreateIssuesTabId = (\n storageKey: string = DDD_ISSUES_TAB_ID_STORAGE_KEY,\n browserWindow: IssuesBrowserWindow | null = readBrowserWindow(),\n): string | null => {\n try {\n const storage = browserWindow?.sessionStorage;\n if (!storage) return null;\n const existingTabId = storage.getItem(storageKey);\n if (existingTabId) return existingTabId;\n const tabId =\n browserWindow?.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n storage.setItem(storageKey, tabId);\n return tabId;\n } catch {\n return null;\n }\n};\n\nexport interface BeaconIssuesTransportOptions {\n /** Sends whatever the beacon does not: every request that is not unloading, or carries headers a beacon cannot. */\n fallback?: IssuesTransport;\n browserWindow?: IssuesBrowserWindow | null;\n}\n\n/**\n * Sends an unloading request (`flush({ unloading: true })`) with `navigator.sendBeacon` (as `text/plain`, no CORS preflight; the backend reads the\n * JSON body regardless of its type) and everything else with the fallback (default: `fetch` with keepalive). A beacon\n * carries no headers: a request with `Authorization` or a server token always goes through the fallback, so the\n * account attribution is never lost. A queued beacon answers 202.\n */\nexport const createBeaconIssuesTransport = (options: BeaconIssuesTransportOptions = {}): IssuesTransport => {\n const fallback = options.fallback ?? createFetchIssuesTransport();\n return async (request) => {\n const browserWindow = options.browserWindow === undefined ? readBrowserWindow() : options.browserWindow;\n const sendBeacon = browserWindow?.navigator?.sendBeacon;\n const hasHeadersBeyondContentType = Object.keys(request.headers).some(\n (headerName) => !['content-type', 'accept'].includes(headerName.toLowerCase()),\n );\n if (request.unloading && typeof sendBeacon === 'function' && !hasHeadersBeyondContentType) {\n try {\n const isQueued = sendBeacon.call(\n browserWindow?.navigator,\n request.url,\n new Blob([request.body], { type: 'text/plain;charset=UTF-8' }),\n );\n if (isQueued) return { status: 202 };\n } catch {\n // Fall through to the fallback.\n }\n }\n return fallback(request);\n };\n};\n\ntype BrowserReporterBaseOptions = Omit<\n IssuesReporterOptions<DddClientIssueEvent, DddClientIssuesReportRequestBody>,\n 'runtime' | 'endpoint' | 'transport' | 'context' | 'serverToken' | 'serverTokenHeader'\n>;\n\nexport interface BrowserIssuesReporterOptions extends BrowserReporterBaseOptions {\n /**\n * The ingest endpoint: a full URL, a path of this origin, or a function read at send time. Default\n * {@link DDD_ISSUES_REPORT_PATH} on this origin.\n */\n endpoint?: string | (() => string | null);\n /** The release the backend files the error under (and looks its source maps up by). Read at send time. */\n release?: () => string | null | undefined;\n /** Default `navigator.language`. */\n locale?: () => string | null | undefined;\n /** Default: beacon on unload, `fetch` (keepalive, no cookies) otherwise, with the fetch from before the capture wrapped it. */\n transport?: IssuesTransport;\n /** `sessionStorage` key of the tab id; null = no tab id. Default {@link DDD_ISSUES_TAB_ID_STORAGE_KEY}. */\n tabIdStorageKey?: string | null;\n browserWindow?: IssuesBrowserWindow;\n}\n\n/**\n * A reporter for the page: runtime `browser`, session caps, viewport / locale / tab id as context, in-app files =\n * this origin's scripts, nothing reported under automation (`navigator.webdriver`). Null outside a browser (SSR).\n */\nexport const createBrowserIssuesReporter = (options: BrowserIssuesReporterOptions): IssuesReporter | null => {\n const browserWindow = options.browserWindow ?? readBrowserWindow();\n if (!browserWindow) return null;\n const tabId =\n options.tabIdStorageKey === null\n ? null\n : readOrCreateIssuesTabId(options.tabIdStorageKey ?? DDD_ISSUES_TAB_ID_STORAGE_KEY, browserWindow);\n const configuredEndpoint = options.endpoint ?? DDD_ISSUES_REPORT_PATH;\n const resolveEndpoint = (): string | null => {\n const endpoint = typeof configuredEndpoint === 'function' ? configuredEndpoint() : configuredEndpoint;\n if (!endpoint) return null;\n const origin = browserWindow.location?.origin;\n return endpoint.startsWith('/') && !endpoint.startsWith('//') && origin ? `${origin}${endpoint}` : endpoint;\n };\n const origin = browserWindow.location?.origin;\n const isInAppFile = (file: string): boolean => (origin ? file.startsWith(`${origin}/`) : false) || file.startsWith('/');\n\n const { endpoint: _endpoint, release, locale, transport, tabIdStorageKey: _tabIdStorageKey, browserWindow: _browserWindow, ...reporterOptions } =\n options;\n return createIssuesReporter({\n isInAppFile,\n isAutomated: () => browserWindow.navigator?.webdriver === true,\n ...reporterOptions,\n runtime: 'browser',\n endpoint: resolveEndpoint,\n context: () => ({\n release: release?.() ?? null,\n tabId,\n // The backend reads a browser's user agent from the request header.\n userAgent: null,\n viewportWidth: browserWindow.innerWidth ?? null,\n viewportHeight: browserWindow.innerHeight ?? null,\n locale: (locale ? locale() : browserWindow.navigator?.language) || null,\n }),\n transport:\n transport ??\n createBeaconIssuesTransport({\n browserWindow,\n fallback: createFetchIssuesTransport({\n fetch: () => readUnwrappedFetch(browserWindow) as unknown as IssuesFetchFunction,\n }),\n }),\n });\n};\n\nexport interface BrowserIssueCaptureOptions {\n browserWindow?: IssuesBrowserWindow;\n /** Breadcrumb per failed request (status ≥ 400 or no answer). Default true. */\n captureFetch?: boolean;\n /** Breadcrumb per `console.error` (its first argument). Default true. */\n captureConsoleErrors?: boolean;\n /** Breadcrumb per click (`data-issues-action`, else tag and role; never text). Default true. */\n captureClicks?: boolean;\n /** Requests that leave no breadcrumb. Default: URLs containing {@link DDD_ISSUES_REPORT_PATH}. */\n isIgnoredRequestUrl?: (url: string) => boolean;\n now?: () => string;\n}\n\nconst describeConsoleArgument = (value: unknown): string => {\n if (typeof value === 'string') return value;\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\ninterface ElementLike {\n tagName: string;\n getAttribute: (name: string) => string | null;\n closest: (selector: string) => ElementLike | null;\n}\n\nconst isElementLike = (value: unknown): value is ElementLike =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ElementLike).closest === 'function' &&\n typeof (value as ElementLike).getAttribute === 'function' &&\n typeof (value as ElementLike).tagName === 'string';\n\n/** `data-issues-action` of the clicked element or an ancestor, else its tag and role — never text. */\nexport const describeIssuesClickTarget = (target: unknown): string | null => {\n if (!isElementLike(target)) return null;\n const withAction = target.closest('[data-issues-action]');\n if (withAction) return withAction.getAttribute('data-issues-action');\n const interactive = target.closest('button, a, [role], input, select, textarea, label') ?? target;\n const role = interactive.getAttribute('role');\n return `${interactive.tagName.toLowerCase()}${role ? `[role=${role}]` : ''}`;\n};\n\nconst describeRequest = (input: unknown, init?: RequestInit): { method: string; url: string } => {\n if (typeof input === 'object' && input !== null && 'url' in input && typeof (input as Request).url === 'string') {\n const request = input as Request;\n return { method: init?.method ?? request.method ?? 'GET', url: request.url };\n }\n return { method: init?.method ?? 'GET', url: String(input) };\n};\n\nconst isAbortError = (error: unknown): boolean =>\n typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError';\n\n/**\n * Installs the browser capture points once per window (before hydration, e.g. in the client instrumentation file):\n * - uncaught errors (`error`) and unhandled rejections → reported;\n * - failed requests, `console.error` and clicks → breadcrumbs only, never reports of their own;\n * - `pagehide` / tab hidden → flush with keepalive.\n * Render crashes come from the app's error boundaries ({@link captureRenderError}). Returns the uninstall function.\n */\nexport const installBrowserIssueCapture = (\n reporter: IssuesReporter,\n options: BrowserIssueCaptureOptions = {},\n): (() => void) => {\n const browserWindow = options.browserWindow ?? readBrowserWindow();\n if (!browserWindow || unwrappedFetchByWindow.has(browserWindow)) return () => undefined;\n const now = options.now ?? (() => new Date().toISOString());\n const isIgnoredRequestUrl = options.isIgnoredRequestUrl ?? ((url: string) => url.includes(DDD_ISSUES_REPORT_PATH));\n const uninstallSteps: (() => void)[] = [];\n\n const listen = (type: string, listener: BrowserEventListener, listenerOptions?: AddEventListenerOptions) => {\n browserWindow.addEventListener(type, listener, listenerOptions);\n uninstallSteps.push(() => browserWindow.removeEventListener(type, listener, listenerOptions));\n };\n\n listen('error', (event) => {\n const errorEvent = event as ErrorEvent;\n // A script error without an Error object (cross-origin, old browsers): the position comes from the event.\n const error =\n errorEvent.error ??\n Object.assign(new Error(errorEvent.message || 'Script error.'), {\n stack: errorEvent.filename\n ? `Error: ${errorEvent.message}\\n at ${errorEvent.filename}:${errorEvent.lineno}:${errorEvent.colno}`\n : undefined,\n });\n reporter.captureError(error, 'error');\n });\n\n listen('unhandledrejection', (event) => {\n reporter.captureError((event as PromiseRejectionEvent).reason, 'unhandledrejection');\n });\n\n if (options.captureClicks !== false) {\n listen(\n 'click',\n (event) => {\n const action = describeIssuesClickTarget(event.target);\n if (action) reporter.addBreadcrumb(uiBreadcrumb(now(), action));\n },\n { capture: true, passive: true },\n );\n }\n\n const originalFetch = browserWindow.fetch;\n unwrappedFetchByWindow.set(browserWindow, originalFetch.bind(browserWindow));\n uninstallSteps.push(() => unwrappedFetchByWindow.delete(browserWindow));\n if (options.captureFetch !== false) {\n const wrappedFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const { method, url } = describeRequest(input, init);\n try {\n const response = await originalFetch.call(browserWindow, input, init);\n if (response.status >= 400 && !isIgnoredRequestUrl(url)) {\n reporter.addBreadcrumb(fetchBreadcrumb(now(), method, url, response.status));\n }\n return response;\n } catch (error) {\n if (!isAbortError(error) && !isIgnoredRequestUrl(url)) {\n reporter.addBreadcrumb(fetchBreadcrumb(now(), method, url, 'network-error'));\n }\n throw error;\n }\n };\n browserWindow.fetch = wrappedFetch as typeof fetch;\n uninstallSteps.push(() => {\n if (browserWindow.fetch === wrappedFetch) browserWindow.fetch = originalFetch;\n });\n }\n\n const browserConsole = browserWindow.console ?? (globalThis as { console?: { error: (...args: unknown[]) => void } }).console;\n if (options.captureConsoleErrors !== false && browserConsole) {\n const originalConsoleError = browserConsole.error;\n const wrappedConsoleError = (...args: unknown[]) => {\n reporter.addBreadcrumb(consoleBreadcrumb(now(), describeConsoleArgument(args[0])));\n originalConsoleError.apply(browserConsole, args);\n };\n browserConsole.error = wrappedConsoleError;\n uninstallSteps.push(() => {\n if (browserConsole.error === wrappedConsoleError) browserConsole.error = originalConsoleError;\n });\n }\n\n const flushOnLeave = () => void reporter.flush({ unloading: true });\n listen('pagehide', flushOnLeave);\n const browserDocument = browserWindow.document;\n if (browserDocument) {\n const flushWhenHidden = () => {\n if (browserDocument.visibilityState === 'hidden') flushOnLeave();\n };\n browserDocument.addEventListener('visibilitychange', flushWhenHidden);\n uninstallSteps.push(() => browserDocument.removeEventListener('visibilitychange', flushWhenHidden));\n }\n\n return () => {\n for (const uninstallStep of uninstallSteps.splice(0).reverse()) uninstallStep();\n };\n};\n\n/**\n * Route tracking for a browser router: call `trackRoute(pathname, params)` on every route change (e.g. from an\n * effect on the router's path and params). The URL is the page's `location.href`, redacted by the reporter.\n */\nexport const createBrowserIssuesRouteTracker = (\n reporter: IssuesReporter,\n browserWindow: IssuesBrowserWindow | null = readBrowserWindow(),\n): { trackRoute: (pathname: string, params?: IssuesRouteParams | null) => string } => {\n const routeTracker = createIssuesRouteTracker(reporter);\n return {\n trackRoute: (pathname, params) => routeTracker.trackRoute(pathname, params, browserWindow?.location?.href ?? pathname),\n };\n};\n\n/**\n * A render crash caught by an error boundary. An error with a `digest` was thrown on the SERVER (React server\n * components): the browser only gets a placeholder message and the server's reporter has the real one, so it is not\n * reported twice unless `reportServerDigests` is set.\n */\nexport const captureRenderError = (\n reporter: IssuesReporter | null | undefined,\n error: unknown,\n options: { reportServerDigests?: boolean } = {},\n): void => {\n const digest = typeof error === 'object' && error !== null ? (error as { digest?: unknown }).digest : undefined;\n if (digest && !options.reportServerDigests) return;\n reporter?.captureError(error, 'react-render');\n};\n"],"mappings":";;;;;;;;;;;;;AA0CA,IAAM,oBAAoB,MAAkC;AAC1D,QAAM,YAAY;AAClB,SAAO,OAAO,UAAU,qBAAqB,cAAc,OAAO,UAAU,UAAU,aACjF,YACD;AACN;AAGA,IAAM,yBAAyB,oBAAI,QAA8B;AAEjE,IAAM,qBAAqB,CAAC,kBAC1B,uBAAuB,IAAI,aAAa,KAAK,cAAc,MAAM,KAAK,aAAa;AAG9E,IAAM,gCAAgC;AAMtC,I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AAE,QAAQ,EAAG,eAAc;AAAA,EAChF;AACF;AAMO,IAAM,kCAAkC,CAC7C,UACA,gBAA4C,kBAAkB,MACsB;AACpF,QAAM,eAAe,yBAAyB,QAAQ;AACtD,SAAO;AAAA,IACL,YAAY,CAAC,UAAU,WAAW,aAAa,WAAW,UAAU,QAAQ,eAAe,UAAU,QAAQ,QAAQ;AAAA,EACvH;AACF;AAOO,IAAM,qBAAqB,CAChC,UACA,OACA,UAA6C,CAAC,MACrC;AACT,QAAM,SAAS,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA+B,SAAS;AACtG,MAAI,UAAU,CAAC,QAAQ,oBAAqB;AAC5C,YAAU,aAAa,OAAO,cAAc;AAC9C;","names":["origin"]}
1
+ {"version":3,"sources":["../../../src/issues/browser/index.ts"],"sourcesContent":["/**\n * `@mgamadeus/ddd-web/issues/browser` — the browser adapter of the issues reporter: a reporter with the page's\n * context and a keepalive / beacon transport, the global capture points (uncaught errors, unhandled rejections,\n * breadcrumbs from failed requests, `console.error` and clicks, flush on `pagehide`), a route tracker and render-error\n * reporting for error boundaries. No framework: a Next.js, Vite or any other app calls these from its own entry points.\n */\nimport {\n consoleBreadcrumb,\n createFetchIssuesTransport,\n createIssuesReporter,\n createIssuesRouteTracker,\n fetchBreadcrumb,\n uiBreadcrumb,\n type IssuesFetchFunction,\n type IssuesReporter,\n type IssuesReporterOptions,\n type IssuesRouteParams,\n type IssuesTransport,\n} from '../index';\nimport { DDD_ISSUES_REPORT_PATH, type DddClientIssueEvent, type DddClientIssuesReportRequestBody } from '../wire';\n\ntype BrowserEventListener = (event: Event) => void;\n\n/** The part of `window` the adapter uses; a test passes a fake (an `EventTarget` with `fetch`). */\nexport interface IssuesBrowserWindow {\n addEventListener: (type: string, listener: BrowserEventListener, options?: boolean | AddEventListenerOptions) => void;\n removeEventListener: (type: string, listener: BrowserEventListener, options?: boolean | EventListenerOptions) => void;\n fetch: typeof fetch;\n document?: {\n visibilityState: string;\n addEventListener: (type: string, listener: BrowserEventListener) => void;\n removeEventListener: (type: string, listener: BrowserEventListener) => void;\n };\n location?: { href: string; origin: string };\n navigator?: { webdriver?: boolean; language?: string; sendBeacon?: (url: string, data?: BodyInit | null) => boolean };\n innerWidth?: number;\n innerHeight?: number;\n sessionStorage?: Pick<Storage, 'getItem' | 'setItem'>;\n crypto?: { randomUUID?: () => string };\n console?: { error: (...args: unknown[]) => void };\n}\n\nconst readBrowserWindow = (): IssuesBrowserWindow | null => {\n const candidate = globalThis as unknown as Partial<IssuesBrowserWindow>;\n return typeof candidate.addEventListener === 'function' && typeof candidate.fetch === 'function'\n ? (candidate as IssuesBrowserWindow)\n : null;\n};\n\n/** The `fetch` from before {@link installBrowserIssueCapture} wrapped it, per window: the reporter's own requests leave no breadcrumbs. */\nconst unwrappedFetchByWindow = new WeakMap<object, typeof fetch>();\n\nconst readUnwrappedFetch = (browserWindow: IssuesBrowserWindow): typeof fetch =>\n unwrappedFetchByWindow.get(browserWindow) ?? browserWindow.fetch.bind(browserWindow);\n\n/** Default key of the per-tab id in `sessionStorage`. */\nexport const DDD_ISSUES_TAB_ID_STORAGE_KEY = 'ddd-issues-tab-id';\n\n/**\n * The id of this tab, kept in `sessionStorage`: tells one user's repeats from many users, never a person. Null when\n * storage is blocked (private mode, a sandboxed frame).\n */\nexport const readOrCreateIssuesTabId = (\n storageKey: string = DDD_ISSUES_TAB_ID_STORAGE_KEY,\n browserWindow: IssuesBrowserWindow | null = readBrowserWindow(),\n): string | null => {\n try {\n const storage = browserWindow?.sessionStorage;\n if (!storage) return null;\n const existingTabId = storage.getItem(storageKey);\n if (existingTabId) return existingTabId;\n const tabId =\n browserWindow?.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n storage.setItem(storageKey, tabId);\n return tabId;\n } catch {\n return null;\n }\n};\n\nexport interface BeaconIssuesTransportOptions {\n /** Sends whatever the beacon does not: every request that is not unloading, or carries headers a beacon cannot. */\n fallback?: IssuesTransport;\n browserWindow?: IssuesBrowserWindow | null;\n}\n\n/**\n * Sends an unloading request (`flush({ unloading: true })`) with `navigator.sendBeacon` (as `text/plain`, no CORS preflight; the backend reads the\n * JSON body regardless of its type) and everything else with the fallback (default: `fetch` with keepalive). A beacon\n * carries no headers: a request with `Authorization` or a server token always goes through the fallback, so the\n * account attribution is never lost. A queued beacon answers 202.\n */\nexport const createBeaconIssuesTransport = (options: BeaconIssuesTransportOptions = {}): IssuesTransport => {\n const fallback = options.fallback ?? createFetchIssuesTransport();\n return async (request) => {\n const browserWindow = options.browserWindow === undefined ? readBrowserWindow() : options.browserWindow;\n const sendBeacon = browserWindow?.navigator?.sendBeacon;\n const hasHeadersBeyondContentType = Object.keys(request.headers).some(\n (headerName) => !['content-type', 'accept'].includes(headerName.toLowerCase()),\n );\n if (request.unloading && typeof sendBeacon === 'function' && !hasHeadersBeyondContentType) {\n try {\n const isQueued = sendBeacon.call(\n browserWindow?.navigator,\n request.url,\n new Blob([request.body], { type: 'text/plain;charset=UTF-8' }),\n );\n if (isQueued) return { status: 202 };\n } catch {\n // Fall through to the fallback.\n }\n }\n return fallback(request);\n };\n};\n\ntype BrowserReporterBaseOptions<TWireEvent, TRequestBody> = Omit<\n IssuesReporterOptions<TWireEvent, TRequestBody>,\n 'runtime' | 'endpoint' | 'transport' | 'context' | 'serverToken' | 'serverTokenHeader'\n>;\n\n/**\n * Generic over the wire types like {@link IssuesReporterOptions}: the defaults are the DDD contract; a `wire` built\n * from your generated models types the event and the body with them.\n */\nexport interface BrowserIssuesReporterOptions<\n TWireEvent = DddClientIssueEvent,\n TRequestBody = DddClientIssuesReportRequestBody,\n> extends BrowserReporterBaseOptions<TWireEvent, TRequestBody> {\n /**\n * The ingest endpoint: a full URL, a path of this origin, or a function read at send time. Default\n * {@link DDD_ISSUES_REPORT_PATH} on this origin.\n */\n endpoint?: string | (() => string | null);\n /** The release the backend files the error under (and looks its source maps up by). Read at send time. */\n release?: () => string | null | undefined;\n /** Default `navigator.language`. */\n locale?: () => string | null | undefined;\n /** Default: beacon on unload, `fetch` (keepalive, no cookies) otherwise, with the fetch from before the capture wrapped it. */\n transport?: IssuesTransport;\n /** `sessionStorage` key of the tab id; null = no tab id. Default {@link DDD_ISSUES_TAB_ID_STORAGE_KEY}. */\n tabIdStorageKey?: string | null;\n browserWindow?: IssuesBrowserWindow;\n}\n\n/**\n * A reporter for the page: runtime `browser`, session caps, viewport / locale / tab id as context, in-app files =\n * this origin's scripts, nothing reported under automation (`navigator.webdriver`). Null outside a browser (SSR).\n */\nexport const createBrowserIssuesReporter = <\n TWireEvent = DddClientIssueEvent,\n TRequestBody = DddClientIssuesReportRequestBody,\n>(\n options: BrowserIssuesReporterOptions<TWireEvent, TRequestBody>,\n): IssuesReporter | null => {\n const browserWindow = options.browserWindow ?? readBrowserWindow();\n if (!browserWindow) return null;\n const tabId =\n options.tabIdStorageKey === null\n ? null\n : readOrCreateIssuesTabId(options.tabIdStorageKey ?? DDD_ISSUES_TAB_ID_STORAGE_KEY, browserWindow);\n const configuredEndpoint = options.endpoint ?? DDD_ISSUES_REPORT_PATH;\n const resolveEndpoint = (): string | null => {\n const endpoint = typeof configuredEndpoint === 'function' ? configuredEndpoint() : configuredEndpoint;\n if (!endpoint) return null;\n const origin = browserWindow.location?.origin;\n return endpoint.startsWith('/') && !endpoint.startsWith('//') && origin ? `${origin}${endpoint}` : endpoint;\n };\n const origin = browserWindow.location?.origin;\n const isInAppFile = (file: string): boolean => (origin ? file.startsWith(`${origin}/`) : false) || file.startsWith('/');\n\n const { endpoint: _endpoint, release, locale, transport, tabIdStorageKey: _tabIdStorageKey, browserWindow: _browserWindow, ...reporterOptions } =\n options;\n return createIssuesReporter<TWireEvent, TRequestBody>({\n isInAppFile,\n isAutomated: () => browserWindow.navigator?.webdriver === true,\n ...reporterOptions,\n runtime: 'browser',\n endpoint: resolveEndpoint,\n context: () => ({\n release: release?.() ?? null,\n tabId,\n // The backend reads a browser's user agent from the request header.\n userAgent: null,\n viewportWidth: browserWindow.innerWidth ?? null,\n viewportHeight: browserWindow.innerHeight ?? null,\n locale: (locale ? locale() : browserWindow.navigator?.language) || null,\n }),\n transport:\n transport ??\n createBeaconIssuesTransport({\n browserWindow,\n fallback: createFetchIssuesTransport({\n fetch: () => readUnwrappedFetch(browserWindow) as unknown as IssuesFetchFunction,\n }),\n }),\n });\n};\n\nexport interface BrowserIssueCaptureOptions {\n browserWindow?: IssuesBrowserWindow;\n /** Breadcrumb per failed request (status ≥ 400 or no answer). Default true. */\n captureFetch?: boolean;\n /** Breadcrumb per `console.error` (its first argument). Default true. */\n captureConsoleErrors?: boolean;\n /** Breadcrumb per click (`data-issues-action`, else tag and role; never text). Default true. */\n captureClicks?: boolean;\n /** Requests that leave no breadcrumb. Default: URLs containing {@link DDD_ISSUES_REPORT_PATH}. */\n isIgnoredRequestUrl?: (url: string) => boolean;\n now?: () => string;\n}\n\nconst describeConsoleArgument = (value: unknown): string => {\n if (typeof value === 'string') return value;\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\ninterface ElementLike {\n tagName: string;\n getAttribute: (name: string) => string | null;\n closest: (selector: string) => ElementLike | null;\n}\n\nconst isElementLike = (value: unknown): value is ElementLike =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ElementLike).closest === 'function' &&\n typeof (value as ElementLike).getAttribute === 'function' &&\n typeof (value as ElementLike).tagName === 'string';\n\n/** `data-issues-action` of the clicked element or an ancestor, else its tag and role — never text. */\nexport const describeIssuesClickTarget = (target: unknown): string | null => {\n if (!isElementLike(target)) return null;\n const withAction = target.closest('[data-issues-action]');\n if (withAction) return withAction.getAttribute('data-issues-action');\n const interactive = target.closest('button, a, [role], input, select, textarea, label') ?? target;\n const role = interactive.getAttribute('role');\n return `${interactive.tagName.toLowerCase()}${role ? `[role=${role}]` : ''}`;\n};\n\nconst describeRequest = (input: unknown, init?: RequestInit): { method: string; url: string } => {\n if (typeof input === 'object' && input !== null && 'url' in input && typeof (input as Request).url === 'string') {\n const request = input as Request;\n return { method: init?.method ?? request.method ?? 'GET', url: request.url };\n }\n return { method: init?.method ?? 'GET', url: String(input) };\n};\n\nconst isAbortError = (error: unknown): boolean =>\n typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError';\n\n/**\n * Installs the browser capture points once per window (before hydration, e.g. in the client instrumentation file):\n * - uncaught errors (`error`) and unhandled rejections → reported;\n * - failed requests, `console.error` and clicks → breadcrumbs only, never reports of their own;\n * - `pagehide` / tab hidden → flush with keepalive.\n * Render crashes come from the app's error boundaries ({@link captureRenderError}). Returns the uninstall function.\n */\nexport const installBrowserIssueCapture = (\n reporter: IssuesReporter,\n options: BrowserIssueCaptureOptions = {},\n): (() => void) => {\n const browserWindow = options.browserWindow ?? readBrowserWindow();\n if (!browserWindow || unwrappedFetchByWindow.has(browserWindow)) return () => undefined;\n const now = options.now ?? (() => new Date().toISOString());\n const isIgnoredRequestUrl = options.isIgnoredRequestUrl ?? ((url: string) => url.includes(DDD_ISSUES_REPORT_PATH));\n const uninstallSteps: (() => void)[] = [];\n\n const listen = (type: string, listener: BrowserEventListener, listenerOptions?: AddEventListenerOptions) => {\n browserWindow.addEventListener(type, listener, listenerOptions);\n uninstallSteps.push(() => browserWindow.removeEventListener(type, listener, listenerOptions));\n };\n\n listen('error', (event) => {\n const errorEvent = event as ErrorEvent;\n // A script error without an Error object (cross-origin, old browsers): the position comes from the event.\n const error =\n errorEvent.error ??\n Object.assign(new Error(errorEvent.message || 'Script error.'), {\n stack: errorEvent.filename\n ? `Error: ${errorEvent.message}\\n at ${errorEvent.filename}:${errorEvent.lineno}:${errorEvent.colno}`\n : undefined,\n });\n reporter.captureError(error, 'error');\n });\n\n listen('unhandledrejection', (event) => {\n reporter.captureError((event as PromiseRejectionEvent).reason, 'unhandledrejection');\n });\n\n if (options.captureClicks !== false) {\n listen(\n 'click',\n (event) => {\n const action = describeIssuesClickTarget(event.target);\n if (action) reporter.addBreadcrumb(uiBreadcrumb(now(), action));\n },\n { capture: true, passive: true },\n );\n }\n\n const originalFetch = browserWindow.fetch;\n unwrappedFetchByWindow.set(browserWindow, originalFetch.bind(browserWindow));\n uninstallSteps.push(() => unwrappedFetchByWindow.delete(browserWindow));\n if (options.captureFetch !== false) {\n const wrappedFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const { method, url } = describeRequest(input, init);\n try {\n const response = await originalFetch.call(browserWindow, input, init);\n if (response.status >= 400 && !isIgnoredRequestUrl(url)) {\n reporter.addBreadcrumb(fetchBreadcrumb(now(), method, url, response.status));\n }\n return response;\n } catch (error) {\n if (!isAbortError(error) && !isIgnoredRequestUrl(url)) {\n reporter.addBreadcrumb(fetchBreadcrumb(now(), method, url, 'network-error'));\n }\n throw error;\n }\n };\n browserWindow.fetch = wrappedFetch as typeof fetch;\n uninstallSteps.push(() => {\n if (browserWindow.fetch === wrappedFetch) browserWindow.fetch = originalFetch;\n });\n }\n\n const browserConsole = browserWindow.console ?? (globalThis as { console?: { error: (...args: unknown[]) => void } }).console;\n if (options.captureConsoleErrors !== false && browserConsole) {\n const originalConsoleError = browserConsole.error;\n const wrappedConsoleError = (...args: unknown[]) => {\n reporter.addBreadcrumb(consoleBreadcrumb(now(), describeConsoleArgument(args[0])));\n originalConsoleError.apply(browserConsole, args);\n };\n browserConsole.error = wrappedConsoleError;\n uninstallSteps.push(() => {\n if (browserConsole.error === wrappedConsoleError) browserConsole.error = originalConsoleError;\n });\n }\n\n const flushOnLeave = () => void reporter.flush({ unloading: true });\n listen('pagehide', flushOnLeave);\n const browserDocument = browserWindow.document;\n if (browserDocument) {\n const flushWhenHidden = () => {\n if (browserDocument.visibilityState === 'hidden') flushOnLeave();\n };\n browserDocument.addEventListener('visibilitychange', flushWhenHidden);\n uninstallSteps.push(() => browserDocument.removeEventListener('visibilitychange', flushWhenHidden));\n }\n\n return () => {\n for (const uninstallStep of uninstallSteps.splice(0).reverse()) uninstallStep();\n };\n};\n\n/**\n * Route tracking for a browser router: call `trackRoute(pathname, params)` on every route change (e.g. from an\n * effect on the router's path and params). The URL is the page's `location.href`, redacted by the reporter.\n */\nexport const createBrowserIssuesRouteTracker = (\n reporter: IssuesReporter,\n browserWindow: IssuesBrowserWindow | null = readBrowserWindow(),\n): { trackRoute: (pathname: string, params?: IssuesRouteParams | null) => string } => {\n const routeTracker = createIssuesRouteTracker(reporter);\n return {\n trackRoute: (pathname, params) => routeTracker.trackRoute(pathname, params, browserWindow?.location?.href ?? pathname),\n };\n};\n\n/**\n * A render crash caught by an error boundary. An error with a `digest` was thrown on the SERVER (React server\n * components): the browser only gets a placeholder message and the server's reporter has the real one, so it is not\n * reported twice unless `reportServerDigests` is set.\n */\nexport const captureRenderError = (\n reporter: IssuesReporter | null | undefined,\n error: unknown,\n options: { reportServerDigests?: boolean } = {},\n): void => {\n const digest = typeof error === 'object' && error !== null ? (error as { digest?: unknown }).digest : undefined;\n if (digest && !options.reportServerDigests) return;\n reporter?.captureError(error, 'react-render');\n};\n"],"mappings":";;;;;;;;;;;;;AA0CA,IAAM,oBAAoB,MAAkC;AAC1D,QAAM,YAAY;AAClB,SAAO,OAAO,UAAU,qBAAqB,cAAc,OAAO,UAAU,UAAU,aACjF,YACD;AACN;AAGA,IAAM,yBAAyB,oBAAI,QAA8B;AAEjE,IAAM,qBAAqB,CAAC,kBAC1B,uBAAuB,IAAI,aAAa,KAAK,cAAc,MAAM,KAAK,aAAa;AAG9E,IAAM,gCAAgC;AAMtC,IAAM,0BAA0B,CACrC,aAAqB,+BACrB,gBAA4C,kBAAkB,MAC5C;AAClB,MAAI;AACF,UAAM,UAAU,eAAe;AAC/B,QAAI,CAAC,QAAS,QAAO;AACrB,UAAM,gBAAgB,QAAQ,QAAQ,UAAU;AAChD,QAAI,cAAe,QAAO;AAC1B,UAAM,QACJ,eAAe,QAAQ,aAAa,KAAK,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,E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MACrC;AACT,QAAM,SAAS,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA+B,SAAS;AACtG,MAAI,UAAU,CAAC,QAAQ,oBAAqB;AAC5C,YAAU,aAAa,OAAO,cAAc;AAC9C;","names":["origin"]}
@@ -28,7 +28,7 @@ import {
28
28
  truncate,
29
29
  uiBreadcrumb,
30
30
  utf8ByteLength
31
- } from "../chunk-GVRMHMNO.js";
31
+ } from "../chunk-4NBJXOD2.js";
32
32
  import "../chunk-JAYJB2EF.js";
33
33
  export {
34
34
  DDD_ISSUES_SERVER_TOKEN_HEADER,
@@ -9,14 +9,25 @@ import { IssuesReporterOptions, IssuesReporter } from '../index.js';
9
9
  * Uses the global `fetch` (Node 18+) and reads `process` only when called — no `node:` import.
10
10
  */
11
11
 
12
- type NodeReporterBaseOptions = Omit<IssuesReporterOptions<DddClientIssueEvent, DddClientIssuesReportRequestBody>, 'runtime' | 'endpoint' | 'transport' | 'context'>;
13
- interface NodeIssuesReporterOptions extends NodeReporterBaseOptions {
12
+ type NodeReporterBaseOptions<TWireEvent, TRequestBody> = Omit<IssuesReporterOptions<TWireEvent, TRequestBody>, 'runtime' | 'endpoint' | 'transport' | 'context'>;
13
+ /**
14
+ * Generic over the wire types like {@link IssuesReporterOptions}: the defaults are the DDD contract; a `wire` built
15
+ * from your generated models types the event and the body with them.
16
+ */
17
+ interface NodeIssuesReporterOptions<TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody> extends NodeReporterBaseOptions<TWireEvent, TRequestBody> {
18
+ /**
19
+ * The full URL of the ingest endpoint (`https://api.example.com/api/public/common/issues/report`), or a function
20
+ * returning it, read at send time. Wins over `apiBaseUrl` when both are set; a function returning null / empty sends
21
+ * nothing. Unset (or null / empty) = `apiBaseUrl` decides.
22
+ */
23
+ endpoint?: string | null | (() => string | null | undefined);
14
24
  /**
15
- * The API origin (`https://api.example.com`, a cluster-internal URL) — the report goes to
16
- * `<apiBaseUrl><reportPath>` — or a function returning the full endpoint URL. Null / empty = nothing is sent.
25
+ * The API origin (`https://api.example.com`, a cluster-internal URL): the report goes to `<apiBaseUrl><reportPath>`.
26
+ * Kept for compatibility: as a FUNCTION it returns the full endpoint URL, not a base URL — use `endpoint` for that.
27
+ * Ignored when `endpoint` is set. Null / empty = nothing is sent.
17
28
  */
18
29
  apiBaseUrl?: string | null | (() => string | null | undefined);
19
- /** Default {@link DDD_ISSUES_REPORT_PATH} */
30
+ /** Appended to a string `apiBaseUrl`. Default {@link DDD_ISSUES_REPORT_PATH} */
20
31
  reportPath?: string;
21
32
  /** The release the backend files the error under (and looks the server's source maps up by). */
22
33
  release?: () => string | null | undefined;
@@ -30,7 +41,7 @@ interface NodeIssuesReporterOptions extends NodeReporterBaseOptions {
30
41
  * files = everything outside `node_modules` and `node:` built-ins. Without `serverToken` the backend files the reports
31
42
  * as a browser's (WEB) — or drops them, when the application requires the token for server reports.
32
43
  */
33
- declare const createNodeIssuesReporter: (options: NodeIssuesReporterOptions) => IssuesReporter;
44
+ declare const createNodeIssuesReporter: <TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody>(options: NodeIssuesReporterOptions<TWireEvent, TRequestBody>) => IssuesReporter;
34
45
  /** The request of a server-side error, as frameworks hand it to their request-error hook. */
35
46
  interface ServerIssueRequest {
36
47
  path: string;
@@ -2,7 +2,7 @@ import {
2
2
  createFetchIssuesTransport,
3
3
  createIssuesReporter,
4
4
  redactUrl
5
- } from "../../chunk-GVRMHMNO.js";
5
+ } from "../../chunk-4NBJXOD2.js";
6
6
  import {
7
7
  DDD_ISSUES_REPORT_PATH
8
8
  } from "../../chunk-JAYJB2EF.js";
@@ -10,8 +10,11 @@ import {
10
10
  // src/issues/node/index.ts
11
11
  var readNodeProcess = () => globalThis.process ?? null;
12
12
  var createNodeIssuesReporter = (options) => {
13
- const { apiBaseUrl, reportPath, release, transport, requestTimeoutMs, ...reporterOptions } = options;
13
+ const { endpoint, apiBaseUrl, reportPath, release, transport, requestTimeoutMs, ...reporterOptions } = options;
14
14
  const resolveEndpoint = () => {
15
+ if (endpoint !== void 0 && endpoint !== null && endpoint !== "") {
16
+ return (typeof endpoint === "function" ? endpoint() : endpoint) || null;
17
+ }
15
18
  if (typeof apiBaseUrl === "function") return apiBaseUrl() || null;
16
19
  if (!apiBaseUrl) return null;
17
20
  return `${apiBaseUrl.replace(/\/+$/, "")}${reportPath ?? DDD_ISSUES_REPORT_PATH}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/issues/node/index.ts"],"sourcesContent":["/**\n * `@mgamadeus/ddd-web/issues/node` — the server adapter of the issues reporter, for a client app's own Node server\n * (an SSR server, a BFF): windowed caps and backoff, the shared server token (the backend files the reports as\n * WEB_SERVER), a request-error handler in the shape of a framework's `onRequestError` hook, and opt-in process hooks.\n * Uses the global `fetch` (Node 18+) and reads `process` only when called — no `node:` import.\n */\nimport {\n createFetchIssuesTransport,\n createIssuesReporter,\n redactUrl,\n type IssuesReporter,\n type IssuesReporterOptions,\n type IssuesTransport,\n} from '../index';\nimport type { DddClientIssueEvent, DddClientIssuesReportRequestBody } from '../wire';\nimport { DDD_ISSUES_REPORT_PATH } from '../wire';\n\ninterface NodeProcessLike {\n version?: string;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n off?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n}\n\nconst readNodeProcess = (): NodeProcessLike | null =>\n ((globalThis as { process?: NodeProcessLike }).process as NodeProcessLike | undefined) ?? null;\n\ntype NodeReporterBaseOptions = Omit<\n IssuesReporterOptions<DddClientIssueEvent, DddClientIssuesReportRequestBody>,\n 'runtime' | 'endpoint' | 'transport' | 'context'\n>;\n\nexport interface NodeIssuesReporterOptions extends NodeReporterBaseOptions {\n /**\n * The API origin (`https://api.example.com`, a cluster-internal URL) — the report goes to\n * `<apiBaseUrl><reportPath>` — or a function returning the full endpoint URL. Null / empty = nothing is sent.\n */\n apiBaseUrl?: string | null | (() => string | null | undefined);\n /** Default {@link DDD_ISSUES_REPORT_PATH} */\n reportPath?: string;\n /** The release the backend files the error under (and looks the server's source maps up by). */\n release?: () => string | null | undefined;\n /** Default `fetch` with a 10 s timeout. */\n transport?: IssuesTransport;\n /** Default 10 000 */\n requestTimeoutMs?: number;\n}\n\n/**\n * A reporter for a Node server: runtime `node`, windowed caps, no breadcrumbs, user agent `Node.js <version>`, in-app\n * files = everything outside `node_modules` and `node:` built-ins. Without `serverToken` the backend files the reports\n * as a browser's (WEB) — or drops them, when the application requires the token for server reports.\n */\nexport const createNodeIssuesReporter = (options: NodeIssuesReporterOptions): IssuesReporter => {\n const { apiBaseUrl, reportPath, release, transport, requestTimeoutMs, ...reporterOptions } = options;\n const resolveEndpoint = (): string | null => {\n if (typeof apiBaseUrl === 'function') return apiBaseUrl() || null;\n if (!apiBaseUrl) return null;\n return `${apiBaseUrl.replace(/\\/+$/, '')}${reportPath ?? DDD_ISSUES_REPORT_PATH}`;\n };\n return createIssuesReporter({\n isInAppFile: (file) => !file.includes('/node_modules/'),\n ...reporterOptions,\n runtime: 'node',\n endpoint: resolveEndpoint,\n context: () => {\n const nodeVersion = readNodeProcess()?.version;\n return { release: release?.() ?? null, userAgent: nodeVersion ? `Node.js ${nodeVersion}` : null };\n },\n transport: transport ?? createFetchIssuesTransport({ timeoutMs: requestTimeoutMs ?? 10_000 }),\n });\n};\n\n/** The request of a server-side error, as frameworks hand it to their request-error hook. */\nexport interface ServerIssueRequest {\n path: string;\n method: string;\n}\n\n/** Where in the server the error happened (fields of a framework's request-error context; all optional). */\nexport interface ServerIssueRequestContext {\n /** The route PATTERN (`/books/[bookId]`), never the URL */\n routePath?: string | null;\n routerKind?: string;\n routeType?: string;\n renderSource?: string;\n}\n\n/**\n * A request-error handler `(error, request, context) => void`, structurally compatible with a framework's\n * `onRequestError` hook (Next.js `instrumentation.ts`). Reports kind `server-request` with the route pattern, the\n * redacted path and the method; the error's `digest` goes in as a tag (an error boundary in the browser sees the same\n * digest and does not report it again). `getReporter` may return null (not configured).\n */\nexport const createServerRequestErrorHandler =\n (getReporter: () => IssuesReporter | null | undefined) =>\n (error: unknown, request: ServerIssueRequest, context: ServerIssueRequestContext = {}): void => {\n try {\n getReporter()?.captureError(error, 'server-request', {\n routePattern: context.routePath || null,\n url: redactUrl(request.path),\n requestMethod: request.method,\n tags: {\n digest: (error as { digest?: string } | null)?.digest,\n routerKind: context.routerKind,\n routeType: context.routeType,\n renderSource: context.renderSource,\n },\n });\n } catch {\n // Never into the framework.\n }\n };\n\nexport interface NodeIssueCaptureOptions {\n /**\n * Also report unhandled promise rejections. Off by default: a listener for `unhandledRejection` changes Node's\n * default behaviour (the process no longer exits on one). Turn it on only where that is wanted.\n */\n unhandledRejections?: boolean;\n}\n\n/**\n * Process hooks: uncaught exceptions are reported through `uncaughtExceptionMonitor` (observes only, Node's crash\n * behaviour is unchanged; the queue is flushed right away), `beforeExit` flushes. Returns the uninstall function.\n */\nexport const installNodeIssueCapture = (\n reporter: IssuesReporter,\n options: NodeIssueCaptureOptions = {},\n): (() => void) => {\n const nodeProcess = readNodeProcess();\n if (!nodeProcess?.on) return () => undefined;\n const uninstallSteps: (() => void)[] = [];\n const listen = (event: string, listener: (...args: unknown[]) => void) => {\n nodeProcess.on?.(event, listener);\n uninstallSteps.push(() => nodeProcess.off?.(event, listener));\n };\n\n listen('uncaughtExceptionMonitor', (error) => {\n reporter.captureError(error, 'error');\n void reporter.flush();\n });\n listen('beforeExit', () => void reporter.flush());\n if (options.unhandledRejections) {\n listen('unhandledRejection', (reason) => reporter.captureError(reason, 'unhandledrejection'));\n }\n\n return () => {\n for (const uninstallStep of uninstallSteps.splice(0).reverse()) uninstallStep();\n };\n};\n"],"mappings":";;;;;;;;;;AAuBA,IAAM,kBAAkB,MACpB,WAA6C,WAA2C;AA4BrF,IAAM,2BAA2B,CAAC,YAAuD;AAC9F,QAAM,EAAE,YAAY,YAAY,SAAS,WAAW,kBAAkB,GAAG,gBAAgB,IAAI;AAC7F,QAAM,kBAAkB,MAAqB;AA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C,UAAU;AAC5C,aAAS,aAAa,OAAO,OAAO;AACpC,SAAK,SAAS,MAAM;AAAA,EACtB,CAAC;AACD,SAAO,cAAc,MAAM,KAAK,SAAS,MAAM,CAAC;AAChD,MAAI,QAAQ,qBAAqB;AAC/B,WAAO,sBAAsB,CAAC,WAAW,SAAS,aAAa,QAAQ,oBAAoB,CAAC;AAAA,EAC9F;AAEA,SAAO,MAAM;AACX,eAAW,iBAAiB,eAAe,OAAO,CAAC,EAAE,QAAQ,EAAG,eAAc;AAAA,EAChF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/issues/node/index.ts"],"sourcesContent":["/**\n * `@mgamadeus/ddd-web/issues/node` — the server adapter of the issues reporter, for a client app's own Node server\n * (an SSR server, a BFF): windowed caps and backoff, the shared server token (the backend files the reports as\n * WEB_SERVER), a request-error handler in the shape of a framework's `onRequestError` hook, and opt-in process hooks.\n * Uses the global `fetch` (Node 18+) and reads `process` only when called — no `node:` import.\n */\nimport {\n createFetchIssuesTransport,\n createIssuesReporter,\n redactUrl,\n type IssuesReporter,\n type IssuesReporterOptions,\n type IssuesTransport,\n} from '../index';\nimport type { DddClientIssueEvent, DddClientIssuesReportRequestBody } from '../wire';\nimport { DDD_ISSUES_REPORT_PATH } from '../wire';\n\ninterface NodeProcessLike {\n version?: string;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n off?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n}\n\nconst readNodeProcess = (): NodeProcessLike | null =>\n ((globalThis as { process?: NodeProcessLike }).process as NodeProcessLike | undefined) ?? null;\n\ntype NodeReporterBaseOptions<TWireEvent, TRequestBody> = Omit<\n IssuesReporterOptions<TWireEvent, TRequestBody>,\n 'runtime' | 'endpoint' | 'transport' | 'context'\n>;\n\n/**\n * Generic over the wire types like {@link IssuesReporterOptions}: the defaults are the DDD contract; a `wire` built\n * from your generated models types the event and the body with them.\n */\nexport interface NodeIssuesReporterOptions<\n TWireEvent = DddClientIssueEvent,\n TRequestBody = DddClientIssuesReportRequestBody,\n> extends NodeReporterBaseOptions<TWireEvent, TRequestBody> {\n /**\n * The full URL of the ingest endpoint (`https://api.example.com/api/public/common/issues/report`), or a function\n * returning it, read at send time. Wins over `apiBaseUrl` when both are set; a function returning null / empty sends\n * nothing. Unset (or null / empty) = `apiBaseUrl` decides.\n */\n endpoint?: string | null | (() => string | null | undefined);\n /**\n * The API origin (`https://api.example.com`, a cluster-internal URL): the report goes to `<apiBaseUrl><reportPath>`.\n * Kept for compatibility: as a FUNCTION it returns the full endpoint URL, not a base URL — use `endpoint` for that.\n * Ignored when `endpoint` is set. Null / empty = nothing is sent.\n */\n apiBaseUrl?: string | null | (() => string | null | undefined);\n /** Appended to a string `apiBaseUrl`. Default {@link DDD_ISSUES_REPORT_PATH} */\n reportPath?: string;\n /** The release the backend files the error under (and looks the server's source maps up by). */\n release?: () => string | null | undefined;\n /** Default `fetch` with a 10 s timeout. */\n transport?: IssuesTransport;\n /** Default 10 000 */\n requestTimeoutMs?: number;\n}\n\n/**\n * A reporter for a Node server: runtime `node`, windowed caps, no breadcrumbs, user agent `Node.js <version>`, in-app\n * files = everything outside `node_modules` and `node:` built-ins. Without `serverToken` the backend files the reports\n * as a browser's (WEB) — or drops them, when the application requires the token for server reports.\n */\nexport const createNodeIssuesReporter = <\n TWireEvent = DddClientIssueEvent,\n TRequestBody = DddClientIssuesReportRequestBody,\n>(\n options: NodeIssuesReporterOptions<TWireEvent, TRequestBody>,\n): IssuesReporter => {\n const { endpoint, apiBaseUrl, reportPath, release, transport, requestTimeoutMs, ...reporterOptions } = options;\n const resolveEndpoint = (): string | null => {\n if (endpoint !== undefined && endpoint !== null && endpoint !== '') {\n return (typeof endpoint === 'function' ? endpoint() : endpoint) || null;\n }\n if (typeof apiBaseUrl === 'function') return apiBaseUrl() || null;\n if (!apiBaseUrl) return null;\n return `${apiBaseUrl.replace(/\\/+$/, '')}${reportPath ?? DDD_ISSUES_REPORT_PATH}`;\n };\n return createIssuesReporter<TWireEvent, TRequestBody>({\n isInAppFile: (file) => !file.includes('/node_modules/'),\n ...reporterOptions,\n runtime: 'node',\n endpoint: resolveEndpoint,\n context: () => {\n const nodeVersion = readNodeProcess()?.version;\n return { release: release?.() ?? null, userAgent: nodeVersion ? `Node.js ${nodeVersion}` : null };\n },\n transport: transport ?? createFetchIssuesTransport({ timeoutMs: requestTimeoutMs ?? 10_000 }),\n });\n};\n\n/** The request of a server-side error, as frameworks hand it to their request-error hook. */\nexport interface ServerIssueRequest {\n path: string;\n method: string;\n}\n\n/** Where in the server the error happened (fields of a framework's request-error context; all optional). */\nexport interface ServerIssueRequestContext {\n /** The route PATTERN (`/books/[bookId]`), never the URL */\n routePath?: string | null;\n routerKind?: string;\n routeType?: string;\n renderSource?: string;\n}\n\n/**\n * A request-error handler `(error, request, context) => void`, structurally compatible with a framework's\n * `onRequestError` hook (Next.js `instrumentation.ts`). Reports kind `server-request` with the route pattern, the\n * redacted path and the method; the error's `digest` goes in as a tag (an error boundary in the browser sees the same\n * digest and does not report it again). `getReporter` may return null (not configured).\n */\nexport const createServerRequestErrorHandler =\n (getReporter: () => IssuesReporter | null | undefined) =>\n (error: unknown, request: ServerIssueRequest, context: ServerIssueRequestContext = {}): void => {\n try {\n getReporter()?.captureError(error, 'server-request', {\n routePattern: context.routePath || null,\n url: redactUrl(request.path),\n requestMethod: request.method,\n tags: {\n digest: (error as { digest?: string } | null)?.digest,\n routerKind: context.routerKind,\n routeType: context.routeType,\n renderSource: context.renderSource,\n },\n });\n } catch {\n // Never into the framework.\n }\n };\n\nexport interface NodeIssueCaptureOptions {\n /**\n * Also report unhandled promise rejections. Off by default: a listener for `unhandledRejection` changes Node's\n * default behaviour (the process no longer exits on one). Turn it on only where that is wanted.\n */\n unhandledRejections?: boolean;\n}\n\n/**\n * Process hooks: uncaught exceptions are reported through `uncaughtExceptionMonitor` (observes only, Node's crash\n * behaviour is unchanged; the queue is flushed right away), `beforeExit` flushes. Returns the uninstall function.\n */\nexport const installNodeIssueCapture = (\n reporter: IssuesReporter,\n options: NodeIssueCaptureOptions = {},\n): (() => void) => {\n const nodeProcess = readNodeProcess();\n if (!nodeProcess?.on) return () => undefined;\n const uninstallSteps: (() => void)[] = [];\n const listen = (event: string, listener: (...args: unknown[]) => void) => {\n nodeProcess.on?.(event, listener);\n uninstallSteps.push(() => nodeProcess.off?.(event, listener));\n };\n\n listen('uncaughtExceptionMonitor', (error) => {\n reporter.captureError(error, 'error');\n void reporter.flush();\n });\n listen('beforeExit', () => void reporter.flush());\n if (options.unhandledRejections) {\n listen('unhandledRejection', (reason) => reporter.captureError(reason, 'unhandledrejection'));\n }\n\n return () => {\n for (const uninstallStep of uninstallSteps.splice(0).reverse()) uninstallStep();\n };\n};\n"],"mappings":";;;;;;;;;;AAuBA,IAAM,kBAAkB,MACpB,WAA6C,WAA2C;AA0CrF,IAAM,2BAA2B,CAItC,YACmB;AACnB,QAAM,EAAE,UAAU,YAAY,YAAY,SAAS,WAAW,kBAAkB,GAAG,gBAAgB,IAAI;AACvG,QAAM,kBAAkB,MAAqB;AAC3C,QAAI,aAAa,UAAa,aAAa,QAAQ,aAAa,IAAI;AAClE,cAAQ,OAAO,aAAa,aAAa,SAAS,IAAI,aAAa;AAAA,IACrE;AACA,QAAI,OAAO,eAAe,WAAY,QAAO,WAAW,KAAK;AAC7D,QAAI,CAAC,WAAY,QAAO;AACxB,WAAO,GAAG,WAAW,QAAQ,QAAQ,EAAE,CAAC,GAAG,cAAc,sBAAsB;AAAA,EACjF;AACA,SAAO,qBAA+C;AAAA,IACpD,aAAa,CAAC,SAAS,CAAC,KAAK,SAAS,gBAAgB;AAAA,IACtD,GAAG;AAAA,IACH,SAAS;AAAA,IACT,UAAU;AAAA,IACV,SAAS,MAAM;AACb,YAAM,cAAc,gBAAgB,GAAG;AACvC,aAAO,EAAE,SAAS,UAAU,KAAK,MAAM,WAAW,cAAc,WAAW,WAAW,KAAK,KAAK;AAAA,IAClG;AAAA,IACA,WAAW,aAAa,2BAA2B,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client for backends built with mgamadeus/ddd, the DDD entity framework for Symfony and Doctrine (Composer/Packagist). Generates a typed RTK Query SDK from the backend's OpenAPI document, builds DDD QueryOptions (filters, orderBy, expand, select, paging) and handles JWT auth with token refresh.",
5
5
  "keywords": [
6
6
  "ddd",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/issues/limits.ts","../src/issues/normalize.ts","../src/issues/redact.ts","../src/issues/breadcrumbs.ts","../src/issues/filters.ts","../src/issues/fingerprint.ts","../src/issues/reporter.ts","../src/issues/route-pattern.ts","../src/issues/transport.ts"],"sourcesContent":["/**\n * Every limit of the issues reporter in one place. The backend enforces its own caps again (mgamadeus/ddd\n * `ClientIssueReportNormalizer`); these keep a broken page from flooding the endpoint and keep requests small. The field\n * caps equal the backend's.\n */\n\n/** Caps of a reporter that lives for one page session: per session, a hard stop after repeated failed sends. */\nexport interface IssuesSessionLimits {\n sendsPerFingerprint: number;\n eventsPerSession: number;\n failedSendsBeforeStop: number;\n}\n\n/** Caps of a long-lived reporter (a server, a mobile app): windows and an exponential backoff instead of a stop. */\nexport interface IssuesWindowedLimits {\n sendsPerFingerprintPerWindow: number;\n fingerprintWindowMs: number;\n eventsPerMinute: number;\n backoffStartMs: number;\n backoffMaxMs: number;\n}\n\nexport interface IssuesLimits {\n /** Field caps per event (characters) */\n nameLength: number;\n messageLength: number;\n framesPerEvent: number;\n fileLength: number;\n functionLength: number;\n rawStackLength: number;\n urlLength: number;\n routePatternLength: number;\n breadcrumbsPerEvent: number;\n breadcrumbMessageLength: number;\n breadcrumbUrlLength: number;\n tagsPerEvent: number;\n tagLength: number;\n requestMethodLength: number;\n clientFingerprintLength: number;\n /** Batching */\n flushDelayMs: number;\n flushAtEvents: number;\n /** The backend drops every event beyond 10 per request (`too-many-events`). */\n eventsPerRequest: number;\n /** Serialized UTF-8 per request; under the browser's 64 KiB keepalive budget */\n requestBytes: number;\n /** Serialized UTF-8 per event, before it is queued (the backend's file sink takes 16 KB per client event) */\n eventBytes: number;\n /** One retry on a network error or a 5xx, never on a 4xx */\n retryDelayMs: number;\n /** Events waiting to be sent; the oldest go first beyond it (a backend that is down for long) */\n queuedEvents: number;\n session: IssuesSessionLimits;\n windowed: IssuesWindowedLimits;\n}\n\nexport type IssuesLimitsOverrides = Partial<Omit<IssuesLimits, 'session' | 'windowed'>> & {\n session?: Partial<IssuesSessionLimits>;\n windowed?: Partial<IssuesWindowedLimits>;\n};\n\nexport const ISSUES_LIMITS: Readonly<IssuesLimits> = Object.freeze({\n nameLength: 128,\n messageLength: 1024,\n framesPerEvent: 30,\n fileLength: 512,\n functionLength: 128,\n rawStackLength: 4096,\n urlLength: 1024,\n routePatternLength: 256,\n breadcrumbsPerEvent: 20,\n breadcrumbMessageLength: 256,\n breadcrumbUrlLength: 1024,\n tagsPerEvent: 10,\n tagLength: 64,\n requestMethodLength: 16,\n clientFingerprintLength: 128,\n\n flushDelayMs: 2_000,\n flushAtEvents: 5,\n eventsPerRequest: 10,\n requestBytes: 48 * 1024,\n eventBytes: 16 * 1024,\n retryDelayMs: 10_000,\n queuedEvents: 50,\n\n session: Object.freeze({\n sendsPerFingerprint: 3,\n eventsPerSession: 25,\n failedSendsBeforeStop: 3,\n }),\n\n windowed: Object.freeze({\n sendsPerFingerprintPerWindow: 3,\n fingerprintWindowMs: 5 * 60_000,\n eventsPerMinute: 60,\n backoffStartMs: 10_000,\n backoffMaxMs: 5 * 60_000,\n }),\n});\n\n/** The default limits with the given ones on top (the nested `session` / `windowed` caps merged field by field). */\nexport const mergeIssuesLimits = (overrides: IssuesLimitsOverrides = {}): IssuesLimits => ({\n ...ISSUES_LIMITS,\n ...overrides,\n session: { ...ISSUES_LIMITS.session, ...overrides.session },\n windowed: { ...ISSUES_LIMITS.windowed, ...overrides.windowed },\n});\n","import { ISSUES_LIMITS } from './limits';\nimport type { CapturedFrame } from './types';\n\n/** The error-like value a reporter received, reduced to what a report carries. */\nexport interface NormalizedError {\n name: string;\n message: string;\n /** Innermost first */\n frames: CapturedFrame[];\n /** Only when the stack had lines but none could be parsed */\n rawStack: string | null;\n}\n\n/** Decides whether a frame's file is the application's own code. */\nexport type InAppFileTest = (file: string) => boolean;\n\nexport const truncate = (value: string, maxLength: number): string =>\n value.length > maxLength ? value.slice(0, maxLength) : value;\n\n/** Files that are never the app's: extensions, the runtime, libraries. */\nconst FOREIGN_FILE =\n /^(chrome-extension|moz-extension|safari-extension|safari-web-extension):|^node:|node_modules|^<anonymous>$|^native$|^\\[native code\\]$/;\n\nexport const isForeignFile = (file: string): boolean => FOREIGN_FILE.test(file);\n\n/** V8 (Chrome, Edge, Node, Hermes): ` at fn (file:1:2)`, ` at file:1:2`, ` at async fn (file:1:2)` */\nconst V8_FRAME = /^\\s*at (?:(.+?) \\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/;\n/** V8 frame without a position: ` at fn (native)`, ` at fn (<anonymous>)` */\nconst V8_FRAME_WITHOUT_POSITION = /^\\s*at (?:(.+?) \\()?([^():]+)\\)?\\s*$/;\n/** SpiderMonkey / JavaScriptCore (Firefox, Safari): `fn@file:1:2`, `@file:1:2` */\nconst GECKO_FRAME = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/;\n\nconst toFrame = (\n functionName: string | undefined,\n file: string,\n line: string | undefined,\n column: string | undefined,\n isInAppFile: InAppFileTest,\n): CapturedFrame => {\n const cleanFunction = (functionName ?? '').replace(/^async /, '').replace(/^new /, '').trim();\n return {\n file: truncate(file, ISSUES_LIMITS.fileLength),\n line: line ? Number(line) : null,\n column: column ? Number(column) : null,\n function: cleanFunction ? truncate(cleanFunction, ISSUES_LIMITS.functionLength) : null,\n inApp: !isForeignFile(file) && isInAppFile(file),\n };\n};\n\n/** Parses a stack string into frames, innermost first. Lines that are not frames (the message) are skipped. */\nexport const parseStack = (\n stack: string,\n isInAppFile: InAppFileTest = () => true,\n maxFrames: number = ISSUES_LIMITS.framesPerEvent,\n): CapturedFrame[] => {\n const frames: CapturedFrame[] = [];\n for (const line of stack.split('\\n')) {\n if (frames.length >= maxFrames) break;\n const v8Match = V8_FRAME.exec(line);\n if (v8Match) {\n frames.push(toFrame(v8Match[1], v8Match[2] ?? '', v8Match[3], v8Match[4], isInAppFile));\n continue;\n }\n const v8MatchWithoutPosition = V8_FRAME_WITHOUT_POSITION.exec(line);\n if (v8MatchWithoutPosition) {\n frames.push(toFrame(v8MatchWithoutPosition[1], v8MatchWithoutPosition[2] ?? '', undefined, undefined, isInAppFile));\n continue;\n }\n const geckoMatch = GECKO_FRAME.exec(line);\n if (geckoMatch) {\n frames.push(toFrame(geckoMatch[1], geckoMatch[2] ?? '', geckoMatch[3], geckoMatch[4], isInAppFile));\n }\n }\n return frames;\n};\n\n/** `Minified React error #418; visit https://react.dev/errors/418…` → the code, so it survives grouping as a name. */\nconst MINIFIED_REACT_ERROR = /Minified React error #(\\d+)/;\n\nconst describeNonError = (value: unknown): string => {\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\ninterface ErrorLike {\n name?: unknown;\n message?: unknown;\n stack?: unknown;\n}\n\nconst isErrorLike = (value: unknown): value is ErrorLike =>\n typeof value === 'object' && value !== null && typeof (value as ErrorLike).message === 'string';\n\n/** Any thrown value (an Error, a string, a rejected object) → name, message, frames. */\nexport const normalizeError = (value: unknown, isInAppFile: InAppFileTest = () => true): NormalizedError => {\n if (!isErrorLike(value)) {\n const message = typeof value === 'string' ? value : describeNonError(value);\n return {\n name: typeof value === 'string' ? 'Error' : 'NonError',\n message: truncate(message, ISSUES_LIMITS.messageLength),\n frames: [],\n rawStack: null,\n };\n }\n\n const message = String(value.message);\n const reactErrorCode = MINIFIED_REACT_ERROR.exec(message)?.[1];\n const declaredName = typeof value.name === 'string' && value.name ? value.name : 'Error';\n const name = reactErrorCode ? `ReactError#${reactErrorCode}` : declaredName;\n const stack = typeof value.stack === 'string' ? value.stack : '';\n const frames = stack ? parseStack(stack, isInAppFile) : [];\n const hasStackLines = stack.split('\\n').length > 1;\n\n return {\n name: truncate(name, ISSUES_LIMITS.nameLength),\n message: truncate(message, ISSUES_LIMITS.messageLength),\n frames,\n rawStack: frames.length === 0 && hasStackLines ? truncate(stack, ISSUES_LIMITS.rawStackLength) : null,\n };\n};\n","/**\n * Client-side redaction of everything a report carries as free text: the page URL, breadcrumb URLs and messages, the\n * error message, the raw stack and tag values. The backend redacts again (mgamadeus/ddd `IssuesLogRedactor` and the\n * client rules of `logClientIssue`); this pass keeps credentials from leaving the device at all.\n */\n\n/** One rule by value, applied to text and URLs alike. */\nexport interface IssuesRedactionRule {\n pattern: RegExp;\n replacement: string;\n}\n\nexport interface IssuesRedactor {\n /** For a URL (page, request, navigation from / to). */\n redactUrl: (url: string) => string;\n /** For free text (error message, breadcrumb message); URLs inside it get the token rules too. */\n redactText: (text: string) => string;\n}\n\nexport interface IssuesRedactorOptions {\n /**\n * Path segments whose NEXT segment is the credential (an invitation, a password reset):\n * `/invitations/abc` → `/invitations/[redacted]`. A segment may contain `/` (`r/confirm`). Default\n * {@link DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS}, the backend's default `redactPathSegments`.\n */\n tokenPathSegments?: readonly string[];\n /** Applied after the built-in rules, e.g. a national phone-number format. */\n additionalRules?: readonly IssuesRedactionRule[];\n}\n\n/** The backend's default `redactPathSegments` (`Common.Issues`). */\nexport const DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS: readonly string[] = Object.freeze([\n 'invitations',\n 'claim-account',\n 'verify-email',\n 'reset-password',\n]);\n\n/** Any query parameter whose name contains `token`. */\nconst TOKEN_QUERY_PARAMETER = /([?&][^=&#]*token[^=&#]*)=[^&#]*/gi;\n\n/** Rules by value. Order matters: a bearer and a JWT go before the generic rules. */\nexport const ISSUES_REDACTION_RULES: readonly IssuesRedactionRule[] = Object.freeze([\n // An Authorization header value copied into a message.\n { pattern: /\\bBearer\\s+[A-Za-z0-9\\-._~+/]+=*/gi, replacement: 'Bearer [redacted]' },\n // A JWT anywhere (access tokens, custom tokens of an identity provider).\n { pattern: /\\beyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]+/g, replacement: '[jwt]' },\n // E-mail addresses.\n { pattern: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi, replacement: '[email]' },\n // UUIDs: a public link's id is often its credential (`/api/public/bookings/<uuid>/cancel`).\n { pattern: /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, replacement: '[uuid]' },\n // International phone numbers (+44 20 7946 0958).\n { pattern: /\\+\\d[\\d\\s().-]{6,}\\d/g, replacement: '[phone]' },\n]);\n\n/** Path segments that are long hex ids (signed links, opaque tokens); ids of 15 hex digits or fewer stay. */\nconst LONG_HEX_PATH_SEGMENT = /\\/[0-9a-f]{16,}(?=[/?#]|$)/gi;\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const createIssuesRedactor = (options: IssuesRedactorOptions = {}): IssuesRedactor => {\n const tokenPathSegments = (options.tokenPathSegments ?? DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS)\n .map((segment) => segment.replace(/^\\/+|\\/+$/g, ''))\n .filter((segment) => segment !== '');\n const tokenRouteSegment =\n tokenPathSegments.length > 0\n ? new RegExp(`/(${tokenPathSegments.map(escapeRegExp).join('|')})/[^/?#]+`, 'g')\n : null;\n const valueRules = [...ISSUES_REDACTION_RULES, ...(options.additionalRules ?? [])];\n\n const redactTokens = (value: string): string => {\n const withoutTokenSegments = tokenRouteSegment ? value.replace(tokenRouteSegment, '/$1/[redacted]') : value;\n return withoutTokenSegments.replace(TOKEN_QUERY_PARAMETER, '$1=[redacted]');\n };\n const applyValueRules = (value: string): string =>\n valueRules.reduce((redacted, rule) => redacted.replace(rule.pattern, rule.replacement), value);\n\n return {\n redactUrl: (url) => applyValueRules(redactTokens(url)).replace(LONG_HEX_PATH_SEGMENT, '/[id]'),\n redactText: (text) => applyValueRules(redactTokens(text)),\n };\n};\n\nconst defaultIssuesRedactor = createIssuesRedactor();\n\n/** {@link IssuesRedactor.redactUrl} with the default rules. */\nexport const redactUrl = (url: string): string => defaultIssuesRedactor.redactUrl(url);\n\n/** {@link IssuesRedactor.redactText} with the default rules. */\nexport const redactText = (text: string): string => defaultIssuesRedactor.redactText(text);\n","import { ISSUES_LIMITS } from './limits';\nimport { truncate } from './normalize';\nimport { type IssuesRedactor, redactText, redactUrl } from './redact';\nimport type { BreadcrumbCategory, CapturedBreadcrumb } from './types';\n\n/**\n * What happened before an error, newest last. Builders only: every string is capped and redacted here, so a caller\n * cannot add an unredacted URL (the reporter applies its own redactor again on add). Never bodies, never input values,\n * never the visible text of a clicked element.\n */\n\nexport interface BreadcrumbTrail {\n add: (breadcrumb: CapturedBreadcrumb) => void;\n /** A copy, oldest first */\n snapshot: () => CapturedBreadcrumb[];\n}\n\n/** Keeps the newest `limit` breadcrumbs. */\nexport const createBreadcrumbTrail = (limit: number = ISSUES_LIMITS.breadcrumbsPerEvent): BreadcrumbTrail => {\n const breadcrumbs: CapturedBreadcrumb[] = [];\n return {\n add: (breadcrumb) => {\n breadcrumbs.push(breadcrumb);\n while (breadcrumbs.length > limit) breadcrumbs.shift();\n },\n snapshot: () => breadcrumbs.slice(),\n };\n};\n\nconst DEFAULT_BREADCRUMB_REDACTOR: IssuesRedactor = { redactUrl, redactText };\n\n/** Caps and redacts every string of a breadcrumb. */\nexport const sanitizeBreadcrumb = (\n breadcrumb: CapturedBreadcrumb,\n redactor: IssuesRedactor = DEFAULT_BREADCRUMB_REDACTOR,\n): CapturedBreadcrumb => {\n const sanitizeUrl = (url: string | null | undefined): string | null =>\n url ? truncate(redactor.redactUrl(url), ISSUES_LIMITS.breadcrumbUrlLength) : null;\n return {\n at: breadcrumb.at,\n category: breadcrumb.category,\n message: truncate(redactor.redactText(breadcrumb.message), ISSUES_LIMITS.breadcrumbMessageLength),\n url: sanitizeUrl(breadcrumb.url),\n from: sanitizeUrl(breadcrumb.from),\n to: sanitizeUrl(breadcrumb.to),\n status: typeof breadcrumb.status === 'number' ? breadcrumb.status : null,\n };\n};\n\ntype BreadcrumbFields = Partial<Pick<CapturedBreadcrumb, 'url' | 'from' | 'to' | 'status'>>;\n\nconst buildBreadcrumb = (\n at: string,\n category: BreadcrumbCategory,\n message: string,\n fields: BreadcrumbFields = {},\n): CapturedBreadcrumb =>\n sanitizeBreadcrumb({\n at,\n category,\n message,\n url: fields.url ?? null,\n from: fields.from ?? null,\n to: fields.to ?? null,\n status: fields.status ?? null,\n });\n\n/** A route change; `from` / `to` are route patterns or paths. */\nexport const navigationBreadcrumb = (at: string, from: string | null, to: string): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'navigation', `${from ?? '(start)'} → ${to}`, { from, to });\n\n/** A failed request: status ≥ 400, or `network-error` when it never got an answer. */\nexport const fetchBreadcrumb = (\n at: string,\n method: string,\n url: string,\n outcome: number | 'network-error',\n): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'fetch', `${method.toUpperCase()} ${outcome}`, {\n url,\n status: outcome === 'network-error' ? null : outcome,\n });\n\n/** `console.error`: its first argument only. */\nexport const consoleBreadcrumb = (at: string, message: string): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'console', message);\n\n/**\n * A click: the element's `data-issues-action` id, else its tag and role. Never its text or `aria-label`, which can\n * hold an e-mail or a name.\n */\nexport const uiBreadcrumb = (at: string, action: string): CapturedBreadcrumb => buildBreadcrumb(at, 'ui', action);\n\n/** Anything else the app wants on the trail. */\nexport const customBreadcrumb = (at: string, message: string, fields: BreadcrumbFields = {}): CapturedBreadcrumb =>\n buildBreadcrumb(at, 'custom', message, fields);\n","import type { CapturedFrame } from './types';\n\n/**\n * What the client never reports: noise that is not a failure of the app, or not actionable per event. The backend\n * drops the chunk-load, `Script error.` and `ResizeObserver loop` patterns again (`clientIgnorePatterns`); dropping\n * here saves the request.\n */\n\nexport interface IssueDropCandidate {\n name: string;\n message: string;\n frames: readonly CapturedFrame[];\n /** The page runs under automation (Playwright / WebDriver: `navigator.webdriver`) */\n automated: boolean;\n}\n\nexport interface IssueDropRule {\n id: string;\n matches: (candidate: IssueDropCandidate) => boolean;\n}\n\nconst messageMatches =\n (pattern: RegExp) =>\n (candidate: IssueDropCandidate): boolean =>\n pattern.test(candidate.message) || pattern.test(candidate.name);\n\nexport const ISSUE_DROP_RULES: readonly IssueDropRule[] = Object.freeze([\n // A tab opened before a deploy asks for chunks the new deploy no longer has.\n { id: 'chunk-load', matches: (candidate: IssueDropCandidate) => candidate.name === 'ChunkLoadError' },\n { id: 'chunk-load', matches: messageMatches(/Loading (CSS )?chunk [\\w-]+ failed/) },\n { id: 'chunk-load', matches: messageMatches(/Failed to fetch dynamically imported module/) },\n { id: 'chunk-load', matches: messageMatches(/Importing a module script failed/) },\n // Browser noise: the observer could not deliver every notification in one frame.\n { id: 'resize-observer', matches: messageMatches(/ResizeObserver loop/) },\n // An error in a cross-origin script: the browser hides everything, nothing to act on.\n { id: 'opaque-script-error', matches: (candidate: IssueDropCandidate) => /^Script error\\.?$/.test(candidate.message.trim()) },\n // Thrown by a browser extension injected into the page.\n {\n id: 'extension',\n matches: (candidate: IssueDropCandidate) =>\n /^(chrome-extension|moz-extension|safari-(web-)?extension):/.test(candidate.frames[0]?.file ?? ''),\n },\n // Wallet extensions and in-app wallet browsers touch `window.ethereum` on every page.\n { id: 'wallet-extension', matches: messageMatches(/\\bwindow\\.ethereum\\b/) },\n // A request the app cancelled itself (navigation, unmount, an aborted query).\n { id: 'aborted', matches: (candidate: IssueDropCandidate) => candidate.name === 'AbortError' },\n // End-to-end runs under automation stay silent.\n { id: 'automated-browser', matches: (candidate: IssueDropCandidate) => candidate.automated },\n]);\n\n/** The id of the first rule that drops the candidate, or null when it is reported. */\nexport const findIssueDropRule = (\n candidate: IssueDropCandidate,\n rules: readonly IssueDropRule[] = ISSUE_DROP_RULES,\n): string | null => rules.find((rule) => rule.matches(candidate))?.id ?? null;\n","import type { CapturedFrame } from './types';\n\n/**\n * The CLIENT's de-duplication key: `name | normalised message | top frame file:function`. Only for folding repeats on\n * one device (sent as `clientFingerprint`, informational); the backend builds the group and issue hashes itself\n * (mgamadeus/ddd `ClientIssuesFingerprintBuilder`) and never trusts this one.\n */\n\n/** URLs, UUIDs, hex ids and numbers become placeholders, so `order 41 failed` and `order 42 failed` are one key. */\nexport const normaliseIssueMessage = (message: string): string =>\n message\n .replace(/https?:\\/\\/\\S+/g, '{url}')\n .replace(/\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, '{uuid}')\n .replace(/\\b[0-9a-f]{8,}\\b/gi, '{hex}')\n .replace(/\\d+/g, '{n}');\n\n/** The top frame is the innermost in-app frame, else the innermost frame. */\nexport const buildClientFingerprint = (name: string, message: string, frames: readonly CapturedFrame[]): string => {\n const topFrame = frames.find((frame) => frame.inApp) ?? frames[0];\n const callSite = topFrame ? `${topFrame.file}:${topFrame.function ?? ''}` : '';\n return `${name}|${normaliseIssueMessage(message)}|${callSite}`;\n};\n","import { createBreadcrumbTrail, sanitizeBreadcrumb } from './breadcrumbs';\nimport { findIssueDropRule, ISSUE_DROP_RULES, type IssueDropRule } from './filters';\nimport { buildClientFingerprint } from './fingerprint';\nimport { type IssuesLimitsOverrides, mergeIssuesLimits } from './limits';\nimport { type InAppFileTest, normalizeError, truncate } from './normalize';\nimport { createIssuesRedactor, type IssuesRedactor } from './redact';\nimport type {\n CaptureExtra,\n CapturedBreadcrumb,\n CapturedIssueContext,\n CapturedIssueEvent,\n CapturedTag,\n IssueKind,\n IssuesRuntime,\n IssuesTransport,\n IssuesWireAdapter,\n} from './types';\nimport {\n type DddClientIssueEvent,\n type DddClientIssuesReportRequestBody,\n dddIssuesWireAdapter,\n} from './wire';\n\n/**\n * The issues reporter: collect → redact → de-duplicate → cap → batch → send. Platform-free: the caller supplies the\n * transport, the context and optionally the wire adapter. It never throws into its caller and never reports its own\n * failures.\n */\n\n/**\n * Header a client app's own server sends its shared secret in; the application's controller files such reports\n * under the section WEB_SERVER. The header name is the application's choice — `serverTokenHeader` overrides it.\n */\nexport const DDD_ISSUES_SERVER_TOKEN_HEADER = 'X-Issues-Server-Token';\n\n/** How the reporter caps what it sends. */\nexport type IssuesRateLimitMode =\n /** One page session: per-fingerprint and per-session caps, a hard stop after repeated failed sends. */\n | 'session'\n /** A long-lived process or app: windowed caps and an exponential backoff. */\n | 'windowed';\n\nexport interface IssuesClock {\n now: () => number;\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (handle: unknown) => void;\n}\n\ninterface TimerGlobals {\n setTimeout: (callback: () => void, delayMs: number) => { unref?: () => void } | number;\n clearTimeout: (handle: unknown) => void;\n}\n\n/** The running platform's timers, read when the reporter is created. On Node they are unref'd. */\nexport const createPlatformIssuesClock = (): IssuesClock => {\n const timers = globalThis as unknown as TimerGlobals;\n return {\n now: () => Date.now(),\n setTimeout: (callback, delayMs) => {\n const handle = timers.setTimeout(callback, delayMs);\n if (typeof handle === 'object' && handle !== null) handle.unref?.();\n return handle;\n },\n clearTimeout: (handle) => timers.clearTimeout(handle),\n };\n};\n\nexport type IssuesContextValues = Partial<Omit<CapturedIssueContext, 'runtime' | 'app'>>;\n\nexport interface IssuesReporterOptions<TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody> {\n runtime: IssuesRuntime;\n /** The client app, e.g. `web`, `admin`, `mobile` */\n app: string;\n /** Full URL of the ingest endpoint, read at send time; null = not configured, nothing is sent. */\n endpoint: () => string | null;\n transport: IssuesTransport;\n /** Read at send time (the release may only be known after the first render). Missing fields are null. */\n context?: () => IssuesContextValues;\n /** Read at capture time: tags every event carries (e.g. the deployed commit); a capture's own tags win on a clash. */\n commonTags?: () => CaptureExtra['tags'];\n /** Default: the DDD contract (`@mgamadeus/ddd-web/issues/wire`). Pass your own to type the body with your models. */\n wire?: IssuesWireAdapter<TWireEvent, TRequestBody>;\n /** A signed-in session's access token, so the backend attributes the error to the account. */\n getAuthorization?: () => string | null | undefined;\n /** The client app's own server only: the shared secret that makes the backend file reports as WEB_SERVER. */\n serverToken?: string;\n /** Default {@link DDD_ISSUES_SERVER_TOKEN_HEADER} */\n serverTokenHeader?: string;\n isInAppFile?: InAppFileTest;\n /** True under automation (`navigator.webdriver`): nothing is reported. */\n isAutomated?: () => boolean;\n /** Default: `session` for `browser`, `windowed` for `node` and `react-native`. */\n rateLimitMode?: IssuesRateLimitMode;\n /** Attach the breadcrumb trail to events. Default: every runtime but `node` (a server's trail mixes requests). */\n attachBreadcrumbs?: boolean;\n /** Default {@link ISSUE_DROP_RULES}; spread them to add your own. */\n dropRules?: readonly IssueDropRule[];\n /** Default {@link createIssuesRedactor}() */\n redactor?: IssuesRedactor;\n limits?: IssuesLimitsOverrides;\n clock?: IssuesClock;\n}\n\nexport interface IssuesReporter {\n /** Reports anything thrown. `kind` says how it was caught; `manual` (default) is the one the backend counts as handled. */\n captureError: (error: unknown, kind?: IssueKind, extra?: CaptureExtra) => void;\n addBreadcrumb: (breadcrumb: CapturedBreadcrumb) => void;\n /** The current route pattern (`/books/[bookId]`) and URL; both name every event captured after it. */\n setRoute: (routePattern: string | null, url: string | null) => void;\n /** Replaces `getAuthorization`, e.g. once the session store exists. */\n setAuthorizationReader: (reader: (() => string | null | undefined) | null) => void;\n /** Sends what is queued. `unloading`: the page is going away — keepalive, every batch at once, no awaiting. */\n flush: (options?: { unloading?: boolean }) => Promise<void>;\n /** Events waiting to be sent. */\n getQueuedEventCount: () => number;\n}\n\ninterface QueuedEvent {\n event: CapturedIssueEvent;\n attempts: number;\n}\n\n/** UTF-8 length of a string, without TextEncoder (not in every runtime this targets). */\nexport const utf8ByteLength = (value: string): number => {\n let bytes = 0;\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff) {\n bytes += 4;\n index++;\n } else bytes += 3;\n }\n return bytes;\n};\n\n/** Room left in a request for the context and the JSON around the events. */\nconst REQUEST_OVERHEAD_BYTES = 2048;\n/** Frames kept when an event is too large (the backend keeps the same number). */\nconst FRAMES_KEPT_WHEN_SHRINKING = 10;\n/** Message length kept when an event is still too large. */\nconst MESSAGE_LENGTH_KEPT_WHEN_SHRINKING = 256;\n\nconst NO_CONTEXT: Omit<CapturedIssueContext, 'runtime' | 'app'> = {\n release: null,\n tabId: null,\n userAgent: null,\n viewportWidth: null,\n viewportHeight: null,\n locale: null,\n};\n\nexport const createIssuesReporter = <TWireEvent = DddClientIssueEvent, TRequestBody = DddClientIssuesReportRequestBody>(\n options: IssuesReporterOptions<TWireEvent, TRequestBody>,\n): IssuesReporter => {\n const limits = mergeIssuesLimits(options.limits);\n const clock = options.clock ?? createPlatformIssuesClock();\n const wire = options.wire ?? (dddIssuesWireAdapter as unknown as IssuesWireAdapter<TWireEvent, TRequestBody>);\n const redactor = options.redactor ?? createIssuesRedactor();\n const dropRules = options.dropRules ?? ISSUE_DROP_RULES;\n const isInAppFile = options.isInAppFile ?? (() => true);\n const rateLimitMode: IssuesRateLimitMode =\n options.rateLimitMode ?? (options.runtime === 'browser' ? 'session' : 'windowed');\n const attachBreadcrumbs = options.attachBreadcrumbs ?? options.runtime !== 'node';\n const isBrowser = options.runtime === 'browser';\n const trail = createBreadcrumbTrail(limits.breadcrumbsPerEvent);\n let readAuthorization = options.getAuthorization ?? null;\n\n let route: { routePattern: string | null; url: string | null } = { routePattern: null, url: null };\n let queue: QueuedEvent[] = [];\n let flushTimer: unknown = null;\n let isSending = false;\n let isKeepaliveInFlight = false;\n\n // Rate limit mode `session`\n const sendsByFingerprint = new Map<string, number>();\n let sessionEvents = 0;\n let failedSends = 0;\n let isStopped = false;\n\n // Rate limit mode `windowed`\n const sendTimesByFingerprint = new Map<string, number[]>();\n let sendTimesOfLastMinute: number[] = [];\n let backoffMs = 0;\n let backoffUntil = 0;\n\n const measureEvent = (event: CapturedIssueEvent): number => utf8ByteLength(JSON.stringify(wire.toWireEvent(event)));\n\n /** Breadcrumbs go first, then frames beyond 10, the raw stack, and the message beyond 256 characters. */\n const shrinkToFit = (event: CapturedIssueEvent): CapturedIssueEvent => {\n const steps: ((current: CapturedIssueEvent) => CapturedIssueEvent)[] = [\n (current) => ({ ...current, breadcrumbs: [] }),\n (current) => ({ ...current, frames: current.frames.slice(0, FRAMES_KEPT_WHEN_SHRINKING) }),\n (current) => ({ ...current, rawStack: null }),\n (current) => ({ ...current, message: truncate(current.message, MESSAGE_LENGTH_KEPT_WHEN_SHRINKING) }),\n ];\n let shrunk = event;\n for (const step of steps) {\n if (measureEvent(shrunk) <= limits.eventBytes) return shrunk;\n shrunk = step(shrunk);\n }\n return shrunk;\n };\n\n /** Whether the caps let one more event with this fingerprint through; records it when they do. */\n const admit = (fingerprint: string): boolean => {\n if (rateLimitMode === 'session') {\n if (isStopped) return false;\n const sends = sendsByFingerprint.get(fingerprint) ?? 0;\n if (sends >= limits.session.sendsPerFingerprint) return false;\n if (sessionEvents >= limits.session.eventsPerSession) return false;\n sendsByFingerprint.set(fingerprint, sends + 1);\n sessionEvents += 1;\n return true;\n }\n const now = clock.now();\n const windowStart = now - limits.windowed.fingerprintWindowMs;\n const fingerprintTimes = (sendTimesByFingerprint.get(fingerprint) ?? []).filter((time) => time > windowStart);\n sendTimesOfLastMinute = sendTimesOfLastMinute.filter((time) => time > now - 60_000);\n if (fingerprintTimes.length >= limits.windowed.sendsPerFingerprintPerWindow) return false;\n if (sendTimesOfLastMinute.length >= limits.windowed.eventsPerMinute) return false;\n fingerprintTimes.push(now);\n sendTimesByFingerprint.set(fingerprint, fingerprintTimes);\n sendTimesOfLastMinute.push(now);\n // A long-lived process sees many one-off fingerprints: forget the expired ones.\n if (sendTimesByFingerprint.size > 500) {\n for (const [key, times] of sendTimesByFingerprint) {\n if (times.every((time) => time <= windowStart)) sendTimesByFingerprint.delete(key);\n }\n }\n return true;\n };\n\n const scheduleFlush = (delayMs: number) => {\n if (flushTimer !== null) return;\n flushTimer = clock.setTimeout(() => {\n flushTimer = null;\n void flush();\n }, delayMs);\n };\n\n const recordFailure = () => {\n if (rateLimitMode === 'session') {\n failedSends += 1;\n if (failedSends >= limits.session.failedSendsBeforeStop) {\n isStopped = true;\n queue = [];\n }\n return;\n }\n backoffMs = backoffMs ? Math.min(backoffMs * 2, limits.windowed.backoffMaxMs) : limits.windowed.backoffStartMs;\n backoffUntil = clock.now() + backoffMs;\n };\n\n const recordSuccess = () => {\n backoffMs = 0;\n backoffUntil = 0;\n };\n\n /** Up to `eventsPerRequest` events and `requestBytes`, oldest first. */\n const takeBatch = (): QueuedEvent[] => {\n const batch: QueuedEvent[] = [];\n let bytes = REQUEST_OVERHEAD_BYTES;\n while (queue.length > 0 && batch.length < limits.eventsPerRequest) {\n const next = queue[0] as QueuedEvent;\n const eventBytes = measureEvent(next.event) + 1;\n if (batch.length > 0 && bytes + eventBytes > limits.requestBytes) break;\n bytes += eventBytes;\n batch.push(next);\n queue.shift();\n }\n return batch;\n };\n\n const buildHeaders = (): Record<string, string> => {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'application/json' };\n try {\n const accessToken = readAuthorization?.();\n if (accessToken) headers.Authorization = `Bearer ${accessToken}`;\n } catch {\n // No session to attribute: the report goes anonymous.\n }\n if (options.serverToken) headers[options.serverTokenHeader ?? DDD_ISSUES_SERVER_TOKEN_HEADER] = options.serverToken;\n return headers;\n };\n\n const buildContext = (): CapturedIssueContext => {\n let contextValues: IssuesContextValues = {};\n try {\n contextValues = options.context?.() ?? {};\n } catch {\n // A context that cannot be read leaves its fields null.\n }\n return { ...NO_CONTEXT, ...contextValues, runtime: options.runtime, app: options.app };\n };\n\n const sendBatch = async (batch: QueuedEvent[], unloading = false): Promise<void> => {\n if (batch.length === 0) return;\n let endpoint: string | null = null;\n try {\n endpoint = options.endpoint();\n } catch {\n endpoint = null;\n }\n if (!endpoint) return;\n const body = JSON.stringify(wire.toRequestBody(buildContext(), batch.map((queued) => wire.toWireEvent(queued.event))));\n const useKeepalive = isBrowser && !isKeepaliveInFlight;\n if (useKeepalive) isKeepaliveInFlight = true;\n\n let status: number | null = null;\n try {\n status = (await options.transport({ url: endpoint, headers: buildHeaders(), body, keepalive: useKeepalive, unloading })).status;\n } catch {\n status = null;\n } finally {\n if (useKeepalive) isKeepaliveInFlight = false;\n }\n\n if (status !== null && status < 400) {\n recordSuccess();\n return;\n }\n const isRetryable = status === null || status >= 500;\n const retryable = isRetryable ? batch.filter((queued) => queued.attempts === 0) : [];\n recordFailure();\n if (retryable.length > 0 && !isStopped) {\n queue = [...retryable.map((queued) => ({ ...queued, attempts: queued.attempts + 1 })), ...queue];\n scheduleFlush(Math.max(limits.retryDelayMs, backoffUntil - clock.now()));\n }\n };\n\n const flush = async (flushOptions?: { unloading?: boolean }): Promise<void> => {\n try {\n if (flushTimer !== null) {\n clock.clearTimeout(flushTimer);\n flushTimer = null;\n }\n if (queue.length === 0 || isStopped) return;\n if (rateLimitMode === 'windowed' && clock.now() < backoffUntil) {\n scheduleFlush(backoffUntil - clock.now());\n return;\n }\n if (flushOptions?.unloading) {\n // The page is going away: no awaiting, every batch now (only the first can ride keepalive).\n while (queue.length > 0) void sendBatch(takeBatch(), true);\n return;\n }\n if (isSending) return;\n isSending = true;\n try {\n await sendBatch(takeBatch());\n } finally {\n isSending = false;\n }\n if (queue.length > 0) scheduleFlush(limits.flushDelayMs);\n } catch {\n // Never into the caller.\n }\n };\n\n const toTags = (tags: CaptureExtra['tags']): CapturedTag[] =>\n Object.entries(tags ?? {})\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .slice(0, limits.tagsPerEvent)\n .map(([key, value]) => ({\n key: truncate(key, limits.tagLength),\n value: truncate(redactor.redactText(value), limits.tagLength),\n }));\n\n const captureError = (error: unknown, kind: IssueKind = 'manual', extra: CaptureExtra = {}) => {\n try {\n const normalized = normalizeError(error, isInAppFile);\n let isAutomated = false;\n try {\n isAutomated = options.isAutomated?.() ?? false;\n } catch {\n isAutomated = false;\n }\n if (findIssueDropRule({ ...normalized, automated: isAutomated }, dropRules)) return;\n\n const message = truncate(redactor.redactText(normalized.message), limits.messageLength);\n const frames = normalized.frames.slice(0, limits.framesPerEvent);\n const fingerprint = truncate(buildClientFingerprint(normalized.name, message, frames), limits.clientFingerprintLength);\n\n const alreadyQueued = queue.find((candidate) => candidate.event.clientFingerprint === fingerprint);\n if (alreadyQueued) {\n alreadyQueued.event.count += 1;\n return;\n }\n if (!admit(fingerprint)) return;\n\n const url = extra.url !== undefined ? extra.url : route.url;\n const routePattern = extra.routePattern !== undefined ? extra.routePattern : route.routePattern;\n let commonTags: CaptureExtra['tags'] = {};\n try {\n commonTags = options.commonTags?.() ?? {};\n } catch {\n commonTags = {};\n }\n const event = shrinkToFit({\n occurredAt: new Date(clock.now()).toISOString(),\n kind,\n level: extra.level ?? 'error',\n name: truncate(normalized.name, limits.nameLength),\n message,\n frames,\n rawStack: normalized.rawStack ? truncate(redactor.redactText(normalized.rawStack), limits.rawStackLength) : null,\n url: url ? truncate(redactor.redactUrl(url), limits.urlLength) : null,\n routePattern: routePattern ? truncate(routePattern, limits.routePatternLength) : null,\n requestMethod: extra.requestMethod ? truncate(extra.requestMethod.toUpperCase(), limits.requestMethodLength) : null,\n httpStatus: extra.httpStatus ?? null,\n breadcrumbs: attachBreadcrumbs ? trail.snapshot() : [],\n tags: toTags({ ...commonTags, ...extra.tags }),\n count: 1,\n clientFingerprint: fingerprint,\n });\n\n queue.push({ event, attempts: 0 });\n if (queue.length > limits.queuedEvents) queue.shift();\n if (queue.length >= limits.flushAtEvents) void flush();\n else scheduleFlush(limits.flushDelayMs);\n } catch {\n // Never into the caller.\n }\n };\n\n return {\n captureError,\n addBreadcrumb: (breadcrumb) => {\n try {\n trail.add(sanitizeBreadcrumb(breadcrumb, redactor));\n } catch {\n // Never into the caller.\n }\n },\n setRoute: (routePattern, url) => {\n route = { routePattern, url };\n },\n setAuthorizationReader: (reader) => {\n readAuthorization = reader;\n },\n flush,\n getQueuedEventCount: () => queue.length,\n };\n};\n","import { navigationBreadcrumb } from './breadcrumbs';\nimport type { CapturedBreadcrumb } from './types';\n\n/** Dynamic route params as routers hand them out (`string` per segment, `string[]` for a catch-all). */\nexport type IssuesRouteParams = Record<string, string | readonly string[] | undefined>;\n\n/**\n * The route PATTERN of a page, rebuilt from its path and its dynamic params: `/books/12/chapters/3` with\n * `{ bookId: '12', chapterId: '3' }` → `/books/[bookId]/chapters/[chapterId]`. The pattern names the issue (one bug on\n * every book's chapter page is one issue) and carries no slug, id or token.\n *\n * Params are matched left to right, each against the first unmatched segment equal to its value, so\n * `/books/3/chapters/3` with `{ bookId: '3', chapterId: '3' }` still comes out right. A catch-all (array value)\n * replaces the run of segments it spans with `[...key]`.\n */\nexport const buildRoutePattern = (pathname: string, params: IssuesRouteParams | null | undefined): string => {\n const segments = pathname.split('/');\n const decode = (segment: string): string => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n };\n const decodedSegments = segments.map(decode);\n let searchFrom = 1;\n\n for (const [key, rawValue] of Object.entries(params ?? {})) {\n if (rawValue === undefined) continue;\n const isCatchAll = typeof rawValue !== 'string';\n const values = (isCatchAll ? [...rawValue] : [rawValue]).map(decode);\n if (values.length === 0) continue;\n for (let start = searchFrom; start + values.length <= segments.length; start++) {\n const isRun = values.every((value, offset) => decodedSegments[start + offset] === value);\n if (!isRun) continue;\n const placeholder = isCatchAll ? `[...${key}]` : `[${key}]`;\n segments.splice(start, values.length, placeholder);\n decodedSegments.splice(start, values.length, placeholder);\n searchFrom = start + 1;\n break;\n }\n }\n return segments.join('/') || '/';\n};\n\n/** The part of a reporter a route tracker drives. */\nexport interface IssuesRouteTarget {\n setRoute: (routePattern: string | null, url: string | null) => void;\n addBreadcrumb: (breadcrumb: CapturedBreadcrumb) => void;\n}\n\nexport interface IssuesRouteTracker {\n /**\n * Call on every route change: sets the reporter's route pattern and URL (the URL defaults to the path) and adds a\n * navigation breadcrumb when the pattern changed. Returns the pattern.\n */\n trackRoute: (pathname: string, params?: IssuesRouteParams | null, url?: string | null) => string;\n}\n\n/** Platform-free: a web router, a React Native navigator or a test calls `trackRoute` itself. */\nexport const createIssuesRouteTracker = (\n target: IssuesRouteTarget,\n now: () => string = () => new Date().toISOString(),\n): IssuesRouteTracker => {\n let previousRoutePattern: string | null = null;\n return {\n trackRoute: (pathname, params, url) => {\n const routePattern = buildRoutePattern(pathname, params);\n target.setRoute(routePattern, url === undefined ? pathname : url);\n if (routePattern !== previousRoutePattern) {\n target.addBreadcrumb(navigationBreadcrumb(now(), previousRoutePattern, routePattern));\n previousRoutePattern = routePattern;\n }\n return routePattern;\n },\n };\n};\n","import type { IssuesTransport } from './types';\n\n/** The part of the Fetch API the transport uses (browser, Node 18+, React Native). */\nexport type IssuesFetchFunction = (\n url: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n keepalive?: boolean;\n credentials?: 'omit' | 'same-origin' | 'include';\n signal?: unknown;\n },\n) => Promise<{ status: number }>;\n\nexport interface FetchIssuesTransportOptions {\n /** Read at send time; default the global `fetch` as it is then. */\n fetch?: () => IssuesFetchFunction | undefined;\n /** Default `omit`: the report carries a bearer when there is a session, never cookies. */\n credentials?: 'omit' | 'same-origin' | 'include';\n /** Aborts a request that takes longer (where `AbortSignal.timeout` exists); default none. */\n timeoutMs?: number;\n}\n\ninterface AbortSignalWithTimeout {\n timeout?: (milliseconds: number) => unknown;\n}\n\n/** POSTs with `fetch`. Rejects on a network error, like `fetch` itself. Touches no global before the first send. */\nexport const createFetchIssuesTransport = (options: FetchIssuesTransportOptions = {}): IssuesTransport => {\n return async (request) => {\n const fetchFunction =\n options.fetch?.() ?? (globalThis as unknown as { fetch?: IssuesFetchFunction }).fetch;\n if (typeof fetchFunction !== 'function') throw new Error('No fetch function available for the issues transport');\n const abortSignalClass = (globalThis as unknown as { AbortSignal?: AbortSignalWithTimeout }).AbortSignal;\n const signal =\n options.timeoutMs !== undefined && typeof abortSignalClass?.timeout === 'function'\n ? abortSignalClass.timeout(options.timeoutMs)\n : undefined;\n const response = await fetchFunction(request.url, {\n method: 'POST',\n headers: request.headers,\n body: request.body,\n credentials: options.credentials ?? 'omit',\n ...(request.keepalive ? { keepalive: true } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n return { status: response.status };\n };\n};\n"],"mappings":";;;;;AA6DO,IAAM,gBAAwC,OAAO,OAAO;AAAA,EACjE,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EAEzB,cAAc;AAAA,EACd,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,cAAc,KAAK;AAAA,EACnB,YAAY,KAAK;AAAA,EACjB,cAAc;AAAA,EACd,cAAc;AAAA,EAEd,SAAS,OAAO,OAAO;AAAA,IACrB,qBAAqB;AAAA,IACrB,kBAAkB;AAAA,IAClB,uBAAuB;AAAA,EACzB,CAAC;AAAA,EAED,UAAU,OAAO,OAAO;AAAA,IACtB,8BAA8B;AAAA,IAC9B,qBAAqB,IAAI;AAAA,IACzB,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,cAAc,IAAI;AAAA,EACpB,CAAC;AACH,CAAC;AAGM,IAAM,oBAAoB,CAAC,YAAmC,CAAC,OAAqB;AAAA,EACzF,GAAG;AAAA,EACH,GAAG;AAAA,EACH,SAAS,EAAE,GAAG,cAAc,SAAS,GAAG,UAAU,QAAQ;AAAA,EAC1D,UAAU,EAAE,GAAG,cAAc,UAAU,GAAG,UAAU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