Skip to content
14 changes: 14 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ 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(invoke, 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).",
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
}

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 @@ -225,6 +232,7 @@ module.exports = [
...RESTRICTED_IMPORT_PATHS,
USE_SEARCH_PARAMS_IMPORT_RESTRICTION,
TAILWIND_MERGE_IMPORT_RESTRICTION,
REGISTER_PLUGIN_IMPORT_RESTRICTION,
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
],
},
],
Expand Down Expand Up @@ -260,6 +268,12 @@ module.exports = [
files: ['src/utils/tw.ts', 'src/utils/__tests__/tw.test.ts'],
rules: { 'no-restricted-imports': 'off' },
},
{
// 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': 'off' },
},
{
// Capacitor hardware back: different bug class (canGoBack + minimizeApp).
files: ['src/hooks/useNativePlugins.ts'],
Expand Down
145 changes: 145 additions & 0 deletions src/utils/__tests__/native-capability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// 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 } 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),
}))

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

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

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

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(
async (p) => (await p.doThing()).value,
() => 'fallback'
)
).resolves.toBe('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(
async (p) => (await p.doThing()).value,
() => 'fallback'
)
).resolves.toBe('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(
async (p) => (await p.doThing()).value,
() => 'fallback'
)
).resolves.toBe('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(
async (p) => (await p.doThing()).value,
(error) => (error instanceof Error ? error.message : 'unknown')
)

expect(result).toBe('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. The
// proxy cannot escape `call`, so the result is always a plain value.
await expect(
expectToSettle(
capability.call(
(p) => p.doThing(),
() => ({ value: 'fallback' })
)
)
).resolves.toEqual({
value: 'native',
})
})

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')
})
})
27 changes: 10 additions & 17 deletions src/utils/clipboard-detect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { registerPlugin } from '@capacitor/core'
import { isIOSNative } from './capacitor'
import { nativeCapability } from './native-capability'

interface ClipboardDetectPlugin {
hasStrings(): Promise<{ value: boolean }>
Expand All @@ -8,7 +7,7 @@ interface ClipboardDetectPlugin {

// 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,10 @@ 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 ClipboardDetect.call(
async (plugin) => (await plugin.hasStrings()).value,
() => false
)
}

/**
Expand All @@ -35,11 +31,8 @@ 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 ClipboardDetect.call(
async (plugin) => (await plugin.hasProbableWebUrl()).value,
() => false
)
}
23 changes: 12 additions & 11 deletions src/utils/deferred-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
// native app. android rides the Play Install Referrer; iOS rides a clipboard
// hand-off written on the store-bounce tap and read once on first launch.
// TASK-20772 — the download modal (TASK-20769) is the eventual web consumer.
import { registerPlugin } from '@capacitor/core'
import posthog from 'posthog-js'
import { ANALYTICS_EVENTS, DEFERRED_LINK_OUTCOMES, type DeferredLinkOutcome } from '@/constants/analytics.consts'
import { PLAY_STORE_URL } from '@/constants/general.consts'
import { isValidLocale } from '@/i18n/config'
import { type AppLocale, resolveLocaleOrNull } from '@/i18n/app/config'
import { isAndroidNative, isIOSNative } from './capacitor'
import { nativeCapability } from './native-capability'
import { getFromCookie, saveToCookie, sanitizeRedirectURL } from './cookie-url.utils'
import { toInviteCode } from './invite-code.utils'
import { deepLinkToNativePath } from './native-routes'
Expand Down Expand Up @@ -52,19 +52,20 @@ export interface DeferredPayload {
dest?: string
}

// app-local android plugin (InstallReferrerPlugin.java); throws "not
// implemented" on iOS/web and on older binaries running OTA'd JS — callers
// catch and treat as null.
const InstallReferrer = registerPlugin<{ getReferrer(): Promise<{ referrer: string | null }> }>('InstallReferrer')
// app-local android plugin (InstallReferrerPlugin.java); absent on iOS/web and
// on older binaries running OTA'd JS, which the capability turns into null.
const InstallReferrer = nativeCapability<{ getReferrer(): Promise<{ referrer: string | null }> }>('InstallReferrer', {
platforms: ['android'],
})

/** raw play install referrer string, or null anywhere it can't be read. */
export async function readInstallReferrer(): Promise<string | null> {
try {
return (await InstallReferrer.getReferrer()).referrer ?? null
} catch {
// older binary without the plugin, iOS/web, or referrer service unavailable
return null
}
// null covers all of: older binary without the plugin, iOS/web, and the
// referrer service being unavailable on a busy first boot.
return InstallReferrer.call(
async (plugin) => (await plugin.getReferrer()).referrer ?? null,
() => null
)
}

