Skip to content
57 changes: 44 additions & 13 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,32 @@ const USE_SEARCH_PARAMS_IMPORT_RESTRICTION = {
"Don't read query params with useSearchParams — use useQueryStates from 'nuqs' (typed parsers, URL as state). See CLAUDE.md 'URL as State'. DS 10 ratchet: existing files are allowlisted; new files must use nuqs.",
}

const REGISTER_PLUGIN_IMPORT_RESTRICTION = {
name: '@capacitor/core',
importNames: ['registerPlugin'],
Comment thread
innolope-dev marked this conversation as resolved.
message:
"Don't call registerPlugin directly — declare the plugin with nativeCapability() from '@/utils/native-capability' and reach it through .call(method, options, onUnavailable). This JS ships over the air onto binaries built months earlier, where the plugin simply does not exist and Capacitor answers a missing native method with a rejected promise, not a compile error: a forgotten try/catch is a crash on a user's device that no type and no test sees. The wrapper also gates on platform and keeps the proxy inside the closure, so it can never be returned across an await (the .then trap that shipped in 1.0.44 and 1.0.45–1.0.47).",
}

// Every import restriction in one list, plus a way to drop exactly one.
//
// Overrides used to write `'no-restricted-imports': 'off'`, which disables the
// WHOLE rule — so the tailwind-merge exemption for tw.ts also switched off the
// barrel-import and registerPlugin bans there, and any future exemption would
// silently do the same to whatever was added since. Naming the one restriction
// being lifted keeps an exemption about the thing it is for.
const BASE_IMPORT_RESTRICTIONS = [
...RESTRICTED_IMPORT_PATHS,
USE_SEARCH_PARAMS_IMPORT_RESTRICTION,
TAILWIND_MERGE_IMPORT_RESTRICTION,
REGISTER_PLUGIN_IMPORT_RESTRICTION,
]

const restrictedImportsExcept = (...lifted) => [
'error',
{ paths: BASE_IMPORT_RESTRICTIONS.filter((restriction) => !lifted.includes(restriction)) },
]

const QUERY_STRING_PUSH_MESSAGE =
"Don't build a query string by hand for router.push/replace — write URL state with useQueryStates from 'nuqs' (its setter updates the params in place; pathname-only navigation is fine). See CLAUDE.md 'URL as State'. DS 10 ratchet: existing files are allowlisted; new files must use nuqs."

