@o3co/ts.hocon 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.ja.md +256 -32
  2. package/README.md +166 -32
  3. package/dist/adapters/env.cjs +26 -1678
  4. package/dist/adapters/env.d.cts +1 -1
  5. package/dist/adapters/env.d.ts +1 -1
  6. package/dist/adapters/env.js +11 -1625
  7. package/dist/adapters/json5.cjs +496 -0
  8. package/dist/adapters/json5.d.cts +47 -0
  9. package/dist/adapters/json5.d.ts +47 -0
  10. package/dist/adapters/json5.js +496 -0
  11. package/dist/adapters/jsonc.cjs +17 -1632
  12. package/dist/adapters/jsonc.d.cts +1 -1
  13. package/dist/adapters/jsonc.d.ts +1 -1
  14. package/dist/adapters/jsonc.js +9 -1586
  15. package/dist/adapters/properties.cjs +7 -1773
  16. package/dist/adapters/properties.d.cts +1 -1
  17. package/dist/adapters/properties.d.ts +1 -1
  18. package/dist/adapters/properties.js +6 -1735
  19. package/dist/adapters/toml.cjs +12 -1626
  20. package/dist/adapters/toml.d.cts +1 -1
  21. package/dist/adapters/toml.d.ts +1 -1
  22. package/dist/adapters/toml.js +10 -1589
  23. package/dist/adapters/yaml.cjs +20 -1635
  24. package/dist/adapters/yaml.d.cts +1 -1
  25. package/dist/adapters/yaml.d.ts +1 -1
  26. package/dist/adapters/yaml.js +10 -1589
  27. package/dist/chunk-GBNQADHT.cjs +83 -0
  28. package/dist/chunk-IMJ7QHIK.cjs +158 -0
  29. package/dist/chunk-QY7ECGS6.js +83 -0
  30. package/dist/chunk-RO4D6BH7.cjs +3792 -0
  31. package/dist/chunk-WTXULUZS.js +3792 -0
  32. package/dist/chunk-XWKO4JM3.js +158 -0
  33. package/dist/{config-Dlq6rF3w.d.cts → config-OccaKqXu.d.cts} +148 -4
  34. package/dist/{config-Dlq6rF3w.d.ts → config-OccaKqXu.d.ts} +148 -4
  35. package/dist/index.cjs +35 -3449
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js +25 -3383
  39. package/dist/zod.cjs +107 -3291
  40. package/dist/zod.d.cts +83 -3
  41. package/dist/zod.d.ts +83 -3
  42. package/dist/zod.js +95 -3245
  43. package/package.json +12 -2
