@mgamadeus/ddd-web 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,623 @@
1
+ import {
2
+ dddIssuesWireAdapter
3
+ } from "./chunk-JAYJB2EF.js";
4
+
5
+ // src/issues/limits.ts
6
+ var ISSUES_LIMITS = Object.freeze({
7
+ nameLength: 128,
8
+ messageLength: 1024,
9
+ framesPerEvent: 30,
10
+ fileLength: 512,
11
+ functionLength: 128,
12
+ rawStackLength: 4096,
13
+ urlLength: 1024,
14
+ routePatternLength: 256,
15
+ breadcrumbsPerEvent: 20,
16
+ breadcrumbMessageLength: 256,
17
+ breadcrumbUrlLength: 1024,
18
+ tagsPerEvent: 10,
19
+ tagLength: 64,
20
+ requestMethodLength: 16,
21
+ clientFingerprintLength: 128,
22
+ flushDelayMs: 2e3,
23
+ flushAtEvents: 5,
24
+ eventsPerRequest: 10,
25
+ requestBytes: 48 * 1024,
26
+ eventBytes: 16 * 1024,
27
+ retryDelayMs: 1e4,
28
+ queuedEvents: 50,
29
+ session: Object.freeze({
30
+ sendsPerFingerprint: 3,
31
+ eventsPerSession: 25,
32
+ failedSendsBeforeStop: 3
33
+ }),
34
+ windowed: Object.freeze({
35
+ sendsPerFingerprintPerWindow: 3,
36
+ fingerprintWindowMs: 5 * 6e4,
37
+ eventsPerMinute: 60,
38
+ backoffStartMs: 1e4,
39
+ backoffMaxMs: 5 * 6e4
40
+ })
41
+ });
42
+ var mergeIssuesLimits = (overrides = {}) => ({
43
+ ...ISSUES_LIMITS,
44
+ ...overrides,
45
+ session: { ...ISSUES_LIMITS.session, ...overrides.session },
46
+ windowed: { ...ISSUES_LIMITS.windowed, ...overrides.windowed }
47
+ });
48
+
49
+ // src/issues/normalize.ts
50
+ var truncate = (value, maxLength) => value.length > maxLength ? value.slice(0, maxLength) : value;
51
+ var FOREIGN_FILE = /^(chrome-extension|moz-extension|safari-extension|safari-web-extension):|^node:|node_modules|^<anonymous>$|^native$|^\[native code\]$/;
52
+ var isForeignFile = (file) => FOREIGN_FILE.test(file);
53
+ var V8_FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
54
+ var V8_FRAME_WITHOUT_POSITION = /^\s*at (?:(.+?) \()?([^():]+)\)?\s*$/;
55
+ var GECKO_FRAME = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
56
+ var toFrame = (functionName, file, line, column, isInAppFile) => {
57
+ const cleanFunction = (functionName ?? "").replace(/^async /, "").replace(/^new /, "").trim();
58
+ return {
59
+ file: truncate(file, ISSUES_LIMITS.fileLength),
60
+ line: line ? Number(line) : null,
61
+ column: column ? Number(column) : null,
62
+ function: cleanFunction ? truncate(cleanFunction, ISSUES_LIMITS.functionLength) : null,
63
+ inApp: !isForeignFile(file) && isInAppFile(file)
64
+ };
65
+ };
66
+ var parseStack = (stack, isInAppFile = () => true, maxFrames = ISSUES_LIMITS.framesPerEvent) => {
67
+ const frames = [];
68
+ for (const line of stack.split("\n")) {
69
+ if (frames.length >= maxFrames) break;
70
+ const v8Match = V8_FRAME.exec(line);
71
+ if (v8Match) {
72
+ frames.push(toFrame(v8Match[1], v8Match[2] ?? "", v8Match[3], v8Match[4], isInAppFile));
73
+ continue;
74
+ }
75
+ const v8MatchWithoutPosition = V8_FRAME_WITHOUT_POSITION.exec(line);
76
+ if (v8MatchWithoutPosition) {
77
+ frames.push(toFrame(v8MatchWithoutPosition[1], v8MatchWithoutPosition[2] ?? "", void 0, void 0, isInAppFile));
78
+ continue;
79
+ }
80
+ const geckoMatch = GECKO_FRAME.exec(line);
81
+ if (geckoMatch) {
82
+ frames.push(toFrame(geckoMatch[1], geckoMatch[2] ?? "", geckoMatch[3], geckoMatch[4], isInAppFile));
83
+ }
84
+ }
85
+ return frames;
86
+ };
87
+ var MINIFIED_REACT_ERROR = /Minified React error #(\d+)/;
88
+ var describeNonError = (value) => {
89
+ if (value === void 0) return "undefined";
90
+ if (value === null) return "null";
91
+ try {
92
+ return JSON.stringify(value) ?? String(value);
93
+ } catch {
94
+ return String(value);
95
+ }
96
+ };
97
+ var isErrorLike = (value) => typeof value === "object" && value !== null && typeof value.message === "string";
98
+ var normalizeError = (value, isInAppFile = () => true) => {
99
+ if (!isErrorLike(value)) {
100
+ const message2 = typeof value === "string" ? value : describeNonError(value);
101
+ return {
102
+ name: typeof value === "string" ? "Error" : "NonError",
103
+ message: truncate(message2, ISSUES_LIMITS.messageLength),
104
+ frames: [],
105
+ rawStack: null
106
+ };
107
+ }
108
+ const message = String(value.message);
109
+ const reactErrorCode = MINIFIED_REACT_ERROR.exec(message)?.[1];
110
+ const declaredName = typeof value.name === "string" && value.name ? value.name : "Error";
111
+ const name = reactErrorCode ? `ReactError#${reactErrorCode}` : declaredName;
112
+ const stack = typeof value.stack === "string" ? value.stack : "";
113
+ const frames = stack ? parseStack(stack, isInAppFile) : [];
114
+ const hasStackLines = stack.split("\n").length > 1;
115
+ return {
116
+ name: truncate(name, ISSUES_LIMITS.nameLength),
117
+ message: truncate(message, ISSUES_LIMITS.messageLength),
118
+ frames,
119
+ rawStack: frames.length === 0 && hasStackLines ? truncate(stack, ISSUES_LIMITS.rawStackLength) : null
120
+ };
121
+ };
122
+
123
+ // src/issues/redact.ts
124
+ var DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS = Object.freeze([
125
+ "invitations",
126
+ "claim-account",
127
+ "verify-email",
128
+ "reset-password"
129
+ ]);
130
+ var TOKEN_QUERY_PARAMETER = /([?&][^=&#]*token[^=&#]*)=[^&#]*/gi;
131
+ var ISSUES_REDACTION_RULES = Object.freeze([
132
+ // An Authorization header value copied into a message.
133
+ { pattern: /\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: "Bearer [redacted]" },
134
+ // A JWT anywhere (access tokens, custom tokens of an identity provider).
135
+ { pattern: /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]+/g, replacement: "[jwt]" },
136
+ // E-mail addresses.
137
+ { pattern: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, replacement: "[email]" },
138
+ // UUIDs: a public link's id is often its credential (`/api/public/bookings/<uuid>/cancel`).
139
+ { 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]" },
140
+ // International phone numbers (+44 20 7946 0958).
141
+ { pattern: /\+\d[\d\s().-]{6,}\d/g, replacement: "[phone]" }
142
+ ]);
143
+ var LONG_HEX_PATH_SEGMENT = /\/[0-9a-f]{16,}(?=[/?#]|$)/gi;
144
+ var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
145
+ var createIssuesRedactor = (options = {}) => {
146
+ 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 valueRules = [...ISSUES_REDACTION_RULES, ...options.additionalRules ?? []];
149
+ const redactTokens = (value) => {
150
+ const withoutTokenSegments = tokenRouteSegment ? value.replace(tokenRouteSegment, "/$1/[redacted]") : value;
151
+ return withoutTokenSegments.replace(TOKEN_QUERY_PARAMETER, "$1=[redacted]");
152
+ };
153
+ const applyValueRules = (value) => valueRules.reduce((redacted, rule) => redacted.replace(rule.pattern, rule.replacement), value);
154
+ return {
155
+ redactUrl: (url) => applyValueRules(redactTokens(url)).replace(LONG_HEX_PATH_SEGMENT, "/[id]"),
156
+ redactText: (text) => applyValueRules(redactTokens(text))
157
+ };
158
+ };
159
+ var defaultIssuesRedactor = createIssuesRedactor();
160
+ var redactUrl = (url) => defaultIssuesRedactor.redactUrl(url);
161
+ var redactText = (text) => defaultIssuesRedactor.redactText(text);
162
+
163
+ // src/issues/breadcrumbs.ts
164
+ var createBreadcrumbTrail = (limit = ISSUES_LIMITS.breadcrumbsPerEvent) => {
165
+ const breadcrumbs = [];
166
+ return {
167
+ add: (breadcrumb) => {
168
+ breadcrumbs.push(breadcrumb);
169
+ while (breadcrumbs.length > limit) breadcrumbs.shift();
170
+ },
171
+ snapshot: () => breadcrumbs.slice()
172
+ };
173
+ };
174
+ var DEFAULT_BREADCRUMB_REDACTOR = { redactUrl, redactText };
175
+ var sanitizeBreadcrumb = (breadcrumb, redactor = DEFAULT_BREADCRUMB_REDACTOR) => {
176
+ const sanitizeUrl = (url) => url ? truncate(redactor.redactUrl(url), ISSUES_LIMITS.breadcrumbUrlLength) : null;
177
+ return {
178
+ at: breadcrumb.at,
179
+ category: breadcrumb.category,
180
+ message: truncate(redactor.redactText(breadcrumb.message), ISSUES_LIMITS.breadcrumbMessageLength),
181
+ url: sanitizeUrl(breadcrumb.url),
182
+ from: sanitizeUrl(breadcrumb.from),
183
+ to: sanitizeUrl(breadcrumb.to),
184
+ status: typeof breadcrumb.status === "number" ? breadcrumb.status : null
185
+ };
186
+ };
187
+ var buildBreadcrumb = (at, category, message, fields = {}) => sanitizeBreadcrumb({
188
+ at,
189
+ category,
190
+ message,
191
+ url: fields.url ?? null,
192
+ from: fields.from ?? null,
193
+ to: fields.to ?? null,
194
+ status: fields.status ?? null
195
+ });
196
+ var navigationBreadcrumb = (at, from, to) => buildBreadcrumb(at, "navigation", `${from ?? "(start)"} \u2192 ${to}`, { from, to });
197
+ var fetchBreadcrumb = (at, method, url, outcome) => buildBreadcrumb(at, "fetch", `${method.toUpperCase()} ${outcome}`, {
198
+ url,
199
+ status: outcome === "network-error" ? null : outcome
200
+ });
201
+ var consoleBreadcrumb = (at, message) => buildBreadcrumb(at, "console", message);
202
+ var uiBreadcrumb = (at, action) => buildBreadcrumb(at, "ui", action);
203
+ var customBreadcrumb = (at, message, fields = {}) => buildBreadcrumb(at, "custom", message, fields);
204
+
205
+ // src/issues/filters.ts
206
+ var messageMatches = (pattern) => (candidate) => pattern.test(candidate.message) || pattern.test(candidate.name);
207
+ var ISSUE_DROP_RULES = Object.freeze([
208
+ // A tab opened before a deploy asks for chunks the new deploy no longer has.
209
+ { id: "chunk-load", matches: (candidate) => candidate.name === "ChunkLoadError" },
210
+ { id: "chunk-load", matches: messageMatches(/Loading (CSS )?chunk [\w-]+ failed/) },
211
+ { id: "chunk-load", matches: messageMatches(/Failed to fetch dynamically imported module/) },
212
+ { id: "chunk-load", matches: messageMatches(/Importing a module script failed/) },
213
+ // Browser noise: the observer could not deliver every notification in one frame.
214
+ { id: "resize-observer", matches: messageMatches(/ResizeObserver loop/) },
215
+ // An error in a cross-origin script: the browser hides everything, nothing to act on.
216
+ { id: "opaque-script-error", matches: (candidate) => /^Script error\.?$/.test(candidate.message.trim()) },
217
+ // Thrown by a browser extension injected into the page.
218
+ {
219
+ id: "extension",
220
+ matches: (candidate) => /^(chrome-extension|moz-extension|safari-(web-)?extension):/.test(candidate.frames[0]?.file ?? "")
221
+ },
222
+ // Wallet extensions and in-app wallet browsers touch `window.ethereum` on every page.
223
+ { id: "wallet-extension", matches: messageMatches(/\bwindow\.ethereum\b/) },
224
+ // A request the app cancelled itself (navigation, unmount, an aborted query).
225
+ { id: "aborted", matches: (candidate) => candidate.name === "AbortError" },
226
+ // End-to-end runs under automation stay silent.
227
+ { id: "automated-browser", matches: (candidate) => candidate.automated }
228
+ ]);
229
+ var findIssueDropRule = (candidate, rules = ISSUE_DROP_RULES) => rules.find((rule) => rule.matches(candidate))?.id ?? null;
230
+
231
+ // src/issues/fingerprint.ts
232
+ var normaliseIssueMessage = (message) => message.replace(/https?:\/\/\S+/g, "{url}").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}").replace(/\b[0-9a-f]{8,}\b/gi, "{hex}").replace(/\d+/g, "{n}");
233
+ var buildClientFingerprint = (name, message, frames) => {
234
+ const topFrame = frames.find((frame) => frame.inApp) ?? frames[0];
235
+ const callSite = topFrame ? `${topFrame.file}:${topFrame.function ?? ""}` : "";
236
+ return `${name}|${normaliseIssueMessage(message)}|${callSite}`;
237
+ };
238
+
239
+ // src/issues/reporter.ts
240
+ var DDD_ISSUES_SERVER_TOKEN_HEADER = "X-Issues-Server-Token";
241
+ var createPlatformIssuesClock = () => {
242
+ const timers = globalThis;
243
+ return {
244
+ now: () => Date.now(),
245
+ setTimeout: (callback, delayMs) => {
246
+ const handle = timers.setTimeout(callback, delayMs);
247
+ if (typeof handle === "object" && handle !== null) handle.unref?.();
248
+ return handle;
249
+ },
250
+ clearTimeout: (handle) => timers.clearTimeout(handle)
251
+ };
252
+ };
253
+ var utf8ByteLength = (value) => {
254
+ let bytes = 0;
255
+ for (let index = 0; index < value.length; index++) {
256
+ const code = value.charCodeAt(index);
257
+ if (code < 128) bytes += 1;
258
+ else if (code < 2048) bytes += 2;
259
+ else if (code >= 55296 && code <= 56319) {
260
+ bytes += 4;
261
+ index++;
262
+ } else bytes += 3;
263
+ }
264
+ return bytes;
265
+ };
266
+ var REQUEST_OVERHEAD_BYTES = 2048;
267
+ var FRAMES_KEPT_WHEN_SHRINKING = 10;
268
+ var MESSAGE_LENGTH_KEPT_WHEN_SHRINKING = 256;
269
+ var NO_CONTEXT = {
270
+ release: null,
271
+ tabId: null,
272
+ userAgent: null,
273
+ viewportWidth: null,
274
+ viewportHeight: null,
275
+ locale: null
276
+ };
277
+ var createIssuesReporter = (options) => {
278
+ const limits = mergeIssuesLimits(options.limits);
279
+ const clock = options.clock ?? createPlatformIssuesClock();
280
+ const wire = options.wire ?? dddIssuesWireAdapter;
281
+ const redactor = options.redactor ?? createIssuesRedactor();
282
+ const dropRules = options.dropRules ?? ISSUE_DROP_RULES;
283
+ const isInAppFile = options.isInAppFile ?? (() => true);
284
+ const rateLimitMode = options.rateLimitMode ?? (options.runtime === "browser" ? "session" : "windowed");
285
+ const attachBreadcrumbs = options.attachBreadcrumbs ?? options.runtime !== "node";
286
+ const isBrowser = options.runtime === "browser";
287
+ const trail = createBreadcrumbTrail(limits.breadcrumbsPerEvent);
288
+ let readAuthorization = options.getAuthorization ?? null;
289
+ let route = { routePattern: null, url: null };
290
+ let queue = [];
291
+ let flushTimer = null;
292
+ let isSending = false;
293
+ let isKeepaliveInFlight = false;
294
+ const sendsByFingerprint = /* @__PURE__ */ new Map();
295
+ let sessionEvents = 0;
296
+ let failedSends = 0;
297
+ let isStopped = false;
298
+ const sendTimesByFingerprint = /* @__PURE__ */ new Map();
299
+ let sendTimesOfLastMinute = [];
300
+ let backoffMs = 0;
301
+ let backoffUntil = 0;
302
+ const measureEvent = (event) => utf8ByteLength(JSON.stringify(wire.toWireEvent(event)));
303
+ const shrinkToFit = (event) => {
304
+ const steps = [
305
+ (current) => ({ ...current, breadcrumbs: [] }),
306
+ (current) => ({ ...current, frames: current.frames.slice(0, FRAMES_KEPT_WHEN_SHRINKING) }),
307
+ (current) => ({ ...current, rawStack: null }),
308
+ (current) => ({ ...current, message: truncate(current.message, MESSAGE_LENGTH_KEPT_WHEN_SHRINKING) })
309
+ ];
310
+ let shrunk = event;
311
+ for (const step of steps) {
312
+ if (measureEvent(shrunk) <= limits.eventBytes) return shrunk;
313
+ shrunk = step(shrunk);
314
+ }
315
+ return shrunk;
316
+ };
317
+ const admit = (fingerprint) => {
318
+ if (rateLimitMode === "session") {
319
+ if (isStopped) return false;
320
+ const sends = sendsByFingerprint.get(fingerprint) ?? 0;
321
+ if (sends >= limits.session.sendsPerFingerprint) return false;
322
+ if (sessionEvents >= limits.session.eventsPerSession) return false;
323
+ sendsByFingerprint.set(fingerprint, sends + 1);
324
+ sessionEvents += 1;
325
+ return true;
326
+ }
327
+ const now = clock.now();
328
+ const windowStart = now - limits.windowed.fingerprintWindowMs;
329
+ const fingerprintTimes = (sendTimesByFingerprint.get(fingerprint) ?? []).filter((time) => time > windowStart);
330
+ sendTimesOfLastMinute = sendTimesOfLastMinute.filter((time) => time > now - 6e4);
331
+ if (fingerprintTimes.length >= limits.windowed.sendsPerFingerprintPerWindow) return false;
332
+ if (sendTimesOfLastMinute.length >= limits.windowed.eventsPerMinute) return false;
333
+ fingerprintTimes.push(now);
334
+ sendTimesByFingerprint.set(fingerprint, fingerprintTimes);
335
+ sendTimesOfLastMinute.push(now);
336
+ if (sendTimesByFingerprint.size > 500) {
337
+ for (const [key, times] of sendTimesByFingerprint) {
338
+ if (times.every((time) => time <= windowStart)) sendTimesByFingerprint.delete(key);
339
+ }
340
+ }
341
+ return true;
342
+ };
343
+ const scheduleFlush = (delayMs) => {
344
+ if (flushTimer !== null) return;
345
+ flushTimer = clock.setTimeout(() => {
346
+ flushTimer = null;
347
+ void flush();
348
+ }, delayMs);
349
+ };
350
+ const recordFailure = () => {
351
+ if (rateLimitMode === "session") {
352
+ failedSends += 1;
353
+ if (failedSends >= limits.session.failedSendsBeforeStop) {
354
+ isStopped = true;
355
+ queue = [];
356
+ }
357
+ return;
358
+ }
359
+ backoffMs = backoffMs ? Math.min(backoffMs * 2, limits.windowed.backoffMaxMs) : limits.windowed.backoffStartMs;
360
+ backoffUntil = clock.now() + backoffMs;
361
+ };
362
+ const recordSuccess = () => {
363
+ backoffMs = 0;
364
+ backoffUntil = 0;
365
+ };
366
+ const takeBatch = () => {
367
+ const batch = [];
368
+ let bytes = REQUEST_OVERHEAD_BYTES;
369
+ while (queue.length > 0 && batch.length < limits.eventsPerRequest) {
370
+ const next = queue[0];
371
+ const eventBytes = measureEvent(next.event) + 1;
372
+ if (batch.length > 0 && bytes + eventBytes > limits.requestBytes) break;
373
+ bytes += eventBytes;
374
+ batch.push(next);
375
+ queue.shift();
376
+ }
377
+ return batch;
378
+ };
379
+ const buildHeaders = () => {
380
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
381
+ try {
382
+ const accessToken = readAuthorization?.();
383
+ if (accessToken) headers.Authorization = `Bearer ${accessToken}`;
384
+ } catch {
385
+ }
386
+ if (options.serverToken) headers[options.serverTokenHeader ?? DDD_ISSUES_SERVER_TOKEN_HEADER] = options.serverToken;
387
+ return headers;
388
+ };
389
+ const buildContext = () => {
390
+ let contextValues = {};
391
+ try {
392
+ contextValues = options.context?.() ?? {};
393
+ } catch {
394
+ }
395
+ return { ...NO_CONTEXT, ...contextValues, runtime: options.runtime, app: options.app };
396
+ };
397
+ const sendBatch = async (batch, unloading = false) => {
398
+ if (batch.length === 0) return;
399
+ let endpoint = null;
400
+ try {
401
+ endpoint = options.endpoint();
402
+ } catch {
403
+ endpoint = null;
404
+ }
405
+ if (!endpoint) return;
406
+ const body = JSON.stringify(wire.toRequestBody(buildContext(), batch.map((queued) => wire.toWireEvent(queued.event))));
407
+ const useKeepalive = isBrowser && !isKeepaliveInFlight;
408
+ if (useKeepalive) isKeepaliveInFlight = true;
409
+ let status = null;
410
+ try {
411
+ status = (await options.transport({ url: endpoint, headers: buildHeaders(), body, keepalive: useKeepalive, unloading })).status;
412
+ } catch {
413
+ status = null;
414
+ } finally {
415
+ if (useKeepalive) isKeepaliveInFlight = false;
416
+ }
417
+ if (status !== null && status < 400) {
418
+ recordSuccess();
419
+ return;
420
+ }
421
+ const isRetryable = status === null || status >= 500;
422
+ const retryable = isRetryable ? batch.filter((queued) => queued.attempts === 0) : [];
423
+ recordFailure();
424
+ if (retryable.length > 0 && !isStopped) {
425
+ queue = [...retryable.map((queued) => ({ ...queued, attempts: queued.attempts + 1 })), ...queue];
426
+ scheduleFlush(Math.max(limits.retryDelayMs, backoffUntil - clock.now()));
427
+ }
428
+ };
429
+ const flush = async (flushOptions) => {
430
+ try {
431
+ if (flushTimer !== null) {
432
+ clock.clearTimeout(flushTimer);
433
+ flushTimer = null;
434
+ }
435
+ if (queue.length === 0 || isStopped) return;
436
+ if (rateLimitMode === "windowed" && clock.now() < backoffUntil) {
437
+ scheduleFlush(backoffUntil - clock.now());
438
+ return;
439
+ }
440
+ if (flushOptions?.unloading) {
441
+ while (queue.length > 0) void sendBatch(takeBatch(), true);
442
+ return;
443
+ }
444
+ if (isSending) return;
445
+ isSending = true;
446
+ try {
447
+ await sendBatch(takeBatch());
448
+ } finally {
449
+ isSending = false;
450
+ }
451
+ if (queue.length > 0) scheduleFlush(limits.flushDelayMs);
452
+ } catch {
453
+ }
454
+ };
455
+ const toTags = (tags) => Object.entries(tags ?? {}).filter((entry) => typeof entry[1] === "string").slice(0, limits.tagsPerEvent).map(([key, value]) => ({
456
+ key: truncate(key, limits.tagLength),
457
+ value: truncate(redactor.redactText(value), limits.tagLength)
458
+ }));
459
+ const captureError = (error, kind = "manual", extra = {}) => {
460
+ try {
461
+ const normalized = normalizeError(error, isInAppFile);
462
+ let isAutomated = false;
463
+ try {
464
+ isAutomated = options.isAutomated?.() ?? false;
465
+ } catch {
466
+ isAutomated = false;
467
+ }
468
+ if (findIssueDropRule({ ...normalized, automated: isAutomated }, dropRules)) return;
469
+ const message = truncate(redactor.redactText(normalized.message), limits.messageLength);
470
+ const frames = normalized.frames.slice(0, limits.framesPerEvent);
471
+ const fingerprint = truncate(buildClientFingerprint(normalized.name, message, frames), limits.clientFingerprintLength);
472
+ const alreadyQueued = queue.find((candidate) => candidate.event.clientFingerprint === fingerprint);
473
+ if (alreadyQueued) {
474
+ alreadyQueued.event.count += 1;
475
+ return;
476
+ }
477
+ if (!admit(fingerprint)) return;
478
+ const url = extra.url !== void 0 ? extra.url : route.url;
479
+ const routePattern = extra.routePattern !== void 0 ? extra.routePattern : route.routePattern;
480
+ let commonTags = {};
481
+ try {
482
+ commonTags = options.commonTags?.() ?? {};
483
+ } catch {
484
+ commonTags = {};
485
+ }
486
+ const event = shrinkToFit({
487
+ occurredAt: new Date(clock.now()).toISOString(),
488
+ kind,
489
+ level: extra.level ?? "error",
490
+ name: truncate(normalized.name, limits.nameLength),
491
+ message,
492
+ frames,
493
+ rawStack: normalized.rawStack ? truncate(redactor.redactText(normalized.rawStack), limits.rawStackLength) : null,
494
+ url: url ? truncate(redactor.redactUrl(url), limits.urlLength) : null,
495
+ routePattern: routePattern ? truncate(routePattern, limits.routePatternLength) : null,
496
+ requestMethod: extra.requestMethod ? truncate(extra.requestMethod.toUpperCase(), limits.requestMethodLength) : null,
497
+ httpStatus: extra.httpStatus ?? null,
498
+ breadcrumbs: attachBreadcrumbs ? trail.snapshot() : [],
499
+ tags: toTags({ ...commonTags, ...extra.tags }),
500
+ count: 1,
501
+ clientFingerprint: fingerprint
502
+ });
503
+ queue.push({ event, attempts: 0 });
504
+ if (queue.length > limits.queuedEvents) queue.shift();
505
+ if (queue.length >= limits.flushAtEvents) void flush();
506
+ else scheduleFlush(limits.flushDelayMs);
507
+ } catch {
508
+ }
509
+ };
510
+ return {
511
+ captureError,
512
+ addBreadcrumb: (breadcrumb) => {
513
+ try {
514
+ trail.add(sanitizeBreadcrumb(breadcrumb, redactor));
515
+ } catch {
516
+ }
517
+ },
518
+ setRoute: (routePattern, url) => {
519
+ route = { routePattern, url };
520
+ },
521
+ setAuthorizationReader: (reader) => {
522
+ readAuthorization = reader;
523
+ },
524
+ flush,
525
+ getQueuedEventCount: () => queue.length
526
+ };
527
+ };
528
+
529
+ // src/issues/route-pattern.ts
530
+ var buildRoutePattern = (pathname, params) => {
531
+ const segments = pathname.split("/");
532
+ const decode = (segment) => {
533
+ try {
534
+ return decodeURIComponent(segment);
535
+ } catch {
536
+ return segment;
537
+ }
538
+ };
539
+ const decodedSegments = segments.map(decode);
540
+ let searchFrom = 1;
541
+ for (const [key, rawValue] of Object.entries(params ?? {})) {
542
+ if (rawValue === void 0) continue;
543
+ const isCatchAll = typeof rawValue !== "string";
544
+ const values = (isCatchAll ? [...rawValue] : [rawValue]).map(decode);
545
+ if (values.length === 0) continue;
546
+ for (let start = searchFrom; start + values.length <= segments.length; start++) {
547
+ const isRun = values.every((value, offset) => decodedSegments[start + offset] === value);
548
+ if (!isRun) continue;
549
+ const placeholder = isCatchAll ? `[...${key}]` : `[${key}]`;
550
+ segments.splice(start, values.length, placeholder);
551
+ decodedSegments.splice(start, values.length, placeholder);
552
+ searchFrom = start + 1;
553
+ break;
554
+ }
555
+ }
556
+ return segments.join("/") || "/";
557
+ };
558
+ var createIssuesRouteTracker = (target, now = () => (/* @__PURE__ */ new Date()).toISOString()) => {
559
+ let previousRoutePattern = null;
560
+ return {
561
+ trackRoute: (pathname, params, url) => {
562
+ const routePattern = buildRoutePattern(pathname, params);
563
+ target.setRoute(routePattern, url === void 0 ? pathname : url);
564
+ if (routePattern !== previousRoutePattern) {
565
+ target.addBreadcrumb(navigationBreadcrumb(now(), previousRoutePattern, routePattern));
566
+ previousRoutePattern = routePattern;
567
+ }
568
+ return routePattern;
569
+ }
570
+ };
571
+ };
572
+
573
+ // src/issues/transport.ts
574
+ var createFetchIssuesTransport = (options = {}) => {
575
+ return async (request) => {
576
+ const fetchFunction = options.fetch?.() ?? globalThis.fetch;
577
+ if (typeof fetchFunction !== "function") throw new Error("No fetch function available for the issues transport");
578
+ const abortSignalClass = globalThis.AbortSignal;
579
+ const signal = options.timeoutMs !== void 0 && typeof abortSignalClass?.timeout === "function" ? abortSignalClass.timeout(options.timeoutMs) : void 0;
580
+ const response = await fetchFunction(request.url, {
581
+ method: "POST",
582
+ headers: request.headers,
583
+ body: request.body,
584
+ credentials: options.credentials ?? "omit",
585
+ ...request.keepalive ? { keepalive: true } : {},
586
+ ...signal !== void 0 ? { signal } : {}
587
+ });
588
+ return { status: response.status };
589
+ };
590
+ };
591
+
592
+ export {
593
+ ISSUES_LIMITS,
594
+ mergeIssuesLimits,
595
+ truncate,
596
+ isForeignFile,
597
+ parseStack,
598
+ normalizeError,
599
+ DEFAULT_ISSUES_TOKEN_PATH_SEGMENTS,
600
+ ISSUES_REDACTION_RULES,
601
+ createIssuesRedactor,
602
+ redactUrl,
603
+ redactText,
604
+ createBreadcrumbTrail,
605
+ sanitizeBreadcrumb,
606
+ navigationBreadcrumb,
607
+ fetchBreadcrumb,
608
+ consoleBreadcrumb,
609
+ uiBreadcrumb,
610
+ customBreadcrumb,
611
+ ISSUE_DROP_RULES,
612
+ findIssueDropRule,
613
+ normaliseIssueMessage,
614
+ buildClientFingerprint,
615
+ DDD_ISSUES_SERVER_TOKEN_HEADER,
616
+ createPlatformIssuesClock,
617
+ utf8ByteLength,
618
+ createIssuesReporter,
619
+ buildRoutePattern,
620
+ createIssuesRouteTracker,
621
+ createFetchIssuesTransport
622
+ };
623
+ //# sourceMappingURL=chunk-GVRMHMNO.js.map