@powerlines/nx 0.11.269 → 0.11.270

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