Expand Down Expand Up @@ -218,16 +244,7 @@ module.exports = [
'react/no-unknown-property': ['error', { ignore: ['jsx', 'global'] }],

// Ban barrel imports (see BANNED_BARREL_PATHS) + useSearchParams (DS 10).
'no-restricted-imports': [
'error',
{
paths: [
...RESTRICTED_IMPORT_PATHS,
USE_SEARCH_PARAMS_IMPORT_RESTRICTION,
TAILWIND_MERGE_IMPORT_RESTRICTION,
],
},
],
'no-restricted-imports': restrictedImportsExcept(),

// Ban self-imports — CLAUDE.md import rules. Confirmed firing on synthetic test.
'import-x/no-self-import': 'error',
Expand Down Expand Up @@ -256,9 +273,16 @@ module.exports = [
},
{
// The wrapper itself (and its census test) are the only legal raw
// tailwind-merge importers.
// tailwind-merge importers. Only THAT restriction is lifted: a blanket
// off also switched the registerPlugin ban off here.
files: ['src/utils/tw.ts', 'src/utils/__tests__/tw.test.ts'],
rules: { 'no-restricted-imports': 'off' },
rules: { 'no-restricted-imports': restrictedImportsExcept(TAILWIND_MERGE_IMPORT_RESTRICTION) },
},
{
// The wrapper itself is the one legal registerPlugin caller — it is
Comment thread
innolope-dev marked this conversation as resolved.
// what every other call site is required to go through.
files: ['src/utils/native-capability.ts'],
rules: { 'no-restricted-imports': restrictedImportsExcept(REGISTER_PLUGIN_IMPORT_RESTRICTION) },
},
{
// Capacitor hardware back: different bug class (canGoBack + minimizeApp).
Expand Down Expand Up @@ -355,7 +379,14 @@ module.exports = [
'src/hooks/useSendFlowOrigin.ts',
],
rules: {
'no-restricted-imports': ['error', { paths: RESTRICTED_IMPORT_PATHS }],
// Only the DS 10 restrictions are lifted. This block REPLACES the
// base rule rather than extending it, so a bare RESTRICTED_IMPORT_PATHS
// let every allowlisted file import registerPlugin directly and walk
// around the single-door invariant.
'no-restricted-imports': restrictedImportsExcept(
USE_SEARCH_PARAMS_IMPORT_RESTRICTION,
TAILWIND_MERGE_IMPORT_RESTRICTION
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
),
},
},
{
Expand Down
1 change: 1 addition & 0 deletions src/utils/__tests__/clipboard-detect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ jest.mock('@capacitor/core', () => ({

jest.mock('../capacitor', () => ({
isIOSNative: jest.fn(() => false),
isNativeBridge: jest.fn(() => true),
}))

const mockIsIOSNative = isIOSNative as jest.MockedFunction<typeof isIOSNative>
Expand Down
1 change: 1 addition & 0 deletions src/utils/__tests__/deferred-link.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jest.mock('../capacitor', () => ({
getPlatform: jest.fn(() => 'web'),
isAndroidNative: jest.fn(() => false),
isIOSNative: jest.fn(() => false),
isNativeBridge: jest.fn(() => true),
}))

jest.mock('../clipboard-detect', () => ({
Expand Down
181 changes: 181 additions & 0 deletions src/utils/__tests__/native-capability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// nativeCapability is the single door to app-local Capacitor plugins, so its
// job is the failure paths: a plugin the running binary predates, a platform
// with no native half, and the registerPlugin proxy's thenable trap.
import { nativeCapability } from '../native-capability'
import { isAndroidNative, isIOSNative, isNativeBridge } from '../capacitor'
import { createPluginProxy, expectToSettle } from '../__mocks__/capacitor-plugin-proxy'

const pluginImplementation: Record<string, unknown> = {}

jest.mock('@capacitor/core', () => ({
// The real registerPlugin returns a Proxy, not a plain object. Mocking it
// as a plain object is what hides the thenable trap, so the house mock is
// used here too.
registerPlugin: jest.fn(() =>
jest.requireActual('../__mocks__/capacitor-plugin-proxy').createPluginProxy(pluginImplementation, 'TestPlugin')
),
}))

jest.mock('../capacitor', () => ({
isIOSNative: jest.fn(() => false),
isAndroidNative: jest.fn(() => false),
// Defaults true so the platform mocks stay the subject of each test; the
// bridge gate gets its own case below.
isNativeBridge: jest.fn(() => true),
}))

const mockIsIOSNative = isIOSNative as jest.MockedFunction<typeof isIOSNative>
const mockIsAndroidNative = isAndroidNative as jest.MockedFunction<typeof isAndroidNative>
const mockIsNativeBridge = isNativeBridge as jest.MockedFunction<typeof isNativeBridge>

interface TestPlugin {
doThing(options?: undefined): Promise<{ value: string }>
}

describe('nativeCapability', () => {
beforeEach(() => {
jest.clearAllMocks()
for (const key of Object.keys(pluginImplementation)) delete pluginImplementation[key]
mockIsIOSNative.mockReturnValue(false)
mockIsAndroidNative.mockReturnValue(false)
mockIsNativeBridge.mockReturnValue(true)
})

it('returns the native answer on a supported platform', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => ({ value: 'native' }))

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'native',
})
})

it('falls back without touching the plugin on an unsupported platform', async () => {
mockIsAndroidNative.mockReturnValue(true)
const doThing = jest.fn()
pluginImplementation.doThing = doThing

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'fallback',
})
// Not merely "answered fallback": on web the proxy exists and invoking
// it rejects, so the gate has to stop the call, not catch it.
expect(doThing).not.toHaveBeenCalled()
})

it('falls back when the running binary predates the plugin', async () => {
mockIsIOSNative.mockReturnValue(true)
// The method is simply absent — exactly an older binary running OTA'd
// JS. The proxy answers with an Unimplemented rejection, not undefined.

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'fallback',
})
})

it('hands the rejection to the fallback, for callers that report it', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => {
throw new Error('user cancelled')
})

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })
const result = await capability.call('doThing', undefined, (error) => ({
value: error instanceof Error ? error.message : 'unknown',
}))

