@jshookmcp/jshook 0.2.8 → 0.3.0

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 (162) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-CqGDXmfc.mjs} +160 -54
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-BdjRfNx7.mjs} +5 -5
  5. package/dist/ConsoleMonitor-DykL3IAw.mjs +2269 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-ETyy0xyo.mjs} +1 -1
  7. package/dist/DetailedDataManager-HT49OrvF.mjs +217 -0
  8. package/dist/EventBus-DFKvADm3.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +153 -0
  10. package/dist/{ExtensionManager-D5-bO9D8.mjs → ExtensionManager-BDMsY2Dz.mjs} +27 -13
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-BN4UQWnX.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-Cc2AFq1Y.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-DruMgsgj.mjs} +21 -21
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs +566 -0
  15. package/dist/InstrumentationSession-DLH0vd-z.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CMtviNW_.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-ITgb_NMi.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-CiL7Z3ey.mjs} +50 -21
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-D9Lkovvn.mjs} +20 -56
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-BBlAixF5.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-DMQ44gen.mjs} +16 -16
  22. package/dist/PageController-BPJNqqBN.mjs +431 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-K7wN8Z-w.mjs} +10 -7
  24. package/dist/PrerequisiteError-TuyZIs6n.mjs +20 -0
  25. package/dist/ProcessRegistry-zGg12QbE.mjs +74 -0
  26. package/dist/ResponseBuilder-CJXWmWNw.mjs +143 -0
  27. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +269 -0
  28. package/dist/ScriptManager-ZuWD-0Jg.mjs +3003 -0
  29. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-D-z0umeT.mjs} +2 -2
  30. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-Cav5AVSL.mjs} +9 -6
  31. package/dist/ToolCatalog-5OJdMiF0.mjs +582 -0
  32. package/dist/ToolError-jh9whhMd.mjs +15 -0
  33. package/dist/ToolProbe-DbCFGyrg.mjs +45 -0
  34. package/dist/ToolRegistry-B9krbTtI.mjs +180 -0
  35. package/dist/ToolRouter.policy-BGDAGyeH.mjs +344 -0
  36. package/dist/TraceRecorder-B41Z5XBj.mjs +1286 -0
  37. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-C2kjj0ze.mjs} +19 -13
  38. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-CKrGOTpo.mjs} +3 -3
  39. package/dist/WorkflowEngine-DJ6M4opp.mjs +569 -0
  40. package/dist/analysis-BHeJW2Nb.mjs +1234 -0
  41. package/dist/antidebug-BRKeyt27.mjs +1081 -0
  42. package/dist/artifactRetention-CPXkUJXp.mjs +598 -0
  43. package/dist/artifacts-DkfosXH3.mjs +59 -0
  44. package/dist/authorization-schema-DRqyJMSk.mjs +31 -0
  45. package/dist/betterSqlite3-DLSBZodi.mjs +74 -0
  46. package/dist/binary-instrument--V3MAhJ4.mjs +971 -0
  47. package/dist/bind-helpers-ClV34xdn.mjs +42 -0
  48. package/dist/boringssl-inspector-Bo_LOLaS.mjs +180 -0
  49. package/dist/browser-Dx3_S2cG.mjs +4369 -0
  50. package/dist/capabilities-CcHlvWgK.mjs +33 -0
  51. package/dist/concurrency-Drev_Vz9.mjs +41 -0
  52. package/dist/{constants-CCvsN80K.mjs → constants-CDZLOoVv.mjs} +105 -48
  53. package/dist/coordination-DgItD9DL.mjs +259 -0
  54. package/dist/debugger-RS3RSAqs.mjs +1288 -0
  55. package/dist/definitions-BEoYofW5.mjs +47 -0
  56. package/dist/definitions-BRaefg3u.mjs +365 -0
  57. package/dist/definitions-BbkvZkiv.mjs +96 -0
  58. package/dist/definitions-BtWSHJ3o.mjs +17 -0
  59. package/dist/definitions-C1gCHO0i.mjs +43 -0
  60. package/dist/definitions-CDOg_b-l.mjs +138 -0
  61. package/dist/definitions-CVPD9hzZ.mjs +54 -0
  62. package/dist/definitions-Cea8Lgl7.mjs +94 -0
  63. package/dist/definitions-DAgIyjxM.mjs +10 -0
  64. package/dist/definitions-DJA27nsL.mjs +66 -0
  65. package/dist/definitions-DKPFU3LW.mjs +25 -0
  66. package/dist/definitions-DPRpZQ96.mjs +47 -0
  67. package/dist/definitions-DUE5gmdn.mjs +18 -0
  68. package/dist/definitions-DYVjOtxa.mjs +26 -0
  69. package/dist/definitions-DcYLVLCo.mjs +37 -0
  70. package/dist/definitions-Pp5LI2H4.mjs +27 -0
  71. package/dist/definitions-j9KdHVNR.mjs +14 -0
  72. package/dist/definitions-uzkjBwa7.mjs +258 -0
  73. package/dist/definitions-va-AnLuQ.mjs +28 -0
  74. package/dist/encoding-DJeqHmpd.mjs +1079 -0
  75. package/dist/evidence-graph-bridge-DcYizFk2.mjs +136 -0
  76. package/dist/{factory-CibqTNC8.mjs → factory-C90tBff6.mjs} +41 -56
  77. package/dist/flat-target-session-Dgax2Cy3.mjs +29 -0
  78. package/dist/graphql-CoHrhweh.mjs +1197 -0
  79. package/dist/handlers-4jmR0nMs.mjs +898 -0
  80. package/dist/handlers-BAHPxcch.mjs +789 -0
  81. package/dist/handlers-BOs9b907.mjs +2600 -0
  82. package/dist/handlers-BWXEy6ef.mjs +917 -0
  83. package/dist/handlers-Bndn6QvE.mjs +111 -0
  84. package/dist/handlers-BqC4bD4s.mjs +681 -0
  85. package/dist/handlers-BtYq60bM2.mjs +276 -0
  86. package/dist/handlers-BzgcB4iv.mjs +799 -0
  87. package/dist/handlers-CRyRWj2b.mjs +859 -0
  88. package/dist/handlers-CVv2H1uq.mjs +592 -0
  89. package/dist/handlers-Dl5a7JS4.mjs +572 -0
  90. package/dist/handlers-Dx2d7jt7.mjs +2537 -0
  91. package/dist/handlers-Dz9PYsCa.mjs +2805 -0
  92. package/dist/handlers-HujRKC3b.mjs +661 -0
  93. package/dist/handlers.impl-XWXkQfyi.mjs +807 -0
  94. package/dist/hooks-B1B8NRHL.mjs +898 -0
  95. package/dist/index.mjs +491 -259
  96. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  97. package/dist/maintenance-PRMkLVRW.mjs +835 -0
  98. package/dist/manifest-67Bok-Si.mjs +58 -0
  99. package/dist/manifest-6lNTMZAB2.mjs +87 -0
  100. package/dist/manifest-B2duEHiH.mjs +90 -0
  101. package/dist/manifest-B6EY9Vm8.mjs +57 -0
  102. package/dist/manifest-B6nKSbyY.mjs +95 -0
  103. package/dist/manifest-BL8AQNPF.mjs +106 -0
  104. package/dist/manifest-BSZvJJmV.mjs +47 -0
  105. package/dist/manifest-BU7qzUyX.mjs +418 -0
  106. package/dist/manifest-Bl62e8WK.mjs +49 -0
  107. package/dist/manifest-Bo5cXjdt.mjs +82 -0
  108. package/dist/manifest-BpS4gtUK.mjs +1347 -0
  109. package/dist/manifest-Bv65_e2W.mjs +101 -0
  110. package/dist/manifest-BytNIF4Z.mjs +117 -0
  111. package/dist/manifest-C-xtsjS3.mjs +81 -0
  112. package/dist/manifest-CDYl7OhA.mjs +66 -0
  113. package/dist/manifest-CRZ3xmkD.mjs +61 -0
  114. package/dist/manifest-CoW6u4Tp.mjs +132 -0
  115. package/dist/manifest-Cq5zN_8A.mjs +50 -0
  116. package/dist/manifest-D7YZM_2e.mjs +194 -0
  117. package/dist/manifest-DE_VrAeQ.mjs +314 -0
  118. package/dist/manifest-DGsXSCpT.mjs +39 -0
  119. package/dist/manifest-DJ2vfEuW.mjs +156 -0
  120. package/dist/manifest-DPXDYhEu.mjs +80 -0
  121. package/dist/manifest-Dd4fQb0a.mjs +322 -0
  122. package/dist/manifest-Deq6opGg.mjs +223 -0
  123. package/dist/manifest-DfJTafJK.mjs +37 -0
  124. package/dist/manifest-DgOdgN_j.mjs +50 -0
  125. package/dist/manifest-DlbMW4v4.mjs +47 -0
  126. package/dist/manifest-DmVfbH0w.mjs +374 -0
  127. package/dist/manifest-Dog6Ddjr.mjs +109 -0
  128. package/dist/manifest-DvgU5FWb.mjs +58 -0
  129. package/dist/manifest-HsfDBs7j.mjs +50 -0
  130. package/dist/manifest-I8oQHvCG.mjs +186 -0
  131. package/dist/manifest-NvH_a-av.mjs +786 -0
  132. package/dist/manifest-cEJU1v0Z.mjs +129 -0
  133. package/dist/manifest-wOl5XLB12.mjs +112 -0
  134. package/dist/modules-tZozf0LQ.mjs +10635 -0
  135. package/dist/mojo-ipc-DXNEXEqb.mjs +640 -0
  136. package/dist/network-CPVvwvFg.mjs +3852 -0
  137. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-um7lCRY3.mjs} +219 -216
  138. package/dist/parse-args-B4cY5Vx5.mjs +39 -0
  139. package/dist/platform-CYeFoTWp.mjs +2161 -0
  140. package/dist/process-BTbgcVc6.mjs +1306 -0
  141. package/dist/proxy-r8YN6nP1.mjs +192 -0
  142. package/dist/registry-Bl8ZQW61.mjs +34 -0
  143. package/dist/response-CWhh2aLo.mjs +34 -0
  144. package/dist/server/plugin-api.mjs +2 -2
  145. package/dist/shared-state-board-BoZnSoj-.mjs +586 -0
  146. package/dist/sourcemap-BIDHUVXy.mjs +934 -0
  147. package/dist/ssrf-policy-Dsqd-DTX.mjs +166 -0
  148. package/dist/streaming-Dal6utPp.mjs +725 -0
  149. package/dist/tool-builder-BHJp32mV.mjs +186 -0
  150. package/dist/transform-DRVgGG90.mjs +1011 -0
  151. package/dist/types-Bx92KJfT.mjs +4 -0
  152. package/dist/wasm-BYx5UOeG.mjs +1044 -0
  153. package/dist/webcrack-Be0_FccV.mjs +747 -0
  154. package/dist/workflow-BpuKEtvn.mjs +725 -0
  155. package/package.json +82 -49
  156. package/dist/ExtensionManager-CPTJhHFg.mjs +0 -2
  157. package/dist/ToolCatalog-Bq4V2sbJ.mjs +0 -67201
  158. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-jJFy20G-.mjs} +0 -0
  159. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-BWmPgQsv.mjs} +0 -0
  160. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-K3V4vGsw.mjs} +0 -0
  161. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-nnMvEohD.mjs} +0 -0
  162. package/dist/{types-BBjOqye-.mjs → types-DDBWs9UP.mjs} +1 -1
