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