@sypnia/telemetry 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-17)
4
+
5
+ First release of `@sypnia/telemetry`, the one package for Sypnia Telemetry's JavaScript SDKs.
6
+
7
+ - Subpaths `browser`, `node`, `next`, `next/client`, `next/server` and `next/opennext`, built from the same sources as `@sypnia/browser` 0.1.2, `@sypnia/node` 0.1.2 and `@sypnia/next` 0.1.3, with the same API.
8
+ - One build with shared chunks: `next/client` and `browser` share one SDK instance, and the Node SDK that `next/server` starts is the one `node` exports.
9
+ - Default ingest endpoint: `https://telemetry.ingest.sypnia.com` (was `https://ingest.sypnia.com`, still served by the same engine). Default API for releases and source maps: `https://telemetry.api.sypnia.com` (was `https://api.sypnia.com`).
10
+ - The SDK reports itself as `@sypnia/telemetry/browser` and `@sypnia/telemetry/node`, version 0.2.0.
11
+ - `next` is an optional peer dependency.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sypnia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @sypnia/telemetry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sypnia Telemetry for JavaScript: errors, sessions, replays, page performance and traces, for the browser, Node servers and Next.js, in one package. Each runtime is a subpath; install once, import what you use.
4
+
5
+ ```bash
6
+ npm install @sypnia/telemetry
7
+ ```
8
+
9
+ | Import | For |
10
+ |---|---|
11
+ | `@sypnia/telemetry/browser` | Anything that runs in a browser |
12
+ | `@sypnia/telemetry/node` | Node servers, queues and functions (SQS, Lambda) |
13
+ | `@sypnia/telemetry/next` | `withSypnia` for `next.config.ts` (source maps at build) |
14
+ | `@sypnia/telemetry/next/client` | `instrumentation-client.ts` |
15
+ | `@sypnia/telemetry/next/server` | `instrumentation.ts` |
16
+ | `@sypnia/telemetry/next/opennext` | Next.js on AWS Lambda with OpenNext |
17
+
18
+ ```ts
19
+ // next.config.ts
20
+ import { withSypnia } from '@sypnia/telemetry/next';
21
+ export default withSypnia({}, { project: process.env.SYPNIA_PROJECT_KEY, service: 'shop-web' });
22
+
23
+ // instrumentation.ts
24
+ export { register, onRequestError } from '@sypnia/telemetry/next/server';
25
+ ```
26
+
27
+ ```ts
28
+ // A Node server: imported first in your entry file
29
+ import { init } from '@sypnia/telemetry/node';
30
+ init({ project: process.env.SYPNIA_PROJECT_KEY, service: 'shop-api' });
31
+ ```
32
+
33
+ Events go to `https://telemetry.ingest.sypnia.com` unless you set `endpoint` (a self-hosted engine). Source maps and releases go to `https://telemetry.api.sypnia.com` unless `SYPNIA_BASE_URL` says otherwise. `next` is an optional peer: only the `next/*` subpaths need it.
34
+
35
+ Docs: [telemetry.docs.sypnia.com/sdks](https://telemetry.docs.sypnia.com/sdks). It replaces `@sypnia/browser`, `@sypnia/node` and `@sypnia/next`, which stay published until their users move.
36
+
37
+ MIT licensed.
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The events the browser SDK sends, as `spec/events.schema.json` (version 1)
3
+ * defines them. Field names are short on purpose: a browser sends thousands.
4
+ */
5
+ declare const SCHEMA_VERSION: 1;
6
+ type DeviceClass = 'mobile' | 'tablet' | 'desktop';
7
+ type NavigationKind = 'load' | 'push' | 'replace' | 'traverse';
8
+ type VitalName = 'LCP' | 'INP' | 'CLS' | 'TTFB' | 'FCP';
9
+ type VitalRating = 'good' | 'needs-improvement' | 'poor';
10
+ type VitalKind = 'image' | 'text' | 'pointer' | 'keyboard';
11
+ type ErrorSource = 'window' | 'promise' | 'boundary' | 'manual';
12
+ /** 1: the default rules (typed input masked). 2: `maskAllText` (every text of the page masked too). */
13
+ type MaskPolicy = 1 | 2;
14
+ declare const CLICK_ROLES: readonly ["button", "link", "tab", "menuitem", "option", "checkbox", "radio", "switch", "select", "input", "textarea", "row", "cell", "heading", "image", "icon", "text", "other"];
15
+ type ClickRole = (typeof CLICK_ROLES)[number];
16
+ type ValidityReason = 'valueMissing' | 'typeMismatch' | 'patternMismatch' | 'tooShort' | 'tooLong' | 'rangeUnderflow' | 'rangeOverflow' | 'stepMismatch' | 'badInput' | 'customError';
17
+ interface PersonRef {
18
+ id: string;
19
+ }
20
+ interface AccountRef {
21
+ id: string;
22
+ }
23
+ /** Fields of every browser event. */
24
+ interface EventBase {
25
+ v: typeof SCHEMA_VERSION;
26
+ type: string;
27
+ ts: number;
28
+ sid: string;
29
+ did: string;
30
+ env: string;
31
+ ver: string | null;
32
+ person: PersonRef | null;
33
+ account: AccountRef | null;
34
+ url: string;
35
+ route: string;
36
+ dev: DeviceClass;
37
+ vw: number;
38
+ vh: number;
39
+ lang: string | null;
40
+ }
41
+ interface SessionStartEvent extends EventBase {
42
+ type: 'session_start';
43
+ ua: string;
44
+ ref: string | null;
45
+ sw: number;
46
+ sh: number;
47
+ tz: string;
48
+ }
49
+ interface IdentifyEvent extends Omit<EventBase, 'person' | 'account'> {
50
+ type: 'identify';
51
+ person: {
52
+ id: string;
53
+ name: string | null;
54
+ email: string | null;
55
+ };
56
+ account: {
57
+ id: string;
58
+ name: string | null;
59
+ } | null;
60
+ }
61
+ interface PageViewEvent extends EventBase {
62
+ type: 'page_view';
63
+ nav: NavigationKind;
64
+ from: string | null;
65
+ }
66
+ interface PageLeaveEvent extends EventBase {
67
+ type: 'page_leave';
68
+ dur: number;
69
+ scroll: number;
70
+ }
71
+ /** What was clicked, in words and in position. Never the value of a field. */
72
+ interface ClickFields {
73
+ sel: string;
74
+ tag: string;
75
+ txt: string | null;
76
+ crole?: ClickRole;
77
+ ctx: string | null;
78
+ href: string | null;
79
+ x: number;
80
+ y: number;
81
+ rx: number;
82
+ ry: number;
83
+ ex: number;
84
+ ey: number;
85
+ ew: number;
86
+ eh: number;
87
+ }
88
+ interface ClickEvent extends EventBase, ClickFields {
89
+ type: 'click';
90
+ }
91
+ interface RageClickEvent extends EventBase, ClickFields {
92
+ type: 'rage_click';
93
+ /** How many clicks the burst had. */
94
+ n: number;
95
+ }
96
+ interface DeadClickEvent extends EventBase, ClickFields {
97
+ type: 'dead_click';
98
+ /** How long the SDK waited, always 1,000. */
99
+ n: 1000;
100
+ }
101
+ interface VitalEvent extends EventBase {
102
+ type: 'vital';
103
+ name: VitalName;
104
+ value: number;
105
+ rating: VitalRating;
106
+ sel?: string;
107
+ kind?: VitalKind;
108
+ }
109
+ interface RequestEvent extends EventBase {
110
+ type: 'request';
111
+ method: string;
112
+ host: string | null;
113
+ path: string;
114
+ status: number;
115
+ dur: number;
116
+ tid: string;
117
+ span: string;
118
+ code?: string;
119
+ msg?: string;
120
+ }
121
+ interface ErrorEvent extends EventBase {
122
+ type: 'error';
123
+ name: string;
124
+ msg: string;
125
+ stack: string | null;
126
+ digest: string | null;
127
+ src: ErrorSource;
128
+ fp: string;
129
+ }
130
+ type CustomProps = Record<string, string | number | boolean | null>;
131
+ interface CustomEvent extends EventBase {
132
+ type: 'custom';
133
+ name: string;
134
+ props?: CustomProps;
135
+ }
136
+ interface FormInvalidEvent extends EventBase {
137
+ type: 'form_invalid';
138
+ field: string | null;
139
+ ctx: string | null;
140
+ reason: ValidityReason | null;
141
+ sel: string;
142
+ }
143
+ interface ReplayChunkEvent extends EventBase {
144
+ type: 'replay_chunk';
145
+ seq: number;
146
+ bytes: number;
147
+ mask: MaskPolicy;
148
+ full?: boolean;
149
+ }
150
+ type ReplayGapReason = 'rejected' | 'failed' | 'overflow' | 'limit';
151
+ interface ReplayGapEvent extends EventBase {
152
+ type: 'replay_gap';
153
+ seq: number;
154
+ reason: ReplayGapReason;
155
+ mask: MaskPolicy;
156
+ }
157
+ type SnapshotSkipReason = 'too_big' | 'upload_failed' | 'limit';
158
+ interface PageSnapshotEvent extends EventBase {
159
+ type: 'page_snapshot';
160
+ bytes: number;
161
+ mask: MaskPolicy;
162
+ skipped?: SnapshotSkipReason;
163
+ }
164
+ type SypniaEvent = SessionStartEvent | IdentifyEvent | PageViewEvent | PageLeaveEvent | ClickEvent | RageClickEvent | DeadClickEvent | VitalEvent | RequestEvent | ErrorEvent | CustomEvent | FormInvalidEvent | ReplayChunkEvent | ReplayGapEvent | PageSnapshotEvent;
165
+
166
+ /** A route or address in a list: a string matches the start (routes: the route and everything under it). */
167
+ type Pattern = string | RegExp;
168
+ /** What `init` takes (docs: sdks/browser#initoptions). */
169
+ interface InitOptions {
170
+ /** The project's ingest key, `spk_…`. Without it the SDK does nothing and prints one warning. */
171
+ project: string;
172
+ /** Where to send: a self-hosted engine's base URL, or a path on your own domain proxied to it. */
173
+ endpoint?: string;
174
+ /** 1 to 40 characters. `production` by default. */
175
+ environment?: string;
176
+ /** Up to 40 characters: the short git commit. */
177
+ release?: string;
178
+ /** `false` turns the SDK into a no-op. */
179
+ enabled?: boolean;
180
+ /** Prints every event, and every decision not to send one, to the console. */
181
+ debug?: boolean;
182
+ /** Paths where the SDK captures nothing at all. */
183
+ ignoreRoutes?: Pattern[];
184
+ /** When set, the only paths where the SDK captures anything (`ignoreRoutes` still applies inside them). */
185
+ allowRoutes?: Pattern[];
186
+ /** Your own way to turn a path into a route. */
187
+ routeFor?: (pathname: string) => string;
188
+ /** Treats the hash as the path, for apps that route with `#/checkout`. */
189
+ hashRouting?: boolean;
190
+ capture?: CaptureOptions;
191
+ /** Addresses outside your origin whose calls are recorded and receive the trace headers. */
192
+ traceTargets?: Pattern[];
193
+ /** Addresses outside your origin whose calls are recorded without any header. */
194
+ recordTargets?: Pattern[];
195
+ /** Calls that are never recorded. */
196
+ ignoreRequests?: Pattern[];
197
+ /** Errors whose message matches are not sent. */
198
+ ignoreErrors?: Pattern[];
199
+ /** Script addresses that are your code although they are served from another origin. */
200
+ appFrames?: Pattern[];
201
+ /** Masks every text in replays and snapshots, and sends no click label, context or field name. */
202
+ maskAllText?: boolean;
203
+ /** Elements to mask, on top of `[data-sypnia-mask]`. */
204
+ maskSelector?: string;
205
+ /** Elements to leave out of replays, on top of `[data-sypnia-block]`, frames (`iframe`, `frame`, `object`, `embed`) and `video`. */
206
+ blockSelector?: string;
207
+ /** `false` never loads the recorder. */
208
+ replay?: false | {
209
+ blockedRoutes?: Pattern[];
210
+ };
211
+ /** Page snapshots for click maps. */
212
+ snapshots?: boolean;
213
+ /** Called with each event before it is queued: return it, changed or not, or `null` to drop it. */
214
+ beforeSend?: (event: SypniaEvent) => SypniaEvent | null;
215
+ }
216
+ interface CaptureOptions {
217
+ errors?: boolean;
218
+ clicks?: boolean;
219
+ requests?: boolean;
220
+ requestFailureDetail?: boolean;
221
+ vitals?: boolean;
222
+ forms?: boolean;
223
+ }
224
+
225
+ /**
226
+ * The public functions (docs: sdks/browser#the-functions-you-call). One SDK
227
+ * per document: the runtime lives on `window`, so every bundle of a page
228
+ * shares it. None of these functions throws, and all of them do nothing on
229
+ * the server, before `init`, with `enabled: false` or after `optOut()`.
230
+ */
231
+
232
+ type IdentifyInput = {
233
+ person: {
234
+ id: string | number;
235
+ name?: string | null;
236
+ email?: string | null;
237
+ };
238
+ account?: {
239
+ id: string | number;
240
+ name?: string | null;
241
+ } | null;
242
+ } | null;
243
+ /** Says who the person is, and their account; `identify(null)` when they sign out. */
244
+ declare function identify(who: IdentifyInput): void;
245
+ /** Sends a custom event: something that matters in your app and that Sypnia cannot see by itself. */
246
+ declare function track(name: string, props?: CustomProps): void;
247
+ /** Reports an error your code caught. */
248
+ declare function reportError(error: unknown, info?: {
249
+ source?: 'manual' | 'boundary';
250
+ digest?: string;
251
+ }): void;
252
+ /** Sends what is waiting now. */
253
+ declare function flush(): Promise<void>;
254
+ /** The current session's id, 32 hex characters, or null. */
255
+ declare function getSessionId(): string | null;
256
+ /** Stops everything for this browser and remembers it (`localStorage`, `sypnia:off`). */
257
+ declare function optOut(): void;
258
+ /** Undoes `optOut`. */
259
+ declare function optIn(): void;
260
+ /**
261
+ * For framework integrations: a navigation was announced before the address
262
+ * changed (Next.js' `onRouterTransitionStart`). Apps do not call it.
263
+ */
264
+ declare function notifyNavigation(url: string, kind: 'push' | 'replace' | 'traverse'): void;
265
+
266
+ export { type CaptureOptions as C, type InitOptions as I, type Pattern as P, type SypniaEvent as S, type CustomProps as a, optOut as b, flush as f, getSessionId as g, identify as i, notifyNavigation as n, optIn as o, reportError as r, track as t };
@@ -0,0 +1,13 @@
1
+ import { I as InitOptions } from '../api-Dqlofw7I.js';
2
+ export { C as CaptureOptions, a as CustomProps, P as Pattern, S as SypniaEvent, f as flush, g as getSessionId, i as identify, n as notifyNavigation, o as optIn, b as optOut, r as reportError, t as track } from '../api-Dqlofw7I.js';
3
+
4
+ /**
5
+ * `@sypnia/browser`: errors, sessions, replay, page performance, failing API
6
+ * calls, and rage and dead clicks, with nothing a person types ever leaving
7
+ * their browser (docs: sdks/browser).
8
+ */
9
+
10
+ /** Starts the SDK. Call it once, as early as your app starts. A second call does nothing. */
11
+ declare function init(options: InitOptions): void;
12
+
13
+ export { InitOptions, init };
@@ -0,0 +1,3 @@
1
+ export { flush, getSessionId, identify, init, notifyNavigation, optIn, optOut, reportError, track } from '../chunk-WL43YGLQ.js';
2
+ import '../chunk-46P5IZVP.js';
3
+ import '../chunk-U6USLZJ2.js';
@@ -0,0 +1,307 @@
1
+ import { pathnameOf, isHexId } from './chunk-U6USLZJ2.js';
2
+
3
+ // ../browser/src/env.ts
4
+ var STORAGE_KEYS = {
5
+ session: "sypnia:session",
6
+ device: "sypnia:device",
7
+ replay: "sypnia:replay",
8
+ off: "sypnia:off"
9
+ };
10
+ function isBrowser() {
11
+ return typeof window !== "undefined" && typeof document !== "undefined";
12
+ }
13
+ function readStorage(key) {
14
+ try {
15
+ return window.localStorage.getItem(key);
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+ function writeStorage(key, value) {
21
+ try {
22
+ window.localStorage.setItem(key, value);
23
+ return true;
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+ function removeStorage(key) {
29
+ try {
30
+ window.localStorage.removeItem(key);
31
+ } catch {
32
+ }
33
+ }
34
+ function safe(fn) {
35
+ try {
36
+ return fn();
37
+ } catch {
38
+ return void 0;
39
+ }
40
+ }
41
+ function whenIdle(callback, timeoutMs = 2e3) {
42
+ const idle = globalThis.requestIdleCallback;
43
+ try {
44
+ if (typeof idle === "function") {
45
+ idle(callback, { timeout: timeoutMs });
46
+ return;
47
+ }
48
+ } catch {
49
+ }
50
+ setTimeout(callback, 0);
51
+ }
52
+ function isHidden() {
53
+ return safe(() => document.visibilityState === "hidden") === true;
54
+ }
55
+ function canGzip() {
56
+ return typeof CompressionStream === "function" && typeof Response === "function";
57
+ }
58
+ async function gzip(text) {
59
+ const bytes = new TextEncoder().encode(text);
60
+ const source = new ReadableStream({
61
+ start(controller) {
62
+ controller.enqueue(bytes);
63
+ controller.close();
64
+ }
65
+ });
66
+ return new Response(source.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
67
+ }
68
+ function retryAfterMs(value, now) {
69
+ if (!value) return null;
70
+ const seconds = Number(value);
71
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
72
+ const date = Date.parse(value);
73
+ return Number.isFinite(date) ? Math.max(0, date - now) : null;
74
+ }
75
+
76
+ // ../browser/src/limits.ts
77
+ var FLUSH_INTERVAL_MS = 1e4;
78
+ var FLUSH_AT_EVENTS = 50;
79
+ var EVENTS_PER_BATCH = 200;
80
+ var BATCH_CHARS = 40800;
81
+ var QUEUE_MAX_EVENTS = 500;
82
+ var RETRY_DELAYS_MS = [1e3, 4e3, 15e3];
83
+ var MAX_RETRY_AFTER_MS = 6e4;
84
+ var SESSION_IDLE_MS = 30 * 6e4;
85
+ var ERRORS_PER_MINUTE = 20;
86
+ var ERROR_DEDUPE_MS = 5e3;
87
+ var RAGE_WINDOW_MS = 1e3;
88
+ var RAGE_RADIUS_PX = 30;
89
+ var RAGE_MIN_CLICKS = 3;
90
+ var DEAD_WAIT_MS = 1e3;
91
+ var DEAD_DEDUPE_MS = 2e3;
92
+ var FORM_INVALID_DEDUPE_MS = 1e3;
93
+ var UNANSWERED_GRACE_MS = 1500;
94
+ var CHARS = {
95
+ env: 40,
96
+ release: 40,
97
+ name: 100,
98
+ message: 500,
99
+ stack: 4e3,
100
+ digest: 100,
101
+ label: 80,
102
+ selector: 200,
103
+ path: 500,
104
+ host: 255,
105
+ userAgent: 500,
106
+ code: 40,
107
+ failureMessage: 160,
108
+ customName: 80,
109
+ propName: 40,
110
+ propValue: 200,
111
+ personId: 128,
112
+ personName: 120,
113
+ email: 254
114
+ };
115
+ var CUSTOM_PROPS_MAX = 20;
116
+
117
+ // ../browser/src/page.ts
118
+ function deviceClassOf(width) {
119
+ if (width < 768) return "mobile";
120
+ if (width < 1024) return "tablet";
121
+ return "desktop";
122
+ }
123
+ function currentPath(hashRouting) {
124
+ const location = safe(() => window.location);
125
+ if (!location) return "/";
126
+ if (hashRouting) {
127
+ const inside = location.hash.replace(/^#!?/, "");
128
+ return pathnameOf(inside.startsWith("/") ? inside : `/${inside}`);
129
+ }
130
+ return pathnameOf(location.pathname);
131
+ }
132
+ function pageRefOf(path, routeFor) {
133
+ const url = pathnameOf(path).slice(0, 500);
134
+ let route;
135
+ try {
136
+ route = routeFor(url) || url;
137
+ } catch {
138
+ route = url;
139
+ }
140
+ return { url, route: route.slice(0, 500) };
141
+ }
142
+ function pageLanguage() {
143
+ const lang = safe(() => document.documentElement.lang || navigator.language) ?? "";
144
+ return lang ? lang.slice(0, 16) : null;
145
+ }
146
+ function viewport() {
147
+ const vw = safe(() => window.innerWidth) || 0;
148
+ return { dev: deviceClassOf(vw), vw, vh: safe(() => window.innerHeight) || 0 };
149
+ }
150
+
151
+ // ../browser/src/recorder/limits.ts
152
+ var CHUNK_INTERVAL_MS = 1e4;
153
+ var CHUNK_CHARS = 2e5;
154
+ var BUFFER_MS = 3e4;
155
+ var RECORD_CHECKOUT_MS = 10 * 6e4;
156
+ var RESYNC_DELAYS_MS = [0, 5e3, 15e3, 6e4, 5 * 6e4];
157
+ var MAX_CHUNKS_PER_SESSION = 720;
158
+ var MAX_EVENT_CHARS = 39e5;
159
+ var MAX_BUFFER_CHARS = 5e6;
160
+ var KEEPALIVE_MAX_CHARS = 6e4;
161
+ var GZIP_ABOVE_CHARS = 2048;
162
+ var PARK_BASE_MS = 1e4;
163
+ var PARK_MAX_MS = 5 * 6e4;
164
+ var SNAPSHOT_DELAY_MS = 2e3;
165
+ var QUIET_MS = 500;
166
+ var MAX_QUIET_WAIT_MS = 1e4;
167
+ var SNAPSHOT_CHARS = 3e6;
168
+
169
+ // ../browser/src/http.ts
170
+ async function readAnswer(response) {
171
+ try {
172
+ const body = await response.json();
173
+ return body && typeof body === "object" ? body : {};
174
+ } catch {
175
+ return {};
176
+ }
177
+ }
178
+ function slowDownOf(body) {
179
+ return body.slow_down && typeof body.slow_down === "object" ? body.slow_down : null;
180
+ }
181
+ async function outcomeOf(response, now) {
182
+ const status = response.status;
183
+ if (response.ok) return { kind: "stored", slowDown: slowDownOf(await readAnswer(response)) };
184
+ const body = await readAnswer(response);
185
+ const code = typeof body.error?.code === "string" ? body.error.code : "";
186
+ if (status === 429 && code === "limit_reached") return { kind: "limit", slowDown: slowDownOf(body) };
187
+ if (status === 408 || status === 429 || status >= 500) {
188
+ const wait = retryAfterMs(safe(() => response.headers.get("retry-after")) ?? null, now);
189
+ return { kind: "retry", retryAfterMs: wait, throttled: status === 429 };
190
+ }
191
+ if (status === 403 && code === "not_recordable") return { kind: "not_recordable" };
192
+ if (status === 401 || status === 403) return { kind: "refused" };
193
+ if (status === 422) return { kind: "session_full" };
194
+ return { kind: "rejected" };
195
+ }
196
+ async function encode(body) {
197
+ if (body.length <= GZIP_ABOVE_CHARS || !canGzip()) return body;
198
+ try {
199
+ return await gzip(body);
200
+ } catch {
201
+ return body;
202
+ }
203
+ }
204
+ function isGzip(payload) {
205
+ if (typeof payload === "string" || payload.byteLength < 2) return false;
206
+ const head = new Uint8Array(payload, 0, 2);
207
+ return head[0] === 31 && head[1] === 139;
208
+ }
209
+ function sizeOf(payload) {
210
+ return typeof payload === "string" ? payload.length : payload.byteLength;
211
+ }
212
+ async function post(url, key, payload, now) {
213
+ try {
214
+ const response = await fetch(url, {
215
+ method: "POST",
216
+ // A small body survives the page going away.
217
+ keepalive: sizeOf(payload) <= KEEPALIVE_MAX_CHARS,
218
+ credentials: "omit",
219
+ // A gzipped body says so: hosts in front of the engine (an AWS Lambda function URL) treat a body without
220
+ // Content-Encoding as text and corrupt the bytes (engine design note 67). The engine still sniffs 1f 8b.
221
+ headers: {
222
+ authorization: `Bearer ${key}`,
223
+ "content-type": "application/json",
224
+ ...isGzip(payload) ? { "content-encoding": "gzip" } : {}
225
+ },
226
+ body: payload
227
+ });
228
+ return await outcomeOf(response, now());
229
+ } catch {
230
+ return { kind: "retry", retryAfterMs: null, throttled: false };
231
+ }
232
+ }
233
+ function beacon(url, key, body) {
234
+ try {
235
+ if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") return false;
236
+ const target = `${url}${url.includes("?") ? "&" : "?"}key=${encodeURIComponent(key)}`;
237
+ return navigator.sendBeacon(target, new Blob([body], { type: "text/plain;charset=UTF-8" }));
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ // ../browser/src/decision.ts
244
+ var SNAPSHOTS_PER_SESSION = 5;
245
+ var MODES = ["record", "buffer", "off"];
246
+ function fallbackDecision(sid, snapshots) {
247
+ return { sid, mode: "buffer", snapshots, seq: 0, snaps: [], maskAllText: false, blockedRoutes: [], slowDown: null };
248
+ }
249
+ function rate(value, fallback) {
250
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : fallback;
251
+ }
252
+ function strings(value) {
253
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
254
+ }
255
+ function decisionFrom(sid, config, random) {
256
+ const replay = config.replay ?? {};
257
+ const mode = MODES.includes(replay.mode) ? replay.mode : "buffer";
258
+ const slowDown = config.slow_down && typeof config.slow_down === "object" ? config.slow_down : null;
259
+ return {
260
+ sid,
261
+ mode: slowDown?.replay === false ? "off" : mode,
262
+ snapshots: slowDown?.replay !== false && random() < rate(config.snapshots?.sample_rate, 0.5),
263
+ seq: 0,
264
+ snaps: [],
265
+ maskAllText: replay.mask_all_text === true,
266
+ blockedRoutes: strings(replay.blocked_routes),
267
+ slowDown
268
+ };
269
+ }
270
+ function readDecision(sid) {
271
+ const raw = readStorage(STORAGE_KEYS.replay);
272
+ if (!raw) return null;
273
+ try {
274
+ const parsed = JSON.parse(raw);
275
+ if (parsed.sid !== sid || !isHexId(sid) || !MODES.includes(parsed.mode)) return null;
276
+ const seq = typeof parsed.seq === "number" && Number.isInteger(parsed.seq) && parsed.seq >= 0 ? parsed.seq : 0;
277
+ return {
278
+ sid,
279
+ mode: parsed.mode,
280
+ snapshots: parsed.snapshots === true,
281
+ seq,
282
+ snaps: strings(parsed.snaps).slice(0, SNAPSHOTS_PER_SESSION),
283
+ maskAllText: parsed.maskAllText === true,
284
+ blockedRoutes: strings(parsed.blockedRoutes),
285
+ slowDown: parsed.slowDown && typeof parsed.slowDown === "object" ? parsed.slowDown : null
286
+ };
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+ function writeDecision(decision) {
292
+ const stored = readDecision(decision.sid);
293
+ let mode = decision.mode;
294
+ let slowDown = decision.slowDown ?? null;
295
+ if (stored) {
296
+ if (stored.seq > decision.seq) decision.seq = stored.seq;
297
+ for (const route of stored.snaps) if (!decision.snaps.includes(route)) decision.snaps.push(route);
298
+ if (stored.mode === "off" || stored.mode === "record" && mode === "buffer") mode = stored.mode;
299
+ slowDown ??= stored.slowDown;
300
+ }
301
+ writeStorage(
302
+ STORAGE_KEYS.replay,
303
+ JSON.stringify({ ...decision, mode, snaps: decision.snaps.slice(0, SNAPSHOTS_PER_SESSION), slowDown })
304
+ );
305
+ }
306
+
307
+ export { BATCH_CHARS, BUFFER_MS, CHARS, CHUNK_CHARS, CHUNK_INTERVAL_MS, CUSTOM_PROPS_MAX, DEAD_DEDUPE_MS, DEAD_WAIT_MS, ERRORS_PER_MINUTE, ERROR_DEDUPE_MS, EVENTS_PER_BATCH, FLUSH_AT_EVENTS, FLUSH_INTERVAL_MS, FORM_INVALID_DEDUPE_MS, KEEPALIVE_MAX_CHARS, MAX_BUFFER_CHARS, MAX_CHUNKS_PER_SESSION, MAX_EVENT_CHARS, MAX_QUIET_WAIT_MS, MAX_RETRY_AFTER_MS, PARK_BASE_MS, PARK_MAX_MS, QUEUE_MAX_EVENTS, QUIET_MS, RAGE_MIN_CLICKS, RAGE_RADIUS_PX, RAGE_WINDOW_MS, RECORD_CHECKOUT_MS, RESYNC_DELAYS_MS, RETRY_DELAYS_MS, SESSION_IDLE_MS, SNAPSHOTS_PER_SESSION, SNAPSHOT_CHARS, SNAPSHOT_DELAY_MS, STORAGE_KEYS, UNANSWERED_GRACE_MS, beacon, currentPath, decisionFrom, deviceClassOf, encode, fallbackDecision, isBrowser, isGzip, isHidden, outcomeOf, pageLanguage, pageRefOf, post, readDecision, readStorage, removeStorage, safe, viewport, whenIdle, writeDecision, writeStorage };
@@ -0,0 +1,24 @@
1
+ import { deserializePatterns } from './chunk-WUAOTFVV.js';
2
+
3
+ // ../next/src/start.ts
4
+ var NEXT_INTERNALS = ["/_next/static", "/_next/image", "/_next/webpack-hmr", "/__nextjs_original-stack-frame"];
5
+ async function startNode(config, dir = process.cwd()) {
6
+ const [sdk, routes] = await Promise.all([import('./node/index.js'), import('./routes-AN3GFTBW.js')]);
7
+ const routeFor = routes.loadRouteResolver(config.distDir, config.basePath, dir) ?? (config.routes?.length ? (await import('./route-names-RNBNXKZI.js')).routeNamer(config.routes, config.basePath) : null);
8
+ const { ignoreRoutes, allowRoutes, ...server } = config.server;
9
+ sdk.init({
10
+ ...server,
11
+ ignoreRoutes: [...NEXT_INTERNALS, ...deserializePatterns(ignoreRoutes) ?? []],
12
+ ...allowRoutes ? { allowRoutes: deserializePatterns(allowRoutes) ?? [] } : {},
13
+ project: config.project,
14
+ endpoint: config.endpoint,
15
+ service: config.service,
16
+ environment: config.environment,
17
+ ...config.release ? { release: config.release } : {},
18
+ debug: config.debug,
19
+ ...routeFor ? { routeFor } : {}
20
+ });
21
+ return sdk;
22
+ }
23
+
24
+ export { startNode };