Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 132 additions & 9 deletions config/scripts/mobile-web-app-external-link-seam.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,146 @@
* Shared by every page route's census rather than restated in each: two spellings of one rule
* drift, and the half that stops being enforced is the half nobody reads again.
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import ts from 'typescript-api'

/** The seam, as the web build resolves it: `.web.ts` wins under the builder's resolveExtensions,
* and it is the one module a page closure may reach react-native's `Linking` from. */
export const EXTERNAL_LINK_SEAM = 'src/platform/external-link.web.ts'

/**
* Whether a module reaches react-native's own `Linking`, by name or through a namespace import.
* Every line on which a module reaches react-native's own `Linking`, by name or through a
* namespace import.
*
* Both quote styles: the tree is single-quoted by the formatter today, so a double-quoted
* specifier would have walked past this unseen — and a census that cannot see a call site is one
* that passes for the wrong reason.
* Parsed rather than matched: a regex over the text names `Linking` inside a comment that talks
* about it and inside a string that quotes it, and a census that reports a line nobody can act on
* is one the next reader learns to ignore. The parser also settles the quote styles for free.
*
* A named import reports the import statement, once however many times the module calls through
* it, because the import is the thing the rule is about and the thing that has to go. The imported
* name is what counts, not the local one: `import { Linking as NativeLinking }` is the same import
* spelled differently, and reading only the binding let it through.
*
* A namespace import reports its uses instead, there being no single line to name — `import * as RN
* from 'react-native'` is not itself an offence — and every alias is read, because a module may
* import the namespace twice and call on either. A default import is read the same way: this
* project's interop settings accept `import RN from 'react-native'` (checked with tsc), so it is a
* binding the whole namespace hangs off exactly as `* as RN` is.
*
* A re-export is reported at the export statement. `export { Linking } from 'react-native'` puts
* the name back in reach of anything that imports this module, and so does `export *`, which
* carries it along with everything else; the statement is the line to delete, exactly as an import
* is.
*
* Lines rather than a boolean because a red census that names `path:line` is read once, and one
* that names a file is grepped for. The boolean below is derived from this, so there is one rule.
*
* `fileName` decides the script kind, and the default is only for callers holding a source with no
* path. In a `.ts` file `const id = <T>(value: T) => value` is a generic arrow; parsed as TSX it is
* an unclosed JSX element, and everything after it — a later `RN.Linking.openURL` included — is
* swallowed into the error node and never walked.
*/
export function reactNativeLinkingSites(source, fileName = 'module.tsx') {
// No explicit script kind: TypeScript reads it off the extension, which is the whole point.
const parsed = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true)
const lineOf = (node) => parsed.getLineAndCharacterOfPosition(node.getStart(parsed)).line + 1
const sites = []
const aliases = new Set()
const fromReactNative = (statement) =>
statement.moduleSpecifier !== undefined &&
ts.isStringLiteral(statement.moduleSpecifier) &&
statement.moduleSpecifier.text === 'react-native'
/** `propertyName` is the exported/imported name when the clause renames it, `name` when it does not. */
const namesLinking = (elements) =>
elements.some((element) => (element.propertyName ?? element.name).text === 'Linking')
for (const statement of parsed.statements) {
if (ts.isExportDeclaration(statement) && fromReactNative(statement)) {
const clause = statement.exportClause
// No clause is `export *`, which carries `Linking` with everything else; a namespace export
// hands the whole module over under one name. Both put it back in reach.
if (clause === undefined || ts.isNamespaceExport(clause) || namesLinking(clause.elements)) {
sites.push(lineOf(statement))
}
continue
}
if (!ts.isImportDeclaration(statement) || !fromReactNative(statement)) {
continue
}
const clause = statement.importClause
if (clause === undefined) {
continue
}
if (clause.name !== undefined) {
aliases.add(clause.name.text)
}
const bindings = clause.namedBindings
if (bindings === undefined) {
continue
}
if (ts.isNamespaceImport(bindings)) {
aliases.add(bindings.name.text)
continue
}
if (namesLinking(bindings.elements)) {
sites.push(lineOf(statement))
}
}
if (aliases.size > 0) {
const visit = (node) => {
if (
ts.isPropertyAccessExpression(node) &&
ts.isIdentifier(node.expression) &&
aliases.has(node.expression.text) &&
node.name.text === 'Linking'
) {
// The line, not the expression: two aliases meeting on one line are one site.
sites.push(lineOf(node))
}
ts.forEachChild(node, visit)
}
ts.forEachChild(parsed, visit)
}
return [...new Set(sites)].sort((left, right) => left - right)
}

