@webext-core/messaging 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Aaron
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # `@webext-core/messaging`
2
+
3
+ A light weight, type-safe wrapper around the `Browser.runtime.sendMessage` APIs.
4
+
5
+ Based loosely off [`webext-bridge`](https://github.com/zikaari/webext-bridge). This does nothing other than provide types to the messaging APIs. `webext-bridge` provides things like queuing and caching, **this does not**.
6
+
7
+ ## Usage
8
+
9
+ In your project, create a file that calls `defineExtensionMessaging`, and exports the two functions it returns.
10
+
11
+ <!-- prettier-ignore -->
12
+ ```ts
13
+ // messaging.ts
14
+ import { defineExtensionMessaging, ProtocolWithReturn } from '@webext-core/messaging';
15
+
16
+ // This defines the data and return types used for each message
17
+ interface ProtocolMap {
18
+ message1: undefined; // No data and no return type
19
+ message2: string; // Only data
20
+ message3: ProtocolWithReturn<undefined, boolean>; // Only a return type
21
+ message4: ProtocolWithReturn<string, boolean>; // Data and return type
22
+ }
23
+
24
+ export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>();
25
+ ```
26
+
27
+ Then import those functions throughout the rest of the extension.
28
+
29
+ ```ts
30
+ // src/background.ts
31
+ import { onMessage } from './messaging';
32
+
33
+ onMessage('message4', message => {
34
+ console.log(message);
35
+ return !!message.data;
36
+ });
37
+ ```
38
+
39
+ ```ts
40
+ // src/popup.ts
41
+ import { sendMessage } from './messaging';
42
+
43
+ sendMessage('message4', 'data').then(console.log);
44
+ ```
package/lib/index.cjs ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var __async = (__this, __arguments, generator) => {
26
+ return new Promise((resolve, reject) => {
27
+ var fulfilled = (value) => {
28
+ try {
29
+ step(generator.next(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var rejected = (value) => {
35
+ try {
36
+ step(generator.throw(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
42
+ step((generator = generator.apply(__this, __arguments)).next());
43
+ });
44
+ };
45
+
46
+ // src/index.ts
47
+ var src_exports = {};
48
+ __export(src_exports, {
49
+ defineExtensionMessaging: () => defineExtensionMessaging
50
+ });
51
+ module.exports = __toCommonJS(src_exports);
52
+ var import_webextension_polyfill = __toESM(require("webextension-polyfill"), 1);
53
+ function defineExtensionMessaging(config) {
54
+ let rootListener;
55
+ let keyListeners = {};
56
+ let idSeq = Math.floor(Math.random() * 1e4);
57
+ function getNextId() {
58
+ return idSeq + 1;
59
+ }
60
+ function onMessage(key, onReceived) {
61
+ var _a, _b, _c;
62
+ if (rootListener == null) {
63
+ (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(
64
+ `[messaging] ${key} initialized message listener for this context`
65
+ );
66
+ rootListener = (message, sender) => __async(this, null, function* () {
67
+ var _a2, _b2, _c2, _d, _e;
68
+ if (typeof message.key != "string" || typeof message.timestamp !== "number") {
69
+ const err = Error(
70
+ `[messaging] Unknown message format, must include the 'key' & 'timestamp' fields, received: ${JSON.stringify(
71
+ message
72
+ )}`
73
+ );
74
+ (_a2 = config == null ? void 0 : config.logger) == null ? void 0 : _a2.error(err);
75
+ throw err;
76
+ }
77
+ (_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
78
+ const entires = Object.entries(keyListeners);
79
+ for (const [key2, listener] of entires) {
80
+ if (message.key !== key2)
81
+ continue;
82
+ (_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
83
+ try {
84
+ const res = yield listener({
85
+ data: message.data,
86
+ sender,
87
+ timestamp: message.timestamp
88
+ });
89
+ (_d = config == null ? void 0 : config.logger) == null ? void 0 : _d.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { res });
90
+ return { res };
91
+ } catch (err) {
92
+ let errMessage;
93
+ if (err instanceof Error)
94
+ errMessage = err.message;
95
+ else
96
+ errMessage = String(err);
97
+ (_e = config == null ? void 0 : config.logger) == null ? void 0 : _e.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { err });
98
+ return { err: errMessage };
99
+ }
100
+ }
101
+ yield new Promise(() => {
102
+ });
103
+ });
104
+ import_webextension_polyfill.default.runtime.onMessage.addListener(rootListener);
105
+ }
106
+ if (keyListeners[key] != null) {
107
+ const err = Error(
108
+ `[messaging] In this JS context, only one listener can be setup for ${key}`
109
+ );
110
+ (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.error(err);
111
+ throw err;
112
+ }
113
+ keyListeners[key] = onReceived;
114
+ (_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${key}`);
115
+ }
116
+ function sendMessage(key, data, tabId) {
117
+ return __async(this, null, function* () {
118
+ var _a, _b;
119
+ const message = { id: getNextId(), key, data, timestamp: Date.now() };
120
+ (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(`[messaging] sendMessage {id=${message.id}} \u2500\u1405`, message);
121
+ let response;
122
+ if (tabId == null)
123
+ response = yield import_webextension_polyfill.default.runtime.sendMessage(message);
124
+ else
125
+ response = yield import_webextension_polyfill.default.tabs.sendMessage(tabId, message);
126
+ const { res, err } = response != null ? response : { err: "No response" };
127
+ (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.debug(`[messaging] sendMessage {id=${message.id}} \u140A\u2500`, { res, err });
128
+ if (err != null)
129
+ throw Error(err);
130
+ return res;
131
+ });
132
+ }
133
+ return { onMessage, sendMessage };
134
+ }
135
+ // Annotate the CommonJS export names for ESM import in node:
136
+ 0 && (module.exports = {
137
+ defineExtensionMessaging
138
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { Runtime } from 'webextension-polyfill';
2
+
3
+ interface Config {
4
+ logger?: {
5
+ debug(...args: any[]): void;
6
+ log(...args: any[]): void;
7
+ warn(...args: any[]): void;
8
+ error(...args: any[]): void;
9
+ };
10
+ }
11
+ declare type ProtocolWithReturn<TData, TResponse> = {
12
+ BtVgCTPYZu: TData;
13
+ RrhVseLgZW: TResponse;
14
+ };
15
+ declare type GetData<T> = T extends ProtocolWithReturn<any, any> ? T['BtVgCTPYZu'] : T;
16
+ declare type GetResponse<T> = T extends ProtocolWithReturn<any, any> ? T['RrhVseLgZW'] : void;
17
+ interface Message<TProtocolMap, TKey extends keyof TProtocolMap> {
18
+ id: number;
19
+ data: GetData<TProtocolMap[TKey]>;
20
+ sender: Runtime.MessageSender;
21
+ timestamp: number;
22
+ }
23
+ declare type MaybePromise<T> = Promise<T> | T;
24
+ declare type OnMessageReceived<TProtocolMap, TKey extends keyof TProtocolMap> = (message: Message<TProtocolMap, TKey>) => MaybePromise<GetResponse<TProtocolMap[TKey]>>;
25
+ declare function defineExtensionMessaging<TProtocolMap>(config?: Config): {
26
+ onMessage: <TKey extends keyof TProtocolMap>(key: TKey, onReceived: OnMessageReceived<TProtocolMap, TKey>) => void;
27
+ sendMessage: <TKey_1 extends keyof TProtocolMap>(key: TKey_1, data: GetData<TProtocolMap[TKey_1]>, tabId?: number) => Promise<GetResponse<TProtocolMap[TKey_1]>>;
28
+ };
29
+
30
+ export { ProtocolWithReturn, defineExtensionMessaging };
package/lib/index.js ADDED
@@ -0,0 +1,108 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+
22
+ // src/index.ts
23
+ import Browser from "webextension-polyfill";
24
+ function defineExtensionMessaging(config) {
25
+ let rootListener;
26
+ let keyListeners = {};
27
+ let idSeq = Math.floor(Math.random() * 1e4);
28
+ function getNextId() {
29
+ return idSeq + 1;
30
+ }
31
+ function onMessage(key, onReceived) {
32
+ var _a, _b, _c;
33
+ if (rootListener == null) {
34
+ (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(
35
+ `[messaging] ${key} initialized message listener for this context`
36
+ );
37
+ rootListener = (message, sender) => __async(this, null, function* () {
38
+ var _a2, _b2, _c2, _d, _e;
39
+ if (typeof message.key != "string" || typeof message.timestamp !== "number") {
40
+ const err = Error(
41
+ `[messaging] Unknown message format, must include the 'key' & 'timestamp' fields, received: ${JSON.stringify(
42
+ message
43
+ )}`
44
+ );
45
+ (_a2 = config == null ? void 0 : config.logger) == null ? void 0 : _a2.error(err);
46
+ throw err;
47
+ }
48
+ (_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
49
+ const entires = Object.entries(keyListeners);
50
+ for (const [key2, listener] of entires) {
51
+ if (message.key !== key2)
52
+ continue;
53
+ (_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
54
+ try {
55
+ const res = yield listener({
56
+ data: message.data,
57
+ sender,
58
+ timestamp: message.timestamp
59
+ });
60
+ (_d = config == null ? void 0 : config.logger) == null ? void 0 : _d.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { res });
61
+ return { res };
62
+ } catch (err) {
63
+ let errMessage;
64
+ if (err instanceof Error)
65
+ errMessage = err.message;
66
+ else
67
+ errMessage = String(err);
68
+ (_e = config == null ? void 0 : config.logger) == null ? void 0 : _e.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { err });
69
+ return { err: errMessage };
70
+ }
71
+ }
72
+ yield new Promise(() => {
73
+ });
74
+ });
75
+ Browser.runtime.onMessage.addListener(rootListener);
76
+ }
77
+ if (keyListeners[key] != null) {
78
+ const err = Error(
79
+ `[messaging] In this JS context, only one listener can be setup for ${key}`
80
+ );
81
+ (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.error(err);
82
+ throw err;
83
+ }
84
+ keyListeners[key] = onReceived;
85
+ (_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${key}`);
86
+ }
87
+ function sendMessage(key, data, tabId) {
88
+ return __async(this, null, function* () {
89
+ var _a, _b;
90
+ const message = { id: getNextId(), key, data, timestamp: Date.now() };
91
+ (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(`[messaging] sendMessage {id=${message.id}} \u2500\u1405`, message);
92
+ let response;
93
+ if (tabId == null)
94
+ response = yield Browser.runtime.sendMessage(message);
95
+ else
96
+ response = yield Browser.tabs.sendMessage(tabId, message);
97
+ const { res, err } = response != null ? response : { err: "No response" };
98
+ (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.debug(`[messaging] sendMessage {id=${message.id}} \u140A\u2500`, { res, err });
99
+ if (err != null)
100
+ throw Error(err);
101
+ return res;
102
+ });
103
+ }
104
+ return { onMessage, sendMessage };
105
+ }
106
+ export {
107
+ defineExtensionMessaging
108
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@webext-core/messaging",
3
+ "version": "1.0.0",
4
+ "description": "Light weight, type-safe wrapper around the extension messaging APIs",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "files": [
11
+ "lib"
12
+ ],
13
+ "main": "lib/index.cjs",
14
+ "module": "lib/index.js",
15
+ "types": "lib/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./lib/index.js",
19
+ "require": "./lib/index.cjs"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "webextension-polyfill": "^0.10.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/webextension-polyfill": "^0.9.1",
27
+ "@vitest/coverage-c8": "^0.24.5",
28
+ "tsup": "^6.4.0",
29
+ "typescript": "^4.8.4",
30
+ "vitest": "^0.24.5",
31
+ "@webext-core/fake-browser": "1.0.0",
32
+ "tsconfig": "0.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsup src/index.ts --clean --out-dir lib --format esm,cjs --dts",
36
+ "test": "vitest -r src",
37
+ "test:coverage": "vitest run -r src --coverage",
38
+ "compile": "tsc --noEmit"
39
+ }
40
+ }