lifecycleion 0.0.1

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 (177) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +125 -0
  3. package/dist/index.cjs +7 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +2 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +5 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/lib/arrays.cjs +95 -0
  10. package/dist/lib/arrays.cjs.map +1 -0
  11. package/dist/lib/arrays.d.cts +15 -0
  12. package/dist/lib/arrays.d.ts +15 -0
  13. package/dist/lib/arrays.js +63 -0
  14. package/dist/lib/arrays.js.map +1 -0
  15. package/dist/lib/ascii-tables/index.cjs +642 -0
  16. package/dist/lib/ascii-tables/index.cjs.map +1 -0
  17. package/dist/lib/ascii-tables/index.d.cts +66 -0
  18. package/dist/lib/ascii-tables/index.d.ts +66 -0
  19. package/dist/lib/ascii-tables/index.js +603 -0
  20. package/dist/lib/ascii-tables/index.js.map +1 -0
  21. package/dist/lib/clamp.cjs +41 -0
  22. package/dist/lib/clamp.cjs.map +1 -0
  23. package/dist/lib/clamp.d.cts +26 -0
  24. package/dist/lib/clamp.d.ts +26 -0
  25. package/dist/lib/clamp.js +15 -0
  26. package/dist/lib/clamp.js.map +1 -0
  27. package/dist/lib/constants.cjs +73 -0
  28. package/dist/lib/constants.cjs.map +1 -0
  29. package/dist/lib/constants.d.cts +17 -0
  30. package/dist/lib/constants.d.ts +17 -0
  31. package/dist/lib/constants.js +34 -0
  32. package/dist/lib/constants.js.map +1 -0
  33. package/dist/lib/curly-brackets.cjs +77 -0
  34. package/dist/lib/curly-brackets.cjs.map +1 -0
  35. package/dist/lib/curly-brackets.d.cts +17 -0
  36. package/dist/lib/curly-brackets.d.ts +17 -0
  37. package/dist/lib/curly-brackets.js +52 -0
  38. package/dist/lib/curly-brackets.js.map +1 -0
  39. package/dist/lib/deep-clone.cjs +87 -0
  40. package/dist/lib/deep-clone.cjs.map +1 -0
  41. package/dist/lib/deep-clone.d.cts +19 -0
  42. package/dist/lib/deep-clone.d.ts +19 -0
  43. package/dist/lib/deep-clone.js +62 -0
  44. package/dist/lib/deep-clone.js.map +1 -0
  45. package/dist/lib/error-to-string.cjs +743 -0
  46. package/dist/lib/error-to-string.cjs.map +1 -0
  47. package/dist/lib/error-to-string.d.cts +3 -0
  48. package/dist/lib/error-to-string.d.ts +3 -0
  49. package/dist/lib/error-to-string.js +706 -0
  50. package/dist/lib/error-to-string.js.map +1 -0
  51. package/dist/lib/event-emitter.cjs +899 -0
  52. package/dist/lib/event-emitter.cjs.map +1 -0
  53. package/dist/lib/event-emitter.d.cts +78 -0
  54. package/dist/lib/event-emitter.d.ts +78 -0
  55. package/dist/lib/event-emitter.js +861 -0
  56. package/dist/lib/event-emitter.js.map +1 -0
  57. package/dist/lib/id-helpers.cjs +205 -0
  58. package/dist/lib/id-helpers.cjs.map +1 -0
  59. package/dist/lib/id-helpers.d.cts +198 -0
  60. package/dist/lib/id-helpers.d.ts +198 -0
  61. package/dist/lib/id-helpers.js +170 -0
  62. package/dist/lib/id-helpers.js.map +1 -0
  63. package/dist/lib/is-boolean.cjs +33 -0
  64. package/dist/lib/is-boolean.cjs.map +1 -0
  65. package/dist/lib/is-boolean.d.cts +19 -0
  66. package/dist/lib/is-boolean.d.ts +19 -0
  67. package/dist/lib/is-boolean.js +8 -0
  68. package/dist/lib/is-boolean.js.map +1 -0
  69. package/dist/lib/is-function.cjs +33 -0
  70. package/dist/lib/is-function.cjs.map +1 -0
  71. package/dist/lib/is-function.d.cts +3 -0
  72. package/dist/lib/is-function.d.ts +3 -0
  73. package/dist/lib/is-function.js +8 -0
  74. package/dist/lib/is-function.js.map +1 -0
  75. package/dist/lib/is-number.cjs +38 -0
  76. package/dist/lib/is-number.cjs.map +1 -0
  77. package/dist/lib/is-number.d.cts +38 -0
  78. package/dist/lib/is-number.d.ts +38 -0
  79. package/dist/lib/is-number.js +12 -0
  80. package/dist/lib/is-number.js.map +1 -0
  81. package/dist/lib/is-plain-object.cjs +33 -0
  82. package/dist/lib/is-plain-object.cjs.map +1 -0
  83. package/dist/lib/is-plain-object.d.cts +20 -0
  84. package/dist/lib/is-plain-object.d.ts +20 -0
  85. package/dist/lib/is-plain-object.js +8 -0
  86. package/dist/lib/is-plain-object.js.map +1 -0
  87. package/dist/lib/is-promise.cjs +34 -0
  88. package/dist/lib/is-promise.cjs.map +1 -0
  89. package/dist/lib/is-promise.d.cts +3 -0
  90. package/dist/lib/is-promise.d.ts +3 -0
  91. package/dist/lib/is-promise.js +9 -0
  92. package/dist/lib/is-promise.js.map +1 -0
  93. package/dist/lib/json-helpers.cjs +49 -0
  94. package/dist/lib/json-helpers.cjs.map +1 -0
  95. package/dist/lib/json-helpers.d.cts +10 -0
  96. package/dist/lib/json-helpers.d.ts +10 -0
  97. package/dist/lib/json-helpers.js +22 -0
  98. package/dist/lib/json-helpers.js.map +1 -0
  99. package/dist/lib/lifecycle-manager/index.cjs +5594 -0
  100. package/dist/lib/lifecycle-manager/index.cjs.map +1 -0
  101. package/dist/lib/lifecycle-manager/index.d.cts +2044 -0
  102. package/dist/lib/lifecycle-manager/index.d.ts +2044 -0
  103. package/dist/lib/lifecycle-manager/index.js +5543 -0
  104. package/dist/lib/lifecycle-manager/index.js.map +1 -0
  105. package/dist/lib/logger/index.cjs +2514 -0
  106. package/dist/lib/logger/index.cjs.map +1 -0
  107. package/dist/lib/logger/index.d.cts +630 -0
  108. package/dist/lib/logger/index.d.ts +630 -0
  109. package/dist/lib/logger/index.js +2470 -0
  110. package/dist/lib/logger/index.js.map +1 -0
  111. package/dist/lib/padding-utils.cjs +77 -0
  112. package/dist/lib/padding-utils.cjs.map +1 -0
  113. package/dist/lib/padding-utils.d.cts +44 -0
  114. package/dist/lib/padding-utils.d.ts +44 -0
  115. package/dist/lib/padding-utils.js +46 -0
  116. package/dist/lib/padding-utils.js.map +1 -0
  117. package/dist/lib/process-signal-manager.cjs +1306 -0
  118. package/dist/lib/process-signal-manager.cjs.map +1 -0
  119. package/dist/lib/process-signal-manager.d.cts +305 -0
  120. package/dist/lib/process-signal-manager.d.ts +305 -0
  121. package/dist/lib/process-signal-manager.js +1269 -0
  122. package/dist/lib/process-signal-manager.js.map +1 -0
  123. package/dist/lib/promise-protected-resolver.cjs +828 -0
  124. package/dist/lib/promise-protected-resolver.cjs.map +1 -0
  125. package/dist/lib/promise-protected-resolver.d.cts +17 -0
  126. package/dist/lib/promise-protected-resolver.d.ts +17 -0
  127. package/dist/lib/promise-protected-resolver.js +791 -0
  128. package/dist/lib/promise-protected-resolver.js.map +1 -0
  129. package/dist/lib/retry-utils/index.cjs +2183 -0
  130. package/dist/lib/retry-utils/index.cjs.map +1 -0
  131. package/dist/lib/retry-utils/index.d.cts +321 -0
  132. package/dist/lib/retry-utils/index.d.ts +321 -0
  133. package/dist/lib/retry-utils/index.js +2133 -0
  134. package/dist/lib/retry-utils/index.js.map +1 -0
  135. package/dist/lib/safe-handle-callback.cjs +818 -0
  136. package/dist/lib/safe-handle-callback.cjs.map +1 -0
  137. package/dist/lib/safe-handle-callback.d.cts +43 -0
  138. package/dist/lib/safe-handle-callback.d.ts +43 -0
  139. package/dist/lib/safe-handle-callback.js +780 -0
  140. package/dist/lib/safe-handle-callback.js.map +1 -0
  141. package/dist/lib/serialize-error/index.cjs +93 -0
  142. package/dist/lib/serialize-error/index.cjs.map +1 -0
  143. package/dist/lib/serialize-error/index.d.cts +26 -0
  144. package/dist/lib/serialize-error/index.d.ts +26 -0
  145. package/dist/lib/serialize-error/index.js +64 -0
  146. package/dist/lib/serialize-error/index.js.map +1 -0
  147. package/dist/lib/single-event-observer.cjs +841 -0
  148. package/dist/lib/single-event-observer.cjs.map +1 -0
  149. package/dist/lib/single-event-observer.d.cts +54 -0
  150. package/dist/lib/single-event-observer.d.ts +54 -0
  151. package/dist/lib/single-event-observer.js +803 -0
  152. package/dist/lib/single-event-observer.js.map +1 -0
  153. package/dist/lib/sleep.cjs +37 -0
  154. package/dist/lib/sleep.cjs.map +1 -0
  155. package/dist/lib/sleep.d.cts +11 -0
  156. package/dist/lib/sleep.d.ts +11 -0
  157. package/dist/lib/sleep.js +12 -0
  158. package/dist/lib/sleep.js.map +1 -0
  159. package/dist/lib/strings.cjs +186 -0
  160. package/dist/lib/strings.cjs.map +1 -0
  161. package/dist/lib/strings.d.cts +107 -0
  162. package/dist/lib/strings.d.ts +107 -0
  163. package/dist/lib/strings.js +149 -0
  164. package/dist/lib/strings.js.map +1 -0
  165. package/dist/lib/tmp-dir.cjs +254 -0
  166. package/dist/lib/tmp-dir.cjs.map +1 -0
  167. package/dist/lib/tmp-dir.d.cts +63 -0
  168. package/dist/lib/tmp-dir.d.ts +63 -0
  169. package/dist/lib/tmp-dir.js +211 -0
  170. package/dist/lib/tmp-dir.js.map +1 -0
  171. package/dist/lib/unix-time-helpers.cjs +53 -0
  172. package/dist/lib/unix-time-helpers.cjs.map +1 -0
  173. package/dist/lib/unix-time-helpers.d.cts +56 -0
  174. package/dist/lib/unix-time-helpers.d.ts +56 -0
  175. package/dist/lib/unix-time-helpers.js +24 -0
  176. package/dist/lib/unix-time-helpers.js.map +1 -0
  177. package/package.json +220 -0