// ---------------------------------------------------------------------------
Expand Down
78 changes: 78 additions & 0 deletions src/utils/native-capability.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { registerPlugin } from '@capacitor/core'
import { isAndroidNative, isIOSNative } from './capacitor'

/**
* The one place app-local Capacitor plugins are reached, because every call to
* one has to survive the same thing: **the JS half ships over the air onto
* binaries built months earlier.** A plugin the current tree takes for granted
* simply is not there on an older shell, and Capacitor's answer to a missing
* native method is a rejected promise, not a compile error — so a forgotten
* try/catch is a crash on a user's device that no test and no type sees.
*
* Three separate hazards get closed here instead of at each call site:
*
* 1. **Missing plugin.** Older binary, or a platform with no implementation:
* the call rejects, and `call()` answers with the caller's fallback.
* 2. **Wrong platform.** `registerPlugin` happily hands back a proxy on web,
* where invoking it rejects. The platform gate means no call is attempted.
* 3. **The thenable trap.** The proxy answers ANY property with a native-method
* wrapper, `.then` included, so resolving a promise WITH a plugin leaves it
* pending forever (shipped twice — getPreferences in 1.0.44, the Crisp
* helper in 1.0.45–1.0.47). Here the proxy never escapes the closure it is
* handed to, so it cannot be returned across an await by construction.
*
* Version-gated capabilities — where the plugin EXISTS but an older native half
* behaves differently — are a different problem and stay bespoke; see
* `canRestartInPlace()` in capgo-updater.ts, which reads the native plugin's own
* version rather than trusting package.json.
*/

type NativePlatform = 'ios' | 'android'

export interface NativeCapability<T> {
/**
* Runs one native call, or answers with `onUnavailable` when it cannot.
*
* The fallback is a function, never a bare value, so every call site has to
* say what "this device can't do it" means — the omission that turns a
* missing plugin into a crash. It receives the rejection for the cases that
* want to report it.
*/
call<R>(invoke: (plugin: T) => Promise<R>, onUnavailable: (error: unknown) => R): Promise<R>
/** Whether a native implementation could exist here at all. No native call. */
isSupportedPlatform(): boolean
}

/**
* Declares an app-local plugin and the platforms whose binaries implement it.
*
* `platforms` is about where the native code was WRITTEN, not where it happens
* to be installed: an iOS-only plugin declares `['ios']`, and an older iOS
* binary that predates it still falls back through `call()`.
*/
export function nativeCapability<T extends object>(
name: string,
{ platforms }: { platforms: NativePlatform[] }
): NativeCapability<T> {
const plugin = registerPlugin<T>(name)

const isSupportedPlatform = () =>
Comment thread
innolope-dev marked this conversation as resolved.
(platforms.includes('ios') && isIOSNative()) || (platforms.includes('android') && isAndroidNative())

return {
isSupportedPlatform,
async call(invoke, onUnavailable) {
if (!isSupportedPlatform()) return onUnavailable(new Error(`${name} is not available on this platform`))
try {
return await invoke(plugin)
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
} catch (error) {
// Every rejection is the same answer to the caller: a missing
// plugin, an unimplemented method on this platform, and a
// genuine native error are indistinguishable here and all mean
// "you don't get this". Callers that need the detail read it
// off the error they are handed.
return onUnavailable(error)
}
},
}
}
Loading
Loading