@starko-one/sdk 0.0.0-stage → 0.1.0-beta.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/LICENSE +17 -0
  3. package/NOTICE +58 -0
  4. package/README.md +81 -2
  5. package/dist/api-B5IHeINe.d.ts +558 -0
  6. package/dist/api-DR4HazCu.d.cts +558 -0
  7. package/dist/browser/index.cjs +168 -0
  8. package/dist/browser/index.d.cts +131 -0
  9. package/dist/browser/index.d.ts +131 -0
  10. package/dist/browser/index.js +7 -0
  11. package/dist/build/rollup.cjs +22 -0
  12. package/dist/build/rollup.d.cts +34 -0
  13. package/dist/build/rollup.d.ts +34 -0
  14. package/dist/build/rollup.js +3 -0
  15. package/dist/build/vite.cjs +51 -0
  16. package/dist/build/vite.d.cts +23 -0
  17. package/dist/build/vite.d.ts +23 -0
  18. package/dist/build/vite.js +46 -0
  19. package/dist/build/webpack.cjs +18 -0
  20. package/dist/build/webpack.d.cts +39 -0
  21. package/dist/build/webpack.d.ts +39 -0
  22. package/dist/build/webpack.js +3 -0
  23. package/dist/chunk-7HYGODU6.cjs +583 -0
  24. package/dist/chunk-A5M4NOVT.js +413 -0
  25. package/dist/chunk-A7MYYWMP.cjs +15 -0
  26. package/dist/chunk-BAQA47FM.js +1113 -0
  27. package/dist/chunk-CM7HM6CC.js +563 -0
  28. package/dist/chunk-DFYNIWUN.js +608 -0
  29. package/dist/chunk-DMVVCGKO.cjs +96 -0
  30. package/dist/chunk-FARGXYJ4.cjs +56 -0
  31. package/dist/chunk-G3MYIAX2.js +1226 -0
  32. package/dist/chunk-G4NAVZQ4.js +249 -0
  33. package/dist/chunk-GH7RYPKS.js +96 -0
  34. package/dist/chunk-HADYYQNL.cjs +134 -0
  35. package/dist/chunk-HOQPAB4X.js +178 -0
  36. package/dist/chunk-J5RU73SW.js +214 -0
  37. package/dist/chunk-JNAJ3YZB.cjs +223 -0
  38. package/dist/chunk-KN7H22EQ.cjs +659 -0
  39. package/dist/chunk-LDQ4I7FZ.cjs +1151 -0
  40. package/dist/chunk-NPGESRVQ.js +1212 -0
  41. package/dist/chunk-OPWM5V7A.cjs +258 -0
  42. package/dist/chunk-PYYWPIFL.cjs +1230 -0
  43. package/dist/chunk-R7JLZ4WO.cjs +115 -0
  44. package/dist/chunk-SC6VQSES.js +213 -0
  45. package/dist/chunk-TPSJGLR3.cjs +220 -0
  46. package/dist/chunk-UKBY6HPC.js +131 -0
  47. package/dist/chunk-VRSEHRBX.cjs +185 -0
  48. package/dist/chunk-X74AONZA.js +90 -0
  49. package/dist/chunk-XW3I5CJN.js +12 -0
  50. package/dist/chunk-XW56FKKJ.js +53 -0
  51. package/dist/chunk-Z3G5SW7R.cjs +1251 -0
  52. package/dist/chunk-ZVMAN7OO.cjs +431 -0
  53. package/dist/cli/index.cjs +1487 -0
  54. package/dist/common-ARWXbeS3.d.ts +36 -0
  55. package/dist/common-CwIFh2hK.d.cts +36 -0
  56. package/dist/dedupe-eHBIfUUD.d.cts +13 -0
  57. package/dist/dedupe-fw8aNtt4.d.ts +13 -0
  58. package/dist/handler-DTZ4Rzcf.d.ts +82 -0
  59. package/dist/handler-_00lctTI.d.cts +82 -0
  60. package/dist/index.cjs +277 -0
  61. package/dist/index.d.cts +187 -0
  62. package/dist/index.d.ts +187 -0
  63. package/dist/index.js +4 -0
  64. package/dist/next/client.cjs +113 -0
  65. package/dist/next/client.d.cts +26 -0
  66. package/dist/next/client.d.ts +26 -0
  67. package/dist/next/client.js +41 -0
  68. package/dist/next/config.cjs +275 -0
  69. package/dist/next/config.d.cts +193 -0
  70. package/dist/next/config.d.ts +193 -0
  71. package/dist/next/config.js +261 -0
  72. package/dist/next/index.cjs +148 -0
  73. package/dist/next/index.d.cts +32 -0
  74. package/dist/next/index.d.ts +32 -0
  75. package/dist/next/index.js +59 -0
  76. package/dist/node/index.cjs +257 -0
  77. package/dist/node/index.d.cts +145 -0
  78. package/dist/node/index.d.ts +145 -0
  79. package/dist/node/index.js +83 -0
  80. package/dist/options-0BhybO54.d.cts +47 -0
  81. package/dist/options-0BhybO54.d.ts +47 -0
  82. package/dist/react/index.cjs +107 -0
  83. package/dist/react/index.d.cts +84 -0
  84. package/dist/react/index.d.ts +84 -0
  85. package/dist/react/index.js +103 -0
  86. package/dist/scope-Bvh45bOf.d.cts +404 -0
  87. package/dist/scope-Bvh45bOf.d.ts +404 -0
  88. package/dist/server-edge-BPOGA3GH.cjs +51 -0
  89. package/dist/server-edge-GYKAJREU.js +48 -0
  90. package/dist/server-node-HYK2OB2J.js +24 -0
  91. package/dist/server-node-J2DBAHDV.cjs +27 -0
  92. package/dist/session-C_WzbEN2.d.cts +4 -0
  93. package/dist/session-C_WzbEN2.d.ts +4 -0
  94. package/dist/session-propagation-B7REA7uy.d.cts +30 -0
  95. package/dist/session-propagation-BnJjKJbR.d.ts +30 -0
  96. package/dist/starko.min.js +6 -0
  97. package/docs/browser.md +381 -0
  98. package/docs/configuration.md +269 -0
  99. package/docs/nextjs.md +312 -0
  100. package/docs/node.md +376 -0
  101. package/docs/other-backends.md +232 -0
  102. package/docs/privacy.md +112 -0
  103. package/docs/react.md +187 -0
  104. package/docs/source-maps.md +332 -0
  105. package/docs/troubleshooting.md +171 -0
  106. package/docs/widget.md +84 -0
  107. package/docs/wire-format.md +367 -0
  108. package/package.json +98 -4
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ // src/types/wire.ts
11
+ var WIRE_VERSION = 1;
12
+ var LIMITS = {
13
+ MAX_EVENTS_PER_ENVELOPE: 20,
14
+ /** Bytes of the request body as sent (after gzip when compressed). */
15
+ MAX_BODY_BYTES: 512 * 1024,
16
+ /** Bytes after decompression. */
17
+ MAX_INFLATED_BYTES: 2 * 1024 * 1024,
18
+ MAX_EXCEPTIONS: 10,
19
+ /** Beyond it the 25 most recent and the 25 oldest frames are kept (the middle of a deep recursion is dropped). */
20
+ MAX_FRAMES: 50,
21
+ /** Distinct `chunk_id`s the server resolves per event; frames of further chunks stay unresolved. */
22
+ MAX_CHUNK_IDS_PER_EVENT: 8,
23
+ /** Nesting depth of the JSON body; deeper bodies are rejected before any processing. */
24
+ MAX_JSON_DEPTH: 20,
25
+ MAX_TYPE: 200,
26
+ MAX_VALUE: 2e3,
27
+ MAX_FILENAME: 1e3,
28
+ MAX_FUNCTION: 300,
29
+ MAX_CONTEXT_LINE: 300,
30
+ /** Lines in each of pre_context / post_context. */
31
+ MAX_CONTEXT_LINES: 7,
32
+ MAX_BREADCRUMBS: 50,
33
+ /** Serialized bytes of all breadcrumbs. */
34
+ MAX_BREADCRUMB_BYTES: 32 * 1024,
35
+ MAX_TAGS: 50,
36
+ MAX_TAG_KEY: 64,
37
+ MAX_TAG_VALUE: 256,
38
+ /** Serialized bytes of `extra` and of `contexts`, each. */
39
+ MAX_EXTRA_BYTES: 16 * 1024,
40
+ MAX_FINGERPRINT: 128,
41
+ MAX_RELEASE: 128,
42
+ MAX_ENVIRONMENT: 64,
43
+ MAX_URL: 2048
44
+ };
45
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9-]{8,70}$/;
46
+ var PATHS = {
47
+ INGEST: "/api/v1/ingest/errors",
48
+ CONFIG: "/api/v1/ingest/config",
49
+ SOURCEMAPS_CHECK: "/api/v1/sourcemaps/check",
50
+ SOURCEMAPS_UPLOAD: "/api/v1/sourcemaps/upload",
51
+ SOURCEMAPS_COMPLETE: "/api/v1/sourcemaps/complete"
52
+ };
53
+ var DEFAULT_HOST = "https://v2.starko.one";
54
+ var SENSITIVE_QUERY_PARAMS = [
55
+ "token",
56
+ "access_token",
57
+ "id_token",
58
+ "refresh_token",
59
+ "code",
60
+ "key",
61
+ "api_key",
62
+ "apikey",
63
+ "secret",
64
+ "password",
65
+ "passwd",
66
+ "pwd",
67
+ "auth",
68
+ "authorization",
69
+ "session",
70
+ "sessionid",
71
+ "sid",
72
+ "sig",
73
+ "signature",
74
+ "jwt",
75
+ "otp",
76
+ "pin",
77
+ "email",
78
+ "phone",
79
+ "ssn",
80
+ "x-amz-signature",
81
+ "x-amz-credential",
82
+ "x-amz-security-token"
83
+ ];
84
+ var REDACTED = "[redacted]";
85
+ var SOURCEMAP_PART_BYTES = 3 * 1024 * 1024;
86
+ var SOURCEMAP_MAX_BYTES = 64 * 1024 * 1024;
87
+ var SOURCEMAP_MAX_PARTS = 32;
88
+ var SOURCEMAP_MAX_CHUNKS_PER_CHECK = 500;
89
+ var DEBUG_ID_GLOBAL = "_starkoDebugIds";
90
+ var NATIVE_DEBUG_ID_GLOBAL = "_debugIds";
91
+ var RELEASE_GLOBAL = "_starkoRelease";
92
+ var DEBUG_ID_COMMENT = "//# debugId=";
93
+ var DEBUG_ID_NAMESPACE = "6f2d3c1e-9b4a-4f07-8a55-7c1e0d9b2a41";
94
+
95
+ // package.json
96
+ var version = "0.1.0-beta.0";
97
+
98
+ exports.DEBUG_ID_COMMENT = DEBUG_ID_COMMENT;
99
+ exports.DEBUG_ID_GLOBAL = DEBUG_ID_GLOBAL;
100
+ exports.DEBUG_ID_NAMESPACE = DEBUG_ID_NAMESPACE;
101
+ exports.DEFAULT_HOST = DEFAULT_HOST;
102
+ exports.LIMITS = LIMITS;
103
+ exports.NATIVE_DEBUG_ID_GLOBAL = NATIVE_DEBUG_ID_GLOBAL;
104
+ exports.PATHS = PATHS;
105
+ exports.REDACTED = REDACTED;
106
+ exports.RELEASE_GLOBAL = RELEASE_GLOBAL;
107
+ exports.SENSITIVE_QUERY_PARAMS = SENSITIVE_QUERY_PARAMS;
108
+ exports.SESSION_ID_PATTERN = SESSION_ID_PATTERN;
109
+ exports.SOURCEMAP_MAX_BYTES = SOURCEMAP_MAX_BYTES;
110
+ exports.SOURCEMAP_MAX_CHUNKS_PER_CHECK = SOURCEMAP_MAX_CHUNKS_PER_CHECK;
111
+ exports.SOURCEMAP_MAX_PARTS = SOURCEMAP_MAX_PARTS;
112
+ exports.SOURCEMAP_PART_BYTES = SOURCEMAP_PART_BYTES;
113
+ exports.WIRE_VERSION = WIRE_VERSION;
114
+ exports.__require = __require;
115
+ exports.version = version;
@@ -0,0 +1,213 @@
1
+ import { getRequestData } from './chunk-A5M4NOVT.js';
2
+ import { parseRetryAfter } from './chunk-UKBY6HPC.js';
3
+ import { nodeStackParser, Client, DEFAULT_REMOTE_CONFIG, isSuppressed } from './chunk-NPGESRVQ.js';
4
+ import { safeStringify, safely } from './chunk-DFYNIWUN.js';
5
+ import { PATHS } from './chunk-GH7RYPKS.js';
6
+
7
+ // src/node/in-app.ts
8
+ var NOT_APP_FILE = /^(?:node:|internal[\\/]|<anonymous>$|native$|\[native code\]$|wasm:\/\/|evalmachine\.)/;
9
+ var NODE_MODULES = /[\\/]node_modules[\\/]/;
10
+ function ownRoot() {
11
+ try {
12
+ const file = nodeStackParser(new Error().stack || "")[0]?.filename;
13
+ if (!file) return void 0;
14
+ const path = file.replace(/^file:\/\//, "");
15
+ const dist = /^(.*[\\/]@starko-one[\\/]sdk[\\/]dist[\\/])/.exec(path);
16
+ if (dist) return dist[1];
17
+ const src = /^(.*[\\/]src[\\/])node[\\/]in-app\.[cm]?[jt]s$/.exec(path);
18
+ if (src) return src[1];
19
+ } catch {
20
+ }
21
+ return void 0;
22
+ }
23
+ var OWN_ROOT = ownRoot();
24
+ function nodeIsInApp(filename) {
25
+ if (!filename) return false;
26
+ if (NOT_APP_FILE.test(filename) || NODE_MODULES.test(filename)) return false;
27
+ if (OWN_ROOT && filename.replace(/^file:\/\//, "").startsWith(OWN_ROOT)) return false;
28
+ return true;
29
+ }
30
+
31
+ // src/node/integrations/request-data.ts
32
+ function requestDataIntegration() {
33
+ return {
34
+ name: "RequestData",
35
+ processEvent(event) {
36
+ const r = getRequestData();
37
+ if (!r) return event;
38
+ const request = { ...event.request };
39
+ if (r.method && !request.method) request.method = r.method;
40
+ if (r.url && !request.url) request.url = r.url;
41
+ if (r.route && !request.route) request.route = r.route;
42
+ if (Object.keys(request).length) event.request = request;
43
+ return event;
44
+ }
45
+ };
46
+ }
47
+
48
+ // src/node/transport.ts
49
+ var GZIP_THRESHOLD = 4 * 1024;
50
+ var SEND_TIMEOUT_MS = 1e4;
51
+ var CONFIG_TIMEOUT_MS = 5e3;
52
+ function deadline(ms) {
53
+ try {
54
+ return typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(ms) : void 0;
55
+ } catch {
56
+ return void 0;
57
+ }
58
+ }
59
+ async function gzip(body) {
60
+ try {
61
+ if (typeof CompressionStream !== "function" || typeof Blob !== "function") return void 0;
62
+ const stream = new Blob([body]).stream().pipeThrough(new CompressionStream("gzip"));
63
+ return new Uint8Array(await new Response(stream).arrayBuffer());
64
+ } catch {
65
+ return void 0;
66
+ }
67
+ }
68
+ function makeServerFetchTransport(options) {
69
+ const host = options.host.replace(/\/+$/, "");
70
+ const apiKey = typeof options.apiKey === "string" && options.apiKey ? options.apiKey : void 0;
71
+ const getFetch = () => options.fetchImpl ?? (typeof fetch === "function" ? fetch : void 0);
72
+ return {
73
+ async send(envelope) {
74
+ const f = getFetch();
75
+ if (!f) return { status: 0 };
76
+ try {
77
+ const json = safeStringify(envelope);
78
+ const headers = { ...options.headers, "Content-Type": "application/json" };
79
+ delete headers.Authorization;
80
+ delete headers.authorization;
81
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
82
+ let body = json;
83
+ if (json.length > GZIP_THRESHOLD) {
84
+ const zipped = await gzip(json);
85
+ if (zipped) {
86
+ body = zipped;
87
+ headers["Content-Encoding"] = "gzip";
88
+ }
89
+ }
90
+ const res = await f(host + PATHS.INGEST, { method: "POST", body, headers, redirect: "manual", signal: deadline(SEND_TIMEOUT_MS) });
91
+ const out = { status: res.type === "opaqueredirect" ? 302 : res.status };
92
+ try {
93
+ out.retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
94
+ } catch {
95
+ }
96
+ if (out.status >= 300 && out.status < 400) {
97
+ try {
98
+ const location = res.headers.get("Location");
99
+ if (location) out.location = location;
100
+ } catch {
101
+ }
102
+ } else if (out.status >= 400) {
103
+ try {
104
+ const reason = (await res.json())?.data?.reason;
105
+ if (typeof reason === "string") out.reason = reason;
106
+ } catch {
107
+ }
108
+ } else {
109
+ try {
110
+ await res.arrayBuffer();
111
+ } catch {
112
+ }
113
+ }
114
+ return out;
115
+ } catch {
116
+ return { status: 0 };
117
+ }
118
+ },
119
+ async fetchConfig() {
120
+ const f = getFetch();
121
+ if (!f) return null;
122
+ try {
123
+ const res = await f(`${host}${PATHS.CONFIG}?workspace=${encodeURIComponent(options.workspaceKey)}`, { method: "GET", redirect: "manual", signal: deadline(CONFIG_TIMEOUT_MS) });
124
+ if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") return null;
125
+ const json = await res.json();
126
+ const data = json && typeof json === "object" ? json.data : null;
127
+ return data && typeof data === "object" ? data : null;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+ };
133
+ }
134
+
135
+ // src/node/server-defaults.ts
136
+ var SERVER_DEFAULTS = {
137
+ defaultMaxEventsPerLifetime: Infinity,
138
+ defaultMaxEventsPerMinute: 300,
139
+ // A burst at start-up (the database is down) must not lose events while the first batches go out.
140
+ defaultMaxQueueSize: 500,
141
+ // After repeated failed batches sending pauses for this long (a browser pauses for the page load).
142
+ failurePauseMs: 5 * 6e4
143
+ };
144
+
145
+ // src/node/server-client.ts
146
+ var LAZY_CONFIG_TIMEOUT_MS = 5e3;
147
+ var ServerClient = class extends Client {
148
+ constructor(options) {
149
+ super(options);
150
+ /** The config has not been read yet (`remote` is the default until it is). */
151
+ this.provisional = false;
152
+ this.skipped = new Promise((r) => this.skip = r);
153
+ }
154
+ configGate() {
155
+ return () => this.readLazyConfig();
156
+ }
157
+ loadRemoteConfig() {
158
+ if (this.options.remoteConfig === false || !this.transport.fetchConfig) return super.loadRemoteConfig();
159
+ this.remote = DEFAULT_REMOTE_CONFIG;
160
+ this.provisional = true;
161
+ }
162
+ /** Read the config once, when the queue is about to send for the first time. Never rejects. */
163
+ readLazyConfig() {
164
+ if (!this.provisional) return Promise.resolve();
165
+ this.lazyConfig || (this.lazyConfig = this.readConfig(LAZY_CONFIG_TIMEOUT_MS, (rc) => {
166
+ this.provisional = false;
167
+ this.applyLateConfig(rc);
168
+ }));
169
+ return Promise.race([this.lazyConfig, this.skipped]);
170
+ }
171
+ /** A config read after events were queued: it applies to what is still unsent. */
172
+ applyLateConfig(rc) {
173
+ this.remote = rc;
174
+ if (!rc.enabled) {
175
+ this.logger.log("config: disabled");
176
+ this.shutdown("config");
177
+ return;
178
+ }
179
+ if (rc.suppress.length || rc.sample_rate < 1) this.queue.filter((e) => !isSuppressed(e, rc.suppress) && (rc.sample_rate >= 1 || Math.random() < rc.sample_rate));
180
+ }
181
+ /**
182
+ * True while a flush now would only wait: a request is already in flight,
183
+ * or sending waits out a back-off, a 429 or a failure pause. Server hooks
184
+ * skip their flush then (the queue sends on its own).
185
+ */
186
+ isSendBusy() {
187
+ return this.queue.isSending || this.queue.isBlocked;
188
+ }
189
+ /**
190
+ * A shutdown deadline passed: abort the requests in flight and start no
191
+ * new one for 30 s (the queue keeps its events; a process that goes on
192
+ * after all sends them then). Never throws.
193
+ */
194
+ abortRequests() {
195
+ safely(this.logger, "abort", () => {
196
+ this.queue.holdOff(3e4);
197
+ const t = this.transport;
198
+ if (typeof t.abort === "function") t.abort();
199
+ }, void 0);
200
+ }
201
+ /**
202
+ * Send without waiting for the remote config (the process is about to end:
203
+ * the fatal path, `beforeExit`, SIGTERM / SIGINT), also when a send is
204
+ * already waiting for it. A config read already under way still applies
205
+ * to what is unsent when it arrives.
206
+ */
207
+ skipRemoteConfig() {
208
+ this.provisional = false;
209
+ this.skip();
210
+ }
211
+ };
212
+
213
+ export { GZIP_THRESHOLD, SERVER_DEFAULTS, ServerClient, makeServerFetchTransport, nodeIsInApp, requestDataIntegration };
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ var chunkZVMAN7OO_cjs = require('./chunk-ZVMAN7OO.cjs');
4
+ var chunkHADYYQNL_cjs = require('./chunk-HADYYQNL.cjs');
5
+ var chunkPYYWPIFL_cjs = require('./chunk-PYYWPIFL.cjs');
6
+ var chunkKN7H22EQ_cjs = require('./chunk-KN7H22EQ.cjs');
7
+ var chunkR7JLZ4WO_cjs = require('./chunk-R7JLZ4WO.cjs');
8
+
9
+ // src/node/in-app.ts
10
+ var NOT_APP_FILE = /^(?:node:|internal[\\/]|<anonymous>$|native$|\[native code\]$|wasm:\/\/|evalmachine\.)/;
11
+ var NODE_MODULES = /[\\/]node_modules[\\/]/;
12
+ function ownRoot() {
13
+ try {
14
+ const file = chunkPYYWPIFL_cjs.nodeStackParser(new Error().stack || "")[0]?.filename;
15
+ if (!file) return void 0;
16
+ const path = file.replace(/^file:\/\//, "");
17
+ const dist = /^(.*[\\/]@starko-one[\\/]sdk[\\/]dist[\\/])/.exec(path);
18
+ if (dist) return dist[1];
19
+ const src = /^(.*[\\/]src[\\/])node[\\/]in-app\.[cm]?[jt]s$/.exec(path);
20
+ if (src) return src[1];
21
+ } catch {
22
+ }
23
+ return void 0;
24
+ }
25
+ var OWN_ROOT = ownRoot();
26
+ function nodeIsInApp(filename) {
27
+ if (!filename) return false;
28
+ if (NOT_APP_FILE.test(filename) || NODE_MODULES.test(filename)) return false;
29
+ if (OWN_ROOT && filename.replace(/^file:\/\//, "").startsWith(OWN_ROOT)) return false;
30
+ return true;
31
+ }
32
+
33
+ // src/node/integrations/request-data.ts
34
+ function requestDataIntegration() {
35
+ return {
36
+ name: "RequestData",
37
+ processEvent(event) {
38
+ const r = chunkZVMAN7OO_cjs.getRequestData();
39
+ if (!r) return event;
40
+ const request = { ...event.request };
41
+ if (r.method && !request.method) request.method = r.method;
42
+ if (r.url && !request.url) request.url = r.url;
43
+ if (r.route && !request.route) request.route = r.route;
44
+ if (Object.keys(request).length) event.request = request;
45
+ return event;
46
+ }
47
+ };
48
+ }
49
+
50
+ // src/node/transport.ts
51
+ var GZIP_THRESHOLD = 4 * 1024;
52
+ var SEND_TIMEOUT_MS = 1e4;
53
+ var CONFIG_TIMEOUT_MS = 5e3;
54
+ function deadline(ms) {
55
+ try {
56
+ return typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(ms) : void 0;
57
+ } catch {
58
+ return void 0;
59
+ }
60
+ }
61
+ async function gzip(body) {
62
+ try {
63
+ if (typeof CompressionStream !== "function" || typeof Blob !== "function") return void 0;
64
+ const stream = new Blob([body]).stream().pipeThrough(new CompressionStream("gzip"));
65
+ return new Uint8Array(await new Response(stream).arrayBuffer());
66
+ } catch {
67
+ return void 0;
68
+ }
69
+ }
70
+ function makeServerFetchTransport(options) {
71
+ const host = options.host.replace(/\/+$/, "");
72
+ const apiKey = typeof options.apiKey === "string" && options.apiKey ? options.apiKey : void 0;
73
+ const getFetch = () => options.fetchImpl ?? (typeof fetch === "function" ? fetch : void 0);
74
+ return {
75
+ async send(envelope) {
76
+ const f = getFetch();
77
+ if (!f) return { status: 0 };
78
+ try {
79
+ const json = chunkKN7H22EQ_cjs.safeStringify(envelope);
80
+ const headers = { ...options.headers, "Content-Type": "application/json" };
81
+ delete headers.Authorization;
82
+ delete headers.authorization;
83
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
84
+ let body = json;
85
+ if (json.length > GZIP_THRESHOLD) {
86
+ const zipped = await gzip(json);
87
+ if (zipped) {
88
+ body = zipped;
89
+ headers["Content-Encoding"] = "gzip";
90
+ }
91
+ }
92
+ const res = await f(host + chunkR7JLZ4WO_cjs.PATHS.INGEST, { method: "POST", body, headers, redirect: "manual", signal: deadline(SEND_TIMEOUT_MS) });
93
+ const out = { status: res.type === "opaqueredirect" ? 302 : res.status };
94
+ try {
95
+ out.retryAfter = chunkHADYYQNL_cjs.parseRetryAfter(res.headers.get("Retry-After"));
96
+ } catch {
97
+ }
98
+ if (out.status >= 300 && out.status < 400) {
99
+ try {
100
+ const location = res.headers.get("Location");
101
+ if (location) out.location = location;
102
+ } catch {
103
+ }
104
+ } else if (out.status >= 400) {
105
+ try {
106
+ const reason = (await res.json())?.data?.reason;
107
+ if (typeof reason === "string") out.reason = reason;
108
+ } catch {
109
+ }
110
+ } else {
111
+ try {
112
+ await res.arrayBuffer();
113
+ } catch {
114
+ }
115
+ }
116
+ return out;
117
+ } catch {
118
+ return { status: 0 };
119
+ }
120
+ },
121
+ async fetchConfig() {
122
+ const f = getFetch();
123
+ if (!f) return null;
124
+ try {
125
+ const res = await f(`${host}${chunkR7JLZ4WO_cjs.PATHS.CONFIG}?workspace=${encodeURIComponent(options.workspaceKey)}`, { method: "GET", redirect: "manual", signal: deadline(CONFIG_TIMEOUT_MS) });
126
+ if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") return null;
127
+ const json = await res.json();
128
+ const data = json && typeof json === "object" ? json.data : null;
129
+ return data && typeof data === "object" ? data : null;
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+ };
135
+ }
136
+
137
+ // src/node/server-defaults.ts
138
+ var SERVER_DEFAULTS = {
139
+ defaultMaxEventsPerLifetime: Infinity,
140
+ defaultMaxEventsPerMinute: 300,
141
+ // A burst at start-up (the database is down) must not lose events while the first batches go out.
142
+ defaultMaxQueueSize: 500,
143
+ // After repeated failed batches sending pauses for this long (a browser pauses for the page load).
144
+ failurePauseMs: 5 * 6e4
145
+ };
146
+
147
+ // src/node/server-client.ts
148
+ var LAZY_CONFIG_TIMEOUT_MS = 5e3;
149
+ var ServerClient = class extends chunkPYYWPIFL_cjs.Client {
150
+ constructor(options) {
151
+ super(options);
152
+ /** The config has not been read yet (`remote` is the default until it is). */
153
+ this.provisional = false;
154
+ this.skipped = new Promise((r) => this.skip = r);
155
+ }
156
+ configGate() {
157
+ return () => this.readLazyConfig();
158
+ }
159
+ loadRemoteConfig() {
160
+ if (this.options.remoteConfig === false || !this.transport.fetchConfig) return super.loadRemoteConfig();
161
+ this.remote = chunkPYYWPIFL_cjs.DEFAULT_REMOTE_CONFIG;
162
+ this.provisional = true;
163
+ }
164
+ /** Read the config once, when the queue is about to send for the first time. Never rejects. */
165
+ readLazyConfig() {
166
+ if (!this.provisional) return Promise.resolve();
167
+ this.lazyConfig || (this.lazyConfig = this.readConfig(LAZY_CONFIG_TIMEOUT_MS, (rc) => {
168
+ this.provisional = false;
169
+ this.applyLateConfig(rc);
170
+ }));
171
+ return Promise.race([this.lazyConfig, this.skipped]);
172
+ }
173
+ /** A config read after events were queued: it applies to what is still unsent. */
174
+ applyLateConfig(rc) {
175
+ this.remote = rc;
176
+ if (!rc.enabled) {
177
+ this.logger.log("config: disabled");
178
+ this.shutdown("config");
179
+ return;
180
+ }
181
+ if (rc.suppress.length || rc.sample_rate < 1) this.queue.filter((e) => !chunkPYYWPIFL_cjs.isSuppressed(e, rc.suppress) && (rc.sample_rate >= 1 || Math.random() < rc.sample_rate));
182
+ }
183
+ /**
184
+ * True while a flush now would only wait: a request is already in flight,
185
+ * or sending waits out a back-off, a 429 or a failure pause. Server hooks
186
+ * skip their flush then (the queue sends on its own).
187
+ */
188
+ isSendBusy() {
189
+ return this.queue.isSending || this.queue.isBlocked;
190
+ }
191
+ /**
192
+ * A shutdown deadline passed: abort the requests in flight and start no
193
+ * new one for 30 s (the queue keeps its events; a process that goes on
194
+ * after all sends them then). Never throws.
195
+ */
196
+ abortRequests() {
197
+ chunkKN7H22EQ_cjs.safely(this.logger, "abort", () => {
198
+ this.queue.holdOff(3e4);
199
+ const t = this.transport;
200
+ if (typeof t.abort === "function") t.abort();
201
+ }, void 0);
202
+ }
203
+ /**
204
+ * Send without waiting for the remote config (the process is about to end:
205
+ * the fatal path, `beforeExit`, SIGTERM / SIGINT), also when a send is
206
+ * already waiting for it. A config read already under way still applies
207
+ * to what is unsent when it arrives.
208
+ */
209
+ skipRemoteConfig() {
210
+ this.provisional = false;
211
+ this.skip();
212
+ }
213
+ };
214
+
215
+ exports.GZIP_THRESHOLD = GZIP_THRESHOLD;
216
+ exports.SERVER_DEFAULTS = SERVER_DEFAULTS;
217
+ exports.ServerClient = ServerClient;
218
+ exports.makeServerFetchTransport = makeServerFetchTransport;
219
+ exports.nodeIsInApp = nodeIsInApp;
220
+ exports.requestDataIntegration = requestDataIntegration;
@@ -0,0 +1,131 @@
1
+ import { originalOf, num, safeStringify, unref, utf8Length } from './chunk-DFYNIWUN.js';
2
+ import { PATHS } from './chunk-GH7RYPKS.js';
3
+
4
+ // src/browser/transport.ts
5
+ var KEEPALIVE_BUDGET = 60 * 1024;
6
+ var REQUEST_TIMEOUT_MS = 12e3;
7
+ function currentFetch() {
8
+ try {
9
+ const f = originalOf(globalThis, "fetch");
10
+ return typeof f === "function" ? f.bind(globalThis) : void 0;
11
+ } catch {
12
+ return void 0;
13
+ }
14
+ }
15
+ var loadedFetch = currentFetch();
16
+ function parseRetryAfter(header, now = Date.now()) {
17
+ if (!header) return void 0;
18
+ const secs = Number(header);
19
+ if (!isNaN(secs)) return Math.max(0, secs);
20
+ const at = Date.parse(header);
21
+ return isNaN(at) ? void 0 : Math.max(0, Math.ceil((at - now) / 1e3));
22
+ }
23
+ function worst(results) {
24
+ const rank = (s) => s === 401 || s === 403 ? 6 : s === 413 ? 5 : s === 429 ? 4 : s === 0 || s >= 500 ? 3 : s >= 400 ? 2 : 1;
25
+ return results.reduce((a, b) => rank(b.status) > rank(a.status) ? b : a, { status: 200 });
26
+ }
27
+ function splitEnvelope(env, budget) {
28
+ const head = utf8Length(safeStringify({ ...env, events: [] }));
29
+ const out = [];
30
+ let cur = { ...env, events: [] };
31
+ let bytes = head;
32
+ for (const e of env.events) {
33
+ const size = utf8Length(safeStringify(e)) + 1;
34
+ if (cur.events.length && bytes + size > budget) {
35
+ out.push({ env: cur, bytes });
36
+ cur = { ...env, events: [] };
37
+ bytes = head;
38
+ }
39
+ cur.events.push(e);
40
+ bytes += size;
41
+ }
42
+ if (cur.events.length) out.push({ env: cur, bytes });
43
+ return out;
44
+ }
45
+ function makeFetchTransport(options) {
46
+ const host = options.host.replace(/\/+$/, "");
47
+ const timeoutMs = Math.max(1, num(options.timeoutMs, REQUEST_TIMEOUT_MS));
48
+ const getFetch = () => options.fetchImpl || loadedFetch || currentFetch();
49
+ let keepaliveBytes = 0;
50
+ const timed = (fallback, request) => {
51
+ const f = getFetch();
52
+ if (!f) return Promise.resolve(fallback);
53
+ let ctl;
54
+ try {
55
+ ctl = new AbortController();
56
+ } catch {
57
+ }
58
+ let t;
59
+ let p;
60
+ try {
61
+ p = request(f, ctl && ctl.signal).catch(() => fallback);
62
+ } catch {
63
+ p = Promise.resolve(fallback);
64
+ }
65
+ const deadline = new Promise((r) => {
66
+ t = setTimeout(() => {
67
+ try {
68
+ if (ctl) ctl.abort();
69
+ } catch {
70
+ }
71
+ r(fallback);
72
+ }, timeoutMs);
73
+ unref(t);
74
+ });
75
+ return Promise.race([p, deadline]).then((v) => {
76
+ clearTimeout(t);
77
+ return v;
78
+ });
79
+ };
80
+ const post = (body, keepalive) => timed({ status: 0 }, async (f, signal) => {
81
+ const res = await f(host + PATHS.INGEST, {
82
+ method: "POST",
83
+ body,
84
+ headers: { "Content-Type": "text/plain;charset=UTF-8" },
85
+ keepalive,
86
+ credentials: "omit",
87
+ redirect: "manual",
88
+ signal
89
+ });
90
+ const out = { status: res.type === "opaqueredirect" ? 302 : res.status };
91
+ try {
92
+ out.retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
93
+ } catch {
94
+ }
95
+ if (out.status >= 400) {
96
+ try {
97
+ const reason = (await res.json())?.data?.reason;
98
+ if (typeof reason === "string") out.reason = reason;
99
+ } catch {
100
+ }
101
+ }
102
+ return out;
103
+ });
104
+ return {
105
+ async send(envelope, opts = {}) {
106
+ if (!opts || !opts.keepalive) return post(safeStringify(envelope), false);
107
+ const results = await Promise.all(
108
+ splitEnvelope(envelope, KEEPALIVE_BUDGET).map(({ env, bytes }) => {
109
+ const fits = keepaliveBytes + bytes <= KEEPALIVE_BUDGET;
110
+ if (fits) keepaliveBytes += bytes;
111
+ return post(safeStringify({ ...env, sent_at: Date.now() }), fits).then((r) => {
112
+ if (fits) keepaliveBytes -= bytes;
113
+ return r;
114
+ });
115
+ })
116
+ );
117
+ return worst(results);
118
+ },
119
+ fetchConfig() {
120
+ return timed(null, async (f, signal) => {
121
+ const res = await f(`${host}${PATHS.CONFIG}?workspace=${encodeURIComponent(options.workspaceKey)}`, { method: "GET", credentials: "omit", redirect: "manual", signal });
122
+ if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) return null;
123
+ const json = await res.json();
124
+ const data = json && typeof json === "object" ? json.data : null;
125
+ return data && typeof data === "object" ? data : null;
126
+ });
127
+ }
128
+ };
129
+ }
130
+
131
+ export { makeFetchTransport, parseRetryAfter };