@powerlines/engine 0.15.0 → 0.15.2

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 (195) hide show
  1. package/dist/api/build.cjs +66 -0
  2. package/dist/api/build.d.cts +14 -0
  3. package/dist/api/build.d.cts.map +1 -0
  4. package/dist/api/build.d.mts +14 -0
  5. package/dist/api/build.d.mts.map +1 -0
  6. package/dist/api/build.mjs +64 -0
  7. package/dist/api/build.mjs.map +1 -0
  8. package/dist/api/clean.cjs +29 -0
  9. package/dist/api/clean.d.cts +14 -0
  10. package/dist/api/clean.d.cts.map +1 -0
  11. package/dist/api/clean.d.mts +14 -0
  12. package/dist/api/clean.d.mts.map +1 -0
  13. package/dist/api/clean.mjs +28 -0
  14. package/dist/api/clean.mjs.map +1 -0
  15. package/dist/api/create.cjs +59 -0
  16. package/dist/api/create.d.cts +14 -0
  17. package/dist/api/create.d.cts.map +1 -0
  18. package/dist/api/create.d.mts +14 -0
  19. package/dist/api/create.d.mts.map +1 -0
  20. package/dist/api/create.mjs +57 -0
  21. package/dist/api/create.mjs.map +1 -0
  22. package/dist/api/deploy.cjs +25 -0
  23. package/dist/api/deploy.d.cts +17 -0
  24. package/dist/api/deploy.d.cts.map +1 -0
  25. package/dist/api/deploy.d.mts +17 -0
  26. package/dist/api/deploy.d.mts.map +1 -0
  27. package/dist/api/deploy.mjs +24 -0
  28. package/dist/api/deploy.mjs.map +1 -0
  29. package/dist/api/docs.cjs +25 -0
  30. package/dist/api/docs.d.cts +17 -0
  31. package/dist/api/docs.d.cts.map +1 -0
  32. package/dist/api/docs.d.mts +17 -0
  33. package/dist/api/docs.d.mts.map +1 -0
  34. package/dist/api/docs.mjs +24 -0
  35. package/dist/api/docs.mjs.map +1 -0
  36. package/dist/api/lint.cjs +28 -0
  37. package/dist/api/lint.d.cts +17 -0
  38. package/dist/api/lint.d.cts.map +1 -0
  39. package/dist/api/lint.d.mts +17 -0
  40. package/dist/api/lint.d.mts.map +1 -0
  41. package/dist/api/lint.mjs +27 -0
  42. package/dist/api/lint.mjs.map +1 -0
  43. package/dist/api/prepare.cjs +69 -0
  44. package/dist/api/prepare.d.cts +14 -0
  45. package/dist/api/prepare.d.cts.map +1 -0
  46. package/dist/api/prepare.d.mts +14 -0
  47. package/dist/api/prepare.d.mts.map +1 -0
  48. package/dist/api/prepare.mjs +68 -0
  49. package/dist/api/prepare.mjs.map +1 -0
  50. package/dist/api/test.cjs +28 -0
  51. package/dist/api/test.d.cts +17 -0
  52. package/dist/api/test.d.cts.map +1 -0
  53. package/dist/api/test.d.mts +17 -0
  54. package/dist/api/test.d.mts.map +1 -0
  55. package/dist/api/test.mjs +27 -0
  56. package/dist/api/test.mjs.map +1 -0
  57. package/dist/api/types.cjs +71 -0
  58. package/dist/api/types.d.cts +17 -0
  59. package/dist/api/types.d.cts.map +1 -0
  60. package/dist/api/types.d.mts +17 -0
  61. package/dist/api/types.d.mts.map +1 -0
  62. package/dist/api/types.mjs +70 -0
  63. package/dist/api/types.mjs.map +1 -0
  64. package/dist/api-6w4hZL6n.d.cts +135 -0
  65. package/dist/api-6w4hZL6n.d.cts.map +1 -0
  66. package/dist/api-Cdw4v0W4.d.mts +135 -0
  67. package/dist/api-Cdw4v0W4.d.mts.map +1 -0
  68. package/dist/config-BNe23XHx.d.mts +204 -0
  69. package/dist/config-BNe23XHx.d.mts.map +1 -0
  70. package/dist/config-D6xUniHh.d.cts +204 -0
  71. package/dist/config-D6xUniHh.d.cts.map +1 -0
  72. package/dist/context/engine-context.cjs +175 -0
  73. package/dist/context/engine-context.d.cts +2 -0
  74. package/dist/context/engine-context.d.mts +2 -0
  75. package/dist/context/engine-context.mjs +173 -0
  76. package/dist/context/engine-context.mjs.map +1 -0
  77. package/dist/context/index.cjs +2 -9
  78. package/dist/context/index.d.cts +2 -660
  79. package/dist/context/index.d.mts +2 -660
  80. package/dist/context/index.mjs +2 -4
  81. package/dist/context-DzgsMSWr.d.mts +149 -0
  82. package/dist/context-DzgsMSWr.d.mts.map +1 -0
  83. package/dist/context-epL7NPvL.d.cts +149 -0
  84. package/dist/context-epL7NPvL.d.cts.map +1 -0
  85. package/dist/engine-context-DEotmVzB.d.mts +54 -0
  86. package/dist/engine-context-DEotmVzB.d.mts.map +1 -0
  87. package/dist/engine-context-Dw8odBCo.d.cts +54 -0
  88. package/dist/engine-context-Dw8odBCo.d.cts.map +1 -0
  89. package/dist/engine.cjs +268 -0
  90. package/dist/engine.d.cts +143 -0
  91. package/dist/engine.d.cts.map +1 -0
  92. package/dist/engine.d.mts +143 -0
  93. package/dist/engine.d.mts.map +1 -0
  94. package/dist/engine.mjs +264 -0
  95. package/dist/engine.mjs.map +1 -0
  96. package/dist/execution-host.cjs +44 -0
  97. package/dist/execution-host.d.cts +14 -0
  98. package/dist/execution-host.d.cts.map +1 -0
  99. package/dist/execution-host.d.mts +14 -0
  100. package/dist/execution-host.d.mts.map +1 -0
  101. package/dist/execution-host.mjs +36 -0
  102. package/dist/execution-host.mjs.map +1 -0
  103. package/dist/helpers/create-execution-host.cjs +51 -0
  104. package/dist/helpers/create-execution-host.d.cts +21 -0
  105. package/dist/helpers/create-execution-host.d.cts.map +1 -0
  106. package/dist/helpers/create-execution-host.d.mts +21 -0
  107. package/dist/helpers/create-execution-host.d.mts.map +1 -0
  108. package/dist/helpers/create-execution-host.mjs +50 -0
  109. package/dist/helpers/create-execution-host.mjs.map +1 -0
  110. package/dist/helpers/execution-host-worker.cjs +308 -0
  111. package/dist/helpers/execution-host-worker.d.cts +68 -0
  112. package/dist/helpers/execution-host-worker.d.cts.map +1 -0
  113. package/dist/helpers/execution-host-worker.d.mts +68 -0
  114. package/dist/helpers/execution-host-worker.d.mts.map +1 -0
  115. package/dist/helpers/execution-host-worker.mjs +307 -0
  116. package/dist/helpers/execution-host-worker.mjs.map +1 -0
  117. package/dist/helpers/finalize.cjs +27 -0
  118. package/dist/helpers/finalize.d.cts +12 -0
  119. package/dist/helpers/finalize.d.cts.map +1 -0
  120. package/dist/helpers/finalize.d.mts +12 -0
  121. package/dist/helpers/finalize.d.mts.map +1 -0
  122. package/dist/helpers/finalize.mjs +26 -0
  123. package/dist/helpers/finalize.mjs.map +1 -0
  124. package/dist/helpers/rpc.cjs +140 -0
  125. package/dist/helpers/rpc.d.cts +7 -0
  126. package/dist/helpers/rpc.d.cts.map +1 -0
  127. package/dist/helpers/rpc.d.mts +7 -0
  128. package/dist/helpers/rpc.d.mts.map +1 -0
  129. package/dist/helpers/rpc.mjs +139 -0
  130. package/dist/helpers/rpc.mjs.map +1 -0
  131. package/dist/index-CNgSR_kt.d.mts +1 -0
  132. package/dist/index-D_TYgLX3.d.cts +1 -0
  133. package/dist/index.cjs +13 -567
  134. package/dist/index.d.cts +9 -126
  135. package/dist/index.d.mts +9 -126
  136. package/dist/index.mjs +7 -567
  137. package/package.json +101 -129
  138. package/dist/_internal/worker.cjs +0 -4843
  139. package/dist/_internal/worker.d.cts +0 -38
  140. package/dist/_internal/worker.d.cts.map +0 -1
  141. package/dist/_internal/worker.d.mts +0 -38
  142. package/dist/_internal/worker.d.mts.map +0 -1
  143. package/dist/_internal/worker.mjs +0 -4804
  144. package/dist/_internal/worker.mjs.map +0 -1
  145. package/dist/api.cjs +0 -1274
  146. package/dist/api.d.cts +0 -265
  147. package/dist/api.d.cts.map +0 -1
  148. package/dist/api.d.mts +0 -265
  149. package/dist/api.d.mts.map +0 -1
  150. package/dist/api.mjs +0 -1270
  151. package/dist/api.mjs.map +0 -1
  152. package/dist/base-context-BUnL_9z8.mjs +0 -241
  153. package/dist/base-context-BUnL_9z8.mjs.map +0 -1
  154. package/dist/base-context-CFvO2N9I.cjs +0 -248
  155. package/dist/context/index.d.cts.map +0 -1
  156. package/dist/context/index.d.mts.map +0 -1
  157. package/dist/engine-context-BuD9AGfd.mjs +0 -41
  158. package/dist/engine-context-BuD9AGfd.mjs.map +0 -1
  159. package/dist/engine-context-NO6enYev.cjs +0 -45
  160. package/dist/execution-context-BgGV4xyW.cjs +0 -2614
  161. package/dist/execution-context-D_CXpe9I.mjs +0 -2570
  162. package/dist/execution-context-D_CXpe9I.mjs.map +0 -1
  163. package/dist/fs-D1nIP45P.mjs +0 -226
  164. package/dist/fs-D1nIP45P.mjs.map +0 -1
  165. package/dist/fs-XogSgMqT.cjs +0 -262
  166. package/dist/index.d.cts.map +0 -1
  167. package/dist/index.d.mts.map +0 -1
  168. package/dist/index.mjs.map +0 -1
  169. package/dist/schemas.cjs +0 -9
  170. package/dist/schemas.d.cts +0 -127
  171. package/dist/schemas.d.cts.map +0 -1
  172. package/dist/schemas.d.mts +0 -127
  173. package/dist/schemas.d.mts.map +0 -1
  174. package/dist/schemas.mjs +0 -3
  175. package/dist/storage/index.cjs +0 -9
  176. package/dist/storage/index.d.cts +0 -419
  177. package/dist/storage/index.d.cts.map +0 -1
  178. package/dist/storage/index.d.mts +0 -419
  179. package/dist/storage/index.d.mts.map +0 -1
  180. package/dist/storage/index.mjs +0 -3
  181. package/dist/ts-morph-BaLPVAdB.cjs +0 -114
  182. package/dist/ts-morph-D0CaA37w.mjs +0 -102
  183. package/dist/ts-morph-D0CaA37w.mjs.map +0 -1
  184. package/dist/tsconfig-Cstsoprg.mjs +0 -155
  185. package/dist/tsconfig-Cstsoprg.mjs.map +0 -1
  186. package/dist/tsconfig-DeyWQC2N.cjs +0 -198
  187. package/dist/typescript/index.cjs +0 -13
  188. package/dist/typescript/index.d.cts +0 -106
  189. package/dist/typescript/index.d.cts.map +0 -1
  190. package/dist/typescript/index.d.mts +0 -106
  191. package/dist/typescript/index.d.mts.map +0 -1
  192. package/dist/typescript/index.mjs +0 -4
  193. package/dist/virtual-BNdKVkRw.cjs +0 -548
  194. package/dist/virtual-gIlTc3Lj.mjs +0 -513
  195. package/dist/virtual-gIlTc3Lj.mjs.map +0 -1
