@powerlines/nx 0.11.239 → 0.11.241

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 (56) hide show
  1. package/dist/src/base/base-executor.d.mts +1 -1
  2. package/dist/src/base/base-executor.d.ts +1 -1
  3. package/dist/src/base/base-executor.js +1 -1
  4. package/dist/src/base/base-executor.mjs +1 -1
  5. package/dist/src/base/index.d.mts +1 -1
  6. package/dist/src/base/index.d.ts +1 -1
  7. package/dist/src/base/index.js +1 -1
  8. package/dist/src/base/index.mjs +1 -1
  9. package/dist/src/{base-executor-Bio0Wn3z.mjs → base-executor-BvEsnkBL.mjs} +55 -25
  10. package/dist/src/base-executor-BvEsnkBL.mjs.map +1 -0
  11. package/dist/src/{base-executor-yjvW7EQ1.d.ts → base-executor-CZijjH-b.d.ts} +12 -3
  12. package/dist/src/{base-executor-yjvW7EQ1.d.ts.map → base-executor-CZijjH-b.d.ts.map} +1 -1
  13. package/dist/src/{base-executor-CPuT8VBu.js → base-executor-CcbUno8j.js} +54 -24
  14. package/dist/src/base-executor-DZRSu2uF.mjs +4658 -0
  15. package/dist/src/base-executor-DZRSu2uF.mjs.map +1 -0
  16. package/dist/src/{base-executor-BcCIQY-2.d.mts → base-executor-kPTbnW7K.d.mts} +12 -3
  17. package/dist/src/{base-executor-BcCIQY-2.d.mts.map → base-executor-kPTbnW7K.d.mts.map} +1 -1
  18. package/dist/src/base-executor-pl95GpNV.js +4676 -0
  19. package/dist/src/base-executor.untyped-7SvGKXcO.d.mts +7 -0
  20. package/dist/src/base-executor.untyped-7SvGKXcO.d.mts.map +1 -0
  21. package/dist/src/executors/build/executor.d.mts +1 -1
  22. package/dist/src/executors/build/executor.d.ts +1 -1
  23. package/dist/src/executors/build/executor.js +1 -1
  24. package/dist/src/executors/build/executor.mjs +1 -1
  25. package/dist/src/executors/build/untyped.d.mts +2 -2
  26. package/dist/src/executors/build/untyped.d.ts +2 -2
  27. package/dist/src/executors/clean/executor.d.mts +1 -1
  28. package/dist/src/executors/clean/executor.d.ts +1 -1
  29. package/dist/src/executors/clean/executor.js +1 -1
  30. package/dist/src/executors/clean/executor.mjs +1 -1
  31. package/dist/src/executors/clean/untyped.d.mts +2 -2
  32. package/dist/src/executors/clean/untyped.d.ts +2 -2
  33. package/dist/src/executors/docs/executor.d.mts +1 -1
  34. package/dist/src/executors/docs/executor.d.ts +1 -1
  35. package/dist/src/executors/docs/executor.js +1 -1
  36. package/dist/src/executors/docs/executor.mjs +1 -1
  37. package/dist/src/executors/docs/untyped.d.mts +2 -2
  38. package/dist/src/executors/lint/executor.d.mts +1 -1
  39. package/dist/src/executors/lint/executor.d.ts +1 -1
  40. package/dist/src/executors/lint/executor.js +1 -1
  41. package/dist/src/executors/lint/executor.mjs +1 -1
  42. package/dist/src/executors/lint/untyped.d.mts +2 -2
  43. package/dist/src/executors/lint/untyped.d.ts +2 -2
  44. package/dist/src/executors/prepare/executor.d.mts +1 -1
  45. package/dist/src/executors/prepare/executor.d.ts +1 -1
  46. package/dist/src/executors/prepare/executor.js +1 -1
  47. package/dist/src/executors/prepare/executor.mjs +1 -1
  48. package/dist/src/executors/prepare/untyped.d.mts +2 -2
  49. package/dist/src/executors/prepare/untyped.d.ts +2 -2
  50. package/dist/src/generators/sync/untyped.d.ts +2 -2
  51. package/dist/src/index.d.mts +1 -1
  52. package/dist/src/index.d.ts +1 -1
  53. package/dist/src/index.js +1 -1
  54. package/dist/src/index.mjs +1 -1
  55. package/package.json +16 -16
  56. package/dist/src/base-executor-Bio0Wn3z.mjs.map +0 -1
