@sazabi/browser 0.2.0-dev.g083f85c

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Sazabi
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # @sazabi/browser-sdk
2
+
3
+ Capture what happens in your users' browsers with `@sazabi/browser-sdk`, the official Sazabi browser SDK. It emits a session-scoped stream of navigation, interactions, console output, JavaScript errors, and network calls as OTLP log records, and injects W3C trace context into your API requests so a frontend symptom and its backend cause share a trace id.
4
+
5
+ `@sazabi/browser-sdk` is a zero-dependency browser library you install in your own web app. It lets you:
6
+
7
+ - Follow a single visitor's session across tabs, from first page load to error
8
+ - Catch uncaught exceptions and unhandled promise rejections with stack traces
9
+ - See rage clicks and dead clicks — the interactions that signal frustration
10
+ - Join frontend network calls to backend logs on a shared `trace_id`
11
+ - Use AI to investigate a browser session end to end
12
+
13
+ ~8 KB gzipped, and designed to never break your app: every hook is wrapped, every patch is reversible, and input values are never captured.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @sazabi/browser-sdk
19
+ # or: bun add / pnpm add / yarn add
20
+ ```
21
+
22
+ ## Get your intake URL
23
+
24
+ Sign in to Sazabi, go to **Settings > Log streams**, choose **Web**, and click **Add**. Sazabi mints a public key and shows your complete intake URL at the top of the setup screen.
25
+
26
+ The SDK needs both values: the intake URL as `intakeHost` (the SDK appends the `/v1/logs` signal path itself) and the full `sazabi_public_...` value as `publicKey`.
27
+
28
+ Unlike most credentials, this one is **meant** to ship in your browser bundle — a public key can only write telemetry into your project, never read from it.
29
+
30
+ ## Quick start
31
+
32
+ ```ts
33
+ // Import first, because a module that runs earlier can capture the native
34
+ // fetch/XHR/history references before the SDK wraps them.
35
+ import "@sazabi/browser-sdk/register";
36
+
37
+ import { init } from "@sazabi/browser-sdk";
38
+
39
+ init({
40
+ intakeHost: "https://<public-key-hex>.<region>.intake.sazabi.com",
41
+ publicKey: "sazabi_public_<public-key-hex>",
42
+ serviceName: "my-web-app",
43
+ serviceVersion: process.env.GIT_SHA,
44
+ environment: "production",
45
+ });
46
+ ```
47
+
48
+ `init()` is idempotent, never throws into your app, and no-ops during server-side rendering, so it is safe in a shared entry module.
49
+
50
+ The register import is optional but recommended. `init()` alone also instruments, but only at call time — and every static import in your entry file evaluates before its first statement, so an HTTP client constructed at module scope wins that race. Requests that slip past instrumentation are still observed through a resource-timing fallback, and the SDK emits a once-per-origin `instrumentation_gap` diagnostic naming the escaped origin, so the gap is visible rather than silent.
51
+
52
+ ## What gets captured
53
+
54
+ Every event carries a cross-tab `session.id`, a per-tab `session.window_id`, `session.distinct_id`, and the page URL, so one user's activity reads as a single ordered timeline. The `web.event_type` attribute names the kind:
55
+
56
+ | `web.event_type` | Contents |
57
+ |------------------|----------|
58
+ | `navigation` | Page loads and SPA route changes — History API, hash, back/forward, and the Navigation API |
59
+ | `click` | Capture-phase clicks with a privacy-safe selector and the element's label ("Save changes") |
60
+ | `rage_click` / `dead_click` | Frustration signals: rapid repeat clicks, and clicks with no visible response |
61
+ | `input` | One event per field engagement — which field, for how long, how many edits, whether pasted. Never keystrokes, values, or value lengths |
62
+ | `error` | Uncaught exceptions and unhandled rejections with `exception.type`, `exception.message`, and `exception.stacktrace` |
63
+ | `network` | fetch and XHR calls with method, status, and duration — plus the trace context injected into them |
64
+ | `log` | Mirrored `console.error` / `console.warn` output, plus anything you send with `log()` |
65
+ | `custom` | Marks you add with `addEvent()` |
66
+
67
+ ## Correlate with your backend
68
+
69
+ The SDK injects a W3C `traceparent` header into same-origin requests by default. To reach an API on another origin, allowlist it — and make sure that API's CORS configuration includes `traceparent` in `Access-Control-Allow-Headers`, or the browser preflight fails and those requests break:
70
+
71
+ ```ts
72
+ init({
73
+ // …
74
+ network: {
75
+ allowlist: ["https://api.example.com"],
76
+ },
77
+ });
78
+ ```
79
+
80
+ Backend log lines that run inside the extracted trace context then share a `trace_id` with the originating browser request. If your backend runs OpenTelemetry, that extraction already happens by default. Set `network: { sampledFlag: true }` if you also want your backend tracer to *record* those traces — the logs-side join works either way.
81
+
82
+ The SDK also records platform request ids echoed on responses (`x-request-id`, `cf-ray`, `x-vercel-id`, and similar) as `web.network.request_id`, giving you an exact join key against CDN and platform logs with no backend changes. Reading these cross-origin requires the header in `Access-Control-Expose-Headers`.
83
+
84
+ ## Identify users
85
+
86
+ ```ts
87
+ import { identify, reset } from "@sazabi/browser-sdk";
88
+
89
+ identify("user_123", { plan: "pro" }); // on sign-in — use your internal id, not an email
90
+ reset(); // on sign-out
91
+ ```
92
+
93
+ `identify()` stamps `session.distinct_id` on subsequent events and records the traits on the identify event. `reset()` clears the identity and rotates the session and window ids, so activity on a shared device never threads into the previous user's timeline; switching identities without a `reset()` rotates automatically.
94
+
95
+ Identity is client-asserted — treat it as a claim, not as authentication.
96
+
97
+ ## Logs, custom events, and console output
98
+
99
+ ```ts
100
+ import { addEvent, log } from "@sazabi/browser-sdk";
101
+
102
+ addEvent("checkout_started", { cartValue: 42 });
103
+ log("WARN", "cache lookup failed", { requestId: "req_9" });
104
+ ```
105
+
106
+ `console.error` and `console.warn` are mirrored into the event stream by default, and the original console behavior is untouched. Configure with `console: { levels: [...] }` or turn it off with `console: { capture: false }`.
107
+
108
+ ## Consent
109
+
110
+ If your users must opt in before capture, pass a consent gate — nothing is installed and nothing is sent until it resolves true:
111
+
112
+ ```ts
113
+ init({
114
+ // …
115
+ consent: () => cookieBanner.accepted(),
116
+ });
117
+ ```
118
+
119
+ `identify()` calls made while consent is pending are buffered and applied when capture starts.
120
+
121
+ ## Configuration
122
+
123
+ | Option | Default | Purpose |
124
+ |--------|---------|---------|
125
+ | `network.capture` | `true` | Emit network events for fetch/XHR |
126
+ | `network.propagateTraceContext` | `true` | Inject `traceparent` into eligible requests |
127
+ | `network.allowlist` | same-origin only | Origins eligible for header injection |
128
+ | `network.sampledFlag` | `false` | Mark minted traces sampled (`-01`) for backend tracers |
129
+ | `network.resourceFallback` | `true` | Observe requests that bypass instrumentation |
130
+ | `network.requestIdHeaders` | common platform headers | Response headers probed for a request id |
131
+ | `console.capture` / `console.levels` | `true`, `["error", "warn"]` | Console mirroring |
132
+ | `input.capture` | `true` | Field-interaction episodes |
133
+ | `consent` | off | Hold all capture until it resolves true |
134
+ | `flushIntervalMs` | `5000` | Batch flush cadence |
135
+
136
+ ## Privacy and safety
137
+
138
+ - **Input values, keystrokes, request bodies, and response bodies are never captured** — not even value lengths.
139
+ - Element names come from developer-authored sources only (`aria-label`, `<label>`, `placeholder`, button captions), and only for interactive elements. Clicks on plain containers, where user content lives, record selectors only.
140
+ - Add `data-sazabi-mask` to any element to suppress text capture for its whole subtree, or `data-sazabi-name` to set an element's reported name explicitly.
141
+ - Every patch is transparent, idempotent, and reversible. SDK failures are invisible to your app, and `shutdown()` restores the original functions.
142
+ - Events are delivered as OTLP/HTTP log records with batching, and flushed with `keepalive` when the tab closes.
143
+
144
+ ## Verifying it works
145
+
146
+ Load your app and click through a few pages. The SDK flushes every 5 seconds and again when the tab is hidden or closed, so the first events land within about 10 seconds. In your browser's network tab, filter for `intake` — POSTs to `/v1/logs` should return 200.
147
+
148
+ Full setup guide and troubleshooting: [docs.sazabi.com/data/log-sources/endpoint/web](https://docs.sazabi.com/data/log-sources/endpoint/web).
@@ -0,0 +1,8 @@
1
+ import type { EventAttributes } from "./types";
2
+ export declare const truncateValue: (value: string, max?: number) => string;
3
+ /**
4
+ * Flatten nested metadata into dot-keyed scalar attributes. Non-scalar leaves
5
+ * are JSON-stringified; strings are length-capped so a hostile or buggy page
6
+ * cannot inflate rows.
7
+ */
8
+ export declare const flattenAttributes: (input: Record<string, unknown>, prefix?: string, depth?: number) => EventAttributes;
@@ -0,0 +1,5 @@
1
+ var l=(t)=>{try{Object.defineProperty(t,"__sazabiBrowserWrapped",{value:!0})}catch{}},R=(t)=>typeof t==="function"&&t.__sazabiBrowserWrapped===!0;var W={push:"pushState",replace:"replaceState",traverse:"popstate",reload:"reload"},I,y=(t)=>{let e=I;if(!e)return;try{let r=window.location.href,n=e.previousUrl;if(e.previousUrl=r,t!=="load"&&n===r)return;e.options.onNavigate(),e.options.emit({type:"navigation",body:`navigation ${window.location.pathname}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.navigation.type":t,"url.full":r,"web.navigation.from":n||void 0}})}catch{}},f,j=(t)=>{let{pushState:e,replaceState:r}=t;return{originalPushState:e,originalReplaceState:r,wrappedPushState:function(...s){e.apply(this,s),y("pushState")},wrappedReplaceState:function(...s){r.apply(this,s),y("replaceState")}}},_=()=>{let t=History.prototype;if(!R(t.pushState)){let e=j(t);l(e.wrappedPushState),l(e.wrappedReplaceState),t.pushState=e.wrappedPushState,t.replaceState=e.wrappedReplaceState,f=e}},Y=()=>{let t=History.prototype;if(f){if(t.pushState===f.wrappedPushState)t.pushState=f.originalPushState;if(t.replaceState===f.wrappedReplaceState)t.replaceState=f.originalReplaceState}f=void 0},J=(t)=>{_(),I={options:t,previousUrl:document.referrer||""};let e=()=>{y("popstate")},r=()=>{y("hashchange")};window.addEventListener("popstate",e),window.addEventListener("hashchange",r);let n=window.navigation,o=(s)=>{let g=s.navigationType,i=W[g??""];if(i)y(i)};return n?.addEventListener("currententrychange",o),y("load"),{teardown(){I=void 0,window.removeEventListener("popstate",e),window.removeEventListener("hashchange",r),n?.removeEventListener("currententrychange",o)}}};var N=(t)=>{try{let e=new URL(t);return e.origin===window.location.origin?e.pathname:`${e.host}${e.pathname}`}catch{return t}},U=(t)=>{if(t===0||t>=500)return"ERROR";if(t>=400)return"WARN";return"INFO"};var L=(t)=>{try{let e=new URL(t,window.location.href);return e.username="",e.password="",e.href}catch{return}},h,M=(t,e)=>{if(t.allowlist.length===0)try{return new URL(e).origin===window.location.origin}catch{return!1}return t.allowlist.some((r)=>typeof r==="string"?e.includes(r):r.test(e))},re=(t)=>{let e=h;if(!e?.propagateTraceContext)return!1;if(e.isInternalUrl(t))return!1;return M(e,t)},A=5000,E=300,w=[],T=(t)=>{if(w.push({url:t,startTime:performance.now()}),w.length>E)w=w.slice(-E)},ne=(t,e)=>{let r=w.findIndex((n)=>n.url===t&&Math.abs(n.startTime-e)<=A);if(r===-1)return!1;return w.splice(r,1),!0},C=(t,e)=>{try{let r=N(e.resolvedUrl),n=e.status>0?String(e.status):"failed",o={type:"network",body:`${e.method} ${r} → ${n}`,severity:U(e.status),timeUnixMs:Date.now(),attributes:{"http.request.method":e.method,"http.response.status_code":e.status>0?e.status:void 0,"url.full":e.resolvedUrl,"web.network.kind":e.kind,"web.network.duration_ms":Math.round(e.durationMs),"web.network.error":e.failureMessage,"web.network.request_id":e.requestId,"web.network.request_id_header":e.requestIdHeader}};if(e.injected)o.traceId=e.injected.traceId,o.spanId=e.injected.spanId;t.emit(o)}catch{}},D=(t,e)=>{try{for(let r of t.requestIdHeaders){let n=e.headers.get(r);if(n)return{requestId:n,requestIdHeader:r}}}catch{}return{}},F=(t,e)=>{try{for(let r of t.requestIdHeaders){let n=e.getResponseHeader(r);if(n)return{requestId:n,requestIdHeader:r}}}catch{}return{}},S,k=0,B=(t)=>{let e=(r,n,o)=>{k++;try{return t.call(r,n,o)}finally{k--}};return function(r,n){let o=h;if(!o||k>0||R(t))return t.call(this,r,n);let s,g="GET",i,p=n;try{let c=typeof r==="string"?r:r instanceof URL?r.href:r.url;if(s=L(c),typeof r==="object"&&"method"in r&&r.method)g=r.method.toUpperCase();if(n?.method)g=n.method.toUpperCase();let x=s===void 0||o.isInternalUrl(s);if(!x&&s&&o.propagateTraceContext&&M(o,s)){let H=o.traceContext.forRequest();if(r instanceof Request&&n===void 0)try{for(let[m,P]of Object.entries(H.headers))if(!r.headers.has(m))r.headers.set(m,P);i=H}catch{i=void 0}else{let m=r instanceof Request&&n?.headers===void 0?new Headers(r.headers):new Headers(n?.headers),P=m.has("traceparent");if(r instanceof Request&&r.headers.has("traceparent"))P=!0;if(!P){for(let[O,X]of Object.entries(H.headers))m.set(O,X);p={...n,headers:m},i=H}}}if(!x&&s!==void 0)T(s);if(x||!o.capture||s===void 0)return e(this,r,p)}catch{return e(this,r,n)}let a=performance.now(),v=s,u=g,q=i;return e(this,r,p).then((c)=>(C(o,{kind:"fetch",method:u,resolvedUrl:v,status:c.status,durationMs:performance.now()-a,injected:q,...D(o,c)}),c),(c)=>{throw C(o,{kind:"fetch",method:u,resolvedUrl:v,status:0,durationMs:performance.now()-a,failureMessage:c instanceof Error?c.message:String(c),injected:q}),c})}},b=new WeakMap,d,K=(t)=>{let{open:e,send:r,setRequestHeader:n}=t;return{originalOpen:e,originalSend:r,originalSetRequestHeader:n,wrappedOpen:function(...i){if(h)try{let[p,a]=i;b.set(this,{method:String(p).toUpperCase(),resolvedUrl:L(String(a)),customTraceparent:!1,start:0,processed:!1})}catch{}e.apply(this,i)},wrappedSend:function(i){let p=h;if(p)try{let a=b.get(this);if(a?.resolvedUrl&&!a.processed){a.processed=!0;let v=p.isInternalUrl(a.resolvedUrl);if(!v&&p.propagateTraceContext&&!a.customTraceparent&&M(p,a.resolvedUrl))try{let u=p.traceContext.forRequest();for(let[q,c]of Object.entries(u.headers))n.call(this,q,c);a.injected=u}catch{a.injected=void 0}if(!v)T(a.resolvedUrl);if(!v&&p.capture)a.start=performance.now(),this.addEventListener("loadend",()=>{let u=h??p;C(u,{kind:"xhr",method:a.method,resolvedUrl:a.resolvedUrl,status:this.status,durationMs:performance.now()-a.start,injected:a.injected,...F(u,this)})})}}catch{}r.call(this,i)},wrappedSetRequestHeader:function(i,p){if(h)try{if(i.toLowerCase()==="traceparent"){let a=b.get(this);if(a)a.customTraceparent=!0}}catch{}n.call(this,i,p)}}},G=()=>{if(!R(window.fetch)){let e=window.fetch,r=B(e);l(r),window.fetch=r,S={original:e,wrapped:r}}let t=XMLHttpRequest.prototype;if(!R(t.open)){let e=K(t);l(e.wrappedOpen),l(e.wrappedSetRequestHeader),l(e.wrappedSend),t.open=e.wrappedOpen,t.setRequestHeader=e.wrappedSetRequestHeader,t.send=e.wrappedSend,d=e}},ae=()=>{if(S&&window.fetch===S.wrapped)window.fetch=S.original;S=void 0;let t=XMLHttpRequest.prototype;if(d){if(t.open===d.wrappedOpen)t.open=d.originalOpen;if(t.setRequestHeader===d.wrappedSetRequestHeader)t.setRequestHeader=d.originalSetRequestHeader;if(t.send===d.wrappedSend)t.send=d.originalSend}d=void 0,w=[]},oe=(t)=>(G(),h=t,{teardown(){h=void 0}});
2
+ export{l as a,R as b,_ as c,Y as d,J as e,N as f,U as g,re as h,ne as i,G as j,ae as k,oe as l};
3
+
4
+ //# debugId=0E88B5801F6610F064756E2164756E21
5
+ //# sourceMappingURL=chunk-rfm4nnme.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/patch-marker.ts", "../src/navigation.ts", "../src/network-event-format.ts", "../src/network.ts"],
4
+ "sourcesContent": [
5
+ "export const WRAPPED_MARKER = \"__sazabiBrowserWrapped\";\n\n/** Best-effort idempotency marker on wrapper functions. */\nexport const markWrapped = (fn: object): void => {\n try {\n Object.defineProperty(fn, WRAPPED_MARKER, { value: true });\n } catch {\n // Non-extensible function object — idempotency guard degrades gracefully.\n }\n};\n\nexport const isWrapped = (fn: unknown): boolean =>\n typeof fn === \"function\" &&\n (fn as unknown as Record<string, unknown>)[WRAPPED_MARKER] === true;\n",
6
+ "import { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { WebEvent } from \"./types\";\n\nexport interface NavigationCaptureOptions {\n emit(event: WebEvent): void;\n /** Fired on every captured navigation (dead-click signal). */\n onNavigate(): void;\n}\n\nexport interface NavigationCaptureHandle {\n teardown(): void;\n}\n\ntype NavigationType =\n | \"load\"\n | \"pushState\"\n | \"replaceState\"\n | \"popstate\"\n | \"hashchange\"\n | \"reload\";\n\n/**\n * Navigation API `currententrychange` types → our History-API-flavored\n * vocabulary, so queries see one taxonomy regardless of which API navigated.\n */\nconst NAVIGATION_API_TYPE_MAP: Record<string, NavigationType> = {\n push: \"pushState\",\n replace: \"replaceState\",\n traverse: \"popstate\",\n reload: \"reload\",\n};\n\n// ------------------------------------------------------------- activation --\n// History patches install dormant (routers commonly capture\n// History.prototype methods at module scope) and consult this slot per call.\n\ninterface ActiveNavigation {\n options: NavigationCaptureOptions;\n previousUrl: string;\n}\n\nlet active: ActiveNavigation | undefined;\n\nconst emitNavigation = (navigationType: NavigationType): void => {\n const current = active;\n if (!current) return;\n try {\n const currentUrl = window.location.href;\n const from = current.previousUrl;\n current.previousUrl = currentUrl;\n if (navigationType !== \"load\" && from === currentUrl) {\n return; // replaceState to the same URL etc. — not a navigation.\n }\n current.options.onNavigate();\n current.options.emit({\n type: \"navigation\",\n body: `navigation ${window.location.pathname}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.navigation.type\": navigationType,\n \"url.full\": currentUrl,\n \"web.navigation.from\": from || undefined,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n};\n\ninterface HistoryPatch {\n originalPushState: History[\"pushState\"];\n originalReplaceState: History[\"replaceState\"];\n wrappedPushState: History[\"pushState\"];\n wrappedReplaceState: History[\"replaceState\"];\n}\n\nlet historyPatch: HistoryPatch | undefined;\n\nconst makeHistoryPatch = (proto: History): HistoryPatch => {\n const originalPushState = proto.pushState;\n const originalReplaceState = proto.replaceState;\n\n const wrappedPushState = function (\n this: History,\n ...args: Parameters<History[\"pushState\"]>\n ): void {\n originalPushState.apply(this, args);\n emitNavigation(\"pushState\");\n };\n\n const wrappedReplaceState = function (\n this: History,\n ...args: Parameters<History[\"replaceState\"]>\n ): void {\n originalReplaceState.apply(this, args);\n emitNavigation(\"replaceState\");\n };\n\n return {\n originalPushState,\n originalReplaceState,\n wrappedPushState,\n wrappedReplaceState,\n };\n};\n\n/**\n * Install dormant history patches around whatever implementations are\n * currently live. Idempotent; re-wraps if a later actor replaced the methods\n * after an earlier install (the displaced wrappers are inert passthroughs).\n */\nexport const ensureNavigationPatches = (): void => {\n const proto = History.prototype;\n if (!isWrapped(proto.pushState)) {\n const patch = makeHistoryPatch(proto);\n markWrapped(patch.wrappedPushState);\n markWrapped(patch.wrappedReplaceState);\n proto.pushState = patch.wrappedPushState;\n proto.replaceState = patch.wrappedReplaceState;\n historyPatch = patch;\n }\n};\n\n/** Restore the natives if the current implementations are still ours. */\nexport const uninstallNavigationPatches = (): void => {\n const proto = History.prototype;\n if (historyPatch) {\n if (proto.pushState === historyPatch.wrappedPushState) {\n proto.pushState = historyPatch.originalPushState;\n }\n if (proto.replaceState === historyPatch.wrappedReplaceState) {\n proto.replaceState = historyPatch.originalReplaceState;\n }\n }\n historyPatch = undefined;\n};\n\n/**\n * SPA navigation capture. Listeners alone miss programmatic navigation —\n * which is most navigation in React apps — so `history.pushState` /\n * `replaceState` are wrapped under the same isolation rules as the network\n * patch.\n */\nexport const installNavigationCapture = (\n options: NavigationCaptureOptions,\n): NavigationCaptureHandle => {\n ensureNavigationPatches();\n active = { options, previousUrl: document.referrer || \"\" };\n\n const onPopState = (): void => {\n emitNavigation(\"popstate\");\n };\n const onHashChange = (): void => {\n emitNavigation(\"hashchange\");\n };\n window.addEventListener(\"popstate\", onPopState);\n window.addEventListener(\"hashchange\", onHashChange);\n\n // Navigation API (Chromium): `navigation.navigate()` same-document\n // navigations call neither pushState nor popstate, but every same-document\n // navigation — whichever API initiated it — fires `currententrychange`.\n // The same-URL dedupe in emitNavigation collapses the overlap with the\n // history patch and legacy listeners; first signal wins.\n const navigationApi = (window as { navigation?: EventTarget }).navigation;\n const onCurrentEntryChange = (event: Event): void => {\n const navigationType = (event as { navigationType?: string | null })\n .navigationType;\n const mapped = NAVIGATION_API_TYPE_MAP[navigationType ?? \"\"];\n if (mapped) {\n // Unmapped/null types (e.g. updateCurrentEntry metadata edits) are\n // not navigations.\n emitNavigation(mapped);\n }\n };\n navigationApi?.addEventListener(\"currententrychange\", onCurrentEntryChange);\n\n // The page we landed on is the first navigation of the window.\n emitNavigation(\"load\");\n\n return {\n teardown() {\n active = undefined;\n window.removeEventListener(\"popstate\", onPopState);\n window.removeEventListener(\"hashchange\", onHashChange);\n navigationApi?.removeEventListener(\n \"currententrychange\",\n onCurrentEntryChange,\n );\n },\n };\n};\n",
7
+ "import type { EventSeverity } from \"./types\";\n\n/** Compact display path: pathname when same-origin, host+path cross-origin. */\nexport const urlPath = (resolved: string): string => {\n try {\n const url = new URL(resolved);\n return url.origin === window.location.origin\n ? url.pathname\n : `${url.host}${url.pathname}`;\n } catch {\n return resolved;\n }\n};\n\n/** Status 0 means transport failure. */\nexport const severityForStatus = (status: number): EventSeverity => {\n if (status === 0 || status >= 500) return \"ERROR\";\n if (status >= 400) return \"WARN\";\n return \"INFO\";\n};\n",
8
+ "import { severityForStatus, urlPath } from \"./network-event-format\";\nimport { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { RequestTraceContext, TraceContextManager } from \"./trace-context\";\nimport type { WebEvent } from \"./types\";\n\nexport interface NetworkCaptureOptions {\n emit(event: WebEvent): void;\n traceContext: TraceContextManager;\n /** Emit network events. */\n capture: boolean;\n /** Inject `traceparent` into allowlisted requests. */\n propagateTraceContext: boolean;\n /** Injection allowlist; empty means same-origin only. */\n allowlist: (string | RegExp)[];\n /** Response headers probed for a platform request id, in priority order. */\n requestIdHeaders: string[];\n /** SDK-internal endpoints: never captured, never injected. */\n isInternalUrl(url: string): boolean;\n}\n\nexport interface NetworkCaptureHandle {\n teardown(): void;\n}\n\nconst resolveUrl = (raw: string): string | undefined => {\n try {\n const url = new URL(raw, window.location.href);\n url.username = \"\";\n url.password = \"\";\n return url.href;\n } catch {\n return undefined;\n }\n};\n\n// ------------------------------------------------------------- activation --\n// Patches install dormant (possibly via `@sazabi/browser/register` before\n// any app module can capture the natives) and consult this slot per call.\n// Undefined slot = transparent passthrough.\n\nlet active: NetworkCaptureOptions | undefined;\n\nconst isAllowedForInjection = (\n options: NetworkCaptureOptions,\n resolved: string,\n): boolean => {\n if (options.allowlist.length === 0) {\n try {\n return new URL(resolved).origin === window.location.origin;\n } catch {\n return false;\n }\n }\n return options.allowlist.some((pattern) =>\n typeof pattern === \"string\"\n ? resolved.includes(pattern)\n : pattern.test(resolved),\n );\n};\n\n/** Injection eligibility for the active config; used by the resource observer\n * to decide whether a bypassed request is a diagnosable instrumentation gap. */\nexport const isActiveInjectionTarget = (resolved: string): boolean => {\n const options = active;\n if (!options?.propagateTraceContext) return false;\n if (options.isInternalUrl(resolved)) return false;\n return isAllowedForInjection(options, resolved);\n};\n\n// ----------------------------------------------------- wrapper-seen ledger --\n// Every request processed by an active wrapper is recorded so the resource-\n// timing observer can tell wrapper-captured traffic (skip: a richer event was\n// already emitted) from traffic that bypassed the patches entirely.\n\ninterface SeenRequest {\n url: string;\n /** performance.now() timebase, comparable to PerformanceEntry.startTime. */\n startTime: number;\n}\n\nconst SEEN_MATCH_WINDOW_MS = 5_000;\nconst SEEN_MAX_ENTRIES = 300;\nlet seenByWrapper: SeenRequest[] = [];\n\nconst recordWrapperRequest = (url: string): void => {\n seenByWrapper.push({ url, startTime: performance.now() });\n if (seenByWrapper.length > SEEN_MAX_ENTRIES) {\n seenByWrapper = seenByWrapper.slice(-SEEN_MAX_ENTRIES);\n }\n};\n\n/** Consume a wrapper-seen record matching this resource entry, if any. */\nexport const consumeWrapperSeen = (url: string, startTime: number): boolean => {\n const index = seenByWrapper.findIndex(\n (seen) =>\n seen.url === url &&\n Math.abs(seen.startTime - startTime) <= SEEN_MATCH_WINDOW_MS,\n );\n if (index === -1) return false;\n seenByWrapper.splice(index, 1);\n return true;\n};\n\nconst emitNetworkEvent = (\n options: NetworkCaptureOptions,\n details: {\n kind: \"fetch\" | \"xhr\";\n method: string;\n resolvedUrl: string;\n status: number;\n durationMs: number;\n failureMessage?: string;\n injected?: RequestTraceContext;\n requestId?: string;\n requestIdHeader?: string;\n },\n): void => {\n try {\n const path = urlPath(details.resolvedUrl);\n const outcome = details.status > 0 ? String(details.status) : \"failed\";\n const event: WebEvent = {\n type: \"network\",\n body: `${details.method} ${path} → ${outcome}`,\n severity: severityForStatus(details.status),\n timeUnixMs: Date.now(),\n attributes: {\n \"http.request.method\": details.method,\n \"http.response.status_code\":\n details.status > 0 ? details.status : undefined,\n \"url.full\": details.resolvedUrl,\n \"web.network.kind\": details.kind,\n \"web.network.duration_ms\": Math.round(details.durationMs),\n \"web.network.error\": details.failureMessage,\n \"web.network.request_id\": details.requestId,\n \"web.network.request_id_header\": details.requestIdHeader,\n },\n };\n if (details.injected) {\n event.traceId = details.injected.traceId;\n event.spanId = details.injected.spanId;\n }\n options.emit(event);\n } catch {\n // Capture failures must never surface to the host.\n }\n};\n\nconst readFetchRequestId = (\n options: NetworkCaptureOptions,\n response: Response,\n): { requestId?: string; requestIdHeader?: string } => {\n try {\n for (const name of options.requestIdHeaders) {\n const value = response.headers.get(name);\n if (value) return { requestId: value, requestIdHeader: name };\n }\n } catch {\n // Header access failures are ignorable detail loss.\n }\n return {};\n};\n\nconst readXhrRequestId = (\n options: NetworkCaptureOptions,\n xhr: XMLHttpRequest,\n): { requestId?: string; requestIdHeader?: string } => {\n try {\n for (const name of options.requestIdHeaders) {\n const value = xhr.getResponseHeader(name);\n if (value) return { requestId: value, requestIdHeader: name };\n }\n } catch {\n // Cross-origin/invalid-state header access — ignorable detail loss.\n }\n return {};\n};\n\n// ------------------------------------------------------------------ fetch --\n\ninterface FetchPatch {\n original: typeof fetch;\n wrapped: typeof fetch;\n}\n\nlet fetchPatch: FetchPatch | undefined;\n\n/**\n * Outermost-wins sandwich guard. When a third party patches fetch between our\n * register-time install and init (Sentry, analytics), init's re-wrap makes\n * the chain ourWrapper2(thirdParty(ourWrapper1(native))) — two ACTIVE copies\n * of our wrapper in one call path, which would double-emit every event. The\n * outermost wrapper raises this depth for the synchronous span of its\n * call-through; inner copies see it and become pure passthroughs.\n */\nlet fetchProcessingDepth = 0;\n\nconst makeWrappedFetch = (originalFetch: typeof fetch): typeof fetch => {\n const callThrough = (\n thisArg: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n fetchProcessingDepth++;\n try {\n return originalFetch.call(thisArg, input, init);\n } finally {\n fetchProcessingDepth--;\n }\n };\n\n return function (\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n const options = active;\n if (!options || fetchProcessingDepth > 0 || isWrapped(originalFetch)) {\n return originalFetch.call(this, input, init);\n }\n\n let resolvedUrl: string | undefined;\n let method = \"GET\";\n let injected: RequestTraceContext | undefined;\n let finalInit = init;\n\n try {\n const rawUrl =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n resolvedUrl = resolveUrl(rawUrl);\n\n if (typeof input === \"object\" && \"method\" in input && input.method) {\n method = input.method.toUpperCase();\n }\n if (init?.method) {\n method = init.method.toUpperCase();\n }\n\n const internal =\n resolvedUrl === undefined || options.isInternalUrl(resolvedUrl);\n\n if (\n !internal &&\n resolvedUrl &&\n options.propagateTraceContext &&\n isAllowedForInjection(options, resolvedUrl)\n ) {\n const requestContext = options.traceContext.forRequest();\n\n if (input instanceof Request && init === undefined) {\n // Headers on a constructed Request are mutable for non-forbidden\n // names; if the guard rejects them, skip injection rather than\n // clone (cloning can consume one-shot bodies).\n try {\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n if (!input.headers.has(name)) {\n input.headers.set(name, value);\n }\n }\n injected = requestContext;\n } catch {\n injected = undefined;\n }\n } else {\n // Per fetch semantics, init.headers replaces the Request's own\n // headers entirely. When the caller passed a Request plus an init\n // WITHOUT headers, seed the merge from the Request so injection\n // does not silently strip Authorization/Content-Type/etc.\n const merged =\n input instanceof Request && init?.headers === undefined\n ? new Headers(input.headers)\n : new Headers(init?.headers);\n let alreadyTraced = merged.has(\"traceparent\");\n if (input instanceof Request && input.headers.has(\"traceparent\")) {\n alreadyTraced = true;\n }\n if (!alreadyTraced) {\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n merged.set(name, value);\n }\n finalInit = { ...init, headers: merged };\n injected = requestContext;\n }\n }\n }\n\n if (!internal && resolvedUrl !== undefined) {\n recordWrapperRequest(resolvedUrl);\n }\n\n if (internal || !options.capture || resolvedUrl === undefined) {\n return callThrough(this, input, finalInit);\n }\n } catch {\n // Any preparation failure: fall through to a plain passthrough call.\n return callThrough(this, input, init);\n }\n\n const start = performance.now();\n const capturedUrl = resolvedUrl;\n const capturedMethod = method;\n const capturedInjection = injected;\n\n return callThrough(this, input, finalInit).then(\n (response) => {\n emitNetworkEvent(options, {\n kind: \"fetch\",\n method: capturedMethod,\n resolvedUrl: capturedUrl,\n status: response.status,\n durationMs: performance.now() - start,\n injected: capturedInjection,\n ...readFetchRequestId(options, response),\n });\n return response;\n },\n (error: unknown) => {\n emitNetworkEvent(options, {\n kind: \"fetch\",\n method: capturedMethod,\n resolvedUrl: capturedUrl,\n status: 0,\n durationMs: performance.now() - start,\n failureMessage:\n error instanceof Error ? error.message : String(error),\n injected: capturedInjection,\n });\n throw error;\n },\n );\n };\n};\n\n// ------------------------------------------------------------------ XHR --\n\ninterface XhrRequestState {\n method: string;\n resolvedUrl?: string;\n customTraceparent: boolean;\n injected?: RequestTraceContext;\n start: number;\n /** Set by the outermost of our send wrappers in a third-party sandwich. */\n processed: boolean;\n}\n\nconst xhrState = new WeakMap<XMLHttpRequest, XhrRequestState>();\n\ninterface XhrPatch {\n originalOpen: XMLHttpRequest[\"open\"];\n originalSend: XMLHttpRequest[\"send\"];\n originalSetRequestHeader: XMLHttpRequest[\"setRequestHeader\"];\n wrappedOpen: XMLHttpRequest[\"open\"];\n wrappedSend: XMLHttpRequest[\"send\"];\n wrappedSetRequestHeader: XMLHttpRequest[\"setRequestHeader\"];\n}\n\nlet xhrPatch: XhrPatch | undefined;\n\nconst makeXhrPatch = (proto: XMLHttpRequest): XhrPatch => {\n const originalOpen = proto.open;\n const originalSend = proto.send;\n const originalSetRequestHeader = proto.setRequestHeader;\n\n // Forward `open` arguments with exact arity: `open(m, u, undefined)` would\n // coerce async to false (sync XHR) — not equivalent to the 2-arg call.\n const wrappedOpen = function (\n this: XMLHttpRequest,\n ...args: [string, string | URL, ...unknown[]]\n ): void {\n if (active) {\n try {\n const [method, url] = args;\n xhrState.set(this, {\n method: String(method).toUpperCase(),\n resolvedUrl: resolveUrl(String(url)),\n customTraceparent: false,\n start: 0,\n processed: false,\n });\n } catch {\n // Tracking failure must not affect the request.\n }\n }\n originalOpen.apply(this, args as Parameters<XMLHttpRequest[\"open\"]>);\n };\n\n const wrappedSetRequestHeader = function (\n this: XMLHttpRequest,\n name: string,\n value: string,\n ): void {\n if (active) {\n try {\n if (name.toLowerCase() === \"traceparent\") {\n const tracked = xhrState.get(this);\n if (tracked) {\n tracked.customTraceparent = true;\n }\n }\n } catch {\n // Ignore.\n }\n }\n originalSetRequestHeader.call(this, name, value);\n };\n\n const wrappedSend = function (\n this: XMLHttpRequest,\n body?: Document | XMLHttpRequestBodyInit | null,\n ): void {\n const options = active;\n if (options) {\n try {\n const tracked = xhrState.get(this);\n // `processed` = an outer copy of our wrapper already handled this\n // send (third-party sandwich); inner copies must not re-inject or\n // attach a second loadend emitter.\n if (tracked?.resolvedUrl && !tracked.processed) {\n tracked.processed = true;\n const internal = options.isInternalUrl(tracked.resolvedUrl);\n\n if (\n !internal &&\n options.propagateTraceContext &&\n !tracked.customTraceparent &&\n isAllowedForInjection(options, tracked.resolvedUrl)\n ) {\n try {\n const requestContext = options.traceContext.forRequest();\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n originalSetRequestHeader.call(this, name, value);\n }\n tracked.injected = requestContext;\n } catch {\n tracked.injected = undefined;\n }\n }\n\n if (!internal) {\n recordWrapperRequest(tracked.resolvedUrl);\n }\n\n if (!internal && options.capture) {\n tracked.start = performance.now();\n this.addEventListener(\"loadend\", () => {\n const current = active ?? options;\n emitNetworkEvent(current, {\n kind: \"xhr\",\n method: tracked.method,\n resolvedUrl: tracked.resolvedUrl as string,\n status: this.status,\n durationMs: performance.now() - tracked.start,\n injected: tracked.injected,\n ...readXhrRequestId(current, this),\n });\n });\n }\n }\n } catch {\n // Fall through to the untouched send.\n }\n }\n originalSend.call(this, body);\n };\n\n return {\n originalOpen,\n originalSend,\n originalSetRequestHeader,\n wrappedOpen,\n wrappedSend,\n wrappedSetRequestHeader,\n };\n};\n\n// ----------------------------------------------------------------- install --\n\n/**\n * Install dormant fetch/XHR patches around whatever implementations are\n * currently live. Idempotent, and re-wraps when a later actor (test stubs,\n * mocking layers) replaced the primitives after an earlier install — the\n * displaced wrapper is an inert passthrough, so single-processing holds.\n */\nexport const ensureNetworkPatches = (): void => {\n if (!isWrapped(window.fetch)) {\n const original = window.fetch;\n const wrapped = makeWrappedFetch(original);\n markWrapped(wrapped);\n window.fetch = wrapped;\n fetchPatch = { original, wrapped };\n }\n\n const proto = XMLHttpRequest.prototype;\n if (!isWrapped(proto.open)) {\n const patch = makeXhrPatch(proto);\n markWrapped(patch.wrappedOpen);\n markWrapped(patch.wrappedSetRequestHeader);\n markWrapped(patch.wrappedSend);\n proto.open = patch.wrappedOpen;\n proto.setRequestHeader = patch.wrappedSetRequestHeader;\n proto.send = patch.wrappedSend;\n xhrPatch = patch;\n }\n};\n\n/**\n * Restore the natives if the current implementations are still ours; if\n * someone patched on top of us, restoring would clobber them — the inactive\n * wrappers pass through.\n */\nexport const uninstallNetworkPatches = (): void => {\n if (fetchPatch && window.fetch === fetchPatch.wrapped) {\n window.fetch = fetchPatch.original;\n }\n fetchPatch = undefined;\n\n const proto = XMLHttpRequest.prototype;\n if (xhrPatch) {\n if (proto.open === xhrPatch.wrappedOpen) {\n proto.open = xhrPatch.originalOpen;\n }\n if (proto.setRequestHeader === xhrPatch.wrappedSetRequestHeader) {\n proto.setRequestHeader = xhrPatch.originalSetRequestHeader;\n }\n if (proto.send === xhrPatch.wrappedSend) {\n proto.send = xhrPatch.originalSend;\n }\n }\n xhrPatch = undefined;\n seenByWrapper = [];\n};\n\nexport const installNetworkCapture = (\n options: NetworkCaptureOptions,\n): NetworkCaptureHandle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B,EAAS,EAEF,CACL,QAAQ,EAAG,CACT,EAAS,OAEb",
11
+ "debugId": "0E88B5801F6610F064756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,17 @@
1
+ import type { ConsoleCaptureLevel, WebEvent } from "./types";
2
+ export interface ConsoleCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ levels: ConsoleCaptureLevel[];
5
+ }
6
+ export interface ConsoleCaptureHandle {
7
+ teardown(): void;
8
+ }
9
+ /** SDK-emitted console lines carry this prefix and are never re-captured. */
10
+ export declare const SDK_CONSOLE_PREFIX = "[@sazabi/browser]";
11
+ /**
12
+ * Mirror selected console levels into the event stream as `log` events.
13
+ * The original console method always runs first — devtools behavior is never
14
+ * altered — and capture failures are swallowed. Lines the SDK itself prints
15
+ * (prefixed with SDK_CONSOLE_PREFIX) are skipped to avoid self-capture.
16
+ */
17
+ export declare const installConsoleCapture: (options: ConsoleCaptureOptions) => ConsoleCaptureHandle;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Human-readable element names for timeline events — a pragmatic subset of
3
+ * the ARIA accessible-name computation, biased hard toward developer-authored
4
+ * sources. The bright line: app-authored static text (labels, aria-label,
5
+ * placeholder, button captions) is capturable; user-reflected text (values,
6
+ * selected options, data rendered into the DOM) is not. `data-sazabi-name`
7
+ * overrides any element's reported name; `data-sazabi-mask` on an ancestor
8
+ * suppresses name capture for the whole subtree.
9
+ */
10
+ /**
11
+ * Name for an input/textarea/select/contenteditable — developer-authored
12
+ * sources only; the field's value and (for selects) the chosen option text
13
+ * are never read.
14
+ */
15
+ export declare const computeInputName: (element: Element) => string | undefined;
16
+ /**
17
+ * Name for a click target: nearest interactive ancestor's accessible-ish
18
+ * name. Residual risk is labels that interpolate user data ("Delete 'My
19
+ * Project'") — that is app-authored markup, capped at 64 chars, and
20
+ * suppressible via `data-sazabi-mask` / overridable via `data-sazabi-name`.
21
+ */
22
+ export declare const computeClickName: (target: Element) => string | undefined;
@@ -0,0 +1,8 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface ErrorCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ }
5
+ export interface ErrorCaptureHandle {
6
+ teardown(): void;
7
+ }
8
+ export declare const installErrorCapture: (options: ErrorCaptureOptions) => ErrorCaptureHandle;
@@ -0,0 +1,30 @@
1
+ import type { BrowserSdkConfig, EventSeverity } from "./types";
2
+ export type { AttributeValue, BrowserSdkConfig, ConsoleCaptureConfig, ConsoleCaptureLevel, EventAttributes, EventSeverity, InputCaptureConfig, NetworkCaptureConfig, WebEvent, WebEventType, } from "./types";
3
+ export { SDK_VERSION } from "./version";
4
+ /**
5
+ * Initialize the SDK. Idempotent: repeat calls are ignored. When `consent`
6
+ * is provided, nothing new is installed — no listeners, no patches, no
7
+ * network — until it resolves true; on false (or a throw) the SDK stays
8
+ * dormant. (Patches pre-installed by `@sazabi/browser/register` exist
9
+ * but remain inert passthroughs until activation.)
10
+ */
11
+ export declare const init: (config: BrowserSdkConfig) => void;
12
+ /** Set the client-asserted user identity (`session.distinct_id`). */
13
+ export declare const identify: (distinctId: string, traits?: Record<string, unknown>) => void;
14
+ /**
15
+ * Logout: clear the client-asserted identity and rotate both session and
16
+ * window ids, so later activity on this device never threads into the
17
+ * previous user's timeline.
18
+ */
19
+ export declare const reset: () => void;
20
+ /** Emit a custom mark into the session event stream. */
21
+ export declare const addEvent: (name: string, attributes?: Record<string, unknown>) => void;
22
+ /**
23
+ * Emit an application log line (`web.event_type: "log"`) with session context
24
+ * attached. Drops silently before init/consent, like all capture.
25
+ */
26
+ export declare const log: (severity: EventSeverity, message: string, metadata?: Record<string, unknown>) => void;
27
+ /** Force-flush queued events. */
28
+ export declare const flush: () => Promise<void>;
29
+ /** Tear down all patches/listeners (restoring originals) and flush. */
30
+ export declare const shutdown: () => Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import{a as P,b as H,d as ce,e as ue,f as q,g as J,h as de,i as Q,k as le,l as pe}from"./chunk-rfm4nnme.js";var v=(e,t=4096)=>e.length>t?e.slice(0,t):e,I=(e,t="",n=0)=>{let r={};for(let[s,o]of Object.entries(e)){let i=t?`${t}.${s}`:s;if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o)&&n<4){Object.assign(r,I(o,i,n+1));continue}if(typeof o==="number"||typeof o==="boolean")r[i]=o;else if(typeof o==="string")r[i]=v(o);else try{r[i]=v(JSON.stringify(o)??"")}catch{}}return r};var R="[@sazabi/browser]",fe={error:"ERROR",warn:"WARN",info:"INFO",debug:"DEBUG"},U=1000,me=4000,ge=(e)=>{let t;if(typeof e==="string")t=e;else if(e instanceof Error)t=`${e.name}: ${e.message}`;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>U?`${t.slice(0,U)}…`:t},K=(e)=>{let t=[],n=!1;for(let r of e.levels){let s=console[r];if(typeof s!=="function"||H(s))continue;let o=function(...i){if(s.apply(this??console,i),n)return;try{if(typeof i[0]==="string"&&i[0].startsWith(R))return;n=!0;let c=i.map(ge).join(" ").slice(0,me);e.emit({type:"log",body:c||`console.${r}`,severity:fe[r],timeUnixMs:Date.now(),attributes:{"web.console.level":r}})}catch{}finally{n=!1}};P(o),console[r]=o,t.push(()=>{if(console[r]===o)console[r]=s})}return{teardown(){for(let r of t)try{r()}catch{}}}};var V=(e)=>{let t=(r)=>{try{let s=r.error,o=s instanceof Error?s.name:"Error",i=r.message||"Unknown error";e.emit({type:"error",body:v(`${o}: ${i}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":o,"exception.message":i,"exception.stacktrace":s instanceof Error?s.stack??"":"","web.error.kind":"uncaught","web.error.filename":r.filename||void 0,"web.error.lineno":r.lineno||void 0,"web.error.colno":r.colno||void 0}})}catch{}},n=(r)=>{try{let s=r.reason,o=s instanceof Error,i=o?s.name:"UnhandledRejection",c=o?s.message:String(s);e.emit({type:"error",body:v(`${i}: ${c}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":i,"exception.message":c,"exception.stacktrace":o?s.stack??"":"","web.error.kind":"unhandledrejection"}})}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),{teardown(){window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n)}}};var ye=["button","a[href]","summary",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="option"]','[role="checkbox"]','[role="switch"]','input[type="submit"]','input[type="button"]','input[type="reset"]'].join(","),w=(e)=>{if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length>64?`${t.slice(0,64)}…`:t},W=(e)=>{try{return e.closest("[data-sazabi-mask]")!==null}catch{return!0}},F=(e)=>{let t=w(e.getAttribute("data-sazabi-name"));if(t)return t;let n=w(e.getAttribute("aria-label"));if(n)return n;let r=e.getAttribute("aria-labelledby");if(!r)return;return w(r.split(/\s+/).map((s)=>document.getElementById(s)?.textContent??"").join(" "))},G=(e)=>{try{if(W(e))return;let t=F(e);if(t)return t;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)for(let r of Array.from(e.labels??[])){let s=w(r.textContent);if(s)return s}let n=w(e.getAttribute("placeholder"));if(n)return n;return w(e.getAttribute("name"))}catch{return}},B=(e)=>{try{let t=e.closest(ye);if(!t||W(t))return;let n=F(t);if(n)return n;if(t instanceof HTMLInputElement)return w(t.getAttribute("value"));return w(t.textContent)}catch{return}};var Y=1000,j=30,Ee=4,be=800,ve=200,we="a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]",O=(e)=>{let t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;if(e.id)return`#${e.id}`;let n=[],r=e;while(r&&n.length<3){let s=r.tagName.toLowerCase();if(r.id){n.unshift(`#${r.id}`);break}let o=Array.from(r.classList).slice(0,2);if(o.length>0)s+=`.${o.join(".")}`;n.unshift(s),r=r.parentElement}return n.join(" > ").slice(0,ve)},X=(e)=>{let t=0,n=0,r=[],s=Number.NEGATIVE_INFINITY,o=new Set,i=new MutationObserver(()=>{t+=1});try{i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch{}let c=(m)=>{try{let y=m.target;if(!(y instanceof Element))return;let a=performance.now(),u=O(y),d=y.tagName.toLowerCase(),l=B(y);e.emit({type:"click",body:l?`click "${l}"`:`click ${u}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}}),r.push({time:a,x:m.clientX,y:m.clientY});while(r.length>0&&a-r[0].time>Y)r.shift();let f=r.filter((g)=>Math.abs(g.x-m.clientX)<=j&&Math.abs(g.y-m.clientY)<=j);if(f.length>=Ee&&a-s>Y)s=a,e.emit({type:"rage_click",body:l?`rage click "${l}"`:`rage click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l,"web.click_count":f.length}});if(y.closest(we)){let g=t,S=n,h=window.setTimeout(()=>{o.delete(h);try{if(t===g&&n===S)e.emit({type:"dead_click",body:l?`dead click "${l}"`:`dead click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}})}catch{}},be);o.add(h)}}catch{}};return document.addEventListener("click",c,{capture:!0,passive:!0}),{notifyNavigation(){n+=1},teardown(){document.removeEventListener("click",c,{capture:!0}),i.disconnect();for(let m of o)window.clearTimeout(m);o.clear()}}};var Se=1e4,he=20,Ie=new Set(["button","submit","reset","image","checkbox","radio","range","file","color"]),Ae=(e)=>{if(e instanceof HTMLInputElement){let t=(e.type||"text").toLowerCase();return Ie.has(t)?void 0:t}if(e instanceof HTMLTextAreaElement)return"textarea";if(e instanceof HTMLSelectElement)return"select";if(e instanceof HTMLElement&&e.isContentEditable)return"contenteditable";return},z=(e)=>{let t=new Map,n=(a,u)=>{t.delete(a.element);try{e.emit({type:"input",body:a.name?`input "${a.name}"`:`input ${a.selector}`,severity:"INFO",timeUnixMs:a.startUnixMs,attributes:{"web.element.selector":a.selector,"web.element.name":a.name,"web.input.field_type":a.fieldType,"web.input.edit_count":a.editCount,"web.input.duration_ms":Math.max(0,Math.round(a.lastInputPerf-a.startPerf)),...a.pasted?{"web.input.pasted":!0}:{},"web.input.ended_by":u}})}catch{}},r=(a)=>{for(let u of Array.from(t.values()))n(u,a)},s=(a)=>{for(let u of Array.from(t.values()))if(a-u.lastInputPerf>Se)n(u,"idle")},o=(a)=>{try{let u=performance.now();s(u);let d=a.target,l=Ae(d);if(l===void 0||!(d instanceof Element))return;if(a.type==="change"&&l!=="select")return;let f=t.get(d);if(!f){if(t.size>=he)return;f={element:d,selector:O(d),name:G(d),fieldType:l,startUnixMs:Date.now(),startPerf:u,lastInputPerf:u,editCount:0,pasted:!1},t.set(d,f)}f.editCount+=1,f.lastInputPerf=u;let g=a.inputType;if(typeof g==="string"&&g.startsWith("insertFromPaste"))f.pasted=!0;if(a.type==="change"&&l==="select")n(f,"change")}catch{}},i=(a)=>{try{let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"blur")}}catch{}},c=(a)=>{try{if(a.key!=="Enter")return;let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"enter")}}catch{}},m=()=>{if(document.visibilityState==="hidden")r("hidden")},y=()=>{r("unload")};return document.addEventListener("input",o,{capture:!0,passive:!0}),document.addEventListener("change",o,{capture:!0,passive:!0}),document.addEventListener("focusout",i,{capture:!0,passive:!0}),document.addEventListener("keydown",c,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",m),window.addEventListener("pagehide",y),{notifyNavigation(){r("navigation")},teardown(){document.removeEventListener("input",o,{capture:!0}),document.removeEventListener("change",o,{capture:!0}),document.removeEventListener("focusout",i,{capture:!0}),document.removeEventListener("keydown",c,{capture:!0}),document.removeEventListener("visibilitychange",m),window.removeEventListener("pagehide",y),r("unload")}}};var _e=/^([0-9a-f]{32})\./,Te=/^[a-z0-9-]+?-([0-9a-f]{32})\./,xe=(e)=>{let t;try{t=new URL(e).hostname}catch{return}let n=(_e.exec(t)??Te.exec(t))?.[1];return n?`sazabi_public_${n}`:void 0};var Ce=(e)=>{let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.pathname.replace(/\/+$/,"");if(n.endsWith("/v1/logs"))n=n.slice(0,-8);return`${t.origin}${n}`},N=(e)=>{let t=e.intakeUrl??e.intakeHost;if(!t)return;let n=Ce(t);if(!n)return;let r=e.publicKey??xe(t);if(!r)return;return{baseUrl:n,publicKey:r}};var Z=(e)=>{if(typeof PerformanceObserver>"u")return{teardown(){}};let t=new Set,n=(o)=>{let i;try{i=new URL(o).origin}catch{return}if(t.has(i))return;t.add(i);let c=`requests to ${i} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import "@sazabi/browser/register" first.`;e.emit({type:"log",body:c,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.sdk.diagnostic":"instrumentation_gap","web.sdk.bypassed_origin":i}});try{console.warn(`${R} ${c}`)}catch{}},r=(o)=>{try{if(o.initiatorType!=="fetch"&&o.initiatorType!=="xmlhttprequest")return;let i=o.name;if(e.isInternalUrl(i))return;if(Q(i,o.startTime))return;let c=o.responseStatus??0,m=Math.round(performance.timeOrigin+o.startTime+o.duration);if(e.emit({type:"network",body:`request ${q(i)} → ${c>0?c:"observed"}`,severity:c>0?J(c):"INFO",timeUnixMs:m,attributes:{"http.response.status_code":c>0?c:void 0,"url.full":i,"web.network.kind":o.initiatorType==="fetch"?"fetch":"xhr","web.network.duration_ms":Math.round(o.duration),"web.network.source":"resource-timing"}}),e.isInjectionTarget(i))n(i)}catch{}},s;try{s=new PerformanceObserver((o)=>{for(let i of o.getEntries())r(i)}),s.observe({type:"resource",buffered:!0})}catch{return{teardown(){}}}return{teardown(){try{s.disconnect()}catch{}}}};var Re=()=>{let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")},T=(e)=>`${e}_${Date.now().toString(36)}${Re()}`,ee=(e)=>{let t=new Map;return{get(n){try{return e().getItem(n)}catch{return t.get(n)??null}},set(n,r){try{e().setItem(n,r)}catch{t.set(n,r)}},remove(n){t.delete(n);try{e().removeItem(n)}catch{}}}},Oe=(e)=>{if(!e)return;try{let t=JSON.parse(e);if(typeof t==="object"&&t!==null&&typeof t.id==="string"&&typeof t.startedAt==="number"&&typeof t.lastActivityAt==="number")return t}catch{}return},te=()=>{let e=ee(()=>window.localStorage),t=ee(()=>window.sessionStorage),n=0,r=()=>{let i=Date.now(),c=Oe(e.get("sazabi.session"));if(c&&i-c.lastActivityAt<=1800000&&i-c.startedAt<=86400000)return c;let m={id:T("sess"),startedAt:i,lastActivityAt:i};return e.set("sazabi.session",JSON.stringify(m)),n=i,m},s=t.get("sazabi.windowId");if(!s)s=T("win"),t.set("sazabi.windowId",s);let o=()=>{let i=Date.now();e.set("sazabi.session",JSON.stringify({id:T("sess"),startedAt:i,lastActivityAt:i})),n=i,s=T("win"),t.set("sazabi.windowId",s)};return{getSessionId(){return r().id},getWindowId(){return s},getDistinctId(){return e.get("sazabi.distinctId")??void 0},setDistinctId(i){let c=e.get("sazabi.distinctId")??void 0;if(c!==void 0&&c!==i)o();e.set("sazabi.distinctId",i)},reset(){e.remove("sazabi.distinctId"),o()},touch(){let i=Date.now(),c=r();if(i-n>=5000)e.set("sazabi.session",JSON.stringify({...c,lastActivityAt:i})),n=i}}};var Ne=/^[0-9a-f]{32}$/,ke=/^[0-9a-f]{16}$/,Le="0".repeat(32),Me="0".repeat(16),ne=(e)=>{let t=new Uint8Array(e);do crypto.getRandomValues(t);while(t.every((n)=>n===0));return Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")},De=(e)=>{if(typeof e!=="object"||e===null)return!1;let{traceId:t,spanId:n,traceFlags:r}=e;return typeof t==="string"&&Ne.test(t)&&t!==Le&&typeof n==="string"&&ke.test(n)&&n!==Me&&typeof r==="number"},Ue=Symbol.for("opentelemetry.js.api.1"),Pe=Symbol.for("OpenTelemetry Context Key SPAN"),He=()=>{try{let r=globalThis[Ue]?.context?.active?.()?.getValue?.(Pe)?.spanContext?.();return De(r)?r:void 0}catch{return}},Ke=(e)=>{let t=(e.traceFlags&255).toString(16).padStart(2,"0");return`00-${e.traceId}-${e.spanId}-${t}`},Ve=(e)=>{try{return e.traceState?.serialize()||void 0}catch{return}},re=(e)=>{let t=()=>({traceId:ne(16),spanId:ne(8),traceFlags:e.sampledFlag?1:0});return{forRequest(){let n=He()??t(),r={traceparent:Ke(n)},s=Ve(n);if(s)r.tracestate=s;return{headers:r,traceId:n.traceId,spanId:n.spanId}}}};var x="@sazabi/browser",A="0.2.0";var $e={DEBUG:5,INFO:9,WARN:13,ERROR:17},We=1024,Fe=(e)=>{if(typeof e==="boolean")return{boolValue:e};if(typeof e==="number")return Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e};return{stringValue:v(e)}},oe=(e)=>{let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;t.push({key:n,value:Fe(r)})}return t},ie=(e,t)=>{let n={timeUnixNano:`${e.timeUnixMs}000000`,severityNumber:$e[e.severity],severityText:e.severity,body:{stringValue:v(e.body,We)},attributes:oe({...t,...e.attributes})};if(e.traceId)n.traceId=e.traceId;if(e.spanId)n.spanId=e.spanId;return n},se=(e)=>{let t=[],n=0,r,s=!1,o=(d)=>JSON.stringify({resourceLogs:[{resource:{attributes:oe(e.resourceAttributes)},scopeLogs:[{scope:{name:x,version:A},logRecords:d}]}]}),i=o([]).length+64,c=Math.max(4096,e.maxBatchBytes-i),m=()=>{if(r!==void 0)window.clearTimeout(r),r=void 0},y=()=>{if(r!==void 0||s)return;r=window.setTimeout(()=>{r=void 0,u()},e.flushIntervalMs)},a=()=>{let d=[],l=[],f=0;for(let g of t){if(l.length>0&&f+g.bytes>c)d.push(l),l=[],f=0;l.push(g.record),f+=g.bytes}if(l.length>0)d.push(l);return t.length=0,n=0,d},u=async(d)=>{if(m(),t.length===0)return;let l=a().map((f)=>e.fetchImpl(e.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.publicKey}`},body:o(f),keepalive:d?.keepalive===!0}).catch(()=>{}));await Promise.all(l)};return{enqueue(d){if(s)return;let l=JSON.stringify(d).length+1;t.push({record:d,bytes:l}),n+=l;while(t.length>e.maxQueuedEvents){let f=t.shift();if(f)n-=f.bytes}if(n>=c)u();else y()},flush:u,async shutdown(){s=!0,await u()}}};var Ge=5000,Be=57344,Ye=500,je=["x-request-id","cf-ray","x-vercel-id","x-amz-cf-id","fly-request-id"],E,k=!1,_,C=!1,ae=(e)=>{let t=window.fetch.bind(window),n=N(e);if(!n)return;let r=`${n.baseUrl}/v1/logs`,s=te();if(C)s.reset(),C=!1;let o=_;if(_=void 0,o)s.setDistinctId(o.distinctId);let i=se({url:r,publicKey:n.publicKey,resourceAttributes:{"service.name":e.serviceName,"service.version":e.serviceVersion,"deployment.environment":e.environment,"telemetry.sdk.name":x,"telemetry.sdk.version":A,"telemetry.sdk.language":"webjs","browser.user_agent":navigator.userAgent,"browser.language":navigator.language},fetchImpl:t,flushIntervalMs:e.flushIntervalMs??Ge,maxBatchBytes:e.maxBatchBytes??Be,maxQueuedEvents:e.maxQueuedEvents??Ye}),c=(p)=>{try{s.touch();let b={"web.event_type":p.type,"session.id":s.getSessionId(),"session.window_id":s.getWindowId(),"session.distinct_id":s.getDistinctId(),"web.page.url":window.location.href,"derived.source":"sdk"};i.enqueue(ie(p,b))}catch{}},m=(p)=>p.startsWith(n.baseUrl),y=(p)=>{try{c(p())}catch{}},a=[],u=V({emit:c});a.push(()=>u.teardown());let d=X({emit:c});a.push(()=>d.teardown());let l;if(e.input?.capture!==!1)l=z({emit:c}),a.push(()=>l?.teardown());let f=ue({emit:c,onNavigate:()=>{d.notifyNavigation(),l?.notifyNavigation()}});if(a.push(()=>f.teardown()),e.console?.capture!==!1){let p=K({emit:c,levels:e.console?.levels??["error","warn"]});a.push(()=>p.teardown())}let g=e.network??{},S=g.capture??!0,h=g.propagateTraceContext??!0;if(S||h){let p=pe({emit:c,traceContext:re({sampledFlag:g.sampledFlag??!1}),capture:S,propagateTraceContext:h,allowlist:g.allowlist??[],requestIdHeaders:g.requestIdHeaders??je,isInternalUrl:m});a.push(()=>p.teardown())}if(S&&g.resourceFallback!==!1){let p=Z({emit:c,isInternalUrl:m,isInjectionTarget:de});a.push(()=>p.teardown())}let L=()=>{if(document.visibilityState==="hidden")i.flush({keepalive:!0})},M=()=>{i.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",M),a.push(()=>{document.removeEventListener("visibilitychange",L),window.removeEventListener("pagehide",M)}),E={identify(p,b){y(()=>(s.setDistinctId(p),{type:"custom",body:`identify ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":"identify",...b?I(b,"custom"):{}}}))},reset(){try{s.reset()}catch{}},addEvent(p,b){y(()=>({type:"custom",body:`custom ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":p,...b?I(b,"custom"):{}}}))},log(p,b,D){y(()=>({type:"log",body:b,severity:p,timeUnixMs:Date.now(),attributes:D?I(D):{}}))},flush(){return i.flush()},async shutdown(){for(let p of a.reverse())try{p()}catch{}le(),ce(),await i.shutdown()}},o)E.identify(o.distinctId,o.traits)},Rt=(e)=>{if(typeof window>"u")return;if(k)return;if(k=!0,!e.serviceName||!N(e)){console.warn("[@sazabi/browser] init() requires intakeUrl and serviceName; SDK disabled. Pass publicKey too if the intake URL is a proxy that carries no key.");return}if(e.consent===void 0){ae(e);return}try{Promise.resolve(e.consent()).then((t)=>{if(t===!0)ae(e)}).catch(()=>{})}catch{}},Ot=(e,t)=>{if(E)E.identify(e,t);else _={distinctId:e,traits:t}},Nt=()=>{if(E)E.reset();else C=!0,_=void 0},kt=(e,t)=>{E?.addEvent(e,t)},Lt=(e,t,n)=>{E?.log(e,t,n)},Mt=async()=>{await E?.flush()},Dt=async()=>{let e=E;E=void 0,k=!1,_=void 0,C=!1,await e?.shutdown()};export{A as SDK_VERSION,kt as addEvent,Mt as flush,Ot as identify,Rt as init,Lt as log,Nt as reset,Dt as shutdown};
2
+
3
+ //# debugId=091BD9F6835879A764756E2164756E21
4
+ //# sourceMappingURL=index.js.map