@webext-core/proxy-service 1.2.1 → 2.0.0-rc.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/lib/index.d.ts CHANGED
@@ -1,63 +1,56 @@
1
- import { ExtensionMessagingConfig } from '@webext-core/messaging';
1
+ import { ExtensionMessagingConfig, RemoveListenerCallback } from '@webext-core/messaging';
2
+ import { DeepAsync, Service } from './types.js';
2
3
 
3
- type Proimsify<T> = T extends Promise<any> ? T : Promise<T>;
4
- type Service = ((...args: any[]) => Promise<any>) | {
5
- [key: string]: any | Service;
6
- };
7
4
  /**
8
5
  * A type that ensures a service has only async methods.
6
+ *
9
7
  * - ***If all methods are async***, it returns the original type.
10
8
  * - ***If the service has non-async methods***, it returns a `DeepAsync` of the service.
11
9
  */
12
- type ProxyService<TService> = TService extends DeepAsync<TService> ? TService : DeepAsync<TService>;
10
+ type ProxyService<T> = T extends DeepAsync<T> ? T : DeepAsync<T>;
13
11
  /**
14
- * A recursive type that deeply converts all methods in `TService` to be async.
12
+ * Create a proxy service that uses the message APIs to proxy function calls to
13
+ * the real service registered in the background with `registerService`.
14
+ *
15
+ * @param key The service key to listen for, must be the same string as the one
16
+ * used in `registerService`.
15
17
  */
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>>;
18
+ declare function createProxyService<T extends Service>(key: ProxyServiceKey<T> | string, config?: ExtensionMessagingConfig): ProxyService<T>;
22
19
  /**
23
- * Configure a proxy service's behavior. It uses `@webext-core/messaging` internally, so any
24
- * config from `ExtensionMessagingConfig` can be passed as well.
20
+ * Sets up message listeners that receive messages from proxies created with
21
+ * `createProxyService`.
22
+ *
23
+ * @param key The service key to listen for, must be the same string as the one
24
+ * used in `createProxyService`.
25
+ * @param realService The real service instance that will handle the requests.
25
26
  */
