@visulima/pail 4.0.0-alpha.9 → 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 +511 -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 +22 -37
  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,435 +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
- import { AbstractJsonReporter } from '../../packem_shared/AbstractJsonReporter-CGKHS8_M.js';
24
- const {
25
- gzipSync
26
- } = __cjs_getBuiltinModule("node:zlib");
27
-
28
- const compressData = async (data) => {
29
- const CompressionStreamClass = globalThis.CompressionStream;
30
- if (CompressionStreamClass) {
31
- const stream = new CompressionStreamClass("gzip");
32
- const writer = stream.writable.getWriter();
33
- const reader = stream.readable.getReader();
34
- const encoder = new TextEncoder();
35
- const chunks = [];
36
- writer.write(encoder.encode(data));
37
- writer.close();
38
- let done = false;
39
- while (!done) {
40
- const result2 = await reader.read();
41
- done = result2.done ?? false;
42
- if (result2.value) {
43
- chunks.push(result2.value);
44
- }
45
- }
46
- const totalLength = chunks.reduce((accumulator, chunk) => accumulator + chunk.length, 0);
47
- const result = new Uint8Array(totalLength);
48
- let offset = 0;
49
- for (const chunk of chunks) {
50
- result.set(chunk, offset);
51
- offset += chunk.length;
52
- }
53
- return result;
54
- }
55
- return gzipSync(data);
56
- };
57
-
58
- class LogSizeError extends Error {
59
- /**
60
- * The log entry data that caused the error
61
- */
62
- logData;
63
- /**
64
- * The actual size of the log entry in bytes
65
- */
66
- actualSize;
67
- /**
68
- * The maximum allowed size in bytes
69
- */
70
- maxSize;
71
- /**
72
- * Creates a new LogSizeError instance.
73
- * @param message Descriptive error message explaining the size violation
74
- * @param logData The log entry data that caused the error
75
- * @param actualSize Size of the log entry in bytes
76
- * @param maxSize Maximum allowed size in bytes
77
- * @example
78
- * ```typescript
79
- * throw new LogSizeError("Log too large", logData, 2000000, 1000000);
80
- * ```
81
- */
82
- constructor(message, logData, actualSize, maxSize) {
83
- super(message);
84
- this.name = "LogSizeError";
85
- this.logData = logData;
86
- this.actualSize = actualSize;
87
- this.maxSize = maxSize;
88
- }
89
- }
90
-
91
- const calculateBackoffDelay = (baseDelay, attempt) => baseDelay * 2 ** attempt;
92
- const sleep = (delay) => new Promise((resolve) => {
93
- setTimeout(resolve, delay);
94
- });
95
- const prepareRequestBody = (body) => {
96
- if (typeof body === "string") {
97
- return body;
98
- }
99
- return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
100
- };
101
- const processResponse = async (response, url, method, headers, body, onDebugRequestResponse, onError) => {
102
- const responseHeaders = {};
103
- response.headers.forEach((value, key) => {
104
- responseHeaders[key] = value;
105
- });
106
- const responseBody = await response.text();
107
- const requestResponse = {
108
- req: {
109
- body,
110
- headers,
111
- method,
112
- url
113
- },
114
- res: {
115
- body: responseBody,
116
- headers: responseHeaders,
117
- status: response.status,
118
- statusText: response.statusText
119
- }
120
- };
121
- if (onDebugRequestResponse) {
122
- onDebugRequestResponse(requestResponse);
123
- }
124
- if (response.ok) {
125
- return false;
126
- }
127
- if (response.status < 500 && response.status !== 429) {
128
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
129
- if (onError) {
130
- onError(error);
131
- }
132
- throw error;
133
- }
134
- return true;
135
- };
136
- const handleRateLimit = (response, respectRateLimit, retryDelay, attempt, maxRetries) => {
137
- if (response.status === 429 && respectRateLimit && attempt < maxRetries) {
138
- const retryAfter = response.headers.get("retry-after");
139
- return retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : calculateBackoffDelay(retryDelay, attempt);
140
- }
141
- return void 0;
142
- };
143
- const handleServerError = (response, retryDelay, attempt, maxRetries) => {
144
- if (response.status >= 500 && attempt < maxRetries) {
145
- return calculateBackoffDelay(retryDelay, attempt);
146
- }
147
- return void 0;
148
- };
149
- const calculateRetryDelay = (response, respectRateLimit, retryDelay, attempt, maxRetries) => {
150
- const rateLimitDelay = handleRateLimit(response, respectRateLimit, retryDelay, attempt, maxRetries);
151
- if (rateLimitDelay !== void 0) {
152
- return rateLimitDelay;
153
- }
154
- return handleServerError(response, retryDelay, attempt, maxRetries);
155
- };
156
- const handleRetryError = async (error, attempt, maxRetries, retryDelay, onError) => {
157
- if (attempt < maxRetries) {
158
- const delay = calculateBackoffDelay(retryDelay, attempt);
159
- await sleep(delay);
160
- return true;
161
- }
162
- if (onError) {
163
- onError(error);
164
- }
165
- return false;
166
- };
167
- const sendWithRetry = async (url, method, headers, body, maxRetries, retryDelay, respectRateLimit, onDebugRequestResponse, onError) => {
168
- let attempt = 0;
169
- while (attempt <= maxRetries) {
170
- try {
171
- const requestBody = prepareRequestBody(body);
172
- const response = await fetch(url, {
173
- body: requestBody,
174
- headers,
175
- method
176
- });
177
- const shouldRetry = await processResponse(response, url, method, headers, body, onDebugRequestResponse, onError);
178
- if (!shouldRetry) {
179
- return;
180
- }
181
- const retryDelayValue = calculateRetryDelay(response, respectRateLimit, retryDelay, attempt, maxRetries);
182
- if (retryDelayValue !== void 0) {
183
- await sleep(retryDelayValue);
184
- attempt += 1;
185
- continue;
186
- }
187
- if (!response.ok) {
188
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
189
- if (onError) {
190
- onError(error);
191
- }
192
- throw error;
193
- }
194
- return;
195
- } catch (error) {
196
- const shouldRetry = await handleRetryError(error, attempt, maxRetries, retryDelay, onError);
197
- if (shouldRetry) {
198
- attempt += 1;
199
- continue;
200
- }
201
- throw error;
202
- }
203
- }
204
- };
205
-
206
- class AbstractHttpReporter extends AbstractJsonReporter {
207
- url;
208
- method;
209
- headers;
210
- contentType;
211
- batchContentType;
212
- onError;
213
- onDebug;
214
- onDebugRequestResponse;
215
- payloadTemplate;
216
- compression;
217
- maxRetries;
218
- retryDelay;
219
- respectRateLimit;
220
- enableBatchSend;
221
- batchSize;
222
- batchSendTimeout;
223
- batchSendDelimiter;
224
- batchMode;
225
- batchFieldName;
226
- maxLogSize;
227
- maxPayloadSize;
228
- edgeCompat;
229
- // Batch management
230
- batchQueue = [];
231
- batchTimeout;
232
- isProcessingBatch = false;
233
- currentBatchSize = 0;
234
- // Track uncompressed size of current batch
235
- /**
236
- * Creates a new instance of AbstractHttpReporter.
237
- * @param config Configuration options for the reporter
238
- */
239
- constructor(config) {
240
- super(config);
241
- this.url = config.url;
242
- this.method = config.method ?? "POST";
243
- this.headers = config.headers ?? {};
244
- this.contentType = config.contentType ?? "application/json";
245
- this.batchContentType = config.batchContentType ?? "application/json";
246
- this.onError = config.onError;
247
- this.onDebug = config.onDebug;
248
- this.onDebugRequestResponse = config.onDebugRequestResponse;
249
- this.payloadTemplate = config.payloadTemplate ?? ((data) => JSON.stringify(data));
250
- this.compression = config.compression ?? false;
251
- this.maxRetries = config.maxRetries ?? 3;
252
- this.retryDelay = config.retryDelay ?? 1e3;
253
- this.respectRateLimit = config.respectRateLimit ?? true;
254
- this.enableBatchSend = config.enableBatchSend ?? true;
255
- this.batchSize = config.batchSize ?? 100;
256
- this.batchSendTimeout = config.batchSendTimeout ?? 5e3;
257
- this.batchSendDelimiter = config.batchSendDelimiter ?? "\n";
258
- this.batchMode = config.batchMode ?? "delimiter";
259
- this.batchFieldName = config.batchFieldName;
260
- if (this.batchMode === "field" && !this.batchFieldName) {
261
- throw new Error("batchFieldName is required when batchMode is 'field'");
262
- }
263
- this.maxLogSize = config.maxLogSize ?? 1048576;
264
- this.maxPayloadSize = config.maxPayloadSize ?? 5242880;
265
- this.edgeCompat = config.edgeCompat ?? false;
266
- }
267
- /**
268
- * Processes and ships log entries to the HTTP endpoint.
269
- * @param message The JSON-formatted log message
270
- * @param logLevel The log level of the message
271
- * @protected
272
- */
273
- // eslint-disable-next-line no-underscore-dangle
274
- _log(message, logLevel) {
275
- try {
276
- const logData = JSON.parse(message);
277
- const logLevelString = logLevel;
278
- const messageString = logData.message;
279
- const payloadTemplate = {
280
- logLevel: logLevelString,
281
- message: messageString ?? ""
282
- };
283
- if (logData.data) {
284
- payloadTemplate["data"] = logData.data;
285
- } else if (logData.context) {
286
- payloadTemplate["data"] = logData.context;
287
- } else {
288
- const rest = { ...logData };
289
- delete rest.message;
290
- if (Object.keys(rest).length > 0) {
291
- payloadTemplate["data"] = rest;
292
- }
293
- }
294
- const payload = this.payloadTemplate(payloadTemplate);
295
- if (this.onDebug) {
296
- this.onDebug({ data: payloadTemplate.data, logLevel: logLevelString, message: messageString });
297
- }
298
- const logEntrySize = this.edgeCompat || typeof TextEncoder === "undefined" ? Buffer.byteLength(payload, "utf8") : new TextEncoder().encode(payload).length;
299
- if (logEntrySize > this.maxLogSize) {
300
- const error = new LogSizeError(
301
- `Log entry exceeds maximum size of ${this.maxLogSize} bytes. Size: ${logEntrySize} bytes`,
302
- { data: payloadTemplate.data, logLevel: logLevelString, message: messageString },
303
- logEntrySize,
304
- this.maxLogSize
305
- );
306
- if (this.onError) {
307
- this.onError(error);
308
- }
309
- return;
310
- }
311
- if (this.enableBatchSend) {
312
- this.addToBatch(payload, logEntrySize);
313
- } else {
314
- this.sendPayload(payload).catch((error) => {
315
- if (this.onError) {
316
- this.onError(error);
317
- }
318
- });
319
- }
320
- } catch (error) {
321
- if (this.onError) {
322
- this.onError(error);
323
- }
324
- }
325
- }
326
- /**
327
- * Adds a payload to the batch queue and triggers sending if conditions are met.
328
- */
329
- addToBatch(payload, logEntrySize) {
330
- const payloadSizeWithEntry = this.currentBatchSize + logEntrySize + this.batchSendDelimiter.length;
331
- const payloadSizeThreshold = this.maxPayloadSize * 0.9;
332
- if (payloadSizeWithEntry > payloadSizeThreshold && this.batchQueue.length > 0) {
333
- this.processBatch();
334
- }
335
- this.batchQueue.push(payload);
336
- this.currentBatchSize += logEntrySize + this.batchSendDelimiter.length;
337
- if (!this.batchTimeout) {
338
- this.batchTimeout = setTimeout(() => {
339
- this.processBatch();
340
- }, this.batchSendTimeout);
341
- }
342
- if (this.batchQueue.length >= this.batchSize) {
343
- this.processBatch();
344
- }
345
- }
346
- /**
347
- * Processes the current batch and sends it to the HTTP endpoint.
348
- */
349
- async processBatch() {
350
- if (this.isProcessingBatch || this.batchQueue.length === 0) {
351
- return;
352
- }
353
- this.isProcessingBatch = true;
354
- if (this.batchTimeout) {
355
- clearTimeout(this.batchTimeout);
356
- this.batchTimeout = void 0;
357
- }
358
- const batch = this.batchQueue.splice(0, this.batchSize);
359
- this.currentBatchSize = 0;
360
- for (let i = 0; i < this.batchQueue.length; i += 1) {
361
- const payload = this.batchQueue[i];
362
- const payloadSize = this.edgeCompat || typeof TextEncoder === "undefined" ? Buffer.byteLength(payload, "utf8") : new TextEncoder().encode(payload).length;
363
- this.currentBatchSize += payloadSize + (i < this.batchQueue.length - 1 ? this.batchSendDelimiter.length : 0);
364
- }
365
- try {
366
- await this.sendBatch(batch);
367
- } catch (error) {
368
- if (this.onError) {
369
- this.onError(error);
370
- }
371
- } finally {
372
- this.isProcessingBatch = false;
373
- if (this.batchQueue.length > 0) {
374
- this.processBatch();
375
- }
376
- }
377
- }
378
- /**
379
- * Sends a batch of payloads to the HTTP endpoint.
380
- */
381
- async sendBatch(batch) {
382
- let batchPayload;
383
- switch (this.batchMode) {
384
- case "array": {
385
- const batchEntries = batch.map((payload) => JSON.parse(payload));
386
- batchPayload = JSON.stringify(batchEntries);
387
- break;
388
- }
389
- case "field": {
390
- const fieldEntries = batch.map((payload) => JSON.parse(payload));
391
- const batchObject = this.batchFieldName ? { [this.batchFieldName]: fieldEntries } : {};
392
- batchPayload = JSON.stringify(batchObject);
393
- break;
394
- }
395
- default: {
396
- batchPayload = batch.join(this.batchSendDelimiter);
397
- break;
398
- }
399
- }
400
- await this.sendPayload(batchPayload, this.batchContentType);
401
- }
402
- /**
403
- * Sends a single payload to the HTTP endpoint.
404
- */
405
- async sendPayload(payload, contentType) {
406
- const headers = typeof this.headers === "function" ? this.headers() : { ...this.headers };
407
- if (!headers["content-type"]) {
408
- headers["content-type"] = contentType ?? this.contentType;
409
- }
410
- let finalPayload = payload;
411
- if (this.compression && !this.edgeCompat) {
412
- try {
413
- finalPayload = await compressData(payload);
414
- headers["content-encoding"] = "gzip";
415
- } catch (error) {
416
- if (this.onError) {
417
- this.onError(new Error(`Compression failed: ${error}`));
418
- }
419
- }
420
- }
421
- await sendWithRetry(
422
- this.url,
423
- this.method,
424
- headers,
425
- finalPayload,
426
- this.maxRetries,
427
- this.retryDelay,
428
- this.respectRateLimit,
429
- this.onDebugRequestResponse,
430
- this.onError
431
- );
432
- }
433
- }
434
-
435
- export { AbstractHttpReporter };
1
+ import{createRequire as S}from"node:module";import{AbstractJsonReporter as w}from"../../packem_shared/AbstractJsonReporter-w_bGGiD-.js";const T=S(import.meta.url),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,f=i=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[t,e]=m.versions.node.split(".").map(Number);if(t>22||t===22&&e>=3||t===20&&e>=16)return m.getBuiltinModule(i)}return T(i)},{Buffer:g}=f("node:buffer"),{gzipSync:x}=f("node:zlib"),z=async i=>{const t=globalThis.CompressionStream;if(t){const e=new t("gzip"),s=e.writable.getWriter(),a=e.readable.getReader(),o=new TextEncoder,n=[];await s.write(o.encode(i)),await s.close();let u=!1;for(;!u;){const h=await a.read();u=h.done,h.value&&n.push(h.value)}const c=n.reduce((h,d)=>h+d.length,0),r=new Uint8Array(c);let l=0;for(let h=0;h<n.length;h+=1){const d=n[h];r.set(d,l),l+=d.length}return r}return x(i)};class D extends Error{logData;actualSize;maxSize;constructor(t,e,s,a){super(t),this.name="LogSizeError",this.logData=e,this.actualSize=s,this.maxSize=a}}const b=(i,t)=>i*2**t,B=/^\d+$/,E=i=>{const t=i.trim();if(B.test(t)){const a=Number.parseInt(t,10);return Math.min(Math.max(a,0)*1e3,6e4)}const e=Date.parse(t);if(Number.isNaN(e))return;const s=e-Date.now();return Math.min(Math.max(s,0),6e4)},y=i=>new Promise(t=>{setTimeout(t,i)}),R=i=>typeof i=="string"?i:new Uint8Array(i.buffer,i.byteOffset,i.byteLength),P=async(i,t,e,s,a,o,n)=>{const u={};i.headers.forEach((l,h)=>{u[h]=l});const c=await i.text(),r={req:{body:a,headers:s,method:e,url:t},res:{body:c,headers:u,status:i.status,statusText:i.statusText}};if(o&&o(r),i.ok)return!1;if(i.status<500&&i.status!==429){const l=new Error(`HTTP ${String(i.status)}: ${i.statusText}`);throw n&&n(l),l}return!0},Q=(i,t,e,s,a)=>{if(i.status===429&&t&&s<a){const o=i.headers.get("retry-after");return(o?E(o):void 0)??b(e,s)}},L=(i,t,e,s)=>{if(i.status>=500&&e<s)return b(t,e)},N=(i,t,e,s,a)=>{const o=Q(i,t,e,s,a);return o!==void 0?o:L(i,e,s,a)},v=async(i,t,e,s,a)=>{if(t<e){const o=b(s,t);return await y(o),!0}return a&&a(i),!1},_=async(i,t,e,s,a,o,n,u,c)=>{let r=0;for(;r<=a;)try{const l=R(s),h=await fetch(i,{body:l,headers:e,method:t});if(!await P(h,i,t,e,s,u,c))return;const d=N(h,n,o,r,a);if(d!==void 0){await y(d),r+=1;continue}if(!h.ok){const p=new Error(`HTTP ${String(h.status)}: ${h.statusText}`);throw c&&c(p),p}return}catch(l){if(await v(l,r,a,o,c)){r+=1;continue}throw l}};class $ extends w{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(t){if(super(t),this.url=t.url,this.method=t.method??"POST",this.headers=t.headers??{},this.contentType=t.contentType??"application/json",this.batchContentType=t.batchContentType??"application/json",this.onError=t.onError,this.onDrop=t.onDrop,this.maxQueueSize=t.maxQueueSize??1e4,this.onDebug=t.onDebug,this.onDebugRequestResponse=t.onDebugRequestResponse,this.payloadTemplate=t.payloadTemplate??(e=>JSON.stringify(e)),this.compression=t.compression??!1,this.maxRetries=t.maxRetries??3,this.retryDelay=t.retryDelay??1e3,this.respectRateLimit=t.respectRateLimit??!0,this.enableBatchSend=t.enableBatchSend??!0,this.batchSize=t.batchSize??100,this.batchSendTimeout=t.batchSendTimeout??5e3,this.batchSendDelimiter=t.batchSendDelimiter??`
2
+ `,this.batchMode=t.batchMode??"delimiter",this.batchFieldName=t.batchFieldName,this.batchMode==="field"&&!this.batchFieldName)throw new Error("batchFieldName is required when batchMode is 'field'");this.maxLogSize=t.maxLogSize??1048576,this.maxPayloadSize=t.maxPayloadSize??5242880,this.edgeCompat=t.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(t=>setTimeout(t,0));continue}await this.processBatch()}}async close(){await this.flush()}async dispose(){await this.close()}_log(t,e){try{const s=JSON.parse(t),a=e,o=s.message,n={logLevel:a,message:o??""};if(s.data)n.data=s.data;else if(s.context)n.data=s.context;else{const r={...s};delete r.message,Object.keys(r).length>0&&(n.data=r)}const u=this.payloadTemplate(n);this.onDebug&&this.onDebug({data:n.data,logLevel:a,message:o});const c=this.edgeCompat||typeof TextEncoder>"u"?g.byteLength(u,"utf8"):new TextEncoder().encode(u).length;if(c>this.maxLogSize){const r=new D(`Log entry exceeds maximum size of ${String(this.maxLogSize)} bytes. Size: ${String(c)} bytes`,{data:n.data,logLevel:a,message:o},c,this.maxLogSize);this.onError&&this.onError(r);return}this.enableBatchSend?this.addToBatch(u,c):this.sendPayload(u).catch(r=>{this.onError&&this.onError(r)})}catch(s){this.onError&&this.onError(s)}}addToBatch(t,e){const s=this.currentBatchSize+e+this.batchSendDelimiter.length,a=this.maxPayloadSize*.9;if(s>a&&this.batchQueue.length>0&&this.processBatch(),this.batchQueue.push(t),this.currentBatchSize+=e+this.batchSendDelimiter.length,this.batchQueue.length>this.maxQueueSize){const o=this.batchQueue.splice(0,this.batchQueue.length-this.maxQueueSize);this.currentBatchSize=this.#t(),this.onDrop&&this.onDrop(o.length)}this.batchTimeout??=setTimeout(()=>{this.processBatch()},this.batchSendTimeout),this.batchQueue.length>=this.batchSize&&this.processBatch()}#t(){let t=0;for(let e=0;e<this.batchQueue.length;e+=1){const s=this.batchQueue[e],a=this.edgeCompat||typeof TextEncoder>"u"?g.byteLength(s,"utf8"):new TextEncoder().encode(s).length;t+=a+(e<this.batchQueue.length-1?this.batchSendDelimiter.length:0)}return t}async processBatch(){if(this.isProcessingBatch||this.batchQueue.length===0)return;this.isProcessingBatch=!0,this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0);const t=this.batchQueue.splice(0,this.batchSize);this.currentBatchSize=this.#t();try{await this.sendBatch(t)}catch(e){this.onError&&this.onError(e)}finally{this.isProcessingBatch=!1,this.batchQueue.length>0&&this.processBatch()}}async sendBatch(t){let e;switch(this.batchMode){case"array":{const s=t.map(a=>JSON.parse(a));e=JSON.stringify(s);break}case"field":{const s=t.map(o=>JSON.parse(o)),a=this.batchFieldName?{[this.batchFieldName]:s}:{};e=JSON.stringify(a);break}default:{e=t.join(this.batchSendDelimiter);break}}await this.sendPayload(e,this.batchContentType)}async sendPayload(t,e){const s=typeof this.headers=="function"?this.headers():{...this.headers};s["content-type"]??=e??this.contentType;let a=t;if(this.compression&&!this.edgeCompat)try{a=await z(t),s["content-encoding"]="gzip"}catch(o){this.onError&&this.onError(new Error(`Compression failed: ${String(o)}`))}await _(this.url,this.method,s,a,this.maxRetries,this.retryDelay,this.respectRateLimit,this.onDebugRequestResponse,this.onError)}}export{$ as AbstractHttpReporter};
@@ -1,39 +1,44 @@
1
- import type { AbstractHttpReporterOptions } from "./abstract-http-reporter.d.ts";
2
- import { AbstractHttpReporter } from "./abstract-http-reporter.d.ts";
1
+ import { AbstractHttpReporterOptions, AbstractHttpReporter } from "./abstract-http-reporter.js";
2
+ import 'type-fest';
3
+ import "../../packem_shared/types.d-bWnqHJKL.js";
4
+ import '@visulima/colorize';
5
+ import '@visulima/interactive-manager';
6
+ import "../../packem_shared/abstract-json-reporter.d-wfESoEa-.js";
7
+ import "../../packem_shared/index.d-T71KjNAr.js";
3
8
  /**
4
- * HTTP Reporter.
5
- *
6
- * A reporter that sends logs to HTTP endpoints.
7
- * Supports batching, compression, retries, and rate limiting.
8
- * Works in both Node.js server and browser environments.
9
- * @template L - The log level type
10
- * @example
11
- * ```typescript
12
- * import { createPail } from "@visulima/pail";
13
- * import { HttpReporter } from "@visulima/pail/reporter/http";
14
- *
15
- * const logger = createPail({
16
- * reporters: [
17
- * new HttpReporter({
18
- * url: "https://api.example.com/logs",
19
- * method: "POST",
20
- * headers: {
21
- * "Authorization": "Bearer token"
22
- * },
23
- * enableBatchSend: true,
24
- * batchSize: 100
25
- * })
26
- * ]
27
- * });
28
- *
29
- * logger.info("Application started", { version: "1.0.0" });
30
- * ```
31
- */
9
+ * HTTP Reporter.
10
+ *
11
+ * A reporter that sends logs to HTTP endpoints.
12
+ * Supports batching, compression, retries, and rate limiting.
13
+ * Works in both Node.js server and browser environments.
14
+ * @template L - The log level type
15
+ * @example
16
+ * ```typescript
17
+ * import { createPail } from "@visulima/pail";
18
+ * import { HttpReporter } from "@visulima/pail/reporter/http";
19
+ *
20
+ * const logger = createPail({
21
+ * reporters: [
22
+ * new HttpReporter({
23
+ * url: "https://api.example.com/logs",
24
+ * method: "POST",
25
+ * headers: {
26
+ * "Authorization": "Bearer token"
27
+ * },
28
+ * enableBatchSend: true,
29
+ * batchSize: 100
30
+ * })
31
+ * ]
32
+ * });
33
+ *
34
+ * logger.info("Application started", { version: "1.0.0" });
35
+ * ```
36
+ */
32
37
  declare class HttpReporter<L extends string = string> extends AbstractHttpReporter<L> {
33
- /**
34
- * Creates a new HTTP Reporter instance.
35
- * @param options Configuration options for HTTP reporting
36
- */
37
- constructor(options: AbstractHttpReporterOptions);
38
+ /**
39
+ * Creates a new HTTP Reporter instance.
40
+ * @param options Configuration options for HTTP reporting
41
+ */
42
+ constructor(options: AbstractHttpReporterOptions);
38
43
  }
39
- export default HttpReporter;
44
+ export { HttpReporter as default };