@walkeros/cli 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +112 -42
  3. package/dist/__tests__/bundle/bundler-helpers.test.d.ts +2 -0
  4. package/dist/__tests__/bundle/bundler-helpers.test.d.ts.map +1 -0
  5. package/dist/__tests__/bundle/bundler-helpers.test.js +285 -0
  6. package/dist/__tests__/bundle/bundler-helpers.test.js.map +1 -0
  7. package/dist/__tests__/bundle/bundler.test.js +176 -166
  8. package/dist/__tests__/bundle/bundler.test.js.map +1 -1
  9. package/dist/__tests__/bundle/programmatic.test.js +77 -54
  10. package/dist/__tests__/bundle/programmatic.test.js.map +1 -1
  11. package/dist/__tests__/bundle/serializer.test.js +1 -1
  12. package/dist/__tests__/bundle/serializer.test.js.map +1 -1
  13. package/dist/__tests__/bundle/template-engine.test.js +1 -1
  14. package/dist/__tests__/bundle/template-engine.test.js.map +1 -1
  15. package/dist/__tests__/cli-e2e.test.js +1 -1
  16. package/dist/__tests__/cli-e2e.test.js.map +1 -1
  17. package/dist/__tests__/cli.test.js +60 -117
  18. package/dist/__tests__/cli.test.js.map +1 -1
  19. package/dist/__tests__/config-loader.test.d.ts +1 -1
  20. package/dist/__tests__/config-loader.test.js +234 -212
  21. package/dist/__tests__/config-loader.test.js.map +1 -1
  22. package/dist/__tests__/core/build-cache.test.d.ts +2 -0
  23. package/dist/__tests__/core/build-cache.test.d.ts.map +1 -0
  24. package/dist/__tests__/core/build-cache.test.js +55 -0
  25. package/dist/__tests__/core/build-cache.test.js.map +1 -0
  26. package/dist/__tests__/core/cache-utils.test.d.ts +2 -0
  27. package/dist/__tests__/core/cache-utils.test.d.ts.map +1 -0
  28. package/dist/__tests__/core/cache-utils.test.js +70 -0
  29. package/dist/__tests__/core/cache-utils.test.js.map +1 -0
  30. package/dist/__tests__/core/config.test.js +1 -1
  31. package/dist/__tests__/core/config.test.js.map +1 -1
  32. package/dist/__tests__/core/logger.test.js +1 -1
  33. package/dist/__tests__/core/logger.test.js.map +1 -1
  34. package/dist/__tests__/integration/bundle-run.integration.test.d.ts +8 -0
  35. package/dist/__tests__/integration/bundle-run.integration.test.d.ts.map +1 -0
  36. package/dist/__tests__/integration/bundle-run.integration.test.js +54 -0
  37. package/dist/__tests__/integration/bundle-run.integration.test.js.map +1 -0
  38. package/dist/__tests__/push/push.test.d.ts +7 -0
  39. package/dist/__tests__/push/push.test.d.ts.map +1 -0
  40. package/dist/__tests__/push/push.test.js +197 -0
  41. package/dist/__tests__/push/push.test.js.map +1 -0
  42. package/dist/__tests__/simulate/env-loader.test.d.ts +2 -0
  43. package/dist/__tests__/simulate/env-loader.test.d.ts.map +1 -0
  44. package/dist/__tests__/simulate/env-loader.test.js +47 -0
  45. package/dist/__tests__/simulate/env-loader.test.js.map +1 -0
  46. package/dist/__tests__/simulate/node-executor.test.d.ts +5 -0
  47. package/dist/__tests__/simulate/node-executor.test.d.ts.map +1 -0
  48. package/dist/__tests__/simulate/node-executor.test.js +25 -0
  49. package/dist/__tests__/simulate/node-executor.test.js.map +1 -0
  50. package/dist/__tests__/simulate/server-simulate.integration.test.d.ts +5 -0
  51. package/dist/__tests__/simulate/server-simulate.integration.test.d.ts.map +1 -0
  52. package/dist/__tests__/simulate/server-simulate.integration.test.js +59 -0
  53. package/dist/__tests__/simulate/server-simulate.integration.test.js.map +1 -0
  54. package/dist/__tests__/smoke/production.smoke.test.d.ts +8 -0
  55. package/dist/__tests__/smoke/production.smoke.test.d.ts.map +1 -0
  56. package/dist/__tests__/smoke/production.smoke.test.js +65 -0
  57. package/dist/__tests__/smoke/production.smoke.test.js.map +1 -0
  58. package/dist/commands/bundle/bundler.d.ts +2 -2
  59. package/dist/commands/bundle/bundler.d.ts.map +1 -1
  60. package/dist/commands/bundle/bundler.js +156 -54
  61. package/dist/commands/bundle/bundler.js.map +1 -1
  62. package/dist/commands/bundle/index.d.ts +17 -11
  63. package/dist/commands/bundle/index.d.ts.map +1 -1
  64. package/dist/commands/bundle/index.js +53 -53
  65. package/dist/commands/bundle/index.js.map +1 -1
  66. package/dist/commands/bundle/package-manager.d.ts +3 -2
  67. package/dist/commands/bundle/package-manager.d.ts.map +1 -1
  68. package/dist/commands/bundle/package-manager.js +34 -7
  69. package/dist/commands/bundle/package-manager.js.map +1 -1
  70. package/dist/commands/bundle/serializer.d.ts +1 -1
  71. package/dist/commands/bundle/serializer.d.ts.map +1 -1
  72. package/dist/commands/bundle/serializer.js +1 -1
  73. package/dist/commands/bundle/serializer.js.map +1 -1
  74. package/dist/commands/bundle/stats.d.ts +2 -2
  75. package/dist/commands/bundle/stats.d.ts.map +1 -1
  76. package/dist/commands/bundle/stats.js +1 -1
  77. package/dist/commands/bundle/stats.js.map +1 -1
  78. package/dist/commands/bundle/template-engine.d.ts +1 -1
  79. package/dist/commands/bundle/template-engine.d.ts.map +1 -1
  80. package/dist/commands/bundle/template-engine.js +2 -2
  81. package/dist/commands/bundle/template-engine.js.map +1 -1
  82. package/dist/commands/cache.d.ts +3 -0
  83. package/dist/commands/cache.d.ts.map +1 -0
  84. package/dist/commands/cache.js +44 -0
  85. package/dist/commands/cache.js.map +1 -0
  86. package/dist/commands/push/index.d.ts +7 -0
  87. package/dist/commands/push/index.d.ts.map +1 -0
  88. package/dist/commands/push/index.js +257 -0
  89. package/dist/commands/push/index.js.map +1 -0
  90. package/dist/commands/push/types.d.ts +21 -0
  91. package/dist/commands/push/types.d.ts.map +1 -0
  92. package/dist/commands/push/types.js +2 -0
  93. package/dist/commands/push/types.js.map +1 -0
  94. package/dist/commands/run/__tests__/run.integration.test.js +15 -16
  95. package/dist/commands/run/__tests__/run.integration.test.js.map +1 -1
  96. package/dist/commands/run/__tests__/validators.test.js +1 -1
  97. package/dist/commands/run/__tests__/validators.test.js.map +1 -1
  98. package/dist/commands/run/execution.d.ts +14 -0
  99. package/dist/commands/run/execution.d.ts.map +1 -0
  100. package/dist/commands/run/execution.js +37 -0
  101. package/dist/commands/run/execution.js.map +1 -0
  102. package/dist/commands/run/index.d.ts +1 -1
  103. package/dist/commands/run/index.d.ts.map +1 -1
  104. package/dist/commands/run/index.js +33 -107
  105. package/dist/commands/run/index.js.map +1 -1
  106. package/dist/commands/run/types.d.ts +1 -1
  107. package/dist/commands/run/types.d.ts.map +1 -1
  108. package/dist/commands/run/utils.d.ts +29 -0
  109. package/dist/commands/run/utils.d.ts.map +1 -0
  110. package/dist/commands/run/utils.js +52 -0
  111. package/dist/commands/run/utils.js.map +1 -0
  112. package/dist/commands/run/validators.d.ts +9 -5
  113. package/dist/commands/run/validators.d.ts.map +1 -1
  114. package/dist/commands/run/validators.js +15 -12
  115. package/dist/commands/run/validators.js.map +1 -1
  116. package/dist/commands/simulate/env-loader.d.ts +19 -0
  117. package/dist/commands/simulate/env-loader.d.ts.map +1 -0
  118. package/dist/commands/simulate/env-loader.js +46 -0
  119. package/dist/commands/simulate/env-loader.js.map +1 -0
  120. package/dist/commands/simulate/index.d.ts +4 -3
  121. package/dist/commands/simulate/index.d.ts.map +1 -1
  122. package/dist/commands/simulate/index.js +11 -19
  123. package/dist/commands/simulate/index.js.map +1 -1
  124. package/dist/commands/simulate/jsdom-executor.d.ts +13 -8
  125. package/dist/commands/simulate/jsdom-executor.d.ts.map +1 -1
  126. package/dist/commands/simulate/jsdom-executor.js +26 -49
  127. package/dist/commands/simulate/jsdom-executor.js.map +1 -1
  128. package/dist/commands/simulate/node-executor.d.ts +28 -0
  129. package/dist/commands/simulate/node-executor.d.ts.map +1 -0
  130. package/dist/commands/simulate/node-executor.js +94 -0
  131. package/dist/commands/simulate/node-executor.js.map +1 -0
  132. package/dist/commands/simulate/simulator.d.ts +1 -1
  133. package/dist/commands/simulate/simulator.d.ts.map +1 -1
  134. package/dist/commands/simulate/simulator.js +44 -36
  135. package/dist/commands/simulate/simulator.js.map +1 -1
  136. package/dist/commands/simulate/types.d.ts +2 -2
  137. package/dist/commands/simulate/types.d.ts.map +1 -1
  138. package/dist/config/build-defaults.d.ts +49 -0
  139. package/dist/config/build-defaults.d.ts.map +1 -0
  140. package/dist/config/build-defaults.js +72 -0
  141. package/dist/config/build-defaults.js.map +1 -0
  142. package/dist/config/index.d.ts +8 -9
  143. package/dist/config/index.d.ts.map +1 -1
  144. package/dist/config/index.js +7 -8
  145. package/dist/config/index.js.map +1 -1
  146. package/dist/config/loader.d.ts +35 -28
  147. package/dist/config/loader.d.ts.map +1 -1
  148. package/dist/config/loader.js +108 -89
  149. package/dist/config/loader.js.map +1 -1
  150. package/dist/config/utils.d.ts.map +1 -1
  151. package/dist/config/utils.js +3 -2
  152. package/dist/config/utils.js.map +1 -1
  153. package/dist/config/validators.d.ts +36 -7
  154. package/dist/config/validators.d.ts.map +1 -1
  155. package/dist/config/validators.js +61 -21
  156. package/dist/config/validators.js.map +1 -1
  157. package/dist/core/asset-resolver.d.ts +8 -15
  158. package/dist/core/asset-resolver.d.ts.map +1 -1
  159. package/dist/core/asset-resolver.js +30 -30
  160. package/dist/core/asset-resolver.js.map +1 -1
  161. package/dist/core/build-cache.d.ts +23 -0
  162. package/dist/core/build-cache.d.ts.map +1 -0
  163. package/dist/core/build-cache.js +43 -0
  164. package/dist/core/build-cache.js.map +1 -0
  165. package/dist/core/cache-utils.d.ts +27 -0
  166. package/dist/core/cache-utils.d.ts.map +1 -0
  167. package/dist/core/cache-utils.js +60 -0
  168. package/dist/core/cache-utils.js.map +1 -0
  169. package/dist/core/docker.d.ts +17 -1
  170. package/dist/core/docker.d.ts.map +1 -1
  171. package/dist/core/docker.js +30 -26
  172. package/dist/core/docker.js.map +1 -1
  173. package/dist/core/execution.d.ts +2 -2
  174. package/dist/core/execution.d.ts.map +1 -1
  175. package/dist/core/execution.js +1 -1
  176. package/dist/core/execution.js.map +1 -1
  177. package/dist/core/index.d.ts +9 -6
  178. package/dist/core/index.d.ts.map +1 -1
  179. package/dist/core/index.js +9 -6
  180. package/dist/core/index.js.map +1 -1
  181. package/dist/core/local-packages.d.ts +19 -0
  182. package/dist/core/local-packages.d.ts.map +1 -0
  183. package/dist/core/local-packages.js +60 -0
  184. package/dist/core/local-packages.js.map +1 -0
  185. package/dist/core/logger.d.ts +11 -0
  186. package/dist/core/logger.d.ts.map +1 -1
  187. package/dist/core/logger.js +14 -0
  188. package/dist/core/logger.js.map +1 -1
  189. package/dist/core/temp-manager.d.ts +51 -0
  190. package/dist/core/temp-manager.d.ts.map +1 -0
  191. package/dist/core/temp-manager.js +73 -0
  192. package/dist/core/temp-manager.js.map +1 -0
  193. package/dist/core/utils.d.ts +10 -0
  194. package/dist/core/utils.d.ts.map +1 -0
  195. package/dist/core/utils.js +12 -0
  196. package/dist/core/utils.js.map +1 -0
  197. package/dist/examples/.npm-cache/content-v2/sha512/0d/2d/7581c288670eaf8538ddd9df145b78756ce3be0791c6e0b9cd33429b3bae894525b9bda287a3cedffbcdd2c7b3107bafc03f2b0367eea489eee1cc042abb +1 -0
  198. package/dist/examples/.npm-cache/content-v2/sha512/12/20/bc4f5acca143809f7e07da1fdafb38137d93243de4d5b403e6e10b92d0d3a6e51eab24fe9dbc9d3ed1cd72e8f7a406085e99c422bb2c7d1166cf9f1f564e +0 -0
  199. package/dist/examples/.npm-cache/content-v2/sha512/22/ee/fb2695b01871c1d36946bdcfb49f1b520a57200d0a0b221b1e7d5f047ab38a8b2ab0e5f0e25a00acde1f3f2f9d24430a18f1092d438bc1a9e9891cc45f75 +0 -0
  200. package/dist/examples/.npm-cache/content-v2/sha512/24/89/da1ce6a61bca6de7e132f241a675c01c83738bf6b78af25b5cce01d3030361332b3fe938571e2b721f1555da9ddf930fdcf8c02f0471556071590e68cc09 +0 -0
  201. package/dist/examples/.npm-cache/content-v2/sha512/47/fd/c6be997da99228c3e279b95d4a46d6913947078a178f54ac71795a159f3513b1483232f4c2d0a1f403178bf9f96bb19615de32a9e2133e949880c6bc15e2 +0 -0
  202. package/dist/examples/.npm-cache/content-v2/sha512/4b/1c/c1cb7f8b32102071a89fef97158daa32080ebaedfbbd596880d2213d84e305abc76d2a95a412ded55c1c3d487adcb1ceff87fc2c85d7e2856ebd9d3f16f3 +0 -0
  203. package/dist/examples/.npm-cache/content-v2/sha512/6e/53/ff864769671f44f39d8a3bf904cd646535b745cc4824a8bb3189193b474678049f43b5178ba15cad7f0289046105e70f1565afc84e907120b35a466690fd +1 -0
  204. package/dist/examples/.npm-cache/content-v2/sha512/70/4c/4c8837d446965c5551b4ea527e95fa011744fb727581d82cf35bb5599ea0b57d18baa490f7af93ef9a16e8e45e5c0802737da20575f4056a4a5c9a3cd288 +0 -0
  205. package/dist/examples/.npm-cache/content-v2/sha512/96/ad/05de3bbb12d7de8ea353f962bdaea7d2eb44f707f2973462a6635daf537c67b46cca7764fed7d464fe62152c3f783a07aba1ceb35e09ad446bff05a4b466 +1 -0
  206. package/dist/examples/.npm-cache/content-v2/sha512/b5/20/52dde94e6cef7170f6089c64a4843e57be18be450d956f4e455905aed047ae6a368451c93035e6ac3ee59576b600f03f815afba0836b3a16e10a9aaca4ba +1 -0
  207. package/dist/examples/.npm-cache/content-v2/sha512/c7/a9/d166a1c39f97df312c59261319ba1cf9aac178bda0a0cb697d5ddd78bd8dd38ef1bf40017bcc8633c2049896c2d70696d9bff9280851f270792ff38bb3a0 +1 -0
  208. package/dist/examples/.npm-cache/content-v2/sha512/e0/d0/8c14083b633e6adbd3c6a93da5fc0f6bbd456c5512ef276920bedd8d85d551052adff992de977aff326616a211aaa2d6ddcc801149e9b7f914f566359b6a +1 -0
  209. package/dist/examples/.npm-cache/content-v2/sha512/e7/c5/06ad3fd79ac4f1031fe0b16ea5e54e232ca397bbcd7592c679021cbfb027276099f8c848f3f7a7691f0102ad53aa64f9141e61d729b037a678bd60440d17 +1 -0
  210. package/dist/examples/.npm-cache/content-v2/sha512/f3/28/d5d32329604ed7d471a4949105daa2cc98858cf24f45b0b97c41d0eb0d5a9fe7bf1f69c792161cc6693e4fc1b52e886ac41875ebfb8fe47fafe417ca3e6e +0 -0
  211. package/dist/examples/.npm-cache/index-v5/04/5a/2b5d7a7c407d85d746baa0f5c9388a333e35a717a8a0a81943daa6cb1364 +3 -0
  212. package/dist/examples/.npm-cache/index-v5/12/9a/eba560cbace295d8ee04cf283015377bd77b379e70968fb6bc407c7fc410 +15 -0
  213. package/dist/examples/.npm-cache/index-v5/2f/a2/7b047564b0ee21ac835ec609e89153dd6549be554d098584d5bfd19fe043 +15 -0
  214. package/dist/examples/.npm-cache/index-v5/32/8e/322d58dd8d1e000be248ada51385bf96288e56039de9feec1a4c6a467653 +3 -0
  215. package/dist/examples/.npm-cache/index-v5/57/93/d1d7cd1402e3e26468db03f2870822bb2c9018a506cdfb3b405f38cd3e1c +3 -0
  216. package/dist/examples/.npm-cache/index-v5/5d/f8/0a1f4fa7149e4ff33e09eb6aea41ac8d1730c868a5d3ace91f762698acff +3 -0
  217. package/dist/examples/.npm-cache/index-v5/69/a4/a92c72d838259b051cdf8e0acfb2bc680b6d4cfc642314a7836c3f7b2c50 +15 -0
  218. package/dist/examples/.npm-cache/index-v5/71/31/6da3423bb203f3de5eb16c942431073f89be2cfcb40058ec91dcb5ce0abc +15 -0
  219. package/dist/examples/.npm-cache/index-v5/7b/94/72b6bffa050d9ef52a558dd220663695bc606f756be0dfa196ef4f3913ba +3 -0
  220. package/dist/examples/.npm-cache/index-v5/85/9e/99e97fdd562517e56285337db91d1a8f2f416b8d631cf4d7d754fa671299 +15 -0
  221. package/dist/examples/.npm-cache/index-v5/92/4c/9416ada81a9b3c679539fd1ab53f8de3d41ff268f35eba7a194389a85b06 +3 -0
  222. package/dist/examples/.npm-cache/index-v5/c1/5a/13df76b218deed8a6ef12961116af5183db98c53fad1b922fd9edc075247 +3 -0
  223. package/dist/examples/.npm-cache/index-v5/cb/11/253c55410a8ab7c4a9ea9d6e1bf8ef1450a581da64c478074dfd82c8bff6 +3 -0
  224. package/dist/examples/.npm-cache/index-v5/d5/ae/b57fad3a62b5ba2dbdf24b042a9e7b70820f3db00e5a630f02e1fea020dc +3 -0
  225. package/dist/examples/.npm-cache/index-v5/d6/32/2f620f83c7d14451de98de8298c2408e05a16cc0829bd16c891ac19d7a67 +3 -0
  226. package/dist/examples/.npm-cache/index-v5/dd/b5/01dc7a3cd8b6a03a69aee9af500d51ae19cb0aa12631a4aafd152148b8e5 +15 -0
  227. package/dist/examples/.npm-cache/index-v5/e0/cf/6b862c15d74630d3871cd813d305210ab741311deb10baf8813014e0bc30 +3 -0
  228. package/dist/examples/.npm-cache/index-v5/e2/be/e880ccd35950a814d3c1dded34d3938ac61b15a195321dc51357f801aad4 +15 -0
  229. package/dist/examples/.npm-cache/index-v5/e5/1f/f4affe0b392cd03288f23cc03abcb274ff11a2c8f8965299de681914abb2 +3 -0
  230. package/dist/examples/.npm-cache/index-v5/f3/5b/9ebe450958ff0d7cc44ab0a00080cb8a3ff1389744b5eab5f97b68a6a6af +3 -0
  231. package/dist/examples/.npm-cache/index-v5/fb/c1/0de405e902866d53e7c30cf36a97dc2578838622b261816f44dc377c9a80 +3 -0
  232. package/dist/examples/README.md +343 -0
  233. package/dist/examples/event.json +53 -0
  234. package/dist/examples/flow-order-complete.json +68 -0
  235. package/dist/examples/flow-simple.json +32 -0
  236. package/dist/examples/flow.json +82 -0
  237. package/dist/examples/server-collect.json +60 -0
  238. package/dist/examples/server-collect.mjs +13540 -0
  239. package/dist/examples/test.html +43 -0
  240. package/dist/examples/web-serve.js +25503 -0
  241. package/dist/examples/web-serve.json +74 -0
  242. package/dist/index.d.ts +98 -200
  243. package/dist/index.d.ts.map +1 -1
  244. package/dist/index.js +2783 -120
  245. package/dist/index.js.map +1 -1
  246. package/dist/schemas/index.d.ts +9 -0
  247. package/dist/schemas/index.d.ts.map +1 -0
  248. package/dist/schemas/index.js +9 -0
  249. package/dist/schemas/index.js.map +1 -0
  250. package/dist/schemas/primitives.d.ts +37 -0
  251. package/dist/schemas/primitives.d.ts.map +1 -0
  252. package/dist/schemas/primitives.js +43 -0
  253. package/dist/schemas/primitives.js.map +1 -0
  254. package/dist/schemas/run.d.ts +23 -0
  255. package/dist/schemas/run.d.ts.map +1 -0
  256. package/dist/schemas/run.js +20 -0
  257. package/dist/schemas/run.js.map +1 -0
  258. package/dist/templates/server.hbs +29 -0
  259. package/dist/templates/web.hbs +45 -0
  260. package/dist/types/bundle.d.ts +68 -190
  261. package/dist/types/bundle.d.ts.map +1 -1
  262. package/dist/types/bundle.js +2 -2
  263. package/dist/types/index.d.ts +2 -2
  264. package/dist/types/index.d.ts.map +1 -1
  265. package/dist/types/index.js +2 -2
  266. package/dist/types/index.js.map +1 -1
  267. package/dist/walker.js +1 -0
  268. package/examples/README.md +42 -29
  269. package/examples/event.json +1 -1
  270. package/examples/flow-order-complete.json +57 -57
  271. package/examples/flow-simple.json +25 -25
  272. package/examples/flow.json +69 -69
  273. package/examples/server-collect.json +51 -44
  274. package/examples/server-collect.mjs +1360 -1190
  275. package/examples/web-serve.js +25469 -11
  276. package/examples/web-serve.json +62 -63
  277. package/package.json +3 -2
  278. package/dist/__tests__/bundle/bundler-integration.test.d.ts +0 -2
  279. package/dist/__tests__/bundle/bundler-integration.test.d.ts.map +0 -1
  280. package/dist/__tests__/bundle/bundler-integration.test.js +0 -106
  281. package/dist/__tests__/bundle/bundler-integration.test.js.map +0 -1
  282. package/dist/__tests__/simulate/programmatic.test.d.ts +0 -2
  283. package/dist/__tests__/simulate/programmatic.test.d.ts.map +0 -1
  284. package/dist/__tests__/simulate/programmatic.test.js +0 -51
  285. package/dist/__tests__/simulate/programmatic.test.js.map +0 -1
  286. package/dist/__tests__/simulate/simulator.test.d.ts +0 -2
  287. package/dist/__tests__/simulate/simulator.test.d.ts.map +0 -1
  288. package/dist/__tests__/simulate/simulator.test.js +0 -29
  289. package/dist/__tests__/simulate/simulator.test.js.map +0 -1
  290. package/dist/config/defaults.d.ts +0 -33
  291. package/dist/config/defaults.d.ts.map +0 -1
  292. package/dist/config/defaults.js +0 -69
  293. package/dist/config/defaults.js.map +0 -1
  294. package/dist/config/parser.d.ts +0 -64
  295. package/dist/config/parser.d.ts.map +0 -1
  296. package/dist/config/parser.js +0 -151
  297. package/dist/config/parser.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,132 +1,2795 @@
