@ihyeon/browser-error-log 0.1.21 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +41 -1
- package/README.md +41 -1
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
package/README.ko.md
CHANGED
|
@@ -84,6 +84,24 @@ errorLog.captureException(new Error('Dashboard could not load', { cause }));
|
|
|
84
84
|
|
|
85
85
|
유효한 원인이 있으면 바깥 스택은 최대 2,048자, 각 원인 구간은 최대 480자를 사용하며 전체 스택은 기존 4,096자 안으로 제한합니다. 구간을 자르기 전에 기존 텍스트·URL 필터를 적용합니다. 프로토콜 필드나 수집기 갱신 없이 기존 뷰어의 스택 상세에서 볼 수 있습니다. 원인 메시지와 경로에도 민감정보가 있을 수 있으므로 앱별 필터를 검토한 뒤 켜세요. `beforeSend`에서 합쳐진 스택을 수정하거나 `delete event.stack`·`event.stack = undefined`로 제거하고 이벤트 전체를 제외할 수도 있습니다. URL 필터가 실패하면 필터링하지 않은 원인 정보를 보내지 않고 이벤트를 버립니다.
|
|
86
86
|
|
|
87
|
+
## 리소스 로딩 실패 수집
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const errorLog = init({
|
|
91
|
+
project: 'my-web',
|
|
92
|
+
endpoint: '/api/events',
|
|
93
|
+
captureResourceErrors: true,
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**이 옵션을 켜기 전에 수집기와 뷰어를 0.2.0 이상으로 갱신하세요.** 자체 백엔드도 스키마와 유형 필터에서 `type: 'resource'`를 허용해야 합니다. 이전 수집기는 새 유형이 섞인 배치 전체를 거부할 수 있습니다. 기본값은 꺼짐이므로 기존 일반 이벤트 유형은 이전 수집기와 계속 사용할 수 있습니다.
|
|
98
|
+
|
|
99
|
+
초기화 이후 현재 문서에서 발생하는 script·스타일시트 link·img의 로딩 오류를 관찰합니다. 이벤트 유형은 `resource`, 이름은 `ResourceLoadError`이며 `Failed to load script resource` 같은 고정 메시지와 단일 값 `context.resourceTag`(`script`, `link`, `img`)·`context.resourceUrl`을 기록합니다. 이미지의 선택된 `currentSrc`가 있으면 이를 사용합니다. HTTP(S) URL만 기존 URL·텍스트 필터와 context 한도로 기록하며 HTML·요소 텍스트·ID·class·alt·폼 값·srcset 목록은 복사하지 않습니다. 수집기 URL과 지원하지 않는 리소스 종류·스킴은 제외합니다.
|
|
100
|
+
|
|
101
|
+
요소의 error 이벤트에는 HTTP 상태나 응답 본문이 없으므로 상태·네트워크 소요 시간·스택을 만들어 넣지 않습니다. 파일 누락, 브라우저 정책, 이미지 디코딩 등 여러 이유로 발생할 수 있으며 SDK가 요청을 반복하거나 확인용 요청을 보내지는 않습니다. fetch·XHR 수집과 독립적으로 동작하고 요소의 기존 핸들러와 기본 동작을 유지합니다. 초기화 전 오류나 다른 문서, window까지 전달되지 않는 이벤트 경계 안의 오류는 복원하지 못합니다.
|
|
102
|
+
|
|
103
|
+
공통 context, 작업 기록, `beforeSend`, 수집 한도, 큐 한도, 진단 통계를 공유합니다. 기존 최대 12개 context 항목 안에서 두 리소스 항목을 공통 context보다 우선합니다. URL·context 콜백 실패 시 이벤트를 버리고 `beforeSend`가 제외하면 필터링으로 집계합니다. `destroy()`는 리스너를 해제합니다. 0.2.0 뷰어의 유형 필터·차트·상세·이력 JSON도 새 유형을 지원합니다.
|
|
104
|
+
|
|
87
105
|
## 오류 전 작업 기록
|
|
88
106
|
|
|
89
107
|
```ts
|
|
@@ -99,6 +117,28 @@ errorLog.clearBreadcrumbs(); // 새 흐름 시작; 이미 수집한 오류는
|
|
|
99
117
|
|
|
100
118
|
뷰어는 두 오류 상세 화면에 이 기록을 표시하고 히스토리 JSON에도 보존합니다. 자체 호스팅 수집기·뷰어는 작업 기록 지원 버전(0.1.16부터)에서 이 선택 필드를 저장·표시합니다. 이전 수집기는 이벤트를 받아도 작업 기록을 생략할 수 있습니다. 자체 백엔드는 `@ihyeon/browser-error-log-protocol`의 `isBreadcrumbTrail`로 작업 기록을 검증할 수 있습니다.
|
|
101
119
|
|
|
120
|
+
## 저장 전 작업 기록 필터
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const errorLog = init({
|
|
124
|
+
project: 'my-web',
|
|
125
|
+
endpoint: '/api/events',
|
|
126
|
+
captureNetworkBreadcrumbs: true,
|
|
127
|
+
beforeBreadcrumb(breadcrumb) {
|
|
128
|
+
const url = breadcrumb.data?.url;
|
|
129
|
+
if (breadcrumb.category === 'http' && typeof url === 'string' && url.endsWith('/api/health')) return null;
|
|
130
|
+
if (breadcrumb.category === 'manual') breadcrumb.category = 'action';
|
|
131
|
+
return breadcrumb;
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
동기 콜백 `beforeBreadcrumb`는 유효한 수동·화면 이동·네트워크 작업을 생성할 때 초기 SDK 정제 후 로컬 버퍼에 저장하기 전에 한 번 실행합니다. `false`·`null`을 반환하면 항목을 제외하고, `BreadcrumbInput`을 반환하면 교체하며, 반환하지 않으면 전달한 복사본의 수정 내용을 사용합니다. 반환값에도 기존 필터와 크기 제한을 다시 적용하고 발생 시각은 SDK의 원래 값을 유지하며 추가 필드는 무시합니다.
|
|
137
|
+
|
|
138
|
+
콜백은 독립된 복사본을 받으므로 나중에 값을 바꿔도 현재 버퍼나 이미 큐에 담긴 오류의 기록을 수정하지 않습니다. 콜백 예외·잘못된 반환값·반환값 정제 실패는 해당 작업만 제외하며 오류 통계를 바꾸지 않습니다. 네트워크 작업을 제외해도 독립 HTTP·네트워크 오류 이벤트는 기존 수집 정책을 따릅니다. 오류 선택에는 `captureNetwork`·`shouldCaptureHttp`·`beforeSend`를 사용하세요. 콜백 실행 중 다시 추가하려는 작업은 무시하며, 콜백에서 클라이언트를 종료하면 이후 그 작업을 저장하지 않습니다.
|
|
139
|
+
|
|
140
|
+
오류가 작업 기록을 복사할 때, `beforeSend` 반환값 정제, 통계 조회, 전송·재시도에서는 이 콜백을 다시 실행하지 않습니다. 최종 이벤트 필터는 기존 `beforeSend`입니다. 이 옵션으로 추가 이벤트·요청·프로토콜 필드를 만들지 않으며 수집기 갱신도 필요하지 않습니다.
|
|
141
|
+
|
|
102
142
|
## SPA 화면 이동 자동 기록
|
|
103
143
|
|
|
104
144
|
```ts
|
|
@@ -159,7 +199,7 @@ currentAppSection = 'account'; // 이후 이벤트에는 현재 값을 사용
|
|
|
159
199
|
|
|
160
200
|
`captureConsole: true`로 `console.error` 호출을 수집할 수 있습니다. 인자를 합친 메시지는 유지하며, 같은 창에서 생성된 첫 번째 `Error` 인자의 이름과 스택도 기록합니다. 동일한 민감정보 필터와 `beforeSend` 제어가 적용됩니다.
|
|
161
201
|
|
|
162
|
-
기본 HTTP 수집은 5xx와 네트워크 실패를 포함하고 의도적인 취소와 수집기 endpoint를 제외합니다. SDK는 URL 쿼리·해시·자격 정보와 흔한 이메일/토큰 패턴을 제거합니다. 요청/응답 본문, 쿠키,
|
|
202
|
+
기본 HTTP 수집은 5xx와 네트워크 실패를 포함하고 의도적인 취소와 수집기 endpoint를 제외합니다. SDK는 URL 쿼리·해시·자격 정보와 흔한 이메일/토큰 패턴을 제거합니다. 요청/응답 본문, 쿠키, 페이지 HTML, 요소 텍스트, 폼 입력, 세션 녹화는 수집하지 않습니다. 오류 메시지, URL 경로, 스택, 사용자 지정 context에는 민감정보가 남을 수 있으므로 앱별 필터를 설정하세요. `beforeSend`나 `sanitizeUrl`이 실패하면 이벤트를 버립니다.
|
|
163
203
|
|
|
164
204
|
사용자 지정 `transport(batch, { signal })`에서는 요청에 `signal`을 전달하고 전송 실패 시 reject하세요. 자동 네트워크 오류 수집이나 요청 기록을 원하면 자기 전송을 제외할 `endpoint`를 지정해야 합니다. 없으면 사용자 지정 transport에서 두 경로를 모두 끕니다. 기본 전송은 credentials를 보내지 않습니다.
|
|
165
205
|
|
package/README.md
CHANGED
|
@@ -84,6 +84,24 @@ Only objects with a string `message` or `stack` are followed, including Error ob
|
|
|
84
84
|
|
|
85
85
|
When a valid cause is present, the outer stack uses up to 2,048 characters and each cause section up to 480, within the existing 4,096-character total stack limit. The existing text/URL filters run before section clipping. No new protocol fields or collector upgrade are needed, and existing viewer stack details show the chain. Review application-specific filters before opting in: cause messages and paths can contain additional sensitive data. `beforeSend` can edit the combined stack, remove it with `delete event.stack` or `event.stack = undefined`, or reject the event. A failing URL sanitizer drops the event rather than sending unfiltered cause data.
|
|
86
86
|
|
|
87
|
+
## Capture failed resource loads
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const errorLog = init({
|
|
91
|
+
project: 'my-web',
|
|
92
|
+
endpoint: '/api/events',
|
|
93
|
+
captureResourceErrors: true,
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Upgrade your collector and viewer to 0.2.0 or later before enabling this option.** Custom backends must accept `type: 'resource'` in their schema and type filters. Older collectors can reject an entire batch containing the new type. The option is off by default, so ordinary existing event types remain usable with older collectors.
|
|
98
|
+
|
|
99
|
+
The SDK observes current-document loading errors from scripts, stylesheet links, and images after initialization. Events use type `resource`, name `ResourceLoadError`, a fixed message such as `Failed to load script resource`, and scalar `context.resourceTag` (`script`, `link`, or `img`) and `context.resourceUrl`. The image's selected `currentSrc` is used when available. Only HTTP(S) URLs are recorded, using the existing URL/text filters and context limits. HTML, element text, IDs, classes, alternate text, form values, and source-set lists are not copied. Collector URLs and unsupported resource kinds/schemes are excluded.
|
|
100
|
+
|
|
101
|
+
Element error events do not expose an HTTP status or response body. These events therefore have no invented status, network timing, or stack. A failed load can have several causes, including a missing file, browser policy, or image decoding. Requests are not repeated or probed. The setting is independent of fetch/XHR capture; native element handlers and default behavior are preserved. Errors before initialization, inside other documents, or behind event boundaries that do not reach the window are not recovered.
|
|
102
|
+
|
|
103
|
+
Resource events share normal context, breadcrumbs, `beforeSend`, rate limits, queue limits, and diagnostics. The two resource context fields take priority over common context within the existing 12-field limit. URL or context hook failures drop the event; a `beforeSend` veto filters it. `destroy()` removes the listener. Viewer type filters, charts, details, and history JSON support the new type in 0.2.0.
|
|
104
|
+
|
|
87
105
|
## Record the steps before an error
|
|
88
106
|
|
|
89
107
|
```ts
|
|
@@ -99,6 +117,28 @@ Each client keeps the latest 20 recorded steps, within a 12,000-byte UTF-8 JSON
|
|
|
99
117
|
|
|
100
118
|
The viewer shows these steps in both error detail views and preserves them in history JSON. Use a collector and viewer with breadcrumb support (introduced in 0.1.16) to retain and display this optional field; older collectors may accept an event while omitting its breadcrumbs. Custom backends can validate the trail with `isBreadcrumbTrail` from `@ihyeon/browser-error-log-protocol`.
|
|
101
119
|
|
|
120
|
+
## Filter steps before they are stored
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const errorLog = init({
|
|
124
|
+
project: 'my-web',
|
|
125
|
+
endpoint: '/api/events',
|
|
126
|
+
captureNetworkBreadcrumbs: true,
|
|
127
|
+
beforeBreadcrumb(breadcrumb) {
|
|
128
|
+
const url = breadcrumb.data?.url;
|
|
129
|
+
if (breadcrumb.category === 'http' && typeof url === 'string' && url.endsWith('/api/health')) return null;
|
|
130
|
+
if (breadcrumb.category === 'manual') breadcrumb.category = 'action';
|
|
131
|
+
return breadcrumb;
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The synchronous `beforeBreadcrumb` hook runs once when a valid manual, navigation, or network step is created, after initial SDK sanitization and before local trail storage. Return `false` or `null` to omit the step, return a `BreadcrumbInput` replacement, or return nothing to keep changes to the supplied copy. Returned content is sanitized again with the existing limits. The SDK keeps its original occurrence time and ignores extra fields.
|
|
137
|
+
|
|
138
|
+
The hook receives independent copies; retaining or changing them later does not rewrite the live trail or queued error snapshots. A throwing hook, invalid replacement, or replacement sanitization failure omits that step without changing error counters. Filtering a network breadcrumb does not suppress the corresponding standalone HTTP/network error; use `captureNetwork`, `shouldCaptureHttp`, or `beforeSend` for error selection. Nested breadcrumb creation during this hook is ignored, and a hook that destroys its client cannot add a step afterward.
|
|
139
|
+
|
|
140
|
+
The hook is not called again when errors snapshot a trail, during `beforeSend` replacement sanitization, on reads, or on delivery/retries. `beforeSend` remains the final event filter. No additional event, request, protocol field, or collector upgrade is required for this hook.
|
|
141
|
+
|
|
102
142
|
## Automatically record SPA navigation
|
|
103
143
|
|
|
104
144
|
```ts
|
|
@@ -159,7 +199,7 @@ Set `context` at initialization to attach common diagnostic fields to every even
|
|
|
159
199
|
|
|
160
200
|
Set `captureConsole: true` to capture `console.error` calls. The combined message is preserved; the first `Error` created in the current window also contributes its name and stack, using the same redaction and `beforeSend` controls.
|
|
161
201
|
|
|
162
|
-
By default, HTTP capture records 5xx responses and network failures, excludes intentional aborts, and excludes the collector endpoint. The SDK strips URL queries, fragments, and credentials and masks common email/token patterns. It does not collect request/response bodies, cookies,
|
|
202
|
+
By default, HTTP capture records 5xx responses and network failures, excludes intentional aborts, and excludes the collector endpoint. The SDK strips URL queries, fragments, and credentials and masks common email/token patterns. It does not collect request/response bodies, cookies, page HTML, element text, form inputs, or session recordings. Error text, URL paths, stacks, and custom context may still contain sensitive data; set application-specific filters. A failing `beforeSend` or `sanitizeUrl` drops the event.
|
|
163
203
|
|
|
164
204
|
For a custom `transport(batch, { signal })`, pass `signal` to your request and reject on delivery failure. Include `endpoint` for collector exclusion when using automatic network error capture or network breadcrumbs; otherwise both are disabled for a custom transport. The default transport omits credentials.
|
|
165
205
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var D=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(n,e,t)=>e in n?D(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Z=(n,e)=>{for(var t in e)D(n,t,{get:e[t],enumerable:!0})},G=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!J.call(n,i)&&i!==t&&D(n,i,{get:()=>e[i],enumerable:!(r=K(e,i))||r.enumerable});return n};var Q=n=>G(D({},"__esModule",{value:!0}),n);var d=(n,e,t)=>Y(n,typeof e!="symbol"?e+"":e,t);var ge={};Z(ge,{init:()=>me});module.exports=Q(ge);var k={count:20,bytes:12e3,category:40,message:256,dataKeys:6,dataKey:80,dataString:200};var ee=20,U=48e3,te=10,re=24e3,M=[250,500],_=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,F=new Set(["javascript","promise","react","console","http","network","manual"]),H=new Set(["browser","webview-ios","webview-android","unknown"]),ne=0;function a(n,e){try{return n==null?void 0:Reflect.get(Object(n),e)}catch{return}}function w(n){try{return String(n)}catch{return"[unavailable]"}}function ie(n,e){return w(n).slice(0,e)}function S(){try{return performance.now()}catch{return Date.now()}}function z(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${(++ne).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function P(n,e){try{if(e?.aborted)return!0}catch{}return a(n,"name")==="AbortError"||a(n,"code")===20}function $(n){if(n==null)return{message:"Unknown error"};let e=a(n,"message"),t=a(n,"name"),r=a(n,"stack");return{message:e==null?w(n):w(e),...t==null?{}:{name:w(t)},...r==null?{}:{stack:w(r)}}}function C(n){return new TextEncoder().encode(n).length}function T(n,e,t,r){return typeof n=="number"&&Number.isFinite(n)?Math.min(t,Math.max(e,Math.floor(n))):r}var q=class extends Error{constructor(t){super(`Collector responded ${t}`);d(this,"status",t)}},B=class extends Error{},j=class extends Error{},I=class{constructor(e){d(this,"active");d(this,"endpoint");d(this,"options");d(this,"networkCaptureEnabled");d(this,"networkBreadcrumbCaptureEnabled");d(this,"navigationCaptureEnabled");d(this,"captureErrorCause");d(this,"transportTimeoutMs");d(this,"startedAt",S());d(this,"viewId",z());d(this,"seenErrors",new WeakSet);d(this,"queue",[]);d(this,"breadcrumbs",[]);d(this,"maxQueueSize");d(this,"maxEventsPerMinute");d(this,"admittedAt",[]);d(this,"cancelWaits",new Set);d(this,"controllers",new Set);d(this,"destroySignal");d(this,"resolveDestroy");d(this,"interval");d(this,"flushing");d(this,"sequence",0);d(this,"inFlight",0);d(this,"sent",0);d(this,"dropped",0);d(this,"filtered",0);d(this,"deduplicated",0);d(this,"droppedByReason",{rateLimit:0,queueOverflow:0,payloadTooLarge:0,processingError:0,deliveryError:0,destroyed:0});d(this,"destroyed",!1);d(this,"lastAdmissionClock");d(this,"onError",e=>{try{let t=a(e,"filename"),r=a(e,"lineno"),i=a(e,"colno"),o={};typeof t=="string"&&t.trim()&&(o.filename=this.cleanUrl(t)),typeof r=="number"&&Number.isFinite(r)&&r>0&&(o.lineno=r),typeof i=="number"&&Number.isFinite(i)&&i>0&&(o.colno=i),this.captureException(a(e,"error")??a(e,"message")??"Script error",{type:"javascript",...Object.keys(o).length?{context:o}:{}})}catch{this.recordDrop("processingError")}});d(this,"onRejection",e=>{this.captureException(e.reason,{type:"promise"})});d(this,"onVisibility",()=>{document.visibilityState==="hidden"&&this.tryBeacon()});this.options=e,this.active=e.enabled!==!1&&typeof window<"u"&&typeof document<"u";let t=!e.transport||!!e.endpoint;if(this.networkCaptureEnabled=e.captureNetwork!==!1&&t,this.networkBreadcrumbCaptureEnabled=e.captureNetworkBreadcrumbs===!0&&t,this.navigationCaptureEnabled=e.captureNavigation===!0,this.captureErrorCause=e.captureErrorCause===!0,this.maxQueueSize=T(e.maxQueueSize,1,100,50),this.maxEventsPerMinute=typeof e.maxEventsPerMinute=="number"&&Number.isFinite(e.maxEventsPerMinute)?T(e.maxEventsPerMinute,1,1e3,1):void 0,this.transportTimeoutMs=T(e.transportTimeoutMs,250,6e4,5e3),this.destroySignal=new Promise(r=>{this.resolveDestroy=r}),!!this.active){if(!e.project||typeof e.project!="string")throw new Error("project is required");if(!e.transport&&!e.endpoint)throw new Error("endpoint or transport is required");this.endpoint=e.endpoint?this.absoluteUrl(e.endpoint):void 0,window.addEventListener("error",this.onError),window.addEventListener("unhandledrejection",this.onRejection),document.addEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ce(this),e.captureConsole===!0&&pe(this),this.navigationCaptureEnabled&&oe(this),this.interval=setInterval(()=>{this.flush()},T(e.flushIntervalMs,10,6e4,1e4))}}captureException(e,t={}){if(!(!this.active||this.destroyed||P(e)))try{if(e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.has(e)){this.deduplicated++;return}let r=this.exceptionFields(e),i=F.has(t.type)?t.type:"manual",o=this.makeEvent(i,r.message,{name:r.name,stack:r.stack,componentStack:t.componentStack,context:t.context});this.enqueue(o)&&e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.add(e)}catch(r){(r instanceof B||r instanceof j)&&this.recordDrop("processingError")}}reportNetwork(e,t,r,i,o,u=!0){if(this.destroyed||!this.active||this.isCollectorUrl(t)||P(o))return;let l=this.networkCaptureEnabled&&u;if(l&&r!==void 0)try{l=this.options.shouldCaptureHttp?this.options.shouldCaptureHttp(r,t,e):r>=500}catch{this.recordDrop("processingError");return}if(this.networkBreadcrumbCaptureEnabled)try{let s=this.cleanBreadcrumbUrl(t);if(s.url){let c={method:this.cleanNetworkBreadcrumbMethod(e),url:s.url,durationMs:T(i,0,36e5,0)};r!==void 0&&Number.isInteger(r)&&r>=0&&r<=599&&(c.status=r),this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:r===void 0?"network":"http",message:r===void 0?"Network failure":"HTTP response",data:c}),this.boundBreadcrumbs(this.breadcrumbs)}else if(l&&!s.safeForError){this.recordDrop("processingError");return}}catch{l&&this.recordDrop("processingError");return}if(l)try{let s={method:ie(e||"GET",16).toUpperCase(),url:t,status:r,durationMs:i},c=o===void 0?void 0:$(o),p=this.makeEvent(r===void 0?"network":"http",r===void 0?c?.message||"Network request failed":`HTTP ${r}`,{name:c?.name,network:s});this.enqueue(p)}catch{this.recordDrop("processingError")}}reportZeroStatusCompletion(e,t,r){this.networkBreadcrumbCaptureEnabled&&this.reportNetwork(e,t,0,r,void 0,!1)}captureConsole(e){if(!(!this.active||this.destroyed))try{let t=e.map(w).join(" "),r;for(let i of e){let o=!1;try{o=i instanceof Error}catch{}if(o){r=this.exceptionFields(i);break}}this.enqueue(this.makeEvent("console",t,{name:r?.name,stack:r?.stack}))}catch{this.recordDrop("processingError")}}addBreadcrumb(e){if(!(!this.active||this.destroyed))try{let t=this.cleanBreadcrumb(e,new Date().toISOString());if(!t)return;this.breadcrumbs.push(t),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}reportNavigation(e,t,r){if(!(!this.active||this.destroyed||!this.navigationCaptureEnabled))try{let i=this.cleanBreadcrumbUrl(e).url,o=this.cleanBreadcrumbUrl(t).url;if(!i||!o||i===o)return;this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:i,to:o,trigger:r}}),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}clearBreadcrumbs(){!this.active||this.destroyed||(this.breadcrumbs.length=0)}flush(){return!this.active||this.destroyed?Promise.resolve():this.flushing?this.flushing:(this.flushing=this.drain().finally(()=>{this.flushing=void 0}),this.flushing)}destroy(){if(!this.destroyed){this.destroyed=!0,this.interval&&clearInterval(this.interval),this.active&&(window.removeEventListener("error",this.onError),window.removeEventListener("unhandledrejection",this.onRejection),document.removeEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ue(this),this.options.captureConsole===!0&&he(this),this.navigationCaptureEnabled&&se(this)),this.recordDrop("destroyed",this.queue.length+this.inFlight),this.queue.length=0,this.breadcrumbs.length=0,this.admittedAt.length=0,this.lastAdmissionClock=void 0;for(let e of this.cancelWaits)e();for(let e of this.controllers)e.abort();this.resolveDestroy(V)}}getStats(){return{queued:this.queue.length,sent:this.sent,dropped:this.dropped}}getDiagnostics(){return{...this.getStats(),inFlight:this.destroyed?0:this.inFlight,filtered:this.filtered,deduplicated:this.deduplicated,droppedByReason:{...this.droppedByReason}}}recordDrop(e,t=1){this.dropped+=t,this.droppedByReason[e]+=t}absoluteUrl(e){try{return new URL(e,window.location.href).href}catch{return e}}isCollectorUrl(e){if(!this.endpoint)return!1;try{let t=new URL(e,window.location.href),r=new URL(this.endpoint,window.location.href);return t.origin===r.origin&&t.pathname===r.pathname}catch{return e===this.endpoint}}cleanUrl(e){let t=w(e);if(this.options.sanitizeUrl){try{t=this.options.sanitizeUrl(t)}catch{throw new B("URL sanitizer failed")}if(typeof t!="string"||!t)throw new B("URL sanitizer returned no URL")}try{let r=new URL(t,window.location.href);return r.protocol!=="http:"&&r.protocol!=="https:"?"[unsupported URL]":(r.username="",r.password="",r.search="",r.hash="",this.cleanText(r.href,1024,!1))}catch{return this.cleanText(t,1024,!1).split(/[?#]/,1)[0]}}cleanBreadcrumbUrl(e){let t=this.cleanUrl(e);if(t==="[unsupported URL]")return{safeForError:!0};try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash?{safeForError:!1}:{url:t.slice(0,k.dataString),safeForError:!0}}catch{return{safeForError:!1}}}cleanNetworkBreadcrumbMethod(e){let t=w(e||"GET").trim().toUpperCase();return/^[A-Z0-9!#$%&'*+.^_`|~-]{1,16}$/.test(t)?t:"GET"}cleanText(e,t,r=!0){let i=w(e);return r&&(i=i.replace(/https?:\/\/[^\s<>"'()[\]]+/gi,o=>this.cleanUrl(o)),i=i.replace(/(^|[\s"'(\[=])((?:\/(?!\/)|\.{1,2}\/)[^\s<>"'()[\]?#]*[?#][^\s<>"'()[\]]+|[a-z][\w.-]*(?:\/[^\s<>"'()[\]?#]*)?(?:\?[a-z0-9_.-]+=[^\s<>"'()[\]]+|#[^\s<>"'()[\]]+)|\?[a-z0-9_.-]+=[^\s<>"'()[\]]+)/gi,(o,u,l)=>{let s=/[.,;!]+$/.exec(l)?.[0]??"",c=l.slice(0,l.length-s.length),p=this.options.sanitizeUrl?this.cleanUrl(c):c.startsWith("?")?"[redacted query]":this.cleanText(c.split(/[?#]/,1)[0],1024,!1);return`${u}${p}${s}`})),i.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+/gi,"Bearer [REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]").slice(0,t)}exceptionFields(e){let t=$(e);if(!this.captureErrorCause||e===null||typeof e!="object"&&typeof e!="function")return t;let r=new WeakSet([e]),i=[],o=e;for(let l=0;l<4;l++){let s=a(o,"cause");if(s===null||typeof s!="object"&&typeof s!="function"||r.has(s))break;r.add(s);let c=a(s,"message"),p=a(s,"stack");if(typeof c!="string"&&typeof p!="string")break;let h=a(s,"name"),f=this.cleanText(typeof h=="string"?h:"Error",100),g=typeof c=="string"?this.cleanText(c,256):"",m=typeof p=="string"?this.cleanText(p,480):"";i.push(`Caused by: ${f}: ${g}${m?`
|
|
2
|
-
${
|
|
3
|
-
${
|
|
4
|
-
`)}`}}cleanContext(e){if(!e||typeof e!="object")return;let t={},r;try{r=Object.keys(e)}catch{return}for(let i of r){if(Object.keys(t).length>=12)break;if(_.test(i))continue;let o=a(e,i),u=this.cleanText(i,80);typeof o=="string"?t[u]=this.cleanText(o,500):(typeof o=="number"&&Number.isFinite(o)||typeof o=="boolean"||o===null)&&(t[u]=o)}return Object.keys(t).length?t:void 0}cleanBreadcrumb(e,t){if(!e||typeof e!="object")return;let r=t??a(e,"occurredAt");if(typeof r!="string")return;try{if(new Date(r).toISOString()!==r)return}catch{return}let i=a(e,"category"),o=a(e,"message");if(i!==void 0&&typeof i!="string"||typeof o!="string")return;let u=this.cleanText(i??(t?"manual":""),k.category),l=this.cleanText(o,k.message);if(!u.trim()||!l.trim())return;let s=a(e,"data"),c={};if(s&&typeof s=="object"){let p;try{p=Object.keys(s)}catch{p=[]}for(let h of p){if(Object.keys(c).length>=k.dataKeys)break;if(_.test(h))continue;let f=this.cleanText(h,k.dataKey),g=a(s,h);typeof g=="string"?c[f]=this.cleanText(g,k.dataString):(typeof g=="number"&&Number.isFinite(g)||typeof g=="boolean"||g===null)&&(c[f]=g)}}return{occurredAt:r,category:u,message:l,...Object.keys(c).length?{data:c}:{}}}boundBreadcrumbs(e){for(;e.length>k.count||C(JSON.stringify(e))>k.bytes;)e.shift()}cleanBreadcrumbTrail(e){let t;try{if(!Array.isArray(e))return;t=e.length}catch{return}if(!Number.isSafeInteger(t)||t<0)return;let r=[];for(let i=Math.max(0,t-k.count);i<t;i++){let o=this.cleanBreadcrumb(a(e,i));o&&(r.push(o),this.boundBreadcrumbs(r))}return r.length?r:void 0}cleanNetwork(e){if(!e||typeof e!="object")return;let t=a(e,"status"),r=typeof t=="number"&&Number.isInteger(t)&&t>=100&&t<=599?t:void 0;return{method:this.cleanText(a(e,"method")??"GET",16).toUpperCase(),url:this.cleanUrl(a(e,"url")??""),...r===void 0?{}:{status:r},durationMs:T(a(e,"durationMs"),0,36e5,0)}}makeEvent(e,t,r={}){let i=a(navigator,"userAgent"),o=this.cleanContext(r.context),u;try{u=this.options.getContext?.()}catch{throw new j("Context resolver failed")}let l=this.cleanContext(u),s=this.cleanContext(this.options.context),c=o;if(l||s){c={...o};for(let h of[l,s])if(h)for(let f of Object.keys(h)){if(Object.keys(c).length>=12)break;Object.prototype.hasOwnProperty.call(c,f)||(c[f]=h[f])}}let p=this.cleanNetwork(r.network);return{schemaVersion:1,eventId:z(),project:this.cleanText(this.options.project,80),environment:this.cleanText(this.options.environment??"development",80),release:this.cleanText(this.options.release??"unknown",120),sdkVersion:"0.1.21",occurredAt:new Date().toISOString(),viewId:this.viewId,sequence:++this.sequence,elapsedMs:T(S()-this.startedAt,0,36e5,0),type:e,message:this.cleanText(t,1024),...r.name===void 0?{}:{name:this.cleanText(r.name,100)},...r.stack===void 0?{}:{stack:this.cleanText(r.stack,4096)},...r.componentStack===void 0?{}:{componentStack:this.cleanText(r.componentStack,2048)},page:this.cleanUrl(window.location.href),runtime:H.has(this.options.runtime)?this.options.runtime:"browser",...typeof i=="string"?{browser:this.cleanText(i,300)}:{},...c?{context:c}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(h=>({...h,...h.data?{data:{...h.data}}:{}}))}:{},...p?{network:p}:{}}}sanitizeReplacement(e,t){let r=a(e,"type"),i=a(e,"runtime"),o=a(e,"name"),u=a(e,"stack"),l=a(e,"componentStack"),s=a(e,"browser"),c=this.cleanContext(a(e,"context")),p=this.cleanBreadcrumbTrail(a(e,"breadcrumbs")),h=this.cleanNetwork(a(e,"network"));return{...t,type:F.has(r)?r:t.type,message:this.cleanText(a(e,"message")??t.message,1024),...o===void 0?{name:t.name}:{name:this.cleanText(o,100)},...u===void 0?{stack:void 0}:{stack:this.cleanText(u,4096)},...l===void 0?{componentStack:t.componentStack}:{componentStack:this.cleanText(l,2048)},page:this.cleanUrl(a(e,"page")??t.page),runtime:H.has(i)?i:t.runtime,...s===void 0?{browser:t.browser}:{browser:this.cleanText(s,300)},...c?{context:c}:{context:void 0},...p?{breadcrumbs:p}:{breadcrumbs:void 0},...h?{network:h}:{network:void 0}}}admissionTime(){let e=S(),t=Number.isFinite(e)?Math.max(0,e,this.lastAdmissionClock??0):this.lastAdmissionClock??0;for(this.lastAdmissionClock=t;this.admittedAt.length&&t-this.admittedAt[0]>=6e4;)this.admittedAt.shift();return this.admittedAt.length<this.maxEventsPerMinute?t:void 0}enqueue(e){if(this.destroyed)return!1;if(this.maxEventsPerMinute!==void 0&&this.admissionTime()===void 0)return this.recordDrop("rateLimit"),!1;let t=e;if(this.options.beforeSend)try{let i={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(u=>({...u,data:u.data&&{...u.data}})),network:e.network&&{...e.network}},o=this.options.beforeSend(i);if(o===!1||o===null)return this.filtered++,!1;t=this.sanitizeReplacement(o===void 0?i:o,e)}catch{return this.recordDrop("processingError"),!1}if(C(JSON.stringify(t))>U)return this.recordDrop("payloadTooLarge"),!1;let r=this.maxEventsPerMinute===void 0?void 0:this.admissionTime();return this.maxEventsPerMinute!==void 0&&r===void 0?(this.recordDrop("rateLimit"),!1):(this.queue.length>=this.maxQueueSize&&(this.queue.shift(),this.recordDrop("queueOverflow")),this.queue.push(t),r!==void 0&&this.admittedAt.push(r),this.queue.length>=this.maxQueueSize&&this.flush(),!0)}takeBatch(e=ee,t=U){let r=[],i=C('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&r.length<e;){let o=this.queue[0],u=C(JSON.stringify(o))+(r.length?1:0);if(r.length&&i+u>t)break;if(!r.length&&i+u>t){this.queue.shift(),this.recordDrop("payloadTooLarge");continue}r.push(this.queue.shift()),i+=u}return{schemaVersion:1,events:r}}async drain(){for(;!this.destroyed&&this.queue.length;){let e=this.takeBatch();if(e.events.length){this.inFlight+=e.events.length;try{await this.sendWithRetry(e)}finally{this.inFlight-=e.events.length}}}}async sendWithRetry(e){for(let t=0;t<=M.length&&!this.destroyed;t++){let r=new AbortController;this.controllers.add(r);let i,o=new Promise((l,s)=>{i=setTimeout(()=>{r.abort(),s(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),u;try{if(await Promise.race([this.send(e,r.signal),o,this.destroySignal])===V||this.destroyed)return;this.sent+=e.events.length;return}catch(l){if(this.destroyed)return;let s=a(l,"status");if(!(typeof s!="number"||s===429||s>=500)||t===M.length)break;u=M[t]}finally{i&&clearTimeout(i),this.controllers.delete(r)}u!==void 0&&await this.wait(u)}this.destroyed||this.recordDrop("deliveryError",e.events.length)}async send(e,t){if(this.options.transport){await this.options.transport(e,{signal:t});return}let r=await window.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),credentials:"omit",signal:t});if(!r.ok)throw new q(r.status)}wait(e){return new Promise(t=>{let r=()=>{clearTimeout(i),this.cancelWaits.delete(r),t()},i=setTimeout(r,e);this.cancelWaits.add(r)})}tryBeacon(){if(!(this.destroyed||this.options.transport||!this.endpoint||!this.queue.length))try{let e=new URL(this.endpoint);if(e.origin!==window.location.origin||e.search||e.hash||e.username||e.password||typeof navigator.sendBeacon!="function")return;let t=this.queue.slice(0,te);for(;t.length>0;){let i=JSON.stringify({schemaVersion:1,events:t});if(C(i)<=re){navigator.sendBeacon(this.endpoint,new Blob([i],{type:"application/json"}))&&(this.queue.splice(0,t.length),this.sent+=t.length);return}t.pop()}}catch{}}},V=Symbol("destroyed"),L,A,N;function oe(n){N||(N=ae()),N?.clients.add(n)}function se(n){let e=N;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),N=void 0))}function X(n,e){let t=new Set,r=Object.getPrototypeOf(n);for(;r&&!t.has(r);){t.add(r);let i=Object.getOwnPropertyDescriptor(r,e);if(i)return i;r=Object.getPrototypeOf(r)}}function ae(){let n,e,t,r,i,o,u,l;try{if(n=window.history,e=window.location.href,i=Object.getOwnPropertyDescriptor(n,"pushState"),o=Object.getOwnPropertyDescriptor(n,"replaceState"),u=i?void 0:X(n,"pushState"),l=o?void 0:X(n,"replaceState"),i&&!("value"in i)||o&&!("value"in o)||!i&&(!u||!("value"in u)||u.writable!==!0)||!o&&(!l||!("value"in l)||l.writable!==!0)||(t=i?i.value:n.pushState,r=o?o.value:n.replaceState,typeof t!="function"||typeof r!="function"))return;let b=y=>y?y.configurable===!0||y.writable===!0:Object.isExtensible(n);if(!b(i)||!b(o))return}catch{return}let s=new Set,c=b=>{try{let y=window.location.href;if(y===e)return;let R=e;e=y;for(let v of s)try{v.reportNavigation(R,y,b)}catch{}}catch{}},p=function(...b){let y=Reflect.apply(t,this,b);return c("pushState"),y},h=function(...b){let y=Reflect.apply(r,this,b);return c("replaceState"),y},f=()=>{c("popstate")},g=()=>{c("hashchange")},m=(b,y,R)=>{try{let v=Object.getOwnPropertyDescriptor(n,b);if(!v||!("value"in v)||v.value!==y)return;R?Object.defineProperty(n,b,R):Reflect.deleteProperty(n,b)}catch{}},E=!1,x=!1;try{Object.defineProperty(n,"pushState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:p}),E=!0,Object.defineProperty(n,"replaceState",{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:o?.writable??!0,value:h}),x=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",g)}catch{try{window.removeEventListener("hashchange",g)}catch{}try{window.removeEventListener("popstate",f)}catch{}x&&m("replaceState",h,o),E&&m("pushState",p,i);return}return{clients:s,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",g)}catch{}m("pushState",p,i),m("replaceState",h,o)}}}function ce(n){L||(L=le()),L.clients.add(n)}function ue(n){let e=L;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),L=void 0))}function de(n,e){let t;if(typeof Request<"u"&&n!==null&&typeof n=="object")if(n instanceof Request)t=a(n,"url");else try{t=Object.getOwnPropertyDescriptor(Request.prototype,"url")?.get?.call(n)}catch{}let r=a(e,"signal");return{url:t??w(n),method:w(a(e,"method")??(t===void 0?void 0:a(n,"method"))??"GET"),signal:r===void 0?t===void 0?void 0:a(n,"signal"):r}}function le(){let n=new Set,e=window.fetch,t;typeof e=="function"&&(t=function(...p){if(!n.size)return Reflect.apply(e,this,p);let h=S(),f;try{f=de(p[0],p[1])}catch{f={url:"",method:"GET"}}let g;try{g=Reflect.apply(e,this,p)}catch(m){if(!P(m,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,S()-h,m);throw m}return g.then(m=>{try{let E=m.status;for(let x of n)x.reportNetwork(f.method,f.url,E,S()-h)}catch{}return m},m=>{if(!P(m,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,S()-h,m);throw m})},window.fetch=t);let r=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,i=r?.open,o=r?.send,u=new WeakMap,l=new WeakMap,s,c;return r&&i&&o&&(s=(function(...p){let h=Reflect.apply(i,this,p);l.get(this)?.();try{u.set(this,{method:w(p[0]),url:w(p[1])})}catch{}return h}),c=function(...p){if(!n.size)return Reflect.apply(o,this,p);let h=u.get(this);if(!h)return Reflect.apply(o,this,p);let f=S(),g=!1,m=!1,E=!1,x=()=>{g=!0},b=()=>{m=!0},y=()=>{this.removeEventListener("abort",x),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",R),l.get(this)===y&&l.delete(this)},R=()=>{if(E=!0,y(),!g)try{let v=this.status;if(v===0&&!m){for(let O of n)O.reportZeroStatusCompletion(h.method,h.url,S()-f);return}for(let O of n)O.reportNetwork(h.method,h.url,v===0?void 0:v,S()-f)}catch{}};try{this.addEventListener("abort",x),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",R)}catch{return y(),Reflect.apply(o,this,p)}try{let v=Reflect.apply(o,this,p);return E||l.set(this,y),v}catch(v){throw y(),v}},r.open=s,r.send=c),{clients:n,cleanup(){t&&window.fetch===t&&(window.fetch=e),r&&s&&r.open===s&&(r.open=i),r&&c&&r.send===c&&(r.send=o)}}}function pe(n){A||(A=fe()),A.clients.add(n)}function he(n){let e=A;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),A=void 0))}function fe(){let n=new Set,e=console.error,t=function(...r){try{return Reflect.apply(e,this,r)}finally{for(let i of n)i.captureConsole(r)}};return console.error=t,{clients:n,cleanup(){console.error===t&&(console.error=e)}}}function me(n){return new I(n)}
|
|
1
|
+
"use strict";var P=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(o,e,t)=>e in o?P(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Z=(o,e)=>{for(var t in e)P(o,t,{get:e[t],enumerable:!0})},G=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!J.call(o,n)&&n!==t&&P(o,n,{get:()=>e[n],enumerable:!(r=W(e,n))||r.enumerable});return o};var Q=o=>G(P({},"__esModule",{value:!0}),o);var h=(o,e,t)=>Y(o,typeof e!="symbol"?e+"":e,t);var ge={};Z(ge,{init:()=>me});module.exports=Q(ge);var k={count:20,bytes:12e3,category:40,message:256,dataKeys:6,dataKey:80,dataString:200};var ee=20,U=48e3,te=10,re=24e3,M=[250,500],_=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,F=new Set(["javascript","promise","react","console","http","network","manual","resource"]),H=new Set(["browser","webview-ios","webview-android","unknown"]),ne=0;function s(o,e){try{return o==null?void 0:Reflect.get(Object(o),e)}catch{return}}function w(o){try{return String(o)}catch{return"[unavailable]"}}function oe(o,e){return w(o).slice(0,e)}function S(){try{return performance.now()}catch{return Date.now()}}function z(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${(++ne).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function j(o,e){try{if(e?.aborted)return!0}catch{}return s(o,"name")==="AbortError"||s(o,"code")===20}function $(o){if(o==null)return{message:"Unknown error"};let e=s(o,"message"),t=s(o,"name"),r=s(o,"stack");return{message:e==null?w(o):w(e),...t==null?{}:{name:w(t)},...r==null?{}:{stack:w(r)}}}function C(o){return new TextEncoder().encode(o).length}function T(o,e,t,r){return typeof o=="number"&&Number.isFinite(o)?Math.min(t,Math.max(e,Math.floor(o))):r}var I=class extends Error{constructor(t){super(`Collector responded ${t}`);h(this,"status",t)}},R=class extends Error{},L=class extends Error{},q=class{constructor(e){h(this,"active");h(this,"endpoint");h(this,"options");h(this,"networkCaptureEnabled");h(this,"networkBreadcrumbCaptureEnabled");h(this,"navigationCaptureEnabled");h(this,"captureErrorCause");h(this,"resourceCaptureEnabled");h(this,"transportTimeoutMs");h(this,"startedAt",S());h(this,"viewId",z());h(this,"seenErrors",new WeakSet);h(this,"queue",[]);h(this,"breadcrumbs",[]);h(this,"recordingBreadcrumb",!1);h(this,"maxQueueSize");h(this,"maxEventsPerMinute");h(this,"admittedAt",[]);h(this,"cancelWaits",new Set);h(this,"controllers",new Set);h(this,"destroySignal");h(this,"resolveDestroy");h(this,"interval");h(this,"flushing");h(this,"sequence",0);h(this,"inFlight",0);h(this,"sent",0);h(this,"dropped",0);h(this,"filtered",0);h(this,"deduplicated",0);h(this,"droppedByReason",{rateLimit:0,queueOverflow:0,payloadTooLarge:0,processingError:0,deliveryError:0,destroyed:0});h(this,"destroyed",!1);h(this,"lastAdmissionClock");h(this,"onError",e=>{try{if(!(s(e,"target")instanceof Window))return;let t=s(e,"filename"),r=s(e,"lineno"),n=s(e,"colno"),i={};typeof t=="string"&&t.trim()&&(i.filename=this.cleanUrl(t)),typeof r=="number"&&Number.isFinite(r)&&r>0&&(i.lineno=r),typeof n=="number"&&Number.isFinite(n)&&n>0&&(i.colno=n),this.captureException(s(e,"error")??s(e,"message")??"Script error",{type:"javascript",...Object.keys(i).length?{context:i}:{}})}catch{this.recordDrop("processingError")}});h(this,"onResourceError",e=>{if(!(this.destroyed||!this.active))try{let t=s(e,"target");if(s(t,"ownerDocument")!==document||!document.contains(t)||s(t,"namespaceURI")!=="http://www.w3.org/1999/xhtml")return;let r=s(t,"localName");if(r!=="script"&&r!=="link"&&r!=="img")return;let n=s(t,"getAttribute");if(typeof n!="function")return;let i=c=>{try{return Reflect.apply(n,t,[c])}catch{return}},d=r,l;if(d==="script"){let c=i("src");if(typeof c!="string"||!c.trim())return;l=s(t,"src")}else if(d==="link"){let c=s(t,"rel");if(typeof c!="string"||!c.split(/\s+/).some(m=>m.toLowerCase()==="stylesheet"))return;let f=i("href");if(typeof f!="string"||!f.trim())return;l=s(t,"href")}else{let c=s(t,"currentSrc");if(typeof c=="string"&&c.trim())l=c;else{let f=i("src");if(typeof f!="string"||!f.trim())return;l=s(t,"src")}}if(typeof l!="string"||!l.trim())return;let a;try{a=new URL(l,window.location.href)}catch{return}if(a.protocol!=="http:"&&a.protocol!=="https:"||this.isCollectorUrl(a.href))return;let u=this.cleanUrl(a.href),p;try{p=new URL(u)}catch{throw new R("Invalid resource URL")}if(p.protocol!=="http:"&&p.protocol!=="https:"||p.username||p.password||p.search||p.hash)throw new R("Unsafe resource URL");this.enqueue(this.makeEvent("resource",`Failed to load ${d} resource`,{name:"ResourceLoadError",context:{resourceTag:d,resourceUrl:u}}))}catch(t){(t instanceof R||t instanceof L)&&this.recordDrop("processingError")}});h(this,"onRejection",e=>{this.captureException(e.reason,{type:"promise"})});h(this,"onVisibility",()=>{document.visibilityState==="hidden"&&this.tryBeacon()});this.options=e,this.active=e.enabled!==!1&&typeof window<"u"&&typeof document<"u";let t=!e.transport||!!e.endpoint;if(this.networkCaptureEnabled=e.captureNetwork!==!1&&t,this.networkBreadcrumbCaptureEnabled=e.captureNetworkBreadcrumbs===!0&&t,this.navigationCaptureEnabled=e.captureNavigation===!0,this.captureErrorCause=e.captureErrorCause===!0,this.resourceCaptureEnabled=e.captureResourceErrors===!0,this.maxQueueSize=T(e.maxQueueSize,1,100,50),this.maxEventsPerMinute=typeof e.maxEventsPerMinute=="number"&&Number.isFinite(e.maxEventsPerMinute)?T(e.maxEventsPerMinute,1,1e3,1):void 0,this.transportTimeoutMs=T(e.transportTimeoutMs,250,6e4,5e3),this.destroySignal=new Promise(r=>{this.resolveDestroy=r}),!!this.active){if(!e.project||typeof e.project!="string")throw new Error("project is required");if(!e.transport&&!e.endpoint)throw new Error("endpoint or transport is required");this.endpoint=e.endpoint?this.absoluteUrl(e.endpoint):void 0,window.addEventListener("error",this.onError),this.resourceCaptureEnabled&&window.addEventListener("error",this.onResourceError,!0),window.addEventListener("unhandledrejection",this.onRejection),document.addEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ce(this),e.captureConsole===!0&&pe(this),this.navigationCaptureEnabled&&ie(this),this.interval=setInterval(()=>{this.flush()},T(e.flushIntervalMs,10,6e4,1e4))}}captureException(e,t={}){if(!(!this.active||this.destroyed||j(e)))try{if(e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.has(e)){this.deduplicated++;return}let r=this.exceptionFields(e),n=F.has(t.type)?t.type:"manual",i=this.makeEvent(n,r.message,{name:r.name,stack:r.stack,componentStack:t.componentStack,context:t.context});this.enqueue(i)&&e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.add(e)}catch(r){(r instanceof R||r instanceof L)&&this.recordDrop("processingError")}}reportNetwork(e,t,r,n,i,d=!0){if(this.destroyed||!this.active||this.isCollectorUrl(t)||j(i))return;let l=this.networkCaptureEnabled&&d;if(l&&r!==void 0)try{l=this.options.shouldCaptureHttp?this.options.shouldCaptureHttp(r,t,e):r>=500}catch{this.recordDrop("processingError");return}if(this.networkBreadcrumbCaptureEnabled)try{let a=this.cleanBreadcrumbUrl(t);if(a.url){let u={method:this.cleanNetworkBreadcrumbMethod(e),url:a.url,durationMs:T(n,0,36e5,0)};r!==void 0&&Number.isInteger(r)&&r>=0&&r<=599&&(u.status=r),this.appendBreadcrumb({occurredAt:new Date().toISOString(),category:r===void 0?"network":"http",message:r===void 0?"Network failure":"HTTP response",data:u})}else if(l&&!a.safeForError){this.recordDrop("processingError");return}}catch{l&&this.recordDrop("processingError");return}if(l)try{let a={method:oe(e||"GET",16).toUpperCase(),url:t,status:r,durationMs:n},u=i===void 0?void 0:$(i),p=this.makeEvent(r===void 0?"network":"http",r===void 0?u?.message||"Network request failed":`HTTP ${r}`,{name:u?.name,network:a});this.enqueue(p)}catch{this.recordDrop("processingError")}}reportZeroStatusCompletion(e,t,r){this.networkBreadcrumbCaptureEnabled&&this.reportNetwork(e,t,0,r,void 0,!1)}captureConsole(e){if(!(!this.active||this.destroyed))try{let t=e.map(w).join(" "),r;for(let n of e){let i=!1;try{i=n instanceof Error}catch{}if(i){r=this.exceptionFields(n);break}}this.enqueue(this.makeEvent("console",t,{name:r?.name,stack:r?.stack}))}catch{this.recordDrop("processingError")}}addBreadcrumb(e){if(!(!this.active||this.destroyed||this.recordingBreadcrumb))try{let t=this.cleanBreadcrumb(e,new Date().toISOString());if(!t)return;this.appendBreadcrumb(t)}catch{}}appendBreadcrumb(e){if(!(this.recordingBreadcrumb||this.destroyed)){if(!this.options.beforeBreadcrumb){this.breadcrumbs.push(e),this.boundBreadcrumbs(this.breadcrumbs);return}this.recordingBreadcrumb=!0;try{let t={...e,...e.data?{data:{...e.data}}:{}},r=this.options.beforeBreadcrumb(t);if(r===!1||r===null)return;let n=this.cleanBreadcrumb(r===void 0?t:r,e.occurredAt);if(!n||this.destroyed)return;this.breadcrumbs.push(n),this.boundBreadcrumbs(this.breadcrumbs)}catch{}finally{this.recordingBreadcrumb=!1}}}reportNavigation(e,t,r){if(!(!this.active||this.destroyed||!this.navigationCaptureEnabled))try{let n=this.cleanBreadcrumbUrl(e).url,i=this.cleanBreadcrumbUrl(t).url;if(!n||!i||n===i)return;this.appendBreadcrumb({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:n,to:i,trigger:r}})}catch{}}clearBreadcrumbs(){!this.active||this.destroyed||(this.breadcrumbs.length=0)}flush(){return!this.active||this.destroyed?Promise.resolve():this.flushing?this.flushing:(this.flushing=this.drain().finally(()=>{this.flushing=void 0}),this.flushing)}destroy(){if(!this.destroyed){this.destroyed=!0,this.interval&&clearInterval(this.interval),this.active&&(window.removeEventListener("error",this.onError),this.resourceCaptureEnabled&&window.removeEventListener("error",this.onResourceError,!0),window.removeEventListener("unhandledrejection",this.onRejection),document.removeEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ue(this),this.options.captureConsole===!0&&he(this),this.navigationCaptureEnabled&&se(this)),this.recordDrop("destroyed",this.queue.length+this.inFlight),this.queue.length=0,this.breadcrumbs.length=0,this.admittedAt.length=0,this.lastAdmissionClock=void 0;for(let e of this.cancelWaits)e();for(let e of this.controllers)e.abort();this.resolveDestroy(V)}}getStats(){return{queued:this.queue.length,sent:this.sent,dropped:this.dropped}}getDiagnostics(){return{...this.getStats(),inFlight:this.destroyed?0:this.inFlight,filtered:this.filtered,deduplicated:this.deduplicated,droppedByReason:{...this.droppedByReason}}}recordDrop(e,t=1){this.dropped+=t,this.droppedByReason[e]+=t}absoluteUrl(e){try{return new URL(e,window.location.href).href}catch{return e}}isCollectorUrl(e){if(!this.endpoint)return!1;try{let t=new URL(e,window.location.href),r=new URL(this.endpoint,window.location.href);return t.origin===r.origin&&t.pathname===r.pathname}catch{return e===this.endpoint}}cleanUrl(e){let t=w(e);if(this.options.sanitizeUrl){try{t=this.options.sanitizeUrl(t)}catch{throw new R("URL sanitizer failed")}if(typeof t!="string"||!t)throw new R("URL sanitizer returned no URL")}try{let r=new URL(t,window.location.href);return r.protocol!=="http:"&&r.protocol!=="https:"?"[unsupported URL]":(r.username="",r.password="",r.search="",r.hash="",this.cleanText(r.href,1024,!1))}catch{return this.cleanText(t,1024,!1).split(/[?#]/,1)[0]}}cleanBreadcrumbUrl(e){let t=this.cleanUrl(e);if(t==="[unsupported URL]")return{safeForError:!0};try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash?{safeForError:!1}:{url:t.slice(0,k.dataString),safeForError:!0}}catch{return{safeForError:!1}}}cleanNetworkBreadcrumbMethod(e){let t=w(e||"GET").trim().toUpperCase();return/^[A-Z0-9!#$%&'*+.^_`|~-]{1,16}$/.test(t)?t:"GET"}cleanText(e,t,r=!0){let n=w(e);return r&&(n=n.replace(/https?:\/\/[^\s<>"'()[\]]+/gi,i=>this.cleanUrl(i)),n=n.replace(/(^|[\s"'(\[=])((?:\/(?!\/)|\.{1,2}\/)[^\s<>"'()[\]?#]*[?#][^\s<>"'()[\]]+|[a-z][\w.-]*(?:\/[^\s<>"'()[\]?#]*)?(?:\?[a-z0-9_.-]+=[^\s<>"'()[\]]+|#[^\s<>"'()[\]]+)|\?[a-z0-9_.-]+=[^\s<>"'()[\]]+)/gi,(i,d,l)=>{let a=/[.,;!]+$/.exec(l)?.[0]??"",u=l.slice(0,l.length-a.length),p=this.options.sanitizeUrl?this.cleanUrl(u):u.startsWith("?")?"[redacted query]":this.cleanText(u.split(/[?#]/,1)[0],1024,!1);return`${d}${p}${a}`})),n.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+/gi,"Bearer [REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]").slice(0,t)}exceptionFields(e){let t=$(e);if(!this.captureErrorCause||e===null||typeof e!="object"&&typeof e!="function")return t;let r=new WeakSet([e]),n=[],i=e;for(let l=0;l<4;l++){let a=s(i,"cause");if(a===null||typeof a!="object"&&typeof a!="function"||r.has(a))break;r.add(a);let u=s(a,"message"),p=s(a,"stack");if(typeof u!="string"&&typeof p!="string")break;let c=s(a,"name"),f=this.cleanText(typeof c=="string"?c:"Error",100),m=typeof u=="string"?this.cleanText(u,256):"",g=typeof p=="string"?this.cleanText(p,480):"";n.push(`Caused by: ${f}: ${m}${g?`
|
|
2
|
+
${g}`:""}`.slice(0,480)),i=a}if(!n.length)return t;let d=t.stack===void 0?`${this.cleanText(t.name??"Error",100)}: ${this.cleanText(t.message,256)}`:this.cleanText(t.stack,2048);return{...t,stack:`${d}
|
|
3
|
+
${n.join(`
|
|
4
|
+
`)}`}}cleanContext(e){if(!e||typeof e!="object")return;let t={},r;try{r=Object.keys(e)}catch{return}for(let n of r){if(Object.keys(t).length>=12)break;if(_.test(n))continue;let i=s(e,n),d=this.cleanText(n,80);typeof i=="string"?t[d]=this.cleanText(i,500):(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"||i===null)&&(t[d]=i)}return Object.keys(t).length?t:void 0}cleanBreadcrumb(e,t){if(!e||typeof e!="object")return;let r=t??s(e,"occurredAt");if(typeof r!="string")return;try{if(new Date(r).toISOString()!==r)return}catch{return}let n=s(e,"category"),i=s(e,"message");if(n!==void 0&&typeof n!="string"||typeof i!="string")return;let d=this.cleanText(n??(t?"manual":""),k.category),l=this.cleanText(i,k.message);if(!d.trim()||!l.trim())return;let a=s(e,"data"),u={};if(a&&typeof a=="object"){let p;try{p=Object.keys(a)}catch{p=[]}for(let c of p){if(Object.keys(u).length>=k.dataKeys)break;if(_.test(c))continue;let f=this.cleanText(c,k.dataKey),m=s(a,c);typeof m=="string"?u[f]=this.cleanText(m,k.dataString):(typeof m=="number"&&Number.isFinite(m)||typeof m=="boolean"||m===null)&&(u[f]=m)}}return{occurredAt:r,category:d,message:l,...Object.keys(u).length?{data:u}:{}}}boundBreadcrumbs(e){for(;e.length>k.count||C(JSON.stringify(e))>k.bytes;)e.shift()}cleanBreadcrumbTrail(e){let t;try{if(!Array.isArray(e))return;t=e.length}catch{return}if(!Number.isSafeInteger(t)||t<0)return;let r=[];for(let n=Math.max(0,t-k.count);n<t;n++){let i=this.cleanBreadcrumb(s(e,n));i&&(r.push(i),this.boundBreadcrumbs(r))}return r.length?r:void 0}cleanNetwork(e){if(!e||typeof e!="object")return;let t=s(e,"status"),r=typeof t=="number"&&Number.isInteger(t)&&t>=100&&t<=599?t:void 0;return{method:this.cleanText(s(e,"method")??"GET",16).toUpperCase(),url:this.cleanUrl(s(e,"url")??""),...r===void 0?{}:{status:r},durationMs:T(s(e,"durationMs"),0,36e5,0)}}makeEvent(e,t,r={}){let n=s(navigator,"userAgent"),i=this.cleanContext(r.context),d;try{d=this.options.getContext?.()}catch{throw new L("Context resolver failed")}let l=this.cleanContext(d),a=this.cleanContext(this.options.context),u=i;if(l||a){u={...i};for(let c of[l,a])if(c)for(let f of Object.keys(c)){if(Object.keys(u).length>=12)break;Object.prototype.hasOwnProperty.call(u,f)||(u[f]=c[f])}}let p=this.cleanNetwork(r.network);return{schemaVersion:1,eventId:z(),project:this.cleanText(this.options.project,80),environment:this.cleanText(this.options.environment??"development",80),release:this.cleanText(this.options.release??"unknown",120),sdkVersion:"0.2.1",occurredAt:new Date().toISOString(),viewId:this.viewId,sequence:++this.sequence,elapsedMs:T(S()-this.startedAt,0,36e5,0),type:e,message:this.cleanText(t,1024),...r.name===void 0?{}:{name:this.cleanText(r.name,100)},...r.stack===void 0?{}:{stack:this.cleanText(r.stack,4096)},...r.componentStack===void 0?{}:{componentStack:this.cleanText(r.componentStack,2048)},page:this.cleanUrl(window.location.href),runtime:H.has(this.options.runtime)?this.options.runtime:"browser",...typeof n=="string"?{browser:this.cleanText(n,300)}:{},...u?{context:u}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(c=>({...c,...c.data?{data:{...c.data}}:{}}))}:{},...p?{network:p}:{}}}sanitizeReplacement(e,t){let r=s(e,"type"),n=s(e,"runtime"),i=s(e,"name"),d=s(e,"stack"),l=s(e,"componentStack"),a=s(e,"browser"),u=this.cleanContext(s(e,"context")),p=this.cleanBreadcrumbTrail(s(e,"breadcrumbs")),c=this.cleanNetwork(s(e,"network"));return{...t,type:F.has(r)?r:t.type,message:this.cleanText(s(e,"message")??t.message,1024),...i===void 0?{name:t.name}:{name:this.cleanText(i,100)},...d===void 0?{stack:void 0}:{stack:this.cleanText(d,4096)},...l===void 0?{componentStack:t.componentStack}:{componentStack:this.cleanText(l,2048)},page:this.cleanUrl(s(e,"page")??t.page),runtime:H.has(n)?n:t.runtime,...a===void 0?{browser:t.browser}:{browser:this.cleanText(a,300)},...u?{context:u}:{context:void 0},...p?{breadcrumbs:p}:{breadcrumbs:void 0},...c?{network:c}:{network:void 0}}}admissionTime(){let e=S(),t=Number.isFinite(e)?Math.max(0,e,this.lastAdmissionClock??0):this.lastAdmissionClock??0;for(this.lastAdmissionClock=t;this.admittedAt.length&&t-this.admittedAt[0]>=6e4;)this.admittedAt.shift();return this.admittedAt.length<this.maxEventsPerMinute?t:void 0}enqueue(e){if(this.destroyed)return!1;if(this.maxEventsPerMinute!==void 0&&this.admissionTime()===void 0)return this.recordDrop("rateLimit"),!1;let t=e;if(this.options.beforeSend)try{let n={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(d=>({...d,data:d.data&&{...d.data}})),network:e.network&&{...e.network}},i=this.options.beforeSend(n);if(i===!1||i===null)return this.filtered++,!1;t=this.sanitizeReplacement(i===void 0?n:i,e)}catch{return this.recordDrop("processingError"),!1}if(C(JSON.stringify(t))>U)return this.recordDrop("payloadTooLarge"),!1;let r=this.maxEventsPerMinute===void 0?void 0:this.admissionTime();return this.maxEventsPerMinute!==void 0&&r===void 0?(this.recordDrop("rateLimit"),!1):(this.queue.length>=this.maxQueueSize&&(this.queue.shift(),this.recordDrop("queueOverflow")),this.queue.push(t),r!==void 0&&this.admittedAt.push(r),this.queue.length>=this.maxQueueSize&&this.flush(),!0)}takeBatch(e=ee,t=U){let r=[],n=C('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&r.length<e;){let i=this.queue[0],d=C(JSON.stringify(i))+(r.length?1:0);if(r.length&&n+d>t)break;if(!r.length&&n+d>t){this.queue.shift(),this.recordDrop("payloadTooLarge");continue}r.push(this.queue.shift()),n+=d}return{schemaVersion:1,events:r}}async drain(){for(;!this.destroyed&&this.queue.length;){let e=this.takeBatch();if(e.events.length){this.inFlight+=e.events.length;try{await this.sendWithRetry(e)}finally{this.inFlight-=e.events.length}}}}async sendWithRetry(e){for(let t=0;t<=M.length&&!this.destroyed;t++){let r=new AbortController;this.controllers.add(r);let n,i=new Promise((l,a)=>{n=setTimeout(()=>{r.abort(),a(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),d;try{if(await Promise.race([this.send(e,r.signal),i,this.destroySignal])===V||this.destroyed)return;this.sent+=e.events.length;return}catch(l){if(this.destroyed)return;let a=s(l,"status");if(!(typeof a!="number"||a===429||a>=500)||t===M.length)break;d=M[t]}finally{n&&clearTimeout(n),this.controllers.delete(r)}d!==void 0&&await this.wait(d)}this.destroyed||this.recordDrop("deliveryError",e.events.length)}async send(e,t){if(this.options.transport){await this.options.transport(e,{signal:t});return}let r=await window.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),credentials:"omit",signal:t});if(!r.ok)throw new I(r.status)}wait(e){return new Promise(t=>{let r=()=>{clearTimeout(n),this.cancelWaits.delete(r),t()},n=setTimeout(r,e);this.cancelWaits.add(r)})}tryBeacon(){if(!(this.destroyed||this.options.transport||!this.endpoint||!this.queue.length))try{let e=new URL(this.endpoint);if(e.origin!==window.location.origin||e.search||e.hash||e.username||e.password||typeof navigator.sendBeacon!="function")return;let t=this.queue.slice(0,te);for(;t.length>0;){let n=JSON.stringify({schemaVersion:1,events:t});if(C(n)<=re){navigator.sendBeacon(this.endpoint,new Blob([n],{type:"application/json"}))&&(this.queue.splice(0,t.length),this.sent+=t.length);return}t.pop()}}catch{}}},V=Symbol("destroyed"),A,N,D;function ie(o){D||(D=ae()),D?.clients.add(o)}function se(o){let e=D;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),D=void 0))}function X(o,e){let t=new Set,r=Object.getPrototypeOf(o);for(;r&&!t.has(r);){t.add(r);let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=Object.getPrototypeOf(r)}}function ae(){let o,e,t,r,n,i,d,l;try{if(o=window.history,e=window.location.href,n=Object.getOwnPropertyDescriptor(o,"pushState"),i=Object.getOwnPropertyDescriptor(o,"replaceState"),d=n?void 0:X(o,"pushState"),l=i?void 0:X(o,"replaceState"),n&&!("value"in n)||i&&!("value"in i)||!n&&(!d||!("value"in d)||d.writable!==!0)||!i&&(!l||!("value"in l)||l.writable!==!0)||(t=n?n.value:o.pushState,r=i?i.value:o.replaceState,typeof t!="function"||typeof r!="function"))return;let b=y=>y?y.configurable===!0||y.writable===!0:Object.isExtensible(o);if(!b(n)||!b(i))return}catch{return}let a=new Set,u=b=>{try{let y=window.location.href;if(y===e)return;let B=e;e=y;for(let v of a)try{v.reportNavigation(B,y,b)}catch{}}catch{}},p=function(...b){let y=Reflect.apply(t,this,b);return u("pushState"),y},c=function(...b){let y=Reflect.apply(r,this,b);return u("replaceState"),y},f=()=>{u("popstate")},m=()=>{u("hashchange")},g=(b,y,B)=>{try{let v=Object.getOwnPropertyDescriptor(o,b);if(!v||!("value"in v)||v.value!==y)return;B?Object.defineProperty(o,b,B):Reflect.deleteProperty(o,b)}catch{}},E=!1,x=!1;try{Object.defineProperty(o,"pushState",{configurable:n?.configurable??!0,enumerable:n?.enumerable??!1,writable:n?.writable??!0,value:p}),E=!0,Object.defineProperty(o,"replaceState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:c}),x=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",m)}catch{try{window.removeEventListener("hashchange",m)}catch{}try{window.removeEventListener("popstate",f)}catch{}x&&g("replaceState",c,i),E&&g("pushState",p,n);return}return{clients:a,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",m)}catch{}g("pushState",p,n),g("replaceState",c,i)}}}function ce(o){A||(A=le()),A.clients.add(o)}function ue(o){let e=A;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),A=void 0))}function de(o,e){let t;if(typeof Request<"u"&&o!==null&&typeof o=="object")if(o instanceof Request)t=s(o,"url");else try{t=Object.getOwnPropertyDescriptor(Request.prototype,"url")?.get?.call(o)}catch{}let r=s(e,"signal");return{url:t??w(o),method:w(s(e,"method")??(t===void 0?void 0:s(o,"method"))??"GET"),signal:r===void 0?t===void 0?void 0:s(o,"signal"):r}}function le(){let o=new Set,e=window.fetch,t;typeof e=="function"&&(t=function(...p){if(!o.size)return Reflect.apply(e,this,p);let c=S(),f;try{f=de(p[0],p[1])}catch{f={url:"",method:"GET"}}let m;try{m=Reflect.apply(e,this,p)}catch(g){if(!j(g,f.signal))for(let E of o)E.reportNetwork(f.method,f.url,void 0,S()-c,g);throw g}return m.then(g=>{try{let E=g.status;for(let x of o)x.reportNetwork(f.method,f.url,E,S()-c)}catch{}return g},g=>{if(!j(g,f.signal))for(let E of o)E.reportNetwork(f.method,f.url,void 0,S()-c,g);throw g})},window.fetch=t);let r=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,n=r?.open,i=r?.send,d=new WeakMap,l=new WeakMap,a,u;return r&&n&&i&&(a=(function(...p){let c=Reflect.apply(n,this,p);l.get(this)?.();try{d.set(this,{method:w(p[0]),url:w(p[1])})}catch{}return c}),u=function(...p){if(!o.size)return Reflect.apply(i,this,p);let c=d.get(this);if(!c)return Reflect.apply(i,this,p);let f=S(),m=!1,g=!1,E=!1,x=()=>{m=!0},b=()=>{g=!0},y=()=>{this.removeEventListener("abort",x),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",B),l.get(this)===y&&l.delete(this)},B=()=>{if(E=!0,y(),!m)try{let v=this.status;if(v===0&&!g){for(let O of o)O.reportZeroStatusCompletion(c.method,c.url,S()-f);return}for(let O of o)O.reportNetwork(c.method,c.url,v===0?void 0:v,S()-f)}catch{}};try{this.addEventListener("abort",x),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",B)}catch{return y(),Reflect.apply(i,this,p)}try{let v=Reflect.apply(i,this,p);return E||l.set(this,y),v}catch(v){throw y(),v}},r.open=a,r.send=u),{clients:o,cleanup(){t&&window.fetch===t&&(window.fetch=e),r&&a&&r.open===a&&(r.open=n),r&&u&&r.send===u&&(r.send=i)}}}function pe(o){N||(N=fe()),N.clients.add(o)}function he(o){let e=N;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),N=void 0))}function fe(){let o=new Set,e=console.error,t=function(...r){try{return Reflect.apply(e,this,r)}finally{for(let n of o)n.captureConsole(r)}};return console.error=t,{clients:o,cleanup(){console.error===t&&(console.error=e)}}}function me(o){return new q(o)}
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|