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