@webview-bridge/web 1.6.2 → 1.7.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@webview-bridge/web",
3
3
  "type": "module",
4
- "version": "1.6.2",
4
+ "version": "1.7.0-rc.1",
5
5
  "description": "Fully Type-Safe Integration for React Native WebView and Web",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -15,21 +15,22 @@
15
15
  "dist",
16
16
  "package.json"
17
17
  ],
18
- "main": "dist/commonjs/index.cjs",
19
- "module": "dist/module/index.mjs",
20
- "types": "dist/typescript/packages/web/src/index.d.ts",
18
+ "main": "dist/index.js",
19
+ "module": "dist/index.cjs",
20
+ "types": "dist/index.d.ts",
21
21
  "exports": {
22
22
  ".": {
23
- "types": "./dist/typescript/packages/web/src/index.d.ts",
24
- "import": "./dist/module/index.mjs",
25
- "require": "./dist/commonjs/index.cjs"
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "require": "./dist/index.cjs"
26
26
  }
27
27
  },
28
- "devDependencies": {
29
- "esbuild": "^0.19.4"
28
+ "dependencies": {
29
+ "@webview-bridge/utils": "1.7.0-rc.1",
30
+ "@webview-bridge/types": "1.7.0-rc.1"
30
31
  },
31
32
  "scripts": {
32
- "build": "node esbuild.config.js && tspc --emitDeclarationOnly",
33
+ "build": "tsup src/index.ts --format cjs,esm --dts --target es5",
33
34
  "test:type": "tsc --noEmit"
34
35
  }
35
36
  }
