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