@webview-bridge/web 1.5.3 → 1.6.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/dist/commonjs/index.cjs +1 -1
- package/dist/module/index.mjs +1 -1
- package/dist/typescript/packages/web/src/index.d.ts +0 -1
- package/dist/typescript/packages/web/src/internal/bridgeInstance.d.ts +5 -3
- package/dist/typescript/packages/web/src/internal/linkBridgeStore.d.ts +1 -1
- package/dist/typescript/packages/web/src/internal/mockStore.d.ts +4 -4
- package/dist/typescript/packages/web/src/linkBridge.d.ts +1 -0
- package/package.json +1 -1
- package/dist/typescript/packages/web/src/linkNativeMethod.d.ts +0 -7
package/dist/commonjs/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var w=Object.defineProperty,W=Object.defineProperties,R=Object.getOwnPropertyDescriptor,A=Object.getOwnPropertyDescriptors,D=Object.getOwnPropertyNames,x=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var S=(t,e,r)=>e in t?w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,f=(t,e)=>{for(var r in e||(e={}))O.call(e,r)&&S(t,r,e[r]);if(x)for(var r of x(e))K.call(e,r)&&S(t,r,e[r]);return t},T=(t,e)=>W(t,A(e));var J=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},I=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of D(e))!O.call(t,i)&&i!==r&&w(t,i,{get:()=>e[i],enumerable:!(s=R(e,i))||s.enumerable});return t};var C=t=>I(w({},"__esModule",{value:!0}),t);var m=(t,e,r)=>(S(t,typeof e!="symbol"?e+"":e,r),r);var B=(t,e,r)=>new Promise((s,i)=>{var n=o=>{try{l(r.next(o))}catch(g){i(g)}},c=o=>{try{l(r.throw(o))}catch(g){i(g)}},l=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,c);l((r=r.apply(t,e)).next())});var q={};J(q,{MethodNotFoundError:()=>v,NativeMethodError:()=>p,linkBridge:()=>$,registerWebMethod:()=>H});module.exports=C(q);var v=class extends Error{constructor(e){super(`Method ${e} is not defined`),this.name="MethodNotFoundError"}},p=class extends Error{constructor(e){super(`An error occurred in the native bridge: ${e}`),this.name="NativeMethodError"}};var h=()=>({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)}}}),M=({emitter:t,evaluate:e,eventId:r,failHandler:s=!1,methodName:i,onFallback:n})=>new Promise((c,l)=>{let o=t.on(`${i}-${r}`,(g,a)=>{o(),a?s instanceof Error?(n==null||n(),l(s)):c(void 0):c(g)});e()});var _="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var P=(t=21)=>Array.from({length:t},()=>_[Math.floor(Math.random()*_.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,c;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 l=Object.keys(t);if(n=l.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,l[i]))return!1;for(i=n;i--!==0;)if(c=l[i],!y(t[c],e[c]))return!1;return!0}return t!==t&&e!==e};var k=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var V=(t,e=!0)=>new Promise((r,s)=>{setTimeout(()=>{e?s(new Error("Timeout")):r(void 0)},t)});var L=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var j=(t,e={})=>{let r=()=>i,s=o=>{let g=f(f({},i),k(o));if(y(i,g))return;let a=i;i=g,c(i,a)};t.on("bridgeStateChange",o=>{s(o)});let i=f({},e),n=new Set,c=(o,g)=>{for(let a of n)a(o,g)};return{getState:r,subscribe:o=>(n.add(o),()=>n.delete(o))}};var b=(t={})=>{let e=t;return{getState:()=>e,subscribe:()=>()=>{}}};var E=class{constructor(e,r,s=[],i){this._options=e;this._emitter=r;this._bridgeMethods=s;this._nativeInitialState=i;m(this,"_defaultTimeoutMs",2e3);m(this,"_isListenerRegistered",!1);m(this,"store",b());m(this,"loose",L());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 c=P();return Promise.race([M({emitter:this._emitter,methodName:e,eventId:c,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:c,args:n})},onFallback:()=>{i==null||i(e,n)},failHandler:r&&new p(e)}),s>0&&V(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 g;let{timeout:s=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,c=Object.entries(n).filter(([a,d])=>typeof d=="function"),l=c.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(c.map(([a,d])=>[a,{value:d,writable:!0}]))),this._bridgeMethods=[...e,...l],this._nativeInitialState=r;let o=e.reduce((a,d)=>{if(!this.isReactNativeWebView)return a;let u=this._createNativeMethod(d,this._willMethodThrowOnError(d),s,i);return Object.defineProperty(this,d,{value:u,writable:!1}),T(f({},a),{[d]:u})},n);if(this.loose=this._createLoose(o),this.store=j(this._emitter,f(f({},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,...d]of(g=window.nativeBatchedEvents)!=null?g:[])this._emitter.emit(a,...d);return window.nativeBatchedEvents=[],!0}};var $=(t={timeout:2e3,throwOnError:!1})=>{var o,g;if(typeof window=="undefined")return{store:b(t==null?void 0:t.initialBridge)};window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=h();window.nativeEmitter||(window.nativeEmitter=e);let r=(o=window.__bridgeMethods__)!=null?o:[],s=(g=window.__bridgeInitialState__)!=null?g:{},i=new E(t,e,r,s);if(r.length===0){let a=e.on("hydrate",({bridgeMethods:d,nativeInitialState:u})=>{i._hydrate(d,u),a()})}let{onFallback:n,onReady:c}=t,l=new Proxy(i,{get:(a,d,u)=>d in a?a[d]:(u._postMessage("fallback",{method:d}),u._willMethodThrowOnError(d)?(...N)=>(n==null||n(d,N),Promise.reject(new v(d))):(console.warn(`[WebViewBridge] ${d} is not defined, using fallback.`),()=>Promise.resolve()))});return c==null||c(l),l};var H=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=h();window.webEmitter=s;for(let[n,c]of e){let l=(o,g)=>B(void 0,null,function*(){var a,d;try{let u=yield c(...g);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:o,value:u}}))}catch(u){(d=window.ReactNativeWebView)==null||d.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:o,error:JSON.stringify(u)}}))}});s.on(n,l)}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});
|
package/dist/module/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty,N=Object.defineProperties;var W=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable;var E=(t,e,r)=>e in t?j(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,f=(t,e)=>{for(var r in e||(e={}))R.call(e,r)&&E(t,r,e[r]);if(S)for(var r of S(e))A.call(e,r)&&E(t,r,e[r]);return t},x=(t,e)=>N(t,W(e));var m=(t,e,r)=>(E(t,typeof e!="symbol"?e+"":e,r),r);var O=(t,e,r)=>new Promise((s,i)=>{var n=o=>{try{l(r.next(o))}catch(g){i(g)}},c=o=>{try{l(r.throw(o))}catch(g){i(g)}},l=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,c);l((r=r.apply(t,e)).next())});var v=class extends Error{constructor(e){super(`Method ${e} is not defined`),this.name="MethodNotFoundError"}},p=class extends Error{constructor(e){super(`An error occurred in the native bridge: ${e}`),this.name="NativeMethodError"}};var w=()=>({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)}}}),T=({emitter:t,evaluate:e,eventId:r,failHandler:s=!1,methodName:i,onFallback:n})=>new Promise((c,l)=>{let o=t.on(`${i}-${r}`,(g,a)=>{o(),a?s instanceof Error?(n==null||n(),l(s)):c(void 0):c(g)});e()});var B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var M=(t=21)=>Array.from({length:t},()=>B[Math.floor(Math.random()*B.length)]).join("");var h=(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,c;if(r&&s){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!h(t[i],e[i]))return!1;return!0}if(r!==s)return!1;let l=Object.keys(t);if(n=l.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,l[i]))return!1;for(i=n;i--!==0;)if(c=l[i],!h(t[c],e[c]))return!1;return!0}return t!==t&&e!==e};var _=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var P=(t,e=!0)=>new Promise((r,s)=>{setTimeout(()=>{e?s(new Error("Timeout")):r(void 0)},t)});var k=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var V=(t,e={})=>{let r=()=>i,s=o=>{let g=f(f({},i),_(o));if(h(i,g))return;let a=i;i=g,c(i,a)};t.on("bridgeStateChange",o=>{s(o)});let i=f({},e),n=new Set,c=(o,g)=>{for(let a of n)a(o,g)};return{getState:r,subscribe:o=>(n.add(o),()=>n.delete(o))}};var y=(t={})=>{let e=t;return{getState:()=>e,subscribe:()=>()=>{}}};var b=class{constructor(e,r,s=[],i){this._options=e;this._emitter=r;this._bridgeMethods=s;this._nativeInitialState=i;m(this,"_defaultTimeoutMs",2e3);m(this,"_isListenerRegistered",!1);m(this,"store",y());m(this,"loose",k());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 c=M();return Promise.race([T({emitter:this._emitter,methodName:e,eventId:c,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:c,args:n})},onFallback:()=>{i==null||i(e,n)},failHandler:r&&new p(e)}),s>0&&P(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 g;let{timeout:s=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,c=Object.entries(n).filter(([a,d])=>typeof d=="function"),l=c.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(c.map(([a,d])=>[a,{value:d,writable:!0}]))),this._bridgeMethods=[...e,...l],this._nativeInitialState=r;let o=e.reduce((a,d)=>{if(!this.isReactNativeWebView)return a;let u=this._createNativeMethod(d,this._willMethodThrowOnError(d),s,i);return Object.defineProperty(this,d,{value:u,writable:!1}),x(f({},a),{[d]:u})},n);if(this.loose=this._createLoose(o),this.store=V(this._emitter,f(f({},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,...d]of(g=window.nativeBatchedEvents)!=null?g:[])this._emitter.emit(a,...d);return window.nativeBatchedEvents=[],!0}};var we=(t={timeout:2e3,throwOnError:!1})=>{var o,g;if(typeof window=="undefined")return{store:y(t==null?void 0:t.initialBridge)};window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=w();window.nativeEmitter||(window.nativeEmitter=e);let r=(o=window.__bridgeMethods__)!=null?o:[],s=(g=window.__bridgeInitialState__)!=null?g:{},i=new b(t,e,r,s);if(r.length===0){let a=e.on("hydrate",({bridgeMethods:d,nativeInitialState:u})=>{i._hydrate(d,u),a()})}let{onFallback:n,onReady:c}=t,l=new Proxy(i,{get:(a,d,u)=>d in a?a[d]:(u._postMessage("fallback",{method:d}),u._willMethodThrowOnError(d)?(...L)=>(n==null||n(d,L),Promise.reject(new v(d))):(console.warn(`[WebViewBridge] ${d} is not defined, using fallback.`),()=>Promise.resolve()))});return c==null||c(l),l};var be=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=w();window.webEmitter=s;for(let[n,c]of e){let l=(o,g)=>O(void 0,null,function*(){var a,d;try{let u=yield c(...g);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:o,value:u}}))}catch(u){(d=window.ReactNativeWebView)==null||d.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:o,error:JSON.stringify(u)}}))}});s.on(n,l)}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{v as MethodNotFoundError,p as NativeMethodError,we as linkBridge,be as registerWebMethod};
|
|
@@ -3,13 +3,15 @@ import { DefaultEmitter } from "../../../../shared/util/src";
|
|
|
3
3
|
import { LinkBridgeOptions } from "../linkBridge";
|
|
4
4
|
import { LinkBridge } from "../types";
|
|
5
5
|
export declare class BridgeInstance<T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any> = ParserSchema<any>> {
|
|
6
|
-
private
|
|
6
|
+
private _options;
|
|
7
7
|
private _emitter;
|
|
8
8
|
private _bridgeMethods;
|
|
9
9
|
_nativeInitialState: PrimitiveObject;
|
|
10
|
-
constructor(
|
|
11
|
-
private
|
|
10
|
+
constructor(_options: LinkBridgeOptions<T, V>, _emitter: DefaultEmitter, _bridgeMethods: string[], _nativeInitialState: PrimitiveObject);
|
|
11
|
+
private _defaultTimeoutMs;
|
|
12
|
+
private _isListenerRegistered;
|
|
12
13
|
store: Omit<T, "setState">;
|
|
14
|
+
get isReactNativeWebView(): boolean;
|
|
13
15
|
get isWebViewBridgeAvailable(): boolean;
|
|
14
16
|
isNativeMethodAvailable(methodName: string): boolean;
|
|
15
17
|
addEventListener<EventName extends KeyOfOrString<V>>(eventName: EventName, listener: (args: Parser<V, EventName>) => void): () => void;
|
|
@@ -4,4 +4,4 @@ export type Store<BridgeObject extends Bridge> = ({ get, set, }: {
|
|
|
4
4
|
get: () => BridgeObject;
|
|
5
5
|
set: (newState: Partial<OnlyJSON<BridgeObject>>) => void;
|
|
6
6
|
}) => BridgeObject;
|
|
7
|
-
export declare const linkBridgeStore: <T extends BridgeStore<T extends Bridge ? T : any>>(emitter: DefaultEmitter, initialState?: Partial<T
|
|
7
|
+
export declare const linkBridgeStore: <T extends BridgeStore<T extends Bridge ? T : any>>(emitter: DefaultEmitter, initialState?: Partial<T>) => Omit<T, "setState">;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
getState()
|
|
4
|
-
subscribe()
|
|
1
|
+
import { PrimitiveObject } from "../../../../shared/util/src/types";
|
|
2
|
+
export declare const mockStore: (initialState?: PrimitiveObject) => {
|
|
3
|
+
getState: () => PrimitiveObject;
|
|
4
|
+
subscribe: () => () => void;
|
|
5
5
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Bridge, BridgeStore, ExcludePrimitive, ExtractStore, ParserSchema } from "../../../shared/util/src/types";
|
|
2
2
|
import { LinkBridge } from "./types";
|
|
3
3
|
export interface LinkBridgeOptions<T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any>> {
|
|
4
|
+
initialBridge?: Partial<ExtractStore<T>>;
|
|
4
5
|
timeout?: number;
|
|
5
6
|
throwOnError?: boolean | (keyof ExtractStore<T>)[] | string[];
|
|
6
7
|
onFallback?: (methodName: string, args: unknown[]) => void;
|
package/package.json
CHANGED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { Bridge, BridgeStore, ExcludePrimitive, ExtractStore, ParserSchema } from "../../../shared/util/src/types";
|
|
2
|
-
import { LinkBridgeOptions } from "./linkBridge";
|
|
3
|
-
import { LinkBridge } from "./types";
|
|
4
|
-
/**
|
|
5
|
-
* @deprecated Use `linkBridge` instead. It's just renamed to `linkBridge`.
|
|
6
|
-
*/
|
|
7
|
-
export declare const linkNativeMethod: <T extends BridgeStore<T extends Bridge ? T : any>, V extends ParserSchema<any>>(options?: LinkBridgeOptions<T, V>) => LinkBridge<ExcludePrimitive<ExtractStore<T>>, Omit<T, "setState">, V>;
|