( devTools: TargetUniverse, rawStackTrace: StackTraceLike, targetId: string | undefined, )
| 566 | } |
| 567 | |
| 568 | export async function createStackTrace( |
| 569 | devTools: TargetUniverse, |
| 570 | rawStackTrace: StackTraceLike, |
| 571 | targetId: string | undefined, |
| 572 | ): Promise<DevTools.StackTrace.StackTrace.StackTrace> { |
| 573 | const targetManager = devTools.universe.context.get(DevTools.TargetManager); |
| 574 | const target = targetId |
| 575 | ? targetManager.targetById(targetId) || devTools.target |
| 576 | : devTools.target; |
| 577 | const model = target.model(DevTools.DebuggerModel) as DevTools.DebuggerModel; |
| 578 | |
| 579 | // DevTools doesn't wait for source maps to attach before building a stack trace, rather it'll send |
| 580 | // an update event once a source map was attached and the stack trace retranslated. This doesn't |
| 581 | // work in the MCP case, so we'll collect all script IDs upfront and wait for any pending source map |
| 582 | // loads before creating the stack trace. We might also have to wait for Debugger.ScriptParsed events if |
| 583 | // the stack trace is created particularly early. |
| 584 | const scriptUrls = new Map<string, string>(); |
| 585 | for (const frame of rawStackTrace.callFrames) { |
| 586 | scriptUrls.set(frame.scriptId, frame.url); |
| 587 | } |
| 588 | for ( |
| 589 | let asyncStack: StackTraceLike | undefined = rawStackTrace.parent; |
| 590 | asyncStack; |
| 591 | asyncStack = asyncStack.parent |
| 592 | ) { |
| 593 | for (const frame of asyncStack.callFrames) { |
| 594 | scriptUrls.set(frame.scriptId, frame.url); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | const signal = AbortSignal.timeout(1_000); |
| 599 | const scripts = await Promise.all( |
| 600 | [...scriptUrls].map(async ([scriptId, url]) => { |
| 601 | try { |
| 602 | const script = await waitForScript(model, scriptId, signal); |
| 603 | // V8 leaves data: URLs out of stack frames. |
| 604 | const scriptUrl = script.sourceURL.startsWith('data:') |
| 605 | ? '' |
| 606 | : script.sourceURL; |
| 607 | // Script ids restart in a new renderer process, so after a |
| 608 | // cross-process navigation the id can belong to another script. |
| 609 | return scriptUrl === url ? script : undefined; |
| 610 | } catch { |
| 611 | // The script is gone, e.g. after a navigation. |
| 612 | return undefined; |
| 613 | } |
| 614 | }), |
| 615 | ); |
| 616 | const knownScripts = scripts.filter(script => script !== undefined); |
| 617 | await waitForSourceMaps(model, knownScripts, signal); |
| 618 | const knownScriptIds = new Set<string>( |
| 619 | knownScripts.map(script => script.scriptId), |
| 620 | ); |
| 621 | |
| 622 | const binding = devTools.universe.context.get( |
| 623 | DevTools.DebuggerWorkspaceBinding, |
| 624 | ); |
| 625 | // DevTools uses branded types for ScriptId and others. Casting the puppeteer protocol type to the DevTools protocol type is safe. |
no test coverage detected