26
- interface ProxyServiceConfig extends ExtensionMessagingConfig {
27
+ declare function registerService<T extends Service, K extends string = ProxyServiceKey<T> | string>(key: K, realService: T, config?: ExtensionMessagingConfig): RemoveListenerCallback;
28
+ declare function isProxyService<T>(obj: unknown): obj is ProxyService<T>;
29
+ interface ProxyServiceConstraint<_> {
27
30
  }
28
-
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
31
  /**
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.
32
+ * Used to constrain a service's type between calls to `createProxyService` and
33
+ * `registerService`.
48
34
  *
49
35
  * @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
- * }
36
+ * ```ts
37
+ * // utils/proxy-service-keys.ts
38
+ * import type { ProxyServiceKey } from '@webext-core/proxy-service';
39
+ * import type { MathService } from './math-service';
40
+ *
41
+ * export const PROXY_SERVICE_KEY = 'math-service' as ProxyServiceKey<MathService>;
42
+ *
43
+ * // background.ts
44
+ * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
45
+ *
46
+ * registerService(PROXY_SERVICE_KEY, new MathService())
47
+ *
48
+ * // content-script.ts
49
+ * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
50
+ *
51
+ * const mathService = await createProxyService(PROXY_SERVICE_KEY);
52
+ * ```
60
53
  */
61
- declare function flattenPromise<T>(promise: Promise<T>): DeepAsync<T>;
54
+ type ProxyServiceKey<T> = string & ProxyServiceConstraint<T>;
62
55
 
63
- export { DeepAsync, ProxyService, ProxyServiceConfig, defineProxyService, flattenPromise };
56
+ export { ProxyService, ProxyServiceKey, createProxyService, isProxyService, registerService };
@@ -4,9 +4,22 @@ var webExtCoreProxyService = (() => {
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
8
  var __getProtoOf = Object.getPrototypeOf;
8
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
10
23
  var __commonJS = (cb, mod) => function __require() {
11
24
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
25
  };
@@ -56,9 +69,9 @@ var webExtCoreProxyService = (() => {
56
69
  });
57
70
  };
58
71
 
59
- // ../../node_modules/webextension-polyfill/dist/browser-polyfill.js
72
+ // ../../node_modules/.bun/webextension-polyfill@0.10.0/node_modules/webextension-polyfill/dist/browser-polyfill.js
60
73
  var require_browser_polyfill = __commonJS({
61
- "../../node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) {
74
+ "../../node_modules/.bun/webextension-polyfill@0.10.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) {
62
75
  (function(global, factory) {
63
76
  if (typeof define === "function" && define.amd) {
64
77
  define("webextension-polyfill", ["module"], factory);
@@ -1051,137 +1064,15 @@ var webExtCoreProxyService = (() => {
1051
1064
  }
1052
1065
  });
1053
1066
 
1054
- // ../../node_modules/isobject/index.js
1055
- var require_isobject = __commonJS({
1056
- "../../node_modules/isobject/index.js"(exports, module) {
1057
- "use strict";
1058
- module.exports = function isObject(val) {
1059
- return val != null && typeof val === "object" && Array.isArray(val) === false;
1060
- };
1061
- }
1062
- });
1063
-
1064
- // ../../node_modules/get-value/index.js
1065
- var require_get_value = __commonJS({
1066
- "../../node_modules/get-value/index.js"(exports, module) {
1067
- var isObject = require_isobject();
1068
- module.exports = function(target, path, options) {
1069
- if (!isObject(options)) {
1070
- options = { default: options };
1071
- }
1072
- if (!isValidObject(target)) {
1073
- return typeof options.default !== "undefined" ? options.default : target;
1074
- }
1075
- if (typeof path === "number") {
1076
- path = String(path);
1077
- }
1078
- const isArray = Array.isArray(path);
1079
- const isString = typeof path === "string";
1080
- const splitChar = options.separator || ".";
1081
- const joinChar = options.joinChar || (typeof splitChar === "string" ? splitChar : ".");
1082
- if (!isString && !isArray) {
1083
- return target;
1084
- }
1085
- if (isString && path in target) {
1086
- return isValid(path, target, options) ? target[path] : options.default;
1087
- }
1088
- let segs = isArray ? path : split(path, splitChar, options);
1089
- let len = segs.length;
1090
- let idx = 0;
1091
- do {
1092
- let prop = segs[idx];
1093
- if (typeof prop === "number") {
1094
- prop = String(prop);
1095
- }
1096
- while (prop && prop.slice(-1) === "\\") {
1097
- prop = join([prop.slice(0, -1), segs[++idx] || ""], joinChar, options);
1098
- }
1099
- if (prop in target) {
1100
- if (!isValid(prop, target, options)) {
1101
- return options.default;
1102
- }
1103
- target = target[prop];
1104
- } else {
1105
- let hasProp = false;
1106
- let n = idx + 1;
1107
- while (n < len) {
1108
- prop = join([prop, segs[n++]], joinChar, options);
1109
- if (hasProp = prop in target) {
1110
- if (!isValid(prop, target, options)) {
1111
- return options.default;
1112
- }
1113
- target = target[prop];
1114
- idx = n - 1;
1115
- break;
1116
- }
1117
- }
1118
- if (!hasProp) {
1119
- return options.default;
1120
- }
1121
- }
1122
- } while (++idx < len && isValidObject(target));
1123
- if (idx === len) {
1124
- return target;
1125
- }
1126
- return options.default;
1127
- };
1128
- function join(segs, joinChar, options) {
1129
- if (typeof options.join === "function") {
1130
- return options.join(segs);
1131
- }
1132
- return segs[0] + joinChar + segs[1];
1133
- }
1134
- function split(path, splitChar, options) {
1135
- if (typeof options.split === "function") {
1136
- return options.split(path);
1137
- }
1138
- return path.split(splitChar);
1139
- }
1140
- function isValid(key, target, options) {
1141
- if (typeof options.isValid === "function") {
1142
- return options.isValid(key, target);
1143
- }
1144
- return true;
1145
- }
1146
- function isValidObject(val) {
1147
- return isObject(val) || Array.isArray(val) || typeof val === "function";
1148
- }
1149
- }
1150
- });
1151
-
1152
1067
  // src/index.ts
1153
1068
  var src_exports = {};
1154
1069
  __export(src_exports, {
1155
- defineProxyService: () => defineProxyService,
1156
- flattenPromise: () => flattenPromise
1070
+ createProxyService: () => createProxyService,
1071
+ isProxyService: () => isProxyService,
1072
+ registerService: () => registerService
1157
1073
  });
1158
1074
 
1159
- // src/isBackground.ts
1160
- var import_webextension_polyfill = __toESM(require_browser_polyfill(), 1);
1161
- function isBackground() {
1162
- if (!canAccessExtensionApi())
1163
- return false;
1164
- const manifest = import_webextension_polyfill.default.runtime.getManifest();
1165
- if (!manifest.background)
1166
- return false;
1167
- return manifest.manifest_version === 3 ? isBackgroundServiceWorker() : isBackgroundPage();
1168
- }
1169
- function canAccessExtensionApi() {
1170
- var _a;
1171
- return !!((_a = import_webextension_polyfill.default.runtime) == null ? void 0 : _a.id);
1172
- }
1173
- var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
1174
- // Firefox
1175
- "/_generated_background_page.html"
1176
- ];
1177
- function isBackgroundPage() {
1178
- return typeof window !== "undefined" && KNOWN_BACKGROUND_PAGE_PATHNAMES.includes(location.pathname);
1179
- }
1180
- function isBackgroundServiceWorker() {
1181
- return typeof window === "undefined";
1182
- }
1183
-
1184
- // ../../node_modules/serialize-error/error-constructors.js
1075
+ // ../../node_modules/.bun/serialize-error@11.0.3/node_modules/serialize-error/error-constructors.js
1185
1076
  var list = [
1186
1077
  // Native ES errors https://262.ecma-international.org/12.0/#sec-well-known-intrinsic-objects
1187
1078
  EvalError,
@@ -1202,7 +1093,7 @@ var webExtCoreProxyService = (() => {
1202
1093
  var errorConstructors = new Map(list);
1203
1094
  var error_constructors_default = errorConstructors;
1204
1095
 
1205
- // ../../node_modules/serialize-error/index.js
1096
+ // ../../node_modules/.bun/serialize-error@11.0.3/node_modules/serialize-error/index.js
1206
1097
  var NonError = class extends Error {
1207
1098
  constructor(message) {
1208
1099
  super(NonError._prepareSuperMessage(message));
@@ -1373,17 +1264,17 @@ var webExtCoreProxyService = (() => {
1373
1264
  var __defProp2 = Object.defineProperty;
1374
1265
  var __defProps = Object.defineProperties;
1375
1266
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1376
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1267
+ var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
1377
1268
  var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1378
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1269
+ var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
1379
1270
  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) => {
1271
+ var __spreadValues2 = (a, b) => {
1381
1272
  for (var prop in b || (b = {}))
1382
1273
  if (__hasOwnProp2.call(b, prop))
1383
1274
  __defNormalProp2(a, prop, b[prop]);
1384
- if (__getOwnPropSymbols)
1385
- for (var prop of __getOwnPropSymbols(b)) {
1386
- if (__propIsEnum.call(b, prop))
1275
+ if (__getOwnPropSymbols2)
1276
+ for (var prop of __getOwnPropSymbols2(b)) {
1277
+ if (__propIsEnum2.call(b, prop))
1387
1278
  __defNormalProp2(a, prop, b[prop]);
1388
1279
  }
1389
1280
  return a;
@@ -1505,129 +1396,83 @@ var webExtCoreProxyService = (() => {
1505
1396
  }
1506
1397
 
1507
1398
  // ../messaging/lib/index.js
1508
- var import_webextension_polyfill2 = __toESM(require_browser_polyfill(), 1);
1399
+ var import_webextension_polyfill = __toESM(require_browser_polyfill(), 1);
1509
1400
  function defineExtensionMessaging(config) {
1510
- return defineGenericMessanging(__spreadProps(__spreadValues({}, config), {
1511
- sendMessage(message, tabId) {
1512
- if (tabId == null)
1513
- return import_webextension_polyfill2.default.runtime.sendMessage(message);
1514
- return import_webextension_polyfill2.default.tabs.sendMessage(tabId, message);
1401
+ return defineGenericMessanging(__spreadProps(__spreadValues2({}, config), {
1402
+ sendMessage(message, arg) {
1403
+ if (arg == null) {
1404
+ return import_webextension_polyfill.default.runtime.sendMessage(message);
1405
+ }
1406
+ const options = typeof arg === "number" ? { tabId: arg } : arg;
1407
+ return import_webextension_polyfill.default.tabs.sendMessage(
1408
+ options.tabId,
1409
+ message,
1410
+ // Pass frameId if specified
1411
+ options.frameId != null ? { frameId: options.frameId } : void 0
1412
+ );
1515
1413
  },
1516
1414
  addRootListener(processMessage) {
1517
1415
  const listener = (message, sender) => {
1518
1416
  if (typeof message === "object")
1519
- return processMessage(__spreadProps(__spreadValues({}, message), { sender }));
1417
+ return processMessage(__spreadProps(__spreadValues2({}, message), { sender }));
1520
1418
  else
1521
1419
  return processMessage(message);
1522
1420
  };
1523
- import_webextension_polyfill2.default.runtime.onMessage.addListener(listener);
1524
- return () => import_webextension_polyfill2.default.runtime.onMessage.removeListener(listener);
1421
+ import_webextension_polyfill.default.runtime.onMessage.addListener(listener);
1422
+ return () => import_webextension_polyfill.default.runtime.onMessage.removeListener(listener);
1525
1423
  }
1526
1424
  }));
1527
1425
  }
1528
1426
 
1529
- // src/defineProxyService.ts
1530
- var import_get_value = __toESM(require_get_value(), 1);
1531
- function defineProxyService(name, init, config) {
1532
- let service;
1533
- const messageKey = `proxy-service.${name}`;
1534
- const { onMessage, sendMessage } = defineExtensionMessaging(config);
1535
- function createProxy(path) {
1536
- const wrapped = () => {
1537
- };
1538
- const proxy = new Proxy(wrapped, {
1539
- // Executed when the object is called as a function
1540
- apply(_target, _thisArg, args) {
1541
- return __async(this, null, function* () {
1542
- const res = yield sendMessage(messageKey, {
1543
- path,
1544
- args
1545
- });
1546
- return res;
1427
+ // src/index.ts
1428
+ function createProxyService(key, config) {
1429
+ return createProxy(defineProxyMessaging(key, config));
1430
+ }
1431
+ function registerService(key, realService, config) {
1432
+ const messenger = defineProxyMessaging(key, config);
1433
+ return messenger.onMessage(messenger.messageKey, ({ data }) => {
1434
+ const method = data.path == null ? realService : get(realService != null ? realService : {}, data.path);
1435
+ if (method)
1436
+ return Promise.resolve(method.bind(realService)(...data.args));
1437
+ });
1438
+ }
1439
+ function isProxyService(obj) {
1440
+ return (obj == null ? void 0 : obj[ProxyServiceSymbol]) === true;
1441
+ }
1442
+ function defineProxyMessaging(key, config) {
1443
+ const messaging = defineExtensionMessaging(config);
1444
+ return __spreadValues({
1445
+ messageKey: `proxy-service.${key}`
1446
+ }, messaging);
1447
+ }
1448
+ function createProxy(messenger, path) {
1449
+ const wrapped = () => {
1450
+ };
1451
+ const proxy = new Proxy(wrapped, {
1452
+ apply(_target, _thisArg, args) {
1453
+ return __async(this, null, function* () {
1454
+ const res = yield messenger.sendMessage(messenger.messageKey, {
1455
+ path,
1456
+ args
1547
1457
  });
1548
- },
1549
- // Executed when accessing a property on an object
1550
- get(target, propertyName, receiver) {
1551
- if (propertyName === "__proxy" || typeof propertyName === "symbol") {
1552
- return Reflect.get(target, propertyName, receiver);
1553
- }
1554
- return createProxy(path == null ? propertyName : `${path}.${propertyName}`);
1555
- }
1556
- });
1557
- proxy.__proxy = true;
1558
- return proxy;
1559
- }
1560
- return [
1561
- function registerService(...args) {
1562
- service = init(...args);
1563
- onMessage(messageKey, ({ data }) => {
1564
- const method = data.path == null ? service : (0, import_get_value.default)(service != null ? service : {}, data.path);
1565
- if (method)
1566
- return Promise.resolve(method.bind(service)(...data.args));
1458
+ return res;
1567
1459
  });
1568
- return service;
1569
1460
  },
1570
- function getService() {
1571
- if (!isBackground())
1572
- return createProxy();
1573
- if (service == null) {
1574
- throw Error(
1575
- `Failed to get an instance of ${name}: in background, but registerService has not been called. Did you forget to call registerService?`
1576
- );
1461
+ get(target, propertyName, receiver) {
1462
+ if (typeof propertyName === "symbol") {
1463
+ return Reflect.get(target, propertyName, receiver);
1577
1464
  }
1578
- return service;
1465
+ return createProxy(messenger, path == null ? [propertyName] : path.concat([propertyName]));
1579
1466
  }
1580
- ];
1467
+ });
1468
+ proxy[ProxyServiceSymbol] = true;
1469
+ return proxy;
1581
1470
  }
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();
1471
+ var ProxyServiceSymbol = Symbol();
1472
+ function get(obj, path) {
1473
+ if (path.length === 0)
1474
+ return obj;
1475
+ return path.reduce((acc, key) => acc == null ? void 0 : acc[key], obj);
1613
1476
  }
1614
1477
  return __toCommonJS(src_exports);
1615
1478
  })();
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
@@ -1,3 +1,19 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
1
17
  var __async = (__this, __arguments, generator) => {
2
18
  return new Promise((resolve, reject) => {
3
19
  var fulfilled = (value) => {
@@ -19,118 +35,61 @@ var __async = (__this, __arguments, generator) => {
19
35
  });
20
36
  };
21
37
 
22
- // src/isBackground.ts
23
- import Browser from "webextension-polyfill";
24
- function isBackground() {
25
- if (!canAccessExtensionApi())
26
- return false;
27
- const manifest = Browser.runtime.getManifest();
28
- if (!manifest.background)
29
- return false;
30
- return manifest.manifest_version === 3 ? isBackgroundServiceWorker() : isBackgroundPage();
38
+ // src/index.ts
39
+ import {
40
+ defineExtensionMessaging
41
+ } from "@webext-core/messaging";
42
+ function createProxyService(key, config) {
43
+ return createProxy(defineProxyMessaging(key, config));
31
44
  }
32
- function canAccessExtensionApi() {
33
- var _a;
34
- return !!((_a = Browser.runtime) == null ? void 0 : _a.id);
45
+ function registerService(key, realService, config) {
46
+ const messenger = defineProxyMessaging(key, config);
47
+ return messenger.onMessage(messenger.messageKey, ({ data }) => {
48
+ const method = data.path == null ? realService : get(realService != null ? realService : {}, data.path);
49
+ if (method)
50
+ return Promise.resolve(method.bind(realService)(...data.args));
51
+ });
35
52
  }
36
- var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
37
- // Firefox
38
- "/_generated_background_page.html"
39
- ];
40
- function isBackgroundPage() {
41
- return typeof window !== "undefined" && KNOWN_BACKGROUND_PAGE_PATHNAMES.includes(location.pathname);
53
+ function isProxyService(obj) {
54
+ return (obj == null ? void 0 : obj[ProxyServiceSymbol]) === true;
42
55
  }
43
- function isBackgroundServiceWorker() {
44
- return typeof window === "undefined";
56
+ function defineProxyMessaging(key, config) {
57
+ const messaging = defineExtensionMessaging(config);
58
+ return __spreadValues({
59
+ messageKey: `proxy-service.${key}`
60
+ }, messaging);
45
61
  }
46
-
47
- // src/defineProxyService.ts
48
- import { defineExtensionMessaging } from "@webext-core/messaging";
49
- import get from "get-value";
50
- function defineProxyService(name, init, config) {
51
- let service;
52
- const messageKey = `proxy-service.${name}`;
53
- const { onMessage, sendMessage } = defineExtensionMessaging(config);
54
- function createProxy(path) {
55
- const wrapped = () => {
56
- };
57
- const proxy = new Proxy(wrapped, {
58
- // Executed when the object is called as a function
59
- apply(_target, _thisArg, args) {
60
- return __async(this, null, function* () {
61
- const res = yield sendMessage(messageKey, {
62
- path,
63
- args
64
- });
65
- return res;
62
+ function createProxy(messenger, path) {
63
+ const wrapped = () => {
64
+ };
65
+ const proxy = new Proxy(wrapped, {
66
+ apply(_target, _thisArg, args) {
67
+ return __async(this, null, function* () {
68
+ const res = yield messenger.sendMessage(messenger.messageKey, {
69
+ path,
70
+ args
66
71
  });
67
- },
68
- // Executed when accessing a property on an object
69
- get(target, propertyName, receiver) {
70
- if (propertyName === "__proxy" || typeof propertyName === "symbol") {
71
- return Reflect.get(target, propertyName, receiver);
72
- }
73
- return createProxy(path == null ? propertyName : `${path}.${propertyName}`);
74
- }
75
- });
76
- proxy.__proxy = true;
77
- return proxy;
78
- }
79
- return [
80
- function registerService(...args) {
81
- service = init(...args);
82
- onMessage(messageKey, ({ data }) => {
83
- const method = data.path == null ? service : get(service != null ? service : {}, data.path);
84
- if (method)
85
- return Promise.resolve(method.bind(service)(...data.args));
72
+ return res;
86
73
  });
87
- return service;
88
74
  },
89
- function getService() {
90
- if (!isBackground())
91
- return createProxy();
92
- if (service == null) {
93
- throw Error(
94
- `Failed to get an instance of ${name}: in background, but registerService has not been called. Did you forget to call registerService?`
95
- );
75
+ get(target, propertyName, receiver) {
76
+ if (typeof propertyName === "symbol") {
77
+ return Reflect.get(target, propertyName, receiver);
96
78
  }
97
- return service;
79
+ return createProxy(messenger, path == null ? [propertyName] : path.concat([propertyName]));
98
80
  }
99
- ];
81
+ });
82
+ proxy[ProxyServiceSymbol] = true;
83
+ return proxy;
100
84
  }
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();
85
+ var ProxyServiceSymbol = Symbol();
86
+ function get(obj, path) {
87
+ if (path.length === 0)
88
+ return obj;
89
+ return path.reduce((acc, key) => acc == null ? void 0 : acc[key], obj);
132
90
  }
133
91
  export {
134
- defineProxyService,
135
- flattenPromise
92
+ createProxyService,
93
+ isProxyService,
94
+ registerService
136
95
  };
package/lib/types.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ type Proimsify<T> = T extends Promise<any> ? T : Promise<T>;
2
+ type Service = ((...args: any[]) => Promise<any>) | {
3
+ [key: string]: any | Service;
4
+ };
5
+ /**
6
+ * A recursive type that deeply converts all methods in `TService` to be async.
7
+ */
8
+ type DeepAsync<TService> = TService extends (...args: any) => any ? ToAsyncFunction<TService> : TService extends {
9
+ [key: string]: any;
10
+ } ? {
11
+ [fn in keyof TService]: DeepAsync<TService[fn]>;
12
+ } : never;
13
+ type ToAsyncFunction<T extends (...args: any) => any> = (...args: Parameters<T>) => Proimsify<ReturnType<T>>;
14
+
15
+ export { DeepAsync, Proimsify, Service };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webext-core/proxy-service",
3
- "version": "1.2.1",
3
+ "version": "2.0.0-rc.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": [
@@ -35,28 +35,24 @@
35
35
  "types": "lib/index.d.ts",
36
36
  "exports": {
37
37
  ".": {
38
- "import": "./lib/index.js",
39
- "require": "./lib/index.cjs"
40
- }
38
+ "types": "./lib/index.d.ts",
39
+ "default": "./lib/index.js"
40
+ },
41
+ "./types": "./lib/types.d.ts"
41
42
  },
42
43
  "scripts": {
43
- "build": "buildc -- tsup src/index.ts --clean --out-dir lib --dts --format esm,cjs,iife --global-name webExtCoreProxyService",
44
+ "build": "buildc -- tsup",
44
45
  "test": "buildc --deps-only -- vitest -r src",
45
46
  "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
- },
50
- "dependencies": {
51
- "get-value": "^3.0.1",
52
- "webextension-polyfill": "^0.10.0"
47
+ "check": "buildc --deps-only -- tsc --noEmit"
53
48
  },
54
49
  "devDependencies": {
55
50
  "@types/get-value": "^3.0.3",
56
51
  "@types/webextension-polyfill": "^0.9.1",
57
- "@webext-core/fake-browser": "workspace:*",
58
- "@webext-core/messaging": "workspace:*",
59
- "tsconfig": "workspace:*"
52
+ "@webext-core/fake-browser": "1.3.4",
53
+ "@webext-core/messaging": "2.3.0",
54
+ "tsconfig": "0.0.0",
55
+ "webextension-polyfill": "^0.10.0"
60
56
  },
61
57
  "peerDependencies": {
62
58
  "webextension-polyfill": ">=0.10.0",
package/lib/index.cjs DELETED
@@ -1,173 +0,0 @@
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
- // 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.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var __async = (__this, __arguments, generator) => {
30
- return new Promise((resolve, reject) => {
31
- var fulfilled = (value) => {
32
- try {
33
- step(generator.next(value));
34
- } catch (e) {
35
- reject(e);
36
- }
37
- };
38
- var rejected = (value) => {
39
- try {
40
- step(generator.throw(value));
41
- } catch (e) {
42
- reject(e);
43
- }
44
- };
45
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
46
- step((generator = generator.apply(__this, __arguments)).next());
47
- });
48
- };
49
-
50
- // src/index.ts
51
- var src_exports = {};
52
- __export(src_exports, {
53
- defineProxyService: () => defineProxyService,
54
- flattenPromise: () => flattenPromise
55
- });
56
- module.exports = __toCommonJS(src_exports);
57
-
58
- // src/isBackground.ts
59
- var import_webextension_polyfill = __toESM(require("webextension-polyfill"), 1);
60
- function isBackground() {
61
- if (!canAccessExtensionApi())
62
- return false;
63
- const manifest = import_webextension_polyfill.default.runtime.getManifest();
64
- if (!manifest.background)
65
- return false;
66
- return manifest.manifest_version === 3 ? isBackgroundServiceWorker() : isBackgroundPage();
67
- }
68
- function canAccessExtensionApi() {
69
- var _a;
70
- return !!((_a = import_webextension_polyfill.default.runtime) == null ? void 0 : _a.id);
71
- }
72
- var KNOWN_BACKGROUND_PAGE_PATHNAMES = [
73
- // Firefox
74
- "/_generated_background_page.html"
75
- ];
76
- function isBackgroundPage() {
77
- return typeof window !== "undefined" && KNOWN_BACKGROUND_PAGE_PATHNAMES.includes(location.pathname);
78
- }
79
- function isBackgroundServiceWorker() {
80
- return typeof window === "undefined";
81
- }
82
-
83
- // src/defineProxyService.ts
84
- var import_messaging = require("@webext-core/messaging");
85
- var import_get_value = __toESM(require("get-value"), 1);
86
- function defineProxyService(name, init, config) {
87
- let service;
88
- const messageKey = `proxy-service.${name}`;
89
- const { onMessage, sendMessage } = (0, import_messaging.defineExtensionMessaging)(config);
90
- function createProxy(path) {
91
- const wrapped = () => {
92
- };
93
- const proxy = new Proxy(wrapped, {
94
- // Executed when the object is called as a function
95
- apply(_target, _thisArg, args) {
96
- return __async(this, null, function* () {
97
- const res = yield sendMessage(messageKey, {
98
- path,
99
- args
100
- });
101
- return res;
102
- });
103
- },
104
- // Executed when accessing a property on an object
105
- get(target, propertyName, receiver) {
106
- if (propertyName === "__proxy" || typeof propertyName === "symbol") {
107
- return Reflect.get(target, propertyName, receiver);
108
- }
109
- return createProxy(path == null ? propertyName : `${path}.${propertyName}`);
110
- }
111
- });
112
- proxy.__proxy = true;
113
- return proxy;
114
- }
115
- return [
116
- function registerService(...args) {
117
- service = init(...args);
118
- onMessage(messageKey, ({ data }) => {
119
- const method = data.path == null ? service : (0, import_get_value.default)(service != null ? service : {}, data.path);
120
- if (method)
121
- return Promise.resolve(method.bind(service)(...data.args));
122
- });
123
- return service;
124
- },
125
- function getService() {
126
- if (!isBackground())
127
- return createProxy();
128
- if (service == null) {
129
- throw Error(
130
- `Failed to get an instance of ${name}: in background, but registerService has not been called. Did you forget to call registerService?`
131
- );
132
- }
133
- return service;
134
- }
135
- ];
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
- }
169
- // Annotate the CommonJS export names for ESM import in node:
170
- 0 && (module.exports = {
171
- defineProxyService,
172
- flattenPromise
173
- });