@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
package/dist/index.js CHANGED
@@ -1,3659 +1,28 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/coerce.ts
9
- var DECIMAL_NUMBER_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
10
- function isHoconWs(cp) {
11
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
12
- if (cp >= 28 && cp <= 31) return true;
13
- if (cp === 32 || cp === 160 || cp === 65279) return true;
14
- if (cp === 5760) return true;
15
- if (cp >= 8192 && cp <= 8202) return true;
16
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
17
- if (cp === 12288) return true;
18
- return false;
19
- }
20
- function trimHoconWs(s) {
21
- let start = 0;
22
- let end = s.length;
23
- while (start < end && isHoconWs(s.charCodeAt(start))) {
24
- start++;
25
- }
26
- while (end > start && isHoconWs(s.charCodeAt(end - 1))) {
27
- end--;
28
- }
29
- return s.slice(start, end);
30
- }
31
- var TRUTHY = /* @__PURE__ */ new Set(["true", "yes", "on"]);
32
- var FALSY = /* @__PURE__ */ new Set(["false", "no", "off"]);
33
- function coerceBoolean(value) {
34
- const lower = value.toLowerCase();
35
- if (TRUTHY.has(lower)) return true;
36
- if (FALSY.has(lower)) return false;
37
- return void 0;
38
- }
39
- function coerceNumber(value) {
40
- if (!DECIMAL_NUMBER_RE.test(value)) return void 0;
41
- return Number(value);
42
- }
43
- var DURATION_UNITS = {
44
- // S19.1–S19.3: the bare nano/micro/milli (+plural) aliases are part of the
45
- // spec's unit lists (HOCON.md L1307–L1309) and accepted by Lightbend
46
- // (typesafe-config 1.4.6 probe, 2026-08-18); they were missing here.
47
- ns: 1e-6,
48
- nano: 1e-6,
49
- nanos: 1e-6,
50
- nanosecond: 1e-6,
51
- nanoseconds: 1e-6,
52
- us: 1e-3,
53
- micro: 1e-3,
54
- micros: 1e-3,
55
- microsecond: 1e-3,
56
- microseconds: 1e-3,
57
- ms: 1,
58
- milli: 1,
59
- millis: 1,
60
- millisecond: 1,
61
- milliseconds: 1,
62
- s: 1e3,
63
- second: 1e3,
64
- seconds: 1e3,
65
- m: 6e4,
66
- minute: 6e4,
67
- minutes: 6e4,
68
- h: 36e5,
69
- hour: 36e5,
70
- hours: 36e5,
71
- d: 864e5,
72
- day: 864e5,
73
- days: 864e5
74
- };
75
- var OUTPUT_DURATION_UNITS = {
76
- ns: 1e-6,
77
- us: 1e-3,
78
- ms: 1,
79
- s: 1e3,
80
- m: 6e4,
81
- h: 36e5,
82
- d: 864e5
83
- };
84
- function parseDuration(value, outputUnit = "ms") {
85
- const trimmed = trimHoconWs(value);
86
- let i = 0;
87
- while (i < trimmed.length) {
88
- const ch = trimmed[i];
89
- if (i === 0 && (ch === "-" || ch === "+")) {
90
- i++;
91
- continue;
92
- }
93
- if (ch !== "." && (ch < "0" || ch > "9")) break;
94
- i++;
95
- }
96
- if (i === 0) return NaN;
97
- const num = Number(trimmed.slice(0, i));
98
- if (Number.isNaN(num)) return NaN;
99
- const unit = trimHoconWs(trimmed.slice(i));
100
- const divisor = OUTPUT_DURATION_UNITS[outputUnit];
101
- if (divisor === void 0) return NaN;
102
- if (unit === "") {
103
- return num / divisor;
104
- }
105
- const mult = DURATION_UNITS[unit];
106
- if (mult === void 0) return NaN;
107
- const ms = num * mult;
108
- return ms / divisor;
109
- }
110
- var BYTE_UNITS = {
111
- // S21.1–S21.4 — the EXACT Lightbend/typesafe-config unit set (1.4.6 probe,
112
- // 2026-08-18). Multi-letter units are case-sensitive: the SI decimal short
113
- // form is `kB` (NOT `KB`/`kb` — Lightbend rejects both), higher decimals
114
- // are `MB`…`YB`, binary prefixes are `Ki`/`KiB`…`Yi`/`YiB` with capital
115
- // first letter, and long forms are lowercase only (`kilobyte`, never
116
- // `Kilobyte`). Only the bare byte unit (`B`/`b`) and the single-letter
117
- // -Xmx forms accept both cases. The old case-insensitive fallback and the
118
- // lowercase alias rows accepted spellings Lightbend rejects — removed.
119
- B: 1,
120
- b: 1,
121
- byte: 1,
122
- bytes: 1,
123
- kB: 1e3,
124
- kilobyte: 1e3,
125
- kilobytes: 1e3,
126
- MB: 1e6,
127
- megabyte: 1e6,
128
- megabytes: 1e6,
129
- GB: 1e9,
130
- gigabyte: 1e9,
131
- gigabytes: 1e9,
132
- TB: 1e12,
133
- terabyte: 1e12,
134
- terabytes: 1e12,
135
- PB: 1e15,
136
- petabyte: 1e15,
137
- petabytes: 1e15,
138
- EB: 1e18,
139
- exabyte: 1e18,
140
- exabytes: 1e18,
141
- ZB: 1e21,
142
- zettabyte: 1e21,
143
- zettabytes: 1e21,
144
- YB: 1e24,
145
- yottabyte: 1e24,
146
- yottabytes: 1e24,
147
- Ki: 1024,
148
- KiB: 1024,
149
- kibibyte: 1024,
150
- kibibytes: 1024,
151
- Mi: 1048576,
152
- MiB: 1048576,
153
- mebibyte: 1048576,
154
- mebibytes: 1048576,
155
- Gi: 1073741824,
156
- GiB: 1073741824,
157
- gibibyte: 1073741824,
158
- gibibytes: 1073741824,
159
- Ti: 1099511627776,
160
- TiB: 1099511627776,
161
- tebibyte: 1099511627776,
162
- tebibytes: 1099511627776,
163
- Pi: 1024 ** 5,
164
- PiB: 1024 ** 5,
165
- pebibyte: 1024 ** 5,
166
- pebibytes: 1024 ** 5,
167
- Ei: 1024 ** 6,
168
- EiB: 1024 ** 6,
169
- exbibyte: 1024 ** 6,
170
- exbibytes: 1024 ** 6,
171
- Zi: 1024 ** 7,
172
- ZiB: 1024 ** 7,
173
- zebibyte: 1024 ** 7,
174
- zebibytes: 1024 ** 7,
175
- Yi: 1024 ** 8,
176
- YiB: 1024 ** 8,
177
- yobibyte: 1024 ** 8,
178
- yobibytes: 1024 ** 8,
179
- // S21.4 — single-letter abbreviations → powers of two (java -Xmx
180
- // convention); Lightbend accepts BOTH cases here, through the full ladder.
181
- K: 1024,
182
- k: 1024,
183
- M: 1024 ** 2,
184
- m: 1024 ** 2,
185
- G: 1024 ** 3,
186
- g: 1024 ** 3,
187
- T: 1024 ** 4,
188
- t: 1024 ** 4,
189
- P: 1024 ** 5,
190
- p: 1024 ** 5,
191
- E: 1024 ** 6,
192
- e: 1024 ** 6,
193
- Z: 1024 ** 7,
194
- z: 1024 ** 7,
195
- Y: 1024 ** 8,
196
- y: 1024 ** 8
197
- };
198
- var OUTPUT_BYTE_UNITS = {
199
- B: 1,
200
- KB: 1e3,
201
- KiB: 1024,
202
- MB: 1e6,
203
- MiB: 1048576,
204
- GB: 1e9,
205
- GiB: 1073741824,
206
- TB: 1e12,
207
- TiB: 1099511627776
208
- };
209
- function parseBytes(value, outputUnit = "B") {
210
- const trimmed = trimHoconWs(value);
211
- let i = 0;
212
- while (i < trimmed.length) {
213
- const ch = trimmed[i];
214
- if (i === 0 && (ch === "-" || ch === "+")) {
215
- i++;
216
- continue;
217
- }
218
- if (ch !== "." && (ch < "0" || ch > "9")) break;
219
- i++;
220
- }
221
- if (i === 0) return NaN;
222
- const num = Number(trimmed.slice(0, i));
223
- if (Number.isNaN(num)) return NaN;
224
- const unit = trimHoconWs(trimmed.slice(i));
225
- const divisor = OUTPUT_BYTE_UNITS[outputUnit];
226
- if (divisor === void 0) return NaN;
227
- if (unit === "") {
228
- const bytes2 = Math.trunc(num);
229
- if (Math.abs(bytes2) > Number.MAX_SAFE_INTEGER) {
230
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
231
- }
232
- return bytes2 / divisor;
233
- }
234
- const mult = BYTE_UNITS[unit];
235
- if (mult === void 0) return NaN;
236
- const bytes = num * mult;
237
- if (Math.abs(bytes) > Number.MAX_SAFE_INTEGER) {
238
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
239
- }
240
- const result = bytes / divisor;
241
- return outputUnit === "B" ? Math.round(result) : result;
242
- }
243
-
244
- // src/errors.ts
245
- var ParseError = class extends Error {
246
- constructor(message, line, col, file) {
247
- super(message);
248
- this.line = line;
249
- this.col = col;
250
- this.file = file;
251
- this.name = "ParseError";
252
- }
253
- };
254
- var ResolveError = class extends Error {
255
- constructor(message, path2, line, col, file) {
256
- super(message);
257
- this.path = path2;
258
- this.line = line;
259
- this.col = col;
260
- this.file = file;
261
- this.name = "ResolveError";
262
- }
263
- };
264
- var PackageLookupError = class extends ResolveError {
265
- constructor(message, identifier, packageFile, line, col) {
266
- super(message, `${identifier}/${packageFile}`, line, col);
267
- this.identifier = identifier;
268
- this.packageFile = packageFile;
269
- this.name = "PackageLookupError";
270
- }
271
- };
272
- var ConfigError = class extends Error {
273
- constructor(message, path2) {
274
- super(message);
275
- this.path = path2;
276
- this.name = "ConfigError";
277
- }
278
- };
279
- var NotResolvedError = class extends ConfigError {
280
- constructor(path2) {
281
- super(`value at path "${path2}" is not resolved (call resolve() first)`, path2);
282
- this.name = "NotResolvedError";
283
- }
284
- };
285
-
286
- // src/internal/resolver/fold-self-ref.ts
287
- function substFullKey(s) {
288
- return stringSegmentsToKey(s.segments.map((seg) => seg.text));
289
- }
290
- function stringSegmentsToKey(segments) {
291
- return segments.map((t) => {
292
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
293
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
294
- }
295
- return t;
296
- }).join(".");
297
- }
298
- function prefixSelfRefRemainder(s, fullKey) {
299
- const texts = s.segments.map((seg) => seg.text);
300
- if (!stringSegmentsToKey(texts).startsWith(fullKey + ".")) return null;
301
- for (let n = 1; n < texts.length; n++) {
302
- if (stringSegmentsToKey(texts.slice(0, n)) === fullKey) return texts.slice(n);
303
- }
304
- return null;
305
- }
306
- function navigateResolverValue(v, remainder) {
307
- let cur = v;
308
- for (const seg of remainder) {
309
- if (isSubst(cur) || isConcat(cur)) return null;
310
- if (isResObj(cur)) {
311
- const next = cur.fields.get(seg);
312
- if (next === void 0) return void 0;
313
- cur = next;
314
- continue;
315
- }
316
- const hv = cur;
317
- if (hv.kind === "object") {
318
- const next = hv.fields.get(seg);
319
- if (next === void 0) return void 0;
320
- cur = next;
321
- continue;
322
- }
323
- return void 0;
324
- }
325
- return cur;
326
- }
327
- function foldPrefixSelfRef(s, replacement, remainder) {
328
- const navigated = navigateResolverValue(replacement, remainder);
329
- if (navigated === null) return s;
330
- if (navigated === void 0) {
331
- return {
332
- _kind: "subst-placeholder",
333
- segments: s.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
334
- optional: s.optional,
335
- knownAbsent: true,
336
- listSuffix: s.listSuffix,
337
- line: s.line,
338
- col: s.col,
339
- prefixLen: s.prefixLen
340
- };
341
- }
342
- return cloneResolverValue(navigated);
343
- }
344
- function mergeResObjLayers(base, top) {
345
- const fields = new Map(base.fields);
346
- for (const [k, tv] of top.fields) {
347
- const bv = fields.get(k);
348
- if (bv !== void 0 && isResObj(bv) && isResObj(tv)) {
349
- fields.set(k, mergeResObjLayers(bv, tv));
350
- } else {
351
- fields.set(k, tv);
352
- }
353
- }
354
- const priorValues = new Map(base.priorValues);
355
- for (const [k, pv] of top.priorValues) priorValues.set(k, pv);
356
- const resetKeys = new Set(base.resetKeys);
357
- for (const k of top.resetKeys) resetKeys.add(k);
358
- return {
359
- _kind: "res-obj",
360
- fields,
361
- priorValues,
362
- resetKeys
363
- };
364
- }
365
- function containsSelfRef(v, fullKey) {
366
- return containsSelfRefInner(v, fullKey, true);
367
- }
368
- function containsSelfRefInner(v, fullKey, allowPrefix) {
369
- if (isSubst(v))
370
- return !v.knownAbsent && (substFullKey(v) === fullKey || allowPrefix && prefixSelfRefRemainder(v, fullKey) !== null);
371
- if (isConcat(v)) return v.nodes.some((n) => containsSelfRefInner(n, fullKey, allowPrefix));
372
- if (isResObj(v)) {
373
- for (const f of v.fields.values()) {
374
- if (containsSelfRefInner(f, fullKey, false)) return true;
375
- }
376
- return false;
377
- }
378
- const hv = v;
379
- if (hv.kind === "array") {
380
- return hv.items.some((item) => containsSelfRefInner(item, fullKey, allowPrefix));
381
- }
382
- if (hv.kind === "object") {
383
- for (const f of hv.fields.values()) {
384
- if (containsSelfRefInner(f, fullKey, false)) return true;
385
- }
386
- return false;
387
- }
388
- return false;
389
- }
390
- function foldSelfRef(v, fullKey, replacement) {
391
- return foldSelfRefInner(v, fullKey, replacement, true);
392
- }
393
- function foldSelfRefInner(v, fullKey, replacement, allowPrefix) {
394
- if (isSubst(v)) {
395
- if (substFullKey(v) === fullKey) return replacement;
396
- if (allowPrefix) {
397
- const remainder = prefixSelfRefRemainder(v, fullKey);
398
- if (remainder !== null) return foldPrefixSelfRef(v, replacement, remainder);
399
- }
400
- return v;
401
- }
402
- if (isConcat(v)) {
403
- return {
404
- _kind: "concat-placeholder",
405
- nodes: v.nodes.map((n) => foldSelfRefInner(n, fullKey, replacement, allowPrefix)),
406
- line: v.line,
407
- col: v.col
408
- };
409
- }
410
- if (isResObj(v)) {
411
- const newFields = /* @__PURE__ */ new Map();
412
- for (const [k, val] of v.fields) {
413
- newFields.set(k, foldSelfRefInner(val, fullKey, replacement, false));
414
- }
415
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
416
- }
417
- const hv = v;
418
- if (hv.kind === "array") {
419
- return {
420
- kind: "array",
421
- items: hv.items.map(
422
- (item) => foldSelfRefInner(item, fullKey, replacement, allowPrefix)
423
- )
424
- };
425
- }
426
- if (hv.kind === "object") {
427
- const newFields = /* @__PURE__ */ new Map();
428
- for (const [k, val] of hv.fields) {
429
- newFields.set(k, foldSelfRefInner(val, fullKey, replacement, false));
430
- }
431
- return { kind: "object", fields: newFields };
432
- }
433
- return v;
434
- }
435
- function foldKnownAbsentSelfRef(v, fullKey, replacement) {
436
- if (isSubst(v)) {
437
- return v.knownAbsent && substFullKey(v) === fullKey ? replacement : v;
438
- }
439
- if (isConcat(v)) {
440
- return {
441
- _kind: "concat-placeholder",
442
- nodes: v.nodes.map((n) => foldKnownAbsentSelfRef(n, fullKey, replacement)),
443
- line: v.line,
444
- col: v.col
445
- };
446
- }
447
- if (isResObj(v)) {
448
- const newFields = /* @__PURE__ */ new Map();
449
- for (const [k, val] of v.fields) {
450
- newFields.set(k, foldKnownAbsentSelfRef(val, fullKey, replacement));
451
- }
452
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
453
- }
454
- const hv = v;
455
- if (hv.kind === "array") {
456
- return {
457
- kind: "array",
458
- items: hv.items.map((item) => foldKnownAbsentSelfRef(item, fullKey, replacement))
459
- };
460
- }
461
- if (hv.kind === "object") {
462
- const newFields = /* @__PURE__ */ new Map();
463
- for (const [k, val] of hv.fields) {
464
- newFields.set(k, foldKnownAbsentSelfRef(val, fullKey, replacement));
465
- }
466
- return { kind: "object", fields: newFields };
467
- }
468
- return v;
469
- }
470
- function foldOrSkipPrior(prior, fullKey, old) {
471
- if (!containsSelfRef(prior, fullKey)) return cloneResolverValue(prior);
472
- if (old === void 0) return foldOptionalSelfRefAbsent(prior, fullKey);
473
- if (isSubst(prior)) {
474
- const remainder = prefixSelfRefRemainder(prior, fullKey);
475
- if (remainder !== null) {
476
- const navigated = navigateResolverValue(old, remainder);
477
- if (navigated === void 0 && prior.optional) return cloneResolverValue(old);
478
- if (navigated !== null && navigated !== void 0 && isResObj(navigated) && isResObj(old)) {
479
- return mergeResObjLayers(
480
- cloneResolverValue(old),
481
- cloneResolverValue(navigated)
482
- );
483
- }
484
- }
485
- }
486
- return foldSelfRef(prior, fullKey, old);
487
- }
488
- function foldOptionalSelfRefAbsent(v, fullKey) {
489
- return foldOptionalSelfRefAbsentInner(v, fullKey, true);
490
- }
491
- function foldOptionalSelfRefAbsentInner(v, fullKey, allowPrefix) {
492
- if (isSubst(v) && (substFullKey(v) === fullKey || allowPrefix && prefixSelfRefRemainder(v, fullKey) !== null)) {
493
- if (!v.optional) return void 0;
494
- return {
495
- _kind: "subst-placeholder",
496
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
497
- optional: v.optional,
498
- knownAbsent: true,
499
- listSuffix: v.listSuffix,
500
- line: v.line,
501
- col: v.col,
502
- prefixLen: v.prefixLen
503
- };
504
- }
505
- if (isConcat(v)) {
506
- const nodes = [];
507
- for (const node of v.nodes) {
508
- const folded = foldOptionalSelfRefAbsentInner(node, fullKey, allowPrefix);
509
- if (folded === void 0) return void 0;
510
- nodes.push(folded);
511
- }
512
- return { _kind: "concat-placeholder", nodes, line: v.line, col: v.col };
513
- }
514
- if (isResObj(v)) {
515
- const fields = /* @__PURE__ */ new Map();
516
- for (const [key, value] of v.fields) {
517
- const folded = foldOptionalSelfRefAbsentInner(value, fullKey, false);
518
- if (folded === void 0) return void 0;
519
- fields.set(key, folded);
520
- }
521
- return { _kind: "res-obj", fields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
522
- }
523
- const hv = v;
524
- if (hv.kind === "array") {
525
- const items = [];
526
- for (const item of hv.items) {
527
- const folded = foldOptionalSelfRefAbsentInner(item, fullKey, allowPrefix);
528
- if (folded === void 0) return void 0;
529
- items.push(folded);
530
- }
531
- return { kind: "array", items };
532
- }
533
- if (hv.kind === "object") {
534
- const fields = /* @__PURE__ */ new Map();
535
- for (const [key, value] of hv.fields) {
536
- const folded = foldOptionalSelfRefAbsentInner(value, fullKey, false);
537
- if (folded === void 0) return void 0;
538
- fields.set(key, folded);
539
- }
540
- return { kind: "object", fields };
541
- }
542
- return cloneResolverValue(v);
543
- }
544
- function cloneResolverValue(v) {
545
- if (isSubst(v)) {
546
- return {
547
- _kind: "subst-placeholder",
548
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
549
- optional: v.optional,
550
- knownAbsent: v.knownAbsent,
551
- listSuffix: v.listSuffix,
552
- line: v.line,
553
- col: v.col,
554
- prefixLen: v.prefixLen
555
- };
556
- }
557
- if (isConcat(v)) {
558
- return {
559
- _kind: "concat-placeholder",
560
- nodes: v.nodes.map((n) => cloneResolverValue(n)),
561
- line: v.line,
562
- col: v.col
563
- };
564
- }
565
- if (isResObj(v)) {
566
- const newFields = /* @__PURE__ */ new Map();
567
- for (const [k, val] of v.fields) newFields.set(k, cloneResolverValue(val));
568
- const newPriors = /* @__PURE__ */ new Map();
569
- for (const [k, val] of v.priorValues) newPriors.set(k, cloneResolverValue(val));
570
- return { _kind: "res-obj", fields: newFields, priorValues: newPriors, resetKeys: new Set(v.resetKeys) };
571
- }
572
- const hv = v;
573
- if (hv.kind === "array") {
574
- return {
575
- kind: "array",
576
- items: hv.items.map((item) => cloneResolverValue(item))
577
- };
578
- }
579
- if (hv.kind === "object") {
580
- const newFields = /* @__PURE__ */ new Map();
581
- for (const [k, val] of hv.fields) {
582
- newFields.set(k, cloneResolverValue(val));
583
- }
584
- return { kind: "object", fields: newFields };
585
- }
586
- return hv;
587
- }
588
- function foldNestedSelfRefs(v, pathPrefix) {
589
- if (!isResObj(v)) return v;
590
- const newFields = /* @__PURE__ */ new Map();
591
- for (const [k, fieldVal] of v.fields) {
592
- const childPath = [...pathPrefix, k];
593
- const fullKey = stringSegmentsToKey(childPath);
594
- const folded = foldNestedSelfRefs(fieldVal, childPath);
595
- let finalVal = folded;
596
- if (containsSelfRef(folded, fullKey)) {
597
- const leafPrior = v.priorValues.get(k);
598
- if (leafPrior !== void 0) {
599
- const leafPriorFolded = foldNestedSelfRefs(leafPrior, childPath);
600
- finalVal = foldSelfRef(folded, fullKey, leafPriorFolded);
601
- }
602
- }
603
- newFields.set(k, finalVal);
604
- }
605
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
606
- }
607
- function containsSubstByPath(v, target) {
608
- if (isSubst(v)) return !v.knownAbsent && segmentsTextEqual(v.segments, target);
609
- if (isConcat(v)) return v.nodes.some((n) => containsSubstByPath(n, target));
610
- if (isResObj(v)) {
611
- for (const f of v.fields.values()) {
612
- if (containsSubstByPath(f, target)) return true;
613
- }
614
- return false;
615
- }
616
- const hv = v;
617
- if (hv.kind === "array") {
618
- return hv.items.some((item) => containsSubstByPath(item, target));
619
- }
620
- if (hv.kind === "object") {
621
- for (const f of hv.fields.values()) {
622
- if (containsSubstByPath(f, target)) return true;
623
- }
624
- return false;
625
- }
626
- return false;
627
- }
628
- function segmentsTextEqual(a, b) {
629
- if (a.length !== b.length) return false;
630
- for (let i = 0; i < a.length; i++) {
631
- const ai = a[i];
632
- const bi = b[i];
633
- if (ai === void 0 || bi === void 0 || ai.text !== bi.text) return false;
634
- }
635
- return true;
636
- }
637
-
638
- // src/internal/resolver/types.ts
639
- var separatorValues = /* @__PURE__ */ new WeakSet();
640
- function isSubst(v) {
641
- return v._kind === "subst-placeholder";
642
- }
643
- function isConcat(v) {
644
- return v._kind === "concat-placeholder";
645
- }
646
- function isResObj(v) {
647
- return v._kind === "res-obj";
648
- }
649
- function makeResObj() {
650
- return { _kind: "res-obj", fields: /* @__PURE__ */ new Map(), priorValues: /* @__PURE__ */ new Map(), resetKeys: /* @__PURE__ */ new Set() };
651
- }
652
- function mergeUnresolved(receiver, fallback) {
653
- const result = makeResObj();
654
- for (const [k, v] of fallback.fields) {
655
- result.fields.set(k, v);
656
- }
657
- for (const [k, v] of fallback.priorValues) {
658
- result.priorValues.set(k, v);
659
- }
660
- for (const [k, rv] of receiver.fields) {
661
- const existing = result.fields.get(k);
662
- if (existing !== void 0) {
663
- const recPrior = receiver.priorValues.get(k);
664
- if (recPrior !== void 0 && !isResObj(recPrior)) {
665
- result.fields.set(k, rv);
666
- continue;
667
- }
668
- if (isResObj(rv) && isResObj(existing)) {
669
- result.fields.set(k, mergeUnresolved(rv, existing));
670
- continue;
671
- }
672
- const foldedPrior = foldOrSkipPrior(existing, k, void 0);
673
- if (foldedPrior !== void 0) result.priorValues.set(k, foldedPrior);
674
- }
675
- result.fields.set(k, rv);
676
- }
677
- for (const [k, v] of receiver.priorValues) {
678
- if (receiver.fields.has(k)) {
679
- result.priorValues.set(k, v);
680
- }
681
- }
682
- return result;
683
- }
684
-
685
- // src/internal/resolver/utils.ts
686
- function segmentsToKey(segments) {
687
- return segments.map((s) => {
688
- const t = s.text;
689
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
690
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
691
- }
692
- return t;
693
- }).join(".");
694
- }
695
- function lookupPath(root, segments) {
696
- const [head, ...tail] = segments;
697
- if (head === void 0) return void 0;
698
- const key = head.text;
699
- const val = root.fields.get(key);
700
- if (val === void 0) return void 0;
701
- if (tail.length === 0) return val;
702
- if (isResObj(val)) return lookupPath(val, tail);
703
- return void 0;
704
- }
705
- function lookupResObj(root, segments) {
706
- let cur = root;
707
- for (const seg of segments) {
708
- const val = cur.fields.get(seg.text);
709
- if (val === void 0 || !isResObj(val)) return void 0;
710
- cur = val;
711
- }
712
- return cur;
713
- }
714
- function deepMergeHoconValues(base, overlay) {
715
- const merged = new Map(base.fields);
716
- for (const [k, v] of overlay.fields) {
717
- const existing = merged.get(k);
718
- if (existing?.kind === "object" && v.kind === "object") {
719
- merged.set(k, deepMergeHoconValues(existing, v));
720
- } else {
721
- merged.set(k, v);
722
- }
723
- }
724
- return { kind: "object", fields: merged };
725
- }
726
- function deepMergeResObjInto(dst, src, pathPrefix = []) {
727
- for (const [k, srcVal] of src.fields) {
728
- const childPrefix = [...pathPrefix, k];
729
- const fullKey = stringSegmentsToKey(childPrefix);
730
- const dstVal = dst.fields.get(k);
731
- if (dstVal !== void 0 && isResObj(dstVal) && isResObj(srcVal)) {
732
- const priorExisting = dst.priorValues.get(k);
733
- const prior = foldOrSkipPrior(dstVal, fullKey, priorExisting);
734
- if (prior !== void 0) dst.priorValues.set(k, prior);
735
- deepMergeResObjInto(dstVal, srcVal, childPrefix);
736
- } else {
737
- if (dstVal !== void 0) {
738
- if (src.resetKeys.has(k)) {
739
- dst.priorValues.delete(k);
740
- } else {
741
- const dstFolded = foldOrSkipPrior(dstVal, fullKey, dst.priorValues.get(k));
742
- if (dstFolded !== void 0) {
743
- const srcPrior = src.priorValues.get(k);
744
- if (srcPrior !== void 0) {
745
- dst.priorValues.set(k, foldKnownAbsentSelfRef(srcPrior, fullKey, dstFolded));
746
- } else {
747
- dst.priorValues.set(k, dstFolded);
748
- }
749
- }
750
- }
751
- }
752
- dst.fields.set(k, srcVal);
753
- }
754
- }
755
- for (const [k, srcPrior] of src.priorValues) {
756
- if (!dst.priorValues.has(k)) {
757
- dst.priorValues.set(k, srcPrior);
758
- }
759
- }
760
- for (const k of src.resetKeys) dst.resetKeys.add(k);
761
- }
762
- function hoconValueToResObj(hv) {
763
- const obj = makeResObj();
764
- if (hv.kind !== "object") return obj;
765
- for (const [key, val] of hv.fields) {
766
- if (val.kind === "object") {
767
- obj.fields.set(key, hoconValueToResObj(val));
768
- } else {
769
- obj.fields.set(key, val);
770
- }
771
- }
772
- return obj;
773
- }
774
- function isFileNotFoundError(e) {
775
- if (!(e instanceof Error)) return false;
776
- const code = e.code;
777
- if (code === "ENOENT" || code === "MODULE_NOT_FOUND") return true;
778
- const msg = e.message.toLowerCase();
779
- return msg.includes("not found") || msg.includes("no such file") || msg.includes("enoent");
780
- }
781
-
782
- // src/internal/resolver/include-loader.ts
783
- import { createRequire } from "module";
784
- import * as nodePath from "path";
785
- import { pathToFileURL } from "url";
786
-
787
- // src/internal/lexer/lexer.ts
788
- function isHoconWhitespace(ch) {
789
- const cp = ch.codePointAt(0) ?? -1;
790
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
791
- if (cp >= 28 && cp <= 31) return true;
792
- if (cp === 32 || cp === 160 || cp === 65279) return true;
793
- if (cp === 5760) return true;
794
- if (cp >= 8192 && cp <= 8202) return true;
795
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
796
- if (cp === 12288) return true;
797
- return false;
798
- }
799
- function isHoconNewline(ch) {
800
- return ch === "\n";
801
- }
802
- var SINGLE_CHAR_TOKENS = {
803
- "{": "lbrace",
804
- "}": "rbrace",
805
- "[": "lbracket",
806
- "]": "rbracket",
807
- ",": "comma",
808
- ":": "colon"
809
- };
810
- var Lexer = class {
811
- constructor(input) {
812
- this.input = input;
813
- this.pos = 0;
814
- this.line = 1;
815
- this.col = 1;
816
- this.hadSpace = false;
817
- // Accumulates literal whitespace chars consumed between tokens. Reset on every
818
- // token push. Used so the parser can preserve path-expression whitespace
819
- // (xx.hocon#42, E13) — e.g. tab vs space adjacent to dots in key paths.
820
- // Comment text is NOT accumulated; only the actual WS chars.
821
- this.whitespaceBuffer = "";
822
- this.tokens = [];
823
- if (input.charCodeAt(0) === 65279) this.input = input.slice(1);
824
- }
825
- tokenize() {
826
- while (this.pos < this.input.length) {
827
- const sl = this.line, sc = this.col;
828
- const ch = this.peek();
829
- if (isHoconNewline(ch)) {
830
- this.advance();
831
- if (this.tokens[this.tokens.length - 1]?.kind !== "newline") {
832
- this.push("newline", "\n", sl, sc);
833
- }
834
- continue;
835
- }
836
- if (isHoconWhitespace(ch)) {
837
- this.whitespaceBuffer += ch;
838
- this.advance();
839
- this.hadSpace = true;
840
- continue;
841
- }
842
- if (ch === "/" && this.peek(1) === "/") {
843
- while (this.pos < this.input.length && this.peek() !== "\n") this.advance();
844
- this.hadSpace = true;
845
- continue;
846
- }
847
- if (ch === "#") {
848
- while (this.pos < this.input.length && this.peek() !== "\n") this.advance();
849
- this.hadSpace = true;
850
- continue;
851
- }
852
- if (ch in SINGLE_CHAR_TOKENS) {
853
- this.advance();
854
- this.push(SINGLE_CHAR_TOKENS[ch], ch, sl, sc);
855
- continue;
856
- }
857
- if (ch === "=") {
858
- this.advance();
859
- this.push("equals", "=", sl, sc);
860
- continue;
861
- }
862
- if (ch === "+" && this.peek(1) === "=") {
863
- this.advance();
864
- this.advance();
865
- this.push("plus_equals", "+=", sl, sc);
866
- continue;
867
- }
868
- if (ch === "$" && this.peek(1) === "{") {
869
- this.advance();
870
- this.advance();
871
- const payload = this.parseSubstBody(sl, sc);
872
- const value = payload.segments.map((s) => {
873
- const t = s.text;
874
- if (t === "" || t.includes(".") || t.includes(" ") || t.includes(" ") || t.includes('"') || t.includes("\\") || t !== t.trim()) {
875
- const escaped = t.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
876
- return `"${escaped}"`;
877
- }
878
- return t;
879
- }).join(".");
880
- this.pushSubst(payload, value, sl, sc);
881
- continue;
882
- }
883
- if (ch === '"' && this.peek(1) === '"' && this.peek(2) === '"') {
884
- this.advance();
885
- this.advance();
886
- this.advance();
887
- let value = "";
888
- let closed = false;
889
- while (this.pos < this.input.length) {
890
- if (this.peek() === '"') {
891
- let quoteCount = 0;
892
- while (this.pos < this.input.length && this.peek() === '"') {
893
- quoteCount++;
894
- this.advance();
895
- }
896
- if (quoteCount >= 3) {
897
- for (let i = 0; i < quoteCount - 3; i++) value += '"';
898
- closed = true;
899
- break;
900
- }
901
- for (let i = 0; i < quoteCount; i++) value += '"';
902
- continue;
903
- }
904
- value += this.advance();
905
- }
906
- if (!closed) {
907
- throw new ParseError("unterminated triple-quoted string", sl, sc);
908
- }
909
- this.push("triple_string", value, sl, sc, true);
910
- continue;
911
- }
912
- if (ch === '"') {
913
- this.advance();
914
- const value = this.readQuotedStringBody(sl, sc);
915
- this.push("string", value, sl, sc, true);
916
- continue;
917
- }
918
- if (isUnquotedStart(ch)) {
919
- let value = "";
920
- while (this.pos < this.input.length && isUnquotedContinue(this.peek(), () => this.peek(1))) {
921
- value += this.advance();
922
- }
923
- this.push("unquoted", value.trimEnd(), sl, sc);
924
- continue;
925
- }
926
- throw new ParseError(`unexpected character: ${JSON.stringify(ch)}`, sl, sc);
927
- }
928
- this.tokens.push({ kind: "eof", value: "", line: this.line, col: this.col, isQuoted: false, precedingSpace: false, precedingWhitespace: "" });
929
- return this.tokens;
930
- }
931
- peek(offset = 0) {
932
- return this.input[this.pos + offset] ?? "";
933
- }
934
- advance() {
935
- const ch = this.input[this.pos++] ?? "";
936
- if (ch === "\n") {
937
- this.line++;
938
- this.col = 1;
939
- } else {
940
- this.col++;
941
- }
942
- return ch;
943
- }
944
- push(kind, value, l, c, isQuoted = false) {
945
- this.tokens.push({ kind, value, line: l, col: c, isQuoted, precedingSpace: this.hadSpace, precedingWhitespace: this.whitespaceBuffer });
946
- this.hadSpace = false;
947
- this.whitespaceBuffer = "";
948
- }
949
- pushSubst(payload, value, l, c) {
950
- this.tokens.push({ kind: "subst", value, line: l, col: c, isQuoted: false, precedingSpace: this.hadSpace, precedingWhitespace: this.whitespaceBuffer, subst: payload });
951
- this.hadSpace = false;
952
- this.whitespaceBuffer = "";
953
- }
954
- /**
955
- * Read body of a quoted string. Opening `"` must already be consumed.
956
- * Returns decoded string. Throws ParseError on unterminated/invalid-escape.
957
- * openLine/openCol are the position of the opening `"` for error reporting.
958
- */
959
- readQuotedStringBody(openLine, openCol) {
960
- let value = "";
961
- while (this.pos < this.input.length && this.peek() !== '"') {
962
- if (this.peek() === "\n") throw new ParseError("unterminated string", openLine, openCol);
963
- if (this.peek() === "\\") {
964
- const escCol = this.col;
965
- this.advance();
966
- if (this.pos >= this.input.length) {
967
- throw new ParseError("unterminated string", openLine, openCol);
968
- }
969
- const esc = this.advance();
970
- switch (esc) {
971
- case "n":
972
- value += "\n";
973
- break;
974
- case "t":
975
- value += " ";
976
- break;
977
- case "r":
978
- value += "\r";
979
- break;
980
- case '"':
981
- value += '"';
982
- break;
983
- case "\\":
984
- value += "\\";
985
- break;
986
- case "/":
987
- value += "/";
988
- break;
989
- case "b":
990
- value += "\b";
991
- break;
992
- case "f":
993
- value += "\f";
994
- break;
995
- case "u": {
996
- if (this.pos + 4 > this.input.length) {
997
- throw new ParseError("invalid unicode escape", openLine, escCol);
998
- }
999
- const hex = this.input.slice(this.pos, this.pos + 4);
1000
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
1001
- throw new ParseError("invalid unicode escape", openLine, escCol);
1002
- }
1003
- const code = parseInt(hex, 16);
1004
- value += String.fromCharCode(code);
1005
- for (let i = 0; i < 4; i++) this.advance();
1006
- break;
1007
- }
1008
- default:
1009
- throw new ParseError(`unknown escape sequence: \\${esc}`, openLine, escCol);
1010
- }
1011
- } else {
1012
- value += this.advance();
1013
- }
1014
- }
1015
- if (this.pos >= this.input.length || this.peek() !== '"') {
1016
- throw new ParseError("unterminated string", openLine, openCol);
1017
- }
1018
- this.advance();
1019
- return value;
1020
- }
1021
- /**
1022
- * Parse the body of a `${...}` substitution (called after `${` has been consumed).
1023
- * Implements Appendix A state machine from the cross-language spec.
1024
- *
1025
- * S13c extension: if the segment-collection loop encounters `[`, it delegates to
1026
- * `parseListSuffix()` which consumes the literal `[]` and sets `listSuffix=true`.
1027
- * ASCII space/tab before `[` is buffered in `pendingWs` and discarded (E7).
1028
- */
1029
- parseSubstBody(startLine, startCol) {
1030
- let optional = false;
1031
- if (this.peek() === "?") {
1032
- this.advance();
1033
- optional = true;
1034
- }
1035
- let curText = "";
1036
- let curStarted = false;
1037
- let curLine = 0;
1038
- let curCol = 0;
1039
- let pendingWs = "";
1040
- const segments = [];
1041
- let lastDot = null;
1042
- let listSuffix = false;
1043
- while (true) {
1044
- if (this.pos >= this.input.length) {
1045
- throw new ParseError("unterminated substitution", startLine, startCol);
1046
- }
1047
- const ch = this.peek();
1048
- if (ch === "}") {
1049
- this.advance();
1050
- pendingWs = "";
1051
- break;
1052
- } else if (ch === "[") {
1053
- if (!curStarted) {
1054
- throw new ParseError("empty segment before '[]' suffix in substitution path", startLine, this.col);
1055
- }
1056
- for (const w of pendingWs) {
1057
- if (w !== " " && w !== " ") {
1058
- throw new ParseError(
1059
- `only ASCII space or tab allowed between substitution path and '[]' suffix (got ${JSON.stringify(w)}, HOCON extra-spec E7)`,
1060
- startLine,
1061
- this.col
1062
- );
1063
- }
1064
- }
1065
- segments.push({ text: curText, line: curLine, col: curCol });
1066
- pendingWs = "";
1067
- listSuffix = this.parseListSuffix(startLine);
1068
- break;
1069
- } else if (ch === '"') {
1070
- const qLine = startLine;
1071
- const qCol = this.col;
1072
- if (curStarted) {
1073
- curText += pendingWs;
1074
- }
1075
- pendingWs = "";
1076
- this.advance();
1077
- const decoded = this.readQuotedStringBody(qLine, qCol);
1078
- curText += decoded;
1079
- if (!curStarted) {
1080
- curLine = qLine;
1081
- curCol = qCol;
1082
- curStarted = true;
1083
- }
1084
- } else if (isUnquotedSubstChar(ch)) {
1085
- if (ch === "-" && !curStarted && !isDecimalDigit(this.peek(1))) {
1086
- const after = this.peek(1) === "" ? "EOF" : JSON.stringify(this.peek(1));
1087
- throw new ParseError(
1088
- `unquoted path segment cannot begin with '-' unless followed by a digit (got '-' then ${after}, HOCON.md L270-276)`,
1089
- startLine,
1090
- this.col
1091
- );
1092
- }
1093
- const uCol = this.col;
1094
- if (curStarted) {
1095
- curText += pendingWs;
1096
- }
1097
- pendingWs = "";
1098
- if (!curStarted) {
1099
- curLine = startLine;
1100
- curCol = uCol;
1101
- curStarted = true;
1102
- }
1103
- while (this.pos < this.input.length && isUnquotedSubstChar(this.peek())) {
1104
- curText += this.advance();
1105
- }
1106
- } else if (ch === ".") {
1107
- const dotCol = this.col;
1108
- pendingWs = "";
1109
- if (!curStarted) {
1110
- throw new ParseError("empty segment in path", startLine, dotCol);
1111
- }
1112
- segments.push({ text: curText, line: curLine, col: curCol });
1113
- curText = "";
1114
- curStarted = false;
1115
- curLine = 0;
1116
- curCol = 0;
1117
- lastDot = [startLine, dotCol];
1118
- this.advance();
1119
- } else if (isHoconNewline(ch)) {
1120
- throw new ParseError("unterminated substitution", startLine, startCol);
1121
- } else if (isHoconWhitespace(ch)) {
1122
- pendingWs += ch;
1123
- this.advance();
1124
- } else {
1125
- throw new ParseError(`unexpected character in substitution path: ${JSON.stringify(ch)}`, startLine, this.col);
1126
- }
1127
- }
1128
- if (!listSuffix) {
1129
- if (curStarted) {
1130
- segments.push({ text: curText, line: curLine, col: curCol });
1131
- } else if (segments.length === 0) {
1132
- throw new ParseError("empty substitution path", startLine, startCol);
1133
- } else {
1134
- const [errLine, errCol] = lastDot ?? [startLine, startCol];
1135
- throw new ParseError("empty segment in path", errLine, errCol);
1136
- }
1137
- }
1138
- return { segments, optional, listSuffix };
1139
- }
1140
- /**
1141
- * Consume the literal `[]` suffix inside a substitution body.
1142
- * Called after the `[` has been detected (but not yet consumed).
1143
- * Requires the next character to be `[`, then exactly `]`, then `}`.
1144
- * Whitespace inside `[]` is not permitted (per spec Decision §1).
1145
- * Returns true (always — only called when listSuffix path is taken).
1146
- */
1147
- parseListSuffix(startLine) {
1148
- this.advance();
1149
- const afterBracket = this.peek();
1150
- if (afterBracket !== "]") {
1151
- const desc = afterBracket === "" ? "EOF" : JSON.stringify(afterBracket);
1152
- throw new ParseError(
1153
- `expected ']' after '[' in substitution list suffix (got ${desc})`,
1154
- startLine,
1155
- this.col
1156
- );
1157
- }
1158
- this.advance();
1159
- if (this.peek() !== "}") {
1160
- const desc = this.peek() === "" ? "EOF" : JSON.stringify(this.peek());
1161
- throw new ParseError(
1162
- `expected '}' after '[]' in substitution list suffix (got ${desc})`,
1163
- startLine,
1164
- this.col
1165
- );
1166
- }
1167
- this.advance();
1168
- return true;
1169
- }
1170
- };
1171
- function tokenize(input) {
1172
- return new Lexer(input).tokenize();
1173
- }
1174
- function isUnquotedSubstChar(ch) {
1175
- if (ch === "" || isHoconWhitespace(ch)) return false;
1176
- if ('"\\'.includes(ch)) return false;
1177
- if ("{}[]".includes(ch)) return false;
1178
- if (":=,+#`^?!@*&$.".includes(ch)) return false;
1179
- return true;
1180
- }
1181
- function isDecimalDigit(ch) {
1182
- return ch >= "0" && ch <= "9";
1183
- }
1184
- function isUnquotedStart(ch) {
1185
- if (ch === "" || isHoconWhitespace(ch)) return false;
1186
- if ('{}[],:=+#"$?!@*&^`\\'.includes(ch)) return false;
1187
- return true;
1188
- }
1189
- function isUnquotedContinue(ch, nextFn) {
1190
- if (ch === "" || isHoconWhitespace(ch)) return false;
1191
- if ('{}[],:=#"$?!@*&^`\\'.includes(ch)) return false;
1192
- if (ch === "+" && nextFn() === "=") return false;
1193
- if (ch === "/" && nextFn() === "/") return false;
1194
- return true;
1195
- }
1196
-
1197
- // src/internal/parser/parser.ts
1198
- var EOF_TOKEN = { kind: "eof", value: "", line: 0, col: 0, isQuoted: false, precedingSpace: false, precedingWhitespace: "", subst: void 0 };
1199
- var Parser = class {
1200
- constructor(tokens) {
1201
- this.tokens = tokens;
1202
- this.pos = 0;
1203
- }
1204
- parse() {
1205
- this.skip("newline");
1206
- const t = this.peek();
1207
- if (t.kind === "lbrace") {
1208
- this.advance();
1209
- const first = this.parseObject(true);
1210
- const allFields = first.kind === "object" ? [...first.fields] : [];
1211
- while (true) {
1212
- this.skip("newline");
1213
- if (this.peek().kind === "eof") break;
1214
- if (this.peek().kind === "lbrace") {
1215
- this.advance();
1216
- const extra = this.parseObject(true);
1217
- if (extra.kind === "object") allFields.push(...extra.fields);
1218
- } else {
1219
- const rest = this.parseObject(false);
1220
- if (rest.kind === "object") allFields.push(...rest.fields);
1221
- break;
1222
- }
1223
- }
1224
- this.skip("newline");
1225
- const remaining2 = this.peek();
1226
- if (remaining2.kind !== "eof") {
1227
- throw new ParseError(`Unexpected token '${remaining2.value}' after closing brace`, remaining2.line, remaining2.col);
1228
- }
1229
- return { kind: "object", fields: allFields, pos: first.pos };
1230
- }
1231
- if (t.kind === "lbracket") {
1232
- this.advance();
1233
- const arr = this.parseArray();
1234
- this.skip("newline");
1235
- const remaining2 = this.peek();
1236
- if (remaining2.kind !== "eof") {
1237
- throw new ParseError(`Unexpected token '${remaining2.value}' after root array`, remaining2.line, remaining2.col);
1238
- }
1239
- return { ...arr, pos: { line: t.line, col: t.col } };
1240
- }
1241
- const root = this.parseObject(false);
1242
- this.skip("newline");
1243
- const remaining = this.peek();
1244
- if (remaining.kind !== "eof") {
1245
- throw new ParseError(`Unexpected token '${remaining.value}' after root content`, remaining.line, remaining.col);
1246
- }
1247
- return root;
1248
- }
1249
- peek(offset = 0) {
1250
- return this.tokens[this.pos + offset] ?? EOF_TOKEN;
1251
- }
1252
- advance() {
1253
- const t = this.tokens[this.pos];
1254
- if (this.pos < this.tokens.length) this.pos++;
1255
- return t ?? EOF_TOKEN;
1256
- }
1257
- skip(...kinds) {
1258
- while (kinds.includes(this.peek().kind)) this.advance();
1259
- }
1260
- currentPos() {
1261
- const t = this.peek();
1262
- return { line: t.line, col: t.col };
1263
- }
1264
- parseObject(expectClosingBrace) {
1265
- const p = this.currentPos();
1266
- const fields = [];
1267
- while (true) {
1268
- this.skip("newline");
1269
- const t = this.peek();
1270
- if (t.kind === "eof" || t.kind === "rbrace") break;
1271
- if (t.kind === "unquoted" && t.value === "include") {
1272
- const next = this.peek(1);
1273
- if (next.kind === "equals" || next.kind === "colon" || next.kind === "plus_equals" || next.kind === "lbrace") {
1274
- throw new ParseError(
1275
- `'include' is reserved at the start of a key path expression; use "include" (quoted) to use it as a key`,
1276
- t.line,
1277
- t.col
1278
- );
1279
- }
1280
- this.advance();
1281
- fields.push(this.parseInclude());
1282
- this.skip("newline");
1283
- if (this.peek().kind === "comma") this.advance();
1284
- this.skip("newline");
1285
- continue;
1286
- }
1287
- const keyPos = this.currentPos();
1288
- const { segments: key, firstWasQuoted } = this.parseKey();
1289
- if (key[0] === "include" && !firstWasQuoted) {
1290
- throw new ParseError(
1291
- `'include' is reserved at the start of a key path expression; use "include".foo (quoted) or rename the key`,
1292
- keyPos.line,
1293
- keyPos.col
1294
- );
1295
- }
1296
- this.skip("newline");
1297
- let append = false;
1298
- const sep = this.peek();
1299
- if (sep.kind === "equals") this.advance();
1300
- else if (sep.kind === "plus_equals") {
1301
- this.advance();
1302
- append = true;
1303
- } else if (sep.kind === "colon") this.advance();
1304
- else if (sep.kind === "lbrace") {
1305
- } else if (sep.kind !== "newline" && sep.kind !== "eof") {
1306
- throw new ParseError(`unexpected token after key: ${sep.kind}`, sep.line, sep.col);
1307
- }
1308
- this.skip("newline");
1309
- const value = this.parseValue();
1310
- fields.push({ key, value, append, pos: keyPos });
1311
- this.skip("newline");
1312
- if (this.peek().kind === "comma") this.advance();
1313
- this.skip("newline");
1314
- }
1315
- if (expectClosingBrace) {
1316
- const t = this.peek();
1317
- if (t.kind !== "rbrace") throw new ParseError("expected }", t.line, t.col);
1318
- this.advance();
1319
- }
1320
- return { kind: "object", fields, pos: p };
1321
- }
1322
- parseKey() {
1323
- const segments = [];
1324
- let trailingDot = false;
1325
- let firstWasQuoted = false;
1326
- let spaceConcat = false;
1327
- let postDotPrefix = "";
1328
- while (true) {
1329
- const t = this.peek();
1330
- if (t.kind === "string") {
1331
- this.advance();
1332
- if (segments.length === 0) firstWasQuoted = true;
1333
- if (spaceConcat) {
1334
- segments[segments.length - 1] = `${segments[segments.length - 1]}${t.precedingWhitespace}${t.value}`;
1335
- } else if (postDotPrefix !== "") {
1336
- segments.push(`${postDotPrefix}${t.value}`);
1337
- postDotPrefix = "";
1338
- } else {
1339
- segments.push(t.value);
1340
- }
1341
- trailingDot = false;
1342
- } else if (t.kind === "unquoted") {
1343
- this.advance();
1344
- const raw = t.value.startsWith(".") && segments.length > 0 && !t.precedingSpace ? t.value.slice(1) : t.value;
1345
- const parts = raw.split(".");
1346
- const leadingDotIsSeparator = spaceConcat || postDotPrefix !== "";
1347
- for (let i = 0; i < parts.length; i++) {
1348
- if (parts[i] !== "") continue;
1349
- if (i === parts.length - 1) continue;
1350
- if (i === 0 && leadingDotIsSeparator) continue;
1351
- throw new ParseError(
1352
- `path has ${i === 0 ? "a leading period '.'" : "two adjacent periods '.'"} \u2014 empty key segment not allowed, use quoted "" (HOCON.md path rules)`,
1353
- t.line,
1354
- t.col
1355
- );
1356
- }
1357
- const filtered = parts.filter((s) => s.length > 0);
1358
- if (spaceConcat) {
1359
- segments[segments.length - 1] = `${segments[segments.length - 1]}${t.precedingWhitespace}`;
1360
- if (raw.startsWith(".")) {
1361
- segments.push(...filtered);
1362
- } else if (filtered.length > 0) {
1363
- const [head, ...tail] = filtered;
1364
- segments[segments.length - 1] = `${segments[segments.length - 1]}${head}`;
1365
- segments.push(...tail);
1366
- }
1367
- } else if (postDotPrefix !== "" && raw.startsWith(".")) {
1368
- segments.push(postDotPrefix);
1369
- postDotPrefix = "";
1370
- segments.push(...filtered);
1371
- } else if (postDotPrefix !== "" && filtered.length > 0) {
1372
- const [head, ...tail] = filtered;
1373
- segments.push(`${postDotPrefix}${head}`, ...tail);
1374
- postDotPrefix = "";
1375
- } else {
1376
- segments.push(...filtered);
1377
- }
1378
- trailingDot = raw.endsWith(".");
1379
- } else {
1380
- if (segments.length === 0) throw new ParseError(`expected key, got ${t.kind}`, t.line, t.col);
1381
- break;
1382
- }
1383
- spaceConcat = false;
1384
- if (trailingDot) {
1385
- const next2 = this.peek();
1386
- if ((next2.kind === "unquoted" || next2.kind === "string") && next2.precedingWhitespace.length > 0) {
1387
- postDotPrefix = next2.precedingWhitespace;
1388
- } else {
1389
- postDotPrefix = "";
1390
- }
1391
- continue;
1392
- }
1393
- const next = this.peek();
1394
- if (next.kind === "unquoted" && next.value === "." && !next.precedingSpace) {
1395
- this.advance();
1396
- trailingDot = true;
1397
- const afterDot = this.peek();
1398
- if ((afterDot.kind === "unquoted" || afterDot.kind === "string") && afterDot.precedingWhitespace.length > 0) {
1399
- postDotPrefix = afterDot.precedingWhitespace;
1400
- }
1401
- continue;
1402
- }
1403
- if (next.kind === "unquoted" && next.value.startsWith(".") && !next.precedingSpace) {
1404
- trailingDot = true;
1405
- continue;
1406
- }
1407
- if ((next.kind === "unquoted" || next.kind === "string") && next.precedingSpace) {
1408
- spaceConcat = true;
1409
- continue;
1410
- }
1411
- break;
1412
- }
1413
- if (trailingDot) {
1414
- const here = this.peek();
1415
- throw new ParseError(
1416
- `path has a trailing period '.' \u2014 empty key segment not allowed (HOCON.md path rules)`,
1417
- here.line,
1418
- here.col
1419
- );
1420
- }
1421
- return { segments, firstWasQuoted };
1422
- }
1423
- parseInclude() {
1424
- const p = this.currentPos();
1425
- this.skip("newline");
1426
- const t = this.peek();
1427
- if (t.kind === "unquoted" && (t.value === "required(" || t.value === "required" || t.value.startsWith("required("))) {
1428
- if (t.value === "required") {
1429
- const next = this.peek(1);
1430
- if (next.kind !== "unquoted" || !next.value.startsWith("(")) {
1431
- throw new ParseError("include required must be followed by (", t.line, t.col);
1432
- }
1433
- }
1434
- this.advance();
1435
- const innerPrefix = t.value.startsWith("required(") ? t.value.slice("required(".length) : "";
1436
- if (innerPrefix === "url" || innerPrefix.startsWith("url(") || innerPrefix === "classpath" || innerPrefix.startsWith("classpath(")) {
1437
- throw new ParseError("include url(...) and classpath(...) are not supported", t.line, t.col);
1438
- }
1439
- const nextTok = this.peek();
1440
- if (innerPrefix === "package" || innerPrefix.startsWith("package(") || innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "package(" || nextTok.value.startsWith("package("))) {
1441
- const consumePackageToken = innerPrefix === "";
1442
- const { qualifier, path: path3 } = this.parsePackageArgs(consumePackageToken);
1443
- return this.makeIncludeField(qualifier, path3, true, p);
1444
- }
1445
- if (innerPrefix === "file" || innerPrefix.startsWith("file(") || innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "file(" || nextTok.value === "file")) {
1446
- if (innerPrefix === "") {
1447
- this.advance();
1448
- }
1449
- const path3 = this.parseQuotedPathSkipWrapper(t);
1450
- return this.makeIncludeField({ kind: "file" }, path3, true, p);
1451
- }
1452
- if (innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "url" || nextTok.value.startsWith("url(") || nextTok.value === "classpath" || nextTok.value.startsWith("classpath("))) {
1453
- throw new ParseError("include url(...) and classpath(...) are not supported", nextTok.line, nextTok.col);
1454
- }
1455
- if (innerPrefix !== "") {
1456
- if (innerPrefix === ")") {
1457
- throw new ParseError("include required(...) must contain a path", t.line, t.col);
1458
- }
1459
- const name = innerPrefix.replace(/\(.*$/, "").replace(/\).*$/, "");
1460
- throw new ParseError(`unknown include qualifier inside required(): "${name}"`, t.line, t.col);
1461
- }
1462
- const path2 = this.parseQuotedPathSkipWrapper(t);
1463
- return this.makeIncludeField({ kind: "bare" }, path2, true, p);
1464
- }
1465
- if (t.kind === "string") {
1466
- const path2 = this.advance().value;
1467
- return this.makeIncludeField({ kind: "bare" }, path2, false, p);
1468
- }
1469
- if (t.kind === "unquoted" && (t.value === "file(" || t.value === "file")) {
1470
- this.advance();
1471
- const path2 = this.parseQuotedPathSkipWrapper(t);
1472
- return this.makeIncludeField({ kind: "file" }, path2, false, p);
1473
- }
1474
- if (t.kind === "unquoted" && (t.value === "package(" || t.value.startsWith("package("))) {
1475
- const { qualifier, path: path2 } = this.parsePackageArgs();
1476
- return this.makeIncludeField(qualifier, path2, false, p);
1477
- }
1478
- if (t.kind === "unquoted" && (t.value === "url" || t.value.startsWith("url("))) {
1479
- throw new ParseError("include url(...) is not supported", t.line, t.col);
1480
- }
1481
- if (t.kind === "unquoted" && (t.value === "classpath" || t.value.startsWith("classpath("))) {
1482
- throw new ParseError("include classpath(...) is not supported", t.line, t.col);
1483
- }
1484
- throw new ParseError(`expected include path, got ${t.kind}`, t.line, t.col);
1485
- }
1486
- makeIncludeField(qualifier, path2, required, pos) {
1487
- return { key: [], value: { kind: "include", qualifier, path: path2, required, pos }, append: false, pos };
1488
- }
1489
- /**
1490
- * Skip past include-syntax wrapper tokens to find the quoted path string.
1491
- * Strict: only allows `(`, `)`, and bare qualifier keywords (file / file( /
1492
- * package / package( / url / url( / classpath / classpath() between the
1493
- * directive and the quoted path. Anything else is a parse error rather than
1494
- * silently swallowed (see ts#113).
1495
- */
1496
- parseQuotedPathSkipWrapper(errTok) {
1497
- while (this.isIncludeWrapperToken(this.peek())) this.advance();
1498
- if (this.peek().kind !== "string") {
1499
- const tok = this.peek();
1500
- if (tok.kind === "eof") throw new ParseError("expected include path", errTok.line, errTok.col);
1501
- const desc = tok.kind === "unquoted" ? `unquoted "${tok.value}"` : tok.kind;
1502
- throw new ParseError(`expected quoted include path, got ${desc}`, tok.line, tok.col);
1503
- }
1504
- const path2 = this.advance().value;
1505
- while (this.peek().kind === "unquoted" && (this.peek().value === ")" || this.peek().value === "))")) {
1506
- this.advance();
1507
- }
1508
- const after = this.peek();
1509
- if (after.kind !== "newline" && after.kind !== "rbrace" && after.kind !== "eof" && after.kind !== "comma") {
1510
- const desc = after.kind === "unquoted" ? `unquoted "${after.value}"` : after.kind;
1511
- throw new ParseError(`unexpected token after include path: ${desc}`, after.line, after.col);
1512
- }
1513
- return path2;
1514
- }
1515
- isIncludeWrapperToken(tok) {
1516
- return tok.kind === "unquoted" && tok.value === "(";
1517
- }
1518
- /**
1519
- * Parse the body of `package("identifier", "file")`.
1520
- *
1521
- * @param consumePackageToken - When true (default), the current token is `package(` and
1522
- * must be consumed first. When false, the lexer already bundled `package(` into the
1523
- * preceding token (e.g. `required(package("`), so we are already positioned at the
1524
- * first string argument.
1525
- */
1526
- parsePackageArgs(consumePackageToken = true) {
1527
- const pkgTok = consumePackageToken ? this.advance() : this.peek();
1528
- this.skip("newline");
1529
- const idTok = this.peek();
1530
- if (idTok.kind !== "string") {
1531
- throw new ParseError("include package: expected quoted identifier as first argument", pkgTok.line, pkgTok.col);
1532
- }
1533
- const identifier = this.advance().value;
1534
- this.skip("newline");
1535
- if (this.peek().kind !== "comma") {
1536
- const after = this.peek();
1537
- throw new ParseError(
1538
- after.kind === "string" ? "include package: missing comma between identifier and file arguments" : "include package: requires exactly two arguments (identifier, file) \u2014 one-arg form is not supported",
1539
- pkgTok.line,
1540
- pkgTok.col
1541
- );
1542
- }
1543
- this.advance();
1544
- this.skip("newline");
1545
- const fileTok = this.peek();
1546
- if (fileTok.kind !== "string") {
1547
- throw new ParseError(
1548
- "include package: requires exactly two arguments (identifier, file) \u2014 one-arg form is not supported",
1549
- pkgTok.line,
1550
- pkgTok.col
1551
- );
1552
- }
1553
- const filePath = this.advance().value;
1554
- while (this.peek().kind !== "newline" && this.peek().kind !== "rbrace" && this.peek().kind !== "eof" && this.peek().kind !== "comma") {
1555
- this.advance();
1556
- }
1557
- return { qualifier: { kind: "package", identifier }, path: filePath };
1558
- }
1559
- parseValue() {
1560
- const p = this.currentPos();
1561
- const parts = [];
1562
- while (true) {
1563
- const t = this.peek();
1564
- if (t.kind === "eof" || t.kind === "newline" || t.kind === "rbrace" || t.kind === "rbracket" || t.kind === "comma") break;
1565
- const hadSpace = t.precedingSpace && parts.length > 0;
1566
- let node;
1567
- if (t.kind === "lbrace") {
1568
- this.advance();
1569
- node = this.parseObject(true);
1570
- } else if (t.kind === "lbracket") {
1571
- this.advance();
1572
- node = this.parseArray();
1573
- } else if (t.kind === "subst") {
1574
- this.advance();
1575
- if (!t.subst) {
1576
- throw new ParseError(`internal: subst token missing payload`, t.line, t.col);
1577
- }
1578
- const payload = t.subst;
1579
- node = { kind: "subst", segments: payload.segments, optional: payload.optional, listSuffix: payload.listSuffix, pos: { line: t.line, col: t.col } };
1580
- } else if (t.kind === "string" || t.kind === "triple_string") {
1581
- this.advance();
1582
- node = { kind: "scalar", raw: t.value, valueType: "string", pos: { line: t.line, col: t.col } };
1583
- } else if (t.kind === "unquoted") {
1584
- this.advance();
1585
- node = { kind: "scalar", raw: t.value, valueType: this.scalarValueType(t.value), pos: { line: t.line, col: t.col } };
1586
- } else if ((t.kind === "colon" || t.kind === "equals") && parts.length > 0) {
1587
- this.advance();
1588
- node = { kind: "scalar", raw: t.value, valueType: "string", pos: { line: t.line, col: t.col } };
1589
- } else {
1590
- break;
1591
- }
1592
- if (hadSpace) {
1593
- const sep = t.precedingWhitespace.length > 0 ? t.precedingWhitespace : " ";
1594
- parts.push({ kind: "scalar", raw: sep, valueType: "string", pos: { line: t.line, col: t.col }, _separator: true });
1595
- }
1596
- parts.push(node);
1597
- }
1598
- if (parts.length === 0) throw new ParseError("expected value", this.peek().line, this.peek().col);
1599
- if (parts.length === 1) {
1600
- return parts[0];
1601
- }
1602
- return { kind: "concat", nodes: parts, pos: p };
1603
- }
1604
- parseArray() {
1605
- const p = this.currentPos();
1606
- const items = [];
1607
- while (true) {
1608
- this.skip("newline");
1609
- if (this.peek().kind === "rbracket" || this.peek().kind === "eof") break;
1610
- items.push(this.parseValue());
1611
- this.skip("newline");
1612
- if (this.peek().kind === "comma") this.advance();
1613
- this.skip("newline");
1614
- }
1615
- const t = this.peek();
1616
- if (t.kind !== "rbracket") throw new ParseError("expected ]", t.line, t.col);
1617
- this.advance();
1618
- return { kind: "array", items, pos: p };
1619
- }
1620
- scalarValueType(raw) {
1621
- if (raw === "true" || raw === "false") return "boolean";
1622
- if (raw === "null") return "null";
1623
- if (raw.length > 0 && (raw.charCodeAt(0) >= 48 && raw.charCodeAt(0) <= 57 || raw.charCodeAt(0) === 45)) {
1624
- if (DECIMAL_NUMBER_RE.test(raw)) return "number";
1625
- }
1626
- return "string";
1627
- }
1628
- };
1629
- function parseTokens(tokens) {
1630
- return new Parser(tokens).parse();
1631
- }
1632
-
1633
- // src/internal/strip-bom.ts
1634
- function stripBom(input) {
1635
- return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
1636
- }
1637
-
1638
- // src/internal/depth.ts
1639
- var MAX_PATH_SEGMENTS = 64;
1640
- function tooDeep(segments) {
1641
- return segments > MAX_PATH_SEGMENTS;
1642
- }
1643
- function guardStackDepth(fn, wrap) {
1644
- try {
1645
- return fn();
1646
- } catch (e) {
1647
- if (!isStackOverflow(e)) throw e;
1648
- throw wrap(STACK_MESSAGE);
1649
- }
1650
- }
1651
- var STACK_MESSAGE = "input is nested too deeply for this engine's stack, or contains a cycle (flatten the document, or break the cycle)";
1652
- function isStackOverflow(e) {
1653
- if (!(e instanceof RangeError)) return false;
1654
- const m = e.message.toLowerCase();
1655
- return m.includes("call stack") || // V8: "Maximum call stack size exceeded"
1656
- m.includes("recursion") || // SpiderMonkey: "too much recursion"
1657
- m.includes("stack overflow");
1658
- }
1659
- function depthError(message) {
1660
- return new ConfigError(message, "");
1661
- }
1662
- async function guardStackDepthAsync(fn, wrap) {
1663
- try {
1664
- return await fn();
1665
- } catch (e) {
1666
- if (!isStackOverflow(e)) throw e;
1667
- throw wrap(STACK_MESSAGE);
1668
- }
1669
- }
1670
-
1671
- // src/internal/properties/properties.ts
1672
- function parseProperties(input) {
1673
- const pairs = [];
1674
- for (const { text, line } of logicalLines(stripBom(input))) {
1675
- const [rawKey, rawValue] = splitKeyValue(text);
1676
- const key = unescapeProps(rawKey, line);
1677
- if (key === "") continue;
1678
- const segments = key.split(".");
1679
- if (tooDeep(segments.length)) {
1680
- throw new ParseError(
1681
- `key maps to a path ${segments.length} segments deep, over the limit of ${MAX_PATH_SEGMENTS}`,
1682
- line,
1683
- 1
1684
- );
1685
- }
1686
- pairs.push([segments, unescapeProps(rawValue, line)]);
1687
- }
1688
- return nestPairs(pairs);
1689
- }
1690
- function nestPairs(pairs) {
1691
- const root = /* @__PURE__ */ Object.create(null);
1692
- const sorted = [...pairs].sort(([a], [b]) => compareSegments(a, b));
1693
- for (const [segments, value] of sorted) {
1694
- setNested(root, segments, value);
1695
- }
1696
- return root;
1697
- }
1698
- function compareSegments(a, b) {
1699
- const n = Math.min(a.length, b.length);
1700
- for (let i = 0; i < n; i++) {
1701
- const x = a[i];
1702
- const y = b[i];
1703
- if (x !== y) return x < y ? -1 : 1;
1704
- }
1705
- return a.length - b.length;
1706
- }
1707
- function logicalLines(input) {
1708
- const natural = input.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
1709
- const out = [];
1710
- for (let i = 0; i < natural.length; i++) {
1711
- let text = trimLeadingSpace(natural[i] ?? "");
1712
- if (text === "" || text.startsWith("#") || text.startsWith("!")) continue;
1713
- const start = i + 1;
1714
- while (endsWithContinuation(text)) {
1715
- text = text.slice(0, -1);
1716
- if (i + 1 >= natural.length) break;
1717
- i++;
1718
- text += trimLeadingSpace(natural[i] ?? "");
1719
- }
1720
- out.push({ text, line: start });
1721
- }
1722
- return out;
1723
- }
1724
- function trimLeadingSpace(s) {
1725
- return s.replace(/^[ \t\f]+/, "");
1726
- }
1727
- function endsWithContinuation(line) {
1728
- let n = 0;
1729
- for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i--) n++;
1730
- return n % 2 === 1;
1731
- }
1732
- function splitKeyValue(line) {
1733
- let key = "";
1734
- let i = 0;
1735
- for (; i < line.length; i++) {
1736
- const c = line[i];
1737
- if (c === "\\" && i + 1 < line.length) {
1738
- key += c + line[i + 1];
1739
- i++;
1740
- continue;
1741
- }
1742
- if (c === "=" || c === ":" || isPropsSpace(c)) break;
1743
- key += c;
1744
- }
1745
- while (i < line.length && isPropsSpace(line[i])) i++;
1746
- if (i < line.length && (line[i] === "=" || line[i] === ":")) {
1747
- i++;
1748
- while (i < line.length && isPropsSpace(line[i])) i++;
1749
- }
1750
- return [key, line.slice(i)];
1751
- }
1752
- function isPropsSpace(c) {
1753
- return c === " " || c === " " || c === "\f";
1754
- }
1755
- function unescapeProps(s, line) {
1756
- let out = "";
1757
- for (let i = 0; i < s.length; i++) {
1758
- if (s[i] !== "\\") {
1759
- out += s[i];
1760
- continue;
1761
- }
1762
- i++;
1763
- if (i >= s.length) break;
1764
- const e = s[i];
1765
- switch (e) {
1766
- case "t":
1767
- out += " ";
1768
- break;
1769
- case "n":
1770
- out += "\n";
1771
- break;
1772
- case "r":
1773
- out += "\r";
1774
- break;
1775
- case "f":
1776
- out += "\f";
1777
- break;
1778
- case "u": {
1779
- const hex = s.slice(i + 1, i + 5);
1780
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
1781
- throw new ParseError(`malformed \\u escape in .properties: \\u${hex}`, line, i + 1);
1782
- }
1783
- out += String.fromCharCode(parseInt(hex, 16));
1784
- i += 4;
1785
- break;
1786
- }
1787
- default:
1788
- out += e;
1789
- }
1790
- }
1791
- return out;
1792
- }
1793
- function setNested(obj, segments, value) {
1794
- let current = obj;
1795
- for (let i = 0; i < segments.length - 1; i++) {
1796
- const seg = segments[i];
1797
- if (!(seg in current) || typeof current[seg] !== "object" || current[seg] === null) {
1798
- current[seg] = /* @__PURE__ */ Object.create(null);
1799
- }
1800
- current = current[seg];
1801
- }
1802
- const last = segments[segments.length - 1];
1803
- if (typeof current[last] === "object" && current[last] !== null) return;
1804
- current[last] = value;
1805
- }
1806
- function propertiesToHoconValue(input) {
1807
- const parsed = parseProperties(input);
1808
- return recordToHoconValue(parsed);
1809
- }
1810
- function recordToHoconValue(obj) {
1811
- const fields = /* @__PURE__ */ new Map();
1812
- for (const [key, val] of Object.entries(obj)) {
1813
- if (typeof val === "string") {
1814
- fields.set(key, { kind: "scalar", raw: val, valueType: "string" });
1815
- } else if (val !== null && typeof val === "object") {
1816
- fields.set(key, recordToHoconValue(val));
1817
- }
1818
- }
1819
- return { kind: "object", fields };
1820
- }
1821
-
1822
- // src/internal/resolver/include-loader.ts
1823
- var _require;
1824
- function getRequire() {
1825
- if (_require === void 0) {
1826
- _require = pickRequire(
1827
- typeof __require === "function" ? __require : void 0,
1828
- import.meta.url
1829
- );
1830
- }
1831
- return _require;
1832
- }
1833
- function pickRequire(candidate, metaUrl) {
1834
- if (typeof candidate?.resolve === "function") {
1835
- return candidate;
1836
- }
1837
- return createRequire(metaUrl ?? pathToFileURL(nodePath.join(process.cwd(), "noop.js")));
1838
- }
1839
- function isPnpPath(p) {
1840
- return p.includes(".yarn/cache") || p.includes(".pnp.cjs") || p.includes(".pnp.loader");
1841
- }
1842
- function assertObjectRootedInclude(ast, sourcePath) {
1843
- if (ast.kind === "array") {
1844
- throw new ResolveError(
1845
- `included file has array at file root \u2014 an included file must contain an object, not an array (HOCON.md L993-994): ${sourcePath}`,
1846
- sourcePath,
1847
- ast.pos.line,
1848
- ast.pos.col
1849
- );
1850
- }
1851
- }
1852
- function validatePackageFile(file, identifier) {
1853
- if (file.length === 0) {
1854
- throw new ParseError(`include package("${identifier}", ...): file argument must be non-empty`, 0, 0);
1855
- }
1856
- if (file.includes("\\")) {
1857
- throw new ParseError(
1858
- `include package("${identifier}", "${file}"): backslash not allowed in file argument (use forward slash)`,
1859
- 0,
1860
- 0
1861
- );
1862
- }
1863
- if (file.startsWith("/")) {
1864
- throw new ParseError(
1865
- `include package("${identifier}", "${file}"): absolute path not allowed in file argument`,
1866
- 0,
1867
- 0
1868
- );
1869
- }
1870
- if (/(?:^|\/)\.\.?(?:\/|$)/u.test(file)) {
1871
- throw new ParseError(
1872
- `include package("${identifier}", "${file}"): path traversal (. or ..) not allowed in file argument`,
1873
- 0,
1874
- 0
1875
- );
1876
- }
1877
- if (file.includes("//")) {
1878
- throw new ParseError(
1879
- `include package("${identifier}", "${file}"): consecutive slashes not allowed in file argument`,
1880
- 0,
1881
- 0
1882
- );
1883
- }
1884
- }
1885
- function validatePackageIdentifier(identifier) {
1886
- if (identifier.length === 0) {
1887
- throw new ParseError("include package: identifier argument must be non-empty", 0, 0);
1888
- }
1889
- }
1890
- function defaultPackageResolver(identifier, file, includingFile, baseDir, resolveFrom) {
1891
- const from = resolveFrom ? Array.isArray(resolveFrom) ? resolveFrom : [resolveFrom] : baseDir ? [baseDir] : includingFile ? [nodePath.dirname(includingFile)] : [process.cwd()];
1892
- let resolved;
1893
- try {
1894
- resolved = getRequire().resolve(`${identifier}/${file}`, { paths: from });
1895
- } catch {
1896
- throw new PackageLookupError(
1897
- `include package("${identifier}", "${file}"): module not found (starting from: ${from.join(", ")})`,
1898
- identifier,
1899
- file,
1900
- 0,
1901
- 0
1902
- );
1903
- }
1904
- if (isPnpPath(resolved)) {
1905
- throw new ResolveError(
1906
- `include package("${identifier}", "${file}"): Yarn Berry PnP store paths are not supported. Provide a custom packageResolver option to handle PnP resolution.`,
1907
- `${identifier}/${file}`,
1908
- 0,
1909
- 0
1910
- );
1911
- }
1912
- const fileParts = file.split("/");
1913
- const expectedBasename = fileParts[fileParts.length - 1] ?? file;
1914
- const resolvedBasename = nodePath.basename(resolved);
1915
- if (resolvedBasename !== expectedBasename) {
1916
- throw new PackageLookupError(
1917
- `include package("${identifier}", "${file}"): case mismatch \u2014 resolved "${resolvedBasename}" but expected "${expectedBasename}" (E11 decision 5: case-sensitive)`,
1918
- identifier,
1919
- file,
1920
- 0,
1921
- 0
1922
- );
1923
- }
1924
- return resolved;
1925
- }
1926
- var IncludeLoader = class {
1927
- constructor(opts) {
1928
- this.opts = opts;
1929
- }
1930
- /**
1931
- * Resolve an include path to an absolute path.
1932
- * - file() includes resolve relative to CWD (or as absolute paths),
1933
- * NOT relative to the including file's directory.
1934
- * - Bare includes resolve relative to the including file's directory (baseDir).
1935
- */
1936
- resolveIncludePath(includePath, baseDir, isFile) {
1937
- return isFile ? nodePath.resolve(includePath) : baseDir ? nodePath.resolve(baseDir, includePath) : nodePath.resolve(includePath);
1938
- }
1939
- load(includePath, required, isFile) {
1940
- const { baseDir, includeStack = [] } = this.opts;
1941
- const absPath = this.resolveIncludePath(includePath, baseDir, !!isFile);
1942
- if (includeStack.includes(absPath)) {
1943
- throw new ResolveError(`circular include: ${absPath}`, absPath, 0, 0);
1944
- }
1945
- if (includeStack.length >= 50) {
1946
- throw new ResolveError(`include depth limit exceeded (max 50)`, includePath, 0, 0);
1947
- }
1948
- const hasExplicitExt = absPath.endsWith(".conf") || absPath.endsWith(".json") || absPath.endsWith(".properties");
1949
- if (hasExplicitExt) {
1950
- const result = this.loadSingle(absPath);
1951
- if (result !== void 0) return result;
1952
- if (required) {
1953
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1954
- }
1955
- return makeResObj();
1956
- }
1957
- const merged = makeResObj();
1958
- let foundAny = false;
1959
- const probeExts = [".properties", ".json", ".conf"];
1960
- for (const ext of probeExts) {
1961
- const obj = this.loadSingle(`${absPath}${ext}`);
1962
- if (obj !== void 0) {
1963
- deepMergeResObjInto(merged, obj, []);
1964
- foundAny = true;
1965
- }
1966
- }
1967
- if (!foundAny && required) {
1968
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1969
- }
1970
- return merged;
1971
- }
1972
- async loadAsync(includePath, required, isFile) {
1973
- const { baseDir, includeStack = [] } = this.opts;
1974
- const absPath = this.resolveIncludePath(includePath, baseDir, !!isFile);
1975
- if (includeStack.includes(absPath)) {
1976
- throw new ResolveError(`circular include: ${absPath}`, absPath, 0, 0);
1977
- }
1978
- if (includeStack.length >= 50) {
1979
- throw new ResolveError(`include depth limit exceeded (max 50)`, includePath, 0, 0);
1980
- }
1981
- const hasExplicitExt = absPath.endsWith(".conf") || absPath.endsWith(".json") || absPath.endsWith(".properties");
1982
- if (hasExplicitExt) {
1983
- const result = await this.loadSingleAsync(absPath);
1984
- if (result !== void 0) return result;
1985
- if (required) {
1986
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1987
- }
1988
- return makeResObj();
1989
- }
1990
- const merged = makeResObj();
1991
- let foundAny = false;
1992
- const probeExts = [".properties", ".json", ".conf"];
1993
- for (const ext of probeExts) {
1994
- const obj = await this.loadSingleAsync(`${absPath}${ext}`);
1995
- if (obj !== void 0) {
1996
- deepMergeResObjInto(merged, obj, []);
1997
- foundAny = true;
1998
- }
1999
- }
2000
- if (!foundAny && required) {
2001
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
2002
- }
2003
- return merged;
2004
- }
2005
- /**
2006
- * Resolve and load `include package("identifier", "file")`.
2007
- * Validates the identifier and file arguments, resolves via the package resolver,
2008
- * performs cycle detection using a JSON-serialised cycle key, and parses the content.
2009
- */
2010
- // `required` is reserved for future optional-package semantics (E11 decision 7);
2011
- // currently all package lookup failures throw regardless of this flag.
2012
- loadPackage(identifier, file, _required) {
2013
- validatePackageIdentifier(identifier);
2014
- validatePackageFile(file, identifier);
2015
- const { includeStack = [], baseDir, resolveFrom, packageResolver, readFileSync: readFileSync2 } = this.opts;
2016
- const cycleKey = JSON.stringify(["package", identifier, file]);
2017
- if (includeStack.includes(cycleKey)) {
2018
- throw new ResolveError(
2019
- `circular include: package("${identifier}", "${file}")`,
2020
- `${identifier}/${file}`,
2021
- 0,
2022
- 0
2023
- );
2024
- }
2025
- if (includeStack.length >= 50) {
2026
- throw new ResolveError(`include depth limit exceeded (max 50)`, `${identifier}/${file}`, 0, 0);
2027
- }
2028
- const resolver = packageResolver ?? ((id, f, includingFile, bDir) => defaultPackageResolver(id, f, includingFile, bDir, resolveFrom));
2029
- const resolvedPath = resolver(identifier, file, void 0, baseDir);
2030
- const content = readFileSync2(resolvedPath);
2031
- const tokens = tokenize(content);
2032
- const ast = parseTokens(tokens);
2033
- assertObjectRootedInclude(ast, resolvedPath);
2034
- return this.onBuildResObj(ast, {
2035
- ...this.opts,
2036
- baseDir: nodePath.dirname(resolvedPath),
2037
- includeStack: [...includeStack, cycleKey]
2038
- });
2039
- }
2040
- /**
2041
- * Async variant of `loadPackage`.
2042
- */
2043
- async loadPackageAsync(identifier, file, _required) {
2044
- validatePackageIdentifier(identifier);
2045
- validatePackageFile(file, identifier);
2046
- const { includeStack = [], baseDir, resolveFrom, packageResolver, readFile, readFileSync: readFileSync2 } = this.opts;
2047
- const cycleKey = JSON.stringify(["package", identifier, file]);
2048
- if (includeStack.includes(cycleKey)) {
2049
- throw new ResolveError(
2050
- `circular include: package("${identifier}", "${file}")`,
2051
- `${identifier}/${file}`,
2052
- 0,
2053
- 0
2054
- );
2055
- }
2056
- if (includeStack.length >= 50) {
2057
- throw new ResolveError(`include depth limit exceeded (max 50)`, `${identifier}/${file}`, 0, 0);
2058
- }
2059
- const resolver = packageResolver ?? ((id, f, includingFile, bDir) => defaultPackageResolver(id, f, includingFile, bDir, resolveFrom));
2060
- const resolvedPath = resolver(identifier, file, void 0, baseDir);
2061
- const read = readFile ? async (p) => readFile(p) : async (p) => readFileSync2(p);
2062
- const content = await read(resolvedPath);
2063
- const tokens = tokenize(content);
2064
- const ast = parseTokens(tokens);
2065
- assertObjectRootedInclude(ast, resolvedPath);
2066
- return this.onBuildResObjAsync(ast, {
2067
- ...this.opts,
2068
- baseDir: nodePath.dirname(resolvedPath),
2069
- includeStack: [...includeStack, cycleKey]
2070
- });
2071
- }
2072
- loadSingle(candidate) {
2073
- const { readFileSync: readFileSync2, includeStack = [] } = this.opts;
2074
- if (includeStack.includes(candidate)) {
2075
- throw new ResolveError(`circular include: ${candidate}`, candidate, 0, 0);
2076
- }
2077
- let content;
2078
- try {
2079
- content = readFileSync2(candidate);
2080
- } catch (e) {
2081
- if (isFileNotFoundError(e)) return void 0;
2082
- throw e;
2083
- }
2084
- if (candidate.endsWith(".properties")) {
2085
- return hoconValueToResObj(propertiesToHoconValue(content));
2086
- }
2087
- const tokens = tokenize(content);
2088
- const ast = parseTokens(tokens);
2089
- assertObjectRootedInclude(ast, candidate);
2090
- return this.onBuildResObj(ast, {
2091
- ...this.opts,
2092
- baseDir: nodePath.dirname(candidate),
2093
- includeStack: [...includeStack, candidate]
2094
- });
2095
- }
2096
- async loadSingleAsync(candidate) {
2097
- const { readFile, readFileSync: readFileSync2, includeStack = [] } = this.opts;
2098
- const read = readFile ? async (p) => readFile(p) : async (p) => readFileSync2(p);
2099
- if (includeStack.includes(candidate)) {
2100
- throw new ResolveError(`circular include: ${candidate}`, candidate, 0, 0);
2101
- }
2102
- let content;
2103
- try {
2104
- content = await read(candidate);
2105
- } catch (e) {
2106
- if (isFileNotFoundError(e)) return void 0;
2107
- throw e;
2108
- }
2109
- if (candidate.endsWith(".properties")) {
2110
- return hoconValueToResObj(propertiesToHoconValue(content));
2111
- }
2112
- const tokens = tokenize(content);
2113
- const ast = parseTokens(tokens);
2114
- assertObjectRootedInclude(ast, candidate);
2115
- return this.onBuildResObjAsync(ast, {
2116
- ...this.opts,
2117
- baseDir: nodePath.dirname(candidate),
2118
- includeStack: [...includeStack, candidate]
2119
- });
2120
- }
2121
- };
2122
-
2123
- // src/internal/resolver/structure-builder.ts
2124
- var StructureBuilder = class _StructureBuilder {
2125
- constructor(opts) {
2126
- this.loader = new IncludeLoader(opts);
2127
- this.loader.onBuildResObj = (a, o) => new _StructureBuilder(o).build(a);
2128
- this.loader.onBuildResObjAsync = async (a, o) => new _StructureBuilder(o).buildAsync(a);
2129
- }
2130
- build(ast, pathPrefix = []) {
2131
- if (ast.kind !== "object") {
2132
- throw new ResolveError("root AST must be an object", "", ast.pos.line, ast.pos.col);
2133
- }
2134
- const obj = makeResObj();
2135
- for (const field of ast.fields) {
2136
- this.applyField(obj, field, pathPrefix);
2137
- }
2138
- return obj;
2139
- }
2140
- async buildAsync(ast, pathPrefix = []) {
2141
- if (ast.kind !== "object") {
2142
- throw new ResolveError("root AST must be an object", "", ast.pos.line, ast.pos.col);
2143
- }
2144
- const obj = makeResObj();
2145
- for (const field of ast.fields) {
2146
- await this.applyFieldAsync(obj, field, pathPrefix);
2147
- }
2148
- return obj;
2149
- }
2150
- applyField(obj, field, pathPrefix) {
2151
- if (field.key.length === 0 && field.value.kind === "include") {
2152
- const { qualifier, path: path2, required } = field.value;
2153
- let included;
2154
- if (qualifier.kind === "package") {
2155
- included = this.loader.loadPackage(qualifier.identifier, path2, required);
2156
- } else {
2157
- included = this.loader.load(path2, required, qualifier.kind === "file");
2158
- }
2159
- if (pathPrefix.length > 0) {
2160
- this.relativizeResObj(included, pathPrefix);
2161
- }
2162
- deepMergeResObjInto(obj, included, pathPrefix);
2163
- return;
2164
- }
2165
- const [head, ...tail] = field.key;
2166
- if (head === void 0) return;
2167
- if (tail.length > 0) {
2168
- const syntheticAst = {
2169
- kind: "object",
2170
- fields: [{ key: tail, value: field.value, append: field.append, pos: field.pos }],
2171
- pos: field.pos
2172
- };
2173
- this.applyField(obj, { key: [head], value: syntheticAst, append: false, pos: field.pos }, pathPrefix);
2174
- return;
2175
- }
2176
- const childPrefix = [...pathPrefix, head];
2177
- const fullKey = stringSegmentsToKey(childPrefix);
2178
- if (field.append) {
2179
- const synthetic = this.desugarAppend(field, childPrefix);
2180
- this.applyField(obj, synthetic, pathPrefix);
2181
- return;
2182
- }
2183
- const existing = obj.fields.get(head);
2184
- const newVal = this.astToResolverValue(field.value, childPrefix);
2185
- if (!containsSelfRef(newVal, fullKey)) {
2186
- obj.resetKeys.add(head);
2187
- }
2188
- if (existing !== void 0) {
2189
- const oldPrior = obj.priorValues.get(head);
2190
- const priorInput = isResObj(existing) ? foldNestedSelfRefs(existing, childPrefix) : existing;
2191
- const prior = foldOrSkipPrior(priorInput, fullKey, oldPrior);
2192
- if (prior !== void 0) obj.priorValues.set(head, prior);
2193
- }
2194
- if (existing !== void 0 && isResObj(existing) && isResObj(newVal)) {
2195
- deepMergeResObjInto(existing, newVal, childPrefix);
2196
- return;
2197
- }
2198
- obj.fields.set(head, newVal);
2199
- }
2200
- async applyFieldAsync(obj, field, pathPrefix) {
2201
- if (field.key.length === 0 && field.value.kind === "include") {
2202
- const { qualifier, path: path2, required } = field.value;
2203
- let included;
2204
- if (qualifier.kind === "package") {
2205
- included = await this.loader.loadPackageAsync(qualifier.identifier, path2, required);
2206
- } else {
2207
- included = await this.loader.loadAsync(path2, required, qualifier.kind === "file");
2208
- }
2209
- if (pathPrefix.length > 0) {
2210
- this.relativizeResObj(included, pathPrefix);
2211
- }
2212
- deepMergeResObjInto(obj, included, pathPrefix);
2213
- return;
2214
- }
2215
- const [head, ...tail] = field.key;
2216
- if (head === void 0) return;
2217
- if (tail.length > 0) {
2218
- const syntheticAst = {
2219
- kind: "object",
2220
- fields: [{ key: tail, value: field.value, append: field.append, pos: field.pos }],
2221
- pos: field.pos
2222
- };
2223
- await this.applyFieldAsync(obj, { key: [head], value: syntheticAst, append: false, pos: field.pos }, pathPrefix);
2224
- return;
2225
- }
2226
- const childPrefix = [...pathPrefix, head];
2227
- const fullKey = stringSegmentsToKey(childPrefix);
2228
- if (field.append) {
2229
- const synthetic = this.desugarAppend(field, childPrefix);
2230
- await this.applyFieldAsync(obj, synthetic, pathPrefix);
2231
- return;
2232
- }
2233
- const existing = obj.fields.get(head);
2234
- const newVal = await this.astToResolverValueAsync(field.value, childPrefix);
2235
- if (!containsSelfRef(newVal, fullKey)) {
2236
- obj.resetKeys.add(head);
2237
- }
2238
- if (existing !== void 0) {
2239
- const oldPrior = obj.priorValues.get(head);
2240
- const priorInput = isResObj(existing) ? foldNestedSelfRefs(existing, childPrefix) : existing;
2241
- const prior = foldOrSkipPrior(priorInput, fullKey, oldPrior);
2242
- if (prior !== void 0) obj.priorValues.set(head, prior);
2243
- }
2244
- if (existing !== void 0 && isResObj(existing) && isResObj(newVal)) {
2245
- deepMergeResObjInto(existing, newVal, childPrefix);
2246
- return;
2247
- }
2248
- obj.fields.set(head, newVal);
2249
- }
2250
- /** Builds the `key = ${?fullkey} [value]` field that `key += value` desugars
2251
- * to (S13b.2, HOCON.md L732). `childPrefix` is the field's fully-qualified
2252
- * path (pathPrefix + key), so a nested `srv { items += x }` references
2253
- * `${?srv.items}`; include relativization rewrites it under a mount prefix.
2254
- * `field.key` is already single-segment here (multi-segment keys are split
2255
- * into nested objects upstream). Returns a NEW AstField (append=false);
2256
- * positions inherit from the original field so resolve-time errors (the
2257
- * S13b.2 non-array check, now via the scalar+array concat) keep a location. */
2258
- desugarAppend(field, childPrefix) {
2259
- const segments = childPrefix.map((text) => ({ text, line: field.pos.line, col: field.pos.col }));
2260
- const subst = { kind: "subst", segments, optional: true, listSuffix: false, pos: field.pos };
2261
- const elemArray = { kind: "array", items: [field.value], pos: field.pos };
2262
- const synthetic = { kind: "concat", nodes: [subst, elemArray], pos: field.pos };
2263
- return { key: field.key, value: synthetic, append: false, pos: field.pos };
2264
- }
2265
- astToResolverValue(ast, pathPrefix) {
2266
- switch (ast.kind) {
2267
- case "scalar": {
2268
- const sv = { kind: "scalar", raw: ast.raw, valueType: ast.valueType };
2269
- if (ast._separator) separatorValues.add(sv);
2270
- return sv;
2271
- }
2272
- case "array":
2273
- return { kind: "array", items: ast.items.map((i) => this.astToResolverValue(i, pathPrefix)) };
2274
- case "object": {
2275
- const inner = this.build(ast, pathPrefix);
2276
- return inner;
2277
- }
2278
- case "subst":
2279
- return { _kind: "subst-placeholder", segments: ast.segments, optional: ast.optional, knownAbsent: false, listSuffix: ast.listSuffix, line: ast.pos.line, col: ast.pos.col, prefixLen: 0 };
2280
- case "concat":
2281
- return { _kind: "concat-placeholder", nodes: ast.nodes.map((n) => this.astToResolverValue(n, pathPrefix)), line: ast.pos.line, col: ast.pos.col };
2282
- case "include":
2283
- return { kind: "scalar", raw: "null", valueType: "null" };
2284
- }
2285
- }
2286
- async astToResolverValueAsync(ast, pathPrefix) {
2287
- switch (ast.kind) {
2288
- case "scalar": {
2289
- const sv = { kind: "scalar", raw: ast.raw, valueType: ast.valueType };
2290
- if (ast._separator) separatorValues.add(sv);
2291
- return sv;
2292
- }
2293
- case "array": {
2294
- const items = [];
2295
- for (const i of ast.items) {
2296
- items.push(await this.astToResolverValueAsync(i, pathPrefix));
2297
- }
2298
- return { kind: "array", items };
2299
- }
2300
- case "object":
2301
- return await this.buildAsync(ast, pathPrefix);
2302
- case "subst":
2303
- return { _kind: "subst-placeholder", segments: ast.segments, optional: ast.optional, knownAbsent: false, listSuffix: ast.listSuffix, line: ast.pos.line, col: ast.pos.col, prefixLen: 0 };
2304
- case "concat": {
2305
- const nodes = [];
2306
- for (const n of ast.nodes) {
2307
- nodes.push(await this.astToResolverValueAsync(n, pathPrefix));
2308
- }
2309
- return { _kind: "concat-placeholder", nodes, line: ast.pos.line, col: ast.pos.col };
2310
- }
2311
- case "include":
2312
- return { kind: "scalar", raw: "null", valueType: "null" };
2313
- }
2314
- }
2315
- // ---- Relativize substitution paths for nested includes ----
2316
- relativizeSubstPaths(val, prefixSegments) {
2317
- if (isSubst(val)) {
2318
- const prefixAsSegments = prefixSegments.map((text) => ({ text, line: 0, col: 0 }));
2319
- val.segments = [...prefixAsSegments, ...val.segments];
2320
- val.prefixLen += prefixSegments.length;
2321
- return;
2322
- }
2323
- if (isConcat(val)) {
2324
- for (const node of val.nodes) {
2325
- this.relativizeSubstPaths(node, prefixSegments);
2326
- }
2327
- return;
2328
- }
2329
- if (isResObj(val)) {
2330
- this.relativizeResObj(val, prefixSegments);
2331
- return;
2332
- }
2333
- const hv = val;
2334
- if (hv.kind === "array") {
2335
- for (const item of hv.items) {
2336
- this.relativizeSubstPaths(item, prefixSegments);
2337
- }
2338
- }
2339
- }
2340
- relativizeResObj(obj, prefixSegments) {
2341
- for (const val of obj.fields.values()) {
2342
- this.relativizeSubstPaths(val, prefixSegments);
2343
- }
2344
- for (const val of obj.priorValues.values()) {
2345
- this.relativizeSubstPaths(val, prefixSegments);
2346
- }
2347
- }
2348
- };
2349
-
2350
- // src/value/numeric-array.ts
2351
- function numericObjectToArray(value) {
2352
- if (value.kind !== "object") return null;
2353
- if (value.fields.size === 0) return null;
2354
- const canonicalInt = /^(0|[1-9][0-9]*)$/;
2355
- const eligible = [];
2356
- for (const [key, val] of value.fields) {
2357
- if (!canonicalInt.test(key)) continue;
2358
- const n = Number(key);
2359
- if (!Number.isInteger(n) || n > 2147483647) continue;
2360
- eligible.push({ n, v: val });
2361
- }
2362
- if (eligible.length === 0) return null;
2363
- eligible.sort((a, b) => a.n - b.n);
2364
- return eligible.map((e) => e.v);
2365
- }
2366
-
2367
- // src/internal/resolver/substitution-resolver.ts
2368
- var SubstitutionResolver = class {
2369
- constructor(root, opts) {
2370
- this.root = root;
2371
- this.opts = opts;
2372
- this.resolving = /* @__PURE__ */ new Set();
2373
- this.cache = /* @__PURE__ */ new Map();
2374
- // Tracks ConcatPlaceholder nodes currently being iterated by resolveConcat.
2375
- // Used by isSelfRef detection: fires only when found === a concat currently
2376
- // mid-iteration (i.e. we are inside found's own resolution), preventing the
2377
- // "foofoo" double-count without misfiring when an external field looks up the
2378
- // same concat via a substitution (multi-reviewer convergence fix).
2379
- //
2380
- // Spec deviation: the S13a.13 spec ★1 decision #1 specified path-equality
2381
- // preservation for self-ref detection. Round-2 multi-agent-review surfaced a
2382
- // false-positive on external lookups (`a = ${?a}foo; b = ${a}`), so the
2383
- // criterion was tightened to node-membership-in-iterating-set — strictly
2384
- // narrower than path-equality. Spec amendment deferred to a follow-up
2385
- // xx.hocon PR (see Phase 6 #3f close-out notes).
2386
- this.resolvingConcats = /* @__PURE__ */ new WeakSet();
2387
- // Path stack tracking the full dotted path of the field currently being
2388
- // assigned in `resolveResObj`. Leaf keys are pushed on entry to each
2389
- // `(key, val)` iteration and popped on exit, so nested objects build up
2390
- // the full path (e.g. `["o", "history"]` while resolving `o.history`).
2391
- //
2392
- // Used to tighten self-ref detection at the L192 found-lookup site:
2393
- // a substitution `${X}` whose looked-up value contains a Subst pointing
2394
- // at `X` is only a true self-reference when the field currently being
2395
- // assigned is `X` (or a descendant of `X`). Without this guard, an
2396
- // external lookup like `b = ${o}` (where o has a self-referential
2397
- // field) would mis-fire and short-circuit to o's prior, returning the
2398
- // wrong value for b. The is_owner gate (rfp prefix-matches s.segments)
2399
- // narrows the check to the owner case only.
2400
- //
2401
- // Cross-impl with rs.hocon v1.5.1's resolving_field_path (same purpose,
2402
- // same prefix-match semantics).
2403
- this.resolvingFieldPath = [];
2404
- // S13a.12 recursion guard: field keys whose prior is currently being
2405
- // resolved through the prefix-self-ref branch. Saved priors are
2406
- // prefix-self-ref-free by the fold invariant, so re-entry only happens on
2407
- // a shape the fold could not see through (a live subst mid-navigation) —
2408
- // report it as a cycle instead of recursing forever.
2409
- this.resolvingPrefixPriors = /* @__PURE__ */ new Set();
2410
- }
2411
- /** Returns a prefix for error messages, including origin info when set. */
2412
- originPrefix() {
2413
- return this.opts.originDescription ? `${this.opts.originDescription}: ` : "";
2414
- }
2415
- resolve() {
2416
- return this.resolveResObj(this.root);
2417
- }
2418
- resolveResObj(obj) {
2419
- const result = /* @__PURE__ */ new Map();
2420
- for (const [key, val] of obj.fields) {
2421
- this.resolvingFieldPath.push(key);
2422
- const fullCacheKey = stringSegmentsToKey(this.resolvingFieldPath);
2423
- this.cache.delete(fullCacheKey);
2424
- try {
2425
- const resolved = this.resolveVal(val, obj);
2426
- if (resolved !== void 0) {
2427
- if (resolved.kind === "object") {
2428
- const prior = obj.priorValues.get(key);
2429
- if (prior !== void 0) {
2430
- const priorResolved = this.resolveVal(prior, obj);
2431
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2432
- const finalValue = deepMergeHoconValues(
2433
- priorResolved,
2434
- resolved
2435
- );
2436
- result.set(key, finalValue);
2437
- this.cache.set(fullCacheKey, finalValue);
2438
- this.cacheDescendants(fullCacheKey, finalValue);
2439
- continue;
2440
- }
2441
- }
2442
- }
2443
- result.set(key, resolved);
2444
- this.cache.set(fullCacheKey, resolved);
2445
- this.cacheDescendants(fullCacheKey, resolved);
2446
- } else {
2447
- const prior = obj.priorValues.get(key);
2448
- if (prior !== void 0) {
2449
- const priorResolved = this.resolveVal(prior, obj);
2450
- if (priorResolved !== void 0) {
2451
- result.set(key, priorResolved);
2452
- this.cache.set(fullCacheKey, priorResolved);
2453
- this.cacheDescendants(fullCacheKey, priorResolved);
2454
- }
2455
- }
2456
- }
2457
- } finally {
2458
- this.resolvingFieldPath.pop();
2459
- }
2460
- }
2461
- return { kind: "object", fields: result };
2462
- }
2463
- /** S13a.12: walk resolved-object fields by segment text. A missing segment
2464
- * or a walk into a scalar/array is path-absent → undefined. */
2465
- navigateResolved(v, remainder) {
2466
- let cur = v;
2467
- for (const seg of remainder) {
2468
- if (cur.kind !== "object") return void 0;
2469
- const next = cur.fields.get(seg);
2470
- if (next === void 0) return void 0;
2471
- cur = next;
2472
- }
2473
- return cur;
2474
- }
2475
- cacheDescendants(prefix, value) {
2476
- if (value.kind !== "object") return;
2477
- for (const [key, child] of value.fields) {
2478
- const childKey = `${prefix}.${stringSegmentsToKey([key])}`;
2479
- this.cache.set(childKey, child);
2480
- this.cacheDescendants(childKey, child);
2481
- }
2482
- }
2483
- resolveVal(v, scope) {
2484
- if (isSubst(v)) return this.resolveSubst(v, scope);
2485
- if (isConcat(v)) {
2486
- this.resolvingConcats.add(v);
2487
- try {
2488
- const concatResult = this.resolveConcat(v.nodes, scope, v.line, v.col);
2489
- return concatResult;
2490
- } finally {
2491
- this.resolvingConcats.delete(v);
2492
- }
2493
- }
2494
- if (isResObj(v)) return this.resolveResObj(v);
2495
- const hv = v;
2496
- if (hv.kind === "array") {
2497
- const items = [];
2498
- for (const item of hv.items) {
2499
- const resolved = this.resolveVal(item, scope);
2500
- if (resolved === void 0) continue;
2501
- items.push(resolved);
2502
- }
2503
- return { kind: "array", items };
2504
- }
2505
- return hv;
2506
- }
2507
- resolveSubst(s, scope) {
2508
- if (s.knownAbsent) {
2509
- if (!s.optional) {
2510
- if (this.opts.allowUnresolved) return s;
2511
- const k = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
2512
- throw new ResolveError(
2513
- `${this.originPrefix()}could not resolve substitution: \${${k}}`,
2514
- k,
2515
- s.line,
2516
- s.col
2517
- );
2518
- }
2519
- return void 0;
2520
- }
2521
- {
2522
- const rfp = this.resolvingFieldPath;
2523
- const sTexts = s.segments.map((seg) => seg.text);
2524
- if (rfp.length > 0 && rfp.length < sTexts.length && stringSegmentsToKey(sTexts.slice(0, rfp.length)) === stringSegmentsToKey(rfp)) {
2525
- const guardKey = stringSegmentsToKey(rfp);
2526
- const prior = scope.priorValues.get(rfp[rfp.length - 1]);
2527
- if (prior !== void 0 && !this.resolvingPrefixPriors.has(guardKey)) {
2528
- this.resolvingPrefixPriors.add(guardKey);
2529
- try {
2530
- const priorResolved = this.resolveVal(prior, scope);
2531
- if (priorResolved !== void 0) {
2532
- const navigated = this.navigateResolved(priorResolved, sTexts.slice(rfp.length));
2533
- if (navigated !== void 0) return navigated;
2534
- }
2535
- } finally {
2536
- this.resolvingPrefixPriors.delete(guardKey);
2537
- }
2538
- }
2539
- if (s.optional) return void 0;
2540
- if (this.opts.allowUnresolved) return s;
2541
- const k = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
2542
- throw new ResolveError(
2543
- `${this.originPrefix()}could not resolve substitution: \${${k}}`,
2544
- k,
2545
- s.line,
2546
- s.col
2547
- );
2548
- }
2549
- }
2550
- const key = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
2551
- if (this.cache.has(key)) return this.cache.get(key);
2552
- if (this.resolving.has(key)) {
2553
- let prior;
2554
- if (s.segments.length > 1) {
2555
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2556
- const parentScope = lookupResObj(
2557
- this.root,
2558
- s.segments.slice(0, s.segments.length - 1)
2559
- );
2560
- prior = parentScope?.priorValues.get(leafSeg);
2561
- } else {
2562
- const rootSeg = s.segments[0]?.text ?? "";
2563
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
2564
- }
2565
- if (prior !== void 0) {
2566
- const saved = this.resolving;
2567
- this.resolving = new Set(saved);
2568
- try {
2569
- return this.resolveVal(prior, scope);
2570
- } finally {
2571
- this.resolving = saved;
2572
- }
2573
- }
2574
- if (s.optional) return void 0;
2575
- throw new ResolveError(
2576
- this.originPrefix() + `circular substitution: ${key}`,
2577
- key,
2578
- s.line,
2579
- s.col
2580
- );
2581
- }
2582
- this.resolving.add(key);
2583
- try {
2584
- const found = lookupPath(this.root, s.segments);
2585
- if (found !== void 0) {
2586
- const rfp = this.resolvingFieldPath;
2587
- const isOwner = rfp.length >= s.segments.length && s.segments.every((seg, i) => rfp[i] === seg.text);
2588
- const isSelfRef = isConcat(found) && this.resolvingConcats.has(found) || isOwner && containsSubstByPath(found, s.segments);
2589
- if (isSelfRef) {
2590
- let prior;
2591
- if (s.segments.length > 1) {
2592
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2593
- const parentScope = lookupResObj(
2594
- this.root,
2595
- s.segments.slice(0, s.segments.length - 1)
2596
- );
2597
- prior = parentScope?.priorValues.get(leafSeg);
2598
- } else {
2599
- const rootSeg = s.segments[0]?.text ?? "";
2600
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
2601
- }
2602
- if (prior !== void 0) {
2603
- const result2 = this.resolveVal(prior, scope);
2604
- if (result2 !== void 0) this.cache.set(key, result2);
2605
- return result2;
2606
- }
2607
- if (s.optional) return void 0;
2608
- throw new ResolveError(
2609
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2610
- key,
2611
- s.line,
2612
- s.col
2613
- );
2614
- }
2615
- let result = this.resolveVal(found, scope);
2616
- const effectiveLen = s.segments.length - s.prefixLen;
2617
- if (effectiveLen === 1 && result !== void 0 && result.kind === "object") {
2618
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2619
- let prior;
2620
- if (s.prefixLen > 0) {
2621
- const parentScope = lookupResObj(
2622
- this.root,
2623
- s.segments.slice(0, s.segments.length - 1)
2624
- );
2625
- prior = parentScope?.priorValues.get(leafSeg);
2626
- } else {
2627
- prior = scope.priorValues.get(leafSeg) ?? this.root.priorValues.get(leafSeg);
2628
- }
2629
- if (prior !== void 0) {
2630
- const priorResolved = this.resolveVal(prior, scope);
2631
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2632
- result = deepMergeHoconValues(
2633
- priorResolved,
2634
- result
2635
- );
2636
- }
2637
- }
2638
- }
2639
- if (result !== void 0) this.cache.set(key, result);
2640
- return result;
2641
- }
2642
- if (s.prefixLen > 0 && s.segments.length > s.prefixLen) {
2643
- const originalSegments = s.segments.slice(s.prefixLen);
2644
- const fallbackFound = lookupPath(this.root, originalSegments);
2645
- if (fallbackFound !== void 0) {
2646
- let result = this.resolveVal(fallbackFound, scope);
2647
- if (originalSegments.length === 1 && result !== void 0 && result.kind === "object") {
2648
- const rootSeg = originalSegments[0]?.text ?? "";
2649
- const prior = this.root.priorValues.get(rootSeg);
2650
- if (prior !== void 0) {
2651
- const priorResolved = this.resolveVal(prior, scope);
2652
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2653
- result = deepMergeHoconValues(
2654
- priorResolved,
2655
- result
2656
- );
2657
- }
2658
- }
2659
- }
2660
- if (result !== void 0) this.cache.set(key, result);
2661
- return result;
2662
- }
2663
- }
2664
- if (s.listSuffix && this.opts.useSystemEnvironment !== false) {
2665
- const result = this.resolveEnvList(s);
2666
- if (result !== void 0) {
2667
- this.cache.set(key, result);
2668
- return result;
2669
- }
2670
- if (s.optional) return void 0;
2671
- const envBase = s.segments.map((seg) => seg.text).join(".");
2672
- throw new ResolveError(
2673
- `${this.originPrefix()}could not resolve substitution: \${${key}} (no environment variables ${envBase}_0, ${envBase}_1, \u2026 set)`,
2674
- key,
2675
- s.line,
2676
- s.col
2677
- );
2678
- } else if (s.listSuffix) {
2679
- if (s.optional) return void 0;
2680
- if (this.opts.allowUnresolved) return s;
2681
- throw new ResolveError(
2682
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2683
- key,
2684
- s.line,
2685
- s.col
2686
- );
2687
- }
2688
- if (this.opts.useSystemEnvironment !== false) {
2689
- const envKey = s.segments.map((seg) => seg.text).join(".");
2690
- const envVal = this.opts.env[envKey] ?? (s.prefixLen > 0 ? this.opts.env[s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".")] : void 0);
2691
- if (envVal !== void 0) {
2692
- const result = { kind: "scalar", raw: envVal, valueType: "string" };
2693
- this.cache.set(key, result);
2694
- return result;
2695
- }
2696
- }
2697
- if (s.optional) return void 0;
2698
- if (this.opts.allowUnresolved) {
2699
- return s;
2700
- }
2701
- throw new ResolveError(
2702
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2703
- key,
2704
- s.line,
2705
- s.col
2706
- );
2707
- } finally {
2708
- this.resolving.delete(key);
2709
- }
2710
- }
2711
- /**
2712
- * S13c: scan environment for NAME_0, NAME_1, … and return an Array<Scalar(String)>.
2713
- *
2714
- * Candidate bases follow the same fully-qualified→bare order used by the scalar
2715
- * env fallback. The first base whose _0 key is present wins entirely — no
2716
- * cross-base merging (spec §Relativized fallback precedence rules).
2717
- *
2718
- * Returns the HoconValue Array if any candidate base has _0, or undefined if
2719
- * none do (caller applies optional/required handling).
2720
- */
2721
- resolveEnvList(s) {
2722
- const bases = this.candidateBases(s);
2723
- for (const base of bases) {
2724
- const key0 = base + "_0";
2725
- if (!(key0 in this.opts.env)) continue;
2726
- const items = [];
2727
- for (let i = 0; ; i++) {
2728
- const k = base + "_" + i;
2729
- if (!(k in this.opts.env)) break;
2730
- items.push({ kind: "scalar", raw: this.opts.env[k], valueType: "string" });
2731
- }
2732
- return { kind: "array", items };
2733
- }
2734
- return void 0;
2735
- }
2736
- /**
2737
- * Return the candidate base names for env-var-list lookup, in precedence order.
2738
- * Mirrors the fully-qualified→bare fallback used by the scalar env path.
2739
- */
2740
- candidateBases(s) {
2741
- const full = s.segments.map((seg) => seg.text).join(".");
2742
- if (s.prefixLen === 0) return [full];
2743
- const bare = s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".");
2744
- return [full, bare];
2745
- }
2746
- resolveConcat(nodes, scope, line = 0, col = 0) {
2747
- const rawResolved = nodes.map((n) => this.resolveVal(n, scope));
2748
- if (this.opts.allowUnresolved) {
2749
- for (const v of rawResolved) {
2750
- if (v !== void 0 && isSubst(v)) {
2751
- return v;
2752
- }
2753
- }
2754
- }
2755
- const resolved = rawResolved.filter((v) => v !== void 0);
2756
- if (resolved.length === 0) return void 0;
2757
- if (resolved.length === 1) return resolved[0];
2758
- const nonSep = resolved.filter((v) => !separatorValues.has(v));
2759
- if (nonSep.length === 0) {
2760
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
2761
- return { kind: "scalar", raw: str, valueType: "string" };
2762
- }
2763
- const joinPair = (left, right) => {
2764
- if (left.kind === "object" && right.kind === "object") {
2765
- return deepMergeHoconValues(left, right);
2766
- }
2767
- if (left.kind === "array" && right.kind === "object") {
2768
- const converted = numericObjectToArray(right);
2769
- if (converted !== null) {
2770
- return { kind: "array", items: [...left.items, ...converted] };
2771
- }
2772
- throw new ResolveError(
2773
- "cannot concatenate array with object: value concatenation requires same-kind operands (S10.4)",
2774
- "",
2775
- line,
2776
- col
2777
- );
2778
- }
2779
- if (left.kind === "object" && right.kind === "array") {
2780
- const converted = numericObjectToArray(left);
2781
- if (converted !== null) {
2782
- return { kind: "array", items: [...converted, ...right.items] };
2783
- }
2784
- throw new ResolveError(
2785
- "cannot concatenate object with array: value concatenation requires same-kind operands (S10.4)",
2786
- "",
2787
- line,
2788
- col
2789
- );
2790
- }
2791
- if (left.kind === "array" && right.kind === "array") {
2792
- return { kind: "array", items: [...left.items, ...right.items] };
2793
- }
2794
- if (left.kind === "array" || right.kind === "array") {
2795
- throw new ResolveError(
2796
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
2797
- "",
2798
- line,
2799
- col
2800
- );
2801
- }
2802
- if (left.kind === "object" || right.kind === "object") {
2803
- throw new ResolveError(
2804
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
2805
- "",
2806
- line,
2807
- col
2808
- );
2809
- }
2810
- return { kind: "scalar", raw: left.raw + right.raw, valueType: "string" };
2811
- };
2812
- const [head, ...tail] = nonSep;
2813
- const folded = tail.reduce(joinPair, head);
2814
- if (folded.kind === "scalar") {
2815
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
2816
- return { kind: "scalar", raw: str, valueType: "string" };
2817
- }
2818
- return folded;
2819
- }
2820
- };
2821
-
2822
- // src/internal/resolver/resolver.ts
2823
- function buildTree(ast, opts) {
2824
- return new StructureBuilder(opts).build(ast);
2825
- }
2826
- function resolveTree(tree, opts) {
2827
- return new SubstitutionResolver(tree, opts).resolve();
2828
- }
2829
- function containsPlaceholders(tree) {
2830
- for (const val of tree.fields.values()) {
2831
- if (valContainsPlaceholders(val)) return true;
2832
- }
2833
- return false;
2834
- }
2835
- function valContainsPlaceholders(v) {
2836
- const rv = v;
2837
- if (isSubst(rv) || isConcat(rv)) return true;
2838
- if (isResObj(rv)) return containsPlaceholders(rv);
2839
- const hv = v;
2840
- if (hv?.kind === "array") {
2841
- return hv.items.some((item) => valContainsPlaceholders(item));
2842
- }
2843
- return false;
2844
- }
2845
- function buildPartialHoconFromResObj(tree) {
2846
- const fields = /* @__PURE__ */ new Map();
2847
- for (const [k, v] of tree.fields) {
2848
- if (!isSubst(v) && !isConcat(v)) {
2849
- if (isResObj(v)) {
2850
- fields.set(k, buildPartialHoconFromResObj(v));
2851
- } else {
2852
- if (!valContainsPlaceholders(v)) {
2853
- fields.set(k, v);
2854
- }
2855
- }
2856
- }
2857
- }
2858
- return { kind: "object", fields };
2859
- }
2860
- function hoconValueToResObj2(value) {
2861
- const obj = makeResObj();
2862
- for (const [k, v] of value.fields) {
2863
- if (v.kind === "object") {
2864
- obj.fields.set(k, hoconValueToResObj2(v));
2865
- } else {
2866
- obj.fields.set(k, v);
2867
- }
2868
- }
2869
- return obj;
2870
- }
2871
- function resolve2(ast, opts) {
2872
- const tree = buildTree(ast, opts);
2873
- return resolveTree(tree, { ...opts, useSystemEnvironment: true, allowUnresolved: false });
2874
- }
2875
- async function resolveAsync(ast, opts) {
2876
- const root = await new StructureBuilder(opts).buildAsync(ast);
2877
- return resolveTree(root, { ...opts, useSystemEnvironment: true, allowUnresolved: false });
2878
- }
2879
-
2880
- // src/render-hocon.ts
2881
- function renderHoconFromRoot(root) {
2882
- const out = [];
2883
- renderObjectBody(out, root, 0);
2884
- return out.join("");
2885
- }
2886
- function renderObjectBody(out, o, depth) {
2887
- const indent = " ".repeat(depth);
2888
- for (const [k, v] of o.fields) {
2889
- out.push(indent, renderKey(k));
2890
- if (v.kind === "object") {
2891
- out.push(" {");
2892
- if (v.fields.size === 0) {
2893
- out.push("}\n");
2894
- continue;
2895
- }
2896
- out.push("\n");
2897
- renderObjectBody(out, v, depth + 1);
2898
- out.push(indent, "}\n");
2899
- } else {
2900
- out.push(" = ");
2901
- renderValue(out, v, depth);
2902
- out.push("\n");
2903
- }
2904
- }
2905
- }
2906
- function renderValue(out, v, depth) {
2907
- switch (v.kind) {
2908
- case "object": {
2909
- if (v.fields.size === 0) {
2910
- out.push("{}");
2911
- return;
2912
- }
2913
- out.push("{\n");
2914
- renderObjectBody(out, v, depth + 1);
2915
- out.push(" ".repeat(depth), "}");
2916
- return;
2917
- }
2918
- case "array":
2919
- renderArray(out, v, depth);
2920
- return;
2921
- case "scalar":
2922
- out.push(renderScalar(v));
2923
- return;
2924
- default:
2925
- throw new ConfigError(
2926
- "renderHocon: unrenderable value (config must be resolved data)",
2927
- ""
2928
- );
2929
- }
2930
- }
2931
- function renderArray(out, a, depth) {
2932
- if (a.items.length === 0) {
2933
- out.push("[]");
2934
- return;
2935
- }
2936
- const inner = " ".repeat(depth + 1);
2937
- out.push("[\n");
2938
- for (const e of a.items) {
2939
- out.push(inner);
2940
- renderValue(out, e, depth + 1);
2941
- out.push("\n");
2942
- }
2943
- out.push(" ".repeat(depth), "]");
2944
- }
2945
- function renderScalar(s) {
2946
- switch (s.valueType) {
2947
- case "null":
2948
- return "null";
2949
- case "boolean":
2950
- case "number":
2951
- return s.raw;
2952
- case "string":
2953
- return renderString(s.raw);
2954
- }
2955
- }
2956
- var SAFE_UNQUOTED_KEY = /^[A-Za-z0-9_-]+$/;
2957
- function renderKey(k) {
2958
- if (k === "include") return quoteString(k);
2959
- return SAFE_UNQUOTED_KEY.test(k) ? k : quoteString(k);
2960
- }
2961
- var SAFE_BARE_STRING = /^[A-Za-z][A-Za-z0-9_-]*$/;
2962
- var STRING_KEYWORDS = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off"]);
2963
- function renderString(s) {
2964
- return SAFE_BARE_STRING.test(s) && !STRING_KEYWORDS.has(s.toLowerCase()) ? s : quoteString(s);
2965
- }
2966
- function quoteString(s) {
2967
- if (s.includes("\n") && !s.includes("\r") && !s.includes('"""') && !s.endsWith('"')) {
2968
- return `"""${s}"""`;
2969
- }
2970
- let b = '"';
2971
- for (const ch of s) {
2972
- switch (ch) {
2973
- case '"':
2974
- b += '\\"';
2975
- break;
2976
- case "\\":
2977
- b += "\\\\";
2978
- break;
2979
- case "\n":
2980
- b += "\\n";
2981
- break;
2982
- case "\r":
2983
- b += "\\r";
2984
- break;
2985
- case " ":
2986
- b += "\\t";
2987
- break;
2988
- default:
2989
- b += ch;
2990
- }
2991
- }
2992
- return b + '"';
2993
- }
2994
-
2995
- // src/config.ts
2996
- var Config = class _Config {
2997
- constructor(root, opts) {
2998
- this.root = root;
2999
- this._resolved = opts?.resolved ?? true;
3000
- this._parseBaseDir = opts?.parseBaseDir;
3001
- this._originDescription = opts?.originDescription;
3002
- this._resObjRoot = opts?.resObjRoot;
3003
- this._resolveOpts = opts?.resolveOpts;
3004
- }
3005
- /** Returns true when the Config's value tree contains no unresolved
3006
- * substitution placeholders. Whole-config granularity (E12 decision 11). */
3007
- isResolved() {
3008
- return this._resolved;
3009
- }
3010
- /** @internal Test-only: construct a resolved Config from a HoconValue. */
3011
- static _fromResolvedValue(root, opts) {
3012
- return new _Config(root, { resolved: true, originDescription: opts?.originDescription });
3013
- }
3014
- /** @internal Construct an unresolved Config carrying a ResObj tree.
3015
- * Used by parseStringWithOptions (deferred path) in T6. */
3016
- static _fromUnresolvedResObj(tree, opts) {
3017
- const partialRoot = buildPartialHoconFromResObj(tree);
3018
- return new _Config(partialRoot, {
3019
- resolved: opts.resolved,
3020
- parseBaseDir: opts.parseBaseDir,
3021
- originDescription: opts.originDescription,
3022
- resObjRoot: tree,
3023
- resolveOpts: opts.resolveOpts
3024
- });
3025
- }
3026
- get(path2) {
3027
- const v = this.lookupNode(path2);
3028
- if (v === void 0) return void 0;
3029
- return hoconToJs(v);
3030
- }
3031
- /**
3032
- * Returns the raw {@link HoconValue} node at `path` as a deeply-immutable
3033
- * {@link ReadonlyHoconValue} view, or `undefined` if the path is absent. Unlike
3034
- * `get` (which decodes to a plain JS value), this exposes the value tree for
3035
- * structural introspection via the `value.ts` accessors (`asString`, `asObject`,
3036
- * `isScalar`, …).
3037
- *
3038
- * `getValue('')` returns the root object node.
3039
- *
3040
- * Throws {@link NotResolvedError} when the node (or its subtree) is unresolved:
3041
- * the `HoconValue` union has no placeholder variant, so an unresolved value
3042
- * cannot be represented. This matches `getConfig` / `getList`.
3043
- */
3044
- getValue(path2) {
3045
- const v = this.lookupNode(path2);
3046
- if (v === void 0) {
3047
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3048
- throw new NotResolvedError(path2);
3049
- }
3050
- return void 0;
3051
- }
3052
- if (v.kind !== "scalar" && !this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3053
- throw new NotResolvedError(path2);
3054
- }
3055
- return v;
3056
- }
3057
- getString(path2) {
3058
- const v = this.requireScalar(path2);
3059
- if (v.valueType === "null") {
3060
- throw new ConfigError(`expected string at ${path2}, got ${v.valueType}`, path2);
3061
- }
3062
- return v.raw;
3063
- }
3064
- getNumber(path2) {
3065
- const v = this.requireScalar(path2);
3066
- const coerced = coerceNumber(v.raw);
3067
- if (coerced !== void 0) return coerced;
3068
- throw new ConfigError(`expected number at ${path2}, got ${v.valueType}`, path2);
3069
- }
3070
- getBoolean(path2) {
3071
- const v = this.requireScalar(path2);
3072
- const coerced = coerceBoolean(v.raw);
3073
- if (coerced !== void 0) return coerced;
3074
- throw new ConfigError(`expected boolean at ${path2}, got ${v.valueType}`, path2);
3075
- }
3076
- getDuration(path2, unit) {
3077
- const v = this.requireScalar(path2);
3078
- if (v.valueType !== "string" && v.valueType !== "number") {
3079
- throw new ConfigError(`expected duration at ${path2}, got ${v.valueType}`, path2);
3080
- }
3081
- const result = parseDuration(v.raw, unit);
3082
- if (Number.isNaN(result)) throw new ConfigError(`invalid duration at ${path2}: ${JSON.stringify(v.raw)}`, path2);
3083
- return result;
3084
- }
3085
- getBytes(path2, unit) {
3086
- const v = this.requireScalar(path2);
3087
- if (v.valueType !== "string" && v.valueType !== "number") {
3088
- throw new ConfigError(`expected byte size at ${path2}, got ${v.valueType}`, path2);
3089
- }
3090
- const result = parseBytes(v.raw, unit);
3091
- if (Number.isNaN(result)) throw new ConfigError(`invalid byte size at ${path2}: ${JSON.stringify(v.raw)}`, path2);
3092
- if (result < 0) throw new ConfigError(`byte size must be non-negative at ${path2}: ${JSON.stringify(v.raw)}`, path2);
3093
- return result;
3094
- }
3095
- getConfig(path2) {
3096
- const v = this.lookupNode(path2);
3097
- if (v === void 0) {
3098
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3099
- throw new NotResolvedError(path2);
3100
- }
3101
- throw new ConfigError(`path not found: ${path2}`, path2);
3102
- }
3103
- if (v.kind !== "object") throw new ConfigError(`expected object at ${path2}`, path2);
3104
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3105
- throw new NotResolvedError(path2);
3106
- }
3107
- return new _Config(v, { resolved: this._resolved });
3108
- }
3109
- getList(path2) {
3110
- const v = this.lookupNode(path2);
3111
- if (v === void 0) {
3112
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3113
- throw new NotResolvedError(path2);
3114
- }
3115
- throw new ConfigError(`path not found: ${path2}`, path2);
3116
- }
3117
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3118
- throw new NotResolvedError(path2);
3119
- }
3120
- if (v.kind === "object") {
3121
- const converted = numericObjectToArray(v);
3122
- if (converted !== null) return converted.map((item) => hoconToJs(item));
3123
- }
3124
- if (v.kind !== "array") throw new ConfigError(`expected array at ${path2}`, path2);
3125
- return v.items.map((item) => hoconToJs(item));
3126
- }
3127
- has(path2) {
3128
- return this.lookupNode(path2) !== void 0;
3129
- }
3130
- keys() {
3131
- return [...this.root.fields.keys()];
3132
- }
3133
- withFallback(fallback) {
3134
- if (fallback == null) return this;
3135
- const selfTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
3136
- const fbTree = fallback._resObjRoot ?? hoconValueToResObj2(fallback.root);
3137
- const merged = mergeUnresolved(selfTree, fbTree);
3138
- const hasPlaceholders = containsPlaceholders(merged);
3139
- const partialRoot = buildPartialHoconFromResObj(merged);
3140
- return new _Config(partialRoot, {
3141
- resolved: !hasPlaceholders,
3142
- parseBaseDir: this._parseBaseDir,
3143
- originDescription: this._originDescription,
3144
- resObjRoot: merged,
3145
- resolveOpts: this._resolveOpts ?? fallback._resolveOpts
3146
- });
3147
- }
3148
- /**
3149
- * Runs substitution resolution (phase 2) on the stored unresolved tree.
3150
- * Idempotent: calling resolve() on an already-resolved Config returns an
3151
- * equivalent resolved Config.
3152
- *
3153
- * opts.allowUnresolved (default false) — when true, leaves unresolved
3154
- * non-optional placeholders in place rather than throwing.
3155
- * opts.useSystemEnvironment (default true) — when false, env var lookups
3156
- * are suppressed (hermetic resolution).
3157
- *
3158
- * E12 decision 3.
3159
- */
3160
- resolve(opts = {}) {
3161
- if (this._resolved) {
3162
- return new _Config(this.root, {
3163
- resolved: true,
3164
- parseBaseDir: this._parseBaseDir,
3165
- originDescription: this._originDescription
3166
- });
3167
- }
3168
- const tree = this._resObjRoot;
3169
- if (!tree) {
3170
- return new _Config(this.root, { resolved: true });
3171
- }
3172
- const resolveOpts = {
3173
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
3174
- throw new Error("no files");
3175
- } },
3176
- allowUnresolved: opts.allowUnresolved ?? false,
3177
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
3178
- originDescription: this._originDescription
3179
- };
3180
- const resolved = resolveTree(tree, resolveOpts);
3181
- if (resolved.kind !== "object") throw new Error("resolve: expected object root");
3182
- if (opts.allowUnresolved) {
3183
- const { stripped, hadPlaceholders } = stripPlaceholderFields(resolved);
3184
- return new _Config(stripped, {
3185
- resolved: !hadPlaceholders,
3186
- parseBaseDir: this._parseBaseDir,
3187
- originDescription: this._originDescription,
3188
- resObjRoot: hadPlaceholders ? tree : void 0,
3189
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
3190
- });
3191
- }
3192
- return new _Config(resolved, {
3193
- resolved: true,
3194
- parseBaseDir: this._parseBaseDir,
3195
- originDescription: this._originDescription
3196
- });
3197
- }
3198
- /**
3199
- * Resolves receiver substitutions using source as lookup context.
3200
- * Source's keys are NOT merged into the result — differs from
3201
- * `this.withFallback(source).resolve()` which includes source keys.
3202
- *
3203
- * Precondition (E12 decision 10): source must be resolved. If
3204
- * source.isResolved() is false, throws NotResolvedError.
3205
- *
3206
- * On an already-resolved receiver, resolveWith is a no-op (returns an
3207
- * equivalent resolved Config, source keys not included).
3208
- *
3209
- * E12 decisions 9, 10.
3210
- */
3211
- resolveWith(source, opts = {}) {
3212
- if (!source.isResolved()) {
3213
- throw new NotResolvedError("source");
3214
- }
3215
- if (this._resolved) {
3216
- return new _Config(this.root, {
3217
- resolved: true,
3218
- parseBaseDir: this._parseBaseDir,
3219
- originDescription: this._originDescription
3220
- });
3221
- }
3222
- const receiverTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
3223
- const srcTree = hoconValueToResObj2(source.root);
3224
- const merged = mergeUnresolved(receiverTree, srcTree);
3225
- const resolveOpts = {
3226
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
3227
- throw new Error("no files");
3228
- } },
3229
- allowUnresolved: opts.allowUnresolved ?? false,
3230
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
3231
- originDescription: this._originDescription
3232
- };
3233
- const resolved = resolveTree(merged, resolveOpts);
3234
- if (resolved.kind !== "object") throw new Error("resolveWith: expected object root");
3235
- const receiverShapeForFilter = resObjToKeyShape(receiverTree);
3236
- const filtered = filterByReceiverShape(resolved, receiverShapeForFilter);
3237
- if (opts.allowUnresolved) {
3238
- const { stripped, hadPlaceholders } = stripPlaceholderFields(filtered);
3239
- return new _Config(stripped, {
3240
- resolved: !hadPlaceholders,
3241
- parseBaseDir: this._parseBaseDir,
3242
- originDescription: this._originDescription,
3243
- resObjRoot: hadPlaceholders ? receiverTree : void 0,
3244
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
3245
- });
3246
- }
3247
- return new _Config(filtered, {
3248
- resolved: true,
3249
- parseBaseDir: this._parseBaseDir,
3250
- originDescription: this._originDescription
3251
- });
3252
- }
3253
- /**
3254
- * The whole config as plain JS data: objects, arrays, strings, numbers,
3255
- * booleans and `null`.
3256
- *
3257
- * Keys are reproduced exactly as the config carries them, `__proto__`,
3258
- * `constructor` and `prototype` included: each is defined as an **own data
3259
- * property**, so the returned object's prototype is always
3260
- * `Object.prototype`, and this call writes nothing to the global one.
3261
- *
3262
- * ### Passing the result to other code
3263
- *
3264
- * A config file — especially a `.properties` file or an env namespace you
3265
- * merged in — can therefore hand you an own `__proto__` key, and what happens
3266
- * next depends entirely on how the consumer copies it:
3267
- *
3268
- * ```ts
3269
- * const data = cfg.toObject()
3270
- * { ...data } // safe — own properties are copied as data
3271
- * structuredClone(data) // safe
3272
- * Object.assign({}, data) // NOT safe — [[Set]] on the {} target hits
3273
- * // Object.prototype's __proto__ setter: the key
3274
- * // vanishes and config data becomes the result's
3275
- * // prototype
3276
- * deepMerge({}, data) // NOT safe — a naive recursive merge reads
3277
- * // target['__proto__'], gets Object.prototype,
3278
- * // and writes to it: global pollution
3279
- * for (const k in data) … // prefer Object.entries / Object.keys
3280
- * ```
3281
- *
3282
- * Those two hazards come from the **destination** object's prototype, so no
3283
- * option here can disarm them — copy with spread or `structuredClone` instead.
3284
- *
3285
- * What `{ nullPrototype: true }` does give you is a result that inherits
3286
- * nothing: every object comes back with a `null` prototype, so reading
3287
- * `x.__proto__`, `x.constructor` or `x.toString` yields config data or
3288
- * `undefined` rather than something from `Object.prototype`, and code that
3289
- * merges *into* this object cannot climb out of it. Keys are all still
3290
- * present. The trade-off is the usual one for prototype-less objects: not
3291
- * `instanceof Object`, and no `hasOwnProperty` of their own.
3292
- *
3293
- * Numbers follow the JS number model, so an integer wider than 2^53 rounds
3294
- * here even when the config holds it exactly — read those with
3295
- * {@link Config.getString} instead.
3296
- */
3297
- toObject(opts) {
3298
- return hoconToJs(this.root, opts?.nullPrototype === true);
3299
- }
3300
- /**
3301
- * Renders this resolved Config as HOCON text (E18; lockstep with go.hocon's
3302
- * `Config.RenderHOCON`, v1.11.0).
3303
- *
3304
- * The output round-trips: parsing it back yields the same value tree. That
3305
- * is the correctness contract, not byte-for-byte formatting — a scalar is
3306
- * quoted whenever leaving it bare would re-parse as a different type (a
3307
- * string `"8080"` becomes `"8080"`, not `8080`), and left bare only when it
3308
- * provably cannot.
3309
- *
3310
- * The Config must be resolved and hold only data (objects, arrays, string /
3311
- * number / boolean / null scalars) — exactly what {@link fromMap} and the
3312
- * format adapters produce. An unresolved placeholder throws
3313
- * {@link ConfigError}; substitutions have no textual round trip through a
3314
- * value tree.
3315
- *
3316
- * The root object's fields are emitted without enclosing braces, nested
3317
- * objects as `key { … }`, arrays as newline-separated `[ … ]`, indented two
3318
- * spaces. Source comments are not represented — a value tree does not carry
3319
- * them.
3320
- */
3321
- renderHocon() {
3322
- if (!this._resolved) {
3323
- throw new ConfigError(
3324
- "renderHocon: unrenderable unresolved substitution (config must be resolved data)",
3325
- ""
3326
- );
3327
- }
3328
- return renderHoconFromRoot(this.root);
3329
- }
3330
- /**
3331
- * @internal Test-only: renders this resolved Config's value tree as canonical
3332
- * JSON (sorted keys, no whitespace). Used by Layer-2 fixture tests to compare
3333
- * against Lightbend ground truth. NOT part of the public API.
3334
- *
3335
- * Throws if the Config is unresolved (contains placeholders).
3336
- */
3337
- _renderJSONForTest() {
3338
- return renderHoconAsJSON(this.root);
3339
- }
3340
- lookupNode(path2) {
3341
- const segments = splitConfigPath(path2);
3342
- let current = this.root;
3343
- for (const seg of segments) {
3344
- if (current.kind !== "object") return void 0;
3345
- const next = current.fields.get(seg);
3346
- if (next === void 0) return void 0;
3347
- current = next;
3348
- }
3349
- return current;
3350
- }
3351
- /**
3352
- * _resObjRootSubtreeHasPlaceholders — walk _resObjRoot to the given path and
3353
- * return true if the subtree there contains any unresolved placeholder.
3354
- * Used by getConfig / getList (T2) to detect transitive unresolved placeholders
3355
- * in object / array subtrees that would otherwise appear to be "resolved" in the
3356
- * partial HoconValue root (because individual leaf fields are omitted rather than
3357
- * the whole subtree when their value is a direct placeholder scalar, but object
3358
- * sub-containers are retained in the partial root with the placeholder-keyed
3359
- * fields omitted from them — so the object appears "present but empty-ish").
3360
- */
3361
- _resObjRootSubtreeHasPlaceholders(path2) {
3362
- const tree = this._resObjRoot;
3363
- if (!tree) return false;
3364
- const segments = splitConfigPath(path2);
3365
- let cur = tree;
3366
- for (const seg of segments) {
3367
- const val = cur.fields.get(seg);
3368
- if (val === void 0) return false;
3369
- if (isResObj(val)) {
3370
- cur = val;
3371
- } else {
3372
- return valContainsPlaceholders(val);
3373
- }
3374
- }
3375
- return containsPlaceholders(cur);
3376
- }
3377
- requireScalar(path2) {
3378
- const v = this.lookupNode(path2);
3379
- if (v === void 0) {
3380
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3381
- throw new NotResolvedError(path2);
3382
- }
3383
- throw new ConfigError(`path not found: ${path2}`, path2);
3384
- }
3385
- if (v.kind !== "scalar") throw new ConfigError(`expected scalar at ${path2}, got ${v.kind}`, path2);
3386
- return v;
3387
- }
3388
- };
3389
- function splitConfigPath(path2) {
3390
- const segments = [];
3391
- let i = 0;
3392
- while (i < path2.length) {
3393
- if (path2[i] === '"') {
3394
- i++;
3395
- let segment = "";
3396
- let closed = false;
3397
- while (i < path2.length) {
3398
- const ch = path2[i];
3399
- if (ch === "\\" && i + 1 < path2.length) {
3400
- const next = path2[i + 1];
3401
- segment += next;
3402
- i += 2;
3403
- continue;
3404
- }
3405
- if (ch === '"') {
3406
- closed = true;
3407
- i++;
3408
- break;
3409
- }
3410
- segment += ch;
3411
- i++;
3412
- }
3413
- if (!closed) throw new ConfigError(`unterminated quoted path segment: ${path2}`, path2);
3414
- segments.push(segment);
3415
- if (i < path2.length && path2[i] === ".") i++;
3416
- } else {
3417
- const dot = path2.indexOf(".", i);
3418
- if (dot === -1) {
3419
- segments.push(path2.slice(i));
3420
- break;
3421
- }
3422
- segments.push(path2.slice(i, dot));
3423
- i = dot + 1;
3424
- }
3425
- }
3426
- return segments;
3427
- }
3428
- function scalarToJs(raw, valueType) {
3429
- switch (valueType) {
3430
- case "null":
3431
- return null;
3432
- case "boolean":
3433
- return raw === "true";
3434
- case "number":
3435
- return Number(raw);
3436
- case "string":
3437
- return raw;
3438
- }
3439
- }
3440
- function hoconToJs(v, nullPrototype = false) {
3441
- switch (v.kind) {
3442
- case "scalar":
3443
- return scalarToJs(v.raw, v.valueType);
3444
- case "array":
3445
- return v.items.map((item) => hoconToJs(item, nullPrototype));
3446
- case "object": {
3447
- const entries = Array.from(v.fields, ([k, val]) => [k, hoconToJs(val, nullPrototype)]);
3448
- if (nullPrototype) {
3449
- const obj = /* @__PURE__ */ Object.create(null);
3450
- for (const [k, val] of entries) Object.defineProperty(obj, k, {
3451
- value: val,
3452
- writable: true,
3453
- enumerable: true,
3454
- configurable: true
3455
- });
3456
- return obj;
3457
- }
3458
- return Object.fromEntries(entries);
3459
- }
3460
- }
3461
- }
3462
- function resObjToKeyShape(tree) {
3463
- const fields = /* @__PURE__ */ new Map();
3464
- for (const [k, v] of tree.fields) {
3465
- if (isSubst(v) || isConcat(v)) {
3466
- fields.set(k, { kind: "scalar", raw: "", valueType: "null" });
3467
- } else if (isResObj(v)) {
3468
- fields.set(k, resObjToKeyShape(v));
3469
- } else {
3470
- fields.set(k, v);
3471
- }
3472
- }
3473
- return { kind: "object", fields };
3474
- }
3475
- function stripPlaceholderFields(v) {
3476
- const fields = /* @__PURE__ */ new Map();
3477
- let hadPlaceholders = false;
3478
- for (const [k, val] of v.fields) {
3479
- if (val._kind === "subst-placeholder" || val._kind === "concat-placeholder") {
3480
- hadPlaceholders = true;
3481
- } else if (val.kind === "object") {
3482
- const inner = stripPlaceholderFields(val);
3483
- if (inner.hadPlaceholders) hadPlaceholders = true;
3484
- fields.set(k, inner.stripped);
3485
- } else {
3486
- fields.set(k, val);
3487
- }
3488
- }
3489
- return { stripped: { kind: "object", fields }, hadPlaceholders };
3490
- }
3491
- function filterByReceiverShape(resolved, receiverShape) {
3492
- const fields = /* @__PURE__ */ new Map();
3493
- for (const [k, rv] of resolved.fields) {
3494
- if (!receiverShape.fields.has(k)) continue;
3495
- const receiverVal = receiverShape.fields.get(k);
3496
- if (rv.kind === "object" && receiverVal.kind === "object") {
3497
- fields.set(k, filterByReceiverShape(rv, receiverVal));
3498
- } else {
3499
- fields.set(k, rv);
3500
- }
3501
- }
3502
- return { kind: "object", fields };
3503
- }
3504
- function renderHoconAsJSON(v) {
3505
- switch (v.kind) {
3506
- case "scalar": {
3507
- switch (v.valueType) {
3508
- case "null":
3509
- return "null";
3510
- case "boolean":
3511
- return v.raw;
3512
- case "number": {
3513
- const norm = normalizeLeadingZeroNumber(v.raw);
3514
- return JSON_NUMBER_RE.test(norm) ? norm : JSON.stringify(v.raw);
3515
- }
3516
- case "string":
3517
- return JSON.stringify(v.raw);
3518
- }
3519
- break;
3520
- }
3521
- case "array": {
3522
- const items = v.items.map(renderHoconAsJSON);
3523
- return `[${items.join(",")}]`;
3524
- }
3525
- case "object": {
3526
- const keys = [...v.fields.keys()].sort();
3527
- const pairs = keys.map((k) => {
3528
- const val = v.fields.get(k);
3529
- return `${JSON.stringify(k)}:${renderHoconAsJSON(val)}`;
3530
- });
3531
- return `{${pairs.join(",")}}`;
3532
- }
3533
- }
3534
- throw new Error(`renderHoconAsJSON: unsupported value kind (unresolved placeholder?)`);
3535
- }
3536
- var JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
3537
- function normalizeLeadingZeroNumber(raw) {
3538
- return raw.replace(/^([+-]?)0+(\d)/, "$1$2");
3539
- }
3540
-
3541
- // src/parse.ts
3542
- import * as fs from "fs";
3543
- import * as path from "path";
3544
- function defaultParseOptions() {
3545
- return { resolveSubstitutions: true };
3546
- }
3547
- function defaultResolveOptions() {
3548
- return { useSystemEnvironment: true, allowUnresolved: false };
3549
- }
3550
- function getEnv(opts) {
3551
- if (opts.env !== void 0) return opts.env;
3552
- if (typeof process !== "undefined" && process.env) return process.env;
3553
- return {};
3554
- }
3555
- function defaultReadFileSync(filePath) {
3556
- return fs.readFileSync(filePath, "utf-8");
3557
- }
3558
- async function defaultReadFile(filePath) {
3559
- return fs.promises.readFile(filePath, "utf-8");
3560
- }
3561
- function buildResolveContext(input, opts) {
3562
- const tokens = tokenize(input);
3563
- const ast = parseTokens(tokens);
3564
- if (ast.kind === "array") {
3565
- const origin = opts.originDescription ?? "input";
3566
- throw new ConfigError(
3567
- `${origin}: ${ast.pos.line}:${ast.pos.col}: document has type array rather than object at file root (HOCON.md L989-991); the Config API requires an object root`,
3568
- ""
3569
- );
3570
- }
3571
- const resolveOpts = {
3572
- env: getEnv(opts),
3573
- baseDir: opts.baseDir,
3574
- readFileSync: opts.readFileSync ?? defaultReadFileSync,
3575
- readFile: opts.readFile,
3576
- originDescription: opts.originDescription,
3577
- resolveFrom: opts.resolveFrom,
3578
- packageResolver: opts.packageResolver
3579
- };
3580
- return { ast, resolveOpts };
3581
- }
3582
- function parse(input, opts = {}) {
3583
- return parseStringWithOptions(input, opts);
3584
- }
3585
- var parseString = parse;
3586
- function parseStringWithOptions(input, opts = {}) {
3587
- return guardStackDepth(
3588
- () => parseStringInner(input, opts),
3589
- (msg) => new ParseError(msg, 1, 1, opts.originDescription)
3590
- );
3591
- }
3592
- function parseStringInner(input, opts) {
3593
- const resolveSubstitutions = opts.resolveSubstitutions ?? true;
3594
- const { ast, resolveOpts } = buildResolveContext(input, opts);
3595
- if (resolveSubstitutions) {
3596
- const value = resolve2(ast, resolveOpts);
3597
- if (value.kind !== "object") throw new Error("resolved value is not an object");
3598
- return new Config(value, { resolved: true, originDescription: opts.originDescription });
3599
- }
3600
- const tree = buildTree(ast, resolveOpts);
3601
- const hasPlaceholders = containsPlaceholders(tree);
3602
- return Config._fromUnresolvedResObj(tree, {
3603
- parseBaseDir: opts.baseDir,
3604
- originDescription: opts.originDescription,
3605
- resolved: !hasPlaceholders,
3606
- resolveOpts
3607
- });
3608
- }
3609
- function parseFileWithOptions(filePath, opts = {}) {
3610
- if (typeof process === "undefined" && !opts.readFileSync) {
3611
- throw new Error("parseFileWithOptions is not supported in browser environments without opts.readFileSync.");
3612
- }
3613
- const resolvedPath = path.resolve(filePath);
3614
- const readFileSync2 = opts.readFileSync ?? defaultReadFileSync;
3615
- const input = readFileSync2(resolvedPath);
3616
- return parseStringWithOptions(input, {
3617
- ...opts,
3618
- baseDir: opts.baseDir ?? path.dirname(resolvedPath),
3619
- readFileSync: readFileSync2
3620
- });
3621
- }
3622
- async function parseAsync(input, opts = {}) {
3623
- return guardStackDepthAsync(async () => {
3624
- const { ast, resolveOpts } = buildResolveContext(input, opts);
3625
- const value = await resolveAsync(ast, resolveOpts);
3626
- if (value.kind !== "object") throw new Error("resolved value is not an object");
3627
- return new Config(value);
3628
- }, (msg) => new ParseError(msg, 1, 1, opts.originDescription));
3629
- }
3630
- function parseFile(filePath, opts = {}) {
3631
- if (typeof process === "undefined" && !opts.readFileSync) {
3632
- throw new Error("parseFile is not supported in browser environments. Provide opts.readFileSync or use parse() instead.");
3633
- }
3634
- const resolvedPath = path.resolve(filePath);
3635
- const readFileSync2 = opts.readFileSync ?? defaultReadFileSync;
3636
- const input = readFileSync2(resolvedPath);
3637
- return parse(input, {
3638
- ...opts,
3639
- baseDir: opts.baseDir ?? path.dirname(resolvedPath),
3640
- readFileSync: readFileSync2
3641
- });
3642
- }
3643
- async function parseFileAsync(filePath, opts = {}) {
3644
- if (typeof process === "undefined" && !opts.readFile) {
3645
- throw new Error("parseFileAsync is not supported in browser environments. Provide opts.readFile or use parseAsync() instead.");
3646
- }
3647
- const resolvedPath = path.resolve(filePath);
3648
- const readFile = opts.readFile ?? defaultReadFile;
3649
- const input = await readFile(resolvedPath);
3650
- return parseAsync(input, {
3651
- ...opts,
3652
- baseDir: opts.baseDir ?? path.dirname(resolvedPath),
3653
- readFile,
3654
- readFileSync: opts.readFileSync ?? defaultReadFileSync
3655
- });
3656
- }
1
+ import {
2
+ defaultParseOptions,
3
+ defaultResolveOptions,
4
+ parse,
5
+ parseAsync,
6
+ parseFile,
7
+ parseFileAsync,
8
+ parseFileWithOptions,
9
+ parseString,
10
+ parseStringWithOptions
11
+ } from "./chunk-XWKO4JM3.js";
12
+ import {
13
+ empty,
14
+ fromMap
15
+ } from "./chunk-QY7ECGS6.js";
16
+ import {
17
+ Config,
18
+ ConfigError,
19
+ NotResolvedError,
20
+ PackageLookupError,
21
+ ParseError,
22
+ ResolveError,
23
+ coerceBoolean,
24
+ coerceNumber
25
+ } from "./chunk-WTXULUZS.js";
3657
26
 
