varlock 0.2.2 → 0.2.3

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 (49) hide show
  1. package/dist/auto-load.js +1 -1
  2. package/dist/{chunk-BHHYQ7SH.js → chunk-2YPKUF3A.js} +3 -3
  3. package/dist/{chunk-BHHYQ7SH.js.map → chunk-2YPKUF3A.js.map} +1 -1
  4. package/dist/{chunk-HPUQ2CCN.js → chunk-BXR2RIO6.js} +4 -4
  5. package/dist/{chunk-HPUQ2CCN.js.map → chunk-BXR2RIO6.js.map} +1 -1
  6. package/dist/{chunk-3FLO3UFZ.js → chunk-HTF7NU5C.js} +7 -7
  7. package/dist/chunk-HTF7NU5C.js.map +1 -0
  8. package/dist/{chunk-ZUNB52KY.js → chunk-ISSW6NKZ.js} +3 -3
  9. package/dist/{chunk-ZUNB52KY.js.map → chunk-ISSW6NKZ.js.map} +1 -1
  10. package/dist/chunk-OY5U5WTF.js +10829 -0
  11. package/dist/chunk-OY5U5WTF.js.map +1 -0
  12. package/dist/chunk-PESTWPBG.js +307 -0
  13. package/dist/chunk-PESTWPBG.js.map +1 -0
  14. package/dist/{chunk-4N3YR2QQ.js → chunk-Q3C4VKFT.js} +5 -5
  15. package/dist/chunk-Q3C4VKFT.js.map +1 -0
  16. package/dist/chunk-QZ6HBRJC.js +97 -0
  17. package/dist/chunk-QZ6HBRJC.js.map +1 -0
  18. package/dist/{chunk-N2HZMIGS.js → chunk-YIXN7TC7.js} +396 -396
  19. package/dist/chunk-YIXN7TC7.js.map +1 -0
  20. package/dist/cli/cli-executable.js +14 -15
  21. package/dist/cli/cli-executable.js.map +1 -1
  22. package/dist/dotenv-compat.js +1 -1
  23. package/dist/{env-graph-BZwrHQbb.d.ts → env-graph-DIcuAiYh.d.ts} +9 -2
  24. package/dist/index.d.ts +2 -3
  25. package/dist/index.js +3 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/init.command-RAYBZ66R.js +9 -0
  28. package/dist/{init.command-DLPZ3R4T.js.map → init.command-RAYBZ66R.js.map} +1 -1
  29. package/dist/load.command-KOSPGLV6.js +9 -0
  30. package/dist/{load.command-4G5POJYR.js.map → load.command-KOSPGLV6.js.map} +1 -1
  31. package/dist/plugin-lib.d.ts +2 -3
  32. package/dist/plugin-lib.js +2 -1
  33. package/dist/run.command-BOBQIELJ.js +10 -0
  34. package/dist/{run.command-L5LLHOW3.js.map → run.command-BOBQIELJ.js.map} +1 -1
  35. package/dist/runtime/env.d.ts +1 -2
  36. package/dist/telemetry.command-SFEMMU3U.js +9 -0
  37. package/dist/{telemetry.command-JF72FOYJ.js.map → telemetry.command-SFEMMU3U.js.map} +1 -1
  38. package/package.json +5 -11
  39. package/dist/chunk-3FLO3UFZ.js.map +0 -1
  40. package/dist/chunk-4N3YR2QQ.js.map +0 -1
  41. package/dist/chunk-FETFVFG5.js +0 -4146
  42. package/dist/chunk-FETFVFG5.js.map +0 -1
  43. package/dist/chunk-N2HZMIGS.js.map +0 -1
  44. package/dist/chunk-N4REMPVX.js +0 -135
  45. package/dist/chunk-N4REMPVX.js.map +0 -1
  46. package/dist/init.command-DLPZ3R4T.js +0 -8
  47. package/dist/load.command-4G5POJYR.js +0 -8
  48. package/dist/run.command-L5LLHOW3.js +0 -9
  49. package/dist/telemetry.command-JF72FOYJ.js +0 -8
