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