3658
27
  // src/value.ts
3659
28
  function asString(v) {
@@ -3683,78 +52,6 @@ function isScalar(v) {
3683
52
  function isNull(v) {
3684
53
  return v.kind === "scalar" && v.valueType === "null";
3685
54
  }
3686
-
3687
- // src/value-factory.ts
3688
- function fromMap(values, originDescription) {
3689
- const fields = guardStackDepth(
3690
- () => coerceObject(values, ""),
3691
- (msg) => depthError(`fromMap: ${msg}`)
3692
- );
3693
- const root = { kind: "object", fields };
3694
- return Config._fromResolvedValue(root, { originDescription });
3695
- }
3696
- function empty(originDescription) {
3697
- const root = { kind: "object", fields: /* @__PURE__ */ new Map() };
3698
- return Config._fromResolvedValue(root, { originDescription });
3699
- }
3700
- var INT64_MAX = 9223372036854775807n;
3701
- var INT64_MIN = -9223372036854775808n;
3702
- function coerceObject(obj, atPath) {
3703
- const fields = /* @__PURE__ */ new Map();
3704
- for (const [k, v] of Object.entries(obj)) {
3705
- const childPath = atPath ? `${atPath}.${k}` : k;
3706
- fields.set(k, coerceValue(v, childPath));
3707
- }
3708
- return fields;
3709
- }
3710
- function coerceValue(v, atPath) {
3711
- if (v === null) {
3712
- return { kind: "scalar", raw: "null", valueType: "null" };
3713
- }
3714
- if (v === void 0) {
3715
- throw new ConfigError(
3716
- `fromMap: undefined is not a valid HOCON value at path "${atPath}"`,
3717
- atPath
3718
- );
3719
- }
3720
- switch (typeof v) {
3721
- case "string":
3722
- return { kind: "scalar", raw: v, valueType: "string" };
3723
- case "number": {
3724
- if (Number.isNaN(v) || !Number.isFinite(v)) {
3725
- throw new ConfigError(
3726
- `fromMap: ${v} is not representable in HOCON (NaN/Infinity not allowed) at path "${atPath}"`,
3727
- atPath
3728
- );
3729
- }
3730
- return { kind: "scalar", raw: Object.is(v, -0) ? "-0" : String(v), valueType: "number" };
3731
- }
3732
- case "boolean":
3733
- return { kind: "scalar", raw: v ? "true" : "false", valueType: "boolean" };
3734
- case "bigint": {
3735
- if (v > INT64_MAX || v < INT64_MIN) {
3736
- throw new ConfigError(
3737
- `fromMap: integer ${v} is out of int64 range (HOCON integers are int64; spec F0.5) at path "${atPath}"`,
3738
- atPath
3739
- );
3740
- }
3741
- return { kind: "scalar", raw: String(v), valueType: "number" };
3742
- }
3743
- case "object": {
3744
- if (Array.isArray(v)) {
3745
- const items = v.map((item, i) => coerceValue(item, `${atPath}[${i}]`));
3746
- return { kind: "array", items };
3747
- }
3748
- const fields = coerceObject(v, atPath);
3749
- return { kind: "object", fields };
3750
- }
3751
- default:
3752
- throw new ConfigError(
3753
- `fromMap: unsupported value type "${typeof v}" at path "${atPath}"`,
3754
- atPath
3755
- );
3756
- }
3757
- }
3758
55
  export {
3759
56
  Config,
3760
57
  ConfigError,