-
Notifications
You must be signed in to change notification settings - Fork 14
feat(native): one door to app-local plugins, with the fallback made mandatory #2978
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
bde2960
feat(native): one door to app-local plugins, with the fallback made m…
innolope-dev b2f286a
fix(native): take a method name, not a callback holding the plugin
innolope-dev b4474d8
test(native): make the proxy-invariant assertion compile-only
innolope-dev 0ec9781
fix(native): close the lint bypass, require a live bridge, fix the me…
innolope-dev f4c259d
fix(lint): narrow the import-rule overrides instead of switching them…
innolope-dev 1d184ca
fix(lint): ban the registerPlugin CALL, not just the named import
innolope-dev 8e5462b
fix(lint): stop the DS 10 override lifting the tailwind-merge ban too
innolope-dev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 = () => | ||
|
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) | ||
|
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) | ||
| } | ||
| }, | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.