@@ -0,0 +1,2514 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/lib/logger/index.ts
31
+ var logger_exports = {};
32
+ __export(logger_exports, {
33
+ ArraySink: () => ArraySink,
34
+ ConsoleSink: () => ConsoleSink,
35
+ FileSink: () => FileSink,
36
+ LogLevel: () => LogLevel,
37
+ Logger: () => Logger,
38
+ NamedPipeSink: () => NamedPipeSink,
39
+ PipeErrorType: () => PipeErrorType,
40
+ getLogLevel: () => getLogLevel
41
+ });
42
+ module.exports = __toCommonJS(logger_exports);
43
+
44
+ // src/lib/strings.ts
45
+ function isString(value) {
46
+ return typeof value === "string";
47
+ }
48
+ function splitGraphemes(text) {
49
+ const graphemes = [];
50
+ let grapheme = "";
51
+ let zwjSequence = "";
52
+ for (let i = 0; i < text.length; i++) {
53
+ const char = text[i];
54
+ const nextChar = text[i + 1] || "";
55
+ const code = char.charCodeAt(0);
56
+ if (code >= 768 && code <= 879 || // Combining Diacritical Marks
57
+ code >= 6832 && code <= 6911 || // Combining Diacritical Marks Extended
58
+ code >= 7616 && code <= 7679 || // Combining Diacritical Marks Supplement
59
+ code >= 65056 && code <= 65071 || // Combining Half Marks
60
+ code >= 3633 && code <= 3642 || // Thai combining marks
61
+ code >= 3655 && code <= 3662) {
62
+ grapheme += char;
63
+ } else if (char === "\u200D") {
64
+ zwjSequence += grapheme + char;
65
+ grapheme = "";
66
+ } else {
67
+ if (grapheme) {
68
+ if (zwjSequence) {
69
+ graphemes.push(zwjSequence + grapheme);
70
+ zwjSequence = "";
71
+ } else {
72
+ graphemes.push(grapheme);
73
+ }
74
+ }
75
+ grapheme = char;
76
+ if (char >= "\uD800" && char <= "\uDBFF" && nextChar >= "\uDC00" && nextChar <= "\uDFFF") {
77
+ grapheme += nextChar;
78
+ i++;
79
+ }
80
+ }
81
+ }
82
+ if (grapheme) {
83
+ if (zwjSequence) {
84
+ graphemes.push(zwjSequence + grapheme);
85
+ } else {
86
+ graphemes.push(grapheme);
87
+ }
88
+ }
89
+ return graphemes;
90
+ }
91
+
92
+ // src/lib/constants.ts
93
+ var BLANK_SPACE = " ";
94
+ var EOL = "\n";
95
+ var DOUBLE_EOL = EOL + EOL;
96
+ var INDENT = " ".repeat(4);
97
+ var DOUBLE_INDENT = INDENT + INDENT;
98
+ var ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
99
+ var ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
100
+ var ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE;
101
+ var DIGITS = "0123456789";
102
+ var HEX_DIGITS = DIGITS + "abcdefABCDEF";
103
+ var PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
104
+ var WHITESPACE = " \n\r\v\f";
105
+ var PRINTABLE = DIGITS + ASCII_LETTERS + PUNCTUATION + WHITESPACE;
106
+
107
+ // src/lib/padding-utils.ts
108
+ function padLeft(str, length, padStr = BLANK_SPACE) {
109
+ return str.padStart(length, padStr);
110
+ }
111
+ function padRight(str, length, padStr = BLANK_SPACE) {
112
+ return str.padEnd(length, padStr);
113
+ }
114
+ function padCenter(str, length, prefer = "left", padStr = BLANK_SPACE) {
115
+ const midStrLength = length - str.length;
116
+ if (midStrLength > 0) {
117
+ const padLeftAmount = prefer === "left" ? Math.ceil(midStrLength / 2) : Math.floor(midStrLength / 2);
118
+ const padRightAmount = prefer === "left" ? Math.floor(midStrLength / 2) : Math.ceil(midStrLength / 2);
119
+ return padLeft("", padLeftAmount, padStr) + str + padRight("", padRightAmount, padStr);
120
+ } else {
121
+ return str;
122
+ }
123
+ }
124
+ function padCenterPreferRight(str, length, padStr = BLANK_SPACE) {
125
+ return padCenter(str, length, "right", padStr);
126
+ }
127
+
128
+ // src/lib/ascii-tables/ascii-table-utils.ts
129
+ var import_string_width = __toESM(require("string-width"), 1);
130
+ var ASCIITableUtils = class _ASCIITableUtils {
131
+ static centerText(text, width) {
132
+ return padCenterPreferRight(text, width, " ");
133
+ }
134
+ static createSeparator(columnWidths, character = "=") {
135
+ const totalWidth = columnWidths.reduce((sum, width) => sum + width + 3, 0) - 1;
136
+ return `+${padRight("", totalWidth, character)}+`;
137
+ }
138
+ static wrapText(text, maxLength) {
139
+ const words = text.split(" ");
140
+ const lines = [];
141
+ let currentLine = "";
142
+ for (const word of words) {
143
+ if ((0, import_string_width.default)(currentLine) + (0, import_string_width.default)(word) + 1 <= maxLength) {
144
+ currentLine += (currentLine ? " " : "") + word;
145
+ } else {
146
+ if (currentLine) {
147
+ lines.push(currentLine);
148
+ }
149
+ if ((0, import_string_width.default)(word) <= maxLength) {
150
+ currentLine = word;
151
+ } else {
152
+ const subWords = _ASCIITableUtils.splitWord(word, maxLength);
153
+ lines.push(...subWords.slice(0, -1));
154
+ currentLine = subWords[subWords.length - 1];
155
+ }
156
+ }
157
+ }
158
+ if (currentLine) {
159
+ lines.push(currentLine);
160
+ }
161
+ return lines;
162
+ }
163
+ static splitWord(word, maxLength) {
164
+ const graphemes = splitGraphemes(word);
165
+ const subWords = [];
166
+ let currentSubWord = "";
167
+ for (const grapheme of graphemes) {
168
+ if ((0, import_string_width.default)(currentSubWord + grapheme) <= maxLength) {
169
+ currentSubWord += grapheme;
170
+ } else {
171
+ subWords.push(currentSubWord);
172
+ currentSubWord = grapheme;
173
+ }
174
+ }
175
+ if (currentSubWord) {
176
+ subWords.push(currentSubWord);
177
+ }
178
+ return subWords;
179
+ }
180
+ };
181
+
182
+ // src/lib/ascii-tables/multi-column-ascii-table.ts
183
+ var import_string_width2 = __toESM(require("string-width"), 1);
184
+ var MultiColumnASCIITable = class {
185
+ headers;
186
+ rows;
187
+ tableWidth;
188
+ emptyMessage;
189
+ widthMode;
190
+ constructor(headers, options = {}) {
191
+ this.headers = headers;
192
+ this.rows = [];
193
+ this.tableWidth = options.tableWidth || 80;
194
+ this.emptyMessage = options.emptyMessage || "";
195
+ this.widthMode = options.widthMode || "flex";
196
+ const minTableWidth = this.getMinimumWidth();
197
+ if (this.tableWidth < minTableWidth) {
198
+ throw new Error(
199
+ `Table width must be at least ${minTableWidth} to accommodate the headers.`
200
+ );
201
+ }
202
+ }
203
+ getMinimumWidth() {
204
+ return this.headers.length * 4 + 1;
205
+ }
206
+ addRow(row) {
207
+ if (row.length !== this.headers.length) {
208
+ throw new Error(
209
+ `Number of values in the row (${row.length}) must match the number of headers (${this.headers.length}).`
210
+ );
211
+ }
212
+ this.rows.push(row);
213
+ }
214
+ toString(options = {}) {
215
+ const tableWidth = options.tableWidth || this.tableWidth;
216
+ const emptyMessage = options.emptyMessage || this.emptyMessage;
217
+ if (this.rows.length === 0) {
218
+ const emptyTableWidth = Math.min(tableWidth, 40);
219
+ const separator = "+" + "-".repeat(emptyTableWidth - 2) + "+";
220
+ const emptyMessageLines = ASCIITableUtils.wrapText(
221
+ emptyMessage,
222
+ emptyTableWidth - 4
223
+ );
224
+ const emptyRows = emptyMessageLines.map((line) => {
225
+ const paddingLeft = " ".repeat(
226
+ Math.floor((emptyTableWidth - (0, import_string_width2.default)(line) - 4) / 2)
227
+ );
228
+ const paddingRight = " ".repeat(
229
+ Math.ceil((emptyTableWidth - (0, import_string_width2.default)(line) - 4) / 2)
230
+ );
231
+ return `| ${paddingLeft}${line}${paddingRight} |`;
232
+ });
233
+ if (emptyRows.length === 0) {
234
+ emptyRows.push(`| ${" ".repeat(emptyTableWidth - 4)} |`);
235
+ }
236
+ return [separator, ...emptyRows, separator].join("\n");
237
+ }
238
+ const columnWidths = this.calculateColumnWidths(options);
239
+ const headerSeparator = ASCIITableUtils.createSeparator(columnWidths);
240
+ const rowSeparator = ASCIITableUtils.createSeparator(columnWidths, "-");
241
+ let tableString = headerSeparator + "\n";
242
+ const header = this.renderRow(this.headers, columnWidths);
243
+ tableString += header + "\n" + rowSeparator + "\n";
244
+ const rows = this.rows.map((row) => {
245
+ return this.renderRow(row, columnWidths);
246
+ });
247
+ tableString += rows.join("\n" + rowSeparator + "\n");
248
+ tableString += "\n" + headerSeparator;
249
+ return tableString;
250
+ }
251
+ calculateColumnWidths(options = {}) {
252
+ const tableWidth = options.tableWidth || this.tableWidth;
253
+ const widthMode = options.widthMode || this.widthMode;
254
+ const numColumns = this.headers.length;
255
+ if (widthMode === "fixed") {
256
+ const availableWidth2 = tableWidth - (numColumns + 1) * 3 + 1;
257
+ const columnWidth = Math.floor(availableWidth2 / numColumns);
258
+ const extraWidth = availableWidth2 % numColumns;
259
+ const columnWidths = new Array(numColumns).fill(columnWidth);
260
+ for (let i = 0; i < extraWidth; i++) {
261
+ columnWidths[i] += 1;
262
+ }
263
+ return columnWidths;
264
+ }
265
+ const availableWidth = tableWidth - (numColumns + 1) * 3 + 1;
266
+ const maxColumnWidth = Math.floor(availableWidth / numColumns);
267
+ const totalContentWidth = this.headers.reduce(
268
+ (sum, header) => sum + (0, import_string_width2.default)(header),
269
+ 0
270
+ );
271
+ if (availableWidth >= totalContentWidth) {
272
+ const remainingWidth = availableWidth - totalContentWidth;
273
+ const extraCharWidth = Math.floor(remainingWidth / numColumns);
274
+ const extraCharRemainder = remainingWidth % numColumns;
275
+ const columnWidths = this.headers.map((header, index) => {
276
+ const extraWidth = index < extraCharRemainder ? 1 : 0;
277
+ return (0, import_string_width2.default)(header) + extraCharWidth + extraWidth;
278
+ });
279
+ return columnWidths;
280
+ } else {
281
+ const columnWidths = this.headers.map(() => maxColumnWidth);
282
+ return columnWidths;
283
+ }
284
+ }
285
+ renderRow(row, columnWidths) {
286
+ const wrappedCells = row.map((value, index) => {
287
+ const wrappedLines = ASCIITableUtils.wrapText(value, columnWidths[index]);
288
+ return wrappedLines.map((line) => line.padEnd(columnWidths[index])).join("\n");
289
+ });
290
+ const maxLines = Math.max(
291
+ ...wrappedCells.map((cell) => cell.split("\n").length)
292
+ );
293
+ const paddedRows = [];
294
+ for (let i = 0; i < maxLines; i++) {
295
+ const rowLine = wrappedCells.map((cell, index) => {
296
+ const cellLines = cell.split("\n");
297
+ const cellLine = cellLines[i] || "";
298
+ const padding = " ".repeat(columnWidths[index] - (0, import_string_width2.default)(cellLine));
299
+ return " " + cellLine + padding + " ";
300
+ });
301
+ paddedRows.push("|" + rowLine.join("|") + "|");
302
+ }
303
+ return paddedRows.join("\n");
304
+ }
305
+ };
306
+
307
+ // src/lib/ascii-tables/key-value-ascii-table.ts
308
+ var import_string_width3 = __toESM(require("string-width"), 1);
309
+
310
+ // src/lib/clamp.ts
311
+ function clamp(value, min, max) {
312
+ return Math.max(min, Math.min(value, max));
313
+ }
314
+
315
+ // src/lib/ascii-tables/key-value-ascii-table.ts
316
+ var KeyValueASCIITable = class _KeyValueASCIITable {
317
+ tableWidth;
318
+ emptyMessage;
319
+ autoAdjustWidthWhenPossible = true;
320
+ rows = [];
321
+ constructor(options = {}) {
322
+ const minTableWidth = this.getMinimumWidth();
323
+ if (options.tableWidth && options.tableWidth < minTableWidth) {
324
+ throw new Error(
325
+ `Table width must be at least ${minTableWidth} to accommodate the table structure.`
326
+ );
327
+ }
328
+ this.tableWidth = options.tableWidth || 80;
329
+ this.autoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? true;
330
+ this.emptyMessage = options.emptyMessage || "";
331
+ }
332
+ getMinimumWidth() {
333
+ return 9;
334
+ }
335
+ /**
336
+ * Adds key and value to the table but placing the value on its own row.
337
+ *
338
+ * @param key
339
+ * @param value
340
+ */
341
+ addValueOnSeparateRow(key, value) {
342
+ const row = { kind: "own", key, value };
343
+ this.rows.push(row);
344
+ }
345
+ /**
346
+ * Adds key and value to the table.
347
+ *
348
+ * If provided value is an instance of ASCIITable or MultiColumnASCIITable, it will be rendered as a nested table on its own row for readability.
349
+ *
350
+ * @param key
351
+ * @param value
352
+ */
353
+ addRow(key, value) {
354
+ const row = { kind: "regular", key, value };
355
+ this.rows.push(row);
356
+ }
357
+ toString(options = {}) {
358
+ const tableWidth = options.tableWidth || this.tableWidth;
359
+ const canAutoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? this.autoAdjustWidthWhenPossible;
360
+ const emptyMessage = options.emptyMessage || this.emptyMessage;
361
+ if (this.rows.length === 0) {
362
+ const emptyTableWidth = Math.min(tableWidth, 40);
363
+ const separator = "+" + "-".repeat(emptyTableWidth - 2) + "+";
364
+ const emptyMessageLines = ASCIITableUtils.wrapText(
365
+ emptyMessage,
366
+ emptyTableWidth - 4
367
+ );
368
+ const emptyRows = emptyMessageLines.map((line) => {
369
+ const paddingLeft = padRight(
370
+ "",
371
+ Math.floor((emptyTableWidth - (0, import_string_width3.default)(line) - 4) / 2),
372
+ " "
373
+ );
374
+ const paddingRight = padRight(
375
+ "",
376
+ Math.ceil((emptyTableWidth - (0, import_string_width3.default)(line) - 4) / 2),
377
+ " "
378
+ );
379
+ return `| ${paddingLeft}${line}${paddingRight} |`;
380
+ });
381
+ if (emptyRows.length === 0) {
382
+ emptyRows.push(`| ${" ".repeat(emptyTableWidth - 4)} |`);
383
+ }
384
+ return [separator, ...emptyRows, separator].join("\n");
385
+ }
386
+ const columnWidths = this.calculateColumnWidths(options);
387
+ const headerSeparator = ASCIITableUtils.createSeparator(columnWidths);
388
+ const rowSeparator = ASCIITableUtils.createSeparator(columnWidths, "-");
389
+ let tableString = headerSeparator + "\n";
390
+ for (const [rowIndex, row] of this.rows.entries()) {
391
+ const { kind, key, value } = row;
392
+ if (kind === "own" || value instanceof _KeyValueASCIITable || value instanceof MultiColumnASCIITable || Array.isArray(value)) {
393
+ const keyString = ASCIITableUtils.centerText(
394
+ key,
395
+ columnWidths[0] + columnWidths[1] + 3
396
+ );
397
+ tableString += `| ${keyString} |
398
+ `;
399
+ tableString += rowSeparator + "\n";
400
+ let valueString = "";
401
+ if (value instanceof _KeyValueASCIITable) {
402
+ valueString = this.formatValue(
403
+ value,
404
+ tableWidth - 4,
405
+ canAutoAdjustWidthWhenPossible,
406
+ ""
407
+ );
408
+ } else if (value instanceof MultiColumnASCIITable) {
409
+ valueString = this.formatValue(
410
+ value,
411
+ tableWidth - 4,
412
+ canAutoAdjustWidthWhenPossible,
413
+ ""
414
+ );
415
+ } else if (Array.isArray(value)) {
416
+ valueString = this.formatValue(
417
+ value,
418
+ tableWidth - 4,
419
+ canAutoAdjustWidthWhenPossible,
420
+ ""
421
+ );
422
+ } else if (row.kind === "own") {
423
+ valueString = this.formatTableRowOnOwnRow(
424
+ value,
425
+ tableWidth - 4,
426
+ tableWidth
427
+ );
428
+ }
429
+ const valueLines = valueString.split("\n");
430
+ const paddedValueLines = valueLines.map((line) => {
431
+ const padding = padRight("", tableWidth - (0, import_string_width3.default)(line) - 4, " ");
432
+ return `| ${line}${padding} |`;
433
+ });
434
+ tableString += paddedValueLines.join("\n") + "\n";
435
+ tableString += headerSeparator + "\n";
436
+ } else {
437
+ const keyLines = ASCIITableUtils.wrapText(key, columnWidths[0]);
438
+ const valueLines = ASCIITableUtils.wrapText(
439
+ this.formatValue(
440
+ value,
441
+ columnWidths[1],
442
+ canAutoAdjustWidthWhenPossible,
443
+ ""
444
+ ),
445
+ columnWidths[1]
446
+ );
447
+ const maxLines = Math.max(keyLines.length, valueLines.length);
448
+ for (let i = 0; i < maxLines; i++) {
449
+ const keyLine = keyLines[i] || "";
450
+ const valueLine = valueLines[i] || "";
451
+ const keyPadding = " ".repeat(columnWidths[0] - (0, import_string_width3.default)(keyLine));
452
+ const valuePadding = " ".repeat(
453
+ columnWidths[1] - (0, import_string_width3.default)(valueLine)
454
+ );
455
+ tableString += `| ${keyLine}${keyPadding} | ${valueLine}${valuePadding} |
456
+ `;
457
+ if (i === maxLines - 1) {
458
+ if (rowIndex === this.rows.length - 1) {
459
+ tableString += headerSeparator + "\n";
460
+ } else {
461
+ tableString += rowSeparator + "\n";
462
+ }
463
+ }
464
+ }
465
+ }
466
+ }
467
+ return tableString.trim();
468
+ }
469
+ calculateColumnWidths(options = {}) {
470
+ const tableWidth = options.tableWidth || this.tableWidth;
471
+ const canAutoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? this.autoAdjustWidthWhenPossible;
472
+ const columnWidths = [0, 0];
473
+ for (const row of this.rows) {
474
+ const { key, value } = row;
475
+ const keyWidth = (0, import_string_width3.default)(key);
476
+ const maxKeyWidth = Math.floor((tableWidth - 7) / 2);
477
+ if (keyWidth > columnWidths[0]) {
478
+ columnWidths[0] = Math.min(keyWidth, maxKeyWidth);
479
+ columnWidths[1] = Math.max(0, tableWidth - columnWidths[0] - 7);
480
+ }
481
+ if (typeof value === "string") {
482
+ const valueWidth = Math.max(
483
+ ...value.split("\n").map((line) => (0, import_string_width3.default)(line))
484
+ );
485
+ if (valueWidth > columnWidths[1]) {
486
+ columnWidths[1] = Math.min(
487
+ valueWidth,
488
+ tableWidth - columnWidths[0] - 7
489
+ );
490
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
491
+ }
492
+ } else if (row.kind === "own") {
493
+ let valueWidth = 0;
494
+ if (isString(value)) {
495
+ valueWidth = Math.max(
496
+ ...value.split("\n").map((line) => (0, import_string_width3.default)(line))
497
+ );
498
+ }
499
+ if (valueWidth > columnWidths[1]) {
500
+ columnWidths[1] = Math.min(
501
+ valueWidth,
502
+ tableWidth - columnWidths[0] - 7
503
+ );
504
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
505
+ }
506
+ } else if (value instanceof _KeyValueASCIITable) {
507
+ let nestedTableColumnWidths = [];
508
+ if (canAutoAdjustWidthWhenPossible) {
509
+ const minWidth = value.getMinimumWidth();
510
+ const availableWidth2 = tableWidth - columnWidths[0] - 7;
511
+ const adjustedWidth = clamp(availableWidth2, minWidth, availableWidth2);
512
+ nestedTableColumnWidths = value.calculateColumnWidths({
513
+ tableWidth: adjustedWidth
514
+ });
515
+ } else {
516
+ nestedTableColumnWidths = value.calculateColumnWidths();
517
+ }
518
+ const nestedTableWidth = nestedTableColumnWidths.reduce((sum, width) => sum + width, 0) + nestedTableColumnWidths.length * 3 - 1;
519
+ const availableWidth = tableWidth - columnWidths[0] - 7;
520
+ if (nestedTableWidth > availableWidth) {
521
+ columnWidths[1] = availableWidth;
522
+ } else {
523
+ columnWidths[1] = Math.max(columnWidths[1], nestedTableWidth);
524
+ }
525
+ } else if (value instanceof MultiColumnASCIITable) {
526
+ let nestedTableColumnWidths = [];
527
+ if (canAutoAdjustWidthWhenPossible) {
528
+ const minWidth = value.getMinimumWidth();
529
+ const availableWidth2 = tableWidth - columnWidths[0] - 7;
530
+ const adjustedWidth = clamp(availableWidth2, minWidth, availableWidth2);
531
+ nestedTableColumnWidths = value.calculateColumnWidths({
532
+ tableWidth: adjustedWidth
533
+ });
534
+ } else {
535
+ nestedTableColumnWidths = value.calculateColumnWidths();
536
+ }
537
+ const nestedTableWidth = nestedTableColumnWidths.reduce((sum, width) => sum + width, 0) + nestedTableColumnWidths.length * 3 - 1;
538
+ const availableWidth = tableWidth - columnWidths[0] - 7;
539
+ if (nestedTableWidth > availableWidth) {
540
+ columnWidths[1] = availableWidth;
541
+ } else {
542
+ columnWidths[1] = Math.max(columnWidths[1], nestedTableWidth);
543
+ }
544
+ } else if (Array.isArray(value)) {
545
+ for (const nestedCell of value) {
546
+ const nestedKeyWidth = (0, import_string_width3.default)(nestedCell.key);
547
+ const maxNestedKeyWidth = Math.floor((tableWidth - 7) / 2);
548
+ if (nestedKeyWidth > columnWidths[0]) {
549
+ columnWidths[0] = Math.min(nestedKeyWidth, maxNestedKeyWidth);
550
+ columnWidths[1] = Math.max(0, tableWidth - columnWidths[0] - 7);
551
+ }
552
+ if (typeof nestedCell.value === "string") {
553
+ const nestedValueWidth = Math.max(
554
+ ...nestedCell.value.split("\n").map((line) => (0, import_string_width3.default)(line))
555
+ );
556
+ if (nestedValueWidth > columnWidths[1]) {
557
+ columnWidths[1] = Math.min(
558
+ nestedValueWidth,
559
+ tableWidth - columnWidths[0] - 7
560
+ );
561
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
562
+ }
563
+ }
564
+ }
565
+ }
566
+ }
567
+ return columnWidths;
568
+ }
569
+ formatValue(value, cellWidth, canAutoAdjustWidthWhenPossible, indent = "") {
570
+ if (typeof value === "string") {
571
+ return value;
572
+ } else if (typeof value === "number") {
573
+ return String(value);
574
+ } else if (typeof value === "boolean") {
575
+ return String(value);
576
+ } else if (value === null) {
577
+ return "null";
578
+ } else if (value === void 0) {
579
+ return "undefined";
580
+ } else if (value instanceof _KeyValueASCIITable) {
581
+ let nestedTableLines;
582
+ if (canAutoAdjustWidthWhenPossible) {
583
+ const minWidth = value.getMinimumWidth();
584
+ const adjustedWidth = clamp(cellWidth, minWidth, cellWidth);
585
+ nestedTableLines = value.toString({ tableWidth: adjustedWidth }).split("\n");
586
+ } else {
587
+ nestedTableLines = value.toString().split("\n");
588
+ }
589
+ const indentedLines = nestedTableLines.map((line) => `${indent}${line}`);
590
+ return indentedLines.join("\n");
591
+ } else if (value instanceof MultiColumnASCIITable) {
592
+ let nestedTableLines;
593
+ if (canAutoAdjustWidthWhenPossible) {
594
+ const minWidth = value.getMinimumWidth();
595
+ const adjustedWidth = clamp(cellWidth, minWidth, cellWidth);
596
+ nestedTableLines = value.toString({ tableWidth: adjustedWidth }).split("\n");
597
+ } else {
598
+ nestedTableLines = value.toString().split("\n");
599
+ }
600
+ const indentedLines = nestedTableLines.map((line) => `${indent}${line}`);
601
+ return indentedLines.join("\n");
602
+ } else if (Array.isArray(value)) {
603
+ const nestedValueLines = [];
604
+ for (const { key, value: nestedValue } of value) {
605
+ const formattedKey = `${indent}${key}:`;
606
+ const formattedValue = this.formatValue(
607
+ nestedValue,
608
+ cellWidth - indent.length - (0, import_string_width3.default)(key) - 2,
609
+ canAutoAdjustWidthWhenPossible,
610
+ `${indent}`
611
+ );
612
+ const wrappedSpacer = padRight("", 4, " ");
613
+ const wrappedValue = formattedValue.split("\n").map((line) => `${indent}${wrappedSpacer}${line}`);
614
+ nestedValueLines.push(formattedKey);
615
+ nestedValueLines.push(...wrappedValue);
616
+ nestedValueLines.push("");
617
+ }
618
+ return nestedValueLines.slice(0, -1).join("\n");
619
+ } else {
620
+ throw new TypeError("Invalid value type provided");
621
+ }
622
+ }
623
+ formatTableRowOnOwnRow(value, width, maxRowLength) {
624
+ const lines = value.split("\n");
625
+ const paddedLines = lines.map((line) => {
626
+ const wrappedLines = ASCIITableUtils.wrapText(line, maxRowLength - 4);
627
+ return wrappedLines.map((wrappedLine) => {
628
+ const padding = padRight(
629
+ "",
630
+ width - (0, import_string_width3.default)(wrappedLine) - 2,
631
+ " "
632
+ );
633
+ return `${wrappedLine}${padding}`;
634
+ }).join("\n");
635
+ });
636
+ return paddedLines.join("\n");
637
+ }
638
+ };
639
+
640
+ // src/lib/error-to-string.ts
641
+ function safeStringify(value) {
642
+ if (value === null || value === void 0) {
643
+ return String(value);
644
+ }
645
+ switch (typeof value) {
646
+ case "string":
647
+ return value;
648
+ case "number":
649
+ case "boolean":
650
+ case "bigint":
651
+ return String(value);
652
+ case "object":
653
+ return JSON.stringify(value);
654
+ case "function":
655
+ return "[Function]";
656
+ case "symbol":
657
+ return value.toString();
658
+ default:
659
+ return String(value);
660
+ }
661
+ }
662
+ function errorToString(error, maxRowLength = 80) {
663
+ const table = errorToASCIITable(error, maxRowLength);
664
+ return table.toString();
665
+ }
666
+ function errorToASCIITable(error, maxRowLength) {
667
+ const table = new KeyValueASCIITable({
668
+ tableWidth: maxRowLength,
669
+ autoAdjustWidthWhenPossible: true
670
+ });
671
+ if (error && typeof error === "object") {
672
+ const err = error;
673
+ table.addRow("Key", "Value");
674
+ if (err["message"]) {
675
+ table.addRow("Message", safeStringify(err["message"]));
676
+ }
677
+ if (err["name"]) {
678
+ table.addRow("Name", safeStringify(err["name"]));
679
+ }
680
+ if (err["code"]) {
681
+ table.addRow("Code", safeStringify(err["code"]));
682
+ }
683
+ if (err["errno"]) {
684
+ table.addRow("Errno", safeStringify(err["errno"]));
685
+ }
686
+ if (err["errPrefix"]) {
687
+ table.addRow("Prefix", safeStringify(err["errPrefix"]));
688
+ }
689
+ if (err["errType"]) {
690
+ table.addRow("errType", safeStringify(err["errType"]));
691
+ }
692
+ if (err["errCode"]) {
693
+ table.addRow("errCode", safeStringify(err["errCode"]));
694
+ }
695
+ if (err["additionalInfo"]) {
696
+ const additionalInfo = err["additionalInfo"];
697
+ const sensitiveFieldNames = err["sensitiveFieldNames"] || [];
698
+ for (const key in additionalInfo) {
699
+ if (sensitiveFieldNames.includes(key)) {
700
+ table.addRow(`AdditionalInfo.${key}`, "***");
701
+ } else {
702
+ const value = additionalInfo[key];
703
+ table.addRow(
704
+ `AdditionalInfo.${key}`,
705
+ stringifyValue(value, table, maxRowLength)
706
+ );
707
+ }
708
+ }
709
+ }
710
+ if (err["stack"]) {
711
+ table.addValueOnSeparateRow("Stack", safeStringify(err["stack"]));
712
+ }
713
+ }
714
+ return table;
715
+ }
716
+ function stringifyValue(value, table, maxRowLength) {
717
+ if (typeof value === "string") {
718
+ return value;
719
+ } else if (Array.isArray(value)) {
720
+ return value.map((item) => {
721
+ const result = stringifyValue(item, table, maxRowLength);
722
+ if (typeof result === "string") {
723
+ return result;
724
+ } else if (result instanceof KeyValueASCIITable) {
725
+ return result.toString();
726
+ } else {
727
+ return JSON.stringify(result);
728
+ }
729
+ }).join(", ");
730
+ } else if (typeof value === "object" && value !== null) {
731
+ if (value instanceof Error) {
732
+ return errorToASCIITable(value, maxRowLength - 4);
733
+ } else {
734
+ const entries = Object.entries(value).map(
735
+ ([key, val]) => ({
736
+ key,
737
+ value: stringifyValue(val, table, maxRowLength - 4)
738
+ })
739
+ );
740
+ return entries;
741
+ }
742
+ } else {
743
+ return String(value);
744
+ }
745
+ }
746
+
747
+ // src/lib/is-promise.ts
748
+ function isPromise(obj) {
749
+ return !!obj && (typeof obj === "object" || typeof obj === "function") && // @ts-expect-error - obj is checked to be object/function, then property access works at runtime
750
+ typeof obj["then"] === "function";
751
+ }
752
+
753
+ // src/lib/is-function.ts
754
+ function isFunction(value) {
755
+ return typeof value === "function" || value instanceof Function;
756
+ }
757
+
758
+ // src/lib/safe-handle-callback.ts
759
+ function safeHandleCallback(callbackName, callback, ...args) {
760
+ const handleError = (error) => {
761
+ if (typeof globalThis.dispatchEvent === "function") {
762
+ globalThis.dispatchEvent(
763
+ new ErrorEvent("reportError", {
764
+ error: new Error(
765
+ `Error in a callback ${callbackName}: ${DOUBLE_EOL}${errorToString(error)}`
766
+ )
767
+ })
768
+ );
769
+ }
770
+ };
771
+ if (isFunction(callback)) {
772
+ try {
773
+ const result = callback(...args);
774
+ if (isPromise(result)) {
775
+ result.catch((error) => {
776
+ handleError(error);
777
+ });
778
+ }
779
+ } catch (error) {
780
+ handleError(error);
781
+ }
782
+ } else {
783
+ handleError(
784
+ new Error(`Callback provided for ${callbackName} is not a function`)
785
+ );
786
+ }
787
+ }
788
+ async function safeHandleCallbackAndWait(callbackName, callback, ...args) {
789
+ const handleError = (error) => {
790
+ if (typeof globalThis.dispatchEvent === "function") {
791
+ globalThis.dispatchEvent(
792
+ new ErrorEvent("reportError", {
793
+ error: new Error(
794
+ `Error in a callback ${callbackName}: ${DOUBLE_EOL}${errorToString(error)}`
795
+ )
796
+ })
797
+ );
798
+ }
799
+ return { success: false, error };
800
+ };
801
+ if (isFunction(callback)) {
802
+ try {
803
+ const result = callback(...args);
804
+ if (isPromise(result)) {
805
+ const value = await result;
806
+ return { success: true, value };
807
+ } else {
808
+ return { success: true, value: result };
809
+ }
810
+ } catch (error) {
811
+ return handleError(error);
812
+ }
813
+ } else {
814
+ return handleError(
815
+ new Error(`Callback provided for ${callbackName} is not a function`)
816
+ );
817
+ }
818
+ }
819
+
820
+ // src/lib/event-emitter.ts
821
+ var EventEmitterProtected = class {
822
+ events;
823
+ constructor() {
824
+ this.events = /* @__PURE__ */ new Map();
825
+ }
826
+ /**
827
+ * Subscribe to an event
828
+ * @param event The event name to subscribe to
829
+ * @param callback The callback function to be called when the event is emitted
830
+ * @returns A function to unsubscribe from the event
831
+ */
832
+ on(event, callback) {
833
+ if (!this.events.has(event)) {
834
+ this.events.set(event, /* @__PURE__ */ new Set());
835
+ }
836
+ const callbacks = this.events.get(event);
837
+ if (callbacks) {
838
+ callbacks.add(callback);
839
+ }
840
+ return () => {
841
+ const callbacks2 = this.events.get(event);
842
+ if (callbacks2) {
843
+ callbacks2.delete(callback);
844
+ if (callbacks2.size === 0) {
845
+ this.events.delete(event);
846
+ }
847
+ }
848
+ };
849
+ }
850
+ /**
851
+ * Subscribe to an event once - automatically unsubscribes after first emission
852
+ * @param event The event name to subscribe to
853
+ * @param callback The callback function to be called when the event is emitted
854
+ * @returns A function to unsubscribe from the event before it's called
855
+ */
856
+ once(event, callback) {
857
+ const unsubscribe = this.on(event, (data) => {
858
+ unsubscribe();
859
+ return callback(data);
860
+ });
861
+ return unsubscribe;
862
+ }
863
+ /**
864
+ * Check if a specific callback is registered for an event.
865
+ * Note: For 'once' handlers, this will return true for the wrapper function, not the original callback.
866
+ * This means hasListener will return false when checking for the original callback of a 'once' subscription.
867
+ *
868
+ * @param event The event name to check
869
+ * @param callback The callback function to look for
870
+ * @returns true if the exact callback is registered, false otherwise
871
+ */
872
+ hasListener(event, callback) {
873
+ const callbacks = this.events.get(event);
874
+ return callbacks?.has(callback) ?? false;
875
+ }
876
+ /**
877
+ * Check if an event has any subscribers
878
+ * @param event The event name to check
879
+ * @returns true if the event has subscribers, false otherwise
880
+ */
881
+ hasListeners(event) {
882
+ const callbacks = this.events.get(event);
883
+ return callbacks !== void 0 && callbacks.size > 0;
884
+ }
885
+ /**
886
+ * Get the number of subscribers for an event
887
+ * @param event The event name to check
888
+ * @returns The number of subscribers
889
+ */
890
+ listenerCount(event) {
891
+ const callbacks = this.events.get(event);
892
+ return callbacks ? callbacks.size : 0;
893
+ }
894
+ /**
895
+ * Remove all event listeners
896
+ * @param event Optional event name. If not provided, removes all listeners for all events
897
+ */
898
+ clear(event) {
899
+ if (event) {
900
+ this.events.delete(event);
901
+ } else {
902
+ this.events.clear();
903
+ }
904
+ }
905
+ /**
906
+ * Emit an event with optional data
907
+ * This method is protected to allow only derived classes to trigger events.
908
+ * @param event The event name to emit
909
+ * @param data Optional data to pass to the event handlers
910
+ */
911
+ emit(event, data) {
912
+ const callbacks = this.events.get(event);
913
+ if (callbacks) {
914
+ for (const callback of callbacks) {
915
+ safeHandleCallback(`event handler for ${event}`, callback, data);
916
+ }
917
+ }
918
+ }
919
+ };
920
+ var EventEmitter = class extends EventEmitterProtected {
921
+ /**
922
+ * Emit an event with optional data
923
+ * This method is public, allowing any code with access to the emitter to trigger events.
924
+ * @param event The event name to emit
925
+ * @param data Optional data to pass to the event handlers
926
+ */
927
+ emit(event, data) {
928
+ super.emit(event, data);
929
+ }
930
+ };
931
+
932
+ // src/lib/unix-time-helpers.ts
933
+ function ms() {
934
+ return Date.now();
935
+ }
936
+
937
+ // src/lib/curly-brackets.ts
938
+ var CurlyBrackets = function(str = "", locals = {}, fallback = "(null)") {
939
+ if (!str.includes("{{")) {
940
+ return str;
941
+ }
942
+ const compiled = CurlyBrackets.compileTemplate(str, fallback);
943
+ return compiled(locals);
944
+ };
945
+ CurlyBrackets.compileTemplate = function(str, fallback = "(null)") {
946
+ const pattern = /(?:\\)?{{(\s*[\w.]+?)(?:\\)?\s*}}/g;
947
+ return (locals) => {
948
+ return str.replace(pattern, (match, p1) => {
949
+ if (typeof p1 !== "string") {
950
+ return match;
951
+ }
952
+ const hasLeadingEscape = match.startsWith("\\");
953
+ const hasEndingEscape = match.endsWith("\\}}");
954
+ const isFullyEscaped = hasLeadingEscape && hasEndingEscape;
955
+ if (isFullyEscaped) {
956
+ return match.slice(1, -3) + "}}";
957
+ }
958
+ if (hasLeadingEscape) {
959
+ return match.slice(1);
960
+ }
961
+ if (hasEndingEscape) {
962
+ return "{{" + p1.trim() + "}}";
963
+ }
964
+ const key = p1.trim();
965
+ const parts = key.split(".");
966
+ let replacement = locals;
967
+ for (const part of parts) {
968
+ if (replacement !== void 0 && replacement !== null && typeof replacement === "object" && part in replacement) {
969
+ replacement = replacement[part];
970
+ } else {
971
+ replacement = void 0;
972
+ break;
973
+ }
974
+ }
975
+ if (replacement === void 0 || replacement === null) {
976
+ return fallback;
977
+ }
978
+ return String(replacement);
979
+ });
980
+ };
981
+ };
982
+ CurlyBrackets.escape = function(str) {
983
+ return str.replace(/(\\)?{{/g, (match, backslash) => backslash ? match : "\\{{").replace(/(\\)?}}/g, (match, backslash) => backslash ? match : "\\}}");
984
+ };
985
+
986
+ // src/lib/is-number.ts
987
+ function isNumber(value) {
988
+ return typeof value === "number" && !isNaN(value);
989
+ }
990
+
991
+ // src/lib/logger/sinks/array.ts
992
+ var ArraySink = class {
993
+ logs = [];
994
+ transformer;
995
+ closed = false;
996
+ constructor(options) {
997
+ this.transformer = options?.transformer;
998
+ }
999
+ write(entry) {
1000
+ if (this.closed) {
1001
+ return;
1002
+ }
1003
+ if (this.transformer) {
1004
+ try {
1005
+ const transformed = this.transformer(entry);
1006
+ if (transformed !== false) {
1007
+ this.logs.push(transformed);
1008
+ return;
1009
+ }
1010
+ } catch {
1011
+ }
1012
+ }
1013
+ this.logs.push(entry);
1014
+ }
1015
+ /**
1016
+ * Clear all stored logs
1017
+ */
1018
+ clear() {
1019
+ this.logs = [];
1020
+ }
1021
+ /**
1022
+ * Get logs in a snapshot-friendly format for testing
1023
+ */
1024
+ getSnapshotFriendlyLogs() {
1025
+ return this.logs.map((log) => `${log.type}: ${log.message}`);
1026
+ }
1027
+ /**
1028
+ * Close the sink and stop accepting new logs
1029
+ */
1030
+ close() {
1031
+ this.closed = true;
1032
+ }
1033
+ };
1034
+
1035
+ // src/lib/logger/sinks/console.ts
1036
+ var import_date_fns = require("date-fns");
1037
+
1038
+ // src/lib/logger/types.ts
1039
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
1040
+ LogLevel2[LogLevel2["ERROR"] = 0] = "ERROR";
1041
+ LogLevel2[LogLevel2["WARN"] = 1] = "WARN";
1042
+ LogLevel2[LogLevel2["NOTICE"] = 2] = "NOTICE";
1043
+ LogLevel2[LogLevel2["SUCCESS"] = 3] = "SUCCESS";
1044
+ LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
1045
+ LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
1046
+ LogLevel2[LogLevel2["RAW"] = 99] = "RAW";
1047
+ return LogLevel2;
1048
+ })(LogLevel || {});
1049
+ function getLogLevel(type) {
1050
+ switch (type) {
1051
+ case "error":
1052
+ return 0 /* ERROR */;
1053
+ case "warn":
1054
+ return 1 /* WARN */;
1055
+ case "notice":
1056
+ return 2 /* NOTICE */;
1057
+ case "success":
1058
+ return 3 /* SUCCESS */;
1059
+ case "info":
1060
+ return 3 /* INFO */;
1061
+ case "debug":
1062
+ return 4 /* DEBUG */;
1063
+ case "raw":
1064
+ return 99 /* RAW */;
1065
+ }
1066
+ }
1067
+
1068
+ // src/lib/logger/utils/color.ts
1069
+ var import_chalk = __toESM(require("chalk"), 1);
1070
+ var browserColors = {
1071
+ error: "color: #a95450;",
1072
+ // red
1073
+ info: "color: #ffffff;",
1074
+ // white
1075
+ warn: "color: #f5f566;",
1076
+ // yellow
1077
+ success: "color: #56b97f;",
1078
+ // green
1079
+ notice: "color: #5883bf;",
1080
+ // blue
1081
+ debug: "color: #808080;"
1082
+ // gray
1083
+ };
1084
+ var chalkColors = {
1085
+ error: "red",
1086
+ info: "white",
1087
+ warn: "yellow",
1088
+ success: "green",
1089
+ notice: "blue",
1090
+ debug: "gray"
1091
+ };
1092
+ function colorize(type, text) {
1093
+ const isBrowser = typeof globalThis !== "undefined" && "window" in globalThis && "document" in globalThis;
1094
+ if (isBrowser) {
1095
+ return {
1096
+ coloredText: `%c${text}`,
1097
+ style: browserColors[type]
1098
+ };
1099
+ } else {
1100
+ const colorName = chalkColors[type];
1101
+ const chalkColor = import_chalk.default[colorName];
1102
+ return {
1103
+ coloredText: chalkColor(text)
1104
+ };
1105
+ }
1106
+ }
1107
+
1108
+ // src/lib/logger/sinks/console.ts
1109
+ var ConsoleSink = class {
1110
+ colors;
1111
+ timestamps;
1112
+ typeLabels;
1113
+ closed = false;
1114
+ muted;
1115
+ minLevel;
1116
+ constructor(options = {}) {
1117
+ this.colors = options.colors ?? true;
1118
+ this.timestamps = options.timestamps ?? false;
1119
+ this.typeLabels = options.typeLabels ?? false;
1120
+ this.muted = options.muted ?? false;
1121
+ this.minLevel = options.minLevel ?? 3 /* INFO */;
1122
+ }
1123
+ write(entry) {
1124
+ if (this.closed || this.muted) {
1125
+ return;
1126
+ }
1127
+ if (entry.type === "raw") {
1128
+ console.log(entry.message);
1129
+ return;
1130
+ }
1131
+ const logLevel = getLogLevel(entry.type);
1132
+ if (logLevel > this.minLevel) {
1133
+ return;
1134
+ }
1135
+ let formattedMessage = "";
1136
+ if (this.timestamps) {
1137
+ const formattedTimestamp = (0, import_date_fns.format)(entry.timestamp, "MM-dd-yyyy HH:mm:ss");
1138
+ formattedMessage = "[" + formattedTimestamp + "] ";
1139
+ }
1140
+ if (this.typeLabels) {
1141
+ formattedMessage += `[${entry.type.toUpperCase()}] `;
1142
+ }
1143
+ if (entry.serviceName) {
1144
+ formattedMessage += `[${entry.serviceName}] `;
1145
+ }
1146
+ if (entry.entityName) {
1147
+ formattedMessage += `[${entry.entityName}] `;
1148
+ }
1149
+ formattedMessage += entry.message;
1150
+ if (this.colors) {
1151
+ const { coloredText, style } = colorize(entry.type, formattedMessage);
1152
+ switch (entry.type) {
1153
+ case "error":
1154
+ if (style) {
1155
+ console.error(coloredText, style);
1156
+ } else {
1157
+ console.error(coloredText);
1158
+ }
1159
+ break;
1160
+ case "info":
1161
+ if (style) {
1162
+ console.info(coloredText, style);
1163
+ } else {
1164
+ console.info(coloredText);
1165
+ }
1166
+ break;
1167
+ case "warn":
1168
+ if (style) {
1169
+ console.warn(coloredText, style);
1170
+ } else {
1171
+ console.warn(coloredText);
1172
+ }
1173
+ break;
1174
+ case "success":
1175
+ case "notice":
1176
+ case "debug":
1177
+ if (style) {
1178
+ console.log(coloredText, style);
1179
+ } else {
1180
+ console.log(coloredText);
1181
+ }
1182
+ break;
1183
+ }
1184
+ } else {
1185
+ switch (entry.type) {
1186
+ case "error":
1187
+ console.error(formattedMessage);
1188
+ break;
1189
+ case "info":
1190
+ console.info(formattedMessage);
1191
+ break;
1192
+ case "warn":
1193
+ console.warn(formattedMessage);
1194
+ break;
1195
+ case "success":
1196
+ case "notice":
1197
+ case "debug":
1198
+ console.log(formattedMessage);
1199
+ break;
1200
+ }
1201
+ }
1202
+ }
1203
+ /**
1204
+ * Set the minimum log level for this sink
1205
+ */
1206
+ setMinLevel(level) {
1207
+ this.minLevel = level;
1208
+ }
1209
+ /**
1210
+ * Get the current minimum log level
1211
+ */
1212
+ getMinLevel() {
1213
+ return this.minLevel;
1214
+ }
1215
+ /**
1216
+ * Mute the sink to stop writing logs to console
1217
+ */
1218
+ mute() {
1219
+ this.muted = true;
1220
+ }
1221
+ /**
1222
+ * Unmute the sink to resume writing logs to console
1223
+ */
1224
+ unmute() {
1225
+ this.muted = false;
1226
+ }
1227
+ /**
1228
+ * Check if the sink is currently muted
1229
+ */
1230
+ isMuted() {
1231
+ return this.muted;
1232
+ }
1233
+ /**
1234
+ * Close the sink and stop accepting new logs
1235
+ */
1236
+ close() {
1237
+ this.closed = true;
1238
+ }
1239
+ };
1240
+
1241
+ // src/lib/logger/utils/redaction.ts
1242
+ var import_datamask = __toESM(require("datamask"), 1);
1243
+
1244
+ // src/lib/deep-clone.ts
1245
+ function deepClone(obj) {
1246
+ return cloneInternal(obj, /* @__PURE__ */ new WeakMap());
1247
+ }
1248
+ function cloneInternal(obj, seen) {
1249
+ if (obj === null || typeof obj !== "object") {
1250
+ return obj;
1251
+ }
1252
+ if (seen.has(obj)) {
1253
+ return seen.get(obj);
1254
+ }
1255
+ if (obj instanceof Date) {
1256
+ return new Date(obj);
1257
+ }
1258
+ if (obj instanceof RegExp) {
1259
+ const flags = obj.flags;
1260
+ const cloned2 = new RegExp(obj.source, flags);
1261
+ cloned2.lastIndex = obj.lastIndex;
1262
+ return cloned2;
1263
+ }
1264
+ if (obj instanceof Map) {
1265
+ const cloned2 = /* @__PURE__ */ new Map();
1266
+ seen.set(obj, cloned2);
1267
+ for (const [key, value] of obj) {
1268
+ cloned2.set(cloneInternal(key, seen), cloneInternal(value, seen));
1269
+ }
1270
+ return cloned2;
1271
+ }
1272
+ if (obj instanceof Set) {
1273
+ const cloned2 = /* @__PURE__ */ new Set();
1274
+ seen.set(obj, cloned2);
1275
+ for (const value of obj) {
1276
+ cloned2.add(cloneInternal(value, seen));
1277
+ }
1278
+ return cloned2;
1279
+ }
1280
+ if (ArrayBuffer.isView(obj) && !(obj instanceof DataView)) {
1281
+ const typedArray = obj;
1282
+ const cloned2 = typedArray.slice();
1283
+ return cloned2;
1284
+ }
1285
+ if (Array.isArray(obj)) {
1286
+ const cloned2 = [];
1287
+ seen.set(obj, cloned2);
1288
+ for (const item of obj) {
1289
+ cloned2.push(cloneInternal(item, seen));
1290
+ }
1291
+ return cloned2;
1292
+ }
1293
+ const cloned = {};
1294
+ seen.set(obj, cloned);
1295
+ for (const key in obj) {
1296
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1297
+ cloned[key] = cloneInternal(obj[key], seen);
1298
+ }
1299
+ }
1300
+ return cloned;
1301
+ }
1302
+
1303
+ // src/lib/logger/utils/redaction.ts
1304
+ var defaultRedactFunction = (_keyName, value) => {
1305
+ if (typeof value === "string") {
1306
+ return import_datamask.default.string(value, "*", 60);
1307
+ }
1308
+ return "***REDACTED***";
1309
+ };
1310
+ function setNestedValue(obj, path, value) {
1311
+ const parts = path.split(".");
1312
+ let current = obj;
1313
+ for (let i = 0; i < parts.length - 1; i++) {
1314
+ const part = parts[i];
1315
+ const next = current[part];
1316
+ if (next === void 0 || next === null || typeof next !== "object") {
1317
+ return;
1318
+ }
1319
+ current = next;
1320
+ }
1321
+ const lastPart = parts[parts.length - 1];
1322
+ if (lastPart !== void 0 && lastPart in current) {
1323
+ current[lastPart] = value;
1324
+ }
1325
+ }
1326
+ function getNestedValue(obj, path) {
1327
+ const parts = path.split(".");
1328
+ let current = obj;
1329
+ for (const part of parts) {
1330
+ if (current === void 0 || current === null || typeof current !== "object" || !(part in current)) {
1331
+ return void 0;
1332
+ }
1333
+ current = current[part];
1334
+ }
1335
+ return current;
1336
+ }
1337
+ function applyRedaction(params, redactedKeys, redactFunction) {
1338
+ if (!redactedKeys || redactedKeys.length === 0) {
1339
+ return params;
1340
+ }
1341
+ const redactFn = redactFunction || defaultRedactFunction;
1342
+ const redactedParams = deepClone(params);
1343
+ for (const key of redactedKeys) {
1344
+ if (key.includes(".")) {
1345
+ const value = getNestedValue(redactedParams, key);
1346
+ if (value !== void 0) {
1347
+ const redactedValue = redactFn(key, value);
1348
+ setNestedValue(redactedParams, key, redactedValue);
1349
+ }
1350
+ } else {
1351
+ if (key in redactedParams) {
1352
+ redactedParams[key] = redactFn(key, redactedParams[key]);
1353
+ }
1354
+ }
1355
+ }
1356
+ return redactedParams;
1357
+ }
1358
+
1359
+ // src/lib/logger/utils/error-object.ts
1360
+ function prepareErrorObjectLog(prefix, error) {
1361
+ prefix = prefix.trim();
1362
+ let prefixLine = "";
1363
+ if (prefix.length > 0) {
1364
+ prefixLine = prefix + ": " + DOUBLE_EOL;
1365
+ }
1366
+ return prefixLine + errorToString(error);
1367
+ }
1368
+
1369
+ // src/lib/logger/logger-service.ts
1370
+ var LoggerService = class _LoggerService {
1371
+ handleLog;
1372
+ serviceName;
1373
+ entityName;
1374
+ constructor(handleLog, serviceName, entityName) {
1375
+ this.handleLog = handleLog;
1376
+ this.serviceName = serviceName;
1377
+ this.entityName = entityName;
1378
+ }
1379
+ /**
1380
+ * Create a scoped logger for a specific entity within this service
1381
+ */
1382
+ entity(entityName) {
1383
+ return new _LoggerService(this.handleLog, this.serviceName, entityName);
1384
+ }
1385
+ /**
1386
+ * Log an error message
1387
+ */
1388
+ error(message, options) {
1389
+ this.handleLog("error", message, {
1390
+ ...options ?? {},
1391
+ serviceName: this.serviceName,
1392
+ entityName: this.entityName
1393
+ });
1394
+ }
1395
+ /**
1396
+ * Log an error object with optional prefix
1397
+ */
1398
+ errorObject(prefix, error, options) {
1399
+ const message = prepareErrorObjectLog(prefix, error);
1400
+ this.handleLog("error", message, {
1401
+ ...options ?? {},
1402
+ serviceName: this.serviceName,
1403
+ entityName: this.entityName,
1404
+ error
1405
+ });
1406
+ }
1407
+ /**
1408
+ * Log an informational message
1409
+ */
1410
+ info(message, options) {
1411
+ this.handleLog("info", message, {
1412
+ ...options ?? {},
1413
+ serviceName: this.serviceName,
1414
+ entityName: this.entityName
1415
+ });
1416
+ }
1417
+ /**
1418
+ * Log a warning message
1419
+ */
1420
+ warn(message, options) {
1421
+ this.handleLog("warn", message, {
1422
+ ...options ?? {},
1423
+ serviceName: this.serviceName,
1424
+ entityName: this.entityName
1425
+ });
1426
+ }
1427
+ /**
1428
+ * Log a success message
1429
+ */
1430
+ success(message, options) {
1431
+ this.handleLog("success", message, {
1432
+ ...options ?? {},
1433
+ serviceName: this.serviceName,
1434
+ entityName: this.entityName
1435
+ });
1436
+ }
1437
+ /**
1438
+ * Log a notice message
1439
+ */
1440
+ notice(message, options) {
1441
+ this.handleLog("notice", message, {
1442
+ ...options ?? {},
1443
+ serviceName: this.serviceName,
1444
+ entityName: this.entityName
1445
+ });
1446
+ }
1447
+ /**
1448
+ * Log a debug message
1449
+ */
1450
+ debug(message, options) {
1451
+ this.handleLog("debug", message, {
1452
+ ...options ?? {},
1453
+ serviceName: this.serviceName,
1454
+ entityName: this.entityName
1455
+ });
1456
+ }
1457
+ /**
1458
+ * Log a raw message without any formatting
1459
+ */
1460
+ raw(message, options) {
1461
+ this.handleLog("raw", message, {
1462
+ ...options ?? {},
1463
+ serviceName: this.serviceName,
1464
+ entityName: this.entityName
1465
+ });
1466
+ }
1467
+ };
1468
+
1469
+ // src/lib/logger/sinks/file.ts
1470
+ var import_fs = __toESM(require("fs"), 1);
1471
+ var FileSinkError = class extends Error {
1472
+ constructor(message, cause) {
1473
+ super(message);
1474
+ this.cause = cause;
1475
+ this.name = "FileSinkError";
1476
+ }
1477
+ };
1478
+ var FileSink = class {
1479
+ logDir;
1480
+ basename;
1481
+ maxSizeMB;
1482
+ jsonFormat;
1483
+ maxRetries;
1484
+ minLevel;
1485
+ onError;
1486
+ logFileStream;
1487
+ currentLogFile;
1488
+ currentLogSize = 0;
1489
+ writeQueue = [];
1490
+ isInitialized = false;
1491
+ initPromise;
1492
+ isProcessing = false;
1493
+ lastError;
1494
+ consecutiveFailures = 0;
1495
+ totalEntriesWritten = 0;
1496
+ totalEntriesFailed = 0;
1497
+ closing = false;
1498
+ closed = false;
1499
+ closeTimeoutMS;
1500
+ constructor(options) {
1501
+ this.logDir = options.logDir;
1502
+ this.basename = options.basename;
1503
+ this.maxSizeMB = options.maxSizeMB ?? 10;
1504
+ this.jsonFormat = options.jsonFormat ?? false;
1505
+ this.maxRetries = options.maxRetries ?? 3;
1506
+ this.closeTimeoutMS = options.closeTimeoutMS ?? 3e4;
1507
+ this.minLevel = options.minLevel ?? 3 /* INFO */;
1508
+ this.onError = options.onError;
1509
+ this.initPromise = this.initialize();
1510
+ }
1511
+ write(entry) {
1512
+ if (this.closing || this.closed) {
1513
+ return;
1514
+ }
1515
+ if (entry.type !== "raw") {
1516
+ const logLevel = getLogLevel(entry.type);
1517
+ if (logLevel > this.minLevel) {
1518
+ return;
1519
+ }
1520
+ }
1521
+ this.writeQueue.push({ entry, attempts: 0 });
1522
+ if (this.isInitialized) {
1523
+ void this.processQueue();
1524
+ } else if (this.initPromise) {
1525
+ void this.initPromise.then(() => this.processQueue());
1526
+ }
1527
+ }
1528
+ /**
1529
+ * Set the minimum log level for this sink
1530
+ */
1531
+ setMinLevel(level) {
1532
+ this.minLevel = level;
1533
+ }
1534
+ /**
1535
+ * Get the current minimum log level
1536
+ */
1537
+ getMinLevel() {
1538
+ return this.minLevel;
1539
+ }
1540
+ /**
1541
+ * Get current health status of the sink
1542
+ */
1543
+ getHealth() {
1544
+ return {
1545
+ isHealthy: this.consecutiveFailures === 0 && this.isInitialized,
1546
+ queueSize: this.writeQueue.length,
1547
+ lastError: this.lastError,
1548
+ consecutiveFailures: this.consecutiveFailures,
1549
+ isInitialized: this.isInitialized
1550
+ };
1551
+ }
1552
+ /**
1553
+ * Flush all pending writes and wait for completion
1554
+ * Returns statistics about the flush operation
1555
+ * @param timeoutMS Maximum time to wait in milliseconds (default: 30000ms / 30s)
1556
+ */
1557
+ async flush(timeoutMS = 3e4) {
1558
+ if (this.initPromise) {
1559
+ await this.initPromise;
1560
+ }
1561
+ const startWritten = this.totalEntriesWritten;
1562
+ const startFailed = this.totalEntriesFailed;
1563
+ const startTime = Date.now();
1564
+ while (this.writeQueue.length > 0 || this.isProcessing) {
1565
+ if (Date.now() - startTime > timeoutMS) {
1566
+ const entriesWritten2 = this.totalEntriesWritten - startWritten;
1567
+ const entriesFailed2 = this.totalEntriesFailed - startFailed;
1568
+ return {
1569
+ success: false,
1570
+ entriesWritten: entriesWritten2,
1571
+ entriesFailed: entriesFailed2,
1572
+ timedOut: true
1573
+ };
1574
+ }
1575
+ await new Promise((resolve) => setTimeout(resolve, 10));
1576
+ }
1577
+ const entriesWritten = this.totalEntriesWritten - startWritten;
1578
+ const entriesFailed = this.totalEntriesFailed - startFailed;
1579
+ return {
1580
+ success: entriesFailed === 0,
1581
+ entriesWritten,
1582
+ entriesFailed,
1583
+ timedOut: false
1584
+ };
1585
+ }
1586
+ /**
1587
+ * Close the log file and wait for all pending writes
1588
+ */
1589
+ async close() {
1590
+ this.closing = true;
1591
+ const startTime = Date.now();
1592
+ if (this.initPromise) {
1593
+ let timeoutHandle;
1594
+ const timeoutSentinel = { timedOut: true };
1595
+ try {
1596
+ const timeoutPromise = new Promise(
1597
+ (resolve) => {
1598
+ timeoutHandle = setTimeout(
1599
+ () => resolve(timeoutSentinel),
1600
+ this.closeTimeoutMS
1601
+ );
1602
+ }
1603
+ );
1604
+ const result = await Promise.race([
1605
+ this.initPromise.then(() => void 0),
1606
+ timeoutPromise
1607
+ ]);
1608
+ if (result === timeoutSentinel) {
1609
+ Promise.resolve(this.initPromise).catch(() => {
1610
+ });
1611
+ }
1612
+ } finally {
1613
+ if (timeoutHandle) {
1614
+ clearTimeout(timeoutHandle);
1615
+ }
1616
+ }
1617
+ }
1618
+ while (this.writeQueue.length > 0 || this.isProcessing) {
1619
+ if (Date.now() - startTime > this.closeTimeoutMS) {
1620
+ break;
1621
+ }
1622
+ await new Promise((resolve) => setTimeout(resolve, 10));
1623
+ }
1624
+ this.closed = true;
1625
+ if (this.logFileStream) {
1626
+ return new Promise((resolve) => {
1627
+ if (!this.logFileStream) {
1628
+ return resolve();
1629
+ }
1630
+ this.logFileStream.end(() => {
1631
+ this.logFileStream = void 0;
1632
+ resolve();
1633
+ });
1634
+ });
1635
+ }
1636
+ }
1637
+ /**
1638
+ * Initialize the file sink asynchronously
1639
+ */
1640
+ async initialize() {
1641
+ try {
1642
+ await import_fs.promises.mkdir(this.logDir, { recursive: true });
1643
+ await this.setupLogFile();
1644
+ this.isInitialized = true;
1645
+ await this.processQueue();
1646
+ } catch {
1647
+ }
1648
+ }
1649
+ /**
1650
+ * Process the write queue
1651
+ * Processes entries one at a time with retry logic
1652
+ */
1653
+ async processQueue() {
1654
+ if (this.isProcessing || this.closed || this.writeQueue.length === 0) {
1655
+ return;
1656
+ }
1657
+ this.isProcessing = true;
1658
+ try {
1659
+ while (this.writeQueue.length > 0) {
1660
+ const queuedEntry = this.writeQueue.shift();
1661
+ if (!queuedEntry) {
1662
+ break;
1663
+ }
1664
+ try {
1665
+ await this.writeEntry(queuedEntry.entry);
1666
+ this.consecutiveFailures = 0;
1667
+ this.totalEntriesWritten++;
1668
+ } catch (error) {
1669
+ const err = error instanceof Error ? error : new Error(String(error));
1670
+ this.lastError = err;
1671
+ this.consecutiveFailures++;
1672
+ const willRetry = queuedEntry.attempts < this.maxRetries;
1673
+ if (this.onError) {
1674
+ try {
1675
+ this.onError(
1676
+ err,
1677
+ queuedEntry.entry,
1678
+ queuedEntry.attempts + 1,
1679
+ willRetry
1680
+ );
1681
+ } catch {
1682
+ }
1683
+ }
1684
+ if (willRetry) {
1685
+ queuedEntry.attempts++;
1686
+ this.writeQueue.push(queuedEntry);
1687
+ } else {
1688
+ this.totalEntriesFailed++;
1689
+ }
1690
+ }
1691
+ }
1692
+ } finally {
1693
+ this.isProcessing = false;
1694
+ }
1695
+ }
1696
+ /**
1697
+ * Write a single entry to the file
1698
+ * If stream is broken, it will be recreated on next attempt
1699
+ */
1700
+ async writeEntry(entry) {
1701
+ if (this.closed) {
1702
+ throw new FileSinkError("Cannot write to closed sink");
1703
+ }
1704
+ if (!this.logFileStream) {
1705
+ await this.setupLogFile();
1706
+ }
1707
+ if (!this.logFileStream) {
1708
+ throw new FileSinkError("No log file stream available");
1709
+ }
1710
+ await this.rotateIfNeeded();
1711
+ const messageToWrite = this.formatEntry(entry);
1712
+ const messageBytes = Buffer.byteLength(messageToWrite, "utf8");
1713
+ const maxSizeBytes = this.maxSizeMB * 1024 * 1024;
1714
+ if (this.currentLogSize + messageBytes > maxSizeBytes) {
1715
+ await this.rotateFile();
1716
+ }
1717
+ return new Promise((resolve, reject) => {
1718
+ if (!this.logFileStream) {
1719
+ return resolve();
1720
+ }
1721
+ this.logFileStream.write(messageToWrite, (err) => {
1722
+ if (err) {
1723
+ this.destroyStream();
1724
+ reject(new FileSinkError("Error writing to log file", err));
1725
+ } else {
1726
+ this.currentLogSize += messageBytes;
1727
+ resolve();
1728
+ }
1729
+ });
1730
+ });
1731
+ }
1732
+ /**
1733
+ * Format a log entry for file output
1734
+ */
1735
+ formatEntry(entry) {
1736
+ let formatted;
1737
+ if (this.jsonFormat) {
1738
+ formatted = JSON.stringify({
1739
+ timestamp: entry.timestamp,
1740
+ type: entry.type,
1741
+ serviceName: entry.serviceName,
1742
+ entityName: entry.entityName,
1743
+ message: entry.message,
1744
+ params: entry.redactedParams
1745
+ // Use redacted params for file output
1746
+ });
1747
+ } else {
1748
+ let text = "";
1749
+ if (entry.type !== "raw") {
1750
+ text = `[${entry.type}] `;
1751
+ if (entry.serviceName) {
1752
+ text += `[${entry.serviceName}] `;
1753
+ }
1754
+ if (entry.entityName) {
1755
+ text += `[${entry.entityName}] `;
1756
+ }
1757
+ }
1758
+ text += entry.message;
1759
+ formatted = text;
1760
+ }
1761
+ return formatted + "\n";
1762
+ }
1763
+ /**
1764
+ * Setup the log file
1765
+ */
1766
+ async setupLogFile() {
1767
+ const currentDate = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1768
+ const currentLogFile = `${this.logDir}/${this.basename}-${currentDate}.log`;
1769
+ try {
1770
+ await import_fs.promises.mkdir(this.logDir, { recursive: true });
1771
+ try {
1772
+ await import_fs.promises.access(currentLogFile);
1773
+ } catch {
1774
+ await import_fs.promises.writeFile(currentLogFile, "", { flag: "a" });
1775
+ }
1776
+ this.logFileStream = import_fs.default.createWriteStream(currentLogFile, { flags: "a" });
1777
+ this.currentLogFile = currentLogFile;
1778
+ this.logFileStream.on("error", () => {
1779
+ this.destroyStream();
1780
+ });
1781
+ try {
1782
+ const stats = await import_fs.promises.stat(currentLogFile);
1783
+ this.currentLogSize = stats.size;
1784
+ } catch {
1785
+ this.currentLogSize = 0;
1786
+ }
1787
+ const maxSizeBytes = this.maxSizeMB * 1024 * 1024;
1788
+ if (this.currentLogSize >= maxSizeBytes) {
1789
+ await this.rotateFile();
1790
+ }
1791
+ } catch (error) {
1792
+ throw new FileSinkError(
1793
+ `Failed to setup log file: ${currentLogFile}`,
1794
+ error
1795
+ );
1796
+ }
1797
+ }
1798
+ /**
1799
+ * Destroy the current stream
1800
+ */
1801
+ destroyStream() {
1802
+ if (this.logFileStream) {
1803
+ try {
1804
+ this.logFileStream.destroy();
1805
+ } catch {
1806
+ } finally {
1807
+ this.logFileStream = void 0;
1808
+ }
1809
+ }
1810
+ }
1811
+ /**
1812
+ * Rotate log file if needed based on size or date
1813
+ */
1814
+ async rotateIfNeeded() {
1815
+ if (!this.logFileStream || !this.currentLogFile) {
1816
+ return;
1817
+ }
1818
+ const currentDate = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1819
+ const expectedFile = `${this.logDir}/${this.basename}-${currentDate}.log`;
1820
+ if (this.currentLogFile !== expectedFile) {
1821
+ await this.setupLogFile();
1822
+ return;
1823
+ }
1824
+ const maxSizeBytes = this.maxSizeMB * 1024 * 1024;
1825
+ if (this.currentLogSize >= maxSizeBytes) {
1826
+ await this.rotateFile();
1827
+ }
1828
+ }
1829
+ /**
1830
+ * Rotate the current log file
1831
+ * Queue processing pauses during rotation, then resumes
1832
+ */
1833
+ async rotateFile() {
1834
+ if (!this.logFileStream || !this.currentLogFile) {
1835
+ return;
1836
+ }
1837
+ const currentDate = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1838
+ await new Promise((resolve) => {
1839
+ if (!this.logFileStream) {
1840
+ return resolve();
1841
+ }
1842
+ this.logFileStream.end(() => {
1843
+ this.logFileStream = void 0;
1844
+ resolve();
1845
+ });
1846
+ });
1847
+ const timestamp = Math.floor(Date.now() / 1e3);
1848
+ const rotatedFile = `${this.logDir}/${this.basename}-${currentDate}-${timestamp}.log`;
1849
+ try {
1850
+ await import_fs.promises.rename(this.currentLogFile, rotatedFile);
1851
+ } catch (error) {
1852
+ throw new FileSinkError(
1853
+ `Error rotating log file from ${this.currentLogFile} to ${rotatedFile}`,
1854
+ error
1855
+ );
1856
+ }
1857
+ await this.setupLogFile();
1858
+ }
1859
+ };
1860
+
1861
+ // src/lib/logger/sinks/named-pipe.ts
1862
+ var fs2 = __toESM(require("fs"), 1);
1863
+ var import_fs2 = require("fs");
1864
+ var os = __toESM(require("os"), 1);
1865
+ var PipeErrorType = /* @__PURE__ */ ((PipeErrorType2) => {
1866
+ PipeErrorType2["WRITE"] = "write";
1867
+ PipeErrorType2["CLOSE"] = "close";
1868
+ PipeErrorType2["NOT_FOUND"] = "not_found";
1869
+ PipeErrorType2["NOT_A_PIPE"] = "not_a_pipe";
1870
+ PipeErrorType2["PERMISSION"] = "permission";
1871
+ PipeErrorType2["UNSUPPORTED_PLATFORM"] = "unsupported_platform";
1872
+ return PipeErrorType2;
1873
+ })(PipeErrorType || {});
1874
+ var NamedPipeSink = class {
1875
+ pipePath;
1876
+ jsonFormat;
1877
+ onError;
1878
+ formatter;
1879
+ pipeStream;
1880
+ writeQueue = [];
1881
+ isInitialized = false;
1882
+ _isReconnecting = false;
1883
+ initPromise;
1884
+ closing = false;
1885
+ closed = false;
1886
+ closeTimeoutMS;
1887
+ constructor(options) {
1888
+ this.pipePath = options.pipePath;
1889
+ this.jsonFormat = options.jsonFormat ?? false;
1890
+ this.onError = options.onError;
1891
+ this.formatter = options.formatter;
1892
+ this.closeTimeoutMS = options.closeTimeoutMS ?? 3e4;
1893
+ this.initPromise = this.initializePipe();
1894
+ }
1895
+ write(entry) {
1896
+ if (this.closing || this.closed) {
1897
+ return;
1898
+ }
1899
+ if (!this.isInitialized) {
1900
+ this.writeQueue.push(entry);
1901
+ return;
1902
+ }
1903
+ this.writeEntry(entry);
1904
+ }
1905
+ /**
1906
+ * Attempt to reconnect to the named pipe.
1907
+ * Useful when the pipe reader restarts or after a temporary error.
1908
+ * Queued writes during the outage will be flushed on successful reconnection.
1909
+ */
1910
+ get isReconnecting() {
1911
+ return this._isReconnecting;
1912
+ }
1913
+ async reconnect() {
1914
+ if (this._isReconnecting) {
1915
+ await this.initPromise;
1916
+ return { success: false, reason: "already_reconnecting" };
1917
+ }
1918
+ this._isReconnecting = true;
1919
+ try {
1920
+ if (this.pipeStream && !this.pipeStream.destroyed) {
1921
+ this.pipeStream.end();
1922
+ this.pipeStream = void 0;
1923
+ }
1924
+ this.isInitialized = false;
1925
+ this.initPromise = this.initializePipe();
1926
+ await this.initPromise;
1927
+ if (this.isInitialized) {
1928
+ return { success: true };
1929
+ } else {
1930
+ return {
1931
+ success: false,
1932
+ reason: "error",
1933
+ error: new Error("Failed to initialize pipe connection")
1934
+ };
1935
+ }
1936
+ } finally {
1937
+ this._isReconnecting = false;
1938
+ }
1939
+ }
1940
+ async close() {
1941
+ this.closing = true;
1942
+ let timeoutHandle;
1943
+ const timeoutSentinel = { timedOut: true };
1944
+ try {
1945
+ const timeoutPromise = new Promise((resolve) => {
1946
+ timeoutHandle = setTimeout(
1947
+ () => resolve(timeoutSentinel),
1948
+ this.closeTimeoutMS
1949
+ );
1950
+ });
1951
+ const result = await Promise.race([
1952
+ this.initPromise.then(() => void 0),
1953
+ timeoutPromise
1954
+ ]);
1955
+ if (result === timeoutSentinel) {
1956
+ Promise.resolve(this.initPromise).catch(() => {
1957
+ });
1958
+ }
1959
+ } finally {
1960
+ if (timeoutHandle) {
1961
+ clearTimeout(timeoutHandle);
1962
+ }
1963
+ }
1964
+ this.closed = true;
1965
+ if (this.pipeStream && !this.pipeStream.destroyed) {
1966
+ return new Promise((resolve) => {
1967
+ try {
1968
+ this.pipeStream?.end(() => {
1969
+ this.pipeStream = void 0;
1970
+ resolve();
1971
+ });
1972
+ } catch (error) {
1973
+ this.handleError(
1974
+ "close" /* CLOSE */,
1975
+ error instanceof Error ? error : new Error(String(error))
1976
+ );
1977
+ resolve();
1978
+ }
1979
+ });
1980
+ }
1981
+ }
1982
+ /**
1983
+ * Initialize the named pipe connection
1984
+ */
1985
+ async initializePipe() {
1986
+ const platform2 = os.platform();
1987
+ if (platform2 !== "linux" && platform2 !== "darwin") {
1988
+ this.handleError(
1989
+ "unsupported_platform" /* UNSUPPORTED_PLATFORM */,
1990
+ new Error(
1991
+ `Named pipes are only supported on Linux and macOS, current platform: ${platform2}`
1992
+ )
1993
+ );
1994
+ return;
1995
+ }
1996
+ try {
1997
+ const stats = await import_fs2.promises.stat(this.pipePath);
1998
+ if (!stats.isFIFO()) {
1999
+ this.handleError(
2000
+ "not_a_pipe" /* NOT_A_PIPE */,
2001
+ new Error(`${this.pipePath} exists but is not a named pipe (FIFO)`)
2002
+ );
2003
+ return;
2004
+ }
2005
+ this.pipeStream = fs2.createWriteStream(this.pipePath, {
2006
+ flags: "a"
2007
+ // Append mode
2008
+ });
2009
+ this.pipeStream.on("error", (err) => {
2010
+ this.handleError("write" /* WRITE */, err);
2011
+ this.pipeStream = void 0;
2012
+ });
2013
+ this.isInitialized = true;
2014
+ this.processQueue();
2015
+ } catch (error) {
2016
+ this.handleError(
2017
+ "not_found" /* NOT_FOUND */,
2018
+ new Error(
2019
+ `Could not open named pipe at ${this.pipePath}: ${error.message}`
2020
+ )
2021
+ );
2022
+ }
2023
+ }
2024
+ /**
2025
+ * Process queued entries
2026
+ */
2027
+ processQueue() {
2028
+ while (this.writeQueue.length > 0 && !this.closed) {
2029
+ const entry = this.writeQueue.shift();
2030
+ if (entry) {
2031
+ this.writeEntry(entry);
2032
+ }
2033
+ }
2034
+ }
2035
+ /**
2036
+ * Write a single entry
2037
+ */
2038
+ writeEntry(entry) {
2039
+ if (this.closed) {
2040
+ return;
2041
+ }
2042
+ if (!this.pipeStream || this.pipeStream.destroyed) {
2043
+ return;
2044
+ }
2045
+ try {
2046
+ const messageToWrite = this.formatEntry(entry);
2047
+ if (!this.pipeStream.write(messageToWrite)) {
2048
+ this.pipeStream.once("drain", () => {
2049
+ });
2050
+ }
2051
+ } catch (error) {
2052
+ this.handleError(
2053
+ "write" /* WRITE */,
2054
+ error instanceof Error ? error : new Error(String(error))
2055
+ );
2056
+ }
2057
+ }
2058
+ /**
2059
+ * Format a log entry for pipe output
2060
+ */
2061
+ formatEntry(entry) {
2062
+ if (this.formatter) {
2063
+ try {
2064
+ return this.formatter(entry) + "\n";
2065
+ } catch {
2066
+ }
2067
+ }
2068
+ let formatted;
2069
+ if (this.jsonFormat) {
2070
+ formatted = JSON.stringify({
2071
+ timestamp: entry.timestamp,
2072
+ type: entry.type,
2073
+ serviceName: entry.serviceName,
2074
+ entityName: entry.entityName,
2075
+ message: entry.message,
2076
+ params: entry.redactedParams
2077
+ });
2078
+ } else {
2079
+ let text = "";
2080
+ if (entry.type !== "raw") {
2081
+ text = `[${entry.type}] `;
2082
+ if (entry.serviceName) {
2083
+ text += `[${entry.serviceName}] `;
2084
+ }
2085
+ if (entry.entityName) {
2086
+ text += `[${entry.entityName}] `;
2087
+ }
2088
+ }
2089
+ text += entry.message;
2090
+ formatted = text;
2091
+ }
2092
+ return formatted + "\n";
2093
+ }
2094
+ /**
2095
+ * Handle errors
2096
+ */
2097
+ handleError(errorType, error) {
2098
+ if (this.onError) {
2099
+ this.onError(errorType, error, this.pipePath);
2100
+ } else {
2101
+ console.error(`NamedPipeSink error (${errorType}): ${error.message}`);
2102
+ }
2103
+ }
2104
+ };
2105
+
2106
+ // src/lib/logger/index.ts
2107
+ var Logger = class _Logger extends EventEmitter {
2108
+ isLoggerClass = true;
2109
+ sinks;
2110
+ redactFunction;
2111
+ callProcessExit;
2112
+ beforeExitCallback;
2113
+ onSinkError;
2114
+ _didExit = false;
2115
+ _exitCode = 0;
2116
+ _exitRequested = false;
2117
+ _isPendingExit = false;
2118
+ _closed = false;
2119
+ _reportErrorListenerRegistered = false;
2120
+ _reportErrorListener = null;
2121
+ constructor(options = {}) {
2122
+ super();
2123
+ this.sinks = options.sinks || [];
2124
+ this.redactFunction = options.redactFunction;
2125
+ this.callProcessExit = options.callProcessExit ?? true;
2126
+ this.beforeExitCallback = options.beforeExitCallback;
2127
+ this.onSinkError = options.onSinkError;
2128
+ }
2129
+ get didExit() {
2130
+ return this._didExit;
2131
+ }
2132
+ get exitCode() {
2133
+ return this._exitCode;
2134
+ }
2135
+ get isPendingExit() {
2136
+ return this._isPendingExit;
2137
+ }
2138
+ get hasExitedOrPending() {
2139
+ return this._didExit || this._isPendingExit;
2140
+ }
2141
+ get closed() {
2142
+ return this._closed;
2143
+ }
2144
+ /**
2145
+ * Exit the process with the specified code
2146
+ */
2147
+ exit(code) {
2148
+ const isFirstExit = !this._exitRequested;
2149
+ this._exitRequested = true;
2150
+ if (!this._didExit) {
2151
+ this._isPendingExit = true;
2152
+ }
2153
+ this.emit("logger", { eventType: "exit-called", code, isFirstExit });
2154
+ if (this.beforeExitCallback) {
2155
+ safeHandleCallbackAndWait(
2156
+ "beforeExit",
2157
+ this.beforeExitCallback,
2158
+ code,
2159
+ isFirstExit
2160
+ ).then((result) => {
2161
+ if (result.success && result.value?.action === "wait") {
2162
+ return;
2163
+ }
2164
+ this.processExit(code);
2165
+ }).catch(() => {
2166
+ this.processExit(code);
2167
+ });
2168
+ } else {
2169
+ this.processExit(code);
2170
+ }
2171
+ }
2172
+ /**
2173
+ * Set or update the beforeExit callback
2174
+ *
2175
+ * This allows setting the callback after Logger construction, which is useful
2176
+ * when the callback needs to reference objects that depend on the Logger instance.
2177
+ *
2178
+ * **Note:** This method overwrites any existing beforeExit callback (including
2179
+ * one set in the Logger constructor). Pass `undefined` to remove the callback.
2180
+ *
2181
+ * **Error Handling:** If the callback throws an error or rejects, the logger will
2182
+ * proceed with exit anyway to prevent the process from hanging. The error will be
2183
+ * reported via the global `reportError` event.
2184
+ *
2185
+ * @param callback - Function to call before process exit (receives exitCode and isFirstExit).
2186
+ * Must return BeforeExitResult indicating whether to proceed with exit or wait.
2187
+ * Return `{ action: 'proceed' }` to continue with exit.
2188
+ * Return `{ action: 'wait' }` to prevent exit (e.g., shutdown already in progress).
2189
+ * If the callback throws, exit proceeds automatically.
2190
+ *
2191
+ * Pass undefined to remove the callback.
2192
+ *
2193
+ * @example
2194
+ * ```typescript
2195
+ * const logger = new Logger();
2196
+ * const lifecycle = new LifecycleManager({ logger });
2197
+ *
2198
+ * // Set callback after both are constructed
2199
+ * logger.setBeforeExitCallback(async (exitCode, isFirstExit) => {
2200
+ * if (isFirstExit) {
2201
+ * await lifecycle.stopAllComponents();
2202
+ * }
2203
+ * return { action: 'proceed' };
2204
+ * });
2205
+ *
2206
+ * // Later, remove the callback
2207
+ * logger.setBeforeExitCallback(undefined);
2208
+ * ```
2209
+ */
2210
+ setBeforeExitCallback(callback) {
2211
+ this.beforeExitCallback = callback;
2212
+ }
2213
+ /**
2214
+ * Log an error message
2215
+ */
2216
+ error(message, options) {
2217
+ this.handleLog("error", message, options);
2218
+ }
2219
+ /**
2220
+ * Log an error object with optional prefix
2221
+ */
2222
+ errorObject(prefix, error, options) {
2223
+ const message = prepareErrorObjectLog(prefix, error);
2224
+ this.handleLog("error", message, { ...options ?? {}, error });
2225
+ }
2226
+ /**
2227
+ * Log an informational message
2228
+ */
2229
+ info(message, options) {
2230
+ this.handleLog("info", message, options);
2231
+ }
2232
+ /**
2233
+ * Log a warning message
2234
+ */
2235
+ warn(message, options) {
2236
+ this.handleLog("warn", message, options);
2237
+ }
2238
+ /**
2239
+ * Log a success message
2240
+ */
2241
+ success(message, options) {
2242
+ this.handleLog("success", message, options);
2243
+ }
2244
+ /**
2245
+ * Log a notice message
2246
+ */
2247
+ notice(message, options) {
2248
+ this.handleLog("notice", message, options);
2249
+ }
2250
+ /**
2251
+ * Log a debug message
2252
+ */
2253
+ debug(message, options) {
2254
+ this.handleLog("debug", message, options);
2255
+ }
2256
+ /**
2257
+ * Log a raw message without any formatting
2258
+ */
2259
+ raw(message, options) {
2260
+ this.handleLog("raw", message, options);
2261
+ }
2262
+ /**
2263
+ * Create a scoped logger with a service name
2264
+ */
2265
+ service(serviceName) {
2266
+ return new LoggerService(this.handleLog.bind(this), serviceName);
2267
+ }
2268
+ /**
2269
+ * Registers a listener for the 'reportError' event.
2270
+ *
2271
+ * If the listener is already registered, it returns 'already_registered'.
2272
+ * If 'globalThis.reportError' is not available, it returns 'not_available'.
2273
+ * Otherwise, it registers the listener and returns 'success'.
2274
+ *
2275
+ * @param prefix - The prefix to use when logging the error object. Default is 'Uncaught exception'.
2276
+ * @returns 'success' if the listener is registered successfully,
2277
+ * 'already_registered' if the listener is already registered,
2278
+ * 'not_available' if 'globalThis.reportError' is not available.
2279
+ */
2280
+ registerReportErrorListener(prefix = "Uncaught exception") {
2281
+ if (this._reportErrorListenerRegistered) {
2282
+ return "already_registered";
2283
+ }
2284
+ if (typeof globalThis.reportError === "undefined") {
2285
+ return "not_available";
2286
+ }
2287
+ this._reportErrorListener = (event) => {
2288
+ const errorEvent = event;
2289
+ this.errorObject(prefix, errorEvent.error);
2290
+ this.emit("logger", {
2291
+ eventType: "uncaughtException",
2292
+ error: errorEvent.error
2293
+ });
2294
+ };
2295
+ globalThis.addEventListener("reportError", this._reportErrorListener);
2296
+ this._reportErrorListenerRegistered = true;
2297
+ return "success";
2298
+ }
2299
+ /**
2300
+ * Unregister the listener for the 'reportError' event.
2301
+ *
2302
+ * If the listener is not registered, it returns 'not_registered'.
2303
+ * Otherwise, it unregister the listener and returns 'success'.
2304
+ *
2305
+ * @returns 'success' if the listener is unregistered successfully,
2306
+ * 'not_registered' if the listener is not registered.
2307
+ */
2308
+ unregisterReportErrorListener() {
2309
+ if (!this._reportErrorListenerRegistered || !this._reportErrorListener) {
2310
+ return "not_registered";
2311
+ }
2312
+ globalThis.removeEventListener("reportError", this._reportErrorListener);
2313
+ this._reportErrorListener = null;
2314
+ this._reportErrorListenerRegistered = false;
2315
+ return "success";
2316
+ }
2317
+ /**
2318
+ * Check if the 'reportError' event listener is registered
2319
+ *
2320
+ * @returns 'true' if the listener is registered, 'false' otherwise.
2321
+ */
2322
+ isReportErrorListenerRegistered() {
2323
+ return this._reportErrorListenerRegistered;
2324
+ }
2325
+ /**
2326
+ * Check if 'globalThis.reportError' is available
2327
+ *
2328
+ * @returns 'true' if 'globalThis.reportError' is available, 'false' otherwise.
2329
+ */
2330
+ isReportErrorAvailable() {
2331
+ return typeof globalThis.reportError !== "undefined";
2332
+ }
2333
+ /**
2334
+ * Add a sink to the logger
2335
+ */
2336
+ addSink(sink) {
2337
+ this.sinks.push(sink);
2338
+ }
2339
+ /**
2340
+ * Remove a sink from the logger
2341
+ * Returns true if the sink was found and removed, false otherwise
2342
+ */
2343
+ removeSink(sink) {
2344
+ const index = this.sinks.indexOf(sink);
2345
+ if (index !== -1) {
2346
+ this.sinks.splice(index, 1);
2347
+ return true;
2348
+ }
2349
+ return false;
2350
+ }
2351
+ /**
2352
+ * Get a readonly copy of the current sinks
2353
+ */
2354
+ getSinks() {
2355
+ return [...this.sinks];
2356
+ }
2357
+ /**
2358
+ * Close all sinks and cleanup resources
2359
+ * After closing, the logger is marked as closed and all sinks are removed
2360
+ */
2361
+ async close() {
2362
+ this._closed = true;
2363
+ await Promise.all(
2364
+ this.sinks.map(async (sink) => {
2365
+ if (sink.close) {
2366
+ try {
2367
+ await sink.close();
2368
+ } catch (error) {
2369
+ this.handleSinkError(error, "close", sink);
2370
+ }
2371
+ }
2372
+ })
2373
+ );
2374
+ this.sinks = [];
2375
+ this.emit("logger", { eventType: "close" });
2376
+ }
2377
+ /**
2378
+ * Create a logger optimized for testing.
2379
+ * Includes an ArraySink by default for easy log inspection.
2380
+ * Process exit is disabled to prevent tests from terminating.
2381
+ */
2382
+ static createTestOptimizedLogger(options) {
2383
+ const arraySink = new ArraySink({
2384
+ transformer: options?.arrayLogTransformer
2385
+ });
2386
+ const consoleSink = options?.includeConsoleSink ? new ConsoleSink({ muted: options?.muteConsole ?? true }) : void 0;
2387
+ const sinks = [arraySink];
2388
+ if (consoleSink) {
2389
+ sinks.push(consoleSink);
2390
+ }
2391
+ sinks.push(...options?.sinks || []);
2392
+ return {
2393
+ logger: new _Logger({
2394
+ sinks,
2395
+ callProcessExit: false
2396
+ }),
2397
+ arraySink,
2398
+ consoleSink
2399
+ };
2400
+ }
2401
+ /**
2402
+ * Create a logger optimized for frontend/browser use.
2403
+ * Includes a ConsoleSink by default for browser devtools output.
2404
+ * Process exit is disabled since browsers don't have process.exit.
2405
+ */
2406
+ static createFrontendOptimizedLogger(options) {
2407
+ const consoleSink = new ConsoleSink({
2408
+ muted: options?.muteConsole ?? false
2409
+ });
2410
+ return {
2411
+ logger: new _Logger({
2412
+ sinks: [consoleSink, ...options?.sinks || []],
2413
+ callProcessExit: false
2414
+ }),
2415
+ consoleSink
2416
+ };
2417
+ }
2418
+ /**
2419
+ * Internal method to handle all log operations
2420
+ */
2421
+ handleLog(type, template, options) {
2422
+ if (this._closed) {
2423
+ return;
2424
+ }
2425
+ const timestamp = ms();
2426
+ const exitCode = options?.exitCode;
2427
+ const serviceName = options?.serviceName?.trim() || void 0;
2428
+ const entityName = options?.entityName?.trim() || void 0;
2429
+ const params = options?.params;
2430
+ const tags = options?.tags;
2431
+ const redactedKeys = options?.redactedKeys;
2432
+ const message = params ? CurlyBrackets(template, params) : template;
2433
+ const redactedParams = params ? applyRedaction(params, redactedKeys, this.redactFunction) : void 0;
2434
+ const entry = {
2435
+ timestamp,
2436
+ type,
2437
+ serviceName,
2438
+ entityName,
2439
+ template,
2440
+ message,
2441
+ params,
2442
+ redactedParams,
2443
+ redactedKeys: params && redactedKeys && redactedKeys.length > 0 ? redactedKeys : void 0,
2444
+ error: options?.error,
2445
+ exitCode: isNumber(exitCode) ? exitCode : void 0,
2446
+ tags: tags && tags.length > 0 ? tags : void 0
2447
+ };
2448
+ for (const sink of this.sinks) {
2449
+ try {
2450
+ const result = sink.write(entry);
2451
+ if (isPromise(result)) {
2452
+ result.catch((error) => {
2453
+ this.handleSinkError(error, "write", sink);
2454
+ });
2455
+ }
2456
+ } catch (error) {
2457
+ this.handleSinkError(error, "write", sink);
2458
+ }
2459
+ }
2460
+ this.emit("logger", {
2461
+ eventType: "log",
2462
+ logType: type,
2463
+ message,
2464
+ timestamp
2465
+ });
2466
+ if (isNumber(exitCode)) {
2467
+ this.exit(exitCode);
2468
+ }
2469
+ }
2470
+ /**
2471
+ * Handle sink errors by calling the onSinkError callback or falling back to console.error
2472
+ */
2473
+ handleSinkError(error, context, sink) {
2474
+ if (this.onSinkError) {
2475
+ try {
2476
+ this.onSinkError(error, context, sink);
2477
+ } catch {
2478
+ console.error(`Error in onSinkError handler: ${error.message}`);
2479
+ }
2480
+ } else {
2481
+ console.error(
2482
+ `Error ${context === "write" ? "writing to" : "closing"} sink: ${error.message}`
2483
+ );
2484
+ }
2485
+ }
2486
+ /**
2487
+ * Process the exit
2488
+ */
2489
+ processExit(code) {
2490
+ this._didExit = true;
2491
+ this._exitCode = code;
2492
+ this._isPendingExit = false;
2493
+ this.emit("logger", { eventType: "exit-process", code });
2494
+ void this.close().finally(() => {
2495
+ if (this.callProcessExit) {
2496
+ if (typeof globalThis.process !== "undefined" && typeof globalThis.process.exit === "function") {
2497
+ globalThis.process.exit(code);
2498
+ }
2499
+ }
2500
+ });
2501
+ }
2502
+ };
2503
+ // Annotate the CommonJS export names for ESM import in node:
2504
+ 0 && (module.exports = {
2505
+ ArraySink,
2506
+ ConsoleSink,
2507
+ FileSink,
2508
+ LogLevel,
2509
+ Logger,
2510
+ NamedPipeSink,
2511
+ PipeErrorType,
2512
+ getLogLevel
2513
+ });
2514
+ //# sourceMappingURL=index.cjs.map