@o3co/ts.hocon 1.9.0 → 1.11.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,1700 @@
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
+ import { pathToFileURL } from "url";
517
+
518
+ // src/internal/strip-bom.ts
519
+ function stripBom(input) {
520
+ return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
521
+ }
522
+
523
+ // src/internal/properties/properties.ts
524
+ function nestPairs(pairs) {
525
+ const root = /* @__PURE__ */ Object.create(null);
526
+ const sorted = [...pairs].sort(([a], [b]) => compareSegments(a, b));
527
+ for (const [segments, value] of sorted) {
528
+ setNested(root, segments, value);
529
+ }
530
+ return root;
531
+ }
532
+ function compareSegments(a, b) {
533
+ const n = Math.min(a.length, b.length);
534
+ for (let i = 0; i < n; i++) {
535
+ const x = a[i];
536
+ const y = b[i];
537
+ if (x !== y) return x < y ? -1 : 1;
538
+ }
539
+ return a.length - b.length;
540
+ }
541
+ function pathKey(segments) {
542
+ return JSON.stringify(segments);
543
+ }
544
+ function setNested(obj, segments, value) {
545
+ let current = obj;
546
+ for (let i = 0; i < segments.length - 1; i++) {
547
+ const seg = segments[i];
548
+ if (!(seg in current) || typeof current[seg] !== "object" || current[seg] === null) {
549
+ current[seg] = /* @__PURE__ */ Object.create(null);
550
+ }
551
+ current = current[seg];
552
+ }
553
+ const last = segments[segments.length - 1];
554
+ if (typeof current[last] === "object" && current[last] !== null) return;
555
+ current[last] = value;
556
+ }
557
+
558
+ // src/value/numeric-array.ts
559
+ function numericObjectToArray(value) {
560
+ if (value.kind !== "object") return null;
561
+ if (value.fields.size === 0) return null;
562
+ const canonicalInt = /^(0|[1-9][0-9]*)$/;
563
+ const eligible = [];
564
+ for (const [key, val] of value.fields) {
565
+ if (!canonicalInt.test(key)) continue;
566
+ const n = Number(key);
567
+ if (!Number.isInteger(n) || n > 2147483647) continue;
568
+ eligible.push({ n, v: val });
569
+ }
570
+ if (eligible.length === 0) return null;
571
+ eligible.sort((a, b) => a.n - b.n);
572
+ return eligible.map((e) => e.v);
573
+ }
574
+
575
+ // src/internal/resolver/substitution-resolver.ts
576
+ var SubstitutionResolver = class {
577
+ constructor(root, opts) {
578
+ this.root = root;
579
+ this.opts = opts;
580
+ this.resolving = /* @__PURE__ */ new Set();
581
+ this.cache = /* @__PURE__ */ new Map();
582
+ // Tracks ConcatPlaceholder nodes currently being iterated by resolveConcat.
583
+ // Used by isSelfRef detection: fires only when found === a concat currently
584
+ // mid-iteration (i.e. we are inside found's own resolution), preventing the
585
+ // "foofoo" double-count without misfiring when an external field looks up the
586
+ // same concat via a substitution (multi-reviewer convergence fix).
587
+ //
588
+ // Spec deviation: the S13a.13 spec ★1 decision #1 specified path-equality
589
+ // preservation for self-ref detection. Round-2 multi-agent-review surfaced a
590
+ // false-positive on external lookups (`a = ${?a}foo; b = ${a}`), so the
591
+ // criterion was tightened to node-membership-in-iterating-set — strictly
592
+ // narrower than path-equality. Spec amendment deferred to a follow-up
593
+ // xx.hocon PR (see Phase 6 #3f close-out notes).
594
+ this.resolvingConcats = /* @__PURE__ */ new WeakSet();
595
+ // Path stack tracking the full dotted path of the field currently being
596
+ // assigned in `resolveResObj`. Leaf keys are pushed on entry to each
597
+ // `(key, val)` iteration and popped on exit, so nested objects build up
598
+ // the full path (e.g. `["o", "history"]` while resolving `o.history`).
599
+ //
600
+ // Used to tighten self-ref detection at the L192 found-lookup site:
601
+ // a substitution `${X}` whose looked-up value contains a Subst pointing
602
+ // at `X` is only a true self-reference when the field currently being
603
+ // assigned is `X` (or a descendant of `X`). Without this guard, an
604
+ // external lookup like `b = ${o}` (where o has a self-referential
605
+ // field) would mis-fire and short-circuit to o's prior, returning the
606
+ // wrong value for b. The is_owner gate (rfp prefix-matches s.segments)
607
+ // narrows the check to the owner case only.
608
+ //
609
+ // Cross-impl with rs.hocon v1.5.1's resolving_field_path (same purpose,
610
+ // same prefix-match semantics).
611
+ this.resolvingFieldPath = [];
612
+ }
613
+ /** Returns a prefix for error messages, including origin info when set. */
614
+ originPrefix() {
615
+ return this.opts.originDescription ? `${this.opts.originDescription}: ` : "";
616
+ }
617
+ resolve() {
618
+ return this.resolveResObj(this.root);
619
+ }
620
+ resolveResObj(obj) {
621
+ const result = /* @__PURE__ */ new Map();
622
+ for (const [key, val] of obj.fields) {
623
+ this.resolvingFieldPath.push(key);
624
+ const fullCacheKey = stringSegmentsToKey(this.resolvingFieldPath);
625
+ this.cache.delete(fullCacheKey);
626
+ let resolved;
627
+ try {
628
+ resolved = this.resolveVal(val, obj);
629
+ } finally {
630
+ this.resolvingFieldPath.pop();
631
+ }
632
+ if (resolved !== void 0) {
633
+ if (resolved.kind === "object") {
634
+ const prior = obj.priorValues.get(key);
635
+ if (prior !== void 0) {
636
+ const priorResolved = this.resolveVal(prior, obj);
637
+ if (priorResolved !== void 0 && priorResolved.kind === "object") {
638
+ const finalValue = deepMergeHoconValues(
639
+ priorResolved,
640
+ resolved
641
+ );
642
+ result.set(key, finalValue);
643
+ this.cache.set(fullCacheKey, finalValue);
644
+ this.cacheDescendants(fullCacheKey, finalValue);
645
+ continue;
646
+ }
647
+ }
648
+ }
649
+ result.set(key, resolved);
650
+ this.cache.set(fullCacheKey, resolved);
651
+ this.cacheDescendants(fullCacheKey, resolved);
652
+ } else {
653
+ const prior = obj.priorValues.get(key);
654
+ if (prior !== void 0) {
655
+ const priorResolved = this.resolveVal(prior, obj);
656
+ if (priorResolved !== void 0) {
657
+ result.set(key, priorResolved);
658
+ this.cache.set(fullCacheKey, priorResolved);
659
+ this.cacheDescendants(fullCacheKey, priorResolved);
660
+ }
661
+ }
662
+ }
663
+ }
664
+ return { kind: "object", fields: result };
665
+ }
666
+ cacheDescendants(prefix, value) {
667
+ if (value.kind !== "object") return;
668
+ for (const [key, child] of value.fields) {
669
+ const childKey = `${prefix}.${stringSegmentsToKey([key])}`;
670
+ this.cache.set(childKey, child);
671
+ this.cacheDescendants(childKey, child);
672
+ }
673
+ }
674
+ resolveVal(v, scope) {
675
+ if (isSubst(v)) return this.resolveSubst(v, scope);
676
+ if (isConcat(v)) {
677
+ this.resolvingConcats.add(v);
678
+ try {
679
+ const concatResult = this.resolveConcat(v.nodes, scope, v.line, v.col);
680
+ return concatResult;
681
+ } finally {
682
+ this.resolvingConcats.delete(v);
683
+ }
684
+ }
685
+ if (isResObj(v)) return this.resolveResObj(v);
686
+ const hv = v;
687
+ if (hv.kind === "array") {
688
+ return {
689
+ kind: "array",
690
+ items: hv.items.map(
691
+ (item) => this.resolveVal(item, scope) ?? { kind: "scalar", raw: "null", valueType: "null" }
692
+ )
693
+ };
694
+ }
695
+ return hv;
696
+ }
697
+ resolveSubst(s, scope) {
698
+ if (s.knownAbsent) return void 0;
699
+ const key = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
700
+ if (this.cache.has(key)) return this.cache.get(key);
701
+ if (this.resolving.has(key)) {
702
+ let prior;
703
+ if (s.segments.length > 1) {
704
+ const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
705
+ const parentScope = lookupResObj(
706
+ this.root,
707
+ s.segments.slice(0, s.segments.length - 1)
708
+ );
709
+ prior = parentScope?.priorValues.get(leafSeg);
710
+ } else {
711
+ const rootSeg = s.segments[0]?.text ?? "";
712
+ prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
713
+ }
714
+ if (prior !== void 0) {
715
+ const saved = this.resolving;
716
+ this.resolving = new Set(saved);
717
+ try {
718
+ return this.resolveVal(prior, scope);
719
+ } finally {
720
+ this.resolving = saved;
721
+ }
722
+ }
723
+ if (s.optional) return void 0;
724
+ throw new ResolveError(
725
+ this.originPrefix() + `circular substitution: ${key}`,
726
+ key,
727
+ s.line,
728
+ s.col
729
+ );
730
+ }
731
+ this.resolving.add(key);
732
+ try {
733
+ const found = lookupPath(this.root, s.segments);
734
+ if (found !== void 0) {
735
+ const rfp = this.resolvingFieldPath;
736
+ const isOwner = rfp.length >= s.segments.length && s.segments.every((seg, i) => rfp[i] === seg.text);
737
+ const isSelfRef = isConcat(found) && this.resolvingConcats.has(found) || isOwner && containsSubstByPath(found, s.segments);
738
+ if (isSelfRef) {
739
+ let prior;
740
+ if (s.segments.length > 1) {
741
+ const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
742
+ const parentScope = lookupResObj(
743
+ this.root,
744
+ s.segments.slice(0, s.segments.length - 1)
745
+ );
746
+ prior = parentScope?.priorValues.get(leafSeg);
747
+ } else {
748
+ const rootSeg = s.segments[0]?.text ?? "";
749
+ prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
750
+ }
751
+ if (prior !== void 0) {
752
+ const result2 = this.resolveVal(prior, scope);
753
+ if (result2 !== void 0) this.cache.set(key, result2);
754
+ return result2;
755
+ }
756
+ if (s.optional) return void 0;
757
+ throw new ResolveError(
758
+ `${this.originPrefix()}could not resolve substitution: \${${key}}`,
759
+ key,
760
+ s.line,
761
+ s.col
762
+ );
763
+ }
764
+ let result = this.resolveVal(found, scope);
765
+ const effectiveLen = s.segments.length - s.prefixLen;
766
+ if (effectiveLen === 1 && result !== void 0 && result.kind === "object") {
767
+ const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
768
+ let prior;
769
+ if (s.prefixLen > 0) {
770
+ const parentScope = lookupResObj(
771
+ this.root,
772
+ s.segments.slice(0, s.segments.length - 1)
773
+ );
774
+ prior = parentScope?.priorValues.get(leafSeg);
775
+ } else {
776
+ prior = scope.priorValues.get(leafSeg) ?? this.root.priorValues.get(leafSeg);
777
+ }
778
+ if (prior !== void 0) {
779
+ const priorResolved = this.resolveVal(prior, scope);
780
+ if (priorResolved !== void 0 && priorResolved.kind === "object") {
781
+ result = deepMergeHoconValues(
782
+ priorResolved,
783
+ result
784
+ );
785
+ }
786
+ }
787
+ }
788
+ if (result !== void 0) this.cache.set(key, result);
789
+ return result;
790
+ }
791
+ if (s.prefixLen > 0 && s.segments.length > s.prefixLen) {
792
+ const originalSegments = s.segments.slice(s.prefixLen);
793
+ const fallbackFound = lookupPath(this.root, originalSegments);
794
+ if (fallbackFound !== void 0) {
795
+ let result = this.resolveVal(fallbackFound, scope);
796
+ if (originalSegments.length === 1 && result !== void 0 && result.kind === "object") {
797
+ const rootSeg = originalSegments[0]?.text ?? "";
798
+ const prior = this.root.priorValues.get(rootSeg);
799
+ if (prior !== void 0) {
800
+ const priorResolved = this.resolveVal(prior, scope);
801
+ if (priorResolved !== void 0 && priorResolved.kind === "object") {
802
+ result = deepMergeHoconValues(
803
+ priorResolved,
804
+ result
805
+ );
806
+ }
807
+ }
808
+ }
809
+ if (result !== void 0) this.cache.set(key, result);
810
+ return result;
811
+ }
812
+ }
813
+ if (s.listSuffix && this.opts.useSystemEnvironment !== false) {
814
+ const result = this.resolveEnvList(s);
815
+ if (result !== void 0) {
816
+ this.cache.set(key, result);
817
+ return result;
818
+ }
819
+ if (s.optional) return void 0;
820
+ const envBase = s.segments.map((seg) => seg.text).join(".");
821
+ throw new ResolveError(
822
+ `${this.originPrefix()}could not resolve substitution: \${${key}} (no environment variables ${envBase}_0, ${envBase}_1, \u2026 set)`,
823
+ key,
824
+ s.line,
825
+ s.col
826
+ );
827
+ } else if (s.listSuffix) {
828
+ if (s.optional) return void 0;
829
+ if (this.opts.allowUnresolved) return s;
830
+ throw new ResolveError(
831
+ `${this.originPrefix()}could not resolve substitution: \${${key}}`,
832
+ key,
833
+ s.line,
834
+ s.col
835
+ );
836
+ }
837
+ if (this.opts.useSystemEnvironment !== false) {
838
+ const envKey = s.segments.map((seg) => seg.text).join(".");
839
+ const envVal = this.opts.env[envKey] ?? (s.prefixLen > 0 ? this.opts.env[s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".")] : void 0);
840
+ if (envVal !== void 0) {
841
+ const result = { kind: "scalar", raw: envVal, valueType: "string" };
842
+ this.cache.set(key, result);
843
+ return result;
844
+ }
845
+ }
846
+ if (s.optional) return void 0;
847
+ if (this.opts.allowUnresolved) {
848
+ return s;
849
+ }
850
+ throw new ResolveError(
851
+ `${this.originPrefix()}could not resolve substitution: \${${key}}`,
852
+ key,
853
+ s.line,
854
+ s.col
855
+ );
856
+ } finally {
857
+ this.resolving.delete(key);
858
+ }
859
+ }
860
+ /**
861
+ * S13c: scan environment for NAME_0, NAME_1, … and return an Array<Scalar(String)>.
862
+ *
863
+ * Candidate bases follow the same fully-qualified→bare order used by the scalar
864
+ * env fallback. The first base whose _0 key is present wins entirely — no
865
+ * cross-base merging (spec §Relativized fallback precedence rules).
866
+ *
867
+ * Returns the HoconValue Array if any candidate base has _0, or undefined if
868
+ * none do (caller applies optional/required handling).
869
+ */
870
+ resolveEnvList(s) {
871
+ const bases = this.candidateBases(s);
872
+ for (const base of bases) {
873
+ const key0 = base + "_0";
874
+ if (!(key0 in this.opts.env)) continue;
875
+ const items = [];
876
+ for (let i = 0; ; i++) {
877
+ const k = base + "_" + i;
878
+ if (!(k in this.opts.env)) break;
879
+ items.push({ kind: "scalar", raw: this.opts.env[k], valueType: "string" });
880
+ }
881
+ return { kind: "array", items };
882
+ }
883
+ return void 0;
884
+ }
885
+ /**
886
+ * Return the candidate base names for env-var-list lookup, in precedence order.
887
+ * Mirrors the fully-qualified→bare fallback used by the scalar env path.
888
+ */
889
+ candidateBases(s) {
890
+ const full = s.segments.map((seg) => seg.text).join(".");
891
+ if (s.prefixLen === 0) return [full];
892
+ const bare = s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".");
893
+ return [full, bare];
894
+ }
895
+ resolveConcat(nodes, scope, line = 0, col = 0) {
896
+ const rawResolved = nodes.map((n) => this.resolveVal(n, scope));
897
+ if (this.opts.allowUnresolved) {
898
+ for (const v of rawResolved) {
899
+ if (v !== void 0 && isSubst(v)) {
900
+ return v;
901
+ }
902
+ }
903
+ }
904
+ const resolved = rawResolved.filter((v) => v !== void 0);
905
+ if (resolved.length === 0) return void 0;
906
+ if (resolved.length === 1) return resolved[0];
907
+ const nonSep = resolved.filter((v) => !separatorValues.has(v));
908
+ if (nonSep.length === 0) {
909
+ const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
910
+ return { kind: "scalar", raw: str, valueType: "string" };
911
+ }
912
+ const joinPair = (left, right) => {
913
+ if (left.kind === "object" && right.kind === "object") {
914
+ return deepMergeHoconValues(left, right);
915
+ }
916
+ if (left.kind === "array" && right.kind === "object") {
917
+ const converted = numericObjectToArray(right);
918
+ if (converted !== null) {
919
+ return { kind: "array", items: [...left.items, ...converted] };
920
+ }
921
+ throw new ResolveError(
922
+ "cannot concatenate array with object: value concatenation requires same-kind operands (S10.4)",
923
+ "",
924
+ line,
925
+ col
926
+ );
927
+ }
928
+ if (left.kind === "object" && right.kind === "array") {
929
+ const converted = numericObjectToArray(left);
930
+ if (converted !== null) {
931
+ return { kind: "array", items: [...converted, ...right.items] };
932
+ }
933
+ throw new ResolveError(
934
+ "cannot concatenate object with array: value concatenation requires same-kind operands (S10.4)",
935
+ "",
936
+ line,
937
+ col
938
+ );
939
+ }
940
+ if (left.kind === "array" && right.kind === "array") {
941
+ return { kind: "array", items: [...left.items, ...right.items] };
942
+ }
943
+ if (left.kind === "array" || right.kind === "array") {
944
+ throw new ResolveError(
945
+ `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
946
+ "",
947
+ line,
948
+ col
949
+ );
950
+ }
951
+ if (left.kind === "object" || right.kind === "object") {
952
+ throw new ResolveError(
953
+ `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
954
+ "",
955
+ line,
956
+ col
957
+ );
958
+ }
959
+ return { kind: "scalar", raw: left.raw + right.raw, valueType: "string" };
960
+ };
961
+ const [head, ...tail] = nonSep;
962
+ const folded = tail.reduce(joinPair, head);
963
+ if (folded.kind === "scalar") {
964
+ const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
965
+ return { kind: "scalar", raw: str, valueType: "string" };
966
+ }
967
+ return folded;
968
+ }
969
+ };
970
+
971
+ // src/internal/resolver/resolver.ts
972
+ function resolveTree(tree, opts) {
973
+ return new SubstitutionResolver(tree, opts).resolve();
974
+ }
975
+ function containsPlaceholders(tree) {
976
+ for (const val of tree.fields.values()) {
977
+ if (valContainsPlaceholders(val)) return true;
978
+ }
979
+ return false;
980
+ }
981
+ function valContainsPlaceholders(v) {
982
+ const rv = v;
983
+ if (isSubst(rv) || isConcat(rv)) return true;
984
+ if (isResObj(rv)) return containsPlaceholders(rv);
985
+ const hv = v;
986
+ if (hv?.kind === "array") {
987
+ return hv.items.some((item) => valContainsPlaceholders(item));
988
+ }
989
+ return false;
990
+ }
991
+ function buildPartialHoconFromResObj(tree) {
992
+ const fields = /* @__PURE__ */ new Map();
993
+ for (const [k, v] of tree.fields) {
994
+ if (!isSubst(v) && !isConcat(v)) {
995
+ if (isResObj(v)) {
996
+ fields.set(k, buildPartialHoconFromResObj(v));
997
+ } else {
998
+ if (!valContainsPlaceholders(v)) {
999
+ fields.set(k, v);
1000
+ }
1001
+ }
1002
+ }
1003
+ }
1004
+ return { kind: "object", fields };
1005
+ }
1006
+ function hoconValueToResObj2(value) {
1007
+ const obj = makeResObj();
1008
+ for (const [k, v] of value.fields) {
1009
+ if (v.kind === "object") {
1010
+ obj.fields.set(k, hoconValueToResObj2(v));
1011
+ } else {
1012
+ obj.fields.set(k, v);
1013
+ }
1014
+ }
1015
+ return obj;
1016
+ }
1017
+
1018
+ // src/config.ts
1019
+ var Config = class _Config {
1020
+ constructor(root, opts) {
1021
+ this.root = root;
1022
+ this._resolved = opts?.resolved ?? true;
1023
+ this._parseBaseDir = opts?.parseBaseDir;
1024
+ this._originDescription = opts?.originDescription;
1025
+ this._resObjRoot = opts?.resObjRoot;
1026
+ this._resolveOpts = opts?.resolveOpts;
1027
+ }
1028
+ /** Returns true when the Config's value tree contains no unresolved
1029
+ * substitution placeholders. Whole-config granularity (E12 decision 11). */
1030
+ isResolved() {
1031
+ return this._resolved;
1032
+ }
1033
+ /** @internal Test-only: construct a resolved Config from a HoconValue. */
1034
+ static _fromResolvedValue(root, opts) {
1035
+ return new _Config(root, { resolved: true, originDescription: opts?.originDescription });
1036
+ }
1037
+ /** @internal Construct an unresolved Config carrying a ResObj tree.
1038
+ * Used by parseStringWithOptions (deferred path) in T6. */
1039
+ static _fromUnresolvedResObj(tree, opts) {
1040
+ const partialRoot = buildPartialHoconFromResObj(tree);
1041
+ return new _Config(partialRoot, {
1042
+ resolved: opts.resolved,
1043
+ parseBaseDir: opts.parseBaseDir,
1044
+ originDescription: opts.originDescription,
1045
+ resObjRoot: tree,
1046
+ resolveOpts: opts.resolveOpts
1047
+ });
1048
+ }
1049
+ get(path) {
1050
+ const v = this.lookupNode(path);
1051
+ if (v === void 0) return void 0;
1052
+ return hoconToJs(v);
1053
+ }
1054
+ /**
1055
+ * Returns the raw {@link HoconValue} node at `path` as a deeply-immutable
1056
+ * {@link ReadonlyHoconValue} view, or `undefined` if the path is absent. Unlike
1057
+ * `get` (which decodes to a plain JS value), this exposes the value tree for
1058
+ * structural introspection via the `value.ts` accessors (`asString`, `asObject`,
1059
+ * `isScalar`, …).
1060
+ *
1061
+ * `getValue('')` returns the root object node.
1062
+ *
1063
+ * Throws {@link NotResolvedError} when the node (or its subtree) is unresolved:
1064
+ * the `HoconValue` union has no placeholder variant, so an unresolved value
1065
+ * cannot be represented. This matches `getConfig` / `getList`.
1066
+ */
1067
+ getValue(path) {
1068
+ const v = this.lookupNode(path);
1069
+ if (v === void 0) {
1070
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1071
+ throw new NotResolvedError(path);
1072
+ }
1073
+ return void 0;
1074
+ }
1075
+ if (v.kind !== "scalar" && !this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1076
+ throw new NotResolvedError(path);
1077
+ }
1078
+ return v;
1079
+ }
1080
+ getString(path) {
1081
+ const v = this.requireScalar(path);
1082
+ if (v.valueType === "null") {
1083
+ throw new ConfigError(`expected string at ${path}, got ${v.valueType}`, path);
1084
+ }
1085
+ return v.raw;
1086
+ }
1087
+ getNumber(path) {
1088
+ const v = this.requireScalar(path);
1089
+ const coerced = coerceNumber(v.raw);
1090
+ if (coerced !== void 0) return coerced;
1091
+ throw new ConfigError(`expected number at ${path}, got ${v.valueType}`, path);
1092
+ }
1093
+ getBoolean(path) {
1094
+ const v = this.requireScalar(path);
1095
+ const coerced = coerceBoolean(v.raw);
1096
+ if (coerced !== void 0) return coerced;
1097
+ throw new ConfigError(`expected boolean at ${path}, got ${v.valueType}`, path);
1098
+ }
1099
+ getDuration(path, unit) {
1100
+ const v = this.requireScalar(path);
1101
+ if (v.valueType !== "string" && v.valueType !== "number") {
1102
+ throw new ConfigError(`expected duration at ${path}, got ${v.valueType}`, path);
1103
+ }
1104
+ const result = parseDuration(v.raw, unit);
1105
+ if (Number.isNaN(result)) throw new ConfigError(`invalid duration at ${path}: ${JSON.stringify(v.raw)}`, path);
1106
+ return result;
1107
+ }
1108
+ getBytes(path, unit) {
1109
+ const v = this.requireScalar(path);
1110
+ if (v.valueType !== "string" && v.valueType !== "number") {
1111
+ throw new ConfigError(`expected byte size at ${path}, got ${v.valueType}`, path);
1112
+ }
1113
+ const result = parseBytes(v.raw, unit);
1114
+ if (Number.isNaN(result)) throw new ConfigError(`invalid byte size at ${path}: ${JSON.stringify(v.raw)}`, path);
1115
+ if (result < 0) throw new ConfigError(`byte size must be non-negative at ${path}: ${JSON.stringify(v.raw)}`, path);
1116
+ return result;
1117
+ }
1118
+ getConfig(path) {
1119
+ const v = this.lookupNode(path);
1120
+ if (v === void 0) {
1121
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1122
+ throw new NotResolvedError(path);
1123
+ }
1124
+ throw new ConfigError(`path not found: ${path}`, path);
1125
+ }
1126
+ if (v.kind !== "object") throw new ConfigError(`expected object at ${path}`, path);
1127
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1128
+ throw new NotResolvedError(path);
1129
+ }
1130
+ return new _Config(v, { resolved: this._resolved });
1131
+ }
1132
+ getList(path) {
1133
+ const v = this.lookupNode(path);
1134
+ if (v === void 0) {
1135
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1136
+ throw new NotResolvedError(path);
1137
+ }
1138
+ throw new ConfigError(`path not found: ${path}`, path);
1139
+ }
1140
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1141
+ throw new NotResolvedError(path);
1142
+ }
1143
+ if (v.kind === "object") {
1144
+ const converted = numericObjectToArray(v);
1145
+ if (converted !== null) return converted.map((item) => hoconToJs(item));
1146
+ }
1147
+ if (v.kind !== "array") throw new ConfigError(`expected array at ${path}`, path);
1148
+ return v.items.map((item) => hoconToJs(item));
1149
+ }
1150
+ has(path) {
1151
+ return this.lookupNode(path) !== void 0;
1152
+ }
1153
+ keys() {
1154
+ return [...this.root.fields.keys()];
1155
+ }
1156
+ withFallback(fallback) {
1157
+ if (fallback == null) return this;
1158
+ const selfTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1159
+ const fbTree = fallback._resObjRoot ?? hoconValueToResObj2(fallback.root);
1160
+ const merged = mergeUnresolved(selfTree, fbTree);
1161
+ const hasPlaceholders = containsPlaceholders(merged);
1162
+ const partialRoot = buildPartialHoconFromResObj(merged);
1163
+ return new _Config(partialRoot, {
1164
+ resolved: !hasPlaceholders,
1165
+ parseBaseDir: this._parseBaseDir,
1166
+ originDescription: this._originDescription,
1167
+ resObjRoot: merged,
1168
+ resolveOpts: this._resolveOpts ?? fallback._resolveOpts
1169
+ });
1170
+ }
1171
+ /**
1172
+ * Runs substitution resolution (phase 2) on the stored unresolved tree.
1173
+ * Idempotent: calling resolve() on an already-resolved Config returns an
1174
+ * equivalent resolved Config.
1175
+ *
1176
+ * opts.allowUnresolved (default false) — when true, leaves unresolved
1177
+ * non-optional placeholders in place rather than throwing.
1178
+ * opts.useSystemEnvironment (default true) — when false, env var lookups
1179
+ * are suppressed (hermetic resolution).
1180
+ *
1181
+ * E12 decision 3.
1182
+ */
1183
+ resolve(opts = {}) {
1184
+ if (this._resolved) {
1185
+ return new _Config(this.root, {
1186
+ resolved: true,
1187
+ parseBaseDir: this._parseBaseDir,
1188
+ originDescription: this._originDescription
1189
+ });
1190
+ }
1191
+ const tree = this._resObjRoot;
1192
+ if (!tree) {
1193
+ return new _Config(this.root, { resolved: true });
1194
+ }
1195
+ const resolveOpts = {
1196
+ ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1197
+ throw new Error("no files");
1198
+ } },
1199
+ allowUnresolved: opts.allowUnresolved ?? false,
1200
+ useSystemEnvironment: opts.useSystemEnvironment ?? true,
1201
+ originDescription: this._originDescription
1202
+ };
1203
+ const resolved = resolveTree(tree, resolveOpts);
1204
+ if (resolved.kind !== "object") throw new Error("resolve: expected object root");
1205
+ if (opts.allowUnresolved) {
1206
+ const { stripped, hadPlaceholders } = stripPlaceholderFields(resolved);
1207
+ return new _Config(stripped, {
1208
+ resolved: !hadPlaceholders,
1209
+ parseBaseDir: this._parseBaseDir,
1210
+ originDescription: this._originDescription,
1211
+ resObjRoot: hadPlaceholders ? tree : void 0,
1212
+ resolveOpts: hadPlaceholders ? resolveOpts : void 0
1213
+ });
1214
+ }
1215
+ return new _Config(resolved, {
1216
+ resolved: true,
1217
+ parseBaseDir: this._parseBaseDir,
1218
+ originDescription: this._originDescription
1219
+ });
1220
+ }
1221
+ /**
1222
+ * Resolves receiver substitutions using source as lookup context.
1223
+ * Source's keys are NOT merged into the result — differs from
1224
+ * `this.withFallback(source).resolve()` which includes source keys.
1225
+ *
1226
+ * Precondition (E12 decision 10): source must be resolved. If
1227
+ * source.isResolved() is false, throws NotResolvedError.
1228
+ *
1229
+ * On an already-resolved receiver, resolveWith is a no-op (returns an
1230
+ * equivalent resolved Config, source keys not included).
1231
+ *
1232
+ * E12 decisions 9, 10.
1233
+ */
1234
+ resolveWith(source, opts = {}) {
1235
+ if (!source.isResolved()) {
1236
+ throw new NotResolvedError("source");
1237
+ }
1238
+ if (this._resolved) {
1239
+ return new _Config(this.root, {
1240
+ resolved: true,
1241
+ parseBaseDir: this._parseBaseDir,
1242
+ originDescription: this._originDescription
1243
+ });
1244
+ }
1245
+ const receiverTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1246
+ const srcTree = hoconValueToResObj2(source.root);
1247
+ const merged = mergeUnresolved(receiverTree, srcTree);
1248
+ const resolveOpts = {
1249
+ ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1250
+ throw new Error("no files");
1251
+ } },
1252
+ allowUnresolved: opts.allowUnresolved ?? false,
1253
+ useSystemEnvironment: opts.useSystemEnvironment ?? true,
1254
+ originDescription: this._originDescription
1255
+ };
1256
+ const resolved = resolveTree(merged, resolveOpts);
1257
+ if (resolved.kind !== "object") throw new Error("resolveWith: expected object root");
1258
+ const receiverShapeForFilter = resObjToKeyShape(receiverTree);
1259
+ const filtered = filterByReceiverShape(resolved, receiverShapeForFilter);
1260
+ if (opts.allowUnresolved) {
1261
+ const { stripped, hadPlaceholders } = stripPlaceholderFields(filtered);
1262
+ return new _Config(stripped, {
1263
+ resolved: !hadPlaceholders,
1264
+ parseBaseDir: this._parseBaseDir,
1265
+ originDescription: this._originDescription,
1266
+ resObjRoot: hadPlaceholders ? receiverTree : void 0,
1267
+ resolveOpts: hadPlaceholders ? resolveOpts : void 0
1268
+ });
1269
+ }
1270
+ return new _Config(filtered, {
1271
+ resolved: true,
1272
+ parseBaseDir: this._parseBaseDir,
1273
+ originDescription: this._originDescription
1274
+ });
1275
+ }
1276
+ /**
1277
+ * The whole config as plain JS data: objects, arrays, strings, numbers,
1278
+ * booleans and `null`.
1279
+ *
1280
+ * Keys are reproduced exactly as the config carries them, `__proto__`,
1281
+ * `constructor` and `prototype` included: each is defined as an **own data
1282
+ * property**, so the returned object's prototype is always
1283
+ * `Object.prototype`, and this call writes nothing to the global one.
1284
+ *
1285
+ * ### Passing the result to other code
1286
+ *
1287
+ * A config file — especially a `.properties` file or an env namespace you
1288
+ * merged in — can therefore hand you an own `__proto__` key, and what happens
1289
+ * next depends entirely on how the consumer copies it:
1290
+ *
1291
+ * ```ts
1292
+ * const data = cfg.toObject()
1293
+ * { ...data } // safe — own properties are copied as data
1294
+ * structuredClone(data) // safe
1295
+ * Object.assign({}, data) // NOT safe — [[Set]] on the {} target hits
1296
+ * // Object.prototype's __proto__ setter: the key
1297
+ * // vanishes and config data becomes the result's
1298
+ * // prototype
1299
+ * deepMerge({}, data) // NOT safe — a naive recursive merge reads
1300
+ * // target['__proto__'], gets Object.prototype,
1301
+ * // and writes to it: global pollution
1302
+ * for (const k in data) … // prefer Object.entries / Object.keys
1303
+ * ```
1304
+ *
1305
+ * Those two hazards come from the **destination** object's prototype, so no
1306
+ * option here can disarm them — copy with spread or `structuredClone` instead.
1307
+ *
1308
+ * What `{ nullPrototype: true }` does give you is a result that inherits
1309
+ * nothing: every object comes back with a `null` prototype, so reading
1310
+ * `x.__proto__`, `x.constructor` or `x.toString` yields config data or
1311
+ * `undefined` rather than something from `Object.prototype`, and code that
1312
+ * merges *into* this object cannot climb out of it. Keys are all still
1313
+ * present. The trade-off is the usual one for prototype-less objects: not
1314
+ * `instanceof Object`, and no `hasOwnProperty` of their own.
1315
+ *
1316
+ * Numbers follow the JS number model, so an integer wider than 2^53 rounds
1317
+ * here even when the config holds it exactly — read those with
1318
+ * {@link Config.getString} instead.
1319
+ */
1320
+ toObject(opts) {
1321
+ return hoconToJs(this.root, opts?.nullPrototype === true);
1322
+ }
1323
+ /**
1324
+ * @internal Test-only: renders this resolved Config's value tree as canonical
1325
+ * JSON (sorted keys, no whitespace). Used by Layer-2 fixture tests to compare
1326
+ * against Lightbend ground truth. NOT part of the public API.
1327
+ *
1328
+ * Throws if the Config is unresolved (contains placeholders).
1329
+ */
1330
+ _renderJSONForTest() {
1331
+ return renderHoconAsJSON(this.root);
1332
+ }
1333
+ lookupNode(path) {
1334
+ const segments = splitConfigPath(path);
1335
+ let current = this.root;
1336
+ for (const seg of segments) {
1337
+ if (current.kind !== "object") return void 0;
1338
+ const next = current.fields.get(seg);
1339
+ if (next === void 0) return void 0;
1340
+ current = next;
1341
+ }
1342
+ return current;
1343
+ }
1344
+ /**
1345
+ * _resObjRootSubtreeHasPlaceholders — walk _resObjRoot to the given path and
1346
+ * return true if the subtree there contains any unresolved placeholder.
1347
+ * Used by getConfig / getList (T2) to detect transitive unresolved placeholders
1348
+ * in object / array subtrees that would otherwise appear to be "resolved" in the
1349
+ * partial HoconValue root (because individual leaf fields are omitted rather than
1350
+ * the whole subtree when their value is a direct placeholder scalar, but object
1351
+ * sub-containers are retained in the partial root with the placeholder-keyed
1352
+ * fields omitted from them — so the object appears "present but empty-ish").
1353
+ */
1354
+ _resObjRootSubtreeHasPlaceholders(path) {
1355
+ const tree = this._resObjRoot;
1356
+ if (!tree) return false;
1357
+ const segments = splitConfigPath(path);
1358
+ let cur = tree;
1359
+ for (const seg of segments) {
1360
+ const val = cur.fields.get(seg);
1361
+ if (val === void 0) return false;
1362
+ if (isResObj(val)) {
1363
+ cur = val;
1364
+ } else {
1365
+ return valContainsPlaceholders(val);
1366
+ }
1367
+ }
1368
+ return containsPlaceholders(cur);
1369
+ }
1370
+ requireScalar(path) {
1371
+ const v = this.lookupNode(path);
1372
+ if (v === void 0) {
1373
+ if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1374
+ throw new NotResolvedError(path);
1375
+ }
1376
+ throw new ConfigError(`path not found: ${path}`, path);
1377
+ }
1378
+ if (v.kind !== "scalar") throw new ConfigError(`expected scalar at ${path}, got ${v.kind}`, path);
1379
+ return v;
1380
+ }
1381
+ };
1382
+ function splitConfigPath(path) {
1383
+ const segments = [];
1384
+ let i = 0;
1385
+ while (i < path.length) {
1386
+ if (path[i] === '"') {
1387
+ i++;
1388
+ let segment = "";
1389
+ let closed = false;
1390
+ while (i < path.length) {
1391
+ const ch = path[i];
1392
+ if (ch === "\\" && i + 1 < path.length) {
1393
+ const next = path[i + 1];
1394
+ segment += next;
1395
+ i += 2;
1396
+ continue;
1397
+ }
1398
+ if (ch === '"') {
1399
+ closed = true;
1400
+ i++;
1401
+ break;
1402
+ }
1403
+ segment += ch;
1404
+ i++;
1405
+ }
1406
+ if (!closed) throw new ConfigError(`unterminated quoted path segment: ${path}`, path);
1407
+ segments.push(segment);
1408
+ if (i < path.length && path[i] === ".") i++;
1409
+ } else {
1410
+ const dot = path.indexOf(".", i);
1411
+ if (dot === -1) {
1412
+ segments.push(path.slice(i));
1413
+ break;
1414
+ }
1415
+ segments.push(path.slice(i, dot));
1416
+ i = dot + 1;
1417
+ }
1418
+ }
1419
+ return segments;
1420
+ }
1421
+ function scalarToJs(raw, valueType) {
1422
+ switch (valueType) {
1423
+ case "null":
1424
+ return null;
1425
+ case "boolean":
1426
+ return raw === "true";
1427
+ case "number":
1428
+ return Number(raw);
1429
+ case "string":
1430
+ return raw;
1431
+ }
1432
+ }
1433
+ function hoconToJs(v, nullPrototype = false) {
1434
+ switch (v.kind) {
1435
+ case "scalar":
1436
+ return scalarToJs(v.raw, v.valueType);
1437
+ case "array":
1438
+ return v.items.map((item) => hoconToJs(item, nullPrototype));
1439
+ case "object": {
1440
+ const entries = Array.from(v.fields, ([k, val]) => [k, hoconToJs(val, nullPrototype)]);
1441
+ if (nullPrototype) {
1442
+ const obj = /* @__PURE__ */ Object.create(null);
1443
+ for (const [k, val] of entries) Object.defineProperty(obj, k, {
1444
+ value: val,
1445
+ writable: true,
1446
+ enumerable: true,
1447
+ configurable: true
1448
+ });
1449
+ return obj;
1450
+ }
1451
+ return Object.fromEntries(entries);
1452
+ }
1453
+ }
1454
+ }
1455
+ function resObjToKeyShape(tree) {
1456
+ const fields = /* @__PURE__ */ new Map();
1457
+ for (const [k, v] of tree.fields) {
1458
+ if (isSubst(v) || isConcat(v)) {
1459
+ fields.set(k, { kind: "scalar", raw: "", valueType: "null" });
1460
+ } else if (isResObj(v)) {
1461
+ fields.set(k, resObjToKeyShape(v));
1462
+ } else {
1463
+ fields.set(k, v);
1464
+ }
1465
+ }
1466
+ return { kind: "object", fields };
1467
+ }
1468
+ function stripPlaceholderFields(v) {
1469
+ const fields = /* @__PURE__ */ new Map();
1470
+ let hadPlaceholders = false;
1471
+ for (const [k, val] of v.fields) {
1472
+ if (val._kind === "subst-placeholder" || val._kind === "concat-placeholder") {
1473
+ hadPlaceholders = true;
1474
+ } else if (val.kind === "object") {
1475
+ const inner = stripPlaceholderFields(val);
1476
+ if (inner.hadPlaceholders) hadPlaceholders = true;
1477
+ fields.set(k, inner.stripped);
1478
+ } else {
1479
+ fields.set(k, val);
1480
+ }
1481
+ }
1482
+ return { stripped: { kind: "object", fields }, hadPlaceholders };
1483
+ }
1484
+ function filterByReceiverShape(resolved, receiverShape) {
1485
+ const fields = /* @__PURE__ */ new Map();
1486
+ for (const [k, rv] of resolved.fields) {
1487
+ if (!receiverShape.fields.has(k)) continue;
1488
+ const receiverVal = receiverShape.fields.get(k);
1489
+ if (rv.kind === "object" && receiverVal.kind === "object") {
1490
+ fields.set(k, filterByReceiverShape(rv, receiverVal));
1491
+ } else {
1492
+ fields.set(k, rv);
1493
+ }
1494
+ }
1495
+ return { kind: "object", fields };
1496
+ }
1497
+ function renderHoconAsJSON(v) {
1498
+ switch (v.kind) {
1499
+ case "scalar": {
1500
+ switch (v.valueType) {
1501
+ case "null":
1502
+ return "null";
1503
+ case "boolean":
1504
+ return v.raw;
1505
+ case "number": {
1506
+ const norm = normalizeLeadingZeroNumber(v.raw);
1507
+ return JSON_NUMBER_RE.test(norm) ? norm : JSON.stringify(v.raw);
1508
+ }
1509
+ case "string":
1510
+ return JSON.stringify(v.raw);
1511
+ }
1512
+ break;
1513
+ }
1514
+ case "array": {
1515
+ const items = v.items.map(renderHoconAsJSON);
1516
+ return `[${items.join(",")}]`;
1517
+ }
1518
+ case "object": {
1519
+ const keys = [...v.fields.keys()].sort();
1520
+ const pairs = keys.map((k) => {
1521
+ const val = v.fields.get(k);
1522
+ return `${JSON.stringify(k)}:${renderHoconAsJSON(val)}`;
1523
+ });
1524
+ return `{${pairs.join(",")}}`;
1525
+ }
1526
+ }
1527
+ throw new Error(`renderHoconAsJSON: unsupported value kind (unresolved placeholder?)`);
1528
+ }
1529
+ var JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
1530
+ function normalizeLeadingZeroNumber(raw) {
1531
+ return raw.replace(/^([+-]?)0+(\d)/, "$1$2");
1532
+ }
1533
+
1534
+ // src/value-factory.ts
1535
+ function fromMap(values, originDescription) {
1536
+ const fields = coerceObject(values, "");
1537
+ const root = { kind: "object", fields };
1538
+ return Config._fromResolvedValue(root, { originDescription });
1539
+ }
1540
+ var INT64_MAX = 9223372036854775807n;
1541
+ var INT64_MIN = -9223372036854775808n;
1542
+ function coerceObject(obj, atPath) {
1543
+ const fields = /* @__PURE__ */ new Map();
1544
+ for (const [k, v] of Object.entries(obj)) {
1545
+ const childPath = atPath ? `${atPath}.${k}` : k;
1546
+ fields.set(k, coerceValue(v, childPath));
1547
+ }
1548
+ return fields;
1549
+ }
1550
+ function coerceValue(v, atPath) {
1551
+ if (v === null) {
1552
+ return { kind: "scalar", raw: "null", valueType: "null" };
1553
+ }
1554
+ if (v === void 0) {
1555
+ throw new ConfigError(
1556
+ `fromMap: undefined is not a valid HOCON value at path "${atPath}"`,
1557
+ atPath
1558
+ );
1559
+ }
1560
+ switch (typeof v) {
1561
+ case "string":
1562
+ return { kind: "scalar", raw: v, valueType: "string" };
1563
+ case "number": {
1564
+ if (Number.isNaN(v) || !Number.isFinite(v)) {
1565
+ throw new ConfigError(
1566
+ `fromMap: ${v} is not representable in HOCON (NaN/Infinity not allowed) at path "${atPath}"`,
1567
+ atPath
1568
+ );
1569
+ }
1570
+ return { kind: "scalar", raw: Object.is(v, -0) ? "-0" : String(v), valueType: "number" };
1571
+ }
1572
+ case "boolean":
1573
+ return { kind: "scalar", raw: v ? "true" : "false", valueType: "boolean" };
1574
+ case "bigint": {
1575
+ if (v > INT64_MAX || v < INT64_MIN) {
1576
+ throw new ConfigError(
1577
+ `fromMap: integer ${v} is out of int64 range (HOCON integers are int64; spec F0.5) at path "${atPath}"`,
1578
+ atPath
1579
+ );
1580
+ }
1581
+ return { kind: "scalar", raw: String(v), valueType: "number" };
1582
+ }
1583
+ case "object": {
1584
+ if (Array.isArray(v)) {
1585
+ const items = v.map((item, i) => coerceValue(item, `${atPath}[${i}]`));
1586
+ return { kind: "array", items };
1587
+ }
1588
+ const fields = coerceObject(v, atPath);
1589
+ return { kind: "object", fields };
1590
+ }
1591
+ default:
1592
+ throw new ConfigError(
1593
+ `fromMap: unsupported value type "${typeof v}" at path "${atPath}"`,
1594
+ atPath
1595
+ );
1596
+ }
1597
+ }
1598
+
1599
+ // src/adapters/env.ts
1600
+ var SEPARATOR = "__";
1601
+ function loadEnv(opts = {}) {
1602
+ const prefix = opts.prefix ?? "";
1603
+ if (prefix === "") {
1604
+ throw new ConfigError(
1605
+ "loadEnv: a prefix is required when mounting the environment (spec F1.1)",
1606
+ ""
1607
+ );
1608
+ }
1609
+ const source = opts.env ?? globalThis.process?.env ?? {};
1610
+ const names = Object.keys(source).sort();
1611
+ const seen = /* @__PURE__ */ new Map();
1612
+ const pairs = [];
1613
+ for (const name of names) {
1614
+ if (!name.startsWith(prefix)) continue;
1615
+ const value = source[name];
1616
+ if (value === void 0) continue;
1617
+ const path = toPath(name.slice(prefix.length));
1618
+ const key = pathKey(path);
1619
+ const prev = seen.get(key);
1620
+ if (prev !== void 0) {
1621
+ throw new ConfigError(`loadEnv: ${prev} and ${name} both map to "${path.join(".")}"`, path.join("."));
1622
+ }
1623
+ seen.set(key, name);
1624
+ pairs.push([path, value]);
1625
+ }
1626
+ return fromMap(nestPairs(pairs), opts.originDescription ?? "environment variables");
1627
+ }
1628
+ function parseDotEnv(input, opts = {}) {
1629
+ const origin = opts.originDescription ?? ".env";
1630
+ const prefix = opts.prefix ?? "";
1631
+ const pairs = [];
1632
+ const lines = stripBom(input).replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
1633
+ for (let i = 0; i < lines.length; i++) {
1634
+ const raw = (lines[i] ?? "").trim();
1635
+ if (raw === "" || raw.startsWith("#")) continue;
1636
+ const line = raw.startsWith("export ") ? raw.slice("export ".length) : raw;
1637
+ const eq = line.indexOf("=");
1638
+ if (eq === -1) throw new ConfigError(`${origin}:${i + 1}: expected NAME=value`, "");
1639
+ const name = line.slice(0, eq).trim();
1640
+ if (name === "") throw new ConfigError(`${origin}:${i + 1}: empty variable name`, "");
1641
+ const value = dotEnvValue(line.slice(eq + 1).replace(/^[ \t]+/, ""), origin, i + 1, name);
1642
+ if (!name.startsWith(prefix)) continue;
1643
+ pairs.push([toPath(name.slice(prefix.length)), value]);
1644
+ }
1645
+ return fromMap(nestPairs(pairs), origin);
1646
+ }
1647
+ function toPath(name) {
1648
+ const segs = name.split(SEPARATOR).map(asciiLower);
1649
+ if (segs.some((s) => s === "")) {
1650
+ throw new ConfigError(`env: "${name}" produces an empty path segment`, name);
1651
+ }
1652
+ return segs;
1653
+ }
1654
+ function asciiLower(s) {
1655
+ return s.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
1656
+ }
1657
+ function dotEnvValue(v, origin, line, name) {
1658
+ const fail = (msg) => {
1659
+ throw new ConfigError(`${origin}:${line}: ${name}: ${msg}`, name);
1660
+ };
1661
+ if (v.startsWith("'")) {
1662
+ const end = v.indexOf("'", 1);
1663
+ if (end === -1) fail("unterminated ' quote (multi-line values are not supported)");
1664
+ if (v.slice(end + 1).trim() !== "") fail(`unexpected text after the closing quote`);
1665
+ return v.slice(1, end);
1666
+ }
1667
+ if (v.startsWith('"')) {
1668
+ let out = "";
1669
+ for (let i = 1; i < v.length; i++) {
1670
+ const c = v[i];
1671
+ if (c === '"') {
1672
+ if (v.slice(i + 1).trim() !== "") fail("unexpected text after the closing quote");
1673
+ return out;
1674
+ }
1675
+ if (c === "\\") {
1676
+ i++;
1677
+ const e = v[i];
1678
+ if (e === void 0) fail("dangling \\ at end of line");
1679
+ else if (e === "n") out += "\n";
1680
+ else if (e === "r") out += "\r";
1681
+ else if (e === "t") out += " ";
1682
+ else if (e === "\\") out += "\\";
1683
+ else if (e === '"') out += '"';
1684
+ else fail(`unknown escape \\${e} (supported: \\n \\r \\t \\\\ \\")`);
1685
+ continue;
1686
+ }
1687
+ out += c;
1688
+ }
1689
+ return fail('unterminated " quote (multi-line values are not supported)');
1690
+ }
1691
+ const trimmed = v.replace(/[ \t]+$/, "");
1692
+ if (/[ \t]#/.test(trimmed)) {
1693
+ fail(`ambiguous value "${trimmed}": trailing comments are not supported, so quote the value if the # belongs to it`);
1694
+ }
1695
+ return trimmed;
1696
+ }
1697
+ export {
1698
+ loadEnv,
1699
+ parseDotEnv
1700
+ };