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