| 1 | import puppeteer from 'puppeteer'; |
| 2 | |
| 3 | export async function parseReactComponentTree(url: string): Promise<string> { |
| 4 | try { |
| 5 | const browser = await puppeteer.connect({ |
| 6 | browserURL: 'http://127.0.0.1:9222', |
| 7 | defaultViewport: null, |
| 8 | }); |
| 9 | |
| 10 | const pages = await browser.pages(); |
| 11 | |
| 12 | let localhostPage = null; |
| 13 | for (const page of pages) { |
| 14 | const pageUrl = await page.url(); |
| 15 | |
| 16 | if (pageUrl.startsWith(url)) { |
| 17 | localhostPage = page; |
| 18 | break; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | if (localhostPage) { |
| 23 | const componentTree = await localhostPage.evaluate(() => { |
| 24 | return (window as any).__REACT_DEVTOOLS_GLOBAL_HOOK__.rendererInterfaces |
| 25 | .get(1) |
| 26 | .__internal_only_getComponentTree(); |
| 27 | }); |
| 28 | |
| 29 | return componentTree; |
| 30 | } else { |
| 31 | throw new Error( |
| 32 | `Could not open the page at ${url}. Is your server running?`, |
| 33 | ); |
| 34 | } |
| 35 | } catch (error) { |
| 36 | throw new Error('Failed extract component tree' + error); |
| 37 | } |
| 38 | } |