powerlines 0.42.32 → 0.42.34

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 (122) hide show
  1. package/dist/api-0aKfs398.mjs +1010 -0
  2. package/dist/api-0aKfs398.mjs.map +1 -0
  3. package/dist/api-7bOKZ8DC.cjs +1030 -0
  4. package/dist/{api-context-k3dnn5KR.cjs → api-context-4t-rlsAr.cjs} +64 -442
  5. package/dist/{api-context-BQi9M07D.mjs → api-context-CmuOyg7q.mjs} +62 -432
  6. package/dist/api-context-CmuOyg7q.mjs.map +1 -0
  7. package/dist/astro.mjs.map +1 -1
  8. package/dist/{chunk-7azAqIA9.cjs → chunk-AIJqnxB6.cjs} +0 -7
  9. package/dist/{chunk-WJdhOJK3.mjs → chunk-CtajNgzt.mjs} +1 -10
  10. package/dist/config.cjs +1 -1
  11. package/dist/config.mjs +1 -1
  12. package/dist/constants.cjs +1 -1
  13. package/dist/constants.mjs +1 -1
  14. package/dist/context/index.cjs +1 -1
  15. package/dist/context/index.d.cts +11 -260
  16. package/dist/context/index.d.cts.map +1 -1
  17. package/dist/context/index.d.mts +12 -261
  18. package/dist/context/index.d.mts.map +1 -1
  19. package/dist/context/index.mjs +1 -1
  20. package/dist/esbuild.cjs +9 -4
  21. package/dist/esbuild.d.cts +2 -2
  22. package/dist/esbuild.d.cts.map +1 -1
  23. package/dist/esbuild.d.mts +2 -2
  24. package/dist/esbuild.d.mts.map +1 -1
  25. package/dist/esbuild.mjs +2 -2
  26. package/dist/esbuild.mjs.map +1 -1
  27. package/dist/farm.cjs +1 -1
  28. package/dist/index.cjs +3 -3
  29. package/dist/index.d.cts +1 -1
  30. package/dist/index.d.mts +2 -2
  31. package/dist/index.mjs +2 -2
  32. package/dist/next.mjs.map +1 -1
  33. package/dist/nuxt.cjs +2 -2
  34. package/dist/nuxt.d.mts +1 -1
  35. package/dist/nuxt.mjs +1 -1
  36. package/dist/nuxt.mjs.map +1 -1
  37. package/dist/plugin-utils.cjs +1 -1
  38. package/dist/plugin-utils.mjs +1 -1
  39. package/dist/rolldown.cjs +7 -2
  40. package/dist/rolldown.d.cts +2 -2
  41. package/dist/rolldown.d.cts.map +1 -1
  42. package/dist/rolldown.d.mts +2 -2
  43. package/dist/rolldown.d.mts.map +1 -1
  44. package/dist/rolldown.mjs +2 -2
  45. package/dist/rolldown.mjs.map +1 -1
  46. package/dist/rollup.cjs +7 -2
  47. package/dist/rollup.d.cts +2 -2
  48. package/dist/rollup.d.cts.map +1 -1
  49. package/dist/rollup.d.mts +2 -2
  50. package/dist/rollup.d.mts.map +1 -1
  51. package/dist/rollup.mjs +2 -2
  52. package/dist/rollup.mjs.map +1 -1
  53. package/dist/rspack.cjs +7 -2
  54. package/dist/rspack.d.cts +2 -2
  55. package/dist/rspack.d.cts.map +1 -1
  56. package/dist/rspack.d.mts +2 -2
  57. package/dist/rspack.d.mts.map +1 -1
  58. package/dist/rspack.mjs +2 -2
  59. package/dist/rspack.mjs.map +1 -1
  60. package/dist/storage/index.cjs +1 -1
  61. package/dist/storage/index.d.cts +1 -1
  62. package/dist/storage/index.d.mts +2 -2
  63. package/dist/storage/index.mjs +1 -1
  64. package/dist/ts-morph-B85ZbV1Q.mjs +102 -0
  65. package/dist/ts-morph-B85ZbV1Q.mjs.map +1 -0
  66. package/dist/ts-morph-Cf4wz3E0.cjs +114 -0
  67. package/dist/{tsconfig-BhVGZ2DK.cjs → tsconfig-ChmbpAO7.cjs} +2 -2
  68. package/dist/{tsconfig-CzYPBpDS.mjs → tsconfig-DoV1dUYg.mjs} +2 -2
  69. package/dist/{tsconfig-CzYPBpDS.mjs.map → tsconfig-DoV1dUYg.mjs.map} +1 -1
  70. package/dist/tsdown.cjs +8 -3
  71. package/dist/tsdown.d.cts +2 -2
  72. package/dist/tsdown.d.cts.map +1 -1
  73. package/dist/tsdown.d.mts +2 -2
  74. package/dist/tsdown.d.mts.map +1 -1
  75. package/dist/tsdown.mjs +3 -3
  76. package/dist/tsdown.mjs.map +1 -1
  77. package/dist/tsup.cjs +8 -3
  78. package/dist/tsup.d.cts +3 -547
  79. package/dist/tsup.d.cts.map +1 -1
  80. package/dist/tsup.d.mts +3 -547
  81. package/dist/tsup.d.mts.map +1 -1
  82. package/dist/tsup.mjs +3 -3
  83. package/dist/tsup.mjs.map +1 -1
  84. package/dist/{types-hdziyQIH.d.mts → types-9O-s0Fpu.d.mts} +1 -1
  85. package/dist/types-9O-s0Fpu.d.mts.map +1 -0
  86. package/dist/typescript/index.cjs +4 -104
  87. package/dist/typescript/index.d.cts +1 -6
  88. package/dist/typescript/index.d.cts.map +1 -1
  89. package/dist/typescript/index.d.mts +2 -7
  90. package/dist/typescript/index.d.mts.map +1 -1
  91. package/dist/typescript/index.mjs +3 -102
  92. package/dist/unloader.cjs +1 -1
  93. package/dist/unplugin.cjs +2 -2
  94. package/dist/unplugin.mjs +1 -1
  95. package/dist/utils.cjs +1 -1
  96. package/dist/utils.mjs +1 -1
  97. package/dist/{virtual-BHb4iMd_.cjs → virtual-BNy8T32w.cjs} +3 -3
  98. package/dist/{virtual-OEHgBu0s.mjs → virtual-PaZGNIrj.mjs} +3 -3
  99. package/dist/{virtual-OEHgBu0s.mjs.map → virtual-PaZGNIrj.mjs.map} +1 -1
  100. package/dist/vite.cjs +7 -2
  101. package/dist/vite.d.cts +2 -2
  102. package/dist/vite.d.mts +2 -2
  103. package/dist/vite.mjs +2 -2
  104. package/dist/vite.mjs.map +1 -1
  105. package/dist/webpack.cjs +7 -2
  106. package/dist/webpack.d.cts +2 -2
  107. package/dist/webpack.d.cts.map +1 -1
  108. package/dist/webpack.d.mts +2 -2
  109. package/dist/webpack.d.mts.map +1 -1
  110. package/dist/webpack.mjs +2 -2
  111. package/dist/webpack.mjs.map +1 -1
  112. package/package.json +14 -13
  113. package/dist/api-D6i8MmbC.mjs +0 -6063
  114. package/dist/api-D6i8MmbC.mjs.map +0 -1
  115. package/dist/api-DZoRNTY7.cjs +0 -6083
  116. package/dist/api-context-BQi9M07D.mjs.map +0 -1
  117. package/dist/base-Bl_AMAlI.d.cts +0 -12
  118. package/dist/base-Bl_AMAlI.d.cts.map +0 -1
  119. package/dist/base-hjCHfNY6.d.mts +0 -12
  120. package/dist/base-hjCHfNY6.d.mts.map +0 -1
  121. package/dist/types-hdziyQIH.d.mts.map +0 -1
  122. package/dist/typescript/index.mjs.map +0 -1
