@gdacm/dashboard-manager 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,4471 @@
1
+ import fs from "fs/promises";
2
+ import path from "path";
3
+ import "@gdacm/grafana-items";
4
+ import crypto from "crypto";
5
+ //#region ../../node_modules/js-yaml/dist/js-yaml.mjs
6
+ /*! js-yaml 5.4.1 https://github.com/nodeca/js-yaml @license MIT */
7
+ /**
8
+ * Returned by a scalar resolver when the source does not match its tag.
9
+ *
10
+ * @category Tags
11
+ */
12
+ var NOT_RESOLVED = Symbol("NOT_RESOLVED");
13
+ /**
14
+ * Create a normalized scalar tag definition.
15
+ *
16
+ * @category Tags
17
+ */
18
+ function defineScalarTag(tagName, options) {
19
+ return {
20
+ tagName,
21
+ nodeKind: "scalar",
22
+ implicit: options.implicit ?? false,
23
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
24
+ implicitFirstChars: options.implicitFirstChars ?? null,
25
+ resolve: options.resolve,
26
+ identify: options.identify,
27
+ represent: options.represent ?? ((data) => String(data)),
28
+ representTagName: options.representTagName ?? (() => tagName)
29
+ };
30
+ }
31
+ /**
32
+ * Create a normalized sequence tag definition.
33
+ *
34
+ * @category Tags
35
+ */
36
+ function defineSequenceTag(tagName, options) {
37
+ const carrierIsResult = options.finalize === void 0;
38
+ return {
39
+ tagName,
40
+ nodeKind: "sequence",
41
+ implicit: false,
42
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
43
+ create: options.create,
44
+ addItem: options.addItem,
45
+ finalize: options.finalize ?? ((carrier) => carrier),
46
+ carrierIsResult,
47
+ identify: options.identify,
48
+ represent: options.represent ?? ((data) => data),
49
+ representTagName: options.representTagName ?? (() => tagName)
50
+ };
51
+ }
52
+ /**
53
+ * Create a normalized mapping tag definition.
54
+ *
55
+ * @category Tags
56
+ */
57
+ function defineMappingTag(tagName, options) {
58
+ const carrierIsResult = options.finalize === void 0;
59
+ return {
60
+ tagName,
61
+ nodeKind: "mapping",
62
+ implicit: false,
63
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
64
+ create: options.create,
65
+ addPair: options.addPair,
66
+ has: options.has,
67
+ keys: options.keys,
68
+ get: options.get,
69
+ finalize: options.finalize ?? ((carrier) => carrier),
70
+ carrierIsResult,
71
+ identify: options.identify,
72
+ represent: options.represent ?? ((data) => data),
73
+ representTagName: options.representTagName ?? (() => tagName)
74
+ };
75
+ }
76
+ /** @category Tags */
77
+ var strTag = defineScalarTag("tag:yaml.org,2002:str", {
78
+ resolve: (source) => source,
79
+ identify: (data) => typeof data === "string"
80
+ });
81
+ var NULL_VALUES$1 = [
82
+ "",
83
+ "~",
84
+ "null",
85
+ "Null",
86
+ "NULL"
87
+ ];
88
+ /** @category Tags */
89
+ var nullCoreTag = defineScalarTag("tag:yaml.org,2002:null", {
90
+ implicit: true,
91
+ implicitFirstChars: [
92
+ "",
93
+ "~",
94
+ "n",
95
+ "N"
96
+ ],
97
+ resolve: (source) => {
98
+ if (NULL_VALUES$1.indexOf(source) !== -1) return null;
99
+ return NOT_RESOLVED;
100
+ },
101
+ identify: (object) => object === null,
102
+ represent: () => "null"
103
+ });
104
+ /** @category Tags */
105
+ var nullJsonTag = defineScalarTag("tag:yaml.org,2002:null", {
106
+ implicit: true,
107
+ implicitFirstChars: ["n"],
108
+ resolve: (source, isExplicit) => {
109
+ if (source === "null" || isExplicit && source === "") return null;
110
+ return NOT_RESOLVED;
111
+ },
112
+ identify: (object) => object === null,
113
+ represent: () => "null"
114
+ });
115
+ var NULL_VALUES = [
116
+ "",
117
+ "~",
118
+ "null",
119
+ "Null",
120
+ "NULL"
121
+ ];
122
+ /** @category Tags */
123
+ var nullYaml11Tag = defineScalarTag("tag:yaml.org,2002:null", {
124
+ implicit: true,
125
+ implicitFirstChars: [
126
+ "",
127
+ "~",
128
+ "n",
129
+ "N"
130
+ ],
131
+ resolve: (source) => {
132
+ if (NULL_VALUES.indexOf(source) !== -1) return null;
133
+ return NOT_RESOLVED;
134
+ },
135
+ identify: (object) => object === null,
136
+ represent: () => "null"
137
+ });
138
+ var TRUE_VALUES$2 = [
139
+ "true",
140
+ "True",
141
+ "TRUE"
142
+ ];
143
+ var FALSE_VALUES$2 = [
144
+ "false",
145
+ "False",
146
+ "FALSE"
147
+ ];
148
+ /** @category Tags */
149
+ var boolCoreTag = defineScalarTag("tag:yaml.org,2002:bool", {
150
+ implicit: true,
151
+ implicitFirstChars: [
152
+ "t",
153
+ "T",
154
+ "f",
155
+ "F"
156
+ ],
157
+ resolve: (source) => {
158
+ if (TRUE_VALUES$2.indexOf(source) !== -1) return true;
159
+ if (FALSE_VALUES$2.indexOf(source) !== -1) return false;
160
+ return NOT_RESOLVED;
161
+ },
162
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
163
+ represent: (object) => object ? "true" : "false"
164
+ });
165
+ var TRUE_VALUES$1 = ["true"];
166
+ var FALSE_VALUES$1 = ["false"];
167
+ /** @category Tags */
168
+ var boolJsonTag = defineScalarTag("tag:yaml.org,2002:bool", {
169
+ implicit: true,
170
+ implicitFirstChars: ["t", "f"],
171
+ resolve: (source) => {
172
+ if (TRUE_VALUES$1.indexOf(source) !== -1) return true;
173
+ if (FALSE_VALUES$1.indexOf(source) !== -1) return false;
174
+ return NOT_RESOLVED;
175
+ },
176
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
177
+ represent: (object) => object ? "true" : "false"
178
+ });
179
+ var TRUE_VALUES = [
180
+ "true",
181
+ "True",
182
+ "TRUE",
183
+ "y",
184
+ "Y",
185
+ "yes",
186
+ "Yes",
187
+ "YES",
188
+ "on",
189
+ "On",
190
+ "ON"
191
+ ];
192
+ var FALSE_VALUES = [
193
+ "false",
194
+ "False",
195
+ "FALSE",
196
+ "n",
197
+ "N",
198
+ "no",
199
+ "No",
200
+ "NO",
201
+ "off",
202
+ "Off",
203
+ "OFF"
204
+ ];
205
+ /** @category Tags */
206
+ var boolYaml11Tag = defineScalarTag("tag:yaml.org,2002:bool", {
207
+ implicit: true,
208
+ implicitFirstChars: [
209
+ "y",
210
+ "Y",
211
+ "n",
212
+ "N",
213
+ "t",
214
+ "T",
215
+ "f",
216
+ "F",
217
+ "o",
218
+ "O"
219
+ ],
220
+ resolve: (source) => {
221
+ if (TRUE_VALUES.indexOf(source) !== -1) return true;
222
+ if (FALSE_VALUES.indexOf(source) !== -1) return false;
223
+ return NOT_RESOLVED;
224
+ },
225
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
226
+ represent: (object) => object ? "true" : "false"
227
+ });
228
+ var YAML_INTEGER_IMPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
229
+ var YAML_INTEGER_EXPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
230
+ function parseYamlInteger$2(source) {
231
+ let value = source;
232
+ let sign = 1;
233
+ if (value[0] === "-" || value[0] === "+") {
234
+ if (value[0] === "-") sign = -1;
235
+ value = value.slice(1);
236
+ }
237
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
238
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
239
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
240
+ return sign * parseInt(value, 10);
241
+ }
242
+ function resolveYamlInteger$2(source, isExplicit) {
243
+ if (isExplicit) {
244
+ if (!YAML_INTEGER_EXPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
245
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
246
+ const result = parseYamlInteger$2(source);
247
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
248
+ }
249
+ /** @category Tags */
250
+ var intCoreTag = defineScalarTag("tag:yaml.org,2002:int", {
251
+ implicit: true,
252
+ implicitFirstChars: [
253
+ "-",
254
+ "+",
255
+ ..."0123456789"
256
+ ],
257
+ resolve: resolveYamlInteger$2,
258
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
259
+ represent: (object) => object.toString(10)
260
+ });
261
+ var YAML_INTEGER_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)$");
262
+ var YAML_INTEGER_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
263
+ function parseYamlInteger$1(source) {
264
+ let value = source;
265
+ let sign = 1;
266
+ if (value[0] === "-" || value[0] === "+") {
267
+ if (value[0] === "-") sign = -1;
268
+ value = value.slice(1);
269
+ }
270
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
271
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
272
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
273
+ return sign * parseInt(value, 10);
274
+ }
275
+ function resolveYamlInteger$1(source, isExplicit) {
276
+ if (isExplicit) {
277
+ if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
278
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
279
+ const result = parseYamlInteger$1(source);
280
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
281
+ }
282
+ /** @category Tags */
283
+ var intJsonTag = defineScalarTag("tag:yaml.org,2002:int", {
284
+ implicit: true,
285
+ implicitFirstChars: ["-", ..."0123456789"],
286
+ resolve: resolveYamlInteger$1,
287
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
288
+ represent: (object) => object.toString(10)
289
+ });
290
+ var YAML_INTEGER_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");
291
+ function parseYamlInteger(source) {
292
+ let value = source.replace(/_/g, "");
293
+ let sign = 1;
294
+ if (value[0] === "-" || value[0] === "+") {
295
+ if (value[0] === "-") sign = -1;
296
+ value = value.slice(1);
297
+ }
298
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
299
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
300
+ if (value.includes(":")) {
301
+ let result = 0;
302
+ for (const part of value.split(":")) result = result * 60 + Number(part);
303
+ return sign * result;
304
+ }
305
+ if (value !== "0" && value[0] === "0") return sign * parseInt(value, 8);
306
+ return sign * parseInt(value, 10);
307
+ }
308
+ function resolveYamlInteger(source) {
309
+ if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED;
310
+ const result = parseYamlInteger(source);
311
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
312
+ }
313
+ /** @category Tags */
314
+ var intYaml11Tag = defineScalarTag("tag:yaml.org,2002:int", {
315
+ implicit: true,
316
+ implicitFirstChars: [
317
+ "-",
318
+ "+",
319
+ ..."0123456789"
320
+ ],
321
+ resolve: resolveYamlInteger,
322
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
323
+ represent: (object) => object.toString(10)
324
+ });
325
+ var YAML_FLOAT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
326
+ var YAML_FLOAT_SPECIAL_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
327
+ function resolveYamlFloat$2(source) {
328
+ if (!YAML_FLOAT_PATTERN$1.test(source)) return NOT_RESOLVED;
329
+ let value = source.toLowerCase();
330
+ const sign = value[0] === "-" ? -1 : 1;
331
+ if ("+-".includes(value[0])) value = value.slice(1);
332
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
333
+ if (value === ".nan") return NaN;
334
+ const result = sign * parseFloat(value);
335
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN$1.test(source)) return result;
336
+ return NOT_RESOLVED;
337
+ }
338
+ function representYamlFloat$2(object) {
339
+ if (isNaN(object)) return ".nan";
340
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
341
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
342
+ if (Object.is(object, -0)) return "-0.0";
343
+ const result = object.toString(10);
344
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
345
+ }
346
+ /** @category Tags */
347
+ var floatCoreTag = defineScalarTag("tag:yaml.org,2002:float", {
348
+ implicit: true,
349
+ implicitFirstChars: [
350
+ "-",
351
+ "+",
352
+ ".",
353
+ ..."0123456789"
354
+ ],
355
+ resolve: resolveYamlFloat$2,
356
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
357
+ represent: representYamlFloat$2
358
+ });
359
+ var YAML_FLOAT_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$");
360
+ var YAML_FLOAT_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
361
+ function resolveYamlFloat$1(source, isExplicit) {
362
+ if (isExplicit) {
363
+ if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
364
+ let value = source.toLowerCase();
365
+ const sign = value[0] === "-" ? -1 : 1;
366
+ if ("+-".includes(value[0])) value = value.slice(1);
367
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
368
+ if (value === ".nan") return NaN;
369
+ const result = sign * parseFloat(value);
370
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
371
+ }
372
+ if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
373
+ const result = Number(source);
374
+ if (Number.isFinite(result)) return result;
375
+ return NOT_RESOLVED;
376
+ }
377
+ function representYamlFloat$1(object) {
378
+ if (isNaN(object)) return ".nan";
379
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
380
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
381
+ if (Object.is(object, -0)) return "-0.0";
382
+ const result = object.toString(10);
383
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
384
+ }
385
+ /** @category Tags */
386
+ var floatJsonTag = defineScalarTag("tag:yaml.org,2002:float", {
387
+ implicit: true,
388
+ implicitFirstChars: ["-", ..."0123456789"],
389
+ resolve: resolveYamlFloat$1,
390
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
391
+ represent: representYamlFloat$1
392
+ });
393
+ var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
394
+ var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
395
+ function resolveYamlFloat(source) {
396
+ if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED;
397
+ let value = source.toLowerCase().replace(/_/g, "");
398
+ const sign = value[0] === "-" ? -1 : 1;
399
+ if ("+-".includes(value[0])) value = value.slice(1);
400
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
401
+ if (value === ".nan") return NaN;
402
+ let result = 0;
403
+ if (value.includes(":")) {
404
+ for (const part of value.split(":")) result = result * 60 + Number(part);
405
+ result *= sign;
406
+ } else result = sign * parseFloat(value);
407
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result;
408
+ return NOT_RESOLVED;
409
+ }
410
+ function representYamlFloat(object) {
411
+ if (isNaN(object)) return ".nan";
412
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
413
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
414
+ if (Object.is(object, -0)) return "-0.0";
415
+ const result = object.toString(10);
416
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
417
+ }
418
+ /** @category Tags */
419
+ var floatYaml11Tag = defineScalarTag("tag:yaml.org,2002:float", {
420
+ implicit: true,
421
+ implicitFirstChars: [
422
+ "-",
423
+ "+",
424
+ ".",
425
+ ..."0123456789"
426
+ ],
427
+ resolve: resolveYamlFloat,
428
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
429
+ represent: representYamlFloat
430
+ });
431
+ /**
432
+ * Enables merge keys in {@link CORE_SCHEMA} when added with
433
+ * {@link Schema.withTags}.
434
+ *
435
+ * @category Tags
436
+ */
437
+ var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", {
438
+ implicit: true,
439
+ implicitFirstChars: ["<"],
440
+ resolve: (source, isExplicit) => {
441
+ if (source === "<<" || isExplicit && source === "") return "<<";
442
+ return NOT_RESOLVED;
443
+ },
444
+ identify: () => false
445
+ });
446
+ var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
447
+ function resolveYamlBinary(source) {
448
+ const input = source.replace(/\s/g, "");
449
+ if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED;
450
+ const binary = atob(input);
451
+ const result = new Uint8Array(binary.length);
452
+ for (let index = 0; index < binary.length; index++) result[index] = binary.charCodeAt(index);
453
+ return result;
454
+ }
455
+ function representYamlBinary(object) {
456
+ let binary = "";
457
+ for (let index = 0; index < object.length; index++) binary += String.fromCharCode(object[index]);
458
+ return btoa(binary);
459
+ }
460
+ /**
461
+ * The `!!binary` tag, represented as a `Uint8Array`.
462
+ *
463
+ * @category Tags
464
+ */
465
+ var binaryTag = defineScalarTag("tag:yaml.org,2002:binary", {
466
+ resolve: resolveYamlBinary,
467
+ identify: (object) => Object.prototype.toString.call(object) === "[object Uint8Array]",
468
+ represent: representYamlBinary
469
+ });
470
+ var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
471
+ var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
472
+ function makeUtcDate(year, month, day, hour = 0, minute = 0, second = 0, fraction = 0) {
473
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
474
+ date.setUTCFullYear(year, month, day);
475
+ return date;
476
+ }
477
+ function resolveYamlTimestamp(source) {
478
+ let match = YAML_DATE_REGEXP.exec(source);
479
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source);
480
+ if (match === null) return NOT_RESOLVED;
481
+ const year = +match[1];
482
+ const month = +match[2] - 1;
483
+ const day = +match[3];
484
+ if (!match[4]) {
485
+ const date = makeUtcDate(year, month, day);
486
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED;
487
+ return date;
488
+ }
489
+ const hour = +match[4];
490
+ const minute = +match[5];
491
+ const second = +match[6];
492
+ let fraction = 0;
493
+ if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED;
494
+ if (match[7]) {
495
+ let value = match[7].slice(0, 3);
496
+ while (value.length < 3) value += "0";
497
+ fraction = +value;
498
+ }
499
+ const date = makeUtcDate(year, month, day, hour, minute, second, fraction);
500
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED;
501
+ if (match[9]) {
502
+ const offsetHour = +match[10];
503
+ const offsetMinute = +(match[11] || 0);
504
+ if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED;
505
+ const offset = (offsetHour * 60 + offsetMinute) * 6e4;
506
+ date.setTime(date.getTime() - (match[9] === "-" ? -offset : offset));
507
+ }
508
+ return date;
509
+ }
510
+ /**
511
+ * The YAML 1.1 `!!timestamp` tag, represented as a JavaScript `Date`.
512
+ *
513
+ * @category Tags
514
+ */
515
+ var timestampTag = defineScalarTag("tag:yaml.org,2002:timestamp", {
516
+ implicit: true,
517
+ implicitFirstChars: [..."0123456789"],
518
+ resolve: resolveYamlTimestamp,
519
+ identify: (object) => object instanceof Date,
520
+ represent: (object) => object.toISOString()
521
+ });
522
+ /** @category Tags */
523
+ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
524
+ create: () => [],
525
+ addItem: (container, item) => {
526
+ container.push(item);
527
+ },
528
+ identify: Array.isArray
529
+ });
530
+ function isPlainObject(data) {
531
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
532
+ const prototype = Object.getPrototypeOf(data);
533
+ return prototype === null || prototype === Object.prototype;
534
+ }
535
+ function pick(object, keys) {
536
+ const result = {};
537
+ for (const key of keys) if (object[key] !== void 0) result[key] = object[key];
538
+ return result;
539
+ }
540
+ /**
541
+ * Provided only for YAML 1.1 compatibility and supported by the loader only.
542
+ * JavaScript has no dedicated class to represent this type, so it cannot be
543
+ * identified and dumped.
544
+ *
545
+ * ```yaml
546
+ * !!omap
547
+ * - one: 1
548
+ * - two: 2
549
+ * ```
550
+ *
551
+ * is loaded as
552
+ *
553
+ * ```javascript
554
+ * [
555
+ * { one: 1 },
556
+ * { two: 2 }
557
+ * ]
558
+ * ```
559
+ *
560
+ * @category Tags
561
+ */
562
+ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
563
+ create: () => ({
564
+ list: [],
565
+ seen: /* @__PURE__ */ new Set()
566
+ }),
567
+ addItem: (carrier, item) => {
568
+ let key;
569
+ if (item instanceof Map) {
570
+ if (item.size !== 1) return "cannot resolve an ordered map item";
571
+ key = item.keys().next().value;
572
+ } else if (isPlainObject(item)) {
573
+ const itemKeys = Object.keys(item);
574
+ if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
575
+ key = itemKeys[0];
576
+ } else return "cannot resolve an ordered map item";
577
+ if (carrier.seen.has(key)) return "duplicate key in ordered map";
578
+ carrier.seen.add(key);
579
+ carrier.list.push(item);
580
+ return "";
581
+ },
582
+ finalize: (carrier) => carrier.list,
583
+ identify: () => false
584
+ });
585
+ /**
586
+ * Provided only for YAML 1.1 compatibility and supported by the loader only.
587
+ * JavaScript has no dedicated class to represent this type, so it cannot be
588
+ * identified and dumped.
589
+ *
590
+ * ```yaml
591
+ * !!pairs
592
+ * - one: 1
593
+ * - two: 2
594
+ * ```
595
+ *
596
+ * is loaded as
597
+ *
598
+ * ```javascript
599
+ * [
600
+ * ['one', 1],
601
+ * ['two', 2]
602
+ * ]
603
+ * ```
604
+ *
605
+ * @category Tags
606
+ */
607
+ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
608
+ create: () => [],
609
+ addItem: (container, item) => {
610
+ if (item instanceof Map) {
611
+ if (item.size !== 1) return "cannot resolve a pairs item";
612
+ container.push(item.entries().next().value);
613
+ return "";
614
+ }
615
+ if (Object.prototype.toString.call(item) !== "[object Object]") return "cannot resolve a pairs item";
616
+ const object = item;
617
+ const keys = Object.keys(object);
618
+ if (keys.length !== 1) return "cannot resolve a pairs item";
619
+ container.push([keys[0], object[keys[0]]]);
620
+ return "";
621
+ },
622
+ identify: () => false
623
+ });
624
+ /**
625
+ * This is the default mapping implementation. It uses `{}` objects and has only
626
+ * partial functionality due to language limitations. This choice was made
627
+ * because users expect to get JavaScript objects, and it was left unchanged to
628
+ * avoid too many breaking changes in the v5 release.
629
+ *
630
+ * Side effects:
631
+ *
632
+ * - `Object.hasOwn()` checks or `for...of` loops are required for safe use (to
633
+ * avoid falling through to prototypes).
634
+ * - Only scalar string keys are supported properly.
635
+ * - Other scalar keys, such as `null` and numbers, are converted to strings.
636
+ * This is historical behaviour, and it can cause side effects such as
637
+ * problems with `!!merge`.
638
+ *
639
+ * Note that non-string scalar keys may be deprecated in future versions.
640
+ *
641
+ * Ideally, use {@link realMapTag} instead.
642
+ *
643
+ * @category Tags
644
+ */
645
+ var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
646
+ create: () => ({}),
647
+ identify: isPlainObject,
648
+ represent: (o) => {
649
+ const map = /* @__PURE__ */ new Map();
650
+ for (const key of Object.keys(o)) map.set(key, o[key]);
651
+ return map;
652
+ },
653
+ addPair: (container, key, value) => {
654
+ if (key !== null && typeof key === "object") return "object-based map does not support complex keys";
655
+ const normalizedKey = String(key);
656
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
657
+ value,
658
+ enumerable: true,
659
+ configurable: true,
660
+ writable: true
661
+ });
662
+ else container[normalizedKey] = value;
663
+ return "";
664
+ },
665
+ has: (container, key) => {
666
+ if (key !== null && typeof key === "object") return false;
667
+ return Object.prototype.hasOwnProperty.call(container, String(key));
668
+ },
669
+ keys: (container) => Object.keys(container),
670
+ get: (container, key) => {
671
+ const normalizedKey = String(key);
672
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
673
+ return container[normalizedKey];
674
+ }
675
+ });
676
+ /**
677
+ * The YAML 1.1 `!!set` tag, represented as a JavaScript `Set`.
678
+ *
679
+ * @category Tags
680
+ */
681
+ var setTag = defineMappingTag("tag:yaml.org,2002:set", {
682
+ create: () => /* @__PURE__ */ new Set(),
683
+ identify: (data) => data instanceof Set,
684
+ represent: (data) => {
685
+ const map = /* @__PURE__ */ new Map();
686
+ for (const key of data) map.set(key, null);
687
+ return map;
688
+ },
689
+ addPair: (container, key, value) => {
690
+ if (value !== null) return "cannot resolve a set item";
691
+ container.add(key);
692
+ return "";
693
+ },
694
+ has: (container, key) => container.has(key),
695
+ keys: (container) => container.keys(),
696
+ get: () => null
697
+ });
698
+ function createTagDefinitionMap() {
699
+ return {
700
+ scalar: Object.create(null),
701
+ sequence: Object.create(null),
702
+ mapping: Object.create(null)
703
+ };
704
+ }
705
+ function createTagDefinitionListMap() {
706
+ return {
707
+ scalar: [],
708
+ sequence: [],
709
+ mapping: []
710
+ };
711
+ }
712
+ function compileTags(tags) {
713
+ const result = [];
714
+ for (const tag of tags) {
715
+ let index = result.length;
716
+ for (let previousIndex = 0; previousIndex < result.length; previousIndex++) {
717
+ const previous = result[previousIndex];
718
+ if (previous.nodeKind === tag.nodeKind && previous.tagName === tag.tagName && previous.matchByTagPrefix === tag.matchByTagPrefix) {
719
+ index = previousIndex;
720
+ break;
721
+ }
722
+ }
723
+ result[index] = tag;
724
+ }
725
+ return result;
726
+ }
727
+ /**
728
+ * Controls tag resolution when loading and type selection when dumping.
729
+ *
730
+ * @category Schemas
731
+ */
732
+ var Schema = class Schema {
733
+ tags;
734
+ /** @internal */
735
+ implicitScalarTags;
736
+ /**
737
+ * Dispatch implicit scalar resolvers by `source.charAt(0)`. Each bucket holds
738
+ * the resolvers that may match that key, in schema order; a key absent from
739
+ * the map uses
740
+ * {@link Schema.implicitScalarAnyFirstChar}
741
+ * (resolvers that declared no first-char constraint, so they apply to any
742
+ * first character).
743
+ */
744
+ implicitScalarByFirstChar;
745
+ implicitScalarAnyFirstChar;
746
+ /**
747
+ * The default scalar tag (`!!str`), resolved once so the composer's fallback
748
+ * for unresolved plain scalars avoids a keyed lookup per scalar.
749
+ *
750
+ * @internal
751
+ */
752
+ defaultScalarTag;
753
+ /**
754
+ * The default container tags (`!!seq` / `!!map`), used by the dumper: when a
755
+ * value is identified by its default tag, the tag is implicit and not
756
+ * printed. Undefined if the schema does not define them (then such values
757
+ * can't be dumped).
758
+ *
759
+ * @internal
760
+ */
761
+ defaultSequenceTag;
762
+ /** @internal */
763
+ defaultMappingTag;
764
+ exact;
765
+ prefix;
766
+ constructor(tags) {
767
+ const compiledTags = compileTags(tags);
768
+ const implicitScalarTags = [];
769
+ const exact = createTagDefinitionMap();
770
+ const prefix = createTagDefinitionListMap();
771
+ for (const tag of compiledTags) {
772
+ if (tag.nodeKind === "scalar" && tag.implicit) {
773
+ if (tag.matchByTagPrefix) throw new Error("Implicit scalar tags cannot match by tag prefix");
774
+ implicitScalarTags.push(tag);
775
+ }
776
+ switch (tag.nodeKind) {
777
+ case "scalar":
778
+ if (tag.matchByTagPrefix) prefix.scalar.push(tag);
779
+ else exact.scalar[tag.tagName] = tag;
780
+ break;
781
+ case "sequence":
782
+ if (tag.matchByTagPrefix) prefix.sequence.push(tag);
783
+ else exact.sequence[tag.tagName] = tag;
784
+ break;
785
+ case "mapping": if (tag.matchByTagPrefix) prefix.mapping.push(tag);
786
+ else exact.mapping[tag.tagName] = tag;
787
+ }
788
+ }
789
+ const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null);
790
+ const keys = /* @__PURE__ */ new Set();
791
+ for (const tag of implicitScalarTags) if (tag.implicitFirstChars !== null) for (const key of tag.implicitFirstChars) keys.add(key);
792
+ const implicitScalarByFirstChar = /* @__PURE__ */ new Map();
793
+ for (const key of keys) implicitScalarByFirstChar.set(key, implicitScalarTags.filter((tag) => tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1));
794
+ const defaultScalarTag = exact.scalar["tag:yaml.org,2002:str"];
795
+ if (!defaultScalarTag) throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");
796
+ this.tags = compiledTags;
797
+ this.implicitScalarTags = implicitScalarTags;
798
+ this.implicitScalarByFirstChar = implicitScalarByFirstChar;
799
+ this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar;
800
+ this.defaultScalarTag = defaultScalarTag;
801
+ this.defaultSequenceTag = exact.sequence["tag:yaml.org,2002:seq"];
802
+ this.defaultMappingTag = exact.mapping["tag:yaml.org,2002:map"];
803
+ this.exact = exact;
804
+ this.prefix = prefix;
805
+ }
806
+ /** @internal */
807
+ lookupScalarTag(tagName) {
808
+ const exactTag = this.exact.scalar[tagName];
809
+ if (exactTag) return exactTag;
810
+ for (const tag of this.prefix.scalar) if (tagName.startsWith(tag.tagName)) return tag;
811
+ }
812
+ /** @internal */
813
+ lookupSequenceTag(tagName) {
814
+ const exactTag = this.exact.sequence[tagName];
815
+ if (exactTag) return exactTag;
816
+ for (const tag of this.prefix.sequence) if (tagName.startsWith(tag.tagName)) return tag;
817
+ }
818
+ /** @internal */
819
+ lookupMappingTag(tagName) {
820
+ const exactTag = this.exact.mapping[tagName];
821
+ if (exactTag) return exactTag;
822
+ for (const tag of this.prefix.mapping) if (tagName.startsWith(tag.tagName)) return tag;
823
+ }
824
+ /** @internal */
825
+ resolveImplicitScalarTag(source) {
826
+ const candidates = this.implicitScalarByFirstChar.get(source.charAt(0)) ?? this.implicitScalarAnyFirstChar;
827
+ for (const tag of candidates) {
828
+ const value = tag.resolve(source, false, tag.tagName);
829
+ if (value !== NOT_RESOLVED) return {
830
+ value,
831
+ tag
832
+ };
833
+ }
834
+ const tag = this.defaultScalarTag;
835
+ return {
836
+ value: tag.resolve(source, false, tag.tagName),
837
+ tag
838
+ };
839
+ }
840
+ /**
841
+ * Creates a new schema with the specified tags added. If a tag already
842
+ * exists, it is replaced by the specified tag.
843
+ *
844
+ * @example
845
+ *
846
+ * ```javascript
847
+ * import { CORE_SCHEMA, mergeTag, realMapTag } from 'js-yaml'
848
+ *
849
+ * const schema = CORE_SCHEMA.withTags(mergeTag, realMapTag)
850
+ * ```
851
+ */
852
+ withTags(...tags) {
853
+ let flatTags = [];
854
+ for (const tag of tags) flatTags = flatTags.concat(tag);
855
+ return new Schema([...this.tags, ...flatTags]);
856
+ }
857
+ };
858
+ /**
859
+ * The YAML 1.2 Failsafe Schema: strings, sequences, and mappings.
860
+ *
861
+ * @category Schemas
862
+ */
863
+ var FAILSAFE_SCHEMA = new Schema([
864
+ strTag,
865
+ seqTag,
866
+ mapTag
867
+ ]);
868
+ new Schema([
869
+ ...FAILSAFE_SCHEMA.tags,
870
+ nullJsonTag,
871
+ boolJsonTag,
872
+ intJsonTag,
873
+ floatJsonTag
874
+ ]);
875
+ /**
876
+ * The default schema for the loaders. Note, {@link CORE_SCHEMA} comes
877
+ * without the `!!merge` tag. You can easily enable it if needed.
878
+ *
879
+ * @example
880
+ * Enable {@link mergeTag}:
881
+ *
882
+ * ```javascript
883
+ * import { load, CORE_SCHEMA, mergeTag } from 'js-yaml'
884
+ *
885
+ * try {
886
+ * load(data, { schema: CORE_SCHEMA.withTags(mergeTag) })
887
+ * } catch (e) {
888
+ * console.error(e)
889
+ * }
890
+ * ```
891
+ *
892
+ * @category Schemas
893
+ */
894
+ var CORE_SCHEMA = new Schema([
895
+ ...FAILSAFE_SCHEMA.tags,
896
+ nullCoreTag,
897
+ boolCoreTag,
898
+ intCoreTag,
899
+ floatCoreTag
900
+ ]);
901
+ /**
902
+ * The dumper schema for maximum compatibility. It combines all supported type
903
+ * variants from YAML 1.1 and YAML 1.2 so strings matching any of them are
904
+ * quoted. This makes the generated YAML more compatible with other parsers.
905
+ *
906
+ * The schema is based on YAML 1.1, but extends `!!int` and `!!float` to accept
907
+ * both YAML 1.1 and Core Schema forms, since Core Schema supports some forms
908
+ * that YAML 1.1 does not.
909
+ *
910
+ * @category Schemas
911
+ */
912
+ var DUMP_SCHEMA = new Schema([
913
+ ...FAILSAFE_SCHEMA.tags,
914
+ nullYaml11Tag,
915
+ boolYaml11Tag,
916
+ intYaml11Tag,
917
+ floatYaml11Tag,
918
+ timestampTag,
919
+ mergeTag,
920
+ binaryTag,
921
+ omapTag,
922
+ pairsTag,
923
+ setTag
924
+ ]).withTags({
925
+ ...intYaml11Tag,
926
+ resolve: (source, isExplicit, tagName) => {
927
+ const result = intYaml11Tag.resolve(source, isExplicit, tagName);
928
+ return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result;
929
+ }
930
+ }, {
931
+ ...floatYaml11Tag,
932
+ resolve: (source, isExplicit, tagName) => {
933
+ const result = floatYaml11Tag.resolve(source, isExplicit, tagName);
934
+ return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result;
935
+ }
936
+ });
937
+ defineMappingTag("tag:yaml.org,2002:map", {
938
+ create: () => /* @__PURE__ */ new Map(),
939
+ addPair: (container, key, value) => {
940
+ container.set(key, value);
941
+ return "";
942
+ },
943
+ has: (container, key) => container.has(key),
944
+ keys: (container) => container.keys(),
945
+ get: (container, key) => container.get(key),
946
+ identify: (data) => data instanceof Map || isPlainObject(data),
947
+ represent: (data) => {
948
+ if (data instanceof Map) return data;
949
+ const map = /* @__PURE__ */ new Map();
950
+ const obj = data;
951
+ for (const key of Object.keys(obj)) map.set(key, obj[key]);
952
+ return map;
953
+ }
954
+ });
955
+ function normalizeKey(key) {
956
+ if (Array.isArray(key)) {
957
+ const array = Array.prototype.slice.call(key);
958
+ for (let index = 0; index < array.length; index++) {
959
+ if (Array.isArray(array[index])) return null;
960
+ if (typeof array[index] === "object" && Object.prototype.toString.call(array[index]) === "[object Object]") array[index] = "[object Object]";
961
+ }
962
+ return String(array);
963
+ }
964
+ if (typeof key === "object" && Object.prototype.toString.call(key) === "[object Object]") return "[object Object]";
965
+ return String(key);
966
+ }
967
+ defineMappingTag("tag:yaml.org,2002:map", {
968
+ create: () => ({}),
969
+ identify: isPlainObject,
970
+ represent: (o) => {
971
+ const map = /* @__PURE__ */ new Map();
972
+ for (const key of Object.keys(o)) map.set(key, o[key]);
973
+ return map;
974
+ },
975
+ addPair: (container, key, value) => {
976
+ const normalizedKey = normalizeKey(key);
977
+ if (normalizedKey === null) return "nested arrays are not supported inside keys";
978
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
979
+ value,
980
+ enumerable: true,
981
+ configurable: true,
982
+ writable: true
983
+ });
984
+ else container[normalizedKey] = value;
985
+ return "";
986
+ },
987
+ has: (container, key) => {
988
+ const normalizedKey = normalizeKey(key);
989
+ return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey);
990
+ },
991
+ keys: (container) => Object.keys(container),
992
+ get: (container, key) => {
993
+ const normalizedKey = String(key);
994
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
995
+ return container[normalizedKey];
996
+ }
997
+ });
998
+ var DEFAULT_SNIPPET_OPTIONS = {
999
+ maxLength: 79,
1000
+ indent: 1,
1001
+ linesBefore: 3,
1002
+ linesAfter: 2
1003
+ };
1004
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
1005
+ let head = "";
1006
+ let tail = "";
1007
+ const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
1008
+ if (position - lineStart > maxHalfLength) {
1009
+ head = " ... ";
1010
+ lineStart = position - maxHalfLength + head.length;
1011
+ }
1012
+ if (lineEnd - position > maxHalfLength) {
1013
+ tail = " ...";
1014
+ lineEnd = position + maxHalfLength - tail.length;
1015
+ }
1016
+ return {
1017
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "โ†’") + tail,
1018
+ pos: position - lineStart + head.length
1019
+ };
1020
+ }
1021
+ function padStart(string, max) {
1022
+ return " ".repeat(Math.max(max - string.length, 0)) + string;
1023
+ }
1024
+ function makeSnippet(mark, options) {
1025
+ if (!mark.buffer) return null;
1026
+ const opts = {
1027
+ ...DEFAULT_SNIPPET_OPTIONS,
1028
+ ...options
1029
+ };
1030
+ const re = /\r?\n|\r|\0/g;
1031
+ const lineStarts = [0];
1032
+ const lineEnds = [];
1033
+ let match;
1034
+ let foundLineNo = -1;
1035
+ while (match = re.exec(mark.buffer)) {
1036
+ lineEnds.push(match.index);
1037
+ lineStarts.push(match.index + match[0].length);
1038
+ if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2;
1039
+ }
1040
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
1041
+ let result = "";
1042
+ const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length;
1043
+ const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3);
1044
+ for (let i = 1; i <= opts.linesBefore; i++) {
1045
+ if (foundLineNo - i < 0) break;
1046
+ const line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
1047
+ result = `${" ".repeat(opts.indent)}${padStart((mark.line - i + 1).toString(), lineNoLength)} | ${line.str}\n${result}`;
1048
+ }
1049
+ const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
1050
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line.str}\n`;
1051
+ result += `${"-".repeat(opts.indent + lineNoLength + 3 + line.pos)}^\n`;
1052
+ for (let i = 1; i <= opts.linesAfter; i++) {
1053
+ if (foundLineNo + i >= lineEnds.length) break;
1054
+ const line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
1055
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + i + 1).toString(), lineNoLength)} | ${line.str}\n`;
1056
+ }
1057
+ return result.replace(/\n$/, "");
1058
+ }
1059
+ function formatError(exception, compact) {
1060
+ let where = "";
1061
+ if (!exception.mark) return exception.reason;
1062
+ if (exception.mark.name) where += `in "${exception.mark.name}" `;
1063
+ where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`;
1064
+ if (!compact && exception.mark.snippet) where += `\n\n${exception.mark.snippet}`;
1065
+ return `${exception.reason} ${where}`;
1066
+ }
1067
+ /**
1068
+ * A YAML error. Unlike an ordinary `Error`, it adds a source snippet showing
1069
+ * the location of the problem to the error message, when available.
1070
+ *
1071
+ * @category Main
1072
+ */
1073
+ var YAMLException = class YAMLException extends Error {
1074
+ reason;
1075
+ mark;
1076
+ /**
1077
+ * Optional `mark` contains source snippet data. Usually, use
1078
+ * {@link YAMLException.throwAt} instead of passing it directly.
1079
+ */
1080
+ constructor(reason, mark) {
1081
+ super();
1082
+ this.name = "YAMLException";
1083
+ this.reason = reason;
1084
+ this.mark = mark;
1085
+ this.message = formatError(this, false);
1086
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
1087
+ }
1088
+ /**
1089
+ * Returns the formatted error, omitting the source snippet in compact mode.
1090
+ */
1091
+ toString(compact) {
1092
+ return `${this.name}: ${formatError(this, compact)}`;
1093
+ }
1094
+ /**
1095
+ * Builds a YAMLException with a source snippet and throws it. `source` is
1096
+ * the raw input text; `position` is an offset into it.
1097
+ */
1098
+ static throwAt(source, position, message, filename = "") {
1099
+ let line = 0;
1100
+ let lineStart = 0;
1101
+ for (let index = 0; index < position; index++) {
1102
+ const ch = source.charCodeAt(index);
1103
+ if (ch === 10) {
1104
+ line++;
1105
+ lineStart = index + 1;
1106
+ } else if (ch === 13) {
1107
+ line++;
1108
+ if (source.charCodeAt(index + 1) === 10) index++;
1109
+ lineStart = index + 1;
1110
+ }
1111
+ }
1112
+ const mark = {
1113
+ name: filename,
1114
+ buffer: source,
1115
+ position,
1116
+ line,
1117
+ column: position - lineStart
1118
+ };
1119
+ mark.snippet = makeSnippet(mark);
1120
+ throw new YAMLException(message, mark);
1121
+ }
1122
+ };
1123
+ /** @category Events */
1124
+ var EVENT_ID = {
1125
+ DOCUMENT: 1,
1126
+ SEQUENCE: 2,
1127
+ MAPPING: 3,
1128
+ SCALAR: 4,
1129
+ ALIAS: 5,
1130
+ POP: 6
1131
+ };
1132
+ /** @category Nodes */
1133
+ var SCALAR_STYLE = {
1134
+ PLAIN: 1,
1135
+ SINGLE_QUOTED: 2,
1136
+ DOUBLE_QUOTED: 3,
1137
+ LITERAL_BLOCK: 4,
1138
+ FOLDED_BLOCK: 5
1139
+ };
1140
+ /** @category Nodes */
1141
+ var COLLECTION_STYLE = {
1142
+ BLOCK: 1,
1143
+ FLOW: 2
1144
+ };
1145
+ /** @category Nodes */
1146
+ var CHOMPING_MODE = {
1147
+ CLIP: 1,
1148
+ STRIP: 2,
1149
+ KEEP: 3
1150
+ };
1151
+ var NO_RANGE$3 = -1;
1152
+ function simpleEscapeSequence(c) {
1153
+ switch (c) {
1154
+ case 48: return "\0";
1155
+ case 97: return "\x07";
1156
+ case 98: return "\b";
1157
+ case 116: return " ";
1158
+ case 9: return " ";
1159
+ case 110: return "\n";
1160
+ case 118: return "\v";
1161
+ case 102: return "\f";
1162
+ case 114: return "\r";
1163
+ case 101: return "\x1B";
1164
+ case 32: return " ";
1165
+ case 34: return "\"";
1166
+ case 47: return "/";
1167
+ case 92: return "\\";
1168
+ case 78: return "ย…";
1169
+ case 95: return "\xA0";
1170
+ case 76: return "\u2028";
1171
+ case 80: return "\u2029";
1172
+ default: return "";
1173
+ }
1174
+ }
1175
+ var simpleEscapeCheck = new Array(256);
1176
+ var simpleEscapeMap = new Array(256);
1177
+ for (let i = 0; i < 256; i++) {
1178
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1179
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
1180
+ }
1181
+ function charFromCodepoint(c) {
1182
+ if (c <= 65535) return String.fromCharCode(c);
1183
+ return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
1184
+ }
1185
+ function fromHexCode$1(c) {
1186
+ if (c >= 48 && c <= 57) return c - 48;
1187
+ return (c | 32) - 97 + 10;
1188
+ }
1189
+ function escapedHexLen$1(c) {
1190
+ if (c === 120) return 2;
1191
+ if (c === 117) return 4;
1192
+ return 8;
1193
+ }
1194
+ function skipFoldedBreaks(input, position, end) {
1195
+ let breaks = 0;
1196
+ while (position < end) {
1197
+ const ch = input.charCodeAt(position);
1198
+ if (ch === 10) {
1199
+ breaks++;
1200
+ position++;
1201
+ } else if (ch === 13) {
1202
+ breaks++;
1203
+ position++;
1204
+ if (input.charCodeAt(position) === 10) position++;
1205
+ } else if (ch === 32 || ch === 9) position++;
1206
+ else break;
1207
+ }
1208
+ return {
1209
+ position,
1210
+ breaks
1211
+ };
1212
+ }
1213
+ function foldedBreaks(count) {
1214
+ if (count === 1) return " ";
1215
+ return "\n".repeat(count - 1);
1216
+ }
1217
+ function getPlainValue(input, start, end) {
1218
+ let result = "";
1219
+ let position = start;
1220
+ let captureStart = start;
1221
+ let captureEnd = start;
1222
+ while (position < end) {
1223
+ const ch = input.charCodeAt(position);
1224
+ if (ch === 10 || ch === 13) {
1225
+ result += input.slice(captureStart, captureEnd);
1226
+ const fold = skipFoldedBreaks(input, position, end);
1227
+ result += foldedBreaks(fold.breaks);
1228
+ position = captureStart = captureEnd = fold.position;
1229
+ } else {
1230
+ position++;
1231
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1232
+ }
1233
+ }
1234
+ return result + input.slice(captureStart, captureEnd);
1235
+ }
1236
+ function getSingleQuotedValue(input, start, end) {
1237
+ let result = "";
1238
+ let position = start;
1239
+ let captureStart = start;
1240
+ let captureEnd = start;
1241
+ while (position < end) {
1242
+ const ch = input.charCodeAt(position);
1243
+ if (ch === 39) {
1244
+ result += input.slice(captureStart, position) + "'";
1245
+ position += 2;
1246
+ captureStart = captureEnd = position;
1247
+ } else if (ch === 10 || ch === 13) {
1248
+ result += input.slice(captureStart, captureEnd);
1249
+ const fold = skipFoldedBreaks(input, position, end);
1250
+ result += foldedBreaks(fold.breaks);
1251
+ position = captureStart = captureEnd = fold.position;
1252
+ } else {
1253
+ position++;
1254
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1255
+ }
1256
+ }
1257
+ return result + input.slice(captureStart, end);
1258
+ }
1259
+ function getDoubleQuotedValue(input, start, end) {
1260
+ let result = "";
1261
+ let position = start;
1262
+ let captureStart = start;
1263
+ let captureEnd = start;
1264
+ while (position < end) {
1265
+ const ch = input.charCodeAt(position);
1266
+ if (ch === 92) {
1267
+ result += input.slice(captureStart, position);
1268
+ position++;
1269
+ const escaped = input.charCodeAt(position);
1270
+ if (escaped === 10 || escaped === 13) position = skipFoldedBreaks(input, position, end).position;
1271
+ else if (escaped < 256 && simpleEscapeCheck[escaped]) {
1272
+ result += simpleEscapeMap[escaped];
1273
+ position++;
1274
+ } else {
1275
+ let hexLength = escapedHexLen$1(escaped);
1276
+ let hexResult = 0;
1277
+ for (; hexLength > 0; hexLength--) {
1278
+ position++;
1279
+ const digit = fromHexCode$1(input.charCodeAt(position));
1280
+ hexResult = (hexResult << 4) + digit;
1281
+ }
1282
+ result += charFromCodepoint(hexResult);
1283
+ position++;
1284
+ }
1285
+ captureStart = captureEnd = position;
1286
+ } else if (ch === 10 || ch === 13) {
1287
+ result += input.slice(captureStart, captureEnd);
1288
+ const fold = skipFoldedBreaks(input, position, end);
1289
+ result += foldedBreaks(fold.breaks);
1290
+ position = captureStart = captureEnd = fold.position;
1291
+ } else {
1292
+ position++;
1293
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1294
+ }
1295
+ }
1296
+ return result + input.slice(captureStart, end);
1297
+ }
1298
+ function getBlockValue(input, start, end, indent, chomping, folded) {
1299
+ const textIndent = indent < 0 ? 0 : indent;
1300
+ const region = input.slice(start, end).replace(/\r\n?/g, "\n");
1301
+ const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n");
1302
+ let result = "";
1303
+ let didReadContent = false;
1304
+ let emptyLines = 0;
1305
+ let atMoreIndented = false;
1306
+ for (const line of lines) {
1307
+ let column = 0;
1308
+ while (column < textIndent && line.charCodeAt(column) === 32) column++;
1309
+ if (indent < 0 || column >= line.length) {
1310
+ emptyLines++;
1311
+ continue;
1312
+ }
1313
+ const content = line.slice(textIndent);
1314
+ const first = content.charCodeAt(0);
1315
+ if (folded) if (first === 32 || first === 9) {
1316
+ atMoreIndented = true;
1317
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1318
+ } else if (atMoreIndented) {
1319
+ atMoreIndented = false;
1320
+ result += "\n".repeat(emptyLines + 1);
1321
+ } else if (emptyLines === 0) {
1322
+ if (didReadContent) result += " ";
1323
+ } else result += "\n".repeat(emptyLines);
1324
+ else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1325
+ result += content;
1326
+ didReadContent = true;
1327
+ emptyLines = 0;
1328
+ }
1329
+ if (chomping === CHOMPING_MODE.KEEP) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1330
+ else if (chomping !== CHOMPING_MODE.STRIP) {
1331
+ if (didReadContent) result += "\n";
1332
+ }
1333
+ return result;
1334
+ }
1335
+ /**
1336
+ * Decodes the scalar referenced by event offsets in `input`.
1337
+ *
1338
+ * @category Events
1339
+ */
1340
+ function getScalarValue(input, scalar) {
1341
+ if (scalar.valueStart === NO_RANGE$3) return "";
1342
+ const { valueStart, valueEnd } = scalar;
1343
+ if (scalar.fast) return input.slice(valueStart, valueEnd);
1344
+ switch (scalar.style) {
1345
+ case SCALAR_STYLE.SINGLE_QUOTED: return getSingleQuotedValue(input, valueStart, valueEnd);
1346
+ case SCALAR_STYLE.DOUBLE_QUOTED: return getDoubleQuotedValue(input, valueStart, valueEnd);
1347
+ case SCALAR_STYLE.LITERAL_BLOCK: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false);
1348
+ case SCALAR_STYLE.FOLDED_BLOCK: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true);
1349
+ default: return getPlainValue(input, valueStart, valueEnd);
1350
+ }
1351
+ }
1352
+ var DEFAULT_TAG_HANDLERS = Object.assign(Object.create(null), {
1353
+ "!": "!",
1354
+ "!!": "tag:yaml.org,2002:"
1355
+ });
1356
+ function tagPercentEncode(source) {
1357
+ return encodeURI(source).replace(/!/g, "%21");
1358
+ }
1359
+ function tagNameFull(rawTag, tagHandlers) {
1360
+ if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1));
1361
+ const handleEnd = rawTag.indexOf("!", 1);
1362
+ const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1);
1363
+ const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle;
1364
+ return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length));
1365
+ }
1366
+ function tagNameShort(fullTag) {
1367
+ let tag = fullTag;
1368
+ if (tag.charCodeAt(0) === 33) {
1369
+ tag = tag.slice(1);
1370
+ return `!${tagPercentEncode(tag)}`;
1371
+ }
1372
+ if (tag.slice(0, 18) === "tag:yaml.org,2002:") return `!!${tagPercentEncode(tag.slice(18))}`;
1373
+ return `!<${tagPercentEncode(tag)}>`;
1374
+ }
1375
+ var NO_RANGE$2 = -1;
1376
+ var MERGE_TAG_NAME = "tag:yaml.org,2002:merge";
1377
+ var DEFAULT_CONSTRUCTOR_OPTIONS = {
1378
+ filename: "",
1379
+ schema: CORE_SCHEMA,
1380
+ json: false,
1381
+ maxTotalMergeKeys: 1e4,
1382
+ maxAliases: -1
1383
+ };
1384
+ function eventPosition$1(event) {
1385
+ if ("tagStart" in event && event.tagStart !== NO_RANGE$2) return event.tagStart;
1386
+ if ("anchorStart" in event && event.anchorStart !== NO_RANGE$2) return event.anchorStart;
1387
+ if ("valueStart" in event && event.valueStart !== NO_RANGE$2) return event.valueStart;
1388
+ if ("start" in event) return event.start;
1389
+ return 0;
1390
+ }
1391
+ function throwError$1(state, message) {
1392
+ YAMLException.throwAt(state.source, state.position, message, state.filename);
1393
+ }
1394
+ function finalizeCollection(state, position, tag, carrier) {
1395
+ try {
1396
+ return tag.finalize(carrier);
1397
+ } catch (error) {
1398
+ if (error instanceof YAMLException) throw error;
1399
+ YAMLException.throwAt(state.source, position, error instanceof Error ? error.message : String(error), state.filename);
1400
+ }
1401
+ }
1402
+ function constructScalar(state, event) {
1403
+ const source = getScalarValue(state.source, event);
1404
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1405
+ const strTag = state.schema.defaultScalarTag;
1406
+ if (rawTag !== "") {
1407
+ if (rawTag === "!") return {
1408
+ value: source,
1409
+ tag: strTag
1410
+ };
1411
+ const tagName = tagNameFull(rawTag, state.tagHandlers);
1412
+ const scalarTag = state.schema.lookupScalarTag(tagName);
1413
+ if (scalarTag) {
1414
+ const result = scalarTag.resolve(source, true, tagName);
1415
+ if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1416
+ return {
1417
+ value: result,
1418
+ tag: scalarTag
1419
+ };
1420
+ }
1421
+ const collectionTagDef = state.schema.lookupMappingTag(tagName) ?? state.schema.lookupSequenceTag(tagName);
1422
+ if (collectionTagDef) {
1423
+ if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1424
+ const carrier = collectionTagDef.create(tagName);
1425
+ return {
1426
+ value: collectionTagDef.carrierIsResult ? carrier : finalizeCollection(state, state.position, collectionTagDef, carrier),
1427
+ tag: collectionTagDef
1428
+ };
1429
+ }
1430
+ throwError$1(state, `unknown scalar tag !<${tagName}>`);
1431
+ }
1432
+ if (event.style === SCALAR_STYLE.PLAIN) return state.schema.resolveImplicitScalarTag(source);
1433
+ return {
1434
+ value: strTag.resolve(source, false, strTag.tagName),
1435
+ tag: strTag
1436
+ };
1437
+ }
1438
+ function collectionTagName(state, event, defaultTagName) {
1439
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1440
+ return rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers);
1441
+ }
1442
+ function isMappingTag(tag) {
1443
+ return tag.nodeKind === "mapping";
1444
+ }
1445
+ function chargeMergeWork(state) {
1446
+ state.totalMergeKeys++;
1447
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1448
+ }
1449
+ function mergeKeys(state, frame, source, sourceTag) {
1450
+ chargeMergeWork(state);
1451
+ for (const sourceKey of sourceTag.keys(source)) {
1452
+ chargeMergeWork(state);
1453
+ if (frame.tag.has(frame.value, sourceKey)) continue;
1454
+ const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1455
+ if (err) throwError$1(state, err);
1456
+ frame.overridable ??= /* @__PURE__ */ new Set();
1457
+ frame.overridable.add(sourceKey);
1458
+ }
1459
+ }
1460
+ function mergeSource(state, frame, source, sourceTag) {
1461
+ state.position = frame.keyPosition;
1462
+ if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
1463
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1464
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1465
+ for (const element of source) {
1466
+ const elementTag = state.nodeTags.get(element);
1467
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1468
+ mergeKeys(state, frame, element, elementTag);
1469
+ }
1470
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1471
+ }
1472
+ function addMappingValue(state, frame, key, value, tag) {
1473
+ state.position = frame.keyPosition;
1474
+ if (frame.keyIsMerge) {
1475
+ mergeSource(state, frame, value, tag);
1476
+ return;
1477
+ }
1478
+ if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) throwError$1(state, "duplicated mapping key");
1479
+ const err = frame.tag.addPair(frame.value, key, value);
1480
+ if (err) throwError$1(state, err);
1481
+ frame.overridable?.delete(key);
1482
+ }
1483
+ function addValue(state, value, tag) {
1484
+ const frame = state.frames[state.frames.length - 1];
1485
+ if (frame.kind === "document") {
1486
+ frame.value = value;
1487
+ frame.hasValue = true;
1488
+ } else if (frame.kind === "sequence") {
1489
+ if (isMappingTag(tag)) state.nodeTags.set(value, tag);
1490
+ const err = frame.tag.addItem(frame.value, value, frame.index++);
1491
+ if (err) throwError$1(state, err);
1492
+ } else if (frame.hasKey) {
1493
+ const key = frame.key;
1494
+ frame.key = void 0;
1495
+ frame.hasKey = false;
1496
+ addMappingValue(state, frame, key, value, tag);
1497
+ } else {
1498
+ frame.key = value;
1499
+ frame.keyPosition = state.position;
1500
+ frame.hasKey = true;
1501
+ frame.keyIsMerge = tag.tagName === MERGE_TAG_NAME;
1502
+ }
1503
+ }
1504
+ function storeAnchor(state, event, value, tag, isValueFinal) {
1505
+ if (event.anchorStart !== NO_RANGE$2) {
1506
+ const anchor = {
1507
+ value,
1508
+ tag,
1509
+ isValueFinal
1510
+ };
1511
+ state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor);
1512
+ return anchor;
1513
+ }
1514
+ return null;
1515
+ }
1516
+ /**
1517
+ * Constructs JavaScript documents directly from parser events, without an
1518
+ * intermediate AST.
1519
+ *
1520
+ * @category Events
1521
+ */
1522
+ function constructFromEvents(events, options) {
1523
+ const state = {
1524
+ ...DEFAULT_CONSTRUCTOR_OPTIONS,
1525
+ ...options,
1526
+ events,
1527
+ documents: [],
1528
+ eventIndex: 0,
1529
+ position: 0,
1530
+ frames: [],
1531
+ anchors: /* @__PURE__ */ new Map(),
1532
+ nodeTags: /* @__PURE__ */ new Map(),
1533
+ tagHandlers: Object.create(null),
1534
+ totalMergeKeys: 0,
1535
+ aliasCount: 0
1536
+ };
1537
+ while (state.eventIndex < state.events.length) {
1538
+ const event = state.events[state.eventIndex++];
1539
+ state.position = eventPosition$1(event);
1540
+ switch (event.type) {
1541
+ case EVENT_ID.DOCUMENT:
1542
+ state.anchors = /* @__PURE__ */ new Map();
1543
+ state.nodeTags = /* @__PURE__ */ new Map();
1544
+ state.aliasCount = 0;
1545
+ state.tagHandlers = Object.create(null);
1546
+ for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix;
1547
+ state.frames.push({
1548
+ kind: "document",
1549
+ position: state.position,
1550
+ value: void 0,
1551
+ hasValue: false
1552
+ });
1553
+ break;
1554
+ case EVENT_ID.SCALAR: {
1555
+ const { value, tag } = constructScalar(state, event);
1556
+ storeAnchor(state, event, value, tag, true);
1557
+ addValue(state, value, tag);
1558
+ break;
1559
+ }
1560
+ case EVENT_ID.SEQUENCE: {
1561
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:seq");
1562
+ const tag = state.schema.lookupSequenceTag(tagName);
1563
+ if (!tag) throwError$1(state, `unknown sequence tag !<${tagName}>`);
1564
+ const value = tag.create(tagName);
1565
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1566
+ state.frames.push({
1567
+ kind: "sequence",
1568
+ position: state.position,
1569
+ value,
1570
+ tag,
1571
+ anchor,
1572
+ index: 0
1573
+ });
1574
+ break;
1575
+ }
1576
+ case EVENT_ID.MAPPING: {
1577
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:map");
1578
+ const tag = state.schema.lookupMappingTag(tagName);
1579
+ if (!tag) throwError$1(state, `unknown mapping tag !<${tagName}>`);
1580
+ const value = tag.create(tagName);
1581
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1582
+ state.frames.push({
1583
+ kind: "mapping",
1584
+ position: state.position,
1585
+ value,
1586
+ tag,
1587
+ anchor,
1588
+ key: void 0,
1589
+ keyPosition: state.position,
1590
+ hasKey: false,
1591
+ keyIsMerge: false,
1592
+ overridable: null
1593
+ });
1594
+ break;
1595
+ }
1596
+ case EVENT_ID.ALIAS: {
1597
+ if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`);
1598
+ const name = state.source.slice(event.anchorStart, event.anchorEnd);
1599
+ const anchor = state.anchors.get(name);
1600
+ if (!anchor) throwError$1(state, `unidentified alias "${name}"`);
1601
+ if (!anchor.isValueFinal) throwError$1(state, `recursive alias "${name}" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`);
1602
+ addValue(state, anchor.value, anchor.tag);
1603
+ break;
1604
+ }
1605
+ case EVENT_ID.POP: {
1606
+ const frame = state.frames.pop();
1607
+ if (frame.kind === "mapping" && frame.hasKey) {
1608
+ state.position = frame.keyPosition;
1609
+ throwError$1(state, "incomplete mapping pair in event stream");
1610
+ }
1611
+ if (frame.kind === "document") state.documents.push(frame.value);
1612
+ else {
1613
+ const value = frame.tag.carrierIsResult ? frame.value : finalizeCollection(state, frame.position, frame.tag, frame.value);
1614
+ if (frame.anchor) {
1615
+ frame.anchor.value = value;
1616
+ frame.anchor.isValueFinal = true;
1617
+ }
1618
+ addValue(state, value, frame.tag);
1619
+ }
1620
+ break;
1621
+ }
1622
+ }
1623
+ }
1624
+ return state.documents;
1625
+ }
1626
+ var NO_RANGE$1 = -1;
1627
+ var HAS_OWN = Object.prototype.hasOwnProperty;
1628
+ var CONTEXT_FLOW_IN = 1;
1629
+ var CONTEXT_FLOW_OUT = 2;
1630
+ var CONTEXT_BLOCK_IN = 3;
1631
+ var CONTEXT_BLOCK_OUT = 4;
1632
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1633
+ var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
1634
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
1635
+ var NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`;
1636
+ var NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`;
1637
+ var PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`);
1638
+ var PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`);
1639
+ var PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`);
1640
+ var DEFAULT_PARSER_OPTIONS = {
1641
+ filename: "",
1642
+ maxDepth: 100
1643
+ };
1644
+ function addDocumentEvent(state, explicitStart, explicitEnd) {
1645
+ state.events.push({
1646
+ type: EVENT_ID.DOCUMENT,
1647
+ explicitStart,
1648
+ explicitEnd,
1649
+ directives: state.directives
1650
+ });
1651
+ }
1652
+ function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1653
+ state.events.push({
1654
+ type: EVENT_ID.SEQUENCE,
1655
+ start,
1656
+ anchorStart,
1657
+ anchorEnd,
1658
+ tagStart,
1659
+ tagEnd,
1660
+ style
1661
+ });
1662
+ }
1663
+ function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1664
+ state.events.push({
1665
+ type: EVENT_ID.MAPPING,
1666
+ start,
1667
+ anchorStart,
1668
+ anchorEnd,
1669
+ tagStart,
1670
+ tagEnd,
1671
+ style
1672
+ });
1673
+ }
1674
+ function insertFlowPairMappingEvent(state, snapshot) {
1675
+ state.events.splice(snapshot.eventsLength, 0, {
1676
+ type: EVENT_ID.MAPPING,
1677
+ start: snapshot.position,
1678
+ anchorStart: NO_RANGE$1,
1679
+ anchorEnd: NO_RANGE$1,
1680
+ tagStart: NO_RANGE$1,
1681
+ tagEnd: NO_RANGE$1,
1682
+ style: COLLECTION_STYLE.FLOW
1683
+ });
1684
+ }
1685
+ function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = CHOMPING_MODE.CLIP, indent = -1, fast = false) {
1686
+ state.events.push({
1687
+ type: EVENT_ID.SCALAR,
1688
+ valueStart,
1689
+ valueEnd,
1690
+ anchorStart,
1691
+ anchorEnd,
1692
+ tagStart,
1693
+ tagEnd,
1694
+ style,
1695
+ chomping,
1696
+ indent,
1697
+ fast
1698
+ });
1699
+ }
1700
+ function addAliasEvent(state, anchorStart, anchorEnd) {
1701
+ state.events.push({
1702
+ type: EVENT_ID.ALIAS,
1703
+ anchorStart,
1704
+ anchorEnd
1705
+ });
1706
+ }
1707
+ function addPopEvent(state) {
1708
+ state.events.push({ type: EVENT_ID.POP });
1709
+ }
1710
+ function addEmptyScalarEvent(state) {
1711
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, SCALAR_STYLE.PLAIN);
1712
+ }
1713
+ function emptyProperties() {
1714
+ return {
1715
+ anchorStart: NO_RANGE$1,
1716
+ anchorEnd: NO_RANGE$1,
1717
+ tagStart: NO_RANGE$1,
1718
+ tagEnd: NO_RANGE$1
1719
+ };
1720
+ }
1721
+ function snapshotState(state) {
1722
+ return {
1723
+ position: state.position,
1724
+ line: state.line,
1725
+ lineStart: state.lineStart,
1726
+ lineIndent: state.lineIndent,
1727
+ firstTabInLine: state.firstTabInLine,
1728
+ eventsLength: state.events.length
1729
+ };
1730
+ }
1731
+ function restoreState(state, snapshot) {
1732
+ state.position = snapshot.position;
1733
+ state.line = snapshot.line;
1734
+ state.lineStart = snapshot.lineStart;
1735
+ state.lineIndent = snapshot.lineIndent;
1736
+ state.firstTabInLine = snapshot.firstTabInLine;
1737
+ state.events.length = snapshot.eventsLength;
1738
+ }
1739
+ function throwError(state, message) {
1740
+ YAMLException.throwAt(state.input.slice(0, state.length), state.position, message, state.filename);
1741
+ }
1742
+ function isEol(c) {
1743
+ return c === 10 || c === 13;
1744
+ }
1745
+ function isWhiteSpace(c) {
1746
+ return c === 9 || c === 32;
1747
+ }
1748
+ function isWsOrEol(c) {
1749
+ return isWhiteSpace(c) || isEol(c);
1750
+ }
1751
+ function isWsOrEolOrEnd(c) {
1752
+ return c === 0 || isWsOrEol(c);
1753
+ }
1754
+ function isFlowIndicator(c) {
1755
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
1756
+ }
1757
+ function fromDecimalCode(c) {
1758
+ return c >= 48 && c <= 57 ? c - 48 : -1;
1759
+ }
1760
+ function fromHexCode(c) {
1761
+ if (c >= 48 && c <= 57) return c - 48;
1762
+ const lc = c | 32;
1763
+ if (lc >= 97 && lc <= 102) return lc - 97 + 10;
1764
+ return -1;
1765
+ }
1766
+ function escapedHexLen(c) {
1767
+ if (c === 120) return 2;
1768
+ if (c === 117) return 4;
1769
+ if (c === 85) return 8;
1770
+ return 0;
1771
+ }
1772
+ function isSimpleEscape(c) {
1773
+ return c === 48 || c === 97 || c === 98 || c === 116 || c === 9 || c === 110 || c === 118 || c === 102 || c === 114 || c === 101 || c === 32 || c === 34 || c === 47 || c === 92 || c === 78 || c === 95 || c === 76 || c === 80;
1774
+ }
1775
+ function consumeLineBreak(state) {
1776
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
1777
+ else {
1778
+ state.position++;
1779
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
1780
+ }
1781
+ state.line++;
1782
+ state.lineStart = state.position;
1783
+ state.lineIndent = 0;
1784
+ state.firstTabInLine = -1;
1785
+ }
1786
+ function skipSeparationSpace(state, allowComments) {
1787
+ let lineBreaks = 0;
1788
+ let ch = state.input.charCodeAt(state.position);
1789
+ let hasSeparation = state.position === state.lineStart || isWsOrEol(state.input.charCodeAt(state.position - 1));
1790
+ while (ch !== 0) {
1791
+ while (isWhiteSpace(ch)) {
1792
+ hasSeparation = true;
1793
+ if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position;
1794
+ ch = state.input.charCodeAt(++state.position);
1795
+ }
1796
+ if (allowComments && hasSeparation && ch === 35) do
1797
+ ch = state.input.charCodeAt(++state.position);
1798
+ while (!isEol(ch) && ch !== 0);
1799
+ if (!isEol(ch)) break;
1800
+ consumeLineBreak(state);
1801
+ lineBreaks++;
1802
+ hasSeparation = true;
1803
+ ch = state.input.charCodeAt(state.position);
1804
+ while (ch === 32) {
1805
+ state.lineIndent++;
1806
+ ch = state.input.charCodeAt(++state.position);
1807
+ }
1808
+ }
1809
+ return lineBreaks;
1810
+ }
1811
+ function testDocumentSeparator(state, position = state.position) {
1812
+ const ch = state.input.charCodeAt(position);
1813
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(position + 1) && ch === state.input.charCodeAt(position + 2)) {
1814
+ const following = state.input.charCodeAt(position + 3);
1815
+ return following === 0 || isWsOrEol(following);
1816
+ }
1817
+ return false;
1818
+ }
1819
+ function skipByteOrderMark(state) {
1820
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
1821
+ state.position++;
1822
+ state.lineStart = state.position;
1823
+ }
1824
+ }
1825
+ function testDocumentBoundary(state) {
1826
+ if (state.position !== state.lineStart) return false;
1827
+ if (testDocumentSeparator(state)) return true;
1828
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
1829
+ const snapshot = snapshotState(state);
1830
+ skipByteOrderMark(state);
1831
+ skipSeparationSpace(state, true);
1832
+ const ch = state.input.charCodeAt(state.position);
1833
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
1834
+ restoreState(state, snapshot);
1835
+ return result;
1836
+ }
1837
+ function skipUntilLineEnd(state) {
1838
+ let ch = state.input.charCodeAt(state.position);
1839
+ while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
1840
+ }
1841
+ function checkPrintable(state, start, end) {
1842
+ if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters");
1843
+ }
1844
+ function readTagProperty(state, props, inFlow) {
1845
+ if (state.input.charCodeAt(state.position) !== 33) return false;
1846
+ if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property");
1847
+ const start = state.position;
1848
+ let isVerbatim = false;
1849
+ let isNamed = false;
1850
+ let tagHandle = "!";
1851
+ let ch = state.input.charCodeAt(++state.position);
1852
+ if (ch === 60) {
1853
+ isVerbatim = true;
1854
+ ch = state.input.charCodeAt(++state.position);
1855
+ } else if (ch === 33) {
1856
+ isNamed = true;
1857
+ tagHandle = "!!";
1858
+ ch = state.input.charCodeAt(++state.position);
1859
+ }
1860
+ let suffixStart = state.position;
1861
+ let tagName;
1862
+ if (isVerbatim) {
1863
+ while (ch !== 0 && ch !== 62) ch = state.input.charCodeAt(++state.position);
1864
+ if (ch !== 62) throwError(state, "unexpected end of the stream within a verbatim tag");
1865
+ tagName = state.input.slice(suffixStart, state.position);
1866
+ state.position++;
1867
+ } else {
1868
+ while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) {
1869
+ if (ch === 33) if (!isNamed) {
1870
+ tagHandle = state.input.slice(suffixStart - 1, state.position + 1);
1871
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters");
1872
+ isNamed = true;
1873
+ suffixStart = state.position + 1;
1874
+ } else throwError(state, "tag suffix cannot contain exclamation marks");
1875
+ ch = state.input.charCodeAt(++state.position);
1876
+ }
1877
+ tagName = state.input.slice(suffixStart, state.position);
1878
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters");
1879
+ }
1880
+ if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`);
1881
+ if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`);
1882
+ props.tagStart = start;
1883
+ props.tagEnd = state.position;
1884
+ return true;
1885
+ }
1886
+ function readAnchorProperty(state, props) {
1887
+ if (state.input.charCodeAt(state.position) !== 38) return false;
1888
+ if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property");
1889
+ state.position++;
1890
+ const start = state.position;
1891
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1892
+ if (state.position === start) throwError(state, "name of an anchor node must contain at least one character");
1893
+ props.anchorStart = start;
1894
+ props.anchorEnd = state.position;
1895
+ return true;
1896
+ }
1897
+ function readAlias(state, props) {
1898
+ if (state.input.charCodeAt(state.position) !== 42) return false;
1899
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties");
1900
+ state.position++;
1901
+ const start = state.position;
1902
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1903
+ if (state.position === start) throwError(state, "name of an alias node must contain at least one character");
1904
+ addAliasEvent(state, start, state.position);
1905
+ return true;
1906
+ }
1907
+ function readFlowScalarBreak(state, nodeIndent) {
1908
+ skipSeparationSpace(state, false);
1909
+ if (state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
1910
+ }
1911
+ function readSingleQuotedScalar(state, nodeIndent, props) {
1912
+ if (state.input.charCodeAt(state.position) !== 39) return false;
1913
+ state.position++;
1914
+ const start = state.position;
1915
+ let simple = true;
1916
+ while (state.input.charCodeAt(state.position) !== 0) {
1917
+ const ch = state.input.charCodeAt(state.position);
1918
+ if (ch === 39) {
1919
+ if (state.input.charCodeAt(state.position + 1) === 39) {
1920
+ simple = false;
1921
+ state.position += 2;
1922
+ continue;
1923
+ }
1924
+ const end = state.position;
1925
+ state.position++;
1926
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1927
+ return true;
1928
+ }
1929
+ if (isEol(ch)) {
1930
+ simple = false;
1931
+ readFlowScalarBreak(state, nodeIndent);
1932
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar");
1933
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
1934
+ else state.position++;
1935
+ }
1936
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
1937
+ }
1938
+ function readDoubleQuotedScalar(state, nodeIndent, props) {
1939
+ if (state.input.charCodeAt(state.position) !== 34) return false;
1940
+ state.position++;
1941
+ const start = state.position;
1942
+ let simple = true;
1943
+ while (state.input.charCodeAt(state.position) !== 0) {
1944
+ const ch = state.input.charCodeAt(state.position);
1945
+ if (ch === 34) {
1946
+ const end = state.position;
1947
+ state.position++;
1948
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1949
+ return true;
1950
+ }
1951
+ if (ch === 92) {
1952
+ simple = false;
1953
+ const escaped = state.input.charCodeAt(++state.position);
1954
+ if (isEol(escaped)) readFlowScalarBreak(state, nodeIndent);
1955
+ else if (isSimpleEscape(escaped)) state.position++;
1956
+ else {
1957
+ let hexLength = escapedHexLen(escaped);
1958
+ if (hexLength === 0) throwError(state, "unknown escape sequence");
1959
+ while (hexLength-- > 0) {
1960
+ state.position++;
1961
+ if (fromHexCode(state.input.charCodeAt(state.position)) < 0) throwError(state, "expected hexadecimal character");
1962
+ }
1963
+ state.position++;
1964
+ }
1965
+ } else if (isEol(ch)) {
1966
+ simple = false;
1967
+ readFlowScalarBreak(state, nodeIndent);
1968
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar");
1969
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
1970
+ else state.position++;
1971
+ }
1972
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
1973
+ }
1974
+ function readBlockScalar(state, parentIndent, props) {
1975
+ const ch = state.input.charCodeAt(state.position);
1976
+ let chomping = CHOMPING_MODE.CLIP;
1977
+ let indent = -1;
1978
+ let detectedIndent = false;
1979
+ if (ch !== 124 && ch !== 62) return false;
1980
+ const style = ch === 124 ? SCALAR_STYLE.LITERAL_BLOCK : SCALAR_STYLE.FOLDED_BLOCK;
1981
+ state.position++;
1982
+ while (state.input.charCodeAt(state.position) !== 0) {
1983
+ const current = state.input.charCodeAt(state.position);
1984
+ const digit = fromDecimalCode(current);
1985
+ if (current === 43 || current === 45) {
1986
+ if (chomping !== CHOMPING_MODE.CLIP) throwError(state, "repeat of a chomping mode identifier");
1987
+ chomping = current === 43 ? CHOMPING_MODE.KEEP : CHOMPING_MODE.STRIP;
1988
+ state.position++;
1989
+ } else if (digit >= 0) {
1990
+ if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
1991
+ if (detectedIndent) throwError(state, "repeat of an indentation width identifier");
1992
+ indent = parentIndent + digit - 1;
1993
+ detectedIndent = true;
1994
+ state.position++;
1995
+ } else break;
1996
+ }
1997
+ let hadWhitespace = false;
1998
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) {
1999
+ hadWhitespace = true;
2000
+ state.position++;
2001
+ }
2002
+ if (hadWhitespace && state.input.charCodeAt(state.position) === 35) skipUntilLineEnd(state);
2003
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2004
+ else if (state.input.charCodeAt(state.position) !== 0) throwError(state, "a line break is expected");
2005
+ let contentIndent = detectedIndent ? indent : -1;
2006
+ let maxLeadingIndent = 0;
2007
+ const valueStart = state.position;
2008
+ let valueEnd = state.position;
2009
+ while (state.input.charCodeAt(state.position) !== 0) {
2010
+ const linePosition = state.position;
2011
+ let column = 0;
2012
+ while (state.input.charCodeAt(linePosition + column) === 32) column++;
2013
+ const first = state.input.charCodeAt(linePosition + column);
2014
+ if (first === 0) {
2015
+ if (contentIndent >= 0) {
2016
+ if (column > contentIndent) valueEnd = linePosition + column;
2017
+ } else if (column > 0) valueEnd = linePosition + column;
2018
+ break;
2019
+ }
2020
+ if (testDocumentBoundary(state)) break;
2021
+ if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2022
+ if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2023
+ if (first === 9 && column < parentIndent) {
2024
+ state.position = linePosition + column;
2025
+ throwError(state, "tab characters must not be used in indentation");
2026
+ }
2027
+ if (column < maxLeadingIndent) {
2028
+ state.position = linePosition + column;
2029
+ throwError(state, "bad indentation of a mapping entry");
2030
+ }
2031
+ }
2032
+ if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) {
2033
+ state.lineIndent = column;
2034
+ state.position = linePosition + column;
2035
+ break;
2036
+ }
2037
+ if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) contentIndent = column;
2038
+ const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent;
2039
+ if (first !== 0 && !isEol(first) && column < requiredIndent) {
2040
+ state.lineIndent = column;
2041
+ state.position = linePosition + column;
2042
+ break;
2043
+ }
2044
+ skipUntilLineEnd(state);
2045
+ valueEnd = state.position;
2046
+ if (isEol(state.input.charCodeAt(state.position))) {
2047
+ consumeLineBreak(state);
2048
+ valueEnd = state.position;
2049
+ }
2050
+ }
2051
+ checkPrintable(state, valueStart, valueEnd);
2052
+ addScalarEvent(state, valueStart, valueEnd, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, style, chomping, contentIndent);
2053
+ return true;
2054
+ }
2055
+ function canStartPlainScalar(state, nodeContext) {
2056
+ const ch = state.input.charCodeAt(state.position);
2057
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
2058
+ if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || inFlow && isFlowIndicator(ch)) return false;
2059
+ if (ch === 63 || ch === 45) {
2060
+ const following = state.input.charCodeAt(state.position + 1);
2061
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false;
2062
+ }
2063
+ return true;
2064
+ }
2065
+ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2066
+ if (!canStartPlainScalar(state, nodeContext)) return false;
2067
+ const start = state.position;
2068
+ let end = state.position;
2069
+ let ch = state.input.charCodeAt(state.position);
2070
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
2071
+ let multiline = false;
2072
+ while (ch !== 0) {
2073
+ if (testDocumentBoundary(state)) break;
2074
+ if (ch === 58) {
2075
+ const following = state.input.charCodeAt(state.position + 1);
2076
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
2077
+ } else if (ch === 35) {
2078
+ if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break;
2079
+ } else if (inFlow && isFlowIndicator(ch)) break;
2080
+ else if (isEol(ch)) {
2081
+ const savedPosition = state.position;
2082
+ const savedLine = state.line;
2083
+ const savedLineStart = state.lineStart;
2084
+ const savedLineIndent = state.lineIndent;
2085
+ skipSeparationSpace(state, false);
2086
+ if (state.lineIndent >= nodeIndent) {
2087
+ multiline = true;
2088
+ ch = state.input.charCodeAt(state.position);
2089
+ continue;
2090
+ }
2091
+ state.position = savedPosition;
2092
+ state.line = savedLine;
2093
+ state.lineStart = savedLineStart;
2094
+ state.lineIndent = savedLineIndent;
2095
+ break;
2096
+ }
2097
+ if (!isWhiteSpace(ch)) end = state.position + 1;
2098
+ ch = state.input.charCodeAt(++state.position);
2099
+ }
2100
+ if (end === start) return false;
2101
+ checkPrintable(state, start, end);
2102
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
2103
+ return true;
2104
+ }
2105
+ function skipFlowSeparationSpace(state, nodeIndent) {
2106
+ const startLine = state.line;
2107
+ skipSeparationSpace(state, true);
2108
+ if (state.line > startLine && state.lineIndent < nodeIndent || state.firstTabInLine !== -1 && state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
2109
+ }
2110
+ function readFlowCollection(state, nodeIndent, props) {
2111
+ const ch = state.input.charCodeAt(state.position);
2112
+ const isMapping = ch === 123;
2113
+ const start = state.position;
2114
+ let readNext = true;
2115
+ if (ch !== 91 && ch !== 123) return false;
2116
+ const terminator = isMapping ? 125 : 93;
2117
+ if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
2118
+ else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
2119
+ state.position++;
2120
+ while (state.input.charCodeAt(state.position) !== 0) {
2121
+ skipFlowSeparationSpace(state, nodeIndent);
2122
+ let ch = state.input.charCodeAt(state.position);
2123
+ if (ch === terminator) {
2124
+ state.position++;
2125
+ addPopEvent(state);
2126
+ return true;
2127
+ } else if (!readNext) throwError(state, "missed comma between flow collection entries");
2128
+ else if (ch === 44) throwError(state, "expected the node content, but found ','");
2129
+ let isPair = false;
2130
+ let isExplicitPair = false;
2131
+ if (ch === 63 && isWsOrEol(state.input.charCodeAt(state.position + 1))) {
2132
+ isPair = isExplicitPair = true;
2133
+ state.position += 1;
2134
+ skipFlowSeparationSpace(state, nodeIndent);
2135
+ }
2136
+ const entryLine = state.line;
2137
+ const entryStart = snapshotState(state);
2138
+ const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2139
+ skipFlowSeparationSpace(state, nodeIndent);
2140
+ ch = state.input.charCodeAt(state.position);
2141
+ if ((isMapping || isExplicitPair || state.line === entryLine) && ch === 58) {
2142
+ isPair = true;
2143
+ state.position++;
2144
+ skipFlowSeparationSpace(state, nodeIndent);
2145
+ if (!isMapping) {
2146
+ insertFlowPairMappingEvent(state, entryStart);
2147
+ if (!keyWasRead) addEmptyScalarEvent(state);
2148
+ } else if (!keyWasRead) addEmptyScalarEvent(state);
2149
+ if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) addEmptyScalarEvent(state);
2150
+ skipFlowSeparationSpace(state, nodeIndent);
2151
+ if (!isMapping) addPopEvent(state);
2152
+ } else if (isMapping && isPair) {
2153
+ if (!keyWasRead) addEmptyScalarEvent(state);
2154
+ addEmptyScalarEvent(state);
2155
+ } else if (isMapping) addEmptyScalarEvent(state);
2156
+ else if (isPair) {
2157
+ insertFlowPairMappingEvent(state, entryStart);
2158
+ if (!keyWasRead) addEmptyScalarEvent(state);
2159
+ addEmptyScalarEvent(state);
2160
+ addPopEvent(state);
2161
+ }
2162
+ ch = state.input.charCodeAt(state.position);
2163
+ if (ch === 44) {
2164
+ readNext = true;
2165
+ state.position++;
2166
+ } else readNext = false;
2167
+ }
2168
+ throwError(state, "unexpected end of the stream within a flow collection");
2169
+ }
2170
+ function readBlockSequence(state, nodeIndent, props) {
2171
+ if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false;
2172
+ addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2173
+ while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {
2174
+ if (state.firstTabInLine !== -1) {
2175
+ state.position = state.firstTabInLine;
2176
+ throwError(state, "tab characters must not be used in indentation");
2177
+ }
2178
+ const entryLine = state.line;
2179
+ state.position++;
2180
+ const hadBreak = skipSeparationSpace(state, true) > 0;
2181
+ if (state.firstTabInLine !== -1 && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2182
+ if (hadBreak && state.lineIndent <= nodeIndent) addEmptyScalarEvent(state);
2183
+ else parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2184
+ skipSeparationSpace(state, true);
2185
+ if (state.lineIndent < nodeIndent || state.position >= state.length) break;
2186
+ if (state.lineIndent > nodeIndent) throwError(state, "bad indentation of a sequence entry");
2187
+ if (state.line === entryLine && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2188
+ }
2189
+ addPopEvent(state);
2190
+ return true;
2191
+ }
2192
+ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2193
+ let atExplicitKey = false;
2194
+ let detected = false;
2195
+ let mappingOpened = false;
2196
+ let pendingExplicitKey = false;
2197
+ if (state.firstTabInLine !== -1) return false;
2198
+ let ch = state.input.charCodeAt(state.position);
2199
+ while (ch !== 0) {
2200
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
2201
+ state.position = state.firstTabInLine;
2202
+ throwError(state, "tab characters must not be used in indentation");
2203
+ }
2204
+ const following = state.input.charCodeAt(state.position + 1);
2205
+ const entryLine = state.line;
2206
+ if ((ch === 63 || ch === 58) && isWsOrEolOrEnd(following)) {
2207
+ if (!mappingOpened) {
2208
+ addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2209
+ mappingOpened = true;
2210
+ }
2211
+ if (ch === 63) {
2212
+ if (atExplicitKey) addEmptyScalarEvent(state);
2213
+ detected = true;
2214
+ atExplicitKey = true;
2215
+ } else if (atExplicitKey) atExplicitKey = false;
2216
+ else {
2217
+ addEmptyScalarEvent(state);
2218
+ detected = true;
2219
+ atExplicitKey = false;
2220
+ }
2221
+ state.position += 1;
2222
+ pendingExplicitKey = true;
2223
+ } else {
2224
+ if (atExplicitKey) {
2225
+ addEmptyScalarEvent(state);
2226
+ atExplicitKey = false;
2227
+ }
2228
+ const beforeKey = snapshotState(state);
2229
+ if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break;
2230
+ if (state.line === entryLine) {
2231
+ ch = state.input.charCodeAt(state.position);
2232
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2233
+ if (ch === 58) {
2234
+ ch = state.input.charCodeAt(++state.position);
2235
+ if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2236
+ if (!mappingOpened) {
2237
+ restoreState(state, beforeKey);
2238
+ addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2239
+ mappingOpened = true;
2240
+ parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
2241
+ ch = state.input.charCodeAt(state.position);
2242
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2243
+ state.position++;
2244
+ }
2245
+ detected = true;
2246
+ atExplicitKey = false;
2247
+ pendingExplicitKey = false;
2248
+ } else if (detected) throwError(state, "expected ':' after a mapping key");
2249
+ else {
2250
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2251
+ restoreState(state, beforeKey);
2252
+ return false;
2253
+ }
2254
+ return true;
2255
+ }
2256
+ } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
2257
+ else {
2258
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2259
+ restoreState(state, beforeKey);
2260
+ return false;
2261
+ }
2262
+ return true;
2263
+ }
2264
+ }
2265
+ if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) pendingExplicitKey = false;
2266
+ if (!atExplicitKey) {
2267
+ if (pendingExplicitKey) {
2268
+ addEmptyScalarEvent(state);
2269
+ pendingExplicitKey = false;
2270
+ }
2271
+ }
2272
+ skipSeparationSpace(state, true);
2273
+ ch = state.input.charCodeAt(state.position);
2274
+ if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry");
2275
+ else if (state.lineIndent < nodeIndent) break;
2276
+ }
2277
+ if (!detected) return false;
2278
+ if (atExplicitKey) addEmptyScalarEvent(state);
2279
+ if (mappingOpened) addPopEvent(state);
2280
+ return true;
2281
+ }
2282
+ function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, allowPropertyMapping = true) {
2283
+ if (state.depth >= state.maxDepth) throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`);
2284
+ state.depth++;
2285
+ let indentStatus = 1;
2286
+ let atNewLine = false;
2287
+ let hasContent = false;
2288
+ let propertyStart = null;
2289
+ const props = emptyProperties();
2290
+ let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN;
2291
+ let allowBlockCollections = allowBlockScalars;
2292
+ const allowBlockStyles = allowBlockScalars;
2293
+ if (allowToSeek && skipSeparationSpace(state, true)) {
2294
+ atNewLine = true;
2295
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2296
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2297
+ else indentStatus = -1;
2298
+ }
2299
+ if (indentStatus === 1) while (true) {
2300
+ const ch = state.input.charCodeAt(state.position);
2301
+ const propertyState = snapshotState(state);
2302
+ if (atNewLine && indentStatus !== 1 && (ch === 33 || ch === 38)) break;
2303
+ if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch === 33 || ch === 38)) {
2304
+ const fallbackState = snapshotState(state);
2305
+ const flowIndent = parentIndent + 1;
2306
+ if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) {
2307
+ state.depth--;
2308
+ return true;
2309
+ }
2310
+ restoreState(state, fallbackState);
2311
+ }
2312
+ if (atNewLine && (ch === 33 && props.tagStart !== NO_RANGE$1 || ch === 38 && props.anchorStart !== NO_RANGE$1)) break;
2313
+ if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) break;
2314
+ if (propertyStart === null) propertyStart = propertyState;
2315
+ if (skipSeparationSpace(state, true)) {
2316
+ atNewLine = true;
2317
+ allowBlockCollections = allowBlockStyles;
2318
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2319
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2320
+ else indentStatus = -1;
2321
+ } else allowBlockCollections = false;
2322
+ }
2323
+ if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact;
2324
+ if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) {
2325
+ const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1;
2326
+ const blockIndent = state.position - state.lineStart;
2327
+ if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true;
2328
+ else {
2329
+ const ch = state.input.charCodeAt(state.position);
2330
+ if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) {
2331
+ const fallbackState = snapshotState(state);
2332
+ const propertyIndent = propertyStart.position - propertyStart.lineStart;
2333
+ restoreState(state, propertyStart);
2334
+ if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) hasContent = true;
2335
+ else restoreState(state, fallbackState);
2336
+ }
2337
+ if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true;
2338
+ }
2339
+ else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props);
2340
+ }
2341
+ allowBlockScalars = allowBlockScalars && !hasContent;
2342
+ if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) {
2343
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN);
2344
+ hasContent = true;
2345
+ }
2346
+ state.depth--;
2347
+ return hasContent || props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1;
2348
+ }
2349
+ function readDirective(state) {
2350
+ if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 37) return false;
2351
+ state.position++;
2352
+ const nameStart = state.position;
2353
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2354
+ const name = state.input.slice(nameStart, state.position);
2355
+ const args = [];
2356
+ if (name.length === 0) throwError(state, "directive name must not be less than one character in length");
2357
+ while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {
2358
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++;
2359
+ if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break;
2360
+ const start = state.position;
2361
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2362
+ args.push(state.input.slice(start, state.position));
2363
+ }
2364
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2365
+ if (name === "YAML") {
2366
+ if (state.directives.some((directive) => directive.kind === "yaml")) throwError(state, "duplication of %YAML directive");
2367
+ if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument");
2368
+ const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
2369
+ if (match === null) throwError(state, "ill-formed argument of the YAML directive");
2370
+ if (parseInt(match[1], 10) !== 1) throwError(state, "unacceptable YAML version of the document");
2371
+ state.directives.push({
2372
+ kind: "yaml",
2373
+ version: args[0]
2374
+ });
2375
+ } else if (name === "TAG") {
2376
+ if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments");
2377
+ const [handle, prefix] = args;
2378
+ if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
2379
+ if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for "${handle}" tag handle`);
2380
+ if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
2381
+ state.tagHandlers[handle] = prefix;
2382
+ state.directives.push({
2383
+ kind: "tag",
2384
+ handle,
2385
+ prefix
2386
+ });
2387
+ }
2388
+ return true;
2389
+ }
2390
+ function readDocument(state) {
2391
+ state.directives = [];
2392
+ state.tagHandlers = Object.create(null);
2393
+ let hasDirectives = false;
2394
+ skipSeparationSpace(state, true);
2395
+ while (readDirective(state)) {
2396
+ hasDirectives = true;
2397
+ skipSeparationSpace(state, true);
2398
+ }
2399
+ let explicitStart = false;
2400
+ let explicitEnd = false;
2401
+ let allowCompact = true;
2402
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) {
2403
+ explicitStart = true;
2404
+ const markerLine = state.line;
2405
+ state.position += 3;
2406
+ skipSeparationSpace(state, true);
2407
+ allowCompact = state.line > markerLine;
2408
+ } else if (hasDirectives) throwError(state, "directives end mark is expected");
2409
+ const documentEventIndex = state.events.length;
2410
+ if (!explicitStart && state.position === state.lineStart && state.input.charCodeAt(state.position) === 46 && testDocumentSeparator(state)) {
2411
+ state.position += 3;
2412
+ skipSeparationSpace(state, true);
2413
+ return;
2414
+ }
2415
+ addDocumentEvent(state, explicitStart, false);
2416
+ if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) addEmptyScalarEvent(state);
2417
+ skipSeparationSpace(state, true);
2418
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
2419
+ explicitEnd = state.input.charCodeAt(state.position) === 46;
2420
+ if (explicitEnd) {
2421
+ const markerLine = state.line;
2422
+ state.position += 3;
2423
+ skipSeparationSpace(state, true);
2424
+ if (state.line === markerLine && state.position < state.length) throwError(state, "end of the stream or a document separator is expected");
2425
+ }
2426
+ }
2427
+ const documentEvent = state.events[documentEventIndex];
2428
+ if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2429
+ addPopEvent(state);
2430
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2431
+ }
2432
+ /**
2433
+ * Parses YAML into a flat event stream referencing source text by offsets.
2434
+ *
2435
+ * @category Events
2436
+ */
2437
+ function parseEvents(input, options) {
2438
+ const length = input.length;
2439
+ const state = {
2440
+ ...DEFAULT_PARSER_OPTIONS,
2441
+ ...options,
2442
+ input: `${input}\0`,
2443
+ length,
2444
+ position: 0,
2445
+ line: 0,
2446
+ lineStart: 0,
2447
+ lineIndent: 0,
2448
+ firstTabInLine: -1,
2449
+ depth: 0,
2450
+ directives: [],
2451
+ tagHandlers: Object.create(null),
2452
+ events: []
2453
+ };
2454
+ const nullpos = input.indexOf("\0");
2455
+ if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
2456
+ while (state.position < state.length) {
2457
+ skipByteOrderMark(state);
2458
+ skipSeparationSpace(state, true);
2459
+ if (state.position >= state.length) break;
2460
+ const documentStart = state.position;
2461
+ readDocument(state);
2462
+ if (state.position === documentStart)
2463
+ /* c8 ignore next */
2464
+ throwError(state, "can not read a document");
2465
+ }
2466
+ return state.events;
2467
+ }
2468
+ var DEFAULT_LOAD_OPTIONS = {
2469
+ ...DEFAULT_PARSER_OPTIONS,
2470
+ ...DEFAULT_CONSTRUCTOR_OPTIONS
2471
+ };
2472
+ function loadDocuments(input, options = {}) {
2473
+ const opts = {
2474
+ ...DEFAULT_LOAD_OPTIONS,
2475
+ ...options
2476
+ };
2477
+ const source = String(input);
2478
+ const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS);
2479
+ const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS);
2480
+ return constructFromEvents(parseEvents(source, pick(opts, PARSER_OPT_KEYS)), {
2481
+ ...pick(opts, CONSTRUCTOR_OPT_KEYS),
2482
+ source
2483
+ });
2484
+ }
2485
+ /**
2486
+ * Parses `string` as a single YAML document. Throws {@link YAMLException} on
2487
+ * error. This function does not understand multi-document or empty sources; it
2488
+ * throws an exception on those.
2489
+ *
2490
+ * > [!NOTE]
2491
+ * > 1. When processing untrusted input, see the
2492
+ * > [security considerations](../docs/safety.md).
2493
+ * > 2. All exceptions MUST be caught, not just {@link YAMLException}.
2494
+ * > 3. The default {@link CORE_SCHEMA} comes without the `!!merge` tag. You can
2495
+ * > easily enable it if needed.
2496
+ * > 4. The default {@link mapTag} is `{}`-object based, with known limitations
2497
+ * > (see description). For full compatibility use {@link realMapTag}
2498
+ * > instead (it uses native JS `Map`).
2499
+ *
2500
+ * @example
2501
+ * Enable {@link mergeTag} and {@link realMapTag}:
2502
+ *
2503
+ * ```javascript
2504
+ * import { load, CORE_SCHEMA, mergeTag, realMapTag } from 'js-yaml'
2505
+ *
2506
+ * try {
2507
+ * load(data, { schema: CORE_SCHEMA.withTags(mergeTag, realMapTag) })
2508
+ * } catch (e) {
2509
+ * console.error(e)
2510
+ * }
2511
+ * ```
2512
+ *
2513
+ * @category Main
2514
+ */
2515
+ function load(input, options) {
2516
+ const documents = loadDocuments(input, options);
2517
+ if (documents.length === 0) throw new YAMLException("expected a document, but the input is empty");
2518
+ if (documents.length === 1) return documents[0];
2519
+ throw new YAMLException("expected a single document in the stream, but found more");
2520
+ }
2521
+ var INVALID = Symbol("INVALID");
2522
+ function buildRepresentTypes(schema) {
2523
+ const defaultTags = new Set([
2524
+ schema.defaultScalarTag,
2525
+ schema.defaultSequenceTag,
2526
+ schema.defaultMappingTag
2527
+ ].filter((t) => t !== void 0));
2528
+ const implicitScalars = schema.implicitScalarTags;
2529
+ const explicitTags = schema.tags.filter((t) => !(t.nodeKind === "scalar" && t.implicit) && !defaultTags.has(t));
2530
+ const defaultTagsLast = schema.tags.filter((t) => defaultTags.has(t));
2531
+ return [
2532
+ ...implicitScalars.map((tag) => ({
2533
+ tag,
2534
+ implicitTag: true
2535
+ })),
2536
+ ...explicitTags.map((tag) => ({
2537
+ tag,
2538
+ implicitTag: false
2539
+ })),
2540
+ ...defaultTagsLast.map((tag) => ({
2541
+ tag,
2542
+ implicitTag: true
2543
+ }))
2544
+ ];
2545
+ }
2546
+ function matchTag(state, object) {
2547
+ for (let index = 0, length = state.representTypes.length; index < length; index += 1) {
2548
+ const { tag, implicitTag } = state.representTypes[index];
2549
+ if (tag.identify(object)) {
2550
+ let tagName;
2551
+ if (tag.matchByTagPrefix) tagName = tag.representTagName(object);
2552
+ else tagName = tag.tagName;
2553
+ return {
2554
+ tag,
2555
+ tagName,
2556
+ implicitTag
2557
+ };
2558
+ }
2559
+ }
2560
+ return null;
2561
+ }
2562
+ function build(state, object) {
2563
+ if (!state.noRefs && object !== null && typeof object === "object") {
2564
+ const existing = state.refs.get(object);
2565
+ if (existing) {
2566
+ if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2567
+ return {
2568
+ kind: "alias",
2569
+ anchor: existing.anchor
2570
+ };
2571
+ }
2572
+ }
2573
+ const matched = matchTag(state, object);
2574
+ if (!matched) {
2575
+ if (object === void 0) return INVALID;
2576
+ if (state.skipInvalid) return INVALID;
2577
+ throw new YAMLException(`unacceptable kind of an object to dump ${Object.prototype.toString.call(object)}`);
2578
+ }
2579
+ const { tag, tagName, implicitTag } = matched;
2580
+ const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
2581
+ if (tag.nodeKind === "scalar") return {
2582
+ kind: "scalar",
2583
+ tag: nodeTagName,
2584
+ tagged: !implicitTag,
2585
+ style: SCALAR_STYLE.PLAIN,
2586
+ value: tag.represent(object)
2587
+ };
2588
+ if (tag.nodeKind === "sequence") {
2589
+ const container = tag.represent(object);
2590
+ const node = {
2591
+ kind: "sequence",
2592
+ tag: nodeTagName,
2593
+ tagged: !implicitTag,
2594
+ style: COLLECTION_STYLE.BLOCK,
2595
+ items: []
2596
+ };
2597
+ if (!state.noRefs) state.refs.set(object, node);
2598
+ for (let index = 0, length = container.length; index < length; index += 1) {
2599
+ let item = build(state, container[index]);
2600
+ if (item === INVALID && container[index] === void 0) item = build(state, null);
2601
+ if (item === INVALID) continue;
2602
+ node.items.push(item);
2603
+ }
2604
+ return node;
2605
+ }
2606
+ const map = tag.represent(object);
2607
+ const node = {
2608
+ kind: "mapping",
2609
+ tag: nodeTagName,
2610
+ tagged: !implicitTag,
2611
+ style: COLLECTION_STYLE.BLOCK,
2612
+ items: []
2613
+ };
2614
+ if (!state.noRefs) state.refs.set(object, node);
2615
+ for (const [objectKey, objectValue] of map) {
2616
+ const key = build(state, objectKey);
2617
+ if (key === INVALID) continue;
2618
+ const value = build(state, objectValue);
2619
+ if (value === INVALID) continue;
2620
+ node.items.push({
2621
+ key,
2622
+ value
2623
+ });
2624
+ }
2625
+ return node;
2626
+ }
2627
+ /**
2628
+ * Convert JS object to AST. A JS value is one YAML document. An unrepresentable
2629
+ * root becomes an empty document, which the presenter renders as an empty
2630
+ * string.
2631
+ *
2632
+ * @category AST
2633
+ */
2634
+ function jsToAst(input, schema, options = {}) {
2635
+ const root = build({
2636
+ representTypes: buildRepresentTypes(schema),
2637
+ noRefs: options.noRefs ?? false,
2638
+ skipInvalid: options.skipInvalid ?? false,
2639
+ refs: /* @__PURE__ */ new Map(),
2640
+ refCounter: 0
2641
+ }, input);
2642
+ return [{
2643
+ contents: root === INVALID ? null : root,
2644
+ directives: []
2645
+ }];
2646
+ }
2647
+ /**
2648
+ * Return from a visitor to stop the whole traversal.
2649
+ *
2650
+ * @category AST
2651
+ */
2652
+ var VISIT_BREAK = Symbol("visit:break");
2653
+ /**
2654
+ * Return from a visitor to skip the current node's children.
2655
+ *
2656
+ * @category AST
2657
+ */
2658
+ var VISIT_SKIP = Symbol("visit:skip");
2659
+ function visitNode(node, visitor, ctx) {
2660
+ const control = visitor(node, ctx);
2661
+ if (control === VISIT_BREAK) return true;
2662
+ if (control === VISIT_SKIP) return false;
2663
+ const depth = ctx.depth + 1;
2664
+ switch (node.kind) {
2665
+ case "sequence":
2666
+ for (const item of node.items) if (visitNode(item, visitor, {
2667
+ depth,
2668
+ parent: node,
2669
+ isKey: false
2670
+ })) return true;
2671
+ break;
2672
+ case "mapping": for (const { key, value } of node.items) {
2673
+ if (visitNode(key, visitor, {
2674
+ depth,
2675
+ parent: node,
2676
+ isKey: true
2677
+ })) return true;
2678
+ if (visitNode(value, visitor, {
2679
+ depth,
2680
+ parent: node,
2681
+ isKey: false
2682
+ })) return true;
2683
+ }
2684
+ }
2685
+ return false;
2686
+ }
2687
+ /**
2688
+ * Walk every node in the documents, calling {@link Visitor} once per
2689
+ * node (pre-order).
2690
+ *
2691
+ * @category AST
2692
+ */
2693
+ function visit(documents, visitor) {
2694
+ for (const doc of documents) if (doc.contents && visitNode(doc.contents, visitor, {
2695
+ depth: 0,
2696
+ parent: null,
2697
+ isKey: false
2698
+ })) return;
2699
+ }
2700
+ function hasBit(mask, bit) {
2701
+ return (mask & 1 << bit) !== 0;
2702
+ }
2703
+ /**
2704
+ * Default scalar styling rules in application order.
2705
+ * See [Scalar styling](../../docs/scalar_styling.md) for usage details.
2706
+ *
2707
+ * @category AST
2708
+ */
2709
+ var DEFAULT_SCALAR_STYLE_RULES = {
2710
+ applyQuoteFlowKeysOption,
2711
+ doubleQuoteForInvisibles,
2712
+ doubleQuoteWhitespaceOnly,
2713
+ applyForceQuotesOption,
2714
+ tryLongOrMultilineAsBlock,
2715
+ quoteInvalidPlain,
2716
+ fallbackToDoubleQuoted
2717
+ };
2718
+ function _preferredQuotedStyle(layout) {
2719
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2720
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2721
+ }
2722
+ function applyQuoteFlowKeysOption(layout) {
2723
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2724
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2725
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2726
+ }
2727
+ function doubleQuoteForInvisibles(layout) {
2728
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2729
+ }
2730
+ function doubleQuoteWhitespaceOnly(layout) {
2731
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2732
+ }
2733
+ function applyForceQuotesOption(layout) {
2734
+ if (!layout.presenterOptions.forceQuotes) return;
2735
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
2736
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
2737
+ }
2738
+ function tryLongOrMultilineAsBlock(layout) {
2739
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
2740
+ const value = layout.node.value;
2741
+ const multiline = value.indexOf("\n") !== -1;
2742
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
2743
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2744
+ return;
2745
+ }
2746
+ const w = layout.presenterOptions.lineWidth;
2747
+ if (w === -1) {
2748
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2749
+ return;
2750
+ }
2751
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2752
+ let position = 0;
2753
+ let shouldFold = false;
2754
+ while (position <= value.length) {
2755
+ let lineEnd = value.length;
2756
+ const nextLineBreak = value.indexOf("\n", position);
2757
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
2758
+ const line = value.slice(position, lineEnd);
2759
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
2760
+ if (nextLineBreak === -1) break;
2761
+ position = nextLineBreak + 1;
2762
+ }
2763
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
2764
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2765
+ }
2766
+ function quoteInvalidPlain(layout) {
2767
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
2768
+ }
2769
+ function fallbackToDoubleQuoted(layout) {
2770
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2771
+ }
2772
+ function setBit(mask, bit) {
2773
+ return mask | 1 << bit;
2774
+ }
2775
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
2776
+ var SRC_B_CHAR = "[\\n\\r]";
2777
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
2778
+ var SRC_S_WHITE = "[ \\t]";
2779
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
2780
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
2781
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
2782
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
2783
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
2784
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
2785
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
2786
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
2787
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
2788
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
2789
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
2790
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
2791
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
2792
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2793
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2794
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
2795
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
2796
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2797
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2798
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
2799
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
2800
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
2801
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
2802
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
2803
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
2804
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
2805
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
2806
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
2807
+ var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
2808
+ var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
2809
+ function canUsePlain(layout) {
2810
+ const str = layout.node.value;
2811
+ if (str !== "") {
2812
+ if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false;
2813
+ if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
2814
+ if (layout.shiftOfContent === 0) {
2815
+ const firstLineBreak = str.indexOf("\n");
2816
+ if (firstLineBreak !== -1) {
2817
+ const content = str.slice(firstLineBreak + 1);
2818
+ if (C_FORBIDDEN_CONTENT.test(content)) return false;
2819
+ }
2820
+ }
2821
+ }
2822
+ const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
2823
+ if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
2824
+ if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
2825
+ return true;
2826
+ }
2827
+ function canUseSingleQuoted(layout) {
2828
+ const str = layout.node.value;
2829
+ if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
2830
+ if (/[ \t]\n|\n[ \t]/.test(str)) return false;
2831
+ if (!layout.isKey && layout.shiftOfContent === 0) {
2832
+ const firstLineBreak = str.indexOf("\n");
2833
+ if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
2834
+ }
2835
+ return true;
2836
+ }
2837
+ function canUseBlock(layout) {
2838
+ if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
2839
+ const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
2840
+ if (contentIndent < 1) return false;
2841
+ if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
2842
+ if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
2843
+ return true;
2844
+ }
2845
+ function detectAllowedStyles(layout) {
2846
+ let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
2847
+ if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
2848
+ if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
2849
+ if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
2850
+ layout.allowedStylesMask = mask;
2851
+ }
2852
+ function renderScalar(layout) {
2853
+ switch (layout.style) {
2854
+ case SCALAR_STYLE.PLAIN: return renderPlain(layout);
2855
+ case SCALAR_STYLE.SINGLE_QUOTED: return renderSingleQuoted(layout);
2856
+ case SCALAR_STYLE.LITERAL_BLOCK: return renderLiteralBlock(layout);
2857
+ case SCALAR_STYLE.FOLDED_BLOCK: return renderFoldedBlock(layout);
2858
+ case SCALAR_STYLE.DOUBLE_QUOTED: return renderDoubleQuoted(layout);
2859
+ }
2860
+ }
2861
+ function renderPlain(layout) {
2862
+ return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
2863
+ }
2864
+ function renderSingleQuoted(layout) {
2865
+ return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
2866
+ }
2867
+ function renderLiteralBlock(layout) {
2868
+ const value = layout.node.value;
2869
+ return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
2870
+ }
2871
+ function renderFoldedBlock(layout) {
2872
+ const value = layout.node.value;
2873
+ const w = layout.presenterOptions.lineWidth;
2874
+ let availableWidth = Infinity;
2875
+ if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2876
+ return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
2877
+ }
2878
+ function renderDoubleQuoted(layout) {
2879
+ return `"${escapeString(layout.node.value)}"`;
2880
+ }
2881
+ function encodeFlowBreaks(string, shiftOfContent) {
2882
+ let nextLF = string.indexOf("\n");
2883
+ if (nextLF === -1) return string;
2884
+ const pad = " ".repeat(shiftOfContent);
2885
+ let result = string.slice(0, nextLF);
2886
+ const lineRe = /(\n+)([^\n]*)/g;
2887
+ lineRe.lastIndex = nextLF;
2888
+ let match;
2889
+ while (match = lineRe.exec(string)) {
2890
+ const breaks = match[1].length;
2891
+ const line = match[2];
2892
+ result += "\n".repeat(breaks + 1) + pad + line;
2893
+ }
2894
+ return result;
2895
+ }
2896
+ function indentString(string, spaces) {
2897
+ const indent = " ".repeat(spaces);
2898
+ let position = 0;
2899
+ let result = "";
2900
+ const length = string.length;
2901
+ while (position < length) {
2902
+ let line;
2903
+ const next = string.indexOf("\n", position);
2904
+ if (next === -1) {
2905
+ line = string.slice(position);
2906
+ position = length;
2907
+ } else {
2908
+ line = string.slice(position, next + 1);
2909
+ position = next + 1;
2910
+ }
2911
+ if (line.length && line !== "\n") result += indent;
2912
+ result += line;
2913
+ }
2914
+ return result;
2915
+ }
2916
+ function needIndentIndicator(string) {
2917
+ return /^\n* /.test(string);
2918
+ }
2919
+ function blockHeader(string, shiftOfParent, shiftOfContent) {
2920
+ const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
2921
+ const clip = string[string.length - 1] === "\n";
2922
+ return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}\n`;
2923
+ }
2924
+ function dropEndingNewline(string) {
2925
+ return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
2926
+ }
2927
+ function isMoreIndented(char) {
2928
+ return char === " " || char === " ";
2929
+ }
2930
+ function foldLine(line, width) {
2931
+ if (line === "" || isMoreIndented(line[0])) return line;
2932
+ const breakRe = / [^ \t]/g;
2933
+ let match;
2934
+ let start = 0;
2935
+ let end;
2936
+ let curr = 0;
2937
+ let next = 0;
2938
+ let result = "";
2939
+ while (match = breakRe.exec(line)) {
2940
+ next = match.index;
2941
+ if (next - start > width) {
2942
+ end = curr > start ? curr : next;
2943
+ result += `\n${line.slice(start, end)}`;
2944
+ start = end + 1;
2945
+ }
2946
+ curr = next;
2947
+ }
2948
+ result += "\n";
2949
+ if (line.length - start > width && curr > start) result += `${line.slice(start, curr)}\n${line.slice(curr + 1)}`;
2950
+ else result += line.slice(start);
2951
+ return result.slice(1);
2952
+ }
2953
+ function foldBlockScalar(string, width) {
2954
+ const lineRe = /(\n+)([^\n]*)/g;
2955
+ let nextLF = string.indexOf("\n");
2956
+ if (nextLF === -1) nextLF = string.length;
2957
+ lineRe.lastIndex = nextLF;
2958
+ let result = foldLine(string.slice(0, nextLF), width);
2959
+ let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
2960
+ let moreIndented;
2961
+ let match;
2962
+ while (match = lineRe.exec(string)) {
2963
+ const prefix = match[1];
2964
+ const line = match[2];
2965
+ moreIndented = line !== "" && isMoreIndented(line[0]);
2966
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
2967
+ prevMoreIndented = moreIndented;
2968
+ }
2969
+ return result;
2970
+ }
2971
+ var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
2972
+ function escapeCharacter(character) {
2973
+ switch (character) {
2974
+ case "\0": return "\\0";
2975
+ case "\x07": return "\\a";
2976
+ case "\b": return "\\b";
2977
+ case " ": return "\\t";
2978
+ case "\n": return "\\n";
2979
+ case "\v": return "\\v";
2980
+ case "\f": return "\\f";
2981
+ case "\r": return "\\r";
2982
+ case "\x1B": return "\\e";
2983
+ case "\"": return "\\\"";
2984
+ case "\\": return "\\\\";
2985
+ case "ย…": return "\\N";
2986
+ case "\xA0": return "\\_";
2987
+ case "\u2028": return "\\L";
2988
+ case "\u2029": return "\\P";
2989
+ }
2990
+ const code = character.charCodeAt(0);
2991
+ const hex = code.toString(16).toUpperCase();
2992
+ if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
2993
+ return `\\u${"0".repeat(4 - hex.length)}${hex}`;
2994
+ }
2995
+ function escapeString(string) {
2996
+ return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
2997
+ }
2998
+ var CHAR_LINE_FEED = 10;
2999
+ var DEFAULT_PRESENTER_OPTIONS = {
3000
+ indent: 2,
3001
+ seqNoIndent: false,
3002
+ seqInlineFirst: true,
3003
+ lineWidth: 80,
3004
+ flowBracketPadding: false,
3005
+ flowSkipCommaSpace: false,
3006
+ flowSkipColonSpace: false,
3007
+ quoteFlowKeys: false,
3008
+ quoteStyle: "single",
3009
+ forceQuotes: false,
3010
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
3011
+ tagBeforeAnchor: false
3012
+ };
3013
+ function nodeTagShort(node) {
3014
+ return node.tagged ? node.tag : tagNameShort(node.tag);
3015
+ }
3016
+ function createPresenterState(options) {
3017
+ const opts = {
3018
+ ...DEFAULT_PRESENTER_OPTIONS,
3019
+ ...options
3020
+ };
3021
+ if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
3022
+ return {
3023
+ ...opts,
3024
+ defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
3025
+ openEnded: false
3026
+ };
3027
+ }
3028
+ function generateNextLine(state, level) {
3029
+ return `\n${" ".repeat(state.indent * level)}`;
3030
+ }
3031
+ function scalarLayout(state, node, parent, level, isKey, flowOnly) {
3032
+ return {
3033
+ node,
3034
+ parent,
3035
+ level,
3036
+ isKey,
3037
+ flowOnly,
3038
+ shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
3039
+ shiftOfContent: state.indent * Math.max(1, level),
3040
+ shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
3041
+ presenterOptions: state,
3042
+ allowedStylesMask: 0,
3043
+ style: node.style
3044
+ };
3045
+ }
3046
+ function writeFlowSequence(state, level, node) {
3047
+ let result = "";
3048
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3049
+ const item = writeNode(state, level, node.items[index], node, {}).text;
3050
+ if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3051
+ result += item;
3052
+ }
3053
+ const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
3054
+ return `[${pad}${result}${pad}]`;
3055
+ }
3056
+ function writeBlockSequence(state, level, node, compact) {
3057
+ let result = "";
3058
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3059
+ const item = writeNode(state, level + 1, node.items[index], node, {
3060
+ block: true,
3061
+ compact: state.seqInlineFirst,
3062
+ isblockseq: true
3063
+ }).text;
3064
+ if (!compact || result !== "") result += generateNextLine(state, level);
3065
+ if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
3066
+ else result += "- ";
3067
+ result += item;
3068
+ }
3069
+ return result;
3070
+ }
3071
+ function writeFlowMapping(state, level, node) {
3072
+ let result = "";
3073
+ for (const { key, value } of node.items) {
3074
+ let pairBuffer = "";
3075
+ if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
3076
+ const keyRender = writeNode(state, level, key, node, { iskey: true });
3077
+ const keyText = keyRender.text;
3078
+ const valueText = writeNode(state, level, value, node, {}).text;
3079
+ const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
3080
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3081
+ const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
3082
+ pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
3083
+ result += pairBuffer;
3084
+ }
3085
+ const pad = state.flowBracketPadding && result !== "" ? " " : "";
3086
+ return `{${pad}${result}${pad}}`;
3087
+ }
3088
+ function writeBlockMapping(state, level, node, compact) {
3089
+ let result = "";
3090
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
3091
+ let pairBuffer = "";
3092
+ if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
3093
+ const { key, value } = node.items[index];
3094
+ const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style === COLLECTION_STYLE.BLOCK && key.items.length !== 0 || key.kind === "scalar" && (key.style === SCALAR_STYLE.LITERAL_BLOCK || key.style === SCALAR_STYLE.FOLDED_BLOCK);
3095
+ const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, {
3096
+ block: true,
3097
+ compact: true,
3098
+ isblockseq: !cannotBeCompact(state, key, level + 1)
3099
+ }) : writeNode(state, level + 1, key, node, {
3100
+ block: true,
3101
+ compact: true,
3102
+ iskey: true
3103
+ });
3104
+ const keyText = keyRender.text;
3105
+ const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
3106
+ const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
3107
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
3108
+ if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
3109
+ else pairBuffer += "? ";
3110
+ pairBuffer += keyText;
3111
+ if (explicitPair) pairBuffer += generateNextLine(state, level);
3112
+ const valueText = writeNode(state, level + 1, value, node, {
3113
+ block: true,
3114
+ compact: explicitPair,
3115
+ isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
3116
+ }).text;
3117
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
3118
+ const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
3119
+ if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
3120
+ else pairBuffer += `${keyColonSep}: `;
3121
+ pairBuffer += valueText;
3122
+ result += pairBuffer;
3123
+ }
3124
+ return result;
3125
+ }
3126
+ function cannotBeCompact(state, node, level) {
3127
+ if (node.kind === "alias") return true;
3128
+ return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
3129
+ }
3130
+ function writeNode(state, level, node, parent, ctx) {
3131
+ if (node.kind === "alias") {
3132
+ state.openEnded = false;
3133
+ return {
3134
+ text: `*${node.anchor}`,
3135
+ noBody: false
3136
+ };
3137
+ }
3138
+ const { block = false, iskey = false, isblockseq = false } = ctx;
3139
+ let compact = ctx.compact ?? false;
3140
+ const hasAnchor = node.anchor !== void 0;
3141
+ if (cannotBeCompact(state, node, level)) compact = false;
3142
+ let body;
3143
+ let shouldPrintTag = node.tagged;
3144
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
3145
+ if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
3146
+ else body = writeFlowMapping(state, level, node);
3147
+ else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
3148
+ else body = writeBlockSequence(state, level, node, compact);
3149
+ else body = writeFlowSequence(state, level, node);
3150
+ else {
3151
+ const layout = scalarLayout(state, node, parent, level, iskey, !block);
3152
+ detectAllowedStyles(layout);
3153
+ for (const rule of state.scalarStyleRules) rule(layout);
3154
+ body = renderScalar(layout);
3155
+ state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n"));
3156
+ shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
3157
+ }
3158
+ if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
3159
+ if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
3160
+ const noBody = body === "";
3161
+ let text = body;
3162
+ if (shouldPrintTag || hasAnchor) {
3163
+ const props = [];
3164
+ const tag = shouldPrintTag ? nodeTagShort(node) : null;
3165
+ const anchor = hasAnchor ? `&${node.anchor}` : null;
3166
+ if (state.tagBeforeAnchor) {
3167
+ if (tag !== null) props.push(tag);
3168
+ if (anchor !== null) props.push(anchor);
3169
+ } else {
3170
+ if (anchor !== null) props.push(anchor);
3171
+ if (tag !== null) props.push(tag);
3172
+ }
3173
+ const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
3174
+ text = `${props.join(" ")}${sep}${body}`;
3175
+ }
3176
+ return {
3177
+ text,
3178
+ noBody
3179
+ };
3180
+ }
3181
+ function rootStartsOwnLine(node) {
3182
+ return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
3183
+ }
3184
+ function writeDocumentDirectives(doc) {
3185
+ let result = "";
3186
+ for (const directive of doc.directives) {
3187
+ if (directive.kind === "yaml") {
3188
+ result += `%YAML ${directive.version}\n`;
3189
+ continue;
3190
+ }
3191
+ const { handle, prefix } = directive;
3192
+ result += `%TAG ${handle} ${prefix}\n`;
3193
+ }
3194
+ return result;
3195
+ }
3196
+ /**
3197
+ * Build YAML from AST.
3198
+ *
3199
+ * @category AST
3200
+ */
3201
+ function present(documents, options) {
3202
+ const state = createPresenterState(options);
3203
+ let result = "";
3204
+ let previousEnded = false;
3205
+ for (let index = 0; index < documents.length; index += 1) {
3206
+ const doc = documents[index];
3207
+ state.openEnded = false;
3208
+ const directives = writeDocumentDirectives(doc);
3209
+ const hasDirectives = directives !== "";
3210
+ const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
3211
+ result += directives;
3212
+ if (doc.contents === null) {
3213
+ if (marker) result += "---\n";
3214
+ } else if (marker) {
3215
+ const body = writeNode(state, 0, doc.contents, null, {
3216
+ block: true,
3217
+ compact: true
3218
+ }).text;
3219
+ const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3220
+ result += `---${sep}${body}\n`;
3221
+ } else result += writeNode(state, 0, doc.contents, null, {
3222
+ block: true,
3223
+ compact: true
3224
+ }).text + "\n";
3225
+ previousEnded = doc.explicitEnd || state.openEnded;
3226
+ if (previousEnded) result += "...\n";
3227
+ }
3228
+ return result;
3229
+ }
3230
+ var DEFAULT_DUMP_OPTIONS = {
3231
+ ...DEFAULT_PRESENTER_OPTIONS,
3232
+ schema: DUMP_SCHEMA,
3233
+ skipInvalid: false,
3234
+ noRefs: false,
3235
+ flowLevel: -1,
3236
+ sortKeys: false,
3237
+ transform: () => {}
3238
+ };
3239
+ function defaultCompareFn(a, b) {
3240
+ const x = String(a);
3241
+ const y = String(b);
3242
+ if (x < y) return -1;
3243
+ if (x > y) return 1;
3244
+ return 0;
3245
+ }
3246
+ /**
3247
+ * Serializes JS object as a YAML document. By default it can dump every
3248
+ * supported YAML type, so it throws an exception if you try to dump regexps or
3249
+ * functions. However, you can disable exceptions by setting the
3250
+ * {@link DumpOptions.skipInvalid} option to `true`.
3251
+ *
3252
+ * @category Main
3253
+ */
3254
+ function dump(input, options = {}) {
3255
+ const opts = {
3256
+ ...DEFAULT_DUMP_OPTIONS,
3257
+ ...options
3258
+ };
3259
+ const documents = jsToAst(input, opts.schema, {
3260
+ noRefs: opts.noRefs,
3261
+ skipInvalid: opts.skipInvalid
3262
+ });
3263
+ if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3264
+ if (ctx.depth < opts.flowLevel) return;
3265
+ if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3266
+ return VISIT_SKIP;
3267
+ });
3268
+ if (opts.sortKeys) {
3269
+ const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
3270
+ visit(documents, (node) => {
3271
+ if (node.kind !== "mapping") return;
3272
+ node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
3273
+ });
3274
+ }
3275
+ opts.transform(documents);
3276
+ return present(documents, {
3277
+ ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
3278
+ schema: opts.schema
3279
+ });
3280
+ }
3281
+ EVENT_ID.DOCUMENT;
3282
+ EVENT_ID.SEQUENCE;
3283
+ EVENT_ID.MAPPING;
3284
+ EVENT_ID.SCALAR;
3285
+ EVENT_ID.ALIAS;
3286
+ EVENT_ID.POP;
3287
+ SCALAR_STYLE.PLAIN;
3288
+ SCALAR_STYLE.SINGLE_QUOTED;
3289
+ SCALAR_STYLE.DOUBLE_QUOTED;
3290
+ SCALAR_STYLE.LITERAL_BLOCK;
3291
+ SCALAR_STYLE.FOLDED_BLOCK;
3292
+ COLLECTION_STYLE.BLOCK;
3293
+ COLLECTION_STYLE.FLOW;
3294
+ CHOMPING_MODE.CLIP;
3295
+ CHOMPING_MODE.STRIP;
3296
+ CHOMPING_MODE.KEEP;
3297
+ //#endregion
3298
+ //#region src/utils/io.js
3299
+ /**
3300
+ *
3301
+ * @param {string} dir
3302
+ */
3303
+ var ensurePathExists = async (dir) => {
3304
+ try {
3305
+ await fs.access(dir);
3306
+ } catch (err) {
3307
+ await fs.mkdir(dir, { recursive: true });
3308
+ }
3309
+ };
3310
+ /**
3311
+ * Checks if a file exists.
3312
+ *
3313
+ * @param {string} filePath
3314
+ * @returns {Promise<boolean>} True if the file exists, false otherwise
3315
+ */
3316
+ var fileExists = async (filePath) => {
3317
+ try {
3318
+ await fs.access(filePath);
3319
+ return true;
3320
+ } catch (err) {
3321
+ return false;
3322
+ }
3323
+ };
3324
+ /**
3325
+ * Writes a JavaScript object to a YAML file.
3326
+ *
3327
+ * @param {string} filePath
3328
+ * @param {Object} data
3329
+ */
3330
+ var writeYamlFile = async (filePath, data) => {
3331
+ const yamlString = dump(data);
3332
+ await ensurePathExists(path.dirname(filePath));
3333
+ await fs.writeFile(filePath, yamlString);
3334
+ };
3335
+ /**
3336
+ * Writes a JavaScript object to a JSON file.
3337
+ *
3338
+ * @param {string} filePath
3339
+ * @param {Object} data
3340
+ */
3341
+ var writeJsonFile = async (filePath, data) => {
3342
+ const jsonString = JSON.stringify(data, null, 2);
3343
+ await ensurePathExists(path.dirname(filePath));
3344
+ await fs.writeFile(filePath, jsonString);
3345
+ };
3346
+ /**
3347
+ * Read a Yaml file and parse its content into a JavaScript object.
3348
+ *
3349
+ * @param {string} filePath
3350
+ * @returns {Promise<Object|null>} The parsed Yaml object
3351
+ */
3352
+ var readYamlFile = async (filePath) => {
3353
+ if (!await fileExists(filePath)) return null;
3354
+ return load(await fs.readFile(filePath, "utf8"));
3355
+ };
3356
+ /**
3357
+ * Reads a JSON file and parses its content into a JavaScript object.
3358
+ *
3359
+ * @param {string} filePath
3360
+ * @returns {Promise<Object|null>} The parsed JSON object
3361
+ */
3362
+ var readJsonFile = async (filePath) => {
3363
+ if (!await fileExists(filePath)) return null;
3364
+ const jsonString = await fs.readFile(filePath, "utf8");
3365
+ return JSON.parse(jsonString);
3366
+ };
3367
+ //#endregion
3368
+ //#region src/info.js
3369
+ /**
3370
+ * @typedef {import("@gdacm/base-types").Info} Info
3371
+ * @typedef {import("@gdacm/base-types").GenericMetaOptions} GenericMetaOptions
3372
+ * @typedef {import("@gdacm/base-types").GenericOptions} GenericOptions
3373
+ */
3374
+ /**
3375
+ * @template {GenericOptions} T
3376
+ * @typedef {import("@gdacm/base-types").MetaOptions<T>} MetaOptions
3377
+ */
3378
+ /**
3379
+ * Get info from environment variables.
3380
+ * - GDM_TEST_NAME: String (-> info.testName)
3381
+ * - GDM_API_URL: String (-> info.apiUrl)
3382
+ * - GDM_API_TOKEN: String (-> info.apiToken)
3383
+ * - GDM_WRITE_ON_DISK: Boolean (-> info.writeOnDisk)
3384
+ * - GDM_CREATE_ON_GRAFANA: Boolean (-> info.createOnGrafana)
3385
+ * - GDM_INCLUDE_*: String (-> info.includes)
3386
+ * @type {Array<{
3387
+ * name: String,
3388
+ * prefix?: String,
3389
+ * key: String,
3390
+ * type: Function,
3391
+ * subtype?: Function,
3392
+ * }>}
3393
+ */
3394
+ var envvars = [
3395
+ {
3396
+ name: "GDM_TEST_NAME",
3397
+ key: "testName",
3398
+ type: String
3399
+ },
3400
+ {
3401
+ name: "GDM_API_URL",
3402
+ key: "apiUrl",
3403
+ type: String
3404
+ },
3405
+ {
3406
+ name: "GDM_API_TOKEN",
3407
+ key: "apiToken",
3408
+ type: String
3409
+ },
3410
+ {
3411
+ name: "GDM_WRITE_ON_DISK",
3412
+ key: "writeOnDisk",
3413
+ type: Boolean
3414
+ },
3415
+ {
3416
+ name: "GDM_CREATE_ON_GRAFANA",
3417
+ key: "createOnGrafana",
3418
+ type: Boolean
3419
+ },
3420
+ {
3421
+ name: "GDM_INCLUDE",
3422
+ prefix: "GDM_INCLUDE_",
3423
+ key: "includes",
3424
+ type: Array,
3425
+ subtype: String
3426
+ }
3427
+ ];
3428
+ /**
3429
+ * @param {...(Info|undefined)} infos
3430
+ * @returns {Info}
3431
+ */
3432
+ var mergeInfos = (...infos) => {
3433
+ /** @type{Info} */
3434
+ let result = {};
3435
+ for (const info of infos) result = {
3436
+ ...result,
3437
+ ...info,
3438
+ includes: [...result?.includes ?? [], ...info?.includes ?? []]
3439
+ };
3440
+ return result;
3441
+ };
3442
+ /**
3443
+ * @returns {Info}
3444
+ */
3445
+ var getEnvVarsInfo = () => {
3446
+ /**
3447
+ * @type {Record<String, String|Number|Boolean|Array<String|Number|Boolean>>}
3448
+ */
3449
+ const info = {};
3450
+ envvars.forEach((envvar) => {
3451
+ const stringValue = process.env[envvar.name];
3452
+ if (stringValue !== void 0) {
3453
+ if (envvar.type === Number) info[envvar.key] = Number(stringValue);
3454
+ else if (envvar.type === Boolean) info[envvar.key] = stringValue === "true" || stringValue === "1";
3455
+ else if (envvar.type === String) info[envvar.key] = stringValue;
3456
+ else if (envvar.type === Array) {
3457
+ if (!info[envvar.key]) info[envvar.key] = [];
3458
+ /** @type{Array<String|Number|Boolean>} */
3459
+ const array = info[envvar.key];
3460
+ if (envvar.subtype === String) array.push(stringValue);
3461
+ else if (envvar.subtype === Number) array.push(Number(stringValue));
3462
+ else if (envvar.subtype === Boolean) array.push(stringValue === "true" || stringValue === "1");
3463
+ }
3464
+ }
3465
+ if (envvar.prefix) {
3466
+ const prefix = envvar.prefix;
3467
+ const envsThatStartWith = Object.keys(process.env).filter((key) => key.startsWith(prefix)).sort();
3468
+ if (envvar.type === Array && envsThatStartWith.length > 0) for (const envName of envsThatStartWith) {
3469
+ const stringValue = process.env[envName];
3470
+ if (stringValue !== void 0) {
3471
+ if (!info[envvar.key]) info[envvar.key] = [];
3472
+ /** @type{Array<String|Number|Boolean>} */
3473
+ const array = info[envvar.key];
3474
+ if (envvar.subtype === String) array.push(stringValue);
3475
+ else if (envvar.subtype === Number) array.push(Number(stringValue));
3476
+ else if (envvar.subtype === Boolean) array.push(stringValue === "true" || stringValue === "1");
3477
+ }
3478
+ }
3479
+ }
3480
+ });
3481
+ return info;
3482
+ };
3483
+ /**
3484
+ * @param {String} folderPath
3485
+ * @param {String} infoPath
3486
+ * @returns {Promise<Info[]|undefined>}
3487
+ */
3488
+ var getInfoFromFolderAndPath = async (folderPath, infoPath) => {
3489
+ const infoFilePath = `${folderPath}/${infoPath}`;
3490
+ const result = [];
3491
+ for (const { ext, readFunc } of [
3492
+ {
3493
+ ext: "json",
3494
+ readFunc: readJsonFile
3495
+ },
3496
+ {
3497
+ ext: "yaml",
3498
+ readFunc: readYamlFile
3499
+ },
3500
+ {
3501
+ ext: "yml",
3502
+ readFunc: readYamlFile
3503
+ }
3504
+ ]) {
3505
+ const filePath = `${infoFilePath}.${ext}`;
3506
+ if (await fileExists(filePath)) {
3507
+ const info = await readFunc(filePath);
3508
+ if (info) result.push(info);
3509
+ }
3510
+ }
3511
+ return result.length > 0 ? result : void 0;
3512
+ };
3513
+ /**
3514
+ * @param {String|String[]} folderPaths
3515
+ * @param {String} infoPath
3516
+ * @returns {Promise<Info[]>}
3517
+ */
3518
+ var getInfosFromFoldersAndPaths = async (folderPaths, infoPath) => {
3519
+ const paths = Array.isArray(folderPaths) ? folderPaths : [folderPaths];
3520
+ const infos = [];
3521
+ for (const path of paths) {
3522
+ const infosFromPath = await getInfoFromFolderAndPath(path, infoPath);
3523
+ if (infosFromPath) infos.push(...infosFromPath);
3524
+ }
3525
+ return infos;
3526
+ };
3527
+ /**
3528
+ * @param {String|String[]} folderPaths
3529
+ * @returns {Promise<Info>}
3530
+ */
3531
+ var getInfoFromFolders = async (folderPaths) => {
3532
+ let infoResult = {};
3533
+ for (const info of await getInfosFromFoldersAndPaths(folderPaths, "info")) infoResult = mergeInfos(infoResult, info);
3534
+ return infoResult;
3535
+ };
3536
+ /**
3537
+ * @template T
3538
+ * @param {String} key
3539
+ * @param {GenericMetaOptions} metaOptions
3540
+ * @param {T} [defaultValue]
3541
+ * @returns {T}
3542
+ */
3543
+ var getFromOptionsOrInfo = (key, metaOptions, defaultValue) => {
3544
+ return metaOptions?.[key] ?? metaOptions?.info?.[key] ?? defaultValue;
3545
+ };
3546
+ /**
3547
+ * @template {GenericOptions} T
3548
+ * @param {...GenericOptions|undefined} metaOptionsList
3549
+ * @returns {MetaOptions<T>}
3550
+ */
3551
+ var mergeOptions = (...metaOptionsList) => {
3552
+ let mergedMetaOptions = {};
3553
+ metaOptionsList.forEach((metaOptions) => {
3554
+ if (metaOptions) mergedMetaOptions = {
3555
+ ...mergedMetaOptions,
3556
+ ...metaOptions,
3557
+ info: mergeInfos(mergedMetaOptions?.info, metaOptions?.info)
3558
+ };
3559
+ });
3560
+ return mergedMetaOptions;
3561
+ };
3562
+ /**
3563
+ * @param {Info|Info[]|undefined} infoCode
3564
+ * @param {String|String[]} localFolderPaths
3565
+ */
3566
+ var getInfo = async (infoCode, localFolderPaths) => {
3567
+ const infoLocal = await getInfoFromFolders(localFolderPaths);
3568
+ const infoEnvVars = getEnvVarsInfo();
3569
+ let infoIntermediate = mergeInfos(...Array.isArray(infoCode) ? infoCode : infoCode ? [infoCode] : [], infoLocal, infoEnvVars);
3570
+ /** @type{Set<String>} */
3571
+ const included = /* @__PURE__ */ new Set();
3572
+ const includes = infoIntermediate.includes;
3573
+ if (includes) {
3574
+ let hasNewIncludes = true;
3575
+ while (hasNewIncludes) {
3576
+ hasNewIncludes = false;
3577
+ for (const include of includes) if (!included.has(include)) {
3578
+ const infosFromIncludes = await getInfosFromFoldersAndPaths(localFolderPaths, include);
3579
+ for (const infoFromInclude of infosFromIncludes) {
3580
+ infoIntermediate = mergeInfos(infoIntermediate, infoFromInclude);
3581
+ hasNewIncludes = true;
3582
+ }
3583
+ included.add(include);
3584
+ }
3585
+ }
3586
+ }
3587
+ return infoIntermediate;
3588
+ };
3589
+ //#endregion
3590
+ //#region src/FolderInfo.js
3591
+ var FolderInfo = class {
3592
+ constructor() {
3593
+ /** @type {string|undefined} */
3594
+ this._vid = void 0;
3595
+ /** @type {string|undefined} */
3596
+ this._sid = void 0;
3597
+ /** @type {string|undefined} */
3598
+ this._name = void 0;
3599
+ /** @type {string|undefined} */
3600
+ this._emoji = void 0;
3601
+ /** @type {string|undefined} */
3602
+ this._parentVid = void 0;
3603
+ /** @type {boolean} */
3604
+ this._fromServer = false;
3605
+ }
3606
+ /**
3607
+ * @returns {string|undefined}
3608
+ */
3609
+ get vid() {
3610
+ return this._vid;
3611
+ }
3612
+ /**
3613
+ * @param {string} vid
3614
+ * @returns {FolderInfo}
3615
+ */
3616
+ setVid(vid) {
3617
+ this._vid = vid;
3618
+ return this;
3619
+ }
3620
+ /**
3621
+ * @returns {string|undefined}
3622
+ */
3623
+ get sid() {
3624
+ return this._sid;
3625
+ }
3626
+ /**
3627
+ * @param {string} sid
3628
+ * @returns {FolderInfo}
3629
+ */
3630
+ setSid(sid) {
3631
+ this._sid = sid;
3632
+ return this;
3633
+ }
3634
+ /**
3635
+ * @returns {string|undefined}
3636
+ */
3637
+ get name() {
3638
+ return this._name;
3639
+ }
3640
+ /**
3641
+ * @param {string} name
3642
+ * @returns {FolderInfo}
3643
+ */
3644
+ setName(name) {
3645
+ this._name = name;
3646
+ return this;
3647
+ }
3648
+ /**
3649
+ * @returns {string|undefined}
3650
+ */
3651
+ get emoji() {
3652
+ return this._emoji;
3653
+ }
3654
+ /**
3655
+ * @param {string} emoji
3656
+ * @returns {FolderInfo}
3657
+ */
3658
+ setEmoji(emoji) {
3659
+ this._emoji = emoji;
3660
+ return this;
3661
+ }
3662
+ /**
3663
+ * @returns {string|undefined}
3664
+ */
3665
+ get parentVid() {
3666
+ return this._parentVid;
3667
+ }
3668
+ /**
3669
+ * @param {string} parentVid
3670
+ * @returns {FolderInfo}
3671
+ */
3672
+ setParentVid(parentVid) {
3673
+ this._parentVid = parentVid;
3674
+ return this;
3675
+ }
3676
+ /**
3677
+ * @returns {boolean}
3678
+ */
3679
+ get fromServer() {
3680
+ return this._fromServer;
3681
+ }
3682
+ /**
3683
+ * @param {boolean} fromServer
3684
+ * @returns {FolderInfo}
3685
+ */
3686
+ setFromServer(fromServer) {
3687
+ this._fromServer = fromServer;
3688
+ return this;
3689
+ }
3690
+ };
3691
+ //#endregion
3692
+ //#region src/DashboardInfo.js
3693
+ /**
3694
+ * @typedef {import("@gdacm/base-types").GenericMetaOptions} GenericMetaOptions
3695
+ * @typedef {import("@gdacm/base-types").DashboardMetaOptions} DashboardMetaOptions
3696
+ */
3697
+ /**
3698
+ * @typedef {FolderInfo|String} FolderInfoDefinition
3699
+ */
3700
+ var DashboardInfo = class {
3701
+ constructor() {
3702
+ /** @type {string|undefined} */
3703
+ this._sid = void 0;
3704
+ /** @type {string|undefined} */
3705
+ this._vid = void 0;
3706
+ /** @type {string|undefined} */
3707
+ this._grafanaId = void 0;
3708
+ /** @type {string|undefined} */
3709
+ this._title = void 0;
3710
+ /** @type {string|undefined} */
3711
+ this._emoji = void 0;
3712
+ /** @type {FolderInfoDefinition[]} */
3713
+ this._path = [];
3714
+ /** @type {string[]} */
3715
+ this._tags = [];
3716
+ /**
3717
+ * @type {GenericMetaOptions}
3718
+ */
3719
+ this._metaOptions = {};
3720
+ /** @type {((uid: string, metaOption: DashboardMetaOptions) => Promise<GrafanaItem>)|undefined} */
3721
+ this._dashboardGenerator = void 0;
3722
+ }
3723
+ /**
3724
+ * @returns {string|undefined}
3725
+ */
3726
+ get sid() {
3727
+ return this._sid;
3728
+ }
3729
+ /**
3730
+ * @param {string} sid
3731
+ * @returns {this}
3732
+ */
3733
+ setSid(sid) {
3734
+ this._sid = sid;
3735
+ return this;
3736
+ }
3737
+ /**
3738
+ * @returns {string|undefined}
3739
+ */
3740
+ get vid() {
3741
+ return this._vid;
3742
+ }
3743
+ /**
3744
+ * @param {string} vid
3745
+ * @returns {this}
3746
+ **/
3747
+ setVid(vid) {
3748
+ this._vid = vid;
3749
+ return this;
3750
+ }
3751
+ /**
3752
+ * @returns {string|undefined}
3753
+ */
3754
+ get grafanaId() {
3755
+ return this._grafanaId;
3756
+ }
3757
+ /**
3758
+ * @param {string} grafanaId
3759
+ * @returns {this}
3760
+ */
3761
+ setGrafanaId(grafanaId) {
3762
+ this._grafanaId = grafanaId;
3763
+ return this;
3764
+ }
3765
+ /**
3766
+ * @returns {string|undefined}
3767
+ */
3768
+ get title() {
3769
+ return this._title;
3770
+ }
3771
+ /**
3772
+ * @param {string} title
3773
+ * @returns {this}
3774
+ */
3775
+ setTitle(title) {
3776
+ this._title = title;
3777
+ return this;
3778
+ }
3779
+ /**
3780
+ * @returns {string|undefined}
3781
+ */
3782
+ get emoji() {
3783
+ return this._emoji;
3784
+ }
3785
+ /**
3786
+ * @param {string} emoji
3787
+ * @returns {this}
3788
+ */
3789
+ setEmoji(emoji) {
3790
+ this._emoji = emoji;
3791
+ return this;
3792
+ }
3793
+ /**
3794
+ * @returns {FolderInfoDefinition[]}
3795
+ */
3796
+ get path() {
3797
+ return [...this._path];
3798
+ }
3799
+ /**
3800
+ * @param {FolderInfoDefinition[]} path
3801
+ * @returns {this}
3802
+ */
3803
+ setPath(path) {
3804
+ this._path = [...path];
3805
+ return this;
3806
+ }
3807
+ /**
3808
+ * @param {FolderInfoDefinition[]} path
3809
+ * @returns {this}
3810
+ */
3811
+ injectIntoPath(path) {
3812
+ this._path = [...path, ...this._path];
3813
+ return this;
3814
+ }
3815
+ /**
3816
+ * @returns {string[]}
3817
+ */
3818
+ get tags() {
3819
+ return this._tags;
3820
+ }
3821
+ /**
3822
+ * @param {string[]} tags
3823
+ * @returns {this}
3824
+ */
3825
+ setTags(tags) {
3826
+ this._tags = tags;
3827
+ return this;
3828
+ }
3829
+ /**
3830
+ * @returns {GenericMetaOptions}
3831
+ */
3832
+ get metaOptions() {
3833
+ return this._metaOptions;
3834
+ }
3835
+ /**
3836
+ * @param {string} key
3837
+ * @param {any} value
3838
+ * @returns {this}
3839
+ */
3840
+ addMetaOption(key, value) {
3841
+ this._metaOptions[key] = value;
3842
+ return this;
3843
+ }
3844
+ /**
3845
+ * @returns {((uid: string, metaOption: DashboardMetaOptions) => Promise<GrafanaItem>)|undefined}
3846
+ */
3847
+ get getDashboard() {
3848
+ return this._dashboardGenerator;
3849
+ }
3850
+ /**
3851
+ * @param {((uid: string, metaOption: DashboardMetaOptions) => Promise<GrafanaItem>)|undefined} dashboardGenerator
3852
+ * @returns {this}
3853
+ */
3854
+ setDashboardGenerator(dashboardGenerator) {
3855
+ this._dashboardGenerator = dashboardGenerator;
3856
+ return this;
3857
+ }
3858
+ };
3859
+ //#endregion
3860
+ //#region src/DashboardsInfo.js
3861
+ /**
3862
+ * @typedef {(DashboardInfo|DashboardsInfo|DashboardInfo[]|DashboardsInfo[]|((info: Object) => DashboardInfo)|((info: Object) => DashboardsInfo)|((info: Object) => DashboardInfo[])|((info: Object) => DashboardsInfo[]))} DashboardsInfoItem
3863
+ */
3864
+ var DashboardsInfo = class DashboardsInfo {
3865
+ /**
3866
+ * @param {DashboardsInfoItem[]} items
3867
+ */
3868
+ constructor(...items) {
3869
+ /** @type {DashboardsInfoItem[]} */
3870
+ this._items = [];
3871
+ items.forEach((item) => this._items.push(item));
3872
+ /**
3873
+ * @type {((dashboardInfo: DashboardInfo, info: Object) => DashboardInfo)[]}
3874
+ */
3875
+ this._onDashboard = [];
3876
+ }
3877
+ /**
3878
+ * @param {Object} info
3879
+ * @param {((dashboardInfo: DashboardInfo, info: Object) => DashboardInfo)[]} onDashboards
3880
+ * @returns {DashboardInfo[]}
3881
+ */
3882
+ getItems(info, onDashboards = []) {
3883
+ /** @type {DashboardInfo[]} */
3884
+ const result = [];
3885
+ for (const item of this._items) if (item instanceof DashboardInfo) result.push(item);
3886
+ else if (item instanceof DashboardsInfo) for (const subItem of item.getItems(info)) result.push(subItem);
3887
+ else if (Array.isArray(item)) {
3888
+ for (const subItem of item) if (subItem instanceof DashboardInfo) result.push(subItem);
3889
+ else if (subItem instanceof DashboardsInfo) for (const subSubItem of subItem.getItems(info)) result.push(subSubItem);
3890
+ } else if (typeof item === "function") {
3891
+ const itemResult = item(info);
3892
+ if (itemResult instanceof DashboardInfo) result.push(itemResult);
3893
+ else if (itemResult instanceof DashboardsInfo) for (const subItem of itemResult.getItems(info)) result.push(subItem);
3894
+ else if (Array.isArray(itemResult)) {
3895
+ for (const subItem of itemResult) if (subItem instanceof DashboardInfo) result.push(subItem);
3896
+ else if (subItem instanceof DashboardsInfo) for (const subSubItem of subItem.getItems(info)) result.push(subSubItem);
3897
+ }
3898
+ }
3899
+ const allOnDashboards = [...this._onDashboard, ...onDashboards];
3900
+ return result.map((dashboardInfo) => {
3901
+ let dashboardInfoResult = dashboardInfo;
3902
+ for (const onDashboard of allOnDashboards) dashboardInfoResult = onDashboard(dashboardInfo, info);
3903
+ return dashboardInfoResult;
3904
+ });
3905
+ }
3906
+ /**
3907
+ * @param {((dashboardInfo: DashboardInfo, info: Object) => DashboardInfo)} callback
3908
+ * @returns {DashboardsInfo}
3909
+ **/
3910
+ forEachDashboard(callback) {
3911
+ this._onDashboard.push(callback);
3912
+ return this;
3913
+ }
3914
+ /**
3915
+ * @param {FolderInfo[]} path
3916
+ * @returns {DashboardsInfo}
3917
+ */
3918
+ setPath(path) {
3919
+ return this.forEachDashboard((dashboardInfo) => dashboardInfo.setPath(path));
3920
+ }
3921
+ };
3922
+ //#endregion
3923
+ //#region src/DashboardProject.js
3924
+ /**
3925
+ * @typedef {import("@gdacm/base-types").GenericMetaOptions} GenericMetaOptions
3926
+ */
3927
+ /**
3928
+ * @typedef {{
3929
+ * rootVid: String|undefined,
3930
+ * rootGrafanaFolder: String|undefined,
3931
+ * vidPrefix: String|undefined,
3932
+ * metaOptions: GenericMetaOptions
3933
+ * }} DashboardProjectProperties<T>
3934
+ */
3935
+ var DashboardProject = class {
3936
+ /**
3937
+ * @param {String} name
3938
+ */
3939
+ constructor(name) {
3940
+ this._name = name;
3941
+ /**
3942
+ * @type {DashboardProjectProperties}
3943
+ */
3944
+ this._properties = {
3945
+ rootVid: void 0,
3946
+ rootGrafanaFolder: void 0,
3947
+ vidPrefix: void 0,
3948
+ metaOptions: {}
3949
+ };
3950
+ /**
3951
+ * @type {{[sid: String]: DashboardInfo}}
3952
+ */
3953
+ this._dashboards = {};
3954
+ /**
3955
+ * @type {DashboardsInfo[]}
3956
+ */
3957
+ this._dashboardsCollection = [];
3958
+ }
3959
+ /**
3960
+ * @param {DashboardInfo} dashboardInfo
3961
+ */
3962
+ addDashboardInfo(dashboardInfo) {
3963
+ if (dashboardInfo.sid) this._dashboards[dashboardInfo.sid] = dashboardInfo;
3964
+ }
3965
+ /**
3966
+ * @param {DashboardsInfo} dashboardsInfo
3967
+ */
3968
+ addDashboardsInfo(dashboardsInfo) {
3969
+ this._dashboardsCollection.push(dashboardsInfo);
3970
+ }
3971
+ /**
3972
+ * @param {String} vid
3973
+ */
3974
+ setRootVid(vid) {
3975
+ this._properties.rootVid = vid;
3976
+ }
3977
+ /**
3978
+ * @param {String} folder
3979
+ */
3980
+ setRootGrafanaFolder(folder) {
3981
+ this._properties.rootGrafanaFolder = folder;
3982
+ }
3983
+ /**
3984
+ * @param {String} prefix
3985
+ */
3986
+ setVidPrefix(prefix) {
3987
+ this._properties.vidPrefix = prefix;
3988
+ }
3989
+ /**
3990
+ * @param {GenericMetaOptions} metaOptions
3991
+ */
3992
+ setMetaOptions(metaOptions) {
3993
+ this._properties.metaOptions = metaOptions;
3994
+ }
3995
+ get dashboards() {
3996
+ return { ...this._dashboards };
3997
+ }
3998
+ /**
3999
+ * @param {Record<String, String|Number|Boolean|*>} info
4000
+ * @returns {DashboardInfo[]}
4001
+ */
4002
+ getDashboards(info) {
4003
+ /** @type {DashboardInfo[]} */
4004
+ const result = [];
4005
+ for (const sid in this._dashboards) {
4006
+ const dashboardInfo = this._dashboards[sid];
4007
+ result.push(dashboardInfo);
4008
+ }
4009
+ for (const dashboardsInfo of this._dashboardsCollection) for (const dashboardInfo of dashboardsInfo.getItems(info)) result.push(dashboardInfo);
4010
+ return result;
4011
+ }
4012
+ get properties() {
4013
+ return { ...this._properties };
4014
+ }
4015
+ get rootVid() {
4016
+ return this._properties.rootVid;
4017
+ }
4018
+ get rootGrafanaFolder() {
4019
+ return this._properties.rootGrafanaFolder;
4020
+ }
4021
+ get vidPrefix() {
4022
+ return this._properties.vidPrefix || this.rootVid;
4023
+ }
4024
+ get metaOptions() {
4025
+ return this._properties.metaOptions;
4026
+ }
4027
+ };
4028
+ //#endregion
4029
+ //#region src/utils/id.js
4030
+ /**
4031
+ *
4032
+ * @param {string} input
4033
+ * @returns {string}
4034
+ */
4035
+ var getHash = (input) => {
4036
+ return crypto.createHash("sha256").update(input).digest("hex");
4037
+ };
4038
+ /**
4039
+ *
4040
+ * @param {string|undefined} vid
4041
+ * @returns {string|undefined} The Grafana ID (40 characters) or undefined if vid is undefined
4042
+ */
4043
+ var getGrafanaId = (vid) => {
4044
+ if (!vid) return;
4045
+ if (vid.length <= 40) return vid;
4046
+ return getHash(vid).substring(0, 40);
4047
+ };
4048
+ /**
4049
+ * @param {String} str
4050
+ * @returns {String} The string without diacritics
4051
+ */
4052
+ var removeDiacritics = (str) => {
4053
+ return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
4054
+ };
4055
+ /**
4056
+ * @param {string} input
4057
+ * @returns {string} The slugified version of the input
4058
+ */
4059
+ var getSlug = (input) => {
4060
+ return removeDiacritics(input).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)+/g, "");
4061
+ };
4062
+ new Intl.Segmenter("fr", { granularity: "grapheme" });
4063
+ //#endregion
4064
+ //#region src/api/httpClient/index.js
4065
+ /**
4066
+ *
4067
+ * @param {{[header: String]: String}} headers
4068
+ * @param {Object} [options]
4069
+ * @param {String} [options.token] - The API token for authentication
4070
+ * @param {String} [options.login] - The login for basic authentication (not supported)
4071
+ * @param {String} [options.password] - The password for basic authentication (not supported)
4072
+ */
4073
+ var ensureAuthentication = (headers, options) => {
4074
+ if (options?.token) headers["Authorization"] = `Bearer ${options.token}`;
4075
+ if (options?.login !== void 0 || options?.password !== void 0) throw new Error("Basic authentication is not supported (yet?). Please use a token instead as it's a more secure method.");
4076
+ };
4077
+ /**
4078
+ * @param {Response} response
4079
+ */
4080
+ var ensureResponseOk = (response) => {
4081
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
4082
+ };
4083
+ /**
4084
+ *
4085
+ * @param {String} url
4086
+ * @param {Object|null|undefined} data
4087
+ * @param {{[header: String]: String}} headers
4088
+ * @param {String} method
4089
+ * @param {Object} [options]
4090
+ * @returns {Promise<Object>}
4091
+ */
4092
+ var processQuery = async (url, data, headers, method, options) => {
4093
+ ensureAuthentication(headers, options);
4094
+ const extra = data ? { body: JSON.stringify(data) } : {};
4095
+ const response = await fetch(url, {
4096
+ method,
4097
+ headers,
4098
+ ...extra
4099
+ });
4100
+ ensureResponseOk(response);
4101
+ return response.json();
4102
+ };
4103
+ /**
4104
+ * @param {String} url
4105
+ * @param {Object} [options]
4106
+ * @returns {Promise<Object>}
4107
+ */
4108
+ var getJson = async (url, options) => {
4109
+ return processQuery(url, null, {}, "GET", options);
4110
+ };
4111
+ /**
4112
+ * @param {String} url
4113
+ * @param {Object|null|undefined} [data]
4114
+ * @param {Object} [options]
4115
+ * @returns {Promise<Object>}
4116
+ */
4117
+ var postJson = async (url, data, options) => {
4118
+ return processQuery(url, data, { "Content-Type": "application/json" }, "POST", options);
4119
+ };
4120
+ /**
4121
+ * @param {String} url
4122
+ * @param {Object|null|undefined} [data]
4123
+ * @param {Object} [options]
4124
+ * @returns {Promise<Object>}
4125
+ */
4126
+ var putJson = async (url, data, options) => {
4127
+ return processQuery(url, data, { "Content-Type": "application/json" }, "PUT", options);
4128
+ };
4129
+ //#endregion
4130
+ //#region src/api/GrafanaApi.js
4131
+ var GrafanaApi = class {
4132
+ /**
4133
+ * @param {Object} [options]
4134
+ * @param {String} [options.apiUrl] - The base URL of the Grafana API
4135
+ * @param {String} [options.apiToken] - The API token for authentication
4136
+ */
4137
+ constructor(options) {
4138
+ if (options?.apiUrl) this.rootUrl = options.apiUrl;
4139
+ if (options?.apiToken) this.token = options.apiToken;
4140
+ }
4141
+ /**
4142
+ * @returns {{token: String, rootUrl: String}} - The parameters for the Grafana API
4143
+ */
4144
+ get _parameters() {
4145
+ if (!this.token || !this.rootUrl) throw new Error("GrafanaApi: Missing required parameters. Please provide both 'apiUrl' and 'apiToken'.");
4146
+ return {
4147
+ token: this.token,
4148
+ rootUrl: this.rootUrl
4149
+ };
4150
+ }
4151
+ /**
4152
+ * @param {String} folderVid
4153
+ * @returns {Promise<Object>} - The response from the Grafana API for the folder information as a json object
4154
+ */
4155
+ async getFolder(folderVid) {
4156
+ const folderUid = getGrafanaId(folderVid);
4157
+ const { token, rootUrl } = this._parameters;
4158
+ return await getJson(`${rootUrl}/api/folders/${folderUid}`, { token });
4159
+ }
4160
+ /**
4161
+ * @param {String} folderName
4162
+ * @param {String} folderVid
4163
+ * @param {String|undefined} parentVid
4164
+ * @returns {Promise<Object>} The response from the Grafana API
4165
+ */
4166
+ async createFolder(folderName, folderVid, parentVid) {
4167
+ const folderUid = getGrafanaId(folderVid);
4168
+ const parentUid = getGrafanaId(parentVid);
4169
+ const { token, rootUrl } = this._parameters;
4170
+ return await postJson(`${rootUrl}/api/folders`, {
4171
+ uid: folderUid,
4172
+ title: folderName,
4173
+ parentUid
4174
+ }, { token });
4175
+ }
4176
+ /**
4177
+ *
4178
+ * @param {String} folderVid
4179
+ * @param {String} newFolderName
4180
+ * @param {String|undefined} parentVid
4181
+ * @param {Number} version
4182
+ */
4183
+ async renameFolder(folderVid, newFolderName, parentVid, version) {
4184
+ const folderUid = getGrafanaId(folderVid);
4185
+ const parentUid = getGrafanaId(parentVid);
4186
+ const { token, rootUrl } = this._parameters;
4187
+ return await putJson(`${rootUrl}/api/folders/${folderUid}`, {
4188
+ uid: folderUid,
4189
+ title: newFolderName,
4190
+ parentUid,
4191
+ version
4192
+ }, { token });
4193
+ }
4194
+ /**
4195
+ * @param {Object} dashboardStruct
4196
+ * @param {String} folderVid
4197
+ * @param {String} message
4198
+ * @returns {Promise<Object>} The response from the Grafana API
4199
+ */
4200
+ async createDashboard(dashboardStruct, folderVid, message) {
4201
+ const folderUid = getGrafanaId(folderVid);
4202
+ const { token, rootUrl } = this._parameters;
4203
+ return await postJson(`${rootUrl}/api/dashboards/db`, {
4204
+ dashboard: dashboardStruct,
4205
+ folderUid,
4206
+ message,
4207
+ overwrite: true
4208
+ }, { token });
4209
+ }
4210
+ };
4211
+ //#endregion
4212
+ //#region src/DashboardManager.js
4213
+ /**
4214
+ * @typedef {import("@gdacm/base-types").GenericMetaOptions} GenericMetaOptions
4215
+ * @typedef {import("@gdacm/base-types").DashboardMetaOptions} DashboardMetaOptions
4216
+ * @typedef {import("@gdacm/base-types").DashboardOptions} DashboardOptions
4217
+ */
4218
+ /**
4219
+ * @typedef {(uid: String, option: Object) => Promise<Object>} DashboardGenerator
4220
+ */
4221
+ var DashboardManager = class {
4222
+ constructor() {
4223
+ /**
4224
+ * @type {{[projectName: string]: DashboardProject}}
4225
+ */
4226
+ this.dashboards = {};
4227
+ }
4228
+ /**
4229
+ * Log information to the console.
4230
+ * @param {...any} args - The arguments to log
4231
+ */
4232
+ #log(...args) {
4233
+ console.log(...args);
4234
+ }
4235
+ /**
4236
+ * @param {string} projectName
4237
+ * @returns {DashboardProject} The project object
4238
+ */
4239
+ _ensureProjectExists(projectName) {
4240
+ if (!this.dashboards[projectName]) this.dashboards[projectName] = new DashboardProject(projectName);
4241
+ return this.dashboards[projectName];
4242
+ }
4243
+ /**
4244
+ * @param {string} projectName
4245
+ * @param {DashboardsInfo} dashboardsInfo
4246
+ * @returns {this}
4247
+ */
4248
+ registerDashboards(projectName, dashboardsInfo) {
4249
+ this._ensureProjectExists(projectName).addDashboardsInfo(dashboardsInfo);
4250
+ return this;
4251
+ }
4252
+ /**
4253
+ * @param {string} projectName
4254
+ * @param {string} rootVid
4255
+ * @param {string} rootGrafanaFolder
4256
+ * @param {string|undefined} vidPrefix
4257
+ * @param {GenericMetaOptions} metaOptions
4258
+ * @returns {this}
4259
+ */
4260
+ setupProject(projectName, rootVid, rootGrafanaFolder, vidPrefix, metaOptions) {
4261
+ const project = this._ensureProjectExists(projectName);
4262
+ project.setRootVid(rootVid);
4263
+ project.setRootGrafanaFolder(rootGrafanaFolder);
4264
+ if (vidPrefix) project.setVidPrefix(vidPrefix);
4265
+ project.setMetaOptions(metaOptions);
4266
+ return this;
4267
+ }
4268
+ /**
4269
+ * @param {string} projectName
4270
+ * @param {string} rootFolderPath
4271
+ * @param {GenericMetaOptions} [metaOptions] - Optional parameters for generating dashboards
4272
+ * @returns {Promise<this>}
4273
+ */
4274
+ async generateDashboards(projectName, rootFolderPath, metaOptions) {
4275
+ const projectDashboards = this._ensureProjectExists(projectName);
4276
+ const localProjectMetaOptions = mergeOptions(projectDashboards.metaOptions, metaOptions);
4277
+ /** @type {Boolean|undefined} */
4278
+ const writeOnDisk = getFromOptionsOrInfo("writeOnDisk", localProjectMetaOptions, true);
4279
+ /** @type {Boolean|undefined} */
4280
+ const createOnGrafana = getFromOptionsOrInfo("createOnGrafana", localProjectMetaOptions, true);
4281
+ /** @type {String|undefined} */
4282
+ const testName = getFromOptionsOrInfo("testName", localProjectMetaOptions, void 0);
4283
+ this.#log(`๐Ÿ”จ๐Ÿ“Š Generating dashboards for project: ${projectName} in folder: ${rootFolderPath} ${testName ? `with test name: ${testName}` : ""}`);
4284
+ if (!projectDashboards) throw new Error(`No dashboards registered for project: ${projectName}`);
4285
+ /**
4286
+ * @type {Object.<string, {sid: string, vid: string, name: string, parentVid: string|undefined, folderPath: string}>}
4287
+ */
4288
+ const foldersToCreate = {};
4289
+ const dashboardsToCreate = [];
4290
+ const { apiToken, apiUrl } = localProjectMetaOptions.info || {};
4291
+ const projectRootVid = projectDashboards.rootVid;
4292
+ if (!projectRootVid) throw new Error(`No rootVid defined for project: ${projectName}`);
4293
+ let projectVidPrefix = projectDashboards.vidPrefix;
4294
+ if (!projectVidPrefix) throw new Error(`No vidPrefix defined for project: ${projectName}`);
4295
+ let projectRootGrafanaFolder = projectDashboards.rootGrafanaFolder;
4296
+ if (!projectRootGrafanaFolder) projectRootGrafanaFolder = projectName;
4297
+ let projectFolderPath = rootFolderPath;
4298
+ foldersToCreate[projectVidPrefix] = {
4299
+ folderPath: projectFolderPath,
4300
+ name: projectRootGrafanaFolder,
4301
+ parentVid: void 0,
4302
+ sid: getSlug(projectRootGrafanaFolder),
4303
+ vid: projectRootVid
4304
+ };
4305
+ if (testName) {
4306
+ const testVid = `${projectVidPrefix}-t`;
4307
+ const testFolderPath = `${projectFolderPath}/__test__`;
4308
+ if (!foldersToCreate[testVid]) foldersToCreate[testVid] = {
4309
+ sid: `t`,
4310
+ vid: testVid,
4311
+ name: "๐Ÿงช __test__",
4312
+ parentVid: projectVidPrefix,
4313
+ folderPath: testFolderPath
4314
+ };
4315
+ projectFolderPath = testFolderPath;
4316
+ projectVidPrefix = testVid;
4317
+ const testNameVid = `${projectVidPrefix}-${getSlug(testName)}`;
4318
+ const testNameFolderPath = `${projectFolderPath}/${getSlug(testName)}`;
4319
+ if (!foldersToCreate[testNameVid]) foldersToCreate[testNameVid] = {
4320
+ sid: getSlug(testName),
4321
+ vid: testNameVid,
4322
+ name: `๐Ÿงช ${testName}`,
4323
+ parentVid: projectVidPrefix,
4324
+ folderPath: testNameFolderPath
4325
+ };
4326
+ projectFolderPath = testNameFolderPath;
4327
+ projectVidPrefix = testNameVid;
4328
+ }
4329
+ for (const dashboardInfo of projectDashboards.getDashboards(localProjectMetaOptions.info || {})) {
4330
+ const sid = dashboardInfo.sid;
4331
+ this.#log(`๐Ÿ“Š Generating dashboard: ${sid}`);
4332
+ const localDashboardMetaOptions = mergeOptions(localProjectMetaOptions, dashboardInfo.metaOptions);
4333
+ /** @type {String[]} */
4334
+ const tagsPublished = getFromOptionsOrInfo("tagsPublished", localDashboardMetaOptions, ["published"]);
4335
+ /** @type {String[]} */
4336
+ const tagsPreview = getFromOptionsOrInfo("tagsPreview", localDashboardMetaOptions, ["preview"]);
4337
+ const vid = `${projectVidPrefix}-${sid}`;
4338
+ const uid = getGrafanaId(vid) || "";
4339
+ let title = dashboardInfo.title || "Untitled Dashboard";
4340
+ let emoji = testName ? "๐Ÿงช" : dashboardInfo.emoji || "๐Ÿ“ˆ";
4341
+ if (emoji && emoji !== "") title = `${emoji} ${title}`;
4342
+ /**
4343
+ * @type{DashboardOptions}
4344
+ */
4345
+ const additionnalOptions = {
4346
+ title,
4347
+ tags: []
4348
+ };
4349
+ if (testName) {
4350
+ additionnalOptions.testName = testName;
4351
+ additionnalOptions.tags.push(...tagsPreview);
4352
+ } else additionnalOptions.tags.push(...tagsPublished);
4353
+ additionnalOptions.tags.push(...dashboardInfo.tags);
4354
+ const dashboardStruct = await dashboardInfo.getDashboard?.(uid, mergeOptions(localDashboardMetaOptions, additionnalOptions));
4355
+ if (dashboardStruct) {
4356
+ this.#log(`๐Ÿ“Š Creating dashboard for sid: ${dashboardInfo.sid} (${title})`);
4357
+ const path = dashboardInfo.path || [];
4358
+ const newPath = [];
4359
+ /** @type {String} */
4360
+ let folderPath = projectFolderPath;
4361
+ /** @type {String} */
4362
+ let folderVid = projectVidPrefix;
4363
+ for (const pathItem of path) {
4364
+ /** @type {String} */
4365
+ let sid = "";
4366
+ /** @type {String} */
4367
+ let name = "";
4368
+ let emoji = "";
4369
+ if (pathItem instanceof FolderInfo) {
4370
+ sid = pathItem.sid || "";
4371
+ name = pathItem.name || "";
4372
+ emoji = pathItem.emoji || "";
4373
+ } else if (typeof pathItem === "string") {
4374
+ sid = getSlug(pathItem);
4375
+ name = pathItem;
4376
+ emoji = "";
4377
+ } else throw new Error(`Invalid path item: ${pathItem}`);
4378
+ if (testName) emoji = "๐Ÿงช";
4379
+ if (!testName && (!emoji || emoji === "")) emoji = "๐Ÿ“š";
4380
+ if (emoji && emoji !== "") name = `${emoji} ${name}`;
4381
+ newPath.push({
4382
+ sid,
4383
+ name
4384
+ });
4385
+ folderPath = `${folderPath}/${sid}`;
4386
+ const parentVid = folderVid;
4387
+ folderVid = `${parentVid}-${sid}`;
4388
+ if (!foldersToCreate[folderVid]) foldersToCreate[folderVid] = {
4389
+ sid,
4390
+ vid: folderVid,
4391
+ name,
4392
+ parentVid,
4393
+ folderPath
4394
+ };
4395
+ }
4396
+ dashboardsToCreate.push({
4397
+ uid,
4398
+ vid,
4399
+ sid,
4400
+ title,
4401
+ content: dashboardStruct.asJson(),
4402
+ folderVid,
4403
+ folderPath,
4404
+ message: `๐Ÿ“Š Autogenerated dashboard for project: ${projectName}, dashboard: ${title}`
4405
+ });
4406
+ }
4407
+ }
4408
+ if (writeOnDisk) {
4409
+ for (const folderInfo of Object.values(foldersToCreate)) await ensurePathExists(folderInfo.folderPath);
4410
+ for (const dashboardToCreate of dashboardsToCreate) {
4411
+ const { sid, content, folderPath } = dashboardToCreate;
4412
+ const filePath = `${folderPath}/${sid}.json`;
4413
+ this.#log(`๐Ÿ“ Writing dashboard to file: ${filePath}`);
4414
+ await writeJsonFile(filePath, content);
4415
+ }
4416
+ }
4417
+ if (createOnGrafana) {
4418
+ const grafanaApi = new GrafanaApi({
4419
+ apiUrl,
4420
+ apiToken
4421
+ });
4422
+ this.#log(`๐Ÿ–ฅ๏ธ Creating dashboards on Grafana ${apiUrl} for project "${projectName}"`);
4423
+ for (const folderInfo of Object.values(foldersToCreate)) try {
4424
+ const { title, version, parentUid } = await grafanaApi.getFolder(folderInfo.vid);
4425
+ const nameHasChanged = folderInfo.name && folderInfo.name.trim() !== "" && folderInfo.name !== title;
4426
+ const parentVidHasChanged = folderInfo.parentVid !== void 0 && getGrafanaId(folderInfo.parentVid) !== parentUid;
4427
+ if (nameHasChanged || parentVidHasChanged) {
4428
+ this.#log(`๐Ÿ“‚ Folder with vid: ${folderInfo.vid} has a different name on Grafana: ${title}, renaming to: ${folderInfo.name}`);
4429
+ await grafanaApi.renameFolder(folderInfo.vid, folderInfo.name, folderInfo.parentVid, version);
4430
+ }
4431
+ } catch (error) {
4432
+ this.#log(`๐Ÿ“ Folder not found (or name mismatch) on Grafana, creating folder: ${folderInfo.name} with vid: ${folderInfo.vid}`);
4433
+ await grafanaApi.createFolder(folderInfo.name, folderInfo.vid, folderInfo.parentVid);
4434
+ }
4435
+ for (const dashboardToCreate of dashboardsToCreate) {
4436
+ const { content, title, folderVid } = dashboardToCreate;
4437
+ {
4438
+ this.#log(`๐Ÿ“Š Creating dashboard on Grafana: ${title} in folder vid: ${folderVid}`);
4439
+ const response = await grafanaApi.createDashboard(content, folderVid, `Autogenerated dashboard for project: ${projectName}, dashboard: ${title}`);
4440
+ this.#log(`๐Ÿ‘Œ Dashboard created: ${JSON.stringify(response)}`);
4441
+ }
4442
+ }
4443
+ }
4444
+ return this;
4445
+ }
4446
+ };
4447
+ //#endregion
4448
+ //#region src/dashboards.js
4449
+ /**
4450
+ * @typedef {import("@gdacm/base-types").Info} Info
4451
+ */
4452
+ /**
4453
+ * @param {string[]} localFolders
4454
+ * @param {string} outDir
4455
+ * @param {Info|Info[]} infosCode
4456
+ * @param {DashboardsInfo} dashboardsInfos
4457
+ * @returns {Promise<void>}
4458
+ */
4459
+ var createDashboards = async (localFolders, outDir, infosCode, dashboardsInfos) => {
4460
+ const info = await getInfo(infosCode, localFolders);
4461
+ const { projectName, projectRootVid, projectRootGrafanaFolder, projectVidPrefix } = info;
4462
+ const dashboardManager = new DashboardManager();
4463
+ if (!projectName || !projectRootVid || !projectRootGrafanaFolder) throw new Error(`Missing projectName or projectRootVid or projectRootGrafanaFolder in info`);
4464
+ dashboardManager.setupProject(projectName, projectRootVid, projectRootGrafanaFolder, projectVidPrefix, { info });
4465
+ dashboardManager.registerDashboards(projectName, new DashboardsInfo(dashboardsInfos));
4466
+ await dashboardManager.generateDashboards(projectName, `${outDir}/${projectRootVid}`);
4467
+ };
4468
+ //#endregion
4469
+ export { DashboardInfo, DashboardManager, DashboardProject, DashboardsInfo, FolderInfo, createDashboards, ensurePathExists, getEnvVarsInfo, getFromOptionsOrInfo, getInfo, mergeOptions, readJsonFile, readYamlFile, writeJsonFile, writeYamlFile };
4470
+
4471
+ //# sourceMappingURL=index.js.map