@faasjs/node-utils 8.0.0-beta.7 → 8.0.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, join, sep } from "node:path";
3
- import { Logger } from "@faasjs/logger";
4
- import { load } from "js-yaml";
5
3
 
6
4
  //#region src/deep_merge.ts
7
5
  const shouldMerge = (item) => {
@@ -23,21 +21,861 @@ const shouldMerge = (item) => {
23
21
  */
24
22
  function deepMerge(...sources) {
25
23
  let acc = Object.create(null);
26
- for (const source of sources) if (Array.isArray(source)) {
27
- if (!Array.isArray(acc)) acc = [];
28
- acc = [...new Set(source.concat(...acc))];
29
- } else if (shouldMerge(source)) for (const [key, value] of Object.entries(source)) {
30
- let val;
31
- if (shouldMerge(value)) val = deepMerge(acc[key], value);
32
- else val = value;
33
- acc = {
24
+ for (const source of sources) {
25
+ if (Array.isArray(source)) {
26
+ if (!Array.isArray(acc)) acc = [];
27
+ acc = [...new Set(source.concat(...acc))];
28
+ continue;
29
+ }
30
+ if (!shouldMerge(source)) continue;
31
+ for (const [key, value] of Object.entries(source)) acc = {
34
32
  ...acc,
35
- [key]: val
33
+ [key]: shouldMerge(value) ? deepMerge(acc[key], value) : value
36
34
  };
37
35
  }
38
36
  return acc;
39
37
  }
40
38
 
39
+ //#endregion
40
+ //#region src/color.ts
41
+ const Color = {
42
+ DEFAULT: 39,
43
+ BLACK: 30,
44
+ RED: 31,
45
+ GREEN: 32,
46
+ ORANGE: 33,
47
+ BLUE: 34,
48
+ MAGENTA: 35,
49
+ CYAN: 36,
50
+ GRAY: 90
51
+ };
52
+ const LevelColor = {
53
+ debug: Color.GRAY,
54
+ info: Color.GREEN,
55
+ warn: Color.ORANGE,
56
+ error: Color.RED
57
+ };
58
+ /**
59
+ * Apply ANSI color codes to a message based on the log level.
60
+ *
61
+ * @param level - The log level to determine the color.
62
+ * @param message - The message to be colorized.
63
+ * @returns The colorized message string.
64
+ */
65
+ function colorfy(level, message) {
66
+ return `\u001b[0${LevelColor[level]}m${message}\u001b[39m`;
67
+ }
68
+
69
+ //#endregion
70
+ //#region src/format.ts
71
+ /**
72
+ * Formats a string using placeholders and arguments.
73
+ *
74
+ * The function supports the following placeholders:
75
+ * - `%o`: Formats the argument as a JSON string if it's an array, otherwise falls through to `%s`.
76
+ * - `%s`: Converts the argument to a string.
77
+ * - `%d`: Converts the argument to a number.
78
+ * - `%j`: Formats the argument as a JSON string.
79
+ */
80
+ function format(fmt, ...args) {
81
+ const re = /(%?)(%([ojds]))/g;
82
+ let fmtString;
83
+ if (typeof fmt !== "string") if (fmt instanceof Error) fmtString = `Error: ${fmt.message}\n${fmt.stack}`;
84
+ else if (fmt instanceof Object) fmtString = JSON.stringify(fmt);
85
+ else fmtString = String(fmt);
86
+ else fmtString = fmt;
87
+ if (args.length) fmtString = fmtString.replace(re, (match, escaped, _, flag) => {
88
+ let arg = args.shift();
89
+ switch (flag) {
90
+ case "o": if (Array.isArray(arg)) {
91
+ arg = JSON.stringify(arg);
92
+ break;
93
+ }
94
+ case "s":
95
+ arg = `${arg}`;
96
+ break;
97
+ case "d":
98
+ arg = Number(arg);
99
+ break;
100
+ case "j":
101
+ arg = JSON.stringify(arg);
102
+ break;
103
+ }
104
+ if (!escaped) return arg;
105
+ args.unshift(arg);
106
+ return match;
107
+ });
108
+ if (args.length) fmtString += ` ${args.join(" ")}`;
109
+ fmtString = fmtString.replace(/%{2,2}/g, "%");
110
+ return fmtString;
111
+ }
112
+
113
+ //#endregion
114
+ //#region src/transport.ts
115
+ /**
116
+ * The transport class that manages the transport handlers and log messages.
117
+ *
118
+ * **Note: This class is not meant to be used directly. Use the {@link getTransport} instead.**
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * import { getTransport } from '@faasjs/node-utils'
123
+ *
124
+ * const transport = getTransport()
125
+ *
126
+ * transport.register('test', async (messages) => {
127
+ * for (const { level, message } of messages)
128
+ * console.log(level, message)
129
+ * })
130
+ *
131
+ * transport.config({ label: 'test', debug: true })
132
+ *
133
+ * // If you using Logger, it will automatically insert messages to the transport.
134
+ * // Otherwise, you can insert messages manually.
135
+ * transport.insert({
136
+ * level: 'info',
137
+ * labels: ['server'],
138
+ * message: 'test message',
139
+ * timestamp: Date.now()
140
+ * })
141
+ *
142
+ * process.on('SIGINT', async () => {
143
+ * await transport.stop()
144
+ * process.exit(0)
145
+ * })
146
+ * ```
147
+ */
148
+ var Transport = class {
149
+ enabled = true;
150
+ handlers = /* @__PURE__ */ new Map();
151
+ logger;
152
+ messages = [];
153
+ flushing = false;
154
+ interval;
155
+ intervalTime = 5e3;
156
+ constructor() {
157
+ this.logger = new Logger("LoggerTransport");
158
+ this.logger.level = "info";
159
+ this.flush = this.flush.bind(this);
160
+ this.interval = setInterval(this.flush, this.intervalTime);
161
+ }
162
+ /**
163
+ * Registers a new transport handler.
164
+ *
165
+ * @param name - The name of the transport handler.
166
+ * @param handler - The transport handler function to be registered.
167
+ */
168
+ register(name, handler) {
169
+ this.logger.info("register", name);
170
+ this.handlers.set(name, handler);
171
+ if (!this.enabled) this.enabled = true;
172
+ }
173
+ /**
174
+ * Unregister a handler by its name.
175
+ *
176
+ * This method logs the unregistration process, removes the handler from the internal collection,
177
+ * and disables the logger if no handlers remain.
178
+ *
179
+ * @param name - The name of the handler to unregister.
180
+ */
181
+ unregister(name) {
182
+ this.logger.info("unregister", name);
183
+ this.handlers.delete(name);
184
+ if (this.handlers.size === 0) this.enabled = false;
185
+ }
186
+ /**
187
+ * Inserts a log message into the transport if it is enabled.
188
+ *
189
+ * @param message - The log message to be inserted.
190
+ */
191
+ insert(message) {
192
+ if (!this.enabled) return;
193
+ this.messages.push(message);
194
+ }
195
+ /**
196
+ * Flushes the current messages by processing them with the registered handlers.
197
+ *
198
+ * If the transport is already flushing, it will wait until the current flush is complete.
199
+ * If the transport is disabled or there are no messages to flush, it will return immediately.
200
+ * If there are no handlers registered, it will log a warning, clear the messages, disable the transport, and stop the interval.
201
+ *
202
+ * The method processes all messages with each handler and logs any errors encountered during the process.
203
+ *
204
+ * @returns {Promise<void>} A promise that resolves when the flush operation is complete.
205
+ */
206
+ async flush() {
207
+ if (this.flushing) return new Promise((resolve) => {
208
+ const interval = setInterval(() => {
209
+ if (!this.flushing) {
210
+ clearInterval(interval);
211
+ resolve();
212
+ }
213
+ }, 100);
214
+ });
215
+ if (!this.enabled || this.messages.length === 0) return;
216
+ if (this.handlers.size === 0) {
217
+ this.logger.warn("no handlers to flush, disable transport");
218
+ this.messages.splice(0, this.messages.length);
219
+ this.enabled = false;
220
+ clearInterval(this.interval);
221
+ return;
222
+ }
223
+ this.flushing = true;
224
+ const messages = this.messages.splice(0, this.messages.length);
225
+ this.logger.debug("flushing %d messages with %d handlers", messages.length, this.handlers.size);
226
+ for (const handler of this.handlers.values()) try {
227
+ await handler(messages);
228
+ } catch (error) {
229
+ this.logger.error(handler.name, error);
230
+ }
231
+ this.flushing = false;
232
+ }
233
+ /**
234
+ * Stops the logger transport.
235
+ *
236
+ * This method performs the following actions:
237
+ * 1. Logs a 'stopping' message.
238
+ * 2. Clears the interval if it is set.
239
+ * 3. Flushes any remaining logs.
240
+ * 4. Disables the transport.
241
+ *
242
+ * @returns {Promise<void>} A promise that resolves when the transport has been stopped.
243
+ */
244
+ async stop() {
245
+ this.logger.info("stopping");
246
+ if (this.interval) {
247
+ clearInterval(this.interval);
248
+ this.interval = void 0;
249
+ }
250
+ await this.flush();
251
+ this.enabled = false;
252
+ }
253
+ /**
254
+ * Resets the transport by clearing handlers, emptying messages, and re-enabling the transport.
255
+ * If an interval is set, it will be cleared.
256
+ */
257
+ reset() {
258
+ this.handlers.clear();
259
+ this.messages.splice(0, this.messages.length);
260
+ this.enabled = true;
261
+ if (this.interval) {
262
+ clearInterval(this.interval);
263
+ this.interval = void 0;
264
+ }
265
+ }
266
+ /**
267
+ * Configure the transport options for the logger.
268
+ *
269
+ * @param {TransportOptions} options - The configuration options for the transport.
270
+ * @param {string} [options.label] - The label to be used by the logger.
271
+ * @param {boolean} [options.debug] - If true, sets the logger level to 'debug', otherwise sets it to 'info'.
272
+ * @param {number} [options.interval] - The interval time in milliseconds for flushing the logs. If different from the current interval, it updates the interval and resets the timer.
273
+ */
274
+ config(options) {
275
+ if (options.label) this.logger.label = options.label;
276
+ if (typeof options.debug === "boolean") this.logger.level = options.debug ? "debug" : "info";
277
+ if (options.interval && options.interval !== this.intervalTime) {
278
+ this.intervalTime = options.interval;
279
+ clearInterval(this.interval);
280
+ this.interval = setInterval(this.flush, this.intervalTime);
281
+ }
282
+ if (!this.enabled) this.enabled = true;
283
+ }
284
+ };
285
+ let current;
286
+ function getTransport() {
287
+ current ||= new Transport();
288
+ return current;
289
+ }
290
+
291
+ //#endregion
292
+ //#region src/logger.ts
293
+ const LevelPriority = {
294
+ debug: 0,
295
+ info: 1,
296
+ warn: 2,
297
+ error: 3
298
+ };
299
+ /**
300
+ * Formats the provided arguments into a string, filtering out any objects
301
+ * with a `__hidden__` property set to `true`. If formatting fails, it attempts
302
+ * to stringify each argument individually.
303
+ *
304
+ * @param {...any[]} args - The arguments to format.
305
+ * @returns {string} The formatted string.
306
+ */
307
+ function formatLogger(fmt, ...args) {
308
+ try {
309
+ return format(fmt, ...args.filter((a) => !a || typeof a !== "object" || a.__hidden__ !== true));
310
+ } catch (e) {
311
+ return `[Unable to format] ${e?.message}`;
312
+ }
313
+ }
314
+ /**
315
+ * Logger Class
316
+ *
317
+ * @example
318
+ * ```ts
319
+ * const logger = new Logger()
320
+ *
321
+ * logger.debug('debug message')
322
+ * logger.info('info message')
323
+ * logger.warn('warn message')
324
+ * logger.error('error message')
325
+ *
326
+ * logger.time('timer name')
327
+ * logger.timeEnd('timer name', 'message') // => 'message +1ms'
328
+ * ```
329
+ */
330
+ var Logger = class {
331
+ silent = false;
332
+ level = "debug";
333
+ colorfyOutput = true;
334
+ label;
335
+ size = 1e3;
336
+ disableTransport = false;
337
+ stdout = console.log;
338
+ stderr = console.error;
339
+ cachedTimers = {};
340
+ /**
341
+ * @param label {string} Prefix label
342
+ */
343
+ constructor(label) {
344
+ if (label) this.label = label;
345
+ if (typeof process === "undefined") return;
346
+ if (!process.env.FaasLog && process.env.npm_config_argv && JSON.parse(process.env.npm_config_argv).original.includes("--silent")) this.silent = true;
347
+ if (process.env.FaasLogTransport !== "true" && (process.env.VITEST || process.env.FaasLogTransport === "false")) this.disableTransport = true;
348
+ switch (process.env.FaasLogMode) {
349
+ case "plain":
350
+ this.colorfyOutput = false;
351
+ break;
352
+ case "pretty":
353
+ this.colorfyOutput = true;
354
+ break;
355
+ default:
356
+ this.colorfyOutput = process.env.FaasMode !== "remote";
357
+ break;
358
+ }
359
+ if (process.env.FaasLog) this.level = process.env.FaasLog.toLowerCase();
360
+ if (process.env.FaasLogSize) this.size = Number(process.env.FaasLogSize);
361
+ }
362
+ /**
363
+ * @param message {string} message
364
+ * @param args {...any=} arguments
365
+ */
366
+ debug(message, ...args) {
367
+ this.log("debug", message, ...args);
368
+ return this;
369
+ }
370
+ /**
371
+ * @param message {string} message
372
+ * @param args {...any=} arguments
373
+ */
374
+ info(message, ...args) {
375
+ this.log("info", message, ...args);
376
+ return this;
377
+ }
378
+ /**
379
+ * @param message {string} message
380
+ * @param args {...any=} arguments
381
+ */
382
+ warn(message, ...args) {
383
+ this.log("warn", message, ...args);
384
+ return this;
385
+ }
386
+ /**
387
+ * @param message {any} message or Error object
388
+ * @param args {...any=} arguments
389
+ */
390
+ error(message, ...args) {
391
+ this.log("error", message, ...args);
392
+ return this;
393
+ }
394
+ /**
395
+ * Start a timer with a specific key and log level.
396
+ *
397
+ * @param key - The unique identifier for the timer.
398
+ * @param level - The log level for the timer. Defaults to 'debug'.
399
+ * @returns The Logger instance for chaining.
400
+ */
401
+ time(key, level = "debug") {
402
+ this.cachedTimers[key] = {
403
+ level,
404
+ time: Date.now()
405
+ };
406
+ return this;
407
+ }
408
+ /**
409
+ * End a timer with a specific key and log the elapsed time.
410
+ *
411
+ * @param key - The unique identifier for the timer.
412
+ * @param message - The message to log with the elapsed time.
413
+ * @param args - Additional arguments to log with the message.
414
+ * @returns The Logger instance for chaining.
415
+ */
416
+ timeEnd(key, message, ...args) {
417
+ if (this.cachedTimers[key]) {
418
+ const timer = this.cachedTimers[key];
419
+ const duration = Date.now() - timer.time;
420
+ message = `${message} +${duration}ms`;
421
+ args.push({
422
+ __hidden__: true,
423
+ performance: {
424
+ name: key,
425
+ startTime: timer.time,
426
+ duration
427
+ }
428
+ });
429
+ this[timer.level](message, ...args);
430
+ delete this.cachedTimers[key];
431
+ } else {
432
+ this.warn("timeEnd not found key %s", key);
433
+ this.debug(message);
434
+ }
435
+ return this;
436
+ }
437
+ /**
438
+ * @param message {string} message
439
+ * @param args {...any=} arguments
440
+ */
441
+ raw(message, ...args) {
442
+ if (this.silent) return this;
443
+ this.stdout(formatLogger(message, ...args));
444
+ return this;
445
+ }
446
+ log(level, message, ...args) {
447
+ if (this.silent) return this;
448
+ if (LevelPriority[level] < LevelPriority[this.level]) return this;
449
+ const formattedMessage = formatLogger(message, ...args);
450
+ if (!formattedMessage && !args.length) return this;
451
+ if (!this.disableTransport) getTransport().insert({
452
+ level,
453
+ labels: this.label?.split(/\]\s*\[/) || [],
454
+ message: formattedMessage,
455
+ timestamp: Date.now(),
456
+ extra: args
457
+ });
458
+ let output = `${level.toUpperCase()} ${this.label ? `[${this.label}] ` : ""}${formattedMessage}`;
459
+ if (this.colorfyOutput) output = colorfy(level, output);
460
+ else if (!this.colorfyOutput) output = output.replace(/\n/g, "");
461
+ if (!output) return this;
462
+ if (this.size > 0 && output.length > this.size && !["error", "warn"].includes(level)) output = `${output.slice(0, this.size - 100)}...[truncated]...${output.slice(output.length - 100)}`;
463
+ if (level === "error") this.stderr(output);
464
+ else this.stdout(output);
465
+ return this;
466
+ }
467
+ };
468
+
469
+ //#endregion
470
+ //#region src/parse_yaml.ts
471
+ function createParseError(line, reason) {
472
+ return Error(`[parseYaml] ${reason} at line ${line}`);
473
+ }
474
+ function isSequenceLine(content) {
475
+ return /^-(\s|$)/.test(content);
476
+ }
477
+ function isMappingValue(value) {
478
+ return !!value && typeof value === "object" && !Array.isArray(value);
479
+ }
480
+ function stripInlineComment(content) {
481
+ let inSingleQuote = false;
482
+ let inDoubleQuote = false;
483
+ let escaped = false;
484
+ for (let i = 0; i < content.length; i++) {
485
+ const char = content[i];
486
+ if (inDoubleQuote) {
487
+ if (escaped) {
488
+ escaped = false;
489
+ continue;
490
+ }
491
+ if (char === "\\") {
492
+ escaped = true;
493
+ continue;
494
+ }
495
+ if (char === "\"") inDoubleQuote = false;
496
+ continue;
497
+ }
498
+ if (inSingleQuote) {
499
+ if (char === "'") {
500
+ if (content[i + 1] === "'") {
501
+ i++;
502
+ continue;
503
+ }
504
+ inSingleQuote = false;
505
+ }
506
+ continue;
507
+ }
508
+ if (char === "\"") {
509
+ inDoubleQuote = true;
510
+ continue;
511
+ }
512
+ if (char === "'") {
513
+ inSingleQuote = true;
514
+ continue;
515
+ }
516
+ if (char === "#" && (i === 0 || /\s/.test(content[i - 1]))) return content.slice(0, i).trimEnd();
517
+ }
518
+ return content.trimEnd();
519
+ }
520
+ function normalizeLines(content) {
521
+ const lines = content.replace(/\r\n?/g, "\n").split("\n");
522
+ const normalized = [];
523
+ for (let i = 0; i < lines.length; i++) {
524
+ const line = lines[i];
525
+ const lineNumber = i + 1;
526
+ const leading = line.match(/^[ \t]*/)?.[0] || "";
527
+ if (leading.includes(" ")) throw createParseError(lineNumber, "Tabs are not supported for indentation");
528
+ const indent = leading.length;
529
+ const contentWithoutComment = stripInlineComment(line.slice(indent));
530
+ if (!contentWithoutComment.trim()) continue;
531
+ if (contentWithoutComment === "---" || contentWithoutComment === "...") throw createParseError(lineNumber, "Multiple YAML documents are not supported");
532
+ normalized.push({
533
+ content: contentWithoutComment,
534
+ indent,
535
+ line: lineNumber
536
+ });
537
+ }
538
+ return normalized;
539
+ }
540
+ function findMappingSeparator(content) {
541
+ let inSingleQuote = false;
542
+ let inDoubleQuote = false;
543
+ let escaped = false;
544
+ for (let i = 0; i < content.length; i++) {
545
+ const char = content[i];
546
+ if (inDoubleQuote) {
547
+ if (escaped) {
548
+ escaped = false;
549
+ continue;
550
+ }
551
+ if (char === "\\") {
552
+ escaped = true;
553
+ continue;
554
+ }
555
+ if (char === "\"") inDoubleQuote = false;
556
+ continue;
557
+ }
558
+ if (inSingleQuote) {
559
+ if (char === "'") {
560
+ if (content[i + 1] === "'") {
561
+ i++;
562
+ continue;
563
+ }
564
+ inSingleQuote = false;
565
+ }
566
+ continue;
567
+ }
568
+ if (char === "\"") {
569
+ inDoubleQuote = true;
570
+ continue;
571
+ }
572
+ if (char === "'") {
573
+ inSingleQuote = true;
574
+ continue;
575
+ }
576
+ if (char !== ":") continue;
577
+ const next = content[i + 1];
578
+ if (typeof next === "undefined" || /\s/.test(next)) return i;
579
+ }
580
+ return -1;
581
+ }
582
+ function parseDoubleQuotedScalar(value, line) {
583
+ let result = "";
584
+ for (let i = 1; i < value.length; i++) {
585
+ const char = value[i];
586
+ if (char === "\"") {
587
+ if (i !== value.length - 1) throw createParseError(line, "Invalid double quoted string");
588
+ return result;
589
+ }
590
+ if (char !== "\\") {
591
+ result += char;
592
+ continue;
593
+ }
594
+ const escaped = value[++i];
595
+ if (typeof escaped === "undefined") throw createParseError(line, "Invalid escape sequence");
596
+ switch (escaped) {
597
+ case "\"":
598
+ case "\\":
599
+ case "/":
600
+ result += escaped;
601
+ break;
602
+ case "b":
603
+ result += "\b";
604
+ break;
605
+ case "f":
606
+ result += "\f";
607
+ break;
608
+ case "n":
609
+ result += "\n";
610
+ break;
611
+ case "r":
612
+ result += "\r";
613
+ break;
614
+ case "t":
615
+ result += " ";
616
+ break;
617
+ case "u": {
618
+ const hex = value.slice(i + 1, i + 5);
619
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw createParseError(line, "Invalid unicode escape sequence");
620
+ result += String.fromCharCode(Number.parseInt(hex, 16));
621
+ i += 4;
622
+ break;
623
+ }
624
+ default: throw createParseError(line, `Unsupported escape sequence \\${escaped}`);
625
+ }
626
+ }
627
+ throw createParseError(line, "Unterminated double quoted string");
628
+ }
629
+ function parseSingleQuotedScalar(value, line) {
630
+ let result = "";
631
+ for (let i = 1; i < value.length; i++) {
632
+ const char = value[i];
633
+ if (char === "'") {
634
+ if (value[i + 1] === "'") {
635
+ result += "'";
636
+ i++;
637
+ continue;
638
+ }
639
+ if (i !== value.length - 1) throw createParseError(line, "Invalid single quoted string");
640
+ return result;
641
+ }
642
+ result += char;
643
+ }
644
+ throw createParseError(line, "Unterminated single quoted string");
645
+ }
646
+ function parseQuotedScalar(value, line) {
647
+ if (value.startsWith("\"")) return parseDoubleQuotedScalar(value, line);
648
+ if (value.startsWith("'")) return parseSingleQuotedScalar(value, line);
649
+ throw createParseError(line, "Invalid quoted string");
650
+ }
651
+ function parsePlainScalar(value) {
652
+ if (value === "~") return null;
653
+ const lower = value.toLowerCase();
654
+ if (lower === "null") return null;
655
+ if (lower === "true") return true;
656
+ if (lower === "false") return false;
657
+ if (/^[-+]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?$/.test(value)) return Number(value);
658
+ return value;
659
+ }
660
+ function parseInlineValue(value, line) {
661
+ if (value.startsWith("|") || value.startsWith(">")) throw createParseError(line, "Block scalar is not supported");
662
+ if (value.startsWith("!")) throw createParseError(line, "YAML tags are not supported");
663
+ if (value === "[]") return [];
664
+ if (value === "{}") return Object.create(null);
665
+ if (value.startsWith("[") || value.startsWith("{")) throw createParseError(line, "Flow collection is not supported");
666
+ if (value.startsWith("\"") || value.startsWith("'")) return parseQuotedScalar(value, line);
667
+ return parsePlainScalar(value);
668
+ }
669
+ function parseKey(rawKey, line) {
670
+ if (!rawKey.length) throw createParseError(line, "Missing mapping key");
671
+ if (rawKey.startsWith("\"") || rawKey.startsWith("'")) return parseQuotedScalar(rawKey, line);
672
+ if (rawKey.startsWith("[") || rawKey.startsWith("{")) throw createParseError(line, "Complex mapping key is not supported");
673
+ return rawKey;
674
+ }
675
+ function parseReferenceToken(value, line, marker) {
676
+ let index = 1;
677
+ while (index < value.length && !/\s/.test(value[index])) index++;
678
+ const name = value.slice(1, index);
679
+ if (!name.length) throw createParseError(line, marker === "&" ? "Missing anchor name" : "Missing alias name");
680
+ if (!/^[^\s\[\]\{\},]+$/.test(name)) throw createParseError(line, marker === "&" ? "Invalid anchor name" : "Invalid alias name");
681
+ return {
682
+ name,
683
+ rest: value.slice(index).trimStart()
684
+ };
685
+ }
686
+ function setAnchor(context, anchorName, value) {
687
+ if (!anchorName) return;
688
+ context.anchors.set(anchorName, value);
689
+ }
690
+ function parseValueToken(token, line, context) {
691
+ let anchorName;
692
+ let rest = token;
693
+ if (rest.startsWith("&")) {
694
+ const anchor = parseReferenceToken(rest, line, "&");
695
+ anchorName = anchor.name;
696
+ rest = anchor.rest;
697
+ if (!rest.length) return {
698
+ anchorName,
699
+ kind: "nested"
700
+ };
701
+ }
702
+ if (rest.startsWith("*")) {
703
+ const alias = parseReferenceToken(rest, line, "*");
704
+ if (alias.rest.length) throw createParseError(line, "Unexpected token after alias");
705
+ if (!context.anchors.has(alias.name)) throw createParseError(line, `Unknown alias "*${alias.name}"`);
706
+ return {
707
+ anchorName,
708
+ kind: "alias",
709
+ value: context.anchors.get(alias.name)
710
+ };
711
+ }
712
+ return {
713
+ anchorName,
714
+ kind: "inline",
715
+ raw: rest
716
+ };
717
+ }
718
+ function parseNode(lines, index, indent, context) {
719
+ const current = lines[index];
720
+ if (!current) return {
721
+ value: null,
722
+ nextIndex: index
723
+ };
724
+ if (current.indent !== indent) throw createParseError(current.line, `Unexpected indentation: expected ${indent} spaces but got ${current.indent}`);
725
+ if (isSequenceLine(current.content)) return parseSequence(lines, index, indent, context);
726
+ return parseMapping(lines, index, indent, context);
727
+ }
728
+ function parseNestedBlockOrNull(lines, index, parentIndent, context) {
729
+ const next = lines[index + 1];
730
+ if (!next || next.indent <= parentIndent) return {
731
+ value: null,
732
+ nextIndex: index + 1
733
+ };
734
+ return parseNode(lines, index + 1, next.indent, context);
735
+ }
736
+ function parseMappingEntry(lines, index, content, entryIndent, line, context) {
737
+ const separator = findMappingSeparator(content);
738
+ if (separator < 0) throw createParseError(line, "Invalid mapping entry, expected \"key: value\"");
739
+ const key = parseKey(content.slice(0, separator).trim(), line);
740
+ const valueToken = content.slice(separator + 1).trimStart();
741
+ if (!valueToken.length) {
742
+ const nested = parseNestedBlockOrNull(lines, index, entryIndent, context);
743
+ return {
744
+ key,
745
+ value: nested.value,
746
+ nextIndex: nested.nextIndex
747
+ };
748
+ }
749
+ const token = parseValueToken(valueToken, line, context);
750
+ if (token.kind === "alias") {
751
+ setAnchor(context, token.anchorName, token.value);
752
+ return {
753
+ key,
754
+ value: token.value,
755
+ nextIndex: index + 1
756
+ };
757
+ }
758
+ if (token.kind === "nested") {
759
+ const nested = parseNestedBlockOrNull(lines, index, entryIndent, context);
760
+ setAnchor(context, token.anchorName, nested.value);
761
+ return {
762
+ key,
763
+ value: nested.value,
764
+ nextIndex: nested.nextIndex
765
+ };
766
+ }
767
+ const inlineValue = parseInlineValue(token.raw, line);
768
+ setAnchor(context, token.anchorName, inlineValue);
769
+ return {
770
+ key,
771
+ value: inlineValue,
772
+ nextIndex: index + 1
773
+ };
774
+ }
775
+ function applyMergeKey(target, source, line) {
776
+ if (Array.isArray(source)) {
777
+ for (const value of source) applyMergeKey(target, value, line);
778
+ return;
779
+ }
780
+ if (!isMappingValue(source)) throw createParseError(line, "Merge key \"<<\" expects a mapping or sequence of mappings");
781
+ for (const key in source) {
782
+ if (Object.hasOwn(target, key)) continue;
783
+ target[key] = source[key];
784
+ }
785
+ }
786
+ function parseMapping(lines, index, indent, context) {
787
+ const value = Object.create(null);
788
+ let currentIndex = index;
789
+ while (currentIndex < lines.length) {
790
+ const line = lines[currentIndex];
791
+ if (line.indent < indent) break;
792
+ if (line.indent > indent) throw createParseError(line.line, `Unexpected indentation in mapping: expected ${indent} spaces but got ${line.indent}`);
793
+ if (isSequenceLine(line.content)) throw createParseError(line.line, "Cannot mix sequence item with mapping at the same indentation");
794
+ const entry = parseMappingEntry(lines, currentIndex, line.content, indent, line.line, context);
795
+ if (entry.key === "<<") applyMergeKey(value, entry.value, line.line);
796
+ else value[entry.key] = entry.value;
797
+ currentIndex = entry.nextIndex;
798
+ }
799
+ return {
800
+ value,
801
+ nextIndex: currentIndex
802
+ };
803
+ }
804
+ function parseSequenceItem(lines, index, indent, context) {
805
+ const line = lines[index];
806
+ const rest = line.content.slice(1);
807
+ if (rest.length && !/^\s/.test(rest)) throw createParseError(line.line, "Missing whitespace after sequence marker \"-\"");
808
+ const token = rest.trimStart();
809
+ if (!token.length) return parseNestedBlockOrNull(lines, index, indent, context);
810
+ const parsedToken = parseValueToken(token, line.line, context);
811
+ if (parsedToken.kind === "alias") {
812
+ setAnchor(context, parsedToken.anchorName, parsedToken.value);
813
+ return {
814
+ value: parsedToken.value,
815
+ nextIndex: index + 1
816
+ };
817
+ }
818
+ if (parsedToken.kind === "nested") {
819
+ const nested = parseNestedBlockOrNull(lines, index, indent, context);
820
+ setAnchor(context, parsedToken.anchorName, nested.value);
821
+ return nested;
822
+ }
823
+ if (findMappingSeparator(parsedToken.raw) < 0) {
824
+ const inlineValue = parseInlineValue(parsedToken.raw, line.line);
825
+ setAnchor(context, parsedToken.anchorName, inlineValue);
826
+ return {
827
+ value: inlineValue,
828
+ nextIndex: index + 1
829
+ };
830
+ }
831
+ const itemIndent = indent + 2;
832
+ const item = Object.create(null);
833
+ const firstEntry = parseMappingEntry(lines, index, parsedToken.raw, itemIndent, line.line, context);
834
+ if (firstEntry.key === "<<") applyMergeKey(item, firstEntry.value, line.line);
835
+ else item[firstEntry.key] = firstEntry.value;
836
+ let currentIndex = firstEntry.nextIndex;
837
+ while (currentIndex < lines.length) {
838
+ const next = lines[currentIndex];
839
+ if (next.indent < itemIndent) break;
840
+ if (next.indent > itemIndent) throw createParseError(next.line, `Unexpected indentation in sequence mapping: expected ${itemIndent} spaces but got ${next.indent}`);
841
+ if (isSequenceLine(next.content)) throw createParseError(next.line, "Cannot mix sequence item with mapping at the same indentation");
842
+ const entry = parseMappingEntry(lines, currentIndex, next.content, itemIndent, next.line, context);
843
+ if (entry.key === "<<") applyMergeKey(item, entry.value, next.line);
844
+ else item[entry.key] = entry.value;
845
+ currentIndex = entry.nextIndex;
846
+ }
847
+ setAnchor(context, parsedToken.anchorName, item);
848
+ return {
849
+ value: item,
850
+ nextIndex: currentIndex
851
+ };
852
+ }
853
+ function parseSequence(lines, index, indent, context) {
854
+ const value = [];
855
+ let currentIndex = index;
856
+ while (currentIndex < lines.length) {
857
+ const line = lines[currentIndex];
858
+ if (line.indent < indent) break;
859
+ if (line.indent > indent) throw createParseError(line.line, `Unexpected indentation in sequence: expected ${indent} spaces but got ${line.indent}`);
860
+ if (!isSequenceLine(line.content)) throw createParseError(line.line, "Cannot mix mapping entry with sequence at the same indentation");
861
+ const item = parseSequenceItem(lines, currentIndex, indent, context);
862
+ value.push(item.value);
863
+ currentIndex = item.nextIndex;
864
+ }
865
+ return {
866
+ value,
867
+ nextIndex: currentIndex
868
+ };
869
+ }
870
+ function parseYaml(content) {
871
+ const lines = normalizeLines(content);
872
+ if (!lines.length) return void 0;
873
+ const context = { anchors: /* @__PURE__ */ new Map() };
874
+ const parsed = parseNode(lines, 0, lines[0].indent, context);
875
+ if (parsed.nextIndex < lines.length) throw createParseError(lines[parsed.nextIndex].line, "Unexpected trailing content");
876
+ return parsed.value;
877
+ }
878
+
41
879
  //#endregion
42
880
  //#region src/load_config.ts
43
881
  function isObject(value) {
@@ -64,6 +902,13 @@ function validateFaasYaml(filePath, config) {
64
902
  }
65
903
  return config;
66
904
  }
905
+ function assignPluginNames(config) {
906
+ if (!config.plugins) return;
907
+ for (const pluginKey in config.plugins) {
908
+ const plugin = config.plugins[pluginKey];
909
+ plugin.name = pluginKey;
910
+ }
911
+ }
67
912
  /**
68
913
  * Load configuration from faas.yaml
69
914
  */
@@ -80,22 +925,21 @@ var Config = class {
80
925
  this.filename = filename;
81
926
  this.logger.debug("load %s in %s", filename, root);
82
927
  const configs = [];
83
- [this.root, "."].concat(dirname(filename.replace(root, "")).split(sep)).reduce((base, path) => {
84
- const root = join(base, path);
85
- if (root === base) return base;
86
- const faas = join(root, "faas.yaml");
87
- if (existsSync(faas)) configs.push(validateFaasYaml(faas, load(readFileSync(faas).toString())));
88
- return root;
89
- });
928
+ const paths = [this.root, "."].concat(dirname(filename.replace(root, "")).split(sep));
929
+ let base = paths[0];
930
+ for (const path of paths.slice(1)) {
931
+ const currentRoot = join(base, path);
932
+ if (currentRoot === base) continue;
933
+ const faas = join(currentRoot, "faas.yaml");
934
+ if (existsSync(faas)) configs.push(validateFaasYaml(faas, parseYaml(readFileSync(faas, "utf8"))));
935
+ base = currentRoot;
936
+ }
90
937
  this.origin = deepMerge(...configs);
91
938
  this.defaults = deepMerge(this.origin.defaults || {});
92
939
  for (const key in this.origin) {
93
- if (key !== "defaults") this[key] = deepMerge(this.defaults, this.origin[key]);
94
- const data = this[key];
95
- if (data.plugins) for (const pluginKey in data.plugins) {
96
- const plugin = data.plugins[pluginKey];
97
- plugin.name = pluginKey;
98
- }
940
+ const data = key === "defaults" ? this.defaults : deepMerge(this.defaults, this.origin[key]);
941
+ if (key !== "defaults") this[key] = data;
942
+ assignPluginNames(data);
99
943
  }
100
944
  }
101
945
  get(key) {
@@ -141,19 +985,12 @@ function detectNodeRuntime() {
141
985
  async function loadPackage(name, defaultNames = "default") {
142
986
  const runtime = detectNodeRuntime();
143
987
  let module;
144
- if (runtime === "module") {
145
- module = await import(name);
146
- if (typeof defaultNames === "string") return defaultNames in module ? module[defaultNames] : module;
147
- for (const key of defaultNames) if (key in module) return module[key];
148
- return module;
149
- }
150
- if (runtime === "commonjs") {
151
- module = globalThis.require(name);
152
- if (typeof defaultNames === "string") return defaultNames in module ? module[defaultNames] : module;
153
- for (const key of defaultNames) if (key in module) return module[key];
154
- return module;
155
- }
156
- throw Error("Unknown runtime");
988
+ if (runtime === "module") module = await import(name);
989
+ else if (runtime === "commonjs") module = globalThis.require(name);
990
+ else throw Error("Unknown runtime");
991
+ if (typeof defaultNames === "string") return defaultNames in module ? module[defaultNames] : module;
992
+ for (const key of defaultNames) if (key in module) return module[key];
993
+ return module;
157
994
  }
158
995
 
159
996
  //#endregion
@@ -209,4 +1046,4 @@ async function streamToObject(stream) {
209
1046
  const streamToString = streamToText;
210
1047
 
211
1048
  //#endregion
212
- export { deepMerge, detectNodeRuntime, loadConfig, loadFunc, loadPackage, resetRuntime, streamToObject, streamToString, streamToText };
1049
+ export { Color, LevelColor, Logger, Transport, colorfy, deepMerge, detectNodeRuntime, formatLogger, getTransport, loadConfig, loadFunc, loadPackage, resetRuntime, streamToObject, streamToString, streamToText };