1
- import { Command } from 'commander';
2
- import { readFileSync } from 'fs';
3
- import { fileURLToPath } from 'url';
4
- import { dirname, join } from 'path';
5
- import { bundleCommand } from './commands/bundle';
6
- import { simulateCommand } from './commands/simulate';
7
- import { runCommand } from './commands/run';
8
- // Get package version dynamically
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
- const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'));
12
- const VERSION = packageJson.version;
13
- // === CLI Commands ===
14
- // Export CLI command handlers
15
- export { bundleCommand, simulateCommand, runCommand };
16
- // === Programmatic API ===
17
- // High-level functions for library usage
18
- export { bundle } from './commands/bundle';
19
- export { simulate } from './commands/simulate';
20
- export { run } from './commands/run';
21
- const program = new Command();
22
- program
23
- .name('walkeros')
24
- .description('walkerOS CLI - Bundle and deploy walkerOS components')
25
- .version(VERSION);
26
- // Bundle command
27
- program
28
- .command('bundle [file]')
29
- .description('Bundle NPM packages with custom code')
30
- .option('-e, --env <name>', 'environment to build (for multi-environment configs)')
31
- .option('--all', 'build all environments (for multi-environment configs)')
32
- .option('-s, --stats', 'show bundle statistics')
33
- .option('--json', 'output statistics in JSON format (implies --stats)')
34
- .option('--no-cache', 'disable package caching and download fresh packages')
35
- .option('-v, --verbose', 'verbose output')
36
- .option('--local', 'execute in local Node.js instead of Docker')
37
- .option('--dry-run', 'preview command without executing')
38
- .option('--silent', 'suppress output')
39
- .action(async (file, options) => {
40
- await bundleCommand({
41
- config: file || 'bundle.config.json',
42
- env: options.env,
43
- all: options.all,
44
- stats: options.stats,
45
- json: options.json,
46
- cache: options.cache,
47
- verbose: options.verbose,
48
- local: options.local,
49
- dryRun: options.dryRun,
50
- silent: options.silent,
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import { readFileSync } from "fs";
6
+ import { fileURLToPath as fileURLToPath2 } from "url";
7
+ import { dirname, join } from "path";
8
+
9
+ // src/commands/bundle/index.ts
10
+ import path9 from "path";
11
+
12
+ // src/core/logger.ts
13
+ import chalk from "chalk";
14
+ function createLogger(options = {}) {
15
+ const { verbose = false, silent = false, json = false } = options;
16
+ const shouldLog = !silent && !json;
17
+ const shouldDebug = verbose && !silent && !json;
18
+ return {
19
+ log: (color, ...args) => {
20
+ if (shouldLog) {
21
+ const message = args.map((arg) => String(arg)).join(" ");
22
+ const colorMap = {
23
+ red: chalk.red,
24
+ green: chalk.green,
25
+ blue: chalk.blue,
26
+ yellow: chalk.yellow,
27
+ gray: chalk.gray,
28
+ grey: chalk.gray,
29
+ cyan: chalk.cyan,
30
+ magenta: chalk.magenta,
31
+ white: chalk.white,
32
+ black: chalk.black
33
+ };
34
+ const colorFn = colorMap[color];
35
+ const coloredMessage = colorFn ? colorFn(message) : message;
36
+ console.log(coloredMessage);
37
+ }
38
+ },
39
+ info: (...args) => {
40
+ if (shouldLog) {
41
+ const message = args.map((arg) => String(arg)).join(" ");
42
+ console.log(chalk.blue(message));
43
+ }
44
+ },
45
+ success: (...args) => {
46
+ if (shouldLog) {
47
+ const message = args.map((arg) => String(arg)).join(" ");
48
+ console.log(chalk.green(message));
49
+ }
50
+ },
51
+ warning: (...args) => {
52
+ if (shouldLog) {
53
+ const message = args.map((arg) => String(arg)).join(" ");
54
+ console.log(chalk.yellow(message));
55
+ }
56
+ },
57
+ warn: (...args) => {
58
+ if (shouldLog) {
59
+ const message = args.map((arg) => String(arg)).join(" ");
60
+ console.log(chalk.yellow(message));
61
+ }
62
+ },
63
+ error: (...args) => {
64
+ if (!json) {
65
+ const message = args.map((arg) => String(arg)).join(" ");
66
+ console.error(chalk.red(message));
67
+ }
68
+ },
69
+ debug: (...args) => {
70
+ if (shouldDebug) {
71
+ const message = args.map((arg) => String(arg)).join(" ");
72
+ console.log(chalk.gray(message));
73
+ }
74
+ },
75
+ gray: (...args) => {
76
+ if (shouldLog) {
77
+ const message = args.map((arg) => String(arg)).join(" ");
78
+ console.log(chalk.gray(message));
79
+ }
80
+ }
81
+ };
82
+ }
83
+ function createCommandLogger(options) {
84
+ return createLogger({
85
+ verbose: options.verbose,
86
+ silent: options.silent ?? false,
87
+ json: options.json
88
+ });
89
+ }
90
+
91
+ // src/core/timer.ts
92
+ function createTimer() {
93
+ let startTime = 0;
94
+ let endTime = 0;
95
+ return {
96
+ start() {
97
+ startTime = Date.now();
98
+ endTime = 0;
99
+ },
100
+ end() {
101
+ endTime = Date.now();
102
+ return endTime - startTime;
103
+ },
104
+ getElapsed() {
105
+ const currentTime = endTime || Date.now();
106
+ return currentTime - startTime;
107
+ },
108
+ format() {
109
+ const elapsed = this.getElapsed();
110
+ return (elapsed / 1e3).toFixed(2) + "s";
111
+ }
112
+ };
113
+ }
114
+
115
+ // src/core/output.ts
116
+ function createJsonOutput(success, data, error, duration) {
117
+ return {
118
+ success,
119
+ ...data && { data },
120
+ ...error && { error },
121
+ ...duration && { duration }
122
+ };
123
+ }
124
+ function createSuccessOutput(data, duration) {
125
+ return createJsonOutput(true, data, void 0, duration);
126
+ }
127
+ function createErrorOutput(error, duration) {
128
+ return createJsonOutput(false, void 0, error, duration);
129
+ }
130
+ function formatBytes(bytes) {
131
+ return (bytes / 1024).toFixed(2);
132
+ }
133
+
134
+ // src/core/docker.ts
135
+ import { spawn } from "child_process";
136
+ import path2 from "path";
137
+ import { VERSION as DOCKER_VERSION } from "@walkeros/docker";
138
+
139
+ // src/config/utils.ts
140
+ import fs from "fs-extra";
141
+ import path from "path";
142
+ import os from "os";
143
+ function isUrl(str) {
144
+ try {
145
+ const url = new URL(str);
146
+ return url.protocol === "http:" || url.protocol === "https:";
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ async function downloadFromUrl(url) {
152
+ if (!isUrl(url)) {
153
+ throw new Error(`Invalid URL: ${url}`);
154
+ }
155
+ try {
156
+ const response = await fetch(url);
157
+ if (!response.ok) {
158
+ throw new Error(
159
+ `Failed to download ${url}: ${response.status} ${response.statusText}`
160
+ );
161
+ }
162
+ const content = await response.text();
163
+ const urlObj = new URL(url);
164
+ const urlFilename = path.basename(urlObj.pathname);
165
+ const extension = path.extname(urlFilename) || ".json";
166
+ const randomId = Math.random().toString(36).substring(2, 11);
167
+ const filename = `walkeros-download-${Date.now()}-${randomId}${extension}`;
168
+ const tempPath = path.join(os.tmpdir(), filename);
169
+ await fs.writeFile(tempPath, content, "utf-8");
170
+ return tempPath;
171
+ } catch (error) {
172
+ if (error instanceof Error) {
173
+ throw new Error(`Failed to download from URL: ${error.message}`);
174
+ }
175
+ throw error;
176
+ }
177
+ }
178
+ async function loadJsonConfig(configPath) {
179
+ let absolutePath;
180
+ let isTemporary = false;
181
+ if (isUrl(configPath)) {
182
+ absolutePath = await downloadFromUrl(configPath);
183
+ isTemporary = true;
184
+ } else {
185
+ absolutePath = path.resolve(configPath);
186
+ if (!await fs.pathExists(absolutePath)) {
187
+ throw new Error(`Configuration file not found: ${absolutePath}`);
188
+ }
189
+ }
190
+ try {
191
+ const rawConfig = await fs.readJson(absolutePath);
192
+ return rawConfig;
193
+ } catch (error) {
194
+ throw new Error(
195
+ `Invalid JSON in config file: ${configPath}. ${error instanceof Error ? error.message : error}`
196
+ );
197
+ } finally {
198
+ if (isTemporary) {
199
+ try {
200
+ await fs.remove(absolutePath);
201
+ } catch {
202
+ }
203
+ }
204
+ }
205
+ }
206
+ function getTempDir(tempDir = ".tmp") {
207
+ const randomId = Math.random().toString(36).substring(2, 11);
208
+ const basePath = path.isAbsolute(tempDir) ? tempDir : path.join(process.cwd(), tempDir);
209
+ return path.join(basePath, `cli-${Date.now()}-${randomId}`);
210
+ }
211
+ async function loadJsonFromSource(source, options) {
212
+ const paramName = options?.name || "input";
213
+ if (!source || source.trim() === "") {
214
+ if (options?.required) {
215
+ throw new Error(`${paramName} is required`);
216
+ }
217
+ if (options?.fallback !== void 0) {
218
+ return options.fallback;
219
+ }
220
+ return {};
221
+ }
222
+ const trimmedSource = source.trim();
223
+ if (isUrl(trimmedSource)) {
224
+ try {
225
+ const tempPath = await downloadFromUrl(trimmedSource);
226
+ try {
227
+ const data = await fs.readJson(tempPath);
228
+ return data;
229
+ } finally {
230
+ try {
231
+ await fs.remove(tempPath);
232
+ } catch {
233
+ }
234
+ }
235
+ } catch (error) {
236
+ throw new Error(
237
+ `Failed to load ${paramName} from URL ${trimmedSource}: ${getErrorMessage(error)}`
238
+ );
239
+ }
240
+ }
241
+ const resolvedPath = path.resolve(trimmedSource);
242
+ if (await fs.pathExists(resolvedPath)) {
243
+ try {
244
+ const data = await fs.readJson(resolvedPath);
245
+ return data;
246
+ } catch (error) {
247
+ throw new Error(
248
+ `Failed to parse ${paramName} from file ${trimmedSource}: ${getErrorMessage(error)}`
249
+ );
250
+ }
251
+ }
252
+ try {
253
+ const parsed = JSON.parse(trimmedSource);
254
+ return parsed;
255
+ } catch (jsonError) {
256
+ if (!trimmedSource.startsWith("{") && !trimmedSource.startsWith("[")) {
257
+ return { name: trimmedSource };
258
+ }
259
+ throw new Error(
260
+ `Failed to parse ${paramName}. Input appears to be JSON but contains errors: ${jsonError instanceof Error ? jsonError.message : String(jsonError)}`
261
+ );
262
+ }
263
+ }
264
+
265
+ // src/core/docker.ts
266
+ var CLI_VERSION = true ? "0.4.2" : "0.0.0";
267
+ var CLI_DOCKER_IMAGE = process.env.WALKEROS_CLI_DOCKER_IMAGE || `walkeros/cli:${CLI_VERSION}`;
268
+ var RUNTIME_DOCKER_IMAGE = process.env.WALKEROS_RUNTIME_DOCKER_IMAGE || `walkeros/docker:${DOCKER_VERSION}`;
269
+ function buildCommonDockerArgs(options) {
270
+ const args = [options.config];
271
+ if (options.json) args.push("--json");
272
+ if (options.verbose) args.push("--verbose");
273
+ if (options.silent) args.push("--silent");
274
+ return args;
275
+ }
276
+ function buildDockerCommand(command, args, options = {}, configFile) {
277
+ const cwd = process.cwd();
278
+ const cmd = ["docker", "run", "--rm"];
279
+ if (configFile && !isUrl(configFile)) {
280
+ const configPath = path2.resolve(cwd, configFile);
281
+ cmd.push("-v", `${configPath}:/config/flow.json:ro`);
282
+ args = args.map((arg) => arg === configFile ? "/config/flow.json" : arg);
283
+ }
284
+ cmd.push("-v", `${cwd}:/workspace`);
285
+ cmd.push("-w", "/workspace");
286
+ if (process.platform !== "win32") {
287
+ try {
288
+ const uid = process.getuid?.();
289
+ const gid = process.getgid?.();
290
+ if (uid !== void 0 && gid !== void 0) {
291
+ cmd.push("--user", `${uid}:${gid}`);
292
+ }
293
+ } catch {
294
+ }
295
+ }
296
+ if (options.verbose) {
297
+ cmd.push("-e", "VERBOSE=true");
298
+ }
299
+ if (options.silent) {
300
+ cmd.push("-e", "SILENT=true");
301
+ }
302
+ cmd.push(CLI_DOCKER_IMAGE);
303
+ cmd.push(command, ...args);
304
+ return cmd;
305
+ }
306
+ async function executeInDocker(command, args, options = {}, configFile) {
307
+ const containerArgs = [...args, "--local"];
308
+ const dockerCmd = buildDockerCommand(
309
+ command,
310
+ containerArgs,
311
+ options,
312
+ configFile
313
+ );
314
+ return new Promise((resolve, reject) => {
315
+ const proc = spawn(dockerCmd[0], dockerCmd.slice(1), {
316
+ stdio: options.silent ? "ignore" : "inherit",
317
+ shell: false
51
318
  });
52
- });
53
- // Simulate command
54
- program
55
- .command('simulate [file]')
56
- .description('Simulate event processing and capture API calls')
57
- .option('-e, --event <source>', 'Event to simulate (JSON string, file path, or URL)')
58
- .option('--json', 'Output results as JSON')
59
- .option('-v, --verbose', 'Verbose output')
60
- .option('--local', 'execute in local Node.js instead of Docker')
61
- .option('--dry-run', 'preview command without executing')
62
- .option('--silent', 'suppress output')
63
- .action(async (file, options) => {
64
- await simulateCommand({
65
- config: file || 'bundle.config.json',
66
- event: options.event,
67
- json: options.json,
68
- verbose: options.verbose,
69
- local: options.local,
70
- dryRun: options.dryRun,
71
- silent: options.silent,
319
+ proc.on("error", (error) => {
320
+ reject(new Error(`Docker execution failed: ${error.message}`));
321
+ });
322
+ proc.on("exit", (code) => {
323
+ if (code === 0) {
324
+ resolve();
325
+ } else {
326
+ reject(new Error(`Docker command exited with code ${code}`));
327
+ }
328
+ });
329
+ });
330
+ }
331
+ async function isDockerAvailable() {
332
+ return new Promise((resolve) => {
333
+ const proc = spawn("docker", ["--version"], {
334
+ stdio: "ignore"
335
+ });
336
+ proc.on("error", () => resolve(false));
337
+ proc.on("exit", (code) => resolve(code === 0));
338
+ });
339
+ }
340
+ function buildDockerRunCommand(mode, flowPath, options = {}) {
341
+ const cwd = process.cwd();
342
+ const cmd = ["docker", "run", "--rm"];
343
+ cmd.push("-e", `MODE=${mode}`);
344
+ if (mode === "collect" && flowPath) {
345
+ const absoluteFlowPath = path2.resolve(cwd, flowPath);
346
+ const flowDir = path2.dirname(absoluteFlowPath);
347
+ const flowFile = path2.basename(absoluteFlowPath);
348
+ cmd.push("-v", `${flowDir}:/app/dist:ro`);
349
+ cmd.push("-e", `FLOW=/app/dist/${flowFile}`);
350
+ }
351
+ if (mode === "serve" && flowPath) {
352
+ const absoluteFilePath = path2.resolve(cwd, flowPath);
353
+ cmd.push("-v", `${absoluteFilePath}:/app/bundle.mjs:ro`);
354
+ cmd.push("-e", "FILE_PATH=/app/bundle.mjs");
355
+ }
356
+ const port = options.port !== void 0 ? options.port : 8080;
357
+ cmd.push("-p", `${port}:${port}`);
358
+ cmd.push("-e", `PORT=${port}`);
359
+ if (options.host) {
360
+ cmd.push("-e", `HOST=${options.host}`);
361
+ }
362
+ if (options.serveName) {
363
+ cmd.push("-e", `SERVE_NAME=${options.serveName}`);
364
+ }
365
+ if (options.servePath) {
366
+ cmd.push("-e", `SERVE_PATH=${options.servePath}`);
367
+ }
368
+ if (process.platform !== "win32") {
369
+ try {
370
+ const uid = process.getuid?.();
371
+ const gid = process.getgid?.();
372
+ if (uid !== void 0 && gid !== void 0) {
373
+ cmd.push("--user", `${uid}:${gid}`);
374
+ }
375
+ } catch {
376
+ }
377
+ }
378
+ cmd.push(RUNTIME_DOCKER_IMAGE);
379
+ return cmd;
380
+ }
381
+ async function executeRunInDocker(mode, flowPath, options = {}) {
382
+ const dockerCmd = buildDockerRunCommand(mode, flowPath, options);
383
+ return new Promise((resolve, reject) => {
384
+ const proc = spawn(dockerCmd[0], dockerCmd.slice(1), {
385
+ stdio: options.silent ? "ignore" : "inherit",
386
+ shell: false
387
+ });
388
+ proc.on("error", (error) => {
389
+ reject(new Error(`Docker execution failed: ${error.message}`));
390
+ });
391
+ proc.on("exit", (code) => {
392
+ if (code === 0) {
393
+ resolve();
394
+ } else {
395
+ reject(new Error(`Docker command exited with code ${code}`));
396
+ }
397
+ });
398
+ });
399
+ }
400
+
401
+ // src/core/execution.ts
402
+ function getExecutionMode(options) {
403
+ if (options.local || process.env.WALKEROS_CONTAINER === "true") {
404
+ return "local";
405
+ }
406
+ return "docker";
407
+ }
408
+ async function executeCommand(localHandler, dockerCommand, dockerArgs, options, logger, configFile) {
409
+ const mode = getExecutionMode(options);
410
+ if (options.dryRun) {
411
+ if (mode === "docker") {
412
+ const cmd = `docker run walkeros/cli:latest ${dockerCommand} ${dockerArgs.join(" ")}`;
413
+ logger?.info(`[DRY-RUN] Would execute: ${cmd}`);
414
+ } else {
415
+ logger?.info(
416
+ `[DRY-RUN] Would execute locally: ${dockerCommand} ${dockerArgs.join(" ")}`
417
+ );
418
+ }
419
+ return;
420
+ }
421
+ if (mode === "local") {
422
+ if (logger && !options.silent) {
423
+ logger.info("\u{1F5A5}\uFE0F Executing locally...");
424
+ }
425
+ await localHandler();
426
+ } else {
427
+ const dockerAvailable = await isDockerAvailable();
428
+ if (!dockerAvailable) {
429
+ throw new Error(
430
+ "Docker is not available. Please install Docker or use --local flag to execute locally."
431
+ );
432
+ }
433
+ if (logger && !options.silent) {
434
+ logger.info("\u{1F433} Executing in Docker container...");
435
+ }
436
+ await executeInDocker(dockerCommand, dockerArgs, options, configFile);
437
+ }
438
+ }
439
+
440
+ // src/core/temp-manager.ts
441
+ import { getHashServer } from "@walkeros/server-core";
442
+ import fs2 from "fs-extra";
443
+
444
+ // src/core/asset-resolver.ts
445
+ import { fileURLToPath } from "url";
446
+ import { existsSync } from "fs";
447
+ import path3 from "path";
448
+ var cachedAssetDir;
449
+ function getAssetDir() {
450
+ if (cachedAssetDir) return cachedAssetDir;
451
+ const currentFile = fileURLToPath(import.meta.url);
452
+ let dir = path3.dirname(currentFile);
453
+ while (dir !== path3.dirname(dir)) {
454
+ if (existsSync(path3.join(dir, "templates"))) {
455
+ cachedAssetDir = dir;
456
+ return dir;
457
+ }
458
+ dir = path3.dirname(dir);
459
+ }
460
+ cachedAssetDir = path3.dirname(currentFile);
461
+ return cachedAssetDir;
462
+ }
463
+ function resolveAsset(assetPath, assetType, baseDir) {
464
+ if (!assetPath.includes("/") && !assetPath.includes("\\")) {
465
+ const assetDir = getAssetDir();
466
+ if (assetType === "template") {
467
+ return path3.join(assetDir, "templates", assetPath);
468
+ }
469
+ return path3.join(assetDir, "examples", assetPath);
470
+ }
471
+ if (path3.isAbsolute(assetPath)) {
472
+ return assetPath;
473
+ }
474
+ return path3.resolve(baseDir || process.cwd(), assetPath);
475
+ }
476
+
477
+ // src/core/utils.ts
478
+ function getErrorMessage(error) {
479
+ return error instanceof Error ? error.message : String(error);
480
+ }
481
+
482
+ // src/core/local-packages.ts
483
+ import path4 from "path";
484
+ import fs3 from "fs-extra";
485
+ async function resolveLocalPackage(packageName, localPath, configDir, logger) {
486
+ const absolutePath = path4.isAbsolute(localPath) ? localPath : path4.resolve(configDir, localPath);
487
+ if (!await fs3.pathExists(absolutePath)) {
488
+ throw new Error(
489
+ `Local package path not found: ${localPath} (resolved to ${absolutePath})`
490
+ );
491
+ }
492
+ const pkgJsonPath = path4.join(absolutePath, "package.json");
493
+ if (!await fs3.pathExists(pkgJsonPath)) {
494
+ throw new Error(
495
+ `No package.json found at ${absolutePath}. Is this a valid package directory?`
496
+ );
497
+ }
498
+ const distPath = path4.join(absolutePath, "dist");
499
+ const hasDistFolder = await fs3.pathExists(distPath);
500
+ if (!hasDistFolder) {
501
+ logger.warn(
502
+ `\u26A0\uFE0F ${packageName}: No dist/ folder found. Using package root.`
503
+ );
504
+ }
505
+ return {
506
+ name: packageName,
507
+ absolutePath,
508
+ distPath: hasDistFolder ? distPath : absolutePath,
509
+ hasDistFolder
510
+ };
511
+ }
512
+ async function copyLocalPackage(localPkg, targetDir, logger) {
513
+ const packageDir = path4.join(targetDir, "node_modules", localPkg.name);
514
+ await fs3.ensureDir(path4.dirname(packageDir));
515
+ await fs3.copy(
516
+ path4.join(localPkg.absolutePath, "package.json"),
517
+ path4.join(packageDir, "package.json")
518
+ );
519
+ if (localPkg.hasDistFolder) {
520
+ await fs3.copy(localPkg.distPath, path4.join(packageDir, "dist"));
521
+ } else {
522
+ const entries = await fs3.readdir(localPkg.absolutePath);
523
+ for (const entry of entries) {
524
+ if (!["node_modules", ".turbo", ".git"].includes(entry)) {
525
+ await fs3.copy(
526
+ path4.join(localPkg.absolutePath, entry),
527
+ path4.join(packageDir, entry)
528
+ );
529
+ }
530
+ }
531
+ }
532
+ logger.info(`\u{1F4E6} Using local: ${localPkg.name} from ${localPkg.absolutePath}`);
533
+ return packageDir;
534
+ }
535
+
536
+ // src/config/validators.ts
537
+ import { schemas } from "@walkeros/core/dev";
538
+ var { safeParseSetup } = schemas;
539
+ function isObject(value) {
540
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
541
+ }
542
+ function validateFlowSetup(data) {
543
+ const result = safeParseSetup(data);
544
+ if (!result.success) {
545
+ const errors = result.error.issues.map((issue) => {
546
+ const path15 = issue.path.length > 0 ? issue.path.map(String).join(".") : "root";
547
+ return ` - ${path15}: ${issue.message}`;
548
+ }).join("\n");
549
+ throw new Error(`Invalid configuration:
550
+ ${errors}`);
551
+ }
552
+ return result.data;
553
+ }
554
+ function getAvailableFlows(setup) {
555
+ return Object.keys(setup.flows);
556
+ }
557
+
558
+ // src/config/build-defaults.ts
559
+ var WEB_BUILD_DEFAULTS = {
560
+ format: "iife",
561
+ platform: "browser",
562
+ target: "es2020",
563
+ template: "web.hbs",
564
+ minify: true,
565
+ sourcemap: false,
566
+ cache: true,
567
+ tempDir: ".tmp",
568
+ windowCollector: "collector",
569
+ windowElb: "elb"
570
+ };
571
+ var SERVER_BUILD_DEFAULTS = {
572
+ format: "esm",
573
+ platform: "node",
574
+ target: "node20",
575
+ template: "server.hbs",
576
+ minify: true,
577
+ sourcemap: false,
578
+ cache: true,
579
+ tempDir: ".tmp"
580
+ };
581
+ var DEFAULT_OUTPUT_PATHS = {
582
+ web: "./dist/walker.js",
583
+ server: "./dist/bundle.mjs"
584
+ };
585
+ function getBuildDefaults(platform) {
586
+ return platform === "web" ? WEB_BUILD_DEFAULTS : SERVER_BUILD_DEFAULTS;
587
+ }
588
+ function getDefaultOutput(platform) {
589
+ return DEFAULT_OUTPUT_PATHS[platform];
590
+ }
591
+
592
+ // src/config/loader.ts
593
+ import path5 from "path";
594
+ import fs4 from "fs-extra";
595
+ import { getFlowConfig, getPlatform } from "@walkeros/core";
596
+ var DEFAULT_INCLUDE_FOLDER = "./shared";
597
+ function loadBundleConfig(rawConfig, options) {
598
+ const setup = validateFlowSetup(rawConfig);
599
+ const availableFlows = getAvailableFlows(setup);
600
+ const flowName = resolveFlow(setup, options.flowName, availableFlows);
601
+ const flowConfig = getFlowConfig(setup, flowName);
602
+ const platform = getPlatform(flowConfig);
603
+ if (!platform) {
604
+ throw new Error(
605
+ `Invalid configuration: flow "${flowName}" must have a "web" or "server" key.`
606
+ );
607
+ }
608
+ const buildDefaults = getBuildDefaults(platform);
609
+ const packages = flowConfig.packages || {};
610
+ let output = getDefaultOutput(platform);
611
+ if (options.buildOverrides?.output) {
612
+ output = options.buildOverrides.output;
613
+ }
614
+ const configDir = path5.dirname(options.configPath);
615
+ if (!path5.isAbsolute(output)) {
616
+ output = path5.resolve(configDir, output);
617
+ }
618
+ let includes = setup.include;
619
+ if (!includes) {
620
+ const defaultIncludePath = path5.resolve(configDir, DEFAULT_INCLUDE_FOLDER);
621
+ if (fs4.pathExistsSync(defaultIncludePath)) {
622
+ includes = [DEFAULT_INCLUDE_FOLDER];
623
+ }
624
+ }
625
+ const buildOptions = {
626
+ ...buildDefaults,
627
+ packages,
628
+ output,
629
+ include: includes,
630
+ configDir,
631
+ ...options.buildOverrides
632
+ };
633
+ const isMultiFlow = availableFlows.length > 1;
634
+ if (isMultiFlow && options.logger) {
635
+ options.logger.info(
636
+ `\u{1F4E6} Using flow: ${flowName} (${availableFlows.length} total)`
637
+ );
638
+ }
639
+ return {
640
+ flowConfig,
641
+ buildOptions,
642
+ flowName,
643
+ isMultiFlow,
644
+ availableFlows
645
+ };
646
+ }
647
+ function resolveFlow(setup, requestedFlow, available) {
648
+ if (available.length === 1) {
649
+ return available[0];
650
+ }
651
+ if (!requestedFlow) {
652
+ throw new Error(
653
+ `Multiple flows found. Please specify a flow using --flow flag.
654
+ Available flows: ${available.join(", ")}`
655
+ );
656
+ }
657
+ if (!available.includes(requestedFlow)) {
658
+ throw new Error(
659
+ `Flow "${requestedFlow}" not found in configuration.
660
+ Available flows: ${available.join(", ")}`
661
+ );
662
+ }
663
+ return requestedFlow;
664
+ }
665
+ function loadAllFlows(rawConfig, options) {
666
+ const setup = validateFlowSetup(rawConfig);
667
+ const flows = getAvailableFlows(setup);
668
+ if (options.logger) {
669
+ options.logger.info(
670
+ `\u{1F4E6} Loading all ${flows.length} flows: ${flows.join(", ")}`
671
+ );
672
+ }
673
+ return flows.map(
674
+ (name) => loadBundleConfig(rawConfig, {
675
+ ...options,
676
+ flowName: name
677
+ })
678
+ );
679
+ }
680
+
681
+ // src/commands/bundle/bundler.ts
682
+ import esbuild from "esbuild";
683
+ import path8 from "path";
684
+ import fs8 from "fs-extra";
685
+
686
+ // src/commands/bundle/package-manager.ts
687
+ import pacote from "pacote";
688
+ import path6 from "path";
689
+ import fs5 from "fs-extra";
690
+
691
+ // src/core/cache-utils.ts
692
+ import { getHashServer as getHashServer2 } from "@walkeros/server-core";
693
+ var HASH_LENGTH = 12;
694
+ function isMutableVersion(version) {
695
+ return version === "latest" || version.includes("^") || version.includes("~") || version.includes("*") || version.includes("x");
696
+ }
697
+ function getTodayDate() {
698
+ return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
699
+ }
700
+ async function getPackageCacheKey(packageName, version, date) {
701
+ const safeName = packageName.replace(/\//g, "-").replace(/@/g, "");
702
+ if (isMutableVersion(version)) {
703
+ const dateStr = date ?? getTodayDate();
704
+ const input2 = `${safeName}@${version}:${dateStr}`;
705
+ return getHashServer2(input2, HASH_LENGTH);
706
+ }
707
+ const input = `${safeName}@${version}`;
708
+ return getHashServer2(input, HASH_LENGTH);
709
+ }
710
+ function normalizeJson(content) {
711
+ const parsed = JSON.parse(content);
712
+ return JSON.stringify(parsed);
713
+ }
714
+ async function getFlowConfigCacheKey(content, date) {
715
+ const dateStr = date ?? getTodayDate();
716
+ const normalized = normalizeJson(content);
717
+ const input = `${normalized}:${dateStr}`;
718
+ return getHashServer2(input, HASH_LENGTH);
719
+ }
720
+
721
+ // src/commands/bundle/package-manager.ts
722
+ function getPackageDirectory(baseDir, packageName, version) {
723
+ return path6.join(baseDir, "node_modules", packageName);
724
+ }
725
+ async function getCachedPackagePath(pkg, tempDir) {
726
+ const cacheDir = path6.join(".tmp", "cache", "packages");
727
+ const cacheKey = await getPackageCacheKey(pkg.name, pkg.version);
728
+ return path6.join(cacheDir, cacheKey);
729
+ }
730
+ async function isPackageCached(pkg, tempDir) {
731
+ const cachedPath = await getCachedPackagePath(pkg, tempDir);
732
+ return fs5.pathExists(cachedPath);
733
+ }
734
+ function validateNoDuplicatePackages(packages) {
735
+ const packageMap = /* @__PURE__ */ new Map();
736
+ for (const pkg of packages) {
737
+ if (!packageMap.has(pkg.name)) {
738
+ packageMap.set(pkg.name, []);
739
+ }
740
+ packageMap.get(pkg.name).push(pkg.version);
741
+ }
742
+ const conflicts = [];
743
+ for (const [name, versions] of packageMap.entries()) {
744
+ const uniqueVersions = [...new Set(versions)];
745
+ if (uniqueVersions.length > 1) {
746
+ conflicts.push(`${name}: [${uniqueVersions.join(", ")}]`);
747
+ }
748
+ }
749
+ if (conflicts.length > 0) {
750
+ throw new Error(
751
+ `Version conflicts detected:
752
+ ${conflicts.map((c) => ` - ${c}`).join("\n")}
753
+
754
+ Each package must use the same version across all declarations. Please update your configuration to use consistent versions.`
755
+ );
756
+ }
757
+ }
758
+ async function resolveDependencies(pkg, packageDir, logger, visited = /* @__PURE__ */ new Set()) {
759
+ const dependencies = [];
760
+ const pkgKey = `${pkg.name}@${pkg.version}`;
761
+ if (visited.has(pkgKey)) {
762
+ return dependencies;
763
+ }
764
+ visited.add(pkgKey);
765
+ try {
766
+ const packageJsonPath = path6.join(packageDir, "package.json");
767
+ if (await fs5.pathExists(packageJsonPath)) {
768
+ const packageJson2 = await fs5.readJson(packageJsonPath);
769
+ const deps = {
770
+ ...packageJson2.dependencies,
771
+ ...packageJson2.peerDependencies
772
+ };
773
+ for (const [name, versionSpec] of Object.entries(deps)) {
774
+ if (typeof versionSpec === "string") {
775
+ dependencies.push({ name, version: versionSpec });
776
+ }
777
+ }
778
+ }
779
+ } catch (error) {
780
+ logger.debug(`Failed to read dependencies for ${pkgKey}: ${error}`);
781
+ }
782
+ return dependencies;
783
+ }
784
+ async function downloadPackages(packages, targetDir, logger, useCache = true, configDir) {
785
+ const packagePaths = /* @__PURE__ */ new Map();
786
+ const downloadQueue = [...packages];
787
+ const processed = /* @__PURE__ */ new Set();
788
+ const localPackageMap = /* @__PURE__ */ new Map();
789
+ for (const pkg of packages) {
790
+ if (pkg.path) {
791
+ localPackageMap.set(pkg.name, pkg.path);
792
+ }
793
+ }
794
+ validateNoDuplicatePackages(packages);
795
+ await fs5.ensureDir(targetDir);
796
+ while (downloadQueue.length > 0) {
797
+ const pkg = downloadQueue.shift();
798
+ const pkgKey = `${pkg.name}@${pkg.version}`;
799
+ if (processed.has(pkgKey)) {
800
+ continue;
801
+ }
802
+ processed.add(pkgKey);
803
+ if (!pkg.path && localPackageMap.has(pkg.name)) {
804
+ pkg.path = localPackageMap.get(pkg.name);
805
+ }
806
+ if (pkg.path) {
807
+ const localPkg = await resolveLocalPackage(
808
+ pkg.name,
809
+ pkg.path,
810
+ configDir || process.cwd(),
811
+ logger
812
+ );
813
+ const installedPath = await copyLocalPackage(localPkg, targetDir, logger);
814
+ packagePaths.set(pkg.name, installedPath);
815
+ const deps = await resolveDependencies(pkg, installedPath, logger);
816
+ for (const dep of deps) {
817
+ const depKey = `${dep.name}@${dep.version}`;
818
+ if (!processed.has(depKey)) {
819
+ downloadQueue.push(dep);
820
+ }
821
+ }
822
+ continue;
823
+ }
824
+ const packageSpec = `${pkg.name}@${pkg.version}`;
825
+ const packageDir = getPackageDirectory(targetDir, pkg.name, pkg.version);
826
+ const cachedPath = await getCachedPackagePath(pkg, targetDir);
827
+ if (useCache && await isPackageCached(pkg, targetDir)) {
828
+ logger.debug(`Using cached ${packageSpec}...`);
829
+ try {
830
+ await fs5.ensureDir(path6.dirname(packageDir));
831
+ await fs5.copy(cachedPath, packageDir);
832
+ packagePaths.set(pkg.name, packageDir);
833
+ const deps = await resolveDependencies(pkg, packageDir, logger);
834
+ for (const dep of deps) {
835
+ const depKey = `${dep.name}@${dep.version}`;
836
+ if (!processed.has(depKey)) {
837
+ downloadQueue.push(dep);
838
+ }
839
+ }
840
+ continue;
841
+ } catch (error) {
842
+ logger.debug(
843
+ `Failed to use cache for ${packageSpec}, downloading fresh: ${error}`
844
+ );
845
+ }
846
+ }
847
+ logger.debug(`Downloading ${packageSpec}...`);
848
+ try {
849
+ await fs5.ensureDir(path6.dirname(packageDir));
850
+ const cacheDir = process.env.NPM_CACHE_DIR || path6.join(process.cwd(), ".npm-cache");
851
+ await pacote.extract(packageSpec, packageDir, {
852
+ // Force npm registry download, prevent workspace resolution
853
+ registry: "https://registry.npmjs.org",
854
+ // Force online fetching from registry (don't use cached workspace packages)
855
+ preferOnline: true,
856
+ // Cache for performance
857
+ cache: cacheDir,
858
+ // Don't resolve relative to workspace context
859
+ where: void 0
860
+ });
861
+ if (useCache) {
862
+ try {
863
+ await fs5.ensureDir(path6.dirname(cachedPath));
864
+ await fs5.copy(packageDir, cachedPath);
865
+ logger.debug(`Cached ${packageSpec} for future use`);
866
+ } catch (cacheError) {
867
+ logger.debug(`Failed to cache ${packageSpec}: ${cacheError}`);
868
+ }
869
+ }
870
+ packagePaths.set(pkg.name, packageDir);
871
+ const deps = await resolveDependencies(pkg, packageDir, logger);
872
+ for (const dep of deps) {
873
+ const depKey = `${dep.name}@${dep.version}`;
874
+ if (!processed.has(depKey)) {
875
+ downloadQueue.push(dep);
876
+ }
877
+ }
878
+ } catch (error) {
879
+ throw new Error(`Failed to download ${packageSpec}: ${error}`);
880
+ }
881
+ }
882
+ return packagePaths;
883
+ }
884
+
885
+ // src/commands/bundle/template-engine.ts
886
+ import fs6 from "fs-extra";
887
+ import Handlebars from "handlebars";
888
+
889
+ // src/commands/bundle/serializer.ts
890
+ function serializeToJS(value, options = {}) {
891
+ const { indent = 2, singleQuotes = false } = options;
892
+ const quote = singleQuotes ? "'" : '"';
893
+ function serialize(val, currentIndent = 0) {
894
+ if (val === null) return "null";
895
+ if (val === void 0) return "undefined";
896
+ if (typeof val === "boolean" || typeof val === "number") {
897
+ return String(val);
898
+ }
899
+ if (typeof val === "string") {
900
+ if (val.includes("=>")) {
901
+ const arrowPatterns = [
902
+ /^\s*\([^)]*\)\s*=>/,
903
+ // (param) => or () =>
904
+ /^\s*\w+\s*=>/,
905
+ // param =>
906
+ /^\s*\([^)]*\)\s*=>\s*\{/,
907
+ // (param) => {
908
+ /^\s*\w+\s*=>\s*\{/
909
+ // param => {
910
+ ];
911
+ if (arrowPatterns.some((pattern) => pattern.test(val))) {
912
+ return val;
913
+ }
914
+ }
915
+ return quote + val.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, '\\"') + quote;
916
+ }
917
+ if (Array.isArray(val)) {
918
+ if (val.length === 0) return "[]";
919
+ const nextIndent = currentIndent + indent;
920
+ const spacing = " ".repeat(nextIndent);
921
+ const items = val.map((item) => spacing + serialize(item, nextIndent)).join(",\n");
922
+ return `[
923
+ ${items}
924
+ ${" ".repeat(currentIndent)}]`;
925
+ }
926
+ if (isObject(val)) {
927
+ const entries = Object.entries(val);
928
+ if (entries.length === 0) return "{}";
929
+ const nextIndent = currentIndent + indent;
930
+ const spacing = " ".repeat(nextIndent);
931
+ const props = entries.map(([key, value2]) => {
932
+ const needsQuotes = /[^a-zA-Z0-9_$]/.test(key) || /^[0-9]/.test(key);
933
+ const keyStr = needsQuotes ? quote + key + quote : key;
934
+ return spacing + keyStr + ": " + serialize(value2, nextIndent);
935
+ }).join(",\n");
936
+ return `{
937
+ ${props}
938
+ ${" ".repeat(currentIndent)}}`;
939
+ }
940
+ return String(val);
941
+ }
942
+ return serialize(value);
943
+ }
944
+ function serializeConfig(config) {
945
+ if (!config || Object.keys(config).length === 0) {
946
+ return "{}";
947
+ }
948
+ return serializeToJS(config, { indent: 2, singleQuotes: true });
949
+ }
950
+ function processTemplateVariables(variables) {
951
+ const processed = { ...variables };
952
+ if (isObject(processed.sources)) {
953
+ const sourcesObj = processed.sources;
954
+ const processedSources = {};
955
+ for (const [name, source] of Object.entries(sourcesObj)) {
956
+ const typedSource = source;
957
+ const { env: _, ...sourceWithoutEnv } = typedSource;
958
+ processedSources[name] = {
959
+ ...sourceWithoutEnv,
960
+ config: isObject(typedSource.config) ? serializeConfig(typedSource.config) : typedSource.config,
961
+ // Pass through string configs unchanged
962
+ ...typedSource.env !== void 0 && { env: typedSource.env }
963
+ };
964
+ }
965
+ processed.sources = processedSources;
966
+ }
967
+ if (isObject(processed.destinations)) {
968
+ const destinationsObj = processed.destinations;
969
+ const processedDestinations = {};
970
+ for (const [name, dest] of Object.entries(destinationsObj)) {
971
+ const typedDest = dest;
972
+ const { env: _, ...destWithoutEnv } = typedDest;
973
+ processedDestinations[name] = {
974
+ ...destWithoutEnv,
975
+ config: isObject(typedDest.config) ? serializeConfig(typedDest.config) : typedDest.config,
976
+ ...typedDest.env !== void 0 && { env: typedDest.env }
977
+ };
978
+ }
979
+ processed.destinations = processedDestinations;
980
+ }
981
+ if (isObject(processed.collector)) {
982
+ processed.collector = serializeConfig(
983
+ processed.collector
984
+ );
985
+ }
986
+ return processed;
987
+ }
988
+
989
+ // src/commands/bundle/template-engine.ts
990
+ var TemplateEngine = class {
991
+ handlebars;
992
+ constructor() {
993
+ this.handlebars = Handlebars.create();
994
+ this.handlebars.registerHelper("eq", (a, b) => a === b);
995
+ }
996
+ /**
997
+ * Load template content from file path
998
+ *
999
+ * @param templatePath - Template path (bare name, relative, or absolute)
1000
+ */
1001
+ async loadTemplate(templatePath) {
1002
+ const resolvedPath = resolveAsset(templatePath, "template");
1003
+ if (!await fs6.pathExists(resolvedPath)) {
1004
+ throw new Error(`Template file not found: ${resolvedPath}`);
1005
+ }
1006
+ return await fs6.readFile(resolvedPath, "utf-8");
1007
+ }
1008
+ /**
1009
+ * Apply template with user code and variable substitution
1010
+ */
1011
+ applyTemplate(template, userCode, sources, destinations, collector, build) {
1012
+ const processedVariables = processTemplateVariables({
1013
+ sources,
1014
+ destinations,
1015
+ collector
1016
+ });
1017
+ const templateData = {
1018
+ CODE: userCode,
1019
+ build: build || {},
1020
+ ...processedVariables
1021
+ };
1022
+ const compiledTemplate = this.handlebars.compile(template);
1023
+ return compiledTemplate(templateData);
1024
+ }
1025
+ /**
1026
+ * Process template with user code
1027
+ */
1028
+ async process(templatePath, userCode, sources, destinations, collector, build) {
1029
+ const template = await this.loadTemplate(templatePath);
1030
+ return this.applyTemplate(
1031
+ template,
1032
+ userCode,
1033
+ sources,
1034
+ destinations,
1035
+ collector,
1036
+ build
1037
+ );
1038
+ }
1039
+ };
1040
+
1041
+ // src/core/build-cache.ts
1042
+ import fs7 from "fs-extra";
1043
+ import path7 from "path";
1044
+ var BUILD_CACHE_DIR = path7.join(".tmp", "cache", "builds");
1045
+ async function getBuildCachePath(configContent, cacheDir = BUILD_CACHE_DIR) {
1046
+ const cacheKey = await getFlowConfigCacheKey(configContent);
1047
+ return path7.join(cacheDir, `${cacheKey}.js`);
1048
+ }
1049
+ async function isBuildCached(configContent, cacheDir = BUILD_CACHE_DIR) {
1050
+ const cachePath = await getBuildCachePath(configContent, cacheDir);
1051
+ return fs7.pathExists(cachePath);
1052
+ }
1053
+ async function cacheBuild(configContent, buildOutput, cacheDir = BUILD_CACHE_DIR) {
1054
+ const cachePath = await getBuildCachePath(configContent, cacheDir);
1055
+ await fs7.ensureDir(path7.dirname(cachePath));
1056
+ await fs7.writeFile(cachePath, buildOutput, "utf-8");
1057
+ }
1058
+ async function getCachedBuild(configContent, cacheDir = BUILD_CACHE_DIR) {
1059
+ const cachePath = await getBuildCachePath(configContent, cacheDir);
1060
+ if (await fs7.pathExists(cachePath)) {
1061
+ return await fs7.readFile(cachePath, "utf-8");
1062
+ }
1063
+ return null;
1064
+ }
1065
+
1066
+ // src/commands/bundle/bundler.ts
1067
+ async function copyIncludes(includes, sourceDir, outputDir, logger) {
1068
+ for (const include of includes) {
1069
+ const sourcePath = path8.resolve(sourceDir, include);
1070
+ const folderName = path8.basename(include);
1071
+ const destPath = path8.join(outputDir, folderName);
1072
+ if (await fs8.pathExists(sourcePath)) {
1073
+ await fs8.copy(sourcePath, destPath);
1074
+ logger.debug(`Copied ${include} to output`);
1075
+ } else {
1076
+ logger.debug(`Include folder not found: ${include}`);
1077
+ }
1078
+ }
1079
+ }
1080
+ function generateCacheKeyContent(flowConfig, buildOptions) {
1081
+ const configForCache = {
1082
+ flow: flowConfig,
1083
+ build: {
1084
+ ...buildOptions,
1085
+ // Exclude non-deterministic fields from cache key
1086
+ tempDir: void 0,
1087
+ output: void 0
1088
+ }
1089
+ };
1090
+ return JSON.stringify(configForCache);
1091
+ }
1092
+ async function bundleCore(flowConfig, buildOptions, logger, showStats = false) {
1093
+ const bundleStartTime = Date.now();
1094
+ const TEMP_DIR = buildOptions.tempDir ? path8.isAbsolute(buildOptions.tempDir) ? buildOptions.tempDir : path8.resolve(buildOptions.tempDir) : getTempDir();
1095
+ if (buildOptions.cache !== false) {
1096
+ const configContent = generateCacheKeyContent(flowConfig, buildOptions);
1097
+ const cached = await isBuildCached(configContent);
1098
+ if (cached) {
1099
+ const cachedBuild = await getCachedBuild(configContent);
1100
+ if (cachedBuild) {
1101
+ logger.info("\u2728 Using cached build");
1102
+ const outputPath = path8.resolve(buildOptions.output);
1103
+ await fs8.ensureDir(path8.dirname(outputPath));
1104
+ await fs8.writeFile(outputPath, cachedBuild);
1105
+ logger.gray(`Output: ${outputPath}`);
1106
+ logger.success("\u2705 Build completed (from cache)");
1107
+ if (showStats) {
1108
+ const stats = await fs8.stat(outputPath);
1109
+ const packageStats = Object.entries(buildOptions.packages).map(
1110
+ ([name, pkg]) => ({
1111
+ name: `${name}@${pkg.version || "latest"}`,
1112
+ size: 0
1113
+ // Size estimation not available for cached builds
1114
+ })
1115
+ );
1116
+ return {
1117
+ totalSize: stats.size,
1118
+ packages: packageStats,
1119
+ buildTime: Date.now() - bundleStartTime,
1120
+ treeshakingEffective: true
1121
+ };
1122
+ }
1123
+ return;
1124
+ }
1125
+ }
1126
+ }
1127
+ try {
1128
+ if (!buildOptions.tempDir) {
1129
+ await fs8.emptyDir(TEMP_DIR);
1130
+ }
1131
+ logger.debug("Cleaned temporary directory");
1132
+ logger.info("\u{1F4E5} Downloading packages...");
1133
+ const packagesArray = Object.entries(buildOptions.packages).map(
1134
+ ([name, packageConfig]) => ({
1135
+ name,
1136
+ version: packageConfig.version || "latest",
1137
+ path: packageConfig.path
1138
+ // Pass local path if defined
1139
+ })
1140
+ );
1141
+ const packagePaths = await downloadPackages(
1142
+ packagesArray,
1143
+ TEMP_DIR,
1144
+ logger,
1145
+ buildOptions.cache,
1146
+ buildOptions.configDir
1147
+ // For resolving relative local paths
1148
+ );
1149
+ for (const [pkgName, pkgPath] of packagePaths.entries()) {
1150
+ if (pkgName.startsWith("@walkeros/")) {
1151
+ const pkgJsonPath = path8.join(pkgPath, "package.json");
1152
+ const pkgJson = await fs8.readJSON(pkgJsonPath);
1153
+ if (!pkgJson.exports && pkgJson.module) {
1154
+ pkgJson.exports = {
1155
+ ".": {
1156
+ import: pkgJson.module,
1157
+ require: pkgJson.main
1158
+ }
1159
+ };
1160
+ await fs8.writeJSON(pkgJsonPath, pkgJson, { spaces: 2 });
1161
+ }
1162
+ }
1163
+ }
1164
+ const packageJsonPath = path8.join(TEMP_DIR, "package.json");
1165
+ await fs8.writeFile(
1166
+ packageJsonPath,
1167
+ JSON.stringify({ type: "module" }, null, 2)
1168
+ );
1169
+ logger.info("\u{1F4DD} Creating entry point...");
1170
+ const entryContent = await createEntryPoint(
1171
+ flowConfig,
1172
+ buildOptions,
1173
+ packagePaths
1174
+ );
1175
+ const entryPath = path8.join(TEMP_DIR, "entry.js");
1176
+ await fs8.writeFile(entryPath, entryContent);
1177
+ logger.info("\u26A1 Bundling with esbuild...");
1178
+ const outputPath = path8.resolve(buildOptions.output);
1179
+ await fs8.ensureDir(path8.dirname(outputPath));
1180
+ const esbuildOptions = createEsbuildOptions(
1181
+ buildOptions,
1182
+ entryPath,
1183
+ outputPath,
1184
+ TEMP_DIR,
1185
+ packagePaths,
1186
+ logger
1187
+ );
1188
+ try {
1189
+ await esbuild.build(esbuildOptions);
1190
+ } catch (buildError) {
1191
+ throw createBuildError(
1192
+ buildError,
1193
+ buildOptions.code || ""
1194
+ );
1195
+ }
1196
+ logger.gray(`Output: ${outputPath}`);
1197
+ if (buildOptions.cache !== false) {
1198
+ const configContent = generateCacheKeyContent(flowConfig, buildOptions);
1199
+ const buildOutput = await fs8.readFile(outputPath, "utf-8");
1200
+ await cacheBuild(configContent, buildOutput);
1201
+ logger.debug("Build cached for future use");
1202
+ }
1203
+ let stats;
1204
+ if (showStats) {
1205
+ stats = await collectBundleStats(
1206
+ outputPath,
1207
+ buildOptions.packages,
1208
+ bundleStartTime,
1209
+ entryContent
1210
+ );
1211
+ }
1212
+ if (buildOptions.include && buildOptions.include.length > 0) {
1213
+ const outputDir = path8.dirname(outputPath);
1214
+ await copyIncludes(
1215
+ buildOptions.include,
1216
+ buildOptions.configDir || process.cwd(),
1217
+ outputDir,
1218
+ logger
1219
+ );
1220
+ }
1221
+ if (!buildOptions.tempDir) {
1222
+ await fs8.remove(TEMP_DIR);
1223
+ logger.debug("Cleaned up temporary files");
1224
+ }
1225
+ return stats;
1226
+ } catch (error) {
1227
+ if (!buildOptions.tempDir) {
1228
+ await fs8.remove(TEMP_DIR).catch(() => {
1229
+ });
1230
+ }
1231
+ throw error;
1232
+ }
1233
+ }
1234
+ async function collectBundleStats(outputPath, packages, startTime, entryContent) {
1235
+ const stats = await fs8.stat(outputPath);
1236
+ const totalSize = stats.size;
1237
+ const buildTime = Date.now() - startTime;
1238
+ const packageStats = Object.entries(packages).map(([name, pkg]) => {
1239
+ const importPattern = new RegExp(`from\\s+['"]${name}['"]`, "g");
1240
+ const namedImportPattern = new RegExp(
1241
+ `import\\s+\\{[^}]*\\}\\s+from\\s+['"]${name}['"]`,
1242
+ "g"
1243
+ );
1244
+ const hasImports = importPattern.test(entryContent) || namedImportPattern.test(entryContent);
1245
+ const packagesCount = Object.keys(packages).length;
1246
+ const estimatedSize = hasImports ? Math.floor(totalSize / packagesCount) : 0;
1247
+ return {
1248
+ name: `${name}@${pkg.version || "latest"}`,
1249
+ size: estimatedSize
1250
+ };
1251
+ });
1252
+ const hasWildcardImports = /import\s+\*\s+as\s+\w+\s+from/.test(entryContent);
1253
+ const treeshakingEffective = !hasWildcardImports;
1254
+ return {
1255
+ totalSize,
1256
+ packages: packageStats,
1257
+ buildTime,
1258
+ treeshakingEffective
1259
+ };
1260
+ }
1261
+ function createEsbuildOptions(buildOptions, entryPath, outputPath, tempDir, packagePaths, logger) {
1262
+ const alias = {};
1263
+ const baseOptions = {
1264
+ entryPoints: [entryPath],
1265
+ bundle: true,
1266
+ format: buildOptions.format,
1267
+ platform: buildOptions.platform,
1268
+ outfile: outputPath,
1269
+ absWorkingDir: tempDir,
1270
+ // Resolve modules from temp directory
1271
+ // alias removed - not needed with absWorkingDir
1272
+ mainFields: ["module", "main"],
1273
+ // Prefer ESM over CJS
1274
+ treeShaking: true,
1275
+ logLevel: "error",
1276
+ minify: buildOptions.minify,
1277
+ sourcemap: buildOptions.sourcemap,
1278
+ resolveExtensions: [".mjs", ".js", ".ts", ".json"],
1279
+ // Prefer .mjs
1280
+ // Enhanced minification options when minify is enabled
1281
+ ...buildOptions.minify && {
1282
+ minifyWhitespace: buildOptions.minifyOptions?.whitespace ?? true,
1283
+ minifyIdentifiers: buildOptions.minifyOptions?.identifiers ?? true,
1284
+ minifySyntax: buildOptions.minifyOptions?.syntax ?? true,
1285
+ legalComments: buildOptions.minifyOptions?.legalComments ?? "none",
1286
+ keepNames: buildOptions.minifyOptions?.keepNames ?? false,
1287
+ charset: "utf8"
1288
+ }
1289
+ };
1290
+ if (buildOptions.platform === "browser") {
1291
+ baseOptions.define = {
1292
+ "process.env.NODE_ENV": '"production"',
1293
+ global: "globalThis"
1294
+ };
1295
+ baseOptions.external = buildOptions.external || [];
1296
+ } else if (buildOptions.platform === "node") {
1297
+ const nodeBuiltins = [
1298
+ "crypto",
1299
+ "fs",
1300
+ "path",
1301
+ "os",
1302
+ "util",
1303
+ "stream",
1304
+ "buffer",
1305
+ "events",
1306
+ "http",
1307
+ "https",
1308
+ "url",
1309
+ "querystring",
1310
+ "zlib"
1311
+ ];
1312
+ const npmPackages = ["express", "express/*", "cors", "cors/*"];
1313
+ baseOptions.external = buildOptions.external ? [...nodeBuiltins, ...npmPackages, ...buildOptions.external] : [...nodeBuiltins, ...npmPackages];
1314
+ if (buildOptions.format === "esm") {
1315
+ baseOptions.banner = {
1316
+ js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`
1317
+ };
1318
+ }
1319
+ }
1320
+ if (buildOptions.target) {
1321
+ baseOptions.target = buildOptions.target;
1322
+ } else if (buildOptions.platform === "node") {
1323
+ baseOptions.target = "node18";
1324
+ } else {
1325
+ baseOptions.target = "es2018";
1326
+ }
1327
+ return baseOptions;
1328
+ }
1329
+ function packageNameToVariable(packageName) {
1330
+ return packageName.replace("@", "_").replace(/[/-]/g, "_").split("_").map(
1331
+ (part, i) => i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)
1332
+ ).join("");
1333
+ }
1334
+ function detectDestinationPackages(flowConfig) {
1335
+ const destinationPackages = /* @__PURE__ */ new Set();
1336
+ const destinations = flowConfig.destinations;
1337
+ if (destinations) {
1338
+ for (const [destKey, destConfig] of Object.entries(destinations)) {
1339
+ if (typeof destConfig === "object" && destConfig !== null && "package" in destConfig && typeof destConfig.package === "string") {
1340
+ destinationPackages.add(destConfig.package);
1341
+ }
1342
+ }
1343
+ }
1344
+ return destinationPackages;
1345
+ }
1346
+ function generateImportStatements(packages, destinationPackages) {
1347
+ const importStatements = [];
1348
+ const examplesMappings = [];
1349
+ for (const [packageName, packageConfig] of Object.entries(packages)) {
1350
+ if (packageConfig.imports && packageConfig.imports.length > 0) {
1351
+ const uniqueImports = [...new Set(packageConfig.imports)];
1352
+ const defaultImports = [];
1353
+ const namedImports = [];
1354
+ for (const imp of uniqueImports) {
1355
+ if (imp.startsWith("default as ")) {
1356
+ defaultImports.push(imp.replace("default as ", ""));
1357
+ } else {
1358
+ namedImports.push(imp);
1359
+ }
1360
+ }
1361
+ if (defaultImports.length > 0) {
1362
+ for (const defaultImport of defaultImports) {
1363
+ importStatements.push(
1364
+ `import ${defaultImport} from '${packageName}';`
1365
+ );
1366
+ }
1367
+ }
1368
+ if (namedImports.length > 0) {
1369
+ const importList = namedImports.join(", ");
1370
+ importStatements.push(
1371
+ `import { ${importList} } from '${packageName}';`
1372
+ );
1373
+ }
1374
+ const examplesImport = uniqueImports.find(
1375
+ (imp) => imp.includes("examples as ")
1376
+ );
1377
+ if (examplesImport) {
1378
+ const examplesVarName = examplesImport.split(" as ")[1];
1379
+ const destinationMatch = packageName.match(
1380
+ /@walkeros\/web-destination-(.+)$/
1381
+ );
1382
+ if (destinationMatch) {
1383
+ const destinationName = destinationMatch[1];
1384
+ examplesMappings.push(
1385
+ ` ${destinationName}: typeof ${examplesVarName} !== 'undefined' ? ${examplesVarName} : undefined`
1386
+ );
1387
+ }
1388
+ }
1389
+ } else {
1390
+ const varName = packageNameToVariable(packageName);
1391
+ importStatements.push(
1392
+ `import * as ${varName} from '${packageName}'; // Consider specifying explicit imports`
1393
+ );
1394
+ }
1395
+ }
1396
+ return { importStatements, examplesMappings };
1397
+ }
1398
+ async function processTemplate(flowConfig, buildOptions) {
1399
+ if (buildOptions.template) {
1400
+ const templateEngine = new TemplateEngine();
1401
+ const flowWithProps = flowConfig;
1402
+ return await templateEngine.process(
1403
+ buildOptions.template,
1404
+ buildOptions.code || "",
1405
+ // Pass user code as parameter (empty if undefined)
1406
+ flowWithProps.sources || {},
1407
+ flowWithProps.destinations || {},
1408
+ flowWithProps.collector || {},
1409
+ buildOptions
1410
+ // Pass build config to template
1411
+ );
1412
+ } else {
1413
+ return buildOptions.code || "";
1414
+ }
1415
+ }
1416
+ function wrapCodeForFormat(code, format, hasTemplate) {
1417
+ if (hasTemplate) {
1418
+ return code;
1419
+ }
1420
+ if (format === "esm") {
1421
+ const hasExport = /^\s*export\s/m.test(code);
1422
+ if (!hasExport) {
1423
+ return `export default ${code}`;
1424
+ }
1425
+ }
1426
+ return code;
1427
+ }
1428
+ function assembleFinalCode(importStatements, examplesObject, wrappedCode, format) {
1429
+ const importsCode = importStatements.join("\n");
1430
+ let finalCode = importsCode ? `${importsCode}
1431
+
1432
+ ${examplesObject}${wrappedCode}` : `${examplesObject}${wrappedCode}`;
1433
+ if (examplesObject && format === "esm") {
1434
+ finalCode += `
1435
+
1436
+ export { examples };`;
1437
+ }
1438
+ return finalCode;
1439
+ }
1440
+ async function createEntryPoint(flowConfig, buildOptions, packagePaths) {
1441
+ const destinationPackages = detectDestinationPackages(flowConfig);
1442
+ const { importStatements } = generateImportStatements(
1443
+ buildOptions.packages,
1444
+ destinationPackages
1445
+ );
1446
+ const examplesObject = "";
1447
+ const templatedCode = await processTemplate(flowConfig, buildOptions);
1448
+ const wrappedCode = wrapCodeForFormat(
1449
+ templatedCode,
1450
+ buildOptions.format,
1451
+ !!buildOptions.template
1452
+ );
1453
+ return assembleFinalCode(
1454
+ importStatements,
1455
+ examplesObject,
1456
+ wrappedCode,
1457
+ buildOptions.format
1458
+ );
1459
+ }
1460
+ function createBuildError(buildError, code) {
1461
+ if (!buildError.errors || buildError.errors.length === 0) {
1462
+ return new Error(`Build failed: ${buildError.message || buildError}`);
1463
+ }
1464
+ const firstError = buildError.errors[0];
1465
+ const location = firstError.location;
1466
+ if (location && location.file && location.file.includes("entry.js")) {
1467
+ const line = location.line;
1468
+ const column = location.column;
1469
+ const codeLines = code.split("\n");
1470
+ const errorLine = codeLines[line - 1] || "";
1471
+ return new Error(
1472
+ `Code syntax error at line ${line}, column ${column}:
1473
+ ${errorLine}
1474
+ ${" ".repeat(column - 1)}^
1475
+ ${firstError.text}`
1476
+ );
1477
+ }
1478
+ return new Error(
1479
+ `Build error: ${firstError.text}
1480
+ ` + (location ? ` at ${location.file}:${location.line}:${location.column}` : "")
1481
+ );
1482
+ }
1483
+
1484
+ // src/commands/bundle/stats.ts
1485
+ function displayStats(stats, logger) {
1486
+ logger.info("\n\u{1F4CA} Bundle Statistics");
1487
+ logger.info("\u2500".repeat(50));
1488
+ const sizeKB = formatBytes(stats.totalSize);
1489
+ logger.info(`Total Size: ${sizeKB} KB`);
1490
+ const timeSeconds = (stats.buildTime / 1e3).toFixed(2);
1491
+ logger.info(`Build Time: ${timeSeconds}s`);
1492
+ const treeshakingStatus = stats.treeshakingEffective ? "\u2705 Effective" : "\u26A0\uFE0F Not optimal (consider using named imports)";
1493
+ logger.info(`Tree-shaking: ${treeshakingStatus}`);
1494
+ if (stats.packages.length > 0) {
1495
+ logger.info(`
1496
+ Package Breakdown:`);
1497
+ stats.packages.forEach((pkg) => {
1498
+ if (pkg.size > 0) {
1499
+ const pkgSizeKB = formatBytes(pkg.size);
1500
+ logger.info(` \u2022 ${pkg.name}: ${pkgSizeKB} KB`);
1501
+ }
1502
+ });
1503
+ }
1504
+ logger.info("\u2500".repeat(50));
1505
+ }
1506
+
1507
+ // src/commands/bundle/index.ts
1508
+ async function bundleCommand(options) {
1509
+ const timer = createTimer();
1510
+ timer.start();
1511
+ const logger = createCommandLogger(options);
1512
+ const dockerArgs = buildCommonDockerArgs(options);
1513
+ if (options.flow) dockerArgs.push("--flow", options.flow);
1514
+ if (options.all) dockerArgs.push("--all");
1515
+ if (options.stats) dockerArgs.push("--stats");
1516
+ if (options.cache === false) dockerArgs.push("--no-cache");
1517
+ await executeCommand(
1518
+ async () => {
1519
+ try {
1520
+ if (options.flow && options.all) {
1521
+ throw new Error("Cannot use both --flow and --all flags together");
1522
+ }
1523
+ logger.info("\u{1F4E6} Reading configuration...");
1524
+ const configPath = resolveAsset(options.config, "config");
1525
+ const rawConfig = await loadJsonConfig(configPath);
1526
+ const configsToBundle = options.all ? loadAllFlows(rawConfig, { configPath, logger }) : [
1527
+ loadBundleConfig(rawConfig, {
1528
+ configPath,
1529
+ flowName: options.flow,
1530
+ logger
1531
+ })
1532
+ ];
1533
+ const results = [];
1534
+ for (const {
1535
+ flowConfig,
1536
+ buildOptions,
1537
+ flowName,
1538
+ isMultiFlow
1539
+ } of configsToBundle) {
1540
+ try {
1541
+ if (options.cache !== void 0) {
1542
+ buildOptions.cache = options.cache;
1543
+ }
1544
+ if (isMultiFlow || options.all) {
1545
+ logger.info(`
1546
+ \u{1F527} Building flow: ${flowName}`);
1547
+ } else {
1548
+ logger.info("\u{1F527} Starting bundle process...");
1549
+ }
1550
+ const shouldCollectStats = options.stats || options.json;
1551
+ const stats = await bundleCore(
1552
+ flowConfig,
1553
+ buildOptions,
1554
+ logger,
1555
+ shouldCollectStats
1556
+ );
1557
+ results.push({
1558
+ flowName,
1559
+ success: true,
1560
+ stats
1561
+ });
1562
+ if (!options.json && !options.all && options.stats && stats) {
1563
+ displayStats(stats, logger);
1564
+ }
1565
+ } catch (error) {
1566
+ const errorMessage = getErrorMessage(error);
1567
+ results.push({
1568
+ flowName,
1569
+ success: false,
1570
+ error: errorMessage
1571
+ });
1572
+ if (!options.all) {
1573
+ throw error;
1574
+ }
1575
+ }
1576
+ }
1577
+ const duration = timer.end() / 1e3;
1578
+ const successCount = results.filter((r) => r.success).length;
1579
+ const failureCount = results.filter((r) => !r.success).length;
1580
+ if (options.json) {
1581
+ const outputLogger = createLogger({ silent: false, json: false });
1582
+ const output = failureCount === 0 ? createSuccessOutput(
1583
+ {
1584
+ flows: results,
1585
+ summary: {
1586
+ total: results.length,
1587
+ success: successCount,
1588
+ failed: failureCount
1589
+ }
1590
+ },
1591
+ duration
1592
+ ) : createErrorOutput(
1593
+ `${failureCount} flow(s) failed to build`,
1594
+ duration
1595
+ );
1596
+ outputLogger.log("white", JSON.stringify(output, null, 2));
1597
+ } else {
1598
+ if (options.all) {
1599
+ logger.info(`
1600
+ \u{1F4CA} Build Summary:`);
1601
+ logger.info(` Total: ${results.length}`);
1602
+ logger.success(` \u2705 Success: ${successCount}`);
1603
+ if (failureCount > 0) {
1604
+ logger.error(` \u274C Failed: ${failureCount}`);
1605
+ }
1606
+ }
1607
+ if (failureCount === 0) {
1608
+ logger.success(
1609
+ `
1610
+ \u2705 Bundle created successfully in ${timer.format()}`
1611
+ );
1612
+ } else {
1613
+ throw new Error(`${failureCount} flow(s) failed to build`);
1614
+ }
1615
+ }
1616
+ } catch (error) {
1617
+ const duration = timer.getElapsed() / 1e3;
1618
+ const errorMessage = getErrorMessage(error);
1619
+ if (options.json) {
1620
+ const outputLogger = createLogger({ silent: false, json: false });
1621
+ const output = createErrorOutput(errorMessage, duration);
1622
+ outputLogger.log("white", JSON.stringify(output, null, 2));
1623
+ } else {
1624
+ logger.error("\u274C Bundle failed:");
1625
+ logger.error(errorMessage);
1626
+ }
1627
+ process.exit(1);
1628
+ }
1629
+ },
1630
+ "bundle",
1631
+ dockerArgs,
1632
+ options,
1633
+ logger,
1634
+ options.config
1635
+ );
1636
+ }
1637
+ async function bundle(configOrPath, options = {}) {
1638
+ let rawConfig;
1639
+ let configPath = path9.resolve(process.cwd(), "walkeros.config.json");
1640
+ if (typeof configOrPath === "string") {
1641
+ configPath = resolveAsset(configOrPath, "config");
1642
+ rawConfig = await loadJsonConfig(configPath);
1643
+ } else {
1644
+ rawConfig = configOrPath;
1645
+ }
1646
+ const { flowConfig, buildOptions } = loadBundleConfig(rawConfig, {
1647
+ configPath,
1648
+ flowName: options.flowName,
1649
+ buildOverrides: options.buildOverrides
1650
+ });
1651
+ if (options.cache !== void 0) {
1652
+ buildOptions.cache = options.cache;
1653
+ }
1654
+ const logger = createCommandLogger(options);
1655
+ return await bundleCore(
1656
+ flowConfig,
1657
+ buildOptions,
1658
+ logger,
1659
+ options.stats ?? false
1660
+ );
1661
+ }
1662
+
1663
+ // src/commands/simulate/simulator.ts
1664
+ import path10 from "path";
1665
+ import fs10 from "fs-extra";
1666
+ import { getPlatform as getPlatform2 } from "@walkeros/core";
1667
+
1668
+ // src/commands/simulate/tracker.ts
1669
+ var CallTracker = class {
1670
+ calls = /* @__PURE__ */ new Map();
1671
+ /**
1672
+ * Wrap a function to track its calls
1673
+ */
1674
+ wrapFunction(name, fn) {
1675
+ const self = this;
1676
+ const targetFn = fn || (() => {
1677
+ });
1678
+ return new Proxy(targetFn, {
1679
+ apply(_target, thisArg, args) {
1680
+ self.logCall(name, args);
1681
+ return targetFn.apply(thisArg, args);
1682
+ }
1683
+ });
1684
+ }
1685
+ /**
1686
+ * Wrap an environment object, tracking specified paths
1687
+ *
1688
+ * @param env - Environment object (from destination's examples/env.ts)
1689
+ * @param paths - Paths to track (e.g., ['gtag:window.gtag', 'gtag:window.dataLayer.push'])
1690
+ */
1691
+ wrapEnv(env, paths) {
1692
+ const wrapped = {};
1693
+ for (const [key, value] of Object.entries(env)) {
1694
+ if (typeof value === "object" && value !== null) {
1695
+ wrapped[key] = Array.isArray(value) ? [...value] : { ...value };
1696
+ } else {
1697
+ wrapped[key] = value;
1698
+ }
1699
+ }
1700
+ for (const fullPath of paths) {
1701
+ const [destKey, ...pathParts] = fullPath.split(":");
1702
+ const path15 = pathParts.join(":");
1703
+ if (!path15) continue;
1704
+ const cleanPath = path15.replace(/^call:/, "");
1705
+ const parts = cleanPath.split(".");
1706
+ let current = wrapped;
1707
+ let source = env;
1708
+ for (let i = 0; i < parts.length - 1; i++) {
1709
+ const part = parts[i];
1710
+ if (!current[part]) {
1711
+ current[part] = {};
1712
+ }
1713
+ current = current[part];
1714
+ source = source && typeof source[part] === "object" && source[part] !== null ? source[part] : void 0;
1715
+ }
1716
+ const finalKey = parts[parts.length - 1];
1717
+ const originalFn = source?.[finalKey];
1718
+ current[finalKey] = this.wrapFunction(
1719
+ `${destKey}:${cleanPath}`,
1720
+ typeof originalFn === "function" ? originalFn : void 0
1721
+ );
1722
+ }
1723
+ return wrapped;
1724
+ }
1725
+ logCall(fullPath, args) {
1726
+ const [destKey, ...pathParts] = fullPath.split(":");
1727
+ const apiPath = pathParts.join(":");
1728
+ if (!this.calls.has(destKey)) {
1729
+ this.calls.set(destKey, []);
1730
+ }
1731
+ this.calls.get(destKey).push({
1732
+ type: "call",
1733
+ path: apiPath,
1734
+ args,
1735
+ timestamp: Date.now()
1736
+ });
1737
+ }
1738
+ getCalls() {
1739
+ return Object.fromEntries(this.calls);
1740
+ }
1741
+ reset() {
1742
+ this.calls.clear();
1743
+ }
1744
+ };
1745
+
1746
+ // src/commands/simulate/jsdom-executor.ts
1747
+ import { JSDOM, VirtualConsole } from "jsdom";
1748
+ import fs9 from "fs-extra";
1749
+ function buildSandboxFromEnvs(envs, destinations, tracker) {
1750
+ const baseBrowserMocks = {
1751
+ Image: class MockImage {
1752
+ src = "";
1753
+ onload = (() => {
1754
+ });
1755
+ onerror = (() => {
1756
+ });
1757
+ },
1758
+ fetch: async () => ({ ok: true, json: async () => ({}) }),
1759
+ location: { href: "http://localhost" },
1760
+ navigator: { userAgent: "Mozilla/5.0 (walkerOS Simulation)" }
1761
+ };
1762
+ const sandbox = {
1763
+ window: { ...baseBrowserMocks },
1764
+ document: {}
1765
+ };
1766
+ for (const [destKey, destConfig] of Object.entries(destinations)) {
1767
+ const destEnv = envs[destKey];
1768
+ if (!destEnv?.push) continue;
1769
+ const mockEnv = destEnv.push;
1770
+ const trackPaths = destEnv.simulation || [];
1771
+ const trackedEnv = tracker.wrapEnv(
1772
+ mockEnv,
1773
+ trackPaths.map((p) => `${destKey}:${p}`)
1774
+ );
1775
+ if (trackedEnv.window && typeof trackedEnv.window === "object") {
1776
+ Object.assign(sandbox.window, trackedEnv.window);
1777
+ }
1778
+ if (trackedEnv.document && typeof trackedEnv.document === "object") {
1779
+ Object.assign(sandbox.document, trackedEnv.document);
1780
+ }
1781
+ }
1782
+ return sandbox;
1783
+ }
1784
+ function waitForWindowProperty(window, prop, timeout = 5e3) {
1785
+ return new Promise((resolve, reject) => {
1786
+ const start = Date.now();
1787
+ const check = () => {
1788
+ if (window[prop] !== void 0) {
1789
+ resolve();
1790
+ } else if (Date.now() - start > timeout) {
1791
+ reject(
1792
+ new Error(
1793
+ `Timeout waiting for window.${prop}. IIFE may have failed to execute or assign to window.`
1794
+ )
1795
+ );
1796
+ } else {
1797
+ setImmediate(check);
1798
+ }
1799
+ };
1800
+ check();
1801
+ });
1802
+ }
1803
+ async function executeInJSDOM(bundlePath, destinations, event, tracker, envs, timeout = 1e4) {
1804
+ const start = Date.now();
1805
+ const virtualConsole = new VirtualConsole();
1806
+ const dom = new JSDOM("<!DOCTYPE html><html><body></body></html>", {
1807
+ url: "http://localhost",
1808
+ runScripts: "dangerously",
1809
+ // Allow script execution
1810
+ resources: "usable",
1811
+ virtualConsole
1812
+ });
1813
+ const { window } = dom;
1814
+ const sandbox = buildSandboxFromEnvs(envs, destinations, tracker);
1815
+ Object.assign(window, sandbox.window);
1816
+ Object.assign(window.document, sandbox.document);
1817
+ const bundleCode = await fs9.readFile(bundlePath, "utf8");
1818
+ try {
1819
+ window.eval(bundleCode);
1820
+ } catch (error) {
1821
+ throw new Error(`Bundle execution failed: ${getErrorMessage(error)}`);
1822
+ }
1823
+ try {
1824
+ await waitForWindowProperty(
1825
+ window,
1826
+ "collector",
1827
+ timeout
1828
+ );
1829
+ await waitForWindowProperty(
1830
+ window,
1831
+ "elb",
1832
+ timeout
1833
+ );
1834
+ } catch (error) {
1835
+ throw new Error(
1836
+ `Window property assignment failed: ${getErrorMessage(error)}`
1837
+ );
1838
+ }
1839
+ const { collector, elb } = window;
1840
+ let elbResult;
1841
+ try {
1842
+ elbResult = await elb(event.name, event.data);
1843
+ } catch (error) {
1844
+ throw new Error(`Event execution failed: ${getErrorMessage(error)}`);
1845
+ }
1846
+ return {
1847
+ collector,
1848
+ elb,
1849
+ elbResult,
1850
+ usage: tracker.getCalls(),
1851
+ duration: Date.now() - start
1852
+ };
1853
+ }
1854
+
1855
+ // src/commands/simulate/node-executor.ts
1856
+ import { pathToFileURL } from "url";
1857
+ function buildGlobalMocksFromEnvs(envs, destinations, tracker) {
1858
+ const globalMocks = {};
1859
+ for (const [destKey] of Object.entries(destinations)) {
1860
+ const destEnv = envs[destKey];
1861
+ if (!destEnv?.push) continue;
1862
+ const mockEnv = destEnv.push;
1863
+ const trackPaths = destEnv.simulation || [];
1864
+ const trackedEnv = tracker.wrapEnv(
1865
+ mockEnv,
1866
+ trackPaths.map((p) => `${destKey}:${p}`)
1867
+ );
1868
+ Object.assign(globalMocks, trackedEnv);
1869
+ }
1870
+ return globalMocks;
1871
+ }
1872
+ function injectGlobalMocks(mocks) {
1873
+ const originalValues = {};
1874
+ for (const [key, value] of Object.entries(mocks)) {
1875
+ originalValues[key] = globalThis[key];
1876
+ globalThis[key] = value;
1877
+ }
1878
+ return () => {
1879
+ for (const [key, value] of Object.entries(originalValues)) {
1880
+ if (value === void 0) {
1881
+ delete globalThis[key];
1882
+ } else {
1883
+ globalThis[key] = value;
1884
+ }
1885
+ }
1886
+ };
1887
+ }
1888
+ async function executeInNode(bundlePath, destinations, event, tracker, envs, timeout = 3e4) {
1889
+ const start = Date.now();
1890
+ const globalMocks = buildGlobalMocksFromEnvs(envs, destinations, tracker);
1891
+ const cleanupMocks = injectGlobalMocks(globalMocks);
1892
+ try {
1893
+ const executeWithTimeout = async () => {
1894
+ const importUrl = process.env.JEST_WORKER_ID ? bundlePath : `${pathToFileURL(bundlePath).href}?t=${Date.now()}`;
1895
+ const module = await import(importUrl);
1896
+ if (!module.default || typeof module.default !== "function") {
1897
+ throw new Error("Bundle does not export default factory function");
1898
+ }
1899
+ const result = await module.default();
1900
+ if (!result || !result.elb || typeof result.elb !== "function") {
1901
+ throw new Error(
1902
+ "Factory function did not return valid result with elb"
1903
+ );
1904
+ }
1905
+ const { collector, elb } = result;
1906
+ let elbResult;
1907
+ try {
1908
+ elbResult = await elb(event.name, event.data);
1909
+ } catch (error) {
1910
+ throw new Error(`Event execution failed: ${getErrorMessage(error)}`);
1911
+ }
1912
+ return {
1913
+ collector,
1914
+ elb,
1915
+ elbResult,
1916
+ usage: tracker.getCalls(),
1917
+ duration: Date.now() - start
1918
+ };
1919
+ };
1920
+ const timeoutPromise = new Promise((_, reject) => {
1921
+ setTimeout(
1922
+ () => reject(new Error(`Server simulation timeout after ${timeout}ms`)),
1923
+ timeout
1924
+ );
72
1925
  });
1926
+ return await Promise.race([executeWithTimeout(), timeoutPromise]);
1927
+ } catch (error) {
1928
+ throw new Error(`Node execution failed: ${getErrorMessage(error)}`);
1929
+ } finally {
1930
+ cleanupMocks();
1931
+ }
1932
+ }
1933
+
1934
+ // src/commands/simulate/env-loader.ts
1935
+ async function loadDestinationEnvs(destinations) {
1936
+ const envs = {};
1937
+ for (const [destKey, destConfig] of Object.entries(destinations)) {
1938
+ const typedConfig = destConfig;
1939
+ if (!typedConfig.package) {
1940
+ continue;
1941
+ }
1942
+ try {
1943
+ const packageName = typedConfig.package;
1944
+ const isDemoPackage = packageName.includes("-demo");
1945
+ const importPath = isDemoPackage ? packageName : `${packageName}/dev`;
1946
+ const module = await import(importPath);
1947
+ const examplesModule = module.examples || module.default?.examples;
1948
+ const envModule = examplesModule?.env;
1949
+ if (envModule?.push) {
1950
+ envs[destKey] = {
1951
+ init: envModule.init,
1952
+ push: envModule.push,
1953
+ simulation: envModule.simulation || []
1954
+ };
1955
+ }
1956
+ } catch (error) {
1957
+ console.warn(
1958
+ `Warning: Could not load env for destination "${destKey}": ${error instanceof Error ? error.message : String(error)}`
1959
+ );
1960
+ }
1961
+ }
1962
+ return envs;
1963
+ }
1964
+
1965
+ // src/commands/simulate/simulator.ts
1966
+ function generateId() {
1967
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
1968
+ }
1969
+ async function simulateCore(configPath, event, options = {}) {
1970
+ const logger = createLogger({
1971
+ verbose: options.verbose || false,
1972
+ silent: options.silent || false,
1973
+ json: options.json || false
1974
+ });
1975
+ try {
1976
+ logger.info("\u{1F3AF} Starting walkerOS simulation...");
1977
+ logger.info("\u{1F4E6} Loading bundle configuration...");
1978
+ const fullConfigPath = path10.resolve(configPath);
1979
+ const rawConfig = await loadJsonConfig(fullConfigPath);
1980
+ loadBundleConfig(rawConfig, { configPath: fullConfigPath });
1981
+ logger.info(`\u{1F680} Executing simulation with event: ${JSON.stringify(event)}`);
1982
+ const result = await executeSimulation(event, fullConfigPath);
1983
+ if (result.success) {
1984
+ logger.info(`\u2705 Simulation completed successfully`);
1985
+ } else {
1986
+ logger.error(`\u274C Simulation failed: ${result.error}`);
1987
+ }
1988
+ return result;
1989
+ } catch (error) {
1990
+ const errorMessage = getErrorMessage(error);
1991
+ logger.error(`\u{1F4A5} Simulation error: ${errorMessage}`);
1992
+ return {
1993
+ success: false,
1994
+ error: errorMessage
1995
+ };
1996
+ }
1997
+ }
1998
+ function formatSimulationResult(result, options = {}) {
1999
+ if (options.json) {
2000
+ const output = {
2001
+ result: result.elbResult,
2002
+ usage: result.usage,
2003
+ duration: result.duration
2004
+ };
2005
+ return JSON.stringify(output, null, 2);
2006
+ }
2007
+ if (result.success) {
2008
+ return "\u2705 Simulation completed successfully";
2009
+ } else {
2010
+ return `\u274C Simulation failed: ${result.error}`;
2011
+ }
2012
+ }
2013
+ async function executeSimulation(event, configPath) {
2014
+ const startTime = Date.now();
2015
+ let bundlePath;
2016
+ const tempDir = getTempDir();
2017
+ try {
2018
+ if (!isObject(event) || !("name" in event) || typeof event.name !== "string") {
2019
+ throw new Error(
2020
+ 'Event must be an object with a "name" property of type string'
2021
+ );
2022
+ }
2023
+ const typedEvent = event;
2024
+ await fs10.ensureDir(tempDir);
2025
+ const rawConfig = await loadJsonConfig(configPath);
2026
+ const { flowConfig, buildOptions } = loadBundleConfig(rawConfig, {
2027
+ configPath
2028
+ });
2029
+ const platform = getPlatform2(flowConfig);
2030
+ const tracker = new CallTracker();
2031
+ const tempOutput = path10.join(
2032
+ tempDir,
2033
+ `simulation-bundle-${generateId()}.${platform === "web" ? "js" : "mjs"}`
2034
+ );
2035
+ const destinations = flowConfig.destinations;
2036
+ const simulationBuildOptions = {
2037
+ ...buildOptions,
2038
+ code: buildOptions.code || "",
2039
+ output: tempOutput,
2040
+ tempDir,
2041
+ ...platform === "web" ? {
2042
+ format: "iife",
2043
+ platform: "browser",
2044
+ windowCollector: "collector",
2045
+ windowElb: "elb"
2046
+ } : {
2047
+ format: "esm",
2048
+ platform: "node"
2049
+ }
2050
+ };
2051
+ await bundleCore(
2052
+ flowConfig,
2053
+ simulationBuildOptions,
2054
+ createLogger({ silent: true }),
2055
+ false
2056
+ );
2057
+ bundlePath = tempOutput;
2058
+ const envs = await loadDestinationEnvs(destinations || {});
2059
+ let result;
2060
+ if (platform === "web") {
2061
+ result = await executeInJSDOM(
2062
+ tempOutput,
2063
+ destinations || {},
2064
+ typedEvent,
2065
+ tracker,
2066
+ envs,
2067
+ 1e4
2068
+ );
2069
+ } else {
2070
+ result = await executeInNode(
2071
+ tempOutput,
2072
+ destinations || {},
2073
+ typedEvent,
2074
+ tracker,
2075
+ envs,
2076
+ 3e4
2077
+ );
2078
+ }
2079
+ const elbResult = result.elbResult;
2080
+ const usage = result.usage;
2081
+ const duration = Date.now() - startTime;
2082
+ return {
2083
+ success: true,
2084
+ elbResult,
2085
+ usage,
2086
+ duration,
2087
+ logs: []
2088
+ };
2089
+ } catch (error) {
2090
+ const duration = Date.now() - startTime;
2091
+ return {
2092
+ success: false,
2093
+ error: getErrorMessage(error),
2094
+ duration
2095
+ };
2096
+ } finally {
2097
+ if (tempDir) {
2098
+ await fs10.remove(tempDir).catch(() => {
2099
+ });
2100
+ }
2101
+ }
2102
+ }
2103
+
2104
+ // src/commands/simulate/index.ts
2105
+ async function simulateCommand(options) {
2106
+ const logger = createCommandLogger(options);
2107
+ const dockerArgs = buildCommonDockerArgs(options);
2108
+ if (options.event) dockerArgs.push("--event", options.event);
2109
+ await executeCommand(
2110
+ async () => {
2111
+ const startTime = Date.now();
2112
+ try {
2113
+ const event = await loadJsonFromSource(options.event, {
2114
+ name: "event"
2115
+ });
2116
+ const result = await simulateCore(options.config, event, {
2117
+ json: options.json,
2118
+ verbose: options.verbose,
2119
+ silent: options.silent
2120
+ });
2121
+ const resultWithDuration = {
2122
+ ...result,
2123
+ duration: (Date.now() - startTime) / 1e3
2124
+ };
2125
+ const outputLogger = createLogger({ silent: false, json: false });
2126
+ const output = formatSimulationResult(resultWithDuration, {
2127
+ json: options.json
2128
+ });
2129
+ outputLogger.log("white", output);
2130
+ if (!result.success) {
2131
+ process.exit(1);
2132
+ }
2133
+ } catch (error) {
2134
+ const errorMessage = getErrorMessage(error);
2135
+ if (options.json) {
2136
+ const outputLogger = createLogger({ silent: false, json: false });
2137
+ const errorOutput = JSON.stringify(
2138
+ {
2139
+ success: false,
2140
+ error: errorMessage,
2141
+ duration: (Date.now() - startTime) / 1e3
2142
+ },
2143
+ null,
2144
+ 2
2145
+ );
2146
+ outputLogger.log("white", errorOutput);
2147
+ } else {
2148
+ const errorLogger = createLogger({ silent: false, json: false });
2149
+ errorLogger.error(`\u274C Simulate command failed: ${errorMessage}`);
2150
+ }
2151
+ process.exit(1);
2152
+ }
2153
+ },
2154
+ "simulate",
2155
+ dockerArgs,
2156
+ options,
2157
+ logger,
2158
+ options.config
2159
+ );
2160
+ }
2161
+ async function simulate(configOrPath, event, options = {}) {
2162
+ if (typeof configOrPath !== "string") {
2163
+ throw new Error(
2164
+ "simulate() currently only supports config file paths. Config object support will be added in a future version. Please provide a path to a configuration file."
2165
+ );
2166
+ }
2167
+ return await simulateCore(configOrPath, event, {
2168
+ json: options.json ?? false,
2169
+ verbose: options.verbose ?? false
2170
+ });
2171
+ }
2172
+
2173
+ // src/commands/push/index.ts
2174
+ import path11 from "path";
2175
+ import { JSDOM as JSDOM2, VirtualConsole as VirtualConsole2 } from "jsdom";
2176
+ import fs11 from "fs-extra";
2177
+ import { getPlatform as getPlatform3 } from "@walkeros/core";
2178
+ import { schemas as schemas2 } from "@walkeros/core/dev";
2179
+ async function pushCommand(options) {
2180
+ const logger = createCommandLogger(options);
2181
+ const dockerArgs = buildCommonDockerArgs(options);
2182
+ dockerArgs.push("--event", options.event);
2183
+ if (options.flow) dockerArgs.push("--flow", options.flow);
2184
+ await executeCommand(
2185
+ async () => {
2186
+ const startTime = Date.now();
2187
+ try {
2188
+ logger.info("\u{1F4E5} Loading event...");
2189
+ const event = await loadJsonFromSource(options.event, {
2190
+ name: "event"
2191
+ });
2192
+ const eventResult = schemas2.PartialEventSchema.safeParse(event);
2193
+ if (!eventResult.success) {
2194
+ const errors = eventResult.error.issues.map((issue) => `${String(issue.path.join("."))}: ${issue.message}`).join(", ");
2195
+ throw new Error(`Invalid event: ${errors}`);
2196
+ }
2197
+ const parsedEvent = eventResult.data;
2198
+ if (!parsedEvent.name) {
2199
+ throw new Error('Invalid event: Missing required "name" property');
2200
+ }
2201
+ const validatedEvent = {
2202
+ name: parsedEvent.name,
2203
+ data: parsedEvent.data || {}
2204
+ };
2205
+ if (!validatedEvent.name.includes(" ")) {
2206
+ logger.warn(
2207
+ `Event name "${validatedEvent.name}" should follow "ENTITY ACTION" format (e.g., "page view")`
2208
+ );
2209
+ }
2210
+ logger.info("\u{1F4E6} Loading flow configuration...");
2211
+ const configPath = path11.resolve(options.config);
2212
+ const rawConfig = await loadJsonConfig(configPath);
2213
+ const { flowConfig, buildOptions, flowName, isMultiFlow } = loadBundleConfig(rawConfig, {
2214
+ configPath: options.config,
2215
+ flowName: options.flow,
2216
+ logger
2217
+ });
2218
+ const platform = getPlatform3(flowConfig);
2219
+ logger.info("\u{1F528} Bundling flow configuration...");
2220
+ const configDir = path11.dirname(configPath);
2221
+ const tempDir = path11.join(
2222
+ configDir,
2223
+ ".tmp",
2224
+ `push-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
2225
+ );
2226
+ await fs11.ensureDir(tempDir);
2227
+ const tempPath = path11.join(
2228
+ tempDir,
2229
+ `bundle.${platform === "web" ? "js" : "mjs"}`
2230
+ );
2231
+ const pushBuildOptions = {
2232
+ ...buildOptions,
2233
+ output: tempPath,
2234
+ // Web uses IIFE for browser-like execution, server uses ESM
2235
+ format: platform === "web" ? "iife" : "esm",
2236
+ platform: platform === "web" ? "browser" : "node",
2237
+ ...platform === "web" && {
2238
+ windowCollector: "collector",
2239
+ windowElb: "elb"
2240
+ }
2241
+ };
2242
+ await bundleCore(flowConfig, pushBuildOptions, logger, false);
2243
+ logger.debug(`Bundle created: ${tempPath}`);
2244
+ let result;
2245
+ if (platform === "web") {
2246
+ logger.info("\u{1F310} Executing in web environment (JSDOM)...");
2247
+ result = await executeWebPush(tempPath, validatedEvent, logger);
2248
+ } else if (platform === "server") {
2249
+ logger.info("\u{1F5A5}\uFE0F Executing in server environment (Node.js)...");
2250
+ result = await executeServerPush(tempPath, validatedEvent, logger);
2251
+ } else {
2252
+ throw new Error(`Unsupported platform: ${platform}`);
2253
+ }
2254
+ const duration = Date.now() - startTime;
2255
+ if (options.json) {
2256
+ const outputLogger = createLogger({ silent: false, json: false });
2257
+ outputLogger.log(
2258
+ "white",
2259
+ JSON.stringify(
2260
+ {
2261
+ success: result.success,
2262
+ event: result.elbResult,
2263
+ duration
2264
+ },
2265
+ null,
2266
+ 2
2267
+ )
2268
+ );
2269
+ } else {
2270
+ if (result.success) {
2271
+ logger.success("\u2705 Event pushed successfully");
2272
+ if (result.elbResult && typeof result.elbResult === "object") {
2273
+ const pushResult = result.elbResult;
2274
+ if ("id" in pushResult && pushResult.id) {
2275
+ logger.info(` Event ID: ${pushResult.id}`);
2276
+ }
2277
+ if ("entity" in pushResult && pushResult.entity) {
2278
+ logger.info(` Entity: ${pushResult.entity}`);
2279
+ }
2280
+ if ("action" in pushResult && pushResult.action) {
2281
+ logger.info(` Action: ${pushResult.action}`);
2282
+ }
2283
+ }
2284
+ logger.info(` Duration: ${duration}ms`);
2285
+ } else {
2286
+ logger.error(`\u274C Push failed: ${result.error}`);
2287
+ process.exit(1);
2288
+ }
2289
+ }
2290
+ try {
2291
+ await fs11.remove(tempDir);
2292
+ } catch {
2293
+ }
2294
+ } catch (error) {
2295
+ const duration = Date.now() - startTime;
2296
+ const errorMessage = getErrorMessage(error);
2297
+ if (options.json) {
2298
+ const outputLogger = createLogger({ silent: false, json: false });
2299
+ outputLogger.log(
2300
+ "white",
2301
+ JSON.stringify(
2302
+ {
2303
+ success: false,
2304
+ error: errorMessage,
2305
+ duration
2306
+ },
2307
+ null,
2308
+ 2
2309
+ )
2310
+ );
2311
+ } else {
2312
+ logger.error(`\u274C Push command failed: ${errorMessage}`);
2313
+ }
2314
+ process.exit(1);
2315
+ }
2316
+ },
2317
+ "push",
2318
+ dockerArgs,
2319
+ options,
2320
+ logger,
2321
+ options.config
2322
+ );
2323
+ }
2324
+ async function executeWebPush(bundlePath, event, logger) {
2325
+ const startTime = Date.now();
2326
+ try {
2327
+ const virtualConsole = new VirtualConsole2();
2328
+ const dom = new JSDOM2("<!DOCTYPE html><html><body></body></html>", {
2329
+ url: "http://localhost",
2330
+ runScripts: "dangerously",
2331
+ resources: "usable",
2332
+ virtualConsole
2333
+ });
2334
+ const { window } = dom;
2335
+ logger.debug("Loading bundle...");
2336
+ const bundleCode = await fs11.readFile(bundlePath, "utf8");
2337
+ window.eval(bundleCode);
2338
+ logger.debug("Waiting for elb...");
2339
+ await waitForWindowProperty2(
2340
+ window,
2341
+ "elb",
2342
+ 5e3
2343
+ );
2344
+ const windowObj = window;
2345
+ const elb = windowObj.elb;
2346
+ logger.info(`Pushing event: ${event.name}`);
2347
+ const elbResult = await elb(event.name, event.data);
2348
+ return {
2349
+ success: true,
2350
+ elbResult,
2351
+ duration: Date.now() - startTime
2352
+ };
2353
+ } catch (error) {
2354
+ return {
2355
+ success: false,
2356
+ duration: Date.now() - startTime,
2357
+ error: getErrorMessage(error)
2358
+ };
2359
+ }
2360
+ }
2361
+ async function executeServerPush(bundlePath, event, logger, timeout = 6e4) {
2362
+ const startTime = Date.now();
2363
+ try {
2364
+ const timeoutPromise = new Promise((_, reject) => {
2365
+ setTimeout(
2366
+ () => reject(new Error(`Server push timeout after ${timeout}ms`)),
2367
+ timeout
2368
+ );
2369
+ });
2370
+ const executePromise = (async () => {
2371
+ logger.debug("Importing bundle...");
2372
+ const flowModule = await import(bundlePath);
2373
+ if (!flowModule.default || typeof flowModule.default !== "function") {
2374
+ throw new Error("Bundle does not export default factory function");
2375
+ }
2376
+ logger.debug("Calling factory function...");
2377
+ const result = await flowModule.default();
2378
+ if (!result || !result.elb || typeof result.elb !== "function") {
2379
+ throw new Error(
2380
+ "Factory function did not return valid result with elb"
2381
+ );
2382
+ }
2383
+ const { elb } = result;
2384
+ logger.info(`Pushing event: ${event.name}`);
2385
+ const elbResult = await elb(event.name, event.data);
2386
+ return {
2387
+ success: true,
2388
+ elbResult,
2389
+ duration: Date.now() - startTime
2390
+ };
2391
+ })();
2392
+ return await Promise.race([executePromise, timeoutPromise]);
2393
+ } catch (error) {
2394
+ return {
2395
+ success: false,
2396
+ duration: Date.now() - startTime,
2397
+ error: getErrorMessage(error)
2398
+ };
2399
+ }
2400
+ }
2401
+ function waitForWindowProperty2(window, prop, timeout = 5e3) {
2402
+ return new Promise((resolve, reject) => {
2403
+ const start = Date.now();
2404
+ const check = () => {
2405
+ if (window[prop] !== void 0) {
2406
+ resolve();
2407
+ } else if (Date.now() - start > timeout) {
2408
+ reject(
2409
+ new Error(
2410
+ `Timeout waiting for window.${prop}. IIFE may have failed to execute.`
2411
+ )
2412
+ );
2413
+ } else {
2414
+ setImmediate(check);
2415
+ }
2416
+ };
2417
+ check();
2418
+ });
2419
+ }
2420
+
2421
+ // src/commands/run/index.ts
2422
+ import path13 from "path";
2423
+
2424
+ // src/commands/run/validators.ts
2425
+ import { existsSync as existsSync2 } from "fs";
2426
+
2427
+ // src/schemas/primitives.ts
2428
+ import { z } from "@walkeros/core/dev";
2429
+ var RunModeSchema = z.enum(["collect", "serve"]).describe("CLI run mode: collect events or serve HTTP");
2430
+ var PortSchema = z.number().int("Port must be an integer").min(1, "Port must be at least 1").max(65535, "Port must be at most 65535").describe("HTTP server port number");
2431
+ var FilePathSchema = z.string().min(1, "File path cannot be empty").describe("Path to configuration file");
2432
+
2433
+ // src/schemas/run.ts
2434
+ import { z as z2 } from "@walkeros/core/dev";
2435
+ var RunOptionsSchema = z2.object({
2436
+ mode: RunModeSchema,
2437
+ flow: FilePathSchema,
2438
+ port: PortSchema.default(8080),
2439
+ flowName: z2.string().optional().describe("Specific flow name to run")
73
2440
  });
74
- // Run command with subcommands
75
- const runCmd = program
76
- .command('run')
77
- .description('Run walkerOS flows in collect or serve mode');
78
- // Run collect subcommand
79
- runCmd
80
- .command('collect [file]')
81
- .description('Run collector mode (event collection endpoint). Defaults to server-collect.mjs if no file specified.')
82
- .option('-p, --port <number>', 'Port to listen on (default: 8080)', parseInt)
83
- .option('-h, --host <address>', 'Host address (default: 0.0.0.0)')
84
- .option('--json', 'Output results as JSON')
85
- .option('-v, --verbose', 'Verbose output')
86
- .option('--local', 'execute in local Node.js instead of Docker')
87
- .option('--dry-run', 'preview command without executing')
88
- .option('--silent', 'suppress output')
89
- .action(async (file, options) => {
90
- await runCommand('collect', {
91
- config: file || 'server-collect.mjs',
2441
+
2442
+ // src/commands/run/validators.ts
2443
+ function validateMode(mode) {
2444
+ const result = RunModeSchema.safeParse(mode);
2445
+ if (!result.success) {
2446
+ throw new Error(
2447
+ `Invalid mode: "${mode}"
2448
+ Valid modes: collect, serve
2449
+ Example: walkeros run collect ./flow.json`
2450
+ );
2451
+ }
2452
+ }
2453
+ function validateFlowFile(filePath) {
2454
+ const absolutePath = resolveAsset(filePath, "bundle");
2455
+ if (!existsSync2(absolutePath)) {
2456
+ throw new Error(
2457
+ `Flow file not found: ${filePath}
2458
+ Resolved path: ${absolutePath}
2459
+ Make sure the file exists and the path is correct`
2460
+ );
2461
+ }
2462
+ return absolutePath;
2463
+ }
2464
+ function validatePort(port) {
2465
+ const result = PortSchema.safeParse(port);
2466
+ if (!result.success) {
2467
+ throw new Error(
2468
+ `Invalid port: ${port}
2469
+ Port must be an integer between 1 and 65535
2470
+ Example: --port 8080`
2471
+ );
2472
+ }
2473
+ }
2474
+
2475
+ // src/commands/run/utils.ts
2476
+ import path12 from "path";
2477
+ import fs12 from "fs-extra";
2478
+ async function prepareBundleForRun(configPath, options) {
2479
+ const configDir = path12.dirname(path12.resolve(configPath));
2480
+ const tempDir = path12.join(
2481
+ configDir,
2482
+ ".tmp",
2483
+ `run-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
2484
+ );
2485
+ await fs12.ensureDir(tempDir);
2486
+ const tempPath = path12.join(tempDir, "bundle.mjs");
2487
+ await bundle(configPath, {
2488
+ cache: true,
2489
+ verbose: options.verbose,
2490
+ silent: options.silent,
2491
+ buildOverrides: {
2492
+ output: tempPath,
2493
+ format: "esm",
2494
+ platform: "node"
2495
+ }
2496
+ });
2497
+ return tempPath;
2498
+ }
2499
+ function isPreBuiltConfig(configPath) {
2500
+ return configPath.endsWith(".mjs") || configPath.endsWith(".js") || configPath.endsWith(".cjs");
2501
+ }
2502
+
2503
+ // src/commands/run/execution.ts
2504
+ import { runFlow, runServeMode } from "@walkeros/docker";
2505
+ async function executeRunLocal(mode, flowPath, options) {
2506
+ switch (mode) {
2507
+ case "collect": {
2508
+ if (!flowPath) {
2509
+ throw new Error("Flow path is required for collect mode");
2510
+ }
2511
+ const config = {
2512
+ port: options.port,
2513
+ host: options.host
2514
+ };
2515
+ await runFlow(flowPath, config);
2516
+ break;
2517
+ }
2518
+ case "serve": {
2519
+ const config = {
92
2520
  port: options.port,
93
2521
  host: options.host,
94
- json: options.json,
95
- verbose: options.verbose,
96
- local: options.local,
97
- dryRun: options.dryRun,
98
- silent: options.silent,
99
- });
100
- });
101
- // Run serve subcommand
102
- runCmd
103
- .command('serve [file]')
104
- .description('Run serve mode (single-file server for browser bundles). Defaults to baked-in web-serve.js if no file specified.')
105
- .option('-p, --port <number>', 'Port to listen on (default: 8080)', parseInt)
106
- .option('-h, --host <address>', 'Host address (default: 0.0.0.0)')
107
- .option('--name <filename>', 'Filename in URL (default: walker.js)')
108
- .option('--path <directory>', 'URL directory path (e.g., libs/v1)')
109
- .option('--json', 'Output results as JSON')
110
- .option('-v, --verbose', 'Verbose output')
111
- .option('--local', 'execute in local Node.js instead of Docker')
112
- .option('--dry-run', 'preview command without executing')
113
- .option('--silent', 'suppress output')
114
- .action(async (file, options) => {
115
- await runCommand('serve', {
116
- config: file || 'web-serve.js',
2522
+ serveName: options.serveName,
2523
+ servePath: options.servePath,
2524
+ filePath: flowPath || void 0
2525
+ };
2526
+ await runServeMode(config);
2527
+ break;
2528
+ }
2529
+ default:
2530
+ throw new Error(`Unknown mode: ${mode}`);
2531
+ }
2532
+ }
2533
+
2534
+ // src/commands/run/index.ts
2535
+ async function runCommand(mode, options) {
2536
+ const timer = createTimer();
2537
+ timer.start();
2538
+ const logger = createCommandLogger(options);
2539
+ try {
2540
+ validateMode(mode);
2541
+ const configPath = validateFlowFile(options.config);
2542
+ if (options.port !== void 0) {
2543
+ validatePort(options.port);
2544
+ }
2545
+ const isPreBuilt = isPreBuiltConfig(configPath);
2546
+ let flowPath = null;
2547
+ if (mode === "collect") {
2548
+ if (isPreBuilt) {
2549
+ flowPath = path13.resolve(configPath);
2550
+ if (!options.json && !options.silent) {
2551
+ logger.info(`\u{1F4E6} Using pre-built flow: ${path13.basename(flowPath)}`);
2552
+ }
2553
+ } else {
2554
+ if (!options.json && !options.silent) {
2555
+ logger.info("\u{1F528} Building flow bundle...");
2556
+ }
2557
+ flowPath = await prepareBundleForRun(configPath, {
2558
+ verbose: options.verbose,
2559
+ silent: options.json || options.silent
2560
+ });
2561
+ if (!options.json && !options.silent) {
2562
+ logger.success("\u2705 Bundle ready");
2563
+ }
2564
+ }
2565
+ }
2566
+ const executionMode = getExecutionMode(options);
2567
+ if (options.dryRun) {
2568
+ if (executionMode === "docker") {
2569
+ logger.info(
2570
+ `[DRY-RUN] Would execute in Docker: run ${mode} with runtime image`
2571
+ );
2572
+ } else {
2573
+ logger.info(`[DRY-RUN] Would execute locally: run ${mode}`);
2574
+ }
2575
+ return;
2576
+ }
2577
+ if (executionMode === "docker") {
2578
+ const dockerAvailable = await isDockerAvailable();
2579
+ if (!dockerAvailable) {
2580
+ throw new Error(
2581
+ "Docker is not available. Please install Docker or use --local flag to execute locally."
2582
+ );
2583
+ }
2584
+ if (!options.json && !options.silent) {
2585
+ logger.info("\u{1F433} Executing in production runtime container...");
2586
+ }
2587
+ await executeRunInDocker(mode, flowPath, {
117
2588
  port: options.port,
118
2589
  host: options.host,
119
- serveName: options.name,
120
- servePath: options.path,
121
- json: options.json,
2590
+ serveName: options.serveName,
2591
+ servePath: options.servePath,
2592
+ silent: options.silent
2593
+ });
2594
+ } else {
2595
+ if (!options.json && !options.silent) {
2596
+ const modeLabel = mode === "collect" ? "Collector" : "Server";
2597
+ logger.info(`\u{1F5A5}\uFE0F Starting ${modeLabel} locally...`);
2598
+ }
2599
+ await executeRunLocal(mode, flowPath, {
2600
+ port: options.port,
2601
+ host: options.host,
2602
+ serveName: options.serveName,
2603
+ servePath: options.servePath
2604
+ });
2605
+ }
2606
+ } catch (error) {
2607
+ const duration = timer.getElapsed() / 1e3;
2608
+ const errorMessage = getErrorMessage(error);
2609
+ if (options.json) {
2610
+ const output = {
2611
+ success: false,
2612
+ mode,
2613
+ error: errorMessage,
2614
+ duration
2615
+ };
2616
+ console.log(JSON.stringify(output, null, 2));
2617
+ } else {
2618
+ logger.error("\u274C Run failed:");
2619
+ logger.error(errorMessage);
2620
+ }
2621
+ process.exit(1);
2622
+ }
2623
+ }
2624
+ async function run(mode, options) {
2625
+ const startTime = Date.now();
2626
+ try {
2627
+ validateMode(mode);
2628
+ let flowFile;
2629
+ if (typeof options.config === "string") {
2630
+ flowFile = validateFlowFile(options.config);
2631
+ } else {
2632
+ throw new Error("Programmatic run() requires config file path");
2633
+ }
2634
+ if (options.port !== void 0) {
2635
+ validatePort(options.port);
2636
+ }
2637
+ const isPreBuilt = isPreBuiltConfig(flowFile);
2638
+ let flowPath;
2639
+ if (isPreBuilt) {
2640
+ flowPath = path13.resolve(flowFile);
2641
+ } else {
2642
+ flowPath = await prepareBundleForRun(flowFile, {
122
2643
  verbose: options.verbose,
123
- local: options.local,
124
- dryRun: options.dryRun,
125
- silent: options.silent,
2644
+ silent: true
2645
+ });
2646
+ }
2647
+ await executeRunLocal(mode, flowPath, {
2648
+ port: options.port,
2649
+ host: options.host,
2650
+ serveName: options.serveName,
2651
+ servePath: options.servePath
126
2652
  });
2653
+ return {
2654
+ success: true,
2655
+ exitCode: 0,
2656
+ duration: Date.now() - startTime
2657
+ };
2658
+ } catch (error) {
2659
+ return {
2660
+ success: false,
2661
+ exitCode: 1,
2662
+ duration: Date.now() - startTime,
2663
+ error: getErrorMessage(error)
2664
+ };
2665
+ }
2666
+ }
2667
+
2668
+ // src/commands/cache.ts
2669
+ import fs13 from "fs-extra";
2670
+ import path14 from "path";
2671
+ var CACHE_DIR = path14.join(".tmp", "cache");
2672
+ function registerCacheCommand(program2) {
2673
+ const cache = program2.command("cache").description("Manage the CLI cache");
2674
+ cache.command("clear").description("Clear all cached packages and builds").option("--packages", "Clear only package cache").option("--builds", "Clear only build cache").action(async (options) => {
2675
+ if (options.packages) {
2676
+ await fs13.remove(path14.join(CACHE_DIR, "packages"));
2677
+ console.log("Package cache cleared");
2678
+ } else if (options.builds) {
2679
+ await fs13.remove(path14.join(CACHE_DIR, "builds"));
2680
+ console.log("Build cache cleared");
2681
+ } else {
2682
+ await fs13.remove(CACHE_DIR);
2683
+ console.log("All caches cleared");
2684
+ }
2685
+ });
2686
+ cache.command("info").description("Show cache statistics").action(async () => {
2687
+ const packagesDir = path14.join(CACHE_DIR, "packages");
2688
+ const buildsDir = path14.join(CACHE_DIR, "builds");
2689
+ const packageCount = await countEntries(packagesDir);
2690
+ const buildCount = await countEntries(buildsDir);
2691
+ console.log(`Cache directory: ${CACHE_DIR}`);
2692
+ console.log(`Cached packages: ${packageCount}`);
2693
+ console.log(`Cached builds: ${buildCount}`);
2694
+ });
2695
+ }
2696
+ async function countEntries(dir) {
2697
+ if (!await fs13.pathExists(dir)) return 0;
2698
+ const entries = await fs13.readdir(dir);
2699
+ return entries.length;
2700
+ }
2701
+
2702
+ // src/index.ts
2703
+ var __filename = fileURLToPath2(import.meta.url);
2704
+ var __dirname = dirname(__filename);
2705
+ var packageJson = JSON.parse(
2706
+ readFileSync(join(__dirname, "../package.json"), "utf-8")
2707
+ );
2708
+ var VERSION = packageJson.version;
2709
+ var program = new Command();
2710
+ program.name("walkeros").description("walkerOS CLI - Bundle and deploy walkerOS components").version(VERSION);
2711
+ program.command("bundle [file]").description("Bundle NPM packages with custom code").option("-f, --flow <name>", "flow to build (for multi-flow configs)").option("--all", "build all flows (for multi-flow configs)").option("-s, --stats", "show bundle statistics").option("--json", "output statistics in JSON format (implies --stats)").option("--no-cache", "disable package caching and download fresh packages").option("-v, --verbose", "verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
2712
+ await bundleCommand({
2713
+ config: file || "bundle.config.json",
2714
+ flow: options.flow,
2715
+ all: options.all,
2716
+ stats: options.stats,
2717
+ json: options.json,
2718
+ cache: options.cache,
2719
+ verbose: options.verbose,
2720
+ local: options.local,
2721
+ dryRun: options.dryRun,
2722
+ silent: options.silent
2723
+ });
2724
+ });
2725
+ program.command("simulate [file]").description("Simulate event processing and capture API calls").option(
2726
+ "-e, --event <source>",
2727
+ "Event to simulate (JSON string, file path, or URL)"
2728
+ ).option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
2729
+ await simulateCommand({
2730
+ config: file || "bundle.config.json",
2731
+ event: options.event,
2732
+ json: options.json,
2733
+ verbose: options.verbose,
2734
+ local: options.local,
2735
+ dryRun: options.dryRun,
2736
+ silent: options.silent
2737
+ });
2738
+ });
2739
+ program.command("push [file]").description("Push an event through the flow with real API execution").requiredOption(
2740
+ "-e, --event <source>",
2741
+ "Event to push (JSON string, file path, or URL)"
2742
+ ).option("--flow <name>", "Flow name (for multi-flow configs)").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("-s, --silent", "Suppress output").option("--local", "Execute in local Node.js instead of Docker").action(async (file, options) => {
2743
+ await pushCommand({
2744
+ config: file || "bundle.config.json",
2745
+ event: options.event,
2746
+ flow: options.flow,
2747
+ json: options.json,
2748
+ verbose: options.verbose,
2749
+ silent: options.silent,
2750
+ local: options.local
2751
+ });
2752
+ });
2753
+ var runCmd = program.command("run").description("Run walkerOS flows in collect or serve mode");
2754
+ runCmd.command("collect [file]").description(
2755
+ "Run collector mode (event collection endpoint). Defaults to server-collect.mjs if no file specified."
2756
+ ).option("-p, --port <number>", "Port to listen on (default: 8080)", parseInt).option("-h, --host <address>", "Host address (default: 0.0.0.0)").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
2757
+ await runCommand("collect", {
2758
+ config: file || "server-collect.mjs",
2759
+ port: options.port,
2760
+ host: options.host,
2761
+ json: options.json,
2762
+ verbose: options.verbose,
2763
+ local: options.local,
2764
+ dryRun: options.dryRun,
2765
+ silent: options.silent
2766
+ });
2767
+ });
2768
+ runCmd.command("serve [file]").description(
2769
+ "Run serve mode (single-file server for browser bundles). Defaults to baked-in web-serve.js if no file specified."
2770
+ ).option("-p, --port <number>", "Port to listen on (default: 8080)", parseInt).option("-h, --host <address>", "Host address (default: 0.0.0.0)").option("--name <filename>", "Filename in URL (default: walker.js)").option("--path <directory>", "URL directory path (e.g., libs/v1)").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
2771
+ await runCommand("serve", {
2772
+ config: file || "web-serve.js",
2773
+ port: options.port,
2774
+ host: options.host,
2775
+ serveName: options.name,
2776
+ servePath: options.path,
2777
+ json: options.json,
2778
+ verbose: options.verbose,
2779
+ local: options.local,
2780
+ dryRun: options.dryRun,
2781
+ silent: options.silent
2782
+ });
127
2783
  });
128
- // Run the CLI
129
- // Note: This file is marked as a bin script in package.json,
130
- // so it's always executed directly (never imported as a library)
2784
+ registerCacheCommand(program);
131
2785
  program.parse();
2786
+ export {
2787
+ bundle,
2788
+ bundleCommand,
2789
+ pushCommand,
2790
+ run,
2791
+ runCommand,
2792
+ simulate,
2793
+ simulateCommand
2794
+ };
132
2795
  //# sourceMappingURL=index.js.map