@@ -1 +0,0 @@
1
- "use strict";var b=Object.defineProperty,A=Object.defineProperties,D=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertyNames,T=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var O=(t,e,r)=>e in t?b(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,u=(t,e)=>{for(var r in e||(e={}))M.call(e,r)&&O(t,r,e[r]);if(T)for(var r of T(e))I.call(e,r)&&O(t,r,e[r]);return t},_=(t,e)=>A(t,K(e));var C=(t,e)=>{for(var r in e)b(t,r,{get:e[r],enumerable:!0})},$=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of J(e))!M.call(t,i)&&i!==r&&b(t,i,{get:()=>e[i],enumerable:!(s=D(e,i))||s.enumerable});return t};var H=t=>$(b({},"__esModule",{value:!0}),t);var p=(t,e,r)=>(O(t,typeof e!="symbol"?e+"":e,r),r);var P=(t,e,r)=>new Promise((s,i)=>{var n=o=>{try{g(r.next(o))}catch(l){i(l)}},d=o=>{try{g(r.throw(o))}catch(l){i(l)}},g=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,d);g((r=r.apply(t,e)).next())});var U={};C(U,{MethodNotFoundError:()=>w,NativeMethodError:()=>h,linkBridge:()=>q,registerWebMethod:()=>G});module.exports=H(U);var w=class extends Error{constructor(e){super(`Method ${e} is not defined`),this.name="MethodNotFoundError"}},h=class extends Error{constructor(e){super(`An error occurred in the native bridge: ${e}`),this.name="NativeMethodError"}};var y=()=>({events:{},emit(t,...e){let r=this.events[t]||[];for(let s=0,i=r.length;s<i;s++)r[s](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var s;this.events[t]=(s=this.events[t])==null?void 0:s.filter(i=>e!==i)}}}),k=({emitter:t,evaluate:e,eventId:r,failHandler:s=!1,methodName:i,onFallback:n})=>new Promise((d,g)=>{let o=t.on(`${i}-${r}`,(l,a)=>{o(),a?s instanceof Error?(n==null||n(),g(s)):d(void 0):d(l)});e()});var V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var L=(t=21)=>Array.from({length:t},()=>V[Math.floor(Math.random()*V.length)]).join("");var E=(t,e)=>{if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){let r=Array.isArray(t),s=Array.isArray(e),i,n,d;if(r&&s){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!E(t[i],e[i]))return!1;return!0}if(r!==s)return!1;let g=Object.keys(t);if(n=g.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,g[i]))return!1;for(i=n;i--!==0;)if(d=g[i],!E(t[d],e[d]))return!1;return!0}return t!==t&&e!==e};var N=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var j=(t,e=!0)=>new Promise((r,s)=>{setTimeout(()=>{e?s(new Error("Timeout")):r(void 0)},t)});var W=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var R=(t,e={})=>{let r=()=>i,s=o=>{let l=u(u({},i),N(o));if(E(i,l))return;let a=i;i=l,d(i,a)};t.on("bridgeStateChange",o=>{s(o)});let i=u({},e),n=new Set,d=(o,l)=>{for(let a of n)a(o,l)};return{getState:r,subscribe:o=>(n.add(o),()=>n.delete(o))}};var S=(t={})=>{let e=t;return{getState:()=>e,subscribe:()=>()=>{}}};var x=class{constructor(e,r,s=[],i){this._options=e;this._emitter=r;this._bridgeMethods=s;this._nativeInitialState=i;p(this,"_defaultTimeoutMs",2e3);p(this,"_isListenerRegistered",!1);p(this,"store",S());p(this,"loose",W());this._hydrate(s,i)}get isReactNativeWebView(){return!!window.ReactNativeWebView}get isWebViewBridgeAvailable(){return this._bridgeMethods.length>0}isNativeMethodAvailable(e){return typeof e=="string"&&this._bridgeMethods.includes(e)}addEventListener(e,r){return this._emitter.on(`postMessage/${String(e)}`,r)}_postMessage(e,r){var s;(s=window.ReactNativeWebView)==null||s.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,s,i){return(...n)=>{let d=L();return Promise.race([k({emitter:this._emitter,methodName:e,eventId:d,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:d,args:n})},onFallback:()=>{i==null||i(e,n)},failHandler:r&&new h(e)}),s>0&&j(s,r)].filter(Boolean))}}_willMethodThrowOnError(e){let{throwOnError:r}=this._options;return r===!0||Array.isArray(r)&&r.includes(e)}_createLoose(e){let{timeout:r=this._defaultTimeoutMs,onFallback:s}=this._options;return new Proxy(e,{get:(i,n)=>n in i&&!["isWebViewBridgeAvailable","isNativeMethodAvailable"].includes(n)?i[n]:this._createNativeMethod(n,this._willMethodThrowOnError(n),r,s)})}_hydrate(e,r={}){var l;let{timeout:s=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,d=Object.entries(n).filter(([a,c])=>typeof c=="function"),g=d.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(d.map(([a,c])=>[a,{value:c,writable:!0}]))),this._bridgeMethods=[...e,...g],this._nativeInitialState=r;let o=e.reduce((a,c)=>{if(!this.isReactNativeWebView)return a;let f=this._createNativeMethod(c,this._willMethodThrowOnError(c),s,i);return Object.defineProperty(this,c,{value:f,writable:!1}),_(u({},a),{[c]:f})},n);if(this.loose=this._createLoose(o),this.store=R(this._emitter,u(u({},o),r)),!this._isListenerRegistered){let a=()=>{document.visibilityState==="visible"&&this._postMessage("getBridgeState")};document.addEventListener("visibilitychange",a),this._isListenerRegistered=!0}this._postMessage("getBridgeState");for(let[a,...c]of(l=window.nativeBatchedEvents)!=null?l:[])this._emitter.emit(a,...c);return window.nativeBatchedEvents=[],!0}};var q=(t={timeout:2e3,throwOnError:!1})=>{var o,l,a;if(typeof window=="undefined"){let c=(o=t==null?void 0:t.initialBridge)!=null?o:{},v=Object.entries(c).filter(([m,B])=>typeof B=="function").map(([m])=>m);return{addEventListener:(m,B)=>()=>{},loose:{},isWebViewBridgeAvailable:v.length>0,isNativeMethodAvailable:m=>v.includes(m),store:S(t==null?void 0:t.initialBridge)}}window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=y();window.nativeEmitter||(window.nativeEmitter=e);let r=(l=window.__bridgeMethods__)!=null?l:[],s=(a=window.__bridgeInitialState__)!=null?a:{},i=new x(t,e,r,s);if(r.length===0){let c=e.on("hydrate",({bridgeMethods:f,nativeInitialState:v})=>{i._hydrate(f,v),c()})}let{onFallback:n,onReady:d}=t,g=new Proxy(i,{get:(c,f,v)=>f in c?c[f]:(v._postMessage("fallback",{method:f}),v._willMethodThrowOnError(f)?(...m)=>(n==null||n(f,m),Promise.reject(new w(f))):(console.warn(`[WebViewBridge] ${f} is not defined, using fallback.`),()=>Promise.resolve()))});return d==null||d(g),g};var G=t=>{if(typeof window!="undefined"&&!window.ReactNativeWebView)return console.warn("[WebViewBridge] Not in a WebView environment"),t;let e=Object.entries(t),r=Object.keys(t),s=y();window.webEmitter=s;for(let[n,d]of e){let g=(o,l)=>P(void 0,null,function*(){var a,c;try{let f=yield d(...l);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:o,value:f}}))}catch(f){(c=window.ReactNativeWebView)==null||c.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:o,error:JSON.stringify(f)}}))}});s.on(n,g)}let i=()=>{var n;(n=window.ReactNativeWebView)==null||n.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})),window.removeEventListener("DOMContentLoaded",i)};return window.ReactNativeWebView?(document.addEventListener("visibilitychange",()=>{var n;document.visibilityState==="visible"&&((n=window.ReactNativeWebView)==null||n.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})))}),i(),t):(window.addEventListener("DOMContentLoaded",i),t)};0&&(module.exports={MethodNotFoundError,NativeMethodError,linkBridge,registerWebMethod});
@@ -1 +0,0 @@
1
- var W=Object.defineProperty,R=Object.defineProperties;var A=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var x=(t,e,r)=>e in t?W(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,u=(t,e)=>{for(var r in e||(e={}))D.call(e,r)&&x(t,r,e[r]);if(B)for(var r of B(e))K.call(e,r)&&x(t,r,e[r]);return t},T=(t,e)=>R(t,A(e));var p=(t,e,r)=>(x(t,typeof e!="symbol"?e+"":e,r),r);var M=(t,e,r)=>new Promise((s,i)=>{var n=o=>{try{g(r.next(o))}catch(l){i(l)}},d=o=>{try{g(r.throw(o))}catch(l){i(l)}},g=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,d);g((r=r.apply(t,e)).next())});var w=class extends Error{constructor(e){super(`Method ${e} is not defined`),this.name="MethodNotFoundError"}},h=class extends Error{constructor(e){super(`An error occurred in the native bridge: ${e}`),this.name="NativeMethodError"}};var b=()=>({events:{},emit(t,...e){let r=this.events[t]||[];for(let s=0,i=r.length;s<i;s++)r[s](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var s;this.events[t]=(s=this.events[t])==null?void 0:s.filter(i=>e!==i)}}}),_=({emitter:t,evaluate:e,eventId:r,failHandler:s=!1,methodName:i,onFallback:n})=>new Promise((d,g)=>{let o=t.on(`${i}-${r}`,(l,a)=>{o(),a?s instanceof Error?(n==null||n(),g(s)):d(void 0):d(l)});e()});var P="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var k=(t=21)=>Array.from({length:t},()=>P[Math.floor(Math.random()*P.length)]).join("");var y=(t,e)=>{if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){let r=Array.isArray(t),s=Array.isArray(e),i,n,d;if(r&&s){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!y(t[i],e[i]))return!1;return!0}if(r!==s)return!1;let g=Object.keys(t);if(n=g.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,g[i]))return!1;for(i=n;i--!==0;)if(d=g[i],!y(t[d],e[d]))return!1;return!0}return t!==t&&e!==e};var V=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var L=(t,e=!0)=>new Promise((r,s)=>{setTimeout(()=>{e?s(new Error("Timeout")):r(void 0)},t)});var N=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var j=(t,e={})=>{let r=()=>i,s=o=>{let l=u(u({},i),V(o));if(y(i,l))return;let a=i;i=l,d(i,a)};t.on("bridgeStateChange",o=>{s(o)});let i=u({},e),n=new Set,d=(o,l)=>{for(let a of n)a(o,l)};return{getState:r,subscribe:o=>(n.add(o),()=>n.delete(o))}};var E=(t={})=>{let e=t;return{getState:()=>e,subscribe:()=>()=>{}}};var S=class{constructor(e,r,s=[],i){this._options=e;this._emitter=r;this._bridgeMethods=s;this._nativeInitialState=i;p(this,"_defaultTimeoutMs",2e3);p(this,"_isListenerRegistered",!1);p(this,"store",E());p(this,"loose",N());this._hydrate(s,i)}get isReactNativeWebView(){return!!window.ReactNativeWebView}get isWebViewBridgeAvailable(){return this._bridgeMethods.length>0}isNativeMethodAvailable(e){return typeof e=="string"&&this._bridgeMethods.includes(e)}addEventListener(e,r){return this._emitter.on(`postMessage/${String(e)}`,r)}_postMessage(e,r){var s;(s=window.ReactNativeWebView)==null||s.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,s,i){return(...n)=>{let d=k();return Promise.race([_({emitter:this._emitter,methodName:e,eventId:d,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:d,args:n})},onFallback:()=>{i==null||i(e,n)},failHandler:r&&new h(e)}),s>0&&L(s,r)].filter(Boolean))}}_willMethodThrowOnError(e){let{throwOnError:r}=this._options;return r===!0||Array.isArray(r)&&r.includes(e)}_createLoose(e){let{timeout:r=this._defaultTimeoutMs,onFallback:s}=this._options;return new Proxy(e,{get:(i,n)=>n in i&&!["isWebViewBridgeAvailable","isNativeMethodAvailable"].includes(n)?i[n]:this._createNativeMethod(n,this._willMethodThrowOnError(n),r,s)})}_hydrate(e,r={}){var l;let{timeout:s=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,d=Object.entries(n).filter(([a,c])=>typeof c=="function"),g=d.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(d.map(([a,c])=>[a,{value:c,writable:!0}]))),this._bridgeMethods=[...e,...g],this._nativeInitialState=r;let o=e.reduce((a,c)=>{if(!this.isReactNativeWebView)return a;let f=this._createNativeMethod(c,this._willMethodThrowOnError(c),s,i);return Object.defineProperty(this,c,{value:f,writable:!1}),T(u({},a),{[c]:f})},n);if(this.loose=this._createLoose(o),this.store=j(this._emitter,u(u({},o),r)),!this._isListenerRegistered){let a=()=>{document.visibilityState==="visible"&&this._postMessage("getBridgeState")};document.addEventListener("visibilitychange",a),this._isListenerRegistered=!0}this._postMessage("getBridgeState");for(let[a,...c]of(l=window.nativeBatchedEvents)!=null?l:[])this._emitter.emit(a,...c);return window.nativeBatchedEvents=[],!0}};var be=(t={timeout:2e3,throwOnError:!1})=>{var o,l,a;if(typeof window=="undefined"){let c=(o=t==null?void 0:t.initialBridge)!=null?o:{},v=Object.entries(c).filter(([m,O])=>typeof O=="function").map(([m])=>m);return{addEventListener:(m,O)=>()=>{},loose:{},isWebViewBridgeAvailable:v.length>0,isNativeMethodAvailable:m=>v.includes(m),store:E(t==null?void 0:t.initialBridge)}}window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=b();window.nativeEmitter||(window.nativeEmitter=e);let r=(l=window.__bridgeMethods__)!=null?l:[],s=(a=window.__bridgeInitialState__)!=null?a:{},i=new S(t,e,r,s);if(r.length===0){let c=e.on("hydrate",({bridgeMethods:f,nativeInitialState:v})=>{i._hydrate(f,v),c()})}let{onFallback:n,onReady:d}=t,g=new Proxy(i,{get:(c,f,v)=>f in c?c[f]:(v._postMessage("fallback",{method:f}),v._willMethodThrowOnError(f)?(...m)=>(n==null||n(f,m),Promise.reject(new w(f))):(console.warn(`[WebViewBridge] ${f} is not defined, using fallback.`),()=>Promise.resolve()))});return d==null||d(g),g};var Se=t=>{if(typeof window!="undefined"&&!window.ReactNativeWebView)return console.warn("[WebViewBridge] Not in a WebView environment"),t;let e=Object.entries(t),r=Object.keys(t),s=b();window.webEmitter=s;for(let[n,d]of e){let g=(o,l)=>M(void 0,null,function*(){var a,c;try{let f=yield d(...l);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:o,value:f}}))}catch(f){(c=window.ReactNativeWebView)==null||c.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:o,error:JSON.stringify(f)}}))}});s.on(n,g)}let i=()=>{var n;(n=window.ReactNativeWebView)==null||n.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})),window.removeEventListener("DOMContentLoaded",i)};return window.ReactNativeWebView?(document.addEventListener("visibilitychange",()=>{var n;document.visibilityState==="visible"&&((n=window.ReactNativeWebView)==null||n.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})))}),i(),t):(window.addEventListener("DOMContentLoaded",i),t)};export{w as MethodNotFoundError,h as NativeMethodError,be as linkBridge,Se as registerWebMethod};
@@ -1,6 +0,0 @@
1
- export declare class MethodNotFoundError extends Error {
2
- constructor(methodName: string);
3
- }
4
- export declare class NativeMethodError extends Error {
5
- constructor(methodName: string);
6
- }
@@ -1,5 +0,0 @@
1
- export * from "./error";
2
- export * from "./linkBridge";
3
- export * from "./registerWebMethod";
4
- export type * from "./types";
5
- export * from "../../../shared/util/src/types";
@@ -1,24 +0,0 @@
1
- import type { Bridge, BridgeStore, ExtractStore, KeyOfOrString, Parser, ParserSchema, PrimitiveObject } from "../../../../shared/util/src/types";
2
- import { DefaultEmitter } from "../../../../shared/util/src";
3
- import { LinkBridgeOptions } from "../linkBridge";
4
- import { LinkBridge } from "../types";
5
- export declare class BridgeInstance<T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any> = ParserSchema<any>> {
6
- private _options;
7
- private _emitter;
8
- private _bridgeMethods;
9
- _nativeInitialState: PrimitiveObject;
10
- constructor(_options: LinkBridgeOptions<T, V>, _emitter: DefaultEmitter, _bridgeMethods: string[], _nativeInitialState: PrimitiveObject);
11
- private _defaultTimeoutMs;
12
- private _isListenerRegistered;
13
- store: Omit<T, "setState">;
14
- get isReactNativeWebView(): boolean;
15
- get isWebViewBridgeAvailable(): boolean;
16
- isNativeMethodAvailable(methodName: string): boolean;
17
- addEventListener<EventName extends KeyOfOrString<V>>(eventName: EventName, listener: (args: Parser<V, EventName>) => void): () => void;
18
- loose: LinkBridge<ExtractStore<T>, Omit<T, "setState">, V>;
19
- private _postMessage;
20
- private _createNativeMethod;
21
- private _willMethodThrowOnError;
22
- private _createLoose;
23
- _hydrate(bridgeMethods: string[], nativeInitialState?: PrimitiveObject): boolean;
24
- }
@@ -1 +0,0 @@
1
- export declare const createPromiseProxy: () => {};
@@ -1,7 +0,0 @@
1
- import { Bridge, BridgeStore, OnlyJSON } from "../../../../shared/util/src/types";
2
- import { DefaultEmitter } from "../../../../shared/util/src";
3
- export type Store<BridgeObject extends Bridge> = ({ get, set, }: {
4
- get: () => BridgeObject;
5
- set: (newState: Partial<OnlyJSON<BridgeObject>>) => void;
6
- }) => BridgeObject;
7
- export declare const linkBridgeStore: <T extends BridgeStore<T extends Bridge ? T : any>>(emitter: DefaultEmitter, initialState?: Partial<T>) => Omit<T, "setState">;
@@ -1,5 +0,0 @@
1
- import { PrimitiveObject } from "../../../../shared/util/src/types";
2
- export declare const mockStore: (initialState?: PrimitiveObject) => {
3
- getState: () => PrimitiveObject;
4
- subscribe: () => () => void;
5
- };
@@ -1,33 +0,0 @@
1
- import type { Bridge, BridgeStore, ExcludePrimitive, ExtractStore, ParserSchema } from "../../../shared/util/src/types";
2
- import { LinkBridge } from "./types";
3
- export interface LinkBridgeOptions<T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any>> {
4
- /**
5
- * It is possible to configure `initialBridge` to operate in a non-React Native environment.
6
- * Prioritize applying the bridge of the React Native WebView, and if it is unavailable, apply the `initialBridge`.
7
- * Therefore, if `initialBridge` is configured, `bridge.isWebViewBridgeAvailable` should be true even in environments that are not React Native.
8
- * @link https://gronxb.github.io/webview-bridge/non-react-native-environment.html
9
- */
10
- initialBridge?: Partial<ExtractStore<T>>;
11
- /**
12
- * Set the timeout in milliseconds after calling the native method.
13
- * @default 2000
14
- */
15
- timeout?: number;
16
- /**
17
- * If `true`, an error will be thrown when calling a method that is not defined in the bridge.
18
- */
19
- throwOnError?: boolean | (keyof ExtractStore<T>)[] | string[];
20
- /**
21
- * Callback function when a method that is not defined in the bridge is called.
22
- */
23
- onFallback?: (methodName: string, args: unknown[]) => void;
24
- /**
25
- * Callback function when the bridge is ready.
26
- */
27
- onReady?: (method: LinkBridge<ExcludePrimitive<ExtractStore<T>>, Omit<T, "setState">, V>) => void;
28
- }
29
- /**
30
- * Create a link to the bridge connected to the React Native WebView.
31
- * @link https://gronxb.github.io/webview-bridge/getting-started.html
32
- */
33
- export declare const linkBridge: <T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any> = ParserSchema<any>>(options?: LinkBridgeOptions<T, V>) => LinkBridge<ExcludePrimitive<ExtractStore<T>>, Omit<T, "setState">, V>;
@@ -1,24 +0,0 @@
1
- import type { WebBridge } from "./types";
2
- /**
3
- * @deprecated Use `bridge.addEventListener` instead.
4
- * @see https://gronxb.github.io/webview-bridge/using-a-post-message.html
5
- * @example
6
- import { linkBridge } from "@webview-bridge/web";
7
- import type { AppBridge, AppPostMessageSchema } from ""; // Import the type 'appBridge' and 'appPostMessageSchema' declared in native
8
-
9
- const bridge = linkBridge<AppBridge, AppPostMessageSchema>({
10
- // ..
11
- });
12
-
13
- const unsubscribe = bridge.addEventListener("eventName1", (data) => {
14
- window.alert(data.message);
15
- });
16
- unsubscribe(); // Unsubscribe from the event
17
-
18
-
19
- const unsubscribe2 = bridge.addEventListener("eventName2", (message) => {
20
- window.alert(message);
21
- });
22
- unsubscribe2(); // Unsubscribe from the event
23
- */
24
- export declare const registerWebMethod: <BridgeObject extends WebBridge>(bridge: BridgeObject) => BridgeObject;
@@ -1,14 +0,0 @@
1
- import type { AsyncFunction, KeyOfOrString, Parser, ParserSchema } from "../../../../shared/util/src/types";
2
- export type WebBridge = Record<string, AsyncFunction>;
3
- export type LinkBridge<T, U, V extends ParserSchema<any>> = {
4
- isWebViewBridgeAvailable: boolean;
5
- isNativeMethodAvailable(method: keyof T): boolean;
6
- isNativeMethodAvailable(method: string): boolean;
7
- store: U;
8
- addEventListener<EventName extends KeyOfOrString<V>>(eventName: EventName, listener: (args: Parser<V, EventName>) => void): () => void;
9
- loose: {
10
- [K in keyof T]: (...args: any[]) => Promise<any>;
11
- } & {
12
- [key: string]: (...args: any[]) => Promise<any>;
13
- };
14
- } & T;
@@ -1,25 +0,0 @@
1
- interface EventsMap {
2
- [event: string]: any;
3
- }
4
- export interface DefaultEvents extends EventsMap {
5
- [event: string]: (...args: any) => void;
6
- }
7
- export interface EventEmitter<Events extends EventsMap = DefaultEvents> {
8
- emit<K extends keyof Events>(this: this, event: K, ...args: Parameters<Events[K]>): void;
9
- events: Partial<{
10
- [E in keyof Events]: Events[E][];
11
- }>;
12
- on<K extends keyof Events>(this: this, event: K, cb: Events[K]): () => void;
13
- }
14
- export type DefaultEmitter = EventEmitter<DefaultEvents>;
15
- export declare const createEvents: <Events extends EventsMap = DefaultEvents>() => EventEmitter<Events>;
16
- export interface CreateResolverOptions {
17
- emitter: DefaultEmitter;
18
- evaluate: () => void;
19
- eventId: string;
20
- failHandler?: Error | false;
21
- methodName: string;
22
- onFallback?: () => void;
23
- }
24
- export declare const createResolver: ({ emitter, evaluate, eventId, failHandler, methodName, onFallback, }: CreateResolverOptions) => Promise<unknown>;
25
- export {};
@@ -1 +0,0 @@
1
- export declare const createRandomId: (size?: number) => string;
@@ -1 +0,0 @@
1
- export declare const equals: (a: any, b: any) => boolean;
@@ -1,6 +0,0 @@
1
- export * from "./createEvents";
2
- export * from "./createRandomId";
3
- export * from "./equals";
4
- export * from "./noop";
5
- export * from "./removeUndefinedKeys";
6
- export * from "./timeout";
@@ -1 +0,0 @@
1
- export declare const noop: () => void;
@@ -1 +0,0 @@
1
- export declare const removeUndefinedKeys: (obj: Record<string, any>) => Record<string, any>;
@@ -1 +0,0 @@
1
- export declare const timeout: (ms: number, throwOnError?: boolean) => Promise<unknown>;
@@ -1,36 +0,0 @@
1
- import type { Infer as SupertructInfer, Struct } from "superstruct";
2
- import type { AnySchema as YupTypeAny, InferType as yupInfer } from "yup";
3
- import type { infer as zodInfer, ZodTypeAny } from "zod";
4
- export type AsyncFunction = (...args: any[]) => Promise<any>;
5
- export type Primitive = string | number | boolean | null | undefined;
6
- export type PrimitiveObject = Record<string, Primitive>;
7
- export type RawJSON = Primitive | {
8
- [key: string]: RawJSON;
9
- } | RawJSONArray;
10
- interface RawJSONArray extends Array<RawJSON> {
11
- }
12
- export type Bridge = Record<string, AsyncFunction | RawJSON>;
13
- export type BridgeStore<T extends Bridge> = {
14
- getState: () => T;
15
- setState: (newState: Partial<OnlyJSON<T>>) => void;
16
- subscribe: (listener: (newState: T, prevState: T) => void) => () => void;
17
- };
18
- export type ExtractStore<S> = S extends {
19
- getState: () => infer T;
20
- } ? T : never;
21
- export type OnlyJSON<T> = {
22
- [P in keyof T as T[P] extends RawJSON ? P : never]: T[P];
23
- };
24
- export type ExcludePrimitive<T> = {
25
- [P in keyof T as T[P] extends RawJSON ? never : P]: T[P];
26
- };
27
- export type KeyOfOrString<T> = T extends undefined ? string : keyof T;
28
- export type PostMessageSchemaObject = Record<string, ZodTypeAny | YupTypeAny | Struct<any>>;
29
- export type ParserSchema<T = object> = {
30
- [P in keyof T]: {
31
- parse: (data: any) => any;
32
- schema: T[P];
33
- };
34
- };
35
- export type Parser<Input extends ParserSchema<any>, EventName> = Input extends undefined ? Record<string, Primitive> | Primitive : EventName extends keyof Input ? Input[EventName]["schema"] extends ZodTypeAny ? zodInfer<Input[EventName]["schema"]> : Input[EventName]["schema"] extends YupTypeAny ? yupInfer<Input[EventName]["schema"]> : Input[EventName]["schema"] extends Struct<any> ? SupertructInfer<Input[EventName]["schema"]> : Record<string, Primitive> | Primitive : never;
36
- export {};