@@ -1,1594 +1,15 @@
1
- // src/adapters/yaml.ts
2
- import YAML from "yaml";
3
-
4
- // src/coerce.ts
5
- var DECIMAL_NUMBER_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
6
- function isHoconWs(cp) {
7
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
8
- if (cp >= 28 && cp <= 31) return true;
9
- if (cp === 32 || cp === 160 || cp === 65279) return true;
10
- if (cp === 5760) return true;
11
- if (cp >= 8192 && cp <= 8202) return true;
12
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
13
- if (cp === 12288) return true;
14
- return false;
15
- }
16
- function trimHoconWs(s) {
17
- let start = 0;
18
- let end = s.length;
19
- while (start < end && isHoconWs(s.charCodeAt(start))) {
20
- start++;
21
- }
22
- while (end > start && isHoconWs(s.charCodeAt(end - 1))) {
23
- end--;
24
- }
25
- return s.slice(start, end);
26
- }
27
- var TRUTHY = /* @__PURE__ */ new Set(["true", "yes", "on"]);
28
- var FALSY = /* @__PURE__ */ new Set(["false", "no", "off"]);
29
- function coerceBoolean(value) {
30
- const lower = value.toLowerCase();
31
- if (TRUTHY.has(lower)) return true;
32
- if (FALSY.has(lower)) return false;
33
- return void 0;
34
- }
35
- function coerceNumber(value) {
36
- if (!DECIMAL_NUMBER_RE.test(value)) return void 0;
37
- return Number(value);
38
- }
39
- var DURATION_UNITS = {
40
- ns: 1e-6,
41
- nanosecond: 1e-6,
42
- nanoseconds: 1e-6,
43
- us: 1e-3,
44
- microsecond: 1e-3,
45
- microseconds: 1e-3,
46
- ms: 1,
47
- millisecond: 1,
48
- milliseconds: 1,
49
- s: 1e3,
50
- second: 1e3,
51
- seconds: 1e3,
52
- m: 6e4,
53
- minute: 6e4,
54
- minutes: 6e4,
55
- h: 36e5,
56
- hour: 36e5,
57
- hours: 36e5,
58
- d: 864e5,
59
- day: 864e5,
60
- days: 864e5
61
- };
62
- var OUTPUT_DURATION_UNITS = {
63
- ns: 1e-6,
64
- us: 1e-3,
65
- ms: 1,
66
- s: 1e3,
67
- m: 6e4,
68
- h: 36e5,
69
- d: 864e5
70
- };
71
- function parseDuration(value, outputUnit = "ms") {
72
- const trimmed = trimHoconWs(value);
73
- let i = 0;
74
- while (i < trimmed.length) {
75
- const ch = trimmed[i];
76
- if (i === 0 && (ch === "-" || ch === "+")) {
77
- i++;
78
- continue;
79
- }
80
- if (ch !== "." && (ch < "0" || ch > "9")) break;
81
- i++;
82
- }
83
- if (i === 0) return NaN;
84
- const num = Number(trimmed.slice(0, i));
85
- if (Number.isNaN(num)) return NaN;
86
- const unit = trimHoconWs(trimmed.slice(i));
87
- const divisor = OUTPUT_DURATION_UNITS[outputUnit];
88
- if (divisor === void 0) return NaN;
89
- if (unit === "") {
90
- return num / divisor;
91
- }
92
- const mult = DURATION_UNITS[unit];
93
- if (mult === void 0) return NaN;
94
- const ms = num * mult;
95
- return ms / divisor;
96
- }
97
- var BYTE_UNITS = {
98
- B: 1,
99
- byte: 1,
100
- bytes: 1,
101
- KB: 1e3,
102
- kilobyte: 1e3,
103
- kilobytes: 1e3,
104
- KiB: 1024,
105
- kibibyte: 1024,
106
- kibibytes: 1024,
107
- MB: 1e6,
108
- megabyte: 1e6,
109
- megabytes: 1e6,
110
- MiB: 1048576,
111
- mebibyte: 1048576,
112
- mebibytes: 1048576,
113
- GB: 1e9,
114
- gigabyte: 1e9,
115
- gigabytes: 1e9,
116
- GiB: 1073741824,
117
- gibibyte: 1073741824,
118
- gibibytes: 1073741824,
119
- TB: 1e12,
120
- terabyte: 1e12,
121
- terabytes: 1e12,
122
- TiB: 1099511627776,
123
- tebibyte: 1099511627776,
124
- tebibytes: 1099511627776,
125
- // S21.4 — HOCON.md L1385: single-letter abbreviations → powers of two (java -Xmx convention).
126
- // Lightbend typesafe-config 1.4.3 verified: 1K=1024, 1M=1048576, etc.
127
- // Both upper- and lowercase accepted per Lightbend behaviour.
128
- // Z/Y (2^70/2^80) are deferred — they overflow MAX_SAFE_INTEGER and require BigInt accessor.
129
- K: 1024,
130
- k: 1024,
131
- M: 1024 ** 2,
132
- m: 1024 ** 2,
133
- G: 1024 ** 3,
134
- g: 1024 ** 3,
135
- T: 1024 ** 4,
136
- t: 1024 ** 4,
137
- P: 1024 ** 5,
138
- p: 1024 ** 5,
139
- E: 1024 ** 6,
140
- e: 1024 ** 6,
141
- // lowercase short-form aliases
142
- b: 1,
143
- kb: 1e3,
144
- kib: 1024,
145
- mb: 1e6,
146
- mib: 1048576,
147
- gb: 1e9,
148
- gib: 1073741824,
149
- tb: 1e12,
150
- tib: 1099511627776
151
- };
152
- var OUTPUT_BYTE_UNITS = {
153
- B: 1,
154
- KB: 1e3,
155
- KiB: 1024,
156
- MB: 1e6,
157
- MiB: 1048576,
158
- GB: 1e9,
159
- GiB: 1073741824,
160
- TB: 1e12,
161
- TiB: 1099511627776
162
- };
163
- function parseBytes(value, outputUnit = "B") {
164
- const trimmed = trimHoconWs(value);
165
- let i = 0;
166
- while (i < trimmed.length) {
167
- const ch = trimmed[i];
168
- if (i === 0 && (ch === "-" || ch === "+")) {
169
- i++;
170
- continue;
171
- }
172
- if (ch !== "." && (ch < "0" || ch > "9")) break;
173
- i++;
174
- }
175
- if (i === 0) return NaN;
176
- const num = Number(trimmed.slice(0, i));
177
- if (Number.isNaN(num)) return NaN;
178
- const unit = trimHoconWs(trimmed.slice(i));
179
- const divisor = OUTPUT_BYTE_UNITS[outputUnit];
180
- if (divisor === void 0) return NaN;
181
- if (unit === "") {
182
- const bytes2 = Math.trunc(num);
183
- if (Math.abs(bytes2) > Number.MAX_SAFE_INTEGER) {
184
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
185
- }
186
- return bytes2 / divisor;
187
- }
188
- let mult = BYTE_UNITS[unit];
189
- if (mult === void 0) {
190
- mult = BYTE_UNITS[unit.toLowerCase()];
191
- }
192
- if (mult === void 0) return NaN;
193
- const bytes = num * mult;
194
- if (Math.abs(bytes) > Number.MAX_SAFE_INTEGER) {
195
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
196
- }
197
- const result = bytes / divisor;
198
- return outputUnit === "B" ? Math.round(result) : result;
199
- }
200
-
201
- // src/errors.ts
202
- var ResolveError = class extends Error {
203
- constructor(message, path, line, col, file) {
204
- super(message);
205
- this.path = path;
206
- this.line = line;
207
- this.col = col;
208
- this.file = file;
209
- this.name = "ResolveError";
210
- }
211
- };
212
- var ConfigError = class extends Error {
213
- constructor(message, path) {
214
- super(message);
215
- this.path = path;
216
- this.name = "ConfigError";
217
- }
218
- };
219
- var NotResolvedError = class extends ConfigError {
220
- constructor(path) {
221
- super(`value at path "${path}" is not resolved (call resolve() first)`, path);
222
- this.name = "NotResolvedError";
223
- }
224
- };
225
-
226
- // src/internal/resolver/fold-self-ref.ts
227
- function substFullKey(s) {
228
- return stringSegmentsToKey(s.segments.map((seg) => seg.text));
229
- }
230
- function stringSegmentsToKey(segments) {
231
- return segments.map((t) => {
232
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
233
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
234
- }
235
- return t;
236
- }).join(".");
237
- }
238
- function containsSelfRef(v, fullKey) {
239
- if (isSubst(v)) return !v.knownAbsent && substFullKey(v) === fullKey;
240
- if (isConcat(v)) return v.nodes.some((n) => containsSelfRef(n, fullKey));
241
- if (isResObj(v)) {
242
- for (const f of v.fields.values()) {
243
- if (containsSelfRef(f, fullKey)) return true;
244
- }
245
- return false;
246
- }
247
- const hv = v;
248
- if (hv.kind === "array") {
249
- return hv.items.some((item) => containsSelfRef(item, fullKey));
250
- }
251
- if (hv.kind === "object") {
252
- for (const f of hv.fields.values()) {
253
- if (containsSelfRef(f, fullKey)) return true;
254
- }
255
- return false;
256
- }
257
- return false;
258
- }
259
- function foldSelfRef(v, fullKey, replacement) {
260
- if (isSubst(v)) {
261
- return substFullKey(v) === fullKey ? replacement : v;
262
- }
263
- if (isConcat(v)) {
264
- return {
265
- _kind: "concat-placeholder",
266
- nodes: v.nodes.map((n) => foldSelfRef(n, fullKey, replacement)),
267
- line: v.line,
268
- col: v.col
269
- };
270
- }
271
- if (isResObj(v)) {
272
- const newFields = /* @__PURE__ */ new Map();
273
- for (const [k, val] of v.fields) {
274
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
275
- }
276
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
277
- }
278
- const hv = v;
279
- if (hv.kind === "array") {
280
- return {
281
- kind: "array",
282
- items: hv.items.map((item) => foldSelfRef(item, fullKey, replacement))
283
- };
284
- }
285
- if (hv.kind === "object") {
286
- const newFields = /* @__PURE__ */ new Map();
287
- for (const [k, val] of hv.fields) {
288
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
289
- }
290
- return { kind: "object", fields: newFields };
291
- }
292
- return v;
293
- }
294
- function foldOrSkipPrior(prior, fullKey, old) {
295
- if (!containsSelfRef(prior, fullKey)) return cloneResolverValue(prior);
296
- if (old === void 0) return foldOptionalSelfRefAbsent(prior, fullKey);
297
- return foldSelfRef(prior, fullKey, old);
298
- }
299
- function foldOptionalSelfRefAbsent(v, fullKey) {
300
- if (isSubst(v) && substFullKey(v) === fullKey) {
301
- if (!v.optional) return void 0;
302
- return {
303
- _kind: "subst-placeholder",
304
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
305
- optional: v.optional,
306
- knownAbsent: true,
307
- listSuffix: v.listSuffix,
308
- line: v.line,
309
- col: v.col,
310
- prefixLen: v.prefixLen
311
- };
312
- }
313
- if (isConcat(v)) {
314
- const nodes = [];
315
- for (const node of v.nodes) {
316
- const folded = foldOptionalSelfRefAbsent(node, fullKey);
317
- if (folded === void 0) return void 0;
318
- nodes.push(folded);
319
- }
320
- return { _kind: "concat-placeholder", nodes, line: v.line, col: v.col };
321
- }
322
- if (isResObj(v)) {
323
- const fields = /* @__PURE__ */ new Map();
324
- for (const [key, value] of v.fields) {
325
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
326
- if (folded === void 0) return void 0;
327
- fields.set(key, folded);
328
- }
329
- return { _kind: "res-obj", fields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
330
- }
331
- const hv = v;
332
- if (hv.kind === "array") {
333
- const items = [];
334
- for (const item of hv.items) {
335
- const folded = foldOptionalSelfRefAbsent(item, fullKey);
336
- if (folded === void 0) return void 0;
337
- items.push(folded);
338
- }
339
- return { kind: "array", items };
340
- }
341
- if (hv.kind === "object") {
342
- const fields = /* @__PURE__ */ new Map();
343
- for (const [key, value] of hv.fields) {
344
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
345
- if (folded === void 0) return void 0;
346
- fields.set(key, folded);
347
- }
348
- return { kind: "object", fields };
349
- }
350
- return cloneResolverValue(v);
351
- }
352
- function cloneResolverValue(v) {
353
- if (isSubst(v)) {
354
- return {
355
- _kind: "subst-placeholder",
356
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
357
- optional: v.optional,
358
- knownAbsent: v.knownAbsent,
359
- listSuffix: v.listSuffix,
360
- line: v.line,
361
- col: v.col,
362
- prefixLen: v.prefixLen
363
- };
364
- }
365
- if (isConcat(v)) {
366
- return {
367
- _kind: "concat-placeholder",
368
- nodes: v.nodes.map((n) => cloneResolverValue(n)),
369
- line: v.line,
370
- col: v.col
371
- };
372
- }
373
- if (isResObj(v)) {
374
- const newFields = /* @__PURE__ */ new Map();
375
- for (const [k, val] of v.fields) newFields.set(k, cloneResolverValue(val));
376
- const newPriors = /* @__PURE__ */ new Map();
377
- for (const [k, val] of v.priorValues) newPriors.set(k, cloneResolverValue(val));
378
- return { _kind: "res-obj", fields: newFields, priorValues: newPriors, resetKeys: new Set(v.resetKeys) };
379
- }
380
- const hv = v;
381
- if (hv.kind === "array") {
382
- return {
383
- kind: "array",
384
- items: hv.items.map((item) => cloneResolverValue(item))
385
- };
386
- }
387
- if (hv.kind === "object") {
388
- const newFields = /* @__PURE__ */ new Map();
389
- for (const [k, val] of hv.fields) {
390
- newFields.set(k, cloneResolverValue(val));
391
- }
392
- return { kind: "object", fields: newFields };
393
- }
394
- return hv;
395
- }
396
- function containsSubstByPath(v, target) {
397
- if (isSubst(v)) return !v.knownAbsent && segmentsTextEqual(v.segments, target);
398
- if (isConcat(v)) return v.nodes.some((n) => containsSubstByPath(n, target));
399
- if (isResObj(v)) {
400
- for (const f of v.fields.values()) {
401
- if (containsSubstByPath(f, target)) return true;
402
- }
403
- return false;
404
- }
405
- const hv = v;
406
- if (hv.kind === "array") {
407
- return hv.items.some((item) => containsSubstByPath(item, target));
408
- }
409
- if (hv.kind === "object") {
410
- for (const f of hv.fields.values()) {
411
- if (containsSubstByPath(f, target)) return true;
412
- }
413
- return false;
414
- }
415
- return false;
416
- }
417
- function segmentsTextEqual(a, b) {
418
- if (a.length !== b.length) return false;
419
- for (let i = 0; i < a.length; i++) {
420
- const ai = a[i];
421
- const bi = b[i];
422
- if (ai === void 0 || bi === void 0 || ai.text !== bi.text) return false;
423
- }
424
- return true;
425
- }
426
-
427
- // src/internal/resolver/types.ts
428
- var separatorValues = /* @__PURE__ */ new WeakSet();
429
- function isSubst(v) {
430
- return v._kind === "subst-placeholder";
431
- }
432
- function isConcat(v) {
433
- return v._kind === "concat-placeholder";
434
- }
435
- function isResObj(v) {
436
- return v._kind === "res-obj";
437
- }
438
- function makeResObj() {
439
- return { _kind: "res-obj", fields: /* @__PURE__ */ new Map(), priorValues: /* @__PURE__ */ new Map(), resetKeys: /* @__PURE__ */ new Set() };
440
- }
441
- function mergeUnresolved(receiver, fallback) {
442
- const result = makeResObj();
443
- for (const [k, v] of fallback.fields) {
444
- result.fields.set(k, v);
445
- }
446
- for (const [k, v] of fallback.priorValues) {
447
- result.priorValues.set(k, v);
448
- }
449
- for (const [k, rv] of receiver.fields) {
450
- const existing = result.fields.get(k);
451
- if (existing !== void 0) {
452
- const recPrior = receiver.priorValues.get(k);
453
- if (recPrior !== void 0 && !isResObj(recPrior)) {
454
- result.fields.set(k, rv);
455
- continue;
456
- }
457
- if (isResObj(rv) && isResObj(existing)) {
458
- result.fields.set(k, mergeUnresolved(rv, existing));
459
- continue;
460
- }
461
- const foldedPrior = foldOrSkipPrior(existing, k, void 0);
462
- if (foldedPrior !== void 0) result.priorValues.set(k, foldedPrior);
463
- }
464
- result.fields.set(k, rv);
465
- }
466
- for (const [k, v] of receiver.priorValues) {
467
- if (receiver.fields.has(k)) {
468
- result.priorValues.set(k, v);
469
- }
470
- }
471
- return result;
472
- }
473
-
474
- // src/internal/resolver/utils.ts
475
- function segmentsToKey(segments) {
476
- return segments.map((s) => {
477
- const t = s.text;
478
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
479
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
480
- }
481
- return t;
482
- }).join(".");
483
- }
484
- function lookupPath(root, segments) {
485
- const [head, ...tail] = segments;
486
- if (head === void 0) return void 0;
487
- const key = head.text;
488
- const val = root.fields.get(key);
489
- if (val === void 0) return void 0;
490
- if (tail.length === 0) return val;
491
- if (isResObj(val)) return lookupPath(val, tail);
492
- return void 0;
493
- }
494
- function lookupResObj(root, segments) {
495
- let cur = root;
496
- for (const seg of segments) {
497
- const val = cur.fields.get(seg.text);
498
- if (val === void 0 || !isResObj(val)) return void 0;
499
- cur = val;
500
- }
501
- return cur;
502
- }
503
- function deepMergeHoconValues(base, overlay) {
504
- const merged = new Map(base.fields);
505
- for (const [k, v] of overlay.fields) {
506
- const existing = merged.get(k);
507
- if (existing?.kind === "object" && v.kind === "object") {
508
- merged.set(k, deepMergeHoconValues(existing, v));
509
- } else {
510
- merged.set(k, v);
511
- }
512
- }
513
- return { kind: "object", fields: merged };
514
- }
515
-
516
- // src/internal/resolver/include-loader.ts
517
- import { createRequire } from "module";
518
- import * as nodePath from "path";
519
- import { pathToFileURL } from "url";
520
-
521
- // src/internal/strip-bom.ts
522
- function stripBom(input) {
523
- return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
524
- }
525
-
526
- // src/internal/depth.ts
527
- function guardStackDepth(fn, wrap) {
528
- try {
529
- return fn();
530
- } catch (e) {
531
- if (!isStackOverflow(e)) throw e;
532
- throw wrap(STACK_MESSAGE);
533
- }
534
- }
535
- var STACK_MESSAGE = "input is nested too deeply for this engine's stack, or contains a cycle (flatten the document, or break the cycle)";
536
- function isStackOverflow(e) {
537
- if (!(e instanceof RangeError)) return false;
538
- const m = e.message.toLowerCase();
539
- return m.includes("call stack") || // V8: "Maximum call stack size exceeded"
540
- m.includes("recursion") || // SpiderMonkey: "too much recursion"
541
- m.includes("stack overflow");
542
- }
543
- function depthError(message) {
544
- return new ConfigError(message, "");
545
- }
546
-
547
- // src/value/numeric-array.ts
548
- function numericObjectToArray(value) {
549
- if (value.kind !== "object") return null;
550
- if (value.fields.size === 0) return null;
551
- const canonicalInt = /^(0|[1-9][0-9]*)$/;
552
- const eligible = [];
553
- for (const [key, val] of value.fields) {
554
- if (!canonicalInt.test(key)) continue;
555
- const n = Number(key);
556
- if (!Number.isInteger(n) || n > 2147483647) continue;
557
- eligible.push({ n, v: val });
558
- }
559
- if (eligible.length === 0) return null;
560
- eligible.sort((a, b) => a.n - b.n);
561
- return eligible.map((e) => e.v);
562
- }
563
-
564
- // src/internal/resolver/substitution-resolver.ts
565
- var SubstitutionResolver = class {
566
- constructor(root, opts) {
567
- this.root = root;
568
- this.opts = opts;
569
- this.resolving = /* @__PURE__ */ new Set();
570
- this.cache = /* @__PURE__ */ new Map();
571
- // Tracks ConcatPlaceholder nodes currently being iterated by resolveConcat.
572
- // Used by isSelfRef detection: fires only when found === a concat currently
573
- // mid-iteration (i.e. we are inside found's own resolution), preventing the
574
- // "foofoo" double-count without misfiring when an external field looks up the
575
- // same concat via a substitution (multi-reviewer convergence fix).
576
- //
577
- // Spec deviation: the S13a.13 spec ★1 decision #1 specified path-equality
578
- // preservation for self-ref detection. Round-2 multi-agent-review surfaced a
579
- // false-positive on external lookups (`a = ${?a}foo; b = ${a}`), so the
580
- // criterion was tightened to node-membership-in-iterating-set — strictly
581
- // narrower than path-equality. Spec amendment deferred to a follow-up
582
- // xx.hocon PR (see Phase 6 #3f close-out notes).
583
- this.resolvingConcats = /* @__PURE__ */ new WeakSet();
584
- // Path stack tracking the full dotted path of the field currently being
585
- // assigned in `resolveResObj`. Leaf keys are pushed on entry to each
586
- // `(key, val)` iteration and popped on exit, so nested objects build up
587
- // the full path (e.g. `["o", "history"]` while resolving `o.history`).
588
- //
589
- // Used to tighten self-ref detection at the L192 found-lookup site:
590
- // a substitution `${X}` whose looked-up value contains a Subst pointing
591
- // at `X` is only a true self-reference when the field currently being
592
- // assigned is `X` (or a descendant of `X`). Without this guard, an
593
- // external lookup like `b = ${o}` (where o has a self-referential
594
- // field) would mis-fire and short-circuit to o's prior, returning the
595
- // wrong value for b. The is_owner gate (rfp prefix-matches s.segments)
596
- // narrows the check to the owner case only.
597
- //
598
- // Cross-impl with rs.hocon v1.5.1's resolving_field_path (same purpose,
599
- // same prefix-match semantics).
600
- this.resolvingFieldPath = [];
601
- }
602
- /** Returns a prefix for error messages, including origin info when set. */
603
- originPrefix() {
604
- return this.opts.originDescription ? `${this.opts.originDescription}: ` : "";
605
- }
606
- resolve() {
607
- return this.resolveResObj(this.root);
608
- }
609
- resolveResObj(obj) {
610
- const result = /* @__PURE__ */ new Map();
611
- for (const [key, val] of obj.fields) {
612
- this.resolvingFieldPath.push(key);
613
- const fullCacheKey = stringSegmentsToKey(this.resolvingFieldPath);
614
- this.cache.delete(fullCacheKey);
615
- let resolved;
616
- try {
617
- resolved = this.resolveVal(val, obj);
618
- } finally {
619
- this.resolvingFieldPath.pop();
620
- }
621
- if (resolved !== void 0) {
622
- if (resolved.kind === "object") {
623
- const prior = obj.priorValues.get(key);
624
- if (prior !== void 0) {
625
- const priorResolved = this.resolveVal(prior, obj);
626
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
627
- const finalValue = deepMergeHoconValues(
628
- priorResolved,
629
- resolved
630
- );
631
- result.set(key, finalValue);
632
- this.cache.set(fullCacheKey, finalValue);
633
- this.cacheDescendants(fullCacheKey, finalValue);
634
- continue;
635
- }
636
- }
637
- }
638
- result.set(key, resolved);
639
- this.cache.set(fullCacheKey, resolved);
640
- this.cacheDescendants(fullCacheKey, resolved);
641
- } else {
642
- const prior = obj.priorValues.get(key);
643
- if (prior !== void 0) {
644
- const priorResolved = this.resolveVal(prior, obj);
645
- if (priorResolved !== void 0) {
646
- result.set(key, priorResolved);
647
- this.cache.set(fullCacheKey, priorResolved);
648
- this.cacheDescendants(fullCacheKey, priorResolved);
649
- }
650
- }
651
- }
652
- }
653
- return { kind: "object", fields: result };
654
- }
655
- cacheDescendants(prefix, value) {
656
- if (value.kind !== "object") return;
657
- for (const [key, child] of value.fields) {
658
- const childKey = `${prefix}.${stringSegmentsToKey([key])}`;
659
- this.cache.set(childKey, child);
660
- this.cacheDescendants(childKey, child);
661
- }
662
- }
663
- resolveVal(v, scope) {
664
- if (isSubst(v)) return this.resolveSubst(v, scope);
665
- if (isConcat(v)) {
666
- this.resolvingConcats.add(v);
667
- try {
668
- const concatResult = this.resolveConcat(v.nodes, scope, v.line, v.col);
669
- return concatResult;
670
- } finally {
671
- this.resolvingConcats.delete(v);
672
- }
673
- }
674
- if (isResObj(v)) return this.resolveResObj(v);
675
- const hv = v;
676
- if (hv.kind === "array") {
677
- return {
678
- kind: "array",
679
- items: hv.items.map(
680
- (item) => this.resolveVal(item, scope) ?? { kind: "scalar", raw: "null", valueType: "null" }
681
- )
682
- };
683
- }
684
- return hv;
685
- }
686
- resolveSubst(s, scope) {
687
- if (s.knownAbsent) return void 0;
688
- const key = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
689
- if (this.cache.has(key)) return this.cache.get(key);
690
- if (this.resolving.has(key)) {
691
- let prior;
692
- if (s.segments.length > 1) {
693
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
694
- const parentScope = lookupResObj(
695
- this.root,
696
- s.segments.slice(0, s.segments.length - 1)
697
- );
698
- prior = parentScope?.priorValues.get(leafSeg);
699
- } else {
700
- const rootSeg = s.segments[0]?.text ?? "";
701
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
702
- }
703
- if (prior !== void 0) {
704
- const saved = this.resolving;
705
- this.resolving = new Set(saved);
706
- try {
707
- return this.resolveVal(prior, scope);
708
- } finally {
709
- this.resolving = saved;
710
- }
711
- }
712
- if (s.optional) return void 0;
713
- throw new ResolveError(
714
- this.originPrefix() + `circular substitution: ${key}`,
715
- key,
716
- s.line,
717
- s.col
718
- );
719
- }
720
- this.resolving.add(key);
721
- try {
722
- const found = lookupPath(this.root, s.segments);
723
- if (found !== void 0) {
724
- const rfp = this.resolvingFieldPath;
725
- const isOwner = rfp.length >= s.segments.length && s.segments.every((seg, i) => rfp[i] === seg.text);
726
- const isSelfRef = isConcat(found) && this.resolvingConcats.has(found) || isOwner && containsSubstByPath(found, s.segments);
727
- if (isSelfRef) {
728
- let prior;
729
- if (s.segments.length > 1) {
730
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
731
- const parentScope = lookupResObj(
732
- this.root,
733
- s.segments.slice(0, s.segments.length - 1)
734
- );
735
- prior = parentScope?.priorValues.get(leafSeg);
736
- } else {
737
- const rootSeg = s.segments[0]?.text ?? "";
738
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
739
- }
740
- if (prior !== void 0) {
741
- const result2 = this.resolveVal(prior, scope);
742
- if (result2 !== void 0) this.cache.set(key, result2);
743
- return result2;
744
- }
745
- if (s.optional) return void 0;
746
- throw new ResolveError(
747
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
748
- key,
749
- s.line,
750
- s.col
751
- );
752
- }
753
- let result = this.resolveVal(found, scope);
754
- const effectiveLen = s.segments.length - s.prefixLen;
755
- if (effectiveLen === 1 && result !== void 0 && result.kind === "object") {
756
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
757
- let prior;
758
- if (s.prefixLen > 0) {
759
- const parentScope = lookupResObj(
760
- this.root,
761
- s.segments.slice(0, s.segments.length - 1)
762
- );
763
- prior = parentScope?.priorValues.get(leafSeg);
764
- } else {
765
- prior = scope.priorValues.get(leafSeg) ?? this.root.priorValues.get(leafSeg);
766
- }
767
- if (prior !== void 0) {
768
- const priorResolved = this.resolveVal(prior, scope);
769
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
770
- result = deepMergeHoconValues(
771
- priorResolved,
772
- result
773
- );
774
- }
775
- }
776
- }
777
- if (result !== void 0) this.cache.set(key, result);
778
- return result;
779
- }
780
- if (s.prefixLen > 0 && s.segments.length > s.prefixLen) {
781
- const originalSegments = s.segments.slice(s.prefixLen);
782
- const fallbackFound = lookupPath(this.root, originalSegments);
783
- if (fallbackFound !== void 0) {
784
- let result = this.resolveVal(fallbackFound, scope);
785
- if (originalSegments.length === 1 && result !== void 0 && result.kind === "object") {
786
- const rootSeg = originalSegments[0]?.text ?? "";
787
- const prior = this.root.priorValues.get(rootSeg);
788
- if (prior !== void 0) {
789
- const priorResolved = this.resolveVal(prior, scope);
790
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
791
- result = deepMergeHoconValues(
792
- priorResolved,
793
- result
794
- );
795
- }
796
- }
797
- }
798
- if (result !== void 0) this.cache.set(key, result);
799
- return result;
800
- }
801
- }
802
- if (s.listSuffix && this.opts.useSystemEnvironment !== false) {
803
- const result = this.resolveEnvList(s);
804
- if (result !== void 0) {
805
- this.cache.set(key, result);
806
- return result;
807
- }
808
- if (s.optional) return void 0;
809
- const envBase = s.segments.map((seg) => seg.text).join(".");
810
- throw new ResolveError(
811
- `${this.originPrefix()}could not resolve substitution: \${${key}} (no environment variables ${envBase}_0, ${envBase}_1, \u2026 set)`,
812
- key,
813
- s.line,
814
- s.col
815
- );
816
- } else if (s.listSuffix) {
817
- if (s.optional) return void 0;
818
- if (this.opts.allowUnresolved) return s;
819
- throw new ResolveError(
820
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
821
- key,
822
- s.line,
823
- s.col
824
- );
825
- }
826
- if (this.opts.useSystemEnvironment !== false) {
827
- const envKey = s.segments.map((seg) => seg.text).join(".");
828
- const envVal = this.opts.env[envKey] ?? (s.prefixLen > 0 ? this.opts.env[s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".")] : void 0);
829
- if (envVal !== void 0) {
830
- const result = { kind: "scalar", raw: envVal, valueType: "string" };
831
- this.cache.set(key, result);
832
- return result;
833
- }
834
- }
835
- if (s.optional) return void 0;
836
- if (this.opts.allowUnresolved) {
837
- return s;
838
- }
839
- throw new ResolveError(
840
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
841
- key,
842
- s.line,
843
- s.col
844
- );
845
- } finally {
846
- this.resolving.delete(key);
847
- }
848
- }
849
- /**
850
- * S13c: scan environment for NAME_0, NAME_1, … and return an Array<Scalar(String)>.
851
- *
852
- * Candidate bases follow the same fully-qualified→bare order used by the scalar
853
- * env fallback. The first base whose _0 key is present wins entirely — no
854
- * cross-base merging (spec §Relativized fallback precedence rules).
855
- *
856
- * Returns the HoconValue Array if any candidate base has _0, or undefined if
857
- * none do (caller applies optional/required handling).
858
- */
859
- resolveEnvList(s) {
860
- const bases = this.candidateBases(s);
861
- for (const base of bases) {
862
- const key0 = base + "_0";
863
- if (!(key0 in this.opts.env)) continue;
864
- const items = [];
865
- for (let i = 0; ; i++) {
866
- const k = base + "_" + i;
867
- if (!(k in this.opts.env)) break;
868
- items.push({ kind: "scalar", raw: this.opts.env[k], valueType: "string" });
869
- }
870
- return { kind: "array", items };
871
- }
872
- return void 0;
873
- }
874
- /**
875
- * Return the candidate base names for env-var-list lookup, in precedence order.
876
- * Mirrors the fully-qualified→bare fallback used by the scalar env path.
877
- */
878
- candidateBases(s) {
879
- const full = s.segments.map((seg) => seg.text).join(".");
880
- if (s.prefixLen === 0) return [full];
881
- const bare = s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".");
882
- return [full, bare];
883
- }
884
- resolveConcat(nodes, scope, line = 0, col = 0) {
885
- const rawResolved = nodes.map((n) => this.resolveVal(n, scope));
886
- if (this.opts.allowUnresolved) {
887
- for (const v of rawResolved) {
888
- if (v !== void 0 && isSubst(v)) {
889
- return v;
890
- }
891
- }
892
- }
893
- const resolved = rawResolved.filter((v) => v !== void 0);
894
- if (resolved.length === 0) return void 0;
895
- if (resolved.length === 1) return resolved[0];
896
- const nonSep = resolved.filter((v) => !separatorValues.has(v));
897
- if (nonSep.length === 0) {
898
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
899
- return { kind: "scalar", raw: str, valueType: "string" };
900
- }
901
- const joinPair = (left, right) => {
902
- if (left.kind === "object" && right.kind === "object") {
903
- return deepMergeHoconValues(left, right);
904
- }
905
- if (left.kind === "array" && right.kind === "object") {
906
- const converted = numericObjectToArray(right);
907
- if (converted !== null) {
908
- return { kind: "array", items: [...left.items, ...converted] };
909
- }
910
- throw new ResolveError(
911
- "cannot concatenate array with object: value concatenation requires same-kind operands (S10.4)",
912
- "",
913
- line,
914
- col
915
- );
916
- }
917
- if (left.kind === "object" && right.kind === "array") {
918
- const converted = numericObjectToArray(left);
919
- if (converted !== null) {
920
- return { kind: "array", items: [...converted, ...right.items] };
921
- }
922
- throw new ResolveError(
923
- "cannot concatenate object with array: value concatenation requires same-kind operands (S10.4)",
924
- "",
925
- line,
926
- col
927
- );
928
- }
929
- if (left.kind === "array" && right.kind === "array") {
930
- return { kind: "array", items: [...left.items, ...right.items] };
931
- }
932
- if (left.kind === "array" || right.kind === "array") {
933
- throw new ResolveError(
934
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
935
- "",
936
- line,
937
- col
938
- );
939
- }
940
- if (left.kind === "object" || right.kind === "object") {
941
- throw new ResolveError(
942
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
943
- "",
944
- line,
945
- col
946
- );
947
- }
948
- return { kind: "scalar", raw: left.raw + right.raw, valueType: "string" };
949
- };
950
- const [head, ...tail] = nonSep;
951
- const folded = tail.reduce(joinPair, head);
952
- if (folded.kind === "scalar") {
953
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
954
- return { kind: "scalar", raw: str, valueType: "string" };
955
- }
956
- return folded;
957
- }
958
- };
959
-
960
- // src/internal/resolver/resolver.ts
961
- function resolveTree(tree, opts) {
962
- return new SubstitutionResolver(tree, opts).resolve();
963
- }
964
- function containsPlaceholders(tree) {
965
- for (const val of tree.fields.values()) {
966
- if (valContainsPlaceholders(val)) return true;
967
- }
968
- return false;
969
- }
970
- function valContainsPlaceholders(v) {
971
- const rv = v;
972
- if (isSubst(rv) || isConcat(rv)) return true;
973
- if (isResObj(rv)) return containsPlaceholders(rv);
974
- const hv = v;
975
- if (hv?.kind === "array") {
976
- return hv.items.some((item) => valContainsPlaceholders(item));
977
- }
978
- return false;
979
- }
980
- function buildPartialHoconFromResObj(tree) {
981
- const fields = /* @__PURE__ */ new Map();
982
- for (const [k, v] of tree.fields) {
983
- if (!isSubst(v) && !isConcat(v)) {
984
- if (isResObj(v)) {
985
- fields.set(k, buildPartialHoconFromResObj(v));
986
- } else {
987
- if (!valContainsPlaceholders(v)) {
988
- fields.set(k, v);
989
- }
990
- }
991
- }
992
- }
993
- return { kind: "object", fields };
994
- }
995
- function hoconValueToResObj2(value) {
996
- const obj = makeResObj();
997
- for (const [k, v] of value.fields) {
998
- if (v.kind === "object") {
999
- obj.fields.set(k, hoconValueToResObj2(v));
1000
- } else {
1001
- obj.fields.set(k, v);
1002
- }
1003
- }
1004
- return obj;
1005
- }
1006
-
1007
- // src/config.ts
1008
- var Config = class _Config {
1009
- constructor(root, opts) {
1010
- this.root = root;
1011
- this._resolved = opts?.resolved ?? true;
1012
- this._parseBaseDir = opts?.parseBaseDir;
1013
- this._originDescription = opts?.originDescription;
1014
- this._resObjRoot = opts?.resObjRoot;
1015
- this._resolveOpts = opts?.resolveOpts;
1016
- }
1017
- /** Returns true when the Config's value tree contains no unresolved
1018
- * substitution placeholders. Whole-config granularity (E12 decision 11). */
1019
- isResolved() {
1020
- return this._resolved;
1021
- }
1022
- /** @internal Test-only: construct a resolved Config from a HoconValue. */
1023
- static _fromResolvedValue(root, opts) {
1024
- return new _Config(root, { resolved: true, originDescription: opts?.originDescription });
1025
- }
1026
- /** @internal Construct an unresolved Config carrying a ResObj tree.
1027
- * Used by parseStringWithOptions (deferred path) in T6. */
1028
- static _fromUnresolvedResObj(tree, opts) {
1029
- const partialRoot = buildPartialHoconFromResObj(tree);
1030
- return new _Config(partialRoot, {
1031
- resolved: opts.resolved,
1032
- parseBaseDir: opts.parseBaseDir,
1033
- originDescription: opts.originDescription,
1034
- resObjRoot: tree,
1035
- resolveOpts: opts.resolveOpts
1036
- });
1037
- }
1038
- get(path) {
1039
- const v = this.lookupNode(path);
1040
- if (v === void 0) return void 0;
1041
- return hoconToJs(v);
1042
- }
1043
- /**
1044
- * Returns the raw {@link HoconValue} node at `path` as a deeply-immutable
1045
- * {@link ReadonlyHoconValue} view, or `undefined` if the path is absent. Unlike
1046
- * `get` (which decodes to a plain JS value), this exposes the value tree for
1047
- * structural introspection via the `value.ts` accessors (`asString`, `asObject`,
1048
- * `isScalar`, …).
1049
- *
1050
- * `getValue('')` returns the root object node.
1051
- *
1052
- * Throws {@link NotResolvedError} when the node (or its subtree) is unresolved:
1053
- * the `HoconValue` union has no placeholder variant, so an unresolved value
1054
- * cannot be represented. This matches `getConfig` / `getList`.
1055
- */
1056
- getValue(path) {
1057
- const v = this.lookupNode(path);
1058
- if (v === void 0) {
1059
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1060
- throw new NotResolvedError(path);
1061
- }
1062
- return void 0;
1063
- }
1064
- if (v.kind !== "scalar" && !this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1065
- throw new NotResolvedError(path);
1066
- }
1067
- return v;
1068
- }
1069
- getString(path) {
1070
- const v = this.requireScalar(path);
1071
- if (v.valueType === "null") {
1072
- throw new ConfigError(`expected string at ${path}, got ${v.valueType}`, path);
1073
- }
1074
- return v.raw;
1075
- }
1076
- getNumber(path) {
1077
- const v = this.requireScalar(path);
1078
- const coerced = coerceNumber(v.raw);
1079
- if (coerced !== void 0) return coerced;
1080
- throw new ConfigError(`expected number at ${path}, got ${v.valueType}`, path);
1081
- }
1082
- getBoolean(path) {
1083
- const v = this.requireScalar(path);
1084
- const coerced = coerceBoolean(v.raw);
1085
- if (coerced !== void 0) return coerced;
1086
- throw new ConfigError(`expected boolean at ${path}, got ${v.valueType}`, path);
1087
- }
1088
- getDuration(path, unit) {
1089
- const v = this.requireScalar(path);
1090
- if (v.valueType !== "string" && v.valueType !== "number") {
1091
- throw new ConfigError(`expected duration at ${path}, got ${v.valueType}`, path);
1092
- }
1093
- const result = parseDuration(v.raw, unit);
1094
- if (Number.isNaN(result)) throw new ConfigError(`invalid duration at ${path}: ${JSON.stringify(v.raw)}`, path);
1095
- return result;
1096
- }
1097
- getBytes(path, unit) {
1098
- const v = this.requireScalar(path);
1099
- if (v.valueType !== "string" && v.valueType !== "number") {
1100
- throw new ConfigError(`expected byte size at ${path}, got ${v.valueType}`, path);
1101
- }
1102
- const result = parseBytes(v.raw, unit);
1103
- if (Number.isNaN(result)) throw new ConfigError(`invalid byte size at ${path}: ${JSON.stringify(v.raw)}`, path);
1104
- if (result < 0) throw new ConfigError(`byte size must be non-negative at ${path}: ${JSON.stringify(v.raw)}`, path);
1105
- return result;
1106
- }
1107
- getConfig(path) {
1108
- const v = this.lookupNode(path);
1109
- if (v === void 0) {
1110
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1111
- throw new NotResolvedError(path);
1112
- }
1113
- throw new ConfigError(`path not found: ${path}`, path);
1114
- }
1115
- if (v.kind !== "object") throw new ConfigError(`expected object at ${path}`, path);
1116
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1117
- throw new NotResolvedError(path);
1118
- }
1119
- return new _Config(v, { resolved: this._resolved });
1120
- }
1121
- getList(path) {
1122
- const v = this.lookupNode(path);
1123
- if (v === void 0) {
1124
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1125
- throw new NotResolvedError(path);
1126
- }
1127
- throw new ConfigError(`path not found: ${path}`, path);
1128
- }
1129
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1130
- throw new NotResolvedError(path);
1131
- }
1132
- if (v.kind === "object") {
1133
- const converted = numericObjectToArray(v);
1134
- if (converted !== null) return converted.map((item) => hoconToJs(item));
1135
- }
1136
- if (v.kind !== "array") throw new ConfigError(`expected array at ${path}`, path);
1137
- return v.items.map((item) => hoconToJs(item));
1138
- }
1139
- has(path) {
1140
- return this.lookupNode(path) !== void 0;
1141
- }
1142
- keys() {
1143
- return [...this.root.fields.keys()];
1144
- }
1145
- withFallback(fallback) {
1146
- if (fallback == null) return this;
1147
- const selfTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1148
- const fbTree = fallback._resObjRoot ?? hoconValueToResObj2(fallback.root);
1149
- const merged = mergeUnresolved(selfTree, fbTree);
1150
- const hasPlaceholders = containsPlaceholders(merged);
1151
- const partialRoot = buildPartialHoconFromResObj(merged);
1152
- return new _Config(partialRoot, {
1153
- resolved: !hasPlaceholders,
1154
- parseBaseDir: this._parseBaseDir,
1155
- originDescription: this._originDescription,
1156
- resObjRoot: merged,
1157
- resolveOpts: this._resolveOpts ?? fallback._resolveOpts
1158
- });
1159
- }
1160
- /**
1161
- * Runs substitution resolution (phase 2) on the stored unresolved tree.
1162
- * Idempotent: calling resolve() on an already-resolved Config returns an
1163
- * equivalent resolved Config.
1164
- *
1165
- * opts.allowUnresolved (default false) — when true, leaves unresolved
1166
- * non-optional placeholders in place rather than throwing.
1167
- * opts.useSystemEnvironment (default true) — when false, env var lookups
1168
- * are suppressed (hermetic resolution).
1169
- *
1170
- * E12 decision 3.
1171
- */
1172
- resolve(opts = {}) {
1173
- if (this._resolved) {
1174
- return new _Config(this.root, {
1175
- resolved: true,
1176
- parseBaseDir: this._parseBaseDir,
1177
- originDescription: this._originDescription
1178
- });
1179
- }
1180
- const tree = this._resObjRoot;
1181
- if (!tree) {
1182
- return new _Config(this.root, { resolved: true });
1183
- }
1184
- const resolveOpts = {
1185
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1186
- throw new Error("no files");
1187
- } },
1188
- allowUnresolved: opts.allowUnresolved ?? false,
1189
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
1190
- originDescription: this._originDescription
1191
- };
1192
- const resolved = resolveTree(tree, resolveOpts);
1193
- if (resolved.kind !== "object") throw new Error("resolve: expected object root");
1194
- if (opts.allowUnresolved) {
1195
- const { stripped, hadPlaceholders } = stripPlaceholderFields(resolved);
1196
- return new _Config(stripped, {
1197
- resolved: !hadPlaceholders,
1198
- parseBaseDir: this._parseBaseDir,
1199
- originDescription: this._originDescription,
1200
- resObjRoot: hadPlaceholders ? tree : void 0,
1201
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
1202
- });
1203
- }
1204
- return new _Config(resolved, {
1205
- resolved: true,
1206
- parseBaseDir: this._parseBaseDir,
1207
- originDescription: this._originDescription
1208
- });
1209
- }
1210
- /**
1211
- * Resolves receiver substitutions using source as lookup context.
1212
- * Source's keys are NOT merged into the result — differs from
1213
- * `this.withFallback(source).resolve()` which includes source keys.
1214
- *
1215
- * Precondition (E12 decision 10): source must be resolved. If
1216
- * source.isResolved() is false, throws NotResolvedError.
1217
- *
1218
- * On an already-resolved receiver, resolveWith is a no-op (returns an
1219
- * equivalent resolved Config, source keys not included).
1220
- *
1221
- * E12 decisions 9, 10.
1222
- */
1223
- resolveWith(source, opts = {}) {
1224
- if (!source.isResolved()) {
1225
- throw new NotResolvedError("source");
1226
- }
1227
- if (this._resolved) {
1228
- return new _Config(this.root, {
1229
- resolved: true,
1230
- parseBaseDir: this._parseBaseDir,
1231
- originDescription: this._originDescription
1232
- });
1233
- }
1234
- const receiverTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1235
- const srcTree = hoconValueToResObj2(source.root);
1236
- const merged = mergeUnresolved(receiverTree, srcTree);
1237
- const resolveOpts = {
1238
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1239
- throw new Error("no files");
1240
- } },
1241
- allowUnresolved: opts.allowUnresolved ?? false,
1242
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
1243
- originDescription: this._originDescription
1244
- };
1245
- const resolved = resolveTree(merged, resolveOpts);
1246
- if (resolved.kind !== "object") throw new Error("resolveWith: expected object root");
1247
- const receiverShapeForFilter = resObjToKeyShape(receiverTree);
1248
- const filtered = filterByReceiverShape(resolved, receiverShapeForFilter);
1249
- if (opts.allowUnresolved) {
1250
- const { stripped, hadPlaceholders } = stripPlaceholderFields(filtered);
1251
- return new _Config(stripped, {
1252
- resolved: !hadPlaceholders,
1253
- parseBaseDir: this._parseBaseDir,
1254
- originDescription: this._originDescription,
1255
- resObjRoot: hadPlaceholders ? receiverTree : void 0,
1256
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
1257
- });
1258
- }
1259
- return new _Config(filtered, {
1260
- resolved: true,
1261
- parseBaseDir: this._parseBaseDir,
1262
- originDescription: this._originDescription
1263
- });
1264
- }
1265
- /**
1266
- * The whole config as plain JS data: objects, arrays, strings, numbers,
1267
- * booleans and `null`.
1268
- *
1269
- * Keys are reproduced exactly as the config carries them, `__proto__`,
1270
- * `constructor` and `prototype` included: each is defined as an **own data
1271
- * property**, so the returned object's prototype is always
1272
- * `Object.prototype`, and this call writes nothing to the global one.
1273
- *
1274
- * ### Passing the result to other code
1275
- *
1276
- * A config file — especially a `.properties` file or an env namespace you
1277
- * merged in — can therefore hand you an own `__proto__` key, and what happens
1278
- * next depends entirely on how the consumer copies it:
1279
- *
1280
- * ```ts
1281
- * const data = cfg.toObject()
1282
- * { ...data } // safe — own properties are copied as data
1283
- * structuredClone(data) // safe
1284
- * Object.assign({}, data) // NOT safe — [[Set]] on the {} target hits
1285
- * // Object.prototype's __proto__ setter: the key
1286
- * // vanishes and config data becomes the result's
1287
- * // prototype
1288
- * deepMerge({}, data) // NOT safe — a naive recursive merge reads
1289
- * // target['__proto__'], gets Object.prototype,
1290
- * // and writes to it: global pollution
1291
- * for (const k in data) … // prefer Object.entries / Object.keys
1292
- * ```
1293
- *
1294
- * Those two hazards come from the **destination** object's prototype, so no
1295
- * option here can disarm them — copy with spread or `structuredClone` instead.
1296
- *
1297
- * What `{ nullPrototype: true }` does give you is a result that inherits
1298
- * nothing: every object comes back with a `null` prototype, so reading
1299
- * `x.__proto__`, `x.constructor` or `x.toString` yields config data or
1300
- * `undefined` rather than something from `Object.prototype`, and code that
1301
- * merges *into* this object cannot climb out of it. Keys are all still
1302
- * present. The trade-off is the usual one for prototype-less objects: not
1303
- * `instanceof Object`, and no `hasOwnProperty` of their own.
1304
- *
1305
- * Numbers follow the JS number model, so an integer wider than 2^53 rounds
1306
- * here even when the config holds it exactly — read those with
1307
- * {@link Config.getString} instead.
1308
- */
1309
- toObject(opts) {
1310
- return hoconToJs(this.root, opts?.nullPrototype === true);
1311
- }
1312
- /**
1313
- * @internal Test-only: renders this resolved Config's value tree as canonical
1314
- * JSON (sorted keys, no whitespace). Used by Layer-2 fixture tests to compare
1315
- * against Lightbend ground truth. NOT part of the public API.
1316
- *
1317
- * Throws if the Config is unresolved (contains placeholders).
1318
- */
1319
- _renderJSONForTest() {
1320
- return renderHoconAsJSON(this.root);
1321
- }
1322
- lookupNode(path) {
1323
- const segments = splitConfigPath(path);
1324
- let current = this.root;
1325
- for (const seg of segments) {
1326
- if (current.kind !== "object") return void 0;
1327
- const next = current.fields.get(seg);
1328
- if (next === void 0) return void 0;
1329
- current = next;
1330
- }
1331
- return current;
1332
- }
1333
- /**
1334
- * _resObjRootSubtreeHasPlaceholders — walk _resObjRoot to the given path and
1335
- * return true if the subtree there contains any unresolved placeholder.
1336
- * Used by getConfig / getList (T2) to detect transitive unresolved placeholders
1337
- * in object / array subtrees that would otherwise appear to be "resolved" in the
1338
- * partial HoconValue root (because individual leaf fields are omitted rather than
1339
- * the whole subtree when their value is a direct placeholder scalar, but object
1340
- * sub-containers are retained in the partial root with the placeholder-keyed
1341
- * fields omitted from them — so the object appears "present but empty-ish").
1342
- */
1343
- _resObjRootSubtreeHasPlaceholders(path) {
1344
- const tree = this._resObjRoot;
1345
- if (!tree) return false;
1346
- const segments = splitConfigPath(path);
1347
- let cur = tree;
1348
- for (const seg of segments) {
1349
- const val = cur.fields.get(seg);
1350
- if (val === void 0) return false;
1351
- if (isResObj(val)) {
1352
- cur = val;
1353
- } else {
1354
- return valContainsPlaceholders(val);
1355
- }
1356
- }
1357
- return containsPlaceholders(cur);
1358
- }
1359
- requireScalar(path) {
1360
- const v = this.lookupNode(path);
1361
- if (v === void 0) {
1362
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1363
- throw new NotResolvedError(path);
1364
- }
1365
- throw new ConfigError(`path not found: ${path}`, path);
1366
- }
1367
- if (v.kind !== "scalar") throw new ConfigError(`expected scalar at ${path}, got ${v.kind}`, path);
1368
- return v;
1369
- }
1370
- };
1371
- function splitConfigPath(path) {
1372
- const segments = [];
1373
- let i = 0;
1374
- while (i < path.length) {
1375
- if (path[i] === '"') {
1376
- i++;
1377
- let segment = "";
1378
- let closed = false;
1379
- while (i < path.length) {
1380
- const ch = path[i];
1381
- if (ch === "\\" && i + 1 < path.length) {
1382
- const next = path[i + 1];
1383
- segment += next;
1384
- i += 2;
1385
- continue;
1386
- }
1387
- if (ch === '"') {
1388
- closed = true;
1389
- i++;
1390
- break;
1391
- }
1392
- segment += ch;
1393
- i++;
1394
- }
1395
- if (!closed) throw new ConfigError(`unterminated quoted path segment: ${path}`, path);
1396
- segments.push(segment);
1397
- if (i < path.length && path[i] === ".") i++;
1398
- } else {
1399
- const dot = path.indexOf(".", i);
1400
- if (dot === -1) {
1401
- segments.push(path.slice(i));
1402
- break;
1403
- }
1404
- segments.push(path.slice(i, dot));
1405
- i = dot + 1;
1406
- }
1407
- }
1408
- return segments;
1409
- }
1410
- function scalarToJs(raw, valueType) {
1411
- switch (valueType) {
1412
- case "null":
1413
- return null;
1414
- case "boolean":
1415
- return raw === "true";
1416
- case "number":
1417
- return Number(raw);
1418
- case "string":
1419
- return raw;
1420
- }
1421
- }
1422
- function hoconToJs(v, nullPrototype = false) {
1423
- switch (v.kind) {
1424
- case "scalar":
1425
- return scalarToJs(v.raw, v.valueType);
1426
- case "array":
1427
- return v.items.map((item) => hoconToJs(item, nullPrototype));
1428
- case "object": {
1429
- const entries = Array.from(v.fields, ([k, val]) => [k, hoconToJs(val, nullPrototype)]);
1430
- if (nullPrototype) {
1431
- const obj = /* @__PURE__ */ Object.create(null);
1432
- for (const [k, val] of entries) Object.defineProperty(obj, k, {
1433
- value: val,
1434
- writable: true,
1435
- enumerable: true,
1436
- configurable: true
1437
- });
1438
- return obj;
1439
- }
1440
- return Object.fromEntries(entries);
1441
- }
1442
- }
1443
- }
1444
- function resObjToKeyShape(tree) {
1445
- const fields = /* @__PURE__ */ new Map();
1446
- for (const [k, v] of tree.fields) {
1447
- if (isSubst(v) || isConcat(v)) {
1448
- fields.set(k, { kind: "scalar", raw: "", valueType: "null" });
1449
- } else if (isResObj(v)) {
1450
- fields.set(k, resObjToKeyShape(v));
1451
- } else {
1452
- fields.set(k, v);
1453
- }
1454
- }
1455
- return { kind: "object", fields };
1456
- }
1457
- function stripPlaceholderFields(v) {
1458
- const fields = /* @__PURE__ */ new Map();
1459
- let hadPlaceholders = false;
1460
- for (const [k, val] of v.fields) {
1461
- if (val._kind === "subst-placeholder" || val._kind === "concat-placeholder") {
1462
- hadPlaceholders = true;
1463
- } else if (val.kind === "object") {
1464
- const inner = stripPlaceholderFields(val);
1465
- if (inner.hadPlaceholders) hadPlaceholders = true;
1466
- fields.set(k, inner.stripped);
1467
- } else {
1468
- fields.set(k, val);
1469
- }
1470
- }
1471
- return { stripped: { kind: "object", fields }, hadPlaceholders };
1472
- }
1473
- function filterByReceiverShape(resolved, receiverShape) {
1474
- const fields = /* @__PURE__ */ new Map();
1475
- for (const [k, rv] of resolved.fields) {
1476
- if (!receiverShape.fields.has(k)) continue;
1477
- const receiverVal = receiverShape.fields.get(k);
1478
- if (rv.kind === "object" && receiverVal.kind === "object") {
1479
- fields.set(k, filterByReceiverShape(rv, receiverVal));
1480
- } else {
1481
- fields.set(k, rv);
1482
- }
1483
- }
1484
- return { kind: "object", fields };
1485
- }
1486
- function renderHoconAsJSON(v) {
1487
- switch (v.kind) {
1488
- case "scalar": {
1489
- switch (v.valueType) {
1490
- case "null":
1491
- return "null";
1492
- case "boolean":
1493
- return v.raw;
1494
- case "number": {
1495
- const norm = normalizeLeadingZeroNumber(v.raw);
1496
- return JSON_NUMBER_RE.test(norm) ? norm : JSON.stringify(v.raw);
1497
- }
1498
- case "string":
1499
- return JSON.stringify(v.raw);
1500
- }
1501
- break;
1502
- }
1503
- case "array": {
1504
- const items = v.items.map(renderHoconAsJSON);
1505
- return `[${items.join(",")}]`;
1506
- }
1507
- case "object": {
1508
- const keys = [...v.fields.keys()].sort();
1509
- const pairs = keys.map((k) => {
1510
- const val = v.fields.get(k);
1511
- return `${JSON.stringify(k)}:${renderHoconAsJSON(val)}`;
1512
- });
1513
- return `{${pairs.join(",")}}`;
1514
- }
1515
- }
1516
- throw new Error(`renderHoconAsJSON: unsupported value kind (unresolved placeholder?)`);
1517
- }
1518
- var JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
1519
- function normalizeLeadingZeroNumber(raw) {
1520
- return raw.replace(/^([+-]?)0+(\d)/, "$1$2");
1521
- }
1522
-
1523
- // src/value-factory.ts
1524
- function fromMap(values, originDescription) {
1525
- const fields = guardStackDepth(
1526
- () => coerceObject(values, ""),
1527
- (msg) => depthError(`fromMap: ${msg}`)
1528
- );
1529
- const root = { kind: "object", fields };
1530
- return Config._fromResolvedValue(root, { originDescription });
1531
- }
1532
- var INT64_MAX = 9223372036854775807n;
1533
- var INT64_MIN = -9223372036854775808n;
1534
- function coerceObject(obj, atPath) {
1535
- const fields = /* @__PURE__ */ new Map();
1536
- for (const [k, v] of Object.entries(obj)) {
1537
- const childPath = atPath ? `${atPath}.${k}` : k;
1538
- fields.set(k, coerceValue(v, childPath));
1539
- }
1540
- return fields;
1541
- }
1542
- function coerceValue(v, atPath) {
1543
- if (v === null) {
1544
- return { kind: "scalar", raw: "null", valueType: "null" };
1545
- }
1546
- if (v === void 0) {
1547
- throw new ConfigError(
1548
- `fromMap: undefined is not a valid HOCON value at path "${atPath}"`,
1549
- atPath
1550
- );
1551
- }
1552
- switch (typeof v) {
1553
- case "string":
1554
- return { kind: "scalar", raw: v, valueType: "string" };
1555
- case "number": {
1556
- if (Number.isNaN(v) || !Number.isFinite(v)) {
1557
- throw new ConfigError(
1558
- `fromMap: ${v} is not representable in HOCON (NaN/Infinity not allowed) at path "${atPath}"`,
1559
- atPath
1560
- );
1561
- }
1562
- return { kind: "scalar", raw: Object.is(v, -0) ? "-0" : String(v), valueType: "number" };
1563
- }
1564
- case "boolean":
1565
- return { kind: "scalar", raw: v ? "true" : "false", valueType: "boolean" };
1566
- case "bigint": {
1567
- if (v > INT64_MAX || v < INT64_MIN) {
1568
- throw new ConfigError(
1569
- `fromMap: integer ${v} is out of int64 range (HOCON integers are int64; spec F0.5) at path "${atPath}"`,
1570
- atPath
1571
- );
1572
- }
1573
- return { kind: "scalar", raw: String(v), valueType: "number" };
1574
- }
1575
- case "object": {
1576
- if (Array.isArray(v)) {
1577
- const items = v.map((item, i) => coerceValue(item, `${atPath}[${i}]`));
1578
- return { kind: "array", items };
1579
- }
1580
- const fields = coerceObject(v, atPath);
1581
- return { kind: "object", fields };
1582
- }
1583
- default:
1584
- throw new ConfigError(
1585
- `fromMap: unsupported value type "${typeof v}" at path "${atPath}"`,
1586
- atPath
1587
- );
1588
- }
1589
- }
1
+ import {
2
+ fromMap
3
+ } from "../chunk-QY7ECGS6.js";
4
+ import {
5
+ ConfigError,
6
+ depthError,
7
+ guardStackDepth,
8
+ stripBom
9
+ } from "../chunk-WTXULUZS.js";
1590
10
 
1591
11
  // src/adapters/yaml.ts
12
+ import YAML from "yaml";
1592
13
  function parseYaml(input, originDescription) {
1593
14
  const docs = YAML.parseAllDocuments(stripBom(input), { version: "1.2", merge: true, intAsBigInt: true });
1594
15
  if (docs.length > 1) {