@powerlines/plugin-webpack 0.5.132 → 0.5.133

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