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