@visulima/pail 4.0.0-alpha.8 → 4.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.
Files changed (145) hide show
  1. package/CHANGELOG.md +531 -0
  2. package/LICENSE.md +270 -166
  3. package/README.md +53 -24
  4. package/dist/error.d.ts +95 -96
  5. package/dist/error.js +5 -76
  6. package/dist/index.browser.d.ts +568 -47
  7. package/dist/index.browser.js +19 -1499
  8. package/dist/index.server.d.ts +749 -65
  9. package/dist/index.server.js +32 -3179
  10. package/dist/middleware/elysia.d.ts +66 -63
  11. package/dist/middleware/elysia.js +1 -70
  12. package/dist/middleware/express.d.ts +74 -71
  13. package/dist/middleware/express.js +1 -29
  14. package/dist/middleware/fastify.d.ts +70 -67
  15. package/dist/middleware/fastify.js +1 -46
  16. package/dist/middleware/hono.d.ts +75 -72
  17. package/dist/middleware/hono.js +1 -33
  18. package/dist/middleware/next/handler.d.ts +102 -34
  19. package/dist/middleware/next/handler.js +1 -53
  20. package/dist/middleware/sveltekit.d.ts +101 -98
  21. package/dist/middleware/sveltekit.js +1 -43
  22. package/dist/object-tree.d.ts +67 -70
  23. package/dist/object-tree.js +2 -89
  24. package/dist/packem_shared/AbstractJsonReporter-Bp_JCrMQ.js +1 -0
  25. package/dist/packem_shared/AbstractJsonReporter-w_bGGiD-.js +1 -0
  26. package/dist/packem_shared/JsonReporter-Sd_lJGS-.js +2 -0
  27. package/dist/packem_shared/JsonReporter-bmem9lcg.js +1 -0
  28. package/dist/packem_shared/PailError-CbU1Ogfa.js +5 -0
  29. package/dist/packem_shared/PrettyReporter-CcDdPQSt.js +44 -0
  30. package/dist/packem_shared/PrettyReporter-DsHfKOU7.js +5 -0
  31. package/dist/packem_shared/abstract-json-reporter.d-wfESoEa-.d.ts +62 -0
  32. package/dist/packem_shared/abstract-pretty-reporter-DrLBJ6ds.js +57 -0
  33. package/dist/packem_shared/addKnownErrorConstructor-C1OJTj2D-0FlJMfXz.js +25 -0
  34. package/dist/packem_shared/constants-DKfCaSUR.js +1 -0
  35. package/dist/packem_shared/constants-ep2nsfdy.js +1 -0
  36. package/dist/packem_shared/create-middleware-logger.d-B-JmQ1Sl.d.ts +47 -0
  37. package/dist/packem_shared/headers-DH0H2s8W.js +1 -0
  38. package/dist/packem_shared/index-Q1764hvO.js +1 -0
  39. package/dist/packem_shared/index.d-T71KjNAr.d.ts +16 -0
  40. package/dist/packem_shared/pailMiddleware-B5DJoBYl.js +1 -0
  41. package/dist/packem_shared/serializeError-C-NFvZ8_-D0CA_Qlx.js +1 -0
  42. package/dist/packem_shared/storage-DaXAlpiO.js +1 -0
  43. package/dist/packem_shared/types.d-Cz9S7jZh.d.ts +201 -0
  44. package/dist/packem_shared/types.d-bWnqHJKL.d.ts +211 -0
  45. package/dist/packem_shared/types.d-xxE3FOD3.d.ts +229 -0
  46. package/dist/packem_shared/useLogger-DB34CuU5.js +1 -0
  47. package/dist/packem_shared/wide-event.d-D3ATYpoK.d.ts +717 -0
  48. package/dist/packem_shared/write-console-log-based-on-level-BqjxV016.js +1 -0
  49. package/dist/packem_shared/write-stream-C7jxLxIT.js +1 -0
  50. package/dist/processor/caller/caller-processor.d.ts +50 -47
  51. package/dist/processor/caller/caller-processor.js +1 -59
  52. package/dist/processor/environment-processor.d.ts +114 -113
  53. package/dist/processor/environment-processor.js +1 -78
  54. package/dist/processor/message-formatter-processor.d.ts +59 -49
  55. package/dist/processor/message-formatter-processor.js +1 -713
  56. package/dist/processor/opentelemetry-processor.d.ts +70 -66
  57. package/dist/processor/opentelemetry-processor.js +1 -52
  58. package/dist/processor/redact-processor.d.ts +99 -41
  59. package/dist/processor/redact-processor.js +1 -30
  60. package/dist/processor/sampling-processor.d.ts +103 -101
  61. package/dist/processor/sampling-processor.js +1 -59
  62. package/dist/reporter/file/json-file-reporter.d.ts +109 -42
  63. package/dist/reporter/file/json-file-reporter.js +2 -136
  64. package/dist/reporter/http/abstract-http-reporter.d.ts +256 -211
  65. package/dist/reporter/http/abstract-http-reporter.js +2 -435
  66. package/dist/reporter/http/http-reporter.d.ts +41 -36
  67. package/dist/reporter/http/http-reporter.edge-light.d.ts +487 -39
  68. package/dist/reporter/http/http-reporter.edge-light.js +2 -733
  69. package/dist/reporter/http/http-reporter.js +1 -13
  70. package/dist/reporter/json/index.browser.d.ts +98 -3
  71. package/dist/reporter/json/index.browser.js +1 -2
  72. package/dist/reporter/json/index.d.ts +53 -3
  73. package/dist/reporter/json/index.js +1 -2
  74. package/dist/reporter/pretty/index.browser.d.ts +105 -2
  75. package/dist/reporter/pretty/index.browser.js +1 -1
  76. package/dist/reporter/pretty/index.d.ts +270 -2
  77. package/dist/reporter/pretty/index.js +1 -1
  78. package/dist/reporter/simple/simple-reporter.server.d.ts +215 -18
  79. package/dist/reporter/simple/simple-reporter.server.js +8 -182
  80. package/dist/wide-event.d.ts +6 -300
  81. package/dist/wide-event.js +1 -281
  82. package/package.json +23 -38
  83. package/dist/constants.d.ts +0 -37
  84. package/dist/interactive/index.d.ts +0 -2
  85. package/dist/interactive/index.js +0 -2
  86. package/dist/interactive/interactive-manager.d.ts +0 -108
  87. package/dist/interactive/interactive-stream-hook.d.ts +0 -68
  88. package/dist/middleware/next/middleware.d.ts +0 -59
  89. package/dist/middleware/next/storage.d.ts +0 -14
  90. package/dist/middleware/shared/create-middleware-logger.d.ts +0 -82
  91. package/dist/middleware/shared/headers.d.ts +0 -14
  92. package/dist/middleware/shared/routes.d.ts +0 -30
  93. package/dist/middleware/shared/storage.d.ts +0 -29
  94. package/dist/packem_shared/AbstractJsonReporter-CGKHS8_M.js +0 -286
  95. package/dist/packem_shared/AbstractJsonReporter-DDjDkciI.js +0 -286
  96. package/dist/packem_shared/InteractiveManager-Cd6A14ZK.js +0 -172
  97. package/dist/packem_shared/InteractiveStreamHook-ePIURL_U.js +0 -133
  98. package/dist/packem_shared/JsonReporter-B3XX8GHN.js +0 -58
  99. package/dist/packem_shared/JsonReporter-p_BXg6Sj.js +0 -28
  100. package/dist/packem_shared/PrettyReporter-BYL3NrdA.js +0 -214
  101. package/dist/packem_shared/PrettyReporter-CvBn-hxP.js +0 -1459
  102. package/dist/packem_shared/Spinner-DIdVcfWq.js +0 -2183
  103. package/dist/packem_shared/abstract-pretty-reporter-jU8WL_6c.js +0 -2602
  104. package/dist/packem_shared/constants-B1RjD_ps.js +0 -99
  105. package/dist/packem_shared/constants-omsTHUWB.js +0 -119
  106. package/dist/packem_shared/createPailError-B11aRfrT.js +0 -76
  107. package/dist/packem_shared/getBarChar-BWj1UrH3.js +0 -404
  108. package/dist/packem_shared/headers-Cp4uLtr4.js +0 -123
  109. package/dist/packem_shared/index-DnkF86LQ.js +0 -658
  110. package/dist/packem_shared/index-frijFf5m.js +0 -1252
  111. package/dist/packem_shared/pailMiddleware-Ci88geIF.js +0 -24
  112. package/dist/packem_shared/storage-D0vqz8OX.js +0 -36
  113. package/dist/packem_shared/useLogger-D0rU3lcX.js +0 -33
  114. package/dist/packem_shared/write-console-log-based-on-level-DBmRYXpj.js +0 -14
  115. package/dist/packem_shared/write-stream-BG8fhcs3.js +0 -6
  116. package/dist/pail.browser.d.ts +0 -412
  117. package/dist/pail.server.d.ts +0 -233
  118. package/dist/processor/caller/get-caller-filename.d.ts +0 -23
  119. package/dist/progress-bar.d.ts +0 -136
  120. package/dist/progress-bar.js +0 -404
  121. package/dist/reporter/file/utils/rotating-file-stream.d.ts +0 -48
  122. package/dist/reporter/http/utils/compression.d.ts +0 -7
  123. package/dist/reporter/http/utils/log-size-error.d.ts +0 -30
  124. package/dist/reporter/http/utils/retry.d.ts +0 -27
  125. package/dist/reporter/json/abstract-json-reporter.d.ts +0 -61
  126. package/dist/reporter/json/json-reporter.browser.d.ts +0 -40
  127. package/dist/reporter/json/json-reporter.server.d.ts +0 -50
  128. package/dist/reporter/pretty/abstract-pretty-reporter.d.ts +0 -83
  129. package/dist/reporter/pretty/pretty-reporter.browser.d.ts +0 -36
  130. package/dist/reporter/pretty/pretty-reporter.server.d.ts +0 -70
  131. package/dist/reporter/raw/raw-reporter.browser.d.ts +0 -5
  132. package/dist/reporter/raw/raw-reporter.server.d.ts +0 -13
  133. package/dist/reporter/utils/default-inspector-config.d.ts +0 -3
  134. package/dist/reporter/utils/format-label.d.ts +0 -3
  135. package/dist/spinner.d.ts +0 -220
  136. package/dist/spinner.js +0 -2183
  137. package/dist/types.d.ts +0 -241
  138. package/dist/utils/ansi-escapes.d.ts +0 -4
  139. package/dist/utils/arrayify.d.ts +0 -2
  140. package/dist/utils/get-longest-badge.d.ts +0 -4
  141. package/dist/utils/get-longest-label.d.ts +0 -4
  142. package/dist/utils/merge-types.d.ts +0 -4
  143. package/dist/utils/stream/safe-stream-handler.d.ts +0 -21
  144. package/dist/utils/write-console-log-based-on-level.d.ts +0 -4
  145. package/dist/utils/write-stream.d.ts +0 -2