@@ -1,2570 +0,0 @@
1
- import { t as PowerlinesBaseContext } from "./base-context-BUnL_9z8.mjs";
2
- import { a as FileSystem } from "./fs-D1nIP45P.mjs";
3
- import { n as FileSystemStorageAdapter, t as VirtualStorageAdapter } from "./virtual-gIlTc3Lj.mjs";
4
- import { i as getTsconfigFilePath } from "./tsconfig-Cstsoprg.mjs";
5
- import { CACHE_HASH_LENGTH, DEFAULT_ENVIRONMENT, GLOBAL_ENVIRONMENT, PLUGIN_NON_HOOK_FIELDS, ROOT_HASH_LENGTH } from "@powerlines/core/constants";
6
- import { getResolutionCombinations, resolve, resolvePackage, resolveSync } from "@stryke/fs/resolve";
7
- import { joinPaths } from "@stryke/path/join";
8
- import { LogLevelLabel } from "@storm-software/config-tools/types";
9
- import { isSet } from "@stryke/type-checks/is-set";
10
- import { isString } from "@stryke/type-checks/is-string";
11
- import { colorText, createLog, extendLog } from "@powerlines/core/lib/logger";
12
- import { isNull } from "@stryke/type-checks/is-null";
13
- import chalk from "chalk";
14
- import defu, { createDefu, defu as defu$1 } from "defu";
15
- import { joinPaths as joinPaths$1 } from "@stryke/path/join-paths";
16
- import { titleCase } from "@stryke/string-format/title-case";
17
- import { isSetObject } from "@stryke/type-checks/is-set-object";
18
- import { format } from "@powerlines/core/lib/utilities/format";
19
- import { addPluginHook, dedupeHooklist, isDuplicate, isPlugin, isPluginConfig, isPluginHook, isPluginHookField, mergeConfig, replacePathTokens } from "@powerlines/core/plugin-utils";
20
- import { toArray } from "@stryke/convert/to-array";
21
- import { existsSync } from "@stryke/fs/exists";
22
- import { getUnique, getUniqueBy } from "@stryke/helpers/get-unique";
23
- import { omit } from "@stryke/helpers/omit";
24
- import { appendPath } from "@stryke/path/append";
25
- import { findFileDotExtensionSafe, findFileExtensionSafe, findFileName, findFilePath, hasFileExtension } from "@stryke/path/file-path-fns";
26
- import { isParentPath } from "@stryke/path/is-parent-path";
27
- import { replaceExtension, replacePath } from "@stryke/path/replace";
28
- import { isFunction } from "@stryke/type-checks/is-function";
29
- import { isObject } from "@stryke/type-checks/is-object";
30
- import { isSetString } from "@stryke/type-checks/is-set-string";
31
- import { readJsonFile } from "@stryke/fs/json";
32
- import { deepClone } from "@stryke/helpers/deep-clone";
33
- import { getUniqueInputs, isTypeDefinition, resolveInputsSync } from "@powerlines/core/lib/entry";
34
- import { relativeToWorkspaceRoot } from "@stryke/fs/get-workspace-root";
35
- import { murmurhash } from "@stryke/hash";
36
- import { hashDirectory } from "@stryke/hash/node";
37
- import { fetchRequest } from "@stryke/http/fetch";
38
- import { kebabCase } from "@stryke/string-format/kebab-case";
39
- import { uuid } from "@stryke/unique-id/uuid";
40
- import { match, tsconfigPathsToRegExp } from "bundle-require";
41
- import { resolveCompatibilityDates } from "compatx";
42
- import { create } from "flat-cache";
43
- import { parse } from "oxc-parser";
44
- import { Agent, Response, interceptors, setGlobalDispatcher } from "undici";
45
- import "@stryke/fs/remove-file";
46
- import * as capnp from "@stryke/capnp";
47
- import { readFileBuffer, readFileBufferSync, writeFileBuffer } from "@stryke/fs/buffer";
48
- import { correctPath, stripStars } from "@stryke/path/correct-path";
49
- import { globToRegex } from "@stryke/path/glob-to-regex";
50
- import { isAbsolutePath } from "@stryke/path/is-type";
51
- import { slash } from "@stryke/path/slash";
52
- import { prettyBytes } from "@stryke/string-format/pretty-bytes";
53
- import { isRegExp } from "@stryke/type-checks/is-regexp";
54
- import { Blob } from "node:buffer";
55
- import { fileURLToPath } from "node:url";
56
- import { getField } from "@stryke/helpers/get-field";
57
-
58
- //#region src/_internal/helpers/environment.ts
59
- function createEnvironment(name, config = {}) {
60
- return defu(config.environments?.[name] ?? {}, {
61
- name,
62
- title: config.title ?? titleCase(config.name),
63
- ssr: false,
64
- resolve: { mainFields: config.platform === "browser" ? [
65
- "browser",
66
- "module",
67
- "jsnext:main",
68
- "jsnext"
69
- ] : [
70
- "module",
71
- "jsnext:main",
72
- "jsnext"
73
- ] },
74
- consumer: config.platform === "browser" ? "client" : "server",
75
- preview: config.platform === "browser" ? {
76
- port: 5173,
77
- open: true,
78
- strictPort: false,
79
- host: "localhost",
80
- allowedHosts: ["."],
81
- cors: true,
82
- headers: {}
83
- } : void 0
84
- });
85
- }
86
- function createDefaultEnvironment(config = {}) {
87
- return createEnvironment(DEFAULT_ENVIRONMENT, config);
88
- }
89
-
90
- //#endregion
91
- //#region src/_internal/helpers/context.ts
92
- function getConfigProps(config = {}, root, cwd) {
93
- return {
94
- name: config.name,
95
- title: config.title,
96
- description: config.description,
97
- projectType: config.projectType,
98
- customLogger: config.customLogger,
99
- logLevel: config.logLevel,
100
- tsconfig: config.tsconfig,
101
- tsconfigRaw: config.tsconfigRaw,
102
- skipCache: config.skipCache,
103
- autoInstall: config.autoInstall,
104
- input: isSetString(config.input) ? [config.input] : config.input,
105
- plugins: config.plugins,
106
- mode: config.mode,
107
- resolve: config.resolve,
108
- framework: config.framework,
109
- ...config,
110
- output: {
111
- ...config.output ?? {},
112
- path: config.output?.path ? appendPath(config.output.path, appendPath(root, cwd)) : void 0
113
- }
114
- };
115
- }
116
-
117
- //#endregion
118
- //#region src/_internal/helpers/meta.ts
119
- /**
120
- * Generates a prefixed project root hash object.
121
- *
122
- * @remarks
123
- * 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.
124
- *
125
- * @param name - The name of the project.
126
- * @param rootHash - The hash of the project root.
127
- * @returns An object containing the name and project root hash.
128
- */
129
- function getPrefixedRootHash(name, rootHash) {
130
- const combined = `${kebabCase(name)}_${rootHash}`;
131
- return combined.length > ROOT_HASH_LENGTH ? combined.slice(0, ROOT_HASH_LENGTH) : combined;
132
- }
133
- /**
134
- * Writes the meta file for the context.
135
- *
136
- * @param context - The context to write the meta file for.
137
- * @returns A promise that resolves when the meta file has been written.
138
- */
139
- async function writeMetaFile(context) {
140
- const metaFilePath = joinPaths$1(context.dataPath, "meta.json");
141
- context.debug(`Writing runtime metadata to ${metaFilePath}`);
142
- await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));
143
- }
144
-
145
- //#endregion
146
- //#region src/_internal/helpers/constants.ts
147
- const DEFAULT_EXTENSIONS = [
148
- "js",
149
- "ts",
150
- "cjs",
151
- "cts",
152
- "mjs",
153
- "mts",
154
- "tsx",
155
- "jsx",
156
- "json",
157
- "json5",
158
- "jsonc",
159
- "md",
160
- "mdx"
161
- ];
162
-
163
- //#endregion
164
- //#region src/_internal/vfs.ts
165
- function toFilePath(path) {
166
- return correctPath(slash(path?.toString() || ".").replace(/^file:\/\//, ""));
167
- }
168
- /**
169
- * Checks if a given file id is valid based on the specified prefix.
170
- *
171
- * @param id - The file ID to check.
172
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
173
- * @returns `true` if the file ID is valid, otherwise `false`.
174
- */
175
- function isValidId(id, prefix = "powerlines") {
176
- return id.replace(/^\\0/, "").startsWith(`${prefix.replace(/:$/, "")}`);
177
- }
178
- /**
179
- * Formats a file id by removing the file extension and prepended runtime prefix.
180
- *
181
- * @param id - The file ID to format.
182
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
183
- * @returns The formatted file ID.
184
- */
185
- function normalizeId(id, prefix = "powerlines") {
186
- return replaceExtension(toFilePath(id)).replace(/^\\0/, "").replace(/^powerlines:/, "").replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), "");
187
- }
188
- /**
189
- * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
190
- *
191
- * @param path - The path to normalize.
192
- * @param builtinsPath - The path to built-in files.
193
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
194
- * @returns The normalized path.
195
- */
196
- function normalizePath(path, builtinsPath, prefix = "powerlines") {
197
- if (!isSetString(path)) {
198
- if (!isString(path)) throw new Error("Path type must be a string or a file descriptor");
199
- throw new Error("Path cannot be empty");
200
- }
201
- return isAbsolutePath(path) ? path : isValidId(toFilePath(path), prefix) ? normalizeId(toFilePath(path), prefix).replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), builtinsPath) : toFilePath(path);
202
- }
203
- /**
204
- * Normalizes glob patterns by resolving them against the workspace root.
205
- *
206
- * @param workspaceRoot - The root directory of the workspace.
207
- * @param patterns - The glob patterns to normalize.
208
- * @returns An array of normalized glob patterns.
209
- */
210
- function normalizeGlobPatterns(workspaceRoot, patterns) {
211
- return getUnique(toArray(patterns).map((pattern) => {
212
- if (isSetObject(pattern) && (isSetString(pattern.input) || isSetString(pattern.glob))) return joinPaths(pattern.input || workspaceRoot, pattern.glob || "**/*");
213
- else if (!isSetString(pattern)) return;
214
- return pattern;
215
- }).filter(isSetString));
216
- }
217
- /**
218
- * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.
219
- *
220
- * @remarks
221
- * 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.
222
- */
223
- var VirtualFileSystem = class VirtualFileSystem {
224
- /**
225
- * A map of virtual file IDs to their associated metadata.
226
- */
227
- #metadata;
228
- /**
229
- * A map of underlying file paths to their virtual file IDs.
230
- */
231
- #ids;
232
- /**
233
- * A map of virtual file IDs to their underlying file paths.
234
- */
235
- #paths;
236
- /**
237
- * The unified volume that combines the virtual file system with the real file system.
238
- *
239
- * @remarks
240
- * This volume allows for seamless access to both virtual and real files.
241
- */
242
- #storage;
243
- /**
244
- * A cache for module resolution results.
245
- */
246
- #resolverCache;
247
- /**
248
- * Indicator specifying if the virtual file system (VFS) is disposed
249
- */
250
- #isDisposed = false;
251
- /**
252
- * The context of the virtual file system.
253
- */
254
- #context;
255
- /**
256
- * The file system's logging function.
257
- */
258
- #log;
259
- /**
260
- * Normalizes a given module id by resolving it against the built-ins path.
261
- *
262
- * @param id - The module id to normalize.
263
- * @returns The normalized module id.
264
- */
265
- #normalizeId(id) {
266
- let normalized = id;
267
- if (isParentPath(normalized, this.#context.builtinsPath)) normalized = replacePath(normalized, this.#context.builtinsPath);
268
- return normalizeId(normalized, this.#context.config.framework);
269
- }
270
- /**
271
- * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
272
- *
273
- * @param path - The path to normalize.
274
- * @returns The normalized path.
275
- */
276
- #normalizePath(path) {
277
- if (!isSetString(path)) {
278
- if (!isString(path)) throw new Error("Path type must be a string or a file descriptor");
279
- throw new Error("Path cannot be empty");
280
- }
281
- return normalizePath(path.includes("{") || path.includes("}") ? replacePathTokens(this.#context, path) : path, this.#context.builtinsPath, this.#context.config.framework);
282
- }
283
- /**
284
- * Gets the storage adapter and relative key for a given key.
285
- *
286
- * @remarks
287
- * The `key` can be either a path or a storage adapter name.
288
- *
289
- * @param key - The key to get the storage adapter for.
290
- * @returns The storage adapter and relative key for the given key.
291
- */
292
- #getStorage(key, preset) {
293
- const path = this.resolveSync(this.#normalizePath(key)) || key;
294
- for (const base of Object.keys(this.#storage).filter(Boolean).sort().reverse()) if ((path === base || isParentPath(path, base)) && (!preset || this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())) return {
295
- base,
296
- relativeKey: replacePath(path, base),
297
- adapter: this.#storage[base]
298
- };
299
- if (!preset || this.#storage[""]?.preset?.toLowerCase() === preset.toLowerCase()) return {
300
- base: "",
301
- relativeKey: path,
302
- adapter: this.#storage[""]
303
- };
304
- this.#storage[path] = preset === "virtual" ? new VirtualStorageAdapter(this.#context, { base: path }) : new FileSystemStorageAdapter(this.#context, { base: path });
305
- return {
306
- base: path,
307
- relativeKey: "",
308
- adapter: this.#storage[path]
309
- };
310
- }
311
- /**
312
- * Gets all storage adapters that match a given base key.
313
- *
314
- * @param base - The base key to match storage adapters against.
315
- * @param includeParent - Whether to include parent storage adapters.
316
- * @returns An array of storage adapters that match the given base key.
317
- */
318
- #getStorages(base = "", includeParent = false) {
319
- const baseKey = this.resolveSync(base) || base;
320
- return Object.keys(this.#storage).sort().reverse().filter((key) => isParentPath(key, baseKey) || includeParent && isParentPath(baseKey, key) || baseKey.includes("*") && (isParentPath(stripStars(baseKey), key) || globToRegex(replaceExtension(baseKey)).test(key))).map((key) => ({
321
- relativeBase: baseKey.length > key.length ? baseKey.slice(key.length) : void 0,
322
- base: key,
323
- adapter: this.#storage[key]
324
- }));
325
- }
326
- /**
327
- * A helper function to resolve modules in the virtual file system (VFS).
328
- *
329
- * @remarks
330
- * This function can be used to resolve modules relative to the project root directory.
331
- *
332
- * @example
333
- * ```ts
334
- * const resolved = await context.resolvePath("some-module", "/path/to/importer");
335
- * ```
336
- *
337
- * @param id - The module to resolve.
338
- * @param importer - An optional path to the importer module.
339
- * @param options - Additional resolution options.
340
- * @returns A promise that resolves to the resolved module path.
341
- */
342
- #innerResolve = async (id, importer, options = {}) => {
343
- let path = id;
344
- if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
345
- if (options.skipAlias !== true) path = this.resolveAlias(path);
346
- if (isAbsolutePath(path) && (!options.isFile || !await this.isDirectory(path))) return path;
347
- const resolverCacheKey = murmurhash({
348
- path: this.#normalizeId(path),
349
- importer,
350
- options
351
- });
352
- let result;
353
- if (!this.#context.config.skipCache) {
354
- result = this.resolverCache.get(resolverCacheKey);
355
- if (result) return result;
356
- }
357
- result = this.paths[this.#normalizeId(path)];
358
- if (!isSetString(result)) {
359
- const paths = options.paths ?? [];
360
- if (importer && !paths.includes(importer)) paths.push(importer);
361
- if (!importer) {
362
- paths.push(this.#context.config.cwd);
363
- paths.push(appendPath(this.#context.config.root, this.#context.config.cwd));
364
- paths.push(appendPath(joinPaths(this.#context.config.root, "src"), this.#context.config.cwd));
365
- }
366
- 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.config.cwd)));
367
- for (const combination of getResolutionCombinations(path, { paths: getUnique(paths) })) {
368
- const { relativeKey, adapter } = this.#getStorage(combination);
369
- if (await adapter.exists(relativeKey)) {
370
- result = combination;
371
- break;
372
- }
373
- }
374
- if (!isSetString(result)) try {
375
- result = await resolve(path, {
376
- ...options,
377
- paths
378
- });
379
- } catch {}
380
- }
381
- if (isSetString(result)) {
382
- if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
383
- return result;
384
- }
385
- };
386
- /**
387
- * A synchronous helper function to resolve modules using the Jiti resolver
388
- *
389
- * @remarks
390
- * This function can be used to resolve modules relative to the project root directory.
391
- *
392
- * @example
393
- * ```ts
394
- * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
395
- * ```
396
- *
397
- * @param id - The module to resolve.
398
- * @param importer - An optional path to the importer module.
399
- * @param options - Additional resolution options.
400
- * @returns The resolved module path.
401
- */
402
- #innerResolveSync = (id, importer, options = {}) => {
403
- let path = id;
404
- if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
405
- if (options.skipAlias !== true) path = this.resolveAlias(path);
406
- if (isAbsolutePath(path) && (!options.isFile || !this.isDirectorySync(path))) return path;
407
- let result;
408
- if (!this.#context.config.skipCache) {
409
- result = this.resolverCache.get(this.#normalizeId(path));
410
- if (isSetString(result)) return result;
411
- }
412
- result = this.paths[this.#normalizeId(path)];
413
- if (!isSetString(result)) {
414
- const paths = options.paths ?? [];
415
- if (importer && !paths.includes(importer)) paths.push(importer);
416
- if (!importer) {
417
- paths.push(this.#context.config.cwd);
418
- paths.push(appendPath(this.#context.config.root, this.#context.config.cwd));
419
- paths.push(appendPath(joinPaths(this.#context.config.root, "src"), this.#context.config.cwd));
420
- }
421
- 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.config.cwd)));
422
- for (const combination of getResolutionCombinations(path, { paths })) {
423
- const { relativeKey, adapter } = this.#getStorage(combination);
424
- if (adapter.existsSync(relativeKey)) {
425
- result = combination;
426
- break;
427
- }
428
- }
429
- if (!isSetString(result)) try {
430
- result = resolveSync(path, {
431
- ...options,
432
- paths
433
- });
434
- } catch {}
435
- }
436
- if (isSetString(result)) {
437
- if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
438
- return result;
439
- }
440
- };
441
- /**
442
- * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
443
- *
444
- * @param context - The context of the virtual file system, typically containing options and logging functions.
445
- * @returns A promise that resolves to a new virtual file system instance.
446
- */
447
- static async create(context) {
448
- context.debug("Starting virtual file system (VFS) initialization processes...");
449
- let result;
450
- if (!context.config.skipCache && existsSync(joinPaths(context.dataPath, "fs.bin"))) {
451
- const buffer = await readFileBuffer(joinPaths(context.dataPath, "fs.bin"));
452
- const fs = new capnp.Message(buffer, false).getRoot(FileSystem);
453
- result = new VirtualFileSystem(context, fs);
454
- if (fs._hasStorage() && fs.storage.length > 0) await Promise.all(fs.storage.values().map(async (file) => {
455
- if (file.path && file.code) {
456
- let id;
457
- if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
458
- let metadata;
459
- if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
460
- await result.write(file.path, file.code, { meta: {
461
- id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
462
- type: metadata?.type || "normal",
463
- properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
464
- ret[kvp.key] = kvp.value;
465
- return ret;
466
- }, {}) : void 0,
467
- timestamp: metadata?.timestamp
468
- } });
469
- }
470
- }));
471
- } else result = new VirtualFileSystem(context, new capnp.Message().initRoot(FileSystem));
472
- result.#log(LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
473
- return result;
474
- }
475
- /**
476
- * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
477
- *
478
- * @param context - The context of the virtual file system, typically containing options and logging functions.
479
- * @returns A new virtual file system instance.
480
- */
481
- static createSync(context) {
482
- context.debug("Starting virtual file system (VFS) initialization processes...");
483
- let result;
484
- if (!context.config.skipCache && existsSync(joinPaths(context.dataPath, "fs.bin"))) {
485
- const buffer = readFileBufferSync(joinPaths(context.dataPath, "fs.bin"));
486
- const fs = new capnp.Message(buffer, false).getRoot(FileSystem);
487
- result = new VirtualFileSystem(context, fs);
488
- if (fs._hasStorage() && fs.storage.length > 0) fs.storage.values().forEach((file) => {
489
- if (file.path && file.code) {
490
- let id;
491
- if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
492
- let metadata;
493
- if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
494
- result.writeSync(file.path, file.code, { meta: {
495
- id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
496
- type: metadata?.type,
497
- properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
498
- ret[kvp.key] = kvp.value;
499
- return ret;
500
- }, {}) : void 0,
501
- timestamp: metadata?.timestamp
502
- } });
503
- }
504
- });
505
- } else result = new VirtualFileSystem(context, new capnp.Message().initRoot(FileSystem));
506
- result.#log(LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
507
- return result;
508
- }
509
- /**
510
- * A map of file ids to their metadata.
511
- */
512
- get metadata() {
513
- return new Proxy(this.#metadata, {
514
- get: (target, prop) => {
515
- return target[this.#normalizeId(prop)];
516
- },
517
- set: (target, prop, value) => {
518
- target[this.#normalizeId(prop)] = value;
519
- return true;
520
- },
521
- deleteProperty: (target, prop) => {
522
- delete target[this.#normalizeId(prop)];
523
- return true;
524
- },
525
- has: (target, prop) => {
526
- return this.#normalizeId(prop) in target;
527
- },
528
- ownKeys: (target) => {
529
- return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
530
- }
531
- });
532
- }
533
- /**
534
- * A map of file paths to their module ids.
535
- */
536
- get ids() {
537
- return new Proxy(this.#ids, {
538
- get: (target, prop) => {
539
- return target[this.#normalizePath(prop)];
540
- },
541
- set: (target, prop, value) => {
542
- target[this.#normalizePath(prop)] = value;
543
- return true;
544
- },
545
- deleteProperty: (target, prop) => {
546
- delete target[this.#normalizePath(prop)];
547
- return true;
548
- },
549
- has: (target, prop) => {
550
- return this.#normalizePath(prop) in target;
551
- },
552
- ownKeys: (target) => {
553
- return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizePath(key)));
554
- }
555
- });
556
- }
557
- /**
558
- * A map of module ids to their file paths.
559
- */
560
- get paths() {
561
- return new Proxy(this.#paths, {
562
- get: (target, prop) => {
563
- return this.#normalizeId(prop) in target ? target[this.#normalizeId(prop)] : void 0;
564
- },
565
- set: (target, prop, value) => {
566
- target[this.#normalizeId(prop)] = value;
567
- return true;
568
- },
569
- deleteProperty: (target, prop) => {
570
- delete target[this.#normalizeId(prop)];
571
- return true;
572
- },
573
- has: (target, prop) => {
574
- return this.#normalizeId(prop) in target;
575
- },
576
- ownKeys: (target) => {
577
- return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
578
- }
579
- });
580
- }
581
- /**
582
- * Gets the resolver cache.
583
- */
584
- get resolverCache() {
585
- if (!this.#resolverCache) this.#resolverCache = create({
586
- cacheId: "module-resolution",
587
- cacheDir: this.#context.cachePath,
588
- ttl: 2.5 * 60 * 1e3,
589
- lruSize: 8e3,
590
- persistInterval: 100
591
- });
592
- return this.#resolverCache;
593
- }
594
- /**
595
- * Creates a new instance of the {@link VirtualFileSystem}.
596
- *
597
- * @param context - The context of the virtual file system, typically containing options and logging functions.
598
- * @param fs - A buffer containing the serialized virtual file system data.
599
- */
600
- constructor(context, fs) {
601
- this.#context = context;
602
- this.#storage = { "": new FileSystemStorageAdapter(context) };
603
- if (isSetObject(this.#context.config.output.storage)) this.#storage = {
604
- ...this.#storage,
605
- ...this.#context.config.output.storage
606
- };
607
- this.#storage.virtual ??= new VirtualStorageAdapter(context, { base: "/_virtual" });
608
- this.#storage[this.#context.config.output.path] ??= new FileSystemStorageAdapter(context, { base: this.#context.config.output.path });
609
- if (this.#context.config.output.copy && this.#context.config.output.copy.path) this.#storage[this.#context.config.output.copy.path] ??= new FileSystemStorageAdapter(context, { base: this.#context.config.output.copy.path });
610
- if (this.#context.config.output.storage !== "fs") {
611
- this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.artifactsPath });
612
- this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.builtinsPath });
613
- this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(context, { base: this.#context.entryPath });
614
- }
615
- this.#metadata = {};
616
- if (fs._hasMetadata()) this.#metadata = fs.metadata.values().reduce((ret, metadata) => {
617
- ret[metadata.id] = {
618
- id: metadata.id,
619
- type: metadata.type,
620
- timestamp: metadata.timestamp ?? Date.now(),
621
- properties: metadata._hasProperties() ? metadata.properties.values().reduce((ret, item) => {
622
- ret[item.key] = item.value;
623
- return ret;
624
- }, {}) : {}
625
- };
626
- return ret;
627
- }, {});
628
- this.#ids = {};
629
- this.#paths = {};
630
- if (fs._hasIds()) {
631
- this.#ids = fs.ids.values().reduce((ret, identifier) => {
632
- ret[identifier.path] ??= identifier.id;
633
- return ret;
634
- }, {});
635
- this.#paths = fs.ids.values().reduce((ret, identifier) => {
636
- ret[identifier.id] ??= identifier.path;
637
- return ret;
638
- }, {});
639
- }
640
- this.#log = extendLog(this.#context.log, "file-system");
641
- }
642
- /**
643
- * Asynchronously checks if a file exists in the virtual file system (VFS).
644
- *
645
- * @param path - The path to the file.
646
- * @returns A promise that resolves to `true` if the file exists, otherwise `false`.
647
- */
648
- async exists(path) {
649
- const { relativeKey, adapter } = this.#getStorage(path);
650
- return adapter.exists(relativeKey);
651
- }
652
- /**
653
- * Synchronously checks if a file exists in the virtual file system (VFS).
654
- *
655
- * @param path - The path to the file.
656
- * @returns `true` if the file exists, otherwise `false`.
657
- */
658
- existsSync(path) {
659
- const { relativeKey, adapter } = this.#getStorage(path);
660
- return adapter.existsSync(relativeKey);
661
- }
662
- /**
663
- * Checks if a file is virtual in the virtual file system (VFS).
664
- *
665
- * @param path - The path to the file.
666
- * @param importer - An optional path to the importer module.
667
- * @param options - Additional resolution options.
668
- * @returns `true` if the file is virtual, otherwise `false`.
669
- */
670
- isVirtual(path, importer, options) {
671
- const resolved = this.resolveSync(path, importer, options);
672
- if (!isSetString(resolved)) {
673
- if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
674
- return false;
675
- }
676
- return this.#getStorage(resolved)?.adapter?.preset === "virtual" || resolved.startsWith(`${this.#context.config.framework}:`) || path.startsWith(`${this.#context.config.framework}:`);
677
- }
678
- /**
679
- * Checks if a path is a directory in the virtual file system (VFS).
680
- *
681
- * @param path - The path to check.
682
- * @param importer - An optional path to the importer module.
683
- * @param options - Additional resolution options.
684
- * @returns `true` if the path is a directory, otherwise `false`.
685
- */
686
- isDirectorySync(path, importer, options) {
687
- const resolved = this.resolveSync(path, importer, options);
688
- if (!isSetString(resolved)) {
689
- if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
690
- return false;
691
- }
692
- return !!(this.existsSync(resolved) && this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved));
693
- }
694
- /**
695
- * Checks if a path is a directory in the virtual file system (VFS).
696
- *
697
- * @param path - The path to check.
698
- * @param importer - An optional path to the importer module.
699
- * @param options - Additional resolution options.
700
- * @returns `true` if the path is a directory, otherwise `false`.
701
- */
702
- async isDirectory(path, importer, options) {
703
- const resolved = await this.resolve(path, importer, options);
704
- if (!isSetString(resolved)) {
705
- if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
706
- return false;
707
- }
708
- return !!(await this.exists(resolved) && await this.#getStorage(resolved)?.adapter?.isDirectory(resolved));
709
- }
710
- /**
711
- * Checks if a path is a file in the virtual file system (VFS).
712
- *
713
- * @param path - The path to check.
714
- * @param importer - An optional path to the importer module.
715
- * @param options - Additional resolution options.
716
- * @returns `true` if the path is a file, otherwise `false`.
717
- */
718
- isFileSync(path, importer, options) {
719
- const resolved = this.resolveSync(path, importer, options);
720
- if (!isSetString(resolved)) {
721
- if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
722
- return false;
723
- }
724
- return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;
725
- }
726
- /**
727
- * Checks if a path is a file in the virtual file system (VFS).
728
- *
729
- * @param path - The path to check.
730
- * @param importer - An optional path to the importer module.
731
- * @param options - Additional resolution options.
732
- * @returns `true` if the path is a file, otherwise `false`.
733
- */
734
- async isFile(path, importer, options) {
735
- const resolved = await this.resolve(path, importer, options);
736
- if (!isSetString(resolved)) {
737
- if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
738
- return false;
739
- }
740
- return await this.#getStorage(resolved)?.adapter?.isFile(resolved) ?? false;
741
- }
742
- /**
743
- * Checks if a file Id must be resolved by the virtual file system (VFS).
744
- *
745
- * @remarks
746
- * Examples of file Ids that would be considered virtual include:
747
- * - Ids that start with the framework specific prefix (e.g. `powerlines:`)
748
- * - Ids that match a configured alias for virtual modules (returned true from {@link VirtualFileSystemInterface.isVirtual})
749
- *
750
- * @param path - The path or id of the file.
751
- * @param importer - An optional path to the importer module, used for resolving the file path.
752
- * @param options - Additional options for resolving the file path.
753
- * @returns `true` if the file is virtual, otherwise `false`.
754
- */
755
- isResolvableId(path, importer, options) {
756
- return path.startsWith(`${this.#context.config.framework}:`) || this.isVirtual(path, importer, options) || this.isAlias(path) || this.isTsconfigPath(path);
757
- }
758
- /**
759
- * Lists files in a given path.
760
- *
761
- * @param path - The path to list files from.
762
- * @returns An array of file names in the specified path.
763
- */
764
- listSync(path) {
765
- let resolvedPath = path;
766
- if (resolvedPath.includes("*")) {
767
- this.#log(LogLevelLabel.WARN, `Invoking "listSync" with a glob pattern is not supported. It is likely you meant to use "globSync". Path: ${path}`);
768
- resolvedPath = stripStars(resolvedPath);
769
- }
770
- return getUnique(this.#getStorages(resolvedPath, true).map((storage) => storage.adapter.listSync(storage.relativeBase ? storage.base ? appendPath(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)).flat().filter(Boolean));
771
- }
772
- /**
773
- * Lists files in a given path.
774
- *
775
- * @param path - The path to list files from.
776
- * @returns An array of file names in the specified path.
777
- */
778
- async list(path) {
779
- let resolvedPath = path;
780
- if (resolvedPath.includes("*")) {
781
- this.#log(LogLevelLabel.WARN, `Invoking "list" with a glob pattern is not supported. It is likely you meant to use "glob". Path: ${path}`);
782
- resolvedPath = stripStars(resolvedPath);
783
- }
784
- return getUnique((await Promise.all(this.#getStorages(resolvedPath, true).map(async (storage) => storage.adapter.list(storage.relativeBase ? storage.base ? appendPath(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)))).flat().filter(Boolean));
785
- }
786
- /**
787
- * Removes a file in the virtual file system (VFS).
788
- *
789
- * @param path - The path to create the directory at.
790
- */
791
- async remove(path) {
792
- const normalizedPath = this.#normalizePath(path);
793
- this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
794
- const { relativeKey, adapter } = this.#getStorage(normalizedPath);
795
- if (hasFileExtension(normalizedPath)) await adapter.remove(relativeKey);
796
- else await adapter.clear(relativeKey);
797
- const id = this.#ids[normalizedPath];
798
- if (id && this.#metadata[id]) {
799
- delete this.#metadata[id];
800
- delete this.#ids[normalizedPath];
801
- delete this.#paths[id];
802
- }
803
- }
804
- /**
805
- * Removes a file in the virtual file system (VFS).
806
- *
807
- * @param path - The path to create the directory at.
808
- */
809
- removeSync(path) {
810
- const normalizedPath = this.#normalizePath(path);
811
- this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
812
- const { relativeKey, adapter } = this.#getStorage(normalizedPath);
813
- if (hasFileExtension(normalizedPath)) adapter.removeSync(relativeKey);
814
- else adapter.clearSync(relativeKey);
815
- const id = this.#ids[normalizedPath];
816
- if (id && this.#metadata[id]) {
817
- delete this.#metadata[id];
818
- delete this.#ids[normalizedPath];
819
- delete this.#paths[id];
820
- }
821
- }
822
- /**
823
- * Glob files in the virtual file system (VFS) based on the provided pattern(s).
824
- *
825
- * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
826
- * @returns An array of file paths matching the provided pattern(s)
827
- */
828
- async glob(patterns) {
829
- const results = [];
830
- for (const pattern of normalizeGlobPatterns(this.#context.config.cwd, patterns)) {
831
- const normalized = this.#normalizePath(pattern);
832
- if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...await this.list(normalized));
833
- else {
834
- const resolved = await this.resolve(normalized);
835
- if (resolved && !results.includes(resolved)) results.push(resolved);
836
- }
837
- else {
838
- const absPattern = isAbsolutePath(normalized) ? normalized : this.#normalizePath(appendPath(normalized, this.#context.config.cwd));
839
- await Promise.all((await this.list(stripStars(absPattern))).map(async (file) => {
840
- if (globToRegex(absPattern).test(file)) {
841
- const resolved = await this.resolve(file);
842
- if (resolved && !results.includes(resolved)) results.push(resolved);
843
- }
844
- }));
845
- }
846
- }
847
- return results;
848
- }
849
- /**
850
- * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).
851
- *
852
- * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
853
- * @returns An array of file paths matching the provided pattern(s)
854
- */
855
- globSync(patterns) {
856
- const results = [];
857
- for (const pattern of normalizeGlobPatterns(this.#context.config.cwd, patterns)) {
858
- const normalized = this.#normalizePath(pattern);
859
- if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...this.listSync(normalized));
860
- else {
861
- const resolved = this.resolveSync(normalized);
862
- if (resolved && !results.includes(resolved)) results.push(resolved);
863
- }
864
- else {
865
- const absPattern = isAbsolutePath(normalized) ? normalized : this.#normalizePath(appendPath(normalized, this.#context.config.cwd));
866
- const files = this.listSync(stripStars(absPattern));
867
- for (const file of files) if (globToRegex(absPattern).test(file)) {
868
- const resolved = this.resolveSync(file);
869
- if (resolved && !results.includes(resolved)) results.push(resolved);
870
- }
871
- }
872
- }
873
- return results;
874
- }
875
- /**
876
- * Copies a file from one path to another in the virtual file system (VFS).
877
- *
878
- * @param srcPath - The source path to copy
879
- * @param destPath - The destination path to copy to
880
- */
881
- async copy(srcPath, destPath) {
882
- const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;
883
- const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;
884
- if (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input)) || !isSetString(dest)) return;
885
- const sourceStr = isString(src) ? src : src.input ? src.input : this.#context.config.cwd;
886
- const source = await this.resolve(sourceStr);
887
- if (!source) return;
888
- if (this.isDirectorySync(source) || isSetString(src) && src.includes("*") || isSetObject(src) && isSetString(src.glob)) await Promise.all((await this.glob(src)).map(async (file) => {
889
- return this.copy(file, appendPath(replacePath(file, sourceStr), dest));
890
- }));
891
- else {
892
- const content = await this.read(source);
893
- if (content !== void 0) await this.write(this.#normalizePath(dest), content, { skipFormat: true });
894
- }
895
- }
896
- /**
897
- * Synchronously copies a file from one path to another in the virtual file system (VFS).
898
- *
899
- * @param srcPath - The source path to copy
900
- * @param destPath - The destination path to copy to
901
- */
902
- copySync(srcPath, destPath) {
903
- const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;
904
- const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;
905
- if (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input)) || !isSetString(dest)) return;
906
- const sourceStr = isString(src) ? src : src.input ? src.input : this.#context.config.cwd;
907
- const source = this.resolveSync(sourceStr);
908
- if (!source) return;
909
- if (this.isDirectorySync(source) || isSetString(src) && src.includes("*") || isSetObject(src) && isSetString(src.glob)) this.globSync(src).map((file) => {
910
- return this.copySync(file, appendPath(findFilePath(replacePath(file, sourceStr)), dest));
911
- });
912
- else {
913
- const content = this.readSync(source);
914
- if (content !== void 0) this.writeSync(this.#normalizePath(hasFileExtension(dest) ? dest : appendPath(findFileName(source), dest)), content, { skipFormat: true });
915
- }
916
- }
917
- /**
918
- * Moves a file (or files) from one path to another in the virtual file system (VFS).
919
- *
920
- * @param srcPath - The source path to move
921
- * @param destPath - The destination path to move to
922
- */
923
- async move(srcPath, destPath) {
924
- if (hasFileExtension(srcPath)) {
925
- await this.copy(srcPath, destPath);
926
- await this.remove(srcPath);
927
- } else await Promise.all((await this.list(srcPath)).map(async (file) => {
928
- await this.copy(file, destPath);
929
- await this.remove(file);
930
- }));
931
- }
932
- /**
933
- * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).
934
- *
935
- * @param srcPath - The source path to move
936
- * @param destPath - The destination path to move to
937
- */
938
- moveSync(srcPath, destPath) {
939
- if (hasFileExtension(srcPath)) {
940
- this.copySync(srcPath, destPath);
941
- this.removeSync(srcPath);
942
- } else this.listSync(srcPath).forEach((file) => {
943
- this.copySync(file, destPath);
944
- this.removeSync(file);
945
- });
946
- }
947
- /**
948
- * Asynchronously reads a file from the virtual file system (VFS).
949
- *
950
- * @param path - The path or ID of the file to read.
951
- * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.
952
- */
953
- async read(path) {
954
- const filePath = await this.resolve(path, void 0, { isFile: true });
955
- if (!filePath || !this.existsSync(filePath)) return;
956
- const { adapter } = this.#getStorage(filePath);
957
- this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
958
- return await adapter.get(filePath) ?? void 0;
959
- }
960
- /**
961
- * Synchronously reads a file from the virtual file system (VFS).
962
- *
963
- * @param path - The path or ID of the file to read.
964
- * @returns The contents of the file as a string, or undefined if the file does not exist.
965
- */
966
- readSync(path) {
967
- const filePath = this.resolveSync(path, void 0, { isFile: true });
968
- if (!filePath || !this.existsSync(filePath)) return;
969
- const { adapter } = this.#getStorage(filePath);
970
- this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
971
- return adapter.getSync(filePath) ?? void 0;
972
- }
973
- /**
974
- * Writes a file to the virtual file system (VFS).
975
- *
976
- * @param path - The path to the file.
977
- * @param data - The contents of the file.
978
- * @param options - Optional parameters for writing the file.
979
- * @returns A promise that resolves when the file is written.
980
- */
981
- async write(path, data = "", options = {}) {
982
- const meta = options.meta ?? {};
983
- const resolvedPath = await this.resolve(this.#normalizePath(path)) || path;
984
- const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
985
- this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
986
- let code = data;
987
- try {
988
- if (!options.skipFormat) code = await format(this.#context, resolvedPath, data);
989
- } catch (err) {
990
- if (DEFAULT_EXTENSIONS.includes(findFileExtensionSafe(resolvedPath, { fullExtension: true }))) this.#log(LogLevelLabel.WARN, `Failed to format file ${resolvedPath} before writing: ${err.message}`);
991
- code = data;
992
- }
993
- this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
994
- const id = this.#normalizeId(meta.id || resolvedPath);
995
- this.metadata[id] = {
996
- type: "normal",
997
- timestamp: Date.now(),
998
- ...this.metadata[id] ?? {},
999
- ...meta
1000
- };
1001
- this.paths[id] = resolvedPath;
1002
- this.ids[resolvedPath] = id;
1003
- return adapter.set(relativeKey, code);
1004
- }
1005
- /**
1006
- * Synchronously writes a file to the virtual file system (VFS).
1007
- *
1008
- * @param path - The file to write.
1009
- * @param data - The contents of the file.
1010
- * @param options - Optional parameters for writing the file.
1011
- */
1012
- writeSync(path, data = "", options = {}) {
1013
- const meta = options.meta ?? {};
1014
- const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;
1015
- const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
1016
- this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
1017
- const id = this.#normalizeId(meta.id || resolvedPath);
1018
- this.metadata[id] = {
1019
- type: "normal",
1020
- timestamp: Date.now(),
1021
- ...this.metadata[id] ?? {},
1022
- ...meta
1023
- };
1024
- this.paths[id] = resolvedPath;
1025
- this.ids[resolvedPath] = id;
1026
- return adapter.setSync(relativeKey, data);
1027
- }
1028
- /**
1029
- * Synchronously creates a directory at the specified path.
1030
- *
1031
- * @param dirPath - The path of the directory to create.
1032
- */
1033
- mkdirSync(dirPath) {
1034
- return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);
1035
- }
1036
- /**
1037
- * Creates a directory at the specified path.
1038
- *
1039
- * @param path - The path of the directory to create.
1040
- */
1041
- async mkdir(path) {
1042
- return this.#getStorage(path)?.adapter?.mkdir(path);
1043
- }
1044
- /**
1045
- * Retrieves the metadata of a file in the virtual file system (VFS).
1046
- *
1047
- * @param pathOrId - The path or ID of the file to retrieve metadata for.
1048
- * @returns The metadata of the file, or undefined if the file does not exist.
1049
- */
1050
- getMetadata(pathOrId) {
1051
- const resolved = this.resolveSync(pathOrId);
1052
- if (resolved && this.metadata[resolved]) return this.metadata[resolved];
1053
- }
1054
- /**
1055
- * Resolves a given module ID using the configured aliases.
1056
- *
1057
- * @remarks
1058
- * This function can be used to map module IDs to different paths based on the alias configuration.
1059
- *
1060
- * @param id - The module ID to resolve.
1061
- * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).
1062
- */
1063
- resolveAlias(id) {
1064
- let path = id;
1065
- if (this.#context.config.resolve.alias) {
1066
- if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) {
1067
- const found = this.#context.config.resolve.alias.filter((alias) => isSetString(alias.find) && (alias.find === path || path.startsWith(`${alias.find}/`)) || isRegExp(alias.find) && alias.find.test(path));
1068
- if (found.length > 0) {
1069
- const alias = found.reduce((ret, current) => {
1070
- 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;
1071
- });
1072
- if (isSetString(alias.find)) path = path.replace(new RegExp(`^${alias.find}`), alias.replacement);
1073
- else if (isRegExp(alias.find)) path = path.replace(alias.find, alias.replacement);
1074
- }
1075
- } else if (isSetObject(this.#context.config.resolve.alias)) {
1076
- const found = Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`));
1077
- if (found.length > 0) {
1078
- const alias = found.reduce((ret, current) => {
1079
- return ret.length > current.length ? ret : current;
1080
- });
1081
- path = path.replace(new RegExp(`^${alias}`), this.#context.config.resolve.alias[alias]);
1082
- }
1083
- }
1084
- }
1085
- return path;
1086
- }
1087
- /**
1088
- * Checks if a given module ID is an alias.
1089
- *
1090
- * @remarks
1091
- * This function can be used to determine if a module ID matches any configured aliases.
1092
- *
1093
- * @param id - The module ID to check.
1094
- * @returns A boolean indicating whether the module ID is an alias.
1095
- */
1096
- isAlias(id) {
1097
- const path = id;
1098
- if (this.#context.config.resolve.alias) {
1099
- if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) return this.#context.config.resolve.alias.filter((alias) => isSetString(alias.find) && (alias.find === path || path.startsWith(`${alias.find}/`)) || isRegExp(alias.find) && alias.find.test(path)).length > 0;
1100
- else if (isSetObject(this.#context.config.resolve.alias)) return Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`)).length > 0;
1101
- }
1102
- return false;
1103
- }
1104
- /**
1105
- * Checks if a given module ID is a tsconfig path.
1106
- *
1107
- * @remarks
1108
- * This function can be used to determine if a module ID matches any configured tsconfig paths.
1109
- *
1110
- * @param id - The module ID to check.
1111
- * @returns A boolean indicating whether the module ID is a tsconfig path.
1112
- */
1113
- isTsconfigPath(id) {
1114
- return !!(this.#context.tsconfig.options.paths && Object.keys(this.#context.tsconfig.options.paths).length > 0 && match(id, this.#context.resolvePatterns));
1115
- }
1116
- /**
1117
- * A helper function to resolve modules in the virtual file system (VFS).
1118
- *
1119
- * @remarks
1120
- * This function can be used to resolve modules relative to the project root directory.
1121
- *
1122
- * @example
1123
- * ```ts
1124
- * const resolved = await context.resolvePath("some-module", "/path/to/importer");
1125
- * ```
1126
- *
1127
- * @param id - The module to resolve.
1128
- * @param importer - An optional path to the importer module.
1129
- * @param options - Additional resolution options.
1130
- * @returns A promise that resolves to the resolved module path.
1131
- */
1132
- async resolve(id, importer, options = {}) {
1133
- const origResult = await this.#innerResolve(id, importer, options);
1134
- if (origResult && options.isFile && await this.isDirectory(origResult)) {
1135
- const indexResult = await this.resolve(joinPaths(origResult, "index"), importer, options);
1136
- if (indexResult) return indexResult;
1137
- if (!hasFileExtension(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1138
- const extResult = await this.resolve(`${origResult}.${ext}`, importer, options);
1139
- if (extResult) return extResult;
1140
- }
1141
- return;
1142
- }
1143
- return origResult;
1144
- }
1145
- /**
1146
- * A synchronous helper function to resolve modules using the Jiti resolver
1147
- *
1148
- * @remarks
1149
- * This function can be used to resolve modules relative to the project root directory.
1150
- *
1151
- * @example
1152
- * ```ts
1153
- * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
1154
- * ```
1155
- *
1156
- * @param id - The module to resolve.
1157
- * @param importer - An optional path to the importer module.
1158
- * @param options - Additional resolution options.
1159
- * @returns The resolved module path.
1160
- */
1161
- resolveSync(id, importer, options = {}) {
1162
- const origResult = this.#innerResolveSync(id, importer, options);
1163
- if (origResult && options.isFile && this.isDirectorySync(origResult)) {
1164
- const indexResult = this.resolveSync(joinPaths(origResult, "index"), importer, options);
1165
- if (indexResult) return indexResult;
1166
- if (!hasFileExtension(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1167
- const extResult = this.resolveSync(`${origResult}.${ext}`, importer, options);
1168
- if (extResult) return extResult;
1169
- }
1170
- return;
1171
- }
1172
- return origResult;
1173
- }
1174
- /**
1175
- * Disposes of the virtual file system (VFS) by saving its state to disk.
1176
- */
1177
- async dispose() {
1178
- if (!this.#isDisposed) {
1179
- this.#isDisposed = true;
1180
- this.#log(LogLevelLabel.DEBUG, "Disposing virtual file system...");
1181
- await this.remove(joinPaths(this.#context.dataPath, "fs.bin"));
1182
- const message = new capnp.Message();
1183
- const fs = message.initRoot(FileSystem);
1184
- const storage = fs._initStorage(Object.keys(this.#paths).length);
1185
- await Promise.all(Object.values(this.#paths).map(async (path, index) => {
1186
- const code = await this.read(path);
1187
- const fd = storage.get(index);
1188
- fd.path = path;
1189
- fd.code = code || "";
1190
- }));
1191
- const ids = fs._initIds(Object.keys(this.#ids).length);
1192
- Object.entries(this.#ids).filter(([, id]) => id).forEach(([path, id], index) => {
1193
- const fileId = ids.get(index);
1194
- fileId.id = id;
1195
- fileId.path = path;
1196
- });
1197
- const metadata = fs._initMetadata(Object.keys(this.#metadata).length);
1198
- Object.entries(this.#metadata).filter(([, value]) => value).forEach(([id, value], index) => {
1199
- const fileMetadata = metadata.get(index);
1200
- fileMetadata.id = id;
1201
- fileMetadata.type = value.type;
1202
- fileMetadata.timestamp = value.timestamp ?? Date.now();
1203
- if (value.properties) {
1204
- const props = fileMetadata._initProperties(Object.keys(value.properties).length);
1205
- Object.entries(value.properties).filter(([, val]) => isSetString(val)).forEach(([key, val], index) => {
1206
- const prop = props.get(index);
1207
- prop.key = key;
1208
- prop.value = val;
1209
- });
1210
- }
1211
- });
1212
- await writeFileBuffer(joinPaths(this.#context.dataPath, "fs.bin"), message.toArrayBuffer());
1213
- if (!this.#context.config.skipCache) this.resolverCache.save(true);
1214
- await Promise.all(this.#getStorages().map(async (storage) => storage.adapter.dispose()));
1215
- this.#log(LogLevelLabel.TRACE, "Virtual file system has been disposed.");
1216
- }
1217
- }
1218
- async [Symbol.asyncDispose]() {
1219
- return this.dispose();
1220
- }
1221
- };
1222
-
1223
- //#endregion
1224
- //#region src/context/context.ts
1225
- setGlobalDispatcher(new Agent({ keepAliveTimeout: 1e4 }).compose(interceptors.retry({
1226
- maxRetries: 3,
1227
- minTimeout: 1e3,
1228
- maxTimeout: 1e4,
1229
- timeoutFactor: 2,
1230
- retryAfter: true
1231
- })));
1232
- const SKIP_CLONING_PROPS = [
1233
- "dependencies",
1234
- "devDependencies",
1235
- "persistedMeta",
1236
- "packageJson",
1237
- "projectJson",
1238
- "tsconfig",
1239
- "resolver",
1240
- "fs",
1241
- "$$internal"
1242
- ];
1243
- var PowerlinesContext = class PowerlinesContext extends PowerlinesBaseContext {
1244
- /**
1245
- * Internal references storage
1246
- *
1247
- * @danger
1248
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1249
- *
1250
- * @internal
1251
- */
1252
- #internal = {};
1253
- #checksum = null;
1254
- #buildId = uuid();
1255
- #releaseId = uuid();
1256
- #fs;
1257
- #tsconfig;
1258
- #parserCache;
1259
- #requestCache;
1260
- /**
1261
- * Create a new Storm context from the workspace root and user config.
1262
- *
1263
- * @param options - The options for resolving the context.
1264
- * @returns A promise that resolves to the new context.
1265
- */
1266
- static async fromOptions(options) {
1267
- const context = new PowerlinesContext(options);
1268
- await context.init(options);
1269
- const powerlinesPath = await resolvePackage("powerlines");
1270
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
1271
- context.powerlinesPath = powerlinesPath;
1272
- return context;
1273
- }
1274
- /**
1275
- * The options provided to the Powerlines process
1276
- */
1277
- options;
1278
- /**
1279
- * An object containing the dependencies that should be installed for the project
1280
- */
1281
- dependencies = {};
1282
- /**
1283
- * An object containing the development dependencies that should be installed for the project
1284
- */
1285
- devDependencies = {};
1286
- /**
1287
- * The persisted meta information about the current build
1288
- */
1289
- persistedMeta = void 0;
1290
- /**
1291
- * The parsed `package.json` file for the project
1292
- */
1293
- packageJson;
1294
- /**
1295
- * The parsed `project.json` file for the project
1296
- */
1297
- projectJson = void 0;
1298
- /**
1299
- * The resolved tsconfig file paths for the project
1300
- */
1301
- resolvePatterns = [];
1302
- /**
1303
- * Internal context fields and methods
1304
- *
1305
- * @danger
1306
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1307
- *
1308
- * @internal
1309
- */
1310
- get $$internal() {
1311
- return this.#internal;
1312
- }
1313
- /**
1314
- * Internal context fields and methods
1315
- *
1316
- * @danger
1317
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1318
- *
1319
- * @internal
1320
- */
1321
- set $$internal(value) {
1322
- this.#internal = value;
1323
- }
1324
- /**
1325
- * The resolved entry type definitions for the project
1326
- */
1327
- get entry() {
1328
- const entry = this.resolvedEntry;
1329
- return resolveInputsSync(this, entry && entry.length > 0 ? entry : Array.isArray(this.config.input) || isSetObject(this.config.input) && !isTypeDefinition(this.config.input) ? this.config.input : toArray(this.config.input).flat());
1330
- }
1331
- /**
1332
- * The TypeScript configuration parsed from the tsconfig file
1333
- */
1334
- get tsconfig() {
1335
- if (!this.#tsconfig) this.tsconfig = { tsconfigFilePath: this.config.tsconfig };
1336
- return this.#tsconfig;
1337
- }
1338
- /**
1339
- * Sets the TypeScript configuration parsed from the tsconfig file
1340
- */
1341
- set tsconfig(value) {
1342
- this.#tsconfig = value;
1343
- this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});
1344
- }
1345
- /**
1346
- * The virtual file system interface for the project
1347
- */
1348
- get fs() {
1349
- if (!this.#fs) this.#fs = VirtualFileSystem.createSync(this);
1350
- return this.#fs;
1351
- }
1352
- /**
1353
- * Get the checksum of the project's current state
1354
- */
1355
- get checksum() {
1356
- return this.#checksum;
1357
- }
1358
- /**
1359
- * The meta information about the current build
1360
- */
1361
- get meta() {
1362
- return {
1363
- buildId: this.#buildId,
1364
- releaseId: this.#releaseId,
1365
- checksum: this.#checksum,
1366
- timestamp: this.timestamp.getTime(),
1367
- rootHash: murmurhash({
1368
- workspaceRoot: this.options?.cwd,
1369
- root: this.config?.root
1370
- }, { maxLength: ROOT_HASH_LENGTH }),
1371
- configHash: murmurhash(this.config, { maxLength: CACHE_HASH_LENGTH })
1372
- };
1373
- }
1374
- /**
1375
- * The resolved configuration options
1376
- */
1377
- get config() {
1378
- return this.resolvedConfig;
1379
- }
1380
- /**
1381
- * Get the path to the artifacts directory for the project
1382
- */
1383
- get artifactsPath() {
1384
- return joinPaths(this.config.cwd, this.config.root, this.config.output.artifactsPath);
1385
- }
1386
- /**
1387
- * Get the path to the builtin modules used by the project
1388
- */
1389
- get builtinsPath() {
1390
- return joinPaths(this.artifactsPath, "builtins");
1391
- }
1392
- /**
1393
- * Get the path to the entry directory for the project
1394
- */
1395
- get entryPath() {
1396
- return joinPaths(this.artifactsPath, "entry");
1397
- }
1398
- /**
1399
- * Get the path to the infrastructure modules used by the project
1400
- */
1401
- get infrastructurePath() {
1402
- return joinPaths(this.artifactsPath, "infrastructure");
1403
- }
1404
- /**
1405
- * Get the path to the data directory for the project
1406
- */
1407
- get dataPath() {
1408
- return joinPaths(this.envPaths.data, "projects", getPrefixedRootHash(this.config.name, this.meta.rootHash));
1409
- }
1410
- /**
1411
- * Get the path to the cache directory for the project
1412
- */
1413
- get cachePath() {
1414
- return joinPaths(this.envPaths.cache, "projects", murmurhash({
1415
- checksum: this.#checksum,
1416
- config: this.meta.configHash
1417
- }, { maxLength: CACHE_HASH_LENGTH }));
1418
- }
1419
- /**
1420
- * Get the path to the generated declaration file for the project
1421
- */
1422
- get typesPath() {
1423
- return this.config.output.types ? appendPath(this.config.output.types, this.config.cwd) : joinPaths(this.config.cwd, this.config.root, "powerlines.d.ts");
1424
- }
1425
- /**
1426
- * Get the project root relative to the workspace root
1427
- */
1428
- get relativeToWorkspaceRoot() {
1429
- return relativeToWorkspaceRoot(this.config.root);
1430
- }
1431
- /**
1432
- * The builtin module id that exist in the Powerlines virtual file system
1433
- */
1434
- get builtins() {
1435
- return Object.values(this.fs.metadata).filter((meta) => meta && meta.type === "builtin").map((meta) => meta?.id).filter(Boolean);
1436
- }
1437
- /**
1438
- * Additional arguments provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed.
1439
- */
1440
- get additionalArgs() {
1441
- return Object.entries(this.config.inlineConfig?.additionalArgs ?? {}).reduce((ret, [key, value]) => {
1442
- const formattedKey = key.replace(/^--?/, "");
1443
- if (ret[formattedKey]) if (Array.isArray(ret[formattedKey])) if (Array.isArray(value)) ret[formattedKey] = [...toArray(ret[formattedKey]), ...value];
1444
- else ret[formattedKey] = [...toArray(ret[formattedKey]), value];
1445
- else ret[formattedKey] = [ret[formattedKey], ...Array.isArray(value) ? value : [value]];
1446
- else ret[formattedKey] = value;
1447
- return ret;
1448
- }, {});
1449
- }
1450
- /**
1451
- * The alias mappings for the project used during module resolution
1452
- *
1453
- * @remarks
1454
- * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.
1455
- */
1456
- get alias() {
1457
- return this.builtins.reduce((ret, id) => {
1458
- const moduleId = `${this.config?.framework || "powerlines"}:${id.replace(/^.*:/, "")}`;
1459
- if (!ret[moduleId]) {
1460
- const path = this.fs.paths[id];
1461
- if (path) ret[moduleId] = path;
1462
- }
1463
- return ret;
1464
- }, this.config.resolve.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
1465
- if (!ret[alias.find.toString()]) ret[alias.find.toString()] = alias.replacement;
1466
- return ret;
1467
- }, {}) : this.config.resolve.alias : {});
1468
- }
1469
- /**
1470
- * Gets the parser cache.
1471
- */
1472
- get parserCache() {
1473
- if (!this.#parserCache) this.#parserCache = create({
1474
- cacheId: "parser",
1475
- cacheDir: this.cachePath,
1476
- ttl: 7200 * 1e3,
1477
- lruSize: 5e3,
1478
- persistInterval: 250
1479
- });
1480
- return this.#parserCache;
1481
- }
1482
- /**
1483
- * Gets the request cache.
1484
- */
1485
- get requestCache() {
1486
- if (!this.#requestCache) this.#requestCache = create({
1487
- cacheId: "http",
1488
- cacheDir: this.cachePath,
1489
- ttl: 360 * 60 * 1e3,
1490
- lruSize: 5e3,
1491
- persistInterval: 250
1492
- });
1493
- return this.#requestCache;
1494
- }
1495
- /**
1496
- * The entry points that exist in the Powerlines virtual file system
1497
- */
1498
- get resolvedEntry() {
1499
- return Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "entry").map(([path, meta]) => {
1500
- const typeDefinition = { file: path };
1501
- if (meta.properties) {
1502
- if (isSetString(meta.properties.file)) typeDefinition.file = meta.properties.file;
1503
- if (isSetString(meta.properties.name)) typeDefinition.name = meta.properties.name;
1504
- if (isSetString(meta.properties["input.file"]) || isSetString(meta.properties["input.name"])) {
1505
- typeDefinition.input ??= {};
1506
- if (isSetString(meta.properties["input.file"])) typeDefinition.input.file = meta.properties["input.file"];
1507
- if (isSetString(meta.properties["input.name"])) typeDefinition.input.name = meta.properties["input.name"];
1508
- }
1509
- if (isSetString(meta.properties.output)) typeDefinition.output = meta.properties.output;
1510
- }
1511
- return typeDefinition;
1512
- }).filter(Boolean);
1513
- }
1514
- /**
1515
- * Creates a new StormContext instance.
1516
- *
1517
- * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.
1518
- */
1519
- constructor(options) {
1520
- super();
1521
- this.options = options;
1522
- }
1523
- /**
1524
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
1525
- *
1526
- * @remarks
1527
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
1528
- *
1529
- * @returns A promise that resolves to the cloned context.
1530
- */
1531
- async clone() {
1532
- const clone = await PowerlinesContext.fromOptions(this.config);
1533
- return this.copyTo(clone);
1534
- }
1535
- /**
1536
- * Create a new logger instance
1537
- *
1538
- * @param name - The name to use for the logger instance
1539
- * @returns A logger function
1540
- */
1541
- createLog(name = null) {
1542
- return createLog(name, {
1543
- ...this.config,
1544
- logLevel: isNull(this.logLevel) ? "silent" : this.logLevel
1545
- });
1546
- }
1547
- /**
1548
- * A function to perform HTTP fetch requests
1549
- *
1550
- * @remarks
1551
- * This function uses a caching layer to avoid duplicate requests during the Powerlines process.
1552
- *
1553
- * @example
1554
- * ```ts
1555
- * const response = await context.fetch("https://api.example.com/data");
1556
- * const data = await response.json();
1557
- * ```
1558
- *
1559
- * @see https://github.com/nodejs/undici
1560
- *
1561
- * @param input - The URL to fetch.
1562
- * @param options - The fetch request options.
1563
- * @returns A promise that resolves to a response returned by the fetch.
1564
- */
1565
- async fetch(input, options = {}) {
1566
- const cacheKey = murmurhash({
1567
- input: input.toString(),
1568
- options: JSON.stringify(options)
1569
- });
1570
- if (!this.config.skipCache && !options.skipCache) {
1571
- const cached = this.requestCache.get(cacheKey);
1572
- if (cached) return new Response(cached.body, {
1573
- status: cached.status,
1574
- statusText: cached.statusText,
1575
- headers: cached.headers
1576
- });
1577
- }
1578
- const response = await fetchRequest(input, {
1579
- timeout: 12e3,
1580
- ...options
1581
- });
1582
- const result = {
1583
- body: await response.text(),
1584
- status: response.status,
1585
- statusText: response.statusText,
1586
- headers: Object.fromEntries(response.headers.entries())
1587
- };
1588
- if (!this.config.skipCache && !options.skipCache) try {
1589
- this.requestCache.set(cacheKey, result);
1590
- } catch {}
1591
- return new Response(result.body, {
1592
- status: result.status,
1593
- statusText: result.statusText,
1594
- headers: result.headers
1595
- });
1596
- }
1597
- /**
1598
- * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.
1599
- *
1600
- * @remarks
1601
- * This function can be used to parse TypeScript code into an AST for further analysis or transformation.
1602
- *
1603
- * @example
1604
- * ```ts
1605
- * const ast = context.parse("const x: number = 42;");
1606
- * ```
1607
- *
1608
- * @see https://rollupjs.org/plugin-development/#this-parse
1609
- * @see https://github.com/oxc/oxc
1610
- *
1611
- * @param code - The source code to parse.
1612
- * @param options - The options to pass to the parser.
1613
- * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.
1614
- */
1615
- async parse(code, options = {}) {
1616
- const cacheKey = murmurhash({
1617
- code,
1618
- options
1619
- });
1620
- let result;
1621
- if (!this.config.skipCache) {
1622
- result = this.parserCache.get(cacheKey);
1623
- if (result) return result;
1624
- }
1625
- result = await parse(`source.${options.lang || "ts"}`, code, {
1626
- ...options,
1627
- sourceType: "module",
1628
- showSemanticErrors: this.config.mode === "development"
1629
- });
1630
- if (!this.config.skipCache) this.parserCache.set(cacheKey, result);
1631
- return result;
1632
- }
1633
- /**
1634
- * A helper function to resolve modules in the Virtual File System
1635
- *
1636
- * @remarks
1637
- * This function can be used to resolve modules relative to the project root directory.
1638
- *
1639
- * @example
1640
- * ```ts
1641
- * const resolved = await context.resolve("some-module", "/path/to/importer");
1642
- * ```
1643
- *
1644
- * @param id - The module to resolve.
1645
- * @param importer - An optional path to the importer module.
1646
- * @param options - Additional resolution options.
1647
- * @returns A promise that resolves to the resolved module path.
1648
- */
1649
- async resolve(id, importer, options = {}) {
1650
- let moduleId = id;
1651
- if (this.config.resolve.alias) {
1652
- if (Array.isArray(this.config.resolve.alias)) {
1653
- const alias = this.config.resolve.alias.find((a) => match(moduleId, [a.find]));
1654
- if (alias) moduleId = alias.replacement;
1655
- } else if (isSetObject(this.config.resolve.alias) && this.config.resolve.alias[id]) moduleId = this.config.resolve.alias[id];
1656
- }
1657
- if (this.fs.isResolvableId(moduleId) || importer && this.fs.isResolvableId(importer)) {
1658
- let resolvedImporter = importer;
1659
- if (importer && this.fs.isResolvableId(importer)) resolvedImporter = await this.fs.resolve(importer, void 0, defu({
1660
- conditions: this.config.resolve.conditions,
1661
- extensions: this.config.resolve.extensions
1662
- }, options));
1663
- const result = await this.fs.resolve(moduleId, resolvedImporter, defu({
1664
- conditions: this.config.resolve.conditions,
1665
- extensions: this.config.resolve.extensions
1666
- }, options));
1667
- if (!result) return;
1668
- const external = Boolean(!match(moduleId, this.config.resolve.noExternal) && (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:") || (!this.fs.isVirtual(moduleId, importer, options) || this.fs.isVirtual(moduleId, importer, options) && this.config.projectType !== "application") && this.config.resolve.skipNodeModulesBundle && !/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)));
1669
- return {
1670
- id: result,
1671
- external,
1672
- virtual: !external
1673
- };
1674
- }
1675
- if (this.config.resolve.skipNodeModulesBundle) {
1676
- if (match(moduleId, this.resolvePatterns) || match(moduleId, this.config.resolve.noExternal)) return;
1677
- if (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
1678
- id: moduleId,
1679
- external: true,
1680
- virtual: false
1681
- };
1682
- if (!/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)) return {
1683
- id: moduleId,
1684
- external: true,
1685
- virtual: false
1686
- };
1687
- } else {
1688
- if (match(moduleId, this.config.resolve.noExternal)) return;
1689
- if (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
1690
- id: moduleId,
1691
- external: true,
1692
- virtual: false
1693
- };
1694
- }
1695
- }
1696
- /**
1697
- * A helper function to load modules from the Virtual File System
1698
- *
1699
- * @remarks
1700
- * This function can be used to load modules relative to the project root directory.
1701
- *
1702
- * @example
1703
- * ```ts
1704
- * const module = await context.load("some-module", "/path/to/importer");
1705
- * ```
1706
- *
1707
- * @param id - The module to load.
1708
- * @returns A promise that resolves to the loaded module.
1709
- */
1710
- async load(id) {
1711
- const resolvedId = await this.fs.resolve(id);
1712
- if (!resolvedId) return;
1713
- const code = await this.fs.read(resolvedId);
1714
- if (!code) return;
1715
- return {
1716
- code,
1717
- map: null
1718
- };
1719
- }
1720
- /**
1721
- * Get the builtin virtual files that exist in the Powerlines virtual file system
1722
- */
1723
- async getBuiltins() {
1724
- return Promise.all(Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "builtin").map(async ([id, meta]) => {
1725
- const code = await this.fs.read(id);
1726
- const path = this.fs.paths[id];
1727
- return {
1728
- ...meta,
1729
- path,
1730
- code
1731
- };
1732
- }));
1733
- }
1734
- /**
1735
- * Resolves a file and writes it to the VFS if it does not already exist
1736
- *
1737
- * @param code - The source code of the file
1738
- * @param path - The path to write the file to
1739
- * @param options - Additional options for writing the file
1740
- */
1741
- async emit(code, path, options = {}) {
1742
- const filePath = options.extension ? findFileExtensionSafe(path) ? options.extension.startsWith(".") ? path.replace(findFileDotExtensionSafe(path), options.extension) : path.replace(findFileExtensionSafe(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : findFileExtensionSafe(path) ? path : `${path}.ts`;
1743
- if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
1744
- needsCodeReference: options.needsCodeReference,
1745
- originalFileName: options.originalFileName,
1746
- fileName: filePath,
1747
- source: code,
1748
- type: "asset"
1749
- });
1750
- return this.fs.write(filePath, code, options);
1751
- }
1752
- /**
1753
- * Synchronously resolves a file and writes it to the VFS if it does not already exist
1754
- *
1755
- * @param code - The source code of the file
1756
- * @param path - The path to write the file to
1757
- * @param options - Additional options for writing the file
1758
- */
1759
- emitSync(code, path, options = {}) {
1760
- const filePath = options.extension ? findFileExtensionSafe(path) ? options.extension.startsWith(".") ? path.replace(findFileDotExtensionSafe(path), options.extension) : path.replace(findFileExtensionSafe(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : findFileExtensionSafe(path) ? path : `${path}.ts`;
1761
- if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
1762
- needsCodeReference: options.needsCodeReference,
1763
- originalFileName: options.originalFileName,
1764
- fileName: filePath,
1765
- source: code,
1766
- type: "asset"
1767
- });
1768
- return this.fs.writeSync(filePath, code, options);
1769
- }
1770
- /**
1771
- * Resolves a entry virtual file and writes it to the VFS if it does not already exist
1772
- *
1773
- * @param code - The source code of the entry file
1774
- * @param path - A path to write the entry file to
1775
- * @param options - Optional write file options
1776
- */
1777
- async emitEntry(code, path, options = {}) {
1778
- return this.emit(code, appendPath(path, this.entryPath), defu({ meta: {
1779
- type: "entry",
1780
- properties: {
1781
- file: appendPath(path, this.entryPath),
1782
- name: options?.name,
1783
- output: options?.output,
1784
- "input.file": options?.input?.file,
1785
- "input.name": options?.input?.name
1786
- }
1787
- } }, omit(options, ["name"])));
1788
- }
1789
- /**
1790
- * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist
1791
- *
1792
- * @param code - The source code of the entry file
1793
- * @param path - A path to write the entry file to
1794
- * @param options - Optional write file options
1795
- */
1796
- emitEntrySync(code, path, options = {}) {
1797
- return this.emitSync(code, appendPath(path, this.entryPath), defu({ meta: {
1798
- type: "entry",
1799
- properties: {
1800
- file: appendPath(path, this.entryPath),
1801
- name: options?.name,
1802
- output: options?.output,
1803
- "input.file": options?.input?.file,
1804
- "input.name": options?.input?.name
1805
- }
1806
- } }, omit(options, ["name"])));
1807
- }
1808
- /**
1809
- * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
1810
- *
1811
- * @param code - The source code of the builtin file
1812
- * @param id - The unique identifier of the builtin file
1813
- * @param options - Optional write file options
1814
- */
1815
- async emitBuiltin(code, id, options = {}) {
1816
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
1817
- if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
1818
- return this.emit(code, appendPath(id, this.builtinsPath), defu(options, { meta: {
1819
- type: "builtin",
1820
- id
1821
- } }));
1822
- }
1823
- /**
1824
- * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist
1825
- *
1826
- * @param code - The source code of the builtin file
1827
- * @param id - The unique identifier of the builtin file
1828
- * @param options - Optional write file options
1829
- */
1830
- emitBuiltinSync(code, id, options = {}) {
1831
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
1832
- if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
1833
- return this.emitSync(code, appendPath(id, this.builtinsPath), defu(options, { meta: {
1834
- type: "builtin",
1835
- id
1836
- } }));
1837
- }
1838
- /**
1839
- * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
1840
- *
1841
- * @param code - The source code of the builtin file
1842
- * @param id - The unique identifier of the builtin file
1843
- * @param options - Optional write file options
1844
- */
1845
- async emitInfrastructure(code, id, options = {}) {
1846
- if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
1847
- if (!isSetString(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
1848
- return this.emit(code, appendPath(id, this.infrastructurePath), defu(options, { meta: {
1849
- type: "infrastructure",
1850
- id
1851
- } }));
1852
- }
1853
- /**
1854
- * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist
1855
- *
1856
- * @param code - The source code of the infrastructure file
1857
- * @param id - The unique identifier of the infrastructure file
1858
- * @param options - Optional write file options
1859
- */
1860
- emitInfrastructureSync(code, id, options = {}) {
1861
- if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
1862
- if (!isSetString(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
1863
- return this.emitSync(code, appendPath(id, this.infrastructurePath), defu(options, { meta: {
1864
- type: "infrastructure",
1865
- id
1866
- } }));
1867
- }
1868
- /**
1869
- * Generates a checksum representing the current context state
1870
- *
1871
- * @param root - The root directory of the project to generate the checksum for
1872
- * @returns A promise that resolves to a string representing the checksum
1873
- */
1874
- async generateChecksum(root = this.config.root) {
1875
- this.#checksum = await hashDirectory(root, { ignore: [
1876
- "node_modules",
1877
- ".git",
1878
- ".nx",
1879
- ".cache",
1880
- "tmp",
1881
- "dist"
1882
- ] });
1883
- return this.#checksum;
1884
- }
1885
- /**
1886
- * Initialize the context with the provided configuration options
1887
- */
1888
- async setup() {
1889
- this.resolvedConfig = mergeConfig({
1890
- inlineConfig: this.config.inlineConfig ?? {},
1891
- userConfig: this.config.userConfig ?? {},
1892
- pluginConfig: this.config.pluginConfig ?? {}
1893
- }, this.options, this.config.inlineConfig ? getConfigProps(this.config.inlineConfig, this.options.root, this.options.cwd) : {}, this.config.userConfig ? getConfigProps(this.config.userConfig, this.options.root, this.options.cwd) : {}, this.config.pluginConfig ? getConfigProps(this.config.pluginConfig, this.options.root, this.options.cwd) : {}, {
1894
- name: this.projectJson?.name || this.packageJson?.name,
1895
- version: this.packageJson?.version,
1896
- description: this.packageJson?.description
1897
- }, {
1898
- projectType: "application",
1899
- platform: "neutral",
1900
- logLevel: "info",
1901
- preview: false,
1902
- environments: {},
1903
- resolve: {}
1904
- });
1905
- await this.innerSetup();
1906
- }
1907
- /**
1908
- * The resolved configuration for this context
1909
- */
1910
- resolvedConfig = {};
1911
- /**
1912
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
1913
- *
1914
- * @remarks
1915
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
1916
- *
1917
- * @returns The cloned context.
1918
- */
1919
- copyTo(context) {
1920
- for (const [key, value] of Object.entries(this)) if (!SKIP_CLONING_PROPS.includes(key)) if (isObject(value) || Array.isArray(value)) context[key] = deepClone(value);
1921
- else context[key] = value;
1922
- context.dependencies = deepClone(this.dependencies);
1923
- context.devDependencies = deepClone(this.devDependencies);
1924
- context.persistedMeta = this.persistedMeta ? deepClone(this.persistedMeta) : void 0;
1925
- context.packageJson = deepClone(this.packageJson);
1926
- context.projectJson = this.projectJson ? deepClone(this.projectJson) : void 0;
1927
- context.tsconfig ??= deepClone(this.tsconfig);
1928
- context.resolver ??= this.resolver;
1929
- context.fs ??= this.#fs;
1930
- context.$$internal = this.$$internal;
1931
- return context;
1932
- }
1933
- /**
1934
- * Initialize the context with the provided configuration options
1935
- *
1936
- * @remarks
1937
- * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.
1938
- *
1939
- * @param options - The configuration options to initialize the context with
1940
- */
1941
- async init(options = {}) {
1942
- await super.init(options);
1943
- this.options.configIndex = options.configIndex ?? this.options.configIndex ?? 0;
1944
- const projectJsonPath = joinPaths(this.options.root, "project.json");
1945
- if (existsSync(projectJsonPath)) this.projectJson = await readJsonFile(projectJsonPath);
1946
- const packageJsonPath = joinPaths(this.options.root, "package.json");
1947
- if (existsSync(packageJsonPath)) {
1948
- this.packageJson = await readJsonFile(packageJsonPath);
1949
- this.options.organization ??= isSetObject(this.packageJson?.author) ? kebabCase(this.packageJson?.author?.name) : kebabCase(this.packageJson?.author);
1950
- }
1951
- this.#checksum = await this.generateChecksum(this.options.root);
1952
- const userConfig = this.configFile.config ? Array.isArray(this.configFile.config) && this.configFile.config.length > this.options.configIndex ? this.configFile.config[this.options.configIndex] : this.configFile.config : {};
1953
- this.resolvedConfig = {
1954
- ...this.options,
1955
- ...userConfig,
1956
- userConfig
1957
- };
1958
- }
1959
- /**
1960
- * Initialize the context with the provided configuration options
1961
- */
1962
- async innerSetup() {
1963
- this.resolvedConfig.compatibilityDate = resolveCompatibilityDates(this.config.inlineConfig.compatibilityDate ?? this.config.userConfig.compatibilityDate ?? this.config.pluginConfig.compatibilityDate, "latest");
1964
- this.resolvedConfig.output = defu(this.resolvedConfig.output ?? {}, {
1965
- path: appendPath(joinPaths(this.config.root, "dist"), this.config.cwd),
1966
- copy: { assets: [
1967
- { glob: "LICENSE" },
1968
- {
1969
- input: this.config.root,
1970
- glob: "*.md"
1971
- },
1972
- {
1973
- input: this.config.root,
1974
- glob: "package.json"
1975
- }
1976
- ] },
1977
- artifactsPath: `.${this.config.framework ?? "powerlines"}`,
1978
- dts: true,
1979
- types: joinPaths(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`)
1980
- });
1981
- this.logger = {
1982
- log: this.createLog(this.config.name),
1983
- level: isNull(this.logLevel) ? "silent" : this.logLevel
1984
- };
1985
- if (this.config.output?.format) this.config.output.format = getUnique(toArray(this.config.output?.format));
1986
- this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
1987
- if (isPlugin(plugin) && isDuplicate(plugin, ret.filter((p) => isPlugin(p)))) return ret;
1988
- ret.push(plugin);
1989
- return ret;
1990
- }, []);
1991
- this.config.input = getUniqueInputs(this.config.input);
1992
- if (this.config.name?.startsWith("@") && this.config.name.split("/").filter(Boolean).length > 1) this.config.name = this.config.name.split("/").filter(Boolean)[1];
1993
- this.config.title ??= titleCase(this.config.name);
1994
- if (this.config.userConfig.resolve?.external) this.config.userConfig.resolve.external = getUnique(this.config.userConfig.resolve.external);
1995
- if (this.config.userConfig.resolve?.noExternal) this.config.userConfig.resolve.noExternal = getUnique(this.config.userConfig.resolve.noExternal);
1996
- if (this.config.resolve.external) this.config.resolve.external = getUnique(this.config.resolve.external);
1997
- if (this.config.resolve.noExternal) this.config.resolve.noExternal = getUnique(this.config.resolve.noExternal);
1998
- this.config.output.format = getUnique(toArray(this.config.output?.format ?? (this.config.projectType === "library" ? ["cjs", "esm"] : ["esm"])));
1999
- if (this.config.output.dts !== false && !this.config.output.types) this.config.output.types = `${this.config.root ? `${this.config.root}/` : ""}${this.config.framework ?? "powerlines"}.d.ts`;
2000
- if (this.config.root && this.config.output.copy !== false) this.config.output.copy = {
2001
- path: joinPaths(this.config.cwd, "dist", replacePath(this.config.root, this.config.cwd)),
2002
- ...this.config.output.copy || {}
2003
- };
2004
- if (this.config.output.copy && this.config.output.copy.path && this.config.output.copy.assets && Array.isArray(this.config.output.copy.assets)) this.config.output.copy.assets = getUniqueBy(this.config.output.copy.assets.map((asset) => {
2005
- return {
2006
- glob: isSetObject(asset) ? asset.glob : asset,
2007
- input: isString(asset) || !asset.input || asset.input === "." || asset.input === "/" || asset.input === "./" ? this.options.cwd : isParentPath(asset.input, this.config.cwd) || asset.input === this.config.cwd ? asset.input : appendPath(asset.input, this.config.cwd),
2008
- output: isSetObject(asset) && asset.output ? isParentPath(asset.output, this.config.cwd) ? asset.output : appendPath(joinPaths(this.config.output.copy.path, replacePath(replacePath(asset.output, replacePath(this.config.output.copy.path, this.config.cwd)), this.config.output.copy.path)), this.config.cwd) : appendPath(this.config.output.copy.path, this.config.cwd),
2009
- ignore: isSetObject(asset) && asset.ignore ? toArray(asset.ignore) : void 0
2010
- };
2011
- }), (a) => `${a.input}-${a.glob}-${a.output}`);
2012
- this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
2013
- if (isPlugin(plugin) && isDuplicate(plugin, ret.filter((p) => isPlugin(p)))) return ret;
2014
- ret.push(plugin);
2015
- return ret;
2016
- }, []);
2017
- if (this.config.output.types) if (isSetString(this.config.output.types)) this.config.output.types = replacePathTokens(this, this.config.output.types);
2018
- else this.config.output.types = joinPaths(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`);
2019
- if (!this.config.userConfig?.logLevel && !this.config.inlineConfig?.logLevel) if (this.config.mode === "development") this.config.logLevel = "debug";
2020
- else this.config.logLevel = "info";
2021
- if (!this.config.userConfig?.output?.sourceMap && !this.config.inlineConfig?.output?.sourceMap) if (this.config.mode === "development") this.config.output.sourceMap = true;
2022
- else this.config.output.sourceMap = false;
2023
- if (!this.config.userConfig?.output?.minify && !this.config.inlineConfig?.output?.minify) if (this.config.mode === "production") this.config.output.minify = true;
2024
- else this.config.output.minify = false;
2025
- if (!this.config.userConfig?.tsconfig && !this.config.inlineConfig?.tsconfig) this.config.tsconfig = getTsconfigFilePath(this.options.cwd, this.options.root);
2026
- else if (this.config.tsconfig) this.config.tsconfig = replacePath(replacePathTokens(this, this.config.tsconfig), this.config.cwd);
2027
- if (this.config.output.copy && this.config.output.copy.assets) this.config.output.copy.assets = this.config.output.copy.assets.map((asset) => ({
2028
- ...asset,
2029
- glob: replacePathTokens(this, asset.glob),
2030
- ignore: asset.ignore ? asset.ignore.map((ignore) => replacePathTokens(this, ignore)) : void 0,
2031
- input: replacePathTokens(this, asset.input),
2032
- output: replacePathTokens(this, asset.output)
2033
- }));
2034
- if (isSetString(this.config.output?.storage) && this.config.output.storage === "virtual" || isSetObject(this.config.output?.storage) && Object.values(this.config.output.storage).every((adapter) => adapter.preset === "virtual")) this.config.output.overwrite = true;
2035
- this.#fs ??= await VirtualFileSystem.create(this);
2036
- }
2037
- };
2038
-
2039
- //#endregion
2040
- //#region src/_internal/helpers/hooks.ts
2041
- const mergeResultObjects = createDefu((obj, key, value) => {
2042
- if (isString(obj[key]) && isString(value)) {
2043
- obj[key] = `${obj[key] || ""}\n${value || ""}`.trim();
2044
- return true;
2045
- }
2046
- return false;
2047
- });
2048
- /**
2049
- * Merges the current hook result with the previous results based on their types.
2050
- *
2051
- * @param currentResult - The current hook result to merge with the previous results.
2052
- * @param previousResults - The previous hook results to merge with the current result.
2053
- * @returns The merged result.
2054
- */
2055
- function mergeResults(currentResult, previousResults) {
2056
- if (!previousResults || previousResults.length === 0) return [currentResult];
2057
- if (isSetString(currentResult)) previousResults = [`${isSetString(previousResults[0]) ? previousResults[0] || "" : ""}\n${isSetString(previousResults[0]) ? currentResult.replace(previousResults[0], "") : currentResult}`.trim()];
2058
- else if (isObject(currentResult)) previousResults = [mergeResultObjects(currentResult, previousResults[0] ?? {})];
2059
- return previousResults;
2060
- }
2061
- /**
2062
- * Merges multiple hook results together, with special handling for string values and object values.
2063
- *
2064
- * @param currentResult - The current hook result to merge with the previous results.
2065
- * @param previousResults - The previous hook results to merge with the current result.
2066
- * @returns The merged result.
2067
- */
2068
- function mergeConfigs(currentResult, previousResults) {
2069
- if (isString(currentResult)) previousResults = `${isString(previousResults) ? previousResults || "" : ""}\n${currentResult || ""}`.trim();
2070
- else if (isObject(currentResult)) previousResults = mergeConfig(currentResult, previousResults ?? {});
2071
- return previousResults;
2072
- }
2073
- /**
2074
- * Calls a hook with the given context, options, and arguments.
2075
- *
2076
- * @param context - The context to use when calling the hook.
2077
- * @param key - The hook to call.
2078
- * @param options - Options for calling the hook.
2079
- * @param args - Arguments to pass to the hook.
2080
- * @returns The return value of the hook.
2081
- */
2082
- async function callHook(context, key, options, ...args) {
2083
- const hooks = context.selectHooks(key, options);
2084
- if (hooks.length > 0) {
2085
- context.debug(` 🧩 Calling ${hooks.length} ${chalk.bold.cyanBright(`${key}${options?.order ? ` (${options.order})` : ""}`)} plugin hook${hooks.length > 1 ? "s" : ""}:\n${hooks.map((hook, index) => ` ${index + 1}. ${colorText(hook.plugin.name)}`).join("\n")}`);
2086
- const invokeHook = async (hook, hookArgs) => {
2087
- return Reflect.apply(hook.handler, hook.context, hookArgs);
2088
- };
2089
- let results = [];
2090
- if (options?.sequential === false) results = await Promise.all(hooks.map(async (hook) => {
2091
- if (!isFunction(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
2092
- return invokeHook(hook, [...args]);
2093
- }));
2094
- else for (const hook of hooks) {
2095
- if (!isFunction(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
2096
- if (options?.result === "first" || options?.asNextParam === false) {
2097
- results.push(await Promise.resolve(invokeHook(hook, [...args])));
2098
- if (options?.result === "first" && isSet(results[results.length - 1])) break;
2099
- } else {
2100
- const sequenceArgs = [...args];
2101
- if (results.length > 0 && sequenceArgs.length > 0) sequenceArgs[0] = isFunction(options.asNextParam) ? await Promise.resolve(options.asNextParam(results[0])) : results[0];
2102
- const result = await Promise.resolve(invokeHook(hook, [...sequenceArgs]));
2103
- if (result) if (options.result === "last") results = [result];
2104
- else if (options.result === "merge" && options.merge) results = [results.length > 0 && results[0] ? await Promise.resolve(options.merge(result, results[0])) : result];
2105
- else results = mergeResults(result, results);
2106
- }
2107
- }
2108
- const definedResults = results.filter((result) => isSet(result));
2109
- if (definedResults.length > 0) {
2110
- let mergedResult = void 0;
2111
- for (const result of definedResults) mergedResult = defu$1(result, mergedResult ?? {});
2112
- return mergedResult;
2113
- }
2114
- }
2115
- }
2116
- function extractHooks(context, hooks, plugin, key, parentKey) {
2117
- const combinedKey = parentKey ? `${parentKey}:${key}` : key;
2118
- const pluginField = getField(plugin, combinedKey.replace(/:/g, "."));
2119
- if (isPluginHookField(combinedKey) && isPluginHook(pluginField)) {
2120
- const pluginHook = pluginField;
2121
- if (!isPluginHook(pluginHook)) return hooks;
2122
- hooks[combinedKey] ??= {
2123
- preEnforced: [],
2124
- preOrdered: [],
2125
- normal: [],
2126
- postEnforced: [],
2127
- postOrdered: []
2128
- };
2129
- if (plugin.enforce) {
2130
- const hookListOrder = `${plugin.enforce}Enforced`;
2131
- hooks[combinedKey][hookListOrder] ??= [];
2132
- hooks[combinedKey][hookListOrder] = addPluginHook(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
2133
- return hooks;
2134
- }
2135
- if (isFunction(pluginHook) || !pluginHook.order) {
2136
- hooks[combinedKey].normal ??= [];
2137
- hooks[combinedKey].normal = addPluginHook(context, plugin, pluginHook, hooks[combinedKey].normal);
2138
- return hooks;
2139
- }
2140
- const hookListOrder = `${pluginHook.order}Ordered`;
2141
- hooks[combinedKey][hookListOrder] ??= [];
2142
- hooks[combinedKey][hookListOrder] = addPluginHook(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
2143
- return hooks;
2144
- } else if (isSetObject(pluginField)) return Object.keys(pluginField).map((pluginKey) => extractHooks(context, hooks, plugin, pluginKey, combinedKey)).reduce((ret, current) => {
2145
- Object.keys(current).forEach((key) => {
2146
- ret[key] ??= {
2147
- preEnforced: [],
2148
- preOrdered: [],
2149
- normal: [],
2150
- postEnforced: [],
2151
- postOrdered: []
2152
- };
2153
- [
2154
- "preEnforced",
2155
- "preOrdered",
2156
- "normal",
2157
- "postEnforced",
2158
- "postOrdered"
2159
- ].forEach((order) => {
2160
- if (current[key]?.[order]) {
2161
- ret[key][order] ??= [];
2162
- ret[key][order] = ret[key][order].concat(current[key][order]);
2163
- }
2164
- });
2165
- });
2166
- return ret;
2167
- }, hooks);
2168
- return hooks;
2169
- }
2170
-
2171
- //#endregion
2172
- //#region src/context/plugin-context.ts
2173
- /**
2174
- * Create a Proxy-based PluginContext
2175
- *
2176
- * @param plugin - The plugin instance
2177
- * @param environment - The environment context
2178
- * @returns The proxied plugin context
2179
- */
2180
- function createPluginContext(plugin, environment) {
2181
- const normalizeMessage = (message) => {
2182
- return isString(message) ? message : message.message;
2183
- };
2184
- const log = environment.extendLog(plugin.name.replaceAll(":", " - "));
2185
- const callHookFn = async (hook, options, ...args) => {
2186
- return environment.$$internal.api.callHook(hook, {
2187
- sequential: true,
2188
- result: "merge",
2189
- ...options,
2190
- environment
2191
- }, ...args);
2192
- };
2193
- const meta = {};
2194
- return new Proxy({}, {
2195
- get(_, prop) {
2196
- if (prop === "$$internal") return {
2197
- ...environment.$$internal,
2198
- environment,
2199
- callHook: callHookFn,
2200
- meta
2201
- };
2202
- if (prop === "log" || prop === "logger") return log;
2203
- if (prop === "fatal") return (message) => {
2204
- log(LogLevelLabel.FATAL, normalizeMessage(message));
2205
- };
2206
- if (prop === "error") return (message) => {
2207
- log(LogLevelLabel.ERROR, normalizeMessage(message));
2208
- };
2209
- if (prop === "warn") return (message) => {
2210
- log(LogLevelLabel.WARN, normalizeMessage(message));
2211
- };
2212
- if (prop === "info") return (message) => {
2213
- log(LogLevelLabel.INFO, normalizeMessage(message));
2214
- };
2215
- if (prop === "debug") return (message) => {
2216
- log(LogLevelLabel.DEBUG, normalizeMessage(message));
2217
- };
2218
- if (prop === "trace") return (message) => {
2219
- log(LogLevelLabel.TRACE, normalizeMessage(message));
2220
- };
2221
- return environment[prop];
2222
- },
2223
- set(_, prop, value) {
2224
- if ([
2225
- "$$internal",
2226
- "environment",
2227
- "config",
2228
- "log",
2229
- "logger",
2230
- "error",
2231
- "warn",
2232
- "plugins",
2233
- "hooks",
2234
- "addPlugin",
2235
- "selectHooks"
2236
- ].includes(prop)) {
2237
- log(LogLevelLabel.WARN, `Cannot set read-only property "${String(prop)}"`);
2238
- return false;
2239
- }
2240
- environment[prop] = value;
2241
- return true;
2242
- }
2243
- });
2244
- }
2245
-
2246
- //#endregion
2247
- //#region src/context/environment-context.ts
2248
- var PowerlinesEnvironmentContext = class PowerlinesEnvironmentContext extends PowerlinesContext {
2249
- /**
2250
- * The hooks registered by plugins in this environment
2251
- */
2252
- #hooks = {};
2253
- /**
2254
- * Create a new context from the config.
2255
- *
2256
- * @param options - The resolved execution options.
2257
- * @param config - The user configuration options.
2258
- * @returns A promise that resolves to the new context.
2259
- */
2260
- static async fromConfig(options, config, environment) {
2261
- const context = new PowerlinesEnvironmentContext(options, config, environment);
2262
- await context.setup();
2263
- const powerlinesPath = await resolvePackage("powerlines");
2264
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2265
- context.powerlinesPath = powerlinesPath;
2266
- return context;
2267
- }
2268
- /**
2269
- * The resolved environment configuration
2270
- */
2271
- environment;
2272
- /**
2273
- * The list of plugins applied to this environment
2274
- */
2275
- plugins = [];
2276
- /**
2277
- * Create a new logger instance
2278
- *
2279
- * @param name - The name to use for the logger instance
2280
- * @returns A logger function
2281
- */
2282
- createLog(name = null) {
2283
- return createLog(name, {
2284
- ...this.config,
2285
- logLevel: isNull(this.config.logLevel) ? "silent" : this.config.logLevel,
2286
- environment: this.environment?.name
2287
- });
2288
- }
2289
- /**
2290
- * The hooks registered by plugins in this environment
2291
- */
2292
- get hooks() {
2293
- return this.#hooks;
2294
- }
2295
- /**
2296
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2297
- *
2298
- * @remarks
2299
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2300
- *
2301
- * @returns A promise that resolves to the cloned context.
2302
- */
2303
- async clone() {
2304
- const context = await PowerlinesEnvironmentContext.fromConfig(deepClone(this.options), deepClone(this.config), deepClone(this.environment));
2305
- return this.copyTo(context);
2306
- }
2307
- /**
2308
- * Initialize the context with the provided configuration options
2309
- */
2310
- async setup() {
2311
- this.resolvedConfig = mergeConfig({
2312
- name: this.config.name,
2313
- title: this.config.title
2314
- }, getConfigProps(this.environment, this.options.root, this.options.cwd), this.config);
2315
- await this.innerSetup();
2316
- }
2317
- async addPlugin(plugin) {
2318
- let resolvedPlugin = plugin;
2319
- if (isFunction(plugin.applyToEnvironment)) {
2320
- const result = await Promise.resolve(plugin.applyToEnvironment(this.environment));
2321
- if (!result || isObject(result) && Object.keys(result).length === 0) return;
2322
- if (isPluginConfig(result)) return this.$$internal.addPlugin(result);
2323
- resolvedPlugin = isPlugin(result) ? result : plugin;
2324
- }
2325
- const context = createPluginContext(resolvedPlugin, this);
2326
- this.plugins.push({
2327
- plugin: resolvedPlugin,
2328
- context
2329
- });
2330
- this.#hooks = Object.entries(Object.keys(resolvedPlugin).filter((key) => !PLUGIN_NON_HOOK_FIELDS.includes(key)).reduce((ret, key) => extractHooks(context, ret, resolvedPlugin, key), this.hooks)).reduce((ret, [key, value]) => {
2331
- if (isSetObject(value)) Object.entries(value).forEach(([type, list]) => {
2332
- ret[key] ??= {};
2333
- ret[key][type] = dedupeHooklist(list);
2334
- });
2335
- return ret;
2336
- }, {});
2337
- }
2338
- /**
2339
- * Retrieves the hook handlers for a specific hook name
2340
- */
2341
- selectHooks(key, options) {
2342
- const result = [];
2343
- if (isPluginHookField(key) && this.hooks[key]) {
2344
- if (this.hooks[key]) if (options?.order) {
2345
- const mapHooksToResult = (hooksList) => hooksList.map((hook) => {
2346
- const plugin = this.plugins.find((p) => p.plugin.name === hook.plugin.name);
2347
- if (!plugin) throw new Error(`Could not find plugin context for plugin "${hook.plugin.name}".`);
2348
- return {
2349
- handler: hook.handler,
2350
- plugin: hook.plugin,
2351
- context: plugin.context
2352
- };
2353
- });
2354
- if (options?.order === "pre") {
2355
- result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));
2356
- result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));
2357
- } else if (options?.order === "post") {
2358
- result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));
2359
- result.push(...mapHooksToResult(this.hooks[key].postEnforced ?? []));
2360
- } else result.push(...mapHooksToResult(this.hooks[key].normal ?? []));
2361
- } else {
2362
- result.push(...this.selectHooks(key, { order: "pre" }));
2363
- result.push(...this.selectHooks(key, { order: "normal" }));
2364
- result.push(...this.selectHooks(key, { order: "post" }));
2365
- }
2366
- }
2367
- return result;
2368
- }
2369
- constructor(options, config, environment) {
2370
- super(options);
2371
- this.resolvedConfig = config;
2372
- this.environment = environment;
2373
- }
2374
- /**
2375
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2376
- *
2377
- * @remarks
2378
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2379
- *
2380
- * @returns The cloned context.
2381
- */
2382
- copyTo(context) {
2383
- context.plugins = this.plugins;
2384
- return super.copyTo(context);
2385
- }
2386
- };
2387
-
2388
- //#endregion
2389
- //#region src/context/execution-context.ts
2390
- var PowerlinesExecutionContext = class PowerlinesExecutionContext extends PowerlinesContext {
2391
- #environments = {};
2392
- #plugins = [];
2393
- /**
2394
- * Create a new Storm context from the workspace root and user config.
2395
- *
2396
- * @param options - The options for resolving the context.
2397
- * @returns A promise that resolves to the new context.
2398
- */
2399
- static async fromOptions(options) {
2400
- const context = new PowerlinesExecutionContext(options);
2401
- await context.init(options);
2402
- const powerlinesPath = await resolvePackage("powerlines");
2403
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2404
- context.powerlinesPath = powerlinesPath;
2405
- return context;
2406
- }
2407
- /**
2408
- * Create a new Storm context from the workspace root and user config.
2409
- *
2410
- * @param options - The options for resolving the context.
2411
- * @returns A promise that resolves to the new context.
2412
- */
2413
- static async fromConfig(options, config) {
2414
- const context = new PowerlinesExecutionContext(options);
2415
- await context.init(options);
2416
- context.config.inlineConfig = config;
2417
- if (context.config.inlineConfig.command === "new") {
2418
- const workspacePackageJsonPath = joinPaths(context.config.cwd, "package.json");
2419
- if (!existsSync(workspacePackageJsonPath)) throw new Error(`The workspace package.json file could not be found at ${workspacePackageJsonPath}`);
2420
- context.packageJson = await readJsonFile(workspacePackageJsonPath);
2421
- }
2422
- await context.setup();
2423
- const powerlinesPath = await resolvePackage("powerlines");
2424
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2425
- context.powerlinesPath = powerlinesPath;
2426
- return context;
2427
- }
2428
- /**
2429
- * Internal context fields and methods
2430
- *
2431
- * @danger
2432
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2433
- *
2434
- * @internal
2435
- */
2436
- get $$internal() {
2437
- return super.$$internal;
2438
- }
2439
- /**
2440
- * Internal context fields and methods
2441
- *
2442
- * @danger
2443
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2444
- *
2445
- * @internal
2446
- */
2447
- set $$internal(value) {
2448
- super.$$internal = value;
2449
- for (const environment of Object.values(this.environments)) environment.$$internal = super.$$internal;
2450
- }
2451
- /**
2452
- * A record of all environments by name
2453
- */
2454
- get environments() {
2455
- return this.#environments;
2456
- }
2457
- get plugins() {
2458
- return this.#plugins;
2459
- }
2460
- /**
2461
- * Creates a new instance.
2462
- *
2463
- * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.
2464
- */
2465
- constructor(options) {
2466
- super(options);
2467
- }
2468
- /**
2469
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2470
- *
2471
- * @remarks
2472
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2473
- *
2474
- * @returns A promise that resolves to the cloned context.
2475
- */
2476
- async clone() {
2477
- const clone = await PowerlinesExecutionContext.fromOptions(this.options);
2478
- clone.config.userConfig = deepClone(this.config.userConfig);
2479
- clone.config.inlineConfig = deepClone(this.config.inlineConfig);
2480
- clone.config.pluginConfig = deepClone(this.config.pluginConfig);
2481
- await clone.setup();
2482
- clone.$$internal = this.$$internal;
2483
- return this.copyTo(clone);
2484
- }
2485
- /**
2486
- * A function to copy the context and update the fields for a specific environment
2487
- *
2488
- * @param environment - The environment configuration to use.
2489
- * @returns A new context instance with the updated environment.
2490
- */
2491
- async in(environment) {
2492
- const context = this.copyTo(await PowerlinesEnvironmentContext.fromConfig(deepClone(this.options), deepClone(this.config), deepClone(environment)));
2493
- context.plugins = [];
2494
- for (const plugin of this.plugins) await context.addPlugin(plugin);
2495
- return context;
2496
- }
2497
- /**
2498
- * Update the context using a new inline configuration options
2499
- */
2500
- async setup() {
2501
- await super.setup();
2502
- await Promise.all(toArray(this.config.environments && Object.keys(this.config.environments).length > 0 ? Object.keys(this.config.environments).map((name) => createEnvironment(name, this.config)) : createDefaultEnvironment(this.config)).map(async (env) => {
2503
- this.#environments[env.name] = await this.in(env);
2504
- }));
2505
- }
2506
- /**
2507
- * Add a plugin to the API context and all environments
2508
- *
2509
- * @param plugin - The plugin to add.
2510
- */
2511
- async addPlugin(plugin) {
2512
- this.plugins.push(plugin);
2513
- await Promise.all(Object.keys(this.environments).map(async (name) => {
2514
- await this.environments[name].addPlugin(plugin);
2515
- }));
2516
- }
2517
- /**
2518
- * Get an environment by name, or the default environment if no name is provided
2519
- *
2520
- * @param name - The name of the environment to retrieve.
2521
- * @returns The requested environment context.
2522
- */
2523
- async getEnvironment(name) {
2524
- let environment;
2525
- if (name) environment = this.environments[name];
2526
- if (Object.keys(this.environments).length === 1) {
2527
- environment = this.environments[Object.keys(this.environments)[0]];
2528
- this.debug(`Applying the only configured environment: ${chalk.bold.cyanBright(environment?.environment.name)}`);
2529
- }
2530
- if (!environment) {
2531
- if (name) throw new Error(`Environment "${name}" not found.`);
2532
- environment = await this.in(createDefaultEnvironment(this.config));
2533
- this.warn(`No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(environment?.environment.name)}`);
2534
- }
2535
- return environment;
2536
- }
2537
- /**
2538
- * A safe version of `getEnvironment` that returns `undefined` if the environment is not found
2539
- *
2540
- * @param name - The name of the environment to retrieve.
2541
- * @returns The requested environment context or `undefined` if not found.
2542
- */
2543
- async getEnvironmentSafe(name) {
2544
- try {
2545
- return await this.getEnvironment(name);
2546
- } catch {
2547
- return;
2548
- }
2549
- }
2550
- /**
2551
- * A function to merge all configured environments into a single context.
2552
- *
2553
- * @remarks
2554
- * If only one environment is configured, that environment will be returned directly.
2555
- *
2556
- * @returns A promise that resolves to a merged/global environment context.
2557
- */
2558
- async toEnvironment() {
2559
- let environment;
2560
- if (Object.keys(this.environments).length > 1) {
2561
- environment = await this.in(createEnvironment(GLOBAL_ENVIRONMENT, this.config));
2562
- this.debug(`Combined all ${Object.keys(this.environments).length} environments into a single global context.`);
2563
- } else environment = await this.getEnvironment();
2564
- return environment;
2565
- }
2566
- };
2567
-
2568
- //#endregion
2569
- export { mergeConfigs as a, callHook as i, PowerlinesEnvironmentContext as n, PowerlinesContext as o, createPluginContext as r, writeMetaFile as s, PowerlinesExecutionContext as t };
2570
- //# sourceMappingURL=execution-context-D_CXpe9I.mjs.map