@o3co/ts.hocon 1.13.0 → 1.14.1

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