@trafficwar/node 1.0.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/dist/index.cjs ADDED
@@ -0,0 +1,973 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var zlib = require('zlib');
5
+ var buffer = require('buffer');
6
+
7
+ // src/client.ts
8
+
9
+ // src/errors.ts
10
+ var TrafficWarError = class extends Error {
11
+ status;
12
+ details;
13
+ retryAfterSeconds;
14
+ ingestId;
15
+ idempotencyKey;
16
+ constructor(message, context = {}) {
17
+ super(
18
+ message,
19
+ context.cause === void 0 ? void 0 : { cause: context.cause }
20
+ );
21
+ this.name = "TrafficWarError";
22
+ this.status = context.status;
23
+ this.details = context.details;
24
+ this.retryAfterSeconds = context.retryAfterSeconds;
25
+ this.ingestId = context.ingestId;
26
+ this.idempotencyKey = context.idempotencyKey;
27
+ }
28
+ };
29
+ var TrafficWarValidationError = class extends TrafficWarError {
30
+ path;
31
+ constructor(message, context = {}) {
32
+ super(message, context);
33
+ this.name = "TrafficWarValidationError";
34
+ this.path = context.path;
35
+ }
36
+ };
37
+ var TrafficWarApiError = class extends TrafficWarError {
38
+ constructor(message, context) {
39
+ super(message, context);
40
+ this.name = "TrafficWarApiError";
41
+ }
42
+ };
43
+ var TrafficWarRateLimitError = class extends TrafficWarApiError {
44
+ period;
45
+ used;
46
+ limit;
47
+ remainingEvents;
48
+ batchEvents;
49
+ retryAfterSecs;
50
+ constructor(message, context) {
51
+ super(message, context);
52
+ this.name = "TrafficWarRateLimitError";
53
+ this.period = context.period;
54
+ this.used = context.used;
55
+ this.limit = context.limit;
56
+ this.remainingEvents = context.remainingEvents;
57
+ this.batchEvents = context.batchEvents;
58
+ this.retryAfterSecs = context.retryAfterSecs;
59
+ }
60
+ };
61
+ var TrafficWarConnectionError = class extends TrafficWarError {
62
+ attempts;
63
+ timedOut;
64
+ aborted;
65
+ constructor(message, context) {
66
+ super(message, context);
67
+ this.name = "TrafficWarConnectionError";
68
+ this.attempts = context.attempts;
69
+ this.timedOut = context.timedOut ?? false;
70
+ this.aborted = context.aborted ?? false;
71
+ }
72
+ };
73
+ var TrafficWarProtocolError = class extends TrafficWarError {
74
+ responseBody;
75
+ constructor(message, context = {}) {
76
+ super(message, context);
77
+ this.name = "TrafficWarProtocolError";
78
+ this.responseBody = context.responseBody;
79
+ }
80
+ };
81
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
82
+ var RFC3339_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/i;
83
+ var STRING_FIELDS = [
84
+ "user_agent",
85
+ "label",
86
+ "ip",
87
+ "source",
88
+ "country",
89
+ "city",
90
+ "trace_id",
91
+ "distinct_id",
92
+ "path",
93
+ "error",
94
+ "exception",
95
+ "error_code",
96
+ "operation_type"
97
+ ];
98
+ var SPAN_KINDS = /* @__PURE__ */ new Set([
99
+ "server",
100
+ "client",
101
+ "producer",
102
+ "consumer",
103
+ "internal"
104
+ ]);
105
+ var FORBIDDEN_IDENTITY_FIELDS = ["user_id", "service", "service_id"];
106
+ function validationError(message, path, idempotencyKey, cause) {
107
+ return new TrafficWarValidationError(message, {
108
+ path,
109
+ idempotencyKey,
110
+ cause
111
+ });
112
+ }
113
+ function assertJsonValue(value, path, ancestors, idempotencyKey) {
114
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
115
+ return;
116
+ }
117
+ if (typeof value === "number") {
118
+ if (!Number.isFinite(value)) {
119
+ throw validationError(
120
+ `${path} must contain only finite JSON numbers`,
121
+ path,
122
+ idempotencyKey
123
+ );
124
+ }
125
+ return;
126
+ }
127
+ if (typeof value !== "object") {
128
+ throw validationError(
129
+ `${path} contains a value that JSON cannot represent`,
130
+ path,
131
+ idempotencyKey
132
+ );
133
+ }
134
+ if (value instanceof Date) {
135
+ throw validationError(
136
+ `${path} contains a Date; only timestamp accepts Date values`,
137
+ path,
138
+ idempotencyKey
139
+ );
140
+ }
141
+ if (ancestors.has(value)) {
142
+ throw validationError(
143
+ `${path} contains a circular reference`,
144
+ path,
145
+ idempotencyKey
146
+ );
147
+ }
148
+ if (!Array.isArray(value)) {
149
+ const prototype = Object.getPrototypeOf(value);
150
+ if (prototype !== Object.prototype && prototype !== null) {
151
+ throw validationError(
152
+ `${path} contains a non-JSON object`,
153
+ path,
154
+ idempotencyKey
155
+ );
156
+ }
157
+ }
158
+ ancestors.add(value);
159
+ try {
160
+ if (Array.isArray(value)) {
161
+ for (let index = 0; index < value.length; index += 1) {
162
+ if (!(index in value)) {
163
+ throw validationError(
164
+ `${path}[${index}] is missing; sparse arrays are not valid JSON values`,
165
+ `${path}[${index}]`,
166
+ idempotencyKey
167
+ );
168
+ }
169
+ assertJsonValue(
170
+ value[index],
171
+ `${path}[${index}]`,
172
+ ancestors,
173
+ idempotencyKey
174
+ );
175
+ }
176
+ return;
177
+ }
178
+ for (const [key, child] of Object.entries(value)) {
179
+ assertJsonValue(child, `${path}.${key}`, ancestors, idempotencyKey);
180
+ }
181
+ } finally {
182
+ ancestors.delete(value);
183
+ }
184
+ }
185
+ function normalizeTimestamp(timestamp, path, idempotencyKey) {
186
+ if (timestamp instanceof Date) {
187
+ if (!Number.isFinite(timestamp.getTime())) {
188
+ throw validationError(
189
+ `${path} must be a valid Date`,
190
+ path,
191
+ idempotencyKey
192
+ );
193
+ }
194
+ return timestamp.toISOString();
195
+ }
196
+ if (typeof timestamp === "number") {
197
+ if (!Number.isSafeInteger(timestamp)) {
198
+ throw validationError(
199
+ `${path} must be an integer epoch-millisecond value`,
200
+ path,
201
+ idempotencyKey
202
+ );
203
+ }
204
+ return timestamp;
205
+ }
206
+ if (typeof timestamp !== "string") {
207
+ throw validationError(
208
+ `${path} must be an RFC3339 string, epoch-millisecond number, or Date`,
209
+ path,
210
+ idempotencyKey
211
+ );
212
+ }
213
+ const match = RFC3339_PATTERN.exec(timestamp);
214
+ const year = Number(match?.[1]);
215
+ const month = Number(match?.[2]);
216
+ const day = Number(match?.[3]);
217
+ const hour = Number(match?.[4]);
218
+ const minute = Number(match?.[5]);
219
+ const second = Number(match?.[6]);
220
+ const offsetHour = match?.[7] === void 0 ? 0 : Number(match[7]);
221
+ const offsetMinute = match?.[8] === void 0 ? 0 : Number(match[8]);
222
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
223
+ const daysInMonth = [
224
+ 31,
225
+ leapYear ? 29 : 28,
226
+ 31,
227
+ 30,
228
+ 31,
229
+ 30,
230
+ 31,
231
+ 31,
232
+ 30,
233
+ 31,
234
+ 30,
235
+ 31
236
+ ][month - 1];
237
+ if (match === null || month < 1 || month > 12 || daysInMonth === void 0 || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59 || !Number.isFinite(Date.parse(timestamp))) {
238
+ throw validationError(
239
+ `${path} must be an RFC3339 string, epoch-millisecond number, or Date`,
240
+ path,
241
+ idempotencyKey
242
+ );
243
+ }
244
+ return timestamp;
245
+ }
246
+ function normalizeEvent(input, path, idempotencyKey) {
247
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
248
+ throw validationError(
249
+ `${path} must be a non-empty object`,
250
+ path,
251
+ idempotencyKey
252
+ );
253
+ }
254
+ let entries;
255
+ try {
256
+ entries = Object.entries(input);
257
+ } catch (cause) {
258
+ throw validationError(
259
+ `${path} could not be read`,
260
+ path,
261
+ idempotencyKey,
262
+ cause
263
+ );
264
+ }
265
+ const normalized = {};
266
+ for (const [key, value] of entries) {
267
+ if (value !== void 0) {
268
+ normalized[key] = value;
269
+ }
270
+ }
271
+ if (typeof normalized.event !== "string" || normalized.event.trim().length === 0) {
272
+ throw validationError(
273
+ `${path}.event must be a non-empty string`,
274
+ `${path}.event`,
275
+ idempotencyKey
276
+ );
277
+ }
278
+ for (const field of FORBIDDEN_IDENTITY_FIELDS) {
279
+ if (Object.hasOwn(normalized, field)) {
280
+ throw validationError(
281
+ `${path}.${field} is derived from the API key and must not be sent`,
282
+ `${path}.${field}`,
283
+ idempotencyKey
284
+ );
285
+ }
286
+ }
287
+ if (Object.hasOwn(normalized, "event_id")) {
288
+ if (typeof normalized.event_id !== "string" || !UUID_PATTERN.test(normalized.event_id)) {
289
+ throw validationError(
290
+ `${path}.event_id must be a UUID string`,
291
+ `${path}.event_id`,
292
+ idempotencyKey
293
+ );
294
+ }
295
+ }
296
+ if (Object.hasOwn(normalized, "timestamp")) {
297
+ normalized.timestamp = normalizeTimestamp(
298
+ normalized.timestamp,
299
+ `${path}.timestamp`,
300
+ idempotencyKey
301
+ );
302
+ }
303
+ if (Object.hasOwn(normalized, "latency_ms") && (typeof normalized.latency_ms !== "number" || !Number.isFinite(normalized.latency_ms))) {
304
+ throw validationError(
305
+ `${path}.latency_ms must be a finite number`,
306
+ `${path}.latency_ms`,
307
+ idempotencyKey
308
+ );
309
+ }
310
+ if (Object.hasOwn(normalized, "status_code") && (typeof normalized.status_code !== "number" || !Number.isInteger(normalized.status_code) || normalized.status_code < 0 || normalized.status_code > 65535)) {
311
+ throw validationError(
312
+ `${path}.status_code must be an integer from 0 to 65535`,
313
+ `${path}.status_code`,
314
+ idempotencyKey
315
+ );
316
+ }
317
+ for (const field of STRING_FIELDS) {
318
+ if (Object.hasOwn(normalized, field) && typeof normalized[field] !== "string") {
319
+ throw validationError(
320
+ `${path}.${field} must be a string`,
321
+ `${path}.${field}`,
322
+ idempotencyKey
323
+ );
324
+ }
325
+ }
326
+ if (Object.hasOwn(normalized, "span_kind") && (typeof normalized.span_kind !== "string" || !SPAN_KINDS.has(normalized.span_kind))) {
327
+ throw validationError(
328
+ `${path}.span_kind must be server, client, producer, consumer, or internal`,
329
+ `${path}.span_kind`,
330
+ idempotencyKey
331
+ );
332
+ }
333
+ try {
334
+ assertJsonValue(normalized, path, /* @__PURE__ */ new WeakSet(), idempotencyKey);
335
+ } catch (error) {
336
+ if (error instanceof TrafficWarValidationError) {
337
+ throw error;
338
+ }
339
+ throw validationError(
340
+ `${path} is not JSON-serializable`,
341
+ path,
342
+ idempotencyKey,
343
+ error
344
+ );
345
+ }
346
+ return normalized;
347
+ }
348
+ function assertUniqueEventIds(events, idempotencyKey) {
349
+ const seen = /* @__PURE__ */ new Set();
350
+ for (let index = 0; index < events.length; index += 1) {
351
+ const eventId = events[index]?.event_id;
352
+ if (typeof eventId !== "string") {
353
+ continue;
354
+ }
355
+ if (seen.has(eventId)) {
356
+ throw validationError(
357
+ `events[${index}].event_id duplicates another event_id in this batch`,
358
+ `events[${index}].event_id`,
359
+ idempotencyKey
360
+ );
361
+ }
362
+ seen.add(eventId);
363
+ }
364
+ }
365
+ function validateIdempotencyKey(value) {
366
+ if (typeof value !== "string" || value.length === 0 || value.length > 256 || !/^[\x21-\x7e]+$/.test(value)) {
367
+ throw new TrafficWarValidationError(
368
+ "idempotencyKey must contain 1-256 visible ASCII characters",
369
+ { path: "options.idempotencyKey" }
370
+ );
371
+ }
372
+ return value;
373
+ }
374
+ function serializeJson(payload, idempotencyKey) {
375
+ let serialized;
376
+ try {
377
+ const value = JSON.stringify(payload);
378
+ if (value === void 0) {
379
+ throw new TypeError("JSON.stringify returned undefined");
380
+ }
381
+ serialized = value;
382
+ } catch (cause) {
383
+ throw validationError(
384
+ "Request body is not JSON-serializable",
385
+ "body",
386
+ idempotencyKey,
387
+ cause
388
+ );
389
+ }
390
+ return buffer.Buffer.from(serialized, "utf8");
391
+ }
392
+
393
+ // package.json
394
+ var package_default = {
395
+ version: "1.0.0"};
396
+
397
+ // src/client.ts
398
+ var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";
399
+ var TRAFFICWAR_DEFAULT_TIMEOUT_MS = 3e4;
400
+ var TRAFFICWAR_DEFAULT_MAX_RETRIES = 3;
401
+ var TRAFFICWAR_MAX_BATCH_SIZE = 1e4;
402
+ var TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES = 2 * 1024 * 1024;
403
+ var TRAFFICWAR_MAX_DECODED_BODY_BYTES = 8 * 1024 * 1024;
404
+ var SDK_VERSION = package_default.version;
405
+ var DEFAULT_COMPRESSION_THRESHOLD_BYTES = 1024;
406
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 425, 500, 502, 503, 504]);
407
+ var RETRY_BASE_DELAY_MS = 250;
408
+ var RETRY_MAX_DELAY_MS = 1e4;
409
+ var MAX_RETRY_AFTER_SECONDS = 60;
410
+ var MAX_TIMER_MS = 2147483647;
411
+ var AttemptTransportFailure = class {
412
+ cause;
413
+ timedOut;
414
+ constructor(cause, timedOut) {
415
+ this.cause = cause;
416
+ this.timedOut = timedOut;
417
+ }
418
+ };
419
+ function asRecord(value) {
420
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
421
+ return void 0;
422
+ }
423
+ return value;
424
+ }
425
+ function finiteNumber(value) {
426
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
427
+ }
428
+ function nonEmptyString(value) {
429
+ return typeof value === "string" && value.length > 0 ? value : void 0;
430
+ }
431
+ function normalizeBaseUrl(value) {
432
+ const candidate = value ?? TRAFFICWAR_DEFAULT_BASE_URL;
433
+ if (typeof candidate !== "string" && !(candidate instanceof URL)) {
434
+ throw new TrafficWarValidationError(
435
+ "baseUrl must be an HTTP or HTTPS URL",
436
+ { path: "options.baseUrl" }
437
+ );
438
+ }
439
+ let url;
440
+ try {
441
+ url = new URL(candidate);
442
+ } catch (cause) {
443
+ throw new TrafficWarValidationError(
444
+ "baseUrl must be a valid HTTP or HTTPS URL",
445
+ { path: "options.baseUrl", cause }
446
+ );
447
+ }
448
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.search.length > 0 || url.hash.length > 0 || url.pathname.replaceAll("/", "").length > 0) {
449
+ throw new TrafficWarValidationError(
450
+ "baseUrl must be an HTTP(S) origin without credentials, path, query, or fragment",
451
+ { path: "options.baseUrl" }
452
+ );
453
+ }
454
+ return url.origin;
455
+ }
456
+ function validateApiKey(value) {
457
+ if (typeof value !== "string" || value.length === 0 || !/^[\x21-\x7e]+$/.test(value)) {
458
+ throw new TrafficWarValidationError(
459
+ "apiKey must be a non-empty visible ASCII string",
460
+ { path: "options.apiKey" }
461
+ );
462
+ }
463
+ return value;
464
+ }
465
+ function validateIntegerOption(name, value, fallback, minimum, maximum) {
466
+ const actual = value ?? fallback;
467
+ if (typeof actual !== "number" || !Number.isSafeInteger(actual) || actual < minimum || actual > maximum) {
468
+ throw new TrafficWarValidationError(
469
+ `${name} must be an integer from ${minimum} to ${maximum}`,
470
+ { path: `options.${name}` }
471
+ );
472
+ }
473
+ return actual;
474
+ }
475
+ function validateCompression(value) {
476
+ const actual = value ?? "auto";
477
+ if (actual !== "auto" && actual !== "gzip" && actual !== "none") {
478
+ throw new TrafficWarValidationError(
479
+ "compression must be auto, gzip, or none",
480
+ { path: "options.compression" }
481
+ );
482
+ }
483
+ return actual;
484
+ }
485
+ function isAbortSignal(value) {
486
+ return value !== null && typeof value === "object" && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
487
+ }
488
+ function requestIdentity(options) {
489
+ if (options !== void 0 && (options === null || typeof options !== "object" || Array.isArray(options))) {
490
+ throw new TrafficWarValidationError(
491
+ "request options must be an object",
492
+ { path: "options" }
493
+ );
494
+ }
495
+ const idempotencyKey = options?.idempotencyKey === void 0 ? crypto.randomUUID() : validateIdempotencyKey(options.idempotencyKey);
496
+ const signal = options?.signal;
497
+ if (signal !== void 0 && !isAbortSignal(signal)) {
498
+ throw new TrafficWarValidationError(
499
+ "signal must be an AbortSignal",
500
+ { path: "options.signal", idempotencyKey }
501
+ );
502
+ }
503
+ return { idempotencyKey, signal };
504
+ }
505
+ function parseBody(text) {
506
+ if (text.length === 0) {
507
+ return { text, value: void 0, isJson: false };
508
+ }
509
+ try {
510
+ return { text, value: JSON.parse(text), isJson: true };
511
+ } catch {
512
+ return { text, value: void 0, isJson: false };
513
+ }
514
+ }
515
+ function bodyRetryAfterSeconds(value) {
516
+ const details = asRecord(value);
517
+ const seconds = finiteNumber(details?.retry_after_secs);
518
+ return seconds !== void 0 && seconds >= 0 ? seconds : void 0;
519
+ }
520
+ function headerRetryAfterSeconds(headers, nowMs) {
521
+ const value = headers.get("retry-after")?.trim();
522
+ if (!value) {
523
+ return void 0;
524
+ }
525
+ if (/^\d+(?:\.\d+)?$/.test(value)) {
526
+ const seconds = Number(value);
527
+ return Number.isFinite(seconds) ? seconds : void 0;
528
+ }
529
+ const dateMs = Date.parse(value);
530
+ if (!Number.isFinite(dateMs)) {
531
+ return void 0;
532
+ }
533
+ return Math.max(0, (dateMs - nowMs) / 1e3);
534
+ }
535
+ function retryAfterSeconds(response, parsed) {
536
+ return headerRetryAfterSeconds(response.headers, Date.now()) ?? bodyRetryAfterSeconds(parsed.value);
537
+ }
538
+ function retryDelayMs(retryIndex, retryAfter) {
539
+ const exponential = Math.min(
540
+ RETRY_MAX_DELAY_MS,
541
+ RETRY_BASE_DELAY_MS * 2 ** Math.min(retryIndex, 20)
542
+ );
543
+ const jitter = Math.random() * exponential;
544
+ return Math.max(jitter, (retryAfter ?? 0) * 1e3);
545
+ }
546
+ async function sleepChunk(ms, signal) {
547
+ if (signal?.aborted) {
548
+ throw signal.reason;
549
+ }
550
+ await new Promise((resolve, reject) => {
551
+ const timer = setTimeout(() => {
552
+ signal?.removeEventListener("abort", onAbort);
553
+ resolve();
554
+ }, ms);
555
+ const onAbort = () => {
556
+ clearTimeout(timer);
557
+ signal?.removeEventListener("abort", onAbort);
558
+ reject(signal?.reason);
559
+ };
560
+ signal?.addEventListener("abort", onAbort, { once: true });
561
+ });
562
+ }
563
+ async function sleep(ms, signal) {
564
+ let remaining = Math.max(0, Math.ceil(ms));
565
+ if (remaining === 0) {
566
+ if (signal?.aborted) {
567
+ throw signal.reason;
568
+ }
569
+ return;
570
+ }
571
+ while (remaining > 0) {
572
+ const chunk = Math.min(remaining, MAX_TIMER_MS);
573
+ await sleepChunk(chunk, signal);
574
+ remaining -= chunk;
575
+ }
576
+ }
577
+ async function executeAttempt(fetcher, url, init, userSignal, timeoutMs) {
578
+ const controller = new AbortController();
579
+ let timedOut = false;
580
+ const timeoutReason = new Error(
581
+ `TrafficWar request timed out after ${timeoutMs} ms`
582
+ );
583
+ const onUserAbort = () => {
584
+ controller.abort(userSignal?.reason);
585
+ };
586
+ if (userSignal?.aborted) {
587
+ controller.abort(userSignal.reason);
588
+ } else {
589
+ userSignal?.addEventListener("abort", onUserAbort, { once: true });
590
+ }
591
+ const timer = setTimeout(() => {
592
+ timedOut = true;
593
+ controller.abort(timeoutReason);
594
+ }, timeoutMs);
595
+ let onAttemptAbort;
596
+ const abortPromise = new Promise((_resolve, reject) => {
597
+ onAttemptAbort = () => reject(controller.signal.reason);
598
+ if (controller.signal.aborted) {
599
+ onAttemptAbort();
600
+ } else {
601
+ controller.signal.addEventListener("abort", onAttemptAbort, {
602
+ once: true
603
+ });
604
+ }
605
+ });
606
+ try {
607
+ const request = (async () => {
608
+ const response = await fetcher(url, {
609
+ ...init,
610
+ signal: controller.signal
611
+ });
612
+ const text = await response.text();
613
+ return { response, text };
614
+ })();
615
+ return await Promise.race([request, abortPromise]);
616
+ } catch (cause) {
617
+ throw new AttemptTransportFailure(cause, timedOut);
618
+ } finally {
619
+ clearTimeout(timer);
620
+ userSignal?.removeEventListener("abort", onUserAbort);
621
+ if (onAttemptAbort) {
622
+ controller.signal.removeEventListener("abort", onAttemptAbort);
623
+ }
624
+ }
625
+ }
626
+ function gzipBody(decoded) {
627
+ return new Promise((resolve, reject) => {
628
+ zlib.gzip(decoded, (error, result) => {
629
+ if (error) {
630
+ reject(error);
631
+ } else {
632
+ resolve(result);
633
+ }
634
+ });
635
+ });
636
+ }
637
+ async function prepareRequest(payload, idempotencyKey, compression, compressionThresholdBytes) {
638
+ const decoded = serializeJson(payload, idempotencyKey);
639
+ if (decoded.byteLength > TRAFFICWAR_MAX_DECODED_BODY_BYTES) {
640
+ throw new TrafficWarValidationError(
641
+ `Decoded request body exceeds ${TRAFFICWAR_MAX_DECODED_BODY_BYTES} bytes`,
642
+ { path: "body", idempotencyKey }
643
+ );
644
+ }
645
+ const useGzip = compression === "gzip" || compression === "auto" && decoded.byteLength >= compressionThresholdBytes;
646
+ let body;
647
+ try {
648
+ body = useGzip ? await gzipBody(decoded) : decoded;
649
+ } catch (cause) {
650
+ throw new TrafficWarValidationError("Unable to gzip request body", {
651
+ path: "body",
652
+ idempotencyKey,
653
+ cause
654
+ });
655
+ }
656
+ if (body.byteLength > TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES) {
657
+ throw new TrafficWarValidationError(
658
+ `Request body exceeds the ${TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES}-byte wire limit`,
659
+ { path: "body", idempotencyKey }
660
+ );
661
+ }
662
+ return {
663
+ body,
664
+ contentEncoding: useGzip ? "gzip" : void 0
665
+ };
666
+ }
667
+ function buildApiError(response, parsed, idempotencyKey) {
668
+ const details = parsed.isJson ? parsed.value : void 0;
669
+ const record = asRecord(details);
670
+ const retryAfter = retryAfterSeconds(response, parsed);
671
+ const ingestId = nonEmptyString(record?.ingest_id);
672
+ const status = nonEmptyString(record?.status);
673
+ const message = nonEmptyString(record?.error);
674
+ if (!parsed.isJson || record === void 0 || status !== "error" && status !== "pending" || message === void 0) {
675
+ throw new TrafficWarProtocolError(
676
+ "TrafficWar returned an invalid error response",
677
+ {
678
+ status: response.status,
679
+ details,
680
+ retryAfterSeconds: retryAfter,
681
+ ingestId,
682
+ idempotencyKey,
683
+ responseBody: parsed.text
684
+ }
685
+ );
686
+ }
687
+ if (response.status === 429) {
688
+ return new TrafficWarRateLimitError(message, {
689
+ status: response.status,
690
+ details,
691
+ retryAfterSeconds: retryAfter,
692
+ ingestId,
693
+ idempotencyKey,
694
+ period: nonEmptyString(record?.period),
695
+ used: finiteNumber(record?.used),
696
+ limit: finiteNumber(record?.limit),
697
+ remainingEvents: finiteNumber(record?.remaining_events),
698
+ batchEvents: finiteNumber(record?.batch_events),
699
+ retryAfterSecs: bodyRetryAfterSeconds(details)
700
+ });
701
+ }
702
+ return new TrafficWarApiError(message, {
703
+ status: response.status,
704
+ details,
705
+ retryAfterSeconds: retryAfter,
706
+ ingestId,
707
+ idempotencyKey
708
+ });
709
+ }
710
+ function parseSuccess(response, parsed, expectedCount, idempotencyKey) {
711
+ const record = asRecord(parsed.value);
712
+ const accepted = finiteNumber(record?.accepted);
713
+ const ingestId = nonEmptyString(record?.ingest_id);
714
+ if (!parsed.isJson || record?.status !== "ok" || accepted === void 0 || !Number.isSafeInteger(accepted) || accepted < 0 || accepted !== expectedCount || ingestId === void 0) {
715
+ throw new TrafficWarProtocolError(
716
+ "TrafficWar returned an invalid success response",
717
+ {
718
+ status: response.status,
719
+ details: parsed.isJson ? parsed.value : void 0,
720
+ retryAfterSeconds: retryAfterSeconds(response, parsed),
721
+ ingestId,
722
+ idempotencyKey,
723
+ responseBody: parsed.text
724
+ }
725
+ );
726
+ }
727
+ return {
728
+ status: "ok",
729
+ accepted,
730
+ ingestId,
731
+ idempotencyKey
732
+ };
733
+ }
734
+ var TrafficWar = class {
735
+ baseUrl;
736
+ timeoutMs;
737
+ maxRetries;
738
+ compression;
739
+ compressionThresholdBytes;
740
+ #apiKey;
741
+ #fetch;
742
+ constructor(options) {
743
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
744
+ throw new TrafficWarValidationError(
745
+ "TrafficWar options must be an object",
746
+ { path: "options" }
747
+ );
748
+ }
749
+ this.#apiKey = validateApiKey(options.apiKey);
750
+ this.baseUrl = normalizeBaseUrl(options.baseUrl);
751
+ this.timeoutMs = validateIntegerOption(
752
+ "timeoutMs",
753
+ options.timeoutMs,
754
+ TRAFFICWAR_DEFAULT_TIMEOUT_MS,
755
+ 1,
756
+ MAX_TIMER_MS
757
+ );
758
+ this.maxRetries = validateIntegerOption(
759
+ "maxRetries",
760
+ options.maxRetries,
761
+ TRAFFICWAR_DEFAULT_MAX_RETRIES,
762
+ 0,
763
+ 100
764
+ );
765
+ this.compression = validateCompression(options.compression);
766
+ this.compressionThresholdBytes = validateIntegerOption(
767
+ "compressionThresholdBytes",
768
+ options.compressionThresholdBytes,
769
+ DEFAULT_COMPRESSION_THRESHOLD_BYTES,
770
+ 0,
771
+ TRAFFICWAR_MAX_DECODED_BODY_BYTES
772
+ );
773
+ if (options.fetch !== void 0 && typeof options.fetch !== "function") {
774
+ throw new TrafficWarValidationError(
775
+ "fetch must be a function",
776
+ { path: "options.fetch" }
777
+ );
778
+ }
779
+ this.#fetch = options.fetch ?? ((input, init) => {
780
+ return globalThis.fetch(input, init);
781
+ });
782
+ }
783
+ async capture(event, options) {
784
+ const identity = requestIdentity(options);
785
+ const normalized = normalizeEvent(
786
+ event,
787
+ "event",
788
+ identity.idempotencyKey
789
+ );
790
+ return this.#send(
791
+ "/v1/server/capture",
792
+ normalized,
793
+ 1,
794
+ identity
795
+ );
796
+ }
797
+ async captureBatch(events, options) {
798
+ const identity = requestIdentity(options);
799
+ if (!Array.isArray(events) || events.length === 0) {
800
+ throw new TrafficWarValidationError(
801
+ "events must be a non-empty array",
802
+ { path: "events", idempotencyKey: identity.idempotencyKey }
803
+ );
804
+ }
805
+ if (events.length > TRAFFICWAR_MAX_BATCH_SIZE) {
806
+ throw new TrafficWarValidationError(
807
+ `events must contain at most ${TRAFFICWAR_MAX_BATCH_SIZE} events`,
808
+ { path: "events", idempotencyKey: identity.idempotencyKey }
809
+ );
810
+ }
811
+ const normalized = events.map(
812
+ (event, index) => normalizeEvent(
813
+ event,
814
+ `events[${index}]`,
815
+ identity.idempotencyKey
816
+ )
817
+ );
818
+ assertUniqueEventIds(normalized, identity.idempotencyKey);
819
+ return this.#send(
820
+ "/v1/server/batch",
821
+ normalized,
822
+ normalized.length,
823
+ identity
824
+ );
825
+ }
826
+ async #send(path, payload, expectedCount, identity) {
827
+ const prepared = await prepareRequest(
828
+ payload,
829
+ identity.idempotencyKey,
830
+ this.compression,
831
+ this.compressionThresholdBytes
832
+ );
833
+ const headers = {
834
+ accept: "application/json",
835
+ authorization: `Bearer ${this.#apiKey}`,
836
+ "content-type": "application/json",
837
+ "idempotency-key": identity.idempotencyKey,
838
+ "user-agent": `@trafficwar/node/${SDK_VERSION}`,
839
+ "x-trafficwar-sdk": `node/${SDK_VERSION}`
840
+ };
841
+ if (prepared.contentEncoding) {
842
+ headers["content-encoding"] = prepared.contentEncoding;
843
+ }
844
+ const url = `${this.baseUrl}${path}`;
845
+ const init = {
846
+ method: "POST",
847
+ headers,
848
+ body: prepared.body,
849
+ redirect: "error"
850
+ };
851
+ let sawTimeout = false;
852
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
853
+ if (identity.signal?.aborted) {
854
+ throw new TrafficWarConnectionError(
855
+ "TrafficWar request was aborted",
856
+ {
857
+ attempts: attempt,
858
+ aborted: true,
859
+ timedOut: sawTimeout,
860
+ idempotencyKey: identity.idempotencyKey,
861
+ cause: identity.signal.reason
862
+ }
863
+ );
864
+ }
865
+ let result;
866
+ try {
867
+ result = await executeAttempt(
868
+ this.#fetch,
869
+ url,
870
+ init,
871
+ identity.signal,
872
+ this.timeoutMs
873
+ );
874
+ } catch (error) {
875
+ const failure = error instanceof AttemptTransportFailure ? error : new AttemptTransportFailure(error, false);
876
+ sawTimeout ||= failure.timedOut;
877
+ if (identity.signal?.aborted) {
878
+ throw new TrafficWarConnectionError(
879
+ "TrafficWar request was aborted",
880
+ {
881
+ attempts: attempt + 1,
882
+ aborted: true,
883
+ timedOut: sawTimeout,
884
+ idempotencyKey: identity.idempotencyKey,
885
+ cause: identity.signal.reason ?? failure.cause
886
+ }
887
+ );
888
+ }
889
+ if (attempt >= this.maxRetries) {
890
+ throw new TrafficWarConnectionError(
891
+ failure.timedOut ? `TrafficWar request timed out after ${this.timeoutMs} ms` : "Unable to reach TrafficWar",
892
+ {
893
+ attempts: attempt + 1,
894
+ timedOut: sawTimeout,
895
+ idempotencyKey: identity.idempotencyKey,
896
+ cause: failure.cause
897
+ }
898
+ );
899
+ }
900
+ try {
901
+ await sleep(retryDelayMs(attempt, void 0), identity.signal);
902
+ } catch (cause) {
903
+ throw new TrafficWarConnectionError(
904
+ "TrafficWar request was aborted",
905
+ {
906
+ attempts: attempt + 1,
907
+ aborted: true,
908
+ timedOut: sawTimeout,
909
+ idempotencyKey: identity.idempotencyKey,
910
+ cause
911
+ }
912
+ );
913
+ }
914
+ continue;
915
+ }
916
+ const parsed = parseBody(result.text);
917
+ if (result.response.ok) {
918
+ return parseSuccess(
919
+ result.response,
920
+ parsed,
921
+ expectedCount,
922
+ identity.idempotencyKey
923
+ );
924
+ }
925
+ if (RETRYABLE_STATUSES.has(result.response.status) && attempt < this.maxRetries) {
926
+ const retryAfter = retryAfterSeconds(result.response, parsed);
927
+ if (retryAfter === void 0 || retryAfter <= MAX_RETRY_AFTER_SECONDS) {
928
+ try {
929
+ await sleep(retryDelayMs(attempt, retryAfter), identity.signal);
930
+ } catch (cause) {
931
+ throw new TrafficWarConnectionError(
932
+ "TrafficWar request was aborted",
933
+ {
934
+ attempts: attempt + 1,
935
+ aborted: true,
936
+ timedOut: sawTimeout,
937
+ idempotencyKey: identity.idempotencyKey,
938
+ cause
939
+ }
940
+ );
941
+ }
942
+ continue;
943
+ }
944
+ }
945
+ throw buildApiError(
946
+ result.response,
947
+ parsed,
948
+ identity.idempotencyKey
949
+ );
950
+ }
951
+ throw new TrafficWarConnectionError("Unable to reach TrafficWar", {
952
+ attempts: this.maxRetries + 1,
953
+ timedOut: sawTimeout,
954
+ idempotencyKey: identity.idempotencyKey
955
+ });
956
+ }
957
+ };
958
+
959
+ exports.TRAFFICWAR_DEFAULT_BASE_URL = TRAFFICWAR_DEFAULT_BASE_URL;
960
+ exports.TRAFFICWAR_DEFAULT_MAX_RETRIES = TRAFFICWAR_DEFAULT_MAX_RETRIES;
961
+ exports.TRAFFICWAR_DEFAULT_TIMEOUT_MS = TRAFFICWAR_DEFAULT_TIMEOUT_MS;
962
+ exports.TRAFFICWAR_MAX_BATCH_SIZE = TRAFFICWAR_MAX_BATCH_SIZE;
963
+ exports.TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES = TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES;
964
+ exports.TRAFFICWAR_MAX_DECODED_BODY_BYTES = TRAFFICWAR_MAX_DECODED_BODY_BYTES;
965
+ exports.TrafficWar = TrafficWar;
966
+ exports.TrafficWarApiError = TrafficWarApiError;
967
+ exports.TrafficWarConnectionError = TrafficWarConnectionError;
968
+ exports.TrafficWarError = TrafficWarError;
969
+ exports.TrafficWarProtocolError = TrafficWarProtocolError;
970
+ exports.TrafficWarRateLimitError = TrafficWarRateLimitError;
971
+ exports.TrafficWarValidationError = TrafficWarValidationError;
972
+ //# sourceMappingURL=index.cjs.map
973
+ //# sourceMappingURL=index.cjs.map