expect(result).toEqual({ value: 'user cancelled' })
})

it('settles rather than hanging, even though the plugin is a proxy', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => ({ value: 'native' }))

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

// The trap this closes: resolving a promise WITH the plugin makes the
// runtime probe proxy.then, which dispatches a native call that never
// invokes either callback — the promise stays pending forever.
await expect(
expectToSettle(capability.call('doThing', undefined, () => ({ value: 'fallback' })))
).resolves.toEqual({ value: 'native' })
})

it('gives callers no way to get the proxy back out', () => {
const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

// The reason `call` takes a method NAME. With a callback signature,
// `call(async (plugin) => plugin, fallback)` type-checks and then hangs
// forever: the async function assimilates the proxy's .then while
// resolving, so it never reaches the catch or the fallback. There is no
// runtime guard for it — the hang happens before any code of ours runs
// again — so the invariant has to hold at the type level, and typecheck
// is a CI job. If this stops erroring, the hole is back.
const callback = async (plugin: TestPlugin) => plugin
const fallback = () => undefined

// Declared and never invoked. TypeScript still checks the body, which
// is the whole assertion — running it would crash: the two-argument
// call leaves onUnavailable undefined, and the point is precisely that
// this does not compile.
//
// Each directive sits directly above its CALL because it binds to the
// next LINE, and prettier wraps a long argument list — which parks the
// error below the comment and reports the directive itself as unused.
const rejectedByTheCompiler = () => {
// @ts-expect-error a callback is not a method name
void capability.call(callback, fallback)
// @ts-expect-error 'notAMethod' is not a method on TestPlugin
void capability.call('notAMethod', undefined, fallback)
}

expect(typeof rejectedByTheCompiler).toBe('function')
})

it('needs a live bridge, not just a native-looking platform', () => {
// isIOSNative/isAndroidNative fall back to a user-agent sniff, which
// deliberately reports a capacitor-flavoured web build as native — a
// Vercel preview opened on an Android phone. There is no bridge there,
// so the plugin proxy would reject; platform alone is not enough.
mockIsIOSNative.mockReturnValue(true)
mockIsNativeBridge.mockReturnValue(false)
const doThing = jest.fn()
pluginImplementation.doThing = doThing

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

expect(capability.isSupportedPlatform()).toBe(false)
return expect(capability.call('doThing', undefined, () => ({ value: 'fallback' })))
.resolves.toEqual({ value: 'fallback' })
.then(() => expect(doThing).not.toHaveBeenCalled())
})

it('reports platform support from the declared platforms', () => {
const iosOnly = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })
const both = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios', 'android'] })

expect(iosOnly.isSupportedPlatform()).toBe(false)

mockIsAndroidNative.mockReturnValue(true)
expect(iosOnly.isSupportedPlatform()).toBe(false)
expect(both.isSupportedPlatform()).toBe(true)

mockIsAndroidNative.mockReturnValue(false)
mockIsIOSNative.mockReturnValue(true)
expect(iosOnly.isSupportedPlatform()).toBe(true)
})

