@powerlines/nx 0.11.221 → 0.11.223

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