@webext-core/proxy-service 1.1.1 → 1.2.1

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/README.md CHANGED
@@ -4,4 +4,4 @@ A type-safe wrapper around the web extension messaging APIs that lets you call a
4
4
 
5
5
  ## Get Started
6
6
 
7
- See [documentation](https://webext-core.aklinker1.io/proxy-service) to get started!
7
+ See [documentation](https://webext-core.aklinker1.io/guide/proxy-service/) to get started!
package/lib/index.cjs CHANGED
@@ -18,6 +18,10 @@ var __copyProps = (to, from, except, desc) => {
18
18
  return to;
19
19
  };
20
20
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
25
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
26
  mod
23
27
  ));
@@ -46,7 +50,8 @@ var __async = (__this, __arguments, generator) => {
46
50
  // src/index.ts
47
51
  var src_exports = {};
48
52
  __export(src_exports, {
49
- defineProxyService: () => defineProxyService
53
+ defineProxyService: () => defineProxyService,
54
+ flattenPromise: () => flattenPromise
50
55
  });
51
56
  module.exports = __toCommonJS(src_exports);
52
57
 
@@ -65,6 +70,7 @@ function canAccessExtensionApi() {
65
70
  return !!((_a = import_webextension_polyfill.default.runtime) == null ? void 0 : _a.id);
66
71
  }
67
72
  var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
73
+ // Firefox
68
74
  "/_generated_background_page.html"
69
75
  ];
