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