@@ -1,733 +1,2 @@
1
- import { createRequire as __cjs_createRequire } from "node:module";
2
-
3
- const __cjs_require = __cjs_createRequire(import.meta.url);
4
-
5
- const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
-
7
- const __cjs_getBuiltinModule = (module) => {
8
- // Check if we're in Node.js and version supports getBuiltinModule
9
- if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
- const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
- // Node.js 20.16.0+ and 22.3.0+
12
- if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
- return __cjs_getProcess.getBuiltinModule(module);
14
- }
15
- }
16
- // Fallback to createRequire
17
- return __cjs_require(module);
18
- };
19
-
20
- const {
21
- Buffer
22
- } = __cjs_getBuiltinModule("node:buffer");
23
- const {
24
- gzipSync
25
- } = __cjs_getBuiltinModule("node:zlib");
26
-
27
- function isPlainObject(value) {
28
- if (typeof value !== "object" || value === null) {
29
- return false;
30
- }
31
- const prototype = Object.getPrototypeOf(value);
32
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
33
- }
34
-
35
- const ErrorProto = Object.create(
36
- {},
37
- {
38
- cause: {
39
- enumerable: false,
40
- value: void 0,
41
- writable: true
42
- },
43
- code: {
44
- enumerable: true,
45
- value: void 0,
46
- writable: true
47
- },
48
- errors: {
49
- enumerable: false,
50
- value: void 0,
51
- writable: true
52
- },
53
- message: {
54
- enumerable: false,
55
- value: void 0,
56
- writable: true
57
- },
58
- name: {
59
- enumerable: false,
60
- value: void 0,
61
- writable: true
62
- },
63
- stack: {
64
- enumerable: false,
65
- value: void 0,
66
- writable: true
67
- }
68
- }
69
- );
70
- const toJsonWasCalled = /* @__PURE__ */ new WeakSet();
71
- const makePropertiesEnumerable = (object) => {
72
- if (!object || typeof object !== "object") {
73
- return;
74
- }
75
- const props = Object.getOwnPropertyNames(object);
76
- for (const prop of props) {
77
- const descriptor = Object.getOwnPropertyDescriptor(object, prop);
78
- if (descriptor) {
79
- if (!descriptor.enumerable) {
80
- Object.defineProperty(object, prop, {
81
- ...descriptor,
82
- enumerable: true
83
- });
84
- }
85
- if (descriptor.value && typeof descriptor.value === "object" && !Array.isArray(descriptor.value) && (Object.getPrototypeOf(descriptor.value) === Object.prototype || Object.getPrototypeOf(descriptor.value) === null)) {
86
- makePropertiesEnumerable(descriptor.value);
87
- }
88
- }
89
- }
90
- };
91
- const toJSON = (from) => {
92
- toJsonWasCalled.add(from);
93
- const json = from.toJSON();
94
- toJsonWasCalled.delete(from);
95
- if (json && typeof json === "object" && Object.isExtensible(json)) {
96
- makePropertiesEnumerable(json);
97
- }
98
- return json;
99
- };
100
- const serializeValue = (value, seen, depth, options) => {
101
- if (value && value instanceof Uint8Array && value.constructor.name === "Buffer") {
102
- return "[object Buffer]";
103
- }
104
- if (value !== null && typeof value === "object" && typeof value.pipe === "function") {
105
- return "[object Stream]";
106
- }
107
- if (value instanceof Error) {
108
- if (seen.has(value)) {
109
- return "[Circular]";
110
- }
111
- depth += 1;
112
- return _serialize(value, options, seen, depth);
113
- }
114
- if (options.useToJSON && typeof value.toJSON === "function") {
115
- return value.toJSON();
116
- }
117
- if (typeof value === "object" && value instanceof Date) {
118
- return value.toISOString();
119
- }
120
- if (typeof value === "function") {
121
- return `[Function: ${value.name || "anonymous"}]`;
122
- }
123
- if (typeof value === "bigint") {
124
- return `${value}n`;
125
- }
126
- if (isPlainObject(value)) {
127
- if (options.maxDepth !== void 0 && options.maxDepth !== Number.POSITIVE_INFINITY && depth + 1 >= options.maxDepth) {
128
- return {};
129
- }
130
- depth += 1;
131
- const plainObject = {};
132
- for (const key in value) {
133
- plainObject[key] = serializeValue(value[key], seen, depth, options);
134
- }
135
- return plainObject;
136
- }
137
- try {
138
- return value;
139
- } catch {
140
- return "[Not Available]";
141
- }
142
- };
143
- const _serialize = (error, options, seen, depth) => {
144
- seen.add(error);
145
- if (options.maxDepth === 0) {
146
- return {};
147
- }
148
- if (options.useToJSON && typeof error.toJSON === "function" && !toJsonWasCalled.has(error)) {
149
- return toJSON(error);
150
- }
151
- const protoError = Object.create(ErrorProto);
152
- Object.defineProperty(protoError, "name", {
153
- configurable: true,
154
- enumerable: true,
155
- value: Object.prototype.toString.call(error.constructor) === "[object Function]" ? error.constructor.name : error.name,
156
- writable: true
157
- });
158
- Object.defineProperty(protoError, "message", {
159
- configurable: true,
160
- enumerable: true,
161
- value: error.message,
162
- writable: true
163
- });
164
- Object.defineProperty(protoError, "stack", {
165
- configurable: true,
166
- enumerable: true,
167
- value: error.stack,
168
- writable: true
169
- });
170
- if (Array.isArray(error.errors)) {
171
- const aggregateErrors = [];
172
- for (const aggregateError of error.errors) {
173
- if (!(aggregateError instanceof Error)) {
174
- throw new TypeError("All errors in the 'errors' property must be instances of Error");
175
- }
176
- if (seen.has(aggregateError)) {
177
- Object.defineProperty(protoError, "errors", {
178
- configurable: true,
179
- enumerable: true,
180
- value: [],
181
- writable: true
182
- });
183
- return protoError;
184
- }
185
- aggregateErrors.push(_serialize(aggregateError, options, seen, depth));
186
- }
187
- Object.defineProperty(protoError, "errors", {
188
- configurable: true,
189
- enumerable: true,
190
- value: aggregateErrors,
191
- writable: true
192
- });
193
- }
194
- if (error.cause !== void 0 && error.cause !== null) {
195
- if (error.cause instanceof Error) {
196
- if (seen.has(error.cause)) {
197
- Object.defineProperty(protoError, "cause", {
198
- configurable: true,
199
- enumerable: true,
200
- value: "[Circular]",
201
- writable: true
202
- });
203
- } else {
204
- Object.defineProperty(protoError, "cause", {
205
- configurable: true,
206
- enumerable: true,
207
- value: _serialize(error.cause, options, seen, depth),
208
- writable: true
209
- });
210
- }
211
- } else {
212
- const serializedCause = serializeValue(error.cause, seen, depth, options);
213
- Object.defineProperty(protoError, "cause", {
214
- configurable: true,
215
- enumerable: true,
216
- value: serializedCause,
217
- writable: true
218
- });
219
- }
220
- }
221
- for (const key in error) {
222
- if (key === "name" || key === "message" || key === "stack" || key === "cause" || key === "errors") {
223
- continue;
224
- }
225
- const value = error[key];
226
- const serializedValue = serializeValue(value, seen, depth, options);
227
- Object.defineProperty(protoError, key, {
228
- configurable: true,
229
- enumerable: true,
230
- value: serializedValue,
231
- writable: true
232
- });
233
- }
234
- if (Array.isArray(options.exclude) && options.exclude.length > 0) {
235
- for (const key of options.exclude) {
236
- try {
237
- delete protoError[key];
238
- } catch {
239
- }
240
- }
241
- }
242
- return protoError;
243
- };
244
- const serialize = (error, options = {}) => _serialize(
245
- error,
246
- {
247
- exclude: options.exclude ?? [],
248
- maxDepth: options.maxDepth ?? Number.POSITIVE_INFINITY,
249
- useToJSON: options.useToJSON ?? false
250
- },
251
- /* @__PURE__ */ new Set(),
252
- 0
253
- );
254
-
255
- const EMPTY_SYMBOL = /* @__PURE__ */ Symbol("EMPTY");
256
-
257
- class AbstractJsonReporter {
258
- /** Custom stringify function for object serialization */
259
- stringify;
260
- /** Error serialization options */
261
- errorOptions;
262
- /**
263
- * Creates a new AbstractJsonReporter instance.
264
- * @param options Configuration options for JSON formatting and error handling
265
- */
266
- constructor(options = {}) {
267
- this.errorOptions = options.error ?? {};
268
- }
269
- /**
270
- * Sets a custom stringify function for object serialization.
271
- * @param function_ The stringify function to use for serialization
272
- */
273
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
274
- setStringify(function_) {
275
- this.stringify = function_;
276
- }
277
- // eslint-disable-next-line sonarjs/cognitive-complexity
278
- log(meta) {
279
- const { context, error, file, message, type, ...rest } = meta;
280
- if (rest.label) {
281
- rest.label = rest.label.trim();
282
- }
283
- if (file) {
284
- rest.file = `${file.name}:${file.line}${file.column ? `:${file.column}` : ""}`;
285
- }
286
- if (message === EMPTY_SYMBOL) {
287
- rest.message = void 0;
288
- } else {
289
- rest.message = message;
290
- }
291
- if (error) {
292
- rest.error = serialize(error, this.errorOptions);
293
- }
294
- if (context) {
295
- const newContext = [];
296
- for (const item of context) {
297
- if (item === EMPTY_SYMBOL) {
298
- continue;
299
- }
300
- if (item instanceof Error) {
301
- newContext.push(serialize(item, this.errorOptions));
302
- } else {
303
- newContext.push(item);
304
- }
305
- }
306
- rest.context = newContext;
307
- }
308
- this._log(this.stringify(rest), type.level);
309
- }
310
- }
311
-
312
- const compressData = async (data) => {
313
- const CompressionStreamClass = globalThis.CompressionStream;
314
- if (CompressionStreamClass) {
315
- const stream = new CompressionStreamClass("gzip");
316
- const writer = stream.writable.getWriter();
317
- const reader = stream.readable.getReader();
318
- const encoder = new TextEncoder();
319
- const chunks = [];
320
- writer.write(encoder.encode(data));
321
- writer.close();
322
- let done = false;
323
- while (!done) {
324
- const result2 = await reader.read();
325
- done = result2.done ?? false;
326
- if (result2.value) {
327
- chunks.push(result2.value);
328
- }
329
- }
330
- const totalLength = chunks.reduce((accumulator, chunk) => accumulator + chunk.length, 0);
331
- const result = new Uint8Array(totalLength);
332
- let offset = 0;
333
- for (const chunk of chunks) {
334
- result.set(chunk, offset);
335
- offset += chunk.length;
336
- }
337
- return result;
338
- }
339
- return gzipSync(data);
340
- };
341
-
342
- class LogSizeError extends Error {
343
- /**
344
- * The log entry data that caused the error
345
- */
346
- logData;
347
- /**
348
- * The actual size of the log entry in bytes
349
- */
350
- actualSize;
351
- /**
352
- * The maximum allowed size in bytes
353
- */
354
- maxSize;
355
- /**
356
- * Creates a new LogSizeError instance.
357
- * @param message Descriptive error message explaining the size violation
358
- * @param logData The log entry data that caused the error
359
- * @param actualSize Size of the log entry in bytes
360
- * @param maxSize Maximum allowed size in bytes
361
- * @example
362
- * ```typescript
363
- * throw new LogSizeError("Log too large", logData, 2000000, 1000000);
364
- * ```
365
- */
366
- constructor(message, logData, actualSize, maxSize) {
367
- super(message);
368
- this.name = "LogSizeError";
369
- this.logData = logData;
370
- this.actualSize = actualSize;
371
- this.maxSize = maxSize;
372
- }
373
- }
374
-
375
- const calculateBackoffDelay = (baseDelay, attempt) => baseDelay * 2 ** attempt;
376
- const sleep = (delay) => new Promise((resolve) => {
377
- setTimeout(resolve, delay);
378
- });
379
- const prepareRequestBody = (body) => {
380
- if (typeof body === "string") {
381
- return body;
382
- }
383
- return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
384
- };
385
- const processResponse = async (response, url, method, headers, body, onDebugRequestResponse, onError) => {
386
- const responseHeaders = {};
387
- response.headers.forEach((value, key) => {
388
- responseHeaders[key] = value;
389
- });
390
- const responseBody = await response.text();
391
- const requestResponse = {
392
- req: {
393
- body,
394
- headers,
395
- method,
396
- url
397
- },
398
- res: {
399
- body: responseBody,
400
- headers: responseHeaders,
401
- status: response.status,
402
- statusText: response.statusText
403
- }
404
- };
405
- if (onDebugRequestResponse) {
406
- onDebugRequestResponse(requestResponse);
407
- }
408
- if (response.ok) {
409
- return false;
410
- }
411
- if (response.status < 500 && response.status !== 429) {
412
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
413
- if (onError) {
414
- onError(error);
415
- }
416
- throw error;
417
- }
418
- return true;
419
- };
420
- const handleRateLimit = (response, respectRateLimit, retryDelay, attempt, maxRetries) => {
421
- if (response.status === 429 && respectRateLimit && attempt < maxRetries) {
422
- const retryAfter = response.headers.get("retry-after");
423
- return retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : calculateBackoffDelay(retryDelay, attempt);
424
- }
425
- return void 0;
426
- };
427
- const handleServerError = (response, retryDelay, attempt, maxRetries) => {
428
- if (response.status >= 500 && attempt < maxRetries) {
429
- return calculateBackoffDelay(retryDelay, attempt);
430
- }
431
- return void 0;
432
- };
433
- const calculateRetryDelay = (response, respectRateLimit, retryDelay, attempt, maxRetries) => {
434
- const rateLimitDelay = handleRateLimit(response, respectRateLimit, retryDelay, attempt, maxRetries);
435
- if (rateLimitDelay !== void 0) {
436
- return rateLimitDelay;
437
- }
438
- return handleServerError(response, retryDelay, attempt, maxRetries);
439
- };
440
- const handleRetryError = async (error, attempt, maxRetries, retryDelay, onError) => {
441
- if (attempt < maxRetries) {
442
- const delay = calculateBackoffDelay(retryDelay, attempt);
443
- await sleep(delay);
444
- return true;
445
- }
446
- if (onError) {
447
- onError(error);
448
- }
449
- return false;
450
- };
451
- const sendWithRetry = async (url, method, headers, body, maxRetries, retryDelay, respectRateLimit, onDebugRequestResponse, onError) => {
452
- let attempt = 0;
453
- while (attempt <= maxRetries) {
454
- try {
455
- const requestBody = prepareRequestBody(body);
456
- const response = await fetch(url, {
457
- body: requestBody,
458
- headers,
459
- method
460
- });
461
- const shouldRetry = await processResponse(response, url, method, headers, body, onDebugRequestResponse, onError);
462
- if (!shouldRetry) {
463
- return;
464
- }
465
- const retryDelayValue = calculateRetryDelay(response, respectRateLimit, retryDelay, attempt, maxRetries);
466
- if (retryDelayValue !== void 0) {
467
- await sleep(retryDelayValue);
468
- attempt += 1;
469
- continue;
470
- }
471
- if (!response.ok) {
472
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
473
- if (onError) {
474
- onError(error);
475
- }
476
- throw error;
477
- }
478
- return;
479
- } catch (error) {
480
- const shouldRetry = await handleRetryError(error, attempt, maxRetries, retryDelay, onError);
481
- if (shouldRetry) {
482
- attempt += 1;
483
- continue;
484
- }
485
- throw error;
486
- }
487
- }
488
- };
489
-
490
- class AbstractHttpReporter extends AbstractJsonReporter {
491
- url;
492
- method;
493
- headers;
494
- contentType;
495
- batchContentType;
496
- onError;
497
- onDebug;
498
- onDebugRequestResponse;
499
- payloadTemplate;
500
- compression;
501
- maxRetries;
502
- retryDelay;
503
- respectRateLimit;
504
- enableBatchSend;
505
- batchSize;
506
- batchSendTimeout;
507
- batchSendDelimiter;
508
- batchMode;
509
- batchFieldName;
510
- maxLogSize;
511
- maxPayloadSize;
512
- edgeCompat;
513
- // Batch management
514
- batchQueue = [];
515
- batchTimeout;
516
- isProcessingBatch = false;
517
- currentBatchSize = 0;
518
- // Track uncompressed size of current batch
519
- /**
520
- * Creates a new instance of AbstractHttpReporter.
521
- * @param config Configuration options for the reporter
522
- */
523
- constructor(config) {
524
- super(config);
525
- this.url = config.url;
526
- this.method = config.method ?? "POST";
527
- this.headers = config.headers ?? {};
528
- this.contentType = config.contentType ?? "application/json";
529
- this.batchContentType = config.batchContentType ?? "application/json";
530
- this.onError = config.onError;
531
- this.onDebug = config.onDebug;
532
- this.onDebugRequestResponse = config.onDebugRequestResponse;
533
- this.payloadTemplate = config.payloadTemplate ?? ((data) => JSON.stringify(data));
534
- this.compression = config.compression ?? false;
535
- this.maxRetries = config.maxRetries ?? 3;
536
- this.retryDelay = config.retryDelay ?? 1e3;
537
- this.respectRateLimit = config.respectRateLimit ?? true;
538
- this.enableBatchSend = config.enableBatchSend ?? true;
539
- this.batchSize = config.batchSize ?? 100;
540
- this.batchSendTimeout = config.batchSendTimeout ?? 5e3;
541
- this.batchSendDelimiter = config.batchSendDelimiter ?? "\n";
542
- this.batchMode = config.batchMode ?? "delimiter";
543
- this.batchFieldName = config.batchFieldName;
544
- if (this.batchMode === "field" && !this.batchFieldName) {
545
- throw new Error("batchFieldName is required when batchMode is 'field'");
546
- }
547
- this.maxLogSize = config.maxLogSize ?? 1048576;
548
- this.maxPayloadSize = config.maxPayloadSize ?? 5242880;
549
- this.edgeCompat = config.edgeCompat ?? false;
550
- }
551
- /**
552
- * Processes and ships log entries to the HTTP endpoint.
553
- * @param message The JSON-formatted log message
554
- * @param logLevel The log level of the message
555
- * @protected
556
- */
557
- // eslint-disable-next-line no-underscore-dangle
558
- _log(message, logLevel) {
559
- try {
560
- const logData = JSON.parse(message);
561
- const logLevelString = logLevel;
562
- const messageString = logData.message;
563
- const payloadTemplate = {
564
- logLevel: logLevelString,
565
- message: messageString ?? ""
566
- };
567
- if (logData.data) {
568
- payloadTemplate["data"] = logData.data;
569
- } else if (logData.context) {
570
- payloadTemplate["data"] = logData.context;
571
- } else {
572
- const rest = { ...logData };
573
- delete rest.message;
574
- if (Object.keys(rest).length > 0) {
575
- payloadTemplate["data"] = rest;
576
- }
577
- }
578
- const payload = this.payloadTemplate(payloadTemplate);
579
- if (this.onDebug) {
580
- this.onDebug({ data: payloadTemplate.data, logLevel: logLevelString, message: messageString });
581
- }
582
- const logEntrySize = this.edgeCompat || typeof TextEncoder === "undefined" ? Buffer.byteLength(payload, "utf8") : new TextEncoder().encode(payload).length;
583
- if (logEntrySize > this.maxLogSize) {
584
- const error = new LogSizeError(
585
- `Log entry exceeds maximum size of ${this.maxLogSize} bytes. Size: ${logEntrySize} bytes`,
586
- { data: payloadTemplate.data, logLevel: logLevelString, message: messageString },
587
- logEntrySize,
588
- this.maxLogSize
589
- );
590
- if (this.onError) {
591
- this.onError(error);
592
- }
593
- return;
594
- }
595
- if (this.enableBatchSend) {
596
- this.addToBatch(payload, logEntrySize);
597
- } else {
598
- this.sendPayload(payload).catch((error) => {
599
- if (this.onError) {
600
- this.onError(error);
601
- }
602
- });
603
- }
604
- } catch (error) {
605
- if (this.onError) {
606
- this.onError(error);
607
- }
608
- }
609
- }
610
- /**
611
- * Adds a payload to the batch queue and triggers sending if conditions are met.
612
- */
613
- addToBatch(payload, logEntrySize) {
614
- const payloadSizeWithEntry = this.currentBatchSize + logEntrySize + this.batchSendDelimiter.length;
615
- const payloadSizeThreshold = this.maxPayloadSize * 0.9;
616
- if (payloadSizeWithEntry > payloadSizeThreshold && this.batchQueue.length > 0) {
617
- this.processBatch();
618
- }
619
- this.batchQueue.push(payload);
620
- this.currentBatchSize += logEntrySize + this.batchSendDelimiter.length;
621
- if (!this.batchTimeout) {
622
- this.batchTimeout = setTimeout(() => {
623
- this.processBatch();
624
- }, this.batchSendTimeout);
625
- }
626
- if (this.batchQueue.length >= this.batchSize) {
627
- this.processBatch();
628
- }
629
- }
630
- /**
631
- * Processes the current batch and sends it to the HTTP endpoint.
632
- */
633
- async processBatch() {
634
- if (this.isProcessingBatch || this.batchQueue.length === 0) {
635
- return;
636
- }
637
- this.isProcessingBatch = true;
638
- if (this.batchTimeout) {
639
- clearTimeout(this.batchTimeout);
640
- this.batchTimeout = void 0;
641
- }
642
- const batch = this.batchQueue.splice(0, this.batchSize);
643
- this.currentBatchSize = 0;
644
- for (let i = 0; i < this.batchQueue.length; i += 1) {
645
- const payload = this.batchQueue[i];
646
- const payloadSize = this.edgeCompat || typeof TextEncoder === "undefined" ? Buffer.byteLength(payload, "utf8") : new TextEncoder().encode(payload).length;
647
- this.currentBatchSize += payloadSize + (i < this.batchQueue.length - 1 ? this.batchSendDelimiter.length : 0);
648
- }
649
- try {
650
- await this.sendBatch(batch);
651
- } catch (error) {
652
- if (this.onError) {
653
- this.onError(error);
654
- }
655
- } finally {
656
- this.isProcessingBatch = false;
657
- if (this.batchQueue.length > 0) {
658
- this.processBatch();
659
- }
660
- }
661
- }
662
- /**
663
- * Sends a batch of payloads to the HTTP endpoint.
664
- */
665
- async sendBatch(batch) {
666
- let batchPayload;
667
- switch (this.batchMode) {
668
- case "array": {
669
- const batchEntries = batch.map((payload) => JSON.parse(payload));
670
- batchPayload = JSON.stringify(batchEntries);
671
- break;
672
- }
673
- case "field": {
674
- const fieldEntries = batch.map((payload) => JSON.parse(payload));
675
- const batchObject = this.batchFieldName ? { [this.batchFieldName]: fieldEntries } : {};
676
- batchPayload = JSON.stringify(batchObject);
677
- break;
678
- }
679
- default: {
680
- batchPayload = batch.join(this.batchSendDelimiter);
681
- break;
682
- }
683
- }
684
- await this.sendPayload(batchPayload, this.batchContentType);
685
- }
686
- /**
687
- * Sends a single payload to the HTTP endpoint.
688
- */
689
- async sendPayload(payload, contentType) {
690
- const headers = typeof this.headers === "function" ? this.headers() : { ...this.headers };
691
- if (!headers["content-type"]) {
692
- headers["content-type"] = contentType ?? this.contentType;
693
- }
694
- let finalPayload = payload;
695
- if (this.compression && !this.edgeCompat) {
696
- try {
697
- finalPayload = await compressData(payload);
698
- headers["content-encoding"] = "gzip";
699
- } catch (error) {
700
- if (this.onError) {
701
- this.onError(new Error(`Compression failed: ${error}`));
702
- }
703
- }
704
- }
705
- await sendWithRetry(
706
- this.url,
707
- this.method,
708
- headers,
709
- finalPayload,
710
- this.maxRetries,
711
- this.retryDelay,
712
- this.respectRateLimit,
713
- this.onDebugRequestResponse,
714
- this.onError
715
- );
716
- }
717
- }
718
-
719
- class HttpReporterEdgeLight extends AbstractHttpReporter {
720
- /**
721
- * Creates a new HTTP Reporter Edge Light instance.
722
- * Edge compatibility mode is automatically enabled.
723
- * @param options Configuration options for HTTP reporting
724
- */
725
- constructor(options) {
726
- super({
727
- ...options,
728
- edgeCompat: true
729
- });
730
- }
731
- }
732
-
733
- export { HttpReporterEdgeLight as default };
1
+ import{createRequire as N}from"node:module";const z=N(import.meta.url),d=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,S=t=>{if(typeof d<"u"&&d.versions&&d.versions.node){const[e,r]=d.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return d.getBuiltinModule(t)}return z(t)},{Buffer:E}=S("node:buffer"),{createRequire:P}=S("node:module"),{gzipSync:B}=S("node:zlib"),R=P(import.meta.url),p=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,_=t=>{if(typeof p<"u"&&p.versions&&p.versions.node){const[e,r]=p.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return p.getBuiltinModule(t)}return R(t)};_("node:util");const L=P(import.meta.url),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,T=t=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[e,r]=m.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return m.getBuiltinModule(t)}return L(t)};T("node:fs");T("node:path");T("node:url");const M=new Map([["Error",Error],["EvalError",EvalError],["RangeError",RangeError],["ReferenceError",ReferenceError],["SyntaxError",SyntaxError],["TypeError",TypeError],["URIError",URIError]]);typeof AggregateError<"u"&&M.set("AggregateError",AggregateError);const $=Object.create({},{cause:{enumerable:!1,value:void 0,writable:!0},code:{enumerable:!0,value:void 0,writable:!0},errors:{enumerable:!1,value:void 0,writable:!0},message:{enumerable:!1,value:void 0,writable:!0},name:{enumerable:!1,value:void 0,writable:!0},stack:{enumerable:!1,value:void 0,writable:!0}}),Q=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null},y=new WeakSet,j=t=>{const e=Object.getOwnPropertyNames(t);for(const r of e){const s=Object.getOwnPropertyDescriptor(t,r);s&&(s.enumerable||Object.defineProperty(t,r,{...s,enumerable:!0}),s.value&&typeof s.value=="object"&&!Array.isArray(s.value)&&(Object.getPrototypeOf(s.value)===Object.prototype||Object.getPrototypeOf(s.value)===null)&&j(s.value))}},A=t=>{y.add(t);const e=t.toJSON();return y.delete(t),Object.isExtensible(e)&&j(e),e},b=(t,e,r,s,o=new Set)=>{if(t&&t instanceof Uint8Array&&t.constructor.name==="Buffer")return"[object Buffer]";if(t!==null&&typeof t=="object"&&"pipe"in t&&typeof t.pipe=="function")return"[object Stream]";if(t instanceof Error)return e.has(t)?"[Circular]":(r+=1,g(t,s,e,r));if(s.useToJSON&&t!==null&&typeof t=="object"&&"toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(typeof URL<"u"&&t instanceof URL)return t.href;if(t instanceof Map){const i=[];for(const[a,n]of t.entries())i.push([b(a,e,r,s,o),b(n,e,r,s,o)]);return{__dataType:"Map",value:i}}if(t instanceof Set){const i=[];for(const a of t.values())i.push(b(a,e,r,s,o));return{__dataType:"Set",value:i}}if(typeof t=="function")return`[Function: ${t.name||"anonymous"}]`;if(typeof t=="bigint")return`${String(t)}n`;if(Q(t)){if(o.has(t))return"[Circular]";if(s.maxDepth!==void 0&&s.maxDepth!==Number.POSITIVE_INFINITY&&r+1>=s.maxDepth)return{};r+=1,o.add(t);const i={};for(const a in t)i[a]=b(t[a],e,r,s,o);return o.delete(t),i}try{return t}catch{return"[Not Available]"}},g=(t,e,r,s)=>{if(r.add(t),e.maxDepth===0)return{};if(e.useToJSON&&typeof t.toJSON=="function"&&!y.has(t))return A(t);const o=Object.create($);if(Object.defineProperty(o,"name",{configurable:!0,enumerable:!0,value:Object.prototype.toString.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,writable:!0}),Object.defineProperty(o,"message",{configurable:!0,enumerable:!0,value:t.message,writable:!0}),Object.defineProperty(o,"stack",{configurable:!0,enumerable:!0,value:t.stack,writable:!0}),Array.isArray(t.errors)){const a=[];for(const n of t.errors){if(!(n instanceof Error))throw new TypeError("All errors in the 'errors' property must be instances of Error");if(r.has(n))return Object.defineProperty(o,"errors",{configurable:!0,enumerable:!0,value:[],writable:!0}),o;a.push(g(n,e,r,s))}Object.defineProperty(o,"errors",{configurable:!0,enumerable:!0,value:a,writable:!0})}const i=t.cause;if(i!=null)if(i instanceof Error)r.has(i)?Object.defineProperty(o,"cause",{configurable:!0,enumerable:!0,value:"[Circular]",writable:!0}):Object.defineProperty(o,"cause",{configurable:!0,enumerable:!0,value:g(i,e,r,s),writable:!0});else{const a=b(i,r,s,e);Object.defineProperty(o,"cause",{configurable:!0,enumerable:!0,value:a,writable:!0})}for(const a in t){if(a==="name"||a==="message"||a==="stack"||a==="cause"||a==="errors")continue;const n=t[a],u=b(n,r,s,e);Object.defineProperty(o,a,{configurable:!0,enumerable:!0,value:u,writable:!0})}if(Array.isArray(e.exclude)&&e.exclude.length>0)for(const a of e.exclude)try{delete o[a]}catch{}return o},v=(t,e={})=>g(t,{exclude:e.exclude??[],maxDepth:e.maxDepth??Number.POSITIVE_INFINITY,useToJSON:e.useToJSON??!1},new Set,0),O=Symbol("EMPTY");class C{stringify;errorOptions;constructor(e={}){this.errorOptions=e.error??{}}setStringify(e){this.stringify=e}log(e){const{context:r,error:s,file:o,message:i,type:a,...n}=e;if(n.label&&(n.label=n.label.trim()),o&&(n.file=`${o.name??""}:${String(o.line)}${o.column?`:${String(o.column)}`:""}`),n.message=i===O?void 0:i,s&&(n.error=v(s,this.errorOptions)),r){const u=[];for(let c=0;c<r.length;c+=1){const h=r[c];h!==O&&(h instanceof Error?u.push(v(h,this.errorOptions)):u.push(h))}n.context=u}this._log(this.stringify(n),a.level)}}const J=async t=>{const e=globalThis.CompressionStream;if(e){const r=new e("gzip"),s=r.writable.getWriter(),o=r.readable.getReader(),i=new TextEncoder,a=[];await s.write(i.encode(t)),await s.close();let n=!1;for(;!n;){const l=await o.read();n=l.done,l.value&&a.push(l.value)}const u=a.reduce((l,f)=>l+f.length,0),c=new Uint8Array(u);let h=0;for(let l=0;l<a.length;l+=1){const f=a[l];c.set(f,h),h+=f.length}return c}return B(t)};class I extends Error{logData;actualSize;maxSize;constructor(e,r,s,o){super(e),this.name="LogSizeError",this.logData=r,this.actualSize=s,this.maxSize=o}}const w=(t,e)=>t*2**e,k=/^\d+$/,F=t=>{const e=t.trim();if(k.test(e)){const o=Number.parseInt(e,10);return Math.min(Math.max(o,0)*1e3,6e4)}const r=Date.parse(e);if(Number.isNaN(r))return;const s=r-Date.now();return Math.min(Math.max(s,0),6e4)},D=t=>new Promise(e=>{setTimeout(e,t)}),q=t=>typeof t=="string"?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),U=async(t,e,r,s,o,i,a)=>{const n={};t.headers.forEach((h,l)=>{n[l]=h});const u=await t.text(),c={req:{body:o,headers:s,method:r,url:e},res:{body:u,headers:n,status:t.status,statusText:t.statusText}};if(i&&i(c),t.ok)return!1;if(t.status<500&&t.status!==429){const h=new Error(`HTTP ${String(t.status)}: ${t.statusText}`);throw a&&a(h),h}return!0},Y=(t,e,r,s,o)=>{if(t.status===429&&e&&s<o){const i=t.headers.get("retry-after");return(i?F(i):void 0)??w(r,s)}},H=(t,e,r,s)=>{if(t.status>=500&&r<s)return w(e,r)},V=(t,e,r,s,o)=>{const i=Y(t,e,r,s,o);return i!==void 0?i:H(t,r,s,o)},W=async(t,e,r,s,o)=>{if(e<r){const i=w(s,e);return await D(i),!0}return o&&o(t),!1},G=async(t,e,r,s,o,i,a,n,u)=>{let c=0;for(;c<=o;)try{const h=q(s),l=await fetch(t,{body:h,headers:r,method:e});if(!await U(l,t,e,r,s,n,u))return;const f=V(l,a,i,c,o);if(f!==void 0){await D(f),c+=1;continue}if(!l.ok){const x=new Error(`HTTP ${String(l.status)}: ${l.statusText}`);throw u&&u(x),x}return}catch(h){if(await W(h,c,o,i,u)){c+=1;continue}throw h}};class K extends C{url;method;headers;contentType;batchContentType;onError;onDrop;maxQueueSize;onDebug;onDebugRequestResponse;payloadTemplate;compression;maxRetries;retryDelay;respectRateLimit;enableBatchSend;batchSize;batchSendTimeout;batchSendDelimiter;batchMode;batchFieldName;maxLogSize;maxPayloadSize;edgeCompat;batchQueue=[];batchTimeout;isProcessingBatch=!1;currentBatchSize=0;constructor(e){if(super(e),this.url=e.url,this.method=e.method??"POST",this.headers=e.headers??{},this.contentType=e.contentType??"application/json",this.batchContentType=e.batchContentType??"application/json",this.onError=e.onError,this.onDrop=e.onDrop,this.maxQueueSize=e.maxQueueSize??1e4,this.onDebug=e.onDebug,this.onDebugRequestResponse=e.onDebugRequestResponse,this.payloadTemplate=e.payloadTemplate??(r=>JSON.stringify(r)),this.compression=e.compression??!1,this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.respectRateLimit=e.respectRateLimit??!0,this.enableBatchSend=e.enableBatchSend??!0,this.batchSize=e.batchSize??100,this.batchSendTimeout=e.batchSendTimeout??5e3,this.batchSendDelimiter=e.batchSendDelimiter??`
2
+ `,this.batchMode=e.batchMode??"delimiter",this.batchFieldName=e.batchFieldName,this.batchMode==="field"&&!this.batchFieldName)throw new Error("batchFieldName is required when batchMode is 'field'");this.maxLogSize=e.maxLogSize??1048576,this.maxPayloadSize=e.maxPayloadSize??5242880,this.edgeCompat=e.edgeCompat??!1}async flush(){for(this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0);this.batchQueue.length>0||this.isProcessingBatch;){if(this.isProcessingBatch){await new Promise(e=>setTimeout(e,0));continue}await this.processBatch()}}async close(){await this.flush()}async dispose(){await this.close()}_log(e,r){try{const s=JSON.parse(e),o=r,i=s.message,a={logLevel:o,message:i??""};if(s.data)a.data=s.data;else if(s.context)a.data=s.context;else{const c={...s};delete c.message,Object.keys(c).length>0&&(a.data=c)}const n=this.payloadTemplate(a);this.onDebug&&this.onDebug({data:a.data,logLevel:o,message:i});const u=this.edgeCompat||typeof TextEncoder>"u"?E.byteLength(n,"utf8"):new TextEncoder().encode(n).length;if(u>this.maxLogSize){const c=new I(`Log entry exceeds maximum size of ${String(this.maxLogSize)} bytes. Size: ${String(u)} bytes`,{data:a.data,logLevel:o,message:i},u,this.maxLogSize);this.onError&&this.onError(c);return}this.enableBatchSend?this.addToBatch(n,u):this.sendPayload(n).catch(c=>{this.onError&&this.onError(c)})}catch(s){this.onError&&this.onError(s)}}addToBatch(e,r){const s=this.currentBatchSize+r+this.batchSendDelimiter.length,o=this.maxPayloadSize*.9;if(s>o&&this.batchQueue.length>0&&this.processBatch(),this.batchQueue.push(e),this.currentBatchSize+=r+this.batchSendDelimiter.length,this.batchQueue.length>this.maxQueueSize){const i=this.batchQueue.splice(0,this.batchQueue.length-this.maxQueueSize);this.currentBatchSize=this.#e(),this.onDrop&&this.onDrop(i.length)}this.batchTimeout??=setTimeout(()=>{this.processBatch()},this.batchSendTimeout),this.batchQueue.length>=this.batchSize&&this.processBatch()}#e(){let e=0;for(let r=0;r<this.batchQueue.length;r+=1){const s=this.batchQueue[r],o=this.edgeCompat||typeof TextEncoder>"u"?E.byteLength(s,"utf8"):new TextEncoder().encode(s).length;e+=o+(r<this.batchQueue.length-1?this.batchSendDelimiter.length:0)}return e}async processBatch(){if(this.isProcessingBatch||this.batchQueue.length===0)return;this.isProcessingBatch=!0,this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0);const e=this.batchQueue.splice(0,this.batchSize);this.currentBatchSize=this.#e();try{await this.sendBatch(e)}catch(r){this.onError&&this.onError(r)}finally{this.isProcessingBatch=!1,this.batchQueue.length>0&&this.processBatch()}}async sendBatch(e){let r;switch(this.batchMode){case"array":{const s=e.map(o=>JSON.parse(o));r=JSON.stringify(s);break}case"field":{const s=e.map(i=>JSON.parse(i)),o=this.batchFieldName?{[this.batchFieldName]:s}:{};r=JSON.stringify(o);break}default:{r=e.join(this.batchSendDelimiter);break}}await this.sendPayload(r,this.batchContentType)}async sendPayload(e,r){const s=typeof this.headers=="function"?this.headers():{...this.headers};s["content-type"]??=r??this.contentType;let o=e;if(this.compression&&!this.edgeCompat)try{o=await J(e),s["content-encoding"]="gzip"}catch(i){this.onError&&this.onError(new Error(`Compression failed: ${String(i)}`))}await G(this.url,this.method,s,o,this.maxRetries,this.retryDelay,this.respectRateLimit,this.onDebugRequestResponse,this.onError)}}class Z extends K{constructor(e){super({...e,edgeCompat:!0})}}export{Z as default};