├── .npmrc ├── .gitignore ├── .npmignore ├── src ├── index.ts ├── api.ts ├── utility.ts ├── types.ts ├── meta.ts ├── component.tsx ├── framework │ └── react.ts └── flavor │ └── remix.ts ├── renovate.json ├── .github └── workflows │ ├── deploy.yml │ └── release.yml ├── esbuild.mjs ├── tsconfig.json ├── LICENSE ├── package.json └── README.md /.npmrc: -------------------------------------------------------------------------------- 1 | //registry.npmjs.org/:_authToken=${NPM_TOKEN} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | **/*.spec.js 4 | .idea -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .github 2 | node_modules 3 | spec 4 | esbuild.mjs -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { Bridge, Node, SimplifiedAstNode, TransferableNode } from './types.js'; 2 | export { initialize } from './api.js'; 3 | export { Epiphany } from './component.js'; -------------------------------------------------------------------------------- /src/api.ts: -------------------------------------------------------------------------------- 1 | import { Remote, windowEndpoint, wrap } from 'comlink'; 2 | import { Bridge } from './types.js'; 3 | 4 | export function initialize(contentWindow: Window): Remote 5 | { 6 | return wrap(windowEndpoint(contentWindow)); 7 | } -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ], 5 | "automerge": true, 6 | "automergeType": "pr", 7 | "platformAutomerge": true, 8 | "lockFileMaintenance": { 9 | "enabled": true, 10 | "automerge": true, 11 | "automergeType": "pr", 12 | "platformAutomerge": true 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/utility.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export function uuid(): string 4 | { 5 | // NOTE(Chris Kruining) 6 | // This is an exemption 7 | // for ts-ignore due to 8 | // performance optimizations, 9 | // do NOT use elsewhere 10 | // @ts-ignore 11 | return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)); 12 | } -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | release: 5 | types: [ published ] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@v4 13 | - name: Publish code to NPM 14 | run: npm publish --access=public 15 | env: 16 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 17 | -------------------------------------------------------------------------------- /esbuild.mjs: -------------------------------------------------------------------------------- 1 | import { compile } from '@kruining/waterlogged'; 2 | 3 | await compile([ 'esm', 'cjs' ], { 4 | entryPoints: [ './src/index.ts' ], 5 | outbase: 'src', 6 | outfile: 'lib/index.$formatExtension', 7 | bundle: true, 8 | sourcemap: true, 9 | minify: false, 10 | platform: 'node', 11 | target: [ 'esnext' ], 12 | external: [ 'react', 'react-dom' ], 13 | watch: process.argv[2] === 'watch', 14 | }); -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "src/index.ts", 4 | ], 5 | "exclude": [ 6 | "lib/**/*.ts", 7 | "node_modules/**/*" 8 | ], 9 | "compilerOptions": { 10 | "lib": [ "esnext", "dom" ], 11 | "moduleResolution": "node", 12 | "module": "esnext", 13 | "target": "esnext", 14 | "rootDir": "src", 15 | "outDir": "lib", 16 | "jsx": "react-jsx", 17 | "strict": true, 18 | "esModuleInterop": true, 19 | "sourceMap": true, 20 | "declaration": true, 21 | "emitDeclarationOnly": true, 22 | "paths": { 23 | "~/*": ["./src/*"] 24 | } 25 | }, 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Chris Kruining 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@kruining/epiphany", 3 | "description": "", 4 | "license": "MIT", 5 | "exports": { 6 | "types": "./lib/index.d.ts", 7 | "import": "./lib/index.mjs", 8 | "require": "./lib/index.cjs", 9 | "default": "./lib/index.mjs" 10 | }, 11 | "main": "./lib/index.mjs", 12 | "type": "module", 13 | "types": "./lib/index.d.ts", 14 | "scripts": { 15 | "build:typed": "node ./esbuild.mjs && tsc", 16 | "build": "node ./esbuild.mjs", 17 | "dev": "node ./esbuild.mjs watch", 18 | "test": "echo \"no tests yet\"" 19 | }, 20 | "peerDependencies": { 21 | "react": "^17.0.2 || ^18.0.0", 22 | "react-dom": "^17.0.2 || ^18.0.0" 23 | }, 24 | "dependencies": { 25 | "comlink": "^4.3.1", 26 | "source-map": "^0.7.3", 27 | "ts-ast-to-literal": "^3.0.0", 28 | "ts-pattern": "^5.0.0", 29 | "typescript": "^5.0.0" 30 | }, 31 | "devDependencies": { 32 | "@kruining/waterlogged": "1.1.45", 33 | "@remix-run/react": "2.0.0", 34 | "@types/node": "18.17.2", 35 | "@types/react": "18.2.22", 36 | "@types/react-dom": "18.2.7", 37 | "esbuild": "0.19.3" 38 | }, 39 | "engines": { 40 | "node": ">=14" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxKind } from 'typescript'; 2 | 3 | export interface Bridge 4 | { 5 | getTree(): Promise, 6 | getNode(id: string): Promise, 7 | getNodeFromPoint(x: number, y: number): Promise, 8 | clickAt(x: number, y: number): Promise, 9 | } 10 | 11 | export type Framework = { 12 | getNode(id: string, flavor: Flavor): Promise, 13 | getNodeFromElement(element: Element, flavor: Flavor, recurse?: boolean): Promise, 14 | }; 15 | 16 | export type Flavor = { 17 | getDetails(node: N, context?: Context): Promise<[ object, Context|undefined ]>, 18 | }; 19 | 20 | export interface Context 21 | { 22 | ast?: SimplifiedAstNode; 23 | } 24 | 25 | export type Node = Record|{ 26 | id: number, 27 | index: number, 28 | key: string, 29 | tag: number, 30 | displayName: string, 31 | children: Node[], 32 | }; 33 | 34 | export type SimplifiedAstNode = { 35 | start: { line: number, character: number, index: number }, 36 | end: { line: number, character: number, index: number }, 37 | kind: SyntaxKind, 38 | type: string, 39 | original: any, 40 | parent?: SimplifiedAstNode, 41 | children: SimplifiedAstNode[], 42 | }; 43 | 44 | export type TransferableNode = Omit; -------------------------------------------------------------------------------- /src/meta.ts: -------------------------------------------------------------------------------- 1 | // import { readConfig } from '@remix-run/dev/config'; 2 | // import { readFile } from 'fs/promises'; 3 | // import { 4 | // Statement, 5 | // VariableStatement, 6 | // ObjectLiteralExpression, 7 | // Identifier, 8 | // createSourceFile, 9 | // ScriptTarget, 10 | // SyntaxKind, 11 | // } from 'typescript'; 12 | // import expressionToLiteral from 'ts-ast-to-literal'; 13 | // import { AssetsManifest } from '@remix-run/react/entry.js'; 14 | // 15 | // export const getConfig = async (root: string) => readConfig(root); 16 | // 17 | // export async function getManifest(root: string) 18 | // { 19 | // const conf = await getConfig(root); 20 | // const file = await readFile(conf.serverBuildPath); 21 | // const source = createSourceFile('temp.ts', file.toString(), ScriptTarget.ESNext); 22 | // 23 | // const manifest = source.statements 24 | // .filter((s: Statement): s is VariableStatement => s.kind === SyntaxKind.VariableStatement) 25 | // .flatMap(s => s.declarationList.declarations) 26 | // .find(d => (d.name as Identifier).escapedText === 'assets_manifest_default') 27 | // ?.initializer as ObjectLiteralExpression|undefined; 28 | // 29 | // if(manifest === undefined) 30 | // { 31 | // throw new Error(`Unable to locate the manifest`); 32 | // } 33 | // 34 | // return expressionToLiteral(manifest); 35 | // } -------------------------------------------------------------------------------- /src/component.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { expose, windowEndpoint } from 'comlink'; 3 | import { Bridge, Framework, Flavor } from './types.js'; 4 | import { FiberNode, getNodeFromElement, getNode } from './framework/react.js'; 5 | import { getDetails } from './flavor/remix.js'; 6 | import React from 'react'; 7 | import { SourceMapConsumer } from 'source-map'; 8 | 9 | const framework: Framework = { 10 | getNode, 11 | getNodeFromElement, 12 | }; 13 | const flavor: Flavor = { 14 | getDetails, 15 | }; 16 | 17 | export function Epiphany() 18 | { 19 | if (process.env.NODE_ENV !== 'development') 20 | { 21 | return <>; 22 | } 23 | 24 | useEffect(() => { 25 | (SourceMapConsumer as any).initialize({ 26 | "lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/lib/mappings.wasm", 27 | }); 28 | 29 | const bridge: Bridge = { 30 | getTree: () => framework.getNodeFromElement(document.documentElement, flavor, true), 31 | getNode: (id: string) => framework.getNode(id, flavor), 32 | getNodeFromPoint: async (x: number, y: number) => { 33 | const element = document.elementFromPoint(x, y); 34 | 35 | return element 36 | ? await framework.getNodeFromElement(element, flavor) 37 | : undefined; 38 | }, 39 | clickAt: async (x: number, y: number) => { 40 | document.elementFromPoint(x, y)?.dispatchEvent(new MouseEvent('click', { 41 | bubbles: true, 42 | cancelable: true, 43 | clientX: x, 44 | clientY: y 45 | })); 46 | }, 47 | }; 48 | 49 | expose(bridge, windowEndpoint(window.parent)); 50 | }, []); 51 | 52 | return <> 53 | } -------------------------------------------------------------------------------- /src/framework/react.ts: -------------------------------------------------------------------------------- 1 | import { Context, Flavor, Node } from '../types.js'; 2 | import { match } from 'ts-pattern'; 3 | import { uuid } from '~/utility.js'; 4 | 5 | export type FiberNode = { 6 | index: number, 7 | key: string, 8 | tag: Tag, 9 | type: any, 10 | stateNode: Element|undefined, 11 | child: FiberNode|null, 12 | sibling: FiberNode|null, 13 | memoizedProps: Record, 14 | _debugID: number, 15 | }; 16 | 17 | export enum Tag 18 | { 19 | Function = 0, 20 | Class = 1, 21 | Intermediate = 2, 22 | Root = 3, 23 | Portal = 4, 24 | Element = 5, 25 | Text = 6, 26 | Fragment = 7, 27 | Mode = 8, 28 | ContextConsumer = 9, 29 | ContextProvider = 10, 30 | Forward = 11, 31 | Profiler = 12, 32 | Suspense = 13, 33 | } 34 | 35 | const fiberCache: WeakMap = new WeakMap; 36 | const nodeMap: Map = new Map; 37 | 38 | function getFiber(element: Element): FiberNode 39 | { 40 | const fiberKey = Object.getOwnPropertyNames(element).find(n => n.startsWith('__reactFiber'))!; 41 | 42 | return (element as any)?.[fiberKey] as FiberNode; 43 | } 44 | 45 | function getChildren(node: FiberNode): FiberNode[] 46 | { 47 | const children = []; 48 | let current = node.child; 49 | while(current !== null) 50 | { 51 | children.push(current); 52 | 53 | current = current.sibling; 54 | } 55 | 56 | return children; 57 | } 58 | 59 | async function fiberToNode(fiber: FiberNode, flavor: Flavor, recurse: boolean = false, context?: Context): Promise 60 | { 61 | if(fiberCache.has(fiber) === false) 62 | { 63 | const { index, key, tag, type } = fiber; 64 | const [ details, newContext ] = await flavor.getDetails(fiber, context); 65 | const id = uuid(); 66 | 67 | const displayName: string = match(tag) 68 | .with(Tag.Element, () => type) 69 | .with(Tag.Class, () => type.constructor.name) 70 | .with(Tag.Function, () => type.name) 71 | .with(Tag.Text, () => fiber.memoizedProps) 72 | .with(Tag.ContextProvider, () => 'Context.Provider') 73 | .with(Tag.Forward, () => type.render.displayName) 74 | .otherwise(() => 'UNHANDLED_TYPE') 75 | 76 | const node = { 77 | ...details, // Details first so that they do not override any of the props beneath 78 | id, 79 | index, 80 | key, 81 | tag, 82 | displayName, 83 | children: recurse 84 | ? await Promise.all(getChildren(fiber).map(f => fiberToNode(f, flavor, recurse, newContext ?? context))) 85 | : [], 86 | }; 87 | 88 | fiberCache.set(fiber, node); 89 | nodeMap.set(id, node); 90 | } 91 | 92 | return fiberCache.get(fiber)!; 93 | } 94 | 95 | export async function getNode(id: string, flavor: Flavor): Promise 96 | { 97 | return nodeMap.get(id); 98 | } 99 | 100 | export async function getNodeFromElement(element: Element, flavor: Flavor, recurse: boolean = false): Promise 101 | { 102 | return fiberToNode(getFiber(element), flavor, recurse); 103 | } -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - "main" 7 | 8 | concurrency: 9 | group: ${{ github.ref || github.run_id }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | build: 14 | name: Build 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | with: 20 | ref: ${{ github.head_ref }} 21 | fetch-depth: 0 22 | 23 | - name: Setup Node 24 | uses: actions/setup-node@v3 25 | with: 26 | node-version: 16 27 | registry-url: https://registry.npmjs.org/ 28 | 29 | - name: Install packages 30 | run: npm ci 31 | 32 | - name: Build code 33 | run: npm run build 34 | 35 | - name: Store project in cache 36 | uses: actions/cache@v3 37 | id: restore-build 38 | with: 39 | path: './*' 40 | key: ${{ github.sha }} 41 | 42 | test: 43 | name: Test 44 | needs: build 45 | runs-on: ${{ matrix.os }} 46 | strategy: 47 | matrix: 48 | os: [ ubuntu-latest ] 49 | node_version: [ 16.x ] 50 | protoc_version: [ 3.x ] 51 | steps: 52 | - name: Load project from cache 53 | uses: actions/cache@v3 54 | id: restore-build 55 | with: 56 | path: './*' 57 | key: ${{ github.sha }} 58 | 59 | - name: Run tests 60 | run: npm test 61 | 62 | publish: 63 | name: Publish 64 | needs: test 65 | runs-on: ubuntu-latest 66 | steps: 67 | - name: Load project from cache 68 | uses: actions/cache@v3 69 | id: restore-build 70 | with: 71 | path: './*' 72 | key: ${{ github.sha }} 73 | 74 | - name: Debug 75 | run: ls -Ral 76 | 77 | - name: Create version number 78 | id: version 79 | uses: codacy/git-version@2.8.0 80 | with: 81 | release-branch: main 82 | 83 | - name: Update package.json 84 | run: | 85 | git config --global user.email "actions@github.com" 86 | git config --global user.name "Github actions" 87 | npm version ${{ steps.version.outputs.version }} 88 | 89 | - name: Publish code to NPM 90 | run: npm publish --access=public 91 | env: 92 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 93 | 94 | - name: Create Changelog 95 | id: changelog 96 | uses: mikepenz/release-changelog-builder-action@v4 97 | env: 98 | GITHUB_TOKEN: ${{ github.token }} 99 | 100 | - name: Zip project 101 | run: zip -r release.zip . 102 | 103 | - name: Create Github release 104 | uses: actions/create-release@v1 105 | id: create_release 106 | with: 107 | draft: false 108 | prerelease: false 109 | release_name: ${{ steps.version.outputs.version }} 110 | tag_name: ${{ steps.version.outputs.version }} 111 | body: ${{ steps.changelog.outputs.changelog }} 112 | env: 113 | GITHUB_TOKEN: ${{ github.token }} 114 | 115 | - name: Upload artifact 116 | uses: actions/upload-release-asset@v1 117 | env: 118 | GITHUB_TOKEN: ${{ github.token }} 119 | with: 120 | upload_url: ${{ steps.create_release.outputs.upload_url }} 121 | asset_path: ./release.zip 122 | asset_name: release.zip 123 | asset_content_type: application/gzip 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Epiphany 2 | introspection library for JS-frameworks, currently with sole support for Remix. 3 | 4 | # Install 5 | 6 | ### The project to be inspected 7 | `npm i -D @kruining/epiphany` 8 | 9 | ### The project that is inspecting 10 | `npm i @kruining/epiphany` 11 | 12 | # Usage 13 | 14 | ### The project to be inspected 15 | `/app/root.tsx` 16 | ```diff 17 | import { 18 | LiveReload, 19 | ScrollRestoration, 20 | Outlet, 21 | Meta, 22 | Scripts, 23 | LinksFunction, 24 | } from 'remix'; 25 | +import { Epiphany } from '@kruining/epiphany'; 26 | 27 | export default function App() 28 | { 29 | return 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | + 42 | 43 | ; 44 | } 45 | ``` 46 | 47 | ### The project that is inspecting 48 | 49 | #### Theoretical 50 | 51 | initialize needs a reference to a `Window` object which is running Epiphany. 52 | it communicates over `postMessage`, hence the need for the `Window`. 53 | 54 | ```ts 55 | import { Bridge, initialize } from '@kruining/epiphany'; 56 | 57 | const frame: Window = iframe.contentWindow; 58 | const bridge: Bridge = initialize(frame); 59 | ``` 60 | 61 | #### Practical 62 | 63 | This is a example of how to could set up initialization for Epiphany. 64 | this is a stripped down version of my own setup for my CMS. 65 | 66 | `/app/feature/cms/inspector.context.ts` 67 | ```tsx 68 | import { Bridge, initialize } from '@kruining/epiphany'; 69 | import { 70 | createContext, Dispatch, Key, 71 | PropsWithChildren, SetStateAction, 72 | useContext, 73 | useEffect, 74 | useMemo, 75 | useState, 76 | } from 'react'; 77 | 78 | const bridgeContext = createContext(undefined); 79 | const frameContext = createContext(undefined); 80 | 81 | export const useBridge = () => useContext(bridgeContext); 82 | export const useSetContentWindow = () => useContext(frameContext); 83 | 84 | let bridge: Bridge|undefined; 85 | export function InspectorProvider({ children }: PropsWithChildren<{}>) 86 | { 87 | const [ state, setState ] = useState(''); 88 | const [ frame, setFrame ] = useState(); 89 | const [ highlights, setHighlights ] = useState([]); 90 | 91 | const providerValue = useMemo(() => bridge, [ state, setState ]); 92 | 93 | useEffect(() => { 94 | if(bridge === undefined && frame !== undefined) 95 | { 96 | bridge = initialize(frame!); 97 | 98 | setState('initialized'); 99 | } 100 | }, [ frame ]); 101 | 102 | const setContentWindow = (window: Window) => { 103 | setFrame(window); 104 | }; 105 | 106 | return 107 | 108 | {children} 109 | 110 | 111 | } 112 | ``` 113 | 114 | ### API 115 | 116 | #### getTree 117 | 118 | This methods gets the whole DOM tree with mapped source locations 119 | 120 | ```ts 121 | const tree = await bridge.getTree(); 122 | ``` 123 | 124 | #### getNode 125 | 126 | Grab a node by its id. this id can be acquired via `getTree` or `getNodeFromPosition`. 127 | 128 | ```ts 129 | const id: string = 'some-uuid'; 130 | const node = await bridge.getNode(id); 131 | ``` 132 | 133 | #### getNodeFromPosition 134 | 135 | Query the element that lies on (x,y) in the inspected project 136 | 137 | ```ts 138 | const event: MouseMoveEvent; 139 | const node = await bridge.getNodeFromPosition(event.x, event.y); 140 | ``` -------------------------------------------------------------------------------- /src/flavor/remix.ts: -------------------------------------------------------------------------------- 1 | import { FiberNode, Tag } from '../framework/react.js'; 2 | import { Context, SimplifiedAstNode } from '../types.js'; 3 | import { SourceMapConsumer } from 'source-map'; 4 | import * as Path from 'path'; 5 | import { createSourceFile, Node, ScriptTarget, SourceFile, SyntaxKind } from 'typescript'; 6 | import { match } from 'ts-pattern'; 7 | 8 | export async function getDetails(node: FiberNode, context?: Context): Promise<[ object, Context|undefined ]> 9 | { 10 | return match>(node.tag) 11 | .with(Tag.Element, async () => { 12 | const { left = 0, top = 0, width = 0, height = 0 } = node.stateNode?.getBoundingClientRect() ?? {}; 13 | let astNode: SimplifiedAstNode|undefined = context?.ast; 14 | const check = (n?: SimplifiedAstNode): boolean => { 15 | const realIndex = Array.from(node.stateNode?.parentNode?.children ?? []).findIndex(c => c === node.stateNode); 16 | const astIndex = n?.parent?.children.filter(c => c.kind === SyntaxKind.JsxElement).findIndex(c => c === n) ?? -1; 17 | 18 | return n?.original.openingElement.tagName.getText() === node.type && realIndex === astIndex; 19 | }; 20 | 21 | if(astNode?.kind === SyntaxKind.SyntaxList) 22 | { 23 | astNode = astNode.children.find(n => n.kind === SyntaxKind.JsxElement && check(n)); 24 | } 25 | 26 | if(check(astNode) === false) 27 | { 28 | astNode = undefined; 29 | } 30 | 31 | return [ 32 | { 33 | rect: { insetInlineStart: left, insetBlockStart: top, inlineSize: width, blockSize: height }, 34 | source: astNode 35 | ? { 36 | ...Object.fromEntries(Object.entries(astNode).filter(([ key ]) => [ 'original', 'parent', 'children' ].includes(key) === false)), 37 | file: astNode?.original.getSourceFile().fileName, 38 | } 39 | : undefined, 40 | }, 41 | astNode !== undefined 42 | ? { ast: astNode.children.at(1) } 43 | : undefined, 44 | ]; 45 | }) 46 | .with(Tag.Function, async () => { 47 | const details: Record = {}; 48 | let context: Context|undefined = undefined; 49 | 50 | if(node.type.name === 'Outlet' && node.child !== null) 51 | { 52 | // Structure => 53 | // 0| Outlet 54 | // 1| |-> Context provider 55 | // 2| |-> Context provider (get the route match from here) 56 | // 3| |-> RemixRoute 57 | // 4| |-> Context provider 58 | // 5| |-> ErrorBoundary (if set) 59 | // 6| |-> CatchBoundary (if set) 60 | // 7| |-> Actual element 61 | 62 | const match = node.child.child!.memoizedProps.value.matches.at(-1); 63 | const { pathname, route, params } = match; 64 | 65 | const vars = Array.from((route?.path?.matchAll(/:(\w+)/g) ?? []), m => m[1]!); 66 | 67 | let element: FiberNode = node.child!.child!.child!.child!.child!.child!; 68 | 69 | if(typeof element.type === 'function' && element.type.name === 'RemixErrorBoundary') 70 | { 71 | element = element.child!; 72 | } 73 | 74 | if(typeof element.type === 'function' && element.type.name === 'RemixCatchBoundary') 75 | { 76 | element = element.child!; 77 | } 78 | 79 | const functionString = element.type.toString(); 80 | 81 | const code = await fetch(route.module).then(r => r.text()); 82 | const sourceMap = await fetch(route.module + '.map').then(r => r.json()); 83 | 84 | const offset = code.indexOf(functionString); 85 | const line = code.substring(0, offset).split('\n').length; 86 | const column = offset - code.substring(0, code.substring(0, offset).lastIndexOf('\n') + 1).length; 87 | 88 | const source = await SourceMapConsumer.with(sourceMap, null, consumer => { 89 | const { source, ...args } = consumer.originalPositionFor({ line, column }); 90 | const content = consumer.sourceContentFor(source ?? '', true); 91 | const file = Path.resolve(source ?? ''); 92 | 93 | return { file, content, ...args }; 94 | }); 95 | 96 | const ast = getSimplifiedAst(source.file, source.content ?? ''); 97 | const rootNode = getNode(ast, source.line! - 1, source.column!)!.parent!; 98 | 99 | context = { 100 | // make the return value the AST so that child components get a chance to read their source location from the ast. 101 | // TODO(Chris Kruining) This is hacky af and I hate it, come up with a proper solution, or beg for PR's from smart people 102 | ast: rootNode 103 | .children.find((c: SimplifiedAstNode) => c.kind === SyntaxKind.Block)! 104 | .children.find((c: SimplifiedAstNode) => c.kind === SyntaxKind.SyntaxList)! 105 | .children.find((c: SimplifiedAstNode) => c.kind === SyntaxKind.ReturnStatement)! 106 | .children.at(1)!, 107 | }; 108 | 109 | details.route = { 110 | pathname: pathname, 111 | id: route.id, 112 | module: route.module, 113 | path: route.path, 114 | source, 115 | astNode: Object.fromEntries(Object.entries(ast).filter(([ key ]) => [ 'original', 'parent', 'children' ].includes(key) === false)), 116 | params: Object.fromEntries( 117 | Array.from(Object.entries(params)).filter(([ k ]) => vars.includes(k)) 118 | ), 119 | }; 120 | } 121 | 122 | return [ 123 | { ...details, source: {} }, 124 | context 125 | ]; 126 | }) 127 | .otherwise(async () => [ {}, undefined ]); 128 | } 129 | 130 | function getSimplifiedAst(file: string, content: string) 131 | { 132 | return recurse(createSourceFile(file, content, ScriptTarget.Latest, true)); 133 | } 134 | 135 | const recurse = (ast: SourceFile, node?: Node, parent?: SimplifiedAstNode): SimplifiedAstNode => { 136 | node ??= ast; 137 | 138 | const n: SimplifiedAstNode = { 139 | start: { ...ast.getLineAndCharacterOfPosition(node.pos), index: node.pos }, 140 | end: { ...ast.getLineAndCharacterOfPosition(node.end), index: node.end }, 141 | kind: node.kind, 142 | type: SyntaxKind[node.kind], 143 | original: node, 144 | parent, 145 | children: [] 146 | }; 147 | 148 | n.children.push(...node.getChildren().map(c => recurse(ast, c, n))); 149 | 150 | return n; 151 | } 152 | const getNode = (node: SimplifiedAstNode, line: number, character: number): SimplifiedAstNode|undefined => { 153 | return ( 154 | (node.start.line < line && node.end.line > line) 155 | || (node.start.line === line && node.start.character <= character) 156 | || (node.end.line === line && node.end.character > character) 157 | ) 158 | ? node.children.map(c => getNode(c, line, character)).filter(c => c !== undefined).at(0) ?? node 159 | : undefined; 160 | }; --------------------------------------------------------------------------------