@@ -0,0 +1,934 @@
1
+ import { cr as SOURCEMAP_V4_RETRY_DELAY_MS, sr as SOURCEMAP_V4_RAW_FIELD_MAX_LEN } from "./constants-CDZLOoVv.mjs";
2
+ import { i as resolveArtifactPath } from "./artifacts-DkfosXH3.mjs";
3
+ import { n as detachFromFlatTarget, t as attachToFlatTarget } from "./flat-target-session-Dgax2Cy3.mjs";
4
+ import { s as evaluateWithTimeout } from "./PageController-BPJNqqBN.mjs";
5
+ import "./definitions-DAgIyjxM.mjs";
6
+ import { dirname, resolve } from "node:path";
7
+ import { mkdir, writeFile } from "node:fs/promises";
8
+ //#region src/server/domains/sourcemap/handlers/shared.ts
9
+ const BASE64_DECODE_MAP = new Map(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((char, index) => [char, index]));
10
+ function fromVlqSigned(value) {
11
+ const isNegative = (value & 1) === 1;
12
+ const shifted = value >> 1;
13
+ return isNegative ? -shifted : shifted;
14
+ }
15
+ function decodeVlqSegment(segment) {
16
+ const values = [];
17
+ let index = 0;
18
+ while (index < segment.length) {
19
+ let result = 0;
20
+ let shift = 0;
21
+ let continuation = true;
22
+ while (continuation) {
23
+ const char = segment.charAt(index);
24
+ if (!char) throw new Error(`Unexpected end of VLQ segment: "${segment}"`);
25
+ index += 1;
26
+ const digit = BASE64_DECODE_MAP.get(char);
27
+ if (digit === void 0) throw new Error(`Invalid VLQ base64 char "${char}" in segment "${segment}"`);
28
+ continuation = (digit & 32) !== 0;
29
+ const digitValue = digit & 31;
30
+ result += digitValue << shift;
31
+ shift += 5;
32
+ }
33
+ values.push(fromVlqSigned(result));
34
+ }
35
+ return values;
36
+ }
37
+ function decodeVlqSegmentUnsigned(segment) {
38
+ const values = [];
39
+ let index = 0;
40
+ while (index < segment.length) {
41
+ let result = 0;
42
+ let shift = 0;
43
+ let continuation = true;
44
+ while (continuation) {
45
+ const char = segment.charAt(index);
46
+ if (!char) throw new Error(`Unexpected end of VLQ segment: "${segment}"`);
47
+ index += 1;
48
+ const digit = BASE64_DECODE_MAP.get(char);
49
+ if (digit === void 0) throw new Error(`Invalid VLQ base64 char "${char}" in segment "${segment}"`);
50
+ continuation = (digit & 32) !== 0;
51
+ const digitValue = digit & 31;
52
+ result += digitValue << shift;
53
+ shift += 5;
54
+ }
55
+ values.push(result);
56
+ }
57
+ return values;
58
+ }
59
+ function decodeMappings(mappings) {
60
+ if (!mappings) return [];
61
+ const decoded = [];
62
+ let previousSource = 0;
63
+ let previousOriginalLine = 0;
64
+ let previousOriginalColumn = 0;
65
+ let previousName = 0;
66
+ const lines = mappings.split(";");
67
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
68
+ const line = lines[lineIndex] ?? "";
69
+ let generatedColumn = 0;
70
+ if (!line) continue;
71
+ const segments = line.split(",");
72
+ for (const segment of segments) {
73
+ if (!segment) continue;
74
+ const values = decodeVlqSegment(segment);
75
+ const generatedDelta = values[0];
76
+ if (generatedDelta === void 0) continue;
77
+ generatedColumn += generatedDelta;
78
+ const mapping = {
79
+ generatedLine: lineIndex + 1,
80
+ generatedColumn
81
+ };
82
+ if (values.length >= 4) {
83
+ previousSource += values[1] ?? 0;
84
+ previousOriginalLine += values[2] ?? 0;
85
+ previousOriginalColumn += values[3] ?? 0;
86
+ mapping.sourceIndex = previousSource;
87
+ mapping.originalLine = previousOriginalLine + 1;
88
+ mapping.originalColumn = previousOriginalColumn;
89
+ if (values.length >= 5) {
90
+ previousName += values[4] ?? 0;
91
+ mapping.nameIndex = previousName;
92
+ }
93
+ }
94
+ decoded.push(mapping);
95
+ }
96
+ }
97
+ return decoded;
98
+ }
99
+ function countMappingsStats(mappings) {
100
+ if (!mappings) return {
101
+ mappingsCount: 0,
102
+ segmentCount: 0
103
+ };
104
+ let mappingsCount = 0;
105
+ let segmentCount = 0;
106
+ let inNonEmptyLine = false;
107
+ for (let i = 0; i < mappings.length; i++) {
108
+ const ch = mappings[i];
109
+ if (ch === ";") {
110
+ if (inNonEmptyLine) mappingsCount++;
111
+ inNonEmptyLine = false;
112
+ } else if (ch === ",") segmentCount++;
113
+ else if (!inNonEmptyLine) {
114
+ inNonEmptyLine = true;
115
+ segmentCount++;
116
+ }
117
+ }
118
+ if (inNonEmptyLine) mappingsCount++;
119
+ return {
120
+ mappingsCount,
121
+ segmentCount
122
+ };
123
+ }
124
+ function json(payload) {
125
+ return { content: [{
126
+ type: "text",
127
+ text: JSON.stringify(payload, null, 2)
128
+ }] };
129
+ }
130
+ function fail(tool, error) {
131
+ return json({
132
+ success: false,
133
+ tool,
134
+ error: error instanceof Error ? error.message : String(error)
135
+ });
136
+ }
137
+ function asRecord(value) {
138
+ return typeof value === "object" && value !== null ? value : {};
139
+ }
140
+ function asString(value) {
141
+ return typeof value === "string" ? value : void 0;
142
+ }
143
+ function hasProtocol(value) {
144
+ return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
145
+ }
146
+ function parseBooleanArg(value, defaultValue) {
147
+ return typeof value === "boolean" ? value : defaultValue;
148
+ }
149
+ function requiredStringArg(value, fieldName) {
150
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${fieldName} is required`);
151
+ return value.trim();
152
+ }
153
+ function optionalStringArg(value) {
154
+ if (typeof value !== "string") return void 0;
155
+ const trimmed = value.trim();
156
+ return trimmed.length > 0 ? trimmed : void 0;
157
+ }
158
+ async function safeDetach(session) {
159
+ if (!session.detach) return;
160
+ try {
161
+ await session.detach();
162
+ } catch {}
163
+ }
164
+ async function trySend(session, method, params) {
165
+ try {
166
+ await session.send(method, params);
167
+ } catch {}
168
+ }
169
+ async function delay(ms) {
170
+ await new Promise((r) => setTimeout(() => r(), ms));
171
+ }
172
+ //#endregion
173
+ //#region src/server/domains/sourcemap/handlers/extension-handlers.ts
174
+ var ExtensionHandlers = class {
175
+ state;
176
+ constructor(state) {
177
+ this.state = state;
178
+ }
179
+ async handleExtensionListInstalled(_args) {
180
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
181
+ try {
182
+ return json((await this.getExtensionTargets(session)).map((target) => ({
183
+ extensionId: target.extensionId,
184
+ name: target.name,
185
+ type: target.type,
186
+ url: target.url
187
+ })));
188
+ } catch (error) {
189
+ return fail("extension_list_installed", error);
190
+ } finally {
191
+ await safeDetach(session);
192
+ }
193
+ }
194
+ async handleExtensionExecuteInContext(args) {
195
+ const extensionId = requiredStringArg(args.extensionId, "extensionId");
196
+ const code = requiredStringArg(args.code, "code");
197
+ const returnByValue = parseBooleanArg(args.returnByValue, true);
198
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
199
+ let attachedSession = null;
200
+ try {
201
+ const targets = await this.getExtensionTargets(session, extensionId);
202
+ if (targets.length === 0) throw new Error(`No background target found for extension: ${extensionId}`);
203
+ const preferred = this.pickPreferredExtensionTarget(targets);
204
+ attachedSession = await attachToFlatTarget(session, preferred.targetId);
205
+ const evaluation = await this.evaluateInAttachedTarget(attachedSession, code, returnByValue);
206
+ return json({
207
+ extensionId,
208
+ target: {
209
+ type: preferred.type,
210
+ url: preferred.url,
211
+ name: preferred.name
212
+ },
213
+ result: evaluation.result,
214
+ exceptionDetails: evaluation.exceptionDetails
215
+ });
216
+ } catch (error) {
217
+ return fail("extension_execute_in_context", error);
218
+ } finally {
219
+ if (attachedSession) await detachFromFlatTarget(session, attachedSession).catch(() => void 0);
220
+ await safeDetach(session);
221
+ }
222
+ }
223
+ async getExtensionTargets(session, expectedExtensionId) {
224
+ const response = asRecord(await session.send("Target.getTargets"));
225
+ const targetInfos = Array.isArray(response.targetInfos) ? response.targetInfos : [];
226
+ const allowedTypes = new Set(["service_worker", "background_page"]);
227
+ const result = [];
228
+ for (const item of targetInfos) {
229
+ const record = asRecord(item);
230
+ const targetId = asString(record.targetId);
231
+ const type = asString(record.type);
232
+ const url = asString(record.url);
233
+ if (!targetId || !type || !url) continue;
234
+ if (!allowedTypes.has(type)) continue;
235
+ const extensionId = this.extractExtensionId(url);
236
+ if (!extensionId) continue;
237
+ if (expectedExtensionId && extensionId !== expectedExtensionId) continue;
238
+ const title = asString(record.title) ?? "";
239
+ result.push({
240
+ targetId,
241
+ extensionId,
242
+ name: title || extensionId,
243
+ type,
244
+ url
245
+ });
246
+ }
247
+ result.sort((left, right) => {
248
+ const leftScore = left.type === "service_worker" ? 0 : 1;
249
+ const rightScore = right.type === "service_worker" ? 0 : 1;
250
+ if (leftScore !== rightScore) return leftScore - rightScore;
251
+ return left.extensionId.localeCompare(right.extensionId);
252
+ });
253
+ return result;
254
+ }
255
+ pickPreferredExtensionTarget(targets) {
256
+ return targets.find((target) => target.type === "service_worker") ?? targets[0];
257
+ }
258
+ extractExtensionId(url) {
259
+ return url.match(/^chrome-extension:\/\/([a-p]{32})(?:\/|$)/i)?.[1] ?? null;
260
+ }
261
+ async evaluateInAttachedTarget(session, code, returnByValue) {
262
+ const response = asRecord(await session.send("Runtime.evaluate", {
263
+ expression: code,
264
+ returnByValue,
265
+ awaitPromise: true
266
+ }));
267
+ const resultEnvelope = asRecord(response.result);
268
+ return {
269
+ result: returnByValue && resultEnvelope.value !== void 0 ? resultEnvelope.value : Object.keys(resultEnvelope).length > 0 ? resultEnvelope : null,
270
+ exceptionDetails: response.exceptionDetails !== void 0 ? response.exceptionDetails : null
271
+ };
272
+ }
273
+ };
274
+ //#endregion
275
+ //#region src/server/domains/sourcemap/handlers/sourcemap-parsing.ts
276
+ /**
277
+ * Sourcemap parsing, URL resolution, and path normalization functions.
278
+ */
279
+ function parseSourceMap(sourceMapUrl, scriptUrl, collector) {
280
+ return loadSourceMap(sourceMapUrl, scriptUrl, collector).then((loaded) => {
281
+ const mappings = decodeMappings(loaded.map.mappings);
282
+ const generatedLines = new Set(mappings.map((item) => item.generatedLine));
283
+ return {
284
+ resolvedUrl: loaded.resolvedUrl,
285
+ map: loaded.map,
286
+ mappings,
287
+ mappingsCount: generatedLines.size,
288
+ segmentCount: mappings.length
289
+ };
290
+ });
291
+ }
292
+ function parseSourceMapStats(sourceMapUrl, scriptUrl, collector) {
293
+ return loadSourceMap(sourceMapUrl, scriptUrl, collector).then((loaded) => {
294
+ const { mappingsCount, segmentCount } = countMappingsStats(loaded.map.mappings);
295
+ return {
296
+ resolvedUrl: loaded.resolvedUrl,
297
+ map: loaded.map,
298
+ mappingsCount,
299
+ segmentCount
300
+ };
301
+ });
302
+ }
303
+ async function loadSourceMap(sourceMapUrl, scriptUrl, collector) {
304
+ const resolvedUrl = resolveSourceMapUrl(sourceMapUrl, scriptUrl ?? "");
305
+ let sourceMapText = "";
306
+ if (resolvedUrl.startsWith("data:")) sourceMapText = decodeDataUriJson(resolvedUrl);
307
+ else sourceMapText = await fetchSourceMapText(resolvedUrl, collector);
308
+ let parsedJson;
309
+ try {
310
+ parsedJson = JSON.parse(sourceMapText);
311
+ } catch {
312
+ throw new Error(`Invalid SourceMap JSON: ${resolvedUrl}`);
313
+ }
314
+ return {
315
+ resolvedUrl,
316
+ map: normalizeSourceMap(parsedJson)
317
+ };
318
+ }
319
+ function normalizeSourceMap(value) {
320
+ const record = asRecord(value);
321
+ if (record.version !== 3) throw new Error("Only SourceMap version 3 is supported");
322
+ const mappings = asString(record.mappings);
323
+ if (mappings === void 0) throw new Error("SourceMap.mappings is required");
324
+ const sources = (Array.isArray(record.sources) ? record.sources : []).map((item) => asString(item)).filter((item) => typeof item === "string");
325
+ const names = (Array.isArray(record.names) ? record.names : []).map((item) => asString(item)).filter((item) => typeof item === "string");
326
+ const sourceRoot = asString(record.sourceRoot);
327
+ let sourcesContent;
328
+ if (Array.isArray(record.sourcesContent)) sourcesContent = record.sourcesContent.map((item) => typeof item === "string" ? item : null);
329
+ return {
330
+ version: 3,
331
+ sources,
332
+ sourcesContent,
333
+ mappings,
334
+ names,
335
+ sourceRoot
336
+ };
337
+ }
338
+ async function fetchSourceMapText(resolvedUrl, collector) {
339
+ validateFetchUrl(resolvedUrl);
340
+ {
341
+ const ac = new AbortController();
342
+ const t = setTimeout(() => ac.abort(), 1e4);
343
+ try {
344
+ const response = await fetch(resolvedUrl, { signal: ac.signal });
345
+ if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
346
+ return await response.text();
347
+ } catch (err) {
348
+ if (err.name === "AbortError") throw new Error(`SourceMap fetch timed out after 10s: ${resolvedUrl}`, { cause: err });
349
+ } finally {
350
+ clearTimeout(t);
351
+ }
352
+ }
353
+ const fetched = await evaluateWithTimeout(await collector.getActivePage(), async (url) => {
354
+ const ac = new AbortController();
355
+ const t = setTimeout(() => ac.abort(), 1e4);
356
+ try {
357
+ const resp = await fetch(url, { signal: ac.signal });
358
+ if (!resp.ok) return `__FETCH_ERROR__HTTP ${resp.status} ${resp.statusText}`;
359
+ return await resp.text();
360
+ } catch (error) {
361
+ return `__FETCH_ERROR__${error instanceof Error ? error.message : String(error)}`;
362
+ } finally {
363
+ clearTimeout(t);
364
+ }
365
+ }, resolvedUrl);
366
+ if (typeof fetched !== "string") throw new Error("Failed to fetch SourceMap content");
367
+ if (fetched.startsWith("__FETCH_ERROR__")) throw new Error(fetched.slice(15) || "Failed to fetch SourceMap content");
368
+ return fetched;
369
+ }
370
+ function validateFetchUrl(url) {
371
+ let parsed;
372
+ try {
373
+ parsed = new URL(url);
374
+ } catch {
375
+ throw new Error(`Invalid URL: ${url}`);
376
+ }
377
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`Blocked: unsupported protocol "${parsed.protocol}"`);
378
+ const hostname = parsed.hostname.toLowerCase();
379
+ const blockedPatterns = [
380
+ /^127\./,
381
+ /^10\./,
382
+ /^172\.(1[6-9]|2\d|3[01])\./,
383
+ /^192\.168\./,
384
+ /^0\./,
385
+ /^169\.254\./,
386
+ /^\[?::1\]?$/,
387
+ /^\[?fe80:/i,
388
+ /^\[?fc00:/i,
389
+ /^\[?fd/i
390
+ ];
391
+ if ([
392
+ "localhost",
393
+ "metadata.google.internal",
394
+ "metadata"
395
+ ].includes(hostname)) throw new Error(`SSRF blocked: hostname "${hostname}" is not allowed`);
396
+ for (const pattern of blockedPatterns) if (pattern.test(hostname)) throw new Error(`SSRF blocked: protected/reserved IP "${hostname}" is not allowed`);
397
+ }
398
+ function decodeDataUriJson(dataUri) {
399
+ const commaIndex = dataUri.indexOf(",");
400
+ if (commaIndex === -1) throw new Error("Invalid data URI source map");
401
+ const metadata = dataUri.slice(0, commaIndex);
402
+ const dataPart = dataUri.slice(commaIndex + 1);
403
+ if (/;base64/i.test(metadata)) return Buffer.from(dataPart, "base64").toString("utf-8");
404
+ return decodeURIComponent(dataPart);
405
+ }
406
+ function resolveSourceMapUrl(sourceMapUrl, scriptUrl) {
407
+ const trimmed = sourceMapUrl.trim();
408
+ if (!trimmed) return "";
409
+ if (trimmed.startsWith("data:")) return trimmed;
410
+ if (hasProtocol(trimmed)) return trimmed;
411
+ if (!scriptUrl) return trimmed;
412
+ try {
413
+ return new URL(trimmed, scriptUrl).toString();
414
+ } catch {
415
+ return trimmed;
416
+ }
417
+ }
418
+ function extractSourceMappingUrlFromScript(scriptSource) {
419
+ const tail = scriptSource.slice(-8192);
420
+ const regex = /(?:\/\/[@#]\s*sourceMappingURL=([^\s]+)|\/\*[@#]\s*sourceMappingURL=([^*]+)\*\/)/g;
421
+ let match;
422
+ let found = null;
423
+ while (true) {
424
+ match = regex.exec(tail);
425
+ if (!match) break;
426
+ const candidate = (match[1] ?? match[2] ?? "").trim();
427
+ if (candidate) found = candidate;
428
+ }
429
+ return found;
430
+ }
431
+ function combineSourceRoot(sourceRoot, sourcePath) {
432
+ if (!sourceRoot) return sourcePath;
433
+ if (!sourcePath) return sourceRoot;
434
+ if (hasProtocol(sourcePath) || sourcePath.startsWith("/")) return sourcePath;
435
+ if (hasProtocol(sourceRoot)) try {
436
+ const base = sourceRoot.endsWith("/") ? sourceRoot : `${sourceRoot}/`;
437
+ return new URL(sourcePath, base).toString();
438
+ } catch {
439
+ return `${sourceRoot.replace(/\/+$/g, "")}/${sourcePath.replace(/^\/+/g, "")}`;
440
+ }
441
+ return `${sourceRoot.replace(/\/+$/g, "")}/${sourcePath.replace(/^\/+/g, "")}`;
442
+ }
443
+ function normalizeSourcePath(sourcePath, index) {
444
+ let candidate = sourcePath.trim();
445
+ if (!candidate) return `source_${index + 1}.js`;
446
+ if (candidate.startsWith("webpack://")) candidate = candidate.slice(10);
447
+ if (candidate.startsWith("data:")) return `inline/source_${index + 1}.txt`;
448
+ if (hasProtocol(candidate)) try {
449
+ const parsed = new URL(candidate);
450
+ candidate = `${parsed.hostname}${parsed.pathname}`;
451
+ } catch {
452
+ candidate = candidate.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
453
+ }
454
+ candidate = candidate.replace(/[?#].*$/g, "");
455
+ candidate = candidate.replace(/^[A-Za-z]:[\\/]/, "");
456
+ candidate = candidate.replace(/^\/+/, "");
457
+ const parts = candidate.split(/[\\/]+/).map((seg) => sanitizePathSegment(seg)).filter((seg) => seg !== "" && seg !== "." && seg !== "..");
458
+ if (parts.length === 0) return `source_${index + 1}.js`;
459
+ return parts.join("/");
460
+ }
461
+ function sanitizePathSegment(segment) {
462
+ const sanitized = Array.from(segment, (char) => {
463
+ const codePoint = char.codePointAt(0);
464
+ return codePoint !== void 0 && (codePoint <= 31 || "<>:\"|?*".includes(char)) ? "_" : char;
465
+ }).join("").replace(/\s+/g, " ").trim();
466
+ if (!sanitized || sanitized === "." || sanitized === "..") return "_";
467
+ return sanitized;
468
+ }
469
+ function safeTarget(value) {
470
+ return value.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "").slice(0, 48);
471
+ }
472
+ //#endregion
473
+ //#region src/server/domains/sourcemap/handlers/sourcemap-handlers.ts
474
+ /**
475
+ * Main sourcemap sub-handler — discover, fetch/parse, reconstruct tree.
476
+ */
477
+ function countScopeNodes(nodes) {
478
+ let count = 0;
479
+ for (const node of nodes) {
480
+ if (!node) continue;
481
+ count += 1 + countScopeNodes(node.children);
482
+ }
483
+ return count;
484
+ }
485
+ var SourcemapHandlers = class {
486
+ state;
487
+ constructor(state) {
488
+ this.state = state;
489
+ }
490
+ async handleSourcemapDiscover(args) {
491
+ const includeInline = parseBooleanArg(args.includeInline, true);
492
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
493
+ const scripts = /* @__PURE__ */ new Map();
494
+ const onScriptParsed = (payload) => {
495
+ const record = asRecord(payload);
496
+ const scriptId = asString(record.scriptId);
497
+ if (!scriptId) return;
498
+ const scriptUrl = asString(record.url) ?? "";
499
+ const sourceMapUrlRaw = asString(record.sourceMapURL) ?? "";
500
+ const existing = scripts.get(scriptId);
501
+ const sourceMapUrlResolved = sourceMapUrlRaw ? resolveSourceMapUrl(sourceMapUrlRaw, scriptUrl) : existing?.sourceMapUrl ?? "";
502
+ scripts.set(scriptId, {
503
+ scriptId,
504
+ scriptUrl: scriptUrl || existing?.scriptUrl || "",
505
+ sourceMapUrl: sourceMapUrlResolved,
506
+ isInline: sourceMapUrlResolved.startsWith("data:")
507
+ });
508
+ };
509
+ try {
510
+ session.on?.("Debugger.scriptParsed", onScriptParsed);
511
+ await session.send("Debugger.enable");
512
+ await delay(SOURCEMAP_V4_RETRY_DELAY_MS);
513
+ for (const item of scripts.values()) {
514
+ if (item.sourceMapUrl) continue;
515
+ if (!item.scriptId || !item.scriptUrl) continue;
516
+ try {
517
+ const scriptSource = asString(asRecord(await session.send("Debugger.getScriptSource", { scriptId: item.scriptId })).scriptSource);
518
+ if (!scriptSource) continue;
519
+ const extracted = extractSourceMappingUrlFromScript(scriptSource);
520
+ if (!extracted) continue;
521
+ const resolvedSourceMap = resolveSourceMapUrl(extracted, item.scriptUrl);
522
+ item.sourceMapUrl = resolvedSourceMap;
523
+ item.isInline = resolvedSourceMap.startsWith("data:");
524
+ } catch {
525
+ continue;
526
+ }
527
+ }
528
+ return json(Array.from(scripts.values()).filter((item) => item.sourceMapUrl.length > 0).filter((item) => includeInline || !item.isInline).toSorted((left, right) => {
529
+ const leftKey = `${left.scriptUrl}|${left.scriptId}`;
530
+ const rightKey = `${right.scriptUrl}|${right.scriptId}`;
531
+ return leftKey.localeCompare(rightKey);
532
+ }).map((item) => ({
533
+ scriptUrl: item.scriptUrl,
534
+ sourceMapUrl: item.sourceMapUrl,
535
+ isInline: item.isInline,
536
+ scriptId: item.scriptId
537
+ })));
538
+ } catch (error) {
539
+ return fail("sourcemap_discover", error);
540
+ } finally {
541
+ session.off?.("Debugger.scriptParsed", onScriptParsed);
542
+ await trySend(session, "Debugger.disable");
543
+ await safeDetach(session);
544
+ }
545
+ }
546
+ async handleSourcemapFetchAndParse(args) {
547
+ try {
548
+ const parsed = await parseSourceMap(requiredStringArg(args.sourceMapUrl, "sourceMapUrl"), optionalStringArg(args.scriptUrl), this.state.collector);
549
+ const responsePayload = {
550
+ sources: parsed.map.sources,
551
+ mappingsCount: parsed.mappingsCount,
552
+ segmentCount: parsed.segmentCount
553
+ };
554
+ if (Array.isArray(parsed.map.sourcesContent)) responsePayload.sourcesContent = parsed.map.sourcesContent;
555
+ return json(responsePayload);
556
+ } catch (error) {
557
+ return fail("sourcemap_fetch_and_parse", error);
558
+ }
559
+ }
560
+ async handleSourcemapReconstructTree(args) {
561
+ try {
562
+ const sourceMapUrl = requiredStringArg(args.sourceMapUrl, "sourceMapUrl");
563
+ const outputDir = optionalStringArg(args.outputDir);
564
+ const parsed = await parseSourceMapStats(sourceMapUrl, void 0, this.state.collector);
565
+ const artifactPath = await resolveArtifactPath({
566
+ category: "reports",
567
+ toolName: "sourcemap-tree",
568
+ target: safeTarget(parsed.resolvedUrl),
569
+ ext: "tmp",
570
+ ...outputDir ? { customDir: outputDir } : {}
571
+ });
572
+ const outputRoot = artifactPath.absolutePath.replace(/\.tmp$/i, "");
573
+ const outputRootDisplay = artifactPath.displayPath.replace(/\.tmp$/i, "");
574
+ await mkdir(outputRoot, { recursive: true });
575
+ const writtenFiles = [];
576
+ let skippedFiles = 0;
577
+ for (let index = 0; index < parsed.map.sources.length; index += 1) {
578
+ const rawSourcePath = parsed.map.sources[index] ?? "";
579
+ const sourcePath = combineSourceRoot(parsed.map.sourceRoot, rawSourcePath);
580
+ const relativePath = normalizeSourcePath(sourcePath, index);
581
+ const absolutePath = resolve(outputRoot, relativePath);
582
+ const sourceContent = parsed.map.sourcesContent && index < parsed.map.sourcesContent.length ? parsed.map.sourcesContent[index] : null;
583
+ const fileContent = typeof sourceContent === "string" ? sourceContent : `/* source content missing in source map: ${sourcePath} */\n`;
584
+ try {
585
+ await mkdir(dirname(absolutePath), { recursive: true });
586
+ await writeFile(absolutePath, fileContent, "utf-8");
587
+ writtenFiles.push(relativePath);
588
+ } catch {
589
+ skippedFiles += 1;
590
+ }
591
+ }
592
+ return json({
593
+ outputDir: outputRootDisplay,
594
+ totalSources: parsed.map.sources.length,
595
+ writtenFiles: writtenFiles.length,
596
+ skippedFiles,
597
+ files: writtenFiles
598
+ });
599
+ } catch (error) {
600
+ return fail("sourcemap_reconstruct_tree", error);
601
+ }
602
+ }
603
+ async handleSourcemapParseV4(args) {
604
+ const sourceMapUrl = requiredStringArg(args.sourceMapUrl, "sourceMapUrl");
605
+ const extractScopes = parseBooleanArg(args.extractScopes, true);
606
+ const extractDebugIds = parseBooleanArg(args.extractDebugIds, true);
607
+ try {
608
+ const raw = await fetchSourceMapText(sourceMapUrl, this.state.collector);
609
+ const parsed = JSON.parse(raw);
610
+ const names = Array.isArray(parsed.names) ? parsed.names.filter((x) => typeof x === "string") : [];
611
+ const sources = Array.isArray(parsed.sources) ? parsed.sources.filter((x) => typeof x === "string") : [];
612
+ const v3Baseline = {
613
+ version: parsed.version,
614
+ sources: sources.length,
615
+ names: names.length,
616
+ mappings: typeof parsed.mappings === "string" ? parsed.mappings.length : 0,
617
+ hasFile: typeof parsed.file === "string",
618
+ hasSourceRoot: typeof parsed.sourceRoot === "string"
619
+ };
620
+ const result = {
621
+ success: true,
622
+ sourceMapUrl,
623
+ version: parsed.version,
624
+ v3Baseline
625
+ };
626
+ if (extractDebugIds && typeof parsed.debugId === "string") {
627
+ const debugIdValid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(parsed.debugId);
628
+ result.debugId = parsed.debugId;
629
+ result.debugIdValid = debugIdValid;
630
+ }
631
+ const scopesField = typeof parsed.scopes === "string" ? parsed.scopes : typeof parsed.x_scopes === "string" ? parsed.x_scopes : void 0;
632
+ if (extractScopes && scopesField) try {
633
+ const decoded = decodeScopesField(scopesField, names, sources);
634
+ result.isV4 = true;
635
+ result.scopes = decoded;
636
+ result.scopeCount = countScopeNodes(decoded.originalScopes);
637
+ result.generatedRangeCount = decoded.generatedRanges.length;
638
+ } catch (scopeError) {
639
+ result.success = false;
640
+ result.scopeDecodeError = scopeError instanceof Error ? scopeError.message : String(scopeError);
641
+ result.rawScopesField = scopesField.substring(0, SOURCEMAP_V4_RAW_FIELD_MAX_LEN) + (scopesField.length > SOURCEMAP_V4_RAW_FIELD_MAX_LEN ? "..." : "");
642
+ result.isV4 = true;
643
+ }
644
+ const extensions = {};
645
+ if (parsed.x_scopeLines) extensions.x_scopeLines = parsed.x_scopeLines;
646
+ if (parsed.x_namesIdx) extensions.x_namesIdx = parsed.x_namesIdx;
647
+ if (parsed.x_computedBases) extensions.x_computedBases = parsed.x_computedBases;
648
+ if (Object.keys(extensions).length > 0) result.extensions = extensions;
649
+ if (!scopesField && !parsed.debugId && Object.keys(extensions).length === 0) {
650
+ result.isV4 = false;
651
+ result.note = "No v4 fields (scopes/debugId) found. This source map is v3 only.";
652
+ }
653
+ if (args.compareV3 === true) result.comparison = {
654
+ v3Only: [
655
+ "version",
656
+ "sources",
657
+ "names",
658
+ "mappings",
659
+ "file",
660
+ "sourceRoot"
661
+ ],
662
+ v4Only: Object.keys(result).filter((k) => ![
663
+ "success",
664
+ "sourceMapUrl",
665
+ "version",
666
+ "v3Baseline",
667
+ "comparison"
668
+ ].includes(k))
669
+ };
670
+ return json(result);
671
+ } catch (error) {
672
+ return fail("sourcemap_parse_v4", error);
673
+ }
674
+ }
675
+ };
676
+ function decodeScopesField(scopesText, names, sources) {
677
+ const items = scopesText.split(",");
678
+ const idx = { value: 0 };
679
+ const originalByStartIndex = [];
680
+ let previousOriginalName = 0;
681
+ let previousOriginalKind = 0;
682
+ let previousOriginalVariable = 0;
683
+ let previousGeneratedLine = 0;
684
+ let previousGeneratedColumn = 0;
685
+ let previousDefinition = 0;
686
+ const readName = (absoluteIndex1Based) => absoluteIndex1Based > 0 && absoluteIndex1Based <= names.length ? names[absoluteIndex1Based - 1] : void 0;
687
+ function safeItem(index) {
688
+ return index >= 0 && index < items.length ? items[index] : void 0;
689
+ }
690
+ function parseOriginalTree(sourceIndex, previousPos) {
691
+ const startItem = safeItem(idx.value++);
692
+ if (!startItem?.startsWith("B")) throw new Error(`expected original scope start 'B', got "${startItem}"`);
693
+ const rawUnsigned = decodeVlqSegmentUnsigned(startItem.slice(1));
694
+ const rawSigned = decodeVlqSegment(startItem.slice(1));
695
+ let p = 0;
696
+ const flags = rawUnsigned[p++] ?? 0;
697
+ const line = previousPos.line + (rawUnsigned[p++] ?? 0);
698
+ const columnRaw = rawUnsigned[p++] ?? 0;
699
+ const column = line === previousPos.line ? previousPos.column + columnRaw : columnRaw;
700
+ let name;
701
+ if ((flags & 1) !== 0) {
702
+ previousOriginalName += rawSigned[p++] ?? 0;
703
+ name = names[previousOriginalName];
704
+ }
705
+ let kind;
706
+ if ((flags & 2) !== 0) {
707
+ previousOriginalKind += rawSigned[p++] ?? 0;
708
+ kind = names[previousOriginalKind];
709
+ }
710
+ const node = {
711
+ index: originalByStartIndex.length,
712
+ sourceIndex,
713
+ start: {
714
+ line,
715
+ column
716
+ },
717
+ end: {
718
+ line,
719
+ column
720
+ },
721
+ name,
722
+ kind,
723
+ isStackFrame: (flags & 4) !== 0,
724
+ variables: [],
725
+ children: []
726
+ };
727
+ originalByStartIndex.push(node);
728
+ let cursorPos = {
729
+ line,
730
+ column
731
+ };
732
+ while (idx.value < items.length) {
733
+ const item = items[idx.value] ?? "";
734
+ if (item.startsWith("D")) {
735
+ idx.value++;
736
+ const vars = decodeVlqSegment(item.slice(1));
737
+ for (const rawVar of vars) {
738
+ previousOriginalVariable += rawVar;
739
+ node.variables.push(names[previousOriginalVariable] ?? `<name:${previousOriginalVariable}>`);
740
+ }
741
+ continue;
742
+ }
743
+ if (item.startsWith("B")) {
744
+ const child = parseOriginalTree(sourceIndex, cursorPos);
745
+ cursorPos = { ...child.end };
746
+ node.children.push(child);
747
+ continue;
748
+ }
749
+ break;
750
+ }
751
+ const endItem = safeItem(idx.value++);
752
+ if (!endItem?.startsWith("C")) throw new Error(`expected original scope end 'C', got "${endItem}"`);
753
+ const endRaw = decodeVlqSegmentUnsigned(endItem.slice(1));
754
+ const endLine = cursorPos.line + (endRaw[0] ?? 0);
755
+ const endColumnRaw = endRaw[1] ?? 0;
756
+ node.end = {
757
+ line: endLine,
758
+ column: endLine === cursorPos.line ? cursorPos.column + endColumnRaw : endColumnRaw
759
+ };
760
+ return node;
761
+ }
762
+ function parseGeneratedTree(previousPos) {
763
+ const startItem = safeItem(idx.value++);
764
+ if (!startItem?.startsWith("E")) throw new Error(`expected generated range start 'E', got "${startItem}"`);
765
+ const rawUnsigned = decodeVlqSegmentUnsigned(startItem.slice(1));
766
+ const rawSigned = decodeVlqSegment(startItem.slice(1));
767
+ let p = 0;
768
+ const flags = rawUnsigned[p++] ?? 0;
769
+ const hasLine = (flags & 1) !== 0;
770
+ const line = previousPos.line + (hasLine ? rawUnsigned[p++] ?? 0 : 0);
771
+ const columnRaw = rawUnsigned[p++] ?? 0;
772
+ const column = line === previousPos.line ? previousPos.column + columnRaw : columnRaw;
773
+ let definitionIndex;
774
+ if ((flags & 2) !== 0) {
775
+ previousDefinition += rawSigned[p++] ?? 0;
776
+ definitionIndex = previousDefinition;
777
+ }
778
+ const node = {
779
+ start: {
780
+ line,
781
+ column
782
+ },
783
+ end: {
784
+ line,
785
+ column
786
+ },
787
+ isStackFrame: (flags & 4) !== 0,
788
+ isHidden: (flags & 8) !== 0,
789
+ definitionIndex,
790
+ children: []
791
+ };
792
+ const subrangeState = /* @__PURE__ */ new Map();
793
+ let previousVariableIndex = 0;
794
+ let cursorPos = {
795
+ line,
796
+ column
797
+ };
798
+ while (idx.value < items.length) {
799
+ const item = items[idx.value] ?? "";
800
+ if (item.startsWith("G")) {
801
+ idx.value++;
802
+ node.bindings = decodeVlqSegmentUnsigned(item.slice(1)).map((v) => readName(v));
803
+ continue;
804
+ }
805
+ if (item.startsWith("H")) {
806
+ idx.value++;
807
+ const sub = decodeVlqSegmentUnsigned(item.slice(1));
808
+ if (!node.bindings) node.bindings = [];
809
+ let s = 0;
810
+ previousVariableIndex += sub[s++] ?? 0;
811
+ const variableIndex = previousVariableIndex;
812
+ const ranges = [];
813
+ let prev = subrangeState.get(variableIndex) ?? {
814
+ line: node.start.line,
815
+ column: node.start.column
816
+ };
817
+ while (s < sub.length) {
818
+ const expr = readName(sub[s++] ?? 0);
819
+ const lineDelta = sub[s++] ?? 0;
820
+ const nextLine = prev.line + lineDelta;
821
+ const colRaw = sub[s++] ?? 0;
822
+ const nextColumn = nextLine === prev.line ? prev.column + colRaw : colRaw;
823
+ ranges.push({
824
+ from: {
825
+ line: nextLine,
826
+ column: nextColumn
827
+ },
828
+ expression: expr
829
+ });
830
+ prev = {
831
+ line: nextLine,
832
+ column: nextColumn
833
+ };
834
+ }
835
+ subrangeState.set(variableIndex, prev);
836
+ while (node.bindings.length <= variableIndex) node.bindings.push(void 0);
837
+ node.bindings[variableIndex] = ranges;
838
+ continue;
839
+ }
840
+ if (item.startsWith("I")) {
841
+ idx.value++;
842
+ const cs = decodeVlqSegmentUnsigned(item.slice(1));
843
+ node.callsite = {
844
+ sourceIndex: cs[0] ?? 0,
845
+ line: cs[1] ?? 0,
846
+ column: cs[2] ?? 0
847
+ };
848
+ continue;
849
+ }
850
+ if (item.startsWith("E")) {
851
+ const child = parseGeneratedTree(cursorPos);
852
+ cursorPos = { ...child.end };
853
+ node.children.push(child);
854
+ continue;
855
+ }
856
+ break;
857
+ }
858
+ const endItem = safeItem(idx.value++);
859
+ if (!endItem?.startsWith("F")) throw new Error(`expected generated range end 'F', got "${endItem}"`);
860
+ const endRaw = decodeVlqSegmentUnsigned(endItem.slice(1));
861
+ const endHasLine = endRaw.length === 2;
862
+ const endLine = cursorPos.line + (endHasLine ? endRaw[0] ?? 0 : 0);
863
+ const endColumnRaw = endRaw[endHasLine ? 1 : 0] ?? 0;
864
+ const endColumn = endLine === cursorPos.line ? cursorPos.column + endColumnRaw : endColumnRaw;
865
+ node.end = {
866
+ line: endLine,
867
+ column: endColumn
868
+ };
869
+ previousGeneratedLine = endLine;
870
+ previousGeneratedColumn = endColumn;
871
+ return node;
872
+ }
873
+ const originalScopes = Array.from({ length: sources.length }, () => null);
874
+ for (let sourceIndex = 0; sourceIndex < sources.length && idx.value < items.length; sourceIndex++) {
875
+ if ((items[idx.value] ?? "") === "") {
876
+ idx.value++;
877
+ continue;
878
+ }
879
+ if (!(items[idx.value] ?? "").startsWith("B")) break;
880
+ originalScopes[sourceIndex] = parseOriginalTree(sourceIndex, {
881
+ line: 0,
882
+ column: 0
883
+ });
884
+ if ((items[idx.value] ?? "") === "") idx.value++;
885
+ }
886
+ const generatedRanges = [];
887
+ while (idx.value < items.length) {
888
+ if ((items[idx.value] ?? "") === "") {
889
+ idx.value++;
890
+ continue;
891
+ }
892
+ generatedRanges.push(parseGeneratedTree({
893
+ line: previousGeneratedLine,
894
+ column: previousGeneratedColumn
895
+ }));
896
+ }
897
+ return {
898
+ originalScopes,
899
+ generatedRanges
900
+ };
901
+ }
902
+ //#endregion
903
+ //#region src/server/domains/sourcemap/handlers.impl.core.ts
904
+ var SourcemapToolHandlers = class {
905
+ collector;
906
+ extension;
907
+ sourcemap;
908
+ constructor(collector) {
909
+ this.collector = collector;
910
+ const state = { collector };
911
+ this.extension = new ExtensionHandlers(state);
912
+ this.sourcemap = new SourcemapHandlers(state);
913
+ }
914
+ handleExtensionListInstalled(args) {
915
+ return this.extension.handleExtensionListInstalled(args);
916
+ }
917
+ handleExtensionExecuteInContext(args) {
918
+ return this.extension.handleExtensionExecuteInContext(args);
919
+ }
920
+ handleSourcemapDiscover(args) {
921
+ return this.sourcemap.handleSourcemapDiscover(args);
922
+ }
923
+ handleSourcemapFetchAndParse(args) {
924
+ return this.sourcemap.handleSourcemapFetchAndParse(args);
925
+ }
926
+ handleSourcemapReconstructTree(args) {
927
+ return this.sourcemap.handleSourcemapReconstructTree(args);
928
+ }
929
+ handleSourcemapParseV4(args) {
930
+ return this.sourcemap.handleSourcemapParseV4(args);
931
+ }
932
+ };
933
+ //#endregion
934
+ export { SourcemapToolHandlers };