diff --git a/packages/core/src/app-flow/presentations-bindings.ts b/packages/core/src/app-flow/presentations-bindings.ts index c84ad7a1..761d5f0d 100644 --- a/packages/core/src/app-flow/presentations-bindings.ts +++ b/packages/core/src/app-flow/presentations-bindings.ts @@ -1,4 +1,6 @@ -import { isAbsolute, relative } from 'node:path' +import { isAbsolute } from 'node:path' +import { fileURLToPath } from 'node:url' +import { relativeSourcePath } from './source-path.ts' import { parseBaseUrl } from '@mobile-dev/shared/protocol.ts' import type { AppFlowPresentationAction, AppFlowPresentations } from '@mobile-dev/shared/app-flow.ts' @@ -189,12 +191,16 @@ export async function bindPresentationSites( const matchFrame = (binding: AppFlowPresentationBinding, frame: AppFlowSymbolicatedFrame) => { const line = frame.lineNumber if (!frame.file || line === undefined || !Number.isInteger(line)) return + let sourceFile = frame.file + if (sourceFile.startsWith('file://')) { + try { sourceFile = fileURLToPath(sourceFile) } catch { return } + } + const file = relativeSourcePath(root, sourceFile) + if (!isProjectFile(file)) return if (binding.kind === 'portal' || binding.kind === 'ui-effect') { - deferred.push({ binding: binding.id, frame }) + deferred.push({ binding: binding.id, frame: { ...frame, file: sourceFile } }) return } - const file = relative(root, frame.file.replace(/^file:\/\//, '')) - if (!isProjectFile(file)) return stats.projectFrames += 1 const column = frame.column @@ -278,7 +284,7 @@ export async function bindPresentationSites( if (frame) matchFrame(reference.owner, frame) } - await resolveDeferred(root, bindings, deferred, matches, ports) + await resolveDeferred(bindings, deferred, matches, ports) stats.placed = new Set(matches.map(match => match.binding)).size stats.entryPlaced = new Set(matches.filter(match => entryIds.has(match.binding)).map(match => match.binding)).size ports.report?.(stats) @@ -347,7 +353,6 @@ async function symbolicate( * supplied by the caller, so an unported stage leaves the leg inert. */ async function resolveDeferred( - root: string, bindings: AppFlowPresentationBinding[], deferred: { binding: string; frame: AppFlowSymbolicatedFrame }[], matches: AppFlowPresentationBindingMatch[], @@ -359,8 +364,7 @@ async function resolveDeferred( for (const { binding, frame } of deferred) { if (matched.has(binding)) continue try { - const file = frame.file!.replace(/^file:\/\//, '') - if (!isProjectFile(relative(root, file))) continue + const file = frame.file! if (!sources.has(file)) sources.set(file, await ports.readSource(file)) const source = sources.get(file) if (source === undefined || source.length > sourceLimit) continue diff --git a/packages/core/src/app-flow/presentations-source.ts b/packages/core/src/app-flow/presentations-source.ts index 2c3d6595..799dccb6 100644 --- a/packages/core/src/app-flow/presentations-source.ts +++ b/packages/core/src/app-flow/presentations-source.ts @@ -1,4 +1,4 @@ -import { relative } from 'node:path' +import { relativeSourcePath } from './source-path.ts' import ts from 'typescript' import type { AppFlowOpeningData, AppFlowPresentationAction, AppFlowPresentations, AppFlowStateSite, AppFlowUiCondition } from '@mobile-dev/shared/app-flow.ts' import { fnName, jsxAttributes, ownerFn, sourceHash, unwrap } from './source-units.ts' @@ -136,7 +136,7 @@ export function scanPresentations(units: Map, root: string, symbol const start = unit.ast.getLineAndCharacterOfPosition(call.getStart()), end = unit.ast.getLineAndCharacterOfPosition(call.getEnd()) states.push({ unit, fn, value: value.name.text, setter: setter.name.text, setterNode: setter.name, - site: { id: key(`${relative(root, unit.file)}:${call.pos}`), file: relative(root, unit.file), line: start.line + 1, column: start.character, endLine: end.line + 1, owner: functionName(fn), paths: [], hook: 'useState', valueName: value.name.text } + site: { id: key(`${relativeSourcePath(root, unit.file)}:${call.pos}`), file: relativeSourcePath(root, unit.file), line: start.line + 1, column: start.character, endLine: end.line + 1, owner: functionName(fn), paths: [], hook: 'useState', valueName: value.name.text } }) }) function known(unit: Unit, node: ts.Node | undefined, env: Map, depth = 0): boolean { @@ -453,7 +453,7 @@ export function scanPresentations(units: Map, root: string, symbol const value = a.initializer && ts.isStringLiteralLike(a.initializer) ? a.initializer.text : constant(unit, expression(a)) if (['string', 'number', 'boolean'].includes(typeof value)) trigger[a.name.getText()] = value as string | number | boolean } - const base = { source: { line: start.line + 1, column: start.character, endLine: end.line + 1, endColumn: end.character }, trigger: Object.keys(trigger).length ? trigger : undefined, handler: exp && ts.isIdentifier(exp) ? exp.text : undefined, id: key(`${relative(root, unit.file)}:${attribute.pos}`), file: relative(root, unit.file), line: loc.line + 1, owner: own, component, prop } + const base = { source: { line: start.line + 1, column: start.character, endLine: end.line + 1, endColumn: end.character }, trigger: Object.keys(trigger).length ? trigger : undefined, handler: exp && ts.isIdentifier(exp) ? exp.text : undefined, id: key(`${relativeSourcePath(root, unit.file)}:${attribute.pos}`), file: relativeSourcePath(root, unit.file), line: loc.line + 1, owner: own, component, prop } // An unconditional presentation call may be extracted from a handler that // also emits analytics. Prop guards must hold in the mounted owner. const props = new Map() diff --git a/packages/core/src/app-flow/source-path.ts b/packages/core/src/app-flow/source-path.ts new file mode 100644 index 00000000..050dd285 --- /dev/null +++ b/packages/core/src/app-flow/source-path.ts @@ -0,0 +1,6 @@ +import { relative, sep } from 'node:path' + +/** Source references and their stable IDs use the same path on every host. */ +export function relativeSourcePath(root: string, file: string): string { + return relative(root, file).split(sep).join('/') +} diff --git a/packages/core/src/app-flow/source-units.ts b/packages/core/src/app-flow/source-units.ts index bba04447..c5303d33 100644 --- a/packages/core/src/app-flow/source-units.ts +++ b/packages/core/src/app-flow/source-units.ts @@ -96,7 +96,10 @@ export function createSourceUnit(file: string, text: string): AppFlowSourceUnit /** Parse a set of `{file, text}` entries, keyed by absolute path. */ export function createSourceUnits(sources: { file: string; text: string }[]): Map { const units = new Map() - for (const source of sources) units.set(source.file, createSourceUnit(source.file, source.text)) + for (const source of sources) { + const file = resolve(source.file) + units.set(file, createSourceUnit(file, source.text)) + } return units } diff --git a/packages/core/src/app-flow/views-source.ts b/packages/core/src/app-flow/views-source.ts index 2ae09aa3..f6a388eb 100644 --- a/packages/core/src/app-flow/views-source.ts +++ b/packages/core/src/app-flow/views-source.ts @@ -1,4 +1,5 @@ -import { relative } from 'node:path' +import { resolve } from 'node:path' +import { relativeSourcePath } from './source-path.ts' import ts from 'typescript' import type { AppFlowSourceView, AppFlowStateSite } from '@mobile-dev/shared/app-flow.ts' import { fnName, jsxAttributes, ownerFn, sourceHash, unwrap } from './source-units.ts' @@ -88,7 +89,7 @@ export function scanSourceViews(units: Map, root: string, symbol: const call = unwrap(n.initializer), fn = owner(n) if (!fn || !ts.isCallExpression(call) || !/^react#use(?:State|Reducer)$/.test(symbol(unit, call.expression.getText()))) continue const value = n.name.elements[0], loc = location(unit, call) - const site: AppFlowStateSite = { id: sourceHash(`${relative(root, unit.file)}:${call.pos}`), file: relative(root, unit.file), ...loc, owner: name(fn), paths: [], hook: symbol(unit, call.expression.getText()).endsWith('useReducer') ? 'useReducer' : 'useState', valueName: value && ts.isBindingElement(value) && ts.isIdentifier(value.name) ? value.name.text : undefined } + const site: AppFlowStateSite = { id: sourceHash(`${relativeSourcePath(root, unit.file)}:${call.pos}`), file: relativeSourcePath(root, unit.file), ...loc, owner: name(fn), paths: [], hook: symbol(unit, call.expression.getText()).endsWith('useReducer') ? 'useReducer' : 'useState', valueName: value && ts.isBindingElement(value) && ts.isIdentifier(value.name) ? value.name.text : undefined } states.push(site) const v = { 0: { site, path: [] } } stateCalls.set(call, v) @@ -100,7 +101,7 @@ export function scanSourceViews(units: Map, root: string, symbol: const fn = owner(n) if (!fn) continue const loc = location(unit, n) - const site: AppFlowStateSite = { id: sourceHash(`${relative(root, unit.file)}:${n.pos}`), file: relative(root, unit.file), ...loc, owner: name(fn), paths: [], hook: symbol(unit, n.expression.getText()).endsWith('useReducer') ? 'useReducer' : 'useState' } + const site: AppFlowStateSite = { id: sourceHash(`${relativeSourcePath(root, unit.file)}:${n.pos}`), file: relativeSourcePath(root, unit.file), ...loc, owner: name(fn), paths: [], hook: symbol(unit, n.expression.getText()).endsWith('useReducer') ? 'useReducer' : 'useState' } states.push(site) stateCalls.set(n, { 0: { site, path: [] } }) calls.set(site.id, { unit, call: n }) @@ -138,7 +139,7 @@ export function scanSourceViews(units: Map, root: string, symbol: if (sources.length) for (const v of sources) { const owners = v.site.owners ??= [] if (!owners.includes(own)) owners.push(own) - const ownerSites = v.site.ownerSites ??= [], file = relative(root, fnUnits.get(fn)?.file ?? fn.getSourceFile().fileName) + const ownerSites = v.site.ownerSites ??= [], file = relativeSourcePath(root, fnUnits.get(fn)?.file ?? fn.getSourceFile().fileName) if (!ownerSites.some(site => site.file === file && site.owner === own)) ownerSites.push({ file, owner: own }) } else for (const v of Object.values(value)) consumers(v, fn, depth + 1) @@ -237,7 +238,7 @@ export function scanSourceViews(units: Map, root: string, symbol: // required callbacks/data cannot be filled with made-up values. const optional = (type: ts.TypeNode | ts.InterfaceDeclaration | undefined, seen = new Set()): boolean => { if (!type) return false - const context = units.get(type.getSourceFile().fileName) + const context = units.get(resolve(type.getSourceFile().fileName)) if (!context) return false if (ts.isTypeReferenceNode(type)) { const key = symbol(context, type.typeName.getText()) @@ -365,7 +366,7 @@ export function scanSourceViews(units: Map, root: string, symbol: ts.isBinaryExpression(parent) && parent.right === p && parent.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ? parent.left : undefined if (condition && truth(unit, condition, ref, state!.value) === undefined) guards++ } - const item = { file: relative(root, resolved.slice(0, split)), component: resolved.slice(split + 1), entry: { file: relative(root, unit.file), source: location(unit, n) }, ...(ref ? { guards } : {}) }, previous = result.get(resolved) + const item = { file: relativeSourcePath(root, resolved.slice(0, split)), component: resolved.slice(split + 1), entry: { file: relativeSourcePath(root, unit.file), source: location(unit, n) }, ...(ref ? { guards } : {}) }, previous = result.get(resolved) if (!previous || (item.guards ?? 0) < (previous.guards ?? 0)) result.set(resolved, item) } } @@ -381,7 +382,7 @@ export function scanSourceViews(units: Map, root: string, symbol: let jsx = false walk(body, n => { if (ts.isJsxElement(n) || ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) jsx = true }) if (!jsx) return - const components = parts(unit, body, extra.state), file = relative(root, unit.file), own = name(fn) + const components = parts(unit, body, extra.state), file = relativeSourcePath(root, unit.file), own = name(fn) const identity = extra.state ? ['state', extra.state] : [file, own, loc, kind, extra.control, extra.branch] const id = hash(identity), existing = views.get(id) const renderBody = ts.isCaseClause(body) || ts.isReturnStatement(body) || ts.isBlock(body) && body.statements.some(ts.isReturnStatement) || (() => { for (let p = body; p.parent && !ts.isFunctionLike(p.parent); p = p.parent) { if (ts.isReturnStatement(p.parent)) return true; if (ts.isJsxElement(p.parent) || ts.isJsxFragment(p.parent)) return false } return false })() @@ -465,15 +466,15 @@ export function scanSourceViews(units: Map, root: string, symbol: if (callee) target = `${fnUnits.get(callee)!.file}#${name(callee)}` if (!fn) continue const list = entries.get(target) ?? [], source = location(unit, n) - list.push({ file: relative(root, unit.file), line: source.line, owner: name(fn), source }) + list.push({ file: relativeSourcePath(root, unit.file), line: source.line, owner: name(fn), source }) entries.set(target, list) } - for (const view of views.values()) if (view.kind === 'component') view.entries = entries.get(`${root}/${view.file}#${view.owner}`) ?? [] + for (const view of views.values()) if (view.kind === 'component') view.entries = entries.get(`${resolve(root, view.file)}#${view.owner}`) ?? [] // Private functions cannot be found through module exports. Their actual JSX // callers let the bundler prove the function before runtime forces a hook render. for (const site of states) { const sources = [{ file: site.file, owner: site.owner }, ...(site.ownerSites ?? [])] - const callers = sources.flatMap(source => (entries.get(`${root}/${source.file}#${source.owner}`) ?? []) + const callers = sources.flatMap(source => (entries.get(`${resolve(root, source.file)}#${source.owner}`) ?? []) .flatMap(entry => entry.source ? [{ component: source.owner, file: entry.file, owner: entry.owner, source: entry.source }] : [])) if (callers.length) site.ownerEntries = [...new Map(callers.map(entry => [JSON.stringify(entry), entry])).values()] } diff --git a/packages/core/test/app-flow-presentations-bindings.test.ts b/packages/core/test/app-flow-presentations-bindings.test.ts index 2d1e0ce8..ac7c8c9f 100644 --- a/packages/core/test/app-flow-presentations-bindings.test.ts +++ b/packages/core/test/app-flow-presentations-bindings.test.ts @@ -1,5 +1,7 @@ import assert from 'node:assert/strict' +import { join, resolve } from 'node:path' import { describe, it } from 'node:test' +import { pathToFileURL } from 'node:url' import type { AppFlowPresentationAction, AppFlowStateSite } from '@mobile-dev/shared/app-flow.ts' import { bindPresentationSites } from '../src/app-flow/presentations-bindings.ts' import type { AppFlowBindingStats, AppFlowPresentationBinding } from '../src/app-flow/presentations-bindings.ts' @@ -27,6 +29,15 @@ function metro(map: (frame: { lineNumber: number; column: number }, index: numbe const at = (line: number, column = 4) => () => ({ file: `${root}/src/Screen.tsx`, lineNumber: line, column }) describe('App Flow presentation binding symbolication', () => { + it('joins a Metro file URL with a project-relative source site', async () => { + const project = resolve('my project') + const file = pathToFileURL(join(project, 'src', 'Screen.tsx')).href + const { fetch } = metro(() => ({ file, lineNumber: 1, column: 0 })) + const binding = { id: 'button', owner: 'Screen', stack: ` at Screen (${bundle}:1:1)` } + const matches = await bindPresentationSites(project, [binding], { states: [state({ id: 'site' })], actions: [] }, { metroOrigin, fetch }) + assert.deepEqual(matches, [{ binding: 'button', site: 'site' }]) + }) + it('parses both stack frame formats and resolves each against Metro', async () => { const bindings: AppFlowPresentationBinding[] = [ { id: 'a', owner: 'Screen', stack: ` at Screen (${bundle}:10:21)` }, diff --git a/packages/core/test/app-flow-typescript-runtime.test.ts b/packages/core/test/app-flow-typescript-runtime.test.ts index 35b3561f..a1779918 100644 --- a/packages/core/test/app-flow-typescript-runtime.test.ts +++ b/packages/core/test/app-flow-typescript-runtime.test.ts @@ -56,7 +56,8 @@ describe("App Flow TypeScript runtime", () => { } assert.ok(error instanceof ExpectedOperationError); assert.equal(error.outcome, "invalid_input"); - assert.match(error.message, new RegExp(`${root}[\\s\\S]*npm install --save-dev typescript`)); + assert.ok(error.message.includes(root)); + assert.match(error.message, /npm install --save-dev typescript/); }); it("prefers the project copy over the one the bundle would otherwise fall back to", async () => {