@@ -0,0 +1,4676 @@
1
+ const require_config = require('./config-CGQhS8tm.js');
2
+ let __storm_software_config_tools_logger = require("@storm-software/config-tools/logger");
3
+ let __storm_software_workspace_tools_base_base_executor = require("@storm-software/workspace-tools/base/base-executor");
4
+ let __stryke_type_checks_is_error = require("@stryke/type-checks/is-error");
5
+ let defu = require("defu");
6
+ defu = require_config.__toESM(defu);
7
+ let __stryke_fs_get_workspace_root = require("@stryke/fs/get-workspace-root");
8
+ let __storm_software_config_tools_logger_console = require("@storm-software/config-tools/logger/console");
9
+ let __stryke_convert_to_array = require("@stryke/convert/to-array");
10
+ let __stryke_fs_helpers = require("@stryke/fs/helpers");
11
+ let __stryke_fs_install = require("@stryke/fs/install");
12
+ let __stryke_fs_list_files = require("@stryke/fs/list-files");
13
+ let __stryke_fs_package_fns = require("@stryke/fs/package-fns");
14
+ let __stryke_fs_resolve = require("@stryke/fs/resolve");
15
+ let __stryke_helpers_omit = require("@stryke/helpers/omit");
16
+ let __stryke_path_append = require("@stryke/path/append");
17
+ let __stryke_path_join_paths = require("@stryke/path/join-paths");
18
+ let __stryke_path_replace = require("@stryke/path/replace");
19
+ let __stryke_type_checks_is_function = require("@stryke/type-checks/is-function");
20
+ let __stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
21
+ let __stryke_type_checks_is_object = require("@stryke/type-checks/is-object");
22
+ let __stryke_type_checks_is_promise = require("@stryke/type-checks/is-promise");
23
+ let __stryke_type_checks_is_set = require("@stryke/type-checks/is-set");
24
+ let __stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
25
+ let __stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
26
+ let __stryke_type_checks_is_string = require("@stryke/type-checks/is-string");
27
+ let chalk = require("chalk");
28
+ chalk = require_config.__toESM(chalk);
29
+ let handlebars = require("handlebars");
30
+ handlebars = require_config.__toESM(handlebars);
31
+ let __stryke_path_file_path_fns = require("@stryke/path/file-path-fns");
32
+ let __stryke_path_is_parent_path = require("@stryke/path/is-parent-path");
33
+ let __stryke_string_format_pretty_bytes = require("@stryke/string-format/pretty-bytes");
34
+ let ts_morph = require("ts-morph");
35
+ let __stryke_helpers_get_unique = require("@stryke/helpers/get-unique");
36
+ let __stryke_type_checks_is_regexp = require("@stryke/type-checks/is-regexp");
37
+ let __stryke_type_checks_is_undefined = require("@stryke/type-checks/is-undefined");
38
+ let __stryke_path_join = require("@stryke/path/join");
39
+ let prettier = require("prettier");
40
+ let node_fs = require("node:fs");
41
+ let __stryke_string_format_package = require("@stryke/string-format/package");
42
+ let __stryke_fs_exists = require("@stryke/fs/exists");
43
+ let __stryke_fs_json = require("@stryke/fs/json");
44
+ require("@stryke/fs/remove-file");
45
+ let __stryke_string_format_kebab_case = require("@stryke/string-format/kebab-case");
46
+ let __donedeal0_superdiff = require("@donedeal0/superdiff");
47
+ let __stryke_json_storm_json = require("@stryke/json/storm-json");
48
+ let __stryke_string_format_title_case = require("@stryke/string-format/title-case");
49
+ let typescript = require("typescript");
50
+ typescript = require_config.__toESM(typescript);
51
+ let __storm_software_config_tools_types = require("@storm-software/config-tools/types");
52
+ let __stryke_env_get_env_paths = require("@stryke/env/get-env-paths");
53
+ let __stryke_hash = require("@stryke/hash");
54
+ let __stryke_hash_node = require("@stryke/hash/node");
55
+ let __stryke_http_fetch = require("@stryke/http/fetch");
56
+ let __stryke_type_checks_is_null = require("@stryke/type-checks/is-null");
57
+ let __stryke_unique_id_uuid = require("@stryke/unique-id/uuid");
58
+ let bundle_require = require("bundle-require");
59
+ let compatx = require("compatx");
60
+ let flat_cache = require("flat-cache");
61
+ let oxc_parser = require("oxc-parser");
62
+ let undici = require("undici");
63
+ let jiti = require("jiti");
64
+ let __stryke_capnp = require("@stryke/capnp");
65
+ __stryke_capnp = require_config.__toESM(__stryke_capnp);
66
+ let __stryke_fs_buffer = require("@stryke/fs/buffer");
67
+ let __stryke_path_correct_path = require("@stryke/path/correct-path");
68
+ let __stryke_path_glob_to_regex = require("@stryke/path/glob-to-regex");
69
+ let __stryke_path_is_type = require("@stryke/path/is-type");
70
+ let __stryke_path_slash = require("@stryke/path/slash");
71
+ let node_buffer = require("node:buffer");
72
+ let node_url = require("node:url");
73
+ let __stryke_fs_is_file = require("@stryke/fs/is-file");
74
+ let __stryke_fs_read_file = require("@stryke/fs/read-file");
75
+ let __stryke_fs_write_file = require("@stryke/fs/write-file");
76
+ let node_fs_promises = require("node:fs/promises");
77
+ let node_path = require("node:path");
78
+ let __stryke_convert_parse_type_definition = require("@stryke/convert/parse-type-definition");
79
+ let __storm_software_config_tools_utilities_colors = require("@storm-software/config-tools/utilities/colors");
80
+ let __stryke_helpers_noop = require("@stryke/helpers/noop");
81
+ require("magic-string");
82
+ let diff_match_patch = require("diff-match-patch");
83
+ diff_match_patch = require_config.__toESM(diff_match_patch);
84
+ require("unplugin");
85
+
86
+ //#region ../powerlines/package.json
87
+ var version = "0.39.20";
88
+
89
+ //#endregion
90
+ //#region ../powerlines/src/typescript/ts-morph.ts
91
+ var VirtualFileSystemHost = class extends ts_morph.InMemoryFileSystemHost {
92
+ #context;
93
+ constructor(context) {
94
+ super();
95
+ this.#context = context;
96
+ }
97
+ deleteSync(path) {
98
+ this.#context.fs.removeSync(path);
99
+ }
100
+ readDirSync(dirPath) {
101
+ if (!this.#context.fs.isDirectorySync(dirPath)) return [];
102
+ return this.#context.fs.listSync(dirPath).reduce((ret, entry) => {
103
+ const fullPath = this.#context.fs.resolveSync(entry);
104
+ if (fullPath) ret.push({
105
+ name: entry,
106
+ isDirectory: this.#context.fs.isDirectorySync(fullPath),
107
+ isFile: this.#context.fs.isFileSync(fullPath),
108
+ isSymlink: false
109
+ });
110
+ return ret;
111
+ }, []);
112
+ }
113
+ async readFile(filePath) {
114
+ if (!this.#context.fs.isFileSync(filePath)) return "";
115
+ return await this.#context.fs.read(filePath);
116
+ }
117
+ readFileSync(filePath) {
118
+ if (!this.#context.fs.isFileSync(filePath)) return "";
119
+ return this.#context.fs.readSync(filePath);
120
+ }
121
+ async writeFile(filePath, fileText) {
122
+ return this.#context.fs.write(filePath, fileText);
123
+ }
124
+ writeFileSync(filePath, fileText) {
125
+ this.#context.fs.writeSync(filePath, fileText);
126
+ }
127
+ async mkdir(dirPath) {
128
+ await this.#context.fs.mkdir(dirPath);
129
+ }
130
+ mkdirSync(dirPath) {
131
+ this.#context.fs.mkdirSync(dirPath);
132
+ }
133
+ async move(srcPath, destPath) {
134
+ await this.#context.fs.move(srcPath, destPath);
135
+ }
136
+ moveSync(srcPath, destPath) {
137
+ this.#context.fs.moveSync(srcPath, destPath);
138
+ }
139
+ async copy(srcPath, destPath) {
140
+ await this.#context.fs.copy(srcPath, destPath);
141
+ }
142
+ copySync(srcPath, destPath) {
143
+ this.#context.fs.copySync(srcPath, destPath);
144
+ }
145
+ async fileExists(filePath) {
146
+ return this.#context.fs.isFile(filePath);
147
+ }
148
+ fileExistsSync(filePath) {
149
+ return this.#context.fs.isFileSync(filePath);
150
+ }
151
+ async directoryExists(dirPath) {
152
+ return this.#context.fs.isDirectory(dirPath);
153
+ }
154
+ directoryExistsSync(dirPath) {
155
+ return this.#context.fs.isDirectorySync(dirPath);
156
+ }
157
+ realpathSync(path) {
158
+ return this.#context.fs.resolveSync(path) || path;
159
+ }
160
+ getCurrentDirectory() {
161
+ return this.#context.workspaceConfig.workspaceRoot;
162
+ }
163
+ async glob(patterns) {
164
+ return this.#context.fs.glob(patterns);
165
+ }
166
+ globSync(patterns) {
167
+ return this.#context.fs.globSync(patterns);
168
+ }
169
+ };
170
+ /**
171
+ * Create a ts-morph {@link Project} instance used for type reflection and module manipulation during processing
172
+ *
173
+ * @param context - The Powerlines context
174
+ * @returns A ts-morph {@link Project} instance
175
+ */
176
+ function createProgram(context, override) {
177
+ context.debug(`Creating ts-morph Project instance with configuration from: ${context.tsconfig.tsconfigFilePath}.`);
178
+ return new ts_morph.Project((0, defu.default)(override ?? {}, {
179
+ skipAddingFilesFromTsConfig: false,
180
+ tsConfigFilePath: context.tsconfig.tsconfigFilePath,
181
+ fileSystem: new VirtualFileSystemHost(context),
182
+ compilerOptions: (0, defu.default)(context.tsconfig.options ?? {}, { lib: ["lib.esnext.full.d.ts"] })
183
+ }));
184
+ }
185
+
186
+ //#endregion
187
+ //#region ../powerlines/src/_internal/helpers/generate-types.ts
188
+ const getModuleCommentBlockRegex = (moduleId) => /* @__PURE__ */ new RegExp(`\\/\\*\\*(?s:.)*?@module\\s+${moduleId}(?s:.)*?\\*\\/\\s+`);
189
+ /**
190
+ * Formats the generated TypeScript types source code.
191
+ *
192
+ * @param code - The generated TypeScript code.
193
+ * @returns The formatted TypeScript code.
194
+ */
195
+ function formatTypes(code) {
196
+ return code.replace(/import\s*(?:type\s*)?\{?[\w,\s]*(?:\}\s*)?from\s*(?:'|")@?[a-zA-Z0-9-\\/.]*(?:'|");?/g, "").replaceAll("#private;", "").replace(/__Ω/g, "");
197
+ }
198
+ /**
199
+ * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.
200
+ *
201
+ * @param context - The context containing options and environment paths.
202
+ * @param files - The list of files to generate types for.
203
+ * @returns A promise that resolves to the generated TypeScript declaration types.
204
+ */
205
+ async function emitBuiltinTypes(context, files) {
206
+ if (files.length === 0) {
207
+ context.debug("No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.");
208
+ return "";
209
+ }
210
+ context.debug(`Running the TypeScript compiler for ${files.length} generated built-in module files.`);
211
+ const program = createProgram(context, {
212
+ skipAddingFilesFromTsConfig: true,
213
+ compilerOptions: {
214
+ declaration: true,
215
+ declarationMap: false,
216
+ emitDeclarationOnly: true,
217
+ sourceMap: false,
218
+ outDir: (0, __stryke_path_replace.replacePath)(context.builtinsPath, context.workspaceConfig.workspaceRoot),
219
+ composite: false,
220
+ incremental: false,
221
+ tsBuildInfoFile: void 0
222
+ }
223
+ });
224
+ program.addSourceFilesAtPaths(files);
225
+ const result = program.emitToMemory({ emitOnlyDtsFiles: true });
226
+ const diagnostics = result.getDiagnostics();
227
+ if (diagnostics && diagnostics.length > 0) if (diagnostics.some((d) => d.getCategory() === ts_morph.DiagnosticCategory.Error)) throw new Error(`The Typescript emit process failed while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === ts_morph.DiagnosticCategory.Error).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
228
+ else if (diagnostics.some((d) => d.getCategory() === ts_morph.DiagnosticCategory.Warning)) context.warn(`The Typescript emit process completed with warnings while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === ts_morph.DiagnosticCategory.Warning).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
229
+ else context.debug(`The Typescript emit process completed with diagnostic messages while generating built-in types: \n ${diagnostics.map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
230
+ const emittedFiles = result.getFiles();
231
+ context.debug(`The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`);
232
+ let builtinModules = "";
233
+ for (const emittedFile of emittedFiles) {
234
+ context.trace(`Processing emitted type declaration file: ${emittedFile.filePath}`);
235
+ const filePath = (0, __stryke_path_append.appendPath)(emittedFile.filePath, context.workspaceConfig.workspaceRoot);
236
+ if (!filePath.endsWith(".map") && (0, __stryke_path_file_path_fns.findFileName)(filePath) !== "tsconfig.tsbuildinfo" && (0, __stryke_path_is_parent_path.isParentPath)(filePath, context.builtinsPath)) {
237
+ const moduleId = `${context.config.framework}:${(0, __stryke_path_replace.replaceExtension)((0, __stryke_path_replace.replacePath)(filePath, context.builtinsPath), "", { fullExtension: true })}`;
238
+ const moduleComment = emittedFile.text.match(getModuleCommentBlockRegex(moduleId))?.find((comment) => (0, __stryke_type_checks_is_set_string.isSetString)(comment?.trim()));
239
+ builtinModules += `${moduleComment ? `\n${moduleComment.trim()}` : ""}
240
+ declare module "${moduleId}" {
241
+ ${emittedFile.text.replace(moduleComment ?? "", "").trim().replace(/^\s*export\s*declare\s*/gm, "export ").replace(/^\s*declare\s*/gm, "")}
242
+ }
243
+ `;
244
+ }
245
+ }
246
+ builtinModules = formatTypes(builtinModules);
247
+ context.debug(`A TypeScript declaration file (size: ${(0, __stryke_string_format_pretty_bytes.prettyBytes)(new Blob((0, __stryke_convert_to_array.toArray)(builtinModules)).size)}) emitted for the built-in modules types.`);
248
+ return builtinModules;
249
+ }
250
+
251
+ //#endregion
252
+ //#region ../core/src/plugin-utils/helpers.ts
253
+ /**
254
+ * Type guard to check if an object is a {@link Plugin}
255
+ *
256
+ * @param value - The object to check
257
+ * @returns True if the object is a {@link Plugin}, false otherwise
258
+ */
259
+ function isPlugin(value) {
260
+ return (0, __stryke_type_checks_is_set_object.isSetObject)(value) && "name" in value && (0, __stryke_type_checks_is_set_string.isSetString)(value.name) && ((0, __stryke_type_checks_is_undefined.isUndefined)(value.api) || "api" in value && (0, __stryke_type_checks_is_set_object.isSetObject)(value.api)) && ((0, __stryke_type_checks_is_undefined.isUndefined)(value.applyToEnvironment) || "applyToEnvironment" in value && (0, __stryke_type_checks_is_function.isFunction)(value.applyToEnvironment)) && ((0, __stryke_type_checks_is_undefined.isUndefined)(value.dedupe) || "dedupe" in value && (0, __stryke_type_checks_is_function.isFunction)(value.dedupe)) && require_config.PLUGIN_HOOKS_FIELDS.every((hook) => (0, __stryke_type_checks_is_undefined.isUndefined)(value[hook]) || hook in value && (isPluginHookFunction(value[hook]) || hook === "config" && (0, __stryke_type_checks_is_set_object.isSetObject)(value[hook]))) && require_config.BUILDER_VARIANTS.every((variant) => (0, __stryke_type_checks_is_undefined.isUndefined)(value[variant]) || variant in value && (0, __stryke_type_checks_is_set_object.isSetObject)(value[variant]));
261
+ }
262
+ /**
263
+ * Type guard to check if an object is a {@link PluginConfigObject}
264
+ *
265
+ * @param value - The object to check
266
+ * @returns True if the object is a {@link PluginConfigObject}, false otherwise
267
+ */
268
+ function isPluginConfigObject(value) {
269
+ return (0, __stryke_type_checks_is_set_object.isSetObject)(value) && "plugin" in value && (((0, __stryke_type_checks_is_set_string.isSetString)(value.plugin) || (0, __stryke_type_checks_is_function.isFunction)(value.plugin)) && "options" in value && (0, __stryke_type_checks_is_set_object.isSetObject)(value.options) || isPlugin(value.plugin));
270
+ }
271
+ /**
272
+ * Type guard to check if an object is a {@link PluginConfigTuple}
273
+ *
274
+ * @param value - The object to check
275
+ * @returns True if the object is a {@link PluginConfigTuple}, false otherwise
276
+ */
277
+ function isPluginConfigTuple(value) {
278
+ return Array.isArray(value) && (value.length === 1 || value.length === 2) && (((0, __stryke_type_checks_is_set_string.isSetString)(value[0]) || (0, __stryke_type_checks_is_function.isFunction)(value[0])) && value.length > 1 && (0, __stryke_type_checks_is_set_object.isSetObject)(value[1]) || isPlugin(value[0]));
279
+ }
280
+ /**
281
+ * Type guard to check if an object is a {@link PluginConfig}
282
+ *
283
+ * @param value - The object to check
284
+ * @returns True if the object is a {@link PluginConfig}, false otherwise
285
+ */
286
+ function isPluginConfig(value) {
287
+ return (0, __stryke_type_checks_is_set_string.isSetString)(value) || (0, __stryke_type_checks_is_function.isFunction)(value) || isPlugin(value) || isPluginConfigObject(value) || isPluginConfigTuple(value) || Array.isArray(value) && value.every((item) => isPluginConfig(item));
288
+ }
289
+ /**
290
+ * Type guard to check if an value is a {@link PluginHook} function
291
+ *
292
+ * @param value - The value to check
293
+ * @returns True if the value is a {@link PluginHook} function, false otherwise
294
+ */
295
+ function isPluginHookObject(value) {
296
+ return (0, __stryke_type_checks_is_set_object.isSetObject)(value) && "handler" in value && (0, __stryke_type_checks_is_function.isFunction)(value.handler);
297
+ }
298
+ /**
299
+ * Type guard to check if an value is a {@link PluginHook} function
300
+ *
301
+ * @param value - The value to check
302
+ * @returns True if the value is a {@link PluginHook} function, false otherwise
303
+ */
304
+ function isPluginHookFunction(value) {
305
+ return (0, __stryke_type_checks_is_function.isFunction)(value) || isPluginHookObject(value);
306
+ }
307
+ /**
308
+ * Type guard to check if an object is a {@link PluginHook}
309
+ *
310
+ * @param value - The object to check
311
+ * @returns True if the object is a {@link PluginHook}, false otherwise
312
+ */
313
+ function isPluginHook(value) {
314
+ return isPluginHookFunction(value) || isPluginHookObject(value);
315
+ }
316
+ /**
317
+ * Extract the hook handler function from a plugin hook
318
+ *
319
+ * @param pluginHook - The plugin hook to extract the handler function from
320
+ * @returns The hook handler function
321
+ */
322
+ function getHookHandler(pluginHook) {
323
+ return (0, __stryke_type_checks_is_function.isFunction)(pluginHook) ? pluginHook : pluginHook.handler;
324
+ }
325
+ /**
326
+ * Check if a hook is external.
327
+ *
328
+ * @param keys - The name of the hook to check.
329
+ * @returns True if the hook is external, false otherwise.
330
+ */
331
+ function isUnpluginHookKey(keys) {
332
+ return require_config.UNPLUGIN_BUILDER_VARIANTS.some((variant) => keys.startsWith(`${variant}:`));
333
+ }
334
+ /**
335
+ * Check if a hook is internal.
336
+ *
337
+ * @param keys - The name of the hook to check.
338
+ * @returns True if the hook is external, false otherwise.
339
+ */
340
+ function isPluginHookField(keys) {
341
+ return !isUnpluginHookKey(keys) && require_config.PLUGIN_HOOKS_FIELDS.includes(keys);
342
+ }
343
+ /**
344
+ * Check if a hook is external.
345
+ *
346
+ * @param field - The name of the hook to check.
347
+ * @returns True if the hook is external, false otherwise.
348
+ */
349
+ function isUnpluginHookField(field) {
350
+ return !isPluginHookField(field) && require_config.UNPLUGIN_BUILDER_VARIANTS.includes(field);
351
+ }
352
+ /**
353
+ * Check if a plugin should be deduplicated.
354
+ *
355
+ * @param plugin - The plugin to check
356
+ * @param plugins - The list of plugins to check against
357
+ * @returns True if the plugin should be deduplicated, false otherwise
358
+ */
359
+ function checkDedupe(plugin, plugins) {
360
+ return plugin.dedupe === false || plugins.some((p) => p.dedupe !== false && ((0, __stryke_type_checks_is_function.isFunction)(p.dedupe) && p.dedupe(plugin) || p.name === plugin.name));
361
+ }
362
+ /**
363
+ * Add a plugin hook to the hooks list.
364
+ *
365
+ * @param context - The plugin context
366
+ * @param plugin - The plugin to add the hook from
367
+ * @param pluginHook - The plugin hook to add
368
+ * @param hooksList - The list of hooks to add to
369
+ */
370
+ function addPluginHook(context, plugin, pluginHook, hooksList) {
371
+ if (!checkDedupe(plugin, hooksList.map((hook) => hook.plugin).filter(Boolean))) {
372
+ const handler = ((...args) => getHookHandler(pluginHook).apply(context, args));
373
+ if (!handler) return;
374
+ hooksList.push({
375
+ plugin,
376
+ handler
377
+ });
378
+ }
379
+ }
380
+ /**
381
+ * Check the provided {@link PluginConfig}, and return a stringified version of the invalid configuration. If an array is provided, check each item in the array.
382
+ *
383
+ * @param config - The plugin configuration to check
384
+ * @returns Null if the configuration is valid, otherwise an array of stringified invalid configurations
385
+ */
386
+ function findInvalidPluginConfig(config) {
387
+ if (isPluginConfig(config)) return null;
388
+ if (Array.isArray(config)) {
389
+ const invalidItems = [];
390
+ config.forEach((item) => {
391
+ const invalid = findInvalidPluginConfig(item);
392
+ if (invalid) invalidItems.push(...invalid.map((i) => JSON.stringify(i, null, 2)));
393
+ });
394
+ return invalidItems.length > 0 ? invalidItems : null;
395
+ }
396
+ return [JSON.stringify(config, null, 2)];
397
+ }
398
+
399
+ //#endregion
400
+ //#region ../core/src/plugin-utils/merge.ts
401
+ const mergePlugin = (0, defu.createDefu)((obj, key, value) => {
402
+ if (isPluginHook(obj[key]) && isPluginHook(value)) {
403
+ obj[key] = {
404
+ ...obj[key],
405
+ ...value,
406
+ handler: async (...params) => {
407
+ const [resultA, resultB] = await Promise.all([getHookHandler(obj[key])(...params), getHookHandler(value)(...params)]);
408
+ return resultB && resultA ? (0, defu.default)(resultA, resultB) : resultA || resultB;
409
+ }
410
+ };
411
+ return true;
412
+ }
413
+ return false;
414
+ });
415
+ /**
416
+ * Merges two configuration objects together, with special handling for string values.
417
+ * If the value from the second object is a non-empty string, it will overwrite the value from the first object.
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * const configA = { name: "Default", version: "1.0.0" };
422
+ * const configB = { name: "Custom", description: "A custom config" };
423
+ * const mergedConfig = mergeConfig(configA, configB);
424
+ * // Result: { name: "Custom", version: "1.0.0", description: "A custom config" }
425
+ * ```
426
+ *
427
+ * @param objA - The first configuration object.
428
+ * @param objB - The second configuration object.
429
+ * @returns The merged configuration object.
430
+ */
431
+ const mergeConfig = (0, defu.createDefu)((obj, key, value) => {
432
+ if ((0, __stryke_type_checks_is_string.isString)(obj[key]) && (0, __stryke_type_checks_is_string.isString)(value)) {
433
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(value)) obj[key] = value;
434
+ return true;
435
+ }
436
+ return false;
437
+ });
438
+
439
+ //#endregion
440
+ //#region ../core/src/lib/utilities/format.ts
441
+ /**
442
+ * Formats code using Prettier based on the file path.
443
+ *
444
+ * @param context - The Powerlines context.
445
+ * @param path - The file path to use for resolving Prettier configuration.
446
+ * @param data - The code string to format.
447
+ * @param force - Whether to force formatting even for output/build paths.
448
+ * @returns A promise that resolves to the formatted code string.
449
+ */
450
+ async function format(context, path, data, force = false) {
451
+ if (!force && ((0, __stryke_path_is_parent_path.isParentPath)(path, (0, __stryke_path_append.appendPath)(context.config.output.outputPath, context.workspaceConfig.workspaceRoot)) || (0, __stryke_path_is_parent_path.isParentPath)(path, (0, __stryke_path_append.appendPath)(context.config.output.buildPath, context.workspaceConfig.workspaceRoot)))) return data;
452
+ let code = data;
453
+ const resolvedConfig = await (0, prettier.resolveConfig)(path);
454
+ if (resolvedConfig) code = await (0, prettier.format)(data, {
455
+ absolutePath: path,
456
+ ...resolvedConfig
457
+ });
458
+ return code;
459
+ }
460
+ /**
461
+ * Formats all files in a folder using Prettier based on their file paths.
462
+ *
463
+ * @param context - The Powerlines context.
464
+ * @param path - The folder path containing files to format.
465
+ * @returns A promise that resolves when all files have been formatted.
466
+ */
467
+ async function formatFolder(context, path) {
468
+ if (!(0, __stryke_path_is_parent_path.isParentPath)(path, (0, __stryke_path_append.appendPath)(context.config.output.outputPath, context.workspaceConfig.workspaceRoot)) && !(0, __stryke_path_is_parent_path.isParentPath)(path, (0, __stryke_path_append.appendPath)(context.config.output.buildPath, context.workspaceConfig.workspaceRoot))) await Promise.allSettled((await (0, __stryke_fs_list_files.listFiles)(path)).map(async (file) => {
469
+ if (!(0, __stryke_path_is_parent_path.isParentPath)(file, (0, __stryke_path_append.appendPath)(context.config.output.outputPath, context.workspaceConfig.workspaceRoot)) && !(0, __stryke_path_is_parent_path.isParentPath)(file, (0, __stryke_path_append.appendPath)(context.config.output.buildPath, context.workspaceConfig.workspaceRoot))) {
470
+ const data = await context.fs.read(file);
471
+ if (data) {
472
+ const formatted = await format(context, file, data);
473
+ return context.fs.write(file, formatted);
474
+ }
475
+ }
476
+ }));
477
+ }
478
+
479
+ //#endregion
480
+ //#region ../core/src/plugin-utils/paths.ts
481
+ /**
482
+ * Replaces tokens in the given path string with their corresponding values from the context.
483
+ *
484
+ * @remarks
485
+ * The following tokens are supported:
486
+ * - `{workspaceRoot}` - The root directory of the workspace.
487
+ * - `{root}` - The root directory of the project (same as `{projectRoot}`).
488
+ * - `{projectRoot}` - The root directory of the project (same as `{root}`).
489
+ * - `{sourceRoot}` - The source root directory of the project (usually `./src`).
490
+ * - `{powerlinesPath}` - The directory where Powerlines is installed.
491
+ * - `{cachePath}` - The environment's directory for cached files.
492
+ * - `{dataPath}` - The environment's directory for data files.
493
+ * - `{logPath}` - The environment's directory for log files.
494
+ * - `{tempPath}` - The environment's directory for temporary files.
495
+ * - `{configPath}` - The environment's directory for configuration files.
496
+ * - `{outputPath}` - The configured output directory for the project.
497
+ * - `{buildPath}` - The configured distribution directory for the project.
498
+ * - `{artifactsPath}` - The configured directory for build artifacts.
499
+ * - `{builtinPath}` - The configured directory for generated built-in plugins.
500
+ * - `{entryPath}` - The configured directory for generated entry files.
501
+ *
502
+ * @param context - The context containing the values for the path tokens.
503
+ * @param path - The path string with tokens to replace.
504
+ * @returns The path string with tokens replaced by their corresponding values from the context.
505
+ */
506
+ function replacePathTokens(context, path) {
507
+ if (!path) return path;
508
+ return path.replaceAll("{workspaceRoot}", context.workspaceConfig.workspaceRoot).replaceAll("{root}", context.config.root).replaceAll("{projectRoot}", context.config.root).replaceAll("{sourceRoot}", (0, __stryke_path_join.joinPaths)(context.config.root, "src")).replaceAll("{powerlinesPath}", context.powerlinesPath).replaceAll("{cachePath}", context.cachePath).replaceAll("{dataPath}", context.dataPath).replaceAll("{logPath}", context.envPaths.log).replaceAll("{tempPath}", context.envPaths.temp).replaceAll("{configPath}", context.envPaths.config).replaceAll("{outputPath}", context.config.output.outputPath).replaceAll("{buildPath}", context.config.output.buildPath).replaceAll("{artifactsPath}", (0, __stryke_path_replace.replacePath)(context.artifactsPath, context.workspaceConfig.workspaceRoot)).replaceAll("{builtinPath}", (0, __stryke_path_replace.replacePath)(context.builtinsPath, context.workspaceConfig.workspaceRoot)).replaceAll("{entryPath}", (0, __stryke_path_replace.replacePath)(context.entryPath, context.workspaceConfig.workspaceRoot));
509
+ }
510
+
511
+ //#endregion
512
+ //#region ../powerlines/src/_internal/helpers/hooks.ts
513
+ const mergeResultObjects = (0, defu.createDefu)((obj, key, value) => {
514
+ if ((0, __stryke_type_checks_is_string.isString)(obj[key]) && (0, __stryke_type_checks_is_string.isString)(value)) {
515
+ obj[key] = `${obj[key] || ""}\n${value || ""}`.trim();
516
+ return true;
517
+ }
518
+ return false;
519
+ });
520
+ /**
521
+ * Merges the current hook result with the previous results based on their types.
522
+ *
523
+ * @param currentResult - The current hook result to merge with the previous results.
524
+ * @param previousResults - The previous hook results to merge with the current result.
525
+ * @returns The merged result.
526
+ */
527
+ function mergeResults(currentResult, previousResults) {
528
+ if ((0, __stryke_type_checks_is_string.isString)(currentResult)) previousResults = [`${(0, __stryke_type_checks_is_string.isString)(previousResults[0]) ? previousResults[0] || "" : ""}\n${currentResult || ""}`.trim()];
529
+ else if ((0, __stryke_type_checks_is_object.isObject)(currentResult)) previousResults = [mergeResultObjects(currentResult, previousResults[0] ?? {})];
530
+ return previousResults;
531
+ }
532
+ /**
533
+ * Merges multiple hook results together, with special handling for string values and object values.
534
+ *
535
+ * @param currentResult - The current hook result to merge with the previous results.
536
+ * @param previousResults - The previous hook results to merge with the current result.
537
+ * @returns The merged result.
538
+ */
539
+ function mergeConfigs(currentResult, previousResults) {
540
+ if ((0, __stryke_type_checks_is_string.isString)(currentResult)) previousResults = [`${(0, __stryke_type_checks_is_string.isString)(previousResults[0]) ? previousResults[0] || "" : ""}\n${currentResult || ""}`.trim()];
541
+ else if ((0, __stryke_type_checks_is_object.isObject)(currentResult)) previousResults = [mergeConfig(currentResult, previousResults[0] ?? {})];
542
+ return previousResults;
543
+ }
544
+ /**
545
+ * Calls a hook with the given context, options, and arguments.
546
+ *
547
+ * @param context - The context to use when calling the hook.
548
+ * @param key - The hook to call.
549
+ * @param options - Options for calling the hook.
550
+ * @param args - Arguments to pass to the hook.
551
+ * @returns The return value of the hook.
552
+ */
553
+ async function callHook(context, key, options, ...args) {
554
+ const hooks = context.selectHooks(key, options);
555
+ if (hooks.length > 0) {
556
+ context.debug(` 🧩 Calling plugin hook: ${chalk.default.bold.cyanBright(`${key}${options?.order ? ` (${options.order})` : ""}`)}`);
557
+ const invokeHook = async (hook, hookArgs) => {
558
+ return Reflect.apply(hook.handler, hook.context, hookArgs);
559
+ };
560
+ let results = [];
561
+ if (options?.sequential === false) results = await Promise.all(hooks.map(async (hook) => {
562
+ if (!(0, __stryke_type_checks_is_function.isFunction)(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
563
+ return invokeHook(hook, [...args]);
564
+ }));
565
+ else for (const hook of hooks) {
566
+ if (!(0, __stryke_type_checks_is_function.isFunction)(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
567
+ if (options?.result === "first" || options?.asNextParam === false) {
568
+ results.push(await Promise.resolve(invokeHook(hook, [...args])));
569
+ if (options?.result === "first" && (0, __stryke_type_checks_is_set.isSet)(results[results.length - 1])) break;
570
+ } else {
571
+ const sequenceArgs = [...args];
572
+ if (results.length > 0 && sequenceArgs.length > 0) sequenceArgs[0] = (0, __stryke_type_checks_is_function.isFunction)(options.asNextParam) ? await Promise.resolve(options.asNextParam(results[0])) : results[0];
573
+ const result = await Promise.resolve(invokeHook(hook, [...sequenceArgs]));
574
+ if (result) if (options.result === "last") results = [result];
575
+ else if (options.result === "merge" && options.merge) results = options.merge(result, results);
576
+ else results = mergeResults(result, results);
577
+ }
578
+ }
579
+ const definedResults = results.filter((result) => (0, __stryke_type_checks_is_set.isSet)(result));
580
+ if (definedResults.length > 0) {
581
+ let mergedResult = void 0;
582
+ for (const result of definedResults) mergedResult = (0, defu.defu)(result, mergedResult ?? {});
583
+ return mergedResult;
584
+ }
585
+ }
586
+ }
587
+
588
+ //#endregion
589
+ //#region ../powerlines/src/_internal/helpers/install.ts
590
+ /**
591
+ * Installs a package if it is not already installed.
592
+ *
593
+ * @param context - The resolved options
594
+ * @param packageName - The name of the package to install
595
+ * @param dev - Whether to install the package as a dev dependency
596
+ */
597
+ async function installPackage(context, packageName, dev = false) {
598
+ if (!await (0, __stryke_fs_package_fns.isPackageListed)((0, __stryke_string_format_package.getPackageName)(packageName), { cwd: context.config.root })) if (context.config.autoInstall) {
599
+ context.warn(`The package "${packageName}" is not installed. It will be installed automatically.`);
600
+ const result = await (0, __stryke_fs_install.install)(packageName, {
601
+ cwd: context.config.root,
602
+ dev
603
+ });
604
+ if ((0, __stryke_type_checks_is_number.isNumber)(result.exitCode) && result.exitCode > 0) {
605
+ context.error(result.stderr);
606
+ throw new Error(`An error occurred while installing the package "${packageName}"`);
607
+ }
608
+ } else context.warn(`The package "${packageName}" is not installed. Since the "autoInstall" option is set to false, it will not be installed automatically.`);
609
+ else if ((0, __stryke_string_format_package.hasPackageVersion)(packageName) && !process.env.POWERLINES_SKIP_VERSION_CHECK) {
610
+ if (!await (0, __stryke_fs_package_fns.doesPackageMatch)((0, __stryke_string_format_package.getPackageName)(packageName), (0, __stryke_string_format_package.getPackageVersion)(packageName), context.config.root)) {
611
+ const packageListing = await (0, __stryke_fs_package_fns.getPackageListing)((0, __stryke_string_format_package.getPackageName)(packageName), { cwd: context.config.root });
612
+ if (!packageListing?.version.startsWith("catalog:") && !packageListing?.version.startsWith("workspace:")) context.warn(`The package "${(0, __stryke_string_format_package.getPackageName)(packageName)}" is installed but does not match the expected version ${(0, __stryke_string_format_package.getPackageVersion)(packageName)} (installed version: ${packageListing?.version || "<Unknown>"}). Please ensure this is intentional before proceeding. Note: You can skip this validation with the "STORM_STACK_SKIP_VERSION_CHECK" environment variable.`);
613
+ }
614
+ }
615
+ }
616
+
617
+ //#endregion
618
+ //#region ../powerlines/src/_internal/helpers/install-dependencies.ts
619
+ /**
620
+ * Install missing project dependencies.
621
+ *
622
+ * @param context - The build context.
623
+ */
624
+ async function installDependencies(context) {
625
+ context.debug(`Checking and installing missing project dependencies.`);
626
+ context.dependencies ??= {};
627
+ context.devDependencies ??= {};
628
+ if (Object.keys(context.dependencies).length === 0 && Object.keys(context.devDependencies).length === 0) {
629
+ context.debug(`No dependencies or devDependencies to install. Skipping installation step.`);
630
+ return;
631
+ }
632
+ context.debug(`The following packages are required: \nDependencies: \n${Object.entries(context.dependencies).map(([name, version$1]) => `- ${name}@${String(version$1)}`).join(" \n")}\n\nDevDependencies: \n${Object.entries(context.devDependencies).map(([name, version$1]) => `- ${name}@${String(version$1)}`).join(" \n")}`);
633
+ await Promise.all([Promise.all(Object.entries(context.dependencies).map(async ([name, version$1]) => installPackage(context, `${(0, __stryke_string_format_package.getPackageName)(name)}@${String(version$1)}`, false))), Promise.all(Object.entries(context.devDependencies).map(async ([name, version$1]) => installPackage(context, `${(0, __stryke_string_format_package.getPackageName)(name)}@${String(version$1)}`, true)))]);
634
+ }
635
+
636
+ //#endregion
637
+ //#region ../powerlines/src/_internal/helpers/meta.ts
638
+ /**
639
+ * Generates a prefixed project root hash object.
640
+ *
641
+ * @remarks
642
+ * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.
643
+ *
644
+ * @param name - The name of the project.
645
+ * @param rootHash - The hash of the project root.
646
+ * @returns An object containing the name and project root hash.
647
+ */
648
+ function getPrefixedRootHash(name, rootHash) {
649
+ const combined = `${(0, __stryke_string_format_kebab_case.kebabCase)(name)}_${rootHash}`;
650
+ return combined.length > require_config.ROOT_HASH_LENGTH ? combined.slice(0, require_config.ROOT_HASH_LENGTH) : combined;
651
+ }
652
+ /**
653
+ * Writes the meta file for the context.
654
+ *
655
+ * @param context - The context to write the meta file for.
656
+ * @returns A promise that resolves when the meta file has been written.
657
+ */
658
+ async function writeMetaFile(context) {
659
+ const metaFilePath = (0, __stryke_path_join_paths.joinPaths)(context.dataPath, "meta.json");
660
+ context.debug(`Writing runtime metadata to ${metaFilePath}`);
661
+ await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));
662
+ }
663
+
664
+ //#endregion
665
+ //#region ../powerlines/src/typescript/tsconfig.ts
666
+ /**
667
+ * Get the path to the tsconfig.json file.
668
+ *
669
+ * @param workspaceRoot - The root directory of the workspace.
670
+ * @param projectRoot - The root directory of the project.
671
+ * @param tsconfig - The path to the tsconfig.json file.
672
+ * @returns The absolute path to the tsconfig.json file.
673
+ * @throws If the tsconfig.json file does not exist.
674
+ */
675
+ function getTsconfigFilePath(workspaceRoot, projectRoot, tsconfig) {
676
+ let tsconfigFilePath;
677
+ if (tsconfig) tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, tsconfig);
678
+ else {
679
+ tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.app.json");
680
+ if (!tsconfigFilePath) {
681
+ tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.lib.json");
682
+ if (!tsconfigFilePath) tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.json");
683
+ }
684
+ }
685
+ if (!tsconfigFilePath) throw new Error(`Cannot find the \`tsconfig.json\` configuration file for the project at ${projectRoot}.`);
686
+ return tsconfigFilePath;
687
+ }
688
+ /**
689
+ * Get the path to the tsconfig.json file.
690
+ *
691
+ * @param workspaceRoot - The root directory of the workspace.
692
+ * @param projectRoot - The root directory of the project.
693
+ * @param tsconfig - The path to the tsconfig.json file.
694
+ * @returns The absolute path to the tsconfig.json file.
695
+ * @throws If the tsconfig.json file does not exist.
696
+ */
697
+ function tryTsconfigFilePath(workspaceRoot, projectRoot, tsconfig) {
698
+ let tsconfigFilePath = tsconfig;
699
+ if (!(0, __stryke_fs_exists.existsSync)(tsconfigFilePath)) {
700
+ tsconfigFilePath = (0, __stryke_path_append.appendPath)(tsconfig, projectRoot);
701
+ if (!(0, __stryke_fs_exists.existsSync)(tsconfigFilePath)) {
702
+ tsconfigFilePath = (0, __stryke_path_append.appendPath)(tsconfig, (0, __stryke_path_append.appendPath)(projectRoot, workspaceRoot));
703
+ if (!(0, __stryke_fs_exists.existsSync)(tsconfigFilePath)) return;
704
+ }
705
+ }
706
+ return tsconfigFilePath;
707
+ }
708
+ /**
709
+ * Check if the TypeScript configuration type matches any of the provided types.
710
+ *
711
+ * @param tsconfigType - The type from the TypeScript configuration.
712
+ * @param types - An array of type names to check against.
713
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
714
+ */
715
+ function findMatch(tsconfigType, types, extensions = [
716
+ ".ts",
717
+ ".tsx",
718
+ ".d.ts"
719
+ ]) {
720
+ return types.find((type) => tsconfigType?.toString().toLowerCase() === type?.toString().toLowerCase() || tsconfigType?.toString().toLowerCase() === `./${type?.toString().toLowerCase()}` || `./${tsconfigType?.toString().toLowerCase()}` === type?.toString().toLowerCase() || extensions.some((ext) => `${tsconfigType?.toString().toLowerCase()}${ext}` === type?.toString().toLowerCase() || `${tsconfigType?.toString().toLowerCase()}${ext}` === `./${type?.toString().toLowerCase()}` || `${type?.toString().toLowerCase()}${ext}` === `./${tsconfigType?.toString().toLowerCase()}` || tsconfigType?.toString().toLowerCase() === `${type?.toString().toLowerCase()}${ext}` || tsconfigType?.toString().toLowerCase() === `./${type?.toString().toLowerCase()}${ext}` || type?.toString().toLowerCase() === `./${tsconfigType?.toString().toLowerCase()}${ext}`));
721
+ }
722
+ /**
723
+ * Check if the TypeScript configuration type matches any of the provided types.
724
+ *
725
+ * @param tsconfigType - The type from the TypeScript configuration.
726
+ * @param types - An array of type names to check against.
727
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
728
+ */
729
+ function findIncludeMatch(tsconfigType, types) {
730
+ return findMatch(tsconfigType, types, [
731
+ ".ts",
732
+ ".tsx",
733
+ ".d.ts",
734
+ ".js",
735
+ ".jsx",
736
+ ".mjs",
737
+ ".cjs",
738
+ ".mts",
739
+ ".cts",
740
+ "/*.ts",
741
+ "/*.tsx",
742
+ "/*.d.ts",
743
+ "/*.js",
744
+ "/*.jsx",
745
+ "/*.mjs",
746
+ "/*.cjs",
747
+ "/*.mts",
748
+ "/*.cts",
749
+ "/**/*.ts",
750
+ "/**/*.tsx",
751
+ "/**/*.d.ts",
752
+ "/**/*.js",
753
+ "/**/*.jsx",
754
+ "/**/*.mjs",
755
+ "/**/*.cjs",
756
+ "/**/*.mts",
757
+ "/**/*.cts"
758
+ ]);
759
+ }
760
+ /**
761
+ * Check if the TypeScript configuration type matches any of the provided types.
762
+ *
763
+ * @param tsconfigType - The type from the TypeScript configuration.
764
+ * @param types - An array of type names to check against.
765
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
766
+ */
767
+ function isIncludeMatchFound(tsconfigType, types) {
768
+ return findIncludeMatch(tsconfigType, types) !== void 0;
769
+ }
770
+ /**
771
+ * Get the parsed TypeScript configuration.
772
+ *
773
+ * @param workspaceRoot - The root directory of the workspace.
774
+ * @param projectRoot - The root directory of the project.
775
+ * @param tsconfig - The path to the tsconfig.json file.
776
+ * @param tsconfigRaw - The raw tsconfig.json content.
777
+ * @param originalTsconfigJson - The original tsconfig.json content.
778
+ * @param host - The TypeScript parse config host.
779
+ * @returns The resolved TypeScript configuration.
780
+ */
781
+ function getParsedTypeScriptConfig(workspaceRoot, projectRoot, tsconfig, tsconfigRaw = {}, originalTsconfigJson, host = typescript.default.sys) {
782
+ const tsconfigFilePath = getTsconfigFilePath(workspaceRoot, projectRoot, tsconfig);
783
+ const tsconfigJson = (0, __stryke_fs_json.readJsonFileSync)(tsconfigFilePath);
784
+ if (!tsconfigJson) throw new Error(`Cannot find the \`tsconfig.json\` configuration file at ${(0, __stryke_path_join_paths.joinPaths)(projectRoot, tsconfig ?? "tsconfig.json")}`);
785
+ const parsedCommandLine = typescript.default.parseJsonConfigFileContent((0, defu.default)(tsconfigRaw ?? {}, tsconfigJson), host, (0, __stryke_path_append.appendPath)(projectRoot, workspaceRoot));
786
+ if (parsedCommandLine.errors.length > 0) {
787
+ const errorMessage = `Cannot parse the TypeScript compiler options. Please investigate the following issues:
788
+ ${parsedCommandLine.errors.map((error) => `- ${(error.category !== void 0 && error.code ? `[${error.category}-${error.code}]: ` : "") + error.messageText.toString()}`).join("\n")}
789
+ `;
790
+ throw new Error(errorMessage);
791
+ }
792
+ return {
793
+ ...parsedCommandLine,
794
+ originalTsconfigJson: originalTsconfigJson ?? tsconfigJson,
795
+ tsconfigJson,
796
+ tsconfigFilePath
797
+ };
798
+ }
799
+
800
+ //#endregion
801
+ //#region ../powerlines/src/_internal/helpers/resolve-tsconfig.ts
802
+ function getTsconfigDtsPath(context) {
803
+ return (0, __stryke_path_join_paths.joinPaths)((0, __stryke_path_file_path_fns.relativePath)((0, __stryke_path_join_paths.joinPaths)(context.workspaceConfig.workspaceRoot, context.config.root), (0, __stryke_path_file_path_fns.findFilePath)(context.dtsPath)), (0, __stryke_path_file_path_fns.findFileName)(context.dtsPath));
804
+ }
805
+ async function resolveTsconfigChanges(context) {
806
+ const tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig, context.config.tsconfigRaw);
807
+ const tsconfigJson = await (0, __stryke_fs_json.readJsonFile)(getTsconfigFilePath(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig));
808
+ tsconfigJson.compilerOptions ??= {};
809
+ if (context.config.output.dts !== false) {
810
+ const dtsRelativePath = getTsconfigDtsPath(context);
811
+ if (!tsconfigJson.include?.some((filePattern) => isIncludeMatchFound(filePattern, [context.dtsPath, dtsRelativePath]))) {
812
+ tsconfigJson.include ??= [];
813
+ tsconfigJson.include.push(dtsRelativePath.startsWith("./") ? dtsRelativePath.slice(2) : dtsRelativePath);
814
+ }
815
+ }
816
+ if (!tsconfig.options.lib?.some((lib) => [
817
+ "lib.esnext.d.ts",
818
+ "lib.es2021.d.ts",
819
+ "lib.es2022.d.ts",
820
+ "lib.es2023.d.ts"
821
+ ].includes(lib.toLowerCase()))) {
822
+ tsconfigJson.compilerOptions.lib ??= [];
823
+ tsconfigJson.compilerOptions.lib.push("esnext");
824
+ }
825
+ if (tsconfig.options.esModuleInterop !== true) tsconfigJson.compilerOptions.esModuleInterop = true;
826
+ if (tsconfig.options.isolatedModules !== true) tsconfigJson.compilerOptions.isolatedModules = true;
827
+ if (context.config.platform === "node") {
828
+ if (!tsconfig.options.types?.some((type) => type.toLowerCase() === "node" || type.toLowerCase() === "@types/node")) {
829
+ tsconfigJson.compilerOptions.types ??= [];
830
+ tsconfigJson.compilerOptions.types.push("node");
831
+ }
832
+ }
833
+ return tsconfigJson;
834
+ }
835
+ async function initializeTsconfig(context) {
836
+ context.debug("Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.");
837
+ if (!(0, __stryke_fs_package_fns.isPackageExists)("typescript")) throw new Error("The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"");
838
+ const tsconfigFilePath = getTsconfigFilePath(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig);
839
+ context.tsconfig.originalTsconfigJson = await (0, __stryke_fs_json.readJsonFile)(tsconfigFilePath);
840
+ context.tsconfig.tsconfigJson = await resolveTsconfigChanges(context);
841
+ context.debug("Writing updated TypeScript configuration (tsconfig.json) file to disk.");
842
+ await context.fs.write(tsconfigFilePath, __stryke_json_storm_json.StormJSON.stringify(context.tsconfig.tsconfigJson));
843
+ context.tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig, context.config.tsconfigRaw, context.tsconfig.originalTsconfigJson);
844
+ }
845
+ async function resolveTsconfig(context) {
846
+ const updateTsconfigJson = await (0, __stryke_fs_json.readJsonFile)(context.tsconfig.tsconfigFilePath);
847
+ if (updateTsconfigJson?.compilerOptions?.types && Array.isArray(updateTsconfigJson.compilerOptions.types) && !updateTsconfigJson.compilerOptions.types.length) delete updateTsconfigJson.compilerOptions.types;
848
+ const result = (0, __donedeal0_superdiff.getObjectDiff)(context.tsconfig.originalTsconfigJson, updateTsconfigJson, {
849
+ ignoreArrayOrder: true,
850
+ showOnly: {
851
+ statuses: [
852
+ "added",
853
+ "deleted",
854
+ "updated"
855
+ ],
856
+ granularity: "deep"
857
+ }
858
+ });
859
+ const changes = [];
860
+ const getChanges = (difference, property) => {
861
+ if (difference.status === "added" || difference.status === "deleted" || difference.status === "updated") if (difference.diff) for (const diff of difference.diff) getChanges(diff, property ? `${property}.${difference.property}` : difference.property);
862
+ else changes.push({
863
+ field: property ? `${property}.${difference.property}` : difference.property,
864
+ status: difference.status,
865
+ previous: difference.status === "added" ? "---" : __stryke_json_storm_json.StormJSON.stringify(difference.previousValue),
866
+ current: difference.status === "deleted" ? "---" : __stryke_json_storm_json.StormJSON.stringify(difference.currentValue)
867
+ });
868
+ };
869
+ for (const diff of result.diff) getChanges(diff);
870
+ if (changes.length > 0) context.warn(`Updating the following configuration values in "${context.tsconfig.tsconfigFilePath}" file:
871
+
872
+ ${changes.map((change, i) => `${chalk.default.bold.whiteBright(`${i + 1}. ${(0, __stryke_string_format_title_case.titleCase)(change.status)} the ${change.field} field: `)}
873
+ ${chalk.default.red(` - Previous: ${change.previous} `)}
874
+ ${chalk.default.green(` - Updated: ${change.current} `)}
875
+ `).join("\n")}
876
+ `);
877
+ await context.fs.write(context.tsconfig.tsconfigFilePath, __stryke_json_storm_json.StormJSON.stringify(updateTsconfigJson));
878
+ context.tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig);
879
+ if (!context.tsconfig) throw new Error("Failed to parse the TypeScript configuration file.");
880
+ }
881
+
882
+ //#endregion
883
+ //#region ../powerlines/src/_internal/helpers/environment.ts
884
+ function createEnvironment(name, userConfig) {
885
+ return (0, defu.default)(userConfig.environments?.[name] ?? {}, {
886
+ name,
887
+ title: userConfig.title || (0, __stryke_string_format_title_case.titleCase)(userConfig.name),
888
+ ssr: false,
889
+ mainFields: userConfig?.platform === "browser" ? [
890
+ "browser",
891
+ "module",
892
+ "jsnext:main",
893
+ "jsnext"
894
+ ] : [
895
+ "module",
896
+ "jsnext:main",
897
+ "jsnext"
898
+ ],
899
+ extensions: [
900
+ ".mjs",
901
+ ".js",
902
+ ".mts",
903
+ ".ts",
904
+ ".jsx",
905
+ ".tsx",
906
+ ".json"
907
+ ],
908
+ consumer: userConfig?.platform === "browser" ? "client" : "server",
909
+ preview: userConfig?.platform === "browser" ? {
910
+ port: 5173,
911
+ open: true,
912
+ strictPort: false,
913
+ host: "localhost",
914
+ allowedHosts: ["."],
915
+ cors: true,
916
+ headers: {}
917
+ } : void 0
918
+ }, userConfig);
919
+ }
920
+ function createDefaultEnvironment(userConfig) {
921
+ return createEnvironment(require_config.DEFAULT_ENVIRONMENT, userConfig);
922
+ }
923
+
924
+ //#endregion
925
+ //#region ../powerlines/src/_internal/helpers/resolver.ts
926
+ /**
927
+ * Create a Jiti resolver for the given workspace and project root.
928
+ *
929
+ * @param options - The options for creating the resolver.
930
+ * @returns A Jiti instance configured for the specified workspace and project root.
931
+ */
932
+ function resolveOptions(options) {
933
+ return (0, defu.default)(options, {
934
+ interopDefault: true,
935
+ fsCache: options.mode !== "development" ? (0, __stryke_path_join_paths.joinPaths)(options.cacheDir, "jiti") : false,
936
+ moduleCache: options.mode !== "development"
937
+ });
938
+ }
939
+ /**
940
+ * Create a Jiti resolver for the given workspace and project root.
941
+ *
942
+ * @param options - The options for creating the resolver.
943
+ * @returns A Jiti instance configured for the specified workspace and project root.
944
+ */
945
+ function createResolver(options) {
946
+ const baseResolver = (0, jiti.createJiti)((0, __stryke_path_join_paths.joinPaths)(options.workspaceRoot, options.root), resolveOptions(options));
947
+ baseResolver.plugin = (0, jiti.createJiti)((0, __stryke_path_join_paths.joinPaths)(options.workspaceRoot, options.root), resolveOptions(options));
948
+ return baseResolver;
949
+ }
950
+
951
+ //#endregion
952
+ //#region ../powerlines/schemas/fs.ts
953
+ var FileMetadata_KeyValuePair = class extends __stryke_capnp.Struct {
954
+ static _capnp = {
955
+ displayName: "KeyValuePair",
956
+ id: "eabb26cf58b2a14c",
957
+ size: new __stryke_capnp.ObjectSize(0, 2)
958
+ };
959
+ get key() {
960
+ return __stryke_capnp.utils.getText(0, this);
961
+ }
962
+ set key(value) {
963
+ __stryke_capnp.utils.setText(0, value, this);
964
+ }
965
+ get value() {
966
+ return __stryke_capnp.utils.getText(1, this);
967
+ }
968
+ set value(value) {
969
+ __stryke_capnp.utils.setText(1, value, this);
970
+ }
971
+ toString() {
972
+ return "FileMetadata_KeyValuePair_" + super.toString();
973
+ }
974
+ };
975
+ /**
976
+ * The identifier for the file data.
977
+ *
978
+ */
979
+ var FileMetadata = class FileMetadata extends __stryke_capnp.Struct {
980
+ static KeyValuePair = FileMetadata_KeyValuePair;
981
+ static _capnp = {
982
+ displayName: "FileMetadata",
983
+ id: "8e2cab5d7e28c7b3",
984
+ size: new __stryke_capnp.ObjectSize(8, 3),
985
+ defaultType: "normal"
986
+ };
987
+ static _Properties;
988
+ /**
989
+ * The type of the file.
990
+ *
991
+ */
992
+ get id() {
993
+ return __stryke_capnp.utils.getText(0, this);
994
+ }
995
+ set id(value) {
996
+ __stryke_capnp.utils.setText(0, value, this);
997
+ }
998
+ /**
999
+ * The timestamp representing the file's creation date.
1000
+ *
1001
+ */
1002
+ get type() {
1003
+ return __stryke_capnp.utils.getText(1, this, FileMetadata._capnp.defaultType);
1004
+ }
1005
+ set type(value) {
1006
+ __stryke_capnp.utils.setText(1, value, this);
1007
+ }
1008
+ /**
1009
+ * Additional metadata associated with the file.
1010
+ *
1011
+ */
1012
+ get timestamp() {
1013
+ return __stryke_capnp.utils.getUint32(0, this);
1014
+ }
1015
+ set timestamp(value) {
1016
+ __stryke_capnp.utils.setUint32(0, value, this);
1017
+ }
1018
+ _adoptProperties(value) {
1019
+ __stryke_capnp.utils.adopt(value, __stryke_capnp.utils.getPointer(2, this));
1020
+ }
1021
+ _disownProperties() {
1022
+ return __stryke_capnp.utils.disown(this.properties);
1023
+ }
1024
+ get properties() {
1025
+ return __stryke_capnp.utils.getList(2, FileMetadata._Properties, this);
1026
+ }
1027
+ _hasProperties() {
1028
+ return !__stryke_capnp.utils.isNull(__stryke_capnp.utils.getPointer(2, this));
1029
+ }
1030
+ _initProperties(length) {
1031
+ return __stryke_capnp.utils.initList(2, FileMetadata._Properties, length, this);
1032
+ }
1033
+ set properties(value) {
1034
+ __stryke_capnp.utils.copyFrom(value, __stryke_capnp.utils.getPointer(2, this));
1035
+ }
1036
+ toString() {
1037
+ return "FileMetadata_" + super.toString();
1038
+ }
1039
+ };
1040
+ /**
1041
+ * An identifier for the file.
1042
+ *
1043
+ */
1044
+ var FileId = class extends __stryke_capnp.Struct {
1045
+ static _capnp = {
1046
+ displayName: "FileId",
1047
+ id: "990d6a471072f997",
1048
+ size: new __stryke_capnp.ObjectSize(0, 2)
1049
+ };
1050
+ /**
1051
+ * A virtual (or actual) path to the file in the file system.
1052
+ *
1053
+ */
1054
+ get id() {
1055
+ return __stryke_capnp.utils.getText(0, this);
1056
+ }
1057
+ set id(value) {
1058
+ __stryke_capnp.utils.setText(0, value, this);
1059
+ }
1060
+ get path() {
1061
+ return __stryke_capnp.utils.getText(1, this);
1062
+ }
1063
+ set path(value) {
1064
+ __stryke_capnp.utils.setText(1, value, this);
1065
+ }
1066
+ toString() {
1067
+ return "FileId_" + super.toString();
1068
+ }
1069
+ };
1070
+ /**
1071
+ * An identifier for the file.
1072
+ *
1073
+ */
1074
+ var FileStorage = class extends __stryke_capnp.Struct {
1075
+ static _capnp = {
1076
+ displayName: "FileStorage",
1077
+ id: "9dca66ac858c9ebe",
1078
+ size: new __stryke_capnp.ObjectSize(0, 2)
1079
+ };
1080
+ /**
1081
+ * A virtual (or actual) path to the file in the file system.
1082
+ *
1083
+ */
1084
+ get path() {
1085
+ return __stryke_capnp.utils.getText(0, this);
1086
+ }
1087
+ set path(value) {
1088
+ __stryke_capnp.utils.setText(0, value, this);
1089
+ }
1090
+ get code() {
1091
+ return __stryke_capnp.utils.getText(1, this);
1092
+ }
1093
+ set code(value) {
1094
+ __stryke_capnp.utils.setText(1, value, this);
1095
+ }
1096
+ toString() {
1097
+ return "FileStorage_" + super.toString();
1098
+ }
1099
+ };
1100
+ var FileSystem = class FileSystem extends __stryke_capnp.Struct {
1101
+ static _capnp = {
1102
+ displayName: "FileSystem",
1103
+ id: "ae0c23d43e56abcf",
1104
+ size: new __stryke_capnp.ObjectSize(0, 3)
1105
+ };
1106
+ static _Ids;
1107
+ static _Storage;
1108
+ static _Metadata;
1109
+ _adoptIds(value) {
1110
+ __stryke_capnp.utils.adopt(value, __stryke_capnp.utils.getPointer(0, this));
1111
+ }
1112
+ _disownIds() {
1113
+ return __stryke_capnp.utils.disown(this.ids);
1114
+ }
1115
+ get ids() {
1116
+ return __stryke_capnp.utils.getList(0, FileSystem._Ids, this);
1117
+ }
1118
+ _hasIds() {
1119
+ return !__stryke_capnp.utils.isNull(__stryke_capnp.utils.getPointer(0, this));
1120
+ }
1121
+ _initIds(length) {
1122
+ return __stryke_capnp.utils.initList(0, FileSystem._Ids, length, this);
1123
+ }
1124
+ set ids(value) {
1125
+ __stryke_capnp.utils.copyFrom(value, __stryke_capnp.utils.getPointer(0, this));
1126
+ }
1127
+ _adoptStorage(value) {
1128
+ __stryke_capnp.utils.adopt(value, __stryke_capnp.utils.getPointer(1, this));
1129
+ }
1130
+ _disownStorage() {
1131
+ return __stryke_capnp.utils.disown(this.storage);
1132
+ }
1133
+ get storage() {
1134
+ return __stryke_capnp.utils.getList(1, FileSystem._Storage, this);
1135
+ }
1136
+ _hasStorage() {
1137
+ return !__stryke_capnp.utils.isNull(__stryke_capnp.utils.getPointer(1, this));
1138
+ }
1139
+ _initStorage(length) {
1140
+ return __stryke_capnp.utils.initList(1, FileSystem._Storage, length, this);
1141
+ }
1142
+ set storage(value) {
1143
+ __stryke_capnp.utils.copyFrom(value, __stryke_capnp.utils.getPointer(1, this));
1144
+ }
1145
+ _adoptMetadata(value) {
1146
+ __stryke_capnp.utils.adopt(value, __stryke_capnp.utils.getPointer(2, this));
1147
+ }
1148
+ _disownMetadata() {
1149
+ return __stryke_capnp.utils.disown(this.metadata);
1150
+ }
1151
+ get metadata() {
1152
+ return __stryke_capnp.utils.getList(2, FileSystem._Metadata, this);
1153
+ }
1154
+ _hasMetadata() {
1155
+ return !__stryke_capnp.utils.isNull(__stryke_capnp.utils.getPointer(2, this));
1156
+ }
1157
+ _initMetadata(length) {
1158
+ return __stryke_capnp.utils.initList(2, FileSystem._Metadata, length, this);
1159
+ }
1160
+ set metadata(value) {
1161
+ __stryke_capnp.utils.copyFrom(value, __stryke_capnp.utils.getPointer(2, this));
1162
+ }
1163
+ toString() {
1164
+ return "FileSystem_" + super.toString();
1165
+ }
1166
+ };
1167
+ FileMetadata._Properties = __stryke_capnp.CompositeList(FileMetadata_KeyValuePair);
1168
+ FileSystem._Ids = __stryke_capnp.CompositeList(FileId);
1169
+ FileSystem._Storage = __stryke_capnp.CompositeList(FileStorage);
1170
+ FileSystem._Metadata = __stryke_capnp.CompositeList(FileMetadata);
1171
+
1172
+ //#endregion
1173
+ //#region ../powerlines/src/storage/base.ts
1174
+ /**
1175
+ * Abstract base class for storage adapters, providing a template for storage operations.
1176
+ */
1177
+ var BaseStorageAdapter = class {
1178
+ /**
1179
+ * Indicates whether the storage adapter has been disposed.
1180
+ */
1181
+ #isDisposed = false;
1182
+ /**
1183
+ * Configuration options for the storage adapter.
1184
+ */
1185
+ options;
1186
+ /**
1187
+ * The storage preset for the adapter.
1188
+ *
1189
+ * @remarks
1190
+ * This can be used as an alternate way to identify the type of storage being used.
1191
+ */
1192
+ preset = null;
1193
+ /**
1194
+ * Constructor for the BaseStorageAdapter.
1195
+ *
1196
+ * @param context - The Powerlines context.
1197
+ * @param options - Configuration options for the storage adapter.
1198
+ */
1199
+ constructor(context, options = { base: "/" }) {
1200
+ this.context = context;
1201
+ this.options = options;
1202
+ this.options.base = (0, node_path.resolve)(options.base);
1203
+ this.options.isReadOnly = !!options.isReadOnly;
1204
+ }
1205
+ /**
1206
+ * Asynchronously checks if a key exists in the storage.
1207
+ *
1208
+ * @param key - The key to check for existence.
1209
+ * @returns A promise that resolves to `true` if the key exists, otherwise `false`.
1210
+ */
1211
+ async exists(key) {
1212
+ return this.existsSync(key);
1213
+ }
1214
+ /**
1215
+ * Asynchronously retrieves the value associated with a given key.
1216
+ *
1217
+ * @param key - The key whose value is to be retrieved.
1218
+ * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.
1219
+ */
1220
+ async get(key) {
1221
+ return this.getSync(key);
1222
+ }
1223
+ /**
1224
+ * Asynchronously sets the value for a given key.
1225
+ *
1226
+ * @param key - The key to set the value for.
1227
+ * @param value - The value to set.
1228
+ */
1229
+ async set(key, value) {
1230
+ if (!this.isReadOnly && (!this.existsSync(key) || this.overwrite)) this.setSync(key, value);
1231
+ }
1232
+ /**
1233
+ * Synchronously creates a directory at the specified path.
1234
+ *
1235
+ * @param _ - The path of the directory to create.
1236
+ */
1237
+ mkdirSync(_) {}
1238
+ /**
1239
+ * Creates a directory at the specified path.
1240
+ *
1241
+ * @param dirPath - The path of the directory to create.
1242
+ */
1243
+ async mkdir(dirPath) {
1244
+ return Promise.resolve(this.mkdirSync(dirPath));
1245
+ }
1246
+ /**
1247
+ * Asynchronously removes a key from the storage.
1248
+ *
1249
+ * @param key - The key to remove.
1250
+ */
1251
+ async remove(key) {
1252
+ if (!this.isReadOnly && this.overwrite) this.removeSync(key);
1253
+ }
1254
+ /**
1255
+ * Synchronously removes all entries from the storage that match the provided base path.
1256
+ *
1257
+ * @param base - The base path to clear keys from.
1258
+ */
1259
+ clearSync(base) {
1260
+ if (!this.isReadOnly && this.overwrite) {
1261
+ const keys = this.listSync(base || this.options.base);
1262
+ if (!keys.length) return;
1263
+ keys.map((key) => this.removeSync(base && !key.startsWith(base) ? (0, __stryke_path_join.joinPaths)(base, key) : key));
1264
+ }
1265
+ }
1266
+ /**
1267
+ * Asynchronously removes all entries from the storage that match the provided base path.
1268
+ *
1269
+ * @param base - The base path to clear keys from.
1270
+ * @returns A promise that resolves when the operation is complete.
1271
+ */
1272
+ async clear(base) {
1273
+ if (!this.isReadOnly && this.overwrite) {
1274
+ const keys = await this.list(base || this.options.base);
1275
+ if (!keys.length) return;
1276
+ await Promise.all(keys.map(async (key) => this.remove(base && !key.startsWith(base) ? (0, __stryke_path_join.joinPaths)(base, key) : key)));
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Asynchronously lists all keys under a given base path.
1281
+ *
1282
+ * @param base - The base path to list keys from.
1283
+ * @returns A promise that resolves to an array of keys under the specified base path.
1284
+ */
1285
+ async list(base) {
1286
+ return this.listSync(base);
1287
+ }
1288
+ /**
1289
+ * Synchronously checks if the given key is a directory.
1290
+ *
1291
+ * @param _ - The key to check.
1292
+ * @returns `true` if the key is a directory, otherwise `false`.
1293
+ */
1294
+ isDirectorySync(_) {
1295
+ return false;
1296
+ }
1297
+ /**
1298
+ * Checks if the given key is a directory.
1299
+ *
1300
+ * @param key - The key to check.
1301
+ * @returns A promise that resolves to `true` if the key is a directory, otherwise `false`.
1302
+ */
1303
+ async isDirectory(key) {
1304
+ return Promise.resolve(this.isDirectorySync(key));
1305
+ }
1306
+ /**
1307
+ * Synchronously checks if the given key is a file.
1308
+ *
1309
+ * @param key - The key to check.
1310
+ * @returns `true` if the key is a file, otherwise `false`.
1311
+ */
1312
+ isFileSync(key) {
1313
+ return this.existsSync(key) && !this.isDirectorySync(key);
1314
+ }
1315
+ /**
1316
+ * Checks if the given key is a file.
1317
+ *
1318
+ * @param key - The key to check.
1319
+ * @returns A promise that resolves to `true` if the key is a file, otherwise `false`.
1320
+ */
1321
+ async isFile(key) {
1322
+ return Promise.resolve(this.isFileSync(key));
1323
+ }
1324
+ /**
1325
+ * Disposes of the storage adapter, releasing any held resources.
1326
+ *
1327
+ * @returns A promise that resolves when the disposal is complete.
1328
+ */
1329
+ dispose() {
1330
+ return Promise.resolve();
1331
+ }
1332
+ /**
1333
+ * Async dispose method to clean up resources.
1334
+ *
1335
+ * @returns A promise that resolves when disposal is complete.
1336
+ */
1337
+ async [Symbol.asyncDispose]() {
1338
+ return this._dispose();
1339
+ }
1340
+ /**
1341
+ * Determines if the storage adapter is read-only based on the provided options.
1342
+ *
1343
+ * @returns `true` if the storage adapter is read-only, otherwise `false`.
1344
+ */
1345
+ get isReadOnly() {
1346
+ return !!this.options.isReadOnly;
1347
+ }
1348
+ /**
1349
+ * Determines if the storage adapter should overwrite existing keys based on the provided options and context configuration.
1350
+ *
1351
+ * @returns `true` if the storage adapter should overwrite existing keys, otherwise `false`.
1352
+ */
1353
+ get overwrite() {
1354
+ return !this.isReadOnly && this.context.config.output.overwrite !== false;
1355
+ }
1356
+ /**
1357
+ * Resolves a given key to its full path within the storage adapter.
1358
+ *
1359
+ * @param key - The key to resolve.
1360
+ * @returns The resolved full path for the key.
1361
+ */
1362
+ resolve(key) {
1363
+ if (!key) return this.options.base;
1364
+ if (/\.\.:|\.\.$/.test(key)) throw new Error(`[${this.name}]: Invalid key: ${JSON.stringify(key)} provided to storage adapter.`);
1365
+ return (0, __stryke_path_append.appendPath)((0, __stryke_path_correct_path.correctPath)(key).replace(/:/g, "/"), this.options.base);
1366
+ }
1367
+ /**
1368
+ * Disposes of the storage adapter, releasing any held resources.
1369
+ *
1370
+ * @returns A promise that resolves when the disposal is complete.
1371
+ */
1372
+ async _dispose() {
1373
+ if (!this.#isDisposed) {
1374
+ await Promise.resolve(this.dispose());
1375
+ this.#isDisposed = true;
1376
+ }
1377
+ }
1378
+ };
1379
+
1380
+ //#endregion
1381
+ //#region ../powerlines/src/storage/helpers.ts
1382
+ /**
1383
+ * Checks if an error is a file system error.
1384
+ *
1385
+ * @param err - The error to check.
1386
+ * @returns `true` if the error is a file system error, otherwise `false`.
1387
+ */
1388
+ function isFileError(err) {
1389
+ return (0, __stryke_type_checks_is_error.isError)(err) && "code" in err && err.code;
1390
+ }
1391
+ /**
1392
+ * Ignores file not found errors.
1393
+ *
1394
+ * @param err - The error to check.
1395
+ * @returns `null` if the error is a file not found error, otherwise returns the error.
1396
+ */
1397
+ function ignoreNotfound(err) {
1398
+ return isFileError(err) && (err.code === "ENOENT" || err.code === "EISDIR" ? null : err);
1399
+ }
1400
+
1401
+ //#endregion
1402
+ //#region ../powerlines/src/storage/file-system.ts
1403
+ /**
1404
+ * File system storage adapter implementation.
1405
+ */
1406
+ var FileSystemStorageAdapter = class extends BaseStorageAdapter {
1407
+ /**
1408
+ * A name identifying the storage adapter type.
1409
+ */
1410
+ name = "file-system";
1411
+ /**
1412
+ * The storage preset for the adapter.
1413
+ *
1414
+ * @remarks
1415
+ * This can be used as an alternate way to identify the type of storage being used.
1416
+ */
1417
+ preset = "fs";
1418
+ /**
1419
+ * Constructor for the FileSystemStorageAdapter.
1420
+ *
1421
+ * @param context - The Powerlines context.
1422
+ * @param options - Configuration options for the storage adapter.
1423
+ */
1424
+ constructor(context, options) {
1425
+ super(context, options);
1426
+ }
1427
+ /**
1428
+ * Synchronously checks if a key exists in the storage.
1429
+ *
1430
+ * @param key - The key to check for existence.
1431
+ * @returns Returns `true` if the key exists, otherwise `false`.
1432
+ */
1433
+ existsSync(key) {
1434
+ return (0, __stryke_fs_exists.existsSync)(this.resolve(key));
1435
+ }
1436
+ /**
1437
+ * Asynchronously checks if a key exists in the storage.
1438
+ *
1439
+ * @param key - The key to check for existence.
1440
+ * @returns A promise that resolves to `true` if the key exists, otherwise `false`.
1441
+ */
1442
+ async exists(key) {
1443
+ return (0, __stryke_fs_exists.exists)(this.resolve(key));
1444
+ }
1445
+ /**
1446
+ * Synchronously retrieves the value associated with a given key.
1447
+ *
1448
+ * @param key - The key whose value is to be retrieved.
1449
+ * @returns The value associated with the key, or `null` if the key does not exist.
1450
+ */
1451
+ getSync(key) {
1452
+ return (0, __stryke_fs_read_file.readFileSync)(this.resolve(key));
1453
+ }
1454
+ /**
1455
+ * Asynchronously retrieves the value associated with a given key.
1456
+ *
1457
+ * @param key - The key whose value is to be retrieved.
1458
+ * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.
1459
+ */
1460
+ async get(key) {
1461
+ return (0, __stryke_fs_read_file.readFile)(this.resolve(key));
1462
+ }
1463
+ /**
1464
+ * Synchronously sets the value for a given key.
1465
+ *
1466
+ * @param key - The key to set the value for.
1467
+ * @param value - The value to set.
1468
+ */
1469
+ setSync(key, value) {
1470
+ if (!this.isReadOnly && (!this.existsSync(key) || this.overwrite)) return (0, __stryke_fs_write_file.writeFileSync)(this.resolve(key), value);
1471
+ }
1472
+ /**
1473
+ * Asynchronously sets the value for a given key.
1474
+ *
1475
+ * @param key - The key to set the value for.
1476
+ * @param value - The value to set.
1477
+ */
1478
+ async set(key, value) {
1479
+ if (!this.isReadOnly && this.overwrite) return (0, __stryke_fs_write_file.writeFile)(this.resolve(key), value);
1480
+ }
1481
+ /**
1482
+ * Synchronously removes a key from the storage.
1483
+ *
1484
+ * @param key - The key to remove.
1485
+ */
1486
+ removeSync(key) {
1487
+ if (!this.isReadOnly && this.overwrite) try {
1488
+ return (0, node_fs.unlinkSync)(this.resolve(key));
1489
+ } catch (err) {
1490
+ return ignoreNotfound(err);
1491
+ }
1492
+ }
1493
+ /**
1494
+ * Asynchronously removes a key from the storage.
1495
+ *
1496
+ * @param key - The key to remove.
1497
+ */
1498
+ async remove(key) {
1499
+ if (!this.isReadOnly && this.overwrite) return (0, node_fs_promises.unlink)(this.resolve(key)).catch(ignoreNotfound);
1500
+ }
1501
+ /**
1502
+ * Synchronously creates a directory at the specified path.
1503
+ *
1504
+ * @param dirPath - The path of the directory to create.
1505
+ */
1506
+ mkdirSync(dirPath) {
1507
+ (0, __stryke_fs_helpers.createDirectorySync)(this.resolve(dirPath));
1508
+ }
1509
+ /**
1510
+ * Creates a directory at the specified path.
1511
+ *
1512
+ * @param dirPath - The path of the directory to create.
1513
+ */
1514
+ async mkdir(dirPath) {
1515
+ await (0, __stryke_fs_helpers.createDirectory)(this.resolve(dirPath));
1516
+ }
1517
+ /**
1518
+ * Lists all keys under a given base path synchronously.
1519
+ *
1520
+ * @param base - The base path to list keys from.
1521
+ * @returns An array of keys under the specified base path.
1522
+ */
1523
+ listSync(base) {
1524
+ try {
1525
+ return (0, __stryke_fs_list_files.listFilesSync)(this.resolve(base), { ignore: this.options.ignore });
1526
+ } catch (err) {
1527
+ return ignoreNotfound(err) ?? [];
1528
+ }
1529
+ }
1530
+ /**
1531
+ * Asynchronously lists all keys under a given base path.
1532
+ *
1533
+ * @param base - The base path to list keys from.
1534
+ * @returns A promise that resolves to an array of keys under the specified base path.
1535
+ */
1536
+ async list(base) {
1537
+ return (0, __stryke_fs_list_files.listFiles)(this.resolve(base), { ignore: this.options.ignore }).catch(ignoreNotfound).then((r) => r || []);
1538
+ }
1539
+ /**
1540
+ * Synchronously checks if the given key is a directory.
1541
+ *
1542
+ * @param key - The key to check.
1543
+ * @returns `true` if the key is a directory, otherwise `false`.
1544
+ */
1545
+ isDirectorySync(key) {
1546
+ return (0, __stryke_fs_is_file.isDirectory)(this.resolve(key));
1547
+ }
1548
+ /**
1549
+ * Synchronously checks if the given key is a file.
1550
+ *
1551
+ * @param key - The key to check.
1552
+ * @returns `true` if the key is a file, otherwise `false`.
1553
+ */
1554
+ isFileSync(key) {
1555
+ return (0, __stryke_fs_is_file.isFile)(this.resolve(key));
1556
+ }
1557
+ };
1558
+
1559
+ //#endregion
1560
+ //#region ../powerlines/src/storage/virtual.ts
1561
+ /**
1562
+ * Virtual/in-memory storage adapter implementation.
1563
+ */
1564
+ var VirtualStorageAdapter = class extends BaseStorageAdapter {
1565
+ /**
1566
+ * A name identifying the storage adapter type.
1567
+ */
1568
+ name = "virtual";
1569
+ /**
1570
+ * The storage preset for the adapter.
1571
+ *
1572
+ * @remarks
1573
+ * This can be used as an alternate way to identify the type of storage being used.
1574
+ */
1575
+ preset = "virtual";
1576
+ /**
1577
+ * In-memory data storage.
1578
+ */
1579
+ data = /* @__PURE__ */ new Map();
1580
+ /**
1581
+ * Constructor for the VirtualStorageAdapter.
1582
+ *
1583
+ * @param context - The Powerlines context.
1584
+ * @param options - Configuration options for the storage adapter.
1585
+ */
1586
+ constructor(context, options) {
1587
+ super(context, options);
1588
+ }
1589
+ /**
1590
+ * Synchronously checks if a key exists in the storage.
1591
+ *
1592
+ * @param key - The key to check for existence.
1593
+ * @returns Returns `true` if the key exists, otherwise `false`.
1594
+ */
1595
+ existsSync(key) {
1596
+ return this.data.has(this.resolve(key));
1597
+ }
1598
+ /**
1599
+ * Synchronously retrieves the value associated with a given key.
1600
+ *
1601
+ * @param key - The key whose value is to be retrieved.
1602
+ * @returns The value associated with the key, or `null` if the key does not exist.
1603
+ */
1604
+ getSync(key) {
1605
+ return this.data.get(this.resolve(key)) ?? null;
1606
+ }
1607
+ /**
1608
+ * Synchronously sets the value for a given key.
1609
+ *
1610
+ * @param key - The key to set the value for.
1611
+ * @param value - The value to set.
1612
+ */
1613
+ setSync(key, value) {
1614
+ if (!this.isReadOnly && (!this.existsSync(key) || this.overwrite)) this.data.set(this.resolve(key), value);
1615
+ }
1616
+ /**
1617
+ * Synchronously removes a key from the storage.
1618
+ *
1619
+ * @param key - The key to remove.
1620
+ */
1621
+ removeSync(key) {
1622
+ if (!this.isReadOnly && this.overwrite) this.data.delete(this.resolve(key));
1623
+ }
1624
+ /**
1625
+ * Lists all keys under a given base path synchronously.
1626
+ *
1627
+ * @param base - The base path to list keys from.
1628
+ * @returns An array of keys under the specified base path.
1629
+ */
1630
+ listSync(base) {
1631
+ return [...this.data.keys().filter((key) => !base ? true : (0, __stryke_path_is_parent_path.isParentPath)(key, this.resolve(base)))];
1632
+ }
1633
+ /**
1634
+ * Disposes of the storage adapter, releasing any held resources.
1635
+ *
1636
+ * @returns A promise that resolves when the disposal is complete.
1637
+ */
1638
+ async dispose() {
1639
+ return this.clear();
1640
+ }
1641
+ /**
1642
+ * Determines if the storage adapter should overwrite existing keys based on the provided options and context configuration.
1643
+ *
1644
+ * @returns `true` if the storage adapter should overwrite existing keys, otherwise `false`.
1645
+ */
1646
+ get overwrite() {
1647
+ return !this.isReadOnly;
1648
+ }
1649
+ };
1650
+
1651
+ //#endregion
1652
+ //#region ../core/src/lib/entry.ts
1653
+ function resolveEntryOutput(context, typeDefinition) {
1654
+ return (0, __stryke_path_replace.replaceExtension)((0, __stryke_path_replace.replacePath)((0, __stryke_path_replace.replacePath)((0, __stryke_path_replace.replacePath)((0, __stryke_path_replace.replacePath)((0, __stryke_path_replace.replacePath)(typeDefinition.file, (0, __stryke_path_join_paths.joinPaths)(context.workspaceConfig.workspaceRoot, context.config.root, "src")), (0, __stryke_path_join_paths.joinPaths)(context.workspaceConfig.workspaceRoot, context.config.root)), (0, __stryke_path_join_paths.joinPaths)(context.config.root, "src")), context.config.root), "src"));
1655
+ }
1656
+ function resolveInput(context, typeDefinition, input, output) {
1657
+ return {
1658
+ ...typeDefinition,
1659
+ input: (0, __stryke_type_checks_is_set_string.isSetString)(input) ? { file: String(input) } : typeDefinition,
1660
+ output: output || resolveEntryOutput(context, typeDefinition)
1661
+ };
1662
+ }
1663
+ /**
1664
+ * Resolves multiple type definitions into their corresponding resolved entry type definitions.
1665
+ *
1666
+ * @param context - The current context
1667
+ * @param typeDefinitions - The type definitions to resolve.
1668
+ * @returns A promise that resolves to an array of resolved entry type definitions.
1669
+ */
1670
+ function resolveInputsSync(context, typeDefinitions) {
1671
+ return ((0, __stryke_type_checks_is_object.isObject)(typeDefinitions) && !isTypeDefinition(typeDefinitions) ? Object.values(typeDefinitions).flat() : (0, __stryke_convert_to_array.toArray)(typeDefinitions)).map((entry) => {
1672
+ if (isResolvedEntryTypeDefinition(entry)) return {
1673
+ ...entry,
1674
+ output: entry.output ? replacePathTokens(context, entry.output) : void 0,
1675
+ file: replacePathTokens(context, entry.file)
1676
+ };
1677
+ let typeDefinition;
1678
+ if ((0, __stryke_type_checks_is_string.isString)(entry)) typeDefinition = (0, __stryke_convert_parse_type_definition.parseTypeDefinition)(replacePathTokens(context, entry));
1679
+ else {
1680
+ typeDefinition = entry;
1681
+ typeDefinition.file = replacePathTokens(context, typeDefinition.file);
1682
+ }
1683
+ const filePath = (0, __stryke_path_is_type.isAbsolutePath)(typeDefinition.file) ? typeDefinition.file : (0, __stryke_path_append.appendPath)(typeDefinition.file, context.config.root);
1684
+ if (context.fs.isFileSync(filePath)) return resolveInput(context, {
1685
+ file: (0, __stryke_path_append.appendPath)(filePath, context.workspaceConfig.workspaceRoot),
1686
+ name: typeDefinition.name
1687
+ });
1688
+ return context.fs.globSync((0, __stryke_path_append.appendPath)(filePath, context.workspaceConfig.workspaceRoot)).map((file) => resolveInput(context, {
1689
+ file,
1690
+ name: typeDefinition.name
1691
+ }));
1692
+ }).flat().filter(Boolean);
1693
+ }
1694
+ /**
1695
+ * Checks if the provided entry is a type definition.
1696
+ *
1697
+ * @param entry - The entry to check.
1698
+ * @returns True if the entry is a type definition, false otherwise.
1699
+ */
1700
+ function isTypeDefinition(entry) {
1701
+ return !(0, __stryke_type_checks_is_string.isString)(entry) && entry.file !== void 0;
1702
+ }
1703
+ /**
1704
+ * Checks if the provided entry is a resolved entry type definition.
1705
+ *
1706
+ * @param entry - The entry to check.
1707
+ * @returns True if the entry is a resolved entry type definition, false otherwise.
1708
+ */
1709
+ function isResolvedEntryTypeDefinition(entry) {
1710
+ return isTypeDefinition(entry) && entry.output !== void 0;
1711
+ }
1712
+ /**
1713
+ * Get unique inputs from the provided list.
1714
+ *
1715
+ * @param inputs - The entry points to process.
1716
+ * @returns An array of unique inputs (by file path or content hash).
1717
+ */
1718
+ function getUniqueInputs(inputs = []) {
1719
+ return (0, __stryke_type_checks_is_object.isObject)(inputs) ? inputs : (0, __stryke_helpers_get_unique.getUniqueBy)((0, __stryke_convert_to_array.toArray)(inputs), (item) => (0, __stryke_type_checks_is_set_string.isSetString)(item) ? item : (0, __stryke_hash.murmurhash)(item ?? {}, { maxLength: 24 }));
1720
+ }
1721
+
1722
+ //#endregion
1723
+ //#region ../core/src/lib/logger.ts
1724
+ /**
1725
+ * Create a logging function with a specific name and options.
1726
+ *
1727
+ * @param name - The name of the logging function.
1728
+ * @param options - The options to configure the logging function.
1729
+ * @returns A logging function.
1730
+ */
1731
+ const createLog = (name, options = {}) => {
1732
+ const logLevel = options.logLevel === null ? __storm_software_config_tools_types.LogLevelLabel.SILENT : options.logLevel || __storm_software_config_tools_types.LogLevelLabel.INFO;
1733
+ if (logLevel === __storm_software_config_tools_types.LogLevelLabel.SILENT) return __stryke_helpers_noop.noop;
1734
+ if (options.customLogger) return options.customLogger;
1735
+ return (type, ...args) => (0, __storm_software_config_tools_logger.getLogFn)((0, __storm_software_config_tools_logger.getLogLevel)(type), {
1736
+ ...options,
1737
+ logLevel
1738
+ })(`${chalk.default.bold.hex((0, __storm_software_config_tools_utilities_colors.getColor)("brand", options))(`${name ? (0, __stryke_string_format_kebab_case.kebabCase)(name) : ""}${options.name ? `${name ? chalk.default.gray(" > ") : ""}${(0, __stryke_string_format_kebab_case.kebabCase)(options.name)}` : ""}${chalk.default.gray(" > ")}`)}${args.join(" ")} `.trim());
1739
+ };
1740
+ const BADGE_COLORS = [
1741
+ "#00A0DD",
1742
+ "#6FCE4E",
1743
+ "#FBBF24",
1744
+ "#F43F5E",
1745
+ "#3B82F6",
1746
+ "#A855F7",
1747
+ "#469592",
1748
+ "#288EDF",
1749
+ "#D8B4FE",
1750
+ "#10B981",
1751
+ "#EF4444",
1752
+ "#F0EC56",
1753
+ "#F472B6",
1754
+ "#22D3EE",
1755
+ "#EAB308",
1756
+ "#84CC16",
1757
+ "#F87171",
1758
+ "#0EA5E9",
1759
+ "#D946EF",
1760
+ "#FACC15",
1761
+ "#34D399",
1762
+ "#8B5CF6"
1763
+ ];
1764
+ const extendLog = (logFn, name) => {
1765
+ return (type, ...args) => logFn(type, ` ${chalk.default.inverse.hex(BADGE_COLORS[name.split("").map((char) => char.charCodeAt(0)).reduce((ret, charCode) => ret + charCode, 0) % BADGE_COLORS.length] || BADGE_COLORS[0])(` ${(0, __stryke_string_format_title_case.titleCase)(name)} `)} ${args.join(" ")} `);
1766
+ };
1767
+
1768
+ //#endregion
1769
+ //#region ../core/src/lib/utilities/file-header.ts
1770
+ function getBaseFileHeader(context) {
1771
+ return `
1772
+ // Generated by ${(0, __stryke_string_format_title_case.titleCase)(context.config.framework) || "Powerlines"}
1773
+ ${context.config.output?.overwrite !== false ? `// Do not edit this file manually - it will be overwritten automatically. Automatic overwrites can be disabled by using the \`output.overwrite\` option.` : `// This file was generated on ${(/* @__PURE__ */ new Date()).toLocaleString()} - it will not be overwritten by ${(0, __stryke_string_format_title_case.titleCase)(context.config.framework)} while the \`output.overwrite\` option is set to \`true\`.`}
1774
+ `;
1775
+ }
1776
+ function getFileHeader(context, options = {}) {
1777
+ const { directive = null, prettierIgnore = false } = options;
1778
+ return `/* eslint-disable */
1779
+ // biome-ignore lint: disable
1780
+ ${prettierIgnore ? `// prettier-ignore` : ""}${directive ? `\n\n${directive}\n` : "\n"}
1781
+ ${getBaseFileHeader(context)}
1782
+
1783
+ `;
1784
+ }
1785
+
1786
+ //#endregion
1787
+ //#region ../core/src/lib/utilities/source-map.ts
1788
+ const dmp = new diff_match_patch.default();
1789
+
1790
+ //#endregion
1791
+ //#region ../powerlines/src/_internal/vfs.ts
1792
+ function toFilePath(path) {
1793
+ return (0, __stryke_path_correct_path.correctPath)((0, __stryke_path_slash.slash)(path?.toString() || ".").replace(/^file:\/\//, ""));
1794
+ }
1795
+ /**
1796
+ * Checks if a given file id is valid based on the specified prefix.
1797
+ *
1798
+ * @param id - The file ID to check.
1799
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
1800
+ * @returns `true` if the file ID is valid, otherwise `false`.
1801
+ */
1802
+ function isValidId(id, prefix = "powerlines") {
1803
+ return id.replace(/^\\0/, "").startsWith(`${prefix.replace(/:$/, "")}`);
1804
+ }
1805
+ /**
1806
+ * Formats a file id by removing the file extension and prepended runtime prefix.
1807
+ *
1808
+ * @param id - The file ID to format.
1809
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
1810
+ * @returns The formatted file ID.
1811
+ */
1812
+ function normalizeId(id, prefix = "powerlines") {
1813
+ return (0, __stryke_path_replace.replaceExtension)(toFilePath(id)).replace(/^\\0/, "").replace(/^powerlines:/, "").replace(/* @__PURE__ */ new RegExp(`^${prefix.replace(/:$/, "")}:`), "");
1814
+ }
1815
+ /**
1816
+ * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
1817
+ *
1818
+ * @param path - The path to normalize.
1819
+ * @param builtinsPath - The path to built-in files.
1820
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
1821
+ * @returns The normalized path.
1822
+ */
1823
+ function normalizePath(path, builtinsPath, prefix = "powerlines") {
1824
+ return (0, __stryke_path_is_type.isAbsolutePath)(path) ? path : isValidId(toFilePath(path), prefix) ? normalizeId(toFilePath(path), prefix).replace(/* @__PURE__ */ new RegExp(`^${prefix.replace(/:$/, "")}:`), builtinsPath) : toFilePath(path);
1825
+ }
1826
+ /**
1827
+ * Normalizes glob patterns by resolving them against the workspace root.
1828
+ *
1829
+ * @param workspaceRoot - The root directory of the workspace.
1830
+ * @param patterns - The glob patterns to normalize.
1831
+ * @returns An array of normalized glob patterns.
1832
+ */
1833
+ function normalizeGlobPatterns(workspaceRoot, patterns) {
1834
+ return (0, __stryke_helpers_get_unique.getUnique)((0, __stryke_convert_to_array.toArray)(patterns).map((pattern) => {
1835
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(pattern) && ((0, __stryke_type_checks_is_set_string.isSetString)(pattern.input) || (0, __stryke_type_checks_is_set_string.isSetString)(pattern.glob))) return (0, __stryke_path_join.joinPaths)(pattern.input || workspaceRoot, pattern.glob || "**/*");
1836
+ else if (!(0, __stryke_type_checks_is_set_string.isSetString)(pattern)) return;
1837
+ return pattern;
1838
+ }).filter(__stryke_type_checks_is_set_string.isSetString));
1839
+ }
1840
+ /**
1841
+ * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.
1842
+ *
1843
+ * @remarks
1844
+ * This class provides methods to manage virtual files, check their existence, retrieve their content, and manipulate the virtual file system. It allows for efficient file management and retrieval without relying on the actual file system.
1845
+ */
1846
+ var VirtualFileSystem = class VirtualFileSystem {
1847
+ /**
1848
+ * A map of virtual file IDs to their associated metadata.
1849
+ */
1850
+ #metadata;
1851
+ /**
1852
+ * A map of underlying file paths to their virtual file IDs.
1853
+ */
1854
+ #ids;
1855
+ /**
1856
+ * A map of virtual file IDs to their underlying file paths.
1857
+ */
1858
+ #paths;
1859
+ /**
1860
+ * The unified volume that combines the virtual file system with the real file system.
1861
+ *
1862
+ * @remarks
1863
+ * This volume allows for seamless access to both virtual and real files.
1864
+ */
1865
+ #storage;
1866
+ /**
1867
+ * A cache for module resolution results.
1868
+ */
1869
+ #resolverCache;
1870
+ /**
1871
+ * Indicator specifying if the virtual file system (VFS) is disposed
1872
+ */
1873
+ #isDisposed = false;
1874
+ /**
1875
+ * The context of the virtual file system.
1876
+ */
1877
+ #context;
1878
+ /**
1879
+ * The file system's logging function.
1880
+ */
1881
+ #log;
1882
+ /**
1883
+ * Normalizes a given module id by resolving it against the built-ins path.
1884
+ *
1885
+ * @param id - The module id to normalize.
1886
+ * @returns The normalized module id.
1887
+ */
1888
+ #normalizeId(id) {
1889
+ let normalized = id;
1890
+ if ((0, __stryke_path_is_parent_path.isParentPath)(normalized, this.#context.builtinsPath)) normalized = (0, __stryke_path_replace.replacePath)(normalized, this.#context.builtinsPath);
1891
+ return normalizeId(normalized, this.#context.config.framework);
1892
+ }
1893
+ /**
1894
+ * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
1895
+ *
1896
+ * @param path - The path to normalize.
1897
+ * @returns The normalized path.
1898
+ */
1899
+ #normalizePath(path) {
1900
+ return normalizePath(path.includes("{") || path.includes("}") ? replacePathTokens(this.#context, path) : path, this.#context.builtinsPath, this.#context.config.framework);
1901
+ }
1902
+ /**
1903
+ * Gets the storage adapter and relative key for a given key.
1904
+ *
1905
+ * @remarks
1906
+ * The `key` can be either a path or a storage adapter name.
1907
+ *
1908
+ * @param key - The key to get the storage adapter for.
1909
+ * @returns The storage adapter and relative key for the given key.
1910
+ */
1911
+ #getStorage(key, preset) {
1912
+ const path = this.resolveSync(this.#normalizePath(key)) || key;
1913
+ for (const base of Object.keys(this.#storage).filter(Boolean).sort().reverse()) if ((path === base || (0, __stryke_path_is_parent_path.isParentPath)(path, base)) && (!preset || this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())) return {
1914
+ base,
1915
+ relativeKey: (0, __stryke_path_replace.replacePath)(path, base),
1916
+ adapter: this.#storage[base]
1917
+ };
1918
+ if (!preset || this.#storage[""]?.preset?.toLowerCase() === preset.toLowerCase()) return {
1919
+ base: "",
1920
+ relativeKey: path,
1921
+ adapter: this.#storage[""]
1922
+ };
1923
+ this.#storage[path] = preset === "virtual" ? new VirtualStorageAdapter(this.#context, { base: path }) : new FileSystemStorageAdapter(this.#context, { base: path });
1924
+ return {
1925
+ base: path,
1926
+ relativeKey: "",
1927
+ adapter: this.#storage[path]
1928
+ };
1929
+ }
1930
+ /**
1931
+ * Gets all storage adapters that match a given base key.
1932
+ *
1933
+ * @param base - The base key to match storage adapters against.
1934
+ * @param includeParent - Whether to include parent storage adapters.
1935
+ * @returns An array of storage adapters that match the given base key.
1936
+ */
1937
+ #getStorages(base = "", includeParent = false) {
1938
+ const baseKey = this.resolveSync(base) || base;
1939
+ return Object.keys(this.#storage).sort().reverse().filter((key) => (0, __stryke_path_is_parent_path.isParentPath)(key, baseKey) || includeParent && (0, __stryke_path_is_parent_path.isParentPath)(baseKey, key) || baseKey.includes("*") && ((0, __stryke_path_is_parent_path.isParentPath)((0, __stryke_path_correct_path.stripStars)(baseKey), key) || (0, __stryke_path_glob_to_regex.globToRegex)((0, __stryke_path_replace.replaceExtension)(baseKey)).test(key))).map((key) => ({
1940
+ relativeBase: baseKey.length > key.length ? baseKey.slice(key.length) : void 0,
1941
+ base: key,
1942
+ adapter: this.#storage[key]
1943
+ }));
1944
+ }
1945
+ /**
1946
+ * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
1947
+ *
1948
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
1949
+ * @returns A promise that resolves to a new virtual file system instance.
1950
+ */
1951
+ static async create(context) {
1952
+ context.debug("Starting virtual file system (VFS) initialization processes...");
1953
+ let result;
1954
+ if (!context.config.skipCache && (0, __stryke_fs_exists.existsSync)((0, __stryke_path_join.joinPaths)(context.dataPath, "fs.bin"))) {
1955
+ const buffer = await (0, __stryke_fs_buffer.readFileBuffer)((0, __stryke_path_join.joinPaths)(context.dataPath, "fs.bin"));
1956
+ const fs = new __stryke_capnp.Message(buffer, false).getRoot(FileSystem);
1957
+ result = new VirtualFileSystem(context, fs);
1958
+ if (fs._hasStorage() && fs.storage.length > 0) await Promise.all(fs.storage.values().map(async (file) => {
1959
+ if (file.path && file.code) {
1960
+ let id;
1961
+ if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
1962
+ let metadata;
1963
+ if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
1964
+ await result.write(file.path, file.code, { meta: {
1965
+ id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
1966
+ type: metadata?.type || "normal",
1967
+ properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
1968
+ ret[kvp.key] = kvp.value;
1969
+ return ret;
1970
+ }, {}) : void 0,
1971
+ timestamp: metadata?.timestamp
1972
+ } });
1973
+ }
1974
+ }));
1975
+ } else result = new VirtualFileSystem(context, new __stryke_capnp.Message().initRoot(FileSystem));
1976
+ result.#log(__storm_software_config_tools_types.LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
1977
+ return result;
1978
+ }
1979
+ /**
1980
+ * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
1981
+ *
1982
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
1983
+ * @returns A new virtual file system instance.
1984
+ */
1985
+ static createSync(context) {
1986
+ context.debug("Starting virtual file system (VFS) initialization processes...");
1987
+ let result;
1988
+ if (!context.config.skipCache && (0, __stryke_fs_exists.existsSync)((0, __stryke_path_join.joinPaths)(context.dataPath, "fs.bin"))) {
1989
+ const buffer = (0, __stryke_fs_buffer.readFileBufferSync)((0, __stryke_path_join.joinPaths)(context.dataPath, "fs.bin"));
1990
+ const fs = new __stryke_capnp.Message(buffer, false).getRoot(FileSystem);
1991
+ result = new VirtualFileSystem(context, fs);
1992
+ if (fs._hasStorage() && fs.storage.length > 0) fs.storage.values().forEach((file) => {
1993
+ if (file.path && file.code) {
1994
+ let id;
1995
+ if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
1996
+ let metadata;
1997
+ if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
1998
+ result.writeSync(file.path, file.code, { meta: {
1999
+ id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
2000
+ type: metadata?.type,
2001
+ properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
2002
+ ret[kvp.key] = kvp.value;
2003
+ return ret;
2004
+ }, {}) : void 0,
2005
+ timestamp: metadata?.timestamp
2006
+ } });
2007
+ }
2008
+ });
2009
+ } else result = new VirtualFileSystem(context, new __stryke_capnp.Message().initRoot(FileSystem));
2010
+ result.#log(__storm_software_config_tools_types.LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
2011
+ return result;
2012
+ }
2013
+ /**
2014
+ * A map of file ids to their metadata.
2015
+ */
2016
+ get metadata() {
2017
+ return new Proxy(this.#metadata, {
2018
+ get: (target, prop) => {
2019
+ return target[this.#normalizeId(prop)];
2020
+ },
2021
+ set: (target, prop, value) => {
2022
+ target[this.#normalizeId(prop)] = value;
2023
+ return true;
2024
+ },
2025
+ deleteProperty: (target, prop) => {
2026
+ delete target[this.#normalizeId(prop)];
2027
+ return true;
2028
+ },
2029
+ has: (target, prop) => {
2030
+ return this.#normalizeId(prop) in target;
2031
+ },
2032
+ ownKeys: (target) => {
2033
+ return (0, __stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
2034
+ }
2035
+ });
2036
+ }
2037
+ /**
2038
+ * A map of file paths to their module ids.
2039
+ */
2040
+ get ids() {
2041
+ return new Proxy(this.#ids, {
2042
+ get: (target, prop) => {
2043
+ return target[this.#normalizePath(prop)];
2044
+ },
2045
+ set: (target, prop, value) => {
2046
+ target[this.#normalizePath(prop)] = value;
2047
+ return true;
2048
+ },
2049
+ deleteProperty: (target, prop) => {
2050
+ delete target[this.#normalizePath(prop)];
2051
+ return true;
2052
+ },
2053
+ has: (target, prop) => {
2054
+ return this.#normalizePath(prop) in target;
2055
+ },
2056
+ ownKeys: (target) => {
2057
+ return (0, __stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizePath(key)));
2058
+ }
2059
+ });
2060
+ }
2061
+ /**
2062
+ * A map of module ids to their file paths.
2063
+ */
2064
+ get paths() {
2065
+ return new Proxy(this.#paths, {
2066
+ get: (target, prop) => {
2067
+ return target[this.#normalizeId(prop)];
2068
+ },
2069
+ set: (target, prop, value) => {
2070
+ target[this.#normalizeId(prop)] = value;
2071
+ return true;
2072
+ },
2073
+ deleteProperty: (target, prop) => {
2074
+ delete target[this.#normalizeId(prop)];
2075
+ return true;
2076
+ },
2077
+ has: (target, prop) => {
2078
+ return this.#normalizeId(prop) in target;
2079
+ },
2080
+ ownKeys: (target) => {
2081
+ return (0, __stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
2082
+ }
2083
+ });
2084
+ }
2085
+ /**
2086
+ * Gets the resolver cache.
2087
+ */
2088
+ get resolverCache() {
2089
+ if (!this.#resolverCache) this.#resolverCache = (0, flat_cache.create)({
2090
+ cacheId: "module-resolution",
2091
+ cacheDir: this.#context.cachePath,
2092
+ ttl: 3600 * 1e3,
2093
+ lruSize: 5e3,
2094
+ persistInterval: 100
2095
+ });
2096
+ return this.#resolverCache;
2097
+ }
2098
+ /**
2099
+ * Creates a new instance of the {@link VirtualFileSystem}.
2100
+ *
2101
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
2102
+ * @param fs - A buffer containing the serialized virtual file system data.
2103
+ */
2104
+ constructor(context, fs) {
2105
+ this.#context = context;
2106
+ this.#storage = { "": new FileSystemStorageAdapter(context) };
2107
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(this.#context.config.output.storage)) this.#storage = {
2108
+ ...this.#storage,
2109
+ ...this.#context.config.output.storage
2110
+ };
2111
+ this.#storage.virtual ??= new VirtualStorageAdapter(context, { base: "/_virtual" });
2112
+ if (this.#context.config.output.storage !== "fs") {
2113
+ this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.artifactsPath });
2114
+ this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.builtinsPath });
2115
+ this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(context, { base: this.#context.entryPath });
2116
+ }
2117
+ this.#metadata = {};
2118
+ if (fs._hasMetadata()) this.#metadata = fs.metadata.values().reduce((ret, metadata) => {
2119
+ ret[metadata.id] = {
2120
+ id: metadata.id,
2121
+ type: metadata.type,
2122
+ timestamp: metadata.timestamp ?? Date.now(),
2123
+ properties: metadata._hasProperties() ? metadata.properties.values().reduce((ret$1, item) => {
2124
+ ret$1[item.key] = item.value;
2125
+ return ret$1;
2126
+ }, {}) : {}
2127
+ };
2128
+ return ret;
2129
+ }, {});
2130
+ this.#ids = {};
2131
+ this.#paths = {};
2132
+ if (fs._hasIds()) {
2133
+ this.#ids = fs.ids.values().reduce((ret, identifier) => {
2134
+ ret[identifier.path] ??= identifier.id;
2135
+ return ret;
2136
+ }, {});
2137
+ this.#paths = fs.ids.values().reduce((ret, identifier) => {
2138
+ ret[identifier.id] ??= identifier.path;
2139
+ return ret;
2140
+ }, {});
2141
+ }
2142
+ this.#log = extendLog(this.#context.log, "file-system");
2143
+ }
2144
+ /**
2145
+ * Asynchronously checks if a file exists in the virtual file system (VFS).
2146
+ *
2147
+ * @param path - The path to the file.
2148
+ * @returns A promise that resolves to `true` if the file exists, otherwise `false`.
2149
+ */
2150
+ async exists(path) {
2151
+ const { relativeKey, adapter } = this.#getStorage(path);
2152
+ return adapter.exists(relativeKey);
2153
+ }
2154
+ /**
2155
+ * Synchronously checks if a file exists in the virtual file system (VFS).
2156
+ *
2157
+ * @param path - The path to the file.
2158
+ * @returns `true` if the file exists, otherwise `false`.
2159
+ */
2160
+ existsSync(path) {
2161
+ const { relativeKey, adapter } = this.#getStorage(path);
2162
+ return adapter.existsSync(relativeKey);
2163
+ }
2164
+ /**
2165
+ * Checks if a file is virtual in the virtual file system (VFS).
2166
+ *
2167
+ * @param path - The path to the file.
2168
+ * @returns `true` if the file is virtual, otherwise `false`.
2169
+ */
2170
+ isVirtual(path) {
2171
+ const resolved = this.resolveSync(path);
2172
+ if (!resolved) return false;
2173
+ return this.#getStorage(resolved)?.adapter?.preset === "virtual";
2174
+ }
2175
+ /**
2176
+ * Checks if a path is a directory in the virtual file system (VFS).
2177
+ *
2178
+ * @param path - The path to check.
2179
+ * @returns `true` if the path is a directory, otherwise `false`.
2180
+ */
2181
+ isDirectorySync(path) {
2182
+ const resolved = this.resolveSync(path);
2183
+ if (!resolved) return false;
2184
+ return !!(this.existsSync(resolved) && this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved));
2185
+ }
2186
+ /**
2187
+ * Checks if a path is a directory in the virtual file system (VFS).
2188
+ *
2189
+ * @param path - The path to check.
2190
+ * @returns `true` if the path is a directory, otherwise `false`.
2191
+ */
2192
+ async isDirectory(path) {
2193
+ const resolved = await this.resolve(path);
2194
+ if (!resolved) return false;
2195
+ return !!(await this.exists(resolved) && await this.#getStorage(resolved)?.adapter?.isDirectory(resolved));
2196
+ }
2197
+ /**
2198
+ * Checks if a path is a file in the virtual file system (VFS).
2199
+ *
2200
+ * @param path - The path to check.
2201
+ * @returns `true` if the path is a file, otherwise `false`.
2202
+ */
2203
+ isFileSync(path) {
2204
+ const resolved = this.resolveSync(path);
2205
+ if (!resolved) return false;
2206
+ return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;
2207
+ }
2208
+ /**
2209
+ * Checks if a path is a file in the virtual file system (VFS).
2210
+ *
2211
+ * @param path - The path to check.
2212
+ * @returns `true` if the path is a file, otherwise `false`.
2213
+ */
2214
+ async isFile(path) {
2215
+ const resolved = await this.resolve(path);
2216
+ if (!resolved) return false;
2217
+ return await this.#getStorage(resolved)?.adapter?.isFile(resolved) ?? false;
2218
+ }
2219
+ /**
2220
+ * Lists files in a given path.
2221
+ *
2222
+ * @param path - The path to list files from.
2223
+ * @returns An array of file names in the specified path.
2224
+ */
2225
+ listSync(path) {
2226
+ let resolvedPath = path;
2227
+ if (resolvedPath.includes("*")) {
2228
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.WARN, `Invoking "listSync" with a glob pattern is not supported. It is likely you meant to use "globSync". Path: ${path}`);
2229
+ resolvedPath = (0, __stryke_path_correct_path.stripStars)(resolvedPath);
2230
+ }
2231
+ return (0, __stryke_helpers_get_unique.getUnique)(this.#getStorages(resolvedPath, true).map((storage) => storage.adapter.listSync(storage.relativeBase ? storage.base ? (0, __stryke_path_append.appendPath)(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)).flat().filter(Boolean));
2232
+ }
2233
+ /**
2234
+ * Lists files in a given path.
2235
+ *
2236
+ * @param path - The path to list files from.
2237
+ * @returns An array of file names in the specified path.
2238
+ */
2239
+ async list(path) {
2240
+ let resolvedPath = path;
2241
+ if (resolvedPath.includes("*")) {
2242
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.WARN, `Invoking "list" with a glob pattern is not supported. It is likely you meant to use "glob". Path: ${path}`);
2243
+ resolvedPath = (0, __stryke_path_correct_path.stripStars)(resolvedPath);
2244
+ }
2245
+ return (0, __stryke_helpers_get_unique.getUnique)((await Promise.all(this.#getStorages(resolvedPath, true).map(async (storage) => storage.adapter.list(storage.relativeBase ? storage.base ? (0, __stryke_path_append.appendPath)(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)))).flat().filter(Boolean));
2246
+ }
2247
+ /**
2248
+ * Removes a file in the virtual file system (VFS).
2249
+ *
2250
+ * @param path - The path to create the directory at.
2251
+ */
2252
+ async remove(path) {
2253
+ const normalizedPath = this.#normalizePath(path);
2254
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
2255
+ const { relativeKey, adapter } = this.#getStorage(normalizedPath);
2256
+ if ((0, __stryke_path_file_path_fns.hasFileExtension)(normalizedPath)) await adapter.remove(relativeKey);
2257
+ else await adapter.clear(relativeKey);
2258
+ const id = this.#ids[normalizedPath];
2259
+ if (id && this.#metadata[id]) {
2260
+ delete this.#metadata[id];
2261
+ delete this.#ids[normalizedPath];
2262
+ delete this.#paths[id];
2263
+ }
2264
+ }
2265
+ /**
2266
+ * Removes a file in the virtual file system (VFS).
2267
+ *
2268
+ * @param path - The path to create the directory at.
2269
+ */
2270
+ removeSync(path) {
2271
+ const normalizedPath = this.#normalizePath(path);
2272
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
2273
+ const { relativeKey, adapter } = this.#getStorage(normalizedPath);
2274
+ if ((0, __stryke_path_file_path_fns.hasFileExtension)(normalizedPath)) adapter.removeSync(relativeKey);
2275
+ else adapter.clearSync(relativeKey);
2276
+ const id = this.#ids[normalizedPath];
2277
+ if (id && this.#metadata[id]) {
2278
+ delete this.#metadata[id];
2279
+ delete this.#ids[normalizedPath];
2280
+ delete this.#paths[id];
2281
+ }
2282
+ }
2283
+ /**
2284
+ * Glob files in the virtual file system (VFS) based on the provided pattern(s).
2285
+ *
2286
+ * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
2287
+ * @returns An array of file paths matching the provided pattern(s)
2288
+ */
2289
+ async glob(patterns) {
2290
+ const results = [];
2291
+ for (const pattern of normalizeGlobPatterns(this.#context.workspaceConfig.workspaceRoot, patterns)) {
2292
+ const normalized = this.#normalizePath(pattern);
2293
+ if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...await this.list(normalized));
2294
+ else {
2295
+ const resolved = await this.resolve(normalized);
2296
+ if (resolved && !results.includes(resolved)) results.push(resolved);
2297
+ }
2298
+ else {
2299
+ const absPattern = (0, __stryke_path_is_type.isAbsolutePath)(normalized) ? normalized : this.#normalizePath((0, __stryke_path_append.appendPath)(normalized, this.#context.workspaceConfig.workspaceRoot));
2300
+ await Promise.all((await this.list((0, __stryke_path_correct_path.stripStars)(absPattern))).map(async (file) => {
2301
+ if ((0, __stryke_path_glob_to_regex.globToRegex)(absPattern).test(file)) {
2302
+ const resolved = await this.resolve(file);
2303
+ if (resolved && !results.includes(resolved)) results.push(resolved);
2304
+ }
2305
+ }));
2306
+ }
2307
+ }
2308
+ return results;
2309
+ }
2310
+ /**
2311
+ * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).
2312
+ *
2313
+ * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
2314
+ * @returns An array of file paths matching the provided pattern(s)
2315
+ */
2316
+ globSync(patterns) {
2317
+ const results = [];
2318
+ for (const pattern of normalizeGlobPatterns(this.#context.workspaceConfig.workspaceRoot, patterns)) {
2319
+ const normalized = this.#normalizePath(pattern);
2320
+ if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...this.listSync(normalized));
2321
+ else {
2322
+ const resolved = this.resolveSync(normalized);
2323
+ if (resolved && !results.includes(resolved)) results.push(resolved);
2324
+ }
2325
+ else {
2326
+ const absPattern = (0, __stryke_path_is_type.isAbsolutePath)(normalized) ? normalized : this.#normalizePath((0, __stryke_path_append.appendPath)(normalized, this.#context.workspaceConfig.workspaceRoot));
2327
+ const files = this.listSync((0, __stryke_path_correct_path.stripStars)(absPattern));
2328
+ for (const file of files) if ((0, __stryke_path_glob_to_regex.globToRegex)(absPattern).test(file)) {
2329
+ const resolved = this.resolveSync(file);
2330
+ if (resolved && !results.includes(resolved)) results.push(resolved);
2331
+ }
2332
+ }
2333
+ }
2334
+ return results;
2335
+ }
2336
+ /**
2337
+ * Copies a file from one path to another in the virtual file system (VFS).
2338
+ *
2339
+ * @param srcPath - The source path to copy
2340
+ * @param destPath - The destination path to copy to
2341
+ */
2342
+ async copy(srcPath, destPath) {
2343
+ const src = srcPath instanceof URL ? (0, node_url.fileURLToPath)(srcPath) : srcPath;
2344
+ const dest = destPath instanceof URL ? (0, node_url.fileURLToPath)(destPath) : destPath;
2345
+ if (!(0, __stryke_type_checks_is_set_string.isSetString)(src) && (!(0, __stryke_type_checks_is_set_object.isSetObject)(src) || !(0, __stryke_type_checks_is_set_string.isSetString)(src.input)) || !(0, __stryke_type_checks_is_set_string.isSetString)(dest)) return;
2346
+ const sourceStr = (0, __stryke_type_checks_is_string.isString)(src) ? src : src.input ? src.input : this.#context.workspaceConfig.workspaceRoot;
2347
+ const source = await this.resolve(sourceStr);
2348
+ if (!source) return;
2349
+ if (this.isDirectorySync(source) || (0, __stryke_type_checks_is_set_string.isSetString)(src) && src.includes("*") || (0, __stryke_type_checks_is_set_object.isSetObject)(src) && (0, __stryke_type_checks_is_set_string.isSetString)(src.glob)) await Promise.all((await this.glob(src)).map(async (file) => {
2350
+ return this.copy(file, (0, __stryke_path_append.appendPath)((0, __stryke_path_replace.replacePath)(file, sourceStr), dest));
2351
+ }));
2352
+ else {
2353
+ const content = await this.read(source);
2354
+ if (content !== void 0) await this.write(this.#normalizePath(dest), content, { skipFormat: true });
2355
+ }
2356
+ }
2357
+ /**
2358
+ * Synchronously copies a file from one path to another in the virtual file system (VFS).
2359
+ *
2360
+ * @param srcPath - The source path to copy
2361
+ * @param destPath - The destination path to copy to
2362
+ */
2363
+ copySync(srcPath, destPath) {
2364
+ const src = srcPath instanceof URL ? (0, node_url.fileURLToPath)(srcPath) : srcPath;
2365
+ const dest = destPath instanceof URL ? (0, node_url.fileURLToPath)(destPath) : destPath;
2366
+ if (!(0, __stryke_type_checks_is_set_string.isSetString)(src) && (!(0, __stryke_type_checks_is_set_object.isSetObject)(src) || !(0, __stryke_type_checks_is_set_string.isSetString)(src.input)) || !(0, __stryke_type_checks_is_set_string.isSetString)(dest)) return;
2367
+ const sourceStr = (0, __stryke_type_checks_is_string.isString)(src) ? src : src.input ? src.input : this.#context.workspaceConfig.workspaceRoot;
2368
+ const source = this.resolveSync(sourceStr);
2369
+ if (!source) return;
2370
+ if (this.isDirectorySync(source) || (0, __stryke_type_checks_is_set_string.isSetString)(src) && src.includes("*") || (0, __stryke_type_checks_is_set_object.isSetObject)(src) && (0, __stryke_type_checks_is_set_string.isSetString)(src.glob)) this.globSync(src).map((file) => {
2371
+ return this.copySync(file, (0, __stryke_path_append.appendPath)((0, __stryke_path_file_path_fns.findFilePath)((0, __stryke_path_replace.replacePath)(file, sourceStr)), dest));
2372
+ });
2373
+ else {
2374
+ const content = this.readSync(source);
2375
+ if (content !== void 0) this.writeSync(this.#normalizePath((0, __stryke_path_file_path_fns.hasFileExtension)(dest) ? dest : (0, __stryke_path_append.appendPath)((0, __stryke_path_file_path_fns.findFileName)(source), dest)), content, { skipFormat: true });
2376
+ }
2377
+ }
2378
+ /**
2379
+ * Moves a file (or files) from one path to another in the virtual file system (VFS).
2380
+ *
2381
+ * @param srcPath - The source path to move
2382
+ * @param destPath - The destination path to move to
2383
+ */
2384
+ async move(srcPath, destPath) {
2385
+ if ((0, __stryke_path_file_path_fns.hasFileExtension)(srcPath)) {
2386
+ await this.copy(srcPath, destPath);
2387
+ await this.remove(srcPath);
2388
+ } else await Promise.all((await this.list(srcPath)).map(async (file) => {
2389
+ await this.copy(file, destPath);
2390
+ await this.remove(file);
2391
+ }));
2392
+ }
2393
+ /**
2394
+ * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).
2395
+ *
2396
+ * @param srcPath - The source path to move
2397
+ * @param destPath - The destination path to move to
2398
+ */
2399
+ moveSync(srcPath, destPath) {
2400
+ if ((0, __stryke_path_file_path_fns.hasFileExtension)(srcPath)) {
2401
+ this.copySync(srcPath, destPath);
2402
+ this.removeSync(srcPath);
2403
+ } else this.listSync(srcPath).forEach((file) => {
2404
+ this.copySync(file, destPath);
2405
+ this.removeSync(file);
2406
+ });
2407
+ }
2408
+ /**
2409
+ * Asynchronously reads a file from the virtual file system (VFS).
2410
+ *
2411
+ * @param path - The path or ID of the file to read.
2412
+ * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.
2413
+ */
2414
+ async read(path) {
2415
+ const filePath = await this.resolve(path);
2416
+ if (!filePath || !this.existsSync(filePath)) return;
2417
+ const { adapter } = this.#getStorage(filePath);
2418
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
2419
+ return await adapter.get(filePath) ?? void 0;
2420
+ }
2421
+ /**
2422
+ * Synchronously reads a file from the virtual file system (VFS).
2423
+ *
2424
+ * @param path - The path or ID of the file to read.
2425
+ * @returns The contents of the file as a string, or undefined if the file does not exist.
2426
+ */
2427
+ readSync(path) {
2428
+ const filePath = this.resolveSync(path);
2429
+ if (!filePath || !this.existsSync(filePath)) return;
2430
+ const { adapter } = this.#getStorage(filePath);
2431
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
2432
+ return adapter.getSync(filePath) ?? void 0;
2433
+ }
2434
+ /**
2435
+ * Writes a file to the virtual file system (VFS).
2436
+ *
2437
+ * @param path - The path to the file.
2438
+ * @param data - The contents of the file.
2439
+ * @param options - Optional parameters for writing the file.
2440
+ * @returns A promise that resolves when the file is written.
2441
+ */
2442
+ async write(path, data = "", options = {}) {
2443
+ const meta = options.meta ?? {};
2444
+ const resolvedPath = await this.resolve(this.#normalizePath(path)) || path;
2445
+ const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
2446
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${(0, __stryke_string_format_pretty_bytes.prettyBytes)(new node_buffer.Blob((0, __stryke_convert_to_array.toArray)(data)).size)})`);
2447
+ let code = data;
2448
+ try {
2449
+ if (!options.skipFormat) code = await format(this.#context, resolvedPath, data);
2450
+ } catch (err) {
2451
+ if ([
2452
+ "js",
2453
+ "ts",
2454
+ "cjs",
2455
+ "cts",
2456
+ "mjs",
2457
+ "mts",
2458
+ "tsx",
2459
+ "jsx",
2460
+ "json",
2461
+ "json5",
2462
+ "jsonc",
2463
+ "md",
2464
+ "mdx"
2465
+ ].includes((0, __stryke_path_file_path_fns.findFileExtensionSafe)(resolvedPath, { fullExtension: true }))) this.#log(__storm_software_config_tools_types.LogLevelLabel.WARN, `Failed to format file ${resolvedPath} before writing: ${err.message}`);
2466
+ code = data;
2467
+ }
2468
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${(0, __stryke_string_format_pretty_bytes.prettyBytes)(new node_buffer.Blob((0, __stryke_convert_to_array.toArray)(code)).size)})`);
2469
+ const id = this.#normalizeId(meta.id || resolvedPath);
2470
+ this.metadata[id] = {
2471
+ type: "normal",
2472
+ timestamp: Date.now(),
2473
+ ...this.metadata[id] ?? {},
2474
+ ...meta
2475
+ };
2476
+ this.paths[id] = resolvedPath;
2477
+ this.ids[resolvedPath] = id;
2478
+ return adapter.set(relativeKey, code);
2479
+ }
2480
+ /**
2481
+ * Synchronously writes a file to the virtual file system (VFS).
2482
+ *
2483
+ * @param path - The file to write.
2484
+ * @param data - The contents of the file.
2485
+ * @param options - Optional parameters for writing the file.
2486
+ */
2487
+ writeSync(path, data = "", options = {}) {
2488
+ const meta = options.meta ?? {};
2489
+ const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;
2490
+ const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
2491
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} file to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${(0, __stryke_string_format_pretty_bytes.prettyBytes)(new node_buffer.Blob((0, __stryke_convert_to_array.toArray)(data)).size)})`);
2492
+ const id = this.#normalizeId(meta.id || resolvedPath);
2493
+ this.metadata[id] = {
2494
+ type: "normal",
2495
+ timestamp: Date.now(),
2496
+ ...this.metadata[id] ?? {},
2497
+ ...meta
2498
+ };
2499
+ this.paths[id] = resolvedPath;
2500
+ this.ids[resolvedPath] = id;
2501
+ return adapter.setSync(relativeKey, data);
2502
+ }
2503
+ /**
2504
+ * Synchronously creates a directory at the specified path.
2505
+ *
2506
+ * @param dirPath - The path of the directory to create.
2507
+ */
2508
+ mkdirSync(dirPath) {
2509
+ return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);
2510
+ }
2511
+ /**
2512
+ * Creates a directory at the specified path.
2513
+ *
2514
+ * @param path - The path of the directory to create.
2515
+ */
2516
+ async mkdir(path) {
2517
+ return this.#getStorage(path)?.adapter?.mkdir(path);
2518
+ }
2519
+ /**
2520
+ * Retrieves the metadata of a file in the virtual file system (VFS).
2521
+ *
2522
+ * @param pathOrId - The path or ID of the file to retrieve metadata for.
2523
+ * @returns The metadata of the file, or undefined if the file does not exist.
2524
+ */
2525
+ getMetadata(pathOrId) {
2526
+ const resolved = this.resolveSync(pathOrId);
2527
+ if (resolved && this.metadata[resolved]) return this.metadata[resolved];
2528
+ }
2529
+ /**
2530
+ * Resolves a given module ID using the configured aliases.
2531
+ *
2532
+ * @remarks
2533
+ * This function can be used to map module IDs to different paths based on the alias configuration.
2534
+ *
2535
+ * @param id - The module ID to resolve.
2536
+ * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).
2537
+ */
2538
+ resolveAlias(id) {
2539
+ let path = id;
2540
+ if (this.#context.config.resolve.alias) {
2541
+ if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) {
2542
+ const found = this.#context.config.resolve.alias.filter((alias) => (0, __stryke_type_checks_is_set_string.isSetString)(alias.find) && (alias.find === path || path.startsWith(`${alias.find}/`)) || (0, __stryke_type_checks_is_regexp.isRegExp)(alias.find) && alias.find.test(path));
2543
+ if (found.length > 0) {
2544
+ const alias = found.reduce((ret, current) => {
2545
+ return ((0, __stryke_type_checks_is_set_string.isSetString)(ret.find) ? ret.find.length : (0, __stryke_type_checks_is_regexp.isRegExp)(ret.find) ? ret.find.source.length : 0) > ((0, __stryke_type_checks_is_set_string.isSetString)(current.find) ? current.find.length : (0, __stryke_type_checks_is_regexp.isRegExp)(current.find) ? current.find.source.length : 0) ? ret : current;
2546
+ });
2547
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(alias.find)) path = path.replace(/* @__PURE__ */ new RegExp(`^${alias.find}`), alias.replacement);
2548
+ else if ((0, __stryke_type_checks_is_regexp.isRegExp)(alias.find)) path = path.replace(alias.find, alias.replacement);
2549
+ }
2550
+ } else if ((0, __stryke_type_checks_is_set_object.isSetObject)(this.#context.config.resolve.alias)) {
2551
+ const found = Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`));
2552
+ if (found.length > 0) {
2553
+ const alias = found.reduce((ret, current) => {
2554
+ return ret.length > current.length ? ret : current;
2555
+ });
2556
+ path = path.replace(/* @__PURE__ */ new RegExp(`^${alias}`), this.#context.config.resolve.alias[alias]);
2557
+ }
2558
+ }
2559
+ }
2560
+ return path;
2561
+ }
2562
+ /**
2563
+ * A helper function to resolve modules in the virtual file system (VFS).
2564
+ *
2565
+ * @remarks
2566
+ * This function can be used to resolve modules relative to the project root directory.
2567
+ *
2568
+ * @example
2569
+ * ```ts
2570
+ * const resolved = await context.resolvePath("some-module", "/path/to/importer");
2571
+ * ```
2572
+ *
2573
+ * @param id - The module to resolve.
2574
+ * @param importer - An optional path to the importer module.
2575
+ * @param options - Additional resolution options.
2576
+ * @returns A promise that resolves to the resolved module path.
2577
+ */
2578
+ async resolve(id, importer, options = {}) {
2579
+ let path = id;
2580
+ if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
2581
+ if (options.skipAlias !== true) path = this.resolveAlias(path);
2582
+ if ((0, __stryke_path_is_type.isAbsolutePath)(path)) return path;
2583
+ const resolverCacheKey = (0, __stryke_hash.murmurhash)({
2584
+ path: this.#normalizeId(path),
2585
+ importer,
2586
+ options
2587
+ });
2588
+ let result;
2589
+ if (!this.#context.config.skipCache) {
2590
+ result = this.resolverCache.get(resolverCacheKey);
2591
+ if (result) return result;
2592
+ }
2593
+ result = this.paths[this.#normalizeId(path)];
2594
+ if (!result) {
2595
+ const paths = options.paths ?? [];
2596
+ if (importer && !paths.includes(importer)) paths.push(importer);
2597
+ paths.push(this.#context.workspaceConfig.workspaceRoot);
2598
+ paths.push((0, __stryke_path_append.appendPath)(this.#context.config.root, this.#context.workspaceConfig.workspaceRoot));
2599
+ paths.push((0, __stryke_path_append.appendPath)((0, __stryke_path_join.joinPaths)(this.#context.config.root, "src"), this.#context.workspaceConfig.workspaceRoot));
2600
+ paths.push(...Object.keys(this.#context.tsconfig?.options?.paths ?? {}).filter((tsconfigPath) => path.startsWith(tsconfigPath.replace(/\*$/, ""))).map((tsconfigPath) => this.#context.tsconfig?.options?.paths?.[tsconfigPath]).flat().filter(Boolean).map((tsconfigPath) => (0, __stryke_path_append.appendPath)(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)));
2601
+ for (const combination of (0, __stryke_fs_resolve.getResolutionCombinations)(path, { paths })) {
2602
+ const { relativeKey, adapter } = this.#getStorage(combination);
2603
+ if (await adapter.exists(relativeKey)) {
2604
+ result = combination;
2605
+ break;
2606
+ }
2607
+ }
2608
+ if (!result) try {
2609
+ result = await (0, __stryke_fs_resolve.resolve)(path, {
2610
+ ...options,
2611
+ paths
2612
+ });
2613
+ } catch {}
2614
+ }
2615
+ if (result && !this.#context.config.skipCache) this.resolverCache.set(resolverCacheKey, result);
2616
+ return result;
2617
+ }
2618
+ /**
2619
+ * A synchronous helper function to resolve modules using the Jiti resolver
2620
+ *
2621
+ * @remarks
2622
+ * This function can be used to resolve modules relative to the project root directory.
2623
+ *
2624
+ * @example
2625
+ * ```ts
2626
+ * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
2627
+ * ```
2628
+ *
2629
+ * @param id - The module to resolve.
2630
+ * @param importer - An optional path to the importer module.
2631
+ * @param options - Additional resolution options.
2632
+ * @returns The resolved module path.
2633
+ */
2634
+ resolveSync(id, importer, options = {}) {
2635
+ let path = id;
2636
+ if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
2637
+ if (options.skipAlias !== true) path = this.resolveAlias(path);
2638
+ if ((0, __stryke_path_is_type.isAbsolutePath)(path)) return path;
2639
+ let result;
2640
+ if (!this.#context.config.skipCache) {
2641
+ result = this.resolverCache.get(this.#normalizeId(path));
2642
+ if (result) return result;
2643
+ }
2644
+ result = this.paths[this.#normalizeId(path)];
2645
+ if (!result) {
2646
+ const paths = options.paths ?? [];
2647
+ if (importer && !paths.includes(importer)) paths.push(importer);
2648
+ paths.push(this.#context.workspaceConfig.workspaceRoot);
2649
+ paths.push((0, __stryke_path_append.appendPath)(this.#context.config.root, this.#context.workspaceConfig.workspaceRoot));
2650
+ paths.push((0, __stryke_path_append.appendPath)((0, __stryke_path_join.joinPaths)(this.#context.config.root, "src"), this.#context.workspaceConfig.workspaceRoot));
2651
+ paths.push(...Object.keys(this.#context.tsconfig?.options?.paths ?? {}).filter((tsconfigPath) => path.startsWith(tsconfigPath.replace(/\*$/, ""))).map((tsconfigPath) => this.#context.tsconfig?.options?.paths?.[tsconfigPath]).flat().filter(Boolean).map((tsconfigPath) => (0, __stryke_path_append.appendPath)(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)));
2652
+ for (const combination of (0, __stryke_fs_resolve.getResolutionCombinations)(path, { paths })) {
2653
+ const { relativeKey, adapter } = this.#getStorage(combination);
2654
+ if (adapter.existsSync(relativeKey)) {
2655
+ result = combination;
2656
+ break;
2657
+ }
2658
+ }
2659
+ if (!result) try {
2660
+ result = (0, __stryke_fs_resolve.resolveSync)(path, {
2661
+ ...options,
2662
+ paths
2663
+ });
2664
+ } catch {}
2665
+ }
2666
+ if (result && !this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
2667
+ return result;
2668
+ }
2669
+ /**
2670
+ * Disposes of the virtual file system (VFS) by saving its state to disk.
2671
+ */
2672
+ async dispose() {
2673
+ if (!this.#isDisposed) {
2674
+ this.#isDisposed = true;
2675
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.DEBUG, "Disposing virtual file system...");
2676
+ await this.remove((0, __stryke_path_join.joinPaths)(this.#context.dataPath, "fs.bin"));
2677
+ const message = new __stryke_capnp.Message();
2678
+ const fs = message.initRoot(FileSystem);
2679
+ const storage = fs._initStorage(Object.keys(this.#paths).length);
2680
+ await Promise.all(Object.values(this.#paths).map(async (path, index) => {
2681
+ const code = await this.read(path);
2682
+ const fd = storage.get(index);
2683
+ fd.path = path;
2684
+ fd.code = code || "";
2685
+ }));
2686
+ const ids = fs._initIds(Object.keys(this.#ids).length);
2687
+ Object.entries(this.#ids).filter(([, id]) => id).forEach(([path, id], index) => {
2688
+ const fileId = ids.get(index);
2689
+ fileId.id = id;
2690
+ fileId.path = path;
2691
+ });
2692
+ const metadata = fs._initMetadata(Object.keys(this.#metadata).length);
2693
+ Object.entries(this.#metadata).filter(([, value]) => value).forEach(([id, value], index) => {
2694
+ const fileMetadata = metadata.get(index);
2695
+ fileMetadata.id = id;
2696
+ fileMetadata.type = value.type;
2697
+ fileMetadata.timestamp = value.timestamp ?? Date.now();
2698
+ if (value.properties) {
2699
+ const props = fileMetadata._initProperties(Object.keys(value.properties).length);
2700
+ Object.entries(value.properties).filter(([, val]) => (0, __stryke_type_checks_is_set_string.isSetString)(val)).forEach(([key, val], index$1) => {
2701
+ const prop = props.get(index$1);
2702
+ prop.key = key;
2703
+ prop.value = val;
2704
+ });
2705
+ }
2706
+ });
2707
+ await (0, __stryke_fs_buffer.writeFileBuffer)((0, __stryke_path_join.joinPaths)(this.#context.dataPath, "fs.bin"), message.toArrayBuffer());
2708
+ if (!this.#context.config.skipCache) this.#resolverCache.save(true);
2709
+ await Promise.all(this.#getStorages().map(async (storage$1) => storage$1.adapter.dispose()));
2710
+ this.#log(__storm_software_config_tools_types.LogLevelLabel.TRACE, "Virtual file system has been disposed.");
2711
+ }
2712
+ }
2713
+ async [Symbol.asyncDispose]() {
2714
+ return this.dispose();
2715
+ }
2716
+ };
2717
+
2718
+ //#endregion
2719
+ //#region ../powerlines/src/context/context.ts
2720
+ const configCache = /* @__PURE__ */ new WeakMap();
2721
+ const envPathCache = /* @__PURE__ */ new WeakMap();
2722
+ (0, undici.setGlobalDispatcher)(new undici.Agent({ keepAliveTimeout: 1e4 }).compose(undici.interceptors.retry({
2723
+ maxRetries: 3,
2724
+ minTimeout: 1e3,
2725
+ maxTimeout: 1e4,
2726
+ timeoutFactor: 2,
2727
+ retryAfter: true
2728
+ })));
2729
+ var PowerlinesContext = class PowerlinesContext {
2730
+ /**
2731
+ * Internal references storage
2732
+ *
2733
+ * @danger
2734
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2735
+ *
2736
+ * @internal
2737
+ */
2738
+ #internal = {};
2739
+ #workspaceConfig;
2740
+ #checksum = null;
2741
+ #buildId = (0, __stryke_unique_id_uuid.uuid)();
2742
+ #releaseId = (0, __stryke_unique_id_uuid.uuid)();
2743
+ #timestamp = Date.now();
2744
+ #fs;
2745
+ #tsconfig;
2746
+ #parserCache;
2747
+ #requestCache;
2748
+ #getConfigProps(config = {}) {
2749
+ return mergeConfig({
2750
+ root: config.root,
2751
+ name: config.name,
2752
+ title: config.title,
2753
+ organization: config.organization,
2754
+ compatibilityDate: (0, compatx.resolveCompatibilityDates)(config.compatibilityDate, "latest"),
2755
+ description: config.description,
2756
+ configFile: config.configFile,
2757
+ projectType: config.projectType,
2758
+ customLogger: config.customLogger,
2759
+ logLevel: config.logLevel,
2760
+ tsconfig: config.tsconfig,
2761
+ tsconfigRaw: config.tsconfigRaw,
2762
+ skipCache: config.skipCache,
2763
+ autoInstall: config.autoInstall,
2764
+ input: config.input,
2765
+ output: config.output,
2766
+ plugins: config.plugins,
2767
+ mode: config.mode,
2768
+ resolve: config.resolve,
2769
+ framework: config.framework,
2770
+ ...config
2771
+ }, { output: config.framework ? {
2772
+ artifactsPath: `.${config.framework ?? "powerlines"}`,
2773
+ dts: (0, __stryke_path_join.joinPaths)(config.root ?? this.config.root, `${config.framework ?? "powerlines"}.d.ts`)
2774
+ } : {} });
2775
+ }
2776
+ /**
2777
+ * Create a new Storm context from the workspace root and user config.
2778
+ *
2779
+ * @param workspaceRoot - The root directory of the workspace.
2780
+ * @param config - The user configuration options.
2781
+ * @returns A promise that resolves to the new context.
2782
+ */
2783
+ static async from(workspaceRoot, config) {
2784
+ const context = new PowerlinesContext(await require_config.loadWorkspaceConfig(workspaceRoot, config.root));
2785
+ await context.withUserConfig(config);
2786
+ const powerlinesPath = await (0, __stryke_fs_resolve.resolvePackage)("powerlines");
2787
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2788
+ context.powerlinesPath = powerlinesPath;
2789
+ return context;
2790
+ }
2791
+ /**
2792
+ * An object containing the dependencies that should be installed for the project
2793
+ */
2794
+ dependencies = {};
2795
+ /**
2796
+ * An object containing the development dependencies that should be installed for the project
2797
+ */
2798
+ devDependencies = {};
2799
+ /**
2800
+ * The persisted meta information about the current build
2801
+ */
2802
+ persistedMeta = void 0;
2803
+ /**
2804
+ * The path to the Powerlines package
2805
+ */
2806
+ powerlinesPath;
2807
+ /**
2808
+ * The parsed `package.json` file for the project
2809
+ */
2810
+ packageJson;
2811
+ /**
2812
+ * The parsed `project.json` file for the project
2813
+ */
2814
+ projectJson = void 0;
2815
+ /**
2816
+ * The module resolver for the project
2817
+ */
2818
+ resolver;
2819
+ /**
2820
+ * The resolved configuration options
2821
+ */
2822
+ resolvePatterns = [];
2823
+ /**
2824
+ * Internal context fields and methods
2825
+ *
2826
+ * @danger
2827
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2828
+ *
2829
+ * @internal
2830
+ */
2831
+ get $$internal() {
2832
+ return this.#internal;
2833
+ }
2834
+ /**
2835
+ * Internal context fields and methods
2836
+ *
2837
+ * @danger
2838
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2839
+ *
2840
+ * @internal
2841
+ */
2842
+ set $$internal(value) {
2843
+ this.#internal = value;
2844
+ }
2845
+ /**
2846
+ * The resolved entry type definitions for the project
2847
+ */
2848
+ get entry() {
2849
+ const entry = this.resolvedEntry;
2850
+ return resolveInputsSync(this, entry && entry.length > 0 ? entry : Array.isArray(this.config.input) || (0, __stryke_type_checks_is_set_object.isSetObject)(this.config.input) && !isTypeDefinition(this.config.input) ? this.config.input : (0, __stryke_convert_to_array.toArray)(this.config.input).flat());
2851
+ }
2852
+ /**
2853
+ * The TypeScript configuration parsed from the tsconfig file
2854
+ */
2855
+ get tsconfig() {
2856
+ if (!this.#tsconfig) this.tsconfig = { tsconfigFilePath: this.config.tsconfig };
2857
+ return this.#tsconfig;
2858
+ }
2859
+ /**
2860
+ * Sets the TypeScript configuration parsed from the tsconfig file
2861
+ */
2862
+ set tsconfig(value) {
2863
+ this.#tsconfig = value;
2864
+ this.resolvePatterns = (0, bundle_require.tsconfigPathsToRegExp)(value?.options?.paths ?? {});
2865
+ }
2866
+ /**
2867
+ * The virtual file system interface for the project
2868
+ */
2869
+ get fs() {
2870
+ if (!this.#fs) this.#fs = VirtualFileSystem.createSync(this);
2871
+ return this.#fs;
2872
+ }
2873
+ /**
2874
+ * Get the checksum of the project's current state
2875
+ */
2876
+ get checksum() {
2877
+ return this.#checksum;
2878
+ }
2879
+ /**
2880
+ * The meta information about the current build
2881
+ */
2882
+ get meta() {
2883
+ return {
2884
+ buildId: this.#buildId,
2885
+ releaseId: this.#releaseId,
2886
+ checksum: this.#checksum,
2887
+ timestamp: this.#timestamp,
2888
+ rootHash: (0, __stryke_hash.murmurhash)({
2889
+ workspaceRoot: this.workspaceConfig?.workspaceRoot,
2890
+ root: this.config?.root
2891
+ }, { maxLength: require_config.ROOT_HASH_LENGTH }),
2892
+ configHash: (0, __stryke_hash.murmurhash)(this.config, { maxLength: require_config.CACHE_HASH_LENGTH })
2893
+ };
2894
+ }
2895
+ /**
2896
+ * The resolved configuration options
2897
+ */
2898
+ get config() {
2899
+ return this.resolvedConfig ?? {};
2900
+ }
2901
+ /**
2902
+ * The logger function
2903
+ */
2904
+ get log() {
2905
+ if (!this.logFn) this.logFn = this.createLog();
2906
+ return this.logFn;
2907
+ }
2908
+ /**
2909
+ * The workspace configuration
2910
+ */
2911
+ get workspaceConfig() {
2912
+ return this.#workspaceConfig;
2913
+ }
2914
+ /**
2915
+ * The environment paths for the project
2916
+ */
2917
+ get envPaths() {
2918
+ if (envPathCache.has({
2919
+ workspaceRoot: this.workspaceConfig.workspaceRoot,
2920
+ framework: this.config?.framework || "powerlines"
2921
+ })) return envPathCache.get({
2922
+ workspaceRoot: this.workspaceConfig.workspaceRoot,
2923
+ framework: this.config?.framework || "powerlines"
2924
+ });
2925
+ const envPaths = (0, __stryke_env_get_env_paths.getEnvPaths)({
2926
+ orgId: "storm-software",
2927
+ appId: this.config?.framework || "powerlines",
2928
+ workspaceRoot: this.workspaceConfig.workspaceRoot
2929
+ });
2930
+ envPathCache.set({
2931
+ workspaceRoot: this.workspaceConfig.workspaceRoot,
2932
+ framework: this.config?.framework || "powerlines"
2933
+ }, envPaths);
2934
+ return envPaths;
2935
+ }
2936
+ /**
2937
+ * Get the path to the artifacts directory for the project
2938
+ */
2939
+ get artifactsPath() {
2940
+ return (0, __stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, this.config.root, this.config.output.artifactsPath);
2941
+ }
2942
+ /**
2943
+ * Get the path to the builtin modules used by the project
2944
+ */
2945
+ get builtinsPath() {
2946
+ return (0, __stryke_path_join.joinPaths)(this.artifactsPath, "builtins");
2947
+ }
2948
+ /**
2949
+ * Get the path to the entry directory for the project
2950
+ */
2951
+ get entryPath() {
2952
+ return (0, __stryke_path_join.joinPaths)(this.artifactsPath, "entry");
2953
+ }
2954
+ /**
2955
+ * Get the path to the data directory for the project
2956
+ */
2957
+ get dataPath() {
2958
+ return (0, __stryke_path_join.joinPaths)(this.envPaths.data, "projects", getPrefixedRootHash(this.config.name, this.meta.rootHash));
2959
+ }
2960
+ /**
2961
+ * Get the path to the cache directory for the project
2962
+ */
2963
+ get cachePath() {
2964
+ return (0, __stryke_path_join.joinPaths)(this.envPaths.cache, "projects", (0, __stryke_hash.murmurhash)({
2965
+ checksum: this.#checksum,
2966
+ config: this.meta.configHash
2967
+ }, { maxLength: require_config.CACHE_HASH_LENGTH }));
2968
+ }
2969
+ /**
2970
+ * Get the path to the generated declaration file for the project
2971
+ */
2972
+ get dtsPath() {
2973
+ return this.config.output.dts ? (0, __stryke_path_append.appendPath)(this.config.output.dts, this.workspaceConfig.workspaceRoot) : (0, __stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, this.config.root, "powerlines.d.ts");
2974
+ }
2975
+ /**
2976
+ * Get the project root relative to the workspace root
2977
+ */
2978
+ get relativeToWorkspaceRoot() {
2979
+ return (0, __stryke_fs_get_workspace_root.relativeToWorkspaceRoot)(this.config.root);
2980
+ }
2981
+ /**
2982
+ * The builtin module id that exist in the Powerlines virtual file system
2983
+ */
2984
+ get builtins() {
2985
+ return Object.values(this.fs.metadata).filter((meta) => meta && meta.type === "builtin").map((meta) => meta?.id).filter(Boolean);
2986
+ }
2987
+ /**
2988
+ * The alias mappings for the project used during module resolution
2989
+ *
2990
+ * @remarks
2991
+ * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.
2992
+ */
2993
+ get alias() {
2994
+ return this.builtins.reduce((ret, id) => {
2995
+ const moduleId = `${this.config?.framework || "powerlines"}:${id.replace(/^.*?:/, "")}`;
2996
+ if (!ret[moduleId]) {
2997
+ const path = this.fs.paths[id];
2998
+ if (path) ret[moduleId] = path;
2999
+ }
3000
+ return ret;
3001
+ }, this.config.resolve.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
3002
+ if (!ret[alias.find.toString()]) ret[alias.find.toString()] = alias.replacement;
3003
+ return ret;
3004
+ }, {}) : this.config.resolve.alias : {});
3005
+ }
3006
+ /**
3007
+ * Gets the parser cache.
3008
+ */
3009
+ get parserCache() {
3010
+ if (!this.#parserCache) this.#parserCache = (0, flat_cache.create)({
3011
+ cacheId: "parser",
3012
+ cacheDir: this.cachePath,
3013
+ ttl: 7200 * 1e3,
3014
+ lruSize: 5e3,
3015
+ persistInterval: 250
3016
+ });
3017
+ return this.#parserCache;
3018
+ }
3019
+ /**
3020
+ * Gets the request cache.
3021
+ */
3022
+ get requestCache() {
3023
+ if (!this.#requestCache) this.#requestCache = (0, flat_cache.create)({
3024
+ cacheId: "http",
3025
+ cacheDir: this.cachePath,
3026
+ ttl: 360 * 60 * 1e3,
3027
+ lruSize: 5e3,
3028
+ persistInterval: 250
3029
+ });
3030
+ return this.#requestCache;
3031
+ }
3032
+ /**
3033
+ * The entry points that exist in the Powerlines virtual file system
3034
+ */
3035
+ get resolvedEntry() {
3036
+ return Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "entry").map(([path, meta]) => {
3037
+ const typeDefinition = { file: path };
3038
+ if (meta.properties) {
3039
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties.file)) typeDefinition.file = meta.properties.file;
3040
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties.name)) typeDefinition.name = meta.properties.name;
3041
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties["input.file"]) || (0, __stryke_type_checks_is_set_string.isSetString)(meta.properties["input.name"])) {
3042
+ typeDefinition.input ??= {};
3043
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties["input.file"])) typeDefinition.input.file = meta.properties["input.file"];
3044
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties["input.name"])) typeDefinition.input.name = meta.properties["input.name"];
3045
+ }
3046
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(meta.properties.output)) typeDefinition.output = meta.properties.output;
3047
+ }
3048
+ return typeDefinition;
3049
+ }).filter(Boolean);
3050
+ }
3051
+ /**
3052
+ * A function to perform HTTP fetch requests
3053
+ *
3054
+ * @remarks
3055
+ * This function uses a caching layer to avoid duplicate requests during the Powerlines process.
3056
+ *
3057
+ * @example
3058
+ * ```ts
3059
+ * const response = await context.fetch("https://api.example.com/data");
3060
+ * const data = await response.json();
3061
+ * ```
3062
+ *
3063
+ * @see https://github.com/nodejs/undici
3064
+ *
3065
+ * @param input - The URL to fetch.
3066
+ * @param options - The fetch request options.
3067
+ * @returns A promise that resolves to a response returned by the fetch.
3068
+ */
3069
+ async fetch(input, options = {}) {
3070
+ const cacheKey = (0, __stryke_hash.murmurhash)({
3071
+ input: input.toString(),
3072
+ options: JSON.stringify(options)
3073
+ });
3074
+ if (!this.config.skipCache && !options.skipCache) {
3075
+ const cached = this.requestCache.get(cacheKey);
3076
+ if (cached) return new undici.Response(cached.body, {
3077
+ status: cached.status,
3078
+ statusText: cached.statusText,
3079
+ headers: cached.headers
3080
+ });
3081
+ }
3082
+ const response = await (0, __stryke_http_fetch.fetchRequest)(input, {
3083
+ timeout: 12e3,
3084
+ ...options
3085
+ });
3086
+ const result = {
3087
+ body: await response.text(),
3088
+ status: response.status,
3089
+ statusText: response.statusText,
3090
+ headers: Object.fromEntries(response.headers.entries())
3091
+ };
3092
+ if (!this.config.skipCache && !options.skipCache) try {
3093
+ this.requestCache.set(cacheKey, result);
3094
+ } catch {}
3095
+ return new undici.Response(result.body, {
3096
+ status: result.status,
3097
+ statusText: result.statusText,
3098
+ headers: result.headers
3099
+ });
3100
+ }
3101
+ /**
3102
+ * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.
3103
+ *
3104
+ * @remarks
3105
+ * This function can be used to parse TypeScript code into an AST for further analysis or transformation.
3106
+ *
3107
+ * @example
3108
+ * ```ts
3109
+ * const ast = context.parse("const x: number = 42;");
3110
+ * ```
3111
+ *
3112
+ * @see https://rollupjs.org/plugin-development/#this-parse
3113
+ * @see https://github.com/oxc/oxc
3114
+ *
3115
+ * @param code - The source code to parse.
3116
+ * @param options - The options to pass to the parser.
3117
+ * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.
3118
+ */
3119
+ async parse(code, options = {}) {
3120
+ const cacheKey = (0, __stryke_hash.murmurhash)({
3121
+ code,
3122
+ options
3123
+ });
3124
+ let result;
3125
+ if (!this.config.skipCache) {
3126
+ result = this.parserCache.get(cacheKey);
3127
+ if (result) return result;
3128
+ }
3129
+ result = await (0, oxc_parser.parse)(`source.${options.lang || "ts"}`, code, {
3130
+ ...options,
3131
+ sourceType: "module",
3132
+ showSemanticErrors: this.config.mode === "development"
3133
+ });
3134
+ if (!this.config.skipCache) this.parserCache.set(cacheKey, result);
3135
+ return result;
3136
+ }
3137
+ /**
3138
+ * A helper function to resolve modules in the Virtual File System
3139
+ *
3140
+ * @remarks
3141
+ * This function can be used to resolve modules relative to the project root directory.
3142
+ *
3143
+ * @example
3144
+ * ```ts
3145
+ * const resolved = await context.resolve("some-module", "/path/to/importer");
3146
+ * ```
3147
+ *
3148
+ * @param id - The module to resolve.
3149
+ * @param importer - An optional path to the importer module.
3150
+ * @param options - Additional resolution options.
3151
+ * @returns A promise that resolves to the resolved module path.
3152
+ */
3153
+ async resolve(id, importer, options = {}) {
3154
+ let moduleId = id;
3155
+ if (this.config.resolve.alias) {
3156
+ if (Array.isArray(this.config.resolve.alias)) {
3157
+ const alias = this.config.resolve.alias.find((a) => (0, bundle_require.match)(moduleId, [a.find]));
3158
+ if (alias) moduleId = alias.replacement;
3159
+ } else if ((0, __stryke_type_checks_is_set_object.isSetObject)(this.config.resolve.alias) && this.config.resolve.alias[id]) moduleId = this.config.resolve.alias[id];
3160
+ }
3161
+ if (this.fs.isVirtual(moduleId)) {
3162
+ const result = await this.fs.resolve(moduleId, importer, {
3163
+ conditions: this.config.resolve.conditions,
3164
+ extensions: this.config.resolve.extensions,
3165
+ ...options
3166
+ });
3167
+ if (!result) return;
3168
+ return {
3169
+ id: result,
3170
+ external: this.config.projectType !== "application"
3171
+ };
3172
+ }
3173
+ if (this.config.resolve.skipNodeModulesBundle) {
3174
+ if ((0, bundle_require.match)(moduleId, this.resolvePatterns) || (0, bundle_require.match)(moduleId, this.config.resolve.noExternal)) return;
3175
+ if ((0, bundle_require.match)(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
3176
+ id: moduleId,
3177
+ external: true
3178
+ };
3179
+ if (!/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)) return {
3180
+ id: moduleId,
3181
+ external: true
3182
+ };
3183
+ } else {
3184
+ if ((0, bundle_require.match)(moduleId, this.config.resolve.noExternal)) return;
3185
+ if ((0, bundle_require.match)(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
3186
+ id: moduleId,
3187
+ external: true
3188
+ };
3189
+ }
3190
+ }
3191
+ /**
3192
+ * A helper function to load modules from the Virtual File System
3193
+ *
3194
+ * @remarks
3195
+ * This function can be used to load modules relative to the project root directory.
3196
+ *
3197
+ * @example
3198
+ * ```ts
3199
+ * const module = await context.load("some-module", "/path/to/importer");
3200
+ * ```
3201
+ *
3202
+ * @param id - The module to load.
3203
+ * @returns A promise that resolves to the loaded module.
3204
+ */
3205
+ async load(id) {
3206
+ const resolvedId = await this.fs.resolve(id);
3207
+ if (!resolvedId) return;
3208
+ const code = await this.fs.read(resolvedId);
3209
+ if (!code) return;
3210
+ return {
3211
+ code,
3212
+ map: null
3213
+ };
3214
+ }
3215
+ /**
3216
+ * Get the builtin virtual files that exist in the Powerlines virtual file system
3217
+ */
3218
+ async getBuiltins() {
3219
+ return Promise.all(Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "builtin").map(async ([id, meta]) => {
3220
+ const code = await this.fs.read(id);
3221
+ const path = this.fs.paths[id];
3222
+ return {
3223
+ ...meta,
3224
+ path,
3225
+ code
3226
+ };
3227
+ }));
3228
+ }
3229
+ /**
3230
+ * Resolves a file and writes it to the VFS if it does not already exist
3231
+ *
3232
+ * @param code - The source code of the file
3233
+ * @param path - The path to write the file to
3234
+ * @param options - Additional options for writing the file
3235
+ */
3236
+ async emit(code, path, options = {}) {
3237
+ const filePath = options.extension ? (0, __stryke_path_file_path_fns.findFileExtensionSafe)(path) ? options.extension.startsWith(".") ? path.replace((0, __stryke_path_file_path_fns.findFileDotExtensionSafe)(path), options.extension) : path.replace((0, __stryke_path_file_path_fns.findFileExtensionSafe)(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : (0, __stryke_path_file_path_fns.findFileExtensionSafe)(path) ? path : `${path}.ts`;
3238
+ if ((0, __stryke_type_checks_is_function.isFunction)(this.emitFile) && options.emitWithBundler) return this.emitFile({
3239
+ needsCodeReference: options.needsCodeReference,
3240
+ originalFileName: options.originalFileName,
3241
+ fileName: filePath,
3242
+ source: code,
3243
+ type: "asset"
3244
+ });
3245
+ return this.fs.write(filePath, code, options);
3246
+ }
3247
+ /**
3248
+ * Synchronously resolves a file and writes it to the VFS if it does not already exist
3249
+ *
3250
+ * @param code - The source code of the file
3251
+ * @param path - The path to write the file to
3252
+ * @param options - Additional options for writing the file
3253
+ */
3254
+ emitSync(code, path, options = {}) {
3255
+ const filePath = options.extension ? (0, __stryke_path_file_path_fns.findFileExtensionSafe)(path) ? options.extension.startsWith(".") ? path.replace((0, __stryke_path_file_path_fns.findFileDotExtensionSafe)(path), options.extension) : path.replace((0, __stryke_path_file_path_fns.findFileExtensionSafe)(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : (0, __stryke_path_file_path_fns.findFileExtensionSafe)(path) ? path : `${path}.ts`;
3256
+ if ((0, __stryke_type_checks_is_function.isFunction)(this.emitFile) && options.emitWithBundler) return this.emitFile({
3257
+ needsCodeReference: options.needsCodeReference,
3258
+ originalFileName: options.originalFileName,
3259
+ fileName: filePath,
3260
+ source: code,
3261
+ type: "asset"
3262
+ });
3263
+ return this.fs.writeSync(filePath, code, options);
3264
+ }
3265
+ /**
3266
+ * Resolves a entry virtual file and writes it to the VFS if it does not already exist
3267
+ *
3268
+ * @param code - The source code of the entry file
3269
+ * @param path - A path to write the entry file to
3270
+ * @param options - Optional write file options
3271
+ */
3272
+ async emitEntry(code, path, options = {}) {
3273
+ return this.emit(code, (0, __stryke_path_append.appendPath)(path, this.entryPath), (0, defu.default)({ meta: {
3274
+ type: "entry",
3275
+ properties: {
3276
+ file: (0, __stryke_path_append.appendPath)(path, this.entryPath),
3277
+ name: options?.name,
3278
+ output: options?.output,
3279
+ "input.file": options?.input?.file,
3280
+ "input.name": options?.input?.name
3281
+ }
3282
+ } }, (0, __stryke_helpers_omit.omit)(options, ["name"])));
3283
+ }
3284
+ /**
3285
+ * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist
3286
+ *
3287
+ * @param code - The source code of the entry file
3288
+ * @param path - A path to write the entry file to
3289
+ * @param options - Optional write file options
3290
+ */
3291
+ emitEntrySync(code, path, options = {}) {
3292
+ return this.emitSync(code, (0, __stryke_path_append.appendPath)(path, this.entryPath), (0, defu.default)({ meta: {
3293
+ type: "entry",
3294
+ properties: {
3295
+ file: (0, __stryke_path_append.appendPath)(path, this.entryPath),
3296
+ name: options?.name,
3297
+ output: options?.output,
3298
+ "input.file": options?.input?.file,
3299
+ "input.name": options?.input?.name
3300
+ }
3301
+ } }, (0, __stryke_helpers_omit.omit)(options, ["name"])));
3302
+ }
3303
+ /**
3304
+ * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
3305
+ *
3306
+ * @param code - The source code of the builtin file
3307
+ * @param id - The unique identifier of the builtin file
3308
+ * @param options - Optional write file options
3309
+ */
3310
+ async emitBuiltin(code, id, options = {}) {
3311
+ if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
3312
+ if (!(0, __stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
3313
+ return this.emit(code, (0, __stryke_path_append.appendPath)(id, this.builtinsPath), (0, defu.default)(options, { meta: {
3314
+ type: "builtin",
3315
+ id
3316
+ } }));
3317
+ }
3318
+ /**
3319
+ * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist
3320
+ *
3321
+ * @param code - The source code of the builtin file
3322
+ * @param id - The unique identifier of the builtin file
3323
+ * @param options - Optional write file options
3324
+ */
3325
+ emitBuiltinSync(code, id, options = {}) {
3326
+ if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
3327
+ if (!(0, __stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
3328
+ return this.emitSync(code, (0, __stryke_path_append.appendPath)(id, this.builtinsPath), (0, defu.default)(options, { meta: {
3329
+ type: "builtin",
3330
+ id
3331
+ } }));
3332
+ }
3333
+ /**
3334
+ * Update the context using a new user configuration options
3335
+ *
3336
+ * @param userConfig - The new user configuration options.
3337
+ */
3338
+ async withUserConfig(userConfig, options = { isHighPriority: true }) {
3339
+ this.mergeUserConfig(userConfig);
3340
+ await this.init(this.config.userConfig, options);
3341
+ }
3342
+ /**
3343
+ * Update the context using a new inline configuration options
3344
+ *
3345
+ * @param inlineConfig - The new inline configuration options.
3346
+ */
3347
+ async withInlineConfig(inlineConfig, options = { isHighPriority: true }) {
3348
+ this.config.inlineConfig = inlineConfig;
3349
+ if (inlineConfig.command === "new") {
3350
+ const workspacePackageJsonPath = (0, __stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, "package.json");
3351
+ if (!(0, __stryke_fs_exists.existsSync)(workspacePackageJsonPath)) throw new Error(`The workspace package.json file could not be found at ${workspacePackageJsonPath}`);
3352
+ this.packageJson = await (0, __stryke_fs_json.readJsonFile)(workspacePackageJsonPath);
3353
+ this.workspaceConfig.repository ??= (0, __stryke_type_checks_is_set_string.isSetString)(this.packageJson?.repository) ? this.packageJson.repository : this.packageJson?.repository?.url;
3354
+ }
3355
+ await this.init(this.config.inlineConfig, options);
3356
+ }
3357
+ /**
3358
+ * A logging function for fatal messages
3359
+ *
3360
+ * @param message - The message to log.
3361
+ */
3362
+ fatal(message) {
3363
+ this.log(__storm_software_config_tools_types.LogLevelLabel.FATAL, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3364
+ }
3365
+ /**
3366
+ * A logging function for error messages
3367
+ *
3368
+ * @param message - The message to log.
3369
+ */
3370
+ error(message) {
3371
+ this.log(__storm_software_config_tools_types.LogLevelLabel.ERROR, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3372
+ }
3373
+ /**
3374
+ * A logging function for warning messages
3375
+ *
3376
+ * @param message - The message to log.
3377
+ */
3378
+ warn(message) {
3379
+ this.log(__storm_software_config_tools_types.LogLevelLabel.WARN, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3380
+ }
3381
+ /**
3382
+ * A logging function for informational messages
3383
+ *
3384
+ * @param message - The message to log.
3385
+ */
3386
+ info(message) {
3387
+ this.log(__storm_software_config_tools_types.LogLevelLabel.INFO, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3388
+ }
3389
+ /**
3390
+ * A logging function for debug messages
3391
+ *
3392
+ * @param message - The message to log.
3393
+ */
3394
+ debug(message) {
3395
+ this.log(__storm_software_config_tools_types.LogLevelLabel.DEBUG, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3396
+ }
3397
+ /**
3398
+ * A logging function for trace messages
3399
+ *
3400
+ * @param message - The message to log.
3401
+ */
3402
+ trace(message) {
3403
+ this.log(__storm_software_config_tools_types.LogLevelLabel.TRACE, (0, __stryke_type_checks_is_string.isString)(message) ? message : __stryke_json_storm_json.StormJSON.stringify(message));
3404
+ }
3405
+ /**
3406
+ * Create a new logger instance
3407
+ *
3408
+ * @param name - The name to use for the logger instance
3409
+ * @returns A logger function
3410
+ */
3411
+ createLog(name = null) {
3412
+ return createLog(name, {
3413
+ ...this.config,
3414
+ logLevel: (0, __stryke_type_checks_is_null.isNull)(this.config.logLevel) ? "silent" : this.config.logLevel
3415
+ });
3416
+ }
3417
+ /**
3418
+ * Extend the current logger instance with a new name
3419
+ *
3420
+ * @param name - The name to use for the extended logger instance
3421
+ * @returns A logger function
3422
+ */
3423
+ extendLog(name) {
3424
+ return extendLog(this.log, name);
3425
+ }
3426
+ /**
3427
+ * Generates a checksum representing the current context state
3428
+ *
3429
+ * @param root - The root directory of the project to generate the checksum for
3430
+ * @returns A promise that resolves to a string representing the checksum
3431
+ */
3432
+ async generateChecksum(root = this.config.root) {
3433
+ this.#checksum = await (0, __stryke_hash_node.hashDirectory)(root, { ignore: [
3434
+ "node_modules",
3435
+ ".git",
3436
+ ".nx",
3437
+ ".cache",
3438
+ "tmp",
3439
+ "dist"
3440
+ ] });
3441
+ return this.#checksum;
3442
+ }
3443
+ /**
3444
+ * Creates a new StormContext instance.
3445
+ *
3446
+ * @param workspaceConfig - The workspace configuration.
3447
+ */
3448
+ constructor(workspaceConfig) {
3449
+ this.#workspaceConfig = workspaceConfig;
3450
+ envPathCache.set({
3451
+ workspaceRoot: workspaceConfig.workspaceRoot,
3452
+ framework: "powerlines"
3453
+ }, (0, __stryke_env_get_env_paths.getEnvPaths)({
3454
+ orgId: ((0, __stryke_type_checks_is_set_object.isSetObject)(workspaceConfig.organization) ? workspaceConfig.organization.name : workspaceConfig.organization) || "storm-software",
3455
+ appId: "powerlines",
3456
+ workspaceRoot: workspaceConfig.workspaceRoot
3457
+ }));
3458
+ }
3459
+ /**
3460
+ * The resolved configuration for this context
3461
+ */
3462
+ resolvedConfig = {};
3463
+ /**
3464
+ * A logger function specific to this context
3465
+ */
3466
+ logFn;
3467
+ /**
3468
+ * Initialize the context with the provided configuration options
3469
+ *
3470
+ * @param config - The partial user configuration to use for initialization.
3471
+ */
3472
+ async init(config = {}, options = { isHighPriority: true }) {
3473
+ const cacheKey = {
3474
+ root: config.root ?? this.config.root ?? this.config.userConfig?.root ?? this.config.inlineConfig?.root,
3475
+ mode: (config.mode ?? this.config.mode) || this.workspaceConfig.mode,
3476
+ skipCache: config.skipCache ?? this.config.skipCache ?? false,
3477
+ configFile: config.configFile ?? this.config.configFile,
3478
+ framework: config.framework ?? this.config.framework ?? "powerlines",
3479
+ command: this.config.inlineConfig?.command,
3480
+ alias: this.config.resolve?.alias ?? config.resolve?.alias
3481
+ };
3482
+ if (configCache.has(cacheKey)) {
3483
+ const result = configCache.get(cacheKey);
3484
+ this.projectJson = result.projectJson;
3485
+ this.packageJson = result.packageJson;
3486
+ this.#checksum = result.checksum;
3487
+ this.resolver = result.resolver;
3488
+ this.mergeUserConfig(result.userConfig.config, this.config.userConfig);
3489
+ } else {
3490
+ const projectJsonPath = (0, __stryke_path_join.joinPaths)(cacheKey.root, "project.json");
3491
+ if ((0, __stryke_fs_exists.existsSync)(projectJsonPath)) this.projectJson = await (0, __stryke_fs_json.readJsonFile)(projectJsonPath);
3492
+ const packageJsonPath = (0, __stryke_path_join.joinPaths)(cacheKey.root, "package.json");
3493
+ if ((0, __stryke_fs_exists.existsSync)(packageJsonPath)) this.packageJson = await (0, __stryke_fs_json.readJsonFile)(packageJsonPath);
3494
+ this.#checksum = await this.generateChecksum(cacheKey.root);
3495
+ this.resolver = createResolver({
3496
+ workspaceRoot: this.workspaceConfig.workspaceRoot,
3497
+ root: cacheKey.root,
3498
+ cacheDir: this.cachePath,
3499
+ mode: cacheKey.mode,
3500
+ logLevel: config.logLevel || this.config.logLevel || this.workspaceConfig.logLevel || "info",
3501
+ skipCache: cacheKey.skipCache,
3502
+ alias: this.config.resolve?.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
3503
+ ret[alias.find.toString()] = alias.replacement;
3504
+ return ret;
3505
+ }, {}) : this.config.resolve.alias : {}
3506
+ });
3507
+ const userConfig = await require_config.loadUserConfigFile(cacheKey.root, this.workspaceConfig.workspaceRoot, this.resolver, cacheKey.command, cacheKey.mode, cacheKey.configFile, cacheKey.framework);
3508
+ this.mergeUserConfig(userConfig.config);
3509
+ configCache.set(cacheKey, {
3510
+ projectJson: this.projectJson,
3511
+ packageJson: this.packageJson,
3512
+ checksum: this.#checksum,
3513
+ resolver: this.resolver,
3514
+ userConfig
3515
+ });
3516
+ }
3517
+ config.tsconfig ??= getTsconfigFilePath(this.workspaceConfig.workspaceRoot, cacheKey.root, config.tsconfig);
3518
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(config)) this.resolvedConfig = mergeConfig({
3519
+ inlineConfig: this.config.inlineConfig,
3520
+ userConfig: this.config.userConfig
3521
+ }, options.isHighPriority ? this.#getConfigProps(config) : {}, {
3522
+ ...this.#getConfigProps(this.config.inlineConfig),
3523
+ command: this.config.inlineConfig?.command
3524
+ }, this.#getConfigProps(this.config.userConfig), {
3525
+ mode: this.workspaceConfig?.mode,
3526
+ logLevel: this.workspaceConfig?.logLevel,
3527
+ skipCache: this.workspaceConfig?.skipCache
3528
+ }, {
3529
+ name: this.projectJson?.name || this.packageJson?.name,
3530
+ version: this.packageJson?.version,
3531
+ description: this.packageJson?.description,
3532
+ output: mergeConfig(config.output ?? {}, {
3533
+ outputPath: cacheKey.root ? (0, __stryke_path_join.joinPaths)(this.workspaceConfig?.directories?.build || "dist", cacheKey.root) : this.workspaceConfig?.directories?.build || "dist",
3534
+ artifactsPath: `.${config.framework ?? "powerlines"}`,
3535
+ dts: (0, __stryke_path_join.joinPaths)(cacheKey.root, `${config.framework ?? "powerlines"}.d.ts`),
3536
+ assets: [
3537
+ { glob: "LICENSE" },
3538
+ {
3539
+ input: cacheKey.root,
3540
+ glob: "*.md"
3541
+ },
3542
+ {
3543
+ input: cacheKey.root,
3544
+ glob: "package.json"
3545
+ }
3546
+ ]
3547
+ })
3548
+ }, options.isHighPriority ? {} : this.#getConfigProps(config), {
3549
+ inlineConfig: {},
3550
+ userConfig: {},
3551
+ framework: "powerlines",
3552
+ mode: "production",
3553
+ projectType: "application",
3554
+ platform: "neutral",
3555
+ logLevel: "info",
3556
+ preview: false,
3557
+ environments: {},
3558
+ resolve: {}
3559
+ });
3560
+ this.config.input = getUniqueInputs(this.config.input);
3561
+ if (this.config.name?.startsWith("@") && this.config.name.split("/").filter(Boolean).length > 1) this.config.name = this.config.name.split("/").filter(Boolean)[1];
3562
+ this.config.title ??= (0, __stryke_string_format_title_case.titleCase)(this.config.name);
3563
+ this.config.organization ??= ((0, __stryke_type_checks_is_set_object.isSetObject)(this.workspaceConfig.organization) ? this.workspaceConfig.organization.name : this.workspaceConfig.organization) || ((0, __stryke_type_checks_is_set_object.isSetObject)(this.packageJson?.author) ? this.packageJson?.author?.name : this.packageJson?.author) || this.config.name;
3564
+ if (this.config.userConfig.resolve?.external) this.config.userConfig.resolve.external = (0, __stryke_helpers_get_unique.getUnique)(this.config.userConfig.resolve.external);
3565
+ if (this.config.userConfig.resolve?.noExternal) this.config.userConfig.resolve.noExternal = (0, __stryke_helpers_get_unique.getUnique)(this.config.userConfig.resolve.noExternal);
3566
+ if (this.config.resolve.external) this.config.resolve.external = (0, __stryke_helpers_get_unique.getUnique)(this.config.resolve.external);
3567
+ if (this.config.resolve.noExternal) this.config.resolve.noExternal = (0, __stryke_helpers_get_unique.getUnique)(this.config.resolve.noExternal);
3568
+ this.config.output.format = (0, __stryke_helpers_get_unique.getUnique)((0, __stryke_convert_to_array.toArray)(this.config.output?.format ?? (this.config.projectType === "library" ? ["cjs", "esm"] : ["esm"])));
3569
+ if (this.config.root && this.config.root !== "." && this.config.root !== "./" && this.config.root !== this.workspaceConfig.workspaceRoot) {
3570
+ this.config.output.outputPath ??= (0, __stryke_path_join.joinPaths)("dist", this.config.root);
3571
+ this.config.output.buildPath ??= (0, __stryke_path_join.joinPaths)(this.config.root, "dist");
3572
+ } else {
3573
+ this.config.output.outputPath ??= "dist";
3574
+ this.config.output.buildPath ??= "dist";
3575
+ }
3576
+ this.config.output.assets = (0, __stryke_helpers_get_unique.getUniqueBy)(this.config.output.assets.map((asset) => {
3577
+ return {
3578
+ glob: (0, __stryke_type_checks_is_set_object.isSetObject)(asset) ? asset.glob : asset,
3579
+ input: (0, __stryke_type_checks_is_string.isString)(asset) || !asset.input || asset.input === "." || asset.input === "/" || asset.input === "./" ? this.workspaceConfig.workspaceRoot : (0, __stryke_path_is_parent_path.isParentPath)(asset.input, this.workspaceConfig.workspaceRoot) || asset.input === this.workspaceConfig.workspaceRoot ? asset.input : (0, __stryke_path_append.appendPath)(asset.input, this.workspaceConfig.workspaceRoot),
3580
+ output: (0, __stryke_type_checks_is_set_object.isSetObject)(asset) && asset.output ? (0, __stryke_path_is_parent_path.isParentPath)(asset.output, this.workspaceConfig.workspaceRoot) ? asset.output : (0, __stryke_path_append.appendPath)((0, __stryke_path_join.joinPaths)(this.config.output.outputPath, (0, __stryke_path_replace.replacePath)((0, __stryke_path_replace.replacePath)(asset.output, (0, __stryke_path_replace.replacePath)(this.config.output.outputPath, this.workspaceConfig.workspaceRoot)), this.config.output.outputPath)), this.workspaceConfig.workspaceRoot) : (0, __stryke_path_append.appendPath)(this.config.output.outputPath, this.workspaceConfig.workspaceRoot),
3581
+ ignore: (0, __stryke_type_checks_is_set_object.isSetObject)(asset) && asset.ignore ? (0, __stryke_convert_to_array.toArray)(asset.ignore) : void 0
3582
+ };
3583
+ }), (a) => `${a.input}-${a.glob}-${a.output}`);
3584
+ this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
3585
+ if (isPlugin(plugin) && checkDedupe(plugin, ret.filter((p) => isPlugin(p)))) return ret;
3586
+ ret.push(plugin);
3587
+ return ret;
3588
+ }, []);
3589
+ if (this.config.tsconfig) this.config.tsconfig = replacePathTokens(this, this.config.tsconfig);
3590
+ if (this.config.output.dts) if ((0, __stryke_type_checks_is_set_string.isSetString)(this.config.output.dts)) this.config.output.dts = replacePathTokens(this, this.config.output.dts);
3591
+ else this.config.output.dts = (0, __stryke_path_join.joinPaths)(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`);
3592
+ if (this.config.output.assets) this.config.output.assets = this.config.output.assets.map((asset) => ({
3593
+ ...asset,
3594
+ glob: replacePathTokens(this, asset.glob),
3595
+ ignore: asset.ignore ? asset.ignore.map((ignore) => replacePathTokens(this, ignore)) : void 0,
3596
+ input: replacePathTokens(this, asset.input),
3597
+ output: replacePathTokens(this, asset.output)
3598
+ }));
3599
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(config.output?.storage) && config.output.storage === "virtual" || (0, __stryke_type_checks_is_set_object.isSetObject)(config.output?.storage) && Object.values(config.output.storage).every((adapter) => adapter.preset === "virtual")) this.config.output.overwrite = true;
3600
+ this.#fs ??= await VirtualFileSystem.create(this);
3601
+ }
3602
+ mergeUserConfig(from = {}, into = this.config.userConfig ?? {}) {
3603
+ this.config.userConfig = mergeConfig({ input: (0, __stryke_type_checks_is_set_object.isSetObject)(from.input) && !(0, __stryke_type_checks_is_regexp.isRegExp)(from.input) && !Array.isArray(from.input) && from.input.file ? from.input.file : (0, __stryke_type_checks_is_set_object.isSetObject)(into?.input) && !(0, __stryke_type_checks_is_regexp.isRegExp)(into.input) && !Array.isArray(into.input) && into.input.file ? into.input.file : Array.isArray(from.input) && from.input.length > 0 ? from.input : Array.isArray(into?.input) && into.input.length > 0 ? into.input : [] }, (0, __stryke_helpers_omit.omit)(from ?? {}, ["input"]), (0, __stryke_helpers_omit.omit)(into ?? {}, ["input"]));
3604
+ if (this.config.userConfig.output?.format) this.config.userConfig.output.format = (0, __stryke_helpers_get_unique.getUnique)((0, __stryke_convert_to_array.toArray)(this.config.userConfig.output?.format));
3605
+ this.config.userConfig.plugins = (this.config.userConfig.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
3606
+ if (isPlugin(plugin) && checkDedupe(plugin, ret.filter((p) => isPlugin(p)))) return ret;
3607
+ ret.push(plugin);
3608
+ return ret;
3609
+ }, []);
3610
+ }
3611
+ };
3612
+
3613
+ //#endregion
3614
+ //#region ../core/src/lib/unplugin/helpers.ts
3615
+ /**
3616
+ * Checks if a value is a valid UnpluginBuilderVariant.
3617
+ *
3618
+ * @param str - The value to check.
3619
+ * @returns True if the value is a UnpluginBuilderVariant, false otherwise.
3620
+ */
3621
+ function isUnpluginBuilderVariant(str) {
3622
+ return (0, __stryke_type_checks_is_set_string.isSetString)(str) && require_config.UNPLUGIN_BUILDER_VARIANTS.includes(str);
3623
+ }
3624
+
3625
+ //#endregion
3626
+ //#region ../powerlines/src/context/plugin-context.ts
3627
+ /**
3628
+ * Create a Proxy-based PluginContext
3629
+ *
3630
+ * @param plugin - The plugin instance
3631
+ * @param environment - The environment context
3632
+ * @returns The proxied plugin context
3633
+ */
3634
+ function createPluginContext(plugin, environment) {
3635
+ const normalizeMessage = (message) => {
3636
+ return (0, __stryke_type_checks_is_string.isString)(message) ? message : message.message;
3637
+ };
3638
+ const log = environment.extendLog(plugin.name.replaceAll(":", " - "));
3639
+ const callHookFn = async (hook, options, ...args) => {
3640
+ return environment.$$internal.api.callHook(hook, {
3641
+ sequential: true,
3642
+ result: "merge",
3643
+ ...options,
3644
+ environment
3645
+ }, ...args);
3646
+ };
3647
+ const meta = {};
3648
+ return new Proxy({}, {
3649
+ get(_, prop) {
3650
+ if (prop === "$$internal") return {
3651
+ ...environment.$$internal,
3652
+ environment,
3653
+ callHook: callHookFn,
3654
+ meta
3655
+ };
3656
+ if (prop === "log" || prop === "logger") return log;
3657
+ if (prop === "fatal") return (message) => {
3658
+ log(__storm_software_config_tools_types.LogLevelLabel.FATAL, normalizeMessage(message));
3659
+ };
3660
+ if (prop === "error") return (message) => {
3661
+ log(__storm_software_config_tools_types.LogLevelLabel.ERROR, normalizeMessage(message));
3662
+ };
3663
+ if (prop === "warn") return (message) => {
3664
+ log(__storm_software_config_tools_types.LogLevelLabel.WARN, normalizeMessage(message));
3665
+ };
3666
+ if (prop === "info") return (message) => {
3667
+ log(__storm_software_config_tools_types.LogLevelLabel.INFO, normalizeMessage(message));
3668
+ };
3669
+ if (prop === "debug") return (message) => {
3670
+ log(__storm_software_config_tools_types.LogLevelLabel.DEBUG, normalizeMessage(message));
3671
+ };
3672
+ if (prop === "trace") return (message) => {
3673
+ log(__storm_software_config_tools_types.LogLevelLabel.TRACE, normalizeMessage(message));
3674
+ };
3675
+ return environment[prop];
3676
+ },
3677
+ set(_, prop, value) {
3678
+ if ([
3679
+ "$$internal",
3680
+ "environment",
3681
+ "config",
3682
+ "log",
3683
+ "logger",
3684
+ "error",
3685
+ "warn",
3686
+ "plugins",
3687
+ "hooks",
3688
+ "addPlugin",
3689
+ "selectHooks"
3690
+ ].includes(prop)) {
3691
+ log(__storm_software_config_tools_types.LogLevelLabel.WARN, `Cannot set read-only property "${String(prop)}"`);
3692
+ return false;
3693
+ }
3694
+ environment[prop] = value;
3695
+ return true;
3696
+ }
3697
+ });
3698
+ }
3699
+
3700
+ //#endregion
3701
+ //#region ../powerlines/src/context/environment-context.ts
3702
+ var PowerlinesEnvironmentContext = class PowerlinesEnvironmentContext extends PowerlinesContext {
3703
+ /**
3704
+ * The hooks registered by plugins in this environment
3705
+ */
3706
+ #hooks = {};
3707
+ /**
3708
+ * Create a new Storm context from the workspace root and user config.
3709
+ *
3710
+ * @param workspaceConfig - The root directory of the workspace.
3711
+ * @param config - The user configuration options.
3712
+ * @returns A promise that resolves to the new context.
3713
+ */
3714
+ static async fromConfig(workspaceConfig, config) {
3715
+ const context = new PowerlinesEnvironmentContext(config, workspaceConfig);
3716
+ await context.init();
3717
+ const powerlinesPath = await (0, __stryke_fs_resolve.resolvePackage)("powerlines");
3718
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
3719
+ context.powerlinesPath = powerlinesPath;
3720
+ return context;
3721
+ }
3722
+ /**
3723
+ * The resolved environment configuration
3724
+ */
3725
+ environment;
3726
+ /**
3727
+ * The list of plugins applied to this environment
3728
+ */
3729
+ plugins = [];
3730
+ /**
3731
+ * The resolved configuration options
3732
+ */
3733
+ get config() {
3734
+ return super.config;
3735
+ }
3736
+ get hooks() {
3737
+ return this.#hooks;
3738
+ }
3739
+ async addPlugin(plugin) {
3740
+ let resolvedPlugin = plugin;
3741
+ if ((0, __stryke_type_checks_is_function.isFunction)(plugin.applyToEnvironment)) {
3742
+ const result = await Promise.resolve(plugin.applyToEnvironment(this.environment));
3743
+ if (!result || (0, __stryke_type_checks_is_object.isObject)(result) && Object.keys(result).length === 0) return;
3744
+ if (isPluginConfig(result)) return this.$$internal.addPlugin(result);
3745
+ resolvedPlugin = isPlugin(result) ? result : plugin;
3746
+ }
3747
+ const context = createPluginContext(resolvedPlugin, this);
3748
+ this.plugins.push({
3749
+ plugin: resolvedPlugin,
3750
+ context
3751
+ });
3752
+ this.#hooks = Object.keys(resolvedPlugin).filter((key) => !require_config.PLUGIN_NON_HOOK_FIELDS.includes(key)).reduce((ret, key) => {
3753
+ const hook = key;
3754
+ if (isPluginHookField(hook)) {
3755
+ const pluginHook = resolvedPlugin[hook];
3756
+ if (!isPluginHook(pluginHook)) return ret;
3757
+ ret[hook] ??= {
3758
+ preEnforced: [],
3759
+ preOrdered: [],
3760
+ normal: [],
3761
+ postEnforced: [],
3762
+ postOrdered: []
3763
+ };
3764
+ if (resolvedPlugin.enforce) {
3765
+ const hookListOrder$1 = `${resolvedPlugin.enforce}Enforced`;
3766
+ ret[hook][hookListOrder$1] ??= [];
3767
+ const bucket = ret[hook][hookListOrder$1];
3768
+ addPluginHook(context, resolvedPlugin, pluginHook, bucket);
3769
+ return ret;
3770
+ }
3771
+ if ((0, __stryke_type_checks_is_function.isFunction)(pluginHook) || !pluginHook.order) {
3772
+ ret[hook].normal ??= [];
3773
+ const bucket = ret[hook].normal;
3774
+ addPluginHook(context, resolvedPlugin, pluginHook, bucket);
3775
+ return ret;
3776
+ }
3777
+ const hookListOrder = `${pluginHook.order}Ordered`;
3778
+ ret[hook][hookListOrder] ??= [];
3779
+ addPluginHook(context, resolvedPlugin, pluginHook, ret[hook][hookListOrder]);
3780
+ return ret;
3781
+ } else if (isUnpluginHookField(hook)) {
3782
+ const unpluginPlugin = resolvedPlugin[hook];
3783
+ if (!(0, __stryke_type_checks_is_set_object.isSetObject)(unpluginPlugin)) return ret;
3784
+ for (const field of Object.keys(unpluginPlugin)) {
3785
+ const variantField = field;
3786
+ const pluginHook = unpluginPlugin[variantField];
3787
+ if (!isPluginHook(pluginHook)) continue;
3788
+ ret[hook] ??= {};
3789
+ ret[hook][variantField] ??= {
3790
+ preEnforced: [],
3791
+ preOrdered: [],
3792
+ normal: [],
3793
+ postEnforced: [],
3794
+ postOrdered: []
3795
+ };
3796
+ if (resolvedPlugin.enforce) {
3797
+ addPluginHook(context, resolvedPlugin, pluginHook, ret[hook][variantField][`${resolvedPlugin.enforce}Enforced`]);
3798
+ return ret;
3799
+ }
3800
+ if ((0, __stryke_type_checks_is_function.isFunction)(pluginHook) || !pluginHook.order) {
3801
+ addPluginHook(context, resolvedPlugin, pluginHook, ret[hook][variantField].normal);
3802
+ return ret;
3803
+ }
3804
+ addPluginHook(context, resolvedPlugin, pluginHook, ret[hook][variantField][`${pluginHook.order}Ordered`]);
3805
+ }
3806
+ } else this.warn(`Unknown plugin hook field: ${String(hook)}`);
3807
+ return ret;
3808
+ }, this.hooks);
3809
+ }
3810
+ /**
3811
+ * Retrieves the hook handlers for a specific hook name
3812
+ */
3813
+ selectHooks(key, options) {
3814
+ const result = [];
3815
+ if (isUnpluginHookKey(key)) {
3816
+ const variant = String(key).split(":")[0];
3817
+ if (isUnpluginBuilderVariant(variant)) {
3818
+ const hooks = this.hooks[variant];
3819
+ if (hooks) {
3820
+ const field = String(key).split(":")[1];
3821
+ if (field && hooks[field]) {
3822
+ const fieldHooks = hooks[field];
3823
+ if (options?.order) {
3824
+ const mapHooksToResult = (hooksList) => hooksList.map((hook) => {
3825
+ const plugin = this.plugins.find((p) => p.plugin.name === hook.plugin.name);
3826
+ if (!plugin) throw new Error(`Could not find plugin context for plugin "${hook.plugin.name}".`);
3827
+ return {
3828
+ handler: hook.handler,
3829
+ plugin: hook.plugin,
3830
+ context: plugin.context
3831
+ };
3832
+ });
3833
+ if (options?.order === "pre") {
3834
+ result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));
3835
+ result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));
3836
+ } else if (options?.order === "post") {
3837
+ result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));
3838
+ result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));
3839
+ } else result.push(...mapHooksToResult(fieldHooks.normal ?? []));
3840
+ } else {
3841
+ result.push(...this.selectHooks(key, { order: "pre" }));
3842
+ result.push(...this.selectHooks(key, { order: "normal" }));
3843
+ result.push(...this.selectHooks(key, { order: "post" }));
3844
+ }
3845
+ }
3846
+ }
3847
+ }
3848
+ } else if (isPluginHookField(key)) {
3849
+ if (this.hooks[key]) {
3850
+ const fieldHooks = this.hooks[key];
3851
+ if (options?.order) {
3852
+ const mapHooksToResult = (hooksList) => hooksList.map((hook) => {
3853
+ const plugin = this.plugins.find((p) => p.plugin.name === hook.plugin.name);
3854
+ if (!plugin) throw new Error(`Could not find plugin context for plugin "${hook.plugin.name}".`);
3855
+ return {
3856
+ handler: hook.handler,
3857
+ plugin: hook.plugin,
3858
+ context: plugin.context
3859
+ };
3860
+ });
3861
+ if (options?.order === "pre") {
3862
+ result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));
3863
+ result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));
3864
+ } else if (options?.order === "post") {
3865
+ result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));
3866
+ result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));
3867
+ } else result.push(...mapHooksToResult(fieldHooks.normal ?? []));
3868
+ } else {
3869
+ result.push(...this.selectHooks(key, { order: "pre" }));
3870
+ result.push(...this.selectHooks(key, { order: "normal" }));
3871
+ result.push(...this.selectHooks(key, { order: "post" }));
3872
+ }
3873
+ }
3874
+ } else throw new Error(`Unknown plugin hook key: ${String(key)}`);
3875
+ return result;
3876
+ }
3877
+ constructor(config, workspaceConfig) {
3878
+ super(workspaceConfig);
3879
+ this.resolvedConfig = config;
3880
+ }
3881
+ };
3882
+
3883
+ //#endregion
3884
+ //#region ../powerlines/src/context/api-context.ts
3885
+ var PowerlinesAPIContext = class PowerlinesAPIContext extends PowerlinesContext {
3886
+ #environments = {};
3887
+ #plugins = [];
3888
+ #log;
3889
+ /**
3890
+ * Create a new Storm context from the workspace root and user config.
3891
+ *
3892
+ * @param workspaceRoot - The root directory of the workspace.
3893
+ * @param config - The user configuration options.
3894
+ * @returns A promise that resolves to the new context.
3895
+ */
3896
+ static async from(workspaceRoot, config) {
3897
+ const context = new PowerlinesAPIContext(await require_config.loadWorkspaceConfig(workspaceRoot, config.root));
3898
+ await context.withUserConfig(config);
3899
+ const powerlinesPath = await (0, __stryke_fs_resolve.resolvePackage)("powerlines");
3900
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
3901
+ context.powerlinesPath = powerlinesPath;
3902
+ return context;
3903
+ }
3904
+ /**
3905
+ * Internal context fields and methods
3906
+ *
3907
+ * @danger
3908
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
3909
+ *
3910
+ * @internal
3911
+ */
3912
+ get $$internal() {
3913
+ return super.$$internal;
3914
+ }
3915
+ /**
3916
+ * Internal context fields and methods
3917
+ *
3918
+ * @danger
3919
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
3920
+ *
3921
+ * @internal
3922
+ */
3923
+ set $$internal(value) {
3924
+ super.$$internal = value;
3925
+ for (const environment of Object.values(this.environments)) environment.$$internal = super.$$internal;
3926
+ }
3927
+ /**
3928
+ * A record of all environments by name
3929
+ */
3930
+ get environments() {
3931
+ return this.#environments;
3932
+ }
3933
+ get log() {
3934
+ if (!this.#log) this.#log = this.createLog();
3935
+ return this.#log;
3936
+ }
3937
+ get plugins() {
3938
+ return this.#plugins;
3939
+ }
3940
+ constructor(workspaceConfig) {
3941
+ super(workspaceConfig);
3942
+ }
3943
+ /**
3944
+ * Initialize the context with the provided configuration options
3945
+ *
3946
+ * @param config - The partial user configuration to use for initialization.
3947
+ */
3948
+ async init(config = {}) {
3949
+ await super.init(config);
3950
+ await Promise.all((0, __stryke_convert_to_array.toArray)(this.config.userConfig.environments && Object.keys(this.config.userConfig.environments).length > 0 ? Object.keys(this.config.userConfig.environments).map((name) => createEnvironment(name, this.config.userConfig)) : createDefaultEnvironment(this.config.userConfig)).map(async (env) => {
3951
+ this.#environments[env.name] = await this.in(env);
3952
+ }));
3953
+ }
3954
+ /**
3955
+ * A function to copy the context and update the fields for a specific environment
3956
+ *
3957
+ * @param environment - The environment configuration to use.
3958
+ * @returns A new context instance with the updated environment.
3959
+ */
3960
+ async in(environment) {
3961
+ let context;
3962
+ if (this.environments[environment.name]) context = this.environments[environment.name];
3963
+ else context = await PowerlinesEnvironmentContext.fromConfig(this.workspaceConfig, this.config);
3964
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(this.config.inlineConfig)) await context.withInlineConfig(this.config.inlineConfig);
3965
+ context.environment = environment;
3966
+ context.plugins = [];
3967
+ for (const plugin of this.plugins) await context.addPlugin(plugin);
3968
+ return context;
3969
+ }
3970
+ /**
3971
+ * Update the context using a new user configuration options
3972
+ *
3973
+ * @param userConfig - The new user configuration options.
3974
+ */
3975
+ async withUserConfig(userConfig, options = { isHighPriority: true }) {
3976
+ await super.withUserConfig(userConfig, options);
3977
+ await Promise.all(Object.keys(this.#environments).map(async (name) => {
3978
+ await this.#environments[name].withUserConfig(userConfig, options);
3979
+ }));
3980
+ }
3981
+ /**
3982
+ * Update the context using a new inline configuration options
3983
+ *
3984
+ * @param inlineConfig - The new inline configuration options.
3985
+ */
3986
+ async withInlineConfig(inlineConfig, options = { isHighPriority: true }) {
3987
+ await super.withInlineConfig(inlineConfig, options);
3988
+ await Promise.all(Object.keys(this.#environments).map(async (name) => {
3989
+ await this.#environments[name].withInlineConfig(inlineConfig, options);
3990
+ }));
3991
+ }
3992
+ /**
3993
+ * Add a plugin to the API context and all environments
3994
+ *
3995
+ * @param plugin - The plugin to add.
3996
+ */
3997
+ async addPlugin(plugin) {
3998
+ this.plugins.push(plugin);
3999
+ await Promise.all(Object.keys(this.environments).map(async (name) => {
4000
+ await this.environments[name].addPlugin(plugin);
4001
+ }));
4002
+ }
4003
+ /**
4004
+ * Get an environment by name, or the default environment if no name is provided
4005
+ *
4006
+ * @param name - The name of the environment to retrieve.
4007
+ * @returns The requested environment context.
4008
+ */
4009
+ async getEnvironment(name) {
4010
+ let environment;
4011
+ if (name) environment = this.environments[name];
4012
+ if (Object.keys(this.environments).length === 1) {
4013
+ environment = this.environments[Object.keys(this.environments)[0]];
4014
+ this.debug(`Applying the only configured environment: ${chalk.default.bold.cyanBright(environment?.environment.name)}`);
4015
+ }
4016
+ if (!environment) {
4017
+ if (name) throw new Error(`Environment "${name}" not found.`);
4018
+ environment = await this.in(createDefaultEnvironment(this.config.userConfig));
4019
+ this.warn(`No environment specified, and no default environment found. Using a temporary default environment: ${chalk.default.bold.cyanBright(environment?.environment.name)}`);
4020
+ }
4021
+ return environment;
4022
+ }
4023
+ /**
4024
+ * A safe version of `getEnvironment` that returns `undefined` if the environment is not found
4025
+ *
4026
+ * @param name - The name of the environment to retrieve.
4027
+ * @returns The requested environment context or `undefined` if not found.
4028
+ */
4029
+ async getEnvironmentSafe(name) {
4030
+ try {
4031
+ return await this.getEnvironment(name);
4032
+ } catch {
4033
+ return;
4034
+ }
4035
+ }
4036
+ /**
4037
+ * A function to merge all configured environments into a single context.
4038
+ *
4039
+ * @remarks
4040
+ * If only one environment is configured, that environment will be returned directly.
4041
+ *
4042
+ * @returns A promise that resolves to a merged/global environment context.
4043
+ */
4044
+ async toEnvironment() {
4045
+ let environment;
4046
+ if (Object.keys(this.environments).length > 1) {
4047
+ environment = await this.in(createEnvironment(require_config.GLOBAL_ENVIRONMENT, this.config.userConfig));
4048
+ this.debug(`Combined all ${Object.keys(this.environments).length} environments into a single global context.`);
4049
+ } else environment = await this.getEnvironment();
4050
+ return environment;
4051
+ }
4052
+ };
4053
+
4054
+ //#endregion
4055
+ //#region ../powerlines/src/api.ts
4056
+ /**
4057
+ * The Powerlines API class
4058
+ *
4059
+ * @remarks
4060
+ * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.
4061
+ *
4062
+ * @public
4063
+ */
4064
+ var PowerlinesAPI = class PowerlinesAPI {
4065
+ /**
4066
+ * The Powerlines context
4067
+ */
4068
+ #context;
4069
+ /**
4070
+ * The Powerlines context
4071
+ */
4072
+ get context() {
4073
+ return this.#context;
4074
+ }
4075
+ /**
4076
+ * Create a new Powerlines API instance
4077
+ *
4078
+ * @param context - The Powerlines context
4079
+ */
4080
+ constructor(context) {
4081
+ this.#context = context;
4082
+ }
4083
+ /**
4084
+ * Initialize a Powerlines API instance
4085
+ *
4086
+ * @param workspaceRoot - The directory of the underlying workspace the Powerlines project exists in
4087
+ * @param config - An object containing the configuration required to run Powerlines tasks.
4088
+ * @returns A new instance of the Powerlines API
4089
+ */
4090
+ static async from(workspaceRoot, config) {
4091
+ const api = new PowerlinesAPI(await PowerlinesAPIContext.from(workspaceRoot, config));
4092
+ api.#context.$$internal = {
4093
+ api,
4094
+ addPlugin: api.#addPlugin.bind(api)
4095
+ };
4096
+ api.context.info(`🔌 The Powerlines Engine v${version} has started`);
4097
+ for (const plugin of api.context.config.plugins ?? []) await api.#addPlugin(plugin);
4098
+ if (api.context.plugins.length === 0) api.context.warn("No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.");
4099
+ const pluginConfig = await api.callHook("config", {
4100
+ environment: await api.context.getEnvironment(),
4101
+ sequential: true,
4102
+ result: "merge",
4103
+ merge: mergeConfigs
4104
+ });
4105
+ await api.context.withUserConfig(pluginConfig, { isHighPriority: false });
4106
+ return api;
4107
+ }
4108
+ /**
4109
+ * Prepare the Powerlines API
4110
+ *
4111
+ * @remarks
4112
+ * This method will prepare the Powerlines API for use, initializing any necessary resources.
4113
+ *
4114
+ * @param inlineConfig - The inline configuration for the prepare command
4115
+ */
4116
+ async prepare(inlineConfig = { command: "prepare" }) {
4117
+ this.context.info(" 🏗️ Preparing the Powerlines project");
4118
+ this.context.debug(" Aggregating configuration options for the Powerlines project");
4119
+ await this.context.withInlineConfig(inlineConfig);
4120
+ await this.#executeEnvironments(async (context) => {
4121
+ context.debug(`Initializing the processing options for the Powerlines project.`);
4122
+ await this.callHook("configResolved", {
4123
+ environment: context,
4124
+ order: "pre"
4125
+ });
4126
+ await initializeTsconfig(context);
4127
+ await this.callHook("configResolved", {
4128
+ environment: context,
4129
+ order: "normal"
4130
+ });
4131
+ if (context.entry.length > 0) context.debug(`The configuration provided ${(0, __stryke_type_checks_is_object.isObject)(context.config.input) ? Object.keys(context.config.input).length : (0, __stryke_convert_to_array.toArray)(context.config.input).length} entry point(s), Powerlines has found ${context.entry.length} entry files(s) for the ${context.config.title} project${context.entry.length > 0 && context.entry.length < 10 ? `: \n${context.entry.map((entry) => `- ${entry.file}${entry.output ? ` -> ${entry.output}` : ""}`).join(" \n")}` : ""}`);
4132
+ else context.warn(`No entry files were found for the ${context.config.title} project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`);
4133
+ await resolveTsconfig(context);
4134
+ await installDependencies(context);
4135
+ await this.callHook("configResolved", {
4136
+ environment: context,
4137
+ order: "post"
4138
+ });
4139
+ context.trace(`Powerlines configuration has been resolved: \n\n${(0, __storm_software_config_tools_logger_console.formatLogMessage)({
4140
+ ...context.config,
4141
+ userConfig: (0, __stryke_type_checks_is_set_object.isSetObject)(context.config.userConfig) ? (0, __stryke_helpers_omit.omit)(context.config.userConfig, ["plugins"]) : void 0,
4142
+ inlineConfig: (0, __stryke_type_checks_is_set_object.isSetObject)(context.config.inlineConfig) ? (0, __stryke_helpers_omit.omit)(context.config.inlineConfig, ["plugins"]) : void 0,
4143
+ plugins: context.plugins.map((plugin) => plugin.plugin.name)
4144
+ })}`);
4145
+ if (!context.fs.existsSync(context.cachePath)) await (0, __stryke_fs_helpers.createDirectory)(context.cachePath);
4146
+ if (!context.fs.existsSync(context.dataPath)) await (0, __stryke_fs_helpers.createDirectory)(context.dataPath);
4147
+ await this.callHook("prepare", {
4148
+ environment: context,
4149
+ order: "pre"
4150
+ });
4151
+ await this.callHook("prepare", {
4152
+ environment: context,
4153
+ order: "normal"
4154
+ });
4155
+ if (context.config.output.dts !== false) {
4156
+ context.debug(`Preparing the TypeScript definitions for the Powerlines project.`);
4157
+ if (context.fs.existsSync(context.dtsPath)) await context.fs.remove(context.dtsPath);
4158
+ if (!await (0, __stryke_fs_resolve.resolvePackage)("typescript")) throw new Error("Could not resolve TypeScript package location. Please ensure TypeScript is installed.");
4159
+ context.debug("Running TypeScript compiler for built-in runtime module files.");
4160
+ let types = await emitBuiltinTypes(context, (await context.getBuiltins()).reduce((ret, builtin) => {
4161
+ const formatted = (0, __stryke_path_replace.replacePath)(builtin.path, context.workspaceConfig.workspaceRoot);
4162
+ if (!ret.includes(formatted)) ret.push(formatted);
4163
+ return ret;
4164
+ }, []));
4165
+ context.debug(`Generating TypeScript declaration file ${context.dtsPath}.`);
4166
+ const directives = [];
4167
+ const asNextParam = (previousResult) => (0, __stryke_type_checks_is_object.isObject)(previousResult) ? previousResult.code : previousResult;
4168
+ let result = await this.callHook("types", {
4169
+ environment: context,
4170
+ sequential: true,
4171
+ order: "pre",
4172
+ result: "merge",
4173
+ asNextParam
4174
+ }, types);
4175
+ if (result) {
4176
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(result)) {
4177
+ types = result.code;
4178
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives.push(...result.directives);
4179
+ } else if ((0, __stryke_type_checks_is_set_string.isSetString)(result)) types = result;
4180
+ }
4181
+ result = await this.callHook("types", {
4182
+ environment: context,
4183
+ sequential: true,
4184
+ order: "normal",
4185
+ result: "merge",
4186
+ asNextParam
4187
+ }, types);
4188
+ if (result) {
4189
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(result)) {
4190
+ types = result.code;
4191
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives.push(...result.directives);
4192
+ } else if ((0, __stryke_type_checks_is_set_string.isSetString)(result)) types = result;
4193
+ }
4194
+ result = await this.callHook("types", {
4195
+ environment: context,
4196
+ sequential: true,
4197
+ order: "post",
4198
+ result: "merge",
4199
+ asNextParam
4200
+ }, types);
4201
+ if (result) {
4202
+ if ((0, __stryke_type_checks_is_set_object.isSetObject)(result)) {
4203
+ types = result.code;
4204
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives.push(...result.directives);
4205
+ } else if ((0, __stryke_type_checks_is_set_string.isSetString)(result)) types = result;
4206
+ }
4207
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(types?.trim()) || directives.length > 0) await context.fs.write(context.dtsPath, `${directives.length > 0 ? `${directives.map((directive) => `/// <reference types="${directive}" />`).join("\n")}
4208
+
4209
+ ` : ""}${getFileHeader(context, {
4210
+ directive: null,
4211
+ prettierIgnore: false
4212
+ })}
4213
+
4214
+ ${formatTypes(types)}
4215
+ `);
4216
+ else {
4217
+ const dtsRelativePath = getTsconfigDtsPath(context);
4218
+ if (context.tsconfig.tsconfigJson.include && isIncludeMatchFound(dtsRelativePath, context.tsconfig.tsconfigJson.include)) {
4219
+ const normalizedDtsRelativePath = dtsRelativePath.startsWith("./") ? dtsRelativePath.slice(2) : dtsRelativePath;
4220
+ context.tsconfig.tsconfigJson.include = context.tsconfig.tsconfigJson.include.filter((includeValue) => includeValue?.toString() !== normalizedDtsRelativePath);
4221
+ await context.fs.write(context.tsconfig.tsconfigFilePath, JSON.stringify(context.tsconfig.tsconfigJson, null, 2));
4222
+ }
4223
+ }
4224
+ }
4225
+ context.tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig);
4226
+ if (!context.tsconfig) throw new Error("Failed to parse the TypeScript configuration file.");
4227
+ this.context.debug("Formatting files generated during the prepare step.");
4228
+ await Promise.all([formatFolder(context, context.builtinsPath), formatFolder(context, context.entryPath)]);
4229
+ await this.callHook("prepare", {
4230
+ environment: context,
4231
+ order: "post"
4232
+ });
4233
+ await writeMetaFile(context);
4234
+ context.persistedMeta = context.meta;
4235
+ });
4236
+ this.context.debug("✔ Powerlines preparation has completed successfully");
4237
+ }
4238
+ /**
4239
+ * Create a new Powerlines project
4240
+ *
4241
+ * @remarks
4242
+ * This method will create a new Powerlines project in the current directory.
4243
+ *
4244
+ * @param inlineConfig - The inline configuration for the new command
4245
+ * @returns A promise that resolves when the project has been created
4246
+ */
4247
+ async new(inlineConfig) {
4248
+ this.context.info(" 🆕 Creating a new Powerlines project");
4249
+ await this.prepare(inlineConfig);
4250
+ await this.#executeEnvironments(async (context) => {
4251
+ context.debug("Initializing the processing options for the Powerlines project.");
4252
+ await this.callHook("new", {
4253
+ environment: context,
4254
+ order: "pre"
4255
+ });
4256
+ const files = await (0, __stryke_fs_list_files.listFiles)((0, __stryke_path_join_paths.joinPaths)(context.powerlinesPath, "files/common/**/*.hbs"));
4257
+ for (const file of files) {
4258
+ context.trace(`Adding template file to project: ${file}`);
4259
+ const template = handlebars.default.compile(file);
4260
+ await context.fs.write((0, __stryke_path_join_paths.joinPaths)(context.config.root, file.replace(".hbs", "")), template(context));
4261
+ }
4262
+ await this.callHook("new", {
4263
+ environment: context,
4264
+ order: "normal"
4265
+ });
4266
+ if (context.config.projectType === "application") {
4267
+ const files$1 = await (0, __stryke_fs_list_files.listFiles)((0, __stryke_path_join_paths.joinPaths)(context.powerlinesPath, "files/application/**/*.hbs"));
4268
+ for (const file of files$1) {
4269
+ context.trace(`Adding application template file: ${file}`);
4270
+ const template = handlebars.default.compile(file);
4271
+ await context.fs.write((0, __stryke_path_join_paths.joinPaths)(context.config.root, file.replace(".hbs", "")), template(context));
4272
+ }
4273
+ } else {
4274
+ const files$1 = await (0, __stryke_fs_list_files.listFiles)((0, __stryke_path_join_paths.joinPaths)(context.powerlinesPath, "files/library/**/*.hbs"));
4275
+ for (const file of files$1) {
4276
+ context.trace(`Adding library template file: ${file}`);
4277
+ const template = handlebars.default.compile(file);
4278
+ await context.fs.write((0, __stryke_path_join_paths.joinPaths)(context.config.root, file.replace(".hbs", "")), template(context));
4279
+ }
4280
+ }
4281
+ await this.callHook("new", {
4282
+ environment: context,
4283
+ order: "post"
4284
+ });
4285
+ });
4286
+ this.context.debug("✔ Powerlines new command completed successfully");
4287
+ }
4288
+ /**
4289
+ * Clean any previously prepared artifacts
4290
+ *
4291
+ * @remarks
4292
+ * This method will remove the previous Powerlines artifacts from the project.
4293
+ *
4294
+ * @param inlineConfig - The inline configuration for the clean command
4295
+ * @returns A promise that resolves when the clean command has completed
4296
+ */
4297
+ async clean(inlineConfig = { command: "clean" }) {
4298
+ this.context.info(" 🧹 Cleaning the previous Powerlines artifacts");
4299
+ await this.prepare(inlineConfig);
4300
+ await this.#executeEnvironments(async (context) => {
4301
+ context.debug("Cleaning the project's dist and artifacts directories.");
4302
+ await context.fs.remove((0, __stryke_path_join_paths.joinPaths)(context.workspaceConfig.workspaceRoot, context.config.output.buildPath));
4303
+ await context.fs.remove((0, __stryke_path_join_paths.joinPaths)(context.workspaceConfig.workspaceRoot, context.config.root, context.config.output.artifactsPath));
4304
+ await this.callHook("clean", {
4305
+ environment: context,
4306
+ sequential: false
4307
+ });
4308
+ });
4309
+ this.context.debug("✔ Powerlines cleaning completed successfully");
4310
+ }
4311
+ /**
4312
+ * Lint the project
4313
+ *
4314
+ * @param inlineConfig - The inline configuration for the lint command
4315
+ * @returns A promise that resolves when the lint command has completed
4316
+ */
4317
+ async lint(inlineConfig = { command: "lint" }) {
4318
+ this.context.info(" 📝 Linting the Powerlines project");
4319
+ await this.prepare(inlineConfig);
4320
+ await this.#executeEnvironments(async (context) => {
4321
+ await this.callHook("lint", {
4322
+ environment: context,
4323
+ sequential: false
4324
+ });
4325
+ });
4326
+ this.context.debug("✔ Powerlines linting completed successfully");
4327
+ }
4328
+ /**
4329
+ * Build the project
4330
+ *
4331
+ * @remarks
4332
+ * This method will build the Powerlines project, generating the necessary artifacts.
4333
+ *
4334
+ * @param inlineConfig - The inline configuration for the build command
4335
+ * @returns A promise that resolves when the build command has completed
4336
+ */
4337
+ async build(inlineConfig = { command: "build" }) {
4338
+ this.context.info(" 📦 Building the Powerlines project");
4339
+ await this.context.generateChecksum();
4340
+ if (this.context.meta.checksum !== this.context.persistedMeta?.checksum || this.context.config.skipCache) {
4341
+ this.context.info("The project has been modified since the last time `prepare` was ran. Re-preparing the project.");
4342
+ await this.prepare(inlineConfig);
4343
+ }
4344
+ if (this.context.config.singleBuild) await this.#handleBuild(await this.#context.toEnvironment());
4345
+ else await this.#executeEnvironments(async (context) => {
4346
+ await this.#handleBuild(context);
4347
+ });
4348
+ this.context.debug("✔ Powerlines build completed successfully");
4349
+ }
4350
+ /**
4351
+ * Prepare the documentation for the project
4352
+ *
4353
+ * @param inlineConfig - The inline configuration for the docs command
4354
+ * @returns A promise that resolves when the documentation generation has completed
4355
+ */
4356
+ async docs(inlineConfig = { command: "docs" }) {
4357
+ this.context.info(" 📓 Generating documentation for the Powerlines project");
4358
+ await this.prepare(inlineConfig);
4359
+ await this.#executeEnvironments(async (context) => {
4360
+ context.debug("Writing documentation for the Powerlines project artifacts.");
4361
+ await this.prepare(inlineConfig);
4362
+ await this.#executeEnvironments(async (context$1) => {
4363
+ await this.callHook("docs", { environment: context$1 });
4364
+ });
4365
+ });
4366
+ this.context.debug("✔ Powerlines documentation generation completed successfully");
4367
+ }
4368
+ /**
4369
+ * Deploy the project source code
4370
+ *
4371
+ * @remarks
4372
+ * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.
4373
+ *
4374
+ * @param inlineConfig - The inline configuration for the deploy command
4375
+ */
4376
+ async deploy(inlineConfig = { command: "deploy" }) {
4377
+ this.context.info(" 🚀 Deploying the Powerlines project");
4378
+ await this.prepare(inlineConfig);
4379
+ await this.#executeEnvironments(async (context) => {
4380
+ await this.callHook("deploy", { environment: context });
4381
+ });
4382
+ this.context.debug("✔ Powerlines deploy completed successfully");
4383
+ }
4384
+ /**
4385
+ * Finalization process
4386
+ *
4387
+ * @remarks
4388
+ * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.
4389
+ *
4390
+ * @returns A promise that resolves when the finalization process has completed
4391
+ */
4392
+ async finalize() {
4393
+ this.context.info(" 🏁 Powerlines finalization processes started");
4394
+ await this.#executeEnvironments(async (context) => {
4395
+ await this.callHook("finalize", { environment: context });
4396
+ await context.fs.dispose();
4397
+ });
4398
+ this.context.debug("✔ Powerlines finalization completed successfully");
4399
+ }
4400
+ /**
4401
+ * Invokes the configured plugin hooks
4402
+ *
4403
+ * @remarks
4404
+ * By default, it will call the `"pre"`, `"normal"`, and `"post"` ordered hooks in sequence
4405
+ *
4406
+ * @param hook - The hook to call
4407
+ * @param options - The options to provide to the hook
4408
+ * @param args - The arguments to pass to the hook
4409
+ * @returns The result of the hook call
4410
+ */
4411
+ async callHook(hook, options, ...args) {
4412
+ return callHook((0, __stryke_type_checks_is_set_object.isSetObject)(options?.environment) ? options.environment : await this.#context.getEnvironment(options?.environment), hook, {
4413
+ sequential: true,
4414
+ ...options
4415
+ }, ...args);
4416
+ }
4417
+ /**
4418
+ * Dispose of the Powerlines API instance
4419
+ *
4420
+ * @remarks
4421
+ * This method will finalize the Powerlines API instance, cleaning up any resources used.
4422
+ */
4423
+ async [Symbol.asyncDispose]() {
4424
+ await this.finalize();
4425
+ }
4426
+ async #handleBuild(context) {
4427
+ await this.callHook("build", {
4428
+ environment: context,
4429
+ order: "pre"
4430
+ });
4431
+ context.debug("Formatting the generated entry files before the build process starts.");
4432
+ await formatFolder(context, context.entryPath);
4433
+ await this.callHook("build", {
4434
+ environment: context,
4435
+ order: "normal"
4436
+ });
4437
+ if (context.config.output.buildPath !== context.config.output.outputPath) {
4438
+ const sourcePath = (0, __stryke_path_append.appendPath)(context.config.output.buildPath, context.workspaceConfig.workspaceRoot);
4439
+ const destinationPath = (0, __stryke_path_join_paths.joinPaths)((0, __stryke_path_append.appendPath)(context.config.output.outputPath, context.workspaceConfig.workspaceRoot), "dist");
4440
+ if (context.fs.existsSync(sourcePath) && sourcePath !== destinationPath) {
4441
+ context.debug(`Copying build output files from project's build directory (${context.config.output.buildPath}) to the workspace's output directory (${context.config.output.outputPath}).`);
4442
+ await context.fs.copy(sourcePath, destinationPath);
4443
+ }
4444
+ }
4445
+ await Promise.all(context.config.output.assets.map(async (asset) => {
4446
+ context.trace(`Copying asset(s): ${chalk.default.redBright(context.workspaceConfig.workspaceRoot === asset.input ? asset.glob : (0, __stryke_path_join_paths.joinPaths)((0, __stryke_path_replace.replacePath)(asset.input, context.workspaceConfig.workspaceRoot), asset.glob))} -> ${chalk.default.greenBright((0, __stryke_path_join_paths.joinPaths)((0, __stryke_path_replace.replacePath)(asset.output, context.workspaceConfig.workspaceRoot), asset.glob))} ${Array.isArray(asset.ignore) && asset.ignore.length > 0 ? ` (ignoring: ${asset.ignore.map((i) => chalk.default.yellowBright(i)).join(", ")})` : ""}`);
4447
+ await context.fs.copy(asset, asset.output);
4448
+ }));
4449
+ await this.callHook("build", {
4450
+ environment: context,
4451
+ order: "post"
4452
+ });
4453
+ }
4454
+ /**
4455
+ * Get the configured environments
4456
+ *
4457
+ * @returns The configured environments
4458
+ */
4459
+ async #getEnvironments() {
4460
+ if (!this.context.config.environments || Object.keys(this.context.config.environments).length <= 1) {
4461
+ this.context.debug("No environments are configured for this Powerlines project. Using the default environment.");
4462
+ return [await this.context.getEnvironment()];
4463
+ }
4464
+ this.context.debug(`Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`);
4465
+ return (await Promise.all(Object.entries(this.context.config.environments).map(async ([name, config]) => {
4466
+ if (!await this.context.getEnvironmentSafe(name)) {
4467
+ const resolvedEnvironment = await this.callHook("configEnvironment", { environment: name }, name, config);
4468
+ if (resolvedEnvironment) this.context.environments[name] = await this.context.in(resolvedEnvironment);
4469
+ }
4470
+ return this.context.environments[name];
4471
+ }))).filter((context) => (0, __stryke_type_checks_is_set.isSet)(context));
4472
+ }
4473
+ /**
4474
+ * Execute a handler function for each environment
4475
+ *
4476
+ * @param handle - The handler function to execute for each environment
4477
+ */
4478
+ async #executeEnvironments(handle) {
4479
+ await Promise.all((await this.#getEnvironments()).map(async (context) => {
4480
+ return Promise.resolve(handle(context));
4481
+ }));
4482
+ }
4483
+ /**
4484
+ * Add a Powerlines plugin used in the build process
4485
+ *
4486
+ * @param config - The import path of the plugin to add
4487
+ */
4488
+ async #addPlugin(config) {
4489
+ if (config) {
4490
+ const result = await this.#initPlugin(config);
4491
+ if (!result) return;
4492
+ for (const plugin of result) {
4493
+ this.context.debug(`Successfully initialized the ${chalk.default.bold.cyanBright(plugin.name)} plugin`);
4494
+ await this.context.addPlugin(plugin);
4495
+ }
4496
+ }
4497
+ }
4498
+ /**
4499
+ * Initialize a Powerlines plugin
4500
+ *
4501
+ * @param config - The configuration for the plugin
4502
+ * @returns The initialized plugin instance, or null if the plugin was a duplicate
4503
+ * @throws Will throw an error if the plugin cannot be found or is invalid
4504
+ */
4505
+ async #initPlugin(config) {
4506
+ let awaited = config;
4507
+ if ((0, __stryke_type_checks_is_promise.isPromiseLike)(config)) awaited = await Promise.resolve(config);
4508
+ if (!isPluginConfig(awaited)) {
4509
+ const invalid = findInvalidPluginConfig(awaited);
4510
+ throw new Error(`Invalid ${invalid && invalid.length > 1 ? "plugins" : "plugin"} specified in the configuration - ${invalid && invalid.length > 0 ? JSON.stringify(awaited) : invalid?.join("\n\n")} \n\nPlease ensure the value is one of the following: \n - an instance of \`Plugin\` \n - a plugin name \n - an object with the \`plugin\` and \`options\` properties \n - a tuple array with the plugin and options \n - a factory function that returns a plugin or array of plugins \n - an array of plugins or plugin configurations`);
4511
+ }
4512
+ let plugins;
4513
+ if (isPlugin(awaited)) plugins = [awaited];
4514
+ else if ((0, __stryke_type_checks_is_function.isFunction)(awaited)) plugins = (0, __stryke_convert_to_array.toArray)(await Promise.resolve(awaited()));
4515
+ else if ((0, __stryke_type_checks_is_string.isString)(awaited)) {
4516
+ const resolved = await this.#resolvePlugin(awaited);
4517
+ if ((0, __stryke_type_checks_is_function.isFunction)(resolved)) plugins = (0, __stryke_convert_to_array.toArray)(await Promise.resolve(resolved()));
4518
+ else plugins = (0, __stryke_convert_to_array.toArray)(resolved);
4519
+ } else if (Array.isArray(awaited) && awaited.every(isPlugin)) plugins = awaited;
4520
+ else if (Array.isArray(awaited) && awaited.every(isPluginConfig)) {
4521
+ plugins = [];
4522
+ for (const pluginConfig of awaited) {
4523
+ const initialized = await this.#initPlugin(pluginConfig);
4524
+ if (initialized) plugins.push(...initialized);
4525
+ }
4526
+ } else if (isPluginConfigTuple(awaited) || isPluginConfigObject(awaited)) {
4527
+ let pluginConfig;
4528
+ let pluginOptions;
4529
+ if (isPluginConfigTuple(awaited)) {
4530
+ pluginConfig = awaited[0];
4531
+ pluginOptions = awaited?.length === 2 ? awaited[1] : void 0;
4532
+ } else {
4533
+ pluginConfig = awaited.plugin;
4534
+ pluginOptions = awaited.options;
4535
+ }
4536
+ if ((0, __stryke_type_checks_is_set_string.isSetString)(pluginConfig)) {
4537
+ const resolved = await this.#resolvePlugin(pluginConfig);
4538
+ if ((0, __stryke_type_checks_is_function.isFunction)(resolved)) plugins = (0, __stryke_convert_to_array.toArray)(await Promise.resolve(pluginOptions ? resolved(pluginOptions) : resolved()));
4539
+ else plugins = (0, __stryke_convert_to_array.toArray)(resolved);
4540
+ } else if ((0, __stryke_type_checks_is_function.isFunction)(pluginConfig)) plugins = (0, __stryke_convert_to_array.toArray)(await Promise.resolve(pluginConfig(pluginOptions)));
4541
+ else if (Array.isArray(pluginConfig) && pluginConfig.every(isPlugin)) plugins = pluginConfig;
4542
+ else if (isPlugin(pluginConfig)) plugins = (0, __stryke_convert_to_array.toArray)(pluginConfig);
4543
+ }
4544
+ if (!plugins) throw new Error(`The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`);
4545
+ if (plugins.length > 0 && !plugins.every(isPlugin)) throw new Error(`The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`);
4546
+ const result = [];
4547
+ for (const plugin of plugins) if (checkDedupe(plugin, this.context.plugins)) this.context.trace(`Duplicate ${chalk.default.bold.cyanBright(plugin.name)} plugin dependency detected - Skipping initialization.`);
4548
+ else {
4549
+ result.push(plugin);
4550
+ this.context.trace(`Initializing the ${chalk.default.bold.cyanBright(plugin.name)} plugin...`);
4551
+ }
4552
+ return result;
4553
+ }
4554
+ async #resolvePlugin(pluginPath) {
4555
+ if (pluginPath.startsWith("@") && pluginPath.split("/").filter(Boolean).length > 2) {
4556
+ const splits = pluginPath.split("/").filter(Boolean);
4557
+ pluginPath = `${splits[0]}/${splits[1]}`;
4558
+ }
4559
+ const isInstalled = (0, __stryke_fs_package_fns.isPackageExists)(pluginPath, { paths: [this.context.workspaceConfig.workspaceRoot, this.context.config.root] });
4560
+ if (!isInstalled && this.context.config.autoInstall) {
4561
+ this.#context.warn(`The plugin package "${pluginPath}" is not installed. It will be installed automatically.`);
4562
+ const result = await (0, __stryke_fs_install.install)(pluginPath, { cwd: this.context.config.root });
4563
+ if ((0, __stryke_type_checks_is_number.isNumber)(result.exitCode) && result.exitCode > 0) {
4564
+ this.#context.error(result.stderr);
4565
+ throw new Error(`An error occurred while installing the build plugin package "${pluginPath}" `);
4566
+ }
4567
+ }
4568
+ try {
4569
+ const module$1 = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve((0, __stryke_path_join_paths.joinPaths)(pluginPath, "plugin")));
4570
+ const result = module$1.plugin ?? module$1.default;
4571
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
4572
+ return result;
4573
+ } catch (error) {
4574
+ try {
4575
+ const module$1 = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve(pluginPath));
4576
+ const result = module$1.plugin ?? module$1.default;
4577
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
4578
+ return result;
4579
+ } catch {
4580
+ if (!isInstalled) throw new Error(`The plugin package "${pluginPath}" is not installed. Please install the package using the command: "npm install ${pluginPath} --save-dev"`);
4581
+ else throw new Error(`An error occurred while importing the build plugin package "${pluginPath}":
4582
+ ${(0, __stryke_type_checks_is_error.isError)(error) ? error.message : String(error)}
4583
+
4584
+ Note: Please ensure the plugin package's default export is a class that extends \`Plugin\` with a constructor that excepts a single arguments of type \`PluginOptions\`.`);
4585
+ }
4586
+ }
4587
+ }
4588
+ };
4589
+
4590
+ //#endregion
4591
+ //#region ../powerlines/src/index.ts
4592
+ /**
4593
+ * The powerlines library used by Storm Software for building NodeJS applications.
4594
+ *
4595
+ * @remarks
4596
+ * A build toolkit and runtime used by Storm Software in TypeScript applications
4597
+ *
4598
+ * @packageDocumentation
4599
+ */
4600
+ var src_default = PowerlinesAPI;
4601
+
4602
+ //#endregion
4603
+ //#region src/base/base-executor.ts
4604
+ /**
4605
+ * A utility function to create a Powerlines executor that can be used with the `withRunExecutor` function.
4606
+ *
4607
+ * @remarks
4608
+ * This function is designed to simplify the creation of Powerlines executors by providing a consistent interface and error handling.
4609
+ *
4610
+ * @param command - The command that the executor will handle (e.g., "new", "prepare", "build", etc.).
4611
+ * @param executorFn - The function that will be executed when the command is run.
4612
+ * @returns A Promise that resolves to the result of the executor function.
4613
+ */
4614
+ function withExecutor(command, executorFn) {
4615
+ return (0, __storm_software_workspace_tools_base_base_executor.withRunExecutor)(`Powerlines ${command} command executor`, async (options, context, workspaceConfig) => {
4616
+ if (!context.projectName) throw new Error("The executor requires `projectName` on the context object.");
4617
+ if (!context.projectName || !context.projectsConfigurations?.projects || !context.projectsConfigurations.projects[context.projectName] || !context.projectsConfigurations.projects[context.projectName]?.root) throw new Error("The executor requires `projectsConfigurations` on the context object.");
4618
+ const projectConfig = context.projectsConfigurations.projects[context.projectName];
4619
+ const api = await src_default.from(workspaceConfig.workspaceRoot, (0, defu.default)({
4620
+ input: options.input,
4621
+ output: {
4622
+ outputPath: options.outputPath ?? projectConfig.targets?.build?.options?.outputPath,
4623
+ format: options.format,
4624
+ sourceMap: options.sourceMap
4625
+ },
4626
+ resolve: {
4627
+ external: options.external,
4628
+ noExternal: options.noExternal,
4629
+ skipNodeModulesBundle: options.skipNodeModulesBundle
4630
+ },
4631
+ root: projectConfig.root,
4632
+ projectType: projectConfig.projectType,
4633
+ sourceRoot: projectConfig.sourceRoot,
4634
+ tsconfig: options.tsconfig,
4635
+ platform: options.platform,
4636
+ define: options.define,
4637
+ logLevel: options.logLevel,
4638
+ mode: options.mode
4639
+ }, options));
4640
+ try {
4641
+ return await Promise.resolve(executorFn((0, defu.default)({
4642
+ projectName: context.projectName,
4643
+ options,
4644
+ workspaceConfig,
4645
+ inlineConfig: {
4646
+ command,
4647
+ configFile: options.configFile
4648
+ },
4649
+ command
4650
+ }, context), api));
4651
+ } catch (error) {
4652
+ (0, __storm_software_config_tools_logger.writeError)(`An error occurred while executing the Powerlines ${command} command executor: ${(0, __stryke_type_checks_is_error.isError)(error) ? `${error.message}
4653
+
4654
+ ${error.stack}` : "Unknown error"}`);
4655
+ return { success: false };
4656
+ } finally {
4657
+ await api.finalize();
4658
+ }
4659
+ }, {
4660
+ skipReadingConfig: false,
4661
+ hooks: { applyDefaultOptions: (options) => {
4662
+ if (options.mode !== "development" && options.mode !== "test") options.mode = "production";
4663
+ options.outputPath ??= "dist/{projectRoot}";
4664
+ options.configFile ??= "{projectRoot}/powerlines.config.ts";
4665
+ return options;
4666
+ } }
4667
+ });
4668
+ }
4669
+
4670
+ //#endregion
4671
+ Object.defineProperty(exports, 'withExecutor', {
4672
+ enumerable: true,
4673
+ get: function () {
4674
+ return withExecutor;
4675
+ }
4676
+ });