@jshookmcp/jshook 0.3.0 → 0.3.1

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 (321) hide show
  1. package/README.md +25 -50
  2. package/README.zh.md +25 -48
  3. package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
  4. package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
  5. package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
  6. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
  7. package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
  8. package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
  9. package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
  10. package/dist/EventBus-DgciURGg.mjs +1 -0
  11. package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
  12. package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
  13. package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
  14. package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
  15. package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
  16. package/dist/{HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -101
  17. package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
  18. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
  19. package/dist/MemoryController-BaqstM5w.mjs +2 -0
  20. package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
  21. package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
  22. package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
  23. package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
  24. package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
  25. package/dist/PageController-D9jVkH0i.mjs +1 -0
  26. package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
  27. package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
  28. package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
  29. package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
  30. package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
  31. package/dist/ScriptManager-fgqiALgj.mjs +7 -0
  32. package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
  33. package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
  34. package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
  35. package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
  36. package/dist/ToolError-DWU_z7gp.mjs +1 -0
  37. package/dist/ToolProbe-xsfALmN3.mjs +1 -0
  38. package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
  39. package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
  40. package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
  41. package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
  42. package/dist/Win32API-Bhi5xFBe.mjs +1 -0
  43. package/dist/Win32Debug-CQteFL4F.mjs +1 -0
  44. package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
  45. package/dist/analysis-BuR-NgX8.mjs +5 -0
  46. package/dist/{antidebug-BRKeyt27.mjs → antidebug-BOTZH6-0.mjs} +8 -259
  47. package/dist/artifactRetention-NBdncOEW.mjs +1 -0
  48. package/dist/artifacts-B5xQuEa_.mjs +1 -0
  49. package/dist/authorization-schema-B40obG1A.mjs +1 -0
  50. package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
  51. package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
  52. package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
  53. package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
  54. package/dist/browser-C4Le3xqA.mjs +11 -0
  55. package/dist/capabilities-DbYCv-HF.mjs +1 -0
  56. package/dist/chunk-C_pMuVsO.mjs +1 -0
  57. package/dist/collector-CKO8RPK8.mjs +1 -0
  58. package/dist/concurrency-CcK46d0h.mjs +1 -0
  59. package/dist/constants-Cp6hBrrx.mjs +1 -0
  60. package/dist/coordination-BbijHEHH.mjs +1 -0
  61. package/dist/debugger-CRJq_krh.mjs +1 -0
  62. package/dist/definitions-BGobEDQa.mjs +1 -0
  63. package/dist/definitions-BGwNSkVm.mjs +1 -0
  64. package/dist/definitions-BbxOUiP-.mjs +1 -0
  65. package/dist/definitions-CCP9gphV.mjs +1 -0
  66. package/dist/definitions-CIO9O-Sw.mjs +1 -0
  67. package/dist/definitions-CYFbewnd.mjs +1 -0
  68. package/dist/definitions-CdWEuIkI.mjs +1 -0
  69. package/dist/definitions-CoQFbggH.mjs +1 -0
  70. package/dist/definitions-CuJRsJ6N.mjs +1 -0
  71. package/dist/definitions-DI9YXsJk.mjs +1 -0
  72. package/dist/definitions-DJklW2sS.mjs +1 -0
  73. package/dist/definitions-DZ8uKusP.mjs +1 -0
  74. package/dist/definitions-Dds_zrWx.mjs +1 -0
  75. package/dist/definitions-Dgrg7f3D.mjs +1 -0
  76. package/dist/definitions-DtE0XLrT.mjs +1 -0
  77. package/dist/definitions-LaYTuwQd.mjs +26 -0
  78. package/dist/definitions-NoVp_9Pm.mjs +1 -0
  79. package/dist/definitions-OvGsfxdt.mjs +1 -0
  80. package/dist/definitions-jXPaVy4P.mjs +1 -0
  81. package/dist/encoding-DGcr6Aj_.mjs +2 -0
  82. package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
  83. package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
  84. package/dist/factory-Cx_1LorX.mjs +1 -0
  85. package/dist/flat-target-session-CO5g78k3.mjs +1 -0
  86. package/dist/formatAddress-C7j2fDlM.mjs +1 -0
  87. package/dist/graphql-HLf3MS8H.mjs +62 -0
  88. package/dist/handlers-BLMa4X7l.mjs +54 -0
  89. package/dist/handlers-BP12ZsWc.mjs +4 -0
  90. package/dist/handlers-BZoPla6E.mjs +1 -0
  91. package/dist/handlers-BggKiVx9.mjs +2 -0
  92. package/dist/handlers-D3iev8g1.mjs +1 -0
  93. package/dist/handlers-D49r1-1P.mjs +1 -0
  94. package/dist/handlers-DCE45Ww8.mjs +2 -0
  95. package/dist/handlers-DW5AbYs5.mjs +5 -0
  96. package/dist/handlers-De5u62Ga2.mjs +1 -0
  97. package/dist/handlers-DmQzIc44.mjs +31 -0
  98. package/dist/handlers-DnJRGp7t.mjs +302 -0
  99. package/dist/handlers-Dv_runVv.mjs +2 -0
  100. package/dist/handlers-S9Ws0IGy.mjs +2 -0
  101. package/dist/{handlers-Dz9PYsCa.mjs → handlers-pVNpaw4A.mjs} +118 -904
  102. package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
  103. package/dist/hooks-DDKppogd.mjs +600 -0
  104. package/dist/index.mjs +12 -5235
  105. package/dist/logger-sBC6IdRT.mjs +1 -0
  106. package/dist/maintenance-CutEO84j.mjs +1 -0
  107. package/dist/manifest-BFGxlDRh.mjs +123 -0
  108. package/dist/manifest-BPuE6oH2.mjs +1 -0
  109. package/dist/manifest-BXry5N09.mjs +1 -0
  110. package/dist/manifest-BeP_zJGb2.mjs +1 -0
  111. package/dist/manifest-C0g67k6U.mjs +1 -0
  112. package/dist/manifest-C1nZkTkO.mjs +1 -0
  113. package/dist/manifest-C7qV1z7F.mjs +1 -0
  114. package/dist/manifest-CDeUZGUZ.mjs +1 -0
  115. package/dist/manifest-CDiCtaQT.mjs +1 -0
  116. package/dist/manifest-CFn0359q2.mjs +1 -0
  117. package/dist/manifest-CGq4NpqH2.mjs +1 -0
  118. package/dist/manifest-CJMGt7Qy.mjs +1 -0
  119. package/dist/manifest-CRIJq4Hs.mjs +1 -0
  120. package/dist/manifest-C_hEIjSx.mjs +1 -0
  121. package/dist/manifest-CeQmtQOY.mjs +1 -0
  122. package/dist/manifest-Cq0j7GZt.mjs +1 -0
  123. package/dist/manifest-CtPmHAdn.mjs +1 -0
  124. package/dist/manifest-Cx2IVMUY.mjs +1 -0
  125. package/dist/manifest-D16xPXro.mjs +1 -0
  126. package/dist/manifest-D44TaRJU.mjs +1 -0
  127. package/dist/manifest-D610kxZr.mjs +2 -0
  128. package/dist/manifest-DC-SMF6b.mjs +1 -0
  129. package/dist/manifest-DD3rtxvV.mjs +1 -0
  130. package/dist/manifest-DKUorv5M.mjs +1 -0
  131. package/dist/manifest-DMJlcsTR.mjs +1 -0
  132. package/dist/manifest-DWUUWBz0.mjs +1 -0
  133. package/dist/manifest-De-6Wf2R.mjs +1 -0
  134. package/dist/manifest-Dgh0uDW-.mjs +1 -0
  135. package/dist/manifest-Dm0o3i2U.mjs +1 -0
  136. package/dist/manifest-DsVh7Y4U.mjs +1 -0
  137. package/dist/manifest-DtEFSRaq.mjs +1 -0
  138. package/dist/manifest-H-EpAyZQ.mjs +1 -0
  139. package/dist/manifest-ais9Afrw.mjs +1 -0
  140. package/dist/manifest-tmb54wmA.mjs +1 -0
  141. package/dist/manifest-yu2xiQqe.mjs +1 -0
  142. package/dist/manifest-zrbrpKCC.mjs +1 -0
  143. package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
  144. package/dist/modules-p-PUNv9r.mjs +332 -0
  145. package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
  146. package/dist/network-BjZ1Y-GB.mjs +7 -0
  147. package/dist/outputPaths-BonGThuc.mjs +2 -0
  148. package/dist/parse-args-Cuk7-xUt.mjs +1 -0
  149. package/dist/platform-C446Lf97.mjs +93 -0
  150. package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
  151. package/dist/process-C9f2A5zk.mjs +962 -0
  152. package/dist/proxy-CvRepxgV.mjs +1 -0
  153. package/dist/registry-DUHIPE-v.mjs +1 -0
  154. package/dist/response-C7rKQst4.mjs +1 -0
  155. package/dist/search-defaults-D2bY-rzH.mjs +1 -0
  156. package/dist/server/plugin-api.mjs +1 -293
  157. package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
  158. package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
  159. package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
  160. package/dist/streaming-CTX58tbb.mjs +1 -0
  161. package/dist/tool-builder-CI9914Tf.mjs +1 -0
  162. package/dist/transform-Cv9P2vVD.mjs +103 -0
  163. package/dist/types-CuyefmGT.mjs +1 -0
  164. package/dist/types-DtThH00r.mjs +1 -0
  165. package/dist/wasm-DaJa8J0V.mjs +174 -0
  166. package/dist/webcrack-CsLLJIs9.mjs +46 -0
  167. package/dist/workflow-CYIXtrWD.mjs +101 -0
  168. package/package.json +50 -78
  169. package/dist/AntiCheatDetector-CqGDXmfc.mjs +0 -350
  170. package/dist/CacheAdapters-jJFy20G-.mjs +0 -80
  171. package/dist/CodeInjector-BdjRfNx7.mjs +0 -150
  172. package/dist/ConsoleMonitor-DykL3IAw.mjs +0 -2269
  173. package/dist/DarwinAPI-ETyy0xyo.mjs +0 -363
  174. package/dist/DetailedDataManager-HT49OrvF.mjs +0 -217
  175. package/dist/EventBus-DFKvADm3.mjs +0 -141
  176. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +0 -153
  177. package/dist/ExtensionManager-BDMsY2Dz.mjs +0 -721
  178. package/dist/FingerprintManager-BN4UQWnX.mjs +0 -96
  179. package/dist/HardwareBreakpoint-Cc2AFq1Y.mjs +0 -239
  180. package/dist/HeapAnalyzer-DruMgsgj.mjs +0 -284
  181. package/dist/InstrumentationSession-DLH0vd-z.mjs +0 -244
  182. package/dist/MemoryController-CMtviNW_.mjs +0 -167
  183. package/dist/MemoryScanSession-ITgb_NMi.mjs +0 -278
  184. package/dist/MemoryScanner-CiL7Z3ey.mjs +0 -428
  185. package/dist/NativeMemoryManager.impl-D9Lkovvn.mjs +0 -485
  186. package/dist/NativeMemoryManager.utils-BBlAixF5.mjs +0 -165
  187. package/dist/PEAnalyzer-DMQ44gen.mjs +0 -385
  188. package/dist/PageController-BPJNqqBN.mjs +0 -431
  189. package/dist/PointerChainEngine-K7wN8Z-w.mjs +0 -325
  190. package/dist/PrerequisiteError-TuyZIs6n.mjs +0 -20
  191. package/dist/ProcessRegistry-zGg12QbE.mjs +0 -74
  192. package/dist/ResponseBuilder-CJXWmWNw.mjs +0 -143
  193. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +0 -269
  194. package/dist/ScriptManager-ZuWD-0Jg.mjs +0 -3003
  195. package/dist/Speedhack-D-z0umeT.mjs +0 -156
  196. package/dist/StealthVerifier-BWmPgQsv.mjs +0 -135
  197. package/dist/StructureAnalyzer-Cav5AVSL.mjs +0 -429
  198. package/dist/ToolCatalog-5OJdMiF0.mjs +0 -582
  199. package/dist/ToolError-jh9whhMd.mjs +0 -15
  200. package/dist/ToolProbe-DbCFGyrg.mjs +0 -45
  201. package/dist/ToolRegistry-B9krbTtI.mjs +0 -180
  202. package/dist/ToolRouter.policy-BGDAGyeH.mjs +0 -344
  203. package/dist/TraceRecorder-B41Z5XBj.mjs +0 -1286
  204. package/dist/VersionDetector-K3V4vGsw.mjs +0 -104
  205. package/dist/Win32API-C2kjj0ze.mjs +0 -346
  206. package/dist/Win32Debug-CKrGOTpo.mjs +0 -274
  207. package/dist/WorkflowEngine-DJ6M4opp.mjs +0 -569
  208. package/dist/analysis-BHeJW2Nb.mjs +0 -1234
  209. package/dist/artifactRetention-CPXkUJXp.mjs +0 -598
  210. package/dist/artifacts-DkfosXH3.mjs +0 -59
  211. package/dist/authorization-schema-DRqyJMSk.mjs +0 -31
  212. package/dist/betterSqlite3-DLSBZodi.mjs +0 -74
  213. package/dist/binary-instrument--V3MAhJ4.mjs +0 -971
  214. package/dist/bind-helpers-ClV34xdn.mjs +0 -42
  215. package/dist/boringssl-inspector-Bo_LOLaS.mjs +0 -180
  216. package/dist/browser-Dx3_S2cG.mjs +0 -4369
  217. package/dist/capabilities-CcHlvWgK.mjs +0 -33
  218. package/dist/chunk-CjcI7cDX.mjs +0 -15
  219. package/dist/concurrency-Drev_Vz9.mjs +0 -41
  220. package/dist/constants-CDZLOoVv.mjs +0 -534
  221. package/dist/coordination-DgItD9DL.mjs +0 -259
  222. package/dist/debugger-RS3RSAqs.mjs +0 -1288
  223. package/dist/definitions-BEoYofW5.mjs +0 -47
  224. package/dist/definitions-BRaefg3u.mjs +0 -365
  225. package/dist/definitions-BbkvZkiv.mjs +0 -96
  226. package/dist/definitions-BtWSHJ3o.mjs +0 -17
  227. package/dist/definitions-C1gCHO0i.mjs +0 -43
  228. package/dist/definitions-CDOg_b-l.mjs +0 -138
  229. package/dist/definitions-CVPD9hzZ.mjs +0 -54
  230. package/dist/definitions-Cea8Lgl7.mjs +0 -94
  231. package/dist/definitions-DAgIyjxM.mjs +0 -10
  232. package/dist/definitions-DJA27nsL.mjs +0 -66
  233. package/dist/definitions-DKPFU3LW.mjs +0 -25
  234. package/dist/definitions-DPRpZQ96.mjs +0 -47
  235. package/dist/definitions-DUE5gmdn.mjs +0 -18
  236. package/dist/definitions-DYVjOtxa.mjs +0 -26
  237. package/dist/definitions-DcYLVLCo.mjs +0 -37
  238. package/dist/definitions-Pp5LI2H4.mjs +0 -27
  239. package/dist/definitions-j9KdHVNR.mjs +0 -14
  240. package/dist/definitions-uzkjBwa7.mjs +0 -258
  241. package/dist/definitions-va-AnLuQ.mjs +0 -28
  242. package/dist/encoding-DJeqHmpd.mjs +0 -1079
  243. package/dist/evidence-graph-bridge-DcYizFk2.mjs +0 -136
  244. package/dist/factory-C90tBff6.mjs +0 -575
  245. package/dist/flat-target-session-Dgax2Cy3.mjs +0 -29
  246. package/dist/formatAddress-nnMvEohD.mjs +0 -17
  247. package/dist/graphql-CoHrhweh.mjs +0 -1197
  248. package/dist/handlers-4jmR0nMs.mjs +0 -898
  249. package/dist/handlers-BAHPxcch.mjs +0 -789
  250. package/dist/handlers-BOs9b907.mjs +0 -2600
  251. package/dist/handlers-BWXEy6ef.mjs +0 -917
  252. package/dist/handlers-Bndn6QvE.mjs +0 -111
  253. package/dist/handlers-BqC4bD4s.mjs +0 -681
  254. package/dist/handlers-BtYq60bM2.mjs +0 -276
  255. package/dist/handlers-BzgcB4iv.mjs +0 -799
  256. package/dist/handlers-CRyRWj2b.mjs +0 -859
  257. package/dist/handlers-CVv2H1uq.mjs +0 -592
  258. package/dist/handlers-Dl5a7JS4.mjs +0 -572
  259. package/dist/handlers-Dx2d7jt7.mjs +0 -2537
  260. package/dist/handlers-HujRKC3b.mjs +0 -661
  261. package/dist/handlers.impl-XWXkQfyi.mjs +0 -807
  262. package/dist/hooks-B1B8NRHL.mjs +0 -898
  263. package/dist/logger-Dh_xb7_2.mjs +0 -93
  264. package/dist/maintenance-PRMkLVRW.mjs +0 -835
  265. package/dist/manifest-67Bok-Si.mjs +0 -58
  266. package/dist/manifest-6lNTMZAB2.mjs +0 -87
  267. package/dist/manifest-B2duEHiH.mjs +0 -90
  268. package/dist/manifest-B6EY9Vm8.mjs +0 -57
  269. package/dist/manifest-B6nKSbyY.mjs +0 -95
  270. package/dist/manifest-BL8AQNPF.mjs +0 -106
  271. package/dist/manifest-BSZvJJmV.mjs +0 -47
  272. package/dist/manifest-BU7qzUyX.mjs +0 -418
  273. package/dist/manifest-Bl62e8WK.mjs +0 -49
  274. package/dist/manifest-Bo5cXjdt.mjs +0 -82
  275. package/dist/manifest-BpS4gtUK.mjs +0 -1347
  276. package/dist/manifest-Bv65_e2W.mjs +0 -101
  277. package/dist/manifest-BytNIF4Z.mjs +0 -117
  278. package/dist/manifest-C-xtsjS3.mjs +0 -81
  279. package/dist/manifest-CDYl7OhA.mjs +0 -66
  280. package/dist/manifest-CRZ3xmkD.mjs +0 -61
  281. package/dist/manifest-CoW6u4Tp.mjs +0 -132
  282. package/dist/manifest-Cq5zN_8A.mjs +0 -50
  283. package/dist/manifest-D7YZM_2e.mjs +0 -194
  284. package/dist/manifest-DE_VrAeQ.mjs +0 -314
  285. package/dist/manifest-DGsXSCpT.mjs +0 -39
  286. package/dist/manifest-DJ2vfEuW.mjs +0 -156
  287. package/dist/manifest-DPXDYhEu.mjs +0 -80
  288. package/dist/manifest-Dd4fQb0a.mjs +0 -322
  289. package/dist/manifest-Deq6opGg.mjs +0 -223
  290. package/dist/manifest-DfJTafJK.mjs +0 -37
  291. package/dist/manifest-DgOdgN_j.mjs +0 -50
  292. package/dist/manifest-DlbMW4v4.mjs +0 -47
  293. package/dist/manifest-DmVfbH0w.mjs +0 -374
  294. package/dist/manifest-Dog6Ddjr.mjs +0 -109
  295. package/dist/manifest-DvgU5FWb.mjs +0 -58
  296. package/dist/manifest-HsfDBs7j.mjs +0 -50
  297. package/dist/manifest-I8oQHvCG.mjs +0 -186
  298. package/dist/manifest-NvH_a-av.mjs +0 -786
  299. package/dist/manifest-cEJU1v0Z.mjs +0 -129
  300. package/dist/manifest-wOl5XLB12.mjs +0 -112
  301. package/dist/modules-tZozf0LQ.mjs +0 -10635
  302. package/dist/mojo-ipc-DXNEXEqb.mjs +0 -640
  303. package/dist/network-CPVvwvFg.mjs +0 -3852
  304. package/dist/outputPaths-um7lCRY3.mjs +0 -1141
  305. package/dist/parse-args-B4cY5Vx5.mjs +0 -39
  306. package/dist/platform-CYeFoTWp.mjs +0 -2161
  307. package/dist/process-BTbgcVc6.mjs +0 -1306
  308. package/dist/proxy-r8YN6nP1.mjs +0 -192
  309. package/dist/registry-Bl8ZQW61.mjs +0 -34
  310. package/dist/response-CWhh2aLo.mjs +0 -34
  311. package/dist/shared-state-board-BoZnSoj-.mjs +0 -586
  312. package/dist/sourcemap-BIDHUVXy.mjs +0 -934
  313. package/dist/ssrf-policy-Dsqd-DTX.mjs +0 -166
  314. package/dist/streaming-Dal6utPp.mjs +0 -725
  315. package/dist/tool-builder-BHJp32mV.mjs +0 -186
  316. package/dist/transform-DRVgGG90.mjs +0 -1011
  317. package/dist/types-Bx92KJfT.mjs +0 -4
  318. package/dist/types-DDBWs9UP.mjs +0 -37
  319. package/dist/wasm-BYx5UOeG.mjs +0 -1044
  320. package/dist/webcrack-Be0_FccV.mjs +0 -747
  321. package/dist/workflow-BpuKEtvn.mjs +0 -725
@@ -1,1044 +0,0 @@
1
- import { Cr as WASM_BITWISE_OPS_THRESHOLD, Dr as WASM_VM_DISPATCH_MIN_LOOPS, Er as WASM_TOOL_TIMEOUT_MS, Tr as WASM_OPTIMIZE_TIMEOUT_MS, wr as WASM_DEAD_CODE_MIN_MATCHES } from "./constants-CDZLOoVv.mjs";
2
- import { o as ExternalToolRunner } from "./modules-tZozf0LQ.mjs";
3
- import { i as resolveArtifactPath } from "./artifacts-DkfosXH3.mjs";
4
- import { a as argString, o as argStringArray, r as argNumber, s as argStringRequired, t as argBool } from "./parse-args-B4cY5Vx5.mjs";
5
- import { n as capabilityReport } from "./capabilities-CcHlvWgK.mjs";
6
- import { t as ToolRegistry } from "./ToolRegistry-B9krbTtI.mjs";
7
- import { t as R } from "./ResponseBuilder-CJXWmWNw.mjs";
8
- import "./definitions-BEoYofW5.mjs";
9
- import { tmpdir } from "node:os";
10
- import { createHash } from "node:crypto";
11
- import { join, normalize, resolve, sep } from "node:path";
12
- import { mkdir, stat, writeFile } from "node:fs/promises";
13
- //#region src/server/domains/wasm/handlers/shared.ts
14
- /**
15
- * Shared types and state for WASM sub-handlers.
16
- */
17
- const isRecord = (value) => typeof value === "object" && value !== null;
18
- const hasErrorResult = (value) => isRecord(value) && typeof value.error === "string";
19
- function validateOutputPath(outputPath) {
20
- const safe = resolve(outputPath);
21
- const cwd = normalize(process.cwd());
22
- const tmp = normalize(tmpdir());
23
- if (!safe.startsWith(`${cwd}${sep}`) && !safe.startsWith(`${tmp}${sep}`)) throw new Error("Path traversal blocked: outputPath must be under project root or temp directory");
24
- return safe;
25
- }
26
- //#endregion
27
- //#region src/server/domains/wasm/handlers/external-base.ts
28
- var ExternalToolHandlersBase = class {
29
- constructor(state) {
30
- this.state = state;
31
- }
32
- ok(payload) {
33
- return { content: [{
34
- type: "text",
35
- text: JSON.stringify({
36
- success: true,
37
- ...payload
38
- }, null, 2)
39
- }] };
40
- }
41
- fail(error, exitCode) {
42
- return { content: [{
43
- type: "text",
44
- text: JSON.stringify({
45
- success: false,
46
- error,
47
- ...exitCode === void 0 ? {} : { exitCode }
48
- }, null, 2)
49
- }] };
50
- }
51
- async writeTextArtifact(options) {
52
- const { outputPath, artifact, content, pathMode = "display" } = options;
53
- if (outputPath) {
54
- const safePath = validateOutputPath(outputPath);
55
- await writeFile(safePath, content, "utf-8");
56
- return safePath;
57
- }
58
- const { absolutePath, displayPath } = await resolveArtifactPath(artifact);
59
- await writeFile(absolutePath, content, "utf-8");
60
- return pathMode === "absolute" ? absolutePath : displayPath;
61
- }
62
- async resolveArtifactOutputPath(options) {
63
- const { outputPath, artifact, pathMode = "absolute" } = options;
64
- if (outputPath) return validateOutputPath(outputPath);
65
- const { absolutePath, displayPath } = await resolveArtifactPath(artifact);
66
- return pathMode === "display" ? displayPath : absolutePath;
67
- }
68
- preview(text, maxLines) {
69
- const lines = text.split("\n");
70
- return lines.slice(0, maxLines).join("\n") + (lines.length > maxLines ? "\n... (truncated)" : "");
71
- }
72
- async tryStatSize(path) {
73
- try {
74
- return (await stat(path)).size;
75
- } catch {
76
- return 0;
77
- }
78
- }
79
- };
80
- //#endregion
81
- //#region src/server/domains/wasm/handlers/external-analysis-handlers.ts
82
- function isExplicitLocalFilePath(input) {
83
- return /^[a-z]:[\\/]/i.test(input) || /^\\\\[^\\]+\\[^\\]+/i.test(input) || /^file:\/\//i.test(input) || /^\/(?:Users|home|tmp|var|etc|opt|usr|srv|mnt|media|private|root|run|dev|proc|sys|Library|Volumes)(?:\/|$)/.test(input);
84
- }
85
- var ExternalAnalysisHandlers = class extends ExternalToolHandlersBase {
86
- async handleWasmDetectObfuscation(args) {
87
- const inputPath = argStringRequired(args, "inputPath");
88
- const verbose = argBool(args, "verbose", false);
89
- const disasmResult = await this.state.runner.run({
90
- tool: "wabt.wasm2wat",
91
- args: [inputPath],
92
- timeoutMs: WASM_TOOL_TIMEOUT_MS
93
- });
94
- if (!disasmResult.ok) return this.fail(`Failed to disassemble: ${disasmResult.stderr}`);
95
- const wat = disasmResult.stdout;
96
- const detections = [];
97
- const brTableCount = (wat.match(/br_table/g) || []).length;
98
- if (brTableCount > 5) detections.push({
99
- type: "control-flow-flattening",
100
- confidence: Math.min(brTableCount / 20, .95),
101
- description: `${brTableCount} br_table dispatches detected — likely flattened control flow`
102
- });
103
- const xorChainCount = (wat.match(/i32\.xor/g) || []).length;
104
- const rotCount = (wat.match(/i32\.rotl|i32\.rotr/g) || []).length;
105
- const shiftCount = (wat.match(/i32\.shl|i32\.shr_[su]/g) || []).length;
106
- if (xorChainCount + rotCount + shiftCount > WASM_BITWISE_OPS_THRESHOLD) detections.push({
107
- type: "constant-encoding",
108
- confidence: Math.min((xorChainCount + rotCount + shiftCount) / 50, .9),
109
- description: `High density of bitwise ops (${xorChainCount} xor, ${shiftCount} shift, ${rotCount} rotate) — constant decoding`
110
- });
111
- const deadCodeMatches = wat.match(/br\s+(?:\$\d+|\d+)\s*\n\s*(?!end\b|\))\S.*$/gm) || [];
112
- if (deadCodeMatches.length > WASM_DEAD_CODE_MIN_MATCHES) detections.push({
113
- type: "dead-code-injection",
114
- confidence: Math.min(deadCodeMatches.length / 30, .85),
115
- description: `${deadCodeMatches.length} code blocks after unconditional branches`
116
- });
117
- const hasLoop = /\(loop/.test(wat);
118
- const hasBrTable = /br_table/.test(wat);
119
- const hasLocalGet = /local\.get\s+\d+/.test(wat);
120
- if (hasLoop && hasBrTable && hasLocalGet) {
121
- const loopCount = (wat.match(/\(loop/g) || []).length;
122
- if (loopCount > WASM_VM_DISPATCH_MIN_LOOPS) detections.push({
123
- type: "vm-dispatch",
124
- confidence: .75,
125
- description: `Loop + br_table + local.get pattern (${loopCount} loops) — possible WASM VM interpreter`
126
- });
127
- }
128
- const funcCount = (wat.match(/\(func\s/g) || []).length;
129
- const totalSize = wat.length;
130
- if (funcCount > 0 && totalSize / funcCount > 5e3) detections.push({
131
- type: "code-bloat",
132
- confidence: .5,
133
- description: `Average ${(totalSize / funcCount).toFixed(0)} chars/function across ${funcCount} functions — unusually large`
134
- });
135
- const hasObfuscation = detections.length > 0;
136
- const maxConfidence = detections.reduce((max, detection) => Math.max(max, detection.confidence), 0);
137
- return this.ok({
138
- inputPath,
139
- hasObfuscation,
140
- overallConfidence: hasObfuscation ? maxConfidence : 0,
141
- detectionCount: detections.length,
142
- detections,
143
- summary: hasObfuscation ? `Detected ${detections.length} obfuscation pattern(s). Highest confidence: ${(maxConfidence * 100).toFixed(0)}%` : "No obfuscation patterns detected.",
144
- ...verbose ? { watPreview: this.preview(wat, 200) } : {}
145
- });
146
- }
147
- async handleWasmInstrumentTrace(args) {
148
- const inputPath = argStringRequired(args, "inputPath");
149
- const allHooks = argBool(args, "allHooks", true);
150
- const hookTypes = argStringArray(args, "hooks");
151
- const outputPath = argString(args, "outputPath");
152
- const disasmResult = await this.state.runner.run({
153
- tool: "wabt.wasm2wat",
154
- args: [inputPath],
155
- timeoutMs: WASM_TOOL_TIMEOUT_MS
156
- });
157
- if (!disasmResult.ok) return this.fail(disasmResult.stderr);
158
- const wat = disasmResult.stdout;
159
- const hooks = allHooks ? [
160
- "call",
161
- "memory",
162
- "branch",
163
- "loop",
164
- "local"
165
- ] : hookTypes.length > 0 ? hookTypes : ["call"];
166
- const funcMatches = wat.match(/\(func\s/g) || [];
167
- const exportMatches = wat.match(/\(export/g) || [];
168
- const importMatches = wat.match(/\(import/g) || [];
169
- const tableMatches = wat.match(/\(table\b/g) || [];
170
- const callIndirectMatches = wat.match(/\bcall_indirect\b/g) || [];
171
- const exportNames = [];
172
- const importEntries = [];
173
- const exportRe = /\(export\s+"([^"]+)"\s+\((\w+)\s+(\$?[\w.]+)\)\)/g;
174
- const importRe = /\(import\s+"([^"]+)"\s+"([^"]+)"/g;
175
- let match;
176
- while ((match = exportRe.exec(wat)) !== null) if (match[1]) exportNames.push(match[1]);
177
- while ((match = importRe.exec(wat)) !== null) if (match[1] && match[2]) importEntries.push({
178
- module: match[1],
179
- name: match[2]
180
- });
181
- const hookPreamble = `
182
- const hookedExports = {};
183
- for (const [k, v] of Object.entries(instance.exports)) { hookedExports[k] = v; }`;
184
- const hookInitCode = {
185
- call: `
186
- const callLog = [];
187
- for (const [name, value] of Object.entries(instance.exports)) {
188
- if (typeof value === 'function') {
189
- hookedExports[name] = new Proxy(value, {
190
- apply(target, thisArg, argumentsList) {
191
- const entry = { type: 'call', name, args: argumentsList.map(String), timestamp: Date.now() };
192
- callLog.push(entry);
193
- try {
194
- const result = Reflect.apply(target, thisArg, argumentsList);
195
- callLog.push({ type: 'return', name, result: String(result), timestamp: Date.now() });
196
- return result;
197
- } catch (err) {
198
- callLog.push({ type: 'throw', name, error: String(err), timestamp: Date.now() });
199
- throw err;
200
- }
201
- }
202
- });
203
- }
204
- }`,
205
- memory: `
206
- const memoryLog = [];
207
- const originalMemory = instance.exports.memory || Object.values(instance.exports).find(e => e instanceof WebAssembly.Memory);
208
- const memTracker = { reads: 0, writes: 0, growEvents: [] };
209
- if (originalMemory) {
210
- const memSnapshot = () => {
211
- const view = new DataView(originalMemory.buffer);
212
- return { byteLength: view.byteLength, pages: view.byteLength / 65536 };
213
- };
214
- memTracker.snapshot = memSnapshot;
215
- const origGrow = originalMemory.grow?.bind(originalMemory);
216
- if (origGrow) {
217
- originalMemory.grow = function(delta) {
218
- const beforePages = originalMemory.buffer.byteLength / 65536;
219
- memoryLog.push({ op: 'grow', delta, beforePages, timestamp: Date.now() });
220
- memTracker.growEvents.push({ delta, beforePages });
221
- return origGrow(delta);
222
- };
223
- }
224
- const memProxy = new Proxy(originalMemory, {
225
- get(target, prop) {
226
- if (prop === 'buffer') {
227
- memTracker.reads++;
228
- }
229
- const val = Reflect.get(target, prop, target);
230
- return typeof val === 'function' ? val.bind(target) : val;
231
- }
232
- });
233
- const memExportName = Object.entries(instance.exports).find(([, v]) => v === originalMemory)?.[0] || 'memory';
234
- hookedExports[memExportName] = memProxy;
235
- memTracker.buffer = originalMemory.buffer;
236
- }`,
237
- branch: `
238
- // === Branch Hook: Tracks JS-visible WebAssembly.Table access only ===
239
- // Internal call_indirect dispatch stays inside the Wasm engine and is not observable from JS.
240
- const branchLog = [];
241
- for (const [tableName, table] of Object.entries(instance.exports)) {
242
- if (!(table instanceof WebAssembly.Table)) continue;
243
- const origGet = table.get.bind(table);
244
- const origGrow = table.grow?.bind(table);
245
- hookedExports[tableName] = new Proxy(table, {
246
- get(t, prop) {
247
- if (prop === 'get') {
248
- return (idx) => {
249
- branchLog.push({ type: 'table_get', table: tableName, index: idx, timestamp: Date.now() });
250
- return origGet(idx);
251
- };
252
- }
253
- if (prop === 'grow' && origGrow) {
254
- return (delta) => {
255
- branchLog.push({ type: 'table_grow', table: tableName, delta, timestamp: Date.now() });
256
- return origGrow(delta);
257
- };
258
- }
259
- const val = t[prop];
260
- return typeof val === 'function' ? val.bind(t) : val;
261
- }
262
- });
263
- }`,
264
- loop: `
265
- const loopLog = [];
266
- const loopCallCounts = {};
267
- const loopSource = hookedExports;
268
- for (const [name, value] of Object.entries(loopSource)) {
269
- if (typeof value === 'function') {
270
- hookedExports[name] = new Proxy(value, {
271
- apply(target, thisArg, args) {
272
- loopCallCounts[name] = (loopCallCounts[name] || 0) + 1;
273
- if (loopCallCounts[name] > 1) {
274
- loopLog.push({ type: 'loop-iteration', func: name, count: loopCallCounts[name], timestamp: Date.now() });
275
- }
276
- return Reflect.apply(target, thisArg, args);
277
- }
278
- });
279
- }
280
- }`,
281
- local: `
282
- const localLog = [];
283
- for (const [globalName, global] of Object.entries(instance.exports)) {
284
- if (!(global instanceof WebAssembly.Global)) continue;
285
- hookedExports[globalName] = new Proxy(global, {
286
- get(target, prop) {
287
- if (prop === 'valueOf' || prop === Symbol.toPrimitive) {
288
- return (...args) => Reflect.apply(target.valueOf, target, args);
289
- }
290
- const val = Reflect.get(target, prop, target);
291
- if (prop === 'value' && typeof val === 'function') {
292
- return target.valueOf();
293
- }
294
- return typeof val === 'function' ? val.bind(target) : val;
295
- },
296
- set(target, prop, newValue) {
297
- if (prop === 'value') {
298
- const oldValue = target.valueOf();
299
- localLog.push({ type: 'global-set', name: globalName, oldValue, newValue, timestamp: Date.now() });
300
- target.value = newValue;
301
- return true;
302
- }
303
- return Reflect.set(target, prop, newValue, target);
304
- }
305
- });
306
- }`
307
- };
308
- const activeHooks = hooks.filter((hook) => hook in hookInitCode);
309
- const activeHookCode = hookPreamble + "\n" + activeHooks.map((hook) => hookInitCode[hook]).join("\n");
310
- const inputPathLiteral = JSON.stringify(inputPath);
311
- const importNamespaceCode = [...new Set(importEntries.map(({ module }) => module))].filter((moduleName) => moduleName !== "env").map((moduleName) => ` ${JSON.stringify(moduleName)}: {},`).join("\n");
312
- const importStubCode = importEntries.map(({ module, name }) => {
313
- const safeModule = JSON.stringify(module);
314
- const safeName = JSON.stringify(name);
315
- return `if (!imports[${safeModule}]) imports[${safeModule}] = {};\n if (!imports[${safeModule}][${safeName}]) imports[${safeModule}][${safeName}] = () => {};`;
316
- }).join("\n ");
317
- const wrapper = `// WASM Instrumentation Wrapper (Wasabi-style)
318
- // Generated by jshookmcp wasm_instrument_trace
319
- // Hooks: ${activeHooks.join(", ")}
320
- // Functions: ${funcMatches.length} | Exports: ${exportNames.join(", ") || "none"} | Imports: ${importEntries.length}
321
-
322
- (async function() {
323
- const wasmBytes = await fetch(${inputPathLiteral}).then(r => r.arrayBuffer());
324
- const module = await WebAssembly.compile(wasmBytes);
325
-
326
- const imports = {
327
- env: {
328
- abort: () => console.warn('[wasabi] abort called'),
329
- memory: new WebAssembly.Memory({ initial: 256, maximum: 1024 }),
330
- seed: () => Math.random(),
331
- 'Math.log': Math.log,
332
- 'Math.random': Math.random,
333
- console: { log: (...a) => console.log('[wasabi]', ...a) },
334
- },
335
- ${importNamespaceCode ? `${importNamespaceCode}\n` : ""} };
336
-
337
- ${importStubCode}
338
-
339
- const instance = await WebAssembly.instantiate(module, imports);
340
-
341
- ${activeHookCode}
342
-
343
- const tracedExports = hookedExports;
344
-
345
- return {
346
- instance,
347
- exports: tracedExports,
348
- hooks: {
349
- ${activeHooks.map((hook) => {
350
- return ` ${hook}: ${hook === "call" ? "callLog" : hook === "memory" ? "memoryLog" : hook === "branch" ? "branchLog" : hook === "loop" ? "loopLog" : "localLog"}`;
351
- }).join(",\n")}
352
- },
353
- stats: {
354
- functions: ${funcMatches.length},
355
- exports: ${exportMatches.length},
356
- imports: ${importMatches.length},
357
- exportNames: ${JSON.stringify(exportNames)},
358
- hookTypes: ${JSON.stringify(activeHooks)}
359
- }
360
- };
361
- })();
362
- `;
363
- let savedPath;
364
- if (outputPath) {
365
- const safePath = validateOutputPath(outputPath);
366
- await writeFile(safePath, wrapper, "utf-8");
367
- savedPath = safePath;
368
- } else savedPath = await this.writeTextArtifact({
369
- artifact: {
370
- category: "wasm",
371
- toolName: "wasm-instrument",
372
- ext: "js"
373
- },
374
- content: wrapper
375
- });
376
- const inputPathLooksLocal = isExplicitLocalFilePath(inputPath);
377
- const warnings = [inputPathLooksLocal ? "Wrapper embeds the provided inputPath into browser-side fetch(). Local filesystem paths are not browser-accessible; provide an http(s) URL instead, or upload the module with wasm_dump and use the resulting URL." : void 0, activeHooks.includes("branch") && callIndirectMatches.length > 0 ? `Branch hook only observes JS-visible WebAssembly.Table access. This module contains ${callIndirectMatches.length} call_indirect site(s), which are dispatched inside the Wasm engine and will not appear in branch logs.` : void 0].filter((warning) => typeof warning === "string" && warning.length > 0);
378
- const warning = warnings.length > 0 ? warnings.join(" ") : void 0;
379
- return this.ok({
380
- artifactPath: savedPath,
381
- hookTypes: activeHooks,
382
- functionCount: funcMatches.length,
383
- exportCount: exportMatches.length,
384
- importCount: importMatches.length,
385
- wrapperSizeBytes: wrapper.length,
386
- note: "Wasabi-style instrumentation wrapper generated. Load in browser with WASM module to trace execution.",
387
- metadata: {
388
- inputPathKind: inputPathLooksLocal ? "local-path" : "url",
389
- wrapperFetchesBrowserUrl: true,
390
- ...activeHooks.includes("branch") ? {
391
- branchHookMode: "js-table-access-only",
392
- callIndirectSites: callIndirectMatches.length,
393
- tableCount: tableMatches.length
394
- } : {}
395
- },
396
- ...warning ? { warning } : {}
397
- });
398
- }
399
- };
400
- //#endregion
401
- //#region src/server/domains/wasm/handlers/external-conversion-handlers.ts
402
- var ExternalConversionHandlers = class extends ExternalToolHandlersBase {
403
- async handleWasmDisassemble(args) {
404
- const inputPath = argStringRequired(args, "inputPath");
405
- const outputPath = argString(args, "outputPath");
406
- const foldExprs = argBool(args, "foldExprs", true);
407
- const toolArgs = [
408
- inputPath,
409
- "-o",
410
- "/dev/stdout"
411
- ];
412
- if (foldExprs) toolArgs.push("--fold-exprs");
413
- const result = await this.state.runner.run({
414
- tool: "wabt.wasm2wat",
415
- args: toolArgs,
416
- timeoutMs: WASM_TOOL_TIMEOUT_MS
417
- });
418
- if (!result.ok) return this.fail(result.stderr, result.exitCode ?? void 0);
419
- const savedPath = await this.writeTextArtifact({
420
- outputPath,
421
- artifact: {
422
- category: "wasm",
423
- toolName: "wasm-disassemble",
424
- ext: "wat"
425
- },
426
- content: result.stdout
427
- });
428
- return this.ok({
429
- artifactPath: savedPath,
430
- totalLines: result.stdout.split("\n").length,
431
- sizeBytes: result.stdout.length,
432
- preview: this.preview(result.stdout, 50),
433
- durationMs: result.durationMs
434
- });
435
- }
436
- async handleWasmDecompile(args) {
437
- const inputPath = argStringRequired(args, "inputPath");
438
- const outputPath = argString(args, "outputPath");
439
- const result = await this.state.runner.run({
440
- tool: "wabt.wasm-decompile",
441
- args: [
442
- inputPath,
443
- "-o",
444
- "/dev/stdout"
445
- ],
446
- timeoutMs: WASM_TOOL_TIMEOUT_MS
447
- });
448
- if (!result.ok) return this.fail(result.stderr, result.exitCode ?? void 0);
449
- const savedPath = await this.writeTextArtifact({
450
- outputPath,
451
- artifact: {
452
- category: "wasm",
453
- toolName: "wasm-decompile",
454
- ext: "dcmp"
455
- },
456
- content: result.stdout
457
- });
458
- return this.ok({
459
- artifactPath: savedPath,
460
- totalLines: result.stdout.split("\n").length,
461
- preview: this.preview(result.stdout, 60),
462
- durationMs: result.durationMs
463
- });
464
- }
465
- async handleWasmInspectSections(args) {
466
- const inputPath = argStringRequired(args, "inputPath");
467
- const flags = ({
468
- headers: "-h",
469
- details: "-x",
470
- disassemble: "-d",
471
- all: "-h -x -d"
472
- }[argString(args, "sections", "details")] || "-x").split(" ");
473
- const result = await this.state.runner.run({
474
- tool: "wabt.wasm-objdump",
475
- args: [...flags, inputPath],
476
- timeoutMs: WASM_TOOL_TIMEOUT_MS
477
- });
478
- if (!result.ok) return this.fail(result.stderr, result.exitCode ?? void 0);
479
- return this.ok({
480
- totalLines: result.stdout.split("\n").length,
481
- preview: this.preview(result.stdout, 100),
482
- durationMs: result.durationMs
483
- });
484
- }
485
- async handleWasmToC(args) {
486
- const inputPath = argStringRequired(args, "inputPath");
487
- const outputDir = argString(args, "outputDir");
488
- const destDir = await this.resolveArtifactOutputPath({
489
- outputPath: outputDir,
490
- artifact: {
491
- category: "wasm",
492
- toolName: "wasm2c",
493
- ext: "dir"
494
- },
495
- pathMode: "absolute"
496
- });
497
- await mkdir(destDir, { recursive: true });
498
- const nameOnly = resolve(inputPath).replace(/\.wasm$/i, "").split(/[/\\]/).pop() || "output";
499
- const cFile = join(destDir, `${nameOnly}.c`);
500
- const hFile = join(destDir, `${nameOnly}.h`);
501
- const result = await this.state.runner.run({
502
- tool: "wabt.wasm2c",
503
- args: [
504
- inputPath,
505
- "-o",
506
- cFile
507
- ],
508
- timeoutMs: WASM_TOOL_TIMEOUT_MS
509
- });
510
- if (!result.ok) return this.fail(result.stderr, result.exitCode ?? void 0);
511
- return this.ok({
512
- outputDir: destDir,
513
- cFile,
514
- hFile,
515
- cSizeBytes: await this.tryStatSize(cFile),
516
- hSizeBytes: await this.tryStatSize(hFile),
517
- durationMs: result.durationMs
518
- });
519
- }
520
- };
521
- //#endregion
522
- //#region src/server/domains/wasm/handlers/external-runtime-handlers.ts
523
- var ExternalRuntimeHandlers = class extends ExternalToolHandlersBase {
524
- async handleWasmOfflineRun(args) {
525
- const inputPath = argStringRequired(args, "inputPath");
526
- const functionName = argStringRequired(args, "functionName");
527
- const fnArgs = argStringArray(args, "args");
528
- const runtime = argString(args, "runtime", "auto");
529
- const timeoutMs = argNumber(args, "timeoutMs", 1e4);
530
- let toolName;
531
- if (runtime === "auto") {
532
- const probes = await this.state.runner.probeAll();
533
- if (probes["runtime.wasmtime"]?.available) toolName = "runtime.wasmtime";
534
- else if (probes["runtime.wasmer"]?.available) toolName = "runtime.wasmer";
535
- else return this.fail("No WASM runtime found. Install wasmtime or wasmer.");
536
- } else toolName = runtime === "wasmer" ? "runtime.wasmer" : "runtime.wasmtime";
537
- const runArgs = toolName === "runtime.wasmtime" ? [
538
- "run",
539
- "--invoke",
540
- functionName,
541
- inputPath,
542
- ...fnArgs
543
- ] : [
544
- "run",
545
- inputPath,
546
- "--invoke",
547
- functionName,
548
- "--",
549
- ...fnArgs
550
- ];
551
- const result = await this.state.runner.run({
552
- tool: toolName,
553
- args: runArgs,
554
- timeoutMs
555
- });
556
- return this.ok({
557
- runtime: toolName,
558
- functionName,
559
- args: fnArgs,
560
- output: result.stdout.trim(),
561
- stderr: result.stderr.trim() || void 0,
562
- exitCode: result.exitCode,
563
- durationMs: result.durationMs,
564
- success: result.ok
565
- });
566
- }
567
- async handleWasmOptimize(args) {
568
- const inputPath = argStringRequired(args, "inputPath");
569
- const outputPath = argString(args, "outputPath");
570
- const level = argString(args, "level", "O2");
571
- const destPath = await this.resolveArtifactOutputPath({
572
- outputPath,
573
- artifact: {
574
- category: "wasm",
575
- toolName: "wasm-opt",
576
- ext: "wasm"
577
- },
578
- pathMode: "absolute"
579
- });
580
- const result = await this.state.runner.run({
581
- tool: "binaryen.wasm-opt",
582
- args: [
583
- `-${level}`,
584
- inputPath,
585
- "-o",
586
- destPath
587
- ],
588
- timeoutMs: WASM_OPTIMIZE_TIMEOUT_MS
589
- });
590
- if (!result.ok) return this.fail(result.stderr, result.exitCode ?? void 0);
591
- const inputSize = await this.tryStatSize(inputPath);
592
- const outputSize = await this.tryStatSize(destPath);
593
- return this.ok({
594
- artifactPath: destPath,
595
- optimizationLevel: level,
596
- inputSizeBytes: inputSize,
597
- outputSizeBytes: outputSize,
598
- reductionPercent: inputSize > 0 ? ((1 - outputSize / inputSize) * 100).toFixed(1) : "0",
599
- durationMs: result.durationMs
600
- });
601
- }
602
- };
603
- //#endregion
604
- //#region src/server/domains/wasm/handlers/external-tool-handlers.ts
605
- var ExternalToolHandlers = class {
606
- conversion;
607
- runtime;
608
- analysis;
609
- constructor(state) {
610
- this.conversion = new ExternalConversionHandlers(state);
611
- this.runtime = new ExternalRuntimeHandlers(state);
612
- this.analysis = new ExternalAnalysisHandlers(state);
613
- }
614
- handleWasmDisassemble(args) {
615
- return this.conversion.handleWasmDisassemble(args);
616
- }
617
- handleWasmDecompile(args) {
618
- return this.conversion.handleWasmDecompile(args);
619
- }
620
- handleWasmInspectSections(args) {
621
- return this.conversion.handleWasmInspectSections(args);
622
- }
623
- handleWasmOfflineRun(args) {
624
- return this.runtime.handleWasmOfflineRun(args);
625
- }
626
- handleWasmOptimize(args) {
627
- return this.runtime.handleWasmOptimize(args);
628
- }
629
- handleWasmToC(args) {
630
- return this.conversion.handleWasmToC(args);
631
- }
632
- handleWasmDetectObfuscation(args) {
633
- return this.analysis.handleWasmDetectObfuscation(args);
634
- }
635
- handleWasmInstrumentTrace(args) {
636
- return this.analysis.handleWasmInstrumentTrace(args);
637
- }
638
- };
639
- //#endregion
640
- //#region src/server/domains/wasm/handlers/browser-handlers.ts
641
- /**
642
- * Browser sub-handler — dump, vmpTrace, memoryInspect.
643
- */
644
- var BrowserHandlers = class {
645
- state;
646
- constructor(state) {
647
- this.state = state;
648
- }
649
- async handleWasmDump(args) {
650
- const moduleIndex = argNumber(args, "moduleIndex", 0);
651
- const outputPath = argString(args, "outputPath");
652
- const page = await this.state.collector.getActivePage();
653
- const result = await page.evaluate((idx) => {
654
- const hooksRaw = window.__aiHooks?.["preset-webassembly-full"];
655
- if (!Array.isArray(hooksRaw) || hooksRaw.length === 0) return { error: "No WASM modules captured. Ensure the webassembly-full hook preset is active and the page has loaded WASM." };
656
- const instantiatedEvents = hooksRaw.filter((e) => e.type === "instantiated");
657
- if (idx >= instantiatedEvents.length) return { error: `Module index ${idx} out of range. Found ${instantiatedEvents.length} instantiated modules.` };
658
- const event = instantiatedEvents[idx];
659
- return {
660
- exports: event.exports,
661
- importMods: event.importMods,
662
- size: event.size,
663
- moduleCount: instantiatedEvents.length
664
- };
665
- }, moduleIndex);
666
- if (hasErrorResult(result)) return { content: [{
667
- type: "text",
668
- text: JSON.stringify({
669
- success: false,
670
- error: result.error
671
- })
672
- }] };
673
- const wasmBytes = await page.evaluate((idx) => {
674
- const storage = window.__wasmModuleStorage;
675
- if (!storage?.[idx]) return null;
676
- const buffer = storage[idx];
677
- return Array.from(new Uint8Array(buffer));
678
- }, moduleIndex);
679
- let savedPath;
680
- let hash;
681
- if (wasmBytes) {
682
- const buffer = Buffer.from(wasmBytes);
683
- hash = createHash("sha256").update(buffer).digest("hex").substring(0, 16);
684
- if (outputPath) {
685
- const safePath = validateOutputPath(outputPath);
686
- await writeFile(safePath, buffer);
687
- savedPath = safePath;
688
- } else {
689
- const { absolutePath, displayPath } = await resolveArtifactPath({
690
- category: "wasm",
691
- toolName: "wasm-dump",
692
- target: hash,
693
- ext: "wasm"
694
- });
695
- await writeFile(absolutePath, buffer);
696
- savedPath = displayPath;
697
- }
698
- } else savedPath = "(binary not available — hook did not store raw bytes)";
699
- return { content: [{
700
- type: "text",
701
- text: JSON.stringify({
702
- success: true,
703
- artifactPath: savedPath,
704
- hash,
705
- size: result.size,
706
- exports: result.exports,
707
- importModules: result.importMods,
708
- totalModules: result.moduleCount,
709
- hint: wasmBytes ? "Use wasm_disassemble or wasm_decompile on the dumped file for further analysis." : "Binary not captured. Inject hook_preset(\"webassembly-full\") BEFORE page navigation, with window.__wasmModuleStorage patching."
710
- }, null, 2)
711
- }] };
712
- }
713
- async handleWasmVmpTrace(args) {
714
- const maxEvents = argNumber(args, "maxEvents", 5e3);
715
- const filterModule = argString(args, "filterModule");
716
- const traceData = await (await this.state.collector.getActivePage()).evaluate((opts) => {
717
- const hooksRaw = window.__aiHooks?.["preset-webassembly-full"];
718
- if (!Array.isArray(hooksRaw) || hooksRaw.length === 0) return { error: "No WASM hook data. Inject hook_preset(\"webassembly-full\") and reload the page." };
719
- let importCalls = hooksRaw.filter((e) => e.type === "import_call");
720
- if (opts.filterModule) importCalls = importCalls.filter((e) => e.mod === opts.filterModule);
721
- const limited = importCalls.slice(0, opts.maxEvents);
722
- const fnCounts = {};
723
- for (const call of limited) {
724
- const key = `${String(call.mod)}.${String(call.fn)}`;
725
- fnCounts[key] = (fnCounts[key] || 0) + 1;
726
- }
727
- const sorted = Object.entries(fnCounts).toSorted((a, b) => b[1] - a[1]).slice(0, 30).map(([name, count]) => ({
728
- name,
729
- count
730
- }));
731
- return {
732
- totalEvents: importCalls.length,
733
- capturedEvents: limited.length,
734
- topFunctions: sorted,
735
- trace: limited.slice(0, 200).map((e) => ({
736
- mod: e.mod,
737
- fn: e.fn,
738
- args: e.args,
739
- ts: e.ts
740
- }))
741
- };
742
- }, {
743
- maxEvents,
744
- filterModule
745
- });
746
- if (hasErrorResult(traceData)) return { content: [{
747
- type: "text",
748
- text: JSON.stringify({
749
- success: false,
750
- error: traceData.error
751
- })
752
- }] };
753
- return { content: [{
754
- type: "text",
755
- text: JSON.stringify({
756
- success: true,
757
- ...traceData,
758
- hint: "Top functions show VMP handler dispatch patterns. Use wasm_disassemble to analyze their implementation."
759
- }, null, 2)
760
- }] };
761
- }
762
- async handleWasmMemoryInspect(args) {
763
- const offset = argNumber(args, "offset", 0);
764
- const length = Math.min(argNumber(args, "length", 256), 65536);
765
- const format = argString(args, "format", "both");
766
- const searchPattern = argString(args, "searchPattern");
767
- const memData = await (await this.state.collector.getActivePage()).evaluate((opts) => {
768
- const win = window;
769
- const hooksRaw = win.__aiHooks?.["preset-webassembly-full"];
770
- const memoryEvents = (Array.isArray(hooksRaw) ? hooksRaw : []).filter((e) => e.type === "memory_created");
771
- const instances = win.__wasmInstances;
772
- if (!Array.isArray(instances) || instances.length === 0) return { error: "No WASM memory available. Ensure the webassembly-full hook is active and a WASM module is instantiated." };
773
- try {
774
- const memory = instances[0].exports?.memory;
775
- if (!memory?.buffer) return { error: "WASM module has no exported memory." };
776
- const buffer = new Uint8Array(memory.buffer);
777
- const slice = Array.from(buffer.slice(opts.offset, opts.offset + opts.length));
778
- let searchResults;
779
- if (opts.searchPattern) {
780
- searchResults = [];
781
- const pattern = opts.searchPattern;
782
- if (/^[0-9a-fA-F\s]+$/.test(pattern)) {
783
- const hexBytes = pattern.replace(/\s/g, "").match(/.{2}/g)?.map((h) => parseInt(h, 16)) || [];
784
- for (let i = opts.offset; i <= Math.min(opts.offset + opts.length - hexBytes.length, buffer.length - hexBytes.length); i++) {
785
- let match = true;
786
- for (let j = 0; j < hexBytes.length; j++) if (buffer[i + j] !== hexBytes[j]) {
787
- match = false;
788
- break;
789
- }
790
- if (match) searchResults.push({ offset: i });
791
- }
792
- } else {
793
- const patternBytes = new TextEncoder().encode(pattern);
794
- for (let i = opts.offset; i <= Math.min(opts.offset + opts.length - patternBytes.length, buffer.length - patternBytes.length); i++) {
795
- let match = true;
796
- for (let j = 0; j < patternBytes.length; j++) if (buffer[i + j] !== patternBytes[j]) {
797
- match = false;
798
- break;
799
- }
800
- if (match) searchResults.push({ offset: i });
801
- }
802
- }
803
- }
804
- return {
805
- totalMemoryPages: memory.buffer.byteLength / 65536,
806
- totalMemoryBytes: memory.buffer.byteLength,
807
- requestedOffset: opts.offset,
808
- requestedLength: opts.length,
809
- data: slice,
810
- searchResults,
811
- memoryInfo: memoryEvents[0] || null
812
- };
813
- } catch (e) {
814
- return { error: `Failed to read WASM memory: ${e instanceof Error ? e.message : String(e)}` };
815
- }
816
- }, {
817
- offset,
818
- length,
819
- searchPattern
820
- });
821
- if (hasErrorResult(memData)) return { content: [{
822
- type: "text",
823
- text: JSON.stringify({
824
- success: false,
825
- error: memData.error
826
- })
827
- }] };
828
- const data = memData.data;
829
- let hexDump = "";
830
- let asciiDump = "";
831
- if (format === "hex" || format === "both") for (let i = 0; i < data.length; i += 16) {
832
- const row = data.slice(i, i + 16);
833
- const addr = (offset + i).toString(16).padStart(8, "0");
834
- const hex = row.map((b) => b.toString(16).padStart(2, "0")).join(" ");
835
- const ascii = row.map((b) => b >= 32 && b < 127 ? String.fromCharCode(b) : ".").join("");
836
- hexDump += `${addr} ${hex.padEnd(48)} |${ascii}|\n`;
837
- }
838
- if (format === "ascii") asciiDump = data.map((b) => b >= 32 && b < 127 ? String.fromCharCode(b) : ".").join("");
839
- return { content: [{
840
- type: "text",
841
- text: JSON.stringify({
842
- success: true,
843
- totalMemoryPages: memData.totalMemoryPages,
844
- totalMemoryBytes: memData.totalMemoryBytes,
845
- offset,
846
- length: data.length,
847
- hexDump: format !== "ascii" ? hexDump : void 0,
848
- asciiDump: format === "ascii" ? asciiDump : void 0,
849
- searchResults: memData.searchResults
850
- }, null, 2)
851
- }] };
852
- }
853
- };
854
- //#endregion
855
- //#region src/server/domains/wasm/handlers/capability-handlers.ts
856
- function toolCapability(capability, toolName, available, reason, fix, tools, probe) {
857
- return {
858
- capability,
859
- status: available ? "available" : "unavailable",
860
- reason,
861
- fix: available ? void 0 : fix,
862
- details: {
863
- tools,
864
- ...probe?.path ? { path: probe.path } : {},
865
- ...probe?.version ? { version: probe.version } : {},
866
- backend: toolName
867
- }
868
- };
869
- }
870
- var CapabilityHandlers = class {
871
- constructor(state) {
872
- this.state = state;
873
- }
874
- async handleWasmCapabilities() {
875
- const probes = await this.state.runner.probeAll();
876
- const currentPageCapability = await this.getCurrentPageCapability();
877
- const hasOfflineRuntime = probes["runtime.wasmtime"]?.available === true || probes["runtime.wasmer"]?.available === true;
878
- return R.raw(capabilityReport("wasm_capabilities", [
879
- currentPageCapability,
880
- toolCapability("wabt_wasm2wat", "wabt.wasm2wat", probes["wabt.wasm2wat"]?.available === true, probes["wabt.wasm2wat"]?.reason, "Install WABT so wasm2wat is available on PATH.", ["wasm_disassemble"], probes["wabt.wasm2wat"]),
881
- toolCapability("wabt_wasm_decompile", "wabt.wasm-decompile", probes["wabt.wasm-decompile"]?.available === true, probes["wabt.wasm-decompile"]?.reason, "Install WABT so wasm-decompile is available on PATH.", ["wasm_decompile"], probes["wabt.wasm-decompile"]),
882
- toolCapability("wabt_wasm_objdump", "wabt.wasm-objdump", probes["wabt.wasm-objdump"]?.available === true, probes["wabt.wasm-objdump"]?.reason, "Install WABT so wasm-objdump is available on PATH.", ["wasm_inspect_sections"], probes["wabt.wasm-objdump"]),
883
- toolCapability("binaryen_wasm_opt", "binaryen.wasm-opt", probes["binaryen.wasm-opt"]?.available === true, probes["binaryen.wasm-opt"]?.reason, "Install Binaryen so wasm-opt is available on PATH.", ["wasm_optimize"], probes["binaryen.wasm-opt"]),
884
- {
885
- capability: "wasm_offline_runtime",
886
- status: hasOfflineRuntime ? "available" : "unavailable",
887
- reason: hasOfflineRuntime ? void 0 : "No offline WASM runtime is available on PATH.",
888
- fix: hasOfflineRuntime ? void 0 : "Install wasmtime or wasmer to enable wasm_offline_run.",
889
- details: {
890
- tools: ["wasm_offline_run"],
891
- runtimes: {
892
- wasmtime: probes["runtime.wasmtime"],
893
- wasmer: probes["runtime.wasmer"]
894
- },
895
- preferredRuntime: probes["runtime.wasmtime"]?.available ? "runtime.wasmtime" : probes["runtime.wasmer"]?.available ? "runtime.wasmer" : null
896
- }
897
- }
898
- ]));
899
- }
900
- async getCurrentPageCapability() {
901
- let page;
902
- try {
903
- page = await this.state.collector.getActivePage();
904
- } catch (error) {
905
- return {
906
- capability: "wasm_browser_capture_current_page",
907
- status: "unknown",
908
- reason: `Current page probe failed: ${error instanceof Error ? error.message : String(error)}`,
909
- fix: "Attach or launch a browser page before using browser-backed WASM tools.",
910
- details: {
911
- tools: [
912
- "wasm_dump",
913
- "wasm_vmp_trace",
914
- "wasm_memory_inspect"
915
- ],
916
- pageAttached: false
917
- }
918
- };
919
- }
920
- if (!page) return {
921
- capability: "wasm_browser_capture_current_page",
922
- status: "unknown",
923
- reason: "No active page is attached.",
924
- fix: "Attach or launch a browser page before using browser-backed WASM tools.",
925
- details: {
926
- tools: [
927
- "wasm_dump",
928
- "wasm_vmp_trace",
929
- "wasm_memory_inspect"
930
- ],
931
- pageAttached: false
932
- }
933
- };
934
- try {
935
- const probe = await page.evaluate(() => {
936
- const win = window;
937
- const hooksRaw = win.__aiHooks?.["preset-webassembly-full"];
938
- const hooks = Array.isArray(hooksRaw) ? hooksRaw : [];
939
- return {
940
- url: location.href,
941
- hookEventCount: hooks.length,
942
- instantiatedCount: hooks.filter((entry) => entry.type === "instantiated").length,
943
- importCallCount: hooks.filter((entry) => entry.type === "import_call").length,
944
- memoryEventCount: hooks.filter((entry) => entry.type === "memory_created").length,
945
- storageCount: Array.isArray(win.__wasmModuleStorage) ? win.__wasmModuleStorage.length : 0,
946
- instanceCount: Array.isArray(win.__wasmInstances) ? win.__wasmInstances.length : 0
947
- };
948
- });
949
- const available = probe.instantiatedCount > 0 || probe.memoryEventCount > 0 || probe.storageCount > 0 || probe.instanceCount > 0;
950
- return {
951
- capability: "wasm_browser_capture_current_page",
952
- status: available ? "available" : "unavailable",
953
- reason: available ? void 0 : "No captured WASM modules or exported memory are visible on the current page.",
954
- fix: available ? void 0 : "Load a page that instantiates WASM. For dump/trace flows, inject hook_preset(\"webassembly-full\") before navigation.",
955
- details: {
956
- tools: [
957
- "wasm_dump",
958
- "wasm_vmp_trace",
959
- "wasm_memory_inspect"
960
- ],
961
- pageAttached: true,
962
- ...probe
963
- }
964
- };
965
- } catch (error) {
966
- return {
967
- capability: "wasm_browser_capture_current_page",
968
- status: "unknown",
969
- reason: `Current page probe failed: ${error instanceof Error ? error.message : String(error)}`,
970
- fix: "Ensure an attached page is still reachable before using browser-backed WASM tools.",
971
- details: {
972
- tools: [
973
- "wasm_dump",
974
- "wasm_vmp_trace",
975
- "wasm_memory_inspect"
976
- ],
977
- pageAttached: true
978
- }
979
- };
980
- }
981
- }
982
- };
983
- //#endregion
984
- //#region src/server/domains/wasm/handlers.impl.core.ts
985
- /**
986
- * WASM domain — composition facade.
987
- *
988
- * External tool operations in ./handlers/external-tool-handlers.ts.
989
- * Browser operations in ./handlers/browser-handlers.ts.
990
- */
991
- var WasmToolHandlers = class {
992
- state;
993
- externalTools;
994
- browser;
995
- capabilities;
996
- constructor(collector) {
997
- const runner = new ExternalToolRunner(new ToolRegistry());
998
- this.state = {
999
- collector,
1000
- runner
1001
- };
1002
- this.externalTools = new ExternalToolHandlers(this.state);
1003
- this.browser = new BrowserHandlers(this.state);
1004
- this.capabilities = new CapabilityHandlers(this.state);
1005
- }
1006
- handleWasmCapabilities() {
1007
- return this.capabilities.handleWasmCapabilities();
1008
- }
1009
- handleWasmDump(args) {
1010
- return this.browser.handleWasmDump(args);
1011
- }
1012
- handleWasmDisassemble(args) {
1013
- return this.externalTools.handleWasmDisassemble(args);
1014
- }
1015
- handleWasmDecompile(args) {
1016
- return this.externalTools.handleWasmDecompile(args);
1017
- }
1018
- handleWasmInspectSections(args) {
1019
- return this.externalTools.handleWasmInspectSections(args);
1020
- }
1021
- handleWasmOfflineRun(args) {
1022
- return this.externalTools.handleWasmOfflineRun(args);
1023
- }
1024
- handleWasmOptimize(args) {
1025
- return this.externalTools.handleWasmOptimize(args);
1026
- }
1027
- handleWasmVmpTrace(args) {
1028
- return this.browser.handleWasmVmpTrace(args);
1029
- }
1030
- handleWasmMemoryInspect(args) {
1031
- return this.browser.handleWasmMemoryInspect(args);
1032
- }
1033
- handleWasmToC(args) {
1034
- return this.externalTools.handleWasmToC(args);
1035
- }
1036
- handleWasmDetectObfuscation(args) {
1037
- return this.externalTools.handleWasmDetectObfuscation(args);
1038
- }
1039
- handleWasmInstrumentTrace(args) {
1040
- return this.externalTools.handleWasmInstrumentTrace(args);
1041
- }
1042
- };
1043
- //#endregion
1044
- export { WasmToolHandlers };