@@ -0,0 +1,1010 @@
1
+ import { n as createProgram } from "./ts-morph-B85ZbV1Q.mjs";
2
+ import { t as utils_exports } from "./utils.mjs";
3
+ import { t as plugin_utils_exports } from "./plugin-utils.mjs";
4
+ import { d as writeMetaFile, f as callHook, p as mergeConfigs, t as PowerlinesAPIContext } from "./api-context-CmuOyg7q.mjs";
5
+ import { a as isIncludeMatchFound, i as getTsconfigFilePath, r as getParsedTypeScriptConfig } from "./tsconfig-DoV1dUYg.mjs";
6
+ import { formatLogMessage } from "@storm-software/config-tools/logger/console";
7
+ import { toArray } from "@stryke/convert/to-array";
8
+ import { copyFiles } from "@stryke/fs/copy-file";
9
+ import { existsSync } from "@stryke/fs/exists";
10
+ import { createDirectory, removeDirectory } from "@stryke/fs/helpers";
11
+ import { install } from "@stryke/fs/install";
12
+ import { listFiles } from "@stryke/fs/list-files";
13
+ import { doesPackageMatch, getPackageListing, isPackageExists, isPackageListed } from "@stryke/fs/package-fns";
14
+ import { resolvePackage } from "@stryke/fs/resolve";
15
+ import { getUnique } from "@stryke/helpers/get-unique";
16
+ import { omit } from "@stryke/helpers/omit";
17
+ import { appendPath } from "@stryke/path/append";
18
+ import { findFileName, findFilePath, relativePath } from "@stryke/path/file-path-fns";
19
+ import { isParentPath } from "@stryke/path/is-parent-path";
20
+ import { joinPaths } from "@stryke/path/join-paths";
21
+ import { replaceExtension, replacePath } from "@stryke/path/replace";
22
+ import { titleCase } from "@stryke/string-format/title-case";
23
+ import { isError } from "@stryke/type-checks/is-error";
24
+ import { isFunction } from "@stryke/type-checks/is-function";
25
+ import { isNumber } from "@stryke/type-checks/is-number";
26
+ import { isObject } from "@stryke/type-checks/is-object";
27
+ import { isPromiseLike } from "@stryke/type-checks/is-promise";
28
+ import { isSet } from "@stryke/type-checks/is-set";
29
+ import { isSetObject } from "@stryke/type-checks/is-set-object";
30
+ import { isSetString } from "@stryke/type-checks/is-set-string";
31
+ import { isString } from "@stryke/type-checks/is-string";
32
+ import chalk from "chalk";
33
+ import defu$1 from "defu";
34
+ import Handlebars from "handlebars";
35
+ import { prettyBytes } from "@stryke/string-format/pretty-bytes";
36
+ import { DiagnosticCategory, Node, Project } from "ts-morph";
37
+ import { getPackageName, getPackageVersion, hasPackageVersion } from "@stryke/string-format/package";
38
+ import { readJsonFile } from "@stryke/fs/json";
39
+ import { getObjectDiff } from "@donedeal0/superdiff";
40
+ import { StormJSON } from "@stryke/json/storm-json";
41
+
42
+ //#region package.json
43
+ var name = "powerlines";
44
+ var version = "0.42.34";
45
+
46
+ //#endregion
47
+ //#region src/_internal/helpers/generate-types.ts
48
+ /**
49
+ * Formats the generated TypeScript types source code.
50
+ *
51
+ * @param code - The generated TypeScript code.
52
+ * @returns The formatted TypeScript code.
53
+ */
54
+ function formatTypes(code = "") {
55
+ return code.replaceAll("#private;", "").replace(/__Ω/g, "");
56
+ }
57
+ async function extractModuleDeclarations(context, filePath, id, code, fileToModuleMap) {
58
+ const mappings = /* @__PURE__ */ new Map();
59
+ const ambient = [];
60
+ const sourceFile = new Project({ useInMemoryFileSystem: true }).createSourceFile("module.d.ts", code);
61
+ for (const ref of sourceFile.getTypeReferenceDirectives()) ambient.push({
62
+ id: ref.getFileName(),
63
+ external: true
64
+ });
65
+ const importLines = [];
66
+ const reExportLines = [];
67
+ const declarationLines = [];
68
+ for (const statement of sourceFile.getStatements()) {
69
+ if (Node.isImportDeclaration(statement)) {
70
+ const moduleSpec = statement.getModuleSpecifierValue();
71
+ const defaultImport = statement.getDefaultImport();
72
+ const namedImports = statement.getNamedImports();
73
+ const namespaceImport = statement.getNamespaceImport();
74
+ if (!defaultImport && namedImports.length === 0 && !namespaceImport) {
75
+ ambient.push({
76
+ id: moduleSpec,
77
+ external: !context.fs.isResolvableId(moduleSpec, filePath)
78
+ });
79
+ continue;
80
+ }
81
+ let resolvedSpec = moduleSpec;
82
+ if (context.fs.isResolvableId(moduleSpec, filePath)) {
83
+ const resolved = await context.resolve(moduleSpec, filePath);
84
+ if (resolved) {
85
+ const mapped = fileToModuleMap.get(resolved.id);
86
+ if (mapped) resolvedSpec = mapped;
87
+ else context.trace(`Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`);
88
+ }
89
+ }
90
+ if (namespaceImport) importLines.push(`\timport * as ${namespaceImport.getText()} from '${resolvedSpec}';`);
91
+ else {
92
+ const specifiers = [];
93
+ if (defaultImport) specifiers.push(`default as ${defaultImport.getText()}`);
94
+ for (const named of namedImports) {
95
+ const alias = named.getAliasNode()?.getText();
96
+ specifiers.push(alias ? `${named.getName()} as ${alias}` : named.getName());
97
+ }
98
+ if (specifiers.length > 0) {
99
+ const typeOnly = statement.isTypeOnly() ? " type" : "";
100
+ importLines.push(`\timport${typeOnly} { ${specifiers.join(", ")} } from '${resolvedSpec}';`);
101
+ }
102
+ }
103
+ continue;
104
+ }
105
+ if (Node.isExportDeclaration(statement)) {
106
+ const moduleSpec = statement.getModuleSpecifierValue();
107
+ if (moduleSpec) {
108
+ let resolvedSpec = moduleSpec;
109
+ if (context.fs.isResolvableId(moduleSpec, filePath)) {
110
+ const resolved = await context.resolve(moduleSpec, filePath);
111
+ if (resolved) {
112
+ const mapped = fileToModuleMap.get(resolved.id);
113
+ if (mapped) resolvedSpec = mapped;
114
+ else context.trace(`Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`);
115
+ }
116
+ }
117
+ const namedExports = statement.getNamedExports();
118
+ if (namedExports.length > 0) {
119
+ const specifiers = namedExports.map((named) => {
120
+ const alias = named.getAliasNode()?.getText();
121
+ return alias ? `${named.getName()} as ${alias}` : named.getName();
122
+ });
123
+ const typeOnly = statement.isTypeOnly() ? " type" : "";
124
+ reExportLines.push(`\texport${typeOnly} { ${specifiers.join(", ")} } from '${resolvedSpec}';`);
125
+ } else reExportLines.push(`\texport * from '${resolvedSpec}';`);
126
+ } else declarationLines.push(`\t${statement.getText()}`);
127
+ continue;
128
+ }
129
+ if (Node.isExportAssignment(statement)) {
130
+ declarationLines.push(`\t${statement.getText()}`);
131
+ continue;
132
+ }
133
+ const text = statement.getText();
134
+ if (text.includes("//# sourceMappingURL=")) continue;
135
+ declarationLines.push(formatTypes(text.replace(/^(export\s+)?declare\s+/, "$1")).split("\n").map((line) => `\t${line}`).join("\n"));
136
+ }
137
+ const moduleComment = code.match(new RegExp(`\\/\\*\\*(?s:.)*?@module\\s+${context.config.framework}:${id}(?s:.)*?\\*\\/\\s+`))?.find((comment) => isSetString(comment?.trim()));
138
+ let content = `${moduleComment ? `${moduleComment.trim()}\n` : ""}declare module "${context.config.framework}:${id}" {`;
139
+ for (const line of importLines) content += `\n${line}`;
140
+ for (const line of reExportLines) content += `\n${line}`;
141
+ for (const line of declarationLines) content += `\n${line}`;
142
+ content += "\n}";
143
+ return {
144
+ content,
145
+ mappings,
146
+ ambient
147
+ };
148
+ }
149
+ /**
150
+ * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.
151
+ *
152
+ * @param context - The context containing options and environment paths.
153
+ * @param files - The list of files to generate types for.
154
+ * @returns A promise that resolves to the generated TypeScript declaration types.
155
+ */
156
+ async function emitBuiltinTypes(context, files) {
157
+ if (files.length === 0) {
158
+ context.debug("No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.");
159
+ return {
160
+ code: "",
161
+ directives: []
162
+ };
163
+ }
164
+ context.debug(`Running the TypeScript compiler for ${files.length} generated built-in module files.`);
165
+ const program = createProgram(context, {
166
+ skipAddingFilesFromTsConfig: true,
167
+ compilerOptions: {
168
+ declaration: true,
169
+ declarationMap: false,
170
+ emitDeclarationOnly: true,
171
+ sourceMap: false,
172
+ outDir: replacePath(context.builtinsPath, context.workspaceConfig.workspaceRoot),
173
+ composite: false,
174
+ incremental: false,
175
+ tsBuildInfoFile: void 0
176
+ }
177
+ });
178
+ program.addSourceFilesAtPaths(files);
179
+ const emitResult = program.emitToMemory({ emitOnlyDtsFiles: true });
180
+ const diagnostics = emitResult.getDiagnostics();
181
+ if (diagnostics && diagnostics.length > 0) if (diagnostics.some((d) => d.getCategory() === DiagnosticCategory.Error)) throw new Error(`The Typescript emit process failed while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === DiagnosticCategory.Error).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
182
+ else if (diagnostics.some((d) => d.getCategory() === DiagnosticCategory.Warning)) context.warn(`The Typescript emit process completed with warnings while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === DiagnosticCategory.Warning).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
183
+ 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")}`);
184
+ const emittedFiles = emitResult.getFiles();
185
+ context.debug(`The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`);
186
+ if (emittedFiles.length === 0) {
187
+ context.warn("The TypeScript compiler did not emit any files for built-in types. This may indicate an issue with the TypeScript configuration or the provided files.");
188
+ return {
189
+ code: "",
190
+ directives: []
191
+ };
192
+ }
193
+ const fileToModuleMap = /* @__PURE__ */ new Map();
194
+ const emittedBuiltinFiles = [];
195
+ for (const emittedFile of emittedFiles) {
196
+ const filePath = appendPath(emittedFile.filePath, context.workspaceConfig.workspaceRoot);
197
+ if (!filePath.endsWith(".map") && findFileName(filePath) !== "tsconfig.tsbuildinfo" && isParentPath(filePath, context.builtinsPath)) {
198
+ const moduleId = replaceExtension(replacePath(replacePath(filePath, context.builtinsPath), replacePath(context.builtinsPath, context.workspaceConfig.workspaceRoot)), "", { fullExtension: true });
199
+ if (context.builtins.includes(moduleId)) {
200
+ fileToModuleMap.set(filePath, moduleId);
201
+ emittedBuiltinFiles.push({
202
+ filePath,
203
+ text: emittedFile.text
204
+ });
205
+ }
206
+ }
207
+ }
208
+ const builtins = await context.getBuiltins();
209
+ const emittedContentMap = /* @__PURE__ */ new Map();
210
+ for (const emittedFile of emittedFiles) {
211
+ const filePath = appendPath(emittedFile.filePath, context.workspaceConfig.workspaceRoot);
212
+ if (!filePath.endsWith(".map") && findFileName(filePath) !== "tsconfig.tsbuildinfo") emittedContentMap.set(filePath, emittedFile.text);
213
+ }
214
+ let code = "";
215
+ const directives = [];
216
+ const ambientModules = /* @__PURE__ */ new Set();
217
+ let isFirst = true;
218
+ for (const entry of emittedBuiltinFiles) {
219
+ context.trace(`Processing emitted type declaration file: ${entry.filePath}`);
220
+ const moduleId = fileToModuleMap.get(entry.filePath);
221
+ const moduleDecl = await extractModuleDeclarations(context, entry.filePath, moduleId, entry.text, fileToModuleMap);
222
+ if (!isFirst) code += "\n\n";
223
+ isFirst = false;
224
+ code += moduleDecl.content;
225
+ for (const dep of moduleDecl.ambient) if (dep.external) {
226
+ const directive = dep.id;
227
+ if (!directives.includes(directive)) directives.push(directive);
228
+ } else if (builtins.some((builtin) => builtin.id === dep.id)) ambientModules.add(builtins.find((builtin) => builtin.id === dep.id).path);
229
+ else if (builtins.some((builtin) => replaceExtension(builtin.path) === replaceExtension(dep.id))) ambientModules.add(dep.id);
230
+ else {
231
+ const resolved = await context.resolve(dep.id, entry.filePath);
232
+ if (resolved) {
233
+ for (const name of [
234
+ resolved.id,
235
+ `${resolved.id}.d.ts`,
236
+ `${resolved.id}.d.mts`,
237
+ `${resolved.id}.d.cts`,
238
+ replaceExtension(resolved.id, ".d.ts"),
239
+ replaceExtension(resolved.id, ".d.mts"),
240
+ replaceExtension(resolved.id, ".d.cts"),
241
+ `${resolved.id}/index.d.ts`
242
+ ]) if (emittedContentMap.has(name)) {
243
+ ambientModules.add(name);
244
+ break;
245
+ }
246
+ }
247
+ }
248
+ }
249
+ for (const ambientFile of ambientModules) {
250
+ const dts = emittedContentMap.get(ambientFile);
251
+ if (dts) {
252
+ const cleaned = dts.replace(/\/\/# sourceMappingURL=.*$/m, "").trim();
253
+ if (cleaned) code += `\n\n${formatTypes(cleaned)}`;
254
+ }
255
+ }
256
+ code = await (0, utils_exports.format)(context, context.typesPath, code);
257
+ context.debug(`A TypeScript declaration file (size: ${prettyBytes(new Blob(toArray(code)).size)}) emitted for the built-in modules types.`);
258
+ return {
259
+ code,
260
+ directives
261
+ };
262
+ }
263
+
264
+ //#endregion
265
+ //#region src/_internal/helpers/install.ts
266
+ /**
267
+ * Installs a package if it is not already installed.
268
+ *
269
+ * @param context - The resolved options
270
+ * @param packageName - The name of the package to install
271
+ * @param dev - Whether to install the package as a dev dependency
272
+ */
273
+ async function installPackage(context, packageName, dev = false) {
274
+ if (!await isPackageListed(getPackageName(packageName), { cwd: context.config.root })) if (context.config.autoInstall) {
275
+ context.warn(`The package "${packageName}" is not installed. It will be installed automatically.`);
276
+ const result = await install(packageName, {
277
+ cwd: context.config.root,
278
+ dev
279
+ });
280
+ if (isNumber(result.exitCode) && result.exitCode > 0) {
281
+ context.error(result.stderr);
282
+ throw new Error(`An error occurred while installing the package "${packageName}"`);
283
+ }
284
+ } else context.warn(`The package "${packageName}" is not installed. Since the "autoInstall" option is set to false, it will not be installed automatically.`);
285
+ else if (hasPackageVersion(packageName) && !process.env.POWERLINES_SKIP_VERSION_CHECK) {
286
+ if (!await doesPackageMatch(getPackageName(packageName), getPackageVersion(packageName), context.config.root)) {
287
+ const packageListing = await getPackageListing(getPackageName(packageName), { cwd: context.config.root });
288
+ if (!packageListing?.version.startsWith("catalog:") && !packageListing?.version.startsWith("workspace:")) context.warn(`The package "${getPackageName(packageName)}" is installed but does not match the expected version ${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.`);
289
+ }
290
+ }
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/_internal/helpers/install-dependencies.ts
295
+ /**
296
+ * Install missing project dependencies.
297
+ *
298
+ * @param context - The build context.
299
+ */
300
+ async function installDependencies(context) {
301
+ context.debug(`Checking and installing missing project dependencies.`);
302
+ context.dependencies ??= {};
303
+ context.devDependencies ??= {};
304
+ if (Object.keys(context.dependencies).length === 0 && Object.keys(context.devDependencies).length === 0) {
305
+ context.debug(`No dependencies or devDependencies to install. Skipping installation step.`);
306
+ return;
307
+ }
308
+ context.debug(`The following packages are required: \nDependencies: \n${Object.entries(context.dependencies).map(([name, version]) => `- ${name}@${String(version)}`).join(" \n")}\n\nDevDependencies: \n${Object.entries(context.devDependencies).map(([name, version]) => `- ${name}@${String(version)}`).join(" \n")}`);
309
+ await Promise.all([Promise.all(Object.entries(context.dependencies).map(async ([name, version]) => installPackage(context, `${getPackageName(name)}@${String(version)}`, false))), Promise.all(Object.entries(context.devDependencies).map(async ([name, version]) => installPackage(context, `${getPackageName(name)}@${String(version)}`, true)))]);
310
+ }
311
+
312
+ //#endregion
313
+ //#region src/_internal/helpers/resolve-tsconfig.ts
314
+ function getTsconfigDtsPath(context) {
315
+ return joinPaths(relativePath(joinPaths(context.workspaceConfig.workspaceRoot, context.config.root), findFilePath(context.typesPath)), findFileName(context.typesPath));
316
+ }
317
+ async function resolveTsconfigChanges(context) {
318
+ const tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig, context.config.tsconfigRaw);
319
+ const tsconfigJson = await readJsonFile(getTsconfigFilePath(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig));
320
+ tsconfigJson.compilerOptions ??= {};
321
+ if (context.config.output.dts !== false) {
322
+ const dtsRelativePath = getTsconfigDtsPath(context);
323
+ if (!tsconfigJson.include?.some((filePattern) => isIncludeMatchFound(filePattern, [context.typesPath, dtsRelativePath]))) {
324
+ tsconfigJson.include ??= [];
325
+ tsconfigJson.include.push(dtsRelativePath.startsWith("./") ? dtsRelativePath.slice(2) : dtsRelativePath);
326
+ }
327
+ }
328
+ if (!tsconfig.options.lib?.some((lib) => [
329
+ "lib.esnext.d.ts",
330
+ "lib.es2021.d.ts",
331
+ "lib.es2022.d.ts",
332
+ "lib.es2023.d.ts"
333
+ ].includes(lib.toLowerCase()))) {
334
+ tsconfigJson.compilerOptions.lib ??= [];
335
+ tsconfigJson.compilerOptions.lib.push("esnext");
336
+ }
337
+ if (tsconfig.options.esModuleInterop !== true) tsconfigJson.compilerOptions.esModuleInterop = true;
338
+ if (tsconfig.options.isolatedModules !== true) tsconfigJson.compilerOptions.isolatedModules = true;
339
+ if (context.config.platform === "node") {
340
+ if (!tsconfig.options.types?.some((type) => type.toLowerCase() === "node" || type.toLowerCase() === "@types/node")) {
341
+ tsconfigJson.compilerOptions.types ??= [];
342
+ tsconfigJson.compilerOptions.types.push("node");
343
+ }
344
+ }
345
+ return tsconfigJson;
346
+ }
347
+ async function initializeTsconfig(context) {
348
+ context.debug("Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.");
349
+ if (!isPackageExists("typescript")) throw new Error("The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"");
350
+ const tsconfigFilePath = getTsconfigFilePath(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig);
351
+ context.tsconfig.originalTsconfigJson = await readJsonFile(tsconfigFilePath);
352
+ context.tsconfig.tsconfigJson = await resolveTsconfigChanges(context);
353
+ context.debug("Writing updated TypeScript configuration (tsconfig.json) file to disk.");
354
+ await context.fs.write(tsconfigFilePath, StormJSON.stringify(context.tsconfig.tsconfigJson));
355
+ context.tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig, context.config.tsconfigRaw, context.tsconfig.originalTsconfigJson);
356
+ }
357
+ async function resolveTsconfig(context) {
358
+ const updateTsconfigJson = await readJsonFile(context.tsconfig.tsconfigFilePath);
359
+ if (updateTsconfigJson?.compilerOptions?.types && Array.isArray(updateTsconfigJson.compilerOptions.types) && !updateTsconfigJson.compilerOptions.types.length) delete updateTsconfigJson.compilerOptions.types;
360
+ const result = getObjectDiff(context.tsconfig.originalTsconfigJson, updateTsconfigJson, {
361
+ ignoreArrayOrder: true,
362
+ showOnly: {
363
+ statuses: [
364
+ "added",
365
+ "deleted",
366
+ "updated"
367
+ ],
368
+ granularity: "deep"
369
+ }
370
+ });
371
+ const changes = [];
372
+ const getChanges = (difference, property) => {
373
+ 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);
374
+ else changes.push({
375
+ field: property ? `${property}.${difference.property}` : difference.property,
376
+ status: difference.status,
377
+ previous: difference.status === "added" ? "---" : StormJSON.stringify(difference.previousValue),
378
+ current: difference.status === "deleted" ? "---" : StormJSON.stringify(difference.currentValue)
379
+ });
380
+ };
381
+ for (const diff of result.diff) getChanges(diff);
382
+ if (changes.length > 0) context.warn(`Updating the following configuration values in "${context.tsconfig.tsconfigFilePath}" file:
383
+
384
+ ${changes.map((change, i) => `${chalk.bold.whiteBright(`${i + 1}. ${titleCase(change.status)} the ${change.field} field: `)}
385
+ ${chalk.red(` - Previous: ${change.previous} `)}
386
+ ${chalk.green(` - Updated: ${change.current} `)}
387
+ `).join("\n")}
388
+ `);
389
+ await context.fs.write(context.tsconfig.tsconfigFilePath, StormJSON.stringify(updateTsconfigJson));
390
+ context.tsconfig = getParsedTypeScriptConfig(context.workspaceConfig.workspaceRoot, context.config.root, context.config.tsconfig);
391
+ if (!context.tsconfig) throw new Error("Failed to parse the TypeScript configuration file.");
392
+ }
393
+
394
+ //#endregion
395
+ //#region src/api.ts
396
+ /**
397
+ * The Powerlines API class
398
+ *
399
+ * @remarks
400
+ * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.
401
+ *
402
+ * @public
403
+ */
404
+ var PowerlinesAPI = class PowerlinesAPI {
405
+ /**
406
+ * The Powerlines context
407
+ */
408
+ #context;
409
+ /**
410
+ * The Powerlines context
411
+ */
412
+ get context() {
413
+ return this.#context;
414
+ }
415
+ /**
416
+ * Create a new Powerlines API instance
417
+ *
418
+ * @param context - The Powerlines context
419
+ */
420
+ constructor(context) {
421
+ this.#context = context;
422
+ }
423
+ /**
424
+ * Initialize a Powerlines API instance
425
+ *
426
+ * @param workspaceRoot - The directory of the underlying workspace the Powerlines project exists in
427
+ * @param config - An object containing the configuration required to run Powerlines tasks.
428
+ * @returns A new instance of the Powerlines API
429
+ */
430
+ static async from(workspaceRoot, config) {
431
+ const api = new PowerlinesAPI(await PowerlinesAPIContext.from(workspaceRoot, config));
432
+ api.#context.$$internal = {
433
+ api,
434
+ addPlugin: api.#addPlugin.bind(api)
435
+ };
436
+ api.context.info(`🔌 The Powerlines Engine v${version} has started`);
437
+ for (const plugin of api.context.config.plugins.flat(10) ?? []) await api.#addPlugin(plugin);
438
+ 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.");
439
+ else api.context.info(`Loaded ${api.context.plugins.length} ${titleCase(api.context.config.framework)} plugin${api.context.plugins.length > 1 ? "s" : ""}: \n${api.context.plugins.map((plugin, index) => ` ${index + 1}. ${(0, utils_exports.colorText)(plugin.name)}`).join("\n")}`);
440
+ const pluginConfig = await api.callHook("config", {
441
+ environment: await api.context.getEnvironment(),
442
+ sequential: true,
443
+ result: "merge",
444
+ merge: mergeConfigs
445
+ });
446
+ await api.context.withUserConfig(pluginConfig, { isHighPriority: false });
447
+ return api;
448
+ }
449
+ /**
450
+ * Generate the Powerlines typescript declaration file
451
+ *
452
+ * @remarks
453
+ * This method will only generate the typescript declaration file for the Powerlines project. It is generally recommended to run the full `prepare` command, which will run this method as part of its process.
454
+ *
455
+ * @param inlineConfig - The inline configuration for the types command
456
+ */
457
+ async types(inlineConfig = { command: "types" }) {
458
+ this.context.info(" 🏗️ Generating typescript declarations for the Powerlines project");
459
+ this.context.debug(" Aggregating configuration options for the Powerlines project");
460
+ inlineConfig.command ??= "types";
461
+ await this.context.withInlineConfig(inlineConfig);
462
+ await this.#executeEnvironments(async (context) => {
463
+ context.debug(`Initializing the processing options for the Powerlines project.`);
464
+ await this.callHook("configResolved", {
465
+ environment: context,
466
+ order: "pre"
467
+ });
468
+ await initializeTsconfig(context);
469
+ await this.callHook("configResolved", {
470
+ environment: context,
471
+ order: "normal"
472
+ });
473
+ if (context.entry.length > 0) context.debug(`The configuration provided ${isObject(context.config.input) ? Object.keys(context.config.input).length : 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")}` : ""}`);
474
+ 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.`);
475
+ await resolveTsconfig(context);
476
+ await installDependencies(context);
477
+ await this.callHook("configResolved", {
478
+ environment: context,
479
+ order: "post"
480
+ });
481
+ context.trace(`Powerlines configuration has been resolved: \n\n${formatLogMessage({
482
+ ...context.config,
483
+ userConfig: isSetObject(context.config.userConfig) ? omit(context.config.userConfig, ["plugins"]) : void 0,
484
+ inlineConfig: isSetObject(context.config.inlineConfig) ? omit(context.config.inlineConfig, ["plugins"]) : void 0,
485
+ plugins: context.plugins.map((plugin) => plugin.plugin.name)
486
+ })}`);
487
+ if (!context.fs.existsSync(context.cachePath)) await createDirectory(context.cachePath);
488
+ if (!context.fs.existsSync(context.dataPath)) await createDirectory(context.dataPath);
489
+ if (context.config.skipCache === true || context.persistedMeta?.checksum !== context.meta.checksum) context.debug(`Using previously prepared files as the meta checksum has not changed.`);
490
+ else {
491
+ context.info(`Running \`prepare\` command as the meta checksum has changed since the last run.`);
492
+ await this.prepare(defu$1({ output: { types: false } }, inlineConfig));
493
+ }
494
+ await this.#types(context);
495
+ this.context.debug("Formatting files generated during the types step.");
496
+ await (0, utils_exports.format)(context, context.typesPath, await context.fs.read(context.typesPath) ?? "");
497
+ await writeMetaFile(context);
498
+ context.persistedMeta = context.meta;
499
+ });
500
+ this.context.debug("✔ Powerlines types generation has completed successfully");
501
+ }
502
+ /**
503
+ * Prepare the Powerlines API
504
+ *
505
+ * @remarks
506
+ * This method will prepare the Powerlines API for use, initializing any necessary resources.
507
+ *
508
+ * @param inlineConfig - The inline configuration for the prepare command
509
+ */
510
+ async prepare(inlineConfig = { command: "prepare" }) {
511
+ this.context.info(" 🏗️ Preparing the Powerlines project");
512
+ this.context.debug(" Aggregating configuration options for the Powerlines project");
513
+ inlineConfig.command ??= "prepare";
514
+ await this.context.withInlineConfig(inlineConfig);
515
+ await this.#executeEnvironments(async (context) => {
516
+ context.debug(`Initializing the processing options for the Powerlines project.`);
517
+ await this.callHook("configResolved", {
518
+ environment: context,
519
+ order: "pre"
520
+ });
521
+ await initializeTsconfig(context);
522
+ await this.callHook("configResolved", {
523
+ environment: context,
524
+ order: "normal"
525
+ });
526
+ if (context.entry.length > 0) context.debug(`The configuration provided ${isObject(context.config.input) ? Object.keys(context.config.input).length : 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")}` : ""}`);
527
+ 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.`);
528
+ await resolveTsconfig(context);
529
+ await installDependencies(context);
530
+ await this.callHook("configResolved", {
531
+ environment: context,
532
+ order: "post"
533
+ });
534
+ context.trace(`Powerlines configuration has been resolved: \n\n${formatLogMessage({
535
+ ...context.config,
536
+ userConfig: isSetObject(context.config.userConfig) ? omit(context.config.userConfig, ["plugins"]) : void 0,
537
+ inlineConfig: isSetObject(context.config.inlineConfig) ? omit(context.config.inlineConfig, ["plugins"]) : void 0,
538
+ plugins: context.plugins.map((plugin) => plugin.plugin.name)
539
+ })}`);
540
+ if (!context.fs.existsSync(context.cachePath)) await createDirectory(context.cachePath);
541
+ if (!context.fs.existsSync(context.dataPath)) await createDirectory(context.dataPath);
542
+ await this.callHook("prepare", {
543
+ environment: context,
544
+ order: "pre"
545
+ });
546
+ await this.callHook("prepare", {
547
+ environment: context,
548
+ order: "normal"
549
+ });
550
+ await this.callHook("prepare", {
551
+ environment: context,
552
+ order: "post"
553
+ });
554
+ if (context.config.output.types !== false) await this.#types(context);
555
+ this.context.debug("Formatting files generated during the prepare step.");
556
+ await Promise.all([(0, utils_exports.formatFolder)(context, context.builtinsPath), (0, utils_exports.formatFolder)(context, context.entryPath)]);
557
+ await writeMetaFile(context);
558
+ context.persistedMeta = context.meta;
559
+ });
560
+ this.context.debug("✔ Powerlines preparation has completed successfully");
561
+ }
562
+ /**
563
+ * Create a new Powerlines project
564
+ *
565
+ * @remarks
566
+ * This method will create a new Powerlines project in the current directory.
567
+ *
568
+ * @param inlineConfig - The inline configuration for the new command
569
+ * @returns A promise that resolves when the project has been created
570
+ */
571
+ async new(inlineConfig) {
572
+ this.context.info(" 🆕 Creating a new Powerlines project");
573
+ inlineConfig.command ??= "new";
574
+ await this.prepare(inlineConfig);
575
+ await this.#executeEnvironments(async (context) => {
576
+ context.debug("Initializing the processing options for the Powerlines project.");
577
+ await this.callHook("new", {
578
+ environment: context,
579
+ order: "pre"
580
+ });
581
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/common/**/*.hbs"));
582
+ for (const file of files) {
583
+ context.trace(`Adding template file to project: ${file}`);
584
+ const template = Handlebars.compile(file);
585
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
586
+ }
587
+ await this.callHook("new", {
588
+ environment: context,
589
+ order: "normal"
590
+ });
591
+ if (context.config.projectType === "application") {
592
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/application/**/*.hbs"));
593
+ for (const file of files) {
594
+ context.trace(`Adding application template file: ${file}`);
595
+ const template = Handlebars.compile(file);
596
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
597
+ }
598
+ } else {
599
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/library/**/*.hbs"));
600
+ for (const file of files) {
601
+ context.trace(`Adding library template file: ${file}`);
602
+ const template = Handlebars.compile(file);
603
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
604
+ }
605
+ }
606
+ await this.callHook("new", {
607
+ environment: context,
608
+ order: "post"
609
+ });
610
+ });
611
+ this.context.debug("✔ Powerlines new command completed successfully");
612
+ }
613
+ /**
614
+ * Clean any previously prepared artifacts
615
+ *
616
+ * @remarks
617
+ * This method will remove the previous Powerlines artifacts from the project.
618
+ *
619
+ * @param inlineConfig - The inline configuration for the clean command
620
+ * @returns A promise that resolves when the clean command has completed
621
+ */
622
+ async clean(inlineConfig = { command: "clean" }) {
623
+ this.context.info(" 🧹 Cleaning the previous Powerlines artifacts");
624
+ inlineConfig.command ??= "clean";
625
+ await this.prepare(inlineConfig);
626
+ await this.#executeEnvironments(async (context) => {
627
+ context.debug("Cleaning the project's dist and artifacts directories.");
628
+ await context.fs.remove(joinPaths(context.workspaceConfig.workspaceRoot, context.config.output.path));
629
+ await context.fs.remove(joinPaths(context.workspaceConfig.workspaceRoot, context.config.root, context.config.output.artifactsPath));
630
+ await this.callHook("clean", {
631
+ environment: context,
632
+ sequential: false
633
+ });
634
+ });
635
+ this.context.debug("✔ Powerlines cleaning completed successfully");
636
+ }
637
+ /**
638
+ * Lint the project
639
+ *
640
+ * @param inlineConfig - The inline configuration for the lint command
641
+ * @returns A promise that resolves when the lint command has completed
642
+ */
643
+ async lint(inlineConfig = { command: "lint" }) {
644
+ this.context.info(" 📝 Linting the Powerlines project");
645
+ inlineConfig.command ??= "lint";
646
+ await this.prepare(inlineConfig);
647
+ await this.#executeEnvironments(async (context) => {
648
+ await this.callHook("lint", {
649
+ environment: context,
650
+ sequential: false
651
+ });
652
+ });
653
+ this.context.debug("✔ Powerlines linting completed successfully");
654
+ }
655
+ /**
656
+ * Build the project
657
+ *
658
+ * @remarks
659
+ * This method will build the Powerlines project, generating the necessary artifacts.
660
+ *
661
+ * @param inlineConfig - The inline configuration for the build command
662
+ * @returns A promise that resolves when the build command has completed
663
+ */
664
+ async build(inlineConfig = { command: "build" }) {
665
+ this.context.info(" 📦 Building the Powerlines project");
666
+ await this.context.generateChecksum();
667
+ if (this.context.meta.checksum !== this.context.persistedMeta?.checksum || this.context.config.skipCache) {
668
+ this.context.info(!this.context.persistedMeta?.checksum ? "No previous build cache found. Preparing the project for the initial build." : this.context.meta.checksum !== this.context.persistedMeta.checksum ? "The project has been modified since the last time `prepare` was ran. Re-preparing the project." : "The project is configured to skip cache. Re-preparing the project.");
669
+ inlineConfig.command ??= "build";
670
+ await this.prepare(inlineConfig);
671
+ }
672
+ if (this.context.config.singleBuild) await this.#handleBuild(await this.#context.toEnvironment());
673
+ else await this.#executeEnvironments(async (context) => {
674
+ await this.#handleBuild(context);
675
+ });
676
+ this.context.debug("✔ Powerlines build completed successfully");
677
+ }
678
+ /**
679
+ * Prepare the documentation for the project
680
+ *
681
+ * @param inlineConfig - The inline configuration for the docs command
682
+ * @returns A promise that resolves when the documentation generation has completed
683
+ */
684
+ async docs(inlineConfig = { command: "docs" }) {
685
+ this.context.info(" 📓 Generating documentation for the Powerlines project");
686
+ inlineConfig.command ??= "docs";
687
+ await this.prepare(inlineConfig);
688
+ await this.#executeEnvironments(async (context) => {
689
+ context.debug("Writing documentation for the Powerlines project artifacts.");
690
+ inlineConfig.command ??= "docs";
691
+ await this.prepare(inlineConfig);
692
+ await this.#executeEnvironments(async (context) => {
693
+ await this.callHook("docs", { environment: context });
694
+ });
695
+ });
696
+ this.context.debug("✔ Powerlines documentation generation completed successfully");
697
+ }
698
+ /**
699
+ * Deploy the project source code
700
+ *
701
+ * @remarks
702
+ * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.
703
+ *
704
+ * @param inlineConfig - The inline configuration for the deploy command
705
+ */
706
+ async deploy(inlineConfig = { command: "deploy" }) {
707
+ this.context.info(" 🚀 Deploying the Powerlines project");
708
+ inlineConfig.command ??= "deploy";
709
+ await this.prepare(inlineConfig);
710
+ await this.#executeEnvironments(async (context) => {
711
+ await this.callHook("deploy", { environment: context });
712
+ });
713
+ this.context.debug("✔ Powerlines deploy completed successfully");
714
+ }
715
+ /**
716
+ * Finalization process
717
+ *
718
+ * @remarks
719
+ * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.
720
+ *
721
+ * @returns A promise that resolves when the finalization process has completed
722
+ */
723
+ async finalize() {
724
+ this.context.info(" 🏁 Powerlines finalization processes started");
725
+ await this.#executeEnvironments(async (context) => {
726
+ await this.callHook("finalize", { environment: context });
727
+ await context.fs.dispose();
728
+ if (existsSync(context.cachePath) && !(await listFiles(joinPaths(context.cachePath, "**/*")))?.length) await removeDirectory(context.cachePath);
729
+ });
730
+ this.context.debug("✔ Powerlines finalization completed successfully");
731
+ }
732
+ /**
733
+ * Invokes the configured plugin hooks
734
+ *
735
+ * @remarks
736
+ * By default, it will call the `"pre"`, `"normal"`, and `"post"` ordered hooks in sequence
737
+ *
738
+ * @param hook - The hook to call
739
+ * @param options - The options to provide to the hook
740
+ * @param args - The arguments to pass to the hook
741
+ * @returns The result of the hook call
742
+ */
743
+ async callHook(hook, options, ...args) {
744
+ return callHook(isSetObject(options?.environment) ? options.environment : await this.#context.getEnvironment(options?.environment), hook, {
745
+ sequential: true,
746
+ ...options
747
+ }, ...args);
748
+ }
749
+ /**
750
+ * Dispose of the Powerlines API instance
751
+ *
752
+ * @remarks
753
+ * This method will finalize the Powerlines API instance, cleaning up any resources used.
754
+ */
755
+ async [Symbol.asyncDispose]() {
756
+ await this.finalize();
757
+ }
758
+ async #handleBuild(context) {
759
+ await this.callHook("build", {
760
+ environment: context,
761
+ order: "pre"
762
+ });
763
+ context.debug("Formatting the generated entry files before the build process starts.");
764
+ await (0, utils_exports.formatFolder)(context, context.entryPath);
765
+ await this.callHook("build", {
766
+ environment: context,
767
+ order: "normal"
768
+ });
769
+ if (context.config.output.copy) {
770
+ context.debug("Copying project's files from build output directory.");
771
+ const destinationPath = isParentPath(appendPath(context.config.output.path, context.workspaceConfig.workspaceRoot), appendPath(context.config.root, context.workspaceConfig.workspaceRoot)) ? joinPaths(context.config.output.copy.path, relativePath(appendPath(context.config.root, context.workspaceConfig.workspaceRoot), appendPath(context.config.output.path, context.workspaceConfig.workspaceRoot))) : joinPaths(context.config.output.copy.path, "dist");
772
+ const sourcePath = appendPath(context.config.output.path, context.workspaceConfig.workspaceRoot);
773
+ if (existsSync(sourcePath) && sourcePath !== destinationPath) {
774
+ context.debug(`Copying files from project's build output directory (${context.config.output.path}) to the project's copy/publish directory (${destinationPath}).`);
775
+ await copyFiles(sourcePath, destinationPath);
776
+ } else context.warn(`The source path for the copy operation ${!existsSync(sourcePath) ? "does not exist" : "is the same as the destination path"}. Source: ${sourcePath}, Destination: ${destinationPath}. Skipping copying of build output files.`);
777
+ if (context.config.output.copy.assets && Array.isArray(context.config.output.copy.assets)) await Promise.all(context.config.output.copy.assets.map(async (asset) => {
778
+ context.trace(`Copying asset(s): ${chalk.redBright(context.workspaceConfig.workspaceRoot === asset.input ? asset.glob : appendPath(asset.glob, replacePath(asset.input, context.workspaceConfig.workspaceRoot)))} -> ${chalk.greenBright(appendPath(asset.glob, replacePath(asset.output, context.workspaceConfig.workspaceRoot)))} ${Array.isArray(asset.ignore) && asset.ignore.length > 0 ? ` (ignoring: ${asset.ignore.map((i) => chalk.yellowBright(i)).join(", ")})` : ""}`);
779
+ await context.fs.copy(asset, asset.output);
780
+ }));
781
+ } else context.debug("No copy configuration found for the project output. Skipping the copying of build output files.");
782
+ await this.callHook("build", {
783
+ environment: context,
784
+ order: "post"
785
+ });
786
+ }
787
+ /**
788
+ * Get the configured environments
789
+ *
790
+ * @returns The configured environments
791
+ */
792
+ async #getEnvironments() {
793
+ if (!this.context.config.environments || Object.keys(this.context.config.environments).length <= 1) {
794
+ this.context.debug("No environments are configured for this Powerlines project. Using the default environment.");
795
+ return [await this.context.getEnvironment()];
796
+ }
797
+ this.context.debug(`Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`);
798
+ return (await Promise.all(Object.entries(this.context.config.environments).map(async ([name, config]) => {
799
+ if (!await this.context.getEnvironmentSafe(name)) {
800
+ const resolvedEnvironment = await this.callHook("configEnvironment", { environment: name }, name, config);
801
+ if (resolvedEnvironment) this.context.environments[name] = await this.context.in(resolvedEnvironment);
802
+ }
803
+ return this.context.environments[name];
804
+ }))).filter((context) => isSet(context));
805
+ }
806
+ /**
807
+ * Execute a handler function for each environment
808
+ *
809
+ * @param handle - The handler function to execute for each environment
810
+ */
811
+ async #executeEnvironments(handle) {
812
+ await Promise.all((await this.#getEnvironments()).map(async (context) => {
813
+ return Promise.resolve(handle(context));
814
+ }));
815
+ }
816
+ /**
817
+ * Add a Powerlines plugin used in the build process
818
+ *
819
+ * @param config - The import path of the plugin to add
820
+ */
821
+ async #addPlugin(config) {
822
+ if (config) {
823
+ const result = await this.#initPlugin(config);
824
+ if (!result) return;
825
+ for (const plugin of result) {
826
+ this.context.debug(`Successfully initialized the ${chalk.bold.cyanBright(plugin.name)} plugin`);
827
+ await this.context.addPlugin(plugin);
828
+ }
829
+ }
830
+ }
831
+ /**
832
+ * Initialize a Powerlines plugin
833
+ *
834
+ * @param config - The configuration for the plugin
835
+ * @returns The initialized plugin instance, or null if the plugin was a duplicate
836
+ * @throws Will throw an error if the plugin cannot be found or is invalid
837
+ */
838
+ async #initPlugin(config) {
839
+ let awaited = config;
840
+ if (isPromiseLike(config)) awaited = await Promise.resolve(config);
841
+ if (!(0, plugin_utils_exports.isPluginConfig)(awaited)) {
842
+ const invalid = (0, plugin_utils_exports.findInvalidPluginConfig)(awaited);
843
+ 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`);
844
+ }
845
+ let plugins;
846
+ if ((0, plugin_utils_exports.isPlugin)(awaited)) plugins = [awaited];
847
+ else if (isFunction(awaited)) plugins = toArray(await Promise.resolve(awaited()));
848
+ else if (isString(awaited)) {
849
+ const resolved = await this.#resolvePlugin(awaited);
850
+ if (isFunction(resolved)) plugins = toArray(await Promise.resolve(resolved()));
851
+ else plugins = toArray(resolved);
852
+ } else if (Array.isArray(awaited) && awaited.every(plugin_utils_exports.isPlugin)) plugins = awaited;
853
+ else if (Array.isArray(awaited) && awaited.every(plugin_utils_exports.isPluginConfig)) {
854
+ plugins = [];
855
+ for (const pluginConfig of awaited) {
856
+ const initialized = await this.#initPlugin(pluginConfig);
857
+ if (initialized) plugins.push(...initialized);
858
+ }
859
+ } else if ((0, plugin_utils_exports.isPluginConfigTuple)(awaited) || (0, plugin_utils_exports.isPluginConfigObject)(awaited)) {
860
+ let pluginConfig;
861
+ let pluginOptions;
862
+ if ((0, plugin_utils_exports.isPluginConfigTuple)(awaited)) {
863
+ pluginConfig = awaited[0];
864
+ pluginOptions = awaited?.length === 2 ? awaited[1] : void 0;
865
+ } else {
866
+ pluginConfig = awaited.plugin;
867
+ pluginOptions = awaited.options;
868
+ }
869
+ if (isSetString(pluginConfig)) {
870
+ const resolved = await this.#resolvePlugin(pluginConfig);
871
+ if (isFunction(resolved)) plugins = toArray(await Promise.resolve(pluginOptions ? resolved(pluginOptions) : resolved()));
872
+ else plugins = toArray(resolved);
873
+ } else if (isFunction(pluginConfig)) plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));
874
+ else if (Array.isArray(pluginConfig) && pluginConfig.every(plugin_utils_exports.isPlugin)) plugins = pluginConfig;
875
+ else if ((0, plugin_utils_exports.isPlugin)(pluginConfig)) plugins = toArray(pluginConfig);
876
+ }
877
+ if (!plugins) throw new Error(`The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`);
878
+ if (plugins.length > 0 && !plugins.every(plugin_utils_exports.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.`);
879
+ const result = [];
880
+ for (const plugin of plugins) if ((0, plugin_utils_exports.isDuplicate)(plugin, this.context.plugins)) this.context.trace(`Duplicate ${chalk.bold.cyanBright(plugin.name)} plugin dependency detected - Skipping initialization.`);
881
+ else {
882
+ result.push(plugin);
883
+ this.context.trace(`Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`);
884
+ }
885
+ return result;
886
+ }
887
+ async #resolvePlugin(pluginPath) {
888
+ if (pluginPath.startsWith("@") && pluginPath.split("/").filter(Boolean).length > 2) {
889
+ const splits = pluginPath.split("/").filter(Boolean);
890
+ pluginPath = `${splits[0]}/${splits[1]}`;
891
+ }
892
+ const isInstalled = isPackageExists(pluginPath, { paths: [this.context.workspaceConfig.workspaceRoot, this.context.config.root] });
893
+ if (!isInstalled && this.context.config.autoInstall) {
894
+ this.#context.warn(`The plugin package "${pluginPath}" is not installed. It will be installed automatically.`);
895
+ const result = await install(pluginPath, { cwd: this.context.config.root });
896
+ if (isNumber(result.exitCode) && result.exitCode > 0) {
897
+ this.#context.error(result.stderr);
898
+ throw new Error(`An error occurred while installing the build plugin package "${pluginPath}" `);
899
+ }
900
+ }
901
+ try {
902
+ const module = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve(joinPaths(pluginPath, "plugin")));
903
+ const result = module.plugin ?? module.default;
904
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
905
+ return result;
906
+ } catch (error) {
907
+ try {
908
+ const module = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve(pluginPath));
909
+ const result = module.plugin ?? module.default;
910
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
911
+ return result;
912
+ } catch {
913
+ if (!isInstalled) throw new Error(`The plugin package "${pluginPath}" is not installed. Please install the package using the command: "npm install ${pluginPath} --save-dev"`);
914
+ else throw new Error(`An error occurred while importing the build plugin package "${pluginPath}":
915
+ ${isError(error) ? error.message : String(error)}
916
+
917
+ 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\`.`);
918
+ }
919
+ }
920
+ }
921
+ /**
922
+ * Generate the Powerlines TypeScript declaration file
923
+ *
924
+ * @remarks
925
+ * This method will generate the TypeScript declaration file for the Powerlines project, including any types provided by plugins.
926
+ *
927
+ * @param context - The environment context to use for generating the TypeScript declaration file
928
+ * @returns A promise that resolves when the TypeScript declaration file has been generated
929
+ */
930
+ async #types(context) {
931
+ context.debug(`Preparing the TypeScript definitions for the Powerlines project.`);
932
+ if (context.fs.existsSync(context.typesPath)) await context.fs.remove(context.typesPath);
933
+ if (!await resolvePackage("typescript")) throw new Error("Could not resolve TypeScript package location. Please ensure TypeScript is installed.");
934
+ context.debug("Running TypeScript compiler for built-in runtime module files.");
935
+ let { code, directives } = await emitBuiltinTypes(context, (await context.getBuiltins()).reduce((ret, builtin) => {
936
+ const formatted = replacePath(builtin.path, context.workspaceConfig.workspaceRoot);
937
+ if (!ret.includes(formatted)) ret.push(formatted);
938
+ return ret;
939
+ }, []));
940
+ context.debug(`Generating TypeScript declaration file ${context.typesPath}.`);
941
+ const merge = async (currentResult, previousResult) => {
942
+ if (!isSetString(currentResult) && !isSetObject(currentResult) && !isSetString(previousResult) && !isSetObject(previousResult)) return {
943
+ code,
944
+ directives
945
+ };
946
+ const previous = (await (0, utils_exports.format)(context, context.typesPath, isSetString(previousResult) ? previousResult : isSetObject(previousResult) ? previousResult.code : "")).trim().replace(code, "").trim();
947
+ const current = (await (0, utils_exports.format)(context, context.typesPath, isSetString(currentResult) ? currentResult : isSetObject(currentResult) ? currentResult.code : "")).trim().replace(previous, "").trim().replace(code, "").trim();
948
+ return {
949
+ directives: [...isSetObject(currentResult) && currentResult.directives ? currentResult.directives : [], ...isSetObject(previousResult) && previousResult.directives ? previousResult.directives : []],
950
+ code: await (0, utils_exports.format)(context, context.typesPath, `${!previous.includes((0, utils_exports.getTypescriptFileHeader)(context)) && !current.includes((0, utils_exports.getTypescriptFileHeader)(context)) ? `${code}\n` : ""}${previous}\n${current}`.trim())
951
+ };
952
+ };
953
+ const asNextParam = (previousResult) => isObject(previousResult) ? previousResult.code : previousResult;
954
+ let result = await this.callHook("types", {
955
+ environment: context,
956
+ sequential: true,
957
+ order: "pre",
958
+ result: "merge",
959
+ merge,
960
+ asNextParam
961
+ }, code);
962
+ if (result) {
963
+ if (isSetObject(result)) {
964
+ code = result.code;
965
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
966
+ } else if (isSetString(result)) code = result;
967
+ }
968
+ result = await this.callHook("types", {
969
+ environment: context,
970
+ sequential: true,
971
+ order: "normal",
972
+ result: "merge",
973
+ merge,
974
+ asNextParam
975
+ }, code);
976
+ if (result) {
977
+ if (isSetObject(result)) {
978
+ code = result.code;
979
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
980
+ } else if (isSetString(result)) code = result;
981
+ }
982
+ result = await this.callHook("types", {
983
+ environment: context,
984
+ sequential: true,
985
+ order: "post",
986
+ result: "merge",
987
+ merge,
988
+ asNextParam
989
+ }, code);
990
+ if (result) {
991
+ if (isSetObject(result)) {
992
+ code = result.code;
993
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
994
+ } else if (isSetString(result)) code = result;
995
+ }
996
+ if (isSetString(code?.trim()) || directives.length > 0) await context.fs.write(context.typesPath, `${directives.length > 0 ? `${directives.map((directive) => `/// <reference types="${directive}" />`).join("\n")}
997
+
998
+ ` : ""}${(0, utils_exports.getTypescriptFileHeader)(context, {
999
+ directive: null,
1000
+ prettierIgnore: false
1001
+ })}
1002
+
1003
+ ${formatTypes(code)}
1004
+ `);
1005
+ }
1006
+ };
1007
+
1008
+ //#endregion
1009
+ export { name as n, version as r, PowerlinesAPI as t };
1010
+ //# sourceMappingURL=api-0aKfs398.mjs.map