it('keeps the house proxy semantics the mock exists to enforce', async () => {
// Guards the guard: if createPluginProxy ever stopped rejecting for
// absent methods, every "older binary" test above would pass vacuously.
const proxy = createPluginProxy<Record<string, unknown>>({}, 'TestPlugin')

await expect((proxy as unknown as TestPlugin).doThing()).rejects.toThrow('is not implemented')
})
})
20 changes: 20 additions & 0 deletions src/utils/__tests__/push-provisioning.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ jest.mock('@capacitor/core', () => ({
jest.mock('../capacitor', () => ({
isIOSNative: jest.fn(() => false),
isAndroidNative: jest.fn(() => false),
isNativeBridge: jest.fn(() => true),
}))

const mockIsIOSNative = isIOSNative as jest.MockedFunction<typeof isIOSNative>
Expand Down Expand Up @@ -62,7 +63,14 @@ describe('getPushProvisioningAvailability', () => {

describe('addCardToWallet', () => {
beforeEach(() => {
// Both platform answers reset AND a supported one enabled explicitly:
// clearAllMocks keeps mockReturnValue, so these tests used to pass only
// because the availability suite above happened to leave Android true.
// Run alone, each took the unsupported-platform fallback and never
// reached addCard at all.
jest.clearAllMocks()
mockIsIOSNative.mockReturnValue(false)
mockIsAndroidNative.mockReturnValue(true)
})

it('passes through the native result', async () => {
Expand All @@ -71,6 +79,7 @@ describe('addCardToWallet', () => {
added: true,
last4: '1234',
})
expect(addCard).toHaveBeenCalled()
})

it('never throws — plugin errors come back as { added: false, error }', async () => {
Expand All @@ -79,5 +88,16 @@ describe('addCardToWallet', () => {
added: false,
error: 'boom',
})
expect(addCard).toHaveBeenCalled()
})

it('is unavailable on web without touching the plugin', async () => {
mockIsAndroidNative.mockReturnValue(false)

await expect(addCardToWallet({ cardId: 'c', cardSecret: 's' })).resolves.toEqual({
added: false,
error: 'PushProvisioning is not available on this platform',
})
expect(addCard).not.toHaveBeenCalled()
})
})
25 changes: 6 additions & 19 deletions src/utils/clipboard-detect.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { registerPlugin } from '@capacitor/core'
import { isIOSNative } from './capacitor'
import { nativeCapability } from './native-capability'

interface ClipboardDetectPlugin {
hasStrings(): Promise<{ value: boolean }>
hasProbableWebUrl(): Promise<{ value: boolean }>
hasStrings(options?: undefined): Promise<{ value: boolean }>
hasProbableWebUrl(options?: undefined): Promise<{ value: boolean }>
}

// App-local iOS plugin (ios/App/App/ClipboardDetectPlugin.swift); no web/Android
// implementation exists — callers must treat "unavailable" as false.
const ClipboardDetect = registerPlugin<ClipboardDetectPlugin>('ClipboardDetect')
const ClipboardDetect = nativeCapability<ClipboardDetectPlugin>('ClipboardDetect', { platforms: ['ios'] })

/**
* iOS-native only: prompt-free "is there text on the clipboard?" check via
Expand All @@ -18,13 +17,7 @@ const ClipboardDetect = registerPlugin<ClipboardDetectPlugin>('ClipboardDetect')
* (OTA'd JS), so the caller simply doesn't offer the paste shortcut there.
*/
export async function clipboardHasStrings(): Promise<boolean> {
if (!isIOSNative()) return false
try {
const { value } = await ClipboardDetect.hasStrings()
return value
} catch {
return false
}
return (await ClipboardDetect.call('hasStrings', undefined, () => ({ value: false }))).value
}

/**
Expand All @@ -35,11 +28,5 @@ export async function clipboardHasStrings(): Promise<boolean> {
* the prompt. False on other platforms and binaries without the method.
*/
export async function clipboardHasProbableWebUrl(): Promise<boolean> {
if (!isIOSNative()) return false
try {
const { value } = await ClipboardDetect.hasProbableWebUrl()
return value
} catch {
return false
}
return (await ClipboardDetect.call('hasProbableWebUrl', undefined, () => ({ value: false }))).value
}
Loading
Loading