@trafficwar/node 1.0.0 → 2.1.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 CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
3
  var zlib = require('zlib');
5
4
  var buffer = require('buffer');
5
+ var crypto = require('crypto');
6
6
 
7
7
  // src/client.ts
8
8
 
@@ -110,9 +110,9 @@ function validationError(message, path, idempotencyKey, cause) {
110
110
  cause
111
111
  });
112
112
  }
113
- function assertJsonValue(value, path, ancestors, idempotencyKey) {
113
+ function snapshotJsonValue(value, path, ancestors, idempotencyKey) {
114
114
  if (value === null || typeof value === "string" || typeof value === "boolean") {
115
- return;
115
+ return value;
116
116
  }
117
117
  if (typeof value === "number") {
118
118
  if (!Number.isFinite(value)) {
@@ -122,7 +122,7 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
122
122
  idempotencyKey
123
123
  );
124
124
  }
125
- return;
125
+ return value;
126
126
  }
127
127
  if (typeof value !== "object") {
128
128
  throw validationError(
@@ -158,6 +158,7 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
158
158
  ancestors.add(value);
159
159
  try {
160
160
  if (Array.isArray(value)) {
161
+ const snapshot2 = [];
161
162
  for (let index = 0; index < value.length; index += 1) {
162
163
  if (!(index in value)) {
163
164
  throw validationError(
@@ -166,18 +167,27 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
166
167
  idempotencyKey
167
168
  );
168
169
  }
169
- assertJsonValue(
170
- value[index],
171
- `${path}[${index}]`,
172
- ancestors,
173
- idempotencyKey
170
+ snapshot2.push(
171
+ snapshotJsonValue(
172
+ value[index],
173
+ `${path}[${index}]`,
174
+ ancestors,
175
+ idempotencyKey
176
+ )
174
177
  );
175
178
  }
176
- return;
179
+ return snapshot2;
177
180
  }
181
+ const snapshot = /* @__PURE__ */ Object.create(null);
178
182
  for (const [key, child] of Object.entries(value)) {
179
- assertJsonValue(child, `${path}.${key}`, ancestors, idempotencyKey);
183
+ snapshot[key] = snapshotJsonValue(
184
+ child,
185
+ `${path}.${key}`,
186
+ ancestors,
187
+ idempotencyKey
188
+ );
180
189
  }
190
+ return snapshot;
181
191
  } finally {
182
192
  ancestors.delete(value);
183
193
  }
@@ -331,7 +341,12 @@ function normalizeEvent(input, path, idempotencyKey) {
331
341
  );
332
342
  }
333
343
  try {
334
- assertJsonValue(normalized, path, /* @__PURE__ */ new WeakSet(), idempotencyKey);
344
+ return snapshotJsonValue(
345
+ normalized,
346
+ path,
347
+ /* @__PURE__ */ new WeakSet(),
348
+ idempotencyKey
349
+ );
335
350
  } catch (error) {
336
351
  if (error instanceof TrafficWarValidationError) {
337
352
  throw error;
@@ -343,33 +358,6 @@ function normalizeEvent(input, path, idempotencyKey) {
343
358
  error
344
359
  );
345
360
  }
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
361
  }
374
362
  function serializeJson(payload, idempotencyKey) {
375
363
  let serialized;
@@ -389,15 +377,85 @@ function serializeJson(payload, idempotencyKey) {
389
377
  }
390
378
  return buffer.Buffer.from(serialized, "utf8");
391
379
  }
380
+ var RANDOM_BITS = 74n;
381
+ var RANDOM_MASK = (1n << RANDOM_BITS) - 1n;
382
+ var MAX_TIMESTAMP = (1n << 48n) - 1n;
383
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("@trafficwar/node.uuidv7-state");
384
+ var processState = globalThis;
385
+ var existingState = processState[STATE_KEY];
386
+ var state = existingState ?? {
387
+ lastTimestamp: -1n,
388
+ lastRandom: 0n
389
+ };
390
+ processState[STATE_KEY] = state;
391
+ function random74() {
392
+ const bytes = crypto.randomBytes(10);
393
+ let value = 0n;
394
+ for (const byte of bytes) {
395
+ value = value << 8n | BigInt(byte);
396
+ }
397
+ return value & RANDOM_MASK;
398
+ }
399
+ function nextFields() {
400
+ const now = BigInt(Date.now());
401
+ if (now < 0n || now > MAX_TIMESTAMP) {
402
+ throw new RangeError("Current time cannot be represented as UUIDv7");
403
+ }
404
+ if (now > state.lastTimestamp) {
405
+ state.lastTimestamp = now;
406
+ state.lastRandom = random74();
407
+ } else if (state.lastRandom < RANDOM_MASK) {
408
+ state.lastRandom += 1n;
409
+ } else {
410
+ if (state.lastTimestamp >= MAX_TIMESTAMP) {
411
+ throw new RangeError("UUIDv7 timestamp space exhausted");
412
+ }
413
+ state.lastTimestamp += 1n;
414
+ state.lastRandom = random74();
415
+ }
416
+ return {
417
+ timestamp: state.lastTimestamp,
418
+ random: state.lastRandom
419
+ };
420
+ }
421
+ function hex(bytes) {
422
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
423
+ ""
424
+ );
425
+ }
426
+ function uuidv7() {
427
+ const { timestamp, random } = nextFields();
428
+ const bytes = new Uint8Array(16);
429
+ let timestampBits = timestamp;
430
+ for (let index = 5; index >= 0; index -= 1) {
431
+ bytes[index] = Number(timestampBits & 0xffn);
432
+ timestampBits >>= 8n;
433
+ }
434
+ bytes[6] = 112 | Number(random >> 70n & 0x0fn);
435
+ bytes[7] = Number(random >> 62n & 0xffn);
436
+ bytes[8] = 128 | Number(random >> 56n & 0x3fn);
437
+ let remaining = random & (1n << 56n) - 1n;
438
+ for (let index = 15; index >= 9; index -= 1) {
439
+ bytes[index] = Number(remaining & 0xffn);
440
+ remaining >>= 8n;
441
+ }
442
+ const value = hex(bytes);
443
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(
444
+ 12,
445
+ 16
446
+ )}-${value.slice(16, 20)}-${value.slice(20)}`;
447
+ }
392
448
 
393
449
  // package.json
394
450
  var package_default = {
395
- version: "1.0.0"};
451
+ version: "2.1.0"};
396
452
 
397
453
  // src/client.ts
398
454
  var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";
399
455
  var TRAFFICWAR_DEFAULT_TIMEOUT_MS = 3e4;
400
456
  var TRAFFICWAR_DEFAULT_MAX_RETRIES = 3;
457
+ var TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS = 1e3;
458
+ var TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE = 1e5;
401
459
  var TRAFFICWAR_MAX_BATCH_SIZE = 1e4;
402
460
  var TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES = 2 * 1024 * 1024;
403
461
  var TRAFFICWAR_MAX_DECODED_BODY_BYTES = 8 * 1024 * 1024;
@@ -416,6 +474,13 @@ var AttemptTransportFailure = class {
416
474
  this.timedOut = timedOut;
417
475
  }
418
476
  };
477
+ var PreparedRequestTooLarge = class extends Error {
478
+ limit;
479
+ constructor(limit) {
480
+ super(limit);
481
+ this.limit = limit;
482
+ }
483
+ };
419
484
  function asRecord(value) {
420
485
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
421
486
  return void 0;
@@ -472,6 +537,16 @@ function validateIntegerOption(name, value, fallback, minimum, maximum) {
472
537
  }
473
538
  return actual;
474
539
  }
540
+ function validateBooleanOption(name, value, fallback) {
541
+ const actual = value ?? fallback;
542
+ if (typeof actual !== "boolean") {
543
+ throw new TrafficWarValidationError(
544
+ `${name} must be a boolean`,
545
+ { path: `options.${name}` }
546
+ );
547
+ }
548
+ return actual;
549
+ }
475
550
  function validateCompression(value) {
476
551
  const actual = value ?? "auto";
477
552
  if (actual !== "auto" && actual !== "gzip" && actual !== "none") {
@@ -482,26 +557,6 @@ function validateCompression(value) {
482
557
  }
483
558
  return actual;
484
559
  }
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
560
  function parseBody(text) {
506
561
  if (text.length === 0) {
507
562
  return { text, value: void 0, isJson: false };
@@ -637,10 +692,7 @@ function gzipBody(decoded) {
637
692
  async function prepareRequest(payload, idempotencyKey, compression, compressionThresholdBytes) {
638
693
  const decoded = serializeJson(payload, idempotencyKey);
639
694
  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
- );
695
+ throw new PreparedRequestTooLarge("decoded");
644
696
  }
645
697
  const useGzip = compression === "gzip" || compression === "auto" && decoded.byteLength >= compressionThresholdBytes;
646
698
  let body;
@@ -654,10 +706,7 @@ async function prepareRequest(payload, idempotencyKey, compression, compressionT
654
706
  });
655
707
  }
656
708
  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
- );
709
+ throw new PreparedRequestTooLarge("wire");
661
710
  }
662
711
  return {
663
712
  body,
@@ -733,12 +782,27 @@ function parseSuccess(response, parsed, expectedCount, idempotencyKey) {
733
782
  }
734
783
  var TrafficWar = class {
735
784
  baseUrl;
785
+ debug;
736
786
  timeoutMs;
737
787
  maxRetries;
738
788
  compression;
739
789
  compressionThresholdBytes;
790
+ flushIntervalMs;
791
+ maxQueueSize;
740
792
  #apiKey;
741
793
  #fetch;
794
+ #onError;
795
+ #queue = [];
796
+ #pendingEventIds = /* @__PURE__ */ new Set();
797
+ #pendingCount = 0;
798
+ #preparedBatch;
799
+ #timer;
800
+ #drainPromise;
801
+ #backgroundPromise;
802
+ #backgroundScheduled = false;
803
+ #closePromise;
804
+ #closing = false;
805
+ #closed = false;
742
806
  constructor(options) {
743
807
  if (options === null || typeof options !== "object" || Array.isArray(options)) {
744
808
  throw new TrafficWarValidationError(
@@ -748,6 +812,7 @@ var TrafficWar = class {
748
812
  }
749
813
  this.#apiKey = validateApiKey(options.apiKey);
750
814
  this.baseUrl = normalizeBaseUrl(options.baseUrl);
815
+ this.debug = validateBooleanOption("debug", options.debug, false);
751
816
  this.timeoutMs = validateIntegerOption(
752
817
  "timeoutMs",
753
818
  options.timeoutMs,
@@ -770,119 +835,420 @@ var TrafficWar = class {
770
835
  0,
771
836
  TRAFFICWAR_MAX_DECODED_BODY_BYTES
772
837
  );
838
+ this.flushIntervalMs = validateIntegerOption(
839
+ "flushIntervalMs",
840
+ options.flushIntervalMs,
841
+ TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS,
842
+ 1,
843
+ MAX_TIMER_MS
844
+ );
845
+ this.maxQueueSize = validateIntegerOption(
846
+ "maxQueueSize",
847
+ options.maxQueueSize,
848
+ TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE,
849
+ 1,
850
+ Number.MAX_SAFE_INTEGER
851
+ );
773
852
  if (options.fetch !== void 0 && typeof options.fetch !== "function") {
774
853
  throw new TrafficWarValidationError(
775
854
  "fetch must be a function",
776
855
  { path: "options.fetch" }
777
856
  );
778
857
  }
858
+ if (options.onError !== void 0 && typeof options.onError !== "function") {
859
+ throw new TrafficWarValidationError(
860
+ "onError must be a function",
861
+ { path: "options.onError" }
862
+ );
863
+ }
779
864
  this.#fetch = options.fetch ?? ((input, init) => {
780
865
  return globalThis.fetch(input, init);
781
866
  });
867
+ this.#onError = options.onError;
868
+ this.#debugLog("client initialized", {
869
+ baseUrl: this.baseUrl,
870
+ compression: this.compression,
871
+ flushIntervalMs: this.flushIntervalMs,
872
+ maxQueueSize: this.maxQueueSize,
873
+ maxRetries: this.maxRetries,
874
+ timeoutMs: this.timeoutMs
875
+ });
782
876
  }
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
- );
877
+ #debugLog(message, details) {
878
+ if (!this.debug) {
879
+ return;
880
+ }
881
+ try {
882
+ console.debug(`[TrafficWar] ${message}`, details);
883
+ } catch {
884
+ }
796
885
  }
797
- async captureBatch(events, options) {
798
- const identity = requestIdentity(options);
799
- if (!Array.isArray(events) || events.length === 0) {
886
+ capture(eventOrEvents) {
887
+ if (this.#closed) {
888
+ throw new TrafficWarValidationError(
889
+ "TrafficWar client is closed",
890
+ { path: "client" }
891
+ );
892
+ }
893
+ if (this.#closing) {
894
+ throw new TrafficWarValidationError(
895
+ "TrafficWar client is closing",
896
+ { path: "client" }
897
+ );
898
+ }
899
+ const isBatch = Array.isArray(eventOrEvents);
900
+ if (isBatch && eventOrEvents.length === 0) {
800
901
  throw new TrafficWarValidationError(
801
902
  "events must be a non-empty array",
802
- { path: "events", idempotencyKey: identity.idempotencyKey }
903
+ { path: "events" }
803
904
  );
804
905
  }
805
- if (events.length > TRAFFICWAR_MAX_BATCH_SIZE) {
906
+ const events = isBatch ? eventOrEvents : [eventOrEvents];
907
+ if (isBatch) {
908
+ for (let index = 0; index < events.length; index += 1) {
909
+ if (!(index in events)) {
910
+ const path = `events[${index}]`;
911
+ throw new TrafficWarValidationError(
912
+ `${path} is missing; sparse event arrays are not supported`,
913
+ { path }
914
+ );
915
+ }
916
+ }
917
+ }
918
+ if (events.length > this.maxQueueSize - this.#pendingCount) {
806
919
  throw new TrafficWarValidationError(
807
- `events must contain at most ${TRAFFICWAR_MAX_BATCH_SIZE} events`,
808
- { path: "events", idempotencyKey: identity.idempotencyKey }
920
+ `TrafficWar queue cannot exceed ${this.maxQueueSize} events`,
921
+ { path: "queue" }
809
922
  );
810
923
  }
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
- );
924
+ const normalized = [];
925
+ for (let index = 0; index < events.length; index += 1) {
926
+ const path = isBatch ? `events[${index}]` : "event";
927
+ normalized.push(normalizeEvent(events[index], path));
928
+ }
929
+ for (const event of normalized) {
930
+ if (!Object.hasOwn(event, "event_id")) {
931
+ event.event_id = uuidv7();
932
+ }
933
+ }
934
+ const incomingEventIds = /* @__PURE__ */ new Set();
935
+ for (let index = 0; index < normalized.length; index += 1) {
936
+ const eventId = normalized[index].event_id;
937
+ if (incomingEventIds.has(eventId) || this.#pendingEventIds.has(eventId)) {
938
+ const path = isBatch ? `events[${index}].event_id` : "event.event_id";
939
+ throw new TrafficWarValidationError(
940
+ `${path} duplicates an unacknowledged event_id`,
941
+ { path }
942
+ );
943
+ }
944
+ incomingEventIds.add(eventId);
945
+ }
946
+ for (const event of normalized) {
947
+ this.#queue.push(event);
948
+ this.#pendingEventIds.add(event.event_id);
949
+ }
950
+ this.#pendingCount += normalized.length;
951
+ this.#debugLog("events queued", {
952
+ added: normalized.length,
953
+ pending: this.#pendingCount
954
+ });
955
+ if (this.#pendingCount >= TRAFFICWAR_MAX_BATCH_SIZE) {
956
+ this.#clearTimer();
957
+ this.#debugLog("automatic flush triggered", {
958
+ pending: this.#pendingCount,
959
+ reason: "batch-size"
960
+ });
961
+ this.#startBackgroundDrain();
962
+ } else {
963
+ this.#ensureTimer();
964
+ }
965
+ }
966
+ /**
967
+ * @deprecated Pass the array directly to capture().
968
+ */
969
+ captureBatch(events) {
970
+ if (!Array.isArray(events) || events.length === 0) {
971
+ throw new TrafficWarValidationError(
972
+ "events must be a non-empty array",
973
+ { path: "events" }
974
+ );
975
+ }
976
+ this.capture(events);
977
+ }
978
+ flush() {
979
+ this.#debugLog("manual flush requested", {
980
+ pending: this.#pendingCount
981
+ });
982
+ if (this.#closePromise) {
983
+ return this.#closePromise;
984
+ }
985
+ this.#clearTimer();
986
+ return this.#startDrain();
987
+ }
988
+ close() {
989
+ if (this.#closed) {
990
+ return Promise.resolve({ accepted: 0, batches: [] });
991
+ }
992
+ if (this.#closePromise) {
993
+ return this.#closePromise;
994
+ }
995
+ this.#debugLog("close requested", {
996
+ pending: this.#pendingCount
997
+ });
998
+ this.#clearTimer();
999
+ this.#closing = true;
1000
+ let closing;
1001
+ closing = Promise.resolve().then(async () => {
1002
+ const batches = [];
1003
+ let accepted = 0;
1004
+ try {
1005
+ do {
1006
+ const result = await this.#startDrain();
1007
+ accepted += result.accepted;
1008
+ for (const batch of result.batches) {
1009
+ batches.push(batch);
1010
+ }
1011
+ } while (this.#pendingCount > 0);
1012
+ this.#clearTimer();
1013
+ this.#closed = true;
1014
+ this.#debugLog("client closed", {
1015
+ accepted,
1016
+ batches: batches.length
1017
+ });
1018
+ return { accepted, batches };
1019
+ } finally {
1020
+ if (this.#closePromise === closing) {
1021
+ this.#closePromise = void 0;
1022
+ }
1023
+ this.#closing = false;
1024
+ if (!this.#closed && this.#pendingCount > 0) {
1025
+ this.#ensureTimer();
1026
+ }
1027
+ }
1028
+ });
1029
+ this.#closePromise = closing;
1030
+ return closing;
1031
+ }
1032
+ #ensureTimer() {
1033
+ if (this.#closed || this.#closing || this.#pendingCount === 0 || this.#timer !== void 0) {
1034
+ return;
1035
+ }
1036
+ const timer = setTimeout(() => {
1037
+ if (this.#timer === timer) {
1038
+ this.#timer = void 0;
1039
+ }
1040
+ this.#debugLog("automatic flush triggered", {
1041
+ pending: this.#pendingCount,
1042
+ reason: "interval"
1043
+ });
1044
+ this.#startBackgroundDrain();
1045
+ }, this.flushIntervalMs);
1046
+ timer.unref();
1047
+ this.#timer = timer;
1048
+ this.#debugLog("flush timer scheduled", {
1049
+ delayMs: this.flushIntervalMs,
1050
+ pending: this.#pendingCount
1051
+ });
825
1052
  }
826
- async #send(path, payload, expectedCount, identity) {
827
- const prepared = await prepareRequest(
828
- payload,
829
- identity.idempotencyKey,
830
- this.compression,
831
- this.compressionThresholdBytes
1053
+ #clearTimer() {
1054
+ if (this.#timer !== void 0) {
1055
+ clearTimeout(this.#timer);
1056
+ this.#timer = void 0;
1057
+ }
1058
+ }
1059
+ #startBackgroundDrain() {
1060
+ if (this.#backgroundScheduled) {
1061
+ return;
1062
+ }
1063
+ this.#backgroundScheduled = true;
1064
+ queueMicrotask(() => {
1065
+ this.#backgroundScheduled = false;
1066
+ if (!this.#closed && this.#pendingCount > 0) {
1067
+ this.#observeBackgroundDrain(this.#startDrain());
1068
+ }
1069
+ });
1070
+ }
1071
+ #observeBackgroundDrain(drain) {
1072
+ if (this.#backgroundPromise === drain) {
1073
+ return;
1074
+ }
1075
+ this.#backgroundPromise = drain;
1076
+ void drain.then(
1077
+ () => {
1078
+ if (this.#backgroundPromise === drain) {
1079
+ this.#backgroundPromise = void 0;
1080
+ }
1081
+ },
1082
+ (error) => {
1083
+ if (this.#backgroundPromise === drain) {
1084
+ this.#backgroundPromise = void 0;
1085
+ }
1086
+ if (this.#onError) {
1087
+ try {
1088
+ const handled = this.#onError(error);
1089
+ void Promise.resolve(handled).catch(() => void 0);
1090
+ } catch {
1091
+ }
1092
+ }
1093
+ }
832
1094
  );
1095
+ }
1096
+ #startDrain() {
1097
+ if (this.#drainPromise) {
1098
+ return this.#drainPromise;
1099
+ }
1100
+ let drain;
1101
+ drain = (async () => {
1102
+ this.#debugLog("flush started", {
1103
+ pending: this.#pendingCount
1104
+ });
1105
+ try {
1106
+ const result = await this.#drain();
1107
+ this.#debugLog("flush completed", {
1108
+ accepted: result.accepted,
1109
+ batches: result.batches.length,
1110
+ pending: this.#pendingCount
1111
+ });
1112
+ return result;
1113
+ } catch (error) {
1114
+ this.#debugLog("flush failed", {
1115
+ errorMessage: error instanceof Error ? error.message : String(error),
1116
+ errorName: error instanceof Error ? error.name : typeof error,
1117
+ pending: this.#pendingCount
1118
+ });
1119
+ throw error;
1120
+ } finally {
1121
+ if (this.#drainPromise === drain) {
1122
+ this.#drainPromise = void 0;
1123
+ }
1124
+ if (this.#pendingCount === 0) {
1125
+ this.#clearTimer();
1126
+ } else if (!this.#closed) {
1127
+ this.#ensureTimer();
1128
+ }
1129
+ }
1130
+ })();
1131
+ this.#drainPromise = drain;
1132
+ return drain;
1133
+ }
1134
+ async #drain() {
1135
+ const batches = [];
1136
+ let accepted = 0;
1137
+ while (this.#pendingCount > 0) {
1138
+ const batch = this.#preparedBatch ?? await this.#prepareNextBatch();
1139
+ this.#preparedBatch = batch;
1140
+ const result = await this.#send(batch);
1141
+ for (const event of batch.events) {
1142
+ this.#pendingEventIds.delete(event.event_id);
1143
+ }
1144
+ this.#preparedBatch = void 0;
1145
+ this.#pendingCount -= batch.events.length;
1146
+ accepted += result.accepted;
1147
+ batches.push(result);
1148
+ }
1149
+ return { accepted, batches };
1150
+ }
1151
+ async #prepareNextBatch() {
1152
+ let count = Math.min(this.#queue.length, TRAFFICWAR_MAX_BATCH_SIZE);
1153
+ if (count === 0) {
1154
+ throw new Error("TrafficWar queue state is inconsistent");
1155
+ }
1156
+ while (true) {
1157
+ const events = this.#queue.slice(0, count);
1158
+ const idempotencyKey = uuidv7();
1159
+ try {
1160
+ const prepared = await prepareRequest(
1161
+ events,
1162
+ idempotencyKey,
1163
+ this.compression,
1164
+ this.compressionThresholdBytes
1165
+ );
1166
+ this.#queue.splice(0, count);
1167
+ const batch = { ...prepared, events, idempotencyKey };
1168
+ this.#debugLog("batch prepared", {
1169
+ bodyBytes: prepared.body.byteLength,
1170
+ contentEncoding: prepared.contentEncoding ?? "identity",
1171
+ events: events.length,
1172
+ idempotencyKey
1173
+ });
1174
+ return batch;
1175
+ } catch (error) {
1176
+ if (!(error instanceof PreparedRequestTooLarge)) {
1177
+ throw error;
1178
+ }
1179
+ if (count > 1) {
1180
+ count = Math.max(1, Math.floor(count / 2));
1181
+ continue;
1182
+ }
1183
+ const message = error.limit === "decoded" ? `Decoded request body exceeds ${TRAFFICWAR_MAX_DECODED_BODY_BYTES} bytes` : `Request body exceeds the ${TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES}-byte wire limit`;
1184
+ throw new TrafficWarValidationError(message, {
1185
+ path: "body",
1186
+ idempotencyKey
1187
+ });
1188
+ }
1189
+ }
1190
+ }
1191
+ async #send(batch, signal) {
833
1192
  const headers = {
834
1193
  accept: "application/json",
835
1194
  authorization: `Bearer ${this.#apiKey}`,
836
1195
  "content-type": "application/json",
837
- "idempotency-key": identity.idempotencyKey,
1196
+ "idempotency-key": batch.idempotencyKey,
838
1197
  "user-agent": `@trafficwar/node/${SDK_VERSION}`,
839
1198
  "x-trafficwar-sdk": `node/${SDK_VERSION}`
840
1199
  };
841
- if (prepared.contentEncoding) {
842
- headers["content-encoding"] = prepared.contentEncoding;
1200
+ if (batch.contentEncoding) {
1201
+ headers["content-encoding"] = batch.contentEncoding;
843
1202
  }
844
- const url = `${this.baseUrl}${path}`;
1203
+ const url = `${this.baseUrl}/v1/server/batch`;
845
1204
  const init = {
846
1205
  method: "POST",
847
1206
  headers,
848
- body: prepared.body,
1207
+ body: batch.body,
849
1208
  redirect: "error"
850
1209
  };
851
1210
  let sawTimeout = false;
852
1211
  for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
853
- if (identity.signal?.aborted) {
1212
+ if (signal?.aborted) {
854
1213
  throw new TrafficWarConnectionError(
855
1214
  "TrafficWar request was aborted",
856
1215
  {
857
1216
  attempts: attempt,
858
1217
  aborted: true,
859
1218
  timedOut: sawTimeout,
860
- idempotencyKey: identity.idempotencyKey,
861
- cause: identity.signal.reason
1219
+ idempotencyKey: batch.idempotencyKey,
1220
+ cause: signal.reason
862
1221
  }
863
1222
  );
864
1223
  }
1224
+ this.#debugLog("request attempt", {
1225
+ attempt: attempt + 1,
1226
+ bodyBytes: batch.body.byteLength,
1227
+ events: batch.events.length,
1228
+ idempotencyKey: batch.idempotencyKey,
1229
+ maxAttempts: this.maxRetries + 1
1230
+ });
865
1231
  let result;
866
1232
  try {
867
1233
  result = await executeAttempt(
868
1234
  this.#fetch,
869
1235
  url,
870
1236
  init,
871
- identity.signal,
1237
+ signal,
872
1238
  this.timeoutMs
873
1239
  );
874
1240
  } catch (error) {
875
1241
  const failure = error instanceof AttemptTransportFailure ? error : new AttemptTransportFailure(error, false);
876
1242
  sawTimeout ||= failure.timedOut;
877
- if (identity.signal?.aborted) {
1243
+ if (signal?.aborted) {
878
1244
  throw new TrafficWarConnectionError(
879
1245
  "TrafficWar request was aborted",
880
1246
  {
881
1247
  attempts: attempt + 1,
882
1248
  aborted: true,
883
1249
  timedOut: sawTimeout,
884
- idempotencyKey: identity.idempotencyKey,
885
- cause: identity.signal.reason ?? failure.cause
1250
+ idempotencyKey: batch.idempotencyKey,
1251
+ cause: signal.reason ?? failure.cause
886
1252
  }
887
1253
  );
888
1254
  }
@@ -892,13 +1258,20 @@ var TrafficWar = class {
892
1258
  {
893
1259
  attempts: attempt + 1,
894
1260
  timedOut: sawTimeout,
895
- idempotencyKey: identity.idempotencyKey,
1261
+ idempotencyKey: batch.idempotencyKey,
896
1262
  cause: failure.cause
897
1263
  }
898
1264
  );
899
1265
  }
1266
+ const delayMs = retryDelayMs(attempt, void 0);
1267
+ this.#debugLog("request retry scheduled", {
1268
+ attempt: attempt + 1,
1269
+ delayMs,
1270
+ idempotencyKey: batch.idempotencyKey,
1271
+ reason: failure.timedOut ? "timeout" : "transport"
1272
+ });
900
1273
  try {
901
- await sleep(retryDelayMs(attempt, void 0), identity.signal);
1274
+ await sleep(delayMs, signal);
902
1275
  } catch (cause) {
903
1276
  throw new TrafficWarConnectionError(
904
1277
  "TrafficWar request was aborted",
@@ -906,7 +1279,7 @@ var TrafficWar = class {
906
1279
  attempts: attempt + 1,
907
1280
  aborted: true,
908
1281
  timedOut: sawTimeout,
909
- idempotencyKey: identity.idempotencyKey,
1282
+ idempotencyKey: batch.idempotencyKey,
910
1283
  cause
911
1284
  }
912
1285
  );
@@ -915,18 +1288,32 @@ var TrafficWar = class {
915
1288
  }
916
1289
  const parsed = parseBody(result.text);
917
1290
  if (result.response.ok) {
918
- return parseSuccess(
1291
+ const ingest = parseSuccess(
919
1292
  result.response,
920
1293
  parsed,
921
- expectedCount,
922
- identity.idempotencyKey
1294
+ batch.events.length,
1295
+ batch.idempotencyKey
923
1296
  );
1297
+ this.#debugLog("request accepted", {
1298
+ accepted: ingest.accepted,
1299
+ attempt: attempt + 1,
1300
+ idempotencyKey: batch.idempotencyKey,
1301
+ ingestId: ingest.ingestId
1302
+ });
1303
+ return ingest;
924
1304
  }
925
1305
  if (RETRYABLE_STATUSES.has(result.response.status) && attempt < this.maxRetries) {
926
1306
  const retryAfter = retryAfterSeconds(result.response, parsed);
927
1307
  if (retryAfter === void 0 || retryAfter <= MAX_RETRY_AFTER_SECONDS) {
1308
+ const delayMs = retryDelayMs(attempt, retryAfter);
1309
+ this.#debugLog("request retry scheduled", {
1310
+ attempt: attempt + 1,
1311
+ delayMs,
1312
+ idempotencyKey: batch.idempotencyKey,
1313
+ reason: `http-${result.response.status}`
1314
+ });
928
1315
  try {
929
- await sleep(retryDelayMs(attempt, retryAfter), identity.signal);
1316
+ await sleep(delayMs, signal);
930
1317
  } catch (cause) {
931
1318
  throw new TrafficWarConnectionError(
932
1319
  "TrafficWar request was aborted",
@@ -934,7 +1321,7 @@ var TrafficWar = class {
934
1321
  attempts: attempt + 1,
935
1322
  aborted: true,
936
1323
  timedOut: sawTimeout,
937
- idempotencyKey: identity.idempotencyKey,
1324
+ idempotencyKey: batch.idempotencyKey,
938
1325
  cause
939
1326
  }
940
1327
  );
@@ -942,21 +1329,28 @@ var TrafficWar = class {
942
1329
  continue;
943
1330
  }
944
1331
  }
1332
+ this.#debugLog("request rejected", {
1333
+ attempt: attempt + 1,
1334
+ idempotencyKey: batch.idempotencyKey,
1335
+ status: result.response.status
1336
+ });
945
1337
  throw buildApiError(
946
1338
  result.response,
947
1339
  parsed,
948
- identity.idempotencyKey
1340
+ batch.idempotencyKey
949
1341
  );
950
1342
  }
951
1343
  throw new TrafficWarConnectionError("Unable to reach TrafficWar", {
952
1344
  attempts: this.maxRetries + 1,
953
1345
  timedOut: sawTimeout,
954
- idempotencyKey: identity.idempotencyKey
1346
+ idempotencyKey: batch.idempotencyKey
955
1347
  });
956
1348
  }
957
1349
  };
958
1350
 
959
1351
  exports.TRAFFICWAR_DEFAULT_BASE_URL = TRAFFICWAR_DEFAULT_BASE_URL;
1352
+ exports.TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS = TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS;
1353
+ exports.TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE = TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE;
960
1354
  exports.TRAFFICWAR_DEFAULT_MAX_RETRIES = TRAFFICWAR_DEFAULT_MAX_RETRIES;
961
1355
  exports.TRAFFICWAR_DEFAULT_TIMEOUT_MS = TRAFFICWAR_DEFAULT_TIMEOUT_MS;
962
1356
  exports.TRAFFICWAR_MAX_BATCH_SIZE = TRAFFICWAR_MAX_BATCH_SIZE;