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