70
76
  function isBackgroundPage() {
@@ -85,6 +91,7 @@ function defineProxyService(name, init, config) {
85
91
  const wrapped = () => {
86
92
  };
87
93
  const proxy = new Proxy(wrapped, {
94
+ // Executed when the object is called as a function
88
95
  apply(_target, _thisArg, args) {
89
96
  return __async(this, null, function* () {
90
97
  const res = yield sendMessage(messageKey, {
@@ -94,6 +101,7 @@ function defineProxyService(name, init, config) {
94
101
  return res;
95
102
  });
96
103
  },
104
+ // Executed when accessing a property on an object
97
105
  get(target, propertyName, receiver) {
98
106
  if (propertyName === "__proxy" || typeof propertyName === "symbol") {
99
107
  return Reflect.get(target, propertyName, receiver);
@@ -126,7 +134,40 @@ function defineProxyService(name, init, config) {
126
134
  }
127
135
  ];
128
136
  }
137
+
138
+ // src/flattenPromise.ts
139
+ var import_get_value2 = __toESM(require("get-value"), 1);
140
+ function flattenPromise(promise) {
141
+ function createProxy(location2) {
142
+ const wrapped = () => {
143
+ };
144
+ const proxy = new Proxy(wrapped, {
145
+ apply(_target, _thisArg, args) {
146
+ return __async(this, null, function* () {
147
+ const t = yield promise;
148
+ const thisArg = (location2 == null ? void 0 : location2.parentPath) ? (0, import_get_value2.default)(t, location2.parentPath) : t;
149
+ const fn = location2 ? (0, import_get_value2.default)(t, location2.propertyPath) : t;
150
+ return fn.apply(thisArg, args);
151
+ });
152
+ },
153
+ // Executed when accessing a property on an object
154
+ get(target, propertyName, receiver) {
155
+ if (propertyName === "__proxy" || typeof propertyName === "symbol") {
156
+ return Reflect.get(target, propertyName, receiver);
157
+ }
158
+ return createProxy({
159
+ propertyPath: location2 == null ? propertyName : `${location2.propertyPath}.${propertyName}`,
160
+ parentPath: location2 == null ? void 0 : location2.propertyPath
161
+ });
162
+ }
163
+ });
164
+ proxy.__proxy = true;
165
+ return proxy;
166
+ }
167
+ return createProxy();
168
+ }
129
169
  // Annotate the CommonJS export names for ESM import in node:
130
170
  0 && (module.exports = {
131
- defineProxyService
171
+ defineProxyService,
172
+ flattenPromise
132
173
  });
package/lib/index.d.ts CHANGED
@@ -1,21 +1,63 @@
1
1
  import { ExtensionMessagingConfig } from '@webext-core/messaging';
2
2
 
3
- declare type Proimsify<T> = T extends Promise<any> ? T : Promise<T>;
4
- declare type Service = ((...args: any[]) => Promise<any>) | {
3
+ type Proimsify<T> = T extends Promise<any> ? T : Promise<T>;
4
+ type Service = ((...args: any[]) => Promise<any>) | {
5
5
  [key: string]: any | Service;
6
6
  };
7
7
  /**
8
- * Make all functions at all nested levels of an object async
8
+ * A type that ensures a service has only async methods.
9
+ * - ***If all methods are async***, it returns the original type.
10
+ * - ***If the service has non-async methods***, it returns a `DeepAsync` of the service.
11
+ */
12
+ type ProxyService<TService> = TService extends DeepAsync<TService> ? TService : DeepAsync<TService>;
13
+ /**
14
+ * A recursive type that deeply converts all methods in `TService` to be async.
15
+ */
16
+ type DeepAsync<TService> = TService extends (...args: any) => any ? ToAsyncFunction<TService> : TService extends {
17
+ [key: string]: any;
18
+ } ? {
19
+ [fn in keyof TService]: DeepAsync<TService[fn]>;
20
+ } : never;
21
+ type ToAsyncFunction<T extends (...args: any) => any> = (...args: Parameters<T>) => Proimsify<ReturnType<T>>;
22
+ /**
23
+ * Configure a proxy service's behavior. It uses `@webext-core/messaging` internally, so any
24
+ * config from `ExtensionMessagingConfig` can be passed as well.
9
25
  */
10
- declare type DeepAsync<TService> = TService extends (...args: any) => any ? ToAsyncFunction<TService> : {
11
- [fn in keyof TService]: TService[fn] extends (...args: any[]) => any ? ToAsyncFunction<TService[fn]> : TService[fn] extends {
12
- [key: string]: any;
13
- } ? DeepAsync<TService[fn]> : never;
14
- };
15
- declare type ToAsyncFunction<T extends (...args: any) => any> = (...args: Parameters<T>) => Proimsify<ReturnType<T>>;
16
26
  interface ProxyServiceConfig extends ExtensionMessagingConfig {
17
27
  }
18
28
 
19
- declare function defineProxyService<TService extends Service, TArgs extends any[]>(name: string, init: (...args: TArgs) => TService, config?: ProxyServiceConfig): [registerService: (...args: TArgs) => TService, getService: () => DeepAsync<TService>];
29
+ /**
30
+ * Utility for creating a service whose functions are executed in the background script regardless
31
+ * of the JS context the they are called from.
32
+ *
33
+ * @param name A unique name for the service. Used to identify which service is being executed.
34
+ * @param init A function that returns your real service implementation. If args are listed,
35
+ * `registerService` will require the same set of arguments.
36
+ * @param config
37
+ * @returns
38
+ * - `registerService`: Used to register your service in the background
39
+ * - `getService`: Used to get an instance of the service anywhere in the extension.
40
+ */
41
+ declare function defineProxyService<TService extends Service, TArgs extends any[]>(name: string, init: (...args: TArgs) => TService, config?: ProxyServiceConfig): [registerService: (...args: TArgs) => TService, getService: () => ProxyService<TService>];
42
+
43
+ /**
44
+ * Given a promise of a variable, return a proxy to that awaits the promise internally so you don't
45
+ * have to call `await` twice.
46
+ *
47
+ * > This can be used to simplify handling `Promise<Dependency>` passed in your services.
48
+ *
49
+ * @example
50
+ * function createService(dependencyPromise: Promise<SomeDependency>) {
51
+ * const dependency = flattenPromise(dependencyPromise);
52
+ *
53
+ * return {
54
+ * doSomething() {
55
+ * await dependency.someAsyncWork();
56
+ * // Instead of `await (await dependencyPromise).someAsyncWork();`
57
+ * }
58
+ * }
59
+ * }
60
+ */
61
+ declare function flattenPromise<T>(promise: Promise<T>): DeepAsync<T>;
20
62
 
21
- export { ProxyServiceConfig, defineProxyService };
63
+ export { DeepAsync, ProxyService, ProxyServiceConfig, defineProxyService, flattenPromise };
@@ -6,6 +6,7 @@ var webExtCoreProxyService = (() => {
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
10
  var __commonJS = (cb, mod) => function __require() {
10
11
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
12
  };
@@ -22,10 +23,18 @@ var webExtCoreProxyService = (() => {
22
23
  return to;
23
24
  };
24
25
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
30
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
31
  mod
27
32
  ));
28
33
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
+ var __publicField = (obj, key, value) => {
35
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
36
+ return value;
37
+ };
29
38
  var __async = (__this, __arguments, generator) => {
30
39
  return new Promise((resolve, reject) => {
31
40
  var fulfilled = (value) => {
@@ -47,9 +56,9 @@ var webExtCoreProxyService = (() => {
47
56
  });
48
57
  };
49
58
 
50
- // ../../node_modules/.pnpm/webextension-polyfill@0.10.0/node_modules/webextension-polyfill/dist/browser-polyfill.js
59
+ // ../../node_modules/webextension-polyfill/dist/browser-polyfill.js
51
60
  var require_browser_polyfill = __commonJS({
52
- "../../node_modules/.pnpm/webextension-polyfill@0.10.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) {
61
+ "../../node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) {
53
62
  (function(global, factory) {
54
63
  if (typeof define === "function" && define.amd) {
55
64
  define("webextension-polyfill", ["module"], factory);
@@ -1042,9 +1051,9 @@ var webExtCoreProxyService = (() => {
1042
1051
  }
1043
1052
  });
1044
1053
 
1045
- // ../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js
1054
+ // ../../node_modules/isobject/index.js
1046
1055
  var require_isobject = __commonJS({
1047
- "../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(exports, module) {
1056
+ "../../node_modules/isobject/index.js"(exports, module) {
1048
1057
  "use strict";
1049
1058
  module.exports = function isObject(val) {
1050
1059
  return val != null && typeof val === "object" && Array.isArray(val) === false;
@@ -1052,9 +1061,9 @@ var webExtCoreProxyService = (() => {
1052
1061
  }
1053
1062
  });
1054
1063
 
1055
- // ../../node_modules/.pnpm/get-value@3.0.1/node_modules/get-value/index.js
1064
+ // ../../node_modules/get-value/index.js
1056
1065
  var require_get_value = __commonJS({
1057
- "../../node_modules/.pnpm/get-value@3.0.1/node_modules/get-value/index.js"(exports, module) {
1066
+ "../../node_modules/get-value/index.js"(exports, module) {
1058
1067
  var isObject = require_isobject();
1059
1068
  module.exports = function(target, path, options) {
1060
1069
  if (!isObject(options)) {
@@ -1143,7 +1152,8 @@ var webExtCoreProxyService = (() => {
1143
1152
  // src/index.ts
1144
1153
  var src_exports = {};
1145
1154
  __export(src_exports, {
1146
- defineProxyService: () => defineProxyService
1155
+ defineProxyService: () => defineProxyService,
1156
+ flattenPromise: () => flattenPromise
1147
1157
  });
1148
1158
 
1149
1159
  // src/isBackground.ts
@@ -1161,6 +1171,7 @@ var webExtCoreProxyService = (() => {
1161
1171
  return !!((_a = import_webextension_polyfill.default.runtime) == null ? void 0 : _a.id);
1162
1172
  }
1163
1173
  var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
1174
+ // Firefox
1164
1175
  "/_generated_background_page.html"
1165
1176
  ];
1166
1177
  function isBackgroundPage() {
@@ -1170,8 +1181,214 @@ var webExtCoreProxyService = (() => {
1170
1181
  return typeof window === "undefined";
1171
1182
  }
1172
1183
 
1173
- // ../messaging/lib/index.js
1174
- var import_webextension_polyfill2 = __toESM(require_browser_polyfill(), 1);
1184
+ // ../../node_modules/serialize-error/error-constructors.js
1185
+ var list = [
1186
+ // Native ES errors https://262.ecma-international.org/12.0/#sec-well-known-intrinsic-objects
1187
+ EvalError,
1188
+ RangeError,
1189
+ ReferenceError,
1190
+ SyntaxError,
1191
+ TypeError,
1192
+ URIError,
1193
+ // Built-in errors
1194
+ globalThis.DOMException,
1195
+ // Node-specific errors
1196
+ // https://nodejs.org/api/errors.html
1197
+ globalThis.AssertionError,
1198
+ globalThis.SystemError
1199
+ ].filter(Boolean).map(
1200
+ (constructor) => [constructor.name, constructor]
1201
+ );
1202
+ var errorConstructors = new Map(list);
1203
+ var error_constructors_default = errorConstructors;
1204
+
1205
+ // ../../node_modules/serialize-error/index.js
1206
+ var NonError = class extends Error {
1207
+ constructor(message) {
1208
+ super(NonError._prepareSuperMessage(message));
1209
+ __publicField(this, "name", "NonError");
1210
+ }
1211
+ static _prepareSuperMessage(message) {
1212
+ try {
1213
+ return JSON.stringify(message);
1214
+ } catch (e) {
1215
+ return String(message);
1216
+ }
1217
+ }
1218
+ };
1219
+ var commonProperties = [
1220
+ {
1221
+ property: "name",
1222
+ enumerable: false
1223
+ },
1224
+ {
1225
+ property: "message",
1226
+ enumerable: false
1227
+ },
1228
+ {
1229
+ property: "stack",
1230
+ enumerable: false
1231
+ },
1232
+ {
1233
+ property: "code",
1234
+ enumerable: true
1235
+ },
1236
+ {
1237
+ property: "cause",
1238
+ enumerable: false
1239
+ }
1240
+ ];
1241
+ var toJsonWasCalled = /* @__PURE__ */ new WeakSet();
1242
+ var toJSON = (from) => {
1243
+ toJsonWasCalled.add(from);
1244
+ const json = from.toJSON();
1245
+ toJsonWasCalled.delete(from);
1246
+ return json;
1247
+ };
1248
+ var getErrorConstructor = (name) => {
1249
+ var _a;
1250
+ return (_a = error_constructors_default.get(name)) != null ? _a : Error;
1251
+ };
1252
+ var destroyCircular = ({
1253
+ from,
1254
+ seen,
1255
+ to,
1256
+ forceEnumerable,
1257
+ maxDepth,
1258
+ depth,
1259
+ useToJSON,
1260
+ serialize
1261
+ }) => {
1262
+ if (!to) {
1263
+ if (Array.isArray(from)) {
1264
+ to = [];
1265
+ } else if (!serialize && isErrorLike(from)) {
1266
+ const Error2 = getErrorConstructor(from.name);
1267
+ to = new Error2();
1268
+ } else {
1269
+ to = {};
1270
+ }
1271
+ }
1272
+ seen.push(from);
1273
+ if (depth >= maxDepth) {
1274
+ return to;
1275
+ }
1276
+ if (useToJSON && typeof from.toJSON === "function" && !toJsonWasCalled.has(from)) {
1277
+ return toJSON(from);
1278
+ }
1279
+ const continueDestroyCircular = (value) => destroyCircular({
1280
+ from: value,
1281
+ seen: [...seen],
1282
+ forceEnumerable,
1283
+ maxDepth,
1284
+ depth,
1285
+ useToJSON,
1286
+ serialize
1287
+ });
1288
+ for (const [key, value] of Object.entries(from)) {
1289
+ if (value && value instanceof Uint8Array && value.constructor.name === "Buffer") {
1290
+ to[key] = "[object Buffer]";
1291
+ continue;
1292
+ }
1293
+ if (value !== null && typeof value === "object" && typeof value.pipe === "function") {
1294
+ to[key] = "[object Stream]";
1295
+ continue;
1296
+ }
1297
+ if (typeof value === "function") {
1298
+ continue;
1299
+ }
1300
+ if (!value || typeof value !== "object") {
1301
+ try {
1302
+ to[key] = value;
1303
+ } catch (e) {
1304
+ }
1305
+ continue;
1306
+ }
1307
+ if (!seen.includes(from[key])) {
1308
+ depth++;
1309
+ to[key] = continueDestroyCircular(from[key]);
1310
+ continue;
1311
+ }
1312
+ to[key] = "[Circular]";
1313
+ }
1314
+ for (const { property, enumerable } of commonProperties) {
1315
+ if (typeof from[property] !== "undefined" && from[property] !== null) {
1316
+ Object.defineProperty(to, property, {
1317
+ value: isErrorLike(from[property]) ? continueDestroyCircular(from[property]) : from[property],
1318
+ enumerable: forceEnumerable ? true : enumerable,
1319
+ configurable: true,
1320
+ writable: true
1321
+ });
1322
+ }
1323
+ }
1324
+ return to;
1325
+ };
1326
+ function serializeError(value, options = {}) {
1327
+ const {
1328
+ maxDepth = Number.POSITIVE_INFINITY,
1329
+ useToJSON = true
1330
+ } = options;
1331
+ if (typeof value === "object" && value !== null) {
1332
+ return destroyCircular({
1333
+ from: value,
1334
+ seen: [],
1335
+ forceEnumerable: true,
1336
+ maxDepth,
1337
+ depth: 0,
1338
+ useToJSON,
1339
+ serialize: true
1340
+ });
1341
+ }
1342
+ if (typeof value === "function") {
1343
+ return `[Function: ${value.name || "anonymous"}]`;
1344
+ }
1345
+ return value;
1346
+ }
1347
+ function deserializeError(value, options = {}) {
1348
+ const { maxDepth = Number.POSITIVE_INFINITY } = options;
1349
+ if (value instanceof Error) {
1350
+ return value;
1351
+ }
1352
+ if (isMinimumViableSerializedError(value)) {
1353
+ const Error2 = getErrorConstructor(value.name);
1354
+ return destroyCircular({
1355
+ from: value,
1356
+ seen: [],
1357
+ to: new Error2(),
1358
+ maxDepth,
1359
+ depth: 0,
1360
+ serialize: false
1361
+ });
1362
+ }
1363
+ return new NonError(value);
1364
+ }
1365
+ function isErrorLike(value) {
1366
+ return Boolean(value) && typeof value === "object" && "name" in value && "message" in value && "stack" in value;
1367
+ }
1368
+ function isMinimumViableSerializedError(value) {
1369
+ return Boolean(value) && typeof value === "object" && "message" in value && !Array.isArray(value);
1370
+ }
1371
+
1372
+ // ../messaging/lib/chunk-BQLFSFFZ.js
1373
+ var __defProp2 = Object.defineProperty;
1374
+ var __defProps = Object.defineProperties;
1375
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1376
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1377
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1378
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1379
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1380
+ var __spreadValues = (a, b) => {
1381
+ for (var prop in b || (b = {}))
1382
+ if (__hasOwnProp2.call(b, prop))
1383
+ __defNormalProp2(a, prop, b[prop]);
1384
+ if (__getOwnPropSymbols)
1385
+ for (var prop of __getOwnPropSymbols(b)) {
1386
+ if (__propIsEnum.call(b, prop))
1387
+ __defNormalProp2(a, prop, b[prop]);
1388
+ }
1389
+ return a;
1390
+ };
1391
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1175
1392
  var __async2 = (__this, __arguments, generator) => {
1176
1393
  return new Promise((resolve, reject) => {
1177
1394
  var fulfilled = (value) => {
@@ -1192,103 +1409,121 @@ var webExtCoreProxyService = (() => {
1192
1409
  step((generator = generator.apply(__this, __arguments)).next());
1193
1410
  });
1194
1411
  };
1195
- function defineExtensionMessaging(config) {
1196
- let rootListener;
1412
+ function defineGenericMessanging(config) {
1413
+ let removeRootListener;
1414
+ let perTypeListeners = {};
1197
1415
  function cleanupRootListener() {
1198
- if (Object.entries(keyListeners).length === 0) {
1199
- import_webextension_polyfill2.default.runtime.onMessage.removeListener(rootListener);
1200
- rootListener = void 0;
1416
+ if (Object.entries(perTypeListeners).length === 0) {
1417
+ removeRootListener == null ? void 0 : removeRootListener();
1418
+ removeRootListener = void 0;
1201
1419
  }
1202
1420
  }
1203
- let keyListeners = {};
1204
1421
  let idSeq = Math.floor(Math.random() * 1e4);
1205
1422
  function getNextId() {
1206
1423
  return idSeq++;
1207
1424
  }
1208
- function onMessage(type, onReceived) {
1209
- var _a, _b, _c;
1210
- if (rootListener == null) {
1211
- (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(
1212
- `[messaging] ${type} initialized message listener for this context`
1213
- );
1214
- rootListener = (message, sender) => {
1215
- var _a2, _b2, _c2;
1216
- if (typeof message.type != "string" || typeof message.timestamp !== "number") {
1217
- const err = Error(
1218
- `[messaging] Unknown message format, must include the 'type' & 'timestamp' fields, received: ${JSON.stringify(
1219
- message
1220
- )}`
1221
- );
1222
- (_a2 = config == null ? void 0 : config.logger) == null ? void 0 : _a2.error(err);
1223
- throw err;
1224
- }
1225
- (_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
1226
- const entries = Object.entries(keyListeners);
1227
- for (const [type2, listener] of entries) {
1228
- if (message.type !== type2)
1229
- continue;
1230
- (_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
1231
- const res = listener({
1232
- data: message.data,
1233
- sender,
1234
- timestamp: message.timestamp
1235
- });
1425
+ return {
1426
+ sendMessage(type, data, ...args) {
1427
+ return __async2(this, null, function* () {
1428
+ var _a2, _b, _c, _d;
1429
+ const _message = {
1430
+ id: getNextId(),
1431
+ type,
1432
+ data,
1433
+ timestamp: Date.now()
1434
+ };
1435
+ const message = (_b = yield (_a2 = config.verifyMessageData) == null ? void 0 : _a2.call(config, _message)) != null ? _b : _message;
1436
+ (_c = config.logger) == null ? void 0 : _c.debug(`[messaging] sendMessage {id=${message.id}} \u2500\u1405`, message, ...args);
1437
+ const response = yield config.sendMessage(message, ...args);
1438
+ const { res, err } = response != null ? response : { err: new Error("No response") };
1439
+ (_d = config.logger) == null ? void 0 : _d.debug(`[messaging] sendMessage {id=${message.id}} \u140A\u2500`, { res, err });
1440
+ if (err != null)
1441
+ throw deserializeError(err);
1442
+ return res;
1443
+ });
1444
+ },
1445
+ onMessage(type, onReceived) {
1446
+ var _a2, _b, _c;
1447
+ if (removeRootListener == null) {
1448
+ (_a2 = config.logger) == null ? void 0 : _a2.debug(
1449
+ `[messaging] "${type}" initialized the message listener for this context`
1450
+ );
1451
+ removeRootListener = config.addRootListener((message) => {
1452
+ var _a3, _b2;
1453
+ if (typeof message.type != "string" || typeof message.timestamp !== "number") {
1454
+ if (config.breakError) {
1455
+ return;
1456
+ }
1457
+ const err = Error(
1458
+ `[messaging] Unknown message format, must include the 'type' & 'timestamp' fields, received: ${JSON.stringify(
1459
+ message
1460
+ )}`
1461
+ );
1462
+ (_a3 = config.logger) == null ? void 0 : _a3.error(err);
1463
+ throw err;
1464
+ }
1465
+ (_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message);
1466
+ const listener = perTypeListeners[message.type];
1467
+ if (listener == null)
1468
+ return;
1469
+ const res = listener(message);
1236
1470
  return Promise.resolve(res).then((res2) => {
1237
- var _a3;
1238
- (_a3 = config == null ? void 0 : config.logger) == null ? void 0 : _a3.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { res: res2 });
1471
+ var _a4, _b3;
1472
+ return (_b3 = (_a4 = config.verifyMessageData) == null ? void 0 : _a4.call(config, res2)) != null ? _b3 : res2;
1473
+ }).then((res2) => {
1474
+ var _a4;
1475
+ (_a4 = config == null ? void 0 : config.logger) == null ? void 0 : _a4.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { res: res2 });
1239
1476
  return { res: res2 };
1240
1477
  }).catch((err) => {
1241
- var _a3;
1242
- let errMessage;
1243
- if (err instanceof Error)
1244
- errMessage = err.message;
1245
- else
1246
- errMessage = String(err);
1247
- (_a3 = config == null ? void 0 : config.logger) == null ? void 0 : _a3.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { err });
1248
- return { err: errMessage };
1478
+ var _a4;
1479
+ (_a4 = config == null ? void 0 : config.logger) == null ? void 0 : _a4.debug(`[messaging] onMessage {id=${message.id}} \u2500\u1405`, { err });
1480
+ return { err: serializeError(err) };
1249
1481
  });
1250
- }
1482
+ });
1483
+ }
1484
+ if (perTypeListeners[type] != null) {
1485
+ const err = Error(
1486
+ `[messaging] In this JS context, only one listener can be setup for ${type}`
1487
+ );
1488
+ (_b = config.logger) == null ? void 0 : _b.error(err);
1489
+ throw err;
1490
+ }
1491
+ perTypeListeners[type] = onReceived;
1492
+ (_c = config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${type}`);
1493
+ return () => {
1494
+ delete perTypeListeners[type];
1495
+ cleanupRootListener();
1251
1496
  };
1252
- import_webextension_polyfill2.default.runtime.onMessage.addListener(rootListener);
1253
- }
1254
- if (keyListeners[type] != null) {
1255
- const err = Error(
1256
- `[messaging] In this JS context, only one listener can be setup for ${type}`
1257
- );
1258
- (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.error(err);
1259
- throw err;
1260
- }
1261
- keyListeners[type] = onReceived;
1262
- (_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${type}`);
1263
- return function removeListener() {
1264
- delete keyListeners[type];
1497
+ },
1498
+ removeAllListeners() {
1499
+ Object.keys(perTypeListeners).forEach((type) => {
1500
+ delete perTypeListeners[type];
1501
+ });
1265
1502
  cleanupRootListener();
1266
- };
1267
- }
1268
- function sendMessage(type, data, tabId) {
1269
- return __async2(this, null, function* () {
1270
- var _a, _b;
1271
- const message = { id: getNextId(), type, data, timestamp: Date.now() };
1272
- (_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(`[messaging] sendMessage {id=${message.id}} \u2500\u1405`, message);
1273
- let response;
1503
+ }
1504
+ };
1505
+ }
1506
+
1507
+ // ../messaging/lib/index.js
1508
+ var import_webextension_polyfill2 = __toESM(require_browser_polyfill(), 1);
1509
+ function defineExtensionMessaging(config) {
1510
+ return defineGenericMessanging(__spreadProps(__spreadValues({}, config), {
1511
+ sendMessage(message, tabId) {
1274
1512
  if (tabId == null)
1275
- response = yield import_webextension_polyfill2.default.runtime.sendMessage(message);
1276
- else
1277
- response = yield import_webextension_polyfill2.default.tabs.sendMessage(tabId, message);
1278
- const { res, err } = response != null ? response : { err: "No response" };
1279
- (_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.debug(`[messaging] sendMessage {id=${message.id}} \u140A\u2500`, { res, err });
1280
- if (err != null)
1281
- throw Error(err);
1282
- return res;
1283
- });
1284
- }
1285
- function removeAllMessageListeners() {
1286
- Object.keys(keyListeners).forEach((type) => {
1287
- delete keyListeners[type];
1288
- });
1289
- cleanupRootListener();
1290
- }
1291
- return { onMessage, sendMessage, removeAllMessageListeners };
1513
+ return import_webextension_polyfill2.default.runtime.sendMessage(message);
1514
+ return import_webextension_polyfill2.default.tabs.sendMessage(tabId, message);
1515
+ },
1516
+ addRootListener(processMessage) {
1517
+ const listener = (message, sender) => {
1518
+ if (typeof message === "object")
1519
+ return processMessage(__spreadProps(__spreadValues({}, message), { sender }));
1520
+ else
1521
+ return processMessage(message);
1522
+ };
1523
+ import_webextension_polyfill2.default.runtime.onMessage.addListener(listener);
1524
+ return () => import_webextension_polyfill2.default.runtime.onMessage.removeListener(listener);
1525
+ }
1526
+ }));
1292
1527
  }
1293
1528
 
1294
1529
  // src/defineProxyService.ts
@@ -1301,6 +1536,7 @@ var webExtCoreProxyService = (() => {
1301
1536
  const wrapped = () => {
1302
1537
  };
1303
1538
  const proxy = new Proxy(wrapped, {
1539
+ // Executed when the object is called as a function
1304
1540
  apply(_target, _thisArg, args) {
1305
1541
  return __async(this, null, function* () {
1306
1542
  const res = yield sendMessage(messageKey, {
@@ -1310,6 +1546,7 @@ var webExtCoreProxyService = (() => {
1310
1546
  return res;
1311
1547
  });
1312
1548
  },
1549
+ // Executed when accessing a property on an object
1313
1550
  get(target, propertyName, receiver) {
1314
1551
  if (propertyName === "__proxy" || typeof propertyName === "symbol") {
1315
1552
  return Reflect.get(target, propertyName, receiver);
@@ -1342,17 +1579,55 @@ var webExtCoreProxyService = (() => {
1342
1579
  }
1343
1580
  ];
1344
1581
  }
1582
+
1583
+ // src/flattenPromise.ts
1584
+ var import_get_value2 = __toESM(require_get_value(), 1);
1585
+ function flattenPromise(promise) {
1586
+ function createProxy(location2) {
1587
+ const wrapped = () => {
1588
+ };
1589
+ const proxy = new Proxy(wrapped, {
1590
+ apply(_target, _thisArg, args) {
1591
+ return __async(this, null, function* () {
1592
+ const t = yield promise;
1593
+ const thisArg = (location2 == null ? void 0 : location2.parentPath) ? (0, import_get_value2.default)(t, location2.parentPath) : t;
1594
+ const fn = location2 ? (0, import_get_value2.default)(t, location2.propertyPath) : t;
1595
+ return fn.apply(thisArg, args);
1596
+ });
1597
+ },
1598
+ // Executed when accessing a property on an object
1599
+ get(target, propertyName, receiver) {
1600
+ if (propertyName === "__proxy" || typeof propertyName === "symbol") {
1601
+ return Reflect.get(target, propertyName, receiver);
1602
+ }
1603
+ return createProxy({
1604
+ propertyPath: location2 == null ? propertyName : `${location2.propertyPath}.${propertyName}`,
1605
+ parentPath: location2 == null ? void 0 : location2.propertyPath
1606
+ });
1607
+ }
1608
+ });
1609
+ proxy.__proxy = true;
1610
+ return proxy;
1611
+ }
1612
+ return createProxy();
1613
+ }
1345
1614
  return __toCommonJS(src_exports);
1346
1615
  })();
1347
- /*!
1348
- * get-value <https://github.com/jonschlinkert/get-value>
1349
- *
1350
- * Copyright (c) 2014-2018, Jon Schlinkert.
1351
- * Released under the MIT License.
1352
- */
1353
- /*!
1354
- * isobject <https://github.com/jonschlinkert/isobject>
1355
- *
1356
- * Copyright (c) 2014-2017, Jon Schlinkert.
1357
- * Released under the MIT License.
1358
- */
1616
+ /*! Bundled license information:
1617
+
1618
+ isobject/index.js:
1619
+ (*!
1620
+ * isobject <https://github.com/jonschlinkert/isobject>
1621
+ *
1622
+ * Copyright (c) 2014-2017, Jon Schlinkert.
1623
+ * Released under the MIT License.
1624
+ *)
1625
+
1626
+ get-value/index.js:
1627
+ (*!
1628
+ * get-value <https://github.com/jonschlinkert/get-value>
1629
+ *
1630
+ * Copyright (c) 2014-2018, Jon Schlinkert.
1631
+ * Released under the MIT License.
1632
+ *)
1633
+ */
package/lib/index.js CHANGED
@@ -34,6 +34,7 @@ function canAccessExtensionApi() {
34
34
  return !!((_a = Browser.runtime) == null ? void 0 : _a.id);
35
35
  }
36
36
  var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
37
+ // Firefox
37
38
  "/_generated_background_page.html"
38
39
  ];
39
40
  function isBackgroundPage() {
@@ -54,6 +55,7 @@ function defineProxyService(name, init, config) {
54
55
  const wrapped = () => {
55
56
  };
56
57
  const proxy = new Proxy(wrapped, {
58
+ // Executed when the object is called as a function
57
59
  apply(_target, _thisArg, args) {
58
60
  return __async(this, null, function* () {
59
61
  const res = yield sendMessage(messageKey, {
@@ -63,6 +65,7 @@ function defineProxyService(name, init, config) {
63
65
  return res;
64
66
  });
65
67
  },
68
+ // Executed when accessing a property on an object
66
69
  get(target, propertyName, receiver) {
67
70
  if (propertyName === "__proxy" || typeof propertyName === "symbol") {
68
71
  return Reflect.get(target, propertyName, receiver);
@@ -95,6 +98,39 @@ function defineProxyService(name, init, config) {
95
98
  }
96
99
  ];
97
100
  }
101
+
102
+ // src/flattenPromise.ts
103
+ import get2 from "get-value";
104
+ function flattenPromise(promise) {
105
+ function createProxy(location2) {
106
+ const wrapped = () => {
107
+ };
108
+ const proxy = new Proxy(wrapped, {
109
+ apply(_target, _thisArg, args) {
110
+ return __async(this, null, function* () {
111
+ const t = yield promise;
112
+ const thisArg = (location2 == null ? void 0 : location2.parentPath) ? get2(t, location2.parentPath) : t;
113
+ const fn = location2 ? get2(t, location2.propertyPath) : t;
114
+ return fn.apply(thisArg, args);
115
+ });
116
+ },
117
+ // Executed when accessing a property on an object
118
+ get(target, propertyName, receiver) {
119
+ if (propertyName === "__proxy" || typeof propertyName === "symbol") {
120
+ return Reflect.get(target, propertyName, receiver);
121
+ }
122
+ return createProxy({
123
+ propertyPath: location2 == null ? propertyName : `${location2.propertyPath}.${propertyName}`,
124
+ parentPath: location2 == null ? void 0 : location2.propertyPath
125
+ });
126
+ }
127
+ });
128
+ proxy.__proxy = true;
129
+ return proxy;
130
+ }
131
+ return createProxy();
132
+ }
98
133
  export {
99
- defineProxyService
134
+ defineProxyService,
135
+ flattenPromise
100
136
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webext-core/proxy-service",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "A type-safe wrapper around the web extension messaging APIs that lets you call a function from anywhere, but execute it in the background. Supports all browsers (Chrome, Firefox, Safari, etc)",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -39,6 +39,14 @@
39
39
  "require": "./lib/index.cjs"
40
40
  }
41
41
  },
42
+ "scripts": {
43
+ "build": "buildc -- tsup src/index.ts --clean --out-dir lib --dts --format esm,cjs,iife --global-name webExtCoreProxyService",
44
+ "test": "buildc --deps-only -- vitest -r src",
45
+ "test:coverage": "buildc --deps-only -- vitest run -r src --coverage",
46
+ "check": "buildc --deps-only -- bun check:typescript && bun check:type-tests",
47
+ "check:typescript": "tsc --noEmit",
48
+ "check:type-tests": "vitest run --typecheck types"
49
+ },
42
50
  "dependencies": {
43
51
  "get-value": "^3.0.1",
44
52
  "webextension-polyfill": "^0.10.0"
@@ -46,23 +54,15 @@
46
54
  "devDependencies": {
47
55
  "@types/get-value": "^3.0.3",
48
56
  "@types/webextension-polyfill": "^0.9.1",
49
- "@vitest/coverage-c8": "^0.24.5",
50
- "tsup": "^6.4.0",
51
- "typescript": "^4.8.4",
52
- "vitest": "0.28.0",
53
- "@webext-core/fake-browser": "1.2.2",
54
- "@webext-core/messaging": "1.3.1",
55
- "tsconfig": "0.0.0"
57
+ "@webext-core/fake-browser": "workspace:*",
58
+ "@webext-core/messaging": "workspace:*",
59
+ "tsconfig": "workspace:*"
56
60
  },
57
61
  "peerDependencies": {
58
- "webextension-polyfill": "^0.10.0",
62
+ "webextension-polyfill": ">=0.10.0",
59
63
  "@webext-core/messaging": ">=1.3.1"
60
64
  },
61
- "scripts": {
62
- "build": "tsup src/index.ts --clean --out-dir lib --dts --format esm,cjs,iife --global-name webExtCoreProxyService",
63
- "build:dependencies": "cd ../.. && turbo run build --filter=@webext-core/proxy-service^...",
64
- "test": "vitest -r src",
65
- "test:coverage": "vitest run -r src --coverage",
66
- "compile": "tsc --noEmit"
65
+ "buildc": {
66
+ "outDir": "lib"
67
67
  }
68
- }
68
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
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.