@trafficwar/node 2.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/README.md CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
  Official, dependency-free TrafficWar server SDK for Node.js 22 and newer.
4
4
 
5
- > **Breaking change in 2.0.0:** `capture` now enqueues events for automatic
6
- > batching instead of waiting for an individual ingestion response.
7
-
8
5
  ## Install
9
6
 
10
7
  ```sh
11
8
  npm install @trafficwar/node
9
+ # or
10
+ pnpm add @trafficwar/node
11
+ # or
12
+ bun add @trafficwar/node
12
13
  ```
13
14
 
14
15
  ## Capture events
@@ -72,6 +73,17 @@ const trafficwar = new TrafficWar({
72
73
  If enqueueing would exceed the configured queue limit, `capture` throws a
73
74
  `TrafficWarValidationError` and enqueues none of that call.
74
75
 
76
+ Set `debug: true` to print queue, flush, request, retry, and acknowledgement
77
+ diagnostics with `console.debug`. Debug logging is off by default and never
78
+ includes API keys or queued event payloads.
79
+
80
+ ```ts
81
+ const trafficwar = new TrafficWar({
82
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
83
+ debug: true,
84
+ });
85
+ ```
86
+
75
87
  The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
76
88
  that omits one. A caller may override it with any valid UUID. Caller-owned
77
89
  objects are never modified.
@@ -134,6 +146,8 @@ attempt, `flush`, or `close` retries that same batch, and explicit `flush` or
134
146
 
135
147
  - `apiKey` (required): TrafficWar server API key.
136
148
  - `baseUrl`: ingest origin. Defaults to `https://ingest.trafficwar.tech`.
149
+ - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
150
+ Defaults to `false`.
137
151
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
138
152
  TrafficWar's 10-second durable acknowledgement window.
139
153
  - `maxRetries`: retries after the first attempt. Defaults to 3.
package/dist/index.cjs CHANGED
@@ -448,7 +448,7 @@ function uuidv7() {
448
448
 
449
449
  // package.json
450
450
  var package_default = {
451
- version: "2.0.0"};
451
+ version: "2.1.0"};
452
452
 
453
453
  // src/client.ts
454
454
  var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";
@@ -537,6 +537,16 @@ function validateIntegerOption(name, value, fallback, minimum, maximum) {
537
537
  }
538
538
  return actual;
539
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
+ }
540
550
  function validateCompression(value) {
541
551
  const actual = value ?? "auto";
542
552
  if (actual !== "auto" && actual !== "gzip" && actual !== "none") {
@@ -772,6 +782,7 @@ function parseSuccess(response, parsed, expectedCount, idempotencyKey) {
772
782
  }
773
783
  var TrafficWar = class {
774
784
  baseUrl;
785
+ debug;
775
786
  timeoutMs;
776
787
  maxRetries;
777
788
  compression;
@@ -801,6 +812,7 @@ var TrafficWar = class {
801
812
  }
802
813
  this.#apiKey = validateApiKey(options.apiKey);
803
814
  this.baseUrl = normalizeBaseUrl(options.baseUrl);
815
+ this.debug = validateBooleanOption("debug", options.debug, false);
804
816
  this.timeoutMs = validateIntegerOption(
805
817
  "timeoutMs",
806
818
  options.timeoutMs,
@@ -853,6 +865,23 @@ var TrafficWar = class {
853
865
  return globalThis.fetch(input, init);
854
866
  });
855
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
+ });
876
+ }
877
+ #debugLog(message, details) {
878
+ if (!this.debug) {
879
+ return;
880
+ }
881
+ try {
882
+ console.debug(`[TrafficWar] ${message}`, details);
883
+ } catch {
884
+ }
856
885
  }
857
886
  capture(eventOrEvents) {
858
887
  if (this.#closed) {
@@ -919,8 +948,16 @@ var TrafficWar = class {
919
948
  this.#pendingEventIds.add(event.event_id);
920
949
  }
921
950
  this.#pendingCount += normalized.length;
951
+ this.#debugLog("events queued", {
952
+ added: normalized.length,
953
+ pending: this.#pendingCount
954
+ });
922
955
  if (this.#pendingCount >= TRAFFICWAR_MAX_BATCH_SIZE) {
923
956
  this.#clearTimer();
957
+ this.#debugLog("automatic flush triggered", {
958
+ pending: this.#pendingCount,
959
+ reason: "batch-size"
960
+ });
924
961
  this.#startBackgroundDrain();
925
962
  } else {
926
963
  this.#ensureTimer();
@@ -939,6 +976,9 @@ var TrafficWar = class {
939
976
  this.capture(events);
940
977
  }
941
978
  flush() {
979
+ this.#debugLog("manual flush requested", {
980
+ pending: this.#pendingCount
981
+ });
942
982
  if (this.#closePromise) {
943
983
  return this.#closePromise;
944
984
  }