/** Whether a module reaches react-native's own `Linking`. */
export function reachesReactNativeLinking(source, fileName = 'module.tsx') {
return reactNativeLinkingSites(source, fileName).length > 0
}

/**
* Every module in a route's closure that can reach a URL without the seam, as `path:line`.
*
* The line is where the name enters the module, not where it is used: a named import is reported
* once however many times the module calls `Linking.openURL`, because the import is what the rule
* is about and what has to go. Only a namespace import reports its uses, there being no single
* line to name — `import * as RN from 'react-native'` is not itself an offence.
*
* Here rather than beside each census: three copies of this walk existed before the source-control
* routes wanted a fourth, and the seam's own module is where the rule they share belongs. A file
* the closure names but this checkout cannot read is not an offender — the closure reports paths
* relative to `mobile/`, and one outside it is read by its caller, not guessed at here.
*/
export function reachesReactNativeLinking(source) {
const named = /import\s*\{[^}]*\bLinking\b[^}]*\}\s*from\s*['"]react-native['"]/s
const namespace = /import\s*\*\s*as\s*(\w+)\s*from\s*['"]react-native['"]/
const asNamespace = namespace.exec(source)
export function externalLinkOffenders(mobileDir, closure) {
return (
named.test(source) || (asNamespace !== null && source.includes(`${asNamespace[1]}.Linking`))
closure.local
.filter((file) => file !== EXTERNAL_LINK_SEAM)
.flatMap((file) => {
let source
try {
source = readFileSync(join(mobileDir, file), 'utf8')
} catch {
return []
}
// The path, so the parser takes the script kind from the extension rather than assuming TSX.
return reactNativeLinkingSites(source, file).map((line) => [file, line])
})
// By path, then by line as a number: sorting the rendered strings puts `:10` before `:2`, and
// a red list is read top to bottom against the file it names.
.sort(([leftFile, leftLine], [rightFile, rightLine]) =>
leftFile === rightFile ? leftLine - rightLine : leftFile < rightFile ? -1 : 1
)
.map(([file, line]) => `${file}:${line}`)
)
}
186 changes: 185 additions & 1 deletion config/scripts/mobile-web-app-external-link-seam.test.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { reachesReactNativeLinking } from './mobile-web-app-external-link-seam.mjs'
import {
externalLinkOffenders,
reachesReactNativeLinking,
reactNativeLinkingSites
} from './mobile-web-app-external-link-seam.mjs'

const mobileDir = fileURLToPath(new URL('../../mobile/', import.meta.url))

describe('the seam predicate', () => {
it.each([
["import { Linking } from 'react-native'", true],
Expand All @@ -12,3 +23,176 @@ describe('the seam predicate', () => {
expect(reachesReactNativeLinking(source)).toBe(expected)
})
})

describe('where the seam predicate says a module reaches Linking', () => {
it('reports the import line, which is what a red census is read for', () => {
expect(
reactNativeLinkingSites(
"import { View } from 'react-native'\n\nimport {\n Linking\n} from 'react-native'\n"
)
).toEqual([3])
})

it('reports every line a namespace import is used on, not just the import', () => {
expect(
reactNativeLinkingSites(
"import * as RN from 'react-native'\nRN.Linking.openURL(a)\nconst b = 1\nRN.Linking.openURL(c)\n"
)
).toEqual([2, 4])
})

it('inspects every alias, not just the first namespace import', () => {
// Two namespace imports of react-native, the first unused. Reading only the first alias makes
// a module that calls `Linking.openURL` on the second report no site at all.
expect(
reactNativeLinkingSites(
"import * as Unused from 'react-native'\nimport * as RN from 'react-native'\nRN.Linking.openURL(u)\n"
)
).toEqual([3])
})

it('counts a line once when two aliases meet on it', () => {
expect(
reactNativeLinkingSites(
"import * as A from 'react-native'\nimport * as B from 'react-native'\nA.Linking.openURL(B.Linking)\n"
)
).toEqual([3])
})

it('names an import that renames Linking, which reading the binding alone missed', () => {
// `import { Linking as NativeLinking }` is the same import spelled differently; the imported
// name lives in `propertyName` when a specifier renames it, and only in `name` when it does
// not. Reading `name` alone let `NativeLinking.openURL` through the census entirely.
expect(
reactNativeLinkingSites(
"import { Linking as NativeLinking } from 'react-native'\nNativeLinking.openURL(u)\n"
)
).toEqual([1])
})

it('leaves alone a local binding that is only spelled Linking', () => {
// The other half of reading `propertyName`: this module imports `View`, so naming it would be
// a red line with nothing to fix at the end of it.
expect(
reactNativeLinkingSites("import { View as Linking } from 'react-native'\nLinking.foo()\n")
).toEqual([])
})

it('reads a default import as the namespace it is, which the interop here allows', () => {
// `import RN from 'react-native'` typechecks here, so it is a binding the whole namespace
// hangs off and a call through it is as invisible to a named-import rule as an alias was.
expect(
reactNativeLinkingSites("import RN from 'react-native'\nRN.Linking.openURL(u)\n")
).toEqual([2])
})

it('leaves alone an alias that is imported and never reaches Linking', () => {
// An import of react-native is not the offence; reaching `Linking` through it is.
expect(reactNativeLinkingSites("import * as RN from 'react-native'\nRN.Platform.OS\n")).toEqual(
[]
)
})

it('parses a .ts module as TypeScript, where a generic arrow is not an unclosed tag', () => {
// `const id = <T>(value: T) => value` is a generic arrow in a `.ts` file and an unclosed JSX
// element in a `.tsx` one. Parsed as TSX, everything after it falls into the error node, so
// the call below was never walked and the module reported nothing at all.
expect(
reactNativeLinkingSites(
"import * as RN from 'react-native'\nconst id = <T>(value: T) => value\nRN.Linking.openURL(u)\n",
'module.ts'
)
).toEqual([3])
})

it.each([
["export { Linking } from 'react-native'\n", 'a named re-export'],
["export { Linking as L } from 'react-native'\n", 'a renamed re-export'],
["export * from 'react-native'\n", 'a wildcard re-export, which carries it with the rest'],
["export * as RN from 'react-native'\n", 'a namespace re-export']
])('names %# : %s', (source) => {
// A re-export puts `Linking` back in reach of whatever imports this module, so the route's
// closure reaches it through a file that never imported it. The export statement is the line
// to delete, exactly as an import is.
expect(reactNativeLinkingSites(source, 'module.ts')).toEqual([1])
})

it.each([
["export { View } from 'react-native'\n", 're-exports something else'],
[
"export { Linking } from './local'\n",
're-exports the name from somewhere that is not react-native'
]
])('leaves alone a module that %# : %s', (source) => {
expect(reactNativeLinkingSites(source, 'module.ts')).toEqual([])
})

it('ignores the name inside a comment, which text matching cannot', () => {
// A module that talks about the rule is not breaking it, and a census that names a comment is
// one whose red list the next reader learns to skip.
expect(
reactNativeLinkingSites(
"import * as RN from 'react-native'\n// never call RN.Linking.openURL here\n/* nor RN.Linking */\n"
)
).toEqual([])
})

it('ignores the name inside a string, and still sees the call beside it', () => {
expect(
reactNativeLinkingSites(
"import * as RN from 'react-native'\nconst hint = 'use RN.Linking.openURL'\nRN.Linking.openURL(u)\n"
)
).toEqual([3])
})

it('ignores a commented-out named import, which was the same class of miss', () => {
expect(reactNativeLinkingSites("// import { Linking } from 'react-native'\n")).toEqual([])
})

it('finds nothing in a module that only names the seam', () => {
expect(
reactNativeLinkingSites("import { openExternalLink } from '../platform/external-link'")
).toEqual([])
})
})

describe('the offenders in a closure', () => {
// The seam itself imports `Linking` and is the one module allowed to, so a walk that did not
// exempt it would report every closure as an offender and never be able to go green.
const closure = { local: ['src/platform/external-link.web.ts', 'src/platform/external-link.ts'] }

it('exempts the seam and names the module that went around it', () => {
expect(externalLinkOffenders(mobileDir, closure)).toEqual(['src/platform/external-link.ts:1'])
})

it('ignores a path this checkout cannot read rather than calling it an offender', () => {
expect(externalLinkOffenders(mobileDir, { local: ['src/not/a/file.ts'] })).toEqual([])
})
})

describe('the order a red list is read in', () => {
// Against a written fixture rather than the tree: the ordering this pins needs one module with
// sites on lines 2 and 10, the pair that sorts one way as numbers and the other as text, and no
// module in the closure has to keep having one.
const root = mkdtempSync(join(tmpdir(), 'orca-seam-census-'))
const lines = ["import * as RN from 'react-native'", 'RN.Linking.openURL(a)']
while (lines.length < 9) {
lines.push('')
}
lines.push('RN.Linking.openURL(b)')
writeFileSync(join(root, 'wide.ts'), `${lines.join('\n')}\n`)
writeFileSync(join(root, 'above.ts'), "import { Linking } from 'react-native'\n")

it('puts line 2 before line 10, which sorting the rendered strings does not', () => {
// `:10` sorts before `:2` as text. The namespace import on line 1 is not itself an offence.
expect(externalLinkOffenders(root, { local: ['wide.ts'] })).toEqual(['wide.ts:2', 'wide.ts:10'])
})

it('orders by path first, so two modules never interleave', () => {
expect(externalLinkOffenders(root, { local: ['wide.ts', 'above.ts'] })).toEqual([
'above.ts:1',
'wide.ts:2',
'wide.ts:10'
])
})
})
19 changes: 2 additions & 17 deletions config/scripts/mobile-web-app-files-external-links.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,14 @@
* page route reaches and which the worktree list declares nothing for — and declares the grant
* because its rows push to the preview in-page, under the session the explorer opened.
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { mobileWebAppRouteClosure } from './build-mobile-web-app-bundle.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs'
import { mobileWebAppDependenciesPresent } from './mobile-web-app-bundle-dependencies.mjs'
import {
EXTERNAL_LINK_SEAM as SEAM,
reachesReactNativeLinking
externalLinkOffenders
} from './mobile-web-app-external-link-seam.mjs'

const mobileDir = fileURLToPath(new URL('../../mobile/', import.meta.url))
Expand All @@ -33,25 +31,12 @@ const PREVIEW = 'app/h/[hostId]/files/preview/[worktreeId].tsx'
/** The seam's only in-domain consumer, and the reason the preview declares the grant itself. */
const MARKDOWN = 'src/components/MobileMarkdown.tsx'

function offenders(closure) {
return closure.local
.filter((file) => file !== SEAM)
.filter((file) => {
try {
return reachesReactNativeLinking(readFileSync(join(mobileDir, file), 'utf8'))
} catch {
return false
}
})
.sort()
}

describeClosure(
'the files page closures',
() => {
it.each([EXPLORER, PREVIEW])('opens every external URL through the seam: %s', async (route) => {
const closure = await mobileWebAppRouteClosure(route)
expect(offenders(closure)).toEqual([])
expect(externalLinkOffenders(mobileDir, closure)).toEqual([])
})

it.each([EXPLORER, PREVIEW])(
Expand Down
Loading
Loading