@jshookmcp/jshook 0.2.9 → 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.
- package/README.md +25 -50
- package/README.zh.md +25 -48
- package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
- package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
- package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
- package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
- package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
- package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
- package/dist/EventBus-DgciURGg.mjs +1 -0
- package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
- package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
- package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
- package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
- package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
- package/dist/{HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -174
- package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
- package/dist/MemoryController-BaqstM5w.mjs +2 -0
- package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
- package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
- package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
- package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
- package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
- package/dist/PageController-D9jVkH0i.mjs +1 -0
- package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
- package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
- package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
- package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
- package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
- package/dist/ScriptManager-fgqiALgj.mjs +7 -0
- package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
- package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
- package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
- package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
- package/dist/ToolError-DWU_z7gp.mjs +1 -0
- package/dist/ToolProbe-xsfALmN3.mjs +1 -0
- package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
- package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
- package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
- package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
- package/dist/Win32API-Bhi5xFBe.mjs +1 -0
- package/dist/Win32Debug-CQteFL4F.mjs +1 -0
- package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
- package/dist/analysis-BuR-NgX8.mjs +5 -0
- package/dist/{antidebug-CqDTB_uk.mjs → antidebug-BOTZH6-0.mjs} +8 -259
- package/dist/artifactRetention-NBdncOEW.mjs +1 -0
- package/dist/artifacts-B5xQuEa_.mjs +1 -0
- package/dist/authorization-schema-B40obG1A.mjs +1 -0
- package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
- package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
- package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
- package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
- package/dist/browser-C4Le3xqA.mjs +11 -0
- package/dist/capabilities-DbYCv-HF.mjs +1 -0
- package/dist/chunk-C_pMuVsO.mjs +1 -0
- package/dist/collector-CKO8RPK8.mjs +1 -0
- package/dist/concurrency-CcK46d0h.mjs +1 -0
- package/dist/constants-Cp6hBrrx.mjs +1 -0
- package/dist/coordination-BbijHEHH.mjs +1 -0
- package/dist/debugger-CRJq_krh.mjs +1 -0
- package/dist/definitions-BGobEDQa.mjs +1 -0
- package/dist/definitions-BGwNSkVm.mjs +1 -0
- package/dist/definitions-BbxOUiP-.mjs +1 -0
- package/dist/definitions-CCP9gphV.mjs +1 -0
- package/dist/definitions-CIO9O-Sw.mjs +1 -0
- package/dist/definitions-CYFbewnd.mjs +1 -0
- package/dist/definitions-CdWEuIkI.mjs +1 -0
- package/dist/definitions-CoQFbggH.mjs +1 -0
- package/dist/definitions-CuJRsJ6N.mjs +1 -0
- package/dist/definitions-DI9YXsJk.mjs +1 -0
- package/dist/definitions-DJklW2sS.mjs +1 -0
- package/dist/definitions-DZ8uKusP.mjs +1 -0
- package/dist/definitions-Dds_zrWx.mjs +1 -0
- package/dist/definitions-Dgrg7f3D.mjs +1 -0
- package/dist/definitions-DtE0XLrT.mjs +1 -0
- package/dist/definitions-LaYTuwQd.mjs +26 -0
- package/dist/definitions-NoVp_9Pm.mjs +1 -0
- package/dist/definitions-OvGsfxdt.mjs +1 -0
- package/dist/definitions-jXPaVy4P.mjs +1 -0
- package/dist/encoding-DGcr6Aj_.mjs +2 -0
- package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
- package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
- package/dist/factory-Cx_1LorX.mjs +1 -0
- package/dist/flat-target-session-CO5g78k3.mjs +1 -0
- package/dist/formatAddress-C7j2fDlM.mjs +1 -0
- package/dist/graphql-HLf3MS8H.mjs +62 -0
- package/dist/handlers-BLMa4X7l.mjs +54 -0
- package/dist/handlers-BP12ZsWc.mjs +4 -0
- package/dist/handlers-BZoPla6E.mjs +1 -0
- package/dist/handlers-BggKiVx9.mjs +2 -0
- package/dist/handlers-D3iev8g1.mjs +1 -0
- package/dist/handlers-D49r1-1P.mjs +1 -0
- package/dist/handlers-DCE45Ww8.mjs +2 -0
- package/dist/handlers-DW5AbYs5.mjs +5 -0
- package/dist/handlers-De5u62Ga2.mjs +1 -0
- package/dist/handlers-DmQzIc44.mjs +31 -0
- package/dist/handlers-DnJRGp7t.mjs +302 -0
- package/dist/handlers-Dv_runVv.mjs +2 -0
- package/dist/handlers-S9Ws0IGy.mjs +2 -0
- package/dist/{handlers-Bl8zkwz1.mjs → handlers-pVNpaw4A.mjs} +144 -841
- package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
- package/dist/hooks-DDKppogd.mjs +600 -0
- package/dist/index.mjs +12 -5225
- package/dist/logger-sBC6IdRT.mjs +1 -0
- package/dist/maintenance-CutEO84j.mjs +1 -0
- package/dist/manifest-BFGxlDRh.mjs +123 -0
- package/dist/manifest-BPuE6oH2.mjs +1 -0
- package/dist/manifest-BXry5N09.mjs +1 -0
- package/dist/manifest-BeP_zJGb2.mjs +1 -0
- package/dist/manifest-C0g67k6U.mjs +1 -0
- package/dist/manifest-C1nZkTkO.mjs +1 -0
- package/dist/manifest-C7qV1z7F.mjs +1 -0
- package/dist/manifest-CDeUZGUZ.mjs +1 -0
- package/dist/manifest-CDiCtaQT.mjs +1 -0
- package/dist/manifest-CFn0359q2.mjs +1 -0
- package/dist/manifest-CGq4NpqH2.mjs +1 -0
- package/dist/manifest-CJMGt7Qy.mjs +1 -0
- package/dist/manifest-CRIJq4Hs.mjs +1 -0
- package/dist/manifest-C_hEIjSx.mjs +1 -0
- package/dist/manifest-CeQmtQOY.mjs +1 -0
- package/dist/manifest-Cq0j7GZt.mjs +1 -0
- package/dist/manifest-CtPmHAdn.mjs +1 -0
- package/dist/manifest-Cx2IVMUY.mjs +1 -0
- package/dist/manifest-D16xPXro.mjs +1 -0
- package/dist/manifest-D44TaRJU.mjs +1 -0
- package/dist/manifest-D610kxZr.mjs +2 -0
- package/dist/manifest-DC-SMF6b.mjs +1 -0
- package/dist/manifest-DD3rtxvV.mjs +1 -0
- package/dist/manifest-DKUorv5M.mjs +1 -0
- package/dist/manifest-DMJlcsTR.mjs +1 -0
- package/dist/manifest-DWUUWBz0.mjs +1 -0
- package/dist/manifest-De-6Wf2R.mjs +1 -0
- package/dist/manifest-Dgh0uDW-.mjs +1 -0
- package/dist/manifest-Dm0o3i2U.mjs +1 -0
- package/dist/manifest-DsVh7Y4U.mjs +1 -0
- package/dist/manifest-DtEFSRaq.mjs +1 -0
- package/dist/manifest-H-EpAyZQ.mjs +1 -0
- package/dist/manifest-ais9Afrw.mjs +1 -0
- package/dist/manifest-tmb54wmA.mjs +1 -0
- package/dist/manifest-yu2xiQqe.mjs +1 -0
- package/dist/manifest-zrbrpKCC.mjs +1 -0
- package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
- package/dist/modules-p-PUNv9r.mjs +332 -0
- package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
- package/dist/network-BjZ1Y-GB.mjs +7 -0
- package/dist/outputPaths-BonGThuc.mjs +2 -0
- package/dist/parse-args-Cuk7-xUt.mjs +1 -0
- package/dist/platform-C446Lf97.mjs +93 -0
- package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
- package/dist/process-C9f2A5zk.mjs +962 -0
- package/dist/proxy-CvRepxgV.mjs +1 -0
- package/dist/registry-DUHIPE-v.mjs +1 -0
- package/dist/response-C7rKQst4.mjs +1 -0
- package/dist/search-defaults-D2bY-rzH.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -293
- package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
- package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
- package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
- package/dist/streaming-CTX58tbb.mjs +1 -0
- package/dist/tool-builder-CI9914Tf.mjs +1 -0
- package/dist/transform-Cv9P2vVD.mjs +103 -0
- package/dist/types-CuyefmGT.mjs +1 -0
- package/dist/types-DtThH00r.mjs +1 -0
- package/dist/wasm-DaJa8J0V.mjs +174 -0
- package/dist/webcrack-CsLLJIs9.mjs +46 -0
- package/dist/workflow-CYIXtrWD.mjs +101 -0
- package/package.json +12 -7
- package/dist/AntiCheatDetector-BNk-EoBt.mjs +0 -244
- package/dist/CacheAdapters-CDe5WPSV.mjs +0 -80
- package/dist/CodeInjector-Cq8q01kp.mjs +0 -150
- package/dist/ConsoleMonitor-CPVQW1Y-.mjs +0 -2201
- package/dist/DarwinAPI-BNPxu0RH.mjs +0 -363
- package/dist/DetailedDataManager-BQQcxh64.mjs +0 -217
- package/dist/EventBus-DgPmwpeu.mjs +0 -141
- package/dist/EvidenceGraphBridge-SFesNera.mjs +0 -153
- package/dist/ExtensionManager-CWYgw0YW.mjs +0 -714
- package/dist/FingerprintManager-gzWtkKuf.mjs +0 -96
- package/dist/HardwareBreakpoint-B9gZCdFP.mjs +0 -239
- package/dist/HeapAnalyzer-BLDH0dCv.mjs +0 -284
- package/dist/InstrumentationSession-CvPC7Jwy.mjs +0 -244
- package/dist/MemoryController-CbVdCIJF.mjs +0 -167
- package/dist/MemoryScanSession-BsDZbLYm.mjs +0 -278
- package/dist/MemoryScanner-Bcpml6II.mjs +0 -425
- package/dist/NativeMemoryManager.impl-dZtA1ZGn.mjs +0 -482
- package/dist/NativeMemoryManager.utils-B-FjA2mJ.mjs +0 -165
- package/dist/PEAnalyzer-D1lzJ_VG.mjs +0 -385
- package/dist/PageController-Bqm2kZ_X.mjs +0 -417
- package/dist/PointerChainEngine-BOhyVsjx.mjs +0 -322
- package/dist/PrerequisiteError-Dl33Svkz.mjs +0 -20
- package/dist/ResponseBuilder-D3iFYx2N.mjs +0 -143
- package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +0 -269
- package/dist/ScriptManager-aHHq0X7U.mjs +0 -3000
- package/dist/Speedhack-CqdIFlQl.mjs +0 -156
- package/dist/StealthVerifier-Bo4T3bz8.mjs +0 -135
- package/dist/StructureAnalyzer-DhFaPvRO.mjs +0 -426
- package/dist/ToolCatalog-C0JGZoOm.mjs +0 -582
- package/dist/ToolError-jh9whhMd.mjs +0 -15
- package/dist/ToolProbe-oC7aPrkv.mjs +0 -45
- package/dist/ToolRegistry-BjaF4oNz.mjs +0 -131
- package/dist/ToolRouter.policy-BWV67ZK-.mjs +0 -304
- package/dist/TraceRecorder-DgxyVbdQ.mjs +0 -519
- package/dist/VersionDetector-CwVLVdDM.mjs +0 -104
- package/dist/Win32API-CePkipZY.mjs +0 -340
- package/dist/Win32Debug-BvKs-gxc.mjs +0 -274
- package/dist/WorkflowEngine-CuvkZtWu.mjs +0 -598
- package/dist/analysis-CL9uACt9.mjs +0 -463
- package/dist/artifactRetention-CFEprwPw.mjs +0 -591
- package/dist/artifacts-Bk2-_uPq.mjs +0 -59
- package/dist/betterSqlite3-0pqusHHH.mjs +0 -74
- package/dist/binary-instrument-CXfpx6fT.mjs +0 -979
- package/dist/bind-helpers-xFfRF-qm.mjs +0 -22
- package/dist/boringssl-inspector-BH2D3VKc.mjs +0 -180
- package/dist/browser-BpOr5PEx.mjs +0 -4082
- package/dist/chunk-CjcI7cDX.mjs +0 -15
- package/dist/concurrency-Bt0yv1kJ.mjs +0 -41
- package/dist/constants-B0OANIBL.mjs +0 -519
- package/dist/coordination-qUbyF8KU.mjs +0 -259
- package/dist/debugger-gnKxRSN0.mjs +0 -1271
- package/dist/definitions-6M-eejaT.mjs +0 -53
- package/dist/definitions-B18eyf0B.mjs +0 -18
- package/dist/definitions-B3QdlrHv.mjs +0 -34
- package/dist/definitions-B4rAvHNZ.mjs +0 -63
- package/dist/definitions-BB_4jnmy.mjs +0 -37
- package/dist/definitions-BMfYXoNC.mjs +0 -43
- package/dist/definitions-Beid2EB3.mjs +0 -27
- package/dist/definitions-C1UvM5Iy.mjs +0 -126
- package/dist/definitions-CXEI7QC72.mjs +0 -216
- package/dist/definitions-C_4r7Fo-2.mjs +0 -14
- package/dist/definitions-CkFDALoa.mjs +0 -26
- package/dist/definitions-Cke7zEb8.mjs +0 -94
- package/dist/definitions-ClJLzsJQ.mjs +0 -25
- package/dist/definitions-Cq-zroAU.mjs +0 -28
- package/dist/definitions-Cy3Sl6gV.mjs +0 -34
- package/dist/definitions-D3VsGcvz.mjs +0 -47
- package/dist/definitions-DVGfrn7y.mjs +0 -96
- package/dist/definitions-LKpC3-nL.mjs +0 -9
- package/dist/definitions-bAhHQJq9.mjs +0 -359
- package/dist/encoding-Bvz5jLRv.mjs +0 -1065
- package/dist/evidence-graph-bridge-C_fv9PuC.mjs +0 -135
- package/dist/factory-DxlGh9Xf.mjs +0 -575
- package/dist/formatAddress-DVkj9kpI.mjs +0 -17
- package/dist/graphql-DYWzJ29s.mjs +0 -1026
- package/dist/handlers-9sAbfIg-.mjs +0 -2552
- package/dist/handlers-C67ktuRN.mjs +0 -710
- package/dist/handlers-C87g8oCe.mjs +0 -276
- package/dist/handlers-CTsDAO6p.mjs +0 -681
- package/dist/handlers-Cgyg6c0U.mjs +0 -645
- package/dist/handlers-D6j6yka7.mjs +0 -2124
- package/dist/handlers-DdFzXLvF.mjs +0 -446
- package/dist/handlers-DeLOCd5m.mjs +0 -799
- package/dist/handlers-DlCJN4Td.mjs +0 -757
- package/dist/handlers-DxGIq15_2.mjs +0 -917
- package/dist/handlers-U6L4xhuF.mjs +0 -585
- package/dist/handlers-tB9Mp9ZK.mjs +0 -84
- package/dist/handlers-tiy7EIBp.mjs +0 -572
- package/dist/handlers.impl-DS0d9fUw.mjs +0 -761
- package/dist/hooks-CzCWByww.mjs +0 -898
- package/dist/logger-Dh_xb7_2.mjs +0 -93
- package/dist/maintenance-P7ePRXQC.mjs +0 -830
- package/dist/manifest-2ToTpjv8.mjs +0 -106
- package/dist/manifest-3g71z6Bg.mjs +0 -79
- package/dist/manifest-82baTv4U.mjs +0 -45
- package/dist/manifest-B3QVVeBS.mjs +0 -82
- package/dist/manifest-BB2J8IMJ.mjs +0 -149
- package/dist/manifest-BKbgbSiY.mjs +0 -60
- package/dist/manifest-Bcf-TJzH.mjs +0 -848
- package/dist/manifest-BmtZzQiQ2.mjs +0 -45
- package/dist/manifest-Bnd7kqEY.mjs +0 -55
- package/dist/manifest-BqQX6OQC2.mjs +0 -65
- package/dist/manifest-BqrQ4Tpj.mjs +0 -81
- package/dist/manifest-Br4RPFt5.mjs +0 -370
- package/dist/manifest-C5qDjysN.mjs +0 -107
- package/dist/manifest-C9RT5nk32.mjs +0 -34
- package/dist/manifest-CAhOuvSl.mjs +0 -204
- package/dist/manifest-CBYWCUBJ.mjs +0 -51
- package/dist/manifest-CFADCRa1.mjs +0 -37
- package/dist/manifest-CQVhavRF.mjs +0 -114
- package/dist/manifest-CT7zZBV1.mjs +0 -48
- package/dist/manifest-CV12bcrF.mjs +0 -121
- package/dist/manifest-CXsRWjjI.mjs +0 -224
- package/dist/manifest-CZLUCfG02.mjs +0 -95
- package/dist/manifest-D6phHKFd.mjs +0 -131
- package/dist/manifest-DCyjf4n2.mjs +0 -294
- package/dist/manifest-DHsnKgP6.mjs +0 -60
- package/dist/manifest-Df_dliIe.mjs +0 -55
- package/dist/manifest-Dh8WBmEW.mjs +0 -129
- package/dist/manifest-DhKRAT8_.mjs +0 -92
- package/dist/manifest-DlpTj4ic2.mjs +0 -193
- package/dist/manifest-DrbmZcFl2.mjs +0 -253
- package/dist/manifest-DuwHjUa5.mjs +0 -70
- package/dist/manifest-DzwvxPJX.mjs +0 -38
- package/dist/manifest-NXctwWQq.mjs +0 -68
- package/dist/manifest-Sc_0JQ13.mjs +0 -418
- package/dist/manifest-gZ4s_UtG.mjs +0 -96
- package/dist/manifest-qSleDqdO.mjs +0 -1023
- package/dist/modules-C184v-S9.mjs +0 -11365
- package/dist/mojo-ipc-B_H61Afw.mjs +0 -525
- package/dist/network-671Cw6hV.mjs +0 -3346
- package/dist/outputPaths-B1uGmrWZ.mjs +0 -1145
- package/dist/parse-args-BlRjqlkL.mjs +0 -39
- package/dist/platform-WmNn8Sxb.mjs +0 -2070
- package/dist/process-QcbIy5Zq.mjs +0 -1401
- package/dist/proxy-DqNs0bAd.mjs +0 -170
- package/dist/registry-D-6e18lB.mjs +0 -34
- package/dist/response-BQVP-xUn.mjs +0 -28
- package/dist/shared-state-board-DV-dpHFJ.mjs +0 -586
- package/dist/sourcemap-Dq8ez8vS.mjs +0 -650
- package/dist/ssrf-policy-ZaUfvhq7.mjs +0 -166
- package/dist/streaming-BUQ0VJsg.mjs +0 -725
- package/dist/tool-builder-DCbIC5Eo.mjs +0 -186
- package/dist/transform-CiYJfNX0.mjs +0 -1007
- package/dist/types-Bx92KJfT.mjs +0 -4
- package/dist/types-CPhOReNX.mjs +0 -37
- package/dist/wasm-DQTnHDs4.mjs +0 -531
- package/dist/workflow-f3xJOcjx.mjs +0 -725
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./PrerequisiteError-Bl3dK8XA.mjs";import{randomUUID as n}from"node:crypto";function r(e){return`
|
|
2
|
+
(function() {
|
|
3
|
+
if (window.__xhrInterceptorInstalled) {
|
|
4
|
+
console.log('[XHRInterceptor] Already installed');
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
window.__xhrInterceptorInstalled = true;
|
|
8
|
+
|
|
9
|
+
const originalXHR = window.__originalXMLHttpRequestForHook || window.XMLHttpRequest;
|
|
10
|
+
window.__originalXMLHttpRequestForHook = originalXHR;
|
|
11
|
+
if (!window.__xhrRequests) {
|
|
12
|
+
window.__xhrRequests = [];
|
|
13
|
+
}
|
|
14
|
+
const xhrRequests = window.__xhrRequests;
|
|
15
|
+
|
|
16
|
+
window.XMLHttpRequest = function() {
|
|
17
|
+
const xhr = new originalXHR();
|
|
18
|
+
const requestInfo = {
|
|
19
|
+
method: '',
|
|
20
|
+
url: '',
|
|
21
|
+
requestHeaders: {},
|
|
22
|
+
responseHeaders: {},
|
|
23
|
+
status: 0,
|
|
24
|
+
response: null,
|
|
25
|
+
timestamp: Date.now(),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const originalOpen = xhr.open;
|
|
29
|
+
xhr.open = function(method, url, ...args) {
|
|
30
|
+
requestInfo.method = method;
|
|
31
|
+
requestInfo.url = url;
|
|
32
|
+
console.log('[XHRInterceptor] XHR opened:', method, url);
|
|
33
|
+
return originalOpen.call(xhr, method, url, ...args);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const originalSetRequestHeader = xhr.setRequestHeader;
|
|
37
|
+
xhr.setRequestHeader = function(header, value) {
|
|
38
|
+
requestInfo.requestHeaders[header] = value;
|
|
39
|
+
return originalSetRequestHeader.call(xhr, header, value);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const originalSend = xhr.send;
|
|
43
|
+
xhr.send = function(body) {
|
|
44
|
+
let bodySize = 0;
|
|
45
|
+
try {
|
|
46
|
+
if (typeof body === 'string') bodySize = body.length;
|
|
47
|
+
else if (body && typeof body.byteLength === 'number') bodySize = body.byteLength;
|
|
48
|
+
else if (body && typeof body.size === 'number') bodySize = body.size;
|
|
49
|
+
} catch {}
|
|
50
|
+
console.log('[XHRInterceptor] XHR sent:', requestInfo.url, 'BodySize:', bodySize);
|
|
51
|
+
|
|
52
|
+
xhr.addEventListener('load', function() {
|
|
53
|
+
requestInfo.status = xhr.status;
|
|
54
|
+
requestInfo.response = xhr.response;
|
|
55
|
+
requestInfo.responseHeaders = xhr.getAllResponseHeaders();
|
|
56
|
+
|
|
57
|
+
xhrRequests.push(requestInfo);
|
|
58
|
+
if (xhrRequests.length > ${e}) {
|
|
59
|
+
xhrRequests.splice(0, xhrRequests.length - ${e});
|
|
60
|
+
}
|
|
61
|
+
console.log('[XHRInterceptor] XHR completed:', requestInfo.url, 'Status:', xhr.status);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return originalSend.call(xhr, body);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
return xhr;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
window.__getXHRRequests = function() {
|
|
71
|
+
return window.__xhrRequests || [];
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
console.log('[XHRInterceptor] XHR interceptor installed');
|
|
75
|
+
})();
|
|
76
|
+
`}function i(e){return`
|
|
77
|
+
(function() {
|
|
78
|
+
if (window.__fetchInterceptorInstalled) {
|
|
79
|
+
console.log('[FetchInterceptor] Already installed');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
window.__fetchInterceptorInstalled = true;
|
|
83
|
+
|
|
84
|
+
const originalFetch = window.__originalFetchForHook || window.fetch;
|
|
85
|
+
window.__originalFetchForHook = originalFetch;
|
|
86
|
+
if (!window.__fetchRequests) {
|
|
87
|
+
window.__fetchRequests = [];
|
|
88
|
+
}
|
|
89
|
+
const fetchRequests = window.__fetchRequests;
|
|
90
|
+
|
|
91
|
+
window.fetch = function(url, options = {}) {
|
|
92
|
+
const requestInfo = {
|
|
93
|
+
url: typeof url === 'string' ? url : url.url,
|
|
94
|
+
method: options.method || 'GET',
|
|
95
|
+
headers: options.headers || {},
|
|
96
|
+
body: options.body,
|
|
97
|
+
timestamp: Date.now(),
|
|
98
|
+
response: null,
|
|
99
|
+
status: 0,
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
console.log('[FetchInterceptor] Fetch called:', requestInfo.method, requestInfo.url);
|
|
103
|
+
|
|
104
|
+
return originalFetch.call(window, url, options).then(async (response) => {
|
|
105
|
+
requestInfo.status = response.status;
|
|
106
|
+
|
|
107
|
+
const clonedResponse = response.clone();
|
|
108
|
+
try {
|
|
109
|
+
requestInfo.response = await clonedResponse.text();
|
|
110
|
+
} catch (e) {
|
|
111
|
+
requestInfo.response = '[Unable to read response]';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fetchRequests.push(requestInfo);
|
|
115
|
+
if (fetchRequests.length > ${e}) {
|
|
116
|
+
fetchRequests.splice(0, fetchRequests.length - ${e});
|
|
117
|
+
}
|
|
118
|
+
// Auto-persist compact summary to localStorage so data survives context compression
|
|
119
|
+
try {
|
|
120
|
+
const summary = { url: requestInfo.url, method: requestInfo.method, status: requestInfo.status, ts: requestInfo.timestamp };
|
|
121
|
+
const prev = JSON.parse(localStorage.getItem('__capturedAPIs') || '[]');
|
|
122
|
+
prev.push(summary);
|
|
123
|
+
if (prev.length > 500) prev.splice(0, prev.length - 500);
|
|
124
|
+
localStorage.setItem('__capturedAPIs', JSON.stringify(prev));
|
|
125
|
+
} catch(e) {
|
|
126
|
+
// best-effort persistence only; ignore quota or serialization failures
|
|
127
|
+
}
|
|
128
|
+
console.log('[FetchInterceptor] Fetch completed:', requestInfo.url, 'Status:', response.status);
|
|
129
|
+
|
|
130
|
+
return response;
|
|
131
|
+
}).catch((error) => {
|
|
132
|
+
console.error('[FetchInterceptor] Fetch failed:', requestInfo.url, error);
|
|
133
|
+
throw error;
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
window.__getFetchRequests = function() {
|
|
138
|
+
return window.__fetchRequests || [];
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
console.log('[FetchInterceptor] Fetch interceptor installed');
|
|
142
|
+
})();
|
|
143
|
+
`}const a=e=>typeof e==`object`&&!!e,o=e=>!a(e)||typeof e.requestId!=`string`||!a(e.request)||typeof e.request.url!=`string`||typeof e.request.method!=`string`||e.request.postData!==void 0&&typeof e.request.postData!=`string`?!1:typeof e.timestamp==`number`,s=e=>!a(e)||typeof e.requestId!=`string`||!a(e.response)||typeof e.response.url!=`string`||typeof e.response.status!=`number`||typeof e.response.statusText!=`string`||typeof e.response.mimeType!=`string`?!1:typeof e.timestamp==`number`,c=e=>a(e)&&typeof e.requestId==`string`,l=e=>a(e)&&typeof e.body==`string`&&typeof e.base64Encoded==`boolean`,u=e=>a(e)?e:{},d=e=>{if(!a(e))return;let t=e.result;if(a(t))return t.value},f=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t,p=(e,t)=>typeof e==`boolean`?e:t;var m=class{cdpSession;networkEnabled=!1;requests=new Map;responses=new Map;MAX_NETWORK_RECORDS=500;MAX_INJECTED_RECORDS=500;JS_RESPONSE_CONCURRENCY=6;responseBodyCache=new Map;MAX_BODY_CACHE_ENTRIES=200;networkListeners={};constructor(t){this.cdpSession=t,this.cdpSession.on(`disconnected`,()=>{e.warn(`NetworkMonitor: CDP session disconnected`),this.networkEnabled=!1,this.networkListeners={}})}async enable(){if(!this.cdpSession)throw Error(`CDP session not initialized`);if(this.networkEnabled){e.warn(`Network monitoring already enabled`);return}try{await this.cdpSession.send(`Network.enable`,{maxTotalBufferSize:1e7,maxResourceBufferSize:5e6,maxPostDataSize:65536}),e.info(`Network domain enabled`),this.networkListeners.requestWillBeSent=t=>{if(!o(t)){e.debug(`Skipping malformed Network.requestWillBeSent payload`);return}let n={requestId:t.requestId,url:t.request.url,method:t.request.method,headers:u(t.request.headers),postData:t.request.postData,timestamp:t.timestamp,type:t.type,httpVersion:t.request.httpVersion,initiator:t.initiator};if(this.requests.set(t.requestId,n),this.requests.size>this.MAX_NETWORK_RECORDS){let e=this.requests.keys().next().value;e&&this.requests.delete(e)}e.debug(`Network request captured: ${t.request.method} ${t.request.url}`)},this.networkListeners.responseReceived=t=>{if(!s(t)){e.debug(`Skipping malformed Network.responseReceived payload`);return}let n={requestId:t.requestId,url:t.response.url,status:t.response.status,statusText:t.response.statusText,headers:u(t.response.headers),mimeType:t.response.mimeType,timestamp:t.timestamp,fromCache:t.response.fromDiskCache||t.response.fromServiceWorker,timing:t.response.timing};if(this.responses.set(t.requestId,n),this.responses.size>this.MAX_NETWORK_RECORDS){let e=this.responses.keys().next().value;e&&this.responses.delete(e)}e.debug(`Network response captured: ${t.response.status} ${t.response.url}`)},this.networkListeners.loadingFinished=t=>{if(!c(t)){e.debug(`Skipping malformed Network.loadingFinished payload`);return}e.debug(`Network loading finished: ${t.requestId}`),this.captureResponseBody(t.requestId).catch(n=>{e.debug(`[BodyCache] Auto-capture failed for ${t.requestId}: ${n instanceof Error?n.message:String(n)}`)})},this.cdpSession.on(`Network.requestWillBeSent`,this.networkListeners.requestWillBeSent),this.cdpSession.on(`Network.responseReceived`,this.networkListeners.responseReceived),this.cdpSession.on(`Network.loadingFinished`,this.networkListeners.loadingFinished),this.networkEnabled=!0,e.info(` Network monitoring enabled successfully`,{requestListeners:!!this.networkListeners.requestWillBeSent,responseListeners:!!this.networkListeners.responseReceived,loadingListeners:!!this.networkListeners.loadingFinished})}catch(t){throw e.error(` Failed to enable network monitoring:`,t),this.networkEnabled=!1,t}}async captureResponseBody(t){if(this.responseBodyCache.has(t))return;let n=this.responses.get(t);if(n&&!n.fromCache)try{let r=await this.cdpSession.send(`Network.getResponseBody`,{requestId:t});if(!l(r))return;if(r.body.length>1048576){e.debug(`[BodyCache] Skipping oversized body for ${t} (${r.body.length} chars)`);return}if(this.responseBodyCache.size>=this.MAX_BODY_CACHE_ENTRIES){let e=this.responseBodyCache.keys().next().value;e&&this.responseBodyCache.delete(e)}this.responseBodyCache.set(t,{body:r.body,base64Encoded:r.base64Encoded}),e.debug(`[BodyCache] Cached body for ${t} (${r.body.length} chars, url=${n.url})`)}catch(n){e.debug(`[BodyCache] Could not capture body for ${t}: ${n instanceof Error?n.message:String(n)}`)}}async disable(){if(this.networkEnabled){this.networkListeners.requestWillBeSent&&this.cdpSession.off(`Network.requestWillBeSent`,this.networkListeners.requestWillBeSent),this.networkListeners.responseReceived&&this.cdpSession.off(`Network.responseReceived`,this.networkListeners.responseReceived),this.networkListeners.loadingFinished&&this.cdpSession.off(`Network.loadingFinished`,this.networkListeners.loadingFinished);try{await this.cdpSession.send(`Network.disable`)}catch(t){e.warn(`Failed to disable Network domain:`,t)}this.networkListeners={},this.networkEnabled=!1,e.info(`Network monitoring disabled`)}}isEnabled(){return this.networkEnabled}getStatus(){return{enabled:this.networkEnabled,requestCount:this.requests.size,responseCount:this.responses.size,listenerCount:Object.keys(this.networkListeners).filter(e=>this.networkListeners[e]!==void 0).length,cdpSessionActive:!0}}getRequests(e){let t=Array.from(this.requests.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.method&&(t=t.filter(t=>t.method===e.method)),e?.limit&&(t=t.slice(-e.limit)),t}getResponses(e){let t=Array.from(this.responses.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.status&&(t=t.filter(t=>t.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getActivity(e){return{request:this.requests.get(e),response:this.responses.get(e)}}async getResponseBody(t){if(!this.cdpSession)throw Error(`CDP session not initialized`);if(!this.networkEnabled)return e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null;let n=this.responseBodyCache.get(t);if(n)return this.responseBodyCache.delete(t),this.responseBodyCache.set(t,n),e.debug(`[BodyCache] Cache hit for ${t}`),n;let r=this.requests.get(t),i=this.responses.get(t);if(!r)return e.error(`Request not found: ${t}. Make sure network monitoring was enabled before the request.`),null;if(!i)return e.warn(`Response not yet received for request: ${t}. The request may still be pending.`),null;try{let n=await this.cdpSession.send(`Network.getResponseBody`,{requestId:t});return l(n)?(e.info(`Response body retrieved for request: ${t}`,{url:i.url,status:i.status,size:n.body.length,base64:n.base64Encoded}),{body:n.body,base64Encoded:n.base64Encoded}):(e.error(`Unexpected response body payload for ${t}`),null)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(`Failed to get response body for ${t}:`,{url:i.url,status:i.status,error:r,hint:`The response body may not be available for this request type (e.g., cached, redirected, or failed requests)`}),null}}async getAllJavaScriptResponses(){let t=Array.from(this.responses.entries()).filter(([,e])=>e.mimeType.includes(`javascript`)||e.url.endsWith(`.js`)||e.url.includes(`.js?`)),n=[];for(let e=0;e<t.length;e+=this.JS_RESPONSE_CONCURRENCY){let r=t.slice(e,e+this.JS_RESPONSE_CONCURRENCY),i=await Promise.all(r.map(async([e,t])=>{let n=await this.getResponseBody(e);if(!n)return null;let r=n.base64Encoded?Buffer.from(n.body,`base64`).toString(`utf-8`):n.body;return{url:t.url,content:r,size:r.length,requestId:e}}));n.push(...i.filter(e=>e!==null))}return e.info(`Collected ${n.length} JavaScript responses`),n}clearRecords(){this.requests.clear(),this.responses.clear(),this.responseBodyCache.clear(),e.info(`Network records cleared`)}getStats(){let e={},t={},n={};for(let t of this.requests.values())e[t.method]=(e[t.method]||0)+1,t.type&&(n[t.type]=(n[t.type]||0)+1);for(let e of this.responses.values())t[e.status]=(t[e.status]||0)+1;return{totalRequests:this.requests.size,totalResponses:this.responses.size,byMethod:e,byStatus:t,byType:n}}async injectXHRInterceptor(t){if(!this.cdpSession)throw Error(`CDP session not initialized`);let n=r(this.MAX_INJECTED_RECORDS);t?.persistent?(await this.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:n}),e.info(`XHR interceptor injected (persistent)`)):(await this.cdpSession.send(`Runtime.evaluate`,{expression:n}),e.info(`XHR interceptor injected`))}async injectFetchInterceptor(t){if(!this.cdpSession)throw Error(`CDP session not initialized`);let n=i(this.MAX_INJECTED_RECORDS);t?.persistent?(await this.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:n}),e.info(`Fetch interceptor injected (persistent)`)):(await this.cdpSession.send(`Runtime.evaluate`,{expression:n}),e.info(`Fetch interceptor injected`))}async getXHRRequests(){if(!this.cdpSession)throw Error(`CDP session not initialized`);try{let e=d(await this.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getXHRRequests ? window.__getXHRRequests() : []`,returnByValue:!0}));return Array.isArray(e)?e.filter(e=>a(e)):[]}catch(t){return e.error(`Failed to get XHR requests:`,t),[]}}async getFetchRequests(){if(!this.cdpSession)throw Error(`CDP session not initialized`);try{let e=d(await this.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getFetchRequests ? window.__getFetchRequests() : []`,returnByValue:!0}));return Array.isArray(e)?e.filter(e=>a(e)):[]}catch(t){return e.error(`Failed to get Fetch requests:`,t),[]}}async clearInjectedBuffers(){if(!this.cdpSession)throw Error(`CDP session not initialized`);try{let e=d(await this.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
144
|
+
(() => {
|
|
145
|
+
const xhrStore = Array.isArray(window.__xhrRequests)
|
|
146
|
+
? window.__xhrRequests
|
|
147
|
+
: (typeof window.__getXHRRequests === 'function' ? window.__getXHRRequests() : null);
|
|
148
|
+
const fetchStore = Array.isArray(window.__fetchRequests)
|
|
149
|
+
? window.__fetchRequests
|
|
150
|
+
: (typeof window.__getFetchRequests === 'function' ? window.__getFetchRequests() : null);
|
|
151
|
+
|
|
152
|
+
const xhrCleared = Array.isArray(xhrStore) ? xhrStore.length : 0;
|
|
153
|
+
const fetchCleared = Array.isArray(fetchStore) ? fetchStore.length : 0;
|
|
154
|
+
|
|
155
|
+
if (Array.isArray(xhrStore)) xhrStore.length = 0;
|
|
156
|
+
if (Array.isArray(fetchStore)) fetchStore.length = 0;
|
|
157
|
+
|
|
158
|
+
return { xhrCleared, fetchCleared };
|
|
159
|
+
})()
|
|
160
|
+
`,returnByValue:!0}));return a(e)?{xhrCleared:f(e.xhrCleared),fetchCleared:f(e.fetchCleared)}:{xhrCleared:0,fetchCleared:0}}catch(t){return e.error(`Failed to clear injected network buffers:`,t),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){if(!this.cdpSession)throw Error(`CDP session not initialized`);try{let e=d(await this.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
161
|
+
(() => {
|
|
162
|
+
let xhrReset = false;
|
|
163
|
+
let fetchReset = false;
|
|
164
|
+
|
|
165
|
+
if (window.__originalXMLHttpRequestForHook) {
|
|
166
|
+
window.XMLHttpRequest = window.__originalXMLHttpRequestForHook;
|
|
167
|
+
xhrReset = true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (window.__originalFetchForHook) {
|
|
171
|
+
window.fetch = window.__originalFetchForHook;
|
|
172
|
+
fetchReset = true;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (Array.isArray(window.__xhrRequests)) window.__xhrRequests.length = 0;
|
|
176
|
+
if (Array.isArray(window.__fetchRequests)) window.__fetchRequests.length = 0;
|
|
177
|
+
|
|
178
|
+
window.__xhrInterceptorInstalled = false;
|
|
179
|
+
window.__fetchInterceptorInstalled = false;
|
|
180
|
+
delete window.__getXHRRequests;
|
|
181
|
+
delete window.__getFetchRequests;
|
|
182
|
+
|
|
183
|
+
return { xhrReset, fetchReset };
|
|
184
|
+
})()
|
|
185
|
+
`,returnByValue:!0}));return a(e)?{xhrReset:p(e.xhrReset,!1),fetchReset:p(e.fetchReset,!1)}:{xhrReset:!1,fetchReset:!1}}catch(t){return e.error(`Failed to reset injected network interceptors:`,t),{xhrReset:!1,fetchReset:!1}}}},h=class{page;networkEnabled=!1;requests=new Map;responses=new Map;MAX_NETWORK_RECORDS=500;MAX_INJECTED_RECORDS=500;requestCounter=0;responseBodyCache=new Map;MAX_BODY_CACHE_ENTRIES=200;requestIdMap=new WeakMap;boundOnRequest=null;boundOnResponse=null;constructor(e){this.page=e}setPage(e){if(this.page===e)return;let t=this.page,n=this.networkEnabled,r=this.boundOnRequest,i=this.boundOnResponse;if(n&&t&&r)try{t.off(`request`,r)}catch{}if(n&&t&&i)try{t.off(`response`,i)}catch{}if(this.page=e,!n||!this.page){this.page||(this.networkEnabled=!1);return}r&&this.page.on(`request`,r),i&&this.page.on(`response`,i)}getPageOrThrow(){if(!this.page)throw Error(`Playwright page not initialized`);return this.page}async evaluateInPage(e){let t=this.getPageOrThrow();if(!t.evaluate)throw Error(`Playwright page.evaluate is not available`);return t.evaluate(e)}async evaluateOnNewDocumentInPage(e){let t=this.getPageOrThrow();if(!t.evaluateOnNewDocument)throw Error(`Playwright page.evaluateOnNewDocument is not available`);return t.evaluateOnNewDocument(e)}isUnknownArray(e){return Array.isArray(e)}isClearedBuffersResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrCleared==`number`&&typeof t.fetchCleared==`number`}isResetInterceptorsResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrReset==`boolean`&&typeof t.fetchReset==`boolean`}isPlaywrightLikeRequest(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.url==`function`&&typeof t.method==`function`&&typeof t.headers==`function`&&typeof t.postData==`function`&&typeof t.resourceType==`function`}isPlaywrightLikeResponse(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.request==`function`&&typeof t.url==`function`&&typeof t.status==`function`&&typeof t.statusText==`function`&&typeof t.headers==`function`}normalizeHttpVersion(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`http/1.0`||t===`1.0`)return`1.0`;if(t===`http/1.1`||t===`1.1`)return`1.1`;if(t===`http/2`||t===`2`||t===`2.0`||t===`h2`)return`h2`;if(t===`http/3`||t===`3`||t===`3.0`||t===`h3`)return`h3`}detectHttpVersion(e){let t=typeof e.httpVersion==`function`?e.httpVersion():void 0,n=this.normalizeHttpVersion(t);if(n)return n;let r=typeof e.protocol==`function`?e.protocol():void 0;return this.normalizeHttpVersion(r)}async enable(){if(this.networkEnabled){e.warn(`PlaywrightNetworkMonitor already enabled`);return}this.boundOnRequest=e=>{if(!this.isPlaywrightLikeRequest(e))return;let t=`pw-${++this.requestCounter}`;this.requestIdMap.set(e,t);let n={requestId:t,url:e.url(),method:e.method(),headers:e.headers(),postData:e.postData()??void 0,timestamp:Date.now(),type:e.resourceType()};if(this.requests.set(t,n),this.requests.size>this.MAX_NETWORK_RECORDS){let e=this.requests.keys().next().value;e&&this.requests.delete(e)}},this.boundOnResponse=t=>{if(!this.isPlaywrightLikeResponse(t))return;let n=t.request(),r=`pw-res-${Date.now()}-${Math.random()}`,i=this.isPlaywrightLikeRequest(n)?this.requestIdMap.get(n)??r:r,a=this.detectHttpVersion(t),o=this.requests.get(i);o&&a&&(o.httpVersion=a);let s={requestId:i,url:t.url(),status:t.status(),statusText:t.statusText(),headers:t.headers(),mimeType:t.headers()[`content-type`]??`unknown`,timestamp:Date.now()};if(this.responses.set(i,s),this.responses.size>this.MAX_NETWORK_RECORDS){let e=this.responses.keys().next().value;e&&this.responses.delete(e)}if(typeof t.body==`function`){let n=i;t.body().then(t=>{if(t.length>1048576){e.debug(`[PW-BodyCache] Skipping oversized body for ${n} (${t.length} bytes)`);return}if(this.responseBodyCache.size>=this.MAX_BODY_CACHE_ENTRIES){let e=this.responseBodyCache.keys().next().value;e&&this.responseBodyCache.delete(e)}/^(text\/|application\/(json|javascript|xml|x-www-form-urlencoded))/i.test(s.mimeType)?this.responseBodyCache.set(n,{body:t.toString(`utf-8`),base64Encoded:!1}):this.responseBodyCache.set(n,{body:t.toString(`base64`),base64Encoded:!0}),e.debug(`[PW-BodyCache] Cached body for ${n} (${t.length} bytes)`)}).catch(t=>{e.debug(`[PW-BodyCache] Could not capture body for ${n}: ${t instanceof Error?t.message:String(t)}`)})}};let t=this.getPageOrThrow();t.on(`request`,this.boundOnRequest),t.on(`response`,this.boundOnResponse),this.networkEnabled=!0,e.info(`PlaywrightNetworkMonitor enabled`)}async disable(){let t=this.getPageOrThrow();if(this.boundOnRequest){try{t.off(`request`,this.boundOnRequest)}catch{}this.boundOnRequest=null}if(this.boundOnResponse){try{t.off(`response`,this.boundOnResponse)}catch{}this.boundOnResponse=null}this.networkEnabled=!1,e.info(`PlaywrightNetworkMonitor disabled`)}isEnabled(){return this.networkEnabled}getRequests(e){let t=Array.from(this.requests.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.method&&(t=t.filter(t=>t.method.toUpperCase()===e.method.toUpperCase())),e?.limit&&(t=t.slice(-e.limit)),t}getResponses(e){let t=Array.from(this.responses.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.status&&(t=t.filter(t=>t.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getStatus(){return{enabled:this.networkEnabled,requestCount:this.requests.size,responseCount:this.responses.size,listenerCount:this.networkEnabled?2:0,cdpSessionActive:!1}}getActivity(e){return{request:this.requests.get(e),response:this.responses.get(e)}}clearRecords(){this.requests.clear(),this.responses.clear(),this.responseBodyCache.clear()}getStats(){let e=Array.from(this.requests.values()),t=Array.from(this.responses.values()),n={};e.forEach(e=>{n[e.method]=(n[e.method]||0)+1});let r={};t.forEach(e=>{r[e.status]=(r[e.status]||0)+1});let i={};return e.forEach(e=>{let t=e.type||`unknown`;i[t]=(i[t]||0)+1}),{totalRequests:e.length,totalResponses:t.length,byMethod:n,byStatus:r,byType:i}}async getResponseBody(t){let n=this.responseBodyCache.get(t);return n?(this.responseBodyCache.delete(t),this.responseBodyCache.set(t,n),e.debug(`[PW-BodyCache] Cache hit for ${t}`),n):(e.warn(`getResponseBody: no cached body for ${t} in Playwright mode`),null)}async injectScript(e){await this.evaluateInPage(e)}async injectXHRInterceptor(e){let t=`
|
|
186
|
+
(function() {
|
|
187
|
+
if (window.__xhrInterceptorInjected) return;
|
|
188
|
+
window.__xhrInterceptorInjected = true;
|
|
189
|
+
const maxRecords = ${this.MAX_INJECTED_RECORDS};
|
|
190
|
+
const OrigXHR = window.__pwOriginalXMLHttpRequest || window.XMLHttpRequest;
|
|
191
|
+
window.__pwOriginalXMLHttpRequest = OrigXHR;
|
|
192
|
+
if (!window.__xhrRequests) window.__xhrRequests = [];
|
|
193
|
+
window.XMLHttpRequest = function() {
|
|
194
|
+
const xhr = new OrigXHR();
|
|
195
|
+
const origOpen = xhr.open.bind(xhr);
|
|
196
|
+
const origSend = xhr.send.bind(xhr);
|
|
197
|
+
xhr.open = function(method, url, ...rest) {
|
|
198
|
+
xhr.__hookMeta = { method, url, timestamp: Date.now() };
|
|
199
|
+
return origOpen(method, url, ...rest);
|
|
200
|
+
};
|
|
201
|
+
xhr.send = function(body) {
|
|
202
|
+
xhr.addEventListener('load', function() {
|
|
203
|
+
window.__xhrRequests.push({
|
|
204
|
+
...xhr.__hookMeta, body: body ? String(body).slice(0, 2048) : null,
|
|
205
|
+
status: xhr.status, response: xhr.responseText.slice(0, 2048),
|
|
206
|
+
});
|
|
207
|
+
if (window.__xhrRequests.length > maxRecords) {
|
|
208
|
+
window.__xhrRequests.splice(0, window.__xhrRequests.length - maxRecords);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
return origSend(body);
|
|
212
|
+
};
|
|
213
|
+
return xhr;
|
|
214
|
+
};
|
|
215
|
+
console.log('[PlaywrightXHR] XHR interceptor injected');
|
|
216
|
+
})();
|
|
217
|
+
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async injectFetchInterceptor(e){let t=`
|
|
218
|
+
(function() {
|
|
219
|
+
if (window.__fetchInterceptorInjected) return;
|
|
220
|
+
window.__fetchInterceptorInjected = true;
|
|
221
|
+
const maxRecords = ${this.MAX_INJECTED_RECORDS};
|
|
222
|
+
const origFetch = window.__pwOriginalFetch || window.fetch;
|
|
223
|
+
window.__pwOriginalFetch = origFetch;
|
|
224
|
+
if (!window.__fetchRequests) window.__fetchRequests = [];
|
|
225
|
+
const normalizeHeaders = (value) => {
|
|
226
|
+
if (!value) return {};
|
|
227
|
+
try {
|
|
228
|
+
if (typeof Headers !== 'undefined' && value instanceof Headers) {
|
|
229
|
+
return Object.fromEntries(value.entries());
|
|
230
|
+
}
|
|
231
|
+
} catch {}
|
|
232
|
+
if (Array.isArray(value)) {
|
|
233
|
+
try {
|
|
234
|
+
return Object.fromEntries(value);
|
|
235
|
+
} catch {
|
|
236
|
+
return {};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return typeof value === 'object' ? value : {};
|
|
240
|
+
};
|
|
241
|
+
window.fetch = function(...args) {
|
|
242
|
+
const [resource, opts = {}] = args;
|
|
243
|
+
const requestLike = resource && typeof resource === 'object' ? resource : null;
|
|
244
|
+
const url =
|
|
245
|
+
typeof resource === 'string'
|
|
246
|
+
? resource
|
|
247
|
+
: typeof resource?.url === 'string'
|
|
248
|
+
? resource.url
|
|
249
|
+
: String(resource);
|
|
250
|
+
const method = opts?.method || requestLike?.method || 'GET';
|
|
251
|
+
const headers = normalizeHeaders(opts?.headers || requestLike?.headers);
|
|
252
|
+
const bodySource = opts?.body;
|
|
253
|
+
const body =
|
|
254
|
+
bodySource === undefined || bodySource === null
|
|
255
|
+
? null
|
|
256
|
+
: String(bodySource).slice(0, 2048);
|
|
257
|
+
const entry = {
|
|
258
|
+
url,
|
|
259
|
+
method,
|
|
260
|
+
headers,
|
|
261
|
+
body,
|
|
262
|
+
timestamp: Date.now(),
|
|
263
|
+
response: null,
|
|
264
|
+
status: 0,
|
|
265
|
+
};
|
|
266
|
+
return origFetch.apply(this, args).then(res => {
|
|
267
|
+
entry.status = res.status;
|
|
268
|
+
return res.clone().text().then(
|
|
269
|
+
(text) => {
|
|
270
|
+
entry.response = text.slice(0, 2048);
|
|
271
|
+
return res;
|
|
272
|
+
},
|
|
273
|
+
() => {
|
|
274
|
+
entry.response = '[Unable to read response]';
|
|
275
|
+
return res;
|
|
276
|
+
},
|
|
277
|
+
).then((response) => {
|
|
278
|
+
window.__fetchRequests.push(entry);
|
|
279
|
+
if (window.__fetchRequests.length > maxRecords) {
|
|
280
|
+
window.__fetchRequests.splice(0, window.__fetchRequests.length - maxRecords);
|
|
281
|
+
}
|
|
282
|
+
// Auto-persist compact summary so data survives context compression
|
|
283
|
+
try {
|
|
284
|
+
const s = { url: entry.url, method: entry.method, status: entry.status, ts: entry.timestamp };
|
|
285
|
+
const prev = JSON.parse(localStorage.getItem('__capturedAPIs') || '[]');
|
|
286
|
+
prev.push(s);
|
|
287
|
+
if (prev.length > 500) prev.splice(0, prev.length - 500);
|
|
288
|
+
localStorage.setItem('__capturedAPIs', JSON.stringify(prev));
|
|
289
|
+
} catch(e) {}
|
|
290
|
+
return response;
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
console.log('[PlaywrightFetch] Fetch interceptor injected');
|
|
295
|
+
})();
|
|
296
|
+
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async getXHRRequests(){try{let e=await this.evaluateInPage(()=>window.__xhrRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get XHR requests: ${t instanceof Error?t.message:String(t)}`),[]}}async getFetchRequests(){try{let e=await this.evaluateInPage(()=>window.__fetchRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get fetch requests: ${t instanceof Error?t.message:String(t)}`),[]}}async clearInjectedBuffers(){try{let e=await this.evaluateInPage(()=>{let e=window,t=e.__xhrRequests,n=e.__fetchRequests,r=Array.isArray(t)?t.length:0,i=Array.isArray(n)?n.length:0;return Array.isArray(t)&&(t.length=0),Array.isArray(n)&&(n.length=0),{xhrCleared:r,fetchCleared:i}});return this.isClearedBuffersResult(e)?e:{xhrCleared:0,fetchCleared:0}}catch(t){return e.warn(`[PW] Failed to clear injected buffers: ${t instanceof Error?t.message:String(t)}`),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){try{let e=await this.evaluateInPage(()=>{let e=window,t=!1,n=!1;return e.__pwOriginalXMLHttpRequest&&(e.XMLHttpRequest=e.__pwOriginalXMLHttpRequest,t=!0),e.__pwOriginalFetch&&(e.fetch=e.__pwOriginalFetch,n=!0),Array.isArray(e.__xhrRequests)&&(e.__xhrRequests.length=0),Array.isArray(e.__fetchRequests)&&(e.__fetchRequests.length=0),e.__xhrInterceptorInjected=!1,e.__fetchInterceptorInjected=!1,{xhrReset:t,fetchReset:n}});return this.isResetInterceptorsResult(e)?e:{xhrReset:!1,fetchReset:!1}}catch(t){return e.warn(`[PW] Failed to reset interceptors: ${t instanceof Error?t.message:String(t)}`),{xhrReset:!1,fetchReset:!1}}}async getAllJavaScriptResponses(){return Array.from(this.responses.values()).filter(e=>e.mimeType.includes(`javascript`))}},g=class{cdpSession;rules=new Map;enabled=!1;eventHandler=null;compiledPatterns=new Map;constructor(e){this.cdpSession=e}async enable(t){let n=[];for(let e of t){let t=this.createRule(e);this.rules.set(t.id,t),this.compiledPatterns.set(t.id,this.compilePattern(t)),n.push(t)}return await this.applyRules(),this.eventHandler||(this.eventHandler=e=>{this.handleRequestPaused(e)},this.cdpSession.on(`Fetch.requestPaused`,this.eventHandler)),this.enabled=!0,e.info(`FetchInterceptor enabled with ${this.rules.size} rule(s)`),n}async disable(){let t=this.rules.size;if(this.eventHandler){try{this.cdpSession.off(`Fetch.requestPaused`,this.eventHandler)}catch{}this.eventHandler=null}try{await this.cdpSession.send(`Fetch.disable`)}catch(t){e.warn(`Fetch.disable failed:`,t)}return this.rules.clear(),this.compiledPatterns.clear(),this.enabled=!1,e.info(`FetchInterceptor disabled, removed ${t} rule(s)`),{removedRules:t}}async removeRule(e){let t=this.rules.delete(e);return this.compiledPatterns.delete(e),t&&(this.rules.size===0?await this.disable():await this.applyRules()),t}listRules(){let e=Array.from(this.rules.values());return{enabled:this.enabled,rules:e,totalHits:e.reduce((e,t)=>e+t.hitCount,0)}}isEnabled(){return this.enabled}createRule(e){let t=[];if(e.responseHeaders)for(let[n,r]of Object.entries(e.responseHeaders))t.push({name:n,value:r});return{id:n().slice(0,8),urlPattern:e.urlPattern,urlPatternType:e.urlPatternType??`glob`,stage:e.stage??`Response`,interceptAction:e.interceptAction??`fulfill`,responseCode:e.responseCode??200,responseHeaders:t,responseBody:e.responseBody??``,hitCount:0,createdAt:Date.now()}}compilePattern(e){if(e.urlPatternType===`regex`)try{return new RegExp(e.urlPattern,`i`)}catch{return new RegExp(e.urlPattern.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`i`)}let t=e.urlPattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`⟨GLOBSTAR⟩`).replace(/\*/g,`[^/]*`).replace(/⟨GLOBSTAR⟩/g,`.*`);return new RegExp(t,`i`)}async applyRules(){let t=[];for(let e of this.rules.values())t.push({urlPattern:e.urlPatternType===`glob`?e.urlPattern:`*`,requestStage:e.stage});if(t.length!==0)try{try{await this.cdpSession.send(`Fetch.disable`)}catch{}await this.cdpSession.send(`Fetch.enable`,{patterns:t.length>0?t:[{urlPattern:`*`,requestStage:`Response`}],handleAuthRequests:!1})}catch(t){throw e.error(`Failed to apply Fetch interception rules:`,t),t}}async handleRequestPaused(t){let n=t.request.url;for(let[r,i]of this.rules){let a=this.compiledPatterns.get(r);if(a&&a.test(n)&&(i.hitCount++,e.info(`[FetchInterceptor] Rule "${i.urlPattern}" matched: ${n}`),await this.applyMatchedRule(i,t,n)))return}await this.continueOriginalRequest(t,n)}async applyMatchedRule(t,n,r){try{switch(t.interceptAction){case`continue`:return await this.continuePausedRequest(n),!0;case`abort`:return await this.cdpSession.send(`Fetch.failRequest`,{requestId:n.requestId,errorReason:`Failed`}),!0;case`fulfill`:return await this.cdpSession.send(`Fetch.fulfillRequest`,{requestId:n.requestId,responseCode:t.responseCode,responseHeaders:this.buildFulfillHeaders(t),body:Buffer.from(t.responseBody,`utf-8`).toString(`base64`)}),!0}}catch(n){return e.error(`[FetchInterceptor] ${t.interceptAction} failed for ${r}:`,n),!1}}buildFulfillHeaders(e){let t=[...e.responseHeaders];return t.some(e=>e.name.toLowerCase()===`content-type`)||(e.responseBody.startsWith(`{`)||e.responseBody.startsWith(`[`)?t.push({name:`Content-Type`,value:`application/json`}):t.push({name:`Content-Type`,value:`text/plain`})),t.some(e=>e.name.toLowerCase()===`access-control-allow-origin`)||t.push({name:`Access-Control-Allow-Origin`,value:`*`}),t}async continuePausedRequest(e){if(e.responseStatusCode!==void 0){await this.cdpSession.send(`Fetch.continueResponse`,{requestId:e.requestId});return}await this.cdpSession.send(`Fetch.continueRequest`,{requestId:e.requestId})}async continueOriginalRequest(t,n){try{await this.continuePausedRequest(t)}catch(t){e.warn(`[FetchInterceptor] continue failed for ${n}:`,t)}}};function _(e){return e}function v(t,n){let r=_(t);if(r.contextSwitchPending)return[];let i=r.messages;n?.type&&(i=i.filter(e=>e.type===n.type));let a=n?.since;return a!==void 0&&(i=i.filter(e=>e.timestamp>=a)),n?.limit&&(i=i.slice(-n.limit)),e.debug(`getLogs: ${i.length} messages`),i}function y(t){let n=_(t);n.messages=[],e.info(`Console logs cleared`)}function b(e){let t=_(e);if(t.contextSwitchPending)return{totalMessages:0,byType:{}};let n={};for(let e of t.messages)n[e.type]=(n[e.type]||0)+1;return{totalMessages:t.messages.length,byType:n}}function x(e,t){let n=_(e);if(n.contextSwitchPending)return[];let r=n.exceptions;t?.url&&(r=r.filter(e=>e.url?.includes(t.url)));let i=t?.since;return i!==void 0&&(r=r.filter(e=>e.timestamp>=i)),t?.limit&&(r=r.slice(-t.limit)),r}function S(t){let n=_(t);n.exceptions=[],e.info(`Exceptions cleared`)}function C(e){return e}function w(e){return e.contextSwitchPending===!0}function T(e){let t=C(e);return w(t)?!1:(t.networkMonitor?.isEnabled()??!1)||(t.playwrightNetworkMonitor?.isEnabled()??!1)}function E(e){let t=C(e);return w(t)?{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:!1}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStatus():t.networkMonitor?t.networkMonitor.getStatus():{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:t.cdpSession!==null}}function D(e,t){let n=C(e);return w(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getRequests(t):n.networkMonitor?.getRequests(t)??[]}function O(e,t){let n=C(e);return w(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getResponses(t):n.networkMonitor?.getResponses(t)??[]}function k(e,t){let n=C(e);return w(n)?{}:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getActivity(t):n.networkMonitor?.getActivity(t)??{}}async function A(t,n){let r=C(t);return w(r)?null:r.playwrightNetworkMonitor?r.playwrightNetworkMonitor.getResponseBody(n):r.networkMonitor?r.networkMonitor.getResponseBody(n):(e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null)}async function j(e){let t=C(e);return w(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getAllJavaScriptResponses():t.networkMonitor?t.networkMonitor.getAllJavaScriptResponses():[]}function M(e){let t=C(e);t.networkMonitor?.clearRecords(),t.playwrightNetworkMonitor?.clearRecords()}async function N(e){let t=C(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.clearInjectedBuffers(),dynamicScriptsCleared:0};let n=t.networkMonitor?await t.networkMonitor.clearInjectedBuffers():{xhrCleared:0,fetchCleared:0},r=await t.clearDynamicScriptBuffer();return{...n,...r}}async function P(e){let t=C(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.resetInjectedInterceptors(),scriptMonitorReset:!1};let n=t.networkMonitor?await t.networkMonitor.resetInjectedInterceptors():{xhrReset:!1,fetchReset:!1},r=await t.resetDynamicScriptMonitoring();return{...n,...r}}function F(e){let t=C(e);return w(t)?{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStats():t.networkMonitor?.getStats()??{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}}async function I(e,n){let r=C(e);if(w(r))throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectXHRInterceptor(n);if(!r.networkMonitor)throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectXHRInterceptor(n)}async function L(e,n){let r=C(e);if(w(r))throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectFetchInterceptor(n);if(!r.networkMonitor)throw new t(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectFetchInterceptor(n)}async function R(e){let t=C(e);return w(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getXHRRequests():t.networkMonitor?t.networkMonitor.getXHRRequests():[]}async function z(e){let t=C(e);return w(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getFetchRequests():t.networkMonitor?t.networkMonitor.getFetchRequests():[]}async function B(t,n){let r=t;if(await r.ensureSession(),!r.cdpSession)throw Error(`CDP session not available after reconnect attempt`);if(r.objectCache.has(n)){let e=r.objectCache.get(n);if(e!==void 0)return e}try{let t=await r.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),i={};for(let e of t.result){if(!e.value)continue;let t=e.value;i[e.name]={value:r.extractValue(t),type:t.type,objectId:t.objectId,description:t.description}}if(!r.objectCache.has(n))for(;r.objectCache.size>=r.MAX_OBJECT_CACHE_SIZE;){let e=r.objectCache.keys().next().value;if(e===void 0)break;r.objectCache.delete(e)}return r.objectCache.set(n,i),e.info(`Object inspected: ${n}`,{propertyCount:Object.keys(i).length}),i}catch(t){throw e.error(`Failed to inspect object:`,t),t}}function V(t){t.objectCache.clear(),e.info(`Object cache cleared`)}function H(e){return e}async function U(n,r){let i=H(n);if(await i.ensureSession(),!i.cdpSession)throw new t(`CDP session not available after reconnect attempt`);let a=`
|
|
297
|
+
(function() {
|
|
298
|
+
if (window.__dynamicScriptMonitorInstalled) {
|
|
299
|
+
console.log('[ScriptMonitor] Already installed');
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
window.__dynamicScriptMonitorInstalled = true;
|
|
303
|
+
|
|
304
|
+
const maxRecords = ${i.MAX_INJECTED_DYNAMIC_SCRIPTS};
|
|
305
|
+
if (!window.__dynamicScripts) {
|
|
306
|
+
window.__dynamicScripts = [];
|
|
307
|
+
}
|
|
308
|
+
const dynamicScripts = window.__dynamicScripts;
|
|
309
|
+
const state = window.__dynamicScriptMonitorState || {};
|
|
310
|
+
if (!state.originalCreateElement) state.originalCreateElement = document.createElement;
|
|
311
|
+
if (!state.originalEval) state.originalEval = window.eval;
|
|
312
|
+
if (!state.originalFunction) state.originalFunction = window.Function;
|
|
313
|
+
window.__dynamicScriptMonitorState = state;
|
|
314
|
+
|
|
315
|
+
const observer = new MutationObserver((mutations) => {
|
|
316
|
+
mutations.forEach((mutation) => {
|
|
317
|
+
mutation.addedNodes.forEach((node) => {
|
|
318
|
+
if (node.nodeName === 'SCRIPT') {
|
|
319
|
+
const script = node;
|
|
320
|
+
const info = {
|
|
321
|
+
type: 'dynamic',
|
|
322
|
+
src: script.src || '(inline)',
|
|
323
|
+
content: script.src ? null : script.textContent,
|
|
324
|
+
timestamp: Date.now(),
|
|
325
|
+
async: script.async,
|
|
326
|
+
defer: script.defer,
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
dynamicScripts.push(info);
|
|
330
|
+
if (dynamicScripts.length > maxRecords) {
|
|
331
|
+
dynamicScripts.splice(0, dynamicScripts.length - maxRecords);
|
|
332
|
+
}
|
|
333
|
+
console.log('[ScriptMonitor] Dynamic script added:', info);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
observer.observe(document.documentElement, {
|
|
340
|
+
childList: true,
|
|
341
|
+
subtree: true,
|
|
342
|
+
});
|
|
343
|
+
state.observer = observer;
|
|
344
|
+
|
|
345
|
+
const originalCreateElement = state.originalCreateElement;
|
|
346
|
+
document.createElement = function(tagName) {
|
|
347
|
+
const element = originalCreateElement.call(document, tagName);
|
|
348
|
+
|
|
349
|
+
if (tagName.toLowerCase() === 'script') {
|
|
350
|
+
console.log('[ScriptMonitor] Script element created via createElement');
|
|
351
|
+
|
|
352
|
+
const originalSetAttribute = element.setAttribute;
|
|
353
|
+
element.setAttribute = function(name, value) {
|
|
354
|
+
if (name === 'src') {
|
|
355
|
+
console.log('[ScriptMonitor] Script src set to:', value);
|
|
356
|
+
}
|
|
357
|
+
return originalSetAttribute.call(element, name, value);
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return element;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const originalEval = state.originalEval;
|
|
365
|
+
window.eval = function(code) {
|
|
366
|
+
console.log('[ScriptMonitor] eval() called with code:',
|
|
367
|
+
typeof code === 'string' ? code.substring(0, 100) + '...' : code);
|
|
368
|
+
return originalEval.call(window, code);
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
const originalFunction = state.originalFunction;
|
|
372
|
+
window.Function = function(...args) {
|
|
373
|
+
console.log('[ScriptMonitor] Function() constructor called with args:', args);
|
|
374
|
+
return originalFunction.apply(this, args);
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
window.__getDynamicScripts = function() {
|
|
378
|
+
return dynamicScripts;
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
console.log('[ScriptMonitor] Dynamic script monitoring enabled');
|
|
382
|
+
})();
|
|
383
|
+
`;r?.persistent?(await i.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:a}),e.info(`Dynamic script monitoring enabled (persistent)`)):(await i.cdpSession.send(`Runtime.evaluate`,{expression:a}),e.info(`Dynamic script monitoring enabled`))}async function W(t){let n=H(t);if(!n.cdpSession)return{dynamicScriptsCleared:0};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
384
|
+
(() => {
|
|
385
|
+
const store = Array.isArray(window.__dynamicScripts)
|
|
386
|
+
? window.__dynamicScripts
|
|
387
|
+
: (typeof window.__getDynamicScripts === 'function'
|
|
388
|
+
? window.__getDynamicScripts()
|
|
389
|
+
: null);
|
|
390
|
+
const dynamicScriptsCleared = Array.isArray(store) ? store.length : 0;
|
|
391
|
+
if (Array.isArray(store)) {
|
|
392
|
+
store.length = 0;
|
|
393
|
+
}
|
|
394
|
+
return { dynamicScriptsCleared };
|
|
395
|
+
})()
|
|
396
|
+
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`dynamicScriptsCleared`in e&&typeof e.dynamicScriptsCleared==`number`?e:{dynamicScriptsCleared:0}}catch(t){return e.error(`Failed to clear dynamic script buffer:`,t),{dynamicScriptsCleared:0}}}async function G(t){let n=H(t);if(!n.cdpSession)return{scriptMonitorReset:!1};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
397
|
+
(() => {
|
|
398
|
+
const state = window.__dynamicScriptMonitorState;
|
|
399
|
+
let scriptMonitorReset = false;
|
|
400
|
+
|
|
401
|
+
try {
|
|
402
|
+
if (state && state.observer && typeof state.observer.disconnect === 'function') {
|
|
403
|
+
state.observer.disconnect();
|
|
404
|
+
state.observer = null;
|
|
405
|
+
scriptMonitorReset = true;
|
|
406
|
+
}
|
|
407
|
+
} catch (_) {}
|
|
408
|
+
|
|
409
|
+
try {
|
|
410
|
+
if (state && state.originalCreateElement) {
|
|
411
|
+
document.createElement = state.originalCreateElement;
|
|
412
|
+
scriptMonitorReset = true;
|
|
413
|
+
}
|
|
414
|
+
} catch (_) {}
|
|
415
|
+
|
|
416
|
+
try {
|
|
417
|
+
if (state && state.originalEval) {
|
|
418
|
+
window.eval = state.originalEval;
|
|
419
|
+
scriptMonitorReset = true;
|
|
420
|
+
}
|
|
421
|
+
} catch (_) {}
|
|
422
|
+
|
|
423
|
+
try {
|
|
424
|
+
if (state && state.originalFunction) {
|
|
425
|
+
window.Function = state.originalFunction;
|
|
426
|
+
scriptMonitorReset = true;
|
|
427
|
+
}
|
|
428
|
+
} catch (_) {}
|
|
429
|
+
|
|
430
|
+
if (Array.isArray(window.__dynamicScripts)) {
|
|
431
|
+
window.__dynamicScripts.length = 0;
|
|
432
|
+
}
|
|
433
|
+
delete window.__getDynamicScripts;
|
|
434
|
+
window.__dynamicScriptMonitorInstalled = false;
|
|
435
|
+
|
|
436
|
+
return { scriptMonitorReset };
|
|
437
|
+
})()
|
|
438
|
+
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`scriptMonitorReset`in e&&typeof e.scriptMonitorReset==`boolean`?e:{scriptMonitorReset:!1}}catch(t){return e.error(`Failed to reset dynamic script monitoring:`,t),{scriptMonitorReset:!1}}}async function K(n){let r=H(n);if(!r.cdpSession)throw new t(`CDP session not initialized`);try{let e=(await r.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getDynamicScripts ? window.__getDynamicScripts() : []`,returnByValue:!0})).result?.value;return Array.isArray(e)?e:[]}catch(t){return e.error(`Failed to get dynamic scripts:`,t),[]}}async function q(n,r,i){let a=H(n);if(!a.cdpSession)throw new t(`CDP session not initialized`);let o=`
|
|
439
|
+
(function() {
|
|
440
|
+
const originalFunc = window.${r};
|
|
441
|
+
if (typeof originalFunc !== 'function') {
|
|
442
|
+
console.error('[Tracer] ${r} is not a function');
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
window.${r} = new Proxy(originalFunc, {
|
|
447
|
+
apply: function(target, thisArg, args) {
|
|
448
|
+
console.log('[Tracer] ${r} called with args:', args);
|
|
449
|
+
const startTime = performance.now();
|
|
450
|
+
|
|
451
|
+
try {
|
|
452
|
+
const result = target.apply(thisArg, args);
|
|
453
|
+
const endTime = performance.now();
|
|
454
|
+
console.log('[Tracer] ${r} returned:', result, 'Time:', (endTime - startTime).toFixed(2), 'ms');
|
|
455
|
+
return result;
|
|
456
|
+
} catch (error) {
|
|
457
|
+
console.error('[Tracer] ${r} threw error:', error);
|
|
458
|
+
throw error;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
console.log('[Tracer] ${r} is now being traced');
|
|
464
|
+
})();
|
|
465
|
+
`;i?.persistent?(await a.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:o}),e.info(`Function tracer injected for: ${r} (persistent)`)):(await a.cdpSession.send(`Runtime.evaluate`,{expression:o}),e.info(`Function tracer injected for: ${r}`))}async function J(n,r,i,a){let o=H(n);if(!o.cdpSession)throw new t(`CDP session not initialized`);let s=`
|
|
466
|
+
(function() {
|
|
467
|
+
const obj = ${r};
|
|
468
|
+
if (!obj) {
|
|
469
|
+
console.error('[Watcher] Object not found: ${r}');
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
let value = obj.${i};
|
|
474
|
+
|
|
475
|
+
Object.defineProperty(obj, '${i}', {
|
|
476
|
+
get: function() {
|
|
477
|
+
console.log('[Watcher] ${r}.${i} accessed, value:', value);
|
|
478
|
+
return value;
|
|
479
|
+
},
|
|
480
|
+
set: function(newValue) {
|
|
481
|
+
console.log('[Watcher] ${r}.${i} changed from', value, 'to', newValue);
|
|
482
|
+
value = newValue;
|
|
483
|
+
},
|
|
484
|
+
enumerable: true,
|
|
485
|
+
configurable: true
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
console.log('[Watcher] Property watcher installed for ${r}.${i}');
|
|
489
|
+
})();
|
|
490
|
+
`;a?.persistent?(await o.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:s}),e.info(`Property watcher injected for: ${r}.${i} (persistent)`)):(await o.cdpSession.send(`Runtime.evaluate`,{expression:s}),e.info(`Property watcher injected for: ${r}.${i}`))}function Y(e){return e}async function X(t,n,r,i){let a=Y(t);a.cdpSession=n,a.usingManagedTargetSession=r,a.lastEnableOptions={...i},a.cdpSession.on(`disconnected`,()=>{e.warn(`ConsoleMonitor CDP session disconnected`),a.cdpSession=null,a.networkMonitor=null,a.usingManagedTargetSession=!1}),await $(a.cdpSession,`Runtime.enable`,{},5e3),await $(a.cdpSession,`Console.enable`,{},5e3),a.cdpSession.on(`Runtime.consoleAPICalled`,t=>{let n=t.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],r={type:t.type,text:t.args.map(e=>a.formatRemoteObject(e)).join(` `),args:t.args.map(e=>a.extractValue(e)),timestamp:t.timestamp,stackTrace:n,url:n[0]?.url,lineNumber:n[0]?.lineNumber,columnNumber:n[0]?.columnNumber};a.messages.push(r),a.messages.length>a.MAX_MESSAGES&&(a.messages=a.messages.slice(-Math.floor(a.MAX_MESSAGES/2))),e.debug(`Console ${t.type}: ${r.text}`)}),a.cdpSession.on(`Console.messageAdded`,e=>{let t=e.message,n={type:t.level||`log`,text:t.text,timestamp:Date.now(),url:t.url,lineNumber:t.line,columnNumber:t.column};a.messages.push(n),a.messages.length>a.MAX_MESSAGES&&(a.messages=a.messages.slice(-Math.floor(a.MAX_MESSAGES/2)))}),i?.enableExceptions!==!1&&a.cdpSession.on(`Runtime.exceptionThrown`,t=>{let n=t.exceptionDetails,r=n.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],i={text:n.exception?.description||n.text,exceptionId:n.exceptionId,timestamp:Date.now(),stackTrace:r,url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,scriptId:n.scriptId};a.exceptions.push(i),a.exceptions.length>a.MAX_EXCEPTIONS&&(a.exceptions=a.exceptions.slice(-Math.floor(a.MAX_EXCEPTIONS/2))),e.error(`Exception thrown: ${i.text}`,{url:i.url,line:i.lineNumber})}),i?.enableNetwork&&(a.networkMonitor=new m(a.cdpSession),await a.networkMonitor.enable()),e.info(`ConsoleMonitor enabled`,{network:i?.enableNetwork||!1,exceptions:i?.enableExceptions!==!1})}async function Z(t,n){let r=Y(t);if(r.playwrightConsoleHandler){n?.enableNetwork&&!r.playwrightNetworkMonitor&&(r.playwrightNetworkMonitor=new h(r.playwrightPage),await r.playwrightNetworkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor Playwright session`));return}let i=r.playwrightPage;r.playwrightConsoleHandler=e=>{let t={type:e.type()||`log`,text:e.text(),timestamp:Date.now()};r.messages.push(t),r.messages.length>r.MAX_MESSAGES&&(r.messages=r.messages.slice(-Math.floor(r.MAX_MESSAGES/2)))},i.on(`console`,r.playwrightConsoleHandler),n?.enableExceptions!==!1&&(r.playwrightErrorHandler=e=>{let t={text:e.message,exceptionId:Date.now(),timestamp:Date.now()};r.exceptions.push(t),r.exceptions.length>r.MAX_EXCEPTIONS&&(r.exceptions=r.exceptions.slice(-Math.floor(r.MAX_EXCEPTIONS/2)))},i.on(`pageerror`,r.playwrightErrorHandler)),n?.enableNetwork&&(r.playwrightNetworkMonitor=new h(r.playwrightPage),await r.playwrightNetworkMonitor.enable()),e.info(`ConsoleMonitor enabled (Playwright/camoufox mode)`,{network:n?.enableNetwork||!1})}async function Q(t){let n=Y(t);if(n.playwrightPage){let e=n.playwrightPage;if(n.playwrightConsoleHandler){try{e.off(`console`,n.playwrightConsoleHandler)}catch{}n.playwrightConsoleHandler=null}if(n.playwrightErrorHandler){try{e.off(`pageerror`,n.playwrightErrorHandler)}catch{}n.playwrightErrorHandler=null}}if(n.playwrightNetworkMonitor&&=(await n.playwrightNetworkMonitor.disable(),null),n.cdpSession){n.networkMonitor&&=(await n.networkMonitor.disable(),null);try{await n.cdpSession.send(`Console.disable`)}catch(t){e.warn(`Failed to disable Console domain:`,t)}try{await n.cdpSession.send(`Runtime.disable`)}catch(t){e.warn(`Failed to disable Runtime domain:`,t)}if(n.usingManagedTargetSession)e.debug(`ConsoleMonitor released managed target session without detaching target`);else try{await n.cdpSession.detach()}catch(t){e.warn(`Failed to detach ConsoleMonitor CDP session:`,t)}n.cdpSession=null,n.usingManagedTargetSession=!1,e.info(`ConsoleMonitor disabled`)}}async function $(e,t,n,r=3e4){return Promise.race([e.send(t,n),new Promise((e,n)=>setTimeout(()=>n(Error(`CDP ${t} timed out after ${r}ms`)),r))])}var ee=class{collector;cdpSession=null;networkMonitor=null;fetchInterceptor=null;playwrightNetworkMonitor=null;playwrightPage=null;usingManagedTargetSession=!1;contextSwitchPending=!1;playwrightConsoleHandler=null;playwrightErrorHandler=null;messages=[];MAX_MESSAGES=1e3;exceptions=[];MAX_EXCEPTIONS=500;MAX_INJECTED_DYNAMIC_SCRIPTS=500;MAX_OBJECT_CACHE_SIZE=1e3;objectCache=new Map;initPromise;lastEnableOptions={};constructor(e){this.collector=e,this.touchSplitMembersForTypeCheck()}touchSplitMembersForTypeCheck(){this.MAX_INJECTED_DYNAMIC_SCRIPTS,this.MAX_OBJECT_CACHE_SIZE,this.clearDynamicScriptBuffer,this.resetDynamicScriptMonitoring,this.usingManagedTargetSession,this.playwrightErrorHandler,this.messages,this.MAX_MESSAGES,this.exceptions,this.MAX_EXCEPTIONS,this.formatRemoteObject,this.extractValue}setPlaywrightPage(e){this.playwrightPage=e,this.playwrightNetworkMonitor?.setPage(e)}clearPlaywrightPage(){this.playwrightPage=null,this.contextSwitchPending=!1,this.playwrightConsoleHandler=null,this.playwrightErrorHandler=null,this.playwrightNetworkMonitor?.setPage(null),this.playwrightNetworkMonitor=null}getManagedTargetSession(){return this.collector.getAttachedTargetSession?.()??null}async createCdpSession(){let e=this.getManagedTargetSession();if(e)return{session:e,managed:!0};let t=await this.collector.getActivePage();return{session:await Promise.race([t.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),managed:!1}}markContextChanged(){!this.cdpSession&&!this.playwrightPage&&!this.networkMonitor&&!this.playwrightNetworkMonitor&&!this.fetchInterceptor||(this.contextSwitchPending=!0,this.clearLogs(),this.clearExceptions(),this.clearNetworkRecords(),this.clearObjectCache(),e.info(`ConsoleMonitor marked stale after active context switch`))}async enable(e){if(this.contextSwitchPending&&await this.disable(),this.initPromise){await this.initPromise,await this.applyPostEnableOptions(e);return}this.initPromise=this.doEnable(e);try{await this.initPromise}finally{this.initPromise=void 0}}async doEnable(t){if(this.playwrightPage)return this.lastEnableOptions={...t},Z(this,t);if(this.cdpSession){t?.enableNetwork&&!this.networkMonitor&&(this.networkMonitor=new m(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`));return}let{session:n,managed:r}=await this.createCdpSession();await X(this,n,r,t)}async applyPostEnableOptions(t){if(t?.enableNetwork){if(this.lastEnableOptions={...this.lastEnableOptions,...t},this.playwrightPage&&this.playwrightConsoleHandler&&!this.playwrightNetworkMonitor){await Z(this,t);return}this.cdpSession&&!this.networkMonitor&&(this.networkMonitor=new m(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`))}}async disable(){try{this.cdpSession&&this.fetchInterceptor&&(await this.fetchInterceptor.disable(),this.fetchInterceptor=null),await Q(this)}finally{this.fetchInterceptor=null,this.initPromise=void 0,this.contextSwitchPending=!1,this.objectCache.clear()}}async ensureSession(){if(this.contextSwitchPending){e.info(`ConsoleMonitor context switched, rebinding on demand...`);let t={...this.lastEnableOptions};await this.disable(),await this.enable(t);return}if(!this.cdpSession&&!this.playwrightPage){e.info(`ConsoleMonitor CDP session lost, reinitializing...`),await this.enable(this.lastEnableOptions);return}if(this.cdpSession)try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{e.warn(`ConsoleMonitor CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.networkMonitor=null,this.fetchInterceptor=null,this.usingManagedTargetSession=!1,await this.enable(this.lastEnableOptions)}}isSessionActive(){return!this.contextSwitchPending&&(this.cdpSession!==null||this.playwrightPage!==null)}getLogs(e){return v(this,e)}async execute(t){await this.ensureSession();try{let n=await $(this.cdpSession,`Runtime.evaluate`,{expression:t,returnByValue:!0});if(n.exceptionDetails)throw e.error(`Console execute error:`,n.exceptionDetails),Error(n.exceptionDetails.text);return e.info(`Console expression executed`),n.result.value}catch(t){throw e.error(`Console execute failed:`,t),t}}clearLogs(){y(this)}getStats(){return b(this)}async close(){try{await this.disable()}finally{this.initPromise=void 0,this.objectCache.clear()}}isNetworkEnabled(){return T(this)}getNetworkStatus(){return E(this)}getNetworkRequests(e){return D(this,e)}getNetworkResponses(e){return O(this,e)}getNetworkActivity(e){return k(this,e)}async getResponseBody(e){return A(this,e)}async getAllJavaScriptResponses(){return j(this)}clearNetworkRecords(){M(this)}async clearInjectedBuffers(){return N(this)}async resetInjectedInterceptors(){return P(this)}getNetworkStats(){return F(this)}async injectXHRInterceptor(e){return I(this,e)}async injectFetchInterceptor(e){return L(this,e)}async getXHRRequests(){return R(this)}async getFetchRequests(){return z(this)}getExceptions(e){return x(this,e)}clearExceptions(){S(this)}async inspectObject(e){return B(this,e)}clearObjectCache(){V(this)}async enableDynamicScriptMonitoring(e){return U(this,e)}async clearDynamicScriptBuffer(){return W(this)}async resetDynamicScriptMonitoring(){return G(this)}async getDynamicScripts(){return K(this)}async injectFunctionTracer(e,t){return q(this,e,t)}async injectPropertyWatcher(e,t,n){return J(this,e,t,n)}async enableFetchIntercept(e){if(await this.ensureSession(),!this.cdpSession)throw Error(`No CDP session available for Fetch interception`);return this.fetchInterceptor||=new g(this.cdpSession),this.fetchInterceptor.enable(e)}async disableFetchIntercept(){if(!this.fetchInterceptor)return{removedRules:0};let e=await this.fetchInterceptor.disable();return this.fetchInterceptor=null,e}async removeFetchInterceptRule(e){if(!this.fetchInterceptor)return!1;let t=await this.fetchInterceptor.removeRule(e);return this.fetchInterceptor.isEnabled()||(this.fetchInterceptor=null),t}getFetchInterceptStatus(){return this.fetchInterceptor?this.fetchInterceptor.listRules():{enabled:!1,rules:[],totalHits:0}}formatRemoteObject(e){return e.value===void 0?e.description?e.description:e.type===`undefined`?`undefined`:e.type===`object`&&e.subtype===`null`?`null`:`[${e.type}]`:String(e.value)}extractValue(e){if(e.value!==void 0)return e.value;if(e.type!==`undefined`)return e.type===`object`&&e.subtype===`null`?null:e.objectId?{__objectId:e.objectId,__type:e.type,__description:e.description}:e.description||`[${e.type}]`}};export{ee as ConsoleMonitor};
|