@webext-core/proxy-service 3.0.0 → 3.0.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
@@ -1,7 +1,10 @@
1
1
  # `@webext-core/proxy-service`
2
2
 
3
- 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).
3
+ A type-safe wrapper around the web extension messaging APIs that lets you call a
4
+ function from anywhere, but execute it in the background. Supports all browsers
5
+ (Chrome, Firefox, Safari, etc).
4
6
 
5
7
  ## Get Started
6
8
 
7
- See [documentation](https://webext-core.aklinker1.io/guide/proxy-service/) to get started!
9
+ See [documentation](https://webext-core.aklinker1.io/proxy-service/installation)
10
+ to get started!
@@ -1,56 +1,51 @@
1
- import { ExtensionMessagingConfig, RemoveListenerCallback } from '@webext-core/messaging';
2
- import { DeepAsync, Service } from './types.js';
3
-
1
+ import { DeepAsync, Service } from "./types.mjs";
2
+ import { ExtensionMessagingConfig, RemoveListenerCallback } from "@webext-core/messaging";
3
+ //#region src/index.d.ts
4
4
  /**
5
5
  * A type that ensures a service has only async methods.
6
6
  *
7
- * - ***If all methods are async***, it returns the original type.
8
- * - ***If the service has non-async methods***, it returns a `DeepAsync` of the service.
7
+ * - _**If all methods are async**_, it returns the original type.
8
+ * - _**If the service has non-async methods**_, it returns a `DeepAsync` of the service.
9
9
  */
10
10
  type ProxyService<T> = T extends DeepAsync<T> ? T : DeepAsync<T>;
11
11
  /**
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`.
12
+ * Create a proxy service that uses the message APIs to proxy function calls to the real service
13
+ * registered in the background with `registerService`.
14
14
  *
15
- * @param key The service key to listen for, must be the same string as the one
16
- * used in `registerService`.
15
+ * @param key The service key to listen for, must be the same string as the one used in
16
+ * `registerService`.
17
17
  */
18
18
  declare function createProxyService<T extends Service>(key: ProxyServiceKey<T> | string, config?: ExtensionMessagingConfig): ProxyService<T>;
19
19
  /**
20
- * Sets up message listeners that receive messages from proxies created with
21
- * `createProxyService`.
20
+ * Sets up message listeners that receive messages from proxies created with `createProxyService`.
22
21
  *
23
- * @param key The service key to listen for, must be the same string as the one
24
- * used in `createProxyService`.
22
+ * @param key The service key to listen for, must be the same string as the one used in
23
+ * `createProxyService`.
25
24
  * @param realService The real service instance that will handle the requests.
26
25
  */
27
26
  declare function registerService<T extends Service, K extends string = ProxyServiceKey<T> | string>(key: K, realService: T, config?: ExtensionMessagingConfig): RemoveListenerCallback;
28
27
  declare function isProxyService<T>(obj: unknown): obj is ProxyService<T>;
29
- interface ProxyServiceConstraint<_> {
30
- }
28
+ interface ProxyServiceConstraint<_> {}
31
29
  /**
32
- * Used to constrain a service's type between calls to `createProxyService` and
33
- * `registerService`.
30
+ * Used to constrain a service's type between calls to `createProxyService` and `registerService`.
34
31
  *
35
32
  * @example
36
- * ```ts
37
- * // utils/proxy-service-keys.ts
38
- * import type { ProxyServiceKey } from '@webext-core/proxy-service';
39
- * import type { MathService } from './math-service';
33
+ * // utils/proxy-service-keys.ts
34
+ * import type { ProxyServiceKey } from '@webext-core/proxy-service';
35
+ * import type { MathService } from './math-service';
40
36
  *
41
- * export const PROXY_SERVICE_KEY = 'math-service' as ProxyServiceKey<MathService>;
37
+ * export const PROXY_SERVICE_KEY = 'math-service' as ProxyServiceKey<MathService>;
42
38
  *
43
- * // background.ts
44
- * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
39
+ * // background.ts
40
+ * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
45
41
  *
46
- * registerService(PROXY_SERVICE_KEY, new MathService())
42
+ * registerService(PROXY_SERVICE_KEY, new MathService());
47
43
  *
48
- * // content-script.ts
49
- * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
44
+ * // content-script.ts
45
+ * import { PROXY_SERVICE_KEY } from './utils/proxy-service-keys';
50
46
  *
51
- * const mathService = await createProxyService(PROXY_SERVICE_KEY);
52
- * ```
47
+ * const mathService = await createProxyService(PROXY_SERVICE_KEY);
53
48
  */
54
49
  type ProxyServiceKey<T> = string & ProxyServiceConstraint<T>;
55
-
56
- export { ProxyService, ProxyServiceKey, createProxyService, isProxyService, registerService };
50
+ //#endregion
51
+ export { ProxyService, ProxyServiceKey, createProxyService, isProxyService, registerService };
@@ -0,0 +1 @@
1
+ var webExtCoreProxyService=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=`string`,n=`object`;function r(e){return e!=null&&typeof e==n&&typeof e.name==t&&typeof e.message==t&&typeof e.stack==t}function i(e){if(typeof e!=n||e==null)return e;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack??``,...e.cause?{cause:i(e.cause)}:{},...i({...e})};if(Array.isArray(e)){let t=[];for(let n of e)t.push(i(n));return t}let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=i(r);return t}function a(e){if(r(e)){let t=Error(e.message,e.cause?{cause:a(e.cause)}:void 0);t.name=e.name,t.stack=e.stack;for(let[n,r]of Object.entries(e))n!==`name`&&n!==`message`&&n!==`stack`&&n!==`cause`&&(t[n]=r);return t}if(e==null||typeof e!=n)return e;if(Array.isArray(e)){let t=[];for(let n of e)t.push(a(n));return t}let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=a(r);return t}function o(e){let t,n={};function r(){Object.entries(n).length===0&&(t?.(),t=void 0)}let o=Math.floor(Math.random()*1e4);function s(){return o++}return{async sendMessage(t,n,...r){let i={id:s(),type:t,data:n,timestamp:Date.now()},o=await e.verifyMessageData?.(i)??i;e.logger?.debug(`[messaging] sendMessage {id=${o.id}} ─ᐅ`,o,...r);let{res:c,err:l}=await e.sendMessage(o,...r)??{err:Error(`No response`)};if(e.logger?.debug(`[messaging] sendMessage {id=${o.id}} ᐊ─`,{res:c,err:l}),l!=null)throw a(l);return c},onMessage(a,o){if(t??=(e.logger?.debug(`[messaging] "${a}" initialized the message listener for this context`),e.addRootListener(t=>{if(typeof t.type!=`string`||typeof t.timestamp!=`number`)if(e.throwOnUnknownMessageFormat){let n=Error(`[messaging] Unknown message format, must include the 'type' & 'timestamp' fields, received: ${JSON.stringify(t)}`);throw e.logger?.error(n),n}else return;e?.logger?.debug(`[messaging] Received message`,t);let r=n[t.type];if(r!=null)return(async()=>{try{let n=await r(t),i=e.verifyMessageData?.(n)??n;return e?.logger?.debug(`[messaging] onMessage {id=${t.id}} ─ᐅ`,{res:i}),{res:i}}catch(n){return e?.logger?.debug(`[messaging] onMessage {id=${t.id}} ─ᐅ`,{err:n}),{err:i(n)}}})()})),n[a]!=null){let t=Error(`[messaging] In this JS context, only one listener can be setup for ${a}`);throw e.logger?.error(t),t}return n[a]=o,e.logger?.log(`[messaging] Added listener for ${a}`),()=>{delete n[a],r()}},removeAllListeners(){Object.keys(n).forEach(e=>{delete n[e]}),r()}}}function s(e){return o({...e,sendMessage(e,t){if(t==null)return new Promise((t,n)=>chrome.runtime.sendMessage(e,e=>{chrome.runtime.lastError?n(Error(chrome.runtime.lastError.message)):t(e)}));let n=typeof t==`number`?{tabId:t}:t;return new Promise(t=>chrome.tabs.sendMessage(n.tabId,e,n.frameId==null?void 0:{frameId:n.frameId},t))},addRootListener(e){let t=(t,n,r)=>{let i=e(typeof t==`object`?{...t,sender:n}:t);return i instanceof Promise?(i.then(r),!0):!1};return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)}})}function c(e,t){return f(d(e,t))}function l(e,t,n){let r=d(e,n);return r.onMessage(r.messageKey,({data:e})=>{let n=e.path==null?t:m(t??{},e.path);if(n)return Promise.resolve(n.bind(t)(...e.args))})}function u(e){return e?.[p]===!0}function d(e,t){let n=s(t);return{messageKey:`proxy-service.${e}`,...n}}function f(e,t){let n=new Proxy((()=>{}),{async apply(n,r,i){return await e.sendMessage(e.messageKey,{path:t,args:i})},get(n,r,i){return typeof r==`symbol`?Reflect.get(n,r,i):f(e,t==null?[r]:t.concat([r]))}});return n[p]=!0,n}let p=Symbol();function m(e,t){return t.length===0?e:t.reduce((e,t)=>e?.[t],e)}return e.createProxyService=c,e.isProxyService=u,e.registerService=l,e})({});
package/dist/index.mjs ADDED
@@ -0,0 +1,64 @@
1
+ import { defineExtensionMessaging } from "@webext-core/messaging";
2
+ //#region src/index.ts
3
+ /**
4
+ * Create a proxy service that uses the message APIs to proxy function calls to the real service
5
+ * registered in the background with `registerService`.
6
+ *
7
+ * @param key The service key to listen for, must be the same string as the one used in
8
+ * `registerService`.
9
+ */
10
+ function createProxyService(key, config) {
11
+ return createProxy(defineProxyMessaging(key, config));
12
+ }
13
+ /**
14
+ * Sets up message listeners that receive messages from proxies created with `createProxyService`.
15
+ *
16
+ * @param key The service key to listen for, must be the same string as the one used in
17
+ * `createProxyService`.
18
+ * @param realService The real service instance that will handle the requests.
19
+ */
20
+ function registerService(key, realService, config) {
21
+ const messenger = defineProxyMessaging(key, config);
22
+ return messenger.onMessage(messenger.messageKey, ({ data }) => {
23
+ const method = data.path == null ? realService : get(realService ?? {}, data.path);
24
+ if (method) return Promise.resolve(method.bind(realService)(...data.args));
25
+ });
26
+ }
27
+ function isProxyService(obj) {
28
+ return obj?.[ProxyServiceSymbol] === true;
29
+ }
30
+ function defineProxyMessaging(key, config) {
31
+ const messaging = defineExtensionMessaging(config);
32
+ return {
33
+ messageKey: `proxy-service.${key}`,
34
+ ...messaging
35
+ };
36
+ }
37
+ /**
38
+ * Create and returns a "deep" proxy. Every property that is accessed returns another proxy, and
39
+ * when a function is called at any depth, a message is sent to the background.
40
+ */
41
+ function createProxy(messenger, path) {
42
+ const wrapped = (() => {});
43
+ const proxy = new Proxy(wrapped, {
44
+ async apply(_target, _thisArg, args) {
45
+ return await messenger.sendMessage(messenger.messageKey, {
46
+ path,
47
+ args
48
+ });
49
+ },
50
+ get(target, propertyName, receiver) {
51
+ if (typeof propertyName === "symbol") return Reflect.get(target, propertyName, receiver);
52
+ return createProxy(messenger, path == null ? [propertyName] : path.concat([propertyName]));
53
+ }
54
+ });
55
+ proxy[ProxyServiceSymbol] = true;
56
+ return proxy;
57
+ }
58
+ const ProxyServiceSymbol = Symbol();
59
+ function get(obj, path) {
60
+ if (path.length === 0) return obj;
61
+ return path.reduce((acc, key) => acc?.[key], obj);
62
+ }
63
+ //#endregion
64
+ export { createProxyService, isProxyService, registerService };
@@ -0,0 +1,12 @@
1
+ //#region src/types.d.ts
2
+ type Proimsify<T> = T extends Promise<any> ? T : Promise<T>;
3
+ type Service = ((...args: any[]) => Promise<any>) | {
4
+ [key: string]: any | Service;
5
+ };
6
+ /** A recursive type that deeply converts all methods in `TService` to be async. */
7
+ type DeepAsync<TService> = TService extends ((...args: any) => any) ? ToAsyncFunction<TService> : TService extends {
8
+ [key: string]: any;
9
+ } ? { [fn in keyof TService]: DeepAsync<TService[fn]>; } : never;
10
+ type ToAsyncFunction<T extends (...args: any) => any> = (...args: Parameters<T>) => Proimsify<ReturnType<T>>;
11
+ //#endregion
12
+ export { DeepAsync, Proimsify, Service };
package/dist/types.mjs ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,64 +1,69 @@
1
1
  {
2
2
  "name": "@webext-core/proxy-service",
3
- "version": "3.0.0",
3
+ "version": "3.0.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
- "license": "MIT",
6
5
  "keywords": [
7
- "web-extension",
6
+ "browser",
8
7
  "browser-extension",
9
- "chrome-extension",
10
- "webext",
11
- "web-ext",
12
8
  "chrome",
13
- "firefox",
14
- "safari",
15
- "browser",
9
+ "chrome-extension",
16
10
  "extension",
11
+ "firefox",
17
12
  "rpc",
18
- "service"
13
+ "safari",
14
+ "service",
15
+ "web-ext",
16
+ "web-extension",
17
+ "webext"
19
18
  ],
20
19
  "homepage": "https://github.com/aklinker1/webext-core/tree/main/packages/proxy-service",
20
+ "license": "MIT",
21
21
  "repository": {
22
22
  "type": "git",
23
- "url": "https://github.com/aklinker1/webext-core",
23
+ "url": "git+https://github.com/aklinker1/webext-core.git",
24
24
  "directory": "packages/proxy-service"
25
25
  },
26
- "type": "module",
27
- "publishConfig": {
28
- "access": "public"
29
- },
30
26
  "files": [
31
- "lib"
27
+ "dist"
32
28
  ],
33
- "main": "lib/index.cjs",
34
- "module": "lib/index.js",
35
- "types": "lib/index.d.ts",
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "module": "dist/index.mjs",
32
+ "types": "dist/index.d.mts",
36
33
  "exports": {
37
34
  ".": {
38
- "types": "./lib/index.d.ts",
39
- "default": "./lib/index.js"
35
+ "types": "./dist/index.d.mts",
36
+ "default": "./dist/index.mjs"
40
37
  },
41
- "./types": "./lib/types.d.ts"
38
+ "./types": {
39
+ "types": "./dist/types.d.mts",
40
+ "default": "./dist/types.mjs"
41
+ }
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
42
45
  },
43
46
  "scripts": {
44
- "build": "buildc -- tsup",
45
- "test": "buildc --deps-only -- vitest -r src",
46
- "test:coverage": "buildc --deps-only -- vitest run -r src --coverage",
47
- "check": "buildc --deps-only -- tsc --noEmit"
47
+ "build": "buildc -- tsdown",
48
+ "test": "buildc --deps-only -- bun test",
49
+ "test:coverage": "buildc --deps-only -- bun test --coverage",
50
+ "check": "bun run build && check",
51
+ "prepack": "bun run build"
48
52
  },
49
53
  "devDependencies": {
54
+ "@types/chrome": "catalog:",
50
55
  "@types/get-value": "^3.0.3",
51
- "@types/webextension-polyfill": "^0.9.1",
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"
56
+ "@webext-core/fake-browser": "workspace:*",
57
+ "@webext-core/messaging": "workspace:*",
58
+ "publint": "catalog:",
59
+ "tsconfig": "workspace:*",
60
+ "tsdown": "catalog:",
61
+ "typescript": "catalog:"
56
62
  },
57
63
  "peerDependencies": {
58
- "webextension-polyfill": ">=0.10.0",
59
64
  "@webext-core/messaging": ">=1.3.1"
60
65
  },
61
- "buildc": {
62
- "outDir": "lib"
66
+ "engines": {
67
+ "node": "*"
63
68
  }
64
69
  }