@@ -1,4146 +0,0 @@
1
- import { redactString } from './chunk-MIBOBKI4.js';
2
- import { __commonJS, __name, __toESM } from './chunk-6PEHRAEP.js';
3
- import process2 from 'process';
4
- import fs, { accessSync } from 'fs';
5
- import fs2, { access } from 'fs/promises';
6
- import os from 'os';
7
- import path2 from 'path';
8
- import { ParsedEnvSpecFunctionCall, ParsedEnvSpecStaticValue, ParsedEnvSpecFunctionArgs, ParsedEnvSpecKeyValuePair, parseEnvSpecDotEnvFile } from '@env-spec/parser';
9
- import { exec } from 'child_process';
10
- import { promisify } from 'util';
11
- import crypto from 'crypto';
12
- import https from 'https';
13
- import semver from 'semver';
14
- import Debug from 'debug';
15
-
16
- // ../../node_modules/.pnpm/ansis@4.2.0/node_modules/ansis/index.cjs
17
- var require_ansis = __commonJS({
18
- "../../node_modules/.pnpm/ansis@4.2.0/node_modules/ansis/index.cjs"(exports, module) {
19
- var e;
20
- var t;
21
- var r;
22
- var { defineProperty: l, setPrototypeOf: n, create: o, keys: s } = Object;
23
- var i = "";
24
- var { round: c, max: a2 } = Math;
25
- var p = /* @__PURE__ */ __name((e2) => {
26
- let t2 = /([a-f\d]{3,6})/i.exec(e2)?.[1], r2 = t2?.length, l2 = parseInt(6 ^ r2 ? 3 ^ r2 ? "0" : t2[0] + t2[0] + t2[1] + t2[1] + t2[2] + t2[2] : t2, 16);
27
- return [l2 >> 16 & 255, l2 >> 8 & 255, 255 & l2];
28
- }, "p");
29
- var u = /* @__PURE__ */ __name((e2, t2, r2) => e2 ^ t2 || t2 ^ r2 ? 16 + 36 * c(e2 / 51) + 6 * c(t2 / 51) + c(r2 / 51) : 8 > e2 ? 16 : e2 > 248 ? 231 : c(24 * (e2 - 8) / 247) + 232, "u");
30
- var d = /* @__PURE__ */ __name((e2) => {
31
- let t2, r2, l2, n2, o2;
32
- return 8 > e2 ? 30 + e2 : 16 > e2 ? e2 - 8 + 90 : (232 > e2 ? (o2 = (e2 -= 16) % 36, t2 = (e2 / 36 | 0) / 5, r2 = (o2 / 6 | 0) / 5, l2 = o2 % 6 / 5) : t2 = r2 = l2 = (10 * (e2 - 232) + 8) / 255, n2 = 2 * a2(t2, r2, l2), n2 ? 30 + (c(l2) << 2 | c(r2) << 1 | c(t2)) + (2 ^ n2 ? 0 : 60) : 30);
33
- }, "d");
34
- var f = (() => {
35
- let r2 = /* @__PURE__ */ __name((e2) => o2.some(((t2) => e2.test(t2))), "r"), l2 = globalThis, n2 = l2.process ?? {}, o2 = n2.argv ?? [], i2 = n2.env ?? {}, c2 = -1;
36
- try {
37
- e = "," + s(i2).join(",");
38
- } catch (e2) {
39
- i2 = {}, c2 = 0;
40
- }
41
- let a3 = "FORCE_COLOR", p2 = { false: 0, 0: 0, 1: 1, 2: 2, 3: 3 }[i2[a3]] ?? -1, u2 = a3 in i2 && p2 || r2(/^--color=?(true|always)?$/);
42
- return u2 && (c2 = p2), ~c2 || (c2 = ((r3, l3, n3) => (t = r3.TERM, { "24bit": 3, truecolor: 3, ansi256: 2, ansi: 1 }[r3.COLORTERM] || (r3.CI ? /,GITHUB/.test(e) ? 3 : 1 : l3 && "dumb" !== t ? n3 ? 3 : /-256/.test(t) ? 2 : 1 : 0)))(i2, !!i2.PM2_HOME || i2.NEXT_RUNTIME?.includes("edge") || !!n2.stdout?.isTTY, "win32" === n2.platform)), !p2 || i2.NO_COLOR || r2(/^--(no-color|color=(false|never))$/) ? 0 : l2.window?.chrome || u2 && !c2 ? 3 : c2;
43
- })();
44
- var g = { open: i, close: i };
45
- var h = 39;
46
- var b = 49;
47
- var O = {};
48
- var m = /* @__PURE__ */ __name(({ p: e2 }, { open: t2, close: l2 }) => {
49
- let o2 = /* @__PURE__ */ __name((e3, ...r2) => {
50
- if (!e3) {
51
- if (t2 && t2 === l2) return t2;
52
- if ((e3 ?? i) === i) return i;
53
- }
54
- let n2, s3 = e3.raw ? String.raw({ raw: e3 }, ...r2) : i + e3, c3 = o2.p, a3 = c3.o, p2 = c3.c;
55
- if (s3.includes("\x1B")) for (; c3; c3 = c3.p) {
56
- let { open: e4, close: t3 } = c3, r3 = t3.length, l3 = i, o3 = 0;
57
- if (r3) for (; ~(n2 = s3.indexOf(t3, o3)); o3 = n2 + r3) l3 += s3.slice(o3, n2) + e4;
58
- s3 = l3 + s3.slice(o3);
59
- }
60
- return a3 + (s3.includes("\n") ? s3.replace(/(\r?\n)/g, p2 + "$1" + a3) : s3) + p2;
61
- }, "o"), s2 = t2, c2 = l2;
62
- return e2 && (s2 = e2.o + t2, c2 = l2 + e2.c), n(o2, r), o2.p = { open: t2, close: l2, o: s2, c: c2, p: e2 }, o2.open = s2, o2.close = c2, o2;
63
- }, "m");
64
- var w = new (/* @__PURE__ */ __name(function e2(t2 = f) {
65
- let s2 = { Ansis: e2, level: t2, isSupported: /* @__PURE__ */ __name(() => a3, "isSupported"), strip: /* @__PURE__ */ __name((e3) => e3.replace(/[›][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, i), "strip"), extend(e3) {
66
- for (let t3 in e3) {
67
- let r2 = e3[t3], l2 = (typeof r2)[0];
68
- "s" === l2 ? (c2(t3, T(...p(r2))), c2(_4(t3), v(...p(r2)))) : c2(t3, r2, "f" === l2);
69
- }
70
- return r = o({}, O), n(s2, r), s2;
71
- } }, c2 = /* @__PURE__ */ __name((e3, t3, r2) => {
72
- O[e3] = { get() {
73
- let n2 = r2 ? (...e4) => m(this, t3(...e4)) : m(this, t3);
74
- return l(this, e3, { value: n2 }), n2;
75
- } };
76
- }, "c"), a3 = t2 > 0, w2 = /* @__PURE__ */ __name((e3, t3) => a3 ? { open: `\x1B[${e3}m`, close: `\x1B[${t3}m` } : g, "w"), y = /* @__PURE__ */ __name((e3) => (t3) => e3(...p(t3)), "y"), R = /* @__PURE__ */ __name((e3, t3) => (r2, l2, n2) => w2(`${e3}8;2;${r2};${l2};${n2}`, t3), "R"), $ = /* @__PURE__ */ __name((e3, t3) => (r2, l2, n2) => w2(((e4, t4, r3) => d(u(e4, t4, r3)))(r2, l2, n2) + e3, t3), "$"), x = /* @__PURE__ */ __name((e3) => (t3, r2, l2) => e3(u(t3, r2, l2)), "x"), T = R(3, h), v = R(4, b), C = /* @__PURE__ */ __name((e3) => w2("38;5;" + e3, h), "C"), E = /* @__PURE__ */ __name((e3) => w2("48;5;" + e3, b), "E");
77
- 2 === t2 ? (T = x(C), v = x(E)) : 1 === t2 && (T = $(0, h), v = $(10, b), C = /* @__PURE__ */ __name((e3) => w2(d(e3), h), "C"), E = /* @__PURE__ */ __name((e3) => w2(d(e3) + 10, b), "E"));
78
- let M, I = { fg: C, bg: E, rgb: T, bgRgb: v, hex: y(T), bgHex: y(v), visible: g, reset: w2(0, 0), bold: w2(1, 22), dim: w2(2, 22), italic: w2(3, 23), underline: w2(4, 24), inverse: w2(7, 27), hidden: w2(8, 28), strikethrough: w2(9, 29) }, _4 = /* @__PURE__ */ __name((e3) => "bg" + e3[0].toUpperCase() + e3.slice(1), "_"), k = "Bright";
79
- return "black,red,green,yellow,blue,magenta,cyan,white,gray".split(",").map(((e3, t3) => {
80
- M = _4(e3), 8 > t3 ? (I[e3 + k] = w2(90 + t3, h), I[M + k] = w2(100 + t3, b)) : t3 = 60, I[e3] = w2(30 + t3, h), I[M] = w2(40 + t3, b);
81
- })), s2.extend(I);
82
- }, "e"))();
83
- module.exports = w, w.default = w;
84
- }
85
- });
86
-
87
- // ../../node_modules/.pnpm/ansis@4.2.0/node_modules/ansis/index.mjs
88
- var import_index = __toESM(require_ansis(), 1);
89
- var ansis_default = import_index.default;
90
- var { Ansis, fg, bg, rgb, bgRgb, hex, bgHex, reset, inverse, hidden, visible, bold, dim, italic, underline, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bgGray, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright } = import_index.default;
91
- var asyncCallbacks = /* @__PURE__ */ new Set();
92
- var callbacks = /* @__PURE__ */ new Set();
93
- var isCalled = false;
94
- var isRegistered = false;
95
- async function flushStdio() {
96
- const flush = /* @__PURE__ */ __name((stream) => new Promise((resolve) => {
97
- if (!stream || !stream.writable || stream.writableEnded || stream.destroyed) {
98
- resolve();
99
- return;
100
- }
101
- const onError = /* @__PURE__ */ __name(() => {
102
- stream.off("error", onError);
103
- resolve();
104
- }, "onError");
105
- stream.once("error", onError);
106
- try {
107
- stream.write("", () => {
108
- stream.off("error", onError);
109
- resolve();
110
- });
111
- } catch {
112
- stream.off("error", onError);
113
- resolve();
114
- }
115
- }), "flush");
116
- const timeout = new Promise((resolve) => {
117
- setTimeout(resolve, 1e3);
118
- });
119
- await Promise.race([
120
- Promise.all([flush(process2.stdout), flush(process2.stderr)]),
121
- timeout
122
- ]);
123
- }
124
- __name(flushStdio, "flushStdio");
125
- async function exit(shouldManuallyExit, isSynchronous, signal) {
126
- if (isCalled) {
127
- return;
128
- }
129
- isCalled = true;
130
- if (asyncCallbacks.size > 0 && isSynchronous) {
131
- console.error([
132
- "SYNCHRONOUS TERMINATION NOTICE:",
133
- "When explicitly exiting the process via process.exit or via a parent process,",
134
- "asynchronous tasks in your exitHooks will not run. Either remove these tasks,",
135
- "use gracefulExit() instead of process.exit(), or ensure your parent process",
136
- "sends a SIGINT to the process running this code."
137
- ].join(" "));
138
- }
139
- let exitCode = 0;
140
- if (signal > 0) {
141
- exitCode = 128 + signal;
142
- } else if (typeof process2.exitCode === "number" || typeof process2.exitCode === "string") {
143
- exitCode = process2.exitCode;
144
- }
145
- const done = /* @__PURE__ */ __name((force = false) => {
146
- if (force === true || shouldManuallyExit === true) {
147
- process2.exit(exitCode);
148
- }
149
- }, "done");
150
- for (const callback of callbacks) {
151
- callback(exitCode);
152
- }
153
- if (isSynchronous) {
154
- done();
155
- return;
156
- }
157
- const promises = [];
158
- let forceAfter = 0;
159
- for (const [callback, wait] of asyncCallbacks) {
160
- forceAfter = Math.max(forceAfter, wait);
161
- promises.push(Promise.resolve(callback(exitCode)));
162
- }
163
- const asyncTimer = forceAfter > 0 ? setTimeout(() => {
164
- done(true);
165
- }, forceAfter) : void 0;
166
- await Promise.all(promises);
167
- clearTimeout(asyncTimer);
168
- await flushStdio();
169
- done();
170
- }
171
- __name(exit, "exit");
172
- function addHook(options) {
173
- const { onExit, wait, isSynchronous } = options;
174
- const asyncCallbackConfig = [onExit, wait];
175
- if (isSynchronous) {
176
- callbacks.add(onExit);
177
- } else {
178
- asyncCallbacks.add(asyncCallbackConfig);
179
- }
180
- if (!isRegistered) {
181
- isRegistered = true;
182
- process2.once("beforeExit", exit.bind(void 0, true, false, -128));
183
- process2.once("SIGINT", exit.bind(void 0, true, false, 2));
184
- process2.once("SIGTERM", exit.bind(void 0, true, false, 15));
185
- process2.once("exit", exit.bind(void 0, false, true, 0));
186
- process2.on("message", (message) => {
187
- if (message === "shutdown") {
188
- exit(true, true, -128);
189
- }
190
- });
191
- }
192
- return () => {
193
- if (isSynchronous) {
194
- callbacks.delete(onExit);
195
- } else {
196
- asyncCallbacks.delete(asyncCallbackConfig);
197
- }
198
- };
199
- }
200
- __name(addHook, "addHook");
201
- function asyncExitHook(onExit, options = {}) {
202
- if (typeof onExit !== "function") {
203
- throw new TypeError("onExit must be a function");
204
- }
205
- if (!(typeof options.wait === "number" && options.wait > 0)) {
206
- throw new TypeError("wait must be set to a positive numeric value");
207
- }
208
- return addHook({
209
- onExit,
210
- wait: options.wait,
211
- isSynchronous: false
212
- });
213
- }
214
- __name(asyncExitHook, "asyncExitHook");
215
- function gracefulExit(signal) {
216
- if (signal !== void 0) {
217
- process2.exitCode = signal;
218
- }
219
- exit(true, false, -128);
220
- }
221
- __name(gracefulExit, "gracefulExit");
222
-
223
- // ../../node_modules/.pnpm/@sindresorhus+is@7.2.0/node_modules/@sindresorhus/is/distribution/utilities.js
224
- function keysOf(value) {
225
- return Object.keys(value);
226
- }
227
- __name(keysOf, "keysOf");
228
-
229
- // ../../node_modules/.pnpm/@sindresorhus+is@7.2.0/node_modules/@sindresorhus/is/distribution/index.js
230
- var typedArrayTypeNames = [
231
- "Int8Array",
232
- "Uint8Array",
233
- "Uint8ClampedArray",
234
- "Int16Array",
235
- "Uint16Array",
236
- "Int32Array",
237
- "Uint32Array",
238
- "Float32Array",
239
- "Float64Array",
240
- "BigInt64Array",
241
- "BigUint64Array"
242
- ];
243
- function isTypedArrayName(name) {
244
- return typedArrayTypeNames.includes(name);
245
- }
246
- __name(isTypedArrayName, "isTypedArrayName");
247
- var objectTypeNames = [
248
- "Function",
249
- "Generator",
250
- "AsyncGenerator",
251
- "GeneratorFunction",
252
- "AsyncGeneratorFunction",
253
- "AsyncFunction",
254
- "Observable",
255
- "Array",
256
- "Buffer",
257
- "Blob",
258
- "Object",
259
- "RegExp",
260
- "Date",
261
- "Error",
262
- "Map",
263
- "Set",
264
- "WeakMap",
265
- "WeakSet",
266
- "WeakRef",
267
- "ArrayBuffer",
268
- "SharedArrayBuffer",
269
- "DataView",
270
- "Promise",
271
- "URL",
272
- "FormData",
273
- "URLSearchParams",
274
- "HTMLElement",
275
- "NaN",
276
- ...typedArrayTypeNames
277
- ];
278
- function isObjectTypeName(name) {
279
- return objectTypeNames.includes(name);
280
- }
281
- __name(isObjectTypeName, "isObjectTypeName");
282
- var primitiveTypeNames = [
283
- "null",
284
- "undefined",
285
- "string",
286
- "number",
287
- "bigint",
288
- "boolean",
289
- "symbol"
290
- ];
291
- function isPrimitiveTypeName(name) {
292
- return primitiveTypeNames.includes(name);
293
- }
294
- __name(isPrimitiveTypeName, "isPrimitiveTypeName");
295
- var getObjectType = /* @__PURE__ */ __name((value) => {
296
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
297
- if (/HTML\w+Element/.test(objectTypeName) && isHtmlElement(value)) {
298
- return "HTMLElement";
299
- }
300
- if (isObjectTypeName(objectTypeName)) {
301
- return objectTypeName;
302
- }
303
- return void 0;
304
- }, "getObjectType");
305
- function detect(value) {
306
- if (value === null) {
307
- return "null";
308
- }
309
- switch (typeof value) {
310
- case "undefined": {
311
- return "undefined";
312
- }
313
- case "string": {
314
- return "string";
315
- }
316
- case "number": {
317
- return Number.isNaN(value) ? "NaN" : "number";
318
- }
319
- case "boolean": {
320
- return "boolean";
321
- }
322
- case "function": {
323
- return "Function";
324
- }
325
- case "bigint": {
326
- return "bigint";
327
- }
328
- case "symbol": {
329
- return "symbol";
330
- }
331
- }
332
- if (isObservable(value)) {
333
- return "Observable";
334
- }
335
- if (isArray(value)) {
336
- return "Array";
337
- }
338
- if (isBuffer(value)) {
339
- return "Buffer";
340
- }
341
- const tagType = getObjectType(value);
342
- if (tagType && tagType !== "Object") {
343
- return tagType;
344
- }
345
- if (hasPromiseApi(value)) {
346
- return "Promise";
347
- }
348
- if (value instanceof String || value instanceof Boolean || value instanceof Number) {
349
- throw new TypeError("Please don't use object wrappers for primitive types");
350
- }
351
- return "Object";
352
- }
353
- __name(detect, "detect");
354
- function hasPromiseApi(value) {
355
- return isFunction(value?.then) && isFunction(value?.catch);
356
- }
357
- __name(hasPromiseApi, "hasPromiseApi");
358
- Object.assign(detect, {
359
- all: isAll,
360
- any: isAny,
361
- array: isArray,
362
- arrayBuffer: isArrayBuffer,
363
- arrayLike: isArrayLike,
364
- asyncFunction: isAsyncFunction,
365
- asyncGenerator: isAsyncGenerator,
366
- asyncGeneratorFunction: isAsyncGeneratorFunction,
367
- asyncIterable: isAsyncIterable,
368
- bigint: isBigint,
369
- bigInt64Array: isBigInt64Array,
370
- bigUint64Array: isBigUint64Array,
371
- blob: isBlob,
372
- boolean: isBoolean,
373
- boundFunction: isBoundFunction,
374
- buffer: isBuffer,
375
- class: isClass,
376
- dataView: isDataView,
377
- date: isDate,
378
- detect,
379
- directInstanceOf: isDirectInstanceOf,
380
- emptyArray: isEmptyArray,
381
- emptyMap: isEmptyMap,
382
- emptyObject: isEmptyObject,
383
- emptySet: isEmptySet,
384
- emptyString: isEmptyString,
385
- emptyStringOrWhitespace: isEmptyStringOrWhitespace,
386
- enumCase: isEnumCase,
387
- error: isError,
388
- evenInteger: isEvenInteger,
389
- falsy: isFalsy,
390
- float32Array: isFloat32Array,
391
- float64Array: isFloat64Array,
392
- formData: isFormData,
393
- function: isFunction,
394
- generator: isGenerator,
395
- generatorFunction: isGeneratorFunction,
396
- htmlElement: isHtmlElement,
397
- infinite: isInfinite,
398
- inRange: isInRange,
399
- int16Array: isInt16Array,
400
- int32Array: isInt32Array,
401
- int8Array: isInt8Array,
402
- integer: isInteger,
403
- iterable: isIterable,
404
- map: isMap,
405
- nan: isNan,
406
- nativePromise: isNativePromise,
407
- negativeNumber: isNegativeNumber,
408
- nodeStream: isNodeStream,
409
- nonEmptyArray: isNonEmptyArray,
410
- nonEmptyMap: isNonEmptyMap,
411
- nonEmptyObject: isNonEmptyObject,
412
- nonEmptySet: isNonEmptySet,
413
- nonEmptyString: isNonEmptyString,
414
- nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace,
415
- null: isNull,
416
- nullOrUndefined: isNullOrUndefined,
417
- number: isNumber,
418
- numericString: isNumericString,
419
- object: isObject,
420
- observable: isObservable,
421
- oddInteger: isOddInteger,
422
- plainObject: isPlainObject,
423
- positiveNumber: isPositiveNumber,
424
- primitive: isPrimitive,
425
- promise: isPromise,
426
- propertyKey: isPropertyKey,
427
- regExp: isRegExp,
428
- safeInteger: isSafeInteger,
429
- set: isSet,
430
- sharedArrayBuffer: isSharedArrayBuffer,
431
- string: isString,
432
- symbol: isSymbol,
433
- truthy: isTruthy,
434
- tupleLike: isTupleLike,
435
- typedArray: isTypedArray,
436
- uint16Array: isUint16Array,
437
- uint32Array: isUint32Array,
438
- uint8Array: isUint8Array,
439
- uint8ClampedArray: isUint8ClampedArray,
440
- undefined: isUndefined,
441
- urlInstance: isUrlInstance,
442
- urlSearchParams: isUrlSearchParams,
443
- urlString: isUrlString,
444
- optional: isOptional,
445
- validDate: isValidDate,
446
- validLength: isValidLength,
447
- weakMap: isWeakMap,
448
- weakRef: isWeakRef,
449
- weakSet: isWeakSet,
450
- whitespaceString: isWhitespaceString
451
- });
452
- function isAbsoluteModule2(remainder) {
453
- return (value) => isInteger(value) && Math.abs(value % 2) === remainder;
454
- }
455
- __name(isAbsoluteModule2, "isAbsoluteModule2");
456
- function validatePredicateArray(predicateArray, allowEmpty) {
457
- if (predicateArray.length === 0) {
458
- if (allowEmpty) ; else {
459
- throw new TypeError("Invalid predicate array");
460
- }
461
- return;
462
- }
463
- for (const predicate of predicateArray) {
464
- if (!isFunction(predicate)) {
465
- throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
466
- }
467
- }
468
- }
469
- __name(validatePredicateArray, "validatePredicateArray");
470
- function isAll(predicate, ...values) {
471
- if (Array.isArray(predicate)) {
472
- const predicateArray = predicate;
473
- validatePredicateArray(predicateArray, values.length === 0);
474
- const combinedPredicate = /* @__PURE__ */ __name((value) => predicateArray.every((singlePredicate) => singlePredicate(value)), "combinedPredicate");
475
- if (values.length === 0) {
476
- return combinedPredicate;
477
- }
478
- return predicateOnArray(Array.prototype.every, combinedPredicate, values);
479
- }
480
- return predicateOnArray(Array.prototype.every, predicate, values);
481
- }
482
- __name(isAll, "isAll");
483
- function isAny(predicate, ...values) {
484
- if (Array.isArray(predicate)) {
485
- const predicateArray = predicate;
486
- validatePredicateArray(predicateArray, values.length === 0);
487
- const combinedPredicate = /* @__PURE__ */ __name((value) => predicateArray.some((singlePredicate) => singlePredicate(value)), "combinedPredicate");
488
- if (values.length === 0) {
489
- return combinedPredicate;
490
- }
491
- return predicateOnArray(Array.prototype.some, combinedPredicate, values);
492
- }
493
- return predicateOnArray(Array.prototype.some, predicate, values);
494
- }
495
- __name(isAny, "isAny");
496
- function isOptional(value, predicate) {
497
- return isUndefined(value) || predicate(value);
498
- }
499
- __name(isOptional, "isOptional");
500
- function isArray(value, assertion) {
501
- if (!Array.isArray(value)) {
502
- return false;
503
- }
504
- if (!isFunction(assertion)) {
505
- return true;
506
- }
507
- return value.every((element) => assertion(element));
508
- }
509
- __name(isArray, "isArray");
510
- function isArrayBuffer(value) {
511
- return getObjectType(value) === "ArrayBuffer";
512
- }
513
- __name(isArrayBuffer, "isArrayBuffer");
514
- function isArrayLike(value) {
515
- return !isNullOrUndefined(value) && !isFunction(value) && isValidLength(value.length);
516
- }
517
- __name(isArrayLike, "isArrayLike");
518
- function isAsyncFunction(value) {
519
- return getObjectType(value) === "AsyncFunction";
520
- }
521
- __name(isAsyncFunction, "isAsyncFunction");
522
- function isAsyncGenerator(value) {
523
- return isAsyncIterable(value) && isFunction(value.next) && isFunction(value.throw);
524
- }
525
- __name(isAsyncGenerator, "isAsyncGenerator");
526
- function isAsyncGeneratorFunction(value) {
527
- return getObjectType(value) === "AsyncGeneratorFunction";
528
- }
529
- __name(isAsyncGeneratorFunction, "isAsyncGeneratorFunction");
530
- function isAsyncIterable(value) {
531
- return isFunction(value?.[Symbol.asyncIterator]);
532
- }
533
- __name(isAsyncIterable, "isAsyncIterable");
534
- function isBigint(value) {
535
- return typeof value === "bigint";
536
- }
537
- __name(isBigint, "isBigint");
538
- function isBigInt64Array(value) {
539
- return getObjectType(value) === "BigInt64Array";
540
- }
541
- __name(isBigInt64Array, "isBigInt64Array");
542
- function isBigUint64Array(value) {
543
- return getObjectType(value) === "BigUint64Array";
544
- }
545
- __name(isBigUint64Array, "isBigUint64Array");
546
- function isBlob(value) {
547
- return getObjectType(value) === "Blob";
548
- }
549
- __name(isBlob, "isBlob");
550
- function isBoolean(value) {
551
- return value === true || value === false;
552
- }
553
- __name(isBoolean, "isBoolean");
554
- function isBoundFunction(value) {
555
- return isFunction(value) && !Object.hasOwn(value, "prototype");
556
- }
557
- __name(isBoundFunction, "isBoundFunction");
558
- function isBuffer(value) {
559
- return value?.constructor?.isBuffer?.(value) ?? false;
560
- }
561
- __name(isBuffer, "isBuffer");
562
- function isClass(value) {
563
- return isFunction(value) && /^class(\s+|{)/.test(value.toString());
564
- }
565
- __name(isClass, "isClass");
566
- function isDataView(value) {
567
- return getObjectType(value) === "DataView";
568
- }
569
- __name(isDataView, "isDataView");
570
- function isDate(value) {
571
- return getObjectType(value) === "Date";
572
- }
573
- __name(isDate, "isDate");
574
- function isDirectInstanceOf(instance, class_) {
575
- if (instance === void 0 || instance === null) {
576
- return false;
577
- }
578
- return Object.getPrototypeOf(instance) === class_.prototype;
579
- }
580
- __name(isDirectInstanceOf, "isDirectInstanceOf");
581
- function isEmptyArray(value) {
582
- return isArray(value) && value.length === 0;
583
- }
584
- __name(isEmptyArray, "isEmptyArray");
585
- function isEmptyMap(value) {
586
- return isMap(value) && value.size === 0;
587
- }
588
- __name(isEmptyMap, "isEmptyMap");
589
- function isEmptyObject(value) {
590
- return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length === 0;
591
- }
592
- __name(isEmptyObject, "isEmptyObject");
593
- function isEmptySet(value) {
594
- return isSet(value) && value.size === 0;
595
- }
596
- __name(isEmptySet, "isEmptySet");
597
- function isEmptyString(value) {
598
- return isString(value) && value.length === 0;
599
- }
600
- __name(isEmptyString, "isEmptyString");
601
- function isEmptyStringOrWhitespace(value) {
602
- return isEmptyString(value) || isWhitespaceString(value);
603
- }
604
- __name(isEmptyStringOrWhitespace, "isEmptyStringOrWhitespace");
605
- function isEnumCase(value, targetEnum) {
606
- return Object.values(targetEnum).includes(value);
607
- }
608
- __name(isEnumCase, "isEnumCase");
609
- function isError(value) {
610
- return getObjectType(value) === "Error";
611
- }
612
- __name(isError, "isError");
613
- function isEvenInteger(value) {
614
- return isAbsoluteModule2(0)(value);
615
- }
616
- __name(isEvenInteger, "isEvenInteger");
617
- function isFalsy(value) {
618
- return !value;
619
- }
620
- __name(isFalsy, "isFalsy");
621
- function isFloat32Array(value) {
622
- return getObjectType(value) === "Float32Array";
623
- }
624
- __name(isFloat32Array, "isFloat32Array");
625
- function isFloat64Array(value) {
626
- return getObjectType(value) === "Float64Array";
627
- }
628
- __name(isFloat64Array, "isFloat64Array");
629
- function isFormData(value) {
630
- return getObjectType(value) === "FormData";
631
- }
632
- __name(isFormData, "isFormData");
633
- function isFunction(value) {
634
- return typeof value === "function";
635
- }
636
- __name(isFunction, "isFunction");
637
- function isGenerator(value) {
638
- return isIterable(value) && isFunction(value?.next) && isFunction(value?.throw);
639
- }
640
- __name(isGenerator, "isGenerator");
641
- function isGeneratorFunction(value) {
642
- return getObjectType(value) === "GeneratorFunction";
643
- }
644
- __name(isGeneratorFunction, "isGeneratorFunction");
645
- var NODE_TYPE_ELEMENT = 1;
646
- var DOM_PROPERTIES_TO_CHECK = [
647
- "innerHTML",
648
- "ownerDocument",
649
- "style",
650
- "attributes",
651
- "nodeValue"
652
- ];
653
- function isHtmlElement(value) {
654
- return isObject(value) && value.nodeType === NODE_TYPE_ELEMENT && isString(value.nodeName) && !isPlainObject(value) && DOM_PROPERTIES_TO_CHECK.every((property) => property in value);
655
- }
656
- __name(isHtmlElement, "isHtmlElement");
657
- function isInfinite(value) {
658
- return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY;
659
- }
660
- __name(isInfinite, "isInfinite");
661
- function isInRange(value, range) {
662
- if (isNumber(range)) {
663
- return value >= Math.min(0, range) && value <= Math.max(range, 0);
664
- }
665
- if (isArray(range) && range.length === 2) {
666
- return value >= Math.min(...range) && value <= Math.max(...range);
667
- }
668
- throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
669
- }
670
- __name(isInRange, "isInRange");
671
- function isInt16Array(value) {
672
- return getObjectType(value) === "Int16Array";
673
- }
674
- __name(isInt16Array, "isInt16Array");
675
- function isInt32Array(value) {
676
- return getObjectType(value) === "Int32Array";
677
- }
678
- __name(isInt32Array, "isInt32Array");
679
- function isInt8Array(value) {
680
- return getObjectType(value) === "Int8Array";
681
- }
682
- __name(isInt8Array, "isInt8Array");
683
- function isInteger(value) {
684
- return Number.isInteger(value);
685
- }
686
- __name(isInteger, "isInteger");
687
- function isIterable(value) {
688
- return isFunction(value?.[Symbol.iterator]);
689
- }
690
- __name(isIterable, "isIterable");
691
- function isMap(value) {
692
- return getObjectType(value) === "Map";
693
- }
694
- __name(isMap, "isMap");
695
- function isNan(value) {
696
- return Number.isNaN(value);
697
- }
698
- __name(isNan, "isNan");
699
- function isNativePromise(value) {
700
- return getObjectType(value) === "Promise";
701
- }
702
- __name(isNativePromise, "isNativePromise");
703
- function isNegativeNumber(value) {
704
- return isNumber(value) && value < 0;
705
- }
706
- __name(isNegativeNumber, "isNegativeNumber");
707
- function isNodeStream(value) {
708
- return isObject(value) && isFunction(value.pipe) && !isObservable(value);
709
- }
710
- __name(isNodeStream, "isNodeStream");
711
- function isNonEmptyArray(value) {
712
- return isArray(value) && value.length > 0;
713
- }
714
- __name(isNonEmptyArray, "isNonEmptyArray");
715
- function isNonEmptyMap(value) {
716
- return isMap(value) && value.size > 0;
717
- }
718
- __name(isNonEmptyMap, "isNonEmptyMap");
719
- function isNonEmptyObject(value) {
720
- return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length > 0;
721
- }
722
- __name(isNonEmptyObject, "isNonEmptyObject");
723
- function isNonEmptySet(value) {
724
- return isSet(value) && value.size > 0;
725
- }
726
- __name(isNonEmptySet, "isNonEmptySet");
727
- function isNonEmptyString(value) {
728
- return isString(value) && value.length > 0;
729
- }
730
- __name(isNonEmptyString, "isNonEmptyString");
731
- function isNonEmptyStringAndNotWhitespace(value) {
732
- return isString(value) && !isEmptyStringOrWhitespace(value);
733
- }
734
- __name(isNonEmptyStringAndNotWhitespace, "isNonEmptyStringAndNotWhitespace");
735
- function isNull(value) {
736
- return value === null;
737
- }
738
- __name(isNull, "isNull");
739
- function isNullOrUndefined(value) {
740
- return isNull(value) || isUndefined(value);
741
- }
742
- __name(isNullOrUndefined, "isNullOrUndefined");
743
- function isNumber(value) {
744
- return typeof value === "number" && !Number.isNaN(value);
745
- }
746
- __name(isNumber, "isNumber");
747
- function isNumericString(value) {
748
- return isString(value) && !isEmptyStringOrWhitespace(value) && !Number.isNaN(Number(value));
749
- }
750
- __name(isNumericString, "isNumericString");
751
- function isObject(value) {
752
- return !isNull(value) && (typeof value === "object" || isFunction(value));
753
- }
754
- __name(isObject, "isObject");
755
- function isObservable(value) {
756
- if (!value) {
757
- return false;
758
- }
759
- if (Symbol.observable !== void 0 && value === value[Symbol.observable]?.()) {
760
- return true;
761
- }
762
- if (value === value["@@observable"]?.()) {
763
- return true;
764
- }
765
- return false;
766
- }
767
- __name(isObservable, "isObservable");
768
- function isOddInteger(value) {
769
- return isAbsoluteModule2(1)(value);
770
- }
771
- __name(isOddInteger, "isOddInteger");
772
- function isPlainObject(value) {
773
- if (typeof value !== "object" || value === null) {
774
- return false;
775
- }
776
- const prototype = Object.getPrototypeOf(value);
777
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
778
- }
779
- __name(isPlainObject, "isPlainObject");
780
- function isPositiveNumber(value) {
781
- return isNumber(value) && value > 0;
782
- }
783
- __name(isPositiveNumber, "isPositiveNumber");
784
- function isPrimitive(value) {
785
- return isNull(value) || isPrimitiveTypeName(typeof value);
786
- }
787
- __name(isPrimitive, "isPrimitive");
788
- function isPromise(value) {
789
- return isNativePromise(value) || hasPromiseApi(value);
790
- }
791
- __name(isPromise, "isPromise");
792
- function isPropertyKey(value) {
793
- return isAny([isString, isNumber, isSymbol], value);
794
- }
795
- __name(isPropertyKey, "isPropertyKey");
796
- function isRegExp(value) {
797
- return getObjectType(value) === "RegExp";
798
- }
799
- __name(isRegExp, "isRegExp");
800
- function isSafeInteger(value) {
801
- return Number.isSafeInteger(value);
802
- }
803
- __name(isSafeInteger, "isSafeInteger");
804
- function isSet(value) {
805
- return getObjectType(value) === "Set";
806
- }
807
- __name(isSet, "isSet");
808
- function isSharedArrayBuffer(value) {
809
- return getObjectType(value) === "SharedArrayBuffer";
810
- }
811
- __name(isSharedArrayBuffer, "isSharedArrayBuffer");
812
- function isString(value) {
813
- return typeof value === "string";
814
- }
815
- __name(isString, "isString");
816
- function isSymbol(value) {
817
- return typeof value === "symbol";
818
- }
819
- __name(isSymbol, "isSymbol");
820
- function isTruthy(value) {
821
- return Boolean(value);
822
- }
823
- __name(isTruthy, "isTruthy");
824
- function isTupleLike(value, guards) {
825
- if (isArray(guards) && isArray(value) && guards.length === value.length) {
826
- return guards.every((guard, index) => guard(value[index]));
827
- }
828
- return false;
829
- }
830
- __name(isTupleLike, "isTupleLike");
831
- function isTypedArray(value) {
832
- return isTypedArrayName(getObjectType(value));
833
- }
834
- __name(isTypedArray, "isTypedArray");
835
- function isUint16Array(value) {
836
- return getObjectType(value) === "Uint16Array";
837
- }
838
- __name(isUint16Array, "isUint16Array");
839
- function isUint32Array(value) {
840
- return getObjectType(value) === "Uint32Array";
841
- }
842
- __name(isUint32Array, "isUint32Array");
843
- function isUint8Array(value) {
844
- return getObjectType(value) === "Uint8Array";
845
- }
846
- __name(isUint8Array, "isUint8Array");
847
- function isUint8ClampedArray(value) {
848
- return getObjectType(value) === "Uint8ClampedArray";
849
- }
850
- __name(isUint8ClampedArray, "isUint8ClampedArray");
851
- function isUndefined(value) {
852
- return value === void 0;
853
- }
854
- __name(isUndefined, "isUndefined");
855
- function isUrlInstance(value) {
856
- return getObjectType(value) === "URL";
857
- }
858
- __name(isUrlInstance, "isUrlInstance");
859
- function isUrlSearchParams(value) {
860
- return getObjectType(value) === "URLSearchParams";
861
- }
862
- __name(isUrlSearchParams, "isUrlSearchParams");
863
- function isUrlString(value) {
864
- if (!isString(value)) {
865
- return false;
866
- }
867
- try {
868
- new URL(value);
869
- return true;
870
- } catch {
871
- return false;
872
- }
873
- }
874
- __name(isUrlString, "isUrlString");
875
- function isValidDate(value) {
876
- return isDate(value) && !isNan(Number(value));
877
- }
878
- __name(isValidDate, "isValidDate");
879
- function isValidLength(value) {
880
- return isSafeInteger(value) && value >= 0;
881
- }
882
- __name(isValidLength, "isValidLength");
883
- function isWeakMap(value) {
884
- return getObjectType(value) === "WeakMap";
885
- }
886
- __name(isWeakMap, "isWeakMap");
887
- function isWeakRef(value) {
888
- return getObjectType(value) === "WeakRef";
889
- }
890
- __name(isWeakRef, "isWeakRef");
891
- function isWeakSet(value) {
892
- return getObjectType(value) === "WeakSet";
893
- }
894
- __name(isWeakSet, "isWeakSet");
895
- function isWhitespaceString(value) {
896
- return isString(value) && /^\s+$/.test(value);
897
- }
898
- __name(isWhitespaceString, "isWhitespaceString");
899
- function predicateOnArray(method, predicate, values) {
900
- if (!isFunction(predicate)) {
901
- throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
902
- }
903
- if (values.length === 0) {
904
- throw new TypeError("Invalid number of values");
905
- }
906
- return method.call(values, predicate);
907
- }
908
- __name(predicateOnArray, "predicateOnArray");
909
-
910
- // ../utils/src/my-dash.ts
911
- function keyBy(array, key) {
912
- return (array || []).reduce((r, x) => ({ ...r, [String(x[key])]: x }), {});
913
- }
914
- __name(keyBy, "keyBy");
915
- function sortBy(array, compareBy) {
916
- if (typeof compareBy === "function") {
917
- const compareMap = /* @__PURE__ */ new Map();
918
- array.forEach((item) => {
919
- compareMap.set(item, compareBy(item));
920
- });
921
- return array.concat().sort(
922
- (a2, b) => compareMap.get(a2) - compareMap.get(b)
923
- );
924
- } else {
925
- return array.concat().sort(
926
- (a2, b) => {
927
- if (a2[compareBy] > b[compareBy]) return 1;
928
- return b[compareBy] > a2[compareBy] ? -1 : 0;
929
- }
930
- );
931
- }
932
- }
933
- __name(sortBy, "sortBy");
934
- function compact(array) {
935
- return array.filter((item) => item !== void 0 && item !== false && item !== null);
936
- }
937
- __name(compact, "compact");
938
- function filter(array, fn) {
939
- return array.filter(fn);
940
- }
941
- __name(filter, "filter");
942
- function each(array, fn) {
943
- if (Array.isArray(array)) {
944
- array.forEach((item, index) => fn(item, String(index)));
945
- } else {
946
- Object.entries(array).forEach(([key, value]) => fn(value, key));
947
- }
948
- }
949
- __name(each, "each");
950
- function castArray(value) {
951
- return Array.isArray(value) ? value : [value];
952
- }
953
- __name(castArray, "castArray");
954
- function mapValues(obj, fn) {
955
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
956
- }
957
- __name(mapValues, "mapValues");
958
- function times(count, fn) {
959
- return Array.from({ length: count }, (_4, i) => fn(i));
960
- }
961
- __name(times, "times");
962
- function map(array, fn) {
963
- return array.map(fn);
964
- }
965
- __name(map, "map");
966
- function flatMap(array, fn) {
967
- return array.flatMap(fn);
968
- }
969
- __name(flatMap, "flatMap");
970
- function intersection(...arrays) {
971
- return arrays.reduce((a2, b) => a2.filter((value) => b.includes(value)));
972
- }
973
- __name(intersection, "intersection");
974
- function pick(obj, keys) {
975
- return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));
976
- }
977
- __name(pick, "pick");
978
- function uniq(array) {
979
- return Array.from(new Set(array));
980
- }
981
- __name(uniq, "uniq");
982
- function fromPairs(pairs) {
983
- return Object.fromEntries(pairs);
984
- }
985
- __name(fromPairs, "fromPairs");
986
- var _ = {
987
- keyBy,
988
- sortBy,
989
- compact,
990
- keys: Object.keys,
991
- values: Object.values,
992
- some: /* @__PURE__ */ __name((a2, fn) => a2.some(fn), "some"),
993
- filter,
994
- each,
995
- castArray,
996
- mapValues,
997
- times,
998
- map,
999
- flatMap,
1000
- intersection,
1001
- pick,
1002
- uniq,
1003
- fromPairs,
1004
- // type checks
1005
- isString,
1006
- isBoolean,
1007
- isError,
1008
- isPromise,
1009
- isFunction,
1010
- isNan,
1011
- isNumber,
1012
- isPlainObject,
1013
- isArray,
1014
- isInteger
1015
- };
1016
- var my_dash_default = _;
1017
-
1018
- // src/env-graph/lib/errors.ts
1019
- var VarlockError = class extends Error {
1020
- constructor(errOrMessage, more) {
1021
- super(my_dash_default.isError(errOrMessage) ? errOrMessage.message : errOrMessage);
1022
- this.more = more;
1023
- if (my_dash_default.isError(errOrMessage)) {
1024
- this.originalError = errOrMessage;
1025
- this.icon = "\u{1F4A5}";
1026
- } else {
1027
- this.originalError = more?.err;
1028
- }
1029
- if (my_dash_default.isArray(more?.tip)) more.tip = more.tip.join("\n");
1030
- this.name = this.constructor.name;
1031
- if (more?.isWarning) this.isWarning = true;
1032
- this.icon ||= this.constructor.defaultIcon;
1033
- }
1034
- static {
1035
- __name(this, "VarlockError");
1036
- }
1037
- originalError;
1038
- get isUnexpected() {
1039
- return !!this.originalError;
1040
- }
1041
- get type() {
1042
- return this.name;
1043
- }
1044
- static defaultIcon = "\u274C";
1045
- icon;
1046
- _isWarning = false;
1047
- get tip() {
1048
- if (!this.more?.tip) return void 0;
1049
- if (my_dash_default.isArray(this.more.tip)) return this.more.tip.join("\n");
1050
- return this.more.tip;
1051
- }
1052
- get location() {
1053
- return this.more?.location;
1054
- }
1055
- get code() {
1056
- return this.more?.code;
1057
- }
1058
- get extraMetadata() {
1059
- return this.more?.extraMetadata;
1060
- }
1061
- set isWarning(w) {
1062
- this._isWarning = w;
1063
- if (this._isWarning) {
1064
- this.icon = "\u{1F9D0}";
1065
- }
1066
- }
1067
- get isWarning() {
1068
- return this._isWarning;
1069
- }
1070
- toJSON() {
1071
- return {
1072
- icon: this.icon,
1073
- type: this.type,
1074
- name: this.name,
1075
- message: this.message,
1076
- isUnexpected: this.isUnexpected,
1077
- ...this.tip && { tip: this.tip },
1078
- ...this.isWarning && { isWarning: this.isWarning }
1079
- };
1080
- }
1081
- };
1082
- var ConfigLoadError = class extends VarlockError {
1083
- static {
1084
- __name(this, "ConfigLoadError");
1085
- }
1086
- cleanedStack;
1087
- constructor(err) {
1088
- super(err);
1089
- let stackLines = (err.stack?.split("\n") || []).slice(1);
1090
- stackLines = stackLines.filter((l) => {
1091
- if (l.includes(" at ViteNodeRunner.")) return false;
1092
- if (l.includes("core/src/config-loader/config-loader.ts")) return false;
1093
- return true;
1094
- });
1095
- this.message = `${err.name}: ${err.message}`;
1096
- this.cleanedStack = stackLines || [];
1097
- }
1098
- toJSON() {
1099
- return {
1100
- ...super.toJSON(),
1101
- cleanedStack: this.cleanedStack
1102
- };
1103
- }
1104
- };
1105
- var ParseError = class extends VarlockError {
1106
- static {
1107
- __name(this, "ParseError");
1108
- }
1109
- static defaultIcon = "\u{1F635}\u200D\u{1F4AB}";
1110
- };
1111
- var SchemaError = class extends VarlockError {
1112
- static {
1113
- __name(this, "SchemaError");
1114
- }
1115
- static defaultIcon = "\u{1F9F0}";
1116
- };
1117
- var ValidationError = class extends VarlockError {
1118
- static {
1119
- __name(this, "ValidationError");
1120
- }
1121
- static defaultIcon = "\u274C";
1122
- };
1123
- var CoercionError = class extends VarlockError {
1124
- static {
1125
- __name(this, "CoercionError");
1126
- }
1127
- static defaultIcon = "\u{1F6D1}";
1128
- };
1129
- var ResolutionError = class _ResolutionError extends VarlockError {
1130
- static {
1131
- __name(this, "ResolutionError");
1132
- }
1133
- static defaultIcon = "\u26D4";
1134
- _retryable = false;
1135
- set retryable(val) {
1136
- this._retryable = val;
1137
- }
1138
- get retryable() {
1139
- if (this._retryable) return true;
1140
- if (this.originalError instanceof _ResolutionError) return this.originalError.retryable;
1141
- return false;
1142
- }
1143
- };
1144
- var EmptyRequiredValueError = class extends ValidationError {
1145
- static {
1146
- __name(this, "EmptyRequiredValueError");
1147
- }
1148
- icon = "\u2753";
1149
- constructor(_val) {
1150
- super("Value is required but is currently empty");
1151
- }
1152
- };
1153
-
1154
- // ../utils/src/try-catch.ts
1155
- function isPromise2(obj) {
1156
- return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
1157
- }
1158
- __name(isPromise2, "isPromise");
1159
- async function tryCatch(tryFn, catchFn) {
1160
- try {
1161
- return await tryFn();
1162
- } catch (err) {
1163
- const catchResult = catchFn(err);
1164
- if (isPromise2(catchResult)) {
1165
- await catchResult;
1166
- }
1167
- }
1168
- }
1169
- __name(tryCatch, "tryCatch");
1170
- async function pathExists(p) {
1171
- try {
1172
- await access(p);
1173
- return true;
1174
- } catch {
1175
- return false;
1176
- }
1177
- }
1178
- __name(pathExists, "pathExists");
1179
- function pathExistsSync(p) {
1180
- try {
1181
- accessSync(p);
1182
- return true;
1183
- } catch {
1184
- return false;
1185
- }
1186
- }
1187
- __name(pathExistsSync, "pathExistsSync");
1188
-
1189
- // src/env-graph/lib/data-types.ts
1190
- var EnvGraphDataType = class {
1191
- constructor(def, factory) {
1192
- this.def = def;
1193
- this.factory = factory;
1194
- }
1195
- static {
1196
- __name(this, "EnvGraphDataType");
1197
- }
1198
- get name() {
1199
- return this.def.name;
1200
- }
1201
- get icon() {
1202
- return this.def.icon;
1203
- }
1204
- get isSensitive() {
1205
- return this.def.sensitive;
1206
- }
1207
- get docsEntries() {
1208
- return this.def.docs;
1209
- }
1210
- /** @internal */
1211
- get _rawDef() {
1212
- return this.def;
1213
- }
1214
- coerce(val) {
1215
- if (this.def.coerce) return this.def.coerce(val);
1216
- if (val === void 0) return void 0;
1217
- return typeof val === "string" ? val : String(val);
1218
- }
1219
- validate(val) {
1220
- return this.def.validate ? this.def.validate(val) : true;
1221
- }
1222
- };
1223
- function createEnvGraphDataType(dataTypeDef) {
1224
- const typeFactoryFn = /* @__PURE__ */ __name((...usageOpts) => {
1225
- return new EnvGraphDataType(
1226
- my_dash_default.isFunction(dataTypeDef) ? dataTypeDef(...usageOpts) : dataTypeDef,
1227
- typeFactoryFn
1228
- );
1229
- }, "typeFactoryFn");
1230
- typeFactoryFn._isEnvGraphDataTypeFactory = true;
1231
- const exampleInstance = typeFactoryFn(...[]);
1232
- typeFactoryFn.dataTypeName = exampleInstance.name;
1233
- return typeFactoryFn;
1234
- }
1235
- __name(createEnvGraphDataType, "createEnvGraphDataType");
1236
- function coerceToString(rawVal) {
1237
- if (rawVal === void 0 || rawVal === null) return "";
1238
- return my_dash_default.isString(rawVal) ? rawVal : String(rawVal);
1239
- }
1240
- __name(coerceToString, "coerceToString");
1241
- function coerceToNumber(rawVal) {
1242
- let numVal;
1243
- if (my_dash_default.isString(rawVal)) {
1244
- const parsed = parseFloat(rawVal);
1245
- if (my_dash_default.isNan(parsed) || parsed === Infinity || parsed === -Infinity) {
1246
- throw new CoercionError("Unable to coerce string to number");
1247
- }
1248
- numVal = parsed;
1249
- } else if (my_dash_default.isNumber(rawVal)) {
1250
- if (numVal === Infinity || numVal === -Infinity) {
1251
- throw new CoercionError("Inifinity is not a valid number");
1252
- }
1253
- numVal = rawVal;
1254
- } else {
1255
- throw new CoercionError(`Cannot convert ${rawVal} to number`);
1256
- }
1257
- return numVal;
1258
- }
1259
- __name(coerceToNumber, "coerceToNumber");
1260
- var StringDataType = createEnvGraphDataType(
1261
- (settings) => ({
1262
- name: "string",
1263
- icon: "carbon:string-text",
1264
- coerce: /* @__PURE__ */ __name((rawVal) => {
1265
- let val = coerceToString(rawVal);
1266
- if (settings?.toUpperCase) val = val.toUpperCase();
1267
- if (settings?.toLowerCase) val = val.toLowerCase();
1268
- return val;
1269
- }, "coerce"),
1270
- validate: /* @__PURE__ */ __name((val) => {
1271
- const errors = [];
1272
- if (settings?.minLength !== void 0 && val.length < settings.minLength) {
1273
- errors.push(new ValidationError(`Length must be more than ${settings.minLength}`));
1274
- }
1275
- if (settings?.maxLength !== void 0 && val.length > settings.maxLength) {
1276
- errors.push(new ValidationError(`Length must be less than ${settings.maxLength}`));
1277
- }
1278
- if (settings?.isLength !== void 0 && val.length !== settings.isLength) {
1279
- errors.push(new ValidationError(`Length must be exactly ${settings.isLength}`));
1280
- }
1281
- if (settings?.startsWith && !val.startsWith(settings.startsWith)) {
1282
- errors.push(new ValidationError(`Value must start with "${settings.startsWith}"`));
1283
- }
1284
- if (settings?.endsWith && !val.endsWith(settings.endsWith)) {
1285
- errors.push(new ValidationError(`Value must start with "${settings.endsWith}"`));
1286
- }
1287
- if (settings?.matches) {
1288
- const regex = my_dash_default.isString(settings.matches) ? new RegExp(settings.matches) : settings.matches;
1289
- const matches = val.match(regex);
1290
- if (!matches) {
1291
- errors.push(new ValidationError(`Value must match regex "${settings.matches}"`));
1292
- }
1293
- }
1294
- return errors.length ? errors : true;
1295
- }, "validate")
1296
- })
1297
- );
1298
- var NumberDataType = createEnvGraphDataType(
1299
- (settings) => ({
1300
- name: "number",
1301
- icon: "carbon:string-integer",
1302
- coerce(rawVal) {
1303
- let numVal = coerceToNumber(rawVal);
1304
- if (settings?.coerceToMinMaxRange) {
1305
- if (settings?.min !== void 0) numVal = Math.max(settings?.min, numVal);
1306
- if (settings?.max !== void 0) numVal = Math.min(settings?.max, numVal);
1307
- }
1308
- if (settings?.isInt === true || settings?.precision === 0) {
1309
- numVal = Math.round(numVal);
1310
- } else if (settings?.precision) {
1311
- const p = 10 ** settings.precision;
1312
- numVal = Math.round(numVal * p) / p;
1313
- }
1314
- return numVal;
1315
- },
1316
- validate(val) {
1317
- const errors = [];
1318
- if (settings?.min !== void 0 && val < settings?.min) {
1319
- errors.push(new ValidationError(`Min value is ${settings?.min}`));
1320
- }
1321
- if (settings?.max !== void 0 && val > settings?.max) {
1322
- errors.push(new ValidationError(`Max value is ${settings?.max}`));
1323
- }
1324
- if (settings?.isDivisibleBy !== void 0 && val % settings.isDivisibleBy !== 0) {
1325
- errors.push(new ValidationError(`Value must be divisible by ${settings?.isDivisibleBy}`));
1326
- }
1327
- return errors.length ? errors : true;
1328
- }
1329
- })
1330
- );
1331
- var BooleanDataType = createEnvGraphDataType({
1332
- name: "boolean",
1333
- icon: "carbon:boolean",
1334
- // probably want allow some settings
1335
- // - more strict about coercion or adding additional true/false values
1336
- // - coercing to other values - like 0,1
1337
- coerce(val) {
1338
- if (my_dash_default.isBoolean(val)) {
1339
- return val;
1340
- } else if (my_dash_default.isString(val)) {
1341
- const cleanVal = val.toLowerCase().trim();
1342
- if (["t", "true", "yes", "on", "1"].includes(cleanVal)) return true;
1343
- if (["f", "false", "no", "off", "0"].includes(cleanVal)) return false;
1344
- throw new CoercionError("Unable to coerce string value to boolean");
1345
- } else if (my_dash_default.isNumber(val)) {
1346
- if (val === 0) return false;
1347
- if (val === 1) return true;
1348
- throw new CoercionError("Unable to coerce number value to boolean (only 0 or 1 is valid)");
1349
- } else {
1350
- throw new CoercionError("Unable to coerce value to boolean");
1351
- }
1352
- },
1353
- // TODO: add settings to be more strict, or to allow other values to coerce to true/false
1354
- validate(val) {
1355
- if (my_dash_default.isBoolean(val)) return true;
1356
- return new ValidationError("Value must be `true` or `false`");
1357
- }
1358
- });
1359
- var UrlDataType = createEnvGraphDataType(
1360
- (settings) => ({
1361
- name: "url",
1362
- icon: "carbon:url",
1363
- coerce(rawVal) {
1364
- const val = coerceToString(rawVal);
1365
- if (settings?.prependHttps && !val.startsWith("https://")) return `https://${val}`;
1366
- return val;
1367
- },
1368
- validate(val) {
1369
- let url;
1370
- try {
1371
- url = new URL(val);
1372
- } catch (err) {
1373
- throw new ValidationError("Invalid URL");
1374
- }
1375
- if (settings?.allowedDomains && !settings.allowedDomains.includes(url.host.toLowerCase())) {
1376
- return new ValidationError(`Domain (${url.host}) is not in allowed list: ${settings.allowedDomains.join(",")}`);
1377
- }
1378
- return true;
1379
- }
1380
- })
1381
- );
1382
- var SimpleObjectDataType = createEnvGraphDataType({
1383
- name: "simple-object",
1384
- icon: "tabler:code-dots",
1385
- // curly brackets with nothing inside
1386
- coerce(val) {
1387
- if (my_dash_default.isPlainObject(val)) return val;
1388
- if (my_dash_default.isString(val)) {
1389
- try {
1390
- const parsedObj = JSON.parse(val);
1391
- if (my_dash_default.isPlainObject(parsedObj)) return parsedObj;
1392
- return new CoercionError("Unable to coerce JSON parsed string to object");
1393
- } catch (err) {
1394
- return new CoercionError("Error parsing JSON string while coercing string to object");
1395
- }
1396
- }
1397
- return new CoercionError("Cannot coerce value to object");
1398
- },
1399
- validate(val) {
1400
- if (my_dash_default.isPlainObject(val)) return true;
1401
- return new ValidationError("Value must be an object");
1402
- }
1403
- });
1404
- var EnumDataType = createEnvGraphDataType(
1405
- (...enumOptions) => ({
1406
- name: "enum",
1407
- icon: "material-symbols-light:category",
1408
- // a few shapes... not sure about this one
1409
- coerce(val) {
1410
- if (my_dash_default.isString(val) || my_dash_default.isNumber(val) || my_dash_default.isBoolean(val)) return val;
1411
- return new CoercionError("Value must be a string, number, or boolean");
1412
- },
1413
- validate(val) {
1414
- const possibleValues = enumOptions || [];
1415
- if (!possibleValues.includes(val)) {
1416
- throw new ValidationError("Current value is not in list of possible values", {
1417
- tip: `Possible values are: "${possibleValues.join('", "')}"`
1418
- });
1419
- }
1420
- },
1421
- _rawEnumOptions: enumOptions
1422
- })
1423
- );
1424
- var EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1425
- var EmailDataType = createEnvGraphDataType(
1426
- (settings) => ({
1427
- name: "email",
1428
- icon: "iconoir:at-sign",
1429
- typeDescription: "standard email address",
1430
- coerce(rawVal) {
1431
- let val = coerceToString(rawVal);
1432
- if (settings?.normalize) val = val.toLowerCase();
1433
- return val;
1434
- },
1435
- validate(val) {
1436
- const result = EMAIL_REGEX.test(val);
1437
- if (result) return true;
1438
- return new ValidationError("Value must be a valid email address");
1439
- }
1440
- })
1441
- );
1442
- var IP_V4_ADDRESS_REGEX = /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/;
1443
- var IP_V6_ADDRESS_REGEX = /^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$/;
1444
- var IpAddressDataType = createEnvGraphDataType(
1445
- (settings) => ({
1446
- name: "ip",
1447
- icon: "iconoir:ip-address-tag",
1448
- typeDescription: "ip v4 or v6 address",
1449
- coerce(rawVal) {
1450
- let val = coerceToString(rawVal);
1451
- if (settings?.normalize) val = val.toLowerCase();
1452
- return val;
1453
- },
1454
- validate(val) {
1455
- const regex = settings?.version === 6 ? IP_V6_ADDRESS_REGEX : IP_V4_ADDRESS_REGEX;
1456
- const result = regex.test(val);
1457
- if (result) return true;
1458
- return new ValidationError("Value must be a valid IP address");
1459
- }
1460
- })
1461
- );
1462
- var PortDataType = createEnvGraphDataType(
1463
- (settings) => ({
1464
- name: "port",
1465
- icon: "material-symbols:captive-portal",
1466
- //! globe with arrow - not sure about this one
1467
- typeDescription: "valid port number between 0 and 65535",
1468
- coerce(rawVal) {
1469
- if (my_dash_default.isString(rawVal)) {
1470
- if (rawVal.includes(".")) throw new CoercionError("Port number must be an integer");
1471
- if (rawVal.includes("e")) throw new CoercionError("Port number should be an integer, not in exponential notation");
1472
- }
1473
- return coerceToNumber(rawVal);
1474
- },
1475
- validate(val) {
1476
- if (settings?.min !== void 0 && val < settings?.min) {
1477
- return new ValidationError(`Min value is ${settings?.min}`);
1478
- }
1479
- if (settings?.max !== void 0 && val > settings?.max) {
1480
- return new ValidationError(`Max value is ${settings?.max}`);
1481
- }
1482
- if (val < 0 || val > 65535) {
1483
- return new ValidationError("Value must be a valid port number (0-65535)");
1484
- }
1485
- return true;
1486
- }
1487
- })
1488
- );
1489
- var SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
1490
- var SemverDataType = createEnvGraphDataType(
1491
- (_settings) => ({
1492
- name: "semver",
1493
- icon: "simple-icons:semver",
1494
- typeDescription: "semantic version string",
1495
- validate(val) {
1496
- const result = SEMVER_REGEX.test(val);
1497
- if (result) return true;
1498
- return new ValidationError("Value must be a valid semantic version string");
1499
- }
1500
- })
1501
- );
1502
- var ISO_DATE_REGEX = /^(?:[+-]?\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24:?00)(?:[.,]\d+(?!:))?)?(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[zZ]|(?:[+-])(?:[01]\d|2[0-3]):?(?:[0-5]\d)?)?)?)?$/;
1503
- var IsoDateDataType = createEnvGraphDataType({
1504
- name: "isoDate",
1505
- icon: "formkit:datetime",
1506
- typeDescription: "ISO 8601 date string with optional time and milliseconds",
1507
- validate(val) {
1508
- const result = ISO_DATE_REGEX.test(val);
1509
- if (result) return true;
1510
- return new ValidationError("Value must be a valid ISO 8601 date string");
1511
- }
1512
- });
1513
- var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1514
- var UuidDataType = createEnvGraphDataType({
1515
- name: "uuid",
1516
- icon: "mdi:identifier",
1517
- typeDescription: "UUID string V1-V5 per RFC4122, including NIL",
1518
- validate(val) {
1519
- const result = UUID_REGEX.test(val);
1520
- if (result) return true;
1521
- return new ValidationError("Value must be a valid UUID string");
1522
- }
1523
- });
1524
- var MD5_REGEX = /^[a-f0-9]{32}$/;
1525
- var Md5DataType = createEnvGraphDataType({
1526
- name: "md5",
1527
- typeDescription: "MD5 hash string",
1528
- validate(val) {
1529
- const result = MD5_REGEX.test(val);
1530
- if (result) return true;
1531
- return new ValidationError("Value must be a valid MD5 hash string");
1532
- }
1533
- });
1534
- var BaseDataTypes = [
1535
- StringDataType,
1536
- NumberDataType,
1537
- BooleanDataType,
1538
- SimpleObjectDataType,
1539
- EnumDataType,
1540
- EmailDataType,
1541
- UrlDataType,
1542
- IpAddressDataType,
1543
- PortDataType,
1544
- SemverDataType,
1545
- IsoDateDataType,
1546
- UuidDataType,
1547
- Md5DataType
1548
- ];
1549
-
1550
- // src/env-graph/lib/simple-queue.ts
1551
- var SimpleQueue = class {
1552
- static {
1553
- __name(this, "SimpleQueue");
1554
- }
1555
- queue = [];
1556
- processing = false;
1557
- /** Add a task to the queue and return a promise that resolves when the task is complete */
1558
- async enqueue(task) {
1559
- return new Promise((resolve, reject) => {
1560
- this.queue.push(async () => {
1561
- try {
1562
- const result = await task();
1563
- resolve(result);
1564
- } catch (err) {
1565
- reject(err);
1566
- }
1567
- });
1568
- this.processQueue();
1569
- });
1570
- }
1571
- async processQueue() {
1572
- if (this.processing || this.queue.length === 0) {
1573
- return;
1574
- }
1575
- this.processing = true;
1576
- const task = this.queue.shift();
1577
- if (task) {
1578
- try {
1579
- await task();
1580
- } finally {
1581
- this.processing = false;
1582
- this.processQueue();
1583
- }
1584
- }
1585
- }
1586
- };
1587
- var DecoratorInstance = class {
1588
- static {
1589
- __name(this, "DecoratorInstance");
1590
- }
1591
- get name() {
1592
- return this.parsedDecorator.name;
1593
- }
1594
- get isFunctionCall() {
1595
- return !!this.parsedDecorator.isBareFnCall;
1596
- }
1597
- // decorator value/args are translated into a resolver when we process the decorator
1598
- _decValueResolver;
1599
- get decValueResolver() {
1600
- return this._decValueResolver;
1601
- }
1602
- _schemaErrors = [];
1603
- get schemaErrors() {
1604
- return [
1605
- ...this._schemaErrors,
1606
- ...this._decValueResolver?.schemaErrors || []
1607
- ];
1608
- }
1609
- // error encountered during `execute` function
1610
- _executionError;
1611
- decoratorDef;
1612
- get incompatibleWith() {
1613
- return this.decoratorDef?.incompatibleWith;
1614
- }
1615
- processed = false;
1616
- processedData;
1617
- async process() {
1618
- if (this.processed) return;
1619
- this.processed = true;
1620
- if (!this.graph) throw new Error("expected graph to be set");
1621
- try {
1622
- const decRegistry = this.isRootDecorator ? this.graph.rootDecoratorsRegistry : this.graph.itemDecoratorsRegistry;
1623
- this.decoratorDef = decRegistry[this.name];
1624
- if (!this.decoratorDef) {
1625
- throw new Error(`Unknown decorator: @${this.name}`);
1626
- }
1627
- if (this.decoratorDef.useFnArgsResolver && this.parsedDecorator.value instanceof ParsedEnvSpecFunctionCall) {
1628
- this._decValueResolver = convertParsedValueToResolvers(
1629
- this.parsedDecorator.value.data.args,
1630
- this.dataSource,
1631
- this.graph.registeredResolverFunctions
1632
- );
1633
- } else {
1634
- this._decValueResolver = convertParsedValueToResolvers(
1635
- this.parsedDecorator.value,
1636
- this.dataSource,
1637
- this.graph.registeredResolverFunctions
1638
- );
1639
- }
1640
- if (this.decValueResolver) {
1641
- await this.decValueResolver.process(this);
1642
- this.processedData = await this.decoratorDef.process?.(this.decValueResolver);
1643
- }
1644
- } catch (e) {
1645
- this._schemaErrors.push(e instanceof SchemaError ? e : new SchemaError(e));
1646
- }
1647
- }
1648
- async execute() {
1649
- await this.decoratorDef.execute?.(this.processedData);
1650
- }
1651
- resolvedValue;
1652
- isResolved = false;
1653
- async resolve() {
1654
- if (this.isResolved) return this.resolvedValue;
1655
- await this.process();
1656
- if (!this.decValueResolver) throw new Error("expected decorator to have a value resolver");
1657
- try {
1658
- this.resolvedValue = await this.decValueResolver.resolve();
1659
- } catch (err) {
1660
- this._schemaErrors.push(err);
1661
- return;
1662
- }
1663
- this.isResolved = true;
1664
- return this.resolvedValue;
1665
- }
1666
- };
1667
- var ItemDecoratorInstance = class extends DecoratorInstance {
1668
- constructor(configItem, dataSource, parsedDecorator) {
1669
- super();
1670
- this.configItem = configItem;
1671
- this.dataSource = dataSource;
1672
- this.parsedDecorator = parsedDecorator;
1673
- }
1674
- static {
1675
- __name(this, "ItemDecoratorInstance");
1676
- }
1677
- isRootDecorator = false;
1678
- get graph() {
1679
- return this.dataSource.graph;
1680
- }
1681
- };
1682
- var RootDecoratorInstance = class extends DecoratorInstance {
1683
- constructor(dataSource, parsedDecorator) {
1684
- super();
1685
- this.dataSource = dataSource;
1686
- this.parsedDecorator = parsedDecorator;
1687
- }
1688
- static {
1689
- __name(this, "RootDecoratorInstance");
1690
- }
1691
- isRootDecorator = true;
1692
- get graph() {
1693
- return this.dataSource.graph;
1694
- }
1695
- };
1696
- var builtInRootDecorators = [
1697
- {
1698
- name: "envFlag",
1699
- deprecated: "use @currentEnv instead"
1700
- },
1701
- {
1702
- name: "currentEnv",
1703
- incompatibleWith: ["envFlag"]
1704
- },
1705
- {
1706
- name: "defaultRequired",
1707
- process: /* @__PURE__ */ __name((decVal) => {
1708
- if (!decVal.isStatic || ![true, false, "infer"].includes(decVal.staticValue)) {
1709
- throw new Error('@defaultRequired decorator value must be set to a static value of true, false, or "infer"');
1710
- }
1711
- }, "process")
1712
- },
1713
- {
1714
- name: "defaultSensitive",
1715
- process: /* @__PURE__ */ __name((decVal) => {
1716
- if (decVal.isStatic && !my_dash_default.isBoolean(decVal.staticValue) || !decVal.isStatic && decVal.fnName && decVal.fnName !== "inferFromPrefix") {
1717
- throw new Error("only true, false, or `inferFromPrefix()` is allowed for @defaultSensitive decorator");
1718
- }
1719
- }, "process")
1720
- },
1721
- {
1722
- name: "disable"
1723
- },
1724
- {
1725
- name: "generateTypes",
1726
- isFunction: true
1727
- },
1728
- {
1729
- name: "import",
1730
- isFunction: true,
1731
- process: /* @__PURE__ */ __name((decVal) => {
1732
- if (!decVal.arrArgs || decVal.arrArgs.length === 0) {
1733
- throw new Error("@import decorator must have at least one argument - the path to import");
1734
- }
1735
- if (decVal.arrArgs.some((a2) => !a2.isStatic)) {
1736
- throw new Error("@import decorator cannot use any dynamic values - all args must be static");
1737
- }
1738
- }, "process")
1739
- },
1740
- {
1741
- name: "plugin",
1742
- isFunction: true
1743
- },
1744
- {
1745
- name: "redactLogs"
1746
- },
1747
- {
1748
- name: "preventLeaks"
1749
- }
1750
- ];
1751
- var builtInItemDecorators = [
1752
- {
1753
- name: "required"
1754
- },
1755
- {
1756
- name: "optional",
1757
- incompatibleWith: ["required"]
1758
- },
1759
- {
1760
- name: "sensitive"
1761
- },
1762
- {
1763
- name: "public",
1764
- incompatibleWith: ["sensitive"]
1765
- },
1766
- {
1767
- name: "type",
1768
- useFnArgsResolver: true
1769
- },
1770
- {
1771
- name: "example"
1772
- },
1773
- {
1774
- name: "docsUrl",
1775
- deprecated: "use `docs()` instead"
1776
- },
1777
- {
1778
- name: "docs",
1779
- isFunction: true
1780
- },
1781
- {
1782
- name: "icon"
1783
- }
1784
- ];
1785
-
1786
- // src/env-graph/lib/resolver.ts
1787
- var execAsync = promisify(exec);
1788
- var Resolver = class {
1789
- constructor(arrArgs, objArgs, dataSource) {
1790
- this.arrArgs = arrArgs;
1791
- this.objArgs = objArgs;
1792
- this.dataSource = dataSource;
1793
- if (this.def.inferredType) this.inferredType = this.def.inferredType;
1794
- }
1795
- static {
1796
- __name(this, "Resolver");
1797
- }
1798
- static def;
1799
- static get fnName() {
1800
- return this.def.name;
1801
- }
1802
- get def() {
1803
- return this.constructor.def;
1804
- }
1805
- get fnName() {
1806
- return this.def.name;
1807
- }
1808
- get label() {
1809
- return this.def.label;
1810
- }
1811
- get icon() {
1812
- return this.def.icon;
1813
- }
1814
- get isStatic() {
1815
- return false;
1816
- }
1817
- get staticValue() {
1818
- return void 0;
1819
- }
1820
- inferredType;
1821
- _schemaErrors = [];
1822
- _depsObj = {};
1823
- get childResolvers() {
1824
- return [
1825
- ...this.arrArgs ?? [],
1826
- ...Object.values(this.objArgs ?? {})
1827
- ];
1828
- }
1829
- get schemaErrors() {
1830
- return [
1831
- ...this._schemaErrors,
1832
- ...this.childResolvers.flatMap((r) => r.schemaErrors)
1833
- ];
1834
- }
1835
- set schemaErrors(v) {
1836
- throw new Error("set _schemaErrors instead");
1837
- }
1838
- get depsObj() {
1839
- const mergedDepsObj = { ...this._depsObj };
1840
- this.childResolvers.forEach((r) => Object.assign(mergedDepsObj, r.depsObj));
1841
- return mergedDepsObj;
1842
- }
1843
- get deps() {
1844
- return Object.keys(this.depsObj);
1845
- }
1846
- parent;
1847
- meta;
1848
- process(parent) {
1849
- this.parent = parent;
1850
- const { argsSchema } = this.def;
1851
- if (argsSchema?.type === "array" && this.objArgs !== void 0) {
1852
- this._schemaErrors.push(new SchemaError("Resolver does not support key-value args"));
1853
- } else if (argsSchema?.type === "object" && this.arrArgs !== void 0) {
1854
- this._schemaErrors.push(new SchemaError("Resolver expects only key-value args"));
1855
- }
1856
- if (argsSchema?.arrayExactLength !== void 0) {
1857
- if (this.arrArgs?.length !== argsSchema.arrayExactLength) {
1858
- this._schemaErrors.push(
1859
- new SchemaError(
1860
- `expects exactly ${argsSchema.arrayExactLength} argument${argsSchema.arrayExactLength > 1 ? "s" : ""}`
1861
- )
1862
- );
1863
- }
1864
- }
1865
- if (argsSchema?.arrayMinLength !== void 0) {
1866
- if ((this.arrArgs?.length ?? 0) < argsSchema.arrayMinLength) {
1867
- this._schemaErrors.push(
1868
- new SchemaError(
1869
- `expects at least ${argsSchema.arrayMinLength} argument${argsSchema.arrayMinLength > 1 ? "s" : ""}`
1870
- )
1871
- );
1872
- }
1873
- }
1874
- if (argsSchema?.arrayMaxLength !== void 0) {
1875
- if ((this.arrArgs?.length ?? 0) > argsSchema.arrayMaxLength) {
1876
- this._schemaErrors.push(
1877
- new SchemaError(`expects at most ${argsSchema.arrayMaxLength} argument${argsSchema.arrayMaxLength > 1 ? "s" : ""}`)
1878
- );
1879
- }
1880
- }
1881
- if (argsSchema?.objKeyMinLength !== void 0) {
1882
- const objKeyLengths = Object.keys(this.objArgs || {}).length;
1883
- if (objKeyLengths < argsSchema.objKeyMinLength) {
1884
- this._schemaErrors.push(
1885
- new SchemaError(
1886
- `expects at least ${argsSchema.objKeyMinLength} key value arg${argsSchema.objKeyMinLength > 1 ? "s" : ""}`
1887
- )
1888
- );
1889
- }
1890
- }
1891
- if (this._schemaErrors.length === 0) {
1892
- try {
1893
- this.meta = this.def.process?.call(this);
1894
- } catch (error) {
1895
- if (error instanceof SchemaError) {
1896
- this._schemaErrors.push(error);
1897
- } else if (error instanceof Error) {
1898
- this._schemaErrors.push(new SchemaError(error));
1899
- } else {
1900
- throw new Error(`Non-error thrown while processing resolver - ${error}`);
1901
- }
1902
- }
1903
- }
1904
- if (!this.def.name.startsWith("\0")) {
1905
- for (const e of this._schemaErrors) {
1906
- e.message = `${this.def.name}(): ${e.message}`;
1907
- }
1908
- }
1909
- this.childResolvers.forEach((r) => {
1910
- r.process(parent);
1911
- });
1912
- }
1913
- // meant to be used by subclass _process methods
1914
- addDep(key) {
1915
- if (!this.envGraph.configSchema[key]) {
1916
- throw new Error(`invalid dependency: ${key}`);
1917
- }
1918
- this._depsObj[key] = true;
1919
- }
1920
- async getCurrentEnv() {
1921
- if (!this.dataSource) throw new Error("expected dataSource to be set");
1922
- await this.dataSource.resolveCurrentEnv();
1923
- return this.dataSource.envFlagValue ? String(this.dataSource.envFlagValue) : void 0;
1924
- }
1925
- async resolve() {
1926
- const resolvedValue = await this.def.resolve.call(this, this.meta);
1927
- return resolvedValue;
1928
- }
1929
- get envGraph() {
1930
- if (this.parent instanceof ConfigItem) {
1931
- return this.parent.envGraph;
1932
- } else if (this.parent instanceof DecoratorInstance) {
1933
- return this.parent.graph;
1934
- }
1935
- }
1936
- // meant to be used by subclass _resolve methods
1937
- getDepValue(key) {
1938
- const depItem = this.envGraph?.configSchema[key];
1939
- if (!depItem) throw new Error(`Referenced item "${key}" not found`);
1940
- if (!depItem.isValid) throw new Error(`Referenced item "${key}" is not valid`);
1941
- return depItem.resolvedValue;
1942
- }
1943
- };
1944
- var StaticValueResolver = class extends Resolver {
1945
- constructor(_staticValue) {
1946
- super([]);
1947
- this._staticValue = _staticValue;
1948
- if (_staticValue !== void 0) {
1949
- this.inferredType = typeof _staticValue;
1950
- }
1951
- }
1952
- static {
1953
- __name(this, "StaticValueResolver");
1954
- }
1955
- static def = {
1956
- name: "\0static",
1957
- // used internally, so we add the extra \0
1958
- icon: "bi:dash",
1959
- async resolve() {
1960
- return this.staticValue;
1961
- }
1962
- };
1963
- // helper so plugins dont need to import and use instanceof
1964
- get isStatic() {
1965
- return true;
1966
- }
1967
- get staticValue() {
1968
- return this._staticValue;
1969
- }
1970
- };
1971
- var FunctionArgsResolver = class extends Resolver {
1972
- static {
1973
- __name(this, "FunctionArgsResolver");
1974
- }
1975
- // we might want to just have a resolve function which resolves all children
1976
- // but it might be useful to let the decorator do it individually
1977
- // so that some can be skipped depending on the other args
1978
- static def = {
1979
- name: "\0fnArgs",
1980
- // used internally, so we add the extra \0
1981
- label: "function args",
1982
- icon: "bi:dash",
1983
- // not actualyl used
1984
- resolve() {
1985
- return void 0;
1986
- }
1987
- };
1988
- // special helper to resolve all child args
1989
- async resolve() {
1990
- const resolvedArrayArgs = [];
1991
- const resolvedObjArgs = {};
1992
- for (const arg of this.arrArgs || []) {
1993
- resolvedArrayArgs.push(await arg.resolve());
1994
- }
1995
- for (const key in this.objArgs) {
1996
- resolvedObjArgs[key] = await this.objArgs[key].resolve();
1997
- }
1998
- return {
1999
- arr: resolvedArrayArgs,
2000
- obj: resolvedObjArgs
2001
- };
2002
- }
2003
- };
2004
- var ErrorResolver = class extends Resolver {
2005
- constructor(err) {
2006
- super([]);
2007
- this.err = err;
2008
- this._schemaErrors.push(err);
2009
- }
2010
- static {
2011
- __name(this, "ErrorResolver");
2012
- }
2013
- static def = {
2014
- name: "\0error",
2015
- // used internally, so we add the extra \0
2016
- icon: "bi:dash",
2017
- async resolve() {
2018
- return void 0;
2019
- }
2020
- };
2021
- };
2022
- function createResolver(def) {
2023
- const ResolverClass = class extends Resolver {
2024
- static {
2025
- __name(this, "ResolverClass");
2026
- }
2027
- };
2028
- ResolverClass.def = def;
2029
- return ResolverClass;
2030
- }
2031
- __name(createResolver, "createResolver");
2032
- var ConcatResolver = createResolver({
2033
- name: "concat",
2034
- icon: "material-symbols:join",
2035
- inferredType: "string",
2036
- argsSchema: {
2037
- type: "array",
2038
- arrayMinLength: 2
2039
- },
2040
- async resolve() {
2041
- const resolvedValues = [];
2042
- for (const arg of this.arrArgs ?? []) {
2043
- const resolvedChildValue = await arg.resolve();
2044
- resolvedValues.push(String(resolvedChildValue ?? ""));
2045
- }
2046
- return resolvedValues.join("");
2047
- }
2048
- });
2049
- var FallbackResolver = createResolver({
2050
- name: "fallback",
2051
- icon: "memory:table-top-stairs-up",
2052
- argsSchema: {
2053
- type: "array",
2054
- arrayMinLength: 2
2055
- },
2056
- async resolve() {
2057
- for (const arg of this.arrArgs ?? []) {
2058
- const resolvedChildValue = await arg.resolve();
2059
- if (resolvedChildValue !== void 0 && resolvedChildValue !== "") {
2060
- return resolvedChildValue;
2061
- }
2062
- }
2063
- }
2064
- });
2065
- var execQueue = new SimpleQueue();
2066
- var ExecResolver = createResolver({
2067
- name: "exec",
2068
- icon: "iconoir:terminal",
2069
- argsSchema: {
2070
- type: "array",
2071
- arrayExactLength: 1
2072
- },
2073
- async resolve() {
2074
- const commandStr = await this.arrArgs?.[0].resolve();
2075
- if (typeof commandStr !== "string") {
2076
- throw new ResolutionError("exec() expects a string arg");
2077
- }
2078
- try {
2079
- const { stdout } = await execQueue.enqueue(() => execAsync(commandStr));
2080
- return stdout.replace(/\n$/, "");
2081
- } catch (err) {
2082
- console.log("exec() failed", err);
2083
- throw new ResolutionError(`exec() command failed: ${commandStr}`);
2084
- }
2085
- }
2086
- });
2087
- var RefResolver = createResolver({
2088
- name: "ref",
2089
- icon: "mdi-light:content-duplicate",
2090
- argsSchema: {
2091
- type: "array",
2092
- arrayExactLength: 1
2093
- },
2094
- process() {
2095
- if (!(this.arrArgs?.[0] instanceof StaticValueResolver)) {
2096
- throw new SchemaError("expects a single static value passed in");
2097
- }
2098
- const refKey = this.arrArgs[0].staticValue;
2099
- if (typeof refKey !== "string") {
2100
- throw new SchemaError("expects a string keyname passed in");
2101
- }
2102
- this.addDep(refKey);
2103
- return refKey;
2104
- },
2105
- async resolve(refKey) {
2106
- return this.getDepValue(refKey);
2107
- }
2108
- });
2109
- var RegexResolver = createResolver({
2110
- name: "regex",
2111
- icon: "mdi:regex",
2112
- argsSchema: {
2113
- type: "array",
2114
- arrayExactLength: 1
2115
- },
2116
- process() {
2117
- if (!(this.arrArgs?.[0] instanceof StaticValueResolver)) {
2118
- throw new SchemaError("expects a single static value passed in");
2119
- }
2120
- const regexStr = this.arrArgs[0].staticValue;
2121
- if (typeof regexStr !== "string") {
2122
- throw new SchemaError("expects a string");
2123
- }
2124
- try {
2125
- return new RegExp(regexStr);
2126
- } catch (err) {
2127
- throw new SchemaError(err.message);
2128
- }
2129
- },
2130
- async resolve(regex) {
2131
- return regex;
2132
- }
2133
- });
2134
- var RemapResolver = createResolver({
2135
- name: "remap",
2136
- icon: "codicon:replace",
2137
- argsSchema: {
2138
- type: "mixed",
2139
- arrayExactLength: 1,
2140
- objKeyMinLength: 1
2141
- },
2142
- process() {
2143
- return this.objArgs;
2144
- },
2145
- async resolve(remappings) {
2146
- const originalValue = await this.arrArgs[0].resolve();
2147
- for (const [remappedVal, matchValResolver] of Object.entries(remappings)) {
2148
- const matchVal = await matchValResolver.resolve();
2149
- if (matchVal instanceof RegExp && originalValue !== void 0) {
2150
- if (matchVal.test(String(originalValue))) return remappedVal;
2151
- } else {
2152
- if (matchVal === originalValue) return remappedVal;
2153
- }
2154
- }
2155
- return originalValue;
2156
- }
2157
- });
2158
- var ForEnvResolver = createResolver({
2159
- name: "forEnv",
2160
- icon: "tabler:flag-question",
2161
- inferredType: "boolean",
2162
- argsSchema: {
2163
- type: "array",
2164
- arrayMinLength: 1
2165
- },
2166
- process() {
2167
- const matchEnvs = this.arrArgs.map((r) => String(r.staticValue));
2168
- return matchEnvs;
2169
- },
2170
- async resolve(matchEnvs) {
2171
- const currentEnv = await this.getCurrentEnv();
2172
- if (!currentEnv) throw new SchemaError("current environment is not set");
2173
- return currentEnv && matchEnvs.includes(currentEnv || "");
2174
- }
2175
- });
2176
- var EqResolver = createResolver({
2177
- name: "eq",
2178
- icon: "material-symbols:equal",
2179
- inferredType: "boolean",
2180
- argsSchema: {
2181
- type: "array",
2182
- arrayExactLength: 2
2183
- },
2184
- process() {
2185
- return { left: this.arrArgs[0], right: this.arrArgs[1] };
2186
- },
2187
- async resolve({ left, right }) {
2188
- const leftVal = await left.resolve();
2189
- const rightVal = await right.resolve();
2190
- return leftVal === rightVal;
2191
- }
2192
- });
2193
- var IfResolver = createResolver({
2194
- name: "if",
2195
- icon: "material-symbols:help-center",
2196
- // question mark
2197
- argsSchema: {
2198
- type: "array",
2199
- arrayMinLength: 1
2200
- },
2201
- process() {
2202
- const condition = this.arrArgs[0];
2203
- const trueVal = this.arrArgs[1];
2204
- const falseVal = this.arrArgs[2];
2205
- if (!trueVal) {
2206
- this.inferredType = "boolean";
2207
- } else if (!falseVal || trueVal.inferredType === falseVal.inferredType) {
2208
- this.inferredType = trueVal.inferredType;
2209
- }
2210
- return { condition, trueVal, falseVal };
2211
- },
2212
- async resolve({ condition, trueVal, falseVal }) {
2213
- const conditionVal = await condition.resolve();
2214
- if (conditionVal) {
2215
- return trueVal ? trueVal.resolve() : true;
2216
- } else {
2217
- if (falseVal) return falseVal.resolve();
2218
- if (trueVal) return void 0;
2219
- return false;
2220
- }
2221
- }
2222
- });
2223
- var NotResolver = createResolver({
2224
- name: "not",
2225
- icon: "material-symbols:not-equal",
2226
- inferredType: "boolean",
2227
- argsSchema: {
2228
- type: "array",
2229
- arrayExactLength: 1
2230
- },
2231
- async resolve() {
2232
- const value = await this.arrArgs[0].resolve();
2233
- return !value;
2234
- }
2235
- });
2236
- var IsEmptyResolver = createResolver({
2237
- name: "isEmpty",
2238
- icon: "material-symbols:empty",
2239
- inferredType: "boolean",
2240
- argsSchema: {
2241
- type: "array",
2242
- arrayExactLength: 1
2243
- },
2244
- async resolve() {
2245
- const value = await this.arrArgs[0].resolve();
2246
- return value === void 0 || value === "";
2247
- }
2248
- });
2249
- var InferFromPrefixResolver = createResolver({
2250
- name: "inferFromPrefix",
2251
- icon: "material-symbols:help-center",
2252
- // question mark
2253
- argsSchema: {
2254
- type: "array",
2255
- arrayExactLength: 1
2256
- },
2257
- process() {
2258
- return this.arrArgs[0].staticValue;
2259
- },
2260
- async resolve(_prefix) {
2261
- return void 0;
2262
- }
2263
- });
2264
- var BaseResolvers = [
2265
- ConcatResolver,
2266
- FallbackResolver,
2267
- RefResolver,
2268
- ExecResolver,
2269
- RemapResolver,
2270
- ForEnvResolver,
2271
- EqResolver,
2272
- IfResolver,
2273
- NotResolver,
2274
- IsEmptyResolver,
2275
- RegexResolver,
2276
- InferFromPrefixResolver
2277
- ];
2278
- function convertParsedValueToResolvers(value, dataSource, registeredResolvers) {
2279
- if (value === void 0) {
2280
- return void 0;
2281
- } else if (value instanceof ParsedEnvSpecStaticValue) {
2282
- return new StaticValueResolver(value.unescapedValue);
2283
- } else if (value instanceof ParsedEnvSpecFunctionCall || value instanceof ParsedEnvSpecFunctionArgs) {
2284
- let ResolverFnClass;
2285
- let argsFromParser;
2286
- if (value instanceof ParsedEnvSpecFunctionCall) {
2287
- ResolverFnClass = registeredResolvers[value.name];
2288
- if (!ResolverFnClass) {
2289
- return new ErrorResolver(new SchemaError(`Unknown resolver function: ${value.name}()`));
2290
- }
2291
- argsFromParser = value.data.args.values;
2292
- } else {
2293
- ResolverFnClass = FunctionArgsResolver;
2294
- argsFromParser = value.values;
2295
- }
2296
- let arrArgsAsResolvers;
2297
- let objArgsAsResolvers;
2298
- for (const arg of argsFromParser) {
2299
- if (arg instanceof ParsedEnvSpecKeyValuePair) {
2300
- objArgsAsResolvers ??= {};
2301
- const valResolver = convertParsedValueToResolvers(arg.value, dataSource, registeredResolvers);
2302
- if (!valResolver) throw new Error("Did not expect to find undefined resolver in key-value arg");
2303
- objArgsAsResolvers[arg.key] = valResolver;
2304
- } else {
2305
- if (objArgsAsResolvers) {
2306
- return new ErrorResolver(new SchemaError("After switching to key-value function args, cannot switch back"));
2307
- }
2308
- const argResolver = convertParsedValueToResolvers(arg, dataSource, registeredResolvers);
2309
- if (!argResolver) throw new Error("Did not expect to find undefined resolver in array arg");
2310
- arrArgsAsResolvers ??= [];
2311
- arrArgsAsResolvers.push(argResolver);
2312
- }
2313
- }
2314
- return new ResolverFnClass(arrArgsAsResolvers, objArgsAsResolvers, dataSource);
2315
- } else {
2316
- throw new Error("Unknown value type");
2317
- }
2318
- }
2319
- __name(convertParsedValueToResolvers, "convertParsedValueToResolvers");
2320
-
2321
- // src/env-graph/lib/graph-utils.ts
2322
- function findGraphCycles(graph) {
2323
- const visited = /* @__PURE__ */ new Set();
2324
- const recursionStack = /* @__PURE__ */ new Set();
2325
- const cycles = [];
2326
- const currentPath = [];
2327
- function dfs(node) {
2328
- if (recursionStack.has(node)) {
2329
- const cycleStart = currentPath.indexOf(node);
2330
- const cycle = currentPath.slice(cycleStart);
2331
- cycles.push(cycle);
2332
- return;
2333
- }
2334
- if (visited.has(node)) {
2335
- return;
2336
- }
2337
- visited.add(node);
2338
- recursionStack.add(node);
2339
- currentPath.push(node);
2340
- for (const neighbor of graph[node] || []) {
2341
- dfs(neighbor);
2342
- }
2343
- recursionStack.delete(node);
2344
- currentPath.pop();
2345
- }
2346
- __name(dfs, "dfs");
2347
- for (const node of Object.keys(graph)) {
2348
- if (!visited.has(node)) {
2349
- dfs(node);
2350
- }
2351
- }
2352
- return cycles;
2353
- }
2354
- __name(findGraphCycles, "findGraphCycles");
2355
- var AUTOGENERATED_FILE_BANNER = `
2356
- // \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1}
2357
- // \u{1F6D1} THIS IS AN AUTOGENERATED FILE - DO NOT EDIT DIRECTLY \u{1F6D1}
2358
- // \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1} \u{1F6D1}
2359
- `;
2360
- var ICON_SIZE = 20;
2361
- var iconCacheFolderInit = false;
2362
- var iconInMemoryCache = {};
2363
- async function fetchIconSvg(iconifyName, color = "808080", iconCacheFolder = "/tmp/varlock-icon-cache") {
2364
- if (!iconCacheFolderInit) {
2365
- fs.mkdirSync(iconCacheFolder, { recursive: true });
2366
- iconCacheFolderInit = true;
2367
- }
2368
- const iconPath = `${iconCacheFolder}/${iconifyName}-${ICON_SIZE}.svg`;
2369
- let svgSrc;
2370
- if (iconInMemoryCache[iconPath]) {
2371
- svgSrc = iconInMemoryCache[iconPath];
2372
- } else if (fs.existsSync(iconPath)) {
2373
- const svgFileBuffer = await fs.promises.readFile(iconPath, "utf-8");
2374
- svgSrc = svgFileBuffer.toString();
2375
- iconInMemoryCache[iconPath] = svgSrc;
2376
- } else {
2377
- try {
2378
- const iconSvg = await fetch(`https://api.iconify.design/${iconifyName.replace(":", "/")}.svg?height=${ICON_SIZE}`);
2379
- svgSrc = await iconSvg.text();
2380
- } catch (err) {
2381
- return;
2382
- }
2383
- if (!svgSrc) return;
2384
- if (svgSrc) {
2385
- await fs.promises.writeFile(iconPath, svgSrc, "utf-8");
2386
- iconInMemoryCache[iconPath] = svgSrc;
2387
- }
2388
- }
2389
- const hexColor = color.startsWith("#") ? color : `#${color}`;
2390
- const colorizedSvg = svgSrc.replaceAll("currentColor", hexColor);
2391
- return colorizedSvg;
2392
- }
2393
- __name(fetchIconSvg, "fetchIconSvg");
2394
- async function getTsDefinitionForItem(item, indentLevel = 0) {
2395
- const i = my_dash_default.times(indentLevel, () => " ").join("");
2396
- const itemSrc = [];
2397
- const jsDocLines = [];
2398
- jsDocLines.push(`**${item.key}**${item.isSensitive ? " \u{1F510} _sensitive_" : ""}`);
2399
- if (item.description) jsDocLines.push(...item.description.split("\n"));
2400
- const iconName = item.icon;
2401
- if (iconName) {
2402
- const iconSvg = await fetchIconSvg(iconName);
2403
- if (iconSvg) jsDocLines.push(`![icon](data:image/svg+xml;utf-8,${encodeURIComponent(iconSvg)}) `);
2404
- }
2405
- const docsLinks = item.docsLinks;
2406
- if (docsLinks.length) {
2407
- jsDocLines.push("");
2408
- docsLinks.forEach((docsEntry) => {
2409
- const docsLink = my_dash_default.compact([docsEntry.url, docsEntry.description]).join(" | ");
2410
- jsDocLines.push(`\u{1F4DA} {@link ${docsLink}}`);
2411
- });
2412
- }
2413
- if (jsDocLines.length === 1) {
2414
- itemSrc.push(`/** ${jsDocLines[0]} */`);
2415
- } else if (jsDocLines.length > 1) {
2416
- itemSrc.push(...[
2417
- "/**",
2418
- // extra 2 trailing spaces are needed to make line breaks visible
2419
- ...my_dash_default.flatMap(jsDocLines, (line) => [` * ${line} `]),
2420
- " */"
2421
- ]);
2422
- }
2423
- const dataType = item.dataType;
2424
- const dataTypeName = dataType?.name;
2425
- let itemTsType = "string";
2426
- if (dataType) {
2427
- if (dataTypeName === "number" || dataTypeName === "port") {
2428
- itemTsType = "number";
2429
- } else if (dataTypeName === "boolean") {
2430
- itemTsType = "boolean";
2431
- } else if (dataTypeName === "simple-object") {
2432
- itemTsType = "Record<string, any>";
2433
- } else if (dataTypeName === "enum") {
2434
- const rawEnumOptions = dataType._rawDef._rawEnumOptions;
2435
- let enumOptions = [];
2436
- enumOptions = rawEnumOptions;
2437
- if (!enumOptions.length) {
2438
- itemTsType = "never";
2439
- } else {
2440
- itemTsType = my_dash_default.map(enumOptions, JSON.stringify).join(" | ");
2441
- }
2442
- }
2443
- }
2444
- const isRequired = item.isRequired && !item.isRequiredDynamic;
2445
- itemSrc.push(`${item.key}${isRequired ? "" : "?"}: ${itemTsType};`);
2446
- itemSrc.push("");
2447
- return my_dash_default.map(itemSrc, (line) => `${i}${line}`);
2448
- }
2449
- __name(getTsDefinitionForItem, "getTsDefinitionForItem");
2450
- async function generateTsTypesSrc(graph) {
2451
- const tsSrc = [
2452
- AUTOGENERATED_FILE_BANNER,
2453
- // might want to add some options to let users inject this, or somehow detect eslint, but fine for now
2454
- "/* eslint-disable */",
2455
- "export type CoercedEnvSchema = {"
2456
- ];
2457
- const exposedNonSensitiveKeys = [];
2458
- for (const itemKey in graph.configSchema) {
2459
- const configItem = graph.configSchema[itemKey];
2460
- tsSrc.push(...await getTsDefinitionForItem(configItem, 1));
2461
- if (!configItem.isSensitive) exposedNonSensitiveKeys.push(itemKey);
2462
- }
2463
- tsSrc.push("};\n");
2464
- tsSrc.push(`
2465
- declare module 'varlock/env' {
2466
- export interface TypedEnvSchema extends Readonly<CoercedEnvSchema> {}
2467
- export interface PublicTypedEnvSchema extends Readonly<Pick<CoercedEnvSchema, '${exposedNonSensitiveKeys.join("' | '")}'>> {}
2468
- }
2469
- `);
2470
- tsSrc.push(`
2471
- export type EnvSchemaAsStrings = {
2472
- [Property in keyof CoercedEnvSchema]:
2473
- CoercedEnvSchema[Property] extends string ? CoercedEnvSchema[Property]
2474
- : (CoercedEnvSchema[Property] extends boolean ? ('true' | 'false') : string)
2475
- };
2476
- `);
2477
- const IMPORT_META_AUGMENTATION = `
2478
- // add types for global import.meta.env
2479
- interface ImportMetaEnv extends EnvSchemaAsStrings {}
2480
- interface ImportMeta {
2481
- readonly env: ImportMetaEnv;
2482
- }`;
2483
- const PROCESS_ENV_AUGMENTATION = `
2484
- // add types for global process.env
2485
- namespace NodeJS {
2486
- interface ProcessEnv extends EnvSchemaAsStrings {}
2487
- }`;
2488
- tsSrc.push(...[
2489
- "declare global {",
2490
- IMPORT_META_AUGMENTATION,
2491
- PROCESS_ENV_AUGMENTATION,
2492
- "}"
2493
- ].filter(Boolean));
2494
- return tsSrc.join("\n");
2495
- }
2496
- __name(generateTsTypesSrc, "generateTsTypesSrc");
2497
- async function generateTypes(graph, lang, typesPath) {
2498
- if (lang !== "ts") throw new Error(`Unsupported @generateTypes lang: ${lang}`);
2499
- const tsSrc = await generateTsTypesSrc(graph);
2500
- await fs.promises.writeFile(typesPath, tsSrc, "utf-8");
2501
- }
2502
- __name(generateTypes, "generateTypes");
2503
-
2504
- // src/env-graph/lib/error-location.ts
2505
- function getErrorLocation(source, parserNode) {
2506
- if (!(source instanceof FileBasedDataSource)) return;
2507
- if (!parserNode.data || !parserNode.data._location || !my_dash_default.isNumber(parserNode.data._location.start.line)) return;
2508
- const lineNumber = parserNode.data._location?.start.line;
2509
- const colNumber = parserNode.data._location?.start.column;
2510
- return {
2511
- id: source.fullPath,
2512
- lineNumber,
2513
- colNumber,
2514
- lineStr: source.rawContents?.split("\n")[lineNumber - 1]?.trim() || ""
2515
- };
2516
- }
2517
- __name(getErrorLocation, "getErrorLocation");
2518
-
2519
- // src/env-graph/lib/env-graph.ts
2520
- var processExists = !!globalThis.process;
2521
- var originalProcessEnv = { ...processExists && process.env };
2522
- var EnvGraph2 = class {
2523
- static {
2524
- __name(this, "EnvGraph");
2525
- }
2526
- // TODO: not sure if this should be the graph of _everything_ in a workspace/project
2527
- // or just the files that are relevant to the current resolution attempt
2528
- // (which would mean it's always through the lens of the current directory/package)
2529
- basePath;
2530
- /** root data source (.env.schema) */
2531
- rootDataSource;
2532
- /** place to store process.env overrides */
2533
- overrideValues = {};
2534
- /** config item key of env flag (toggles env-specific data sources enabled) */
2535
- envFlagKey;
2536
- /** graph-level fallback value for environment flag */
2537
- envFlagFallback;
2538
- configSchema = {};
2539
- /** virtual imports for testing */
2540
- virtualImports;
2541
- setVirtualImports(basePath, files) {
2542
- this.virtualImports = {};
2543
- for (const [fileName, fileContents] of Object.entries(files)) {
2544
- this.virtualImports[path2.join(basePath, fileName)] = fileContents;
2545
- }
2546
- }
2547
- get sortedDataSources() {
2548
- function getSourceAndChildren(s) {
2549
- return [s, ...s.children ? s.children.flatMap(getSourceAndChildren) : []];
2550
- }
2551
- __name(getSourceAndChildren, "getSourceAndChildren");
2552
- return this.rootDataSource ? getSourceAndChildren(this.rootDataSource) : [];
2553
- }
2554
- registeredResolverFunctions = {};
2555
- registerResolver(resolverClass) {
2556
- const fnName = resolverClass.fnName;
2557
- if (fnName in this.registeredResolverFunctions) {
2558
- throw new Error(`Resolver ${fnName} already registered`);
2559
- }
2560
- this.registeredResolverFunctions[fnName] = resolverClass;
2561
- }
2562
- dataTypesRegistry = {};
2563
- registerDataType(factory) {
2564
- const name = factory.dataTypeName;
2565
- if (name in this.dataTypesRegistry) {
2566
- throw new Error(`Data type "${name}" already registered`);
2567
- }
2568
- this.dataTypesRegistry[factory.dataTypeName] = factory;
2569
- }
2570
- itemDecoratorsRegistry = {};
2571
- registerItemDecorator(decoratorDef) {
2572
- const name = decoratorDef.name;
2573
- if (name in this.itemDecoratorsRegistry) {
2574
- throw new Error(`Item decorator "${name}" already registered`);
2575
- }
2576
- this.itemDecoratorsRegistry[decoratorDef.name] = decoratorDef;
2577
- }
2578
- rootDecoratorsRegistry = {};
2579
- registerRootDecorator(decoratorDef) {
2580
- const name = decoratorDef.name;
2581
- if (name in this.itemDecoratorsRegistry) {
2582
- throw new Error(`Root decorator "${name}" already registered`);
2583
- }
2584
- this.rootDecoratorsRegistry[decoratorDef.name] = decoratorDef;
2585
- }
2586
- constructor() {
2587
- for (const dataType of BaseDataTypes) {
2588
- this.registerDataType(dataType);
2589
- }
2590
- for (const resolverClass of BaseResolvers) {
2591
- this.registerResolver(resolverClass);
2592
- }
2593
- for (const rootDec of builtInRootDecorators) {
2594
- this.registerRootDecorator(rootDec);
2595
- }
2596
- for (const itemDec of builtInItemDecorators) {
2597
- this.registerItemDecorator(itemDec);
2598
- }
2599
- this.overrideValues = originalProcessEnv;
2600
- }
2601
- async setRootDataSource(source) {
2602
- if (this.rootDataSource) throw new Error("root data source already set");
2603
- this.rootDataSource = source;
2604
- source.graph = this;
2605
- await source.finishInit();
2606
- }
2607
- async finishLoad() {
2608
- for (const source of this.sortedDataSources) {
2609
- if (!source.isValid) return;
2610
- }
2611
- for (const plugin of this.plugins) {
2612
- if (plugin.loadingError) return;
2613
- }
2614
- let processingError = false;
2615
- for (const source of this.sortedDataSources) {
2616
- if (source.disabled) continue;
2617
- for (const decInstance of source.rootDecorators) {
2618
- await decInstance.process();
2619
- if (decInstance.schemaErrors.length) processingError = true;
2620
- }
2621
- }
2622
- for (const itemKey in this.configSchema) {
2623
- const item = this.configSchema[itemKey];
2624
- await item.process();
2625
- if (item.errors.length) processingError = true;
2626
- }
2627
- if (processingError) return;
2628
- const cycles = findGraphCycles(this.graphAdjacencyList);
2629
- for (const cycleItemKeys of cycles) {
2630
- for (const itemKey of cycleItemKeys) {
2631
- const item = this.configSchema[itemKey];
2632
- item._schemaErrors.push(
2633
- new SchemaError(
2634
- cycleItemKeys.length === 1 ? "Item cannot have dependency on itself" : `Dependency cycle detected: (${cycleItemKeys.join(", ")})`
2635
- )
2636
- );
2637
- }
2638
- }
2639
- for (const source of this.sortedDataSources) {
2640
- if (source.disabled) continue;
2641
- for (const decInstance of source.rootDecorators) {
2642
- if (!decInstance.decValueResolver) throw new Error("expected decorator value resolver");
2643
- await this.resolveEnvValues(decInstance.decValueResolver.deps);
2644
- try {
2645
- await decInstance.execute();
2646
- } catch (err) {
2647
- decInstance._executionError = new SchemaError(
2648
- err,
2649
- { location: getErrorLocation(source, decInstance.parsedDecorator) }
2650
- );
2651
- }
2652
- }
2653
- }
2654
- await this.getRootDec("redactLogs")?.resolve();
2655
- await this.getRootDec("preventLeaks")?.resolve();
2656
- }
2657
- get graphAdjacencyList() {
2658
- const adjList = {};
2659
- for (const itemKey in this.configSchema) {
2660
- const item = this.configSchema[itemKey];
2661
- adjList[itemKey] = item.dependencyKeys;
2662
- }
2663
- return adjList;
2664
- }
2665
- async resolveEnvValues(keys) {
2666
- const keysToResolve = keys ?? my_dash_default.keys(this.configSchema);
2667
- if (!keysToResolve.length) return;
2668
- const adjList = my_dash_default.pick(this.graphAdjacencyList, keysToResolve);
2669
- const reverseAdjList = {};
2670
- for (const itemKey in adjList) {
2671
- const itemDeps = adjList[itemKey];
2672
- for (const dep of itemDeps) {
2673
- reverseAdjList[dep] ??= [];
2674
- reverseAdjList[dep].push(itemKey);
2675
- }
2676
- }
2677
- const itemsToResolveStatus = my_dash_default.fromPairs(keysToResolve.map((key) => [key, false]));
2678
- const deferred = new Promise((resolve, _reject) => {
2679
- const markItemCompleted = /* @__PURE__ */ __name((itemKey) => {
2680
- delete itemsToResolveStatus[itemKey];
2681
- if (reverseAdjList[itemKey]) {
2682
- reverseAdjList[itemKey].forEach(resolveItem);
2683
- }
2684
- if (my_dash_default.keys(itemsToResolveStatus).length === 0) resolve();
2685
- }, "markItemCompleted");
2686
- const resolveItem = /* @__PURE__ */ __name(async (itemKey) => {
2687
- if (itemsToResolveStatus[itemKey] !== false) return;
2688
- const item = this.configSchema[itemKey];
2689
- if (item.errors.length) {
2690
- markItemCompleted(itemKey);
2691
- return;
2692
- }
2693
- for (const depKey of adjList[itemKey] || []) {
2694
- const depItem = this.configSchema[depKey];
2695
- if (depItem.validationState === "error") {
2696
- item.resolutionError = new ResolutionError(`Dependency ${depKey} is invalid`);
2697
- markItemCompleted(itemKey);
2698
- return;
2699
- } else if (depKey in itemsToResolveStatus) {
2700
- return;
2701
- }
2702
- }
2703
- itemsToResolveStatus[itemKey] = true;
2704
- await item.resolve();
2705
- markItemCompleted(itemKey);
2706
- }, "resolveItem");
2707
- for (const itemKey in this.configSchema) {
2708
- resolveItem(itemKey);
2709
- }
2710
- });
2711
- return deferred;
2712
- }
2713
- getResolvedEnvObject() {
2714
- const envObject = {};
2715
- for (const itemKey in this.configSchema) {
2716
- const item = this.configSchema[itemKey];
2717
- envObject[itemKey] = item.resolvedValue;
2718
- }
2719
- return envObject;
2720
- }
2721
- getSerializedGraph() {
2722
- const serializedGraph = {
2723
- basePath: this.basePath,
2724
- sources: [],
2725
- config: {},
2726
- settings: {}
2727
- };
2728
- for (const source of this.sortedDataSources) {
2729
- serializedGraph.sources.push({
2730
- label: source.label,
2731
- enabled: !source.disabled,
2732
- path: source instanceof FileBasedDataSource ? path2.relative(this.basePath ?? "", source.fullPath) : void 0
2733
- });
2734
- }
2735
- for (const itemKey in this.configSchema) {
2736
- const item = this.configSchema[itemKey];
2737
- serializedGraph.config[itemKey] = {
2738
- value: item.resolvedValue,
2739
- isSensitive: item.isSensitive
2740
- };
2741
- }
2742
- serializedGraph.settings.redactLogs = this.getRootDec("redactLogs")?.resolvedValue ?? true;
2743
- serializedGraph.settings.preventLeaks = this.getRootDec("preventLeaks")?.resolvedValue ?? true;
2744
- return serializedGraph;
2745
- }
2746
- get isInvalid() {
2747
- return my_dash_default.some(my_dash_default.values(this.configSchema), (i) => !i.isValid);
2748
- }
2749
- async generateTypes(lang, outputPath) {
2750
- await generateTypes(this, lang, outputPath);
2751
- }
2752
- getRootDec(decoratorName) {
2753
- const sources = Array.from(this.sortedDataSources).reverse();
2754
- for (const s of sources) {
2755
- if (s.disabled) continue;
2756
- const dec = s.getRootDec(decoratorName);
2757
- if (dec) return dec;
2758
- }
2759
- return void 0;
2760
- }
2761
- getRootDecFns(decoratorName) {
2762
- const allDecs = [];
2763
- const sources = Array.from(this.sortedDataSources).reverse();
2764
- for (const source of sources) {
2765
- if (source.disabled) continue;
2766
- const decs = source.getRootDecFns(decoratorName);
2767
- allDecs.push(...decs);
2768
- }
2769
- return allDecs;
2770
- }
2771
- /** plugins installed globally in the graph */
2772
- plugins = [];
2773
- };
2774
-
2775
- // src/env-graph/lib/config-item.ts
2776
- var ConfigItem = class {
2777
- constructor(envGraph, key) {
2778
- this.envGraph = envGraph;
2779
- this.key = key;
2780
- }
2781
- static {
2782
- __name(this, "ConfigItem");
2783
- }
2784
- /**
2785
- * fetch ordered list of definitions for this item, by following up sorted data sources list
2786
- */
2787
- get defs() {
2788
- const defs = [];
2789
- for (const source of this.envGraph.sortedDataSources) {
2790
- if (!source.configItemDefs[this.key]) continue;
2791
- if (source.disabled) continue;
2792
- if (source.importKeys && !source.importKeys.includes(this.key)) continue;
2793
- const itemDef = source.configItemDefs[this.key];
2794
- if (itemDef) defs.push({ itemDef, source });
2795
- }
2796
- return defs;
2797
- }
2798
- get description() {
2799
- for (const def of this.defs) {
2800
- if (def.itemDef.description) return def.itemDef.description;
2801
- }
2802
- }
2803
- get icon() {
2804
- const explicitIconDec = this.getDec("icon");
2805
- if (explicitIconDec) return explicitIconDec.resolvedValue;
2806
- return this.dataType?.icon;
2807
- }
2808
- get docsLinks() {
2809
- const links = [];
2810
- if (this.dataType?.docsEntries) {
2811
- for (const entry of this.dataType.docsEntries) {
2812
- if (my_dash_default.isPlainObject(entry)) links.push(entry);
2813
- else links.push({ url: entry });
2814
- }
2815
- }
2816
- const docsUrlDec = this.getDec("docsUrl");
2817
- if (docsUrlDec) {
2818
- links.push({ url: docsUrlDec.resolvedValue });
2819
- }
2820
- const docsDecs = this.getDecFns("docs");
2821
- for (const docsDec of docsDecs) {
2822
- const decVal = docsDec.resolvedValue;
2823
- if (!decVal.arr || !my_dash_default.isArray(decVal.arr)) throw new Error("expected an array of docs() args");
2824
- if (decVal.arr.length === 1) {
2825
- links.push({ url: decVal.arr[0] });
2826
- } else if (decVal.arr.length === 2) {
2827
- links.push({ url: decVal.arr[1], description: decVal.arr[0] });
2828
- }
2829
- }
2830
- return links;
2831
- }
2832
- get valueResolver() {
2833
- if (this.key in this.envGraph.overrideValues) {
2834
- return new StaticValueResolver(this.envGraph.overrideValues[this.key]);
2835
- }
2836
- for (const def of this.defs) {
2837
- if (def.itemDef.resolver) {
2838
- return def.itemDef.resolver;
2839
- }
2840
- }
2841
- }
2842
- allDecorators = [];
2843
- effectiveDecorators = {};
2844
- effectiveDecoratorFns = {};
2845
- getDec(decoratorName) {
2846
- return this.effectiveDecorators[decoratorName];
2847
- }
2848
- getDecFns(decoratorName) {
2849
- return this.effectiveDecoratorFns[decoratorName] || [];
2850
- }
2851
- async resolveDecorators() {
2852
- for (const dec of Object.values(this.effectiveDecorators)) {
2853
- await dec.resolve();
2854
- }
2855
- for (const decs of Object.values(this.effectiveDecoratorFns)) {
2856
- for (const dec of decs) {
2857
- await dec.resolve();
2858
- }
2859
- }
2860
- }
2861
- dataType;
2862
- _schemaErrors = [];
2863
- get resolverSchemaErrors() {
2864
- return this.valueResolver?.schemaErrors || [];
2865
- }
2866
- get decoratorSchemaErrors() {
2867
- return my_dash_default.values(this.allDecorators).flatMap((d) => d.schemaErrors);
2868
- }
2869
- isProcessed = false;
2870
- async process() {
2871
- if (this.isProcessed) return;
2872
- this.isProcessed = true;
2873
- for (const def of this.defs) {
2874
- if (def.itemDef.parsedValue && !def.itemDef.resolver) {
2875
- def.itemDef.resolver = convertParsedValueToResolvers(
2876
- def.itemDef.parsedValue,
2877
- def.source,
2878
- this.envGraph.registeredResolverFunctions
2879
- );
2880
- }
2881
- await def.itemDef.resolver?.process(this);
2882
- }
2883
- for (const def of this.defs) {
2884
- def.itemDef.decorators = def.itemDef.parsedDecorators?.map((d) => new ItemDecoratorInstance(this, def.source, d));
2885
- const decKeysInThisDef = /* @__PURE__ */ new Set();
2886
- const allDecsInThisDef = def.itemDef.decorators?.map((d) => d.name);
2887
- for (const dec of def.itemDef.decorators || []) {
2888
- await dec.process();
2889
- this.allDecorators?.push(dec);
2890
- if (dec.isFunctionCall) {
2891
- this.effectiveDecoratorFns[dec.name] ||= [];
2892
- this.effectiveDecoratorFns[dec.name].push(dec);
2893
- } else {
2894
- if (decKeysInThisDef.has(dec.name)) {
2895
- dec._schemaErrors.push(new SchemaError(`decorator @${dec.name} cannot be used twice in same definition`));
2896
- continue;
2897
- }
2898
- if (dec.incompatibleWith) {
2899
- for (const otherDecName of dec.incompatibleWith) {
2900
- if (allDecsInThisDef?.includes(otherDecName)) {
2901
- dec._schemaErrors.push(new SchemaError(`decorator @${dec.name} is incompatible with @${otherDecName} in the same definition`));
2902
- continue;
2903
- }
2904
- }
2905
- }
2906
- this.effectiveDecorators[dec.name] ||= dec;
2907
- }
2908
- decKeysInThisDef.add(dec.name);
2909
- }
2910
- }
2911
- const typeDec = this.getDec("type");
2912
- let dataTypeName;
2913
- let dataTypeArgs;
2914
- const typeDecParsedValue = typeDec?.parsedDecorator.value;
2915
- if (typeDecParsedValue instanceof ParsedEnvSpecStaticValue) {
2916
- dataTypeName = typeDecParsedValue.value;
2917
- } else if (typeDecParsedValue instanceof ParsedEnvSpecFunctionCall) {
2918
- dataTypeName = typeDecParsedValue.name;
2919
- dataTypeArgs = typeDecParsedValue.simplifiedArgs;
2920
- }
2921
- if (!dataTypeName && this.valueResolver?.inferredType) {
2922
- dataTypeName = this.valueResolver.inferredType;
2923
- }
2924
- dataTypeName ||= "string";
2925
- dataTypeArgs ||= [];
2926
- if (!(dataTypeName in this.envGraph.dataTypesRegistry)) {
2927
- this._schemaErrors.push(new SchemaError(`unknown data type: ${dataTypeName}`));
2928
- } else {
2929
- const dataTypeFactory = this.envGraph.dataTypesRegistry[dataTypeName];
2930
- this.dataType = dataTypeFactory(...my_dash_default.isPlainObject(dataTypeArgs) ? [dataTypeArgs] : dataTypeArgs);
2931
- }
2932
- }
2933
- get dependencyKeys() {
2934
- return my_dash_default.uniq([
2935
- ...this.valueResolver?.deps || [],
2936
- ...my_dash_default.values(this.effectiveDecorators).flatMap(
2937
- (dec) => dec.decValueResolver?.deps || []
2938
- ),
2939
- ...my_dash_default.values(this.effectiveDecoratorFns).flatMap(
2940
- (decArr) => decArr.flatMap(
2941
- (d) => d.decValueResolver?.deps || []
2942
- )
2943
- )
2944
- ]);
2945
- }
2946
- /**
2947
- * special early resolution helper
2948
- * currently used to resolve the envFlag before everything else has been loaded
2949
- * */
2950
- async earlyResolve() {
2951
- await this.process();
2952
- for (const depKey of this.dependencyKeys) {
2953
- const depItem = this.envGraph.configSchema[depKey];
2954
- if (!depItem) {
2955
- throw new Error(`eager resolution eror - non-existant dependency: ${depKey}`);
2956
- }
2957
- await depItem.earlyResolve();
2958
- }
2959
- await this.resolve();
2960
- }
2961
- _isRequired = true;
2962
- /**
2963
- * need to track if required-ness is dynamic, e.g. based on current env
2964
- * because that will affect type generation (only _always_ required items are never undefined)
2965
- * */
2966
- _isRequiredDynamic = false;
2967
- async processRequired() {
2968
- try {
2969
- for (const def of this.defs) {
2970
- const requiredDecs = def.itemDef.decorators?.filter((d) => d.name === "required" || d.name === "optional") || [];
2971
- const requiredDec = requiredDecs[0];
2972
- if (requiredDec) {
2973
- const usingOptional = requiredDec.name === "optional";
2974
- if (requiredDec.decValueResolver?.fnName !== "\0static") {
2975
- this._isRequiredDynamic = true;
2976
- }
2977
- const requiredDecoratorVal = await requiredDec.resolve();
2978
- if (requiredDec.schemaErrors.length) {
2979
- this._isRequired = false;
2980
- return;
2981
- }
2982
- if (![true, false, void 0].includes(requiredDecoratorVal)) {
2983
- throw new SchemaError("@required/@optional must resolve to a boolean or undefined");
2984
- }
2985
- if (requiredDecoratorVal !== void 0) {
2986
- this._isRequired = usingOptional ? !requiredDecoratorVal : requiredDecoratorVal;
2987
- return;
2988
- }
2989
- }
2990
- const defaultRequiredDec = def.source.getRootDec("defaultRequired");
2991
- if (defaultRequiredDec) {
2992
- const defaultRequiredVal = await defaultRequiredDec.resolve();
2993
- if (my_dash_default.isBoolean(defaultRequiredVal)) {
2994
- this._isRequired = defaultRequiredVal;
2995
- return;
2996
- } else if (defaultRequiredVal === "infer") {
2997
- if (def.itemDef.resolver) {
2998
- if (def.itemDef.resolver instanceof StaticValueResolver) {
2999
- this._isRequired = def.itemDef.resolver.staticValue !== void 0 && def.itemDef.resolver.staticValue !== "";
3000
- } else {
3001
- this._isRequired = true;
3002
- }
3003
- } else {
3004
- this._isRequired = false;
3005
- }
3006
- return;
3007
- } else {
3008
- throw new SchemaError('@defaultRequired must resolve to a boolean or "infer"');
3009
- }
3010
- }
3011
- }
3012
- } catch (err) {
3013
- this._schemaErrors.push(err instanceof SchemaError ? err : new SchemaError(err));
3014
- }
3015
- }
3016
- get isRequired() {
3017
- return this._isRequired;
3018
- }
3019
- get isRequiredDynamic() {
3020
- return this._isRequiredDynamic;
3021
- }
3022
- _isSensitive = true;
3023
- get isSensitive() {
3024
- return this._isSensitive;
3025
- }
3026
- async processSensitive() {
3027
- const sensitiveFromDataType = this.dataType?.isSensitive;
3028
- for (const def of this.defs) {
3029
- const sensitiveDecs = def.itemDef.decorators?.filter((d) => d.name === "sensitive" || d.name === "public") || [];
3030
- const sensitiveDec = sensitiveDecs[0];
3031
- if (sensitiveDec) {
3032
- const usingPublic = sensitiveDec.name === "public";
3033
- const sensitiveDecValue = await sensitiveDec.resolve();
3034
- if (sensitiveDec.schemaErrors.length) {
3035
- return;
3036
- }
3037
- if (![true, false, void 0].includes(sensitiveDecValue)) {
3038
- throw new SchemaError("@sensitive/@public must resolve to a boolean or undefined");
3039
- }
3040
- if (sensitiveDecValue !== void 0) {
3041
- this._isSensitive = usingPublic ? !sensitiveDecValue : sensitiveDecValue;
3042
- return;
3043
- }
3044
- }
3045
- if (sensitiveFromDataType !== void 0) continue;
3046
- const defaultSensitiveDec = def.source.getRootDec("defaultSensitive");
3047
- if (defaultSensitiveDec) {
3048
- if (!defaultSensitiveDec.decValueResolver) throw new Error("expected defaultSensitive to have a value resolver");
3049
- if (defaultSensitiveDec.decValueResolver.fnName === "inferFromPrefix") {
3050
- const prefix = defaultSensitiveDec.decValueResolver.arrArgs[0].staticValue;
3051
- if (!my_dash_default.isString(prefix)) {
3052
- this._schemaErrors.push(new SchemaError("@defaultSensitive inferFromPrefix() requires a single string argument"));
3053
- return;
3054
- }
3055
- this._isSensitive = !this.key.startsWith(prefix);
3056
- return;
3057
- } else {
3058
- const defaultSensitiveVal = await defaultSensitiveDec.resolve();
3059
- if (!my_dash_default.isBoolean(defaultSensitiveVal)) {
3060
- this._schemaErrors.push(new SchemaError("@defaultSensitive must resolve to a boolean value"));
3061
- } else {
3062
- this._isSensitive = defaultSensitiveVal;
3063
- return;
3064
- }
3065
- }
3066
- }
3067
- }
3068
- if (sensitiveFromDataType !== void 0) this._isSensitive = sensitiveFromDataType;
3069
- }
3070
- get errors() {
3071
- return my_dash_default.compact([
3072
- ...this._schemaErrors || [],
3073
- ...this.resolverSchemaErrors || [],
3074
- ...this.decoratorSchemaErrors || [],
3075
- this.resolutionError,
3076
- this.coercionError,
3077
- ...this.validationErrors || []
3078
- ]);
3079
- }
3080
- get validationState() {
3081
- const errors = this.errors;
3082
- if (!errors.length) return "valid";
3083
- return my_dash_default.some(errors, (e) => !e.isWarning) ? "error" : "warn";
3084
- }
3085
- /** resolved value _before coercion_ */
3086
- resolvedRawValue;
3087
- isResolved = false;
3088
- /** resolved value after coercion */
3089
- resolvedValue;
3090
- isValidated = false;
3091
- resolutionError;
3092
- coercionError;
3093
- validationErrors;
3094
- get isCoerced() {
3095
- return this.resolvedRawValue !== this.resolvedValue;
3096
- }
3097
- async resolve(reset2 = false) {
3098
- if (this._schemaErrors.length) return;
3099
- if (this.resolverSchemaErrors.length) return;
3100
- if (reset2) {
3101
- this.isResolved = false;
3102
- this.isValidated = false;
3103
- this.resolutionError = void 0;
3104
- this.coercionError = void 0;
3105
- this.validationErrors = void 0;
3106
- this.resolvedRawValue = void 0;
3107
- this.resolvedValue = void 0;
3108
- }
3109
- if (this.isResolved) {
3110
- return;
3111
- }
3112
- await this.resolveDecorators();
3113
- await this.processRequired();
3114
- await this.processSensitive();
3115
- if (!this.valueResolver) {
3116
- this.isResolved = true;
3117
- this.resolvedRawValue = void 0;
3118
- } else {
3119
- try {
3120
- this.resolvedRawValue = await this.valueResolver.resolve();
3121
- } catch (err) {
3122
- if (err instanceof ResolutionError) {
3123
- this.resolutionError = err;
3124
- } else {
3125
- this.resolutionError = new ResolutionError(`error resolving value: ${err}`);
3126
- this.resolutionError.cause = err;
3127
- }
3128
- }
3129
- }
3130
- if (this.resolvedRawValue instanceof RegExp) {
3131
- this.resolutionError = new ResolutionError("regex() is meant to be used within function args, not as a final resolved value");
3132
- }
3133
- if (this.resolutionError) return;
3134
- this.isResolved = true;
3135
- if (this.resolvedRawValue === void 0 || this.resolvedRawValue === "") {
3136
- this.resolvedValue = this.resolvedRawValue;
3137
- if (this.isRequired) {
3138
- this.validationErrors = [new EmptyRequiredValueError(void 0)];
3139
- }
3140
- return;
3141
- }
3142
- if (!this.dataType) throw new Error("expected dataType to be set");
3143
- try {
3144
- const coerceResult = this.dataType.coerce(this.resolvedRawValue);
3145
- if (coerceResult instanceof Error) throw coerceResult;
3146
- this.resolvedValue = coerceResult;
3147
- } catch (err) {
3148
- if (err instanceof CoercionError) {
3149
- this.coercionError = err;
3150
- return;
3151
- } else if (err instanceof Error) {
3152
- this.coercionError = new CoercionError("Unexpected error coercing value");
3153
- this.coercionError.cause = err;
3154
- } else {
3155
- this.coercionError = new CoercionError(`Unexpected non-error throw during coerce - ${err}`);
3156
- }
3157
- return;
3158
- }
3159
- try {
3160
- const validateResult = await this.dataType.validate(this.resolvedValue);
3161
- if (validateResult instanceof Error || my_dash_default.isArray(validateResult) && validateResult[0] instanceof Error) throw validateResult;
3162
- if (validateResult === false) {
3163
- throw new ValidationError("validation failed with `false` return value");
3164
- }
3165
- this.isValidated = true;
3166
- } catch (err) {
3167
- if (my_dash_default.isArray(err)) {
3168
- this.validationErrors = err;
3169
- } else if (err instanceof ValidationError) {
3170
- this.validationErrors = [err];
3171
- } else if (err instanceof Error) {
3172
- const validationError = new ValidationError("Unexpected error during validation");
3173
- validationError.cause = err;
3174
- this.validationErrors = [validationError];
3175
- } else {
3176
- const validationError = new ValidationError(`Unexpected non-error thrown during validation - ${err}`);
3177
- validationError.cause = err;
3178
- this.validationErrors = [validationError];
3179
- }
3180
- return;
3181
- }
3182
- }
3183
- get isValid() {
3184
- return this.validationState === "valid";
3185
- }
3186
- };
3187
- var importedPluginModulePaths = /* @__PURE__ */ new Set();
3188
- var VarlockPlugin = class {
3189
- static {
3190
- __name(this, "VarlockPlugin");
3191
- }
3192
- // helper so end user code can get same error classes
3193
- ERRORS = {
3194
- ValidationError,
3195
- CoercionError,
3196
- SchemaError,
3197
- ResolutionError
3198
- };
3199
- _packageJson;
3200
- _name;
3201
- get name() {
3202
- return this._packageJson?.name || this._name || "unnamed plugin";
3203
- }
3204
- set name(val) {
3205
- this._name = val;
3206
- }
3207
- _version;
3208
- get version() {
3209
- return this._packageJson?.version || this._version || "0.0.0";
3210
- }
3211
- set version(val) {
3212
- this._version = val;
3213
- }
3214
- _icon;
3215
- get icon() {
3216
- return this._icon || "mdi:puzzle";
3217
- }
3218
- set icon(val) {
3219
- this._icon = val;
3220
- }
3221
- loadingError;
3222
- localPath;
3223
- /** reference to the `@plugin()` decorator instance(s) that installed the plugin */
3224
- installDecoratorInstances = [];
3225
- type;
3226
- constructor(opts) {
3227
- this.type = opts.type;
3228
- this.localPath = opts?.localPath;
3229
- this._packageJson = opts?.packageJson;
3230
- }
3231
- // awkwardly using get here to make sure we bind the debug function to this
3232
- // which lets us destructure it in plugin code
3233
- debugger;
3234
- get debug() {
3235
- return (...args) => {
3236
- if (!this.debugger) {
3237
- if (!this.name) throw new Error("expected plugin name to be set before using debug");
3238
- this.debugger = Debug(`varlock:plugin:${this.name}`);
3239
- }
3240
- return this.debugger(...args);
3241
- };
3242
- }
3243
- dataTypes = [];
3244
- registerDataType(dataTypeDef) {
3245
- this.debug("registerDataType", dataTypeDef.name);
3246
- this.dataTypes.push(dataTypeDef);
3247
- }
3248
- rootDecorators = [];
3249
- registerRootDecorator(decoratorDef) {
3250
- this.debug("registerRootDecorator", decoratorDef.name);
3251
- this.rootDecorators.push(decoratorDef);
3252
- }
3253
- itemDecorators = [];
3254
- registerItemDecorator(decoratorDef) {
3255
- this.debug("registerItemDecorator", decoratorDef.name);
3256
- this.itemDecorators.push(decoratorDef);
3257
- }
3258
- resolverFunctions = [];
3259
- registerResolverFunction(resolverDef) {
3260
- this.debug("registerResolverFunction", resolverDef.name);
3261
- this.resolverFunctions.push(resolverDef);
3262
- }
3263
- get pluginFilePath() {
3264
- if (this.type === "single-file") return this.localPath;
3265
- const pluginExport = this._packageJson?.exports?.["./plugin"] || "";
3266
- if (!pluginExport) throw new Error("Plugin package.json is missing ./plugin export");
3267
- return path2.join(this.localPath, pluginExport);
3268
- }
3269
- async executePluginModule() {
3270
- globalThis.plugin = this;
3271
- try {
3272
- if (!await pathExists(this.pluginFilePath)) throw new Error(`Plugin file not found: ${this.pluginFilePath}`);
3273
- importedPluginModulePaths.add(this.pluginFilePath);
3274
- await import(this.pluginFilePath);
3275
- } catch (err) {
3276
- this.loadingError = err;
3277
- }
3278
- delete globalThis.plugin;
3279
- }
3280
- };
3281
- async function initPluginFromLocalPath(localPath) {
3282
- const stats = await fs2.stat(localPath);
3283
- if (stats.isFile()) {
3284
- const ext = path2.extname(localPath).toLowerCase();
3285
- if ([".js", ".cjs", ".mjs"].includes(ext) === false) {
3286
- throw new SchemaError(`Single-file plugin must be a .js, .cjs, or .mjs file: ${localPath}`);
3287
- }
3288
- return new VarlockPlugin({
3289
- type: "single-file",
3290
- localPath
3291
- });
3292
- } else if (stats.isDirectory()) {
3293
- const pkgJsonPath = path2.join(localPath, "package.json");
3294
- if (!await pathExists(pkgJsonPath)) {
3295
- throw new SchemaError("Plugin is missing package.json file");
3296
- }
3297
- const packageJsonContents = JSON.parse(await fs2.readFile(pkgJsonPath, "utf-8"));
3298
- if (!packageJsonContents.exports?.["./plugin"]) {
3299
- throw new SchemaError('Plugin is missing "./plugin" export in package.json');
3300
- }
3301
- return new VarlockPlugin({
3302
- type: "package",
3303
- localPath,
3304
- packageJson: packageJsonContents
3305
- });
3306
- } else {
3307
- throw new Error(`Invalid plugin path (not a file or directory): ${localPath}`);
3308
- }
3309
- }
3310
- __name(initPluginFromLocalPath, "initPluginFromLocalPath");
3311
- async function registerPluginInGraph(graph, plugin, pluginDecorator) {
3312
- let existingPlugin;
3313
- for (const possibleMatchingPlugin of graph.plugins) {
3314
- if (plugin.type === "single-file") {
3315
- if (possibleMatchingPlugin.type === "single-file" && possibleMatchingPlugin.localPath === plugin.localPath) {
3316
- existingPlugin = possibleMatchingPlugin;
3317
- }
3318
- } else if (plugin.type === "package") {
3319
- if (possibleMatchingPlugin.name === plugin.name) {
3320
- if (possibleMatchingPlugin.version === plugin.version) {
3321
- const installedInSources = possibleMatchingPlugin.installDecoratorInstances.map((dec) => dec.dataSource);
3322
- if (installedInSources.includes(pluginDecorator.dataSource)) {
3323
- pluginDecorator._schemaErrors.push(new SchemaError(`Plugin ${plugin.name} already installed in this data source`));
3324
- return;
3325
- }
3326
- existingPlugin = possibleMatchingPlugin;
3327
- } else {
3328
- pluginDecorator._schemaErrors.push(new SchemaError(`Plugin ${plugin.name} version conflict: tried to install version ${plugin.version} but version ${possibleMatchingPlugin.version} is already installed`));
3329
- return;
3330
- }
3331
- }
3332
- }
3333
- }
3334
- if (existingPlugin) {
3335
- existingPlugin.installDecoratorInstances.push(pluginDecorator);
3336
- return;
3337
- }
3338
- plugin.installDecoratorInstances.push(pluginDecorator);
3339
- graph.plugins.push(plugin);
3340
- await plugin.executePluginModule();
3341
- if (plugin.loadingError) {
3342
- return;
3343
- }
3344
- for (const rootDec of plugin.rootDecorators || []) {
3345
- graph.registerRootDecorator(rootDec);
3346
- }
3347
- for (const itemDec of plugin.itemDecorators || []) {
3348
- graph.registerItemDecorator(itemDec);
3349
- }
3350
- for (const dataType of plugin.dataTypes || []) {
3351
- graph.registerDataType(createEnvGraphDataType(dataType));
3352
- }
3353
- for (const resolverDef of plugin.resolverFunctions || []) {
3354
- graph.registerResolver(createResolver(resolverDef));
3355
- }
3356
- }
3357
- __name(registerPluginInGraph, "registerPluginInGraph");
3358
- async function downloadPlugin(url) {
3359
- const exec2 = promisify(exec);
3360
- const cacheDir = path2.join(os.homedir(), ".varlock", "plugins-cache");
3361
- const indexPath = path2.join(cacheDir, "index.json");
3362
- await fs2.mkdir(cacheDir, { recursive: true });
3363
- let index = {};
3364
- try {
3365
- const indexRaw = await fs2.readFile(indexPath, "utf-8");
3366
- index = JSON.parse(indexRaw);
3367
- } catch {
3368
- }
3369
- if (index[url]) {
3370
- const pluginDir = path2.join(cacheDir, index[url]);
3371
- if (await fs2.stat(pluginDir).then(() => true, () => false)) {
3372
- return pluginDir;
3373
- }
3374
- }
3375
- const tmpTgz = path2.join(cacheDir, `tmp-${crypto.randomBytes(8).toString("hex")}.tgz`);
3376
- await new Promise((resolve, reject) => {
3377
- const file = fs.createWriteStream(tmpTgz);
3378
- https.get(url, (res) => {
3379
- if (res.statusCode !== 200) {
3380
- reject(new Error(`Failed to download plugin: ${res.statusCode}`));
3381
- return;
3382
- }
3383
- res.pipe(file);
3384
- file.on("finish", () => file.close(() => resolve()));
3385
- file.on("error", reject);
3386
- }).on("error", reject);
3387
- });
3388
- const tmpExtractDir = path2.join(cacheDir, `tmp-extract-${crypto.randomBytes(8).toString("hex")}`);
3389
- await fs2.mkdir(tmpExtractDir);
3390
- await exec2(`tar -xzf ${tmpTgz} -C ${tmpExtractDir}`);
3391
- let pkgJsonPath = path2.join(tmpExtractDir, "package", "package.json");
3392
- let pluginRoot = path2.join(tmpExtractDir, "package");
3393
- if (!await fs2.stat(pkgJsonPath).then(() => true, () => false)) {
3394
- pkgJsonPath = path2.join(tmpExtractDir, "package.json");
3395
- pluginRoot = tmpExtractDir;
3396
- if (!await fs2.stat(pkgJsonPath).then(() => true, () => false)) {
3397
- throw new Error("package.json not found in plugin tgz");
3398
- }
3399
- }
3400
- const pkgJson = JSON.parse(await fs2.readFile(pkgJsonPath, "utf-8"));
3401
- const safePackageName = (pkgJson.name || "").replaceAll("/", "-").replaceAll("@", "");
3402
- const dirName = `${safePackageName}_${pkgJson.version || ""}_${crypto.randomBytes(4).toString("hex")}`;
3403
- const finalDir = path2.join(cacheDir, dirName);
3404
- await fs2.rm(finalDir, { recursive: true, force: true });
3405
- await fs2.rename(pluginRoot, finalDir);
3406
- await fs2.rm(tmpTgz, { force: true });
3407
- await fs2.rm(tmpExtractDir, { recursive: true, force: true });
3408
- index[url] = dirName;
3409
- await fs2.writeFile(indexPath, JSON.stringify(index, null, 2));
3410
- return finalDir;
3411
- }
3412
- __name(downloadPlugin, "downloadPlugin");
3413
- async function processPluginInstallDecorators(dataSource) {
3414
- const graph = dataSource.graph;
3415
- if (!graph) throw new Error("Data source not attached to graph");
3416
- const installPluginDecorators = dataSource.getRootDecFns("plugin");
3417
- if (installPluginDecorators.length) {
3418
- if (!(dataSource instanceof FileBasedDataSource)) {
3419
- dataSource._loadingError = new Error("@plugin can only be used from a file-based data source");
3420
- return;
3421
- }
3422
- const dataSourceDir = path2.dirname(dataSource.fullPath);
3423
- for (const pluginDecorator of installPluginDecorators) {
3424
- let pluginSrcPath;
3425
- try {
3426
- const installPluginArgs = await pluginDecorator.resolve();
3427
- const pluginSourceDescriptor = installPluginArgs.arr[0];
3428
- if (!my_dash_default.isString(pluginSourceDescriptor)) {
3429
- throw new SchemaError("Bad @plugin - must provide a string source location");
3430
- }
3431
- if (pluginSourceDescriptor.startsWith("./") || pluginSourceDescriptor.startsWith("../") || pluginSourceDescriptor.startsWith("/")) {
3432
- pluginSrcPath = pluginSourceDescriptor.startsWith("/") ? pluginSourceDescriptor : path2.resolve(dataSourceDir, pluginSourceDescriptor);
3433
- if (!await pathExists(pluginSrcPath)) {
3434
- throw new SchemaError(`Bad @plugin path: ${pluginSourceDescriptor}`);
3435
- }
3436
- } else if (pluginSourceDescriptor.includes(":")) {
3437
- const protocol = pluginSourceDescriptor.split(":")[0];
3438
- if (["https", "npm", "jsr", "git"].includes(protocol)) {
3439
- throw new SchemaError(`@plugin source protocol "${protocol}" is not yet supported`);
3440
- } else {
3441
- throw new SchemaError(`Bad @plugin source protocol: ${protocol}`);
3442
- }
3443
- } else {
3444
- const atLocation = pluginSourceDescriptor.indexOf("@", 1);
3445
- let versionDescriptor;
3446
- let moduleName;
3447
- if (atLocation === -1) {
3448
- moduleName = pluginSourceDescriptor;
3449
- } else {
3450
- moduleName = pluginSourceDescriptor.slice(0, atLocation);
3451
- versionDescriptor = pluginSourceDescriptor.slice(atLocation + 1);
3452
- }
3453
- if (!moduleName.startsWith("@varlock/")) {
3454
- throw new SchemaError(`Plugin "${moduleName}" blocked - only official @varlock/* plugins are supported for now, third-party plugins will be supported in future releases`);
3455
- }
3456
- const semverRange = semver.validRange(versionDescriptor);
3457
- if (versionDescriptor && !semverRange) {
3458
- throw new SchemaError(`Bad @plugin version descriptor: ${versionDescriptor}`);
3459
- } else if (semverRange === "*") {
3460
- throw new SchemaError(`Version descriptor "${versionDescriptor}" is too broad`);
3461
- } else if (versionDescriptor === "") {
3462
- throw new SchemaError('Bad @plugin version descriptor - remove "@" or specify a valid version');
3463
- }
3464
- let currentDir = dataSourceDir;
3465
- let nodeModulesPath;
3466
- while (currentDir) {
3467
- if (await pathExists(path2.join(currentDir, "package.json"))) {
3468
- nodeModulesPath = path2.join(currentDir, "node_modules");
3469
- break;
3470
- }
3471
- const parentDir = path2.dirname(currentDir);
3472
- if (parentDir === currentDir) break;
3473
- currentDir = parentDir;
3474
- }
3475
- if (nodeModulesPath) {
3476
- const pluginPackagePath = path2.join(nodeModulesPath, moduleName);
3477
- if (await pathExists(pluginPackagePath)) {
3478
- const pluginPackageJsonPath = path2.join(pluginPackagePath, "package.json");
3479
- const packageJsonString = await fs2.readFile(pluginPackageJsonPath, "utf-8");
3480
- const packageJson = JSON.parse(packageJsonString);
3481
- const packageVersion = packageJson.version;
3482
- if (versionDescriptor && !semver.satisfies(packageVersion, versionDescriptor)) {
3483
- throw new SchemaError(`Installed plugin "${moduleName}" version "${packageVersion}" does not satisfy requested version "${versionDescriptor}"`, {
3484
- location: getErrorLocation(dataSource, pluginDecorator)
3485
- });
3486
- }
3487
- pluginSrcPath = pluginPackagePath;
3488
- }
3489
- }
3490
- if (!pluginSrcPath) {
3491
- if (!versionDescriptor) {
3492
- if (nodeModulesPath) {
3493
- throw new SchemaError(`Plugin "${moduleName}" unable to resolve - install locally via your package.json file`);
3494
- } else {
3495
- throw new SchemaError(`Plugin "${moduleName}" unable to resolve - set a fixed version (e.g., \`@plugin(${moduleName}@1.2.3)\`)`);
3496
- }
3497
- } else if (!semver.valid(versionDescriptor)) {
3498
- throw new SchemaError(`Plugin "${moduleName}" must use a fixed version when not installing via package.json (e.g., \`@plugin(${moduleName}@1.2.3)\`)`, {
3499
- location: getErrorLocation(dataSource, pluginDecorator)
3500
- });
3501
- }
3502
- const npmInfoUrl = `https://registry.npmjs.org/${moduleName}/${versionDescriptor}`;
3503
- const npmInfoReq = await fetch(npmInfoUrl);
3504
- if (!npmInfoReq.ok) {
3505
- throw new Error(`Failed to fetch plugin "${moduleName}@${versionDescriptor}" from npm: ${npmInfoReq.status} ${npmInfoReq.statusText}`);
3506
- }
3507
- const npmInfo = await npmInfoReq.json();
3508
- const tarballUrl = npmInfo?.dist?.tarball;
3509
- if (!tarballUrl) {
3510
- throw new Error(`Failed to find tarball URL for plugin "${moduleName}@${versionDescriptor}" from npm`);
3511
- }
3512
- const downloadedPluginPath = await downloadPlugin(tarballUrl);
3513
- pluginSrcPath = downloadedPluginPath;
3514
- }
3515
- }
3516
- const plugin = await initPluginFromLocalPath(pluginSrcPath);
3517
- await registerPluginInGraph(graph, plugin, pluginDecorator);
3518
- } catch (err) {
3519
- pluginDecorator._schemaErrors.push(err);
3520
- continue;
3521
- }
3522
- }
3523
- }
3524
- }
3525
- __name(processPluginInstallDecorators, "processPluginInstallDecorators");
3526
-
3527
- // src/env-graph/lib/data-source.ts
3528
- var DATA_SOURCE_TYPES = Object.freeze({
3529
- schema: {
3530
- fileSuffixes: ["schema"]
3531
- },
3532
- example: {
3533
- fileSuffixes: ["sample", "example"]
3534
- },
3535
- defaults: {
3536
- fileSuffixes: ["default", "defaults"]
3537
- },
3538
- values: {
3539
- fileSuffixes: []
3540
- },
3541
- overrides: {
3542
- fileSuffixes: ["local", "override"]
3543
- },
3544
- container: {}
3545
- });
3546
- var EnvGraphDataSource4 = class {
3547
- static {
3548
- __name(this, "EnvGraphDataSource");
3549
- }
3550
- static DATA_SOURCE_TYPES = DATA_SOURCE_TYPES;
3551
- /** reference back to the graph */
3552
- graph;
3553
- /** parent data source - everything except the root will have a parent */
3554
- parent;
3555
- /** child data sources */
3556
- children = [];
3557
- /**
3558
- * tracks if this data source was imported, and additional settings about the import (restricting keys)
3559
- * */
3560
- importMeta;
3561
- get isImport() {
3562
- return !!this.importMeta?.isImport || !!this.parent?.isImport;
3563
- }
3564
- get isPartialImport() {
3565
- return (this.importKeys || []).length > 0;
3566
- }
3567
- get importKeys() {
3568
- const importKeysArrays = [];
3569
- let currentSource = this;
3570
- while (currentSource) {
3571
- if (currentSource.importMeta?.importKeys && currentSource.importMeta.importKeys.length) {
3572
- importKeysArrays.push(currentSource.importMeta.importKeys);
3573
- }
3574
- currentSource = currentSource.parent;
3575
- }
3576
- if (importKeysArrays.length) {
3577
- const keysToImport = my_dash_default.intersection(...importKeysArrays);
3578
- return keysToImport;
3579
- }
3580
- }
3581
- /** adds a child data source and sets up the correct references in both directions */
3582
- async addChild(child, importMeta) {
3583
- if (!this.graph) throw new Error("expected graph to be set");
3584
- this.children.unshift(child);
3585
- child.parent = this;
3586
- child.graph = this.graph;
3587
- if (importMeta) child.importMeta = importMeta;
3588
- await child.finishInit();
3589
- }
3590
- /** environment flag key (as set by @envFlag decorator) - only if set within this source */
3591
- _envFlagKey;
3592
- /** environment flag key getter that will follow up the parent chain */
3593
- get envFlagKey() {
3594
- return this._envFlagKey || this.parent?.envFlagKey;
3595
- }
3596
- /** helper to set the current envFlag key, also propogating upwards */
3597
- setEnvFlag(key) {
3598
- this._envFlagKey = key;
3599
- if (this.parent && !this.isPartialImport && !this.parent._envFlagKey) {
3600
- this.parent.setEnvFlag(key);
3601
- }
3602
- }
3603
- /** environment flag config item getter (follows up the parent chain) */
3604
- get envFlagConfigItem() {
3605
- const envFlagKey = this.envFlagKey;
3606
- return envFlagKey ? this.graph?.configSchema[envFlagKey] : void 0;
3607
- }
3608
- /** environment flag value getter (follows up the parent chain), and checks the graph-level fallback */
3609
- get envFlagValue() {
3610
- const envFlagItem = this.envFlagConfigItem;
3611
- if (envFlagItem) return envFlagItem.resolvedValue;
3612
- return this.graph.envFlagFallback;
3613
- }
3614
- /** helper to resolve the envFlag value */
3615
- async resolveCurrentEnv() {
3616
- const envFlagItem = this.envFlagConfigItem;
3617
- if (envFlagItem) {
3618
- if (envFlagItem.resolvedValue) return envFlagItem.resolvedValue;
3619
- await envFlagItem.earlyResolve();
3620
- return envFlagItem.resolvedValue;
3621
- }
3622
- return this.graph.envFlagFallback;
3623
- }
3624
- /** finish init process for this data source */
3625
- async finishInit() {
3626
- if (!this.graph) throw new Error("expected graph to be set");
3627
- await this._finishInit();
3628
- if (this.loadingError) {
3629
- return;
3630
- }
3631
- const disabledDec = this.getRootDec("disable");
3632
- if (disabledDec) {
3633
- const disabledVal = await disabledDec.resolve();
3634
- if (!my_dash_default.isBoolean(disabledVal)) {
3635
- this._loadingError = new Error("expected @disable to be boolean value");
3636
- return;
3637
- }
3638
- this._disabled = disabledVal;
3639
- }
3640
- if (this.disabled) return;
3641
- for (const itemKey of this.importKeys || my_dash_default.keys(this.configItemDefs)) {
3642
- const itemDef = this.configItemDefs[itemKey];
3643
- if (!itemDef) continue;
3644
- this.graph.configSchema[itemKey] ??= new ConfigItem(this.graph, itemKey);
3645
- }
3646
- const currentEnvDec = this.getRootDec("currentEnv");
3647
- const envFlagDec = this.getRootDec("envFlag");
3648
- if (currentEnvDec && envFlagDec) {
3649
- this._loadingError = new Error("Cannot use both @currentEnv and @envFlag decorators");
3650
- }
3651
- let envFlagItemKey;
3652
- let skipCurrentEnvProcessing = false;
3653
- if (currentEnvDec) {
3654
- const parsedValue = currentEnvDec.parsedDecorator.value;
3655
- if (parsedValue instanceof ParsedEnvSpecFunctionCall && parsedValue.name === "ref") {
3656
- const args = parsedValue.simplifiedArgs;
3657
- if (Array.isArray(args) && args.length > 0 && typeof args[0] === "string") {
3658
- envFlagItemKey = args[0];
3659
- if (this.isPartialImport && !this.importKeys?.includes(envFlagItemKey)) {
3660
- skipCurrentEnvProcessing = true;
3661
- }
3662
- }
3663
- }
3664
- if (!skipCurrentEnvProcessing) {
3665
- await currentEnvDec.process();
3666
- if (!currentEnvDec.decValueResolver) {
3667
- throw new Error("No resolver found for @currentEnv decorator");
3668
- }
3669
- if (currentEnvDec.decValueResolver.fnName !== "ref") {
3670
- throw new Error("Expected @currentEnv decorator to be set to direct reference - ie `$APP_ENV`");
3671
- }
3672
- }
3673
- } else if (envFlagDec) {
3674
- await envFlagDec.process();
3675
- if (!envFlagDec.decValueResolver) throw new Error("@envFlag resolver not set");
3676
- if (!envFlagDec.decValueResolver.staticValue) {
3677
- throw new Error("Expected @envFlag decorator to be static value");
3678
- }
3679
- envFlagItemKey = String(envFlagDec.decValueResolver.staticValue);
3680
- }
3681
- if (envFlagItemKey) {
3682
- if (!this.configItemDefs[envFlagItemKey]) {
3683
- this._loadingError = new Error(`environment flag "${envFlagItemKey}" must be defined within this schema`);
3684
- return;
3685
- }
3686
- this.setEnvFlag(envFlagItemKey);
3687
- }
3688
- const defaultSensitiveDec = this.getRootDec("defaultSensitive");
3689
- await defaultSensitiveDec?.process();
3690
- const defaultRequiredDec = this.getRootDec("defaultRequired");
3691
- await defaultRequiredDec?.process();
3692
- await processPluginInstallDecorators(this);
3693
- if (!this.isValid) return;
3694
- const importDecs = this.getRootDecFns("import");
3695
- if (importDecs.length) {
3696
- for (const importDec of importDecs) {
3697
- try {
3698
- await importDec.process();
3699
- if (importDec.decValueResolver?.objArgs?.enabled) {
3700
- const enabledResolver = importDec.decValueResolver.objArgs.enabled;
3701
- const enabledDeps = enabledResolver.deps;
3702
- for (const depKey of enabledDeps) {
3703
- const depItem = this.graph.configSchema[depKey];
3704
- if (!depItem) {
3705
- throw new Error(`@import enabled parameter depends on non-existent item: ${depKey}`);
3706
- }
3707
- await depItem.earlyResolve();
3708
- }
3709
- }
3710
- const importArgs = await importDec.resolve();
3711
- const importPath = importArgs.arr[0];
3712
- const importKeys = importArgs.arr.slice(1);
3713
- if (!importKeys.every(my_dash_default.isString)) {
3714
- throw new Error("expected @import keys to all be strings");
3715
- }
3716
- let fullImportPath;
3717
- if (importPath.startsWith("./") || importPath.startsWith("../")) {
3718
- if (!(this instanceof FileBasedDataSource)) {
3719
- throw new Error("@import of files can only be used from a file-based data source");
3720
- }
3721
- fullImportPath = path2.resolve(this.fullPath, "..", importPath);
3722
- } else if (importPath.startsWith("~/") || importPath === "~") {
3723
- fullImportPath = path2.join(os.homedir(), importPath.slice(1));
3724
- } else if (importPath.startsWith("/")) {
3725
- fullImportPath = importPath;
3726
- }
3727
- const enabledValue = importArgs.obj.enabled ?? true;
3728
- if (!my_dash_default.isBoolean(enabledValue)) {
3729
- throw new Error("expected @import enabled parameter to be a boolean");
3730
- }
3731
- if (!enabledValue) continue;
3732
- const allowMissing = importArgs.obj.allowMissing ?? false;
3733
- if (!my_dash_default.isBoolean(allowMissing)) {
3734
- throw new Error("expected @import allowMissing parameter to be a boolean");
3735
- }
3736
- if (fullImportPath) {
3737
- const fileName = path2.basename(fullImportPath);
3738
- if (this.graph.virtualImports) {
3739
- if (importPath.endsWith("/")) {
3740
- const dirExists = Object.keys(this.graph.virtualImports).some((p) => p.startsWith(fullImportPath));
3741
- if (!dirExists && allowMissing) continue;
3742
- if (!dirExists) {
3743
- this._loadingError = new Error(`Virtual directory import ${fullImportPath} not found`);
3744
- return;
3745
- }
3746
- await this.addChild(new DirectoryDataSource(fullImportPath), {
3747
- isImport: true,
3748
- importKeys
3749
- });
3750
- } else {
3751
- const fileExists = this.graph.virtualImports[fullImportPath];
3752
- if (!fileExists && allowMissing) continue;
3753
- if (!fileExists) {
3754
- this._loadingError = new Error(`Virtual import ${fullImportPath} not found`);
3755
- return;
3756
- }
3757
- const source = new DotEnvFileDataSource(fullImportPath, {
3758
- overrideContents: this.graph.virtualImports[fullImportPath]
3759
- });
3760
- await this.addChild(source, { isImport: true, importKeys });
3761
- }
3762
- } else {
3763
- const fsStat = await tryCatch(async () => fs2.stat(fullImportPath), (_err) => {
3764
- });
3765
- if (!fsStat && allowMissing) continue;
3766
- if (!fsStat) {
3767
- this._loadingError = new Error(`Import path does not exist: ${fullImportPath}`);
3768
- return;
3769
- }
3770
- if (importPath.endsWith("/")) {
3771
- if (fsStat.isDirectory()) {
3772
- await this.addChild(new DirectoryDataSource(fullImportPath), {
3773
- isImport: true,
3774
- importKeys
3775
- });
3776
- } else {
3777
- this._loadingError = new Error(`Imported path ending with "/" is not a directory: ${fullImportPath}`);
3778
- return;
3779
- }
3780
- } else {
3781
- if (fsStat.isDirectory()) {
3782
- this._loadingError = new Error('Imported path is a directory, add trailing "/" to import');
3783
- return;
3784
- } else if (!fileName.startsWith(".env.")) {
3785
- this._loadingError = new Error("imported file must be a .env.* file");
3786
- return;
3787
- }
3788
- await this.addChild(new DotEnvFileDataSource(fullImportPath), { isImport: true, importKeys });
3789
- }
3790
- }
3791
- } else if (importPath.startsWith("http://") || importPath.startsWith("https://")) {
3792
- this._loadingError = new Error("http imports not supported yet");
3793
- return;
3794
- } else if (importPath.startsWith("npm:")) {
3795
- this._loadingError = new Error("npm imports not supported yet");
3796
- return;
3797
- } else {
3798
- this._loadingError = new Error("unsupported import type");
3799
- return;
3800
- }
3801
- } catch (err) {
3802
- this._loadingError = err;
3803
- return;
3804
- }
3805
- }
3806
- }
3807
- }
3808
- /**
3809
- * called by the finishInit - meant to be overridden by subclasses
3810
- * to add specific behaviour for that data source type
3811
- * @internal
3812
- * */
3813
- async _finishInit() {
3814
- }
3815
- type = "values";
3816
- applyForEnv;
3817
- _disabled = false;
3818
- get disabled() {
3819
- return this._disabled || this.parent?._disabled;
3820
- }
3821
- /** an error encountered while loading/parsing the data source */
3822
- _loadingError;
3823
- get loadingError() {
3824
- if (this._loadingError) return this._loadingError;
3825
- if (this.graph) {
3826
- for (const plugin of this.graph.plugins) {
3827
- if (plugin.loadingError) {
3828
- for (const installDecorator of plugin.installDecoratorInstances) {
3829
- if (installDecorator.dataSource === this) {
3830
- return plugin.loadingError;
3831
- }
3832
- }
3833
- }
3834
- }
3835
- }
3836
- return void 0;
3837
- }
3838
- _schemaErrors = [];
3839
- get schemaErrors() {
3840
- return my_dash_default.compact([
3841
- ...this._schemaErrors,
3842
- ...this.rootDecorators.flatMap((d) => d.schemaErrors)
3843
- ]);
3844
- }
3845
- get resolutionErrors() {
3846
- return my_dash_default.compact([...this.rootDecorators.flatMap((d) => d._executionError)]);
3847
- }
3848
- get isValid() {
3849
- return !this.loadingError && !this.schemaErrors.length && !this.resolutionErrors.length;
3850
- }
3851
- configItemDefs = {};
3852
- decorators = [];
3853
- getRootDecorators(decName) {
3854
- return this.decorators.filter((d) => d.name === decName);
3855
- }
3856
- getRootDecoratorSimpleValue(decName) {
3857
- const decorators = this.getRootDecorators(decName);
3858
- if (decorators.length === 0) return void 0;
3859
- if (decorators.length > 1) throw new Error(`Multiple ${decName} decorators found`);
3860
- return decorators[0].simplifiedValue;
3861
- }
3862
- rootDecorators = [];
3863
- getRootDec(decName) {
3864
- return this.rootDecorators.find((d) => d.name === decName && !d.isFunctionCall);
3865
- }
3866
- getRootDecFns(decName) {
3867
- return this.rootDecorators.filter((d) => d.name === decName && d.isFunctionCall);
3868
- }
3869
- };
3870
- var FileBasedDataSource = class extends EnvGraphDataSource4 {
3871
- static {
3872
- __name(this, "FileBasedDataSource");
3873
- }
3874
- fullPath;
3875
- fileName;
3876
- rawContents;
3877
- get typeLabel() {
3878
- return this.constructor.format;
3879
- }
3880
- relativePath;
3881
- get label() {
3882
- return this.relativePath;
3883
- }
3884
- static format = "unknown";
3885
- // no abstract static
3886
- static validFileExtensions = [];
3887
- get validFileExtensions() {
3888
- return this.constructor.validFileExtensions;
3889
- }
3890
- constructor(fullPath, opts) {
3891
- super();
3892
- this.fullPath = fullPath;
3893
- this.fileName = path2.basename(fullPath);
3894
- this.relativePath = path2.relative(process.cwd(), fullPath);
3895
- if (opts?.overrideContents) {
3896
- this.rawContents = opts.overrideContents;
3897
- }
3898
- if (this.fileName.startsWith(".env")) {
3899
- const fileNameParts = this.fileName.substring(1).split(".");
3900
- const maybeExtension = fileNameParts[fileNameParts.length - 1];
3901
- if (this.validFileExtensions.includes(maybeExtension)) {
3902
- fileNameParts.pop();
3903
- }
3904
- const maybeFileType = fileNameParts[fileNameParts.length - 1];
3905
- for (const [possibleSourceType, possibleSourceSpec] of Object.entries(DATA_SOURCE_TYPES)) {
3906
- if (!("fileSuffixes" in possibleSourceSpec)) continue;
3907
- if (possibleSourceSpec.fileSuffixes.includes(maybeFileType)) {
3908
- this.type = possibleSourceType;
3909
- break;
3910
- }
3911
- }
3912
- if (this.type !== "values") fileNameParts.pop();
3913
- if (fileNameParts.length > 2) {
3914
- throw Error(`Unsure how to interpret filename - ${this.fileName}`);
3915
- } else if (fileNameParts.length === 2) {
3916
- this.applyForEnv = fileNameParts[1];
3917
- }
3918
- }
3919
- }
3920
- // no async constructors... :(
3921
- async _finishInit() {
3922
- if (!this.rawContents) {
3923
- if (!await pathExists(this.fullPath)) {
3924
- this._loadingError = new Error(`File does not exist: ${this.fullPath}`);
3925
- return;
3926
- }
3927
- this.rawContents = await fs2.readFile(this.fullPath, "utf8");
3928
- }
3929
- if (this.rawContents) await this._parseContents();
3930
- }
3931
- };
3932
- var DotEnvFileDataSource = class extends FileBasedDataSource {
3933
- static {
3934
- __name(this, "DotEnvFileDataSource");
3935
- }
3936
- static format = ".env";
3937
- static validFileExtensions = [];
3938
- // no extension for dotenv files!
3939
- parsedFile;
3940
- async _parseContents() {
3941
- const rawContents = this.rawContents;
3942
- this.parsedFile = await tryCatch(
3943
- () => parseEnvSpecDotEnvFile(rawContents),
3944
- (error) => {
3945
- this._loadingError = new ParseError(`Parse error: ${error.message}`, {
3946
- location: {
3947
- id: this.fullPath,
3948
- lineNumber: error.location.start.line,
3949
- colNumber: error.location.start.column,
3950
- lineStr: rawContents.split("\n")[error.location.start.line - 1]
3951
- }
3952
- });
3953
- this._loadingError.cause = error;
3954
- }
3955
- );
3956
- if (this.loadingError) return;
3957
- if (!this.parsedFile) throw new Error("Failed to parse .env file");
3958
- if (!this.graph) throw new Error("expected graph to be set");
3959
- this.rootDecorators = this.parsedFile.decoratorsArray.map((d) => new RootDecoratorInstance(this, d));
3960
- for (const item of this.parsedFile.configItems) {
3961
- this.configItemDefs[item.key] = {
3962
- description: item.description,
3963
- parsedValue: item.value,
3964
- parsedDecorators: item.decoratorsArray
3965
- };
3966
- }
3967
- }
3968
- };
3969
- var DirectoryDataSource = class extends EnvGraphDataSource4 {
3970
- constructor(basePath) {
3971
- super();
3972
- this.basePath = basePath;
3973
- }
3974
- static {
3975
- __name(this, "DirectoryDataSource");
3976
- }
3977
- type = "container";
3978
- typeLabel = "directory";
3979
- get label() {
3980
- return `directory - ${this.basePath}`;
3981
- }
3982
- schemaDataSource;
3983
- async addAutoLoadedFile(fileName) {
3984
- if (!this.graph) throw new Error("expected graph to be set");
3985
- const filePath = path2.join(this.basePath, fileName);
3986
- if (this.graph.virtualImports) {
3987
- if (this.graph.virtualImports[filePath]) {
3988
- const source2 = new DotEnvFileDataSource(filePath, { overrideContents: this.graph.virtualImports[filePath] });
3989
- await this.addChild(source2);
3990
- return source2;
3991
- }
3992
- return;
3993
- }
3994
- if (!await pathExists(filePath)) return;
3995
- const source = new DotEnvFileDataSource(filePath);
3996
- await this.addChild(source);
3997
- return source;
3998
- }
3999
- async _finishInit() {
4000
- if (!this.graph) throw new Error("expected graph to be set");
4001
- await this.addAutoLoadedFile(".env.schema");
4002
- await this.addAutoLoadedFile(".env");
4003
- if (this.children.length) {
4004
- this.schemaDataSource = this.children[this.children.length - 1];
4005
- }
4006
- await this.addAutoLoadedFile(".env.local");
4007
- let currentEnv;
4008
- if (this.schemaDataSource?._envFlagKey) {
4009
- const envFlagKey = this.schemaDataSource._envFlagKey;
4010
- if (this.isPartialImport && !this.importKeys?.includes(envFlagKey)) {
4011
- this._loadingError = new Error(
4012
- `Imported directory has @currentEnv set to $${envFlagKey}, but "${envFlagKey}" is not included in the import list. Add "${envFlagKey}" to the @import() arguments.`
4013
- );
4014
- return;
4015
- }
4016
- const envFlagItem = this.graph.configSchema[envFlagKey];
4017
- if (envFlagItem) {
4018
- if (!envFlagItem.resolvedValue) await envFlagItem.earlyResolve();
4019
- currentEnv = envFlagItem.resolvedValue?.toString();
4020
- }
4021
- }
4022
- currentEnv ||= (await this.resolveCurrentEnv())?.toString() || this.envFlagValue?.toString();
4023
- if (currentEnv) {
4024
- await this.addAutoLoadedFile(`.env.${currentEnv}`);
4025
- await this.addAutoLoadedFile(`.env.${currentEnv}.local`);
4026
- }
4027
- }
4028
- };
4029
- async function loadEnvGraph(opts) {
4030
- const graph = new EnvGraph2();
4031
- if (opts?.entryFilePath) {
4032
- const resolvedPath = path2.resolve(opts.entryFilePath);
4033
- if (opts.entryFilePath.endsWith("/") || opts.entryFilePath.endsWith(path2.sep)) {
4034
- graph.basePath = resolvedPath;
4035
- if (opts?.afterInit) await opts.afterInit(graph);
4036
- if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
4037
- await graph.setRootDataSource(new DirectoryDataSource(resolvedPath));
4038
- } else {
4039
- graph.basePath = path2.dirname(resolvedPath);
4040
- if (opts?.afterInit) await opts.afterInit(graph);
4041
- if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
4042
- await graph.setRootDataSource(new DotEnvFileDataSource(resolvedPath));
4043
- }
4044
- } else {
4045
- graph.basePath = opts?.basePath ?? process.cwd();
4046
- if (opts?.afterInit) await opts.afterInit(graph);
4047
- if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
4048
- await graph.setRootDataSource(new DirectoryDataSource(graph.basePath));
4049
- }
4050
- await graph.finishLoad();
4051
- return graph;
4052
- }
4053
- __name(loadEnvGraph, "loadEnvGraph");
4054
-
4055
- // src/lib/formatting.ts
4056
- function applyMods(str, mods) {
4057
- if (!mods) return str;
4058
- if (my_dash_default.isArray(mods)) {
4059
- let modStr = str;
4060
- mods.forEach((mod) => {
4061
- modStr = ansis_default[mod](modStr);
4062
- });
4063
- return modStr;
4064
- }
4065
- return ansis_default[mods](str);
4066
- }
4067
- __name(applyMods, "applyMods");
4068
- function formattedValue(val, showType = false) {
4069
- let strVal = "";
4070
- let strType = "";
4071
- let mods;
4072
- if (my_dash_default.isBoolean(val)) {
4073
- strVal = val.toString();
4074
- mods = ["yellow", "italic"];
4075
- strType = "boolean";
4076
- } else if (my_dash_default.isNumber(val)) {
4077
- strVal = val.toString();
4078
- mods = "yellow";
4079
- strType = "number";
4080
- } else if (my_dash_default.isString(val)) {
4081
- strVal = `"${val}"`;
4082
- strType = "string";
4083
- } else if (my_dash_default.isPlainObject(val)) {
4084
- strVal = JSON.stringify(val);
4085
- strType = "object";
4086
- } else if (val === null) {
4087
- strVal = "null";
4088
- mods = "gray";
4089
- } else if (val === void 0) {
4090
- strVal = "undefined";
4091
- mods = "gray";
4092
- }
4093
- return [
4094
- applyMods(strVal, mods),
4095
- showType && strType ? ansis_default.gray(` (${strType})`) : ""
4096
- ].join("");
4097
- }
4098
- __name(formattedValue, "formattedValue");
4099
- function joinAndCompact(strings, joinChar = " ") {
4100
- return strings.filter((s) => (
4101
- // we'll not filter out empty strings - because it's useful to just add newlines
4102
- s !== void 0 && s !== null && s !== false
4103
- )).join(joinChar);
4104
- }
4105
- __name(joinAndCompact, "joinAndCompact");
4106
- var VALIDATION_STATE_COLORS = {
4107
- error: "red",
4108
- warn: "yellow",
4109
- valid: "cyan"
4110
- };
4111
- function getItemSummary(item) {
4112
- const summary = [];
4113
- const itemErrors = item.errors;
4114
- const icon = itemErrors.length ? itemErrors[0].icon : "\u2705";
4115
- const isSensitive = item.isSensitive;
4116
- const isRequired = item.isRequired;
4117
- summary.push(joinAndCompact([
4118
- icon,
4119
- ansis_default[VALIDATION_STATE_COLORS[item.validationState]](item.key) + (isRequired ? ansis_default.magenta("*") : ""),
4120
- // ansis.gray(`[type = ${item.type.typeLabel}]`),
4121
- isSensitive && ` \u{1F510}${ansis_default.gray.italic("sensitive")}`
4122
- // item.useAt ? ansis.gray.italic(`(${item.useAt?.join(', ')})`) : undefined,
4123
- ]));
4124
- let valAsStr = formattedValue(item.resolvedValue, false);
4125
- if (isSensitive && item.resolvedValue && my_dash_default.isString(item.resolvedValue)) {
4126
- valAsStr = redactString(item.resolvedValue);
4127
- }
4128
- summary.push(joinAndCompact([
4129
- ansis_default.gray(" \u2514"),
4130
- valAsStr,
4131
- item.isCoerced && ansis_default.gray.italic("< coerced from ") + (isSensitive ? formattedValue(item.resolvedRawValue) : formattedValue(item.resolvedRawValue, false))
4132
- ]));
4133
- itemErrors?.forEach((err) => {
4134
- summary.push(ansis_default[err.isWarning ? "yellow" : "red"](` - ${err.isWarning ? "[WARNING] " : ""}${err.message}`));
4135
- if (err.tip) {
4136
- summary.push(...err.tip.split("\n").map((line) => ` ${line}`));
4137
- }
4138
- });
4139
- return summary.join("\n");
4140
- }
4141
- __name(getItemSummary, "getItemSummary");
4142
- //! these are probably not relevant anymore, or needs to move to a plugin layer?
4143
-
4144
- export { CoercionError, ConfigLoadError, DotEnvFileDataSource, EnvGraph2 as EnvGraph, FileBasedDataSource, ResolutionError, SchemaError, ValidationError, VarlockError, ansis_default, asyncExitHook, getItemSummary, gracefulExit, joinAndCompact, loadEnvGraph, my_dash_default, pathExists, pathExistsSync, tryCatch };
4145
- //# sourceMappingURL=chunk-FETFVFG5.js.map
4146
- //# sourceMappingURL=chunk-FETFVFG5.js.map