@visulima/pail 4.0.0-alpha.12 → 4.0.0-alpha.14

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