@@ -952,6 +992,9 @@ var TrafficWar = class {
952
992
  if (this.#closePromise) {
953
993
  return this.#closePromise;
954
994
  }
995
+ this.#debugLog("close requested", {
996
+ pending: this.#pendingCount
997
+ });
955
998
  this.#clearTimer();
956
999
  this.#closing = true;
957
1000
  let closing;
@@ -968,6 +1011,10 @@ var TrafficWar = class {
968
1011
  } while (this.#pendingCount > 0);
969
1012
  this.#clearTimer();
970
1013
  this.#closed = true;
1014
+ this.#debugLog("client closed", {
1015
+ accepted,
1016
+ batches: batches.length
1017
+ });
971
1018
  return { accepted, batches };
972
1019
  } finally {
973
1020
  if (this.#closePromise === closing) {
@@ -990,10 +1037,18 @@ var TrafficWar = class {
990
1037
  if (this.#timer === timer) {
991
1038
  this.#timer = void 0;
992
1039
  }
1040
+ this.#debugLog("automatic flush triggered", {
1041
+ pending: this.#pendingCount,
1042
+ reason: "interval"
1043
+ });
993
1044
  this.#startBackgroundDrain();
994
1045
  }, this.flushIntervalMs);
995
1046
  timer.unref();
996
1047
  this.#timer = timer;
1048
+ this.#debugLog("flush timer scheduled", {
1049
+ delayMs: this.flushIntervalMs,
1050
+ pending: this.#pendingCount
1051
+ });
997
1052
  }
998
1053
  #clearTimer() {
999
1054
  if (this.#timer !== void 0) {
@@ -1044,8 +1099,24 @@ var TrafficWar = class {
1044
1099
  }
1045
1100
  let drain;
1046
1101
  drain = (async () => {
1102
+ this.#debugLog("flush started", {
1103
+ pending: this.#pendingCount
1104
+ });
1047
1105
  try {
1048
- return await this.#drain();
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;
1049
1120
  } finally {
1050
1121
  if (this.#drainPromise === drain) {
1051
1122
  this.#drainPromise = void 0;
@@ -1093,7 +1164,14 @@ var TrafficWar = class {
1093
1164
  this.compressionThresholdBytes
1094
1165
  );
1095
1166
  this.#queue.splice(0, count);
1096
- return { ...prepared, events, idempotencyKey };
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;
1097
1175
  } catch (error) {
1098
1176
  if (!(error instanceof PreparedRequestTooLarge)) {
1099
1177
  throw error;
@@ -1143,6 +1221,13 @@ var TrafficWar = class {
1143
1221
  }
1144
1222
  );
1145
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
+ });
1146
1231
  let result;
1147
1232
  try {
1148
1233
  result = await executeAttempt(
@@ -1178,8 +1263,15 @@ var TrafficWar = class {
1178
1263
  }
1179
1264
  );
1180
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
+ });
1181
1273
  try {
1182
- await sleep(retryDelayMs(attempt, void 0), signal);
1274
+ await sleep(delayMs, signal);
1183
1275
  } catch (cause) {
1184
1276
  throw new TrafficWarConnectionError(
1185
1277
  "TrafficWar request was aborted",
@@ -1196,18 +1288,32 @@ var TrafficWar = class {
1196
1288
  }
1197
1289
  const parsed = parseBody(result.text);
1198
1290
  if (result.response.ok) {
1199
- return parseSuccess(
1291
+ const ingest = parseSuccess(
1200
1292
  result.response,
1201
1293
  parsed,
1202
1294
  batch.events.length,
1203
1295
  batch.idempotencyKey
1204
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;
1205
1304
  }
1206
1305
  if (RETRYABLE_STATUSES.has(result.response.status) && attempt < this.maxRetries) {
1207
1306
  const retryAfter = retryAfterSeconds(result.response, parsed);
1208
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
+ });
1209
1315
  try {
1210
- await sleep(retryDelayMs(attempt, retryAfter), signal);
1316
+ await sleep(delayMs, signal);
1211
1317
  } catch (cause) {
1212
1318
  throw new TrafficWarConnectionError(
1213
1319
  "TrafficWar request was aborted",
@@ -1223,6 +1329,11 @@ var TrafficWar = class {
1223
1329
  continue;
1224
1330
  }
1225
1331
  }
1332
+ this.#debugLog("request rejected", {
1333
+ attempt: attempt + 1,
1334
+ idempotencyKey: batch.idempotencyKey,
1335
+ status: result.response.status
1336
+ });
1226
1337
  throw buildApiError(
1227
1338
  result.response,
1228
1339
  parsed,