-
-
Notifications
You must be signed in to change notification settings - Fork 27
Add browser runtime post message stream #69
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 all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ab9e9a2
Add Chrome runtime post message stream
Mrtenz 93d8541
Fix tests
Mrtenz 2a5e352
Export stream
Mrtenz 3a55477
Fix coverage
Mrtenz 7fc0945
Remove callback
Mrtenz d3dbeeb
Make the stream compatible with more browsers
Mrtenz cda33e2
Remove webextension-polyfill
Mrtenz e40128c
Fix some PR comments
Mrtenz 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
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
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,135 @@ | ||
| import { BrowserRuntimePostMessageStream } from './BrowserRuntimePostMessageStream'; | ||
|
|
||
| describe('BrowserRuntimePostMessageStream', () => { | ||
| beforeEach(() => { | ||
| const addListener = jest.fn(); | ||
| const sendMessage = jest.fn().mockImplementation((message) => { | ||
| // Propagate message to all listeners. | ||
| addListener.mock.calls.forEach(([listener]) => { | ||
| setTimeout(() => listener(message)); | ||
| }); | ||
| }); | ||
|
|
||
| Object.assign(global, { | ||
| chrome: undefined, | ||
| browser: { | ||
| runtime: { | ||
| sendMessage, | ||
| onMessage: { | ||
| addListener, | ||
| removeListener: jest.fn(), | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it('throws if browser.runtime.sendMessage is not a function', () => { | ||
| // @ts-expect-error - Invalid function type. | ||
| browser.runtime.sendMessage = undefined; | ||
|
|
||
| expect( | ||
| () => new BrowserRuntimePostMessageStream({ name: 'foo', target: 'bar' }), | ||
| ).toThrow( | ||
| 'browser.runtime.sendMessage is not a function. This class should only be instantiated in a web extension.', | ||
| ); | ||
|
|
||
| // @ts-expect-error - Invalid function type. | ||
| browser.runtime.sendMessage = 'foo'; | ||
|
|
||
| expect( | ||
| () => new BrowserRuntimePostMessageStream({ name: 'foo', target: 'bar' }), | ||
| ).toThrow( | ||
| 'browser.runtime.sendMessage is not a function. This class should only be instantiated in a web extension.', | ||
| ); | ||
|
|
||
| // @ts-expect-error - Invalid function type. | ||
| browser.runtime = undefined; | ||
|
|
||
| expect( | ||
| () => new BrowserRuntimePostMessageStream({ name: 'foo', target: 'bar' }), | ||
| ).toThrow( | ||
| 'browser.runtime.sendMessage is not a function. This class should only be instantiated in a web extension.', | ||
| ); | ||
|
|
||
| // @ts-expect-error - Invalid function type. | ||
| browser = undefined; | ||
|
|
||
| expect( | ||
| () => new BrowserRuntimePostMessageStream({ name: 'foo', target: 'bar' }), | ||
| ).toThrow( | ||
| 'browser.runtime.sendMessage is not a function. This class should only be instantiated in a web extension.', | ||
| ); | ||
| }); | ||
|
|
||
| it('supports chrome.runtime', () => { | ||
| const addListener = jest.fn(); | ||
| const sendMessage = jest.fn().mockImplementation((message) => { | ||
| // Propagate message to all listeners. | ||
| addListener.mock.calls.forEach(([listener]) => { | ||
| setTimeout(() => listener(message)); | ||
| }); | ||
| }); | ||
|
|
||
| Object.assign(global, { | ||
| browser: undefined, | ||
| chrome: { | ||
| runtime: { | ||
| sendMessage, | ||
| onMessage: { | ||
| addListener, | ||
| removeListener: jest.fn(), | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| expect( | ||
| () => new BrowserRuntimePostMessageStream({ name: 'foo', target: 'bar' }), | ||
| ).not.toThrow(); | ||
| }); | ||
|
|
||
| it('can communicate between streams and be destroyed', async () => { | ||
| // Initialize sender stream | ||
| const streamA = new BrowserRuntimePostMessageStream({ | ||
| name: 'a', | ||
| target: 'b', | ||
| }); | ||
|
|
||
| // Initialize receiver stream. Multiplies incoming values by 5 and | ||
| // returns them. | ||
| const streamB = new BrowserRuntimePostMessageStream({ | ||
| name: 'b', | ||
| target: 'a', | ||
| }); | ||
|
|
||
| streamB.on('data', (value) => streamB.write(value * 5)); | ||
|
|
||
| // Get a deferred Promise for the result | ||
| const responsePromise = new Promise((resolve) => { | ||
| streamA.once('data', (num) => { | ||
| resolve(Number(num)); | ||
| }); | ||
| }); | ||
|
|
||
| // Write to stream A, triggering a response from stream B | ||
| streamA.write(111); | ||
|
|
||
| expect(await responsePromise).toStrictEqual(555); | ||
|
|
||
| const throwingListener = (data: any) => { | ||
| throw new Error(`Unexpected data on stream: ${data}`); | ||
| }; | ||
|
|
||
| streamA.once('data', throwingListener); | ||
| streamB.once('data', throwingListener); | ||
|
|
||
| browser.runtime.sendMessage(new Event('message')); | ||
|
|
||
| // Destroy streams and confirm that they were destroyed | ||
| streamA.destroy(); | ||
| streamB.destroy(); | ||
| expect(streamA.destroyed).toStrictEqual(true); | ||
| expect(streamB.destroyed).toStrictEqual(true); | ||
| }); | ||
| }); |
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,83 @@ | ||
| import { | ||
| BasePostMessageStream, | ||
| PostMessageEvent, | ||
| } from '../BasePostMessageStream'; | ||
| import { isValidStreamMessage } from '../utils'; | ||
|
|
||
| export interface BrowserRuntimePostMessageStreamArgs { | ||
| name: string; | ||
| target: string; | ||
| } | ||
|
|
||
| /** | ||
| * A {@link browser.runtime} stream. | ||
| */ | ||
| export class BrowserRuntimePostMessageStream extends BasePostMessageStream { | ||
| #name: string; | ||
|
|
||
| #target: string; | ||
|
|
||
| /** | ||
| * Creates a stream for communicating with other streams across the extension | ||
| * runtime. | ||
| * | ||
| * @param args - Options bag. | ||
| * @param args.name - The name of the stream. Used to differentiate between | ||
| * multiple streams sharing the same runtime. | ||
| * @param args.target - The name of the stream to exchange messages with. | ||
| */ | ||
| constructor({ name, target }: BrowserRuntimePostMessageStreamArgs) { | ||
| super(); | ||
|
|
||
| this.#name = name; | ||
| this.#target = target; | ||
| this._onMessage = this._onMessage.bind(this); | ||
|
|
||
| this._getRuntime().onMessage.addListener(this._onMessage); | ||
|
|
||
| this._handshake(); | ||
| } | ||
|
|
||
| protected _postMessage(data: unknown): void { | ||
| // This returns a Promise, which resolves if the receiver responds to the | ||
| // message. Rather than responding to specific messages, we send new | ||
| // messages in response to incoming messages, so we don't care about the | ||
| // Promise. | ||
| this._getRuntime().sendMessage({ | ||
| target: this.#target, | ||
| data, | ||
| }); | ||
| } | ||
|
|
||
| private _onMessage(message: PostMessageEvent): void { | ||
| if (!isValidStreamMessage(message) || message.target !== this.#name) { | ||
| return; | ||
| } | ||
|
|
||
| this._onData(message.data); | ||
| } | ||
|
|
||
| private _getRuntime(): typeof browser.runtime { | ||
| if ( | ||
| 'chrome' in globalThis && | ||
| typeof chrome?.runtime?.sendMessage === 'function' | ||
| ) { | ||
| return chrome.runtime; | ||
| } | ||
|
|
||
| if ( | ||
| 'browser' in globalThis && | ||
| typeof browser?.runtime?.sendMessage === 'function' | ||
| ) { | ||
| return browser.runtime; | ||
| } | ||
|
|
||
| throw new Error( | ||
| 'browser.runtime.sendMessage is not a function. This class should only be instantiated in a web extension.', | ||
| ); | ||
| } | ||
|
|
||
| _destroy(): void { | ||
| this._getRuntime().onMessage.removeListener(this._onMessage); | ||
| } | ||
| } |
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,9 @@ | ||
| // eslint-disable-next-line import/unambiguous | ||
| declare namespace browser.runtime { | ||
| export function sendMessage<Response>(message: any): Promise<Response>; | ||
|
|
||
| export const onMessage: { | ||
| addListener(listener: (message: any) => void): void; | ||
| removeListener(listener: (message: any) => void): void; | ||